Compare commits
27 Commits
Author | SHA1 | Date | |
---|---|---|---|
9e2a94fcd9 | |||
8a3e8d331d | |||
1be9b2612c | |||
7c9aaeafa2 | |||
46c0078885 | |||
87ebf3b1d6 | |||
45238f8196 | |||
44f3a12fbe | |||
61acada2a0 | |||
c68fbbd89d | |||
97a0b6a543 | |||
3bccae492d | |||
0120a89d9c | |||
3da6fc3b7e | |||
34dd15ead7 | |||
b3d441e9d6 | |||
4b3dc3756c | |||
10027b98b5 | |||
da17dad63b | |||
fba6c422a8 | |||
0b4b93932d | |||
f42900ec46 | |||
eeca624ba6 | |||
84d08bad16 | |||
1181f33e9d | |||
797e200d08 | |||
d2f231066b |
@ -3,5 +3,4 @@ VITE_KC_API_BASE_URL=https://api.dev.kittycad.io
|
|||||||
VITE_KC_SITE_BASE_URL=https://dev.kittycad.io
|
VITE_KC_SITE_BASE_URL=https://dev.kittycad.io
|
||||||
VITE_KC_SKIP_AUTH=false
|
VITE_KC_SKIP_AUTH=false
|
||||||
VITE_KC_CONNECTION_TIMEOUT_MS=5000
|
VITE_KC_CONNECTION_TIMEOUT_MS=5000
|
||||||
VITE_KC_CONNECTION_WEBRTC_REPORT_STATS_MS=0
|
|
||||||
VITE_KC_SENTRY_DSN=
|
VITE_KC_SENTRY_DSN=
|
||||||
|
@ -3,5 +3,4 @@ VITE_KC_API_BASE_URL=https://api.kittycad.io
|
|||||||
VITE_KC_SITE_BASE_URL=https://kittycad.io
|
VITE_KC_SITE_BASE_URL=https://kittycad.io
|
||||||
VITE_KC_SKIP_AUTH=false
|
VITE_KC_SKIP_AUTH=false
|
||||||
VITE_KC_CONNECTION_TIMEOUT_MS=15000
|
VITE_KC_CONNECTION_TIMEOUT_MS=15000
|
||||||
VITE_KC_CONNECTION_WEBRTC_REPORT_STATS_MS=30000
|
|
||||||
VITE_KC_SENTRY_DSN=https://a814f2f66734989a90367f48feee28ca@o1042111.ingest.sentry.io/4505789425844224
|
VITE_KC_SENTRY_DSN=https://a814f2f66734989a90367f48feee28ca@o1042111.ingest.sentry.io/4505789425844224
|
||||||
|
65
.github/workflows/ci.yml
vendored
65
.github/workflows/ci.yml
vendored
@ -1,4 +1,4 @@
|
|||||||
name: CI
|
name: CI
|
||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
@ -13,17 +13,31 @@ jobs:
|
|||||||
check-format:
|
check-format:
|
||||||
runs-on: 'ubuntu-20.04'
|
runs-on: 'ubuntu-20.04'
|
||||||
steps:
|
steps:
|
||||||
|
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version-file: '.nvmrc'
|
node-version-file: '.nvmrc'
|
||||||
|
cache: 'yarn'
|
||||||
- run: yarn install
|
- run: yarn install
|
||||||
|
|
||||||
- run: yarn fmt-check
|
- run: yarn fmt-check
|
||||||
|
|
||||||
|
check-types:
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: actions/setup-node@v3
|
||||||
|
with:
|
||||||
|
node-version-file: '.nvmrc'
|
||||||
|
cache: 'yarn'
|
||||||
|
- run: yarn install
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
workspaces: "./src/wasm-lib"
|
||||||
|
|
||||||
|
- run: yarn build:wasm
|
||||||
|
- run: yarn tsc
|
||||||
|
|
||||||
|
|
||||||
build-test-web:
|
build-test-web:
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
@ -36,12 +50,15 @@ jobs:
|
|||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version-file: '.nvmrc'
|
node-version-file: '.nvmrc'
|
||||||
|
cache: 'yarn'
|
||||||
|
|
||||||
- run: yarn install
|
- run: yarn install
|
||||||
|
|
||||||
- run: yarn build:wasm
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
workspaces: "./src/wasm-lib"
|
||||||
|
|
||||||
- run: yarn tsc
|
- run: yarn build:wasm
|
||||||
|
|
||||||
- run: yarn simpleserver:ci
|
- run: yarn simpleserver:ci
|
||||||
|
|
||||||
@ -49,14 +66,12 @@ jobs:
|
|||||||
|
|
||||||
- run: yarn test:cov
|
- run: yarn test:cov
|
||||||
|
|
||||||
- run: yarn test:rust
|
|
||||||
|
|
||||||
- id: export_version
|
- id: export_version
|
||||||
run: echo "version=`cat package.json | jq -r '.version'`" >> "$GITHUB_OUTPUT"
|
run: echo "version=`cat package.json | jq -r '.version'`" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
|
||||||
build-apps:
|
build-apps:
|
||||||
needs: [check-format, build-test-web]
|
needs: [check-format, build-test-web, check-types]
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
@ -87,6 +102,10 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
workspaces: './src-tauri -> target'
|
workspaces: './src-tauri -> target'
|
||||||
|
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
workspaces: "./src/wasm-lib"
|
||||||
|
|
||||||
- name: wasm prep
|
- name: wasm prep
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
@ -110,15 +129,22 @@ jobs:
|
|||||||
- name: Fix format
|
- name: Fix format
|
||||||
run: yarn fmt
|
run: yarn fmt
|
||||||
|
|
||||||
|
- name: install apple silicon target mac
|
||||||
|
if: matrix.os == 'macos-latest'
|
||||||
|
run: |
|
||||||
|
rustup target add aarch64-apple-darwin
|
||||||
|
|
||||||
- name: Build the app for the current platform (no upload)
|
- name: Build the app for the current platform (no upload)
|
||||||
uses: tauri-apps/tauri-action@v0
|
uses: tauri-apps/tauri-action@v0
|
||||||
env:
|
env:
|
||||||
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
|
||||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||||
|
with:
|
||||||
|
args: ${{ matrix.os == 'macos-latest' && '--target universal-apple-darwin' || '' }}
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v3
|
- uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
path: src-tauri/target/release/bundle/*/*
|
path: ${{ matrix.os == 'macos-latest' && 'src-tauri/target/universal-apple-darwin/release/bundle/*/*' || 'src-tauri/target/release/bundle/*/*' }}
|
||||||
|
|
||||||
|
|
||||||
publish-apps-release:
|
publish-apps-release:
|
||||||
@ -133,8 +159,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Generate the update static endpoint
|
- name: Generate the update static endpoint
|
||||||
run: |
|
run: |
|
||||||
ls -l artifact
|
ls -l artifact/*/*itty*
|
||||||
ls -l artifact/*
|
|
||||||
DARWIN_SIG=`cat artifact/macos/*.app.tar.gz.sig`
|
DARWIN_SIG=`cat artifact/macos/*.app.tar.gz.sig`
|
||||||
LINUX_SIG=`cat artifact/appimage/*.AppImage.tar.gz.sig`
|
LINUX_SIG=`cat artifact/appimage/*.AppImage.tar.gz.sig`
|
||||||
WINDOWS_SIG=`cat artifact/nsis/*.nsis.zip.sig`
|
WINDOWS_SIG=`cat artifact/nsis/*.nsis.zip.sig`
|
||||||
@ -154,6 +179,10 @@ jobs:
|
|||||||
"signature": $darwin_sig,
|
"signature": $darwin_sig,
|
||||||
"url": $darwin_url
|
"url": $darwin_url
|
||||||
},
|
},
|
||||||
|
"darwin-aarch64": {
|
||||||
|
"signature": $darwin_sig,
|
||||||
|
"url": $darwin_url
|
||||||
|
},
|
||||||
"linux-x86_64": {
|
"linux-x86_64": {
|
||||||
"signature": $linux_sig,
|
"signature": $linux_sig,
|
||||||
"url": $linux_url
|
"url": $linux_url
|
||||||
@ -175,15 +204,15 @@ jobs:
|
|||||||
uses: google-github-actions/setup-gcloud@v1.1.1
|
uses: google-github-actions/setup-gcloud@v1.1.1
|
||||||
with:
|
with:
|
||||||
project_id: kittycadapi
|
project_id: kittycadapi
|
||||||
|
|
||||||
- name: Upload release files to public bucket
|
- name: Upload release files to public bucket
|
||||||
uses: google-github-actions/upload-cloud-storage@v1.0.3
|
uses: google-github-actions/upload-cloud-storage@v1.0.3
|
||||||
with:
|
with:
|
||||||
path: artifact
|
path: artifact
|
||||||
glob: '*/*'
|
glob: '*/*itty*'
|
||||||
parent: false
|
parent: false
|
||||||
destination: dl.kittycad.io/releases/modeling-app/v${{ env.VERSION_NO_V }}
|
destination: dl.kittycad.io/releases/modeling-app/v${{ env.VERSION_NO_V }}
|
||||||
|
|
||||||
- name: Upload update endpoint to public bucket
|
- name: Upload update endpoint to public bucket
|
||||||
uses: google-github-actions/upload-cloud-storage@v1.0.3
|
uses: google-github-actions/upload-cloud-storage@v1.0.3
|
||||||
with:
|
with:
|
||||||
@ -193,4 +222,4 @@ jobs:
|
|||||||
- name: Upload release files to Github
|
- name: Upload release files to Github
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
with:
|
with:
|
||||||
files: artifact/*/*
|
files: artifact/*/*itty*
|
||||||
|
@ -5,3 +5,5 @@ coverage
|
|||||||
# Ignore Rust projects:
|
# Ignore Rust projects:
|
||||||
*.rs
|
*.rs
|
||||||
target
|
target
|
||||||
|
src/wasm-lib/pkg
|
||||||
|
src/wasm-lib/kcl/bindings
|
||||||
|
21
README.md
21
README.md
@ -86,3 +86,24 @@ The PR may serve as a place to discuss the human-readable changelog and extra QA
|
|||||||
3. Create a new release and tag pointing to the bump version commit using semantic versioning `v{x}.{y}.{z}`
|
3. Create a new release and tag pointing to the bump version commit using semantic versioning `v{x}.{y}.{z}`
|
||||||
|
|
||||||
4. A new Action kicks in at https://github.com/KittyCAD/modeling-app/actions, uploading artifacts to the release
|
4. A new Action kicks in at https://github.com/KittyCAD/modeling-app/actions, uploading artifacts to the release
|
||||||
|
|
||||||
|
## Fuzzing the parser
|
||||||
|
|
||||||
|
Make sure you install cargo fuzz:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ cargo install cargo-fuzz
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ cd src/wasm-lib/kcl
|
||||||
|
|
||||||
|
# list the fuzz targets
|
||||||
|
$ cargo fuzz list
|
||||||
|
|
||||||
|
# run the parser fuzzer
|
||||||
|
$ cargo +nightly fuzz run parser
|
||||||
|
```
|
||||||
|
|
||||||
|
For more information on fuzzing you can check out
|
||||||
|
[this guide](https://rust-fuzz.github.io/book/cargo-fuzz.html).
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "untitled-app",
|
"name": "untitled-app",
|
||||||
"version": "0.3.1",
|
"version": "0.5.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@codemirror/autocomplete": "^6.9.0",
|
"@codemirror/autocomplete": "^6.9.0",
|
||||||
@ -10,7 +10,7 @@
|
|||||||
"@fortawesome/react-fontawesome": "^0.2.0",
|
"@fortawesome/react-fontawesome": "^0.2.0",
|
||||||
"@headlessui/react": "^1.7.13",
|
"@headlessui/react": "^1.7.13",
|
||||||
"@headlessui/tailwindcss": "^0.2.0",
|
"@headlessui/tailwindcss": "^0.2.0",
|
||||||
"@kittycad/lib": "^0.0.35",
|
"@kittycad/lib": "^0.0.37",
|
||||||
"@lezer/javascript": "^1.4.7",
|
"@lezer/javascript": "^1.4.7",
|
||||||
"@open-rpc/client-js": "^1.8.1",
|
"@open-rpc/client-js": "^1.8.1",
|
||||||
"@react-hook/resize-observer": "^1.2.6",
|
"@react-hook/resize-observer": "^1.2.6",
|
||||||
@ -70,7 +70,7 @@
|
|||||||
"fmt": "prettier --write ./src",
|
"fmt": "prettier --write ./src",
|
||||||
"fmt-check": "prettier --check ./src",
|
"fmt-check": "prettier --check ./src",
|
||||||
"build:wasm": "yarn wasm-prep && (cd src/wasm-lib && wasm-pack build --target web --out-dir pkg && cargo test -p kcl-lib export_bindings) && cp src/wasm-lib/pkg/wasm_lib_bg.wasm public && yarn fmt && yarn remove-importmeta",
|
"build:wasm": "yarn wasm-prep && (cd src/wasm-lib && wasm-pack build --target web --out-dir pkg && cargo test -p kcl-lib export_bindings) && cp src/wasm-lib/pkg/wasm_lib_bg.wasm public && yarn fmt && yarn remove-importmeta",
|
||||||
"remove-importmeta": "sed -i 's/import.meta.url//g' \"./src/wasm-lib/pkg/wasm_lib.js\"; sed -i '' 's/import.meta.url//g' \"./src/wasm-lib/pkg/wasm_lib.js\" || echo \"sed for both mac and linux\"",
|
"remove-importmeta": "sed -i 's/import.meta.url/window.location.origin/g' \"./src/wasm-lib/pkg/wasm_lib.js\"; sed -i '' 's/import.meta.url/window.location.origin/g' \"./src/wasm-lib/pkg/wasm_lib.js\" || echo \"sed for both mac and linux\"",
|
||||||
"wasm-prep": "rm -rf src/wasm-lib/pkg && mkdir src/wasm-lib/pkg && rm -rf src/wasm-lib/kcl/bindings",
|
"wasm-prep": "rm -rf src/wasm-lib/pkg && mkdir src/wasm-lib/pkg && rm -rf src/wasm-lib/kcl/bindings",
|
||||||
"lint": "eslint --fix src",
|
"lint": "eslint --fix src",
|
||||||
"bump-jsons": "echo \"$(jq --arg v \"$VERSION\" '.version=$v' package.json --indent 2)\" > package.json && echo \"$(jq --arg v \"$VERSION\" '.package.version=$v' src-tauri/tauri.conf.json --indent 2)\" > src-tauri/tauri.conf.json"
|
"bump-jsons": "echo \"$(jq --arg v \"$VERSION\" '.version=$v' package.json --indent 2)\" > package.json && echo \"$(jq --arg v \"$VERSION\" '.package.version=$v' src-tauri/tauri.conf.json --indent 2)\" > src-tauri/tauri.conf.json"
|
||||||
|
@ -8,7 +8,7 @@
|
|||||||
},
|
},
|
||||||
"package": {
|
"package": {
|
||||||
"productName": "kittycad-modeling",
|
"productName": "kittycad-modeling",
|
||||||
"version": "0.3.1"
|
"version": "0.5.0"
|
||||||
},
|
},
|
||||||
"tauri": {
|
"tauri": {
|
||||||
"allowlist": {
|
"allowlist": {
|
||||||
|
287
src/App.tsx
287
src/App.tsx
@ -2,7 +2,6 @@ import {
|
|||||||
useRef,
|
useRef,
|
||||||
useEffect,
|
useEffect,
|
||||||
useLayoutEffect,
|
useLayoutEffect,
|
||||||
useMemo,
|
|
||||||
useCallback,
|
useCallback,
|
||||||
MouseEventHandler,
|
MouseEventHandler,
|
||||||
} from 'react'
|
} from 'react'
|
||||||
@ -10,30 +9,20 @@ import { DebugPanel } from './components/DebugPanel'
|
|||||||
import { v4 as uuidv4 } from 'uuid'
|
import { v4 as uuidv4 } from 'uuid'
|
||||||
import { asyncParser } from './lang/abstractSyntaxTree'
|
import { asyncParser } from './lang/abstractSyntaxTree'
|
||||||
import { _executor } from './lang/executor'
|
import { _executor } from './lang/executor'
|
||||||
import CodeMirror from '@uiw/react-codemirror'
|
import { PaneType, useStore } from './useStore'
|
||||||
import { linter, lintGutter } from '@codemirror/lint'
|
|
||||||
import { ViewUpdate, EditorView } from '@codemirror/view'
|
|
||||||
import {
|
|
||||||
lineHighlightField,
|
|
||||||
addLineHighlight,
|
|
||||||
} from './editor/highlightextension'
|
|
||||||
import { PaneType, Selections, useStore } from './useStore'
|
|
||||||
import Server from './editor/lsp/server'
|
|
||||||
import Client from './editor/lsp/client'
|
|
||||||
import { Logs, KCLErrors } from './components/Logs'
|
import { Logs, KCLErrors } from './components/Logs'
|
||||||
import { CollapsiblePanel } from './components/CollapsiblePanel'
|
import { CollapsiblePanel } from './components/CollapsiblePanel'
|
||||||
import { MemoryPanel } from './components/MemoryPanel'
|
import { MemoryPanel } from './components/MemoryPanel'
|
||||||
import { useHotKeyListener } from './hooks/useHotKeyListener'
|
import { useHotKeyListener } from './hooks/useHotKeyListener'
|
||||||
import { Stream } from './components/Stream'
|
import { Stream } from './components/Stream'
|
||||||
import ModalContainer from 'react-modal-promise'
|
import ModalContainer from 'react-modal-promise'
|
||||||
import { FromServer, IntoServer } from './editor/lsp/codec'
|
|
||||||
import {
|
import {
|
||||||
EngineCommand,
|
EngineCommand,
|
||||||
EngineCommandManager,
|
EngineCommandManager,
|
||||||
} from './lang/std/engineConnection'
|
} from './lang/std/engineConnection'
|
||||||
import { isOverlap, throttle } from './lib/utils'
|
import { throttle } from './lib/utils'
|
||||||
import { AppHeader } from './components/AppHeader'
|
import { AppHeader } from './components/AppHeader'
|
||||||
import { KCLError, kclErrToDiagnostic } from './lang/errors'
|
import { KCLError } from './lang/errors'
|
||||||
import { Resizable } from 're-resizable'
|
import { Resizable } from 're-resizable'
|
||||||
import {
|
import {
|
||||||
faCode,
|
faCode,
|
||||||
@ -41,96 +30,75 @@ import {
|
|||||||
faSquareRootVariable,
|
faSquareRootVariable,
|
||||||
} from '@fortawesome/free-solid-svg-icons'
|
} from '@fortawesome/free-solid-svg-icons'
|
||||||
import { useHotkeys } from 'react-hotkeys-hook'
|
import { useHotkeys } from 'react-hotkeys-hook'
|
||||||
import { TEST } from './env'
|
|
||||||
import { getNormalisedCoordinates } from './lib/utils'
|
import { getNormalisedCoordinates } from './lib/utils'
|
||||||
import { Themes, getSystemTheme } from './lib/theme'
|
|
||||||
import { isTauri } from './lib/isTauri'
|
import { isTauri } from './lib/isTauri'
|
||||||
import { useLoaderData, useParams } from 'react-router-dom'
|
import { useLoaderData } from 'react-router-dom'
|
||||||
import { writeTextFile } from '@tauri-apps/api/fs'
|
|
||||||
import { PROJECT_ENTRYPOINT } from './lib/tauriFS'
|
|
||||||
import { IndexLoaderData } from './Router'
|
import { IndexLoaderData } from './Router'
|
||||||
import { toast } from 'react-hot-toast'
|
|
||||||
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
|
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
|
||||||
import { onboardingPaths } from 'routes/Onboarding'
|
import { onboardingPaths } from 'routes/Onboarding'
|
||||||
import { LanguageServerClient } from 'editor/lsp'
|
import { cameraMouseDragGuards } from 'lib/cameraControls'
|
||||||
import kclLanguage from 'editor/lsp/language'
|
import { CameraDragInteractionType_type } from '@kittycad/lib/dist/types/src/models'
|
||||||
|
import { CodeMenu } from 'components/CodeMenu'
|
||||||
|
import { TextEditor } from 'components/TextEditor'
|
||||||
|
import { Themes, getSystemTheme } from 'lib/theme'
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
const { code: loadedCode, project } = useLoaderData() as IndexLoaderData
|
const { code: loadedCode, project } = useLoaderData() as IndexLoaderData
|
||||||
const pathParams = useParams()
|
|
||||||
const streamRef = useRef<HTMLDivElement>(null)
|
const streamRef = useRef<HTMLDivElement>(null)
|
||||||
useHotKeyListener()
|
useHotKeyListener()
|
||||||
const {
|
const {
|
||||||
editorView,
|
|
||||||
setEditorView,
|
|
||||||
setSelectionRanges,
|
|
||||||
selectionRanges,
|
|
||||||
addLog,
|
addLog,
|
||||||
addKCLError,
|
addKCLError,
|
||||||
code,
|
|
||||||
setCode,
|
setCode,
|
||||||
setAst,
|
setAst,
|
||||||
setError,
|
setError,
|
||||||
setProgramMemory,
|
setProgramMemory,
|
||||||
resetLogs,
|
resetLogs,
|
||||||
resetKCLErrors,
|
resetKCLErrors,
|
||||||
selectionRangeTypeMap,
|
|
||||||
setArtifactMap,
|
setArtifactMap,
|
||||||
engineCommandManager,
|
engineCommandManager,
|
||||||
setEngineCommandManager,
|
setEngineCommandManager,
|
||||||
|
highlightRange,
|
||||||
setHighlightRange,
|
setHighlightRange,
|
||||||
setCursor2,
|
setCursor2,
|
||||||
sourceRangeMap,
|
|
||||||
setMediaStream,
|
setMediaStream,
|
||||||
setIsStreamReady,
|
setIsStreamReady,
|
||||||
isStreamReady,
|
isStreamReady,
|
||||||
isLSPServerReady,
|
buttonDownInStream,
|
||||||
setIsLSPServerReady,
|
|
||||||
isMouseDownInStream,
|
|
||||||
formatCode,
|
|
||||||
openPanes,
|
openPanes,
|
||||||
setOpenPanes,
|
setOpenPanes,
|
||||||
didDragInStream,
|
didDragInStream,
|
||||||
setDidDragInStream,
|
|
||||||
setStreamDimensions,
|
setStreamDimensions,
|
||||||
streamDimensions,
|
streamDimensions,
|
||||||
|
setIsExecuting,
|
||||||
|
defferedCode,
|
||||||
} = useStore((s) => ({
|
} = useStore((s) => ({
|
||||||
editorView: s.editorView,
|
|
||||||
setEditorView: s.setEditorView,
|
|
||||||
setSelectionRanges: s.setSelectionRanges,
|
|
||||||
selectionRanges: s.selectionRanges,
|
|
||||||
setGuiMode: s.setGuiMode,
|
|
||||||
addLog: s.addLog,
|
addLog: s.addLog,
|
||||||
code: s.code,
|
defferedCode: s.defferedCode,
|
||||||
setCode: s.setCode,
|
setCode: s.setCode,
|
||||||
setAst: s.setAst,
|
setAst: s.setAst,
|
||||||
setError: s.setError,
|
setError: s.setError,
|
||||||
setProgramMemory: s.setProgramMemory,
|
setProgramMemory: s.setProgramMemory,
|
||||||
resetLogs: s.resetLogs,
|
resetLogs: s.resetLogs,
|
||||||
resetKCLErrors: s.resetKCLErrors,
|
resetKCLErrors: s.resetKCLErrors,
|
||||||
selectionRangeTypeMap: s.selectionRangeTypeMap,
|
|
||||||
setArtifactMap: s.setArtifactNSourceRangeMaps,
|
setArtifactMap: s.setArtifactNSourceRangeMaps,
|
||||||
engineCommandManager: s.engineCommandManager,
|
engineCommandManager: s.engineCommandManager,
|
||||||
setEngineCommandManager: s.setEngineCommandManager,
|
setEngineCommandManager: s.setEngineCommandManager,
|
||||||
|
highlightRange: s.highlightRange,
|
||||||
setHighlightRange: s.setHighlightRange,
|
setHighlightRange: s.setHighlightRange,
|
||||||
isShiftDown: s.isShiftDown,
|
|
||||||
setCursor: s.setCursor,
|
|
||||||
setCursor2: s.setCursor2,
|
setCursor2: s.setCursor2,
|
||||||
sourceRangeMap: s.sourceRangeMap,
|
|
||||||
setMediaStream: s.setMediaStream,
|
setMediaStream: s.setMediaStream,
|
||||||
isStreamReady: s.isStreamReady,
|
isStreamReady: s.isStreamReady,
|
||||||
setIsStreamReady: s.setIsStreamReady,
|
setIsStreamReady: s.setIsStreamReady,
|
||||||
isLSPServerReady: s.isLSPServerReady,
|
buttonDownInStream: s.buttonDownInStream,
|
||||||
setIsLSPServerReady: s.setIsLSPServerReady,
|
|
||||||
isMouseDownInStream: s.isMouseDownInStream,
|
|
||||||
formatCode: s.formatCode,
|
|
||||||
addKCLError: s.addKCLError,
|
addKCLError: s.addKCLError,
|
||||||
openPanes: s.openPanes,
|
openPanes: s.openPanes,
|
||||||
setOpenPanes: s.setOpenPanes,
|
setOpenPanes: s.setOpenPanes,
|
||||||
didDragInStream: s.didDragInStream,
|
didDragInStream: s.didDragInStream,
|
||||||
setDidDragInStream: s.setDidDragInStream,
|
|
||||||
setStreamDimensions: s.setStreamDimensions,
|
setStreamDimensions: s.setStreamDimensions,
|
||||||
streamDimensions: s.streamDimensions,
|
streamDimensions: s.streamDimensions,
|
||||||
|
setIsExecuting: s.setIsExecuting,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@ -138,7 +106,7 @@ export function App() {
|
|||||||
context: { token },
|
context: { token },
|
||||||
},
|
},
|
||||||
settings: {
|
settings: {
|
||||||
context: { showDebugPanel, theme, onboardingStatus },
|
context: { showDebugPanel, onboardingStatus, cameraControls, theme },
|
||||||
},
|
},
|
||||||
} = useGlobalStateContext()
|
} = useGlobalStateContext()
|
||||||
|
|
||||||
@ -179,80 +147,6 @@ export function App() {
|
|||||||
}
|
}
|
||||||
}, [loadedCode, setCode])
|
}, [loadedCode, setCode])
|
||||||
|
|
||||||
// const onChange = React.useCallback((value: string, viewUpdate: ViewUpdate) => {
|
|
||||||
const onChange = (value: string, viewUpdate: ViewUpdate) => {
|
|
||||||
setCode(value)
|
|
||||||
if (isTauri() && pathParams.id) {
|
|
||||||
// Save the file to disk
|
|
||||||
// Note that PROJECT_ENTRYPOINT is hardcoded until we support multiple files
|
|
||||||
writeTextFile(pathParams.id + '/' + PROJECT_ENTRYPOINT, value).catch(
|
|
||||||
(err) => {
|
|
||||||
// TODO: add Sentry per GH issue #254 (https://github.com/KittyCAD/modeling-app/issues/254)
|
|
||||||
console.error('error saving file', err)
|
|
||||||
toast.error('Error saving file, please check file permissions')
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (editorView) {
|
|
||||||
editorView?.dispatch({ effects: addLineHighlight.of([0, 0]) })
|
|
||||||
}
|
|
||||||
} //, []);
|
|
||||||
const onUpdate = (viewUpdate: ViewUpdate) => {
|
|
||||||
if (!editorView) {
|
|
||||||
setEditorView(viewUpdate.view)
|
|
||||||
}
|
|
||||||
const ranges = viewUpdate.state.selection.ranges
|
|
||||||
|
|
||||||
const isChange =
|
|
||||||
ranges.length !== selectionRanges.codeBasedSelections.length ||
|
|
||||||
ranges.some(({ from, to }, i) => {
|
|
||||||
return (
|
|
||||||
from !== selectionRanges.codeBasedSelections[i].range[0] ||
|
|
||||||
to !== selectionRanges.codeBasedSelections[i].range[1]
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!isChange) return
|
|
||||||
const codeBasedSelections: Selections['codeBasedSelections'] = ranges.map(
|
|
||||||
({ from, to }) => {
|
|
||||||
if (selectionRangeTypeMap[to]) {
|
|
||||||
return {
|
|
||||||
type: selectionRangeTypeMap[to],
|
|
||||||
range: [from, to],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
type: 'default',
|
|
||||||
range: [from, to],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
const idBasedSelections = codeBasedSelections
|
|
||||||
.map(({ type, range }) => {
|
|
||||||
const hasOverlap = Object.entries(sourceRangeMap).filter(
|
|
||||||
([_, sourceRange]) => {
|
|
||||||
return isOverlap(sourceRange, range)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
if (hasOverlap.length) {
|
|
||||||
return {
|
|
||||||
type,
|
|
||||||
id: hasOverlap[0][0],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.filter(Boolean) as any
|
|
||||||
|
|
||||||
engineCommandManager?.cusorsSelected({
|
|
||||||
otherSelections: [],
|
|
||||||
idBasedSelections,
|
|
||||||
})
|
|
||||||
|
|
||||||
setSelectionRanges({
|
|
||||||
otherSelections: [],
|
|
||||||
codeBasedSelections,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
const streamWidth = streamRef?.current?.offsetWidth
|
const streamWidth = streamRef?.current?.offsetWidth
|
||||||
const streamHeight = streamRef?.current?.offsetHeight
|
const streamHeight = streamRef?.current?.offsetHeight
|
||||||
|
|
||||||
@ -286,16 +180,17 @@ export function App() {
|
|||||||
let unsubFn: any[] = []
|
let unsubFn: any[] = []
|
||||||
const asyncWrap = async () => {
|
const asyncWrap = async () => {
|
||||||
try {
|
try {
|
||||||
if (!code) {
|
if (!defferedCode) {
|
||||||
setAst(null)
|
setAst(null)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const _ast = await asyncParser(code)
|
const _ast = await asyncParser(defferedCode)
|
||||||
setAst(_ast)
|
setAst(_ast)
|
||||||
resetLogs()
|
resetLogs()
|
||||||
resetKCLErrors()
|
resetKCLErrors()
|
||||||
engineCommandManager.endSession()
|
engineCommandManager.endSession()
|
||||||
engineCommandManager.startNewSession()
|
engineCommandManager.startNewSession()
|
||||||
|
setIsExecuting(true)
|
||||||
const programMemory = await _executor(
|
const programMemory = await _executor(
|
||||||
_ast,
|
_ast,
|
||||||
{
|
{
|
||||||
@ -327,16 +222,20 @@ export function App() {
|
|||||||
|
|
||||||
const { artifactMap, sourceRangeMap } =
|
const { artifactMap, sourceRangeMap } =
|
||||||
await engineCommandManager.waitForAllCommands()
|
await engineCommandManager.waitForAllCommands()
|
||||||
|
setIsExecuting(false)
|
||||||
|
|
||||||
setArtifactMap({ artifactMap, sourceRangeMap })
|
setArtifactMap({ artifactMap, sourceRangeMap })
|
||||||
const unSubHover = engineCommandManager.subscribeToUnreliable({
|
const unSubHover = engineCommandManager.subscribeToUnreliable({
|
||||||
event: 'highlight_set_entity',
|
event: 'highlight_set_entity',
|
||||||
callback: ({ data }) => {
|
callback: ({ data }) => {
|
||||||
if (!data?.entity_id) {
|
if (data?.entity_id) {
|
||||||
setHighlightRange([0, 0])
|
|
||||||
} else {
|
|
||||||
const sourceRange = sourceRangeMap[data.entity_id]
|
const sourceRange = sourceRangeMap[data.entity_id]
|
||||||
setHighlightRange(sourceRange)
|
setHighlightRange(sourceRange)
|
||||||
|
} else if (
|
||||||
|
!highlightRange ||
|
||||||
|
(highlightRange[0] !== 0 && highlightRange[1] !== 0)
|
||||||
|
) {
|
||||||
|
setHighlightRange([0, 0])
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@ -358,6 +257,7 @@ export function App() {
|
|||||||
|
|
||||||
setError()
|
setError()
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
setIsExecuting(false)
|
||||||
if (e instanceof KCLError) {
|
if (e instanceof KCLError) {
|
||||||
addKCLError(e)
|
addKCLError(e)
|
||||||
} else {
|
} else {
|
||||||
@ -371,36 +271,38 @@ export function App() {
|
|||||||
return () => {
|
return () => {
|
||||||
unsubFn.forEach((fn) => fn())
|
unsubFn.forEach((fn) => fn())
|
||||||
}
|
}
|
||||||
}, [code, isStreamReady, engineCommandManager])
|
}, [defferedCode, isStreamReady, engineCommandManager])
|
||||||
|
|
||||||
const debounceSocketSend = throttle<EngineCommand>((message) => {
|
const debounceSocketSend = throttle<EngineCommand>((message) => {
|
||||||
engineCommandManager?.sendSceneCommand(message)
|
engineCommandManager?.sendSceneCommand(message)
|
||||||
}, 16)
|
}, 16)
|
||||||
const handleMouseMove: MouseEventHandler<HTMLDivElement> = ({
|
const handleMouseMove: MouseEventHandler<HTMLDivElement> = (e) => {
|
||||||
clientX,
|
e.nativeEvent.preventDefault()
|
||||||
clientY,
|
|
||||||
ctrlKey,
|
|
||||||
shiftKey,
|
|
||||||
currentTarget,
|
|
||||||
nativeEvent,
|
|
||||||
}) => {
|
|
||||||
nativeEvent.preventDefault()
|
|
||||||
if (isMouseDownInStream) {
|
|
||||||
setDidDragInStream(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
const { x, y } = getNormalisedCoordinates({
|
const { x, y } = getNormalisedCoordinates({
|
||||||
clientX,
|
clientX: e.clientX,
|
||||||
clientY,
|
clientY: e.clientY,
|
||||||
el: currentTarget,
|
el: e.currentTarget,
|
||||||
...streamDimensions,
|
...streamDimensions,
|
||||||
})
|
})
|
||||||
|
|
||||||
const interaction = ctrlKey ? 'zoom' : shiftKey ? 'pan' : 'rotate'
|
|
||||||
|
|
||||||
const newCmdId = uuidv4()
|
const newCmdId = uuidv4()
|
||||||
|
|
||||||
if (isMouseDownInStream) {
|
if (buttonDownInStream) {
|
||||||
|
const interactionGuards = cameraMouseDragGuards[cameraControls]
|
||||||
|
let interaction: CameraDragInteractionType_type
|
||||||
|
|
||||||
|
const eWithButton = { ...e, button: buttonDownInStream }
|
||||||
|
|
||||||
|
if (interactionGuards.pan.callback(eWithButton)) {
|
||||||
|
interaction = 'pan'
|
||||||
|
} else if (interactionGuards.rotate.callback(eWithButton)) {
|
||||||
|
interaction = 'rotate'
|
||||||
|
} else if (interactionGuards.zoom.dragCallback(eWithButton)) {
|
||||||
|
interaction = 'zoom'
|
||||||
|
} else {
|
||||||
|
return
|
||||||
|
}
|
||||||
debounceSocketSend({
|
debounceSocketSend({
|
||||||
type: 'modeling_cmd_req',
|
type: 'modeling_cmd_req',
|
||||||
cmd: {
|
cmd: {
|
||||||
@ -422,56 +324,6 @@ export function App() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const extraExtensions = useMemo(() => {
|
|
||||||
if (TEST) return []
|
|
||||||
return [
|
|
||||||
lintGutter(),
|
|
||||||
linter((_view) => {
|
|
||||||
return kclErrToDiagnostic(useStore.getState().kclErrors)
|
|
||||||
}),
|
|
||||||
EditorView.lineWrapping,
|
|
||||||
]
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
// So this is a bit weird, we need to initialize the lsp server and client.
|
|
||||||
// But the server happens async so we break this into two parts.
|
|
||||||
// Below is the client and server promise.
|
|
||||||
const { lspClient } = useMemo(() => {
|
|
||||||
const intoServer: IntoServer = new IntoServer()
|
|
||||||
const fromServer: FromServer = FromServer.create()
|
|
||||||
const client = new Client(fromServer, intoServer)
|
|
||||||
if (!TEST) {
|
|
||||||
Server.initialize(intoServer, fromServer).then((lspServer) => {
|
|
||||||
lspServer.start()
|
|
||||||
setIsLSPServerReady(true)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const lspClient = new LanguageServerClient({ client })
|
|
||||||
return { lspClient }
|
|
||||||
}, [setIsLSPServerReady])
|
|
||||||
|
|
||||||
// Here we initialize the plugin which will start the client.
|
|
||||||
// When we have multi-file support the name of the file will be a dep of
|
|
||||||
// this use memo, as well as the directory structure, which I think is
|
|
||||||
// a good setup becuase it will restart the client but not the server :)
|
|
||||||
// We do not want to restart the server, its just wasteful.
|
|
||||||
const kclLSP = useMemo(() => {
|
|
||||||
let plugin = null
|
|
||||||
if (isLSPServerReady && !TEST) {
|
|
||||||
// Set up the lsp plugin.
|
|
||||||
const lsp = kclLanguage({
|
|
||||||
// When we have more than one file, we'll need to change this.
|
|
||||||
documentUri: `file:///we-just-have-one-file-for-now.kcl`,
|
|
||||||
workspaceFolders: null,
|
|
||||||
client: lspClient,
|
|
||||||
})
|
|
||||||
|
|
||||||
plugin = lsp
|
|
||||||
}
|
|
||||||
return plugin
|
|
||||||
}, [lspClient, isLSPServerReady])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="h-screen overflow-hidden relative flex flex-col cursor-pointer select-none"
|
className="h-screen overflow-hidden relative flex flex-col cursor-pointer select-none"
|
||||||
@ -482,7 +334,7 @@ export function App() {
|
|||||||
className={
|
className={
|
||||||
'transition-opacity transition-duration-75 ' +
|
'transition-opacity transition-duration-75 ' +
|
||||||
paneOpacity +
|
paneOpacity +
|
||||||
(isMouseDownInStream ? ' pointer-events-none' : '')
|
(buttonDownInStream ? ' pointer-events-none' : '')
|
||||||
}
|
}
|
||||||
project={project}
|
project={project}
|
||||||
enableMenu={true}
|
enableMenu={true}
|
||||||
@ -491,7 +343,7 @@ export function App() {
|
|||||||
<Resizable
|
<Resizable
|
||||||
className={
|
className={
|
||||||
'h-full flex flex-col flex-1 z-10 my-5 ml-5 pr-1 transition-opacity transition-duration-75 ' +
|
'h-full flex flex-col flex-1 z-10 my-5 ml-5 pr-1 transition-opacity transition-duration-75 ' +
|
||||||
(isMouseDownInStream || onboardingStatus === 'camera'
|
(buttonDownInStream || onboardingStatus === 'camera'
|
||||||
? ' pointer-events-none '
|
? ' pointer-events-none '
|
||||||
: ' ') +
|
: ' ') +
|
||||||
paneOpacity
|
paneOpacity
|
||||||
@ -513,36 +365,11 @@ export function App() {
|
|||||||
<CollapsiblePanel
|
<CollapsiblePanel
|
||||||
title="Code"
|
title="Code"
|
||||||
icon={faCode}
|
icon={faCode}
|
||||||
className="open:!mb-2 overflow-x-hidden"
|
className="open:!mb-2"
|
||||||
open={openPanes.includes('code')}
|
open={openPanes.includes('code')}
|
||||||
|
menu={<CodeMenu />}
|
||||||
>
|
>
|
||||||
<div className="px-2 py-1">
|
<TextEditor theme={editorTheme} />
|
||||||
<button
|
|
||||||
// disabled={!shouldFormat}
|
|
||||||
onClick={formatCode}
|
|
||||||
// className={`${!shouldFormat && 'text-gray-300'}`}
|
|
||||||
>
|
|
||||||
format
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
id="code-mirror-override"
|
|
||||||
className="overflow-x-hidden h-full"
|
|
||||||
>
|
|
||||||
<CodeMirror
|
|
||||||
className="h-full overflow-hidden-x"
|
|
||||||
value={code}
|
|
||||||
extensions={
|
|
||||||
kclLSP
|
|
||||||
? [kclLSP, lineHighlightField, ...extraExtensions]
|
|
||||||
: [lineHighlightField, ...extraExtensions]
|
|
||||||
}
|
|
||||||
onChange={onChange}
|
|
||||||
onUpdate={onUpdate}
|
|
||||||
theme={editorTheme}
|
|
||||||
onCreateEditor={(_editorView) => setEditorView(_editorView)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</CollapsiblePanel>
|
</CollapsiblePanel>
|
||||||
<section className="flex flex-col">
|
<section className="flex flex-col">
|
||||||
<MemoryPanel
|
<MemoryPanel
|
||||||
@ -573,7 +400,7 @@ export function App() {
|
|||||||
className={
|
className={
|
||||||
'transition-opacity transition-duration-75 ' +
|
'transition-opacity transition-duration-75 ' +
|
||||||
paneOpacity +
|
paneOpacity +
|
||||||
(isMouseDownInStream ? ' pointer-events-none' : '')
|
(buttonDownInStream ? ' pointer-events-none' : '')
|
||||||
}
|
}
|
||||||
open={openPanes.includes('debug')}
|
open={openPanes.includes('debug')}
|
||||||
/>
|
/>
|
||||||
|
@ -8,7 +8,6 @@ import { EqualAngle } from './components/Toolbar/EqualAngle'
|
|||||||
import { Intersect } from './components/Toolbar/Intersect'
|
import { Intersect } from './components/Toolbar/Intersect'
|
||||||
import { SetHorzVertDistance } from './components/Toolbar/SetHorzVertDistance'
|
import { SetHorzVertDistance } from './components/Toolbar/SetHorzVertDistance'
|
||||||
import { SetAngleLength } from './components/Toolbar/setAngleLength'
|
import { SetAngleLength } from './components/Toolbar/setAngleLength'
|
||||||
import { ConvertToVariable } from './components/Toolbar/ConvertVariable'
|
|
||||||
import { SetAbsDistance } from './components/Toolbar/SetAbsDistance'
|
import { SetAbsDistance } from './components/Toolbar/SetAbsDistance'
|
||||||
import { SetAngleBetween } from './components/Toolbar/SetAngleBetween'
|
import { SetAngleBetween } from './components/Toolbar/SetAngleBetween'
|
||||||
import { Fragment, useEffect } from 'react'
|
import { Fragment, useEffect } from 'react'
|
||||||
@ -164,7 +163,6 @@ export const Toolbar = () => {
|
|||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
<ConvertToVariable />
|
|
||||||
<HorzVert horOrVert="horizontal" />
|
<HorzVert horOrVert="horizontal" />
|
||||||
<HorzVert horOrVert="vertical" />
|
<HorzVert horOrVert="vertical" />
|
||||||
<EqualLength />
|
<EqualLength />
|
||||||
|
@ -198,29 +198,25 @@ export const CreateNewVariable = ({
|
|||||||
isNewVariableNameUnique,
|
isNewVariableNameUnique,
|
||||||
setNewVariableName,
|
setNewVariableName,
|
||||||
shouldCreateVariable,
|
shouldCreateVariable,
|
||||||
setShouldCreateVariable,
|
setShouldCreateVariable = () => {},
|
||||||
showCheckbox = true,
|
showCheckbox = true,
|
||||||
}: {
|
}: {
|
||||||
isNewVariableNameUnique: boolean
|
isNewVariableNameUnique: boolean
|
||||||
newVariableName: string
|
newVariableName: string
|
||||||
setNewVariableName: (a: string) => void
|
setNewVariableName: (a: string) => void
|
||||||
shouldCreateVariable: boolean
|
shouldCreateVariable?: boolean
|
||||||
setShouldCreateVariable: (a: boolean) => void
|
setShouldCreateVariable?: (a: boolean) => void
|
||||||
showCheckbox?: boolean
|
showCheckbox?: boolean
|
||||||
}) => {
|
}) => {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<label
|
<label htmlFor="create-new-variable" className="block mt-3 font-mono">
|
||||||
htmlFor="create-new-variable"
|
|
||||||
className="block text-sm font-medium text-gray-700 mt-3 font-mono"
|
|
||||||
>
|
|
||||||
Create new variable
|
Create new variable
|
||||||
</label>
|
</label>
|
||||||
<div className="mt-1 flex flex-1">
|
<div className="mt-1 flex gap-2 items-center">
|
||||||
{showCheckbox && (
|
{showCheckbox && (
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md font-mono pl-1 flex-shrink"
|
|
||||||
checked={shouldCreateVariable}
|
checked={shouldCreateVariable}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setShouldCreateVariable(e.target.checked)
|
setShouldCreateVariable(e.target.checked)
|
||||||
@ -232,7 +228,10 @@ export const CreateNewVariable = ({
|
|||||||
disabled={!shouldCreateVariable}
|
disabled={!shouldCreateVariable}
|
||||||
name="create-new-variable"
|
name="create-new-variable"
|
||||||
id="create-new-variable"
|
id="create-new-variable"
|
||||||
className={`shadow-sm font-[monospace] focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md font-mono pl-1 flex-shrink-0 ${
|
autoFocus={true}
|
||||||
|
autoCapitalize="off"
|
||||||
|
autoCorrect="off"
|
||||||
|
className={`font-mono flex-1 sm:text-sm px-2 py-1 rounded-sm bg-chalkboard-10 dark:bg-chalkboard-90 text-chalkboard-90 dark:text-chalkboard-10 ${
|
||||||
!shouldCreateVariable ? 'opacity-50' : ''
|
!shouldCreateVariable ? 'opacity-50' : ''
|
||||||
}`}
|
}`}
|
||||||
value={newVariableName}
|
value={newVariableName}
|
||||||
|
19
src/components/CodeMenu.module.css
Normal file
19
src/components/CodeMenu.module.css
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
.button {
|
||||||
|
@apply flex justify-between items-center gap-2 px-2 py-1 text-left border-none rounded-sm;
|
||||||
|
@apply font-mono text-xs font-bold select-none text-chalkboard-90;
|
||||||
|
@apply ui-active:bg-liquid-10/50 ui-active:text-liquid-90;
|
||||||
|
@apply transition-colors ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
:global(.dark) .button {
|
||||||
|
@apply text-chalkboard-30;
|
||||||
|
@apply ui-active:bg-chalkboard-80 ui-active:text-liquid-10;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button small {
|
||||||
|
@apply text-chalkboard-60;
|
||||||
|
}
|
||||||
|
|
||||||
|
:global(.dark) .button small {
|
||||||
|
@apply text-chalkboard-40;
|
||||||
|
}
|
59
src/components/CodeMenu.tsx
Normal file
59
src/components/CodeMenu.tsx
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
import { Menu } from '@headlessui/react'
|
||||||
|
import { PropsWithChildren } from 'react'
|
||||||
|
import { faEllipsis } from '@fortawesome/free-solid-svg-icons'
|
||||||
|
import { ActionIcon } from './ActionIcon'
|
||||||
|
import { useStore } from 'useStore'
|
||||||
|
import styles from './CodeMenu.module.css'
|
||||||
|
import { useConvertToVariable } from 'hooks/useToolbarGuards'
|
||||||
|
import { editorShortcutMeta } from './TextEditor'
|
||||||
|
|
||||||
|
export const CodeMenu = ({ children }: PropsWithChildren) => {
|
||||||
|
const { formatCode } = useStore((s) => ({
|
||||||
|
formatCode: s.formatCode,
|
||||||
|
}))
|
||||||
|
const { enable: convertToVarEnabled, handleClick: handleConvertToVarClick } =
|
||||||
|
useConvertToVariable()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Menu>
|
||||||
|
<div
|
||||||
|
className="relative"
|
||||||
|
onClick={(e) => {
|
||||||
|
if (e.eventPhase === 3) {
|
||||||
|
e.stopPropagation()
|
||||||
|
e.preventDefault()
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Menu.Button className="p-0 border-none relative">
|
||||||
|
<ActionIcon
|
||||||
|
icon={faEllipsis}
|
||||||
|
bgClassName={
|
||||||
|
'bg-chalkboard-20 dark:bg-chalkboard-110 hover:bg-liquid-10/50 hover:dark:bg-chalkboard-90 ui-active:bg-chalkboard-80 ui-active:dark:bg-chalkboard-90 rounded'
|
||||||
|
}
|
||||||
|
iconClassName={'text-chalkboard-90 dark:text-chalkboard-40'}
|
||||||
|
/>
|
||||||
|
</Menu.Button>
|
||||||
|
<Menu.Items className="absolute right-0 left-auto w-72 flex flex-col gap-1 divide-y divide-chalkboard-20 dark:divide-chalkboard-70 align-stretch px-0 py-1 bg-chalkboard-10 dark:bg-chalkboard-90 rounded-sm shadow-lg border border-solid border-chalkboard-20/50 dark:border-chalkboard-80/50">
|
||||||
|
<Menu.Item>
|
||||||
|
<button onClick={() => formatCode()} className={styles.button}>
|
||||||
|
<span>Format code</span>
|
||||||
|
<small>{editorShortcutMeta.formatCode.display}</small>
|
||||||
|
</button>
|
||||||
|
</Menu.Item>
|
||||||
|
{convertToVarEnabled && (
|
||||||
|
<Menu.Item>
|
||||||
|
<button
|
||||||
|
onClick={handleConvertToVarClick}
|
||||||
|
className={styles.button}
|
||||||
|
>
|
||||||
|
<span>Convert to Variable</span>
|
||||||
|
<small>{editorShortcutMeta.convertToVariable.display}</small>
|
||||||
|
</button>
|
||||||
|
</Menu.Item>
|
||||||
|
)}
|
||||||
|
</Menu.Items>
|
||||||
|
</div>
|
||||||
|
</Menu>
|
||||||
|
)
|
||||||
|
}
|
@ -1,5 +1,5 @@
|
|||||||
.panel {
|
.panel {
|
||||||
@apply relative overflow-auto z-0;
|
@apply relative z-0;
|
||||||
@apply bg-chalkboard-10/70 backdrop-blur-sm;
|
@apply bg-chalkboard-10/70 backdrop-blur-sm;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
.header {
|
.header {
|
||||||
@apply sticky top-0 z-10 cursor-pointer;
|
@apply sticky top-0 z-10 cursor-pointer;
|
||||||
@apply flex items-center gap-2 w-full p-2;
|
@apply flex items-center justify-between gap-2 w-full p-2;
|
||||||
@apply font-mono text-xs font-bold select-none text-chalkboard-90;
|
@apply font-mono text-xs font-bold select-none text-chalkboard-90;
|
||||||
@apply bg-chalkboard-20;
|
@apply bg-chalkboard-20;
|
||||||
}
|
}
|
||||||
|
@ -8,6 +8,7 @@ export interface CollapsiblePanelProps
|
|||||||
title: string
|
title: string
|
||||||
icon?: IconDefinition
|
icon?: IconDefinition
|
||||||
open?: boolean
|
open?: boolean
|
||||||
|
menu?: React.ReactNode
|
||||||
iconClassNames?: {
|
iconClassNames?: {
|
||||||
bg?: string
|
bg?: string
|
||||||
icon?: string
|
icon?: string
|
||||||
@ -18,21 +19,27 @@ export const PanelHeader = ({
|
|||||||
title,
|
title,
|
||||||
icon,
|
icon,
|
||||||
iconClassNames,
|
iconClassNames,
|
||||||
|
menu,
|
||||||
}: CollapsiblePanelProps) => {
|
}: CollapsiblePanelProps) => {
|
||||||
return (
|
return (
|
||||||
<summary className={styles.header}>
|
<summary className={styles.header}>
|
||||||
<ActionIcon
|
<div className="flex gap-2 align-center flex-1">
|
||||||
icon={icon}
|
<ActionIcon
|
||||||
bgClassName={
|
icon={icon}
|
||||||
'bg-chalkboard-30 dark:bg-chalkboard-90 group-open:bg-chalkboard-80 rounded ' +
|
bgClassName={
|
||||||
(iconClassNames?.bg || '')
|
'bg-chalkboard-30 dark:bg-chalkboard-90 group-open:bg-chalkboard-80 rounded ' +
|
||||||
}
|
(iconClassNames?.bg || '')
|
||||||
iconClassName={
|
}
|
||||||
'text-chalkboard-90 dark:text-chalkboard-40 group-open:text-liquid-10 ' +
|
iconClassName={
|
||||||
(iconClassNames?.icon || '')
|
'text-chalkboard-90 dark:text-chalkboard-40 group-open:text-liquid-10 ' +
|
||||||
}
|
(iconClassNames?.icon || '')
|
||||||
/>
|
}
|
||||||
{title}
|
/>
|
||||||
|
{title}
|
||||||
|
</div>
|
||||||
|
<div className="group-open:opacity-100 opacity-0 group-open:pointer-events-auto pointer-events-none">
|
||||||
|
{menu}
|
||||||
|
</div>
|
||||||
</summary>
|
</summary>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -43,6 +50,7 @@ export const CollapsiblePanel = ({
|
|||||||
children,
|
children,
|
||||||
className,
|
className,
|
||||||
iconClassNames,
|
iconClassNames,
|
||||||
|
menu,
|
||||||
...props
|
...props
|
||||||
}: CollapsiblePanelProps) => {
|
}: CollapsiblePanelProps) => {
|
||||||
return (
|
return (
|
||||||
@ -50,7 +58,12 @@ export const CollapsiblePanel = ({
|
|||||||
{...props}
|
{...props}
|
||||||
className={styles.panel + ' group ' + (className || '')}
|
className={styles.panel + ' group ' + (className || '')}
|
||||||
>
|
>
|
||||||
<PanelHeader title={title} icon={icon} iconClassNames={iconClassNames} />
|
<PanelHeader
|
||||||
|
title={title}
|
||||||
|
icon={icon}
|
||||||
|
iconClassNames={iconClassNames}
|
||||||
|
menu={menu}
|
||||||
|
/>
|
||||||
{children}
|
{children}
|
||||||
</details>
|
</details>
|
||||||
)
|
)
|
||||||
|
@ -196,7 +196,7 @@ const CommandBar = () => {
|
|||||||
setCommandBarOpen(false)
|
setCommandBarOpen(false)
|
||||||
clearState()
|
clearState()
|
||||||
}}
|
}}
|
||||||
className="fixed inset-0 overflow-y-auto p-4 pt-[25vh]"
|
className="fixed inset-0 z-40 overflow-y-auto p-4 pt-[25vh]"
|
||||||
>
|
>
|
||||||
<Transition.Child
|
<Transition.Child
|
||||||
enter="duration-100 ease-out"
|
enter="duration-100 ease-out"
|
||||||
@ -207,7 +207,7 @@ const CommandBar = () => {
|
|||||||
leaveTo="opacity-0"
|
leaveTo="opacity-0"
|
||||||
as={Fragment}
|
as={Fragment}
|
||||||
>
|
>
|
||||||
<Dialog.Overlay className="fixed z-40 inset-0 bg-chalkboard-10/70 dark:bg-chalkboard-110/50" />
|
<Dialog.Overlay className="fixed inset-0 bg-chalkboard-10/70 dark:bg-chalkboard-110/50" />
|
||||||
</Transition.Child>
|
</Transition.Child>
|
||||||
<Transition.Child
|
<Transition.Child
|
||||||
enter="duration-100 ease-out"
|
enter="duration-100 ease-out"
|
||||||
@ -221,7 +221,7 @@ const CommandBar = () => {
|
|||||||
<Combobox
|
<Combobox
|
||||||
value={selectedCommand}
|
value={selectedCommand}
|
||||||
onChange={handleCommandSelection}
|
onChange={handleCommandSelection}
|
||||||
className="rounded relative mx-auto z-40 p-2 bg-chalkboard-10 dark:bg-chalkboard-100 border dark:border-chalkboard-70 max-w-xl w-full shadow-lg"
|
className="rounded relative mx-auto p-2 bg-chalkboard-10 dark:bg-chalkboard-100 border dark:border-chalkboard-70 max-w-xl w-full shadow-lg"
|
||||||
as="div"
|
as="div"
|
||||||
>
|
>
|
||||||
<div className="flex gap-2 items-center">
|
<div className="flex gap-2 items-center">
|
||||||
|
@ -1,6 +1,9 @@
|
|||||||
import { Dialog, Transition } from '@headlessui/react'
|
import { Dialog, Transition } from '@headlessui/react'
|
||||||
import { Fragment } from 'react'
|
import { Fragment } from 'react'
|
||||||
import { useCalc, CreateNewVariable } from './AvailableVarsHelpers'
|
import { useCalc, CreateNewVariable } from './AvailableVarsHelpers'
|
||||||
|
import { ActionButton } from './ActionButton'
|
||||||
|
import { faPlus } from '@fortawesome/free-solid-svg-icons'
|
||||||
|
import { toast } from 'react-hot-toast'
|
||||||
|
|
||||||
export const SetVarNameModal = ({
|
export const SetVarNameModal = ({
|
||||||
isOpen,
|
isOpen,
|
||||||
@ -19,67 +22,65 @@ export const SetVarNameModal = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Transition appear show={isOpen} as={Fragment}>
|
<Transition appear show={isOpen} as={Fragment}>
|
||||||
<Dialog as="div" className="relative z-10" onClose={onReject}>
|
<Dialog
|
||||||
|
as="div"
|
||||||
|
className="fixed inset-0 z-40 overflow-y-auto p-4 pt-[25vh]"
|
||||||
|
onClose={onReject}
|
||||||
|
>
|
||||||
<Transition.Child
|
<Transition.Child
|
||||||
as={Fragment}
|
as={Fragment}
|
||||||
enter="ease-out duration-300"
|
enter="ease-out duration-300"
|
||||||
enterFrom="opacity-0"
|
enterFrom="opacity-0 translate-y-4"
|
||||||
enterTo="opacity-100"
|
enterTo="opacity-100 translate-y-0"
|
||||||
leave="ease-in duration-200"
|
leave="ease-in duration-75"
|
||||||
leaveFrom="opacity-100"
|
leaveFrom="opacity-100"
|
||||||
leaveTo="opacity-0"
|
leaveTo="opacity-0"
|
||||||
>
|
>
|
||||||
<div className="fixed inset-0 bg-black bg-opacity-25" />
|
<Dialog.Overlay className="fixed inset-0 bg-chalkboard-10/70 dark:bg-chalkboard-110/50" />
|
||||||
</Transition.Child>
|
</Transition.Child>
|
||||||
|
|
||||||
<div className="fixed inset-0 overflow-y-auto">
|
<Transition.Child
|
||||||
<div className="flex min-h-full items-center justify-center p-4 text-center">
|
as={Fragment}
|
||||||
<Transition.Child
|
enter="ease-out duration-300"
|
||||||
as={Fragment}
|
enterFrom="opacity-0 scale-95"
|
||||||
enter="ease-out duration-300"
|
enterTo="opacity-100 scale-100"
|
||||||
enterFrom="opacity-0 scale-95"
|
leave="ease-in duration-200"
|
||||||
enterTo="opacity-100 scale-100"
|
leaveFrom="opacity-100 scale-100"
|
||||||
leave="ease-in duration-200"
|
leaveTo="opacity-0 scale-95"
|
||||||
leaveFrom="opacity-100 scale-100"
|
>
|
||||||
leaveTo="opacity-0 scale-95"
|
<Dialog.Panel className="rounded relative mx-auto px-4 py-8 bg-chalkboard-10 dark:bg-chalkboard-100 border dark:border-chalkboard-70 max-w-xl w-full shadow-lg">
|
||||||
|
<form
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
onResolve({
|
||||||
|
variableName: newVariableName,
|
||||||
|
})
|
||||||
|
toast.success(`Added variable ${newVariableName}`)
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
|
<CreateNewVariable
|
||||||
<Dialog.Title
|
setNewVariableName={setNewVariableName}
|
||||||
as="h3"
|
newVariableName={newVariableName}
|
||||||
className="text-lg font-medium leading-6 text-gray-900 capitalize"
|
isNewVariableNameUnique={isNewVariableNameUnique}
|
||||||
|
shouldCreateVariable={true}
|
||||||
|
showCheckbox={false}
|
||||||
|
/>
|
||||||
|
<div className="mt-8 flex justify-between">
|
||||||
|
<ActionButton
|
||||||
|
Element="button"
|
||||||
|
type="submit"
|
||||||
|
disabled={!isNewVariableNameUnique}
|
||||||
|
icon={{ icon: faPlus }}
|
||||||
>
|
>
|
||||||
Set {valueName}
|
Add variable
|
||||||
</Dialog.Title>
|
</ActionButton>
|
||||||
|
<ActionButton Element="button" onClick={() => onReject(false)}>
|
||||||
<CreateNewVariable
|
Cancel
|
||||||
setNewVariableName={setNewVariableName}
|
</ActionButton>
|
||||||
newVariableName={newVariableName}
|
</div>
|
||||||
isNewVariableNameUnique={isNewVariableNameUnique}
|
</form>
|
||||||
shouldCreateVariable={true}
|
</Dialog.Panel>
|
||||||
setShouldCreateVariable={() => {}}
|
</Transition.Child>
|
||||||
/>
|
|
||||||
<div className="mt-4">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
disabled={!isNewVariableNameUnique}
|
|
||||||
className={`inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 ${
|
|
||||||
!isNewVariableNameUnique
|
|
||||||
? 'opacity-50 cursor-not-allowed'
|
|
||||||
: ''
|
|
||||||
}`}
|
|
||||||
onClick={() =>
|
|
||||||
onResolve({
|
|
||||||
variableName: newVariableName,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
Add variable
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</Dialog.Panel>
|
|
||||||
</Transition.Child>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</Transition>
|
</Transition>
|
||||||
)
|
)
|
||||||
|
@ -9,27 +9,37 @@ import { v4 as uuidv4 } from 'uuid'
|
|||||||
import { useStore } from '../useStore'
|
import { useStore } from '../useStore'
|
||||||
import { getNormalisedCoordinates } from '../lib/utils'
|
import { getNormalisedCoordinates } from '../lib/utils'
|
||||||
import Loading from './Loading'
|
import Loading from './Loading'
|
||||||
|
import { cameraMouseDragGuards } from 'lib/cameraControls'
|
||||||
|
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
|
||||||
|
import { CameraDragInteractionType_type } from '@kittycad/lib/dist/types/src/models'
|
||||||
|
|
||||||
export const Stream = ({ className = '' }) => {
|
export const Stream = ({ className = '' }) => {
|
||||||
const [isLoading, setIsLoading] = useState(true)
|
const [isLoading, setIsLoading] = useState(true)
|
||||||
|
const [clickCoords, setClickCoords] = useState<{ x: number; y: number }>()
|
||||||
const videoRef = useRef<HTMLVideoElement>(null)
|
const videoRef = useRef<HTMLVideoElement>(null)
|
||||||
const {
|
const {
|
||||||
mediaStream,
|
mediaStream,
|
||||||
engineCommandManager,
|
engineCommandManager,
|
||||||
setIsMouseDownInStream,
|
setButtonDownInStream,
|
||||||
didDragInStream,
|
didDragInStream,
|
||||||
setDidDragInStream,
|
setDidDragInStream,
|
||||||
streamDimensions,
|
streamDimensions,
|
||||||
|
isExecuting,
|
||||||
} = useStore((s) => ({
|
} = useStore((s) => ({
|
||||||
mediaStream: s.mediaStream,
|
mediaStream: s.mediaStream,
|
||||||
engineCommandManager: s.engineCommandManager,
|
engineCommandManager: s.engineCommandManager,
|
||||||
isMouseDownInStream: s.isMouseDownInStream,
|
setButtonDownInStream: s.setButtonDownInStream,
|
||||||
setIsMouseDownInStream: s.setIsMouseDownInStream,
|
|
||||||
fileId: s.fileId,
|
fileId: s.fileId,
|
||||||
didDragInStream: s.didDragInStream,
|
didDragInStream: s.didDragInStream,
|
||||||
setDidDragInStream: s.setDidDragInStream,
|
setDidDragInStream: s.setDidDragInStream,
|
||||||
streamDimensions: s.streamDimensions,
|
streamDimensions: s.streamDimensions,
|
||||||
|
isExecuting: s.isExecuting,
|
||||||
}))
|
}))
|
||||||
|
const {
|
||||||
|
settings: {
|
||||||
|
context: { cameraControls },
|
||||||
|
},
|
||||||
|
} = useGlobalStateContext()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (
|
if (
|
||||||
@ -42,23 +52,29 @@ export const Stream = ({ className = '' }) => {
|
|||||||
videoRef.current.srcObject = mediaStream
|
videoRef.current.srcObject = mediaStream
|
||||||
}, [mediaStream, engineCommandManager])
|
}, [mediaStream, engineCommandManager])
|
||||||
|
|
||||||
const handleMouseDown: MouseEventHandler<HTMLVideoElement> = ({
|
const handleMouseDown: MouseEventHandler<HTMLVideoElement> = (e) => {
|
||||||
clientX,
|
|
||||||
clientY,
|
|
||||||
ctrlKey,
|
|
||||||
}) => {
|
|
||||||
if (!videoRef.current) return
|
if (!videoRef.current) return
|
||||||
const { x, y } = getNormalisedCoordinates({
|
const { x, y } = getNormalisedCoordinates({
|
||||||
clientX,
|
clientX: e.clientX,
|
||||||
clientY,
|
clientY: e.clientY,
|
||||||
el: videoRef.current,
|
el: videoRef.current,
|
||||||
...streamDimensions,
|
...streamDimensions,
|
||||||
})
|
})
|
||||||
console.log('click', x, y)
|
|
||||||
|
|
||||||
const newId = uuidv4()
|
const newId = uuidv4()
|
||||||
|
|
||||||
const interaction = ctrlKey ? 'pan' : 'rotate'
|
const interactionGuards = cameraMouseDragGuards[cameraControls]
|
||||||
|
let interaction: CameraDragInteractionType_type
|
||||||
|
|
||||||
|
if (interactionGuards.pan.callback(e)) {
|
||||||
|
interaction = 'pan'
|
||||||
|
} else if (interactionGuards.rotate.callback(e)) {
|
||||||
|
interaction = 'rotate'
|
||||||
|
} else if (interactionGuards.zoom.dragCallback(e)) {
|
||||||
|
interaction = 'zoom'
|
||||||
|
} else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
engineCommandManager?.sendSceneCommand({
|
engineCommandManager?.sendSceneCommand({
|
||||||
type: 'modeling_cmd_req',
|
type: 'modeling_cmd_req',
|
||||||
@ -70,10 +86,13 @@ export const Stream = ({ className = '' }) => {
|
|||||||
cmd_id: newId,
|
cmd_id: newId,
|
||||||
})
|
})
|
||||||
|
|
||||||
setIsMouseDownInStream(true)
|
setButtonDownInStream(e.button)
|
||||||
|
setClickCoords({ x, y })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleScroll: WheelEventHandler<HTMLVideoElement> = (e) => {
|
const handleScroll: WheelEventHandler<HTMLVideoElement> = (e) => {
|
||||||
|
if (!cameraMouseDragGuards[cameraControls].zoom.scrollCallback(e)) return
|
||||||
|
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
engineCommandManager?.sendSceneCommand({
|
engineCommandManager?.sendSceneCommand({
|
||||||
type: 'modeling_cmd_req',
|
type: 'modeling_cmd_req',
|
||||||
@ -111,7 +130,7 @@ export const Stream = ({ className = '' }) => {
|
|||||||
cmd_id: newCmdId,
|
cmd_id: newCmdId,
|
||||||
})
|
})
|
||||||
|
|
||||||
setIsMouseDownInStream(false)
|
setButtonDownInStream(0)
|
||||||
if (!didDragInStream) {
|
if (!didDragInStream) {
|
||||||
engineCommandManager?.sendSceneCommand({
|
engineCommandManager?.sendSceneCommand({
|
||||||
type: 'modeling_cmd_req',
|
type: 'modeling_cmd_req',
|
||||||
@ -124,6 +143,19 @@ export const Stream = ({ className = '' }) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
setDidDragInStream(false)
|
setDidDragInStream(false)
|
||||||
|
setClickCoords(undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleMouseMove: MouseEventHandler<HTMLVideoElement> = (e) => {
|
||||||
|
if (!clickCoords) return
|
||||||
|
|
||||||
|
const delta =
|
||||||
|
((clickCoords.x - e.clientX) ** 2 + (clickCoords.y - e.clientY) ** 2) **
|
||||||
|
0.5
|
||||||
|
|
||||||
|
if (delta > 5 && !didDragInStream) {
|
||||||
|
setDidDragInStream(true)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -139,7 +171,9 @@ export const Stream = ({ className = '' }) => {
|
|||||||
onContextMenuCapture={(e) => e.preventDefault()}
|
onContextMenuCapture={(e) => e.preventDefault()}
|
||||||
onWheel={handleScroll}
|
onWheel={handleScroll}
|
||||||
onPlay={() => setIsLoading(false)}
|
onPlay={() => setIsLoading(false)}
|
||||||
className="w-full h-full"
|
onMouseMoveCapture={handleMouseMove}
|
||||||
|
className={`w-full h-full ${isExecuting && 'blur-md'}`}
|
||||||
|
style={{ transitionDuration: '200ms', transitionProperty: 'filter' }}
|
||||||
/>
|
/>
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<div className="text-center absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
|
<div className="text-center absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
|
||||||
|
267
src/components/TextEditor.tsx
Normal file
267
src/components/TextEditor.tsx
Normal file
@ -0,0 +1,267 @@
|
|||||||
|
import ReactCodeMirror, {
|
||||||
|
Extension,
|
||||||
|
ViewUpdate,
|
||||||
|
keymap,
|
||||||
|
} from '@uiw/react-codemirror'
|
||||||
|
import { FromServer, IntoServer } from 'editor/lsp/codec'
|
||||||
|
import Server from '../editor/lsp/server'
|
||||||
|
import Client from '../editor/lsp/client'
|
||||||
|
import { TEST } from 'env'
|
||||||
|
import { useCommandsContext } from 'hooks/useCommandsContext'
|
||||||
|
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
|
||||||
|
import { useConvertToVariable } from 'hooks/useToolbarGuards'
|
||||||
|
import { Themes } from 'lib/theme'
|
||||||
|
import { useMemo } from 'react'
|
||||||
|
import { linter, lintGutter } from '@codemirror/lint'
|
||||||
|
import { Selections, useStore } from 'useStore'
|
||||||
|
import { LanguageServerClient } from 'editor/lsp'
|
||||||
|
import kclLanguage from 'editor/lsp/language'
|
||||||
|
import { isTauri } from 'lib/isTauri'
|
||||||
|
import { useParams } from 'react-router-dom'
|
||||||
|
import { writeTextFile } from '@tauri-apps/api/fs'
|
||||||
|
import { PROJECT_ENTRYPOINT } from 'lib/tauriFS'
|
||||||
|
import { toast } from 'react-hot-toast'
|
||||||
|
import {
|
||||||
|
EditorView,
|
||||||
|
addLineHighlight,
|
||||||
|
lineHighlightField,
|
||||||
|
} from 'editor/highlightextension'
|
||||||
|
import { isOverlap } from 'lib/utils'
|
||||||
|
import { kclErrToDiagnostic } from 'lang/errors'
|
||||||
|
import { CSSRuleObject } from 'tailwindcss/types/config'
|
||||||
|
|
||||||
|
export const editorShortcutMeta = {
|
||||||
|
formatCode: {
|
||||||
|
codeMirror: 'Alt-Shift-f',
|
||||||
|
display: 'Alt + Shift + F',
|
||||||
|
},
|
||||||
|
convertToVariable: {
|
||||||
|
codeMirror: 'Ctrl-Shift-c',
|
||||||
|
display: 'Ctrl + Shift + C',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TextEditor = ({
|
||||||
|
theme,
|
||||||
|
}: {
|
||||||
|
theme: Themes.Light | Themes.Dark
|
||||||
|
}) => {
|
||||||
|
const pathParams = useParams()
|
||||||
|
const {
|
||||||
|
code,
|
||||||
|
defferedSetCode,
|
||||||
|
editorView,
|
||||||
|
engineCommandManager,
|
||||||
|
formatCode,
|
||||||
|
isLSPServerReady,
|
||||||
|
selectionRanges,
|
||||||
|
selectionRangeTypeMap,
|
||||||
|
setEditorView,
|
||||||
|
setIsLSPServerReady,
|
||||||
|
setSelectionRanges,
|
||||||
|
sourceRangeMap,
|
||||||
|
} = useStore((s) => ({
|
||||||
|
code: s.code,
|
||||||
|
defferedCode: s.defferedCode,
|
||||||
|
defferedSetCode: s.defferedSetCode,
|
||||||
|
editorView: s.editorView,
|
||||||
|
engineCommandManager: s.engineCommandManager,
|
||||||
|
formatCode: s.formatCode,
|
||||||
|
isLSPServerReady: s.isLSPServerReady,
|
||||||
|
selectionRanges: s.selectionRanges,
|
||||||
|
selectionRangeTypeMap: s.selectionRangeTypeMap,
|
||||||
|
setCode: s.setCode,
|
||||||
|
setEditorView: s.setEditorView,
|
||||||
|
setIsLSPServerReady: s.setIsLSPServerReady,
|
||||||
|
setSelectionRanges: s.setSelectionRanges,
|
||||||
|
sourceRangeMap: s.sourceRangeMap,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const {
|
||||||
|
settings: {
|
||||||
|
context: { textWrapping },
|
||||||
|
},
|
||||||
|
} = useGlobalStateContext()
|
||||||
|
const { setCommandBarOpen } = useCommandsContext()
|
||||||
|
const { enable: convertEnabled, handleClick: convertCallback } =
|
||||||
|
useConvertToVariable()
|
||||||
|
|
||||||
|
// So this is a bit weird, we need to initialize the lsp server and client.
|
||||||
|
// But the server happens async so we break this into two parts.
|
||||||
|
// Below is the client and server promise.
|
||||||
|
const { lspClient } = useMemo(() => {
|
||||||
|
const intoServer: IntoServer = new IntoServer()
|
||||||
|
const fromServer: FromServer = FromServer.create()
|
||||||
|
const client = new Client(fromServer, intoServer)
|
||||||
|
if (!TEST) {
|
||||||
|
Server.initialize(intoServer, fromServer).then((lspServer) => {
|
||||||
|
lspServer.start()
|
||||||
|
setIsLSPServerReady(true)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const lspClient = new LanguageServerClient({ client })
|
||||||
|
return { lspClient }
|
||||||
|
}, [setIsLSPServerReady])
|
||||||
|
|
||||||
|
// Here we initialize the plugin which will start the client.
|
||||||
|
// When we have multi-file support the name of the file will be a dep of
|
||||||
|
// this use memo, as well as the directory structure, which I think is
|
||||||
|
// a good setup becuase it will restart the client but not the server :)
|
||||||
|
// We do not want to restart the server, its just wasteful.
|
||||||
|
const kclLSP = useMemo(() => {
|
||||||
|
let plugin = null
|
||||||
|
if (isLSPServerReady && !TEST) {
|
||||||
|
// Set up the lsp plugin.
|
||||||
|
const lsp = kclLanguage({
|
||||||
|
// When we have more than one file, we'll need to change this.
|
||||||
|
documentUri: `file:///we-just-have-one-file-for-now.kcl`,
|
||||||
|
workspaceFolders: null,
|
||||||
|
client: lspClient,
|
||||||
|
})
|
||||||
|
|
||||||
|
plugin = lsp
|
||||||
|
}
|
||||||
|
return plugin
|
||||||
|
}, [lspClient, isLSPServerReady])
|
||||||
|
|
||||||
|
// const onChange = React.useCallback((value: string, viewUpdate: ViewUpdate) => {
|
||||||
|
const onChange = (value: string, viewUpdate: ViewUpdate) => {
|
||||||
|
defferedSetCode(value)
|
||||||
|
if (isTauri() && pathParams.id) {
|
||||||
|
// Save the file to disk
|
||||||
|
// Note that PROJECT_ENTRYPOINT is hardcoded until we support multiple files
|
||||||
|
writeTextFile(pathParams.id + '/' + PROJECT_ENTRYPOINT, value).catch(
|
||||||
|
(err) => {
|
||||||
|
// TODO: add Sentry per GH issue #254 (https://github.com/KittyCAD/modeling-app/issues/254)
|
||||||
|
console.error('error saving file', err)
|
||||||
|
toast.error('Error saving file, please check file permissions')
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (editorView) {
|
||||||
|
editorView?.dispatch({ effects: addLineHighlight.of([0, 0]) })
|
||||||
|
}
|
||||||
|
} //, []);
|
||||||
|
const onUpdate = (viewUpdate: ViewUpdate) => {
|
||||||
|
if (!editorView) {
|
||||||
|
setEditorView(viewUpdate.view)
|
||||||
|
}
|
||||||
|
const ranges = viewUpdate.state.selection.ranges
|
||||||
|
|
||||||
|
const isChange =
|
||||||
|
ranges.length !== selectionRanges.codeBasedSelections.length ||
|
||||||
|
ranges.some(({ from, to }, i) => {
|
||||||
|
return (
|
||||||
|
from !== selectionRanges.codeBasedSelections[i].range[0] ||
|
||||||
|
to !== selectionRanges.codeBasedSelections[i].range[1]
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!isChange) return
|
||||||
|
const codeBasedSelections: Selections['codeBasedSelections'] = ranges.map(
|
||||||
|
({ from, to }) => {
|
||||||
|
if (selectionRangeTypeMap[to]) {
|
||||||
|
return {
|
||||||
|
type: selectionRangeTypeMap[to],
|
||||||
|
range: [from, to],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
type: 'default',
|
||||||
|
range: [from, to],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
const idBasedSelections = codeBasedSelections
|
||||||
|
.map(({ type, range }) => {
|
||||||
|
const hasOverlap = Object.entries(sourceRangeMap).filter(
|
||||||
|
([_, sourceRange]) => {
|
||||||
|
return isOverlap(sourceRange, range)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if (hasOverlap.length) {
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
id: hasOverlap[0][0],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter(Boolean) as any
|
||||||
|
|
||||||
|
engineCommandManager?.cusorsSelected({
|
||||||
|
otherSelections: [],
|
||||||
|
idBasedSelections,
|
||||||
|
})
|
||||||
|
|
||||||
|
setSelectionRanges({
|
||||||
|
otherSelections: [],
|
||||||
|
codeBasedSelections,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const editorExtensions = useMemo(() => {
|
||||||
|
const extensions = [
|
||||||
|
lineHighlightField,
|
||||||
|
keymap.of([
|
||||||
|
{
|
||||||
|
key: 'Meta-k',
|
||||||
|
run: () => {
|
||||||
|
setCommandBarOpen(true)
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: editorShortcutMeta.formatCode.codeMirror,
|
||||||
|
run: () => {
|
||||||
|
formatCode()
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: editorShortcutMeta.convertToVariable.codeMirror,
|
||||||
|
run: () => {
|
||||||
|
if (convertEnabled) {
|
||||||
|
convertCallback()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
] as Extension[]
|
||||||
|
|
||||||
|
if (kclLSP) extensions.push(kclLSP)
|
||||||
|
|
||||||
|
// These extensions have proven to mess with vitest
|
||||||
|
if (!TEST) {
|
||||||
|
extensions.push(
|
||||||
|
lintGutter(),
|
||||||
|
linter((_view) => {
|
||||||
|
return kclErrToDiagnostic(useStore.getState().kclErrors)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
if (textWrapping === 'On') extensions.push(EditorView.lineWrapping)
|
||||||
|
}
|
||||||
|
|
||||||
|
return extensions
|
||||||
|
}, [kclLSP, textWrapping])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
id="code-mirror-override"
|
||||||
|
className="full-height-subtract"
|
||||||
|
style={{ '--height-subtract': '4.25rem' } as CSSRuleObject}
|
||||||
|
>
|
||||||
|
<ReactCodeMirror
|
||||||
|
className="h-full"
|
||||||
|
value={code}
|
||||||
|
extensions={editorExtensions}
|
||||||
|
onChange={onChange}
|
||||||
|
onUpdate={onUpdate}
|
||||||
|
theme={theme}
|
||||||
|
onCreateEditor={(_editorView) => setEditorView(_editorView)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
@ -1,61 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react'
|
|
||||||
import { create } from 'react-modal-promise'
|
|
||||||
import { useStore } from '../../useStore'
|
|
||||||
import { isNodeSafeToReplace } from '../../lang/queryAst'
|
|
||||||
import { SetVarNameModal } from '../SetVarNameModal'
|
|
||||||
import { moveValueIntoNewVariable } from '../../lang/modifyAst'
|
|
||||||
|
|
||||||
const getModalInfo = create(SetVarNameModal as any)
|
|
||||||
|
|
||||||
export const ConvertToVariable = () => {
|
|
||||||
const { guiMode, selectionRanges, ast, programMemory, updateAst } = useStore(
|
|
||||||
(s) => ({
|
|
||||||
guiMode: s.guiMode,
|
|
||||||
ast: s.ast,
|
|
||||||
updateAst: s.updateAst,
|
|
||||||
selectionRanges: s.selectionRanges,
|
|
||||||
programMemory: s.programMemory,
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const [enableAngLen, setEnableAngLen] = useState(false)
|
|
||||||
useEffect(() => {
|
|
||||||
if (!ast) return
|
|
||||||
|
|
||||||
const { isSafe, value } = isNodeSafeToReplace(
|
|
||||||
ast,
|
|
||||||
selectionRanges.codeBasedSelections?.[0]?.range || []
|
|
||||||
)
|
|
||||||
const canReplace = isSafe && value.type !== 'Identifier'
|
|
||||||
const isOnlyOneSelection = selectionRanges.codeBasedSelections.length === 1
|
|
||||||
|
|
||||||
const _enableHorz = canReplace && isOnlyOneSelection
|
|
||||||
setEnableAngLen(_enableHorz)
|
|
||||||
}, [guiMode, selectionRanges])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
onClick={async () => {
|
|
||||||
if (!ast) return
|
|
||||||
try {
|
|
||||||
const { variableName } = await getModalInfo({
|
|
||||||
valueName: 'var',
|
|
||||||
} as any)
|
|
||||||
|
|
||||||
const { modifiedAst: _modifiedAst } = moveValueIntoNewVariable(
|
|
||||||
ast,
|
|
||||||
programMemory,
|
|
||||||
selectionRanges.codeBasedSelections[0].range,
|
|
||||||
variableName
|
|
||||||
)
|
|
||||||
|
|
||||||
updateAst(_modifiedAst)
|
|
||||||
} catch (e) {
|
|
||||||
console.log('e', e)
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
disabled={!enableAngLen}
|
|
||||||
>
|
|
||||||
ConvertToVariable
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
}
|
|
@ -208,7 +208,13 @@ export class LanguageServerPlugin implements PluginValue {
|
|||||||
filterText: filterText ?? label,
|
filterText: filterText ?? label,
|
||||||
}
|
}
|
||||||
if (documentation) {
|
if (documentation) {
|
||||||
completion.info = formatContents(documentation)
|
completion.info = () => {
|
||||||
|
const htmlString = formatContents(documentation)
|
||||||
|
const htmlNode = document.createElement('div')
|
||||||
|
htmlNode.style.display = 'contents'
|
||||||
|
htmlNode.innerHTML = htmlString
|
||||||
|
return { dom: htmlNode }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return completion
|
return completion
|
||||||
|
@ -8,8 +8,6 @@ export const VITE_KC_API_WS_MODELING_URL = import.meta.env
|
|||||||
.VITE_KC_API_WS_MODELING_URL
|
.VITE_KC_API_WS_MODELING_URL
|
||||||
export const VITE_KC_API_BASE_URL = import.meta.env.VITE_KC_API_BASE_URL
|
export const VITE_KC_API_BASE_URL = import.meta.env.VITE_KC_API_BASE_URL
|
||||||
export const VITE_KC_SITE_BASE_URL = import.meta.env.VITE_KC_SITE_BASE_URL
|
export const VITE_KC_SITE_BASE_URL = import.meta.env.VITE_KC_SITE_BASE_URL
|
||||||
export const VITE_KC_CONNECTION_WEBRTC_REPORT_STATS_MS = import.meta.env
|
|
||||||
.VITE_KC_CONNECTION_WEBRTC_REPORT_STATS_MS
|
|
||||||
export const VITE_KC_CONNECTION_TIMEOUT_MS = import.meta.env
|
export const VITE_KC_CONNECTION_TIMEOUT_MS = import.meta.env
|
||||||
.VITE_KC_CONNECTION_TIMEOUT_MS
|
.VITE_KC_CONNECTION_TIMEOUT_MS
|
||||||
export const VITE_KC_SENTRY_DSN = import.meta.env.VITE_KC_SENTRY_DSN
|
export const VITE_KC_SENTRY_DSN = import.meta.env.VITE_KC_SENTRY_DSN
|
||||||
|
56
src/hooks/useToolbarGuards.ts
Normal file
56
src/hooks/useToolbarGuards.ts
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
import { SetVarNameModal } from 'components/SetVarNameModal'
|
||||||
|
import { moveValueIntoNewVariable } from 'lang/modifyAst'
|
||||||
|
import { isNodeSafeToReplace } from 'lang/queryAst'
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { create } from 'react-modal-promise'
|
||||||
|
import { useStore } from 'useStore'
|
||||||
|
|
||||||
|
const getModalInfo = create(SetVarNameModal as any)
|
||||||
|
|
||||||
|
export function useConvertToVariable() {
|
||||||
|
const { guiMode, selectionRanges, ast, programMemory, updateAst } = useStore(
|
||||||
|
(s) => ({
|
||||||
|
guiMode: s.guiMode,
|
||||||
|
ast: s.ast,
|
||||||
|
updateAst: s.updateAst,
|
||||||
|
selectionRanges: s.selectionRanges,
|
||||||
|
programMemory: s.programMemory,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
const [enable, setEnabled] = useState(false)
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ast) return
|
||||||
|
|
||||||
|
const { isSafe, value } = isNodeSafeToReplace(
|
||||||
|
ast,
|
||||||
|
selectionRanges.codeBasedSelections?.[0]?.range || []
|
||||||
|
)
|
||||||
|
const canReplace = isSafe && value.type !== 'Identifier'
|
||||||
|
const isOnlyOneSelection = selectionRanges.codeBasedSelections.length === 1
|
||||||
|
|
||||||
|
const _enableHorz = canReplace && isOnlyOneSelection
|
||||||
|
setEnabled(_enableHorz)
|
||||||
|
}, [guiMode, selectionRanges])
|
||||||
|
|
||||||
|
const handleClick = async () => {
|
||||||
|
if (!ast) return
|
||||||
|
try {
|
||||||
|
const { variableName } = await getModalInfo({
|
||||||
|
valueName: 'var',
|
||||||
|
} as any)
|
||||||
|
|
||||||
|
const { modifiedAst: _modifiedAst } = moveValueIntoNewVariable(
|
||||||
|
ast,
|
||||||
|
programMemory,
|
||||||
|
selectionRanges.codeBasedSelections[0].range,
|
||||||
|
variableName
|
||||||
|
)
|
||||||
|
|
||||||
|
updateAst(_modifiedAst)
|
||||||
|
} catch (e) {
|
||||||
|
console.log('e', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { enable, handleClick }
|
||||||
|
}
|
@ -82,11 +82,22 @@ code {
|
|||||||
monospace;
|
monospace;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.full-height-subtract {
|
||||||
|
--height-subtract: 2.25rem;
|
||||||
|
height: 100%;
|
||||||
|
max-height: calc(100% - var(--height-subtract));
|
||||||
|
}
|
||||||
|
|
||||||
#code-mirror-override .cm-editor {
|
#code-mirror-override .cm-editor {
|
||||||
@apply bg-transparent;
|
@apply h-full bg-transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
#code-mirror-override .cm-scroller {
|
#code-mirror-override .cm-scroller {
|
||||||
|
@apply h-full;
|
||||||
|
}
|
||||||
|
|
||||||
|
#code-mirror-override .cm-scroller::-webkit-scrollbar {
|
||||||
|
@apply h-0;
|
||||||
}
|
}
|
||||||
|
|
||||||
#code-mirror-override .cm-activeLine,
|
#code-mirror-override .cm-activeLine,
|
||||||
@ -137,14 +148,39 @@ code {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#code-mirror-override .cm-tooltip {
|
#code-mirror-override .cm-tooltip {
|
||||||
font-size: 80%;
|
@apply text-xs shadow-md;
|
||||||
|
@apply bg-chalkboard-10 text-chalkboard-80;
|
||||||
|
@apply rounded-sm border-solid border border-chalkboard-40/30 border-l-liquid-10;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark #code-mirror-override .cm-tooltip {
|
||||||
|
@apply bg-chalkboard-110 text-chalkboard-40;
|
||||||
|
@apply border-chalkboard-70/20 border-l-liquid-70;
|
||||||
}
|
}
|
||||||
|
|
||||||
#code-mirror-override .cm-tooltip-hover {
|
#code-mirror-override .cm-tooltip-hover {
|
||||||
|
@apply py-1 px-2 w-max max-w-md;
|
||||||
}
|
}
|
||||||
|
|
||||||
#code-mirror-override .cm-tooltip-hover .documentation {
|
#code-mirror-override .cm-completionInfo {
|
||||||
padding: 5;
|
@apply px-4 rounded-l-none;
|
||||||
|
@apply bg-chalkboard-10 text-liquid-90;
|
||||||
|
@apply border-liquid-40/30;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark #code-mirror-override .cm-completionInfo {
|
||||||
|
@apply bg-liquid-120 text-liquid-50;
|
||||||
|
@apply border-liquid-90/60;
|
||||||
|
}
|
||||||
|
|
||||||
|
#code-mirror-override .cm-tooltip-autocomplete li {
|
||||||
|
@apply px-2 py-1;
|
||||||
|
}
|
||||||
|
#code-mirror-override .cm-tooltip-autocomplete li[aria-selected='true'] {
|
||||||
|
@apply bg-liquid-10 text-liquid-110;
|
||||||
|
}
|
||||||
|
.dark #code-mirror-override .cm-tooltip-autocomplete li[aria-selected='true'] {
|
||||||
|
@apply bg-liquid-100 text-liquid-20;
|
||||||
}
|
}
|
||||||
|
|
||||||
#code-mirror-override .cm-content {
|
#code-mirror-override .cm-content {
|
||||||
|
@ -1564,7 +1564,7 @@ const key = 'c'`
|
|||||||
start: code.indexOf('\n// this is a comment'),
|
start: code.indexOf('\n// this is a comment'),
|
||||||
end: code.indexOf('const key'),
|
end: code.indexOf('const key'),
|
||||||
value: {
|
value: {
|
||||||
type: 'block',
|
type: 'blockComment',
|
||||||
value: 'this is a comment',
|
value: 'this is a comment',
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@ -1602,7 +1602,7 @@ const key = 'c'`
|
|||||||
start: 106,
|
start: 106,
|
||||||
end: 166,
|
end: 166,
|
||||||
value: {
|
value: {
|
||||||
type: 'block',
|
type: 'blockComment',
|
||||||
value: 'this is\n a comment\n spanning a few lines',
|
value: 'this is\n a comment\n spanning a few lines',
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@ -1625,7 +1625,7 @@ const key = 'c'`
|
|||||||
start: 125,
|
start: 125,
|
||||||
end: 141,
|
end: 141,
|
||||||
value: {
|
value: {
|
||||||
type: 'block',
|
type: 'blockComment',
|
||||||
value: 'a comment',
|
value: 'a comment',
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
@ -318,9 +318,9 @@ describe('it recasts wrapped object expressions in pipe bodies with correct inde
|
|||||||
|> line({ to: [0.62, 4.15], tag: 'seg01' }, %)
|
|> line({ to: [0.62, 4.15], tag: 'seg01' }, %)
|
||||||
|> line([2.77, -1.24], %)
|
|> line([2.77, -1.24], %)
|
||||||
|> angledLineThatIntersects({
|
|> angledLineThatIntersects({
|
||||||
angle: 201,
|
angle: 201,
|
||||||
offset: -1.35,
|
offset: -1.35,
|
||||||
intersectTag: 'seg01'
|
intersectTag: 'seg01'
|
||||||
}, %)
|
}, %)
|
||||||
|> line([-0.42, -1.72], %)
|
|> line([-0.42, -1.72], %)
|
||||||
show(part001)`
|
show(part001)`
|
||||||
|
@ -1,20 +1,21 @@
|
|||||||
import { SourceRange } from 'lang/executor'
|
import { SourceRange } from 'lang/executor'
|
||||||
import { Selections } from 'useStore'
|
import { Selections } from 'useStore'
|
||||||
import {
|
import { VITE_KC_API_WS_MODELING_URL, VITE_KC_CONNECTION_TIMEOUT_MS } from 'env'
|
||||||
VITE_KC_API_WS_MODELING_URL,
|
|
||||||
VITE_KC_CONNECTION_TIMEOUT_MS,
|
|
||||||
VITE_KC_CONNECTION_WEBRTC_REPORT_STATS_MS,
|
|
||||||
} from 'env'
|
|
||||||
import { Models } from '@kittycad/lib'
|
import { Models } from '@kittycad/lib'
|
||||||
import { exportSave } from 'lib/exportSave'
|
import { exportSave } from 'lib/exportSave'
|
||||||
import { v4 as uuidv4 } from 'uuid'
|
import { v4 as uuidv4 } from 'uuid'
|
||||||
import * as Sentry from '@sentry/react'
|
import * as Sentry from '@sentry/react'
|
||||||
|
|
||||||
interface ResultCommand {
|
interface CommandInfo {
|
||||||
|
commandType: CommandTypes
|
||||||
|
range: SourceRange
|
||||||
|
parentId?: string
|
||||||
|
}
|
||||||
|
interface ResultCommand extends CommandInfo {
|
||||||
type: 'result'
|
type: 'result'
|
||||||
data: any
|
data: any
|
||||||
}
|
}
|
||||||
interface PendingCommand {
|
interface PendingCommand extends CommandInfo {
|
||||||
type: 'pending'
|
type: 'pending'
|
||||||
promise: Promise<any>
|
promise: Promise<any>
|
||||||
resolve: (val: any) => void
|
resolve: (val: any) => void
|
||||||
@ -34,6 +35,8 @@ interface NewTrackArgs {
|
|||||||
|
|
||||||
type WebSocketResponse = Models['OkWebSocketResponseData_type']
|
type WebSocketResponse = Models['OkWebSocketResponseData_type']
|
||||||
|
|
||||||
|
type ClientMetrics = Models['ClientMetrics_type']
|
||||||
|
|
||||||
// EngineConnection encapsulates the connection(s) to the Engine
|
// EngineConnection encapsulates the connection(s) to the Engine
|
||||||
// for the EngineCommandManager; namely, the underlying WebSocket
|
// for the EngineCommandManager; namely, the underlying WebSocket
|
||||||
// and WebRTC connections.
|
// and WebRTC connections.
|
||||||
@ -53,6 +56,9 @@ export class EngineConnection {
|
|||||||
private onClose: (engineConnection: EngineConnection) => void
|
private onClose: (engineConnection: EngineConnection) => void
|
||||||
private onNewTrack: (track: NewTrackArgs) => void
|
private onNewTrack: (track: NewTrackArgs) => void
|
||||||
|
|
||||||
|
// TODO: actual type is ClientMetrics
|
||||||
|
private webrtcStatsCollector?: () => Promise<ClientMetrics>
|
||||||
|
|
||||||
constructor({
|
constructor({
|
||||||
url,
|
url,
|
||||||
token,
|
token,
|
||||||
@ -188,15 +194,17 @@ export class EngineConnection {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
Promise.all([
|
if (this.shouldTrace()) {
|
||||||
handshakeSpan.promise,
|
Promise.all([
|
||||||
iceSpan.promise,
|
handshakeSpan.promise,
|
||||||
dataChannelSpan.promise,
|
iceSpan.promise,
|
||||||
mediaTrackSpan.promise,
|
dataChannelSpan.promise,
|
||||||
]).then(() => {
|
mediaTrackSpan.promise,
|
||||||
console.log('All spans finished, reporting')
|
]).then(() => {
|
||||||
webrtcMediaTransaction?.finish()
|
console.log('All spans finished, reporting')
|
||||||
})
|
webrtcMediaTransaction?.finish()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
this.onWebsocketOpen(this)
|
this.onWebsocketOpen(this)
|
||||||
})
|
})
|
||||||
@ -297,7 +305,9 @@ export class EngineConnection {
|
|||||||
|
|
||||||
this.pc.addEventListener('connectionstatechange', (event) => {
|
this.pc.addEventListener('connectionstatechange', (event) => {
|
||||||
if (this.pc?.iceConnectionState === 'connected') {
|
if (this.pc?.iceConnectionState === 'connected') {
|
||||||
iceSpan.resolve?.()
|
if (this.shouldTrace()) {
|
||||||
|
iceSpan.resolve?.()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@ -330,6 +340,17 @@ export class EngineConnection {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
.catch(console.log)
|
.catch(console.log)
|
||||||
|
} else if (resp.type === 'metrics_request') {
|
||||||
|
if (this.webrtcStatsCollector === undefined) {
|
||||||
|
// TODO: Error message here?
|
||||||
|
return
|
||||||
|
}
|
||||||
|
this.webrtcStatsCollector().then((client_metrics) => {
|
||||||
|
this.send({
|
||||||
|
type: 'metrics_response',
|
||||||
|
metrics: client_metrics,
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO(paultag): This ought to be both controllable, as well as something
|
// TODO(paultag): This ought to be both controllable, as well as something
|
||||||
@ -361,127 +382,58 @@ export class EngineConnection {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set up the background thread to keep an eye on statistical
|
this.webrtcStatsCollector = (): Promise<ClientMetrics> => {
|
||||||
// information about the WebRTC media stream from the server to
|
return new Promise((resolve, reject) => {
|
||||||
// us. We'll also eventually want more global statistical information,
|
if (mediaStream.getVideoTracks().length !== 1) {
|
||||||
// but this will give us a baseline.
|
reject(new Error('too many video tracks to report'))
|
||||||
if (parseInt(VITE_KC_CONNECTION_WEBRTC_REPORT_STATS_MS) !== 0) {
|
|
||||||
setInterval(() => {
|
|
||||||
if (this.pc === undefined) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (!this.shouldTrace()) {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the WebRTC Statistics API to collect statistical information
|
let videoTrack = mediaStream.getVideoTracks()[0]
|
||||||
// about the WebRTC connection we're using to report to Sentry.
|
this.pc?.getStats(videoTrack).then((videoTrackStats) => {
|
||||||
mediaStream.getVideoTracks().forEach((videoTrack) => {
|
// TODO(paultag): this needs type information from the KittyCAD typescript
|
||||||
let trackStats = new Map<string, any>()
|
// library once it's updated
|
||||||
this.pc?.getStats(videoTrack).then((videoTrackStats) => {
|
let client_metrics: ClientMetrics = {
|
||||||
// Sentry only allows 10 metrics per transaction. We're going
|
rtc_frames_decoded: 0,
|
||||||
// to have to pick carefully here, eventually send like a prom
|
rtc_frames_dropped: 0,
|
||||||
// file or something to the peer.
|
rtc_frames_received: 0,
|
||||||
|
rtc_frames_per_second: 0,
|
||||||
|
rtc_freeze_count: 0,
|
||||||
|
rtc_jitter_sec: 0.0,
|
||||||
|
rtc_keyframes_decoded: 0,
|
||||||
|
rtc_total_freezes_duration_sec: 0.0,
|
||||||
|
}
|
||||||
|
|
||||||
const transaction = Sentry.startTransaction({
|
// TODO(paultag): Since we can technically have multiple WebRTC
|
||||||
name: 'webrtc-stats',
|
// video tracks (even if the Server doesn't at the moment), we
|
||||||
})
|
// ought to send stats for every video track(?), and add the stream
|
||||||
videoTrackStats.forEach((videoTrackReport) => {
|
// ID into it. This raises the cardinality of collected metrics
|
||||||
if (videoTrackReport.type === 'inbound-rtp') {
|
// when/if we do, but for now, just report the one stream.
|
||||||
// RTC Stream Info
|
|
||||||
// transaction.setMeasurement(
|
videoTrackStats.forEach((videoTrackReport) => {
|
||||||
// 'mediaStreamTrack.framesDecoded',
|
if (videoTrackReport.type === 'inbound-rtp') {
|
||||||
// videoTrackReport.framesDecoded,
|
client_metrics.rtc_frames_decoded =
|
||||||
// 'frame'
|
videoTrackReport.framesDecoded
|
||||||
// )
|
client_metrics.rtc_frames_dropped =
|
||||||
transaction.setMeasurement(
|
videoTrackReport.framesDropped
|
||||||
'rtcFramesDropped',
|
client_metrics.rtc_frames_received =
|
||||||
videoTrackReport.framesDropped,
|
videoTrackReport.framesReceived
|
||||||
''
|
client_metrics.rtc_frames_per_second =
|
||||||
)
|
videoTrackReport.framesPerSecond || 0
|
||||||
// transaction.setMeasurement(
|
client_metrics.rtc_freeze_count = videoTrackReport.freezeCount
|
||||||
// 'mediaStreamTrack.framesReceived',
|
client_metrics.rtc_jitter_sec = videoTrackReport.jitter
|
||||||
// videoTrackReport.framesReceived,
|
client_metrics.rtc_keyframes_decoded =
|
||||||
// 'frame'
|
videoTrackReport.keyFramesDecoded
|
||||||
// )
|
client_metrics.rtc_total_freezes_duration_sec =
|
||||||
transaction.setMeasurement(
|
videoTrackReport.totalFreezesDuration
|
||||||
'rtcFramesPerSecond',
|
} else if (videoTrackReport.type === 'transport') {
|
||||||
videoTrackReport.framesPerSecond,
|
// videoTrackReport.bytesReceived,
|
||||||
'fps'
|
// videoTrackReport.bytesSent,
|
||||||
)
|
}
|
||||||
transaction.setMeasurement(
|
|
||||||
'rtcFreezeCount',
|
|
||||||
videoTrackReport.freezeCount,
|
|
||||||
''
|
|
||||||
)
|
|
||||||
transaction.setMeasurement(
|
|
||||||
'rtcJitter',
|
|
||||||
videoTrackReport.jitter,
|
|
||||||
'second'
|
|
||||||
)
|
|
||||||
// transaction.setMeasurement(
|
|
||||||
// 'mediaStreamTrack.jitterBufferDelay',
|
|
||||||
// videoTrackReport.jitterBufferDelay,
|
|
||||||
// ''
|
|
||||||
// )
|
|
||||||
// transaction.setMeasurement(
|
|
||||||
// 'mediaStreamTrack.jitterBufferEmittedCount',
|
|
||||||
// videoTrackReport.jitterBufferEmittedCount,
|
|
||||||
// ''
|
|
||||||
// )
|
|
||||||
// transaction.setMeasurement(
|
|
||||||
// 'mediaStreamTrack.jitterBufferMinimumDelay',
|
|
||||||
// videoTrackReport.jitterBufferMinimumDelay,
|
|
||||||
// ''
|
|
||||||
// )
|
|
||||||
// transaction.setMeasurement(
|
|
||||||
// 'mediaStreamTrack.jitterBufferTargetDelay',
|
|
||||||
// videoTrackReport.jitterBufferTargetDelay,
|
|
||||||
// ''
|
|
||||||
// )
|
|
||||||
transaction.setMeasurement(
|
|
||||||
'rtcKeyFramesDecoded',
|
|
||||||
videoTrackReport.keyFramesDecoded,
|
|
||||||
''
|
|
||||||
)
|
|
||||||
transaction.setMeasurement(
|
|
||||||
'rtcTotalFreezesDuration',
|
|
||||||
videoTrackReport.totalFreezesDuration,
|
|
||||||
'second'
|
|
||||||
)
|
|
||||||
// transaction.setMeasurement(
|
|
||||||
// 'mediaStreamTrack.totalInterFrameDelay',
|
|
||||||
// videoTrackReport.totalInterFrameDelay,
|
|
||||||
// ''
|
|
||||||
// )
|
|
||||||
transaction.setMeasurement(
|
|
||||||
'rtcTotalPausesDuration',
|
|
||||||
videoTrackReport.totalPausesDuration,
|
|
||||||
'second'
|
|
||||||
)
|
|
||||||
// transaction.setMeasurement(
|
|
||||||
// 'mediaStreamTrack.totalProcessingDelay',
|
|
||||||
// videoTrackReport.totalProcessingDelay,
|
|
||||||
// 'second'
|
|
||||||
// )
|
|
||||||
} else if (videoTrackReport.type === 'transport') {
|
|
||||||
// // Bytes i/o
|
|
||||||
// transaction.setMeasurement(
|
|
||||||
// 'mediaStreamTrack.bytesReceived',
|
|
||||||
// videoTrackReport.bytesReceived,
|
|
||||||
// 'byte'
|
|
||||||
// )
|
|
||||||
// transaction.setMeasurement(
|
|
||||||
// 'mediaStreamTrack.bytesSent',
|
|
||||||
// videoTrackReport.bytesSent,
|
|
||||||
// 'byte'
|
|
||||||
// )
|
|
||||||
}
|
|
||||||
})
|
|
||||||
transaction?.finish()
|
|
||||||
})
|
})
|
||||||
|
resolve(client_metrics)
|
||||||
})
|
})
|
||||||
}, VITE_KC_CONNECTION_WEBRTC_REPORT_STATS_MS)
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
this.onNewTrack({
|
this.onNewTrack({
|
||||||
@ -490,10 +442,6 @@ export class EngineConnection {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
// During startup, we'll track the time from `connect` being called
|
|
||||||
// until the 'done' event fires.
|
|
||||||
let connectionStarted = new Date()
|
|
||||||
|
|
||||||
this.pc.addEventListener('datachannel', (event) => {
|
this.pc.addEventListener('datachannel', (event) => {
|
||||||
this.unreliableDataChannel = event.channel
|
this.unreliableDataChannel = event.channel
|
||||||
|
|
||||||
@ -537,6 +485,7 @@ export class EngineConnection {
|
|||||||
this.websocket = undefined
|
this.websocket = undefined
|
||||||
this.pc = undefined
|
this.pc = undefined
|
||||||
this.unreliableDataChannel = undefined
|
this.unreliableDataChannel = undefined
|
||||||
|
this.webrtcStatsCollector = undefined
|
||||||
|
|
||||||
this.onClose(this)
|
this.onClose(this)
|
||||||
this.ready = false
|
this.ready = false
|
||||||
@ -546,6 +495,8 @@ export class EngineConnection {
|
|||||||
export type EngineCommand = Models['WebSocketRequest_type']
|
export type EngineCommand = Models['WebSocketRequest_type']
|
||||||
type ModelTypes = Models['OkModelingCmdResponse_type']['type']
|
type ModelTypes = Models['OkModelingCmdResponse_type']['type']
|
||||||
|
|
||||||
|
type CommandTypes = Models['ModelingCmd_type']['type']
|
||||||
|
|
||||||
type UnreliableResponses = Extract<
|
type UnreliableResponses = Extract<
|
||||||
Models['OkModelingCmdResponse_type'],
|
Models['OkModelingCmdResponse_type'],
|
||||||
{ type: 'highlight_set_entity' }
|
{ type: 'highlight_set_entity' }
|
||||||
@ -687,15 +638,22 @@ export class EngineCommandManager {
|
|||||||
const resolve = command.resolve
|
const resolve = command.resolve
|
||||||
this.artifactMap[id] = {
|
this.artifactMap[id] = {
|
||||||
type: 'result',
|
type: 'result',
|
||||||
|
range: command.range,
|
||||||
|
commandType: command.commandType,
|
||||||
|
parentId: command.parentId ? command.parentId : undefined,
|
||||||
data: modelingResponse,
|
data: modelingResponse,
|
||||||
}
|
}
|
||||||
resolve({
|
resolve({
|
||||||
id,
|
id,
|
||||||
|
commandType: command.commandType,
|
||||||
|
range: command.range,
|
||||||
data: modelingResponse,
|
data: modelingResponse,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
this.artifactMap[id] = {
|
this.artifactMap[id] = {
|
||||||
type: 'result',
|
type: 'result',
|
||||||
|
commandType: command?.commandType,
|
||||||
|
range: command?.range,
|
||||||
data: modelingResponse,
|
data: modelingResponse,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -747,8 +705,29 @@ export class EngineCommandManager {
|
|||||||
delete this.unreliableSubscriptions[event][id]
|
delete this.unreliableSubscriptions[event][id]
|
||||||
}
|
}
|
||||||
endSession() {
|
endSession() {
|
||||||
// this.websocket?.close()
|
// TODO: instead of sending a single command with `object_ids: Object.keys(this.artifactMap)`
|
||||||
// socket.off('command')
|
// we need to loop over them each individualy because if the engine doesn't recognise a single
|
||||||
|
// id the whole command fails.
|
||||||
|
Object.entries(this.artifactMap).forEach(([id, artifact]) => {
|
||||||
|
const artifactTypesToDelete: ArtifactMap[string]['commandType'][] = [
|
||||||
|
// 'start_path' creates a new scene object for the path, which is why it needs to be deleted,
|
||||||
|
// however all of the segments in the path are its children so there don't need to be deleted.
|
||||||
|
// this fact is very opaque in the api and docs (as to what should can be deleted).
|
||||||
|
// Using an array is the list is likely to grow.
|
||||||
|
'start_path',
|
||||||
|
]
|
||||||
|
if (!artifactTypesToDelete.includes(artifact.commandType)) return
|
||||||
|
|
||||||
|
const deletCmd: EngineCommand = {
|
||||||
|
type: 'modeling_cmd_req',
|
||||||
|
cmd_id: uuidv4(),
|
||||||
|
cmd: {
|
||||||
|
type: 'remove_scene_objects',
|
||||||
|
object_ids: [id],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
this.engineConnection?.send(deletCmd)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
cusorsSelected(selections: {
|
cusorsSelected(selections: {
|
||||||
otherSelections: Selections['otherSelections']
|
otherSelections: Selections['otherSelections']
|
||||||
@ -801,11 +780,20 @@ export class EngineCommandManager {
|
|||||||
JSON.stringify(command)
|
JSON.stringify(command)
|
||||||
)
|
)
|
||||||
return Promise.resolve()
|
return Promise.resolve()
|
||||||
|
} else if (
|
||||||
|
cmd.type === 'mouse_move' &&
|
||||||
|
this.engineConnection.unreliableDataChannel
|
||||||
|
) {
|
||||||
|
cmd.sequence = this.outSequence
|
||||||
|
this.outSequence++
|
||||||
|
this.engineConnection?.unreliableDataChannel?.send(
|
||||||
|
JSON.stringify(command)
|
||||||
|
)
|
||||||
|
return Promise.resolve()
|
||||||
}
|
}
|
||||||
console.log('sending command', command)
|
|
||||||
// since it's not mouse drag or highlighting send over TCP and keep track of the command
|
// since it's not mouse drag or highlighting send over TCP and keep track of the command
|
||||||
this.engineConnection?.send(command)
|
this.engineConnection?.send(command)
|
||||||
return this.handlePendingCommand(command.cmd_id)
|
return this.handlePendingCommand(command.cmd_id, command.cmd)
|
||||||
}
|
}
|
||||||
sendModelingCommand({
|
sendModelingCommand({
|
||||||
id,
|
id,
|
||||||
@ -823,15 +811,35 @@ export class EngineCommandManager {
|
|||||||
return Promise.resolve()
|
return Promise.resolve()
|
||||||
}
|
}
|
||||||
this.engineConnection?.send(command)
|
this.engineConnection?.send(command)
|
||||||
return this.handlePendingCommand(id)
|
if (typeof command !== 'string' && command.type === 'modeling_cmd_req') {
|
||||||
|
return this.handlePendingCommand(id, command?.cmd, range)
|
||||||
|
} else if (typeof command === 'string') {
|
||||||
|
const parseCommand: EngineCommand = JSON.parse(command)
|
||||||
|
if (parseCommand.type === 'modeling_cmd_req')
|
||||||
|
return this.handlePendingCommand(id, parseCommand?.cmd, range)
|
||||||
|
}
|
||||||
|
throw 'shouldnt reach here'
|
||||||
}
|
}
|
||||||
handlePendingCommand(id: string) {
|
handlePendingCommand(
|
||||||
|
id: string,
|
||||||
|
command: Models['ModelingCmd_type'],
|
||||||
|
range?: SourceRange
|
||||||
|
) {
|
||||||
let resolve: (val: any) => void = () => {}
|
let resolve: (val: any) => void = () => {}
|
||||||
const promise = new Promise((_resolve, reject) => {
|
const promise = new Promise((_resolve, reject) => {
|
||||||
resolve = _resolve
|
resolve = _resolve
|
||||||
})
|
})
|
||||||
|
const getParentId = (): string | undefined => {
|
||||||
|
if (command.type === 'extend_path') {
|
||||||
|
return command.path
|
||||||
|
}
|
||||||
|
// TODO handle other commands that have a parent
|
||||||
|
}
|
||||||
this.artifactMap[id] = {
|
this.artifactMap[id] = {
|
||||||
|
range: range || [0, 0],
|
||||||
type: 'pending',
|
type: 'pending',
|
||||||
|
commandType: command.type,
|
||||||
|
parentId: getParentId(),
|
||||||
promise,
|
promise,
|
||||||
resolve,
|
resolve,
|
||||||
}
|
}
|
||||||
|
@ -59,19 +59,19 @@ describe('testing swaping out sketch calls with xLine/xLineTo', () => {
|
|||||||
` |> lineTo({ to: [1, 1], tag: 'abc1' }, %)`,
|
` |> lineTo({ to: [1, 1], tag: 'abc1' }, %)`,
|
||||||
` |> line({ to: [-2.04, -0.7], tag: 'abc2' }, %)`,
|
` |> line({ to: [-2.04, -0.7], tag: 'abc2' }, %)`,
|
||||||
` |> angledLine({`,
|
` |> angledLine({`,
|
||||||
` angle: 157,`,
|
` angle: 157,`,
|
||||||
` length: 1.69,`,
|
` length: 1.69,`,
|
||||||
` tag: 'abc3'`,
|
` tag: 'abc3'`,
|
||||||
` }, %)`,
|
` }, %)`,
|
||||||
` |> angledLineOfXLength({`,
|
` |> angledLineOfXLength({`,
|
||||||
` angle: 217,`,
|
` angle: 217,`,
|
||||||
` length: 0.86,`,
|
` length: 0.86,`,
|
||||||
` tag: 'abc4'`,
|
` tag: 'abc4'`,
|
||||||
` }, %)`,
|
` }, %)`,
|
||||||
` |> angledLineOfYLength({`,
|
` |> angledLineOfYLength({`,
|
||||||
` angle: 104,`,
|
` angle: 104,`,
|
||||||
` length: 1.58,`,
|
` length: 1.58,`,
|
||||||
` tag: 'abc5'`,
|
` tag: 'abc5'`,
|
||||||
` }, %)`,
|
` }, %)`,
|
||||||
` |> angledLineToX({ angle: 55, to: -2.89, tag: 'abc6' }, %)`,
|
` |> angledLineToX({ angle: 55, to: -2.89, tag: 'abc6' }, %)`,
|
||||||
` |> angledLineToY({ angle: 330, to: 2.53, tag: 'abc7' }, %)`,
|
` |> angledLineToY({ angle: 330, to: 2.53, tag: 'abc7' }, %)`,
|
||||||
@ -144,9 +144,9 @@ describe('testing swaping out sketch calls with xLine/xLineTo', () => {
|
|||||||
inputCode: bigExample,
|
inputCode: bigExample,
|
||||||
callToSwap: [
|
callToSwap: [
|
||||||
`angledLine({`,
|
`angledLine({`,
|
||||||
` angle: 157,`,
|
` angle: 157,`,
|
||||||
` length: 1.69,`,
|
` length: 1.69,`,
|
||||||
` tag: 'abc3'`,
|
` tag: 'abc3'`,
|
||||||
` }, %)`,
|
` }, %)`,
|
||||||
].join('\n'),
|
].join('\n'),
|
||||||
constraintType: 'horizontal',
|
constraintType: 'horizontal',
|
||||||
@ -172,9 +172,9 @@ describe('testing swaping out sketch calls with xLine/xLineTo', () => {
|
|||||||
inputCode: bigExample,
|
inputCode: bigExample,
|
||||||
callToSwap: [
|
callToSwap: [
|
||||||
`angledLineOfXLength({`,
|
`angledLineOfXLength({`,
|
||||||
` angle: 217,`,
|
` angle: 217,`,
|
||||||
` length: 0.86,`,
|
` length: 0.86,`,
|
||||||
` tag: 'abc4'`,
|
` tag: 'abc4'`,
|
||||||
` }, %)`,
|
` }, %)`,
|
||||||
].join('\n'),
|
].join('\n'),
|
||||||
constraintType: 'horizontal',
|
constraintType: 'horizontal',
|
||||||
@ -201,9 +201,9 @@ describe('testing swaping out sketch calls with xLine/xLineTo', () => {
|
|||||||
inputCode: bigExample,
|
inputCode: bigExample,
|
||||||
callToSwap: [
|
callToSwap: [
|
||||||
`angledLineOfYLength({`,
|
`angledLineOfYLength({`,
|
||||||
` angle: 104,`,
|
` angle: 104,`,
|
||||||
` length: 1.58,`,
|
` length: 1.58,`,
|
||||||
` tag: 'abc5'`,
|
` tag: 'abc5'`,
|
||||||
` }, %)`,
|
` }, %)`,
|
||||||
].join('\n'),
|
].join('\n'),
|
||||||
constraintType: 'vertical',
|
constraintType: 'vertical',
|
||||||
|
@ -133,64 +133,64 @@ const myAng2 = 134
|
|||||||
const part001 = startSketchAt([0, 0])
|
const part001 = startSketchAt([0, 0])
|
||||||
|> line({ to: [1, 3.82], tag: 'seg01' }, %) // ln-should-get-tag
|
|> line({ to: [1, 3.82], tag: 'seg01' }, %) // ln-should-get-tag
|
||||||
|> angledLineToX([
|
|> angledLineToX([
|
||||||
-angleToMatchLengthX('seg01', myVar, %),
|
-angleToMatchLengthX('seg01', myVar, %),
|
||||||
myVar
|
myVar
|
||||||
], %) // ln-lineTo-xAbsolute should use angleToMatchLengthX helper
|
], %) // ln-lineTo-xAbsolute should use angleToMatchLengthX helper
|
||||||
|> angledLineToY([
|
|> angledLineToY([
|
||||||
-angleToMatchLengthY('seg01', myVar, %),
|
-angleToMatchLengthY('seg01', myVar, %),
|
||||||
myVar
|
myVar
|
||||||
], %) // ln-lineTo-yAbsolute should use angleToMatchLengthY helper
|
], %) // ln-lineTo-yAbsolute should use angleToMatchLengthY helper
|
||||||
|> angledLine([45, segLen('seg01', %)], %) // ln-lineTo-free should become angledLine
|
|> angledLine([45, segLen('seg01', %)], %) // ln-lineTo-free should become angledLine
|
||||||
|> angledLine([45, segLen('seg01', %)], %) // ln-angledLineToX-free should become angledLine
|
|> angledLine([45, segLen('seg01', %)], %) // ln-angledLineToX-free should become angledLine
|
||||||
|> angledLine([myAng, segLen('seg01', %)], %) // ln-angledLineToX-angle should become angledLine
|
|> angledLine([myAng, segLen('seg01', %)], %) // ln-angledLineToX-angle should become angledLine
|
||||||
|> angledLineToX([
|
|> angledLineToX([
|
||||||
angleToMatchLengthX('seg01', myVar2, %),
|
angleToMatchLengthX('seg01', myVar2, %),
|
||||||
myVar2
|
myVar2
|
||||||
], %) // ln-angledLineToX-xAbsolute should use angleToMatchLengthX to get angle
|
], %) // ln-angledLineToX-xAbsolute should use angleToMatchLengthX to get angle
|
||||||
|> angledLine([-45, segLen('seg01', %)], %) // ln-angledLineToY-free should become angledLine
|
|> angledLine([-45, segLen('seg01', %)], %) // ln-angledLineToY-free should become angledLine
|
||||||
|> angledLine([myAng2, segLen('seg01', %)], %) // ln-angledLineToY-angle should become angledLine
|
|> angledLine([myAng2, segLen('seg01', %)], %) // ln-angledLineToY-angle should become angledLine
|
||||||
|> angledLineToY([
|
|> angledLineToY([
|
||||||
angleToMatchLengthY('seg01', myVar3, %),
|
angleToMatchLengthY('seg01', myVar3, %),
|
||||||
myVar3
|
myVar3
|
||||||
], %) // ln-angledLineToY-yAbsolute should use angleToMatchLengthY to get angle
|
], %) // ln-angledLineToY-yAbsolute should use angleToMatchLengthY to get angle
|
||||||
|> line([
|
|> line([
|
||||||
min(segLen('seg01', %), myVar),
|
min(segLen('seg01', %), myVar),
|
||||||
legLen(segLen('seg01', %), myVar)
|
legLen(segLen('seg01', %), myVar)
|
||||||
], %) // ln-should use legLen for y
|
], %) // ln-should use legLen for y
|
||||||
|> line([
|
|> line([
|
||||||
min(segLen('seg01', %), myVar),
|
min(segLen('seg01', %), myVar),
|
||||||
-legLen(segLen('seg01', %), myVar)
|
-legLen(segLen('seg01', %), myVar)
|
||||||
], %) // ln-legLen but negative
|
], %) // ln-legLen but negative
|
||||||
|> angledLine([-112, segLen('seg01', %)], %) // ln-should become angledLine
|
|> angledLine([-112, segLen('seg01', %)], %) // ln-should become angledLine
|
||||||
|> angledLine([myVar, segLen('seg01', %)], %) // ln-use segLen for secound arg
|
|> angledLine([myVar, segLen('seg01', %)], %) // ln-use segLen for secound arg
|
||||||
|> angledLine([45, segLen('seg01', %)], %) // ln-segLen again
|
|> angledLine([45, segLen('seg01', %)], %) // ln-segLen again
|
||||||
|> angledLine([54, segLen('seg01', %)], %) // ln-should be transformed to angledLine
|
|> angledLine([54, segLen('seg01', %)], %) // ln-should be transformed to angledLine
|
||||||
|> angledLineOfXLength([
|
|> angledLineOfXLength([
|
||||||
legAngX(segLen('seg01', %), myVar),
|
legAngX(segLen('seg01', %), myVar),
|
||||||
min(segLen('seg01', %), myVar)
|
min(segLen('seg01', %), myVar)
|
||||||
], %) // ln-should use legAngX to calculate angle
|
], %) // ln-should use legAngX to calculate angle
|
||||||
|> angledLineOfXLength([
|
|> angledLineOfXLength([
|
||||||
180 + legAngX(segLen('seg01', %), myVar),
|
180 + legAngX(segLen('seg01', %), myVar),
|
||||||
min(segLen('seg01', %), myVar)
|
min(segLen('seg01', %), myVar)
|
||||||
], %) // ln-same as above but should have + 180 to match original quadrant
|
], %) // ln-same as above but should have + 180 to match original quadrant
|
||||||
|> line([
|
|> line([
|
||||||
legLen(segLen('seg01', %), myVar),
|
legLen(segLen('seg01', %), myVar),
|
||||||
min(segLen('seg01', %), myVar)
|
min(segLen('seg01', %), myVar)
|
||||||
], %) // ln-legLen again but yRelative
|
], %) // ln-legLen again but yRelative
|
||||||
|> line([
|
|> line([
|
||||||
-legLen(segLen('seg01', %), myVar),
|
-legLen(segLen('seg01', %), myVar),
|
||||||
min(segLen('seg01', %), myVar)
|
min(segLen('seg01', %), myVar)
|
||||||
], %) // ln-negative legLen yRelative
|
], %) // ln-negative legLen yRelative
|
||||||
|> angledLine([58, segLen('seg01', %)], %) // ln-angledLineOfYLength-free should become angledLine
|
|> angledLine([58, segLen('seg01', %)], %) // ln-angledLineOfYLength-free should become angledLine
|
||||||
|> angledLine([myAng, segLen('seg01', %)], %) // ln-angledLineOfYLength-angle should become angledLine
|
|> angledLine([myAng, segLen('seg01', %)], %) // ln-angledLineOfYLength-angle should become angledLine
|
||||||
|> angledLineOfXLength([
|
|> angledLineOfXLength([
|
||||||
legAngY(segLen('seg01', %), myVar),
|
legAngY(segLen('seg01', %), myVar),
|
||||||
min(segLen('seg01', %), myVar)
|
min(segLen('seg01', %), myVar)
|
||||||
], %) // ln-angledLineOfYLength-yRelative use legAngY
|
], %) // ln-angledLineOfYLength-yRelative use legAngY
|
||||||
|> angledLineOfXLength([
|
|> angledLineOfXLength([
|
||||||
270 + legAngY(segLen('seg01', %), myVar),
|
270 + legAngY(segLen('seg01', %), myVar),
|
||||||
min(segLen('seg01', %), myVar)
|
min(segLen('seg01', %), myVar)
|
||||||
], %) // ln-angledLineOfYLength-yRelative with angle > 90 use binExp
|
], %) // ln-angledLineOfYLength-yRelative with angle > 90 use binExp
|
||||||
|> xLine(segLen('seg01', %), %) // ln-xLine-free should sub in segLen
|
|> xLine(segLen('seg01', %), %) // ln-xLine-free should sub in segLen
|
||||||
|> yLine(segLen('seg01', %), %) // ln-yLine-free should sub in segLen
|
|> yLine(segLen('seg01', %), %) // ln-yLine-free should sub in segLen
|
||||||
|> xLine(segLen('seg01', %), %) // ln-xLineTo-free should convert to xLine
|
|> xLine(segLen('seg01', %), %) // ln-xLineTo-free should convert to xLine
|
||||||
@ -406,9 +406,9 @@ show(part001)`
|
|||||||
'setVertDistance'
|
'setVertDistance'
|
||||||
)
|
)
|
||||||
expect(expectedCode).toContain(`|> lineTo([
|
expect(expectedCode).toContain(`|> lineTo([
|
||||||
lastSegX(%) + myVar,
|
lastSegX(%) + myVar,
|
||||||
segEndY('seg01', %) + 2.93
|
segEndY('seg01', %) + 2.93
|
||||||
], %) // xRelative`)
|
], %) // xRelative`)
|
||||||
})
|
})
|
||||||
it('testing for yRelative to horizontal distance', async () => {
|
it('testing for yRelative to horizontal distance', async () => {
|
||||||
const expectedCode = await helperThing(
|
const expectedCode = await helperThing(
|
||||||
@ -417,9 +417,9 @@ show(part001)`
|
|||||||
'setHorzDistance'
|
'setHorzDistance'
|
||||||
)
|
)
|
||||||
expect(expectedCode).toContain(`|> lineTo([
|
expect(expectedCode).toContain(`|> lineTo([
|
||||||
segEndX('seg01', %) + 2.6,
|
segEndX('seg01', %) + 2.6,
|
||||||
lastSegY(%) + myVar
|
lastSegY(%) + myVar
|
||||||
], %) // yRelative`)
|
], %) // yRelative`)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
@ -1426,7 +1426,6 @@ export function transformAstSketchLines({
|
|||||||
selectionRanges.codeBasedSelections.forEach(({ range }, index) => {
|
selectionRanges.codeBasedSelections.forEach(({ range }, index) => {
|
||||||
const callBack = transformInfos?.[index].createNode
|
const callBack = transformInfos?.[index].createNode
|
||||||
const transformTo = transformInfos?.[index].tooltip
|
const transformTo = transformInfos?.[index].tooltip
|
||||||
console.log('transformTo', transformInfos)
|
|
||||||
if (!callBack || !transformTo) throw new Error('no callback helper')
|
if (!callBack || !transformTo) throw new Error('no callback helper')
|
||||||
|
|
||||||
const getNode = getNodeFromPathCurry(
|
const getNode = getNodeFromPathCurry(
|
||||||
|
133
src/lib/cameraControls.ts
Normal file
133
src/lib/cameraControls.ts
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
const noModifiersPressed = (e: React.MouseEvent) =>
|
||||||
|
!e.ctrlKey && !e.shiftKey && !e.altKey && !e.metaKey
|
||||||
|
|
||||||
|
export type CADProgram =
|
||||||
|
| 'KittyCAD'
|
||||||
|
| 'OnShape'
|
||||||
|
| 'Solidworks'
|
||||||
|
| 'NX'
|
||||||
|
| 'Creo'
|
||||||
|
| 'AutoCAD'
|
||||||
|
|
||||||
|
export const cadPrograms: CADProgram[] = [
|
||||||
|
'KittyCAD',
|
||||||
|
'OnShape',
|
||||||
|
'Solidworks',
|
||||||
|
'NX',
|
||||||
|
'Creo',
|
||||||
|
'AutoCAD',
|
||||||
|
]
|
||||||
|
|
||||||
|
interface MouseGuardHandler {
|
||||||
|
description: string
|
||||||
|
callback: (e: React.MouseEvent) => boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MouseGuardZoomHandler {
|
||||||
|
description: string
|
||||||
|
dragCallback: (e: React.MouseEvent) => boolean
|
||||||
|
scrollCallback: (e: React.MouseEvent) => boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MouseGuard {
|
||||||
|
pan: MouseGuardHandler
|
||||||
|
zoom: MouseGuardZoomHandler
|
||||||
|
rotate: MouseGuardHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
export const cameraMouseDragGuards: Record<CADProgram, MouseGuard> = {
|
||||||
|
KittyCAD: {
|
||||||
|
pan: {
|
||||||
|
description: 'Right click + Shift + drag or middle click + drag',
|
||||||
|
callback: (e) =>
|
||||||
|
(e.button === 3 && noModifiersPressed(e)) ||
|
||||||
|
(e.button === 2 && e.shiftKey),
|
||||||
|
},
|
||||||
|
zoom: {
|
||||||
|
description: 'Scroll wheel or Right click + Ctrl + drag',
|
||||||
|
dragCallback: (e) => e.button === 2 && e.ctrlKey,
|
||||||
|
scrollCallback: () => true,
|
||||||
|
},
|
||||||
|
rotate: {
|
||||||
|
description: 'Right click + drag',
|
||||||
|
callback: (e) => e.button === 2 && noModifiersPressed(e),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
OnShape: {
|
||||||
|
pan: {
|
||||||
|
description: 'Right click + Ctrl + drag or middle click + drag',
|
||||||
|
callback: (e) =>
|
||||||
|
(e.button === 2 && e.ctrlKey) ||
|
||||||
|
(e.button === 3 && noModifiersPressed(e)),
|
||||||
|
},
|
||||||
|
zoom: {
|
||||||
|
description: 'Scroll wheel',
|
||||||
|
dragCallback: () => false,
|
||||||
|
scrollCallback: () => true,
|
||||||
|
},
|
||||||
|
rotate: {
|
||||||
|
description: 'Right click + drag',
|
||||||
|
callback: (e) => e.button === 2 && noModifiersPressed(e),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Solidworks: {
|
||||||
|
pan: {
|
||||||
|
description: 'Right click + Ctrl + drag',
|
||||||
|
callback: (e) => e.button === 2 && e.ctrlKey,
|
||||||
|
},
|
||||||
|
zoom: {
|
||||||
|
description: 'Scroll wheel or Middle click + Shift + drag',
|
||||||
|
dragCallback: (e) => e.button === 3 && e.shiftKey,
|
||||||
|
scrollCallback: () => true,
|
||||||
|
},
|
||||||
|
rotate: {
|
||||||
|
description: 'Middle click + drag',
|
||||||
|
callback: (e) => e.button === 3 && noModifiersPressed(e),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
NX: {
|
||||||
|
pan: {
|
||||||
|
description: 'Middle click + Shift + drag',
|
||||||
|
callback: (e) => e.button === 3 && e.shiftKey,
|
||||||
|
},
|
||||||
|
zoom: {
|
||||||
|
description: 'Scroll wheel or Middle click + Ctrl + drag',
|
||||||
|
dragCallback: (e) => e.button === 3 && e.ctrlKey,
|
||||||
|
scrollCallback: () => true,
|
||||||
|
},
|
||||||
|
rotate: {
|
||||||
|
description: 'Middle click + drag',
|
||||||
|
callback: (e) => e.button === 3 && noModifiersPressed(e),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Creo: {
|
||||||
|
pan: {
|
||||||
|
description: 'Middle click + Shift + drag',
|
||||||
|
callback: (e) => e.button === 3 && e.shiftKey,
|
||||||
|
},
|
||||||
|
zoom: {
|
||||||
|
description: 'Scroll wheel or Middle click + Ctrl + drag',
|
||||||
|
dragCallback: (e) => e.button === 3 && e.ctrlKey,
|
||||||
|
scrollCallback: () => true,
|
||||||
|
},
|
||||||
|
rotate: {
|
||||||
|
description: 'Middle click + drag',
|
||||||
|
callback: (e) => e.button === 3 && noModifiersPressed(e),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
AutoCAD: {
|
||||||
|
pan: {
|
||||||
|
description: 'Middle click + drag',
|
||||||
|
callback: (e) => e.button === 3 && noModifiersPressed(e),
|
||||||
|
},
|
||||||
|
zoom: {
|
||||||
|
description: 'Scroll wheel',
|
||||||
|
dragCallback: () => false,
|
||||||
|
scrollCallback: () => true,
|
||||||
|
},
|
||||||
|
rotate: {
|
||||||
|
description: 'Middle click + Shift + drag',
|
||||||
|
callback: (e) => e.button === 3 && e.shiftKey,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
@ -56,6 +56,27 @@ export function throttle<T>(
|
|||||||
return throttled
|
return throttled
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// takes a function and executes it after the wait time, if the function is called again before the wait time is up, the timer is reset
|
||||||
|
export function defferExecution<T>(func: (args: T) => any, wait: number) {
|
||||||
|
let timeout: ReturnType<typeof setTimeout> | null
|
||||||
|
let latestArgs: T
|
||||||
|
|
||||||
|
function later() {
|
||||||
|
timeout = null
|
||||||
|
func(latestArgs)
|
||||||
|
}
|
||||||
|
|
||||||
|
function deffered(args: T) {
|
||||||
|
latestArgs = args
|
||||||
|
if (timeout) {
|
||||||
|
clearTimeout(timeout)
|
||||||
|
}
|
||||||
|
timeout = setTimeout(later, wait)
|
||||||
|
}
|
||||||
|
|
||||||
|
return deffered
|
||||||
|
}
|
||||||
|
|
||||||
export function getNormalisedCoordinates({
|
export function getNormalisedCoordinates({
|
||||||
clientX,
|
clientX,
|
||||||
clientY,
|
clientY,
|
||||||
|
@ -1,29 +1,54 @@
|
|||||||
import { assign, createMachine } from 'xstate'
|
import { assign, createMachine } from 'xstate'
|
||||||
import { BaseUnit, baseUnitsUnion } from '../useStore'
|
|
||||||
import { CommandBarMeta } from '../lib/commands'
|
import { CommandBarMeta } from '../lib/commands'
|
||||||
import { Themes, getSystemTheme, setThemeClass } from '../lib/theme'
|
import { Themes, getSystemTheme, setThemeClass } from '../lib/theme'
|
||||||
|
import { CADProgram, cadPrograms } from 'lib/cameraControls'
|
||||||
|
|
||||||
|
export const DEFAULT_PROJECT_NAME = 'project-$nnn'
|
||||||
|
|
||||||
export enum UnitSystem {
|
export enum UnitSystem {
|
||||||
Imperial = 'imperial',
|
Imperial = 'imperial',
|
||||||
Metric = 'metric',
|
Metric = 'metric',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const baseUnits = {
|
||||||
|
imperial: ['in', 'ft'],
|
||||||
|
metric: ['mm', 'cm', 'm'],
|
||||||
|
} as const
|
||||||
|
|
||||||
|
export type BaseUnit = 'in' | 'ft' | 'mm' | 'cm' | 'm'
|
||||||
|
|
||||||
|
export const baseUnitsUnion = Object.values(baseUnits).flatMap((v) => v)
|
||||||
|
|
||||||
|
export type Toggle = 'On' | 'Off'
|
||||||
|
|
||||||
export const SETTINGS_PERSIST_KEY = 'SETTINGS_PERSIST_KEY'
|
export const SETTINGS_PERSIST_KEY = 'SETTINGS_PERSIST_KEY'
|
||||||
|
|
||||||
export const settingsCommandBarMeta: CommandBarMeta = {
|
export const settingsCommandBarMeta: CommandBarMeta = {
|
||||||
'Set Theme': {
|
'Set Base Unit': {
|
||||||
displayValue: (args: string[]) => 'Change the app theme',
|
displayValue: (args: string[]) => 'Set your default base unit',
|
||||||
args: [
|
args: [
|
||||||
{
|
{
|
||||||
name: 'theme',
|
name: 'baseUnit',
|
||||||
type: 'select',
|
type: 'select',
|
||||||
defaultValue: 'theme',
|
defaultValue: 'baseUnit',
|
||||||
options: Object.values(Themes).map((v) => ({ name: v })) as {
|
options: Object.values(baseUnitsUnion).map((v) => ({ name: v })),
|
||||||
name: string
|
|
||||||
}[],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
'Set Camera Controls': {
|
||||||
|
displayValue: (args: string[]) => 'Set your camera controls',
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
name: 'cameraControls',
|
||||||
|
type: 'select',
|
||||||
|
defaultValue: 'cameraControls',
|
||||||
|
options: Object.values(cadPrograms).map((v) => ({ name: v })),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
'Set Default Directory': {
|
||||||
|
hide: 'both',
|
||||||
|
},
|
||||||
'Set Default Project Name': {
|
'Set Default Project Name': {
|
||||||
displayValue: (args: string[]) => 'Set a new default project name',
|
displayValue: (args: string[]) => 'Set a new default project name',
|
||||||
hide: 'web',
|
hide: 'web',
|
||||||
@ -37,9 +62,33 @@ export const settingsCommandBarMeta: CommandBarMeta = {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
'Set Default Directory': {
|
'Set Onboarding Status': {
|
||||||
hide: 'both',
|
hide: 'both',
|
||||||
},
|
},
|
||||||
|
'Set Text Wrapping': {
|
||||||
|
displayValue: (args: string[]) => 'Set whether text in the editor wraps',
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
name: 'textWrapping',
|
||||||
|
type: 'select',
|
||||||
|
defaultValue: 'textWrapping',
|
||||||
|
options: [{ name: 'On' }, { name: 'Off' }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
'Set Theme': {
|
||||||
|
displayValue: (args: string[]) => 'Change the app theme',
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
name: 'theme',
|
||||||
|
type: 'select',
|
||||||
|
defaultValue: 'theme',
|
||||||
|
options: Object.values(Themes).map((v): { name: string } => ({
|
||||||
|
name: v,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
'Set Unit System': {
|
'Set Unit System': {
|
||||||
displayValue: (args: string[]) => 'Set your default unit system',
|
displayValue: (args: string[]) => 'Set your default unit system',
|
||||||
args: [
|
args: [
|
||||||
@ -51,20 +100,6 @@ export const settingsCommandBarMeta: CommandBarMeta = {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
'Set Base Unit': {
|
|
||||||
displayValue: (args: string[]) => 'Set your default base unit',
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
name: 'baseUnit',
|
|
||||||
type: 'select',
|
|
||||||
defaultValue: 'baseUnit',
|
|
||||||
options: Object.values(baseUnitsUnion).map((v) => ({ name: v })),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
'Set Onboarding Status': {
|
|
||||||
hide: 'both',
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const settingsMachine = createMachine(
|
export const settingsMachine = createMachine(
|
||||||
@ -73,35 +108,34 @@ export const settingsMachine = createMachine(
|
|||||||
id: 'Settings',
|
id: 'Settings',
|
||||||
predictableActionArguments: true,
|
predictableActionArguments: true,
|
||||||
context: {
|
context: {
|
||||||
theme: Themes.System,
|
|
||||||
defaultProjectName: '',
|
|
||||||
unitSystem: UnitSystem.Imperial,
|
|
||||||
baseUnit: 'in' as BaseUnit,
|
baseUnit: 'in' as BaseUnit,
|
||||||
|
cameraControls: 'KittyCAD' as CADProgram,
|
||||||
defaultDirectory: '',
|
defaultDirectory: '',
|
||||||
showDebugPanel: false,
|
defaultProjectName: DEFAULT_PROJECT_NAME,
|
||||||
onboardingStatus: '',
|
onboardingStatus: '',
|
||||||
|
showDebugPanel: false,
|
||||||
|
textWrapping: 'On' as Toggle,
|
||||||
|
theme: Themes.System,
|
||||||
|
unitSystem: UnitSystem.Imperial,
|
||||||
},
|
},
|
||||||
initial: 'idle',
|
initial: 'idle',
|
||||||
states: {
|
states: {
|
||||||
idle: {
|
idle: {
|
||||||
entry: ['setThemeClass'],
|
entry: ['setThemeClass'],
|
||||||
on: {
|
on: {
|
||||||
'Set Theme': {
|
'Set Base Unit': {
|
||||||
actions: [
|
actions: [
|
||||||
assign({
|
assign({ baseUnit: (_, event) => event.data.baseUnit }),
|
||||||
theme: (_, event) => event.data.theme,
|
|
||||||
}),
|
|
||||||
'persistSettings',
|
'persistSettings',
|
||||||
'toastSuccess',
|
'toastSuccess',
|
||||||
'setThemeClass',
|
|
||||||
],
|
],
|
||||||
target: 'idle',
|
target: 'idle',
|
||||||
internal: true,
|
internal: true,
|
||||||
},
|
},
|
||||||
'Set Default Project Name': {
|
'Set Camera Controls': {
|
||||||
actions: [
|
actions: [
|
||||||
assign({
|
assign({
|
||||||
defaultProjectName: (_, event) => event.data.defaultProjectName,
|
cameraControls: (_, event) => event.data.cameraControls,
|
||||||
}),
|
}),
|
||||||
'persistSettings',
|
'persistSettings',
|
||||||
'toastSuccess',
|
'toastSuccess',
|
||||||
@ -120,12 +154,11 @@ export const settingsMachine = createMachine(
|
|||||||
target: 'idle',
|
target: 'idle',
|
||||||
internal: true,
|
internal: true,
|
||||||
},
|
},
|
||||||
'Set Unit System': {
|
'Set Default Project Name': {
|
||||||
actions: [
|
actions: [
|
||||||
assign({
|
assign({
|
||||||
unitSystem: (_, event) => event.data.unitSystem,
|
defaultProjectName: (_, event) =>
|
||||||
baseUnit: (_, event) =>
|
event.data.defaultProjectName.trim() || DEFAULT_PROJECT_NAME,
|
||||||
event.data.unitSystem === 'imperial' ? 'in' : 'mm',
|
|
||||||
}),
|
}),
|
||||||
'persistSettings',
|
'persistSettings',
|
||||||
'toastSuccess',
|
'toastSuccess',
|
||||||
@ -133,9 +166,46 @@ export const settingsMachine = createMachine(
|
|||||||
target: 'idle',
|
target: 'idle',
|
||||||
internal: true,
|
internal: true,
|
||||||
},
|
},
|
||||||
'Set Base Unit': {
|
'Set Onboarding Status': {
|
||||||
actions: [
|
actions: [
|
||||||
assign({ baseUnit: (_, event) => event.data.baseUnit }),
|
assign({
|
||||||
|
onboardingStatus: (_, event) => event.data.onboardingStatus,
|
||||||
|
}),
|
||||||
|
'persistSettings',
|
||||||
|
],
|
||||||
|
target: 'idle',
|
||||||
|
internal: true,
|
||||||
|
},
|
||||||
|
'Set Text Wrapping': {
|
||||||
|
actions: [
|
||||||
|
assign({
|
||||||
|
textWrapping: (_, event) => event.data.textWrapping,
|
||||||
|
}),
|
||||||
|
'persistSettings',
|
||||||
|
'toastSuccess',
|
||||||
|
],
|
||||||
|
target: 'idle',
|
||||||
|
internal: true,
|
||||||
|
},
|
||||||
|
'Set Theme': {
|
||||||
|
actions: [
|
||||||
|
assign({
|
||||||
|
theme: (_, event) => event.data.theme,
|
||||||
|
}),
|
||||||
|
'persistSettings',
|
||||||
|
'toastSuccess',
|
||||||
|
'setThemeClass',
|
||||||
|
],
|
||||||
|
target: 'idle',
|
||||||
|
internal: true,
|
||||||
|
},
|
||||||
|
'Set Unit System': {
|
||||||
|
actions: [
|
||||||
|
assign({
|
||||||
|
unitSystem: (_, event) => event.data.unitSystem,
|
||||||
|
baseUnit: (_, event) =>
|
||||||
|
event.data.unitSystem === 'imperial' ? 'in' : 'mm',
|
||||||
|
}),
|
||||||
'persistSettings',
|
'persistSettings',
|
||||||
'toastSuccess',
|
'toastSuccess',
|
||||||
],
|
],
|
||||||
@ -155,34 +225,26 @@ export const settingsMachine = createMachine(
|
|||||||
target: 'idle',
|
target: 'idle',
|
||||||
internal: true,
|
internal: true,
|
||||||
},
|
},
|
||||||
'Set Onboarding Status': {
|
|
||||||
actions: [
|
|
||||||
assign({
|
|
||||||
onboardingStatus: (_, event) => event.data.onboardingStatus,
|
|
||||||
}),
|
|
||||||
'persistSettings',
|
|
||||||
],
|
|
||||||
target: 'idle',
|
|
||||||
internal: true,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
tsTypes: {} as import('./settingsMachine.typegen').Typegen0,
|
tsTypes: {} as import('./settingsMachine.typegen').Typegen0,
|
||||||
schema: {
|
schema: {
|
||||||
events: {} as
|
events: {} as
|
||||||
| { type: 'Set Theme'; data: { theme: Themes } }
|
| { type: 'Set Base Unit'; data: { baseUnit: BaseUnit } }
|
||||||
|
| { type: 'Set Camera Controls'; data: { cameraControls: CADProgram } }
|
||||||
|
| { type: 'Set Default Directory'; data: { defaultDirectory: string } }
|
||||||
| {
|
| {
|
||||||
type: 'Set Default Project Name'
|
type: 'Set Default Project Name'
|
||||||
data: { defaultProjectName: string }
|
data: { defaultProjectName: string }
|
||||||
}
|
}
|
||||||
| { type: 'Set Default Directory'; data: { defaultDirectory: string } }
|
| { type: 'Set Onboarding Status'; data: { onboardingStatus: string } }
|
||||||
|
| { type: 'Set Text Wrapping'; data: { textWrapping: Toggle } }
|
||||||
|
| { type: 'Set Theme'; data: { theme: Themes } }
|
||||||
| {
|
| {
|
||||||
type: 'Set Unit System'
|
type: 'Set Unit System'
|
||||||
data: { unitSystem: UnitSystem }
|
data: { unitSystem: UnitSystem }
|
||||||
}
|
}
|
||||||
| { type: 'Set Base Unit'; data: { baseUnit: BaseUnit } }
|
|
||||||
| { type: 'Set Onboarding Status'; data: { onboardingStatus: string } }
|
|
||||||
| { type: 'Toggle Debug Panel' },
|
| { type: 'Toggle Debug Panel' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
@ -15,25 +15,31 @@ export interface Typegen0 {
|
|||||||
eventsCausingActions: {
|
eventsCausingActions: {
|
||||||
persistSettings:
|
persistSettings:
|
||||||
| 'Set Base Unit'
|
| 'Set Base Unit'
|
||||||
|
| 'Set Camera Controls'
|
||||||
| 'Set Default Directory'
|
| 'Set Default Directory'
|
||||||
| 'Set Default Project Name'
|
| 'Set Default Project Name'
|
||||||
| 'Set Onboarding Status'
|
| 'Set Onboarding Status'
|
||||||
|
| 'Set Text Wrapping'
|
||||||
| 'Set Theme'
|
| 'Set Theme'
|
||||||
| 'Set Unit System'
|
| 'Set Unit System'
|
||||||
| 'Toggle Debug Panel'
|
| 'Toggle Debug Panel'
|
||||||
setThemeClass:
|
setThemeClass:
|
||||||
| 'Set Base Unit'
|
| 'Set Base Unit'
|
||||||
|
| 'Set Camera Controls'
|
||||||
| 'Set Default Directory'
|
| 'Set Default Directory'
|
||||||
| 'Set Default Project Name'
|
| 'Set Default Project Name'
|
||||||
| 'Set Onboarding Status'
|
| 'Set Onboarding Status'
|
||||||
|
| 'Set Text Wrapping'
|
||||||
| 'Set Theme'
|
| 'Set Theme'
|
||||||
| 'Set Unit System'
|
| 'Set Unit System'
|
||||||
| 'Toggle Debug Panel'
|
| 'Toggle Debug Panel'
|
||||||
| 'xstate.init'
|
| 'xstate.init'
|
||||||
toastSuccess:
|
toastSuccess:
|
||||||
| 'Set Base Unit'
|
| 'Set Base Unit'
|
||||||
|
| 'Set Camera Controls'
|
||||||
| 'Set Default Directory'
|
| 'Set Default Directory'
|
||||||
| 'Set Default Project Name'
|
| 'Set Default Project Name'
|
||||||
|
| 'Set Text Wrapping'
|
||||||
| 'Set Theme'
|
| 'Set Theme'
|
||||||
| 'Set Unit System'
|
| 'Set Unit System'
|
||||||
| 'Toggle Debug Panel'
|
| 'Toggle Debug Panel'
|
||||||
|
@ -28,6 +28,7 @@ import {
|
|||||||
import useStateMachineCommands from '../hooks/useStateMachineCommands'
|
import useStateMachineCommands from '../hooks/useStateMachineCommands'
|
||||||
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
|
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
|
||||||
import { useCommandsContext } from 'hooks/useCommandsContext'
|
import { useCommandsContext } from 'hooks/useCommandsContext'
|
||||||
|
import { DEFAULT_PROJECT_NAME } from 'machines/settingsMachine'
|
||||||
|
|
||||||
// This route only opens in the Tauri desktop context for now,
|
// This route only opens in the Tauri desktop context for now,
|
||||||
// as defined in Router.tsx, so we can use the Tauri APIs and types.
|
// as defined in Router.tsx, so we can use the Tauri APIs and types.
|
||||||
@ -38,6 +39,7 @@ const Home = () => {
|
|||||||
const {
|
const {
|
||||||
settings: {
|
settings: {
|
||||||
context: { defaultDirectory, defaultProjectName },
|
context: { defaultDirectory, defaultProjectName },
|
||||||
|
send: sendToSettings,
|
||||||
},
|
},
|
||||||
} = useGlobalStateContext()
|
} = useGlobalStateContext()
|
||||||
|
|
||||||
@ -71,16 +73,33 @@ const Home = () => {
|
|||||||
context: ContextFrom<typeof homeMachine>,
|
context: ContextFrom<typeof homeMachine>,
|
||||||
event: EventFrom<typeof homeMachine, 'Create project'>
|
event: EventFrom<typeof homeMachine, 'Create project'>
|
||||||
) => {
|
) => {
|
||||||
let name =
|
let name = (
|
||||||
event.data && 'name' in event.data
|
event.data && 'name' in event.data
|
||||||
? event.data.name
|
? event.data.name
|
||||||
: defaultProjectName
|
: defaultProjectName
|
||||||
|
).trim()
|
||||||
|
let shouldUpdateDefaultProjectName = false
|
||||||
|
|
||||||
|
// If there is no default project name, flag it to be set to the default
|
||||||
|
if (!name) {
|
||||||
|
name = DEFAULT_PROJECT_NAME
|
||||||
|
shouldUpdateDefaultProjectName = true
|
||||||
|
}
|
||||||
|
|
||||||
if (doesProjectNameNeedInterpolated(name)) {
|
if (doesProjectNameNeedInterpolated(name)) {
|
||||||
const nextIndex = await getNextProjectIndex(name, projects)
|
const nextIndex = await getNextProjectIndex(name, projects)
|
||||||
name = interpolateProjectNameWithIndex(name, nextIndex)
|
name = interpolateProjectNameWithIndex(name, nextIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
await createNewProject(context.defaultDirectory + '/' + name)
|
await createNewProject(context.defaultDirectory + '/' + name)
|
||||||
|
|
||||||
|
if (shouldUpdateDefaultProjectName) {
|
||||||
|
sendToSettings({
|
||||||
|
type: 'Set Default Project Name',
|
||||||
|
data: { defaultProjectName: DEFAULT_PROJECT_NAME },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return `Successfully created "${name}"`
|
return `Successfully created "${name}"`
|
||||||
},
|
},
|
||||||
renameProject: async (
|
renameProject: async (
|
||||||
|
@ -4,8 +4,8 @@ import { onboardingPaths, useDismiss, useNextClick } from '.'
|
|||||||
import { useStore } from '../../useStore'
|
import { useStore } from '../../useStore'
|
||||||
|
|
||||||
export default function Units() {
|
export default function Units() {
|
||||||
const { isMouseDownInStream } = useStore((s) => ({
|
const { buttonDownInStream } = useStore((s) => ({
|
||||||
isMouseDownInStream: s.isMouseDownInStream,
|
buttonDownInStream: s.buttonDownInStream,
|
||||||
}))
|
}))
|
||||||
const dismiss = useDismiss()
|
const dismiss = useDismiss()
|
||||||
const next = useNextClick(onboardingPaths.SKETCHING)
|
const next = useNextClick(onboardingPaths.SKETCHING)
|
||||||
@ -15,7 +15,7 @@ export default function Units() {
|
|||||||
<div
|
<div
|
||||||
className={
|
className={
|
||||||
'max-w-2xl flex flex-col justify-center bg-chalkboard-10 dark:bg-chalkboard-90 p-8 rounded' +
|
'max-w-2xl flex flex-col justify-center bg-chalkboard-10 dark:bg-chalkboard-90 p-8 rounded' +
|
||||||
(isMouseDownInStream ? '' : ' pointer-events-auto')
|
(buttonDownInStream ? '' : ' pointer-events-auto')
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<h1 className="text-2xl font-bold">Camera</h1>
|
<h1 className="text-2xl font-bold">Camera</h1>
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { faArrowRight, faXmark } from '@fortawesome/free-solid-svg-icons'
|
import { faArrowRight, faXmark } from '@fortawesome/free-solid-svg-icons'
|
||||||
import { BaseUnit, baseUnits } from '../../useStore'
|
import { BaseUnit, baseUnits } from '../../machines/settingsMachine'
|
||||||
import { ActionButton } from '../../components/ActionButton'
|
import { ActionButton } from '../../components/ActionButton'
|
||||||
import { SettingsSection } from '../Settings'
|
import { SettingsSection } from '../Settings'
|
||||||
import { Toggle } from '../../components/Toggle/Toggle'
|
import { Toggle } from '../../components/Toggle/Toggle'
|
||||||
|
@ -6,13 +6,22 @@ import {
|
|||||||
import { ActionButton } from '../components/ActionButton'
|
import { ActionButton } from '../components/ActionButton'
|
||||||
import { AppHeader } from '../components/AppHeader'
|
import { AppHeader } from '../components/AppHeader'
|
||||||
import { open } from '@tauri-apps/api/dialog'
|
import { open } from '@tauri-apps/api/dialog'
|
||||||
import { BaseUnit, baseUnits } from '../useStore'
|
import {
|
||||||
|
BaseUnit,
|
||||||
|
DEFAULT_PROJECT_NAME,
|
||||||
|
baseUnits,
|
||||||
|
} from '../machines/settingsMachine'
|
||||||
import { Toggle } from '../components/Toggle/Toggle'
|
import { Toggle } from '../components/Toggle/Toggle'
|
||||||
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
|
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
|
||||||
import { useHotkeys } from 'react-hotkeys-hook'
|
import { useHotkeys } from 'react-hotkeys-hook'
|
||||||
import { IndexLoaderData, paths } from '../Router'
|
import { IndexLoaderData, paths } from '../Router'
|
||||||
import { Themes } from '../lib/theme'
|
import { Themes } from '../lib/theme'
|
||||||
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
|
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
|
||||||
|
import {
|
||||||
|
CADProgram,
|
||||||
|
cadPrograms,
|
||||||
|
cameraMouseDragGuards,
|
||||||
|
} from 'lib/cameraControls'
|
||||||
import { UnitSystem } from 'machines/settingsMachine'
|
import { UnitSystem } from 'machines/settingsMachine'
|
||||||
|
|
||||||
export const Settings = () => {
|
export const Settings = () => {
|
||||||
@ -25,12 +34,13 @@ export const Settings = () => {
|
|||||||
send,
|
send,
|
||||||
state: {
|
state: {
|
||||||
context: {
|
context: {
|
||||||
|
baseUnit,
|
||||||
|
cameraControls,
|
||||||
|
defaultDirectory,
|
||||||
defaultProjectName,
|
defaultProjectName,
|
||||||
showDebugPanel,
|
showDebugPanel,
|
||||||
defaultDirectory,
|
|
||||||
unitSystem,
|
|
||||||
baseUnit,
|
|
||||||
theme,
|
theme,
|
||||||
|
unitSystem,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@ -82,6 +92,42 @@ export const Settings = () => {
|
|||||||
, and start a discussion if you don't see it! Your feedback will help
|
, and start a discussion if you don't see it! Your feedback will help
|
||||||
us prioritize what to build next.
|
us prioritize what to build next.
|
||||||
</p>
|
</p>
|
||||||
|
<SettingsSection
|
||||||
|
title="Camera Controls"
|
||||||
|
description="How you want to control the camera in the 3D view"
|
||||||
|
>
|
||||||
|
<select
|
||||||
|
id="camera-controls"
|
||||||
|
className="block w-full px-3 py-1 border border-chalkboard-30 bg-transparent"
|
||||||
|
value={cameraControls}
|
||||||
|
onChange={(e) => {
|
||||||
|
send({
|
||||||
|
type: 'Set Camera Controls',
|
||||||
|
data: { cameraControls: e.target.value as CADProgram },
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{cadPrograms.map((program) => (
|
||||||
|
<option key={program} value={program}>
|
||||||
|
{program}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<ul className="text-sm my-2 mx-4 leading-relaxed">
|
||||||
|
<li>
|
||||||
|
<strong>Pan:</strong>{' '}
|
||||||
|
{cameraMouseDragGuards[cameraControls].pan.description}
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>Zoom:</strong>{' '}
|
||||||
|
{cameraMouseDragGuards[cameraControls].zoom.description}
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong>Rotate:</strong>{' '}
|
||||||
|
{cameraMouseDragGuards[cameraControls].rotate.description}
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</SettingsSection>
|
||||||
{(window as any).__TAURI__ && (
|
{(window as any).__TAURI__ && (
|
||||||
<>
|
<>
|
||||||
<SettingsSection
|
<SettingsSection
|
||||||
@ -118,10 +164,14 @@ export const Settings = () => {
|
|||||||
className="block w-full px-3 py-1 border border-chalkboard-30 bg-transparent"
|
className="block w-full px-3 py-1 border border-chalkboard-30 bg-transparent"
|
||||||
defaultValue={defaultProjectName}
|
defaultValue={defaultProjectName}
|
||||||
onBlur={(e) => {
|
onBlur={(e) => {
|
||||||
|
const newValue = e.target.value.trim() || DEFAULT_PROJECT_NAME
|
||||||
send({
|
send({
|
||||||
type: 'Set Default Project Name',
|
type: 'Set Default Project Name',
|
||||||
data: { defaultProjectName: e.target.value },
|
data: {
|
||||||
|
defaultProjectName: newValue,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
e.target.value = newValue
|
||||||
}}
|
}}
|
||||||
autoCapitalize="off"
|
autoCapitalize="off"
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
|
384
src/useStore.ts
384
src/useStore.ts
@ -19,6 +19,7 @@ import {
|
|||||||
EngineCommandManager,
|
EngineCommandManager,
|
||||||
} from './lang/std/engineConnection'
|
} from './lang/std/engineConnection'
|
||||||
import { KCLError } from './lang/errors'
|
import { KCLError } from './lang/errors'
|
||||||
|
import { defferExecution } from 'lib/utils'
|
||||||
|
|
||||||
export type Selection = {
|
export type Selection = {
|
||||||
type: 'default' | 'line-end' | 'line-mid'
|
type: 'default' | 'line-end' | 'line-mid'
|
||||||
@ -94,15 +95,6 @@ export type GuiModes =
|
|||||||
position: Position
|
position: Position
|
||||||
}
|
}
|
||||||
|
|
||||||
export const baseUnits = {
|
|
||||||
imperial: ['in', 'ft'],
|
|
||||||
metric: ['mm', 'cm', 'm'],
|
|
||||||
} as const
|
|
||||||
|
|
||||||
export type BaseUnit = 'in' | 'ft' | 'mm' | 'cm' | 'm'
|
|
||||||
|
|
||||||
export const baseUnitsUnion = Object.values(baseUnits).flatMap((v) => v)
|
|
||||||
|
|
||||||
export type PaneType =
|
export type PaneType =
|
||||||
| 'code'
|
| 'code'
|
||||||
| 'variables'
|
| 'variables'
|
||||||
@ -141,7 +133,9 @@ export interface StoreState {
|
|||||||
) => void
|
) => void
|
||||||
updateAstAsync: (ast: Program, focusPath?: PathToNode) => void
|
updateAstAsync: (ast: Program, focusPath?: PathToNode) => void
|
||||||
code: string
|
code: string
|
||||||
|
defferedCode: string
|
||||||
setCode: (code: string) => void
|
setCode: (code: string) => void
|
||||||
|
defferedSetCode: (code: string) => void
|
||||||
formatCode: () => void
|
formatCode: () => void
|
||||||
errorState: {
|
errorState: {
|
||||||
isError: boolean
|
isError: boolean
|
||||||
@ -166,8 +160,8 @@ export interface StoreState {
|
|||||||
setIsStreamReady: (isStreamReady: boolean) => void
|
setIsStreamReady: (isStreamReady: boolean) => void
|
||||||
isLSPServerReady: boolean
|
isLSPServerReady: boolean
|
||||||
setIsLSPServerReady: (isLSPServerReady: boolean) => void
|
setIsLSPServerReady: (isLSPServerReady: boolean) => void
|
||||||
isMouseDownInStream: boolean
|
buttonDownInStream: number
|
||||||
setIsMouseDownInStream: (isMouseDownInStream: boolean) => void
|
setButtonDownInStream: (buttonDownInStream: number) => void
|
||||||
didDragInStream: boolean
|
didDragInStream: boolean
|
||||||
setDidDragInStream: (didDragInStream: boolean) => void
|
setDidDragInStream: (didDragInStream: boolean) => void
|
||||||
fileId: string
|
fileId: string
|
||||||
@ -177,6 +171,8 @@ export interface StoreState {
|
|||||||
streamWidth: number
|
streamWidth: number
|
||||||
streamHeight: number
|
streamHeight: number
|
||||||
}) => void
|
}) => void
|
||||||
|
isExecuting: boolean
|
||||||
|
setIsExecuting: (isExecuting: boolean) => void
|
||||||
|
|
||||||
showHomeMenu: boolean
|
showHomeMenu: boolean
|
||||||
setHomeShowMenu: (showMenu: boolean) => void
|
setHomeShowMenu: (showMenu: boolean) => void
|
||||||
@ -195,193 +191,207 @@ let pendingAstUpdates: number[] = []
|
|||||||
|
|
||||||
export const useStore = create<StoreState>()(
|
export const useStore = create<StoreState>()(
|
||||||
persist(
|
persist(
|
||||||
(set, get) => ({
|
(set, get) => {
|
||||||
editorView: null,
|
const setDefferedCode = defferExecution(
|
||||||
setEditorView: (editorView) => {
|
(code: string) => set({ defferedCode: code }),
|
||||||
set({ editorView })
|
600
|
||||||
},
|
)
|
||||||
highlightRange: [0, 0],
|
return {
|
||||||
setHighlightRange: (selection) => {
|
editorView: null,
|
||||||
set({ highlightRange: selection })
|
setEditorView: (editorView) => {
|
||||||
const editorView = get().editorView
|
set({ editorView })
|
||||||
if (editorView) {
|
},
|
||||||
editorView.dispatch({ effects: addLineHighlight.of(selection) })
|
highlightRange: [0, 0],
|
||||||
}
|
setHighlightRange: (selection) => {
|
||||||
},
|
set({ highlightRange: selection })
|
||||||
setCursor: (selections) => {
|
const editorView = get().editorView
|
||||||
const { editorView } = get()
|
if (editorView) {
|
||||||
if (!editorView) return
|
editorView.dispatch({ effects: addLineHighlight.of(selection) })
|
||||||
const ranges: ReturnType<typeof EditorSelection.cursor>[] = []
|
|
||||||
const selectionRangeTypeMap: { [key: number]: Selection['type'] } = {}
|
|
||||||
set({ selectionRangeTypeMap })
|
|
||||||
selections.codeBasedSelections.forEach(({ range, type }) => {
|
|
||||||
if (range?.[1]) {
|
|
||||||
ranges.push(EditorSelection.cursor(range[1]))
|
|
||||||
selectionRangeTypeMap[range[1]] = type
|
|
||||||
}
|
}
|
||||||
})
|
},
|
||||||
setTimeout(() => {
|
setCursor: (selections) => {
|
||||||
editorView.dispatch({
|
const { editorView } = get()
|
||||||
selection: EditorSelection.create(
|
if (!editorView) return
|
||||||
ranges,
|
const ranges: ReturnType<typeof EditorSelection.cursor>[] = []
|
||||||
selections.codeBasedSelections.length - 1
|
const selectionRangeTypeMap: { [key: number]: Selection['type'] } = {}
|
||||||
),
|
set({ selectionRangeTypeMap })
|
||||||
|
selections.codeBasedSelections.forEach(({ range, type }) => {
|
||||||
|
if (range?.[1]) {
|
||||||
|
ranges.push(EditorSelection.cursor(range[1]))
|
||||||
|
selectionRangeTypeMap[range[1]] = type
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
|
||||||
},
|
|
||||||
setCursor2: (codeSelections) => {
|
|
||||||
const currestSelections = get().selectionRanges
|
|
||||||
const code = get().code
|
|
||||||
if (!codeSelections) {
|
|
||||||
get().setCursor({
|
|
||||||
otherSelections: currestSelections.otherSelections,
|
|
||||||
codeBasedSelections: [
|
|
||||||
{ range: [0, code.length - 1], type: 'default' },
|
|
||||||
],
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const selections: Selections = {
|
|
||||||
...currestSelections,
|
|
||||||
codeBasedSelections: get().isShiftDown
|
|
||||||
? [...currestSelections.codeBasedSelections, codeSelections]
|
|
||||||
: [codeSelections],
|
|
||||||
}
|
|
||||||
get().setCursor(selections)
|
|
||||||
},
|
|
||||||
selectionRangeTypeMap: {},
|
|
||||||
selectionRanges: {
|
|
||||||
otherSelections: [],
|
|
||||||
codeBasedSelections: [],
|
|
||||||
},
|
|
||||||
setSelectionRanges: (selectionRanges) =>
|
|
||||||
set({ selectionRanges, selectionRangeTypeMap: {} }),
|
|
||||||
guiMode: { mode: 'default' },
|
|
||||||
lastGuiMode: { mode: 'default' },
|
|
||||||
setGuiMode: (guiMode) => {
|
|
||||||
set({ guiMode })
|
|
||||||
},
|
|
||||||
logs: [],
|
|
||||||
addLog: (log) => {
|
|
||||||
if (Array.isArray(log)) {
|
|
||||||
const cleanLog: any = log.map(({ __geoMeta, ...rest }) => rest)
|
|
||||||
set((state) => ({ logs: [...state.logs, cleanLog] }))
|
|
||||||
} else {
|
|
||||||
set((state) => ({ logs: [...state.logs, log] }))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
resetLogs: () => {
|
|
||||||
set({ logs: [] })
|
|
||||||
},
|
|
||||||
kclErrors: [],
|
|
||||||
addKCLError: (e) => {
|
|
||||||
set((state) => ({ kclErrors: [...state.kclErrors, e] }))
|
|
||||||
},
|
|
||||||
resetKCLErrors: () => {
|
|
||||||
set({ kclErrors: [] })
|
|
||||||
},
|
|
||||||
ast: null,
|
|
||||||
setAst: (ast) => {
|
|
||||||
set({ ast })
|
|
||||||
},
|
|
||||||
updateAst: async (ast, { focusPath, callBack = () => {} } = {}) => {
|
|
||||||
const newCode = recast(ast)
|
|
||||||
const astWithUpdatedSource = parser_wasm(newCode)
|
|
||||||
callBack(astWithUpdatedSource)
|
|
||||||
|
|
||||||
set({ ast: astWithUpdatedSource, code: newCode })
|
|
||||||
if (focusPath) {
|
|
||||||
const { node } = getNodeFromPath<any>(astWithUpdatedSource, focusPath)
|
|
||||||
const { start, end } = node
|
|
||||||
if (!start || !end) return
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
get().setCursor({
|
editorView.dispatch({
|
||||||
codeBasedSelections: [
|
selection: EditorSelection.create(
|
||||||
{
|
ranges,
|
||||||
type: 'default',
|
selections.codeBasedSelections.length - 1
|
||||||
range: [start, end],
|
),
|
||||||
},
|
|
||||||
],
|
|
||||||
otherSelections: [],
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
},
|
||||||
},
|
setCursor2: (codeSelections) => {
|
||||||
updateAstAsync: async (ast, focusPath) => {
|
const currestSelections = get().selectionRanges
|
||||||
// clear any pending updates
|
const code = get().code
|
||||||
pendingAstUpdates.forEach((id) => clearTimeout(id))
|
if (!codeSelections) {
|
||||||
pendingAstUpdates = []
|
get().setCursor({
|
||||||
// setup a new update
|
otherSelections: currestSelections.otherSelections,
|
||||||
pendingAstUpdates.push(
|
codeBasedSelections: [
|
||||||
setTimeout(() => {
|
{ range: [0, code.length - 1], type: 'default' },
|
||||||
get().updateAst(ast, { focusPath })
|
],
|
||||||
}, 100) as unknown as number
|
})
|
||||||
)
|
return
|
||||||
},
|
}
|
||||||
code: '',
|
const selections: Selections = {
|
||||||
setCode: (code) => {
|
...currestSelections,
|
||||||
set({ code })
|
codeBasedSelections: get().isShiftDown
|
||||||
},
|
? [...currestSelections.codeBasedSelections, codeSelections]
|
||||||
formatCode: async () => {
|
: [codeSelections],
|
||||||
const code = get().code
|
}
|
||||||
const ast = parser_wasm(code)
|
get().setCursor(selections)
|
||||||
const newCode = recast(ast)
|
},
|
||||||
set({ code: newCode, ast })
|
selectionRangeTypeMap: {},
|
||||||
},
|
selectionRanges: {
|
||||||
errorState: {
|
otherSelections: [],
|
||||||
isError: false,
|
codeBasedSelections: [],
|
||||||
error: '',
|
},
|
||||||
},
|
setSelectionRanges: (selectionRanges) =>
|
||||||
setError: (error = '') => {
|
set({ selectionRanges, selectionRangeTypeMap: {} }),
|
||||||
set({ errorState: { isError: !!error, error } })
|
guiMode: { mode: 'default' },
|
||||||
},
|
lastGuiMode: { mode: 'default' },
|
||||||
programMemory: { root: {}, pendingMemory: {} },
|
setGuiMode: (guiMode) => {
|
||||||
setProgramMemory: (programMemory) => set({ programMemory }),
|
set({ guiMode })
|
||||||
isShiftDown: false,
|
},
|
||||||
setIsShiftDown: (isShiftDown) => set({ isShiftDown }),
|
logs: [],
|
||||||
artifactMap: {},
|
addLog: (log) => {
|
||||||
sourceRangeMap: {},
|
if (Array.isArray(log)) {
|
||||||
setArtifactNSourceRangeMaps: (maps) => set({ ...maps }),
|
const cleanLog: any = log.map(({ __geoMeta, ...rest }) => rest)
|
||||||
setEngineCommandManager: (engineCommandManager) =>
|
set((state) => ({ logs: [...state.logs, cleanLog] }))
|
||||||
set({ engineCommandManager }),
|
} else {
|
||||||
setMediaStream: (mediaStream) => set({ mediaStream }),
|
set((state) => ({ logs: [...state.logs, log] }))
|
||||||
isStreamReady: false,
|
}
|
||||||
setIsStreamReady: (isStreamReady) => set({ isStreamReady }),
|
},
|
||||||
isLSPServerReady: false,
|
resetLogs: () => {
|
||||||
setIsLSPServerReady: (isLSPServerReady) => set({ isLSPServerReady }),
|
set({ logs: [] })
|
||||||
isMouseDownInStream: false,
|
},
|
||||||
setIsMouseDownInStream: (isMouseDownInStream) => {
|
kclErrors: [],
|
||||||
set({ isMouseDownInStream })
|
addKCLError: (e) => {
|
||||||
},
|
set((state) => ({ kclErrors: [...state.kclErrors, e] }))
|
||||||
didDragInStream: false,
|
},
|
||||||
setDidDragInStream: (didDragInStream) => {
|
resetKCLErrors: () => {
|
||||||
set({ didDragInStream })
|
set({ kclErrors: [] })
|
||||||
},
|
},
|
||||||
// For stream event handling
|
ast: null,
|
||||||
fileId: '',
|
setAst: (ast) => {
|
||||||
setFileId: (fileId) => set({ fileId }),
|
set({ ast })
|
||||||
streamDimensions: { streamWidth: 1280, streamHeight: 720 },
|
},
|
||||||
setStreamDimensions: (streamDimensions) => set({ streamDimensions }),
|
updateAst: async (ast, { focusPath, callBack = () => {} } = {}) => {
|
||||||
|
const newCode = recast(ast)
|
||||||
|
const astWithUpdatedSource = parser_wasm(newCode)
|
||||||
|
callBack(astWithUpdatedSource)
|
||||||
|
|
||||||
// tauri specific app settings
|
set({ ast: astWithUpdatedSource, code: newCode })
|
||||||
defaultDir: {
|
if (focusPath) {
|
||||||
dir: '',
|
const { node } = getNodeFromPath<any>(
|
||||||
},
|
astWithUpdatedSource,
|
||||||
isBannerDismissed: false,
|
focusPath
|
||||||
setBannerDismissed: (isBannerDismissed) => set({ isBannerDismissed }),
|
)
|
||||||
openPanes: ['code'],
|
const { start, end } = node
|
||||||
setOpenPanes: (openPanes) => set({ openPanes }),
|
if (!start || !end) return
|
||||||
showHomeMenu: true,
|
setTimeout(() => {
|
||||||
setHomeShowMenu: (showHomeMenu) => set({ showHomeMenu }),
|
get().setCursor({
|
||||||
homeMenuItems: [],
|
codeBasedSelections: [
|
||||||
setHomeMenuItems: (homeMenuItems) => set({ homeMenuItems }),
|
{
|
||||||
}),
|
type: 'default',
|
||||||
|
range: [start, end],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
otherSelections: [],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
updateAstAsync: async (ast, focusPath) => {
|
||||||
|
// clear any pending updates
|
||||||
|
pendingAstUpdates.forEach((id) => clearTimeout(id))
|
||||||
|
pendingAstUpdates = []
|
||||||
|
// setup a new update
|
||||||
|
pendingAstUpdates.push(
|
||||||
|
setTimeout(() => {
|
||||||
|
get().updateAst(ast, { focusPath })
|
||||||
|
}, 100) as unknown as number
|
||||||
|
)
|
||||||
|
},
|
||||||
|
code: '',
|
||||||
|
defferedCode: '',
|
||||||
|
setCode: (code) => set({ code, defferedCode: code }),
|
||||||
|
defferedSetCode: (code) => {
|
||||||
|
set({ code })
|
||||||
|
setDefferedCode(code)
|
||||||
|
},
|
||||||
|
formatCode: async () => {
|
||||||
|
const code = get().code
|
||||||
|
const ast = parser_wasm(code)
|
||||||
|
const newCode = recast(ast)
|
||||||
|
set({ code: newCode, ast })
|
||||||
|
},
|
||||||
|
errorState: {
|
||||||
|
isError: false,
|
||||||
|
error: '',
|
||||||
|
},
|
||||||
|
setError: (error = '') => {
|
||||||
|
set({ errorState: { isError: !!error, error } })
|
||||||
|
},
|
||||||
|
programMemory: { root: {}, pendingMemory: {} },
|
||||||
|
setProgramMemory: (programMemory) => set({ programMemory }),
|
||||||
|
isShiftDown: false,
|
||||||
|
setIsShiftDown: (isShiftDown) => set({ isShiftDown }),
|
||||||
|
artifactMap: {},
|
||||||
|
sourceRangeMap: {},
|
||||||
|
setArtifactNSourceRangeMaps: (maps) => set({ ...maps }),
|
||||||
|
setEngineCommandManager: (engineCommandManager) =>
|
||||||
|
set({ engineCommandManager }),
|
||||||
|
setMediaStream: (mediaStream) => set({ mediaStream }),
|
||||||
|
isStreamReady: false,
|
||||||
|
setIsStreamReady: (isStreamReady) => set({ isStreamReady }),
|
||||||
|
isLSPServerReady: false,
|
||||||
|
setIsLSPServerReady: (isLSPServerReady) => set({ isLSPServerReady }),
|
||||||
|
buttonDownInStream: 0,
|
||||||
|
setButtonDownInStream: (buttonDownInStream) => {
|
||||||
|
set({ buttonDownInStream })
|
||||||
|
},
|
||||||
|
didDragInStream: false,
|
||||||
|
setDidDragInStream: (didDragInStream) => {
|
||||||
|
set({ didDragInStream })
|
||||||
|
},
|
||||||
|
// For stream event handling
|
||||||
|
fileId: '',
|
||||||
|
setFileId: (fileId) => set({ fileId }),
|
||||||
|
streamDimensions: { streamWidth: 1280, streamHeight: 720 },
|
||||||
|
setStreamDimensions: (streamDimensions) => set({ streamDimensions }),
|
||||||
|
isExecuting: false,
|
||||||
|
setIsExecuting: (isExecuting) => set({ isExecuting }),
|
||||||
|
|
||||||
|
// tauri specific app settings
|
||||||
|
defaultDir: {
|
||||||
|
dir: '',
|
||||||
|
},
|
||||||
|
isBannerDismissed: false,
|
||||||
|
setBannerDismissed: (isBannerDismissed) => set({ isBannerDismissed }),
|
||||||
|
openPanes: ['code'],
|
||||||
|
setOpenPanes: (openPanes) => set({ openPanes }),
|
||||||
|
showHomeMenu: true,
|
||||||
|
setHomeShowMenu: (showHomeMenu) => set({ showHomeMenu }),
|
||||||
|
homeMenuItems: [],
|
||||||
|
setHomeMenuItems: (homeMenuItems) => set({ homeMenuItems }),
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'store',
|
name: 'store',
|
||||||
partialize: (state) =>
|
partialize: (state) =>
|
||||||
Object.fromEntries(
|
Object.fromEntries(
|
||||||
Object.entries(state).filter(([key]) =>
|
Object.entries(state).filter(([key]) =>
|
||||||
['code', 'openPanes'].includes(key)
|
['code', 'defferedCode', 'openPanes'].includes(key)
|
||||||
)
|
)
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
6
src/wasm-lib/Cargo.lock
generated
6
src/wasm-lib/Cargo.lock
generated
@ -1094,7 +1094,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "kcl-lib"
|
name = "kcl-lib"
|
||||||
version = "0.1.20"
|
version = "0.1.26"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bson",
|
"bson",
|
||||||
@ -1126,9 +1126,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "kittycad"
|
name = "kittycad"
|
||||||
version = "0.2.23"
|
version = "0.2.25"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b8b33e5df8f82b97e5f5af94ff1400ae37449d0f5f1bb79acedf17cf2193680f"
|
checksum = "d9cf962b1e81a0b4eb923a727e761b40672cbacc7f5f0b75e13579d346352bc7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64 0.21.2",
|
"base64 0.21.2",
|
||||||
|
@ -11,7 +11,7 @@ crate-type = ["cdylib"]
|
|||||||
bson = { version = "2.7.0", features = ["uuid-1", "chrono"] }
|
bson = { version = "2.7.0", features = ["uuid-1", "chrono"] }
|
||||||
gloo-utils = "0.2.0"
|
gloo-utils = "0.2.0"
|
||||||
kcl-lib = { path = "kcl" }
|
kcl-lib = { path = "kcl" }
|
||||||
kittycad = { version = "0.2.23", default-features = false, features = ["js"] }
|
kittycad = { version = "0.2.25", default-features = false, features = ["js"] }
|
||||||
serde_json = "1.0.93"
|
serde_json = "1.0.93"
|
||||||
wasm-bindgen = "0.2.87"
|
wasm-bindgen = "0.2.87"
|
||||||
wasm-bindgen-futures = "0.4.37"
|
wasm-bindgen-futures = "0.4.37"
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "kcl-lib"
|
name = "kcl-lib"
|
||||||
description = "KittyCAD Language"
|
description = "KittyCAD Language"
|
||||||
version = "0.1.20"
|
version = "0.1.26"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
@ -11,9 +11,9 @@ license = "MIT"
|
|||||||
anyhow = { version = "1.0.75", features = ["backtrace"] }
|
anyhow = { version = "1.0.75", features = ["backtrace"] }
|
||||||
clap = { version = "4.4.2", features = ["cargo", "derive", "env", "unicode"] }
|
clap = { version = "4.4.2", features = ["cargo", "derive", "env", "unicode"] }
|
||||||
dashmap = "5.5.3"
|
dashmap = "5.5.3"
|
||||||
derive-docs = { version = "0.1.1" }
|
derive-docs = { version = "0.1.3" }
|
||||||
#derive-docs = { path = "../derive-docs" }
|
#derive-docs = { path = "../derive-docs" }
|
||||||
kittycad = { version = "0.2.23", default-features = false, features = ["js"] }
|
kittycad = { version = "0.2.25", default-features = false, features = ["js"] }
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
parse-display = "0.8.2"
|
parse-display = "0.8.2"
|
||||||
regex = "1.7.1"
|
regex = "1.7.1"
|
||||||
|
4
src/wasm-lib/kcl/fuzz/.gitignore
vendored
Normal file
4
src/wasm-lib/kcl/fuzz/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
target
|
||||||
|
corpus
|
||||||
|
artifacts
|
||||||
|
coverage
|
2218
src/wasm-lib/kcl/fuzz/Cargo.lock
generated
Normal file
2218
src/wasm-lib/kcl/fuzz/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
27
src/wasm-lib/kcl/fuzz/Cargo.toml
Normal file
27
src/wasm-lib/kcl/fuzz/Cargo.toml
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
[package]
|
||||||
|
name = "kcl-lib-fuzz"
|
||||||
|
version = "0.0.0"
|
||||||
|
publish = false
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[package.metadata]
|
||||||
|
cargo-fuzz = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
libfuzzer-sys = "0.4"
|
||||||
|
|
||||||
|
[dependencies.kcl-lib]
|
||||||
|
path = ".."
|
||||||
|
|
||||||
|
# Prevent this from interfering with workspaces
|
||||||
|
[workspace]
|
||||||
|
members = ["."]
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
debug = 1
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "parser"
|
||||||
|
path = "fuzz_targets/parser.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
14
src/wasm-lib/kcl/fuzz/fuzz_targets/parser.rs
Normal file
14
src/wasm-lib/kcl/fuzz/fuzz_targets/parser.rs
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
#![no_main]
|
||||||
|
#[macro_use]
|
||||||
|
extern crate libfuzzer_sys;
|
||||||
|
extern crate kcl_lib;
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
if let Ok(s) = std::str::from_utf8(data) {
|
||||||
|
let tokens = kcl_lib::tokeniser::lexer(s);
|
||||||
|
let parser = kcl_lib::parser::Parser::new(tokens);
|
||||||
|
if let Ok(_) = parser.ast() {
|
||||||
|
println!("OK");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
@ -27,12 +27,16 @@ pub struct Program {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Program {
|
impl Program {
|
||||||
pub fn recast(&self, indentation: &str, is_with_block: bool) -> String {
|
pub fn recast(&self, options: &FormatOptions, indentation_level: usize) -> String {
|
||||||
self.body
|
let indentation = options.get_indentation(indentation_level);
|
||||||
|
let result = self
|
||||||
|
.body
|
||||||
.iter()
|
.iter()
|
||||||
.map(|statement| match statement.clone() {
|
.map(|statement| match statement.clone() {
|
||||||
BodyItem::ExpressionStatement(expression_statement) => {
|
BodyItem::ExpressionStatement(expression_statement) => {
|
||||||
expression_statement.expression.recast(indentation, false)
|
expression_statement
|
||||||
|
.expression
|
||||||
|
.recast(options, indentation_level, false)
|
||||||
}
|
}
|
||||||
BodyItem::VariableDeclaration(variable_declaration) => variable_declaration
|
BodyItem::VariableDeclaration(variable_declaration) => variable_declaration
|
||||||
.declarations
|
.declarations
|
||||||
@ -43,56 +47,44 @@ impl Program {
|
|||||||
indentation,
|
indentation,
|
||||||
variable_declaration.kind,
|
variable_declaration.kind,
|
||||||
declaration.id.name,
|
declaration.id.name,
|
||||||
declaration.init.recast("", false)
|
declaration.init.recast(options, 0, false)
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.collect::<String>(),
|
.collect::<String>(),
|
||||||
BodyItem::ReturnStatement(return_statement) => {
|
BodyItem::ReturnStatement(return_statement) => {
|
||||||
format!("{}return {}", indentation, return_statement.argument.recast("", false))
|
format!(
|
||||||
|
"{}return {}",
|
||||||
|
indentation,
|
||||||
|
return_statement.argument.recast(options, 0, false)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(index, recast_str)| {
|
.map(|(index, recast_str)| {
|
||||||
let is_legit_custom_whitespace_or_comment = |s: String| s != " " && s != "\n" && s != " " && s != "\t";
|
let start_string = if index == 0 {
|
||||||
|
// We need to indent.
|
||||||
// determine the value of startString
|
|
||||||
let last_white_space_or_comment = if index > 0 {
|
|
||||||
let tmp = if let Some(non_code_node) = self.non_code_meta.none_code_nodes.get(&(index - 1)) {
|
|
||||||
non_code_node.format(indentation)
|
|
||||||
} else {
|
|
||||||
" ".to_string()
|
|
||||||
};
|
|
||||||
tmp
|
|
||||||
} else {
|
|
||||||
" ".to_string()
|
|
||||||
};
|
|
||||||
// indentation of this line will be covered by the previous if we're using a custom whitespace or comment
|
|
||||||
let mut start_string = if is_legit_custom_whitespace_or_comment(last_white_space_or_comment) {
|
|
||||||
String::new()
|
|
||||||
} else {
|
|
||||||
indentation.to_owned()
|
|
||||||
};
|
|
||||||
if index == 0 {
|
|
||||||
if let Some(start) = self.non_code_meta.start.clone() {
|
if let Some(start) = self.non_code_meta.start.clone() {
|
||||||
start_string = start.format(indentation);
|
start.format(&indentation)
|
||||||
} else {
|
} else {
|
||||||
start_string = indentation.to_owned();
|
indentation.to_string()
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
|
// Do nothing, we already applied the indentation elsewhere.
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
|
||||||
// determine the value of endString
|
// determine the value of the end string
|
||||||
let maybe_line_break: String = if index == self.body.len() - 1 && !is_with_block {
|
// basically if we are inside a nested function we want to end with a new line
|
||||||
|
let maybe_line_break: String = if index == self.body.len() - 1 && indentation_level == 0 {
|
||||||
String::new()
|
String::new()
|
||||||
} else {
|
} else {
|
||||||
"\n".to_string()
|
"\n".to_string()
|
||||||
};
|
};
|
||||||
let mut custom_white_space_or_comment = match self.non_code_meta.none_code_nodes.get(&index) {
|
|
||||||
Some(custom_white_space_or_comment) => custom_white_space_or_comment.format(indentation),
|
let custom_white_space_or_comment = match self.non_code_meta.none_code_nodes.get(&index) {
|
||||||
|
Some(custom_white_space_or_comment) => custom_white_space_or_comment.format(&indentation),
|
||||||
None => String::new(),
|
None => String::new(),
|
||||||
};
|
};
|
||||||
if !is_legit_custom_whitespace_or_comment(custom_white_space_or_comment.clone()) {
|
|
||||||
custom_white_space_or_comment = String::new();
|
|
||||||
}
|
|
||||||
let end_string = if custom_white_space_or_comment.is_empty() {
|
let end_string = if custom_white_space_or_comment.is_empty() {
|
||||||
maybe_line_break
|
maybe_line_break
|
||||||
} else {
|
} else {
|
||||||
@ -103,7 +95,14 @@ impl Program {
|
|||||||
})
|
})
|
||||||
.collect::<String>()
|
.collect::<String>()
|
||||||
.trim()
|
.trim()
|
||||||
.to_string()
|
.to_string();
|
||||||
|
|
||||||
|
// Insert a final new line if the user wants it.
|
||||||
|
if options.insert_final_newline {
|
||||||
|
format!("{}\n", result)
|
||||||
|
} else {
|
||||||
|
result
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the body item that includes the given character position.
|
/// Returns the body item that includes the given character position.
|
||||||
@ -118,6 +117,18 @@ impl Program {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the body item that includes the given character position.
|
||||||
|
pub fn get_mut_body_item_for_position(&mut self, pos: usize) -> Option<&mut BodyItem> {
|
||||||
|
for item in &mut self.body {
|
||||||
|
let source_range: SourceRange = item.clone().into();
|
||||||
|
if source_range.contains(pos) {
|
||||||
|
return Some(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns a value that includes the given character position.
|
/// Returns a value that includes the given character position.
|
||||||
/// This is a bit more recursive than `get_body_item_for_position`.
|
/// This is a bit more recursive than `get_body_item_for_position`.
|
||||||
pub fn get_value_for_position(&self, pos: usize) -> Option<&Value> {
|
pub fn get_value_for_position(&self, pos: usize) -> Option<&Value> {
|
||||||
@ -150,6 +161,82 @@ impl Program {
|
|||||||
|
|
||||||
symbols
|
symbols
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename the variable declaration at the given position.
|
||||||
|
pub fn rename_symbol(&mut self, new_name: &str, pos: usize) {
|
||||||
|
// The position must be within the variable declaration.
|
||||||
|
let mut old_name = None;
|
||||||
|
for item in &mut self.body {
|
||||||
|
match item {
|
||||||
|
BodyItem::ExpressionStatement(_expression_statement) => {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
BodyItem::VariableDeclaration(ref mut variable_declaration) => {
|
||||||
|
if let Some(var_old_name) = variable_declaration.rename_symbol(new_name, pos) {
|
||||||
|
old_name = Some(var_old_name);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BodyItem::ReturnStatement(_return_statement) => continue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(old_name) = old_name {
|
||||||
|
// Now rename all the identifiers in the rest of the program.
|
||||||
|
self.rename_identifiers(&old_name, new_name);
|
||||||
|
} else {
|
||||||
|
// Okay so this was not a top level variable declaration.
|
||||||
|
// But it might be a variable declaration inside a function or function params.
|
||||||
|
// So we need to check that.
|
||||||
|
let Some(ref mut item) = self.get_mut_body_item_for_position(pos) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Recurse over the item.
|
||||||
|
let mut value = match item {
|
||||||
|
BodyItem::ExpressionStatement(ref mut expression_statement) => {
|
||||||
|
Some(&mut expression_statement.expression)
|
||||||
|
}
|
||||||
|
BodyItem::VariableDeclaration(ref mut variable_declaration) => {
|
||||||
|
variable_declaration.get_mut_value_for_position(pos)
|
||||||
|
}
|
||||||
|
BodyItem::ReturnStatement(ref mut return_statement) => Some(&mut return_statement.argument),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if we have a function expression.
|
||||||
|
if let Some(Value::FunctionExpression(ref mut function_expression)) = &mut value {
|
||||||
|
// Check if the params to the function expression contain the position.
|
||||||
|
for param in &mut function_expression.params {
|
||||||
|
let param_source_range: SourceRange = param.clone().into();
|
||||||
|
if param_source_range.contains(pos) {
|
||||||
|
let old_name = param.name.clone();
|
||||||
|
// Rename the param.
|
||||||
|
param.rename(&old_name, new_name);
|
||||||
|
// Now rename all the identifiers in the rest of the program.
|
||||||
|
function_expression.body.rename_identifiers(&old_name, new_name);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
for item in &mut self.body {
|
||||||
|
match item {
|
||||||
|
BodyItem::ExpressionStatement(ref mut expression_statement) => {
|
||||||
|
expression_statement.expression.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
|
BodyItem::VariableDeclaration(ref mut variable_declaration) => {
|
||||||
|
variable_declaration.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
|
BodyItem::ReturnStatement(ref mut return_statement) => {
|
||||||
|
return_statement.argument.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait ValueMeta {
|
pub trait ValueMeta {
|
||||||
@ -249,19 +336,18 @@ pub enum Value {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Value {
|
impl Value {
|
||||||
fn recast(&self, indentation: &str, is_in_pipe_expression: bool) -> String {
|
fn recast(&self, options: &FormatOptions, indentation_level: usize, is_in_pipe: bool) -> String {
|
||||||
let indentation = indentation.to_string() + if is_in_pipe_expression { " " } else { "" };
|
|
||||||
match &self {
|
match &self {
|
||||||
Value::BinaryExpression(bin_exp) => bin_exp.recast(),
|
Value::BinaryExpression(bin_exp) => bin_exp.recast(options),
|
||||||
Value::ArrayExpression(array_exp) => array_exp.recast(&indentation, is_in_pipe_expression),
|
Value::ArrayExpression(array_exp) => array_exp.recast(options, indentation_level, is_in_pipe),
|
||||||
Value::ObjectExpression(ref obj_exp) => obj_exp.recast(&indentation, is_in_pipe_expression),
|
Value::ObjectExpression(ref obj_exp) => obj_exp.recast(options, indentation_level, is_in_pipe),
|
||||||
Value::MemberExpression(mem_exp) => mem_exp.recast(),
|
Value::MemberExpression(mem_exp) => mem_exp.recast(),
|
||||||
Value::Literal(literal) => literal.recast(),
|
Value::Literal(literal) => literal.recast(),
|
||||||
Value::FunctionExpression(func_exp) => func_exp.recast(&indentation),
|
Value::FunctionExpression(func_exp) => func_exp.recast(options, indentation_level),
|
||||||
Value::CallExpression(call_exp) => call_exp.recast(&indentation, is_in_pipe_expression),
|
Value::CallExpression(call_exp) => call_exp.recast(options, indentation_level, is_in_pipe),
|
||||||
Value::Identifier(ident) => ident.name.to_string(),
|
Value::Identifier(ident) => ident.name.to_string(),
|
||||||
Value::PipeExpression(pipe_exp) => pipe_exp.recast(&indentation),
|
Value::PipeExpression(pipe_exp) => pipe_exp.recast(options, indentation_level),
|
||||||
Value::UnaryExpression(unary_exp) => unary_exp.recast(),
|
Value::UnaryExpression(unary_exp) => unary_exp.recast(options),
|
||||||
Value::PipeSubstitution(_) => crate::parser::PIPE_SUBSTITUTION_OPERATOR.to_string(),
|
Value::PipeSubstitution(_) => crate::parser::PIPE_SUBSTITUTION_OPERATOR.to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -317,6 +403,29 @@ impl Value {
|
|||||||
Value::UnaryExpression(unary_expression) => unary_expression.get_hover_value_for_position(pos, code),
|
Value::UnaryExpression(unary_expression) => unary_expression.get_hover_value_for_position(pos, code),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
match self {
|
||||||
|
Value::Literal(_literal) => {}
|
||||||
|
Value::Identifier(ref mut identifier) => identifier.rename(old_name, new_name),
|
||||||
|
Value::BinaryExpression(ref mut binary_expression) => {
|
||||||
|
binary_expression.rename_identifiers(old_name, new_name)
|
||||||
|
}
|
||||||
|
Value::FunctionExpression(_function_identifier) => {}
|
||||||
|
Value::CallExpression(ref mut call_expression) => call_expression.rename_identifiers(old_name, new_name),
|
||||||
|
Value::PipeExpression(ref mut pipe_expression) => pipe_expression.rename_identifiers(old_name, new_name),
|
||||||
|
Value::PipeSubstitution(_) => {}
|
||||||
|
Value::ArrayExpression(ref mut array_expression) => array_expression.rename_identifiers(old_name, new_name),
|
||||||
|
Value::ObjectExpression(ref mut object_expression) => {
|
||||||
|
object_expression.rename_identifiers(old_name, new_name)
|
||||||
|
}
|
||||||
|
Value::MemberExpression(ref mut member_expression) => {
|
||||||
|
member_expression.rename_identifiers(old_name, new_name)
|
||||||
|
}
|
||||||
|
Value::UnaryExpression(ref mut unary_expression) => unary_expression.rename_identifiers(old_name, new_name),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<Value> for crate::executor::SourceRange {
|
impl From<Value> for crate::executor::SourceRange {
|
||||||
@ -355,13 +464,13 @@ impl From<&BinaryPart> for crate::executor::SourceRange {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl BinaryPart {
|
impl BinaryPart {
|
||||||
fn recast(&self, indentation: &str) -> String {
|
fn recast(&self, options: &FormatOptions, indentation_level: usize) -> String {
|
||||||
match &self {
|
match &self {
|
||||||
BinaryPart::Literal(literal) => literal.recast(),
|
BinaryPart::Literal(literal) => literal.recast(),
|
||||||
BinaryPart::Identifier(identifier) => identifier.name.to_string(),
|
BinaryPart::Identifier(identifier) => identifier.name.to_string(),
|
||||||
BinaryPart::BinaryExpression(binary_expression) => binary_expression.recast(),
|
BinaryPart::BinaryExpression(binary_expression) => binary_expression.recast(options),
|
||||||
BinaryPart::CallExpression(call_expression) => call_expression.recast(indentation, false),
|
BinaryPart::CallExpression(call_expression) => call_expression.recast(options, indentation_level, false),
|
||||||
BinaryPart::UnaryExpression(unary_expression) => unary_expression.recast(),
|
BinaryPart::UnaryExpression(unary_expression) => unary_expression.recast(options),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -422,6 +531,23 @@ impl BinaryPart {
|
|||||||
BinaryPart::UnaryExpression(unary_expression) => unary_expression.get_hover_value_for_position(pos, code),
|
BinaryPart::UnaryExpression(unary_expression) => unary_expression.get_hover_value_for_position(pos, code),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
match self {
|
||||||
|
BinaryPart::Literal(_literal) => {}
|
||||||
|
BinaryPart::Identifier(ref mut identifier) => identifier.rename(old_name, new_name),
|
||||||
|
BinaryPart::BinaryExpression(ref mut binary_expression) => {
|
||||||
|
binary_expression.rename_identifiers(old_name, new_name)
|
||||||
|
}
|
||||||
|
BinaryPart::CallExpression(ref mut call_expression) => {
|
||||||
|
call_expression.rename_identifiers(old_name, new_name)
|
||||||
|
}
|
||||||
|
BinaryPart::UnaryExpression(ref mut unary_expression) => {
|
||||||
|
unary_expression.rename_identifiers(old_name, new_name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
||||||
@ -436,17 +562,17 @@ pub struct NoneCodeNode {
|
|||||||
impl NoneCodeNode {
|
impl NoneCodeNode {
|
||||||
pub fn value(&self) -> String {
|
pub fn value(&self) -> String {
|
||||||
match &self.value {
|
match &self.value {
|
||||||
NoneCodeValue::Inline { value } => value.clone(),
|
NoneCodeValue::InlineComment { value } => value.clone(),
|
||||||
NoneCodeValue::Block { value } => value.clone(),
|
NoneCodeValue::BlockComment { value } => value.clone(),
|
||||||
NoneCodeValue::NewLineBlock { value } => value.clone(),
|
NoneCodeValue::NewLineBlockComment { value } => value.clone(),
|
||||||
NoneCodeValue::NewLine => "\n\n".to_string(),
|
NoneCodeValue::NewLine => "\n\n".to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn format(&self, indentation: &str) -> String {
|
pub fn format(&self, indentation: &str) -> String {
|
||||||
match &self.value {
|
match &self.value {
|
||||||
NoneCodeValue::Inline { value } => format!(" // {}\n", value),
|
NoneCodeValue::InlineComment { value } => format!(" // {}\n", value),
|
||||||
NoneCodeValue::Block { value } => {
|
NoneCodeValue::BlockComment { value } => {
|
||||||
let add_start_new_line = if self.start == 0 { "" } else { "\n" };
|
let add_start_new_line = if self.start == 0 { "" } else { "\n" };
|
||||||
if value.contains('\n') {
|
if value.contains('\n') {
|
||||||
format!("{}{}/* {} */\n", add_start_new_line, indentation, value)
|
format!("{}{}/* {} */\n", add_start_new_line, indentation, value)
|
||||||
@ -454,7 +580,7 @@ impl NoneCodeNode {
|
|||||||
format!("{}{}// {}\n", add_start_new_line, indentation, value)
|
format!("{}{}// {}\n", add_start_new_line, indentation, value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
NoneCodeValue::NewLineBlock { value } => {
|
NoneCodeValue::NewLineBlockComment { value } => {
|
||||||
let add_start_new_line = if self.start == 0 { "" } else { "\n\n" };
|
let add_start_new_line = if self.start == 0 { "" } else { "\n\n" };
|
||||||
if value.contains('\n') {
|
if value.contains('\n') {
|
||||||
format!("{}{}/* {} */\n", add_start_new_line, indentation, value)
|
format!("{}{}/* {} */\n", add_start_new_line, indentation, value)
|
||||||
@ -471,9 +597,29 @@ impl NoneCodeNode {
|
|||||||
#[ts(export)]
|
#[ts(export)]
|
||||||
#[serde(tag = "type", rename_all = "camelCase")]
|
#[serde(tag = "type", rename_all = "camelCase")]
|
||||||
pub enum NoneCodeValue {
|
pub enum NoneCodeValue {
|
||||||
Inline { value: String },
|
/// An inline comment.
|
||||||
Block { value: String },
|
/// An example of this is the following: `1 + 1 // This is an inline comment`.
|
||||||
NewLineBlock { value: String },
|
InlineComment {
|
||||||
|
value: String,
|
||||||
|
},
|
||||||
|
/// A block comment.
|
||||||
|
/// An example of this is the following:
|
||||||
|
/// ```python,no_run
|
||||||
|
/// /* This is a
|
||||||
|
/// block comment */
|
||||||
|
/// 1 + 1
|
||||||
|
/// ```
|
||||||
|
/// Now this is important. The block comment is attached to the next line.
|
||||||
|
/// This is always the case. Also the block comment doesnt have a new line above it.
|
||||||
|
/// If it did it would be a `NewLineBlockComment`.
|
||||||
|
BlockComment {
|
||||||
|
value: String,
|
||||||
|
},
|
||||||
|
/// A block comment that has a new line above it.
|
||||||
|
/// The user explicitly added a new line above the block comment.
|
||||||
|
NewLineBlockComment {
|
||||||
|
value: String,
|
||||||
|
},
|
||||||
// A new line like `\n\n` NOT a new line like `\n`.
|
// A new line like `\n\n` NOT a new line like `\n`.
|
||||||
// This is also not a comment.
|
// This is also not a comment.
|
||||||
NewLine,
|
NewLine,
|
||||||
@ -539,13 +685,13 @@ pub struct CallExpression {
|
|||||||
impl_value_meta!(CallExpression);
|
impl_value_meta!(CallExpression);
|
||||||
|
|
||||||
impl CallExpression {
|
impl CallExpression {
|
||||||
fn recast(&self, indentation: &str, is_in_pipe_expression: bool) -> String {
|
fn recast(&self, options: &FormatOptions, indentation_level: usize, is_in_pipe: bool) -> String {
|
||||||
format!(
|
format!(
|
||||||
"{}({})",
|
"{}({})",
|
||||||
self.callee.name,
|
self.callee.name,
|
||||||
self.arguments
|
self.arguments
|
||||||
.iter()
|
.iter()
|
||||||
.map(|arg| arg.recast(indentation, is_in_pipe_expression))
|
.map(|arg| arg.recast(options, indentation_level, is_in_pipe))
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(", ")
|
.join(", ")
|
||||||
)
|
)
|
||||||
@ -671,6 +817,15 @@ impl CallExpression {
|
|||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
self.callee.rename(old_name, new_name);
|
||||||
|
|
||||||
|
for arg in &mut self.arguments {
|
||||||
|
arg.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A function declaration.
|
/// A function declaration.
|
||||||
@ -723,6 +878,50 @@ impl VariableDeclaration {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns a value that includes the given character position.
|
||||||
|
pub fn get_mut_value_for_position(&mut self, pos: usize) -> Option<&mut Value> {
|
||||||
|
for declaration in &mut self.declarations {
|
||||||
|
let source_range: SourceRange = declaration.clone().into();
|
||||||
|
if source_range.contains(pos) {
|
||||||
|
return Some(&mut declaration.init);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rename the variable declaration at the given position.
|
||||||
|
/// This returns the old name of the variable, if it found one.
|
||||||
|
pub fn rename_symbol(&mut self, new_name: &str, pos: usize) -> Option<String> {
|
||||||
|
// The position must be within the variable declaration.
|
||||||
|
let source_range: SourceRange = self.clone().into();
|
||||||
|
if !source_range.contains(pos) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
for declaration in &mut self.declarations {
|
||||||
|
let declaration_source_range: SourceRange = declaration.id.clone().into();
|
||||||
|
if declaration_source_range.contains(pos) {
|
||||||
|
let old_name = declaration.id.name.clone();
|
||||||
|
declaration.id.name = new_name.to_string();
|
||||||
|
return Some(old_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
for declaration in &mut self.declarations {
|
||||||
|
// Skip the init for the variable with the new name since it is the one we are renaming.
|
||||||
|
if declaration.id.name == new_name {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
declaration.init.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_lsp_symbols(&self, code: &str) -> Vec<DocumentSymbol> {
|
pub fn get_lsp_symbols(&self, code: &str) -> Vec<DocumentSymbol> {
|
||||||
let mut symbols = vec![];
|
let mut symbols = vec![];
|
||||||
|
|
||||||
@ -839,7 +1038,9 @@ impl VariableKind {
|
|||||||
pub struct VariableDeclarator {
|
pub struct VariableDeclarator {
|
||||||
pub start: usize,
|
pub start: usize,
|
||||||
pub end: usize,
|
pub end: usize,
|
||||||
|
/// The identifier of the variable.
|
||||||
pub id: Identifier,
|
pub id: Identifier,
|
||||||
|
/// The value of the variable.
|
||||||
pub init: Value,
|
pub init: Value,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -901,6 +1102,15 @@ pub struct Identifier {
|
|||||||
|
|
||||||
impl_value_meta!(Identifier);
|
impl_value_meta!(Identifier);
|
||||||
|
|
||||||
|
impl Identifier {
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
if self.name == old_name {
|
||||||
|
self.name = new_name.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
||||||
#[ts(export)]
|
#[ts(export)]
|
||||||
#[serde(tag = "type")]
|
#[serde(tag = "type")]
|
||||||
@ -923,27 +1133,35 @@ pub struct ArrayExpression {
|
|||||||
impl_value_meta!(ArrayExpression);
|
impl_value_meta!(ArrayExpression);
|
||||||
|
|
||||||
impl ArrayExpression {
|
impl ArrayExpression {
|
||||||
fn recast(&self, indentation: &str, is_in_pipe_expression: bool) -> String {
|
fn recast(&self, options: &FormatOptions, indentation_level: usize, is_in_pipe: bool) -> String {
|
||||||
let flat_recast = format!(
|
let flat_recast = format!(
|
||||||
"[{}]",
|
"[{}]",
|
||||||
self.elements
|
self.elements
|
||||||
.iter()
|
.iter()
|
||||||
.map(|el| el.recast("", false))
|
.map(|el| el.recast(options, 0, false))
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(", ")
|
.join(", ")
|
||||||
);
|
);
|
||||||
let max_array_length = 40;
|
let max_array_length = 40;
|
||||||
if flat_recast.len() > max_array_length {
|
if flat_recast.len() > max_array_length {
|
||||||
let indentation = indentation.to_string() + " ";
|
let inner_indentation = if is_in_pipe {
|
||||||
|
options.get_indentation_offset_pipe(indentation_level + 1)
|
||||||
|
} else {
|
||||||
|
options.get_indentation(indentation_level + 1)
|
||||||
|
};
|
||||||
format!(
|
format!(
|
||||||
"[\n{}{}\n{}]",
|
"[\n{}{}\n{}]",
|
||||||
indentation,
|
inner_indentation,
|
||||||
self.elements
|
self.elements
|
||||||
.iter()
|
.iter()
|
||||||
.map(|el| el.recast(&indentation, false))
|
.map(|el| el.recast(options, indentation_level, false))
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(format!(",\n{}", indentation).as_str()),
|
.join(format!(",\n{}", inner_indentation).as_str()),
|
||||||
if is_in_pipe_expression { " " } else { "" }
|
if is_in_pipe {
|
||||||
|
options.get_indentation_offset_pipe(indentation_level)
|
||||||
|
} else {
|
||||||
|
options.get_indentation(indentation_level)
|
||||||
|
},
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
flat_recast
|
flat_recast
|
||||||
@ -1019,6 +1237,13 @@ impl ArrayExpression {
|
|||||||
}],
|
}],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
for element in &mut self.elements {
|
||||||
|
element.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
||||||
@ -1031,27 +1256,35 @@ pub struct ObjectExpression {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ObjectExpression {
|
impl ObjectExpression {
|
||||||
fn recast(&self, indentation: &str, is_in_pipe_expression: bool) -> String {
|
fn recast(&self, options: &FormatOptions, indentation_level: usize, is_in_pipe: bool) -> String {
|
||||||
let flat_recast = format!(
|
let flat_recast = format!(
|
||||||
"{{ {} }}",
|
"{{ {} }}",
|
||||||
self.properties
|
self.properties
|
||||||
.iter()
|
.iter()
|
||||||
.map(|prop| { format!("{}: {}", prop.key.name, prop.value.recast("", false)) })
|
.map(|prop| { format!("{}: {}", prop.key.name, prop.value.recast(options, 0, false)) })
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(", ")
|
.join(", ")
|
||||||
);
|
);
|
||||||
let max_array_length = 40;
|
let max_array_length = 40;
|
||||||
if flat_recast.len() > max_array_length {
|
if flat_recast.len() > max_array_length {
|
||||||
let indentation = indentation.to_owned() + " ";
|
let inner_indentation = if is_in_pipe {
|
||||||
|
options.get_indentation_offset_pipe(indentation_level + 1)
|
||||||
|
} else {
|
||||||
|
options.get_indentation(indentation_level + 1)
|
||||||
|
};
|
||||||
format!(
|
format!(
|
||||||
"{{\n{}{}\n{}}}",
|
"{{\n{}{}\n{}}}",
|
||||||
indentation,
|
inner_indentation,
|
||||||
self.properties
|
self.properties
|
||||||
.iter()
|
.iter()
|
||||||
.map(|prop| { format!("{}: {}", prop.key.name, prop.value.recast("", is_in_pipe_expression)) })
|
.map(|prop| { format!("{}: {}", prop.key.name, prop.value.recast(options, 0, false)) })
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(format!(",\n{}", indentation).as_str()),
|
.join(format!(",\n{}", inner_indentation).as_str()),
|
||||||
if is_in_pipe_expression { " " } else { "" }
|
if is_in_pipe {
|
||||||
|
options.get_indentation_offset_pipe(indentation_level)
|
||||||
|
} else {
|
||||||
|
options.get_indentation(indentation_level)
|
||||||
|
},
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
flat_recast
|
flat_recast
|
||||||
@ -1125,6 +1358,13 @@ impl ObjectExpression {
|
|||||||
}],
|
}],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
for property in &mut self.properties {
|
||||||
|
property.value.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl_value_meta!(ObjectExpression);
|
impl_value_meta!(ObjectExpression);
|
||||||
@ -1342,6 +1582,21 @@ impl MemberExpression {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
match &mut self.object {
|
||||||
|
MemberObject::MemberExpression(ref mut member_expression) => {
|
||||||
|
member_expression.rename_identifiers(old_name, new_name)
|
||||||
|
}
|
||||||
|
MemberObject::Identifier(ref mut identifier) => identifier.rename(old_name, new_name),
|
||||||
|
}
|
||||||
|
|
||||||
|
match &mut self.property {
|
||||||
|
LiteralIdentifier::Identifier(ref mut identifier) => identifier.rename(old_name, new_name),
|
||||||
|
LiteralIdentifier::Literal(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
||||||
@ -1370,7 +1625,7 @@ impl BinaryExpression {
|
|||||||
self.operator.precedence()
|
self.operator.precedence()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn recast(&self) -> String {
|
fn recast(&self, options: &FormatOptions) -> String {
|
||||||
let maybe_wrap_it = |a: String, doit: bool| -> String {
|
let maybe_wrap_it = |a: String, doit: bool| -> String {
|
||||||
if doit {
|
if doit {
|
||||||
format!("({})", a)
|
format!("({})", a)
|
||||||
@ -1393,9 +1648,9 @@ impl BinaryExpression {
|
|||||||
|
|
||||||
format!(
|
format!(
|
||||||
"{} {} {}",
|
"{} {} {}",
|
||||||
maybe_wrap_it(self.left.recast(""), should_wrap_left),
|
maybe_wrap_it(self.left.recast(options, 0), should_wrap_left),
|
||||||
self.operator,
|
self.operator,
|
||||||
maybe_wrap_it(self.right.recast(""), should_wrap_right)
|
maybe_wrap_it(self.right.recast(options, 0), should_wrap_right)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1458,6 +1713,12 @@ impl BinaryExpression {
|
|||||||
}],
|
}],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
self.left.rename_identifiers(old_name, new_name);
|
||||||
|
self.right.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_json_number_as_f64(j: &serde_json::Value, source_range: SourceRange) -> Result<f64, KclError> {
|
pub fn parse_json_number_as_f64(j: &serde_json::Value, source_range: SourceRange) -> Result<f64, KclError> {
|
||||||
@ -1532,8 +1793,8 @@ pub struct UnaryExpression {
|
|||||||
impl_value_meta!(UnaryExpression);
|
impl_value_meta!(UnaryExpression);
|
||||||
|
|
||||||
impl UnaryExpression {
|
impl UnaryExpression {
|
||||||
fn recast(&self) -> String {
|
fn recast(&self, options: &FormatOptions) -> String {
|
||||||
format!("{}{}", &self.operator, self.argument.recast(""))
|
format!("{}{}", &self.operator, self.argument.recast(options, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_result(
|
pub fn get_result(
|
||||||
@ -1565,6 +1826,11 @@ impl UnaryExpression {
|
|||||||
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
self.argument.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, FromStr, Display)]
|
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, FromStr, Display)]
|
||||||
@ -1595,13 +1861,13 @@ pub struct PipeExpression {
|
|||||||
impl_value_meta!(PipeExpression);
|
impl_value_meta!(PipeExpression);
|
||||||
|
|
||||||
impl PipeExpression {
|
impl PipeExpression {
|
||||||
fn recast(&self, indentation: &str) -> String {
|
fn recast(&self, options: &FormatOptions, indentation_level: usize) -> String {
|
||||||
self.body
|
self.body
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(index, statement)| {
|
.map(|(index, statement)| {
|
||||||
let indentation = indentation.to_string() + " ";
|
let indentation = options.get_indentation(indentation_level + 1);
|
||||||
let mut s = statement.recast(&indentation, true);
|
let mut s = statement.recast(options, indentation_level + 1, true);
|
||||||
let non_code_meta = self.non_code_meta.clone();
|
let non_code_meta = self.non_code_meta.clone();
|
||||||
if let Some(non_code_meta_value) = non_code_meta.none_code_nodes.get(&index) {
|
if let Some(non_code_meta_value) = non_code_meta.none_code_nodes.get(&index) {
|
||||||
s += non_code_meta_value.format(&indentation).trim_end_matches('\n')
|
s += non_code_meta_value.format(&indentation).trim_end_matches('\n')
|
||||||
@ -1641,6 +1907,13 @@ impl PipeExpression {
|
|||||||
pipe_info.index = 0;
|
pipe_info.index = 0;
|
||||||
execute_pipe_body(memory, &self.body, pipe_info, self.into(), engine)
|
execute_pipe_body(memory, &self.body, pipe_info, self.into(), engine)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rename all identifiers that have the old name to the new given name.
|
||||||
|
fn rename_identifiers(&mut self, old_name: &str, new_name: &str) {
|
||||||
|
for statement in &mut self.body {
|
||||||
|
statement.rename_identifiers(old_name, new_name);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_pipe_body(
|
fn execute_pipe_body(
|
||||||
@ -1706,17 +1979,16 @@ pub struct FunctionExpression {
|
|||||||
impl_value_meta!(FunctionExpression);
|
impl_value_meta!(FunctionExpression);
|
||||||
|
|
||||||
impl FunctionExpression {
|
impl FunctionExpression {
|
||||||
pub fn recast(&self, indentation: &str) -> String {
|
pub fn recast(&self, options: &FormatOptions, indentation_level: usize) -> String {
|
||||||
format!(
|
format!(
|
||||||
"({}) => {{\n{}{}{}\n}}",
|
"({}) => {{\n{}{}\n}}",
|
||||||
self.params
|
self.params
|
||||||
.iter()
|
.iter()
|
||||||
.map(|param| param.name.clone())
|
.map(|param| param.name.clone())
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(", "),
|
.join(", "),
|
||||||
indentation,
|
options.get_indentation(indentation_level + 1),
|
||||||
" ",
|
self.body.recast(options, indentation_level + 1)
|
||||||
self.body.recast(" ", true)
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1756,6 +2028,58 @@ pub enum Hover {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Format options.
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
||||||
|
#[ts(export)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct FormatOptions {
|
||||||
|
/// Size of a tab in spaces.
|
||||||
|
pub tab_size: usize,
|
||||||
|
/// Prefer tabs over spaces.
|
||||||
|
pub use_tabs: bool,
|
||||||
|
/// How to handle the final newline in the file.
|
||||||
|
/// If true, ensure file ends with a newline.
|
||||||
|
/// If false, ensure file does not end with a newline.
|
||||||
|
pub insert_final_newline: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for FormatOptions {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FormatOptions {
|
||||||
|
/// Define the default format options.
|
||||||
|
/// We use 2 spaces for indentation.
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
tab_size: 2,
|
||||||
|
use_tabs: false,
|
||||||
|
insert_final_newline: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the indentation string for the given level.
|
||||||
|
pub fn get_indentation(&self, level: usize) -> String {
|
||||||
|
if self.use_tabs {
|
||||||
|
"\t".repeat(level)
|
||||||
|
} else {
|
||||||
|
" ".repeat(level * self.tab_size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the indentation string for the given level.
|
||||||
|
/// But offset the pipe operator (and a space) by one level.
|
||||||
|
pub fn get_indentation_offset_pipe(&self, level: usize) -> String {
|
||||||
|
if self.use_tabs {
|
||||||
|
"\t".repeat(level + 1)
|
||||||
|
} else {
|
||||||
|
" ".repeat(level * self.tab_size) + " ".repeat(PIPE_OPERATOR.len() + 1).as_str()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -1797,7 +2121,7 @@ show(part001)"#;
|
|||||||
let some_program: crate::abstract_syntax_tree_types::Program =
|
let some_program: crate::abstract_syntax_tree_types::Program =
|
||||||
serde_json::from_str(some_program_string).unwrap();
|
serde_json::from_str(some_program_string).unwrap();
|
||||||
|
|
||||||
let recasted = some_program.recast("", false);
|
let recasted = some_program.recast(&Default::default(), 0);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
recasted,
|
recasted,
|
||||||
r#"const part001 = startSketchAt('default')
|
r#"const part001 = startSketchAt('default')
|
||||||
@ -1816,7 +2140,7 @@ show(part001)"#
|
|||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
recasted,
|
recasted,
|
||||||
r#"const part001 = startSketchAt([0.0, 5.0])
|
r#"const part001 = startSketchAt([0.0, 5.0])
|
||||||
@ -1834,7 +2158,7 @@ show(part001)"#
|
|||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
recasted,
|
recasted,
|
||||||
r#"const part001 = startSketchAt([0.0, 5.0])
|
r#"const part001 = startSketchAt([0.0, 5.0])
|
||||||
@ -1852,7 +2176,7 @@ show(part001)"#
|
|||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
recasted,
|
recasted,
|
||||||
r#"const part001 = startSketchAt([0.0, 5.0])
|
r#"const part001 = startSketchAt([0.0, 5.0])
|
||||||
@ -1877,7 +2201,7 @@ show(part001)"#
|
|||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
recasted,
|
recasted,
|
||||||
r#"const myFn = () => {
|
r#"const myFn = () => {
|
||||||
@ -1913,7 +2237,7 @@ const mySk1 = startSketchAt([0, 0])
|
|||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
recasted,
|
recasted,
|
||||||
r#"// comment at start
|
r#"// comment at start
|
||||||
@ -1940,9 +2264,9 @@ a comment between pipe expression statements */
|
|||||||
|> line({ to: [0.62, 4.15], tag: 'seg01' }, %)
|
|> line({ to: [0.62, 4.15], tag: 'seg01' }, %)
|
||||||
|> line([2.77, -1.24], %)
|
|> line([2.77, -1.24], %)
|
||||||
|> angledLineThatIntersects({
|
|> angledLineThatIntersects({
|
||||||
angle: 201,
|
angle: 201,
|
||||||
offset: -1.35,
|
offset: -1.35,
|
||||||
intersectTag: 'seg01'
|
intersectTag: 'seg01'
|
||||||
}, %)
|
}, %)
|
||||||
|> line([-0.42, -1.72], %)
|
|> line([-0.42, -1.72], %)
|
||||||
|
|
||||||
@ -1951,7 +2275,7 @@ show(part001)"#;
|
|||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(recasted, some_program_string);
|
assert_eq!(recasted, some_program_string);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1964,12 +2288,19 @@ const yo = {
|
|||||||
anum: 2,
|
anum: 2,
|
||||||
identifier: three,
|
identifier: three,
|
||||||
binExp: 4 + 5
|
binExp: 4 + 5
|
||||||
}"#;
|
}
|
||||||
|
const yo = [
|
||||||
|
1,
|
||||||
|
" 2,",
|
||||||
|
"three",
|
||||||
|
4 + 5,
|
||||||
|
" hey oooooo really long long long"
|
||||||
|
]"#;
|
||||||
let tokens = crate::tokeniser::lexer(some_program_string);
|
let tokens = crate::tokeniser::lexer(some_program_string);
|
||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(recasted, some_program_string);
|
assert_eq!(recasted, some_program_string);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1987,7 +2318,7 @@ const things = "things"
|
|||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(recasted, some_program_string.trim());
|
assert_eq!(recasted, some_program_string.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2005,7 +2336,125 @@ const things = "things"
|
|||||||
let parser = crate::parser::Parser::new(tokens);
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
let program = parser.ast().unwrap();
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
let recasted = program.recast("", false);
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
assert_eq!(recasted, some_program_string.trim());
|
assert_eq!(recasted, some_program_string.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_recast_array_new_line_in_pipe() {
|
||||||
|
let some_program_string = r#"const myVar = 3
|
||||||
|
const myVar2 = 5
|
||||||
|
const myVar3 = 6
|
||||||
|
const myAng = 40
|
||||||
|
const myAng2 = 134
|
||||||
|
const part001 = startSketchAt([0, 0])
|
||||||
|
|> line({ to: [1, 3.82], tag: 'seg01' }, %) // ln-should-get-tag
|
||||||
|
|> angledLineToX([
|
||||||
|
-angleToMatchLengthX('seg01', myVar, %),
|
||||||
|
myVar
|
||||||
|
], %) // ln-lineTo-xAbsolute should use angleToMatchLengthX helper
|
||||||
|
|> angledLineToY([
|
||||||
|
-angleToMatchLengthY('seg01', myVar, %),
|
||||||
|
myVar
|
||||||
|
], %) // ln-lineTo-yAbsolute should use angleToMatchLengthY helper"#;
|
||||||
|
let tokens = crate::tokeniser::lexer(some_program_string);
|
||||||
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
|
assert_eq!(recasted, some_program_string);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_recast_array_new_line_in_pipe_custom() {
|
||||||
|
let some_program_string = r#"const myVar = 3
|
||||||
|
const myVar2 = 5
|
||||||
|
const myVar3 = 6
|
||||||
|
const myAng = 40
|
||||||
|
const myAng2 = 134
|
||||||
|
const part001 = startSketchAt([0, 0])
|
||||||
|
|> line({ to: [1, 3.82], tag: 'seg01' }, %) // ln-should-get-tag
|
||||||
|
|> angledLineToX([
|
||||||
|
-angleToMatchLengthX('seg01', myVar, %),
|
||||||
|
myVar
|
||||||
|
], %) // ln-lineTo-xAbsolute should use angleToMatchLengthX helper
|
||||||
|
|> angledLineToY([
|
||||||
|
-angleToMatchLengthY('seg01', myVar, %),
|
||||||
|
myVar
|
||||||
|
], %) // ln-lineTo-yAbsolute should use angleToMatchLengthY helper
|
||||||
|
"#;
|
||||||
|
let tokens = crate::tokeniser::lexer(some_program_string);
|
||||||
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
|
let program = parser.ast().unwrap();
|
||||||
|
|
||||||
|
let recasted = program.recast(
|
||||||
|
&FormatOptions {
|
||||||
|
tab_size: 3,
|
||||||
|
use_tabs: false,
|
||||||
|
insert_final_newline: true,
|
||||||
|
},
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert_eq!(recasted, some_program_string);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_recast_after_rename_std() {
|
||||||
|
let some_program_string = r#"const part001 = startSketchAt([0.0000000000, 5.0000000000])
|
||||||
|
|> line([0.4900857016, -0.0240763666], %)
|
||||||
|
|
||||||
|
const part002 = "part002"
|
||||||
|
const things = [part001, 0.0]
|
||||||
|
let blah = 1
|
||||||
|
const foo = false
|
||||||
|
let baz = {a: 1, part001: "thing"}
|
||||||
|
|
||||||
|
fn ghi = (part001) => {
|
||||||
|
return part001
|
||||||
|
}
|
||||||
|
|
||||||
|
show(part001)"#;
|
||||||
|
let tokens = crate::tokeniser::lexer(some_program_string);
|
||||||
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
|
let mut program = parser.ast().unwrap();
|
||||||
|
program.rename_symbol("mySuperCoolPart", 6);
|
||||||
|
|
||||||
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
|
assert_eq!(
|
||||||
|
recasted,
|
||||||
|
r#"const mySuperCoolPart = startSketchAt([0.0, 5.0])
|
||||||
|
|> line([0.4900857016, -0.0240763666], %)
|
||||||
|
|
||||||
|
const part002 = "part002"
|
||||||
|
const things = [mySuperCoolPart, 0.0]
|
||||||
|
let blah = 1
|
||||||
|
const foo = false
|
||||||
|
let baz = { a: 1, part001: "thing" }
|
||||||
|
|
||||||
|
fn ghi = (part001) => {
|
||||||
|
return part001
|
||||||
|
}
|
||||||
|
|
||||||
|
show(mySuperCoolPart)"#
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_recast_after_rename_fn_args() {
|
||||||
|
let some_program_string = r#"fn ghi = (x, y, z) => {
|
||||||
|
return x
|
||||||
|
}"#;
|
||||||
|
let tokens = crate::tokeniser::lexer(some_program_string);
|
||||||
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
|
let mut program = parser.ast().unwrap();
|
||||||
|
program.rename_symbol("newName", 10);
|
||||||
|
|
||||||
|
let recasted = program.recast(&Default::default(), 0);
|
||||||
|
assert_eq!(
|
||||||
|
recasted,
|
||||||
|
r#"fn ghi = (newName, y, z) => {
|
||||||
|
return newName
|
||||||
|
}"#
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -87,6 +87,9 @@ impl EngineConnection {
|
|||||||
|
|
||||||
if let Some(msg) = ws_resp.resp {
|
if let Some(msg) = ws_resp.resp {
|
||||||
match msg {
|
match msg {
|
||||||
|
OkWebSocketResponseData::MetricsRequest {} => {
|
||||||
|
// @paultag todo
|
||||||
|
}
|
||||||
OkWebSocketResponseData::IceServerInfo { ice_servers } => {
|
OkWebSocketResponseData::IceServerInfo { ice_servers } => {
|
||||||
println!("got ice server info: {:?}", ice_servers);
|
println!("got ice server info: {:?}", ice_servers);
|
||||||
}
|
}
|
||||||
|
@ -642,7 +642,7 @@ pub fn execute(
|
|||||||
for (index, param) in function_expression.params.iter().enumerate() {
|
for (index, param) in function_expression.params.iter().enumerate() {
|
||||||
fn_memory.add(
|
fn_memory.add(
|
||||||
¶m.name,
|
¶m.name,
|
||||||
args.clone().get(index).unwrap().clone(),
|
args.get(index).unwrap().clone(),
|
||||||
param.into(),
|
param.into(),
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
|
@ -228,8 +228,8 @@ impl ReversePolishNotation {
|
|||||||
.collect::<Vec<Token>>(),
|
.collect::<Vec<Token>>(),
|
||||||
);
|
);
|
||||||
return rpn.parse();
|
return rpn.parse();
|
||||||
} else if current_token.value == ")" {
|
} else if current_token.value == ")" && !self.operators.is_empty() {
|
||||||
if !self.operators.is_empty() && self.operators[self.operators.len() - 1].value != "(" {
|
if self.operators[self.operators.len() - 1].value != "(" {
|
||||||
// pop operators off the stack and push them to postFix until we find the matching '('
|
// pop operators off the stack and push them to postFix until we find the matching '('
|
||||||
let rpn = ReversePolishNotation::new(
|
let rpn = ReversePolishNotation::new(
|
||||||
&self.parser.tokens,
|
&self.parser.tokens,
|
||||||
|
@ -336,17 +336,26 @@ impl Parser {
|
|||||||
value: if start_end_string.starts_with("\n\n") && is_new_line_comment {
|
value: if start_end_string.starts_with("\n\n") && is_new_line_comment {
|
||||||
// Preserve if they want a whitespace line before the comment.
|
// Preserve if they want a whitespace line before the comment.
|
||||||
// But let's just allow one.
|
// But let's just allow one.
|
||||||
NoneCodeValue::NewLineBlock { value: full_string }
|
NoneCodeValue::NewLineBlockComment { value: full_string }
|
||||||
} else if is_new_line_comment {
|
} else if is_new_line_comment {
|
||||||
NoneCodeValue::Block { value: full_string }
|
NoneCodeValue::BlockComment { value: full_string }
|
||||||
} else {
|
} else {
|
||||||
NoneCodeValue::Inline { value: full_string }
|
NoneCodeValue::InlineComment { value: full_string }
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
Ok((Some(node), end_index - 1))
|
Ok((Some(node), end_index - 1))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn next_meaningful_token(&self, index: usize, offset: Option<usize>) -> Result<TokenReturnWithNonCode, KclError> {
|
fn next_meaningful_token(&self, index: usize, offset: Option<usize>) -> Result<TokenReturnWithNonCode, KclError> {
|
||||||
|
// There is no next meaningful token.
|
||||||
|
if index >= self.tokens.len() - 1 {
|
||||||
|
return Ok(TokenReturnWithNonCode {
|
||||||
|
token: None,
|
||||||
|
index: self.tokens.len() - 1,
|
||||||
|
non_code_node: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
let new_index = index + offset.unwrap_or(1);
|
let new_index = index + offset.unwrap_or(1);
|
||||||
let Ok(token) = self.get_token(new_index) else {
|
let Ok(token) = self.get_token(new_index) else {
|
||||||
return Ok(TokenReturnWithNonCode {
|
return Ok(TokenReturnWithNonCode {
|
||||||
@ -405,7 +414,7 @@ impl Parser {
|
|||||||
if found_another_opening_brace {
|
if found_another_opening_brace {
|
||||||
return self.find_closing_brace(index + 1, brace_count + 1, search_opening_brace);
|
return self.find_closing_brace(index + 1, brace_count + 1, search_opening_brace);
|
||||||
}
|
}
|
||||||
if found_another_closing_brace {
|
if found_another_closing_brace && brace_count > 0 {
|
||||||
return self.find_closing_brace(index + 1, brace_count - 1, search_opening_brace);
|
return self.find_closing_brace(index + 1, brace_count - 1, search_opening_brace);
|
||||||
}
|
}
|
||||||
// non-brace token, increment and continue
|
// non-brace token, increment and continue
|
||||||
@ -610,6 +619,12 @@ impl Parser {
|
|||||||
fn make_member_expression(&self, index: usize) -> Result<MemberExpressionReturn, KclError> {
|
fn make_member_expression(&self, index: usize) -> Result<MemberExpressionReturn, KclError> {
|
||||||
let current_token = self.get_token(index)?;
|
let current_token = self.get_token(index)?;
|
||||||
let mut keys_info = self.collect_object_keys(index, None)?;
|
let mut keys_info = self.collect_object_keys(index, None)?;
|
||||||
|
if keys_info.is_empty() {
|
||||||
|
return Err(KclError::Syntax(KclErrorDetails {
|
||||||
|
source_ranges: vec![current_token.into()],
|
||||||
|
message: "expected to be started on a identifier or literal".to_string(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
let last_key = keys_info[keys_info.len() - 1].clone();
|
let last_key = keys_info[keys_info.len() - 1].clone();
|
||||||
let first_key = keys_info.remove(0);
|
let first_key = keys_info.remove(0);
|
||||||
let root = self.make_identifier(index)?;
|
let root = self.make_identifier(index)?;
|
||||||
@ -679,7 +694,11 @@ impl Parser {
|
|||||||
return Ok(index);
|
return Ok(index);
|
||||||
}
|
}
|
||||||
let next_right = self.next_meaningful_token(maybe_operator.index, None)?;
|
let next_right = self.next_meaningful_token(maybe_operator.index, None)?;
|
||||||
self.find_end_of_binary_expression(next_right.index)
|
if next_right.index != index {
|
||||||
|
self.find_end_of_binary_expression(next_right.index)
|
||||||
|
} else {
|
||||||
|
Ok(index)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Ok(index)
|
Ok(index)
|
||||||
}
|
}
|
||||||
@ -847,6 +866,8 @@ impl Parser {
|
|||||||
fn make_array_expression(&self, index: usize) -> Result<ArrayReturn, KclError> {
|
fn make_array_expression(&self, index: usize) -> Result<ArrayReturn, KclError> {
|
||||||
let opening_brace_token = self.get_token(index)?;
|
let opening_brace_token = self.get_token(index)?;
|
||||||
let first_element_token = self.next_meaningful_token(index, None)?;
|
let first_element_token = self.next_meaningful_token(index, None)?;
|
||||||
|
// Make sure there is a closing brace.
|
||||||
|
let _closing_brace = self.find_closing_brace(index, 0, "")?;
|
||||||
let array_elements = self.make_array_elements(first_element_token.index, Vec::new())?;
|
let array_elements = self.make_array_elements(first_element_token.index, Vec::new())?;
|
||||||
Ok(ArrayReturn {
|
Ok(ArrayReturn {
|
||||||
expression: ArrayExpression {
|
expression: ArrayExpression {
|
||||||
@ -1018,7 +1039,7 @@ impl Parser {
|
|||||||
} else {
|
} else {
|
||||||
return Err(KclError::Unimplemented(KclErrorDetails {
|
return Err(KclError::Unimplemented(KclErrorDetails {
|
||||||
source_ranges: vec![argument_token_token.clone().into()],
|
source_ranges: vec![argument_token_token.clone().into()],
|
||||||
message: format!("Unexpected token {} ", argument_token_token.value),
|
message: format!("Unexpected token {}", argument_token_token.value),
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -1043,18 +1064,18 @@ impl Parser {
|
|||||||
|
|
||||||
Err(KclError::Unimplemented(KclErrorDetails {
|
Err(KclError::Unimplemented(KclErrorDetails {
|
||||||
source_ranges: vec![argument_token_token.clone().into()],
|
source_ranges: vec![argument_token_token.clone().into()],
|
||||||
message: format!("Unexpected token {} ", argument_token_token.value),
|
message: format!("Unexpected token {}", argument_token_token.value),
|
||||||
}))
|
}))
|
||||||
} else {
|
} else {
|
||||||
Err(KclError::Unimplemented(KclErrorDetails {
|
Err(KclError::Unimplemented(KclErrorDetails {
|
||||||
source_ranges: vec![brace_or_comma_token.into()],
|
source_ranges: vec![brace_or_comma_token.into()],
|
||||||
message: format!("Unexpected token {} ", brace_or_comma_token.value),
|
message: format!("Unexpected token {}", brace_or_comma_token.value),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Err(KclError::Unimplemented(KclErrorDetails {
|
Err(KclError::Unimplemented(KclErrorDetails {
|
||||||
source_ranges: vec![brace_or_comma_token.into()],
|
source_ranges: vec![brace_or_comma_token.into()],
|
||||||
message: format!("Unexpected token {} ", brace_or_comma_token.value),
|
message: format!("Unexpected token {}", brace_or_comma_token.value),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1063,6 +1084,8 @@ impl Parser {
|
|||||||
let current_token = self.get_token(index)?;
|
let current_token = self.get_token(index)?;
|
||||||
let brace_token = self.next_meaningful_token(index, None)?;
|
let brace_token = self.next_meaningful_token(index, None)?;
|
||||||
let callee = self.make_identifier(index)?;
|
let callee = self.make_identifier(index)?;
|
||||||
|
// Make sure there is a closing brace.
|
||||||
|
let _closing_brace_token = self.find_closing_brace(brace_token.index, 0, "")?;
|
||||||
let args = self.make_arguments(brace_token.index, vec![])?;
|
let args = self.make_arguments(brace_token.index, vec![])?;
|
||||||
let closing_brace_token = self.get_token(args.last_index)?;
|
let closing_brace_token = self.get_token(args.last_index)?;
|
||||||
let function = if let Some(stdlib_fn) = self.stdlib.get(&callee.name) {
|
let function = if let Some(stdlib_fn) = self.stdlib.get(&callee.name) {
|
||||||
@ -1105,42 +1128,42 @@ impl Parser {
|
|||||||
) -> Result<VariableDeclaratorsReturn, KclError> {
|
) -> Result<VariableDeclaratorsReturn, KclError> {
|
||||||
let current_token = self.get_token(index)?;
|
let current_token = self.get_token(index)?;
|
||||||
let assignment = self.next_meaningful_token(index, None)?;
|
let assignment = self.next_meaningful_token(index, None)?;
|
||||||
if let Some(assignment_token) = assignment.token {
|
let Some(assignment_token) = assignment.token else {
|
||||||
let contents_start_token = self.next_meaningful_token(assignment.index, None)?;
|
return Err(KclError::Unimplemented(KclErrorDetails {
|
||||||
let pipe_start_index = if assignment_token.token_type == TokenType::Operator {
|
|
||||||
contents_start_token.index
|
|
||||||
} else {
|
|
||||||
assignment.index
|
|
||||||
};
|
|
||||||
let next_pipe_operator = self.has_pipe_operator(pipe_start_index, None)?;
|
|
||||||
let init: Value;
|
|
||||||
let last_index = if next_pipe_operator.token.is_some() {
|
|
||||||
let pipe_expression_result = self.make_pipe_expression(assignment.index)?;
|
|
||||||
init = Value::PipeExpression(Box::new(pipe_expression_result.expression));
|
|
||||||
pipe_expression_result.last_index
|
|
||||||
} else {
|
|
||||||
let value_result = self.make_value(contents_start_token.index)?;
|
|
||||||
init = value_result.value;
|
|
||||||
value_result.last_index
|
|
||||||
};
|
|
||||||
let current_declarator = VariableDeclarator {
|
|
||||||
start: current_token.start,
|
|
||||||
end: self.get_token(last_index)?.end,
|
|
||||||
id: self.make_identifier(index)?,
|
|
||||||
init,
|
|
||||||
};
|
|
||||||
let mut declarations = previous_declarators;
|
|
||||||
declarations.push(current_declarator);
|
|
||||||
Ok(VariableDeclaratorsReturn {
|
|
||||||
declarations,
|
|
||||||
last_index,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
Err(KclError::Unimplemented(KclErrorDetails {
|
|
||||||
source_ranges: vec![current_token.clone().into()],
|
source_ranges: vec![current_token.clone().into()],
|
||||||
message: format!("Unexpected token {} ", current_token.value),
|
message: format!("Unexpected token {}", current_token.value),
|
||||||
}))
|
}));
|
||||||
}
|
};
|
||||||
|
|
||||||
|
let contents_start_token = self.next_meaningful_token(assignment.index, None)?;
|
||||||
|
let pipe_start_index = if assignment_token.token_type == TokenType::Operator {
|
||||||
|
contents_start_token.index
|
||||||
|
} else {
|
||||||
|
assignment.index
|
||||||
|
};
|
||||||
|
let next_pipe_operator = self.has_pipe_operator(pipe_start_index, None)?;
|
||||||
|
let init: Value;
|
||||||
|
let last_index = if next_pipe_operator.token.is_some() {
|
||||||
|
let pipe_expression_result = self.make_pipe_expression(assignment.index)?;
|
||||||
|
init = Value::PipeExpression(Box::new(pipe_expression_result.expression));
|
||||||
|
pipe_expression_result.last_index
|
||||||
|
} else {
|
||||||
|
let value_result = self.make_value(contents_start_token.index)?;
|
||||||
|
init = value_result.value;
|
||||||
|
value_result.last_index
|
||||||
|
};
|
||||||
|
let current_declarator = VariableDeclarator {
|
||||||
|
start: current_token.start,
|
||||||
|
end: self.get_token(last_index)?.end,
|
||||||
|
id: self.make_identifier(index)?,
|
||||||
|
init,
|
||||||
|
};
|
||||||
|
let mut declarations = previous_declarators;
|
||||||
|
declarations.push(current_declarator);
|
||||||
|
Ok(VariableDeclaratorsReturn {
|
||||||
|
declarations,
|
||||||
|
last_index,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_variable_declaration(&self, index: usize) -> Result<VariableDeclarationResult, KclError> {
|
fn make_variable_declaration(&self, index: usize) -> Result<VariableDeclarationResult, KclError> {
|
||||||
@ -1184,7 +1207,7 @@ impl Parser {
|
|||||||
} else {
|
} else {
|
||||||
Err(KclError::Unimplemented(KclErrorDetails {
|
Err(KclError::Unimplemented(KclErrorDetails {
|
||||||
source_ranges: vec![brace_or_comma_token.into()],
|
source_ranges: vec![brace_or_comma_token.into()],
|
||||||
message: format!("Unexpected token {} ", brace_or_comma_token.value),
|
message: format!("Unexpected token {}", brace_or_comma_token.value),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1192,6 +1215,12 @@ impl Parser {
|
|||||||
fn make_unary_expression(&self, index: usize) -> Result<UnaryExpressionResult, KclError> {
|
fn make_unary_expression(&self, index: usize) -> Result<UnaryExpressionResult, KclError> {
|
||||||
let current_token = self.get_token(index)?;
|
let current_token = self.get_token(index)?;
|
||||||
let next_token = self.next_meaningful_token(index, None)?;
|
let next_token = self.next_meaningful_token(index, None)?;
|
||||||
|
if next_token.token.is_none() {
|
||||||
|
return Err(KclError::Syntax(KclErrorDetails {
|
||||||
|
source_ranges: vec![current_token.into()],
|
||||||
|
message: "expected another token".to_string(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
let argument = self.make_value(next_token.index)?;
|
let argument = self.make_value(next_token.index)?;
|
||||||
let argument_token = self.get_token(argument.last_index)?;
|
let argument_token = self.get_token(argument.last_index)?;
|
||||||
Ok(UnaryExpressionResult {
|
Ok(UnaryExpressionResult {
|
||||||
@ -1232,7 +1261,6 @@ impl Parser {
|
|||||||
return Ok(ExpressionStatementResult {
|
return Ok(ExpressionStatementResult {
|
||||||
expression: ExpressionStatement {
|
expression: ExpressionStatement {
|
||||||
start: current_token.start,
|
start: current_token.start,
|
||||||
// end: call_expression.last_index,
|
|
||||||
end,
|
end,
|
||||||
expression: Value::CallExpression(Box::new(call_expression.expression)),
|
expression: Value::CallExpression(Box::new(call_expression.expression)),
|
||||||
},
|
},
|
||||||
@ -1314,6 +1342,8 @@ impl Parser {
|
|||||||
|
|
||||||
fn make_object_expression(&self, index: usize) -> Result<ObjectExpressionResult, KclError> {
|
fn make_object_expression(&self, index: usize) -> Result<ObjectExpressionResult, KclError> {
|
||||||
let opening_brace_token = self.get_token(index)?;
|
let opening_brace_token = self.get_token(index)?;
|
||||||
|
// Make sure there is a closing brace.
|
||||||
|
let _closing_brace = self.find_closing_brace(index, 0, "")?;
|
||||||
let first_property_token = self.next_meaningful_token(index, None)?;
|
let first_property_token = self.next_meaningful_token(index, None)?;
|
||||||
let object_properties = self.make_object_properties(first_property_token.index, vec![])?;
|
let object_properties = self.make_object_properties(first_property_token.index, vec![])?;
|
||||||
Ok(ObjectExpressionResult {
|
Ok(ObjectExpressionResult {
|
||||||
@ -1665,7 +1695,7 @@ const key = 'c'"#,
|
|||||||
Some(NoneCodeNode {
|
Some(NoneCodeNode {
|
||||||
start: 38,
|
start: 38,
|
||||||
end: 60,
|
end: 60,
|
||||||
value: NoneCodeValue::Block {
|
value: NoneCodeValue::BlockComment {
|
||||||
value: "this is a comment".to_string(),
|
value: "this is a comment".to_string(),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@ -1687,7 +1717,7 @@ const key = 'c'"#,
|
|||||||
Some(NoneCodeNode {
|
Some(NoneCodeNode {
|
||||||
start: 106,
|
start: 106,
|
||||||
end: 166,
|
end: 166,
|
||||||
value: NoneCodeValue::Block {
|
value: NoneCodeValue::BlockComment {
|
||||||
value: "this is\n a comment\n spanning a few lines".to_string(),
|
value: "this is\n a comment\n spanning a few lines".to_string(),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@ -2716,4 +2746,139 @@ show(mySk1)"#;
|
|||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.err().unwrap().to_string().contains("file is empty"));
|
assert!(result.err().unwrap().to_string().contains("file is empty"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_half_pipe_small() {
|
||||||
|
let tokens = crate::tokeniser::lexer(
|
||||||
|
"const secondExtrude = startSketchAt([0,0])
|
||||||
|
|",
|
||||||
|
);
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result.err().unwrap().to_string().contains("Unexpected token"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_half_pipe() {
|
||||||
|
let tokens = crate::tokeniser::lexer(
|
||||||
|
"const height = 10
|
||||||
|
|
||||||
|
const firstExtrude = startSketchAt([0,0])
|
||||||
|
|> line([0, 8], %)
|
||||||
|
|> line([20, 0], %)
|
||||||
|
|> line([0, -8], %)
|
||||||
|
|> close(%)
|
||||||
|
|> extrude(2, %)
|
||||||
|
|
||||||
|
show(firstExtrude)
|
||||||
|
|
||||||
|
const secondExtrude = startSketchAt([0,0])
|
||||||
|
|",
|
||||||
|
);
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result.err().unwrap().to_string().contains("Unexpected token"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_greater_bang() {
|
||||||
|
let tokens = crate::tokeniser::lexer(">!");
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_z_percent_parens() {
|
||||||
|
let tokens = crate::tokeniser::lexer("z%)");
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result.err().unwrap().to_string().contains("Unexpected token"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_parens_unicode() {
|
||||||
|
let tokens = crate::tokeniser::lexer("(ޜ");
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_nested_open_brackets() {
|
||||||
|
let tokens = crate::tokeniser::lexer(
|
||||||
|
r#"
|
||||||
|
z(-[["#,
|
||||||
|
);
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result.err().unwrap().to_string().contains("unexpected end"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_weird_new_line_function() {
|
||||||
|
let tokens = crate::tokeniser::lexer(
|
||||||
|
r#"z
|
||||||
|
(--#"#,
|
||||||
|
);
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result.err().unwrap().to_string().contains("unexpected end"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_weird_lots_of_fancy_brackets() {
|
||||||
|
let tokens = crate::tokeniser::lexer(r#"zz({{{{{{{{)iegAng{{{{{{{##"#);
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result.err().unwrap().to_string().contains("unexpected end"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_weird_close_before_open() {
|
||||||
|
let tokens = crate::tokeniser::lexer(
|
||||||
|
r#"fn)n
|
||||||
|
e
|
||||||
|
["#,
|
||||||
|
);
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result
|
||||||
|
.err()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
.contains("expected to be started on a identifier or literal"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_weird_close_before_nada() {
|
||||||
|
let tokens = crate::tokeniser::lexer(r#"fn)n-"#);
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result.err().unwrap().to_string().contains("expected another token"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_weird_lots_of_slashes() {
|
||||||
|
let tokens = crate::tokeniser::lexer(
|
||||||
|
r#"J///////////o//+///////////P++++*++++++P///////˟
|
||||||
|
++4"#,
|
||||||
|
);
|
||||||
|
let parser = Parser::new(tokens);
|
||||||
|
let result = parser.ast();
|
||||||
|
assert!(result.is_err());
|
||||||
|
assert!(result
|
||||||
|
.err()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
.contains("unexpected end of expression"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -233,6 +233,7 @@ impl LanguageServer for Backend {
|
|||||||
document_symbol_provider: Some(OneOf::Left(true)),
|
document_symbol_provider: Some(OneOf::Left(true)),
|
||||||
hover_provider: Some(HoverProviderCapability::Simple(true)),
|
hover_provider: Some(HoverProviderCapability::Simple(true)),
|
||||||
inlay_hint_provider: Some(OneOf::Left(true)),
|
inlay_hint_provider: Some(OneOf::Left(true)),
|
||||||
|
rename_provider: Some(OneOf::Left(true)),
|
||||||
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
|
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
|
||||||
SemanticTokensRegistrationOptions {
|
SemanticTokensRegistrationOptions {
|
||||||
text_document_registration_options: {
|
text_document_registration_options: {
|
||||||
@ -552,19 +553,14 @@ impl LanguageServer for Backend {
|
|||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
// Now recast it.
|
// Now recast it.
|
||||||
// Make spaces for the tab size.
|
let recast = ast.recast(
|
||||||
/*let mut tab_size = String::new();
|
&crate::abstract_syntax_tree_types::FormatOptions {
|
||||||
for _ in 0..params.options.tab_size {
|
tab_size: params.options.tab_size as usize,
|
||||||
tab_size.push(' ');
|
insert_final_newline: params.options.insert_final_newline.unwrap_or(false),
|
||||||
}*/
|
use_tabs: !params.options.insert_spaces,
|
||||||
// TODO: use the tab size.
|
},
|
||||||
let mut recast = ast.recast("", false).trim().to_string();
|
0,
|
||||||
if let Some(insert_final_newline) = params.options.insert_final_newline {
|
);
|
||||||
if insert_final_newline {
|
|
||||||
recast.push('\n');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let source_range = SourceRange([0, current_code.len() - 1]);
|
let source_range = SourceRange([0, current_code.len() - 1]);
|
||||||
let range = source_range.to_lsp_range(¤t_code);
|
let range = source_range.to_lsp_range(¤t_code);
|
||||||
Ok(Some(vec![TextEdit {
|
Ok(Some(vec![TextEdit {
|
||||||
@ -572,6 +568,43 @@ impl LanguageServer for Backend {
|
|||||||
range,
|
range,
|
||||||
}]))
|
}]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn rename(&self, params: RenameParams) -> RpcResult<Option<WorkspaceEdit>> {
|
||||||
|
let filename = params.text_document_position.text_document.uri.to_string();
|
||||||
|
|
||||||
|
let Some(current_code) = self.current_code_map.get(&filename) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Parse the ast.
|
||||||
|
// I don't know if we need to do this again since it should be updated in the context.
|
||||||
|
// But I figure better safe than sorry since this will write back out to the file.
|
||||||
|
let tokens = crate::tokeniser::lexer(¤t_code);
|
||||||
|
let parser = crate::parser::Parser::new(tokens);
|
||||||
|
let Ok(mut ast) = parser.ast() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Let's convert the position to a character index.
|
||||||
|
let pos = position_to_char_index(params.text_document_position.position, ¤t_code);
|
||||||
|
// Now let's perform the rename on the ast.
|
||||||
|
ast.rename_symbol(¶ms.new_name, pos);
|
||||||
|
// Now recast it.
|
||||||
|
let recast = ast.recast(&Default::default(), 0);
|
||||||
|
let source_range = SourceRange([0, current_code.len() - 1]);
|
||||||
|
let range = source_range.to_lsp_range(¤t_code);
|
||||||
|
Ok(Some(WorkspaceEdit {
|
||||||
|
changes: Some(HashMap::from([(
|
||||||
|
params.text_document_position.text_document.uri,
|
||||||
|
vec![TextEdit {
|
||||||
|
new_text: recast,
|
||||||
|
range,
|
||||||
|
}],
|
||||||
|
)])),
|
||||||
|
document_changes: None,
|
||||||
|
change_annotations: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get completions from our stdlib.
|
/// Get completions from our stdlib.
|
||||||
|
@ -206,8 +206,8 @@ fn is_block_comment(character: &str) -> bool {
|
|||||||
BLOCKCOMMENT.is_match(character)
|
BLOCKCOMMENT.is_match(character)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn match_first(str: &str, regex: &Regex) -> Option<String> {
|
fn match_first(s: &str, regex: &Regex) -> Option<String> {
|
||||||
regex.find(str).map(|the_match| the_match.as_str().to_string())
|
regex.find(s).map(|the_match| the_match.as_str().to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_token(token_type: TokenType, value: &str, start: usize) -> Token {
|
fn make_token(token_type: TokenType, value: &str, start: usize) -> Token {
|
||||||
@ -219,8 +219,8 @@ fn make_token(token_type: TokenType, value: &str, start: usize) -> Token {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn return_token_at_index(str: &str, start_index: usize) -> Option<Token> {
|
fn return_token_at_index(s: &str, start_index: usize) -> Option<Token> {
|
||||||
let str_from_index = &str[start_index..];
|
let str_from_index = &s.chars().skip(start_index).collect::<String>();
|
||||||
if is_string(str_from_index) {
|
if is_string(str_from_index) {
|
||||||
return Some(make_token(
|
return Some(make_token(
|
||||||
TokenType::String,
|
TokenType::String,
|
||||||
@ -348,21 +348,22 @@ fn return_token_at_index(str: &str, start_index: usize) -> Option<Token> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn lexer(str: &str) -> Vec<Token> {
|
fn recursively_tokenise(s: &str, current_index: usize, previous_tokens: Vec<Token>) -> Vec<Token> {
|
||||||
fn recursively_tokenise(str: &str, current_index: usize, previous_tokens: Vec<Token>) -> Vec<Token> {
|
if current_index >= s.len() {
|
||||||
if current_index >= str.len() {
|
return previous_tokens;
|
||||||
return previous_tokens;
|
|
||||||
}
|
|
||||||
let token = return_token_at_index(str, current_index);
|
|
||||||
let Some(token) = token else {
|
|
||||||
return recursively_tokenise(str, current_index + 1, previous_tokens);
|
|
||||||
};
|
|
||||||
let mut new_tokens = previous_tokens;
|
|
||||||
let token_length = token.value.len();
|
|
||||||
new_tokens.push(token);
|
|
||||||
recursively_tokenise(str, current_index + token_length, new_tokens)
|
|
||||||
}
|
}
|
||||||
recursively_tokenise(str, 0, Vec::new())
|
let token = return_token_at_index(s, current_index);
|
||||||
|
let Some(token) = token else {
|
||||||
|
return recursively_tokenise(s, current_index + 1, previous_tokens);
|
||||||
|
};
|
||||||
|
let mut new_tokens = previous_tokens;
|
||||||
|
let token_length = token.value.len();
|
||||||
|
new_tokens.push(token);
|
||||||
|
recursively_tokenise(s, current_index + token_length, new_tokens)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn lexer(s: &str) -> Vec<Token> {
|
||||||
|
recursively_tokenise(s, 0, Vec::new())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
@ -76,7 +76,8 @@ pub fn recast_wasm(json_str: &str) -> Result<JsValue, JsError> {
|
|||||||
let program: kcl_lib::abstract_syntax_tree_types::Program =
|
let program: kcl_lib::abstract_syntax_tree_types::Program =
|
||||||
serde_json::from_str(json_str).map_err(JsError::from)?;
|
serde_json::from_str(json_str).map_err(JsError::from)?;
|
||||||
|
|
||||||
let result = program.recast("", false);
|
// Use the default options until we integrate into the UI the ability to change them.
|
||||||
|
let result = program.recast(&Default::default(), 0);
|
||||||
Ok(JsValue::from_serde(&result)?)
|
Ok(JsValue::from_serde(&result)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1530,10 +1530,10 @@
|
|||||||
resolved "https://registry.yarnpkg.com/@juggle/resize-observer/-/resize-observer-3.4.0.tgz#08d6c5e20cf7e4cc02fd181c4b0c225cd31dbb60"
|
resolved "https://registry.yarnpkg.com/@juggle/resize-observer/-/resize-observer-3.4.0.tgz#08d6c5e20cf7e4cc02fd181c4b0c225cd31dbb60"
|
||||||
integrity sha512-dfLbk+PwWvFzSxwk3n5ySL0hfBog779o8h68wK/7/APo/7cgyWp5jcXockbxdk5kFRkbeXWm4Fbi9FrdN381sA==
|
integrity sha512-dfLbk+PwWvFzSxwk3n5ySL0hfBog779o8h68wK/7/APo/7cgyWp5jcXockbxdk5kFRkbeXWm4Fbi9FrdN381sA==
|
||||||
|
|
||||||
"@kittycad/lib@^0.0.35":
|
"@kittycad/lib@^0.0.37":
|
||||||
version "0.0.35"
|
version "0.0.37"
|
||||||
resolved "https://registry.yarnpkg.com/@kittycad/lib/-/lib-0.0.35.tgz#bde8868048f9fd53f8309e7308aeba622898b935"
|
resolved "https://registry.yarnpkg.com/@kittycad/lib/-/lib-0.0.37.tgz#ec4f6c4fb5d06402a19339f3374036b6582d2265"
|
||||||
integrity sha512-qM8AyP2QUlDfPWNxb1Fs/Pq9AebGVDN1OHjByxbGomKCy0jFdN2TsyDdhQH/CAZGfBCgPEfr5bq6rkUBGSXcNw==
|
integrity sha512-P8p9FeLV79/0Lfd0RioBta1drzhmpROnU4YV38+zsAA4LhibQCTjeekRkxVvHztGumPxz9pPsAeeLJyuz2RWKQ==
|
||||||
dependencies:
|
dependencies:
|
||||||
node-fetch "3.3.2"
|
node-fetch "3.3.2"
|
||||||
openapi-types "^12.0.0"
|
openapi-types "^12.0.0"
|
||||||
|
Reference in New Issue
Block a user