Compare commits

..

1 Commits

Author SHA1 Message Date
cc145a267c WIP: Do we need to derive JsonSchema? 2024-09-24 12:30:50 -05:00
50 changed files with 460 additions and 977 deletions

File diff suppressed because one or more lines are too long

4
interface.d.ts vendored
View File

@ -63,10 +63,6 @@ export interface IElectronAPI {
kittycad: (access: string, args: any) => any
listMachines: () => Promise<MachinesListing>
getMachineApiIp: () => Promise<string | null>
onUpdateDownloaded: (
callback: (value: string) => void
) => Electron.IpcRenderer
appRestart: () => void
}
declare global {

View File

@ -22,7 +22,6 @@ import {
} from 'lib/toolbar'
import { isDesktop } from 'lib/isDesktop'
import { openExternalBrowserIfDesktop } from 'lib/openWindow'
import { convertSelectionsToOld } from 'lib/selections'
export function Toolbar({
className = '',
@ -39,17 +38,12 @@ export function Toolbar({
'!border-transparent hover:!border-chalkboard-20 dark:enabled:hover:!border-primary pressed:!border-primary ui-open:!border-primary'
const sketchPathId = useMemo(() => {
if (
!isSingleCursorInPipe(
convertSelectionsToOld(context.selectionRanges),
kclManager.ast
)
) {
if (!isSingleCursorInPipe(context.selectionRanges, kclManager.ast)) {
return false
}
return isCursorInSketchCommandRange(
engineCommandManager.artifactGraph,
convertSelectionsToOld(context.selectionRanges)
context.selectionRanges
)
}, [engineCommandManager.artifactGraph, context.selectionRanges])

View File

@ -77,7 +77,7 @@ import {
createPipeSubstitution,
findUniqueName,
} from 'lang/modifyAst'
import { Selections__old, getEventForSegmentSelection } from 'lib/selections'
import { Selections, getEventForSegmentSelection } from 'lib/selections'
import { createGridHelper, orthoScale, perspScale } from './helpers'
import { Models } from '@kittycad/lib'
import { uuidv4 } from 'lib/utils'
@ -374,7 +374,7 @@ export class SceneEntities {
forward: [number, number, number]
up: [number, number, number]
position?: [number, number, number]
selectionRanges?: Selections__old
selectionRanges?: Selections
}): Promise<{
truncatedAst: Program
programMemoryOverride: ProgramMemory
@ -1171,7 +1171,6 @@ export class SceneEntities {
},
onMove: () => {},
onClick: (args) => {
console.log('onClick', args)
if (args?.mouseEvent.which !== 1) return
if (!args || !args.selected) {
sceneInfra.modelingSend({
@ -1184,7 +1183,6 @@ export class SceneEntities {
}
const { selected } = args
const event = getEventForSegmentSelection(selected)
console.log('event', event)
if (!event) return
sceneInfra.modelingSend(event)
},

View File

@ -1,42 +0,0 @@
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { ActionButton } from './ActionButton'
describe('ActionButton tests', () => {
it('ActionButton with no iconStart or iconEnd should have even left and right padding', () => {
render(<ActionButton Element="button">No icons</ActionButton>)
expect(screen.getByRole('button')).toHaveClass('px-2')
})
it('ActionButton with iconStart should have no padding on the left', () => {
render(
<ActionButton Element="button" iconStart={{ icon: 'trash' }}>
Start icon only
</ActionButton>
)
expect(screen.getByRole('button')).toHaveClass('pr-2')
})
it('ActionButton with iconEnd should have no padding on the right', () => {
render(
<ActionButton Element="button" iconEnd={{ icon: 'trash' }}>
End icon only
</ActionButton>
)
expect(screen.getByRole('button')).toHaveClass('pl-2')
})
it('ActionButton with both icons should have no padding on either side', () => {
render(
<ActionButton
Element="button"
iconStart={{ icon: 'trash' }}
iconEnd={{ icon: 'trash' }}
>
Both icons
</ActionButton>
)
expect(screen.getByRole('button')).not.toHaveClass('px-2')
expect(screen.getByRole('button')).toHaveClass('px-0')
})
})

View File

@ -44,11 +44,11 @@ export const ActionButton = forwardRef((props: ActionButtonProps, ref) => {
const classNames = `action-button p-0 m-0 group mono text-xs leading-none flex items-center gap-2 rounded-sm border-solid border border-chalkboard-30 hover:border-chalkboard-40 enabled:dark:border-chalkboard-70 dark:hover:border-chalkboard-60 dark:bg-chalkboard-90/50 text-chalkboard-100 dark:text-chalkboard-10 ${
props.iconStart
? props.iconEnd
? 'px-0' // No padding if both icons are present
: 'pr-2' // Padding on the right if only the start icon is present
? 'px-0'
: 'pr-2'
: props.iconEnd
? 'pl-2' // Padding on the left if only the end icon is present
: 'px-2' // Padding on both sides if no icons are present
? 'px-2'
: 'pl-2'
} ${props.className ? props.className : ''}`
switch (props.Element) {

View File

@ -12,7 +12,6 @@ import { useKclContext } from 'lang/KclProvider'
import { useModelingContext } from 'hooks/useModelingContext'
import { executeAst } from 'lang/langHelpers'
import { trap } from 'lib/trap'
import { convertSelectionsToOld } from 'lib/selections'
export const AvailableVars = ({
onVarClick,
@ -97,8 +96,7 @@ export function useCalc({
} {
const { programMemory } = useKclContext()
const { context } = useModelingContext()
const selectionRange = convertSelectionsToOld(context.selectionRanges)
.codeBasedSelections[0].range
const selectionRange = context.selectionRanges.codeBasedSelections[0].range
const inputRef = useRef<HTMLInputElement>(null)
const [availableVarInfo, setAvailableVarInfo] = useState<
ReturnType<typeof findAllPreviousVariables>

View File

@ -2,7 +2,7 @@ import { useCommandsContext } from 'hooks/useCommandsContext'
import { CustomIcon } from '../CustomIcon'
import React, { useState } from 'react'
import { ActionButton } from '../ActionButton'
import { Selections__old, getSelectionTypeDisplayText } from 'lib/selections'
import { Selections, getSelectionTypeDisplayText } from 'lib/selections'
import { useHotkeys } from 'react-hotkeys-hook'
import { KclCommandValue, KclExpressionWithVariable } from 'lib/commandTypes'
import Tooltip from 'components/Tooltip'
@ -125,9 +125,7 @@ function CommandBarHeader({ children }: React.PropsWithChildren<{}>) {
<span data-testid="header-arg-value">
{argValue ? (
arg.inputType === 'selection' ? (
getSelectionTypeDisplayText(
argValue as Selections__old
)
getSelectionTypeDisplayText(argValue as Selections)
) : arg.inputType === 'kcl' ? (
roundOff(
Number(

View File

@ -3,10 +3,8 @@ import { useCommandsContext } from 'hooks/useCommandsContext'
import { useKclContext } from 'lang/KclProvider'
import { CommandArgument } from 'lib/commandTypes'
import {
Selection__old,
Selection,
canSubmitSelectionArg,
convertSelectionToOld,
convertSelectionsToOld,
getSelectionType,
getSelectionTypeDisplayText,
} from 'lib/selections'
@ -14,15 +12,13 @@ import { modelingMachine } from 'machines/modelingMachine'
import { useEffect, useMemo, useRef, useState } from 'react'
import { StateFrom } from 'xstate'
const semanticEntityNames: { [key: string]: Array<Selection__old['type']> } = {
const semanticEntityNames: { [key: string]: Array<Selection['type']> } = {
face: ['extrude-wall', 'start-cap', 'end-cap'],
edge: ['edge', 'line', 'arc'],
point: ['point', 'line-end', 'line-mid'],
}
function getSemanticSelectionType(
selectionType: Array<Selection__old['type']>
) {
function getSemanticSelectionType(selectionType: Array<Selection['type']>) {
const semanticSelectionType = new Set()
selectionType.forEach((type) => {
Object.entries(semanticEntityNames).forEach(([entity, entityTypes]) => {
@ -53,14 +49,10 @@ function CommandBarSelectionInput({
const [hasSubmitted, setHasSubmitted] = useState(false)
const selection = useSelector(arg.machineActor, selectionSelector)
const selectionsByType = useMemo(() => {
const selectionRangeEnd = !selection
? null
: convertSelectionsToOld(selection)?.codeBasedSelections[0]?.range[1]
return !selectionRangeEnd || selectionRangeEnd === code.length || !selection
const selectionRangeEnd = selection?.codeBasedSelections[0]?.range[1]
return !selectionRangeEnd || selectionRangeEnd === code.length
? 'none'
: !selection
? 'none'
: getSelectionType(convertSelectionsToOld(selection))
: getSelectionType(selection)
}, [selection, code])
const canSubmitSelection = useMemo<boolean>(
() => canSubmitSelectionArg(selectionsByType, arg),
@ -95,8 +87,6 @@ function CommandBarSelectionInput({
onSubmit(selection)
}
const selectionOld = selection && convertSelectionsToOld(selection)
return (
<form id="arg-form" onSubmit={handleSubmit}>
<label
@ -106,7 +96,7 @@ function CommandBarSelectionInput({
}
>
{canSubmitSelection
? getSelectionTypeDisplayText(selectionOld) + ' selected'
? getSelectionTypeDisplayText(selection) + ' selected'
: `Please select ${
arg.multiple ? 'one or more ' : 'one '
}${getSemanticSelectionType(arg.selectionTypes).join(' or ')}`}

View File

@ -21,7 +21,6 @@ export const EngineCommands = () => {
const [engineCommands, clearEngineCommands] = useEngineCommands()
const [containsFilter, setContainsFilter] = useState('')
const [customCmd, setCustomCmd] = useState('')
console.log(JSON.stringify(engineCommands, null, 2))
return (
<div>
<input
@ -65,10 +64,7 @@ export const EngineCommands = () => {
)
})}
</div>
<button
data-testid="clear-commands"
onClick={() => clearEngineCommands()}
>
<button data-testid="clear-commands" onClick={clearEngineCommands}>
Clear
</button>
<br />

View File

@ -37,17 +37,13 @@ import {
} from './Toolbar/SetAngleBetween'
import { applyConstraintAngleLength } from './Toolbar/setAngleLength'
import {
Selections__old,
Selections,
canSweepSelection,
handleSelectionBatch,
isSelectionLastLine,
isRangeBetweenCharacters,
isSketchPipe,
updateSelections,
convertSelectionsToOld,
convertSelectionToOld,
Selections,
updateSelections2,
} from 'lib/selections'
import { applyConstraintIntersect } from './Toolbar/Intersect'
import { applyConstraintAbsDistance } from './Toolbar/SetAbsDistance'
@ -253,7 +249,6 @@ export const ModelingMachineProvider = ({
'Set selection': assign(
({ context: { selectionRanges, sketchDetails }, event }) => {
// this was needed for ts after adding 'Set selection' action to on done modal events
// const oldSelections = convertSelectionsToOld(selectionRanges)
const setSelections =
('data' in event &&
event.data &&
@ -280,12 +275,8 @@ export const ModelingMachineProvider = ({
})
})
}
// let selections: Selections__old = {
// codeBasedSelections: [],
// otherSelections: [],
// }
let selections: Selections = {
graphSelections: [],
codeBasedSelections: [],
otherSelections: [],
}
if (setSelections.selectionType === 'singleCodeCursor') {
@ -295,28 +286,21 @@ export const ModelingMachineProvider = ({
!editorManager.isShiftDown
) {
selections = {
graphSelections: [],
codeBasedSelections: [],
otherSelections: [],
}
} else if (
setSelections.selection &&
!editorManager.isShiftDown
) {
// const oldSelection = convertSelectionToOld(setSelections.selection)
// if (oldSelection) {
// }
selections = {
graphSelections: [setSelections.selection],
codeBasedSelections: [setSelections.selection],
otherSelections: [],
}
} else if (setSelections.selection && editorManager.isShiftDown) {
// const oldSelection = convertSelectionToOld(setSelections.selection)
// if (oldSelection) {
// }
selections = {
graphSelections: [
...selectionRanges.graphSelections,
codeBasedSelections: [
...selectionRanges.codeBasedSelections,
setSelections.selection,
],
otherSelections: selectionRanges.otherSelections,
@ -328,7 +312,7 @@ export const ModelingMachineProvider = ({
codeMirrorSelection,
updateSceneObjectColors,
} = handleSelectionBatch({
selections: convertSelectionsToOld(selections),
selections,
})
codeMirrorSelection && dispatchSelection(codeMirrorSelection)
engineEvents &&
@ -352,18 +336,18 @@ export const ModelingMachineProvider = ({
if (setSelections.selectionType === 'otherSelection') {
if (editorManager.isShiftDown) {
selections = {
graphSelections: selectionRanges.graphSelections,
codeBasedSelections: selectionRanges.codeBasedSelections,
otherSelections: [setSelections.selection],
}
} else {
selections = {
graphSelections: [],
codeBasedSelections: [],
otherSelections: [setSelections.selection],
}
}
const { engineEvents, updateSceneObjectColors } =
handleSelectionBatch({
selections: convertSelectionsToOld(selections),
selections,
})
engineEvents &&
engineEvents.forEach((event) => {
@ -376,9 +360,7 @@ export const ModelingMachineProvider = ({
}
}
if (setSelections.selectionType === 'completeSelection') {
editorManager.selectRange(
convertSelectionsToOld(setSelections.selection)
)
editorManager.selectRange(setSelections.selection)
if (!sketchDetails)
return {
selectionRanges: setSelections.selection,
@ -512,11 +494,10 @@ export const ModelingMachineProvider = ({
'has valid sweep selection': ({ context: { selectionRanges } }) => {
// A user can begin extruding if they either have 1+ faces selected or nothing selected
// TODO: I believe this guard only allows for extruding a single face at a time
const _selections = convertSelectionsToOld(selectionRanges)
const hasNoSelection =
_selections.codeBasedSelections.length === 0 ||
isRangeBetweenCharacters(_selections) ||
isSelectionLastLine(_selections, codeManager.code)
selectionRanges.codeBasedSelections.length === 0 ||
isRangeBetweenCharacters(selectionRanges) ||
isSelectionLastLine(selectionRanges, codeManager.code)
if (hasNoSelection) {
// they have no selection, we should enable the button
@ -524,34 +505,31 @@ export const ModelingMachineProvider = ({
// BUT only if there's extrudable geometry
return doesSceneHaveSweepableSketch(kclManager.ast)
}
if (!isSketchPipe(_selections)) return false
if (!isSketchPipe(selectionRanges)) return false
return canSweepSelection(_selections)
return canSweepSelection(selectionRanges)
},
'has valid selection for deletion': ({
context: { selectionRanges },
}) => {
const _selections = convertSelectionsToOld(selectionRanges)
if (!commandBarState.matches('Closed')) return false
if (_selections.codeBasedSelections.length <= 0) return false
if (selectionRanges.codeBasedSelections.length <= 0) return false
return true
},
'has valid fillet selection': ({ context: { selectionRanges } }) => {
const _selections = convertSelectionsToOld(selectionRanges)
return hasValidFilletSelection({
selectionRanges: _selections,
'has valid fillet selection': ({ context: { selectionRanges } }) =>
hasValidFilletSelection({
selectionRanges,
ast: kclManager.ast,
code: codeManager.code,
})
},
}),
'Selection is on face': ({ context: { selectionRanges }, event }) => {
if (event.type !== 'Enter sketch') return false
if (event.data?.forceNewSketch) return false
const _selections = convertSelectionsToOld(selectionRanges)
if (!isSingleCursorInPipe(_selections, kclManager.ast)) return false
if (!isSingleCursorInPipe(selectionRanges, kclManager.ast))
return false
return !!isCursorInSketchCommandRange(
engineCommandManager.artifactGraph,
_selections
selectionRanges
)
},
'Has exportable geometry': () => {
@ -641,8 +619,7 @@ export const ModelingMachineProvider = ({
}),
'animate-to-sketch': fromPromise(
async ({ input: { selectionRanges } }) => {
const _selections = convertSelectionsToOld(selectionRanges)
const sourceRange = _selections.codeBasedSelections[0].range
const sourceRange = selectionRanges.codeBasedSelections[0].range
const sketchPathToNode = getNodePathFromSourceRange(
kclManager.ast,
sourceRange
@ -666,48 +643,10 @@ export const ModelingMachineProvider = ({
),
'Get horizontal info': fromPromise(
async ({ input: { selectionRanges, sketchDetails } }) => {
const _selections = convertSelectionsToOld(selectionRanges)
const { modifiedAst, pathToNodeMap } =
await applyConstraintHorzVertDistance({
constraint: 'setHorzDistance',
selectionRanges: _selections,
})
const _modifiedAst = parse(recast(modifiedAst))
if (!sketchDetails)
return Promise.reject(new Error('No sketch details'))
const updatedPathToNode = updatePathToNodeFromMap(
sketchDetails.sketchPathToNode,
pathToNodeMap
)
const updatedAst =
await sceneEntitiesManager.updateAstAndRejigSketch(
updatedPathToNode,
_modifiedAst,
sketchDetails.zAxis,
sketchDetails.yAxis,
sketchDetails.origin
)
if (err(updatedAst)) return Promise.reject(updatedAst)
// const selection = updateSelections(
const selection = updateSelections2(
pathToNodeMap,
selectionRanges,
updatedAst.newAst
)
if (err(selection)) return Promise.reject(selection)
return {
selectionType: 'completeSelection',
selection,
updatedPathToNode,
}
}
),
'Get vertical info': fromPromise(
async ({ input: { selectionRanges, sketchDetails } }) => {
const { modifiedAst, pathToNodeMap } =
await applyConstraintHorzVertDistance({
constraint: 'setVertDistance',
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
})
const _modifiedAst = parse(recast(modifiedAst))
if (!sketchDetails)
@ -727,7 +666,43 @@ export const ModelingMachineProvider = ({
if (err(updatedAst)) return Promise.reject(updatedAst)
const selection = updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
)
if (err(selection)) return Promise.reject(selection)
return {
selectionType: 'completeSelection',
selection,
updatedPathToNode,
}
}
),
'Get vertical info': fromPromise(
async ({ input: { selectionRanges, sketchDetails } }) => {
const { modifiedAst, pathToNodeMap } =
await applyConstraintHorzVertDistance({
constraint: 'setVertDistance',
selectionRanges,
})
const _modifiedAst = parse(recast(modifiedAst))
if (!sketchDetails)
return Promise.reject(new Error('No sketch details'))
const updatedPathToNode = updatePathToNodeFromMap(
sketchDetails.sketchPathToNode,
pathToNodeMap
)
const updatedAst =
await sceneEntitiesManager.updateAstAndRejigSketch(
updatedPathToNode,
_modifiedAst,
sketchDetails.zAxis,
sketchDetails.yAxis,
sketchDetails.origin
)
if (err(updatedAst)) return Promise.reject(updatedAst)
const selection = updateSelections(
pathToNodeMap,
selectionRanges,
updatedAst.newAst
)
if (err(selection)) return Promise.reject(selection)
@ -741,15 +716,15 @@ export const ModelingMachineProvider = ({
'Get angle info': fromPromise(
async ({ input: { selectionRanges, sketchDetails } }) => {
const info = angleBetweenInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
})
if (err(info)) return Promise.reject(info)
const { modifiedAst, pathToNodeMap } = await (info.enabled
? applyConstraintAngleBetween({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
})
: applyConstraintAngleLength({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
angleOrLength: 'setAngle',
}))
const _modifiedAst = parse(recast(modifiedAst))
@ -772,7 +747,7 @@ export const ModelingMachineProvider = ({
if (err(updatedAst)) return Promise.reject(updatedAst)
const selection = updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
)
if (err(selection)) return Promise.reject(selection)

View File

@ -1,64 +0,0 @@
import toast from 'react-hot-toast'
import { ActionButton } from './ActionButton'
import { openExternalBrowserIfDesktop } from 'lib/openWindow'
export function ToastUpdate({
version,
onRestart,
}: {
version: string
onRestart: () => void
}) {
return (
<div className="inset-0 z-50 grid place-content-center rounded bg-chalkboard-110/50 shadow-md">
<div className="max-w-3xl min-w-[35rem] p-8 rounded bg-chalkboard-10 dark:bg-chalkboard-90">
<div className="my-4 flex items-baseline">
<span
className="px-3 py-1 text-xl rounded-full bg-primary text-chalkboard-10"
data-testid="update-version"
>
v{version}
</span>
<span className="ml-4 text-md text-bold">
A new update has downloaded and will be available next time you
start the app. You can view the release notes{' '}
<a
onClick={openExternalBrowserIfDesktop(
`https://github.com/KittyCAD/modeling-app/releases/tag/v${version}`
)}
href={`https://github.com/KittyCAD/modeling-app/releases/tag/v${version}`}
target="_blank"
rel="noreferrer"
>
here on GitHub.
</a>
</span>
</div>
<div className="flex justify-between gap-8">
<ActionButton
Element="button"
iconStart={{
icon: 'arrowRotateRight',
}}
name="Restart app now"
onClick={onRestart}
>
Restart app now
</ActionButton>
<ActionButton
Element="button"
iconStart={{
icon: 'checkmark',
}}
name="Got it"
onClick={() => {
toast.dismiss()
}}
>
Got it
</ActionButton>
</div>
</div>
</div>
)
}

View File

@ -1,5 +1,5 @@
import { toolTips } from 'lang/langHelpers'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { Program, Expr, VariableDeclarator } from '../../lang/wasm'
import {
getNodePathFromSourceRange,
@ -18,7 +18,7 @@ import { TransformInfo } from 'lang/std/stdTypes'
export function equalAngleInfo({
selectionRanges,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
}):
| {
transforms: TransformInfo[]
@ -82,7 +82,7 @@ export function equalAngleInfo({
export function applyConstraintEqualAngle({
selectionRanges,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
}):
| {
modifiedAst: Program

View File

@ -1,5 +1,5 @@
import { toolTips } from 'lang/langHelpers'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { Program, Expr, VariableDeclarator } from '../../lang/wasm'
import {
getNodePathFromSourceRange,
@ -18,7 +18,7 @@ import { err } from 'lib/trap'
export function setEqualLengthInfo({
selectionRanges,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
}):
| {
transforms: TransformInfo[]
@ -83,7 +83,7 @@ export function setEqualLengthInfo({
export function applyConstraintEqualLength({
selectionRanges,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
}):
| {
modifiedAst: Program

View File

@ -1,5 +1,5 @@
import { toolTips } from 'lang/langHelpers'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { Program, ProgramMemory, Expr } from '../../lang/wasm'
import {
getNodePathFromSourceRange,
@ -15,7 +15,7 @@ import { kclManager } from 'lib/singletons'
import { err } from 'lib/trap'
export function horzVertInfo(
selectionRanges: Selections__old,
selectionRanges: Selections,
horOrVert: 'vertical' | 'horizontal'
):
| {
@ -53,7 +53,7 @@ export function horzVertInfo(
}
export function applyConstraintHorzVert(
selectionRanges: Selections__old,
selectionRanges: Selections,
horOrVert: 'vertical' | 'horizontal',
ast: Program,
programMemory: ProgramMemory

View File

@ -1,6 +1,6 @@
import { toolTips } from 'lang/langHelpers'
import { Selections } from 'lib/selections'
import { Program, Expr, VariableDeclarator } from '../../lang/wasm'
import { Selections__old } from 'lib/selections'
import {
getNodePathFromSourceRange,
getNodeFromPath,
@ -25,12 +25,12 @@ const getModalInfo = createInfoModal(GetInfoModal)
export function intersectInfo({
selectionRanges,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
}):
| {
transforms: TransformInfo[]
enabled: boolean
forcedSelectionRanges: Selections__old
forcedSelectionRanges: Selections
}
| Error {
if (selectionRanges.codeBasedSelections.length < 2) {
@ -134,7 +134,7 @@ export function intersectInfo({
export async function applyConstraintIntersect({
selectionRanges,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
}): Promise<{
modifiedAst: Program
pathToNodeMap: PathToNodeMap

View File

@ -1,5 +1,5 @@
import { toolTips } from 'lang/langHelpers'
import { Selection__old, Selections__old } from 'lib/selections'
import { Selection, Selections } from 'lib/selections'
import { PathToNode, Program, Expr } from '../../lang/wasm'
import {
getNodePathFromSourceRange,
@ -18,13 +18,13 @@ export function removeConstrainingValuesInfo({
selectionRanges,
pathToNodes,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
pathToNodes?: Array<PathToNode>
}):
| {
transforms: TransformInfo[]
enabled: boolean
updatedSelectionRanges: Selections__old
updatedSelectionRanges: Selections
}
| Error {
const paths =
@ -45,7 +45,7 @@ export function removeConstrainingValuesInfo({
? {
otherSelections: [],
codeBasedSelections: nodes.map(
(node): Selection__old => ({
(node): Selection => ({
range: [node.start, node.end],
type: 'default',
})
@ -73,7 +73,7 @@ export function applyRemoveConstrainingValues({
selectionRanges,
pathToNodes,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
pathToNodes?: Array<PathToNode>
}):
| {

View File

@ -1,6 +1,6 @@
import { toolTips } from 'lang/langHelpers'
import { Selections } from 'lib/selections'
import { Program, Expr } from '../../lang/wasm'
import { Selections__old } from 'lib/selections'
import {
getNodePathFromSourceRange,
getNodeFromPath,
@ -32,7 +32,7 @@ export function absDistanceInfo({
selectionRanges,
constraint,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
constraint: Constraint
}):
| {
@ -93,7 +93,7 @@ export async function applyConstraintAbsDistance({
selectionRanges,
constraint,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
constraint: 'xAbs' | 'yAbs'
}): Promise<{
modifiedAst: Program
@ -157,7 +157,7 @@ export function applyConstraintAxisAlign({
selectionRanges,
constraint,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
constraint: 'snapToYAxis' | 'snapToXAxis'
}):
| {

View File

@ -1,6 +1,6 @@
import { toolTips } from 'lang/langHelpers'
import { Selections } from 'lib/selections'
import { Program, Expr, VariableDeclarator } from '../../lang/wasm'
import { Selections__old } from 'lib/selections'
import {
getNodePathFromSourceRange,
getNodeFromPath,
@ -24,7 +24,7 @@ const getModalInfo = createInfoModal(GetInfoModal)
export function angleBetweenInfo({
selectionRanges,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
}):
| {
transforms: TransformInfo[]
@ -90,7 +90,7 @@ export async function applyConstraintAngleBetween({
selectionRanges,
}: // constraint,
{
selectionRanges: Selections__old
selectionRanges: Selections
// constraint: 'setHorzDistance' | 'setVertDistance'
}): Promise<{
modifiedAst: Program

View File

@ -16,7 +16,7 @@ import { GetInfoModal, createInfoModal } from '../SetHorVertDistanceModal'
import { createLiteral, createVariableDeclaration } from '../../lang/modifyAst'
import { removeDoubleNegatives } from '../AvailableVarsHelpers'
import { kclManager } from 'lib/singletons'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { cleanErrs, err } from 'lib/trap'
const getModalInfo = createInfoModal(GetInfoModal)
@ -25,7 +25,7 @@ export function horzVertDistanceInfo({
selectionRanges,
constraint,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
constraint: 'setHorzDistance' | 'setVertDistance'
}):
| {
@ -95,7 +95,7 @@ export async function applyConstraintHorzVertDistance({
// TODO align will always be false (covered by synconous applyConstraintHorzVertAlign), remove it
isAlign = false,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
constraint: 'setHorzDistance' | 'setVertDistance'
isAlign?: false
}): Promise<{
@ -181,7 +181,7 @@ export function applyConstraintHorzVertAlign({
selectionRanges,
constraint,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
constraint: 'setHorzDistance' | 'setVertDistance'
}):
| {

View File

@ -1,6 +1,6 @@
import { toolTips } from 'lang/langHelpers'
import { Selections } from 'lib/selections'
import { Program, Expr } from '../../lang/wasm'
import { Selections__old } from 'lib/selections'
import {
getNodePathFromSourceRange,
getNodeFromPath,
@ -32,7 +32,7 @@ export function angleLengthInfo({
selectionRanges,
angleOrLength = 'setLength',
}: {
selectionRanges: Selections__old
selectionRanges: Selections
angleOrLength?: 'setLength' | 'setAngle'
}):
| {
@ -74,7 +74,7 @@ export async function applyConstraintAngleLength({
selectionRanges,
angleOrLength = 'setLength',
}: {
selectionRanges: Selections__old
selectionRanges: Selections
angleOrLength?: 'setLength' | 'setAngle'
}): Promise<{
modifiedAst: Program

View File

@ -2,11 +2,7 @@ import { EditorView, ViewUpdate } from '@codemirror/view'
import { EditorSelection, Annotation, Transaction } from '@codemirror/state'
import { engineCommandManager } from 'lib/singletons'
import { modelingMachine, ModelingMachineEvent } from 'machines/modelingMachine'
import {
Selections__old,
Selection__old,
processCodeMirrorRanges,
} from 'lib/selections'
import { Selections, processCodeMirrorRanges, Selection } from 'lib/selections'
import { undo, redo } from '@codemirror/commands'
import { CommandBarMachineEvent } from 'machines/commandBarMachine'
import { addLineHighlight, addLineHighlightEvent } from './highlightextension'
@ -35,7 +31,7 @@ export default class EditorManager {
private _copilotEnabled: boolean = true
private _isShiftDown: boolean = false
private _selectionRanges: Selections__old = {
private _selectionRanges: Selections = {
otherSelections: [],
codeBasedSelections: [],
}
@ -77,7 +73,7 @@ export default class EditorManager {
this._isShiftDown = isShiftDown
}
set selectionRanges(selectionRanges: Selections__old) {
set selectionRanges(selectionRanges: Selections) {
this._selectionRanges = selectionRanges
}
@ -101,7 +97,7 @@ export default class EditorManager {
return this._highlightRange
}
setHighlightRange(selections: Array<Selection__old['range']>): void {
setHighlightRange(selections: Array<Selection['range']>): void {
this._highlightRange = selections
const selectionsWithSafeEnds = selections.map((s): [number, number] => {
@ -207,7 +203,7 @@ export default class EditorManager {
return false
}
selectRange(selections: Selections__old) {
selectRange(selections: Selections) {
if (selections.codeBasedSelections.length === 0) {
return
}

View File

@ -9,9 +9,10 @@ import { useModelingContext } from './useModelingContext'
import { getEventForSelectWithPoint } from 'lib/selections'
import {
getCapCodeRef,
getSweepEdgeCodeRef,
getSweepFromSuspectedSweepSurface,
getSolid2dCodeRef,
getWallCodeRef,
getCodeRefsByArtifactId,
} from 'lang/std/artifactGraph'
import { err, reportRejection } from 'lib/trap'
import { DefaultPlaneStr, getFaceDetails } from 'clientSideScene/sceneEntities'
@ -28,14 +29,52 @@ export function useEngineConnectionSubscriptions() {
event: 'highlight_set_entity',
callback: ({ data }) => {
if (data?.entity_id) {
const codeRefs = getCodeRefsByArtifactId(
data.entity_id,
engineCommandManager.artifactGraph
const artifact = engineCommandManager.artifactGraph.get(
data.entity_id
)
if (codeRefs) {
editorManager.setHighlightRange(codeRefs.map(({ range }) => range))
if (artifact?.type === 'solid2D') {
const codeRef = getSolid2dCodeRef(
artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return
editorManager.setHighlightRange([codeRef.range])
} else if (artifact?.type === 'cap') {
const codeRef = getCapCodeRef(
artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return
editorManager.setHighlightRange([codeRef.range])
} else if (artifact?.type === 'wall') {
const extrusion = getSweepFromSuspectedSweepSurface(
data.entity_id,
engineCommandManager.artifactGraph
)
const codeRef = getWallCodeRef(
artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return
editorManager.setHighlightRange(
err(extrusion)
? [codeRef.range]
: [codeRef.range, extrusion.codeRef.range]
)
} else if (artifact?.type === 'sweepEdge') {
const codeRef = getSweepEdgeCodeRef(
artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return
editorManager.setHighlightRange([codeRef.range])
} else if (artifact?.type === 'segment') {
editorManager.setHighlightRange([
artifact?.codeRef?.range || [0, 0],
])
} else {
editorManager.setHighlightRange([[0, 0]])
}
editorManager.setHighlightRange([[0, 0]])
} else if (
!editorManager.highlightRange ||
(editorManager.highlightRange[0][0] !== 0 &&

View File

@ -11,7 +11,6 @@ import { useModelingContext } from './useModelingContext'
import { PathToNode, SourceRange } from 'lang/wasm'
import { useKclContext } from 'lang/KclProvider'
import { toSync } from 'lib/utils'
import { convertSelectionsToOld } from 'lib/selections'
export const getVarNameModal = createSetVarNameModal(SetVarNameModal)
@ -29,19 +28,14 @@ export function useConvertToVariable(range?: SourceRange) {
const meta = isNodeSafeToReplace(
parsed,
range ||
convertSelectionsToOld(context.selectionRanges).codeBasedSelections?.[0]
?.range ||
[]
range || context.selectionRanges.codeBasedSelections?.[0]?.range || []
)
if (trap(meta)) return
const { isSafe, value } = meta
const canReplace = isSafe && value.type !== 'Identifier'
const isOnlyOneSelection =
!!range ||
convertSelectionsToOld(context.selectionRanges).codeBasedSelections
.length === 1
!!range || context.selectionRanges.codeBasedSelections.length === 1
setEnabled(canReplace && isOnlyOneSelection)
}, [context.selectionRanges])
@ -58,9 +52,7 @@ export function useConvertToVariable(range?: SourceRange) {
moveValueIntoNewVariable(
ast,
kclManager.programMemory,
range ||
convertSelectionsToOld(context.selectionRanges)
.codeBasedSelections[0].range,
range || context.selectionRanges.codeBasedSelections[0].range,
variableName
)

View File

@ -1,13 +1,12 @@
import ReactDOM from 'react-dom/client'
import './index.css'
import reportWebVitals from './reportWebVitals'
import toast, { Toaster } from 'react-hot-toast'
import { Toaster } from 'react-hot-toast'
import { Router } from './Router'
import { HotkeysProvider } from 'react-hotkeys-hook'
import ModalContainer from 'react-modal-promise'
import { isDesktop } from 'lib/isDesktop'
import { AppStreamProvider } from 'AppState'
import { ToastUpdate } from 'components/ToastUpdate'
// uncomment for xstate inspector
// import { DEV } from 'env'
@ -53,17 +52,4 @@ root.render(
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()
isDesktop() &&
window.electron.onUpdateDownloaded((version: string) => {
const message = `A new update (${version}) was downloaded and will be available next time you open the app.`
console.log(message)
toast.custom(
ToastUpdate({
version,
onRestart: () => {
window.electron.appRestart()
},
}),
{ duration: 30000 }
)
})
isDesktop()

View File

@ -1,5 +1,5 @@
import { executeAst, lintAst } from 'lang/langHelpers'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { KCLError, kclErrorsToDiagnostics } from './errors'
import { uuidv4 } from 'lib/utils'
import { EngineCommandManager } from './std/engineConnection'
@ -425,14 +425,14 @@ export class KclManager {
}
): Promise<{
newAst: Program
selections?: Selections__old
selections?: Selections
}> {
const newCode = recast(ast)
if (err(newCode)) return Promise.reject(newCode)
const astWithUpdatedSource = this.safeParse(newCode)
if (!astWithUpdatedSource) return Promise.reject(new Error('bad ast'))
let returnVal: Selections__old | undefined = undefined
let returnVal: Selections | undefined = undefined
if (optionalParams?.focusPath) {
returnVal = {

View File

@ -1,5 +1,5 @@
import { Selection } from 'lib/selections'
import { err, reportRejection, trap } from 'lib/trap'
import { Selection__old } from 'lib/selections'
import {
Program,
CallExpression,
@ -762,7 +762,7 @@ export function createBinaryExpressionWithUnary([left, right]: [
export function giveSketchFnCallTag(
ast: Program,
range: Selection__old['range'],
range: Selection['range'],
tag?: string
):
| {
@ -836,7 +836,7 @@ export function moveValueIntoNewVariablePath(
export function moveValueIntoNewVariable(
ast: Program,
programMemory: ProgramMemory,
sourceRange: Selection__old['range'],
sourceRange: Selection['range'],
variableName: string
): {
modifiedAst: Program
@ -955,7 +955,7 @@ export function removeSingleConstraintInfo(
export async function deleteFromSelection(
ast: Program,
selection: Selection__old,
selection: Selection,
programMemory: ProgramMemory,
getFaceDetails: (id: string) => Promise<Models['FaceIsPlanar_type']> = () =>
({} as any)

View File

@ -19,7 +19,7 @@ import {
import { getNodeFromPath, getNodePathFromSourceRange } from '../queryAst'
import { createLiteral } from 'lang/modifyAst'
import { err } from 'lib/trap'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { engineCommandManager, kclManager } from 'lib/singletons'
import { VITE_KC_DEV_TOKEN } from 'env'
import { KclCommandValue } from 'lib/commandTypes'
@ -106,7 +106,7 @@ const runGetPathToExtrudeForSegmentSelectionTest = async (
code.indexOf(selectedSegmentSnippet),
code.indexOf(selectedSegmentSnippet) + selectedSegmentSnippet.length,
]
const selection: Selections__old = {
const selection: Selections = {
codeBasedSelections: [
{
range: segmentRange,
@ -469,7 +469,7 @@ const runModifyAstWithFilletAndTagTest = async (
code.indexOf(selectionSnippet) + selectionSnippet.length,
]
)
const selection: Selections__old = {
const selection: Selections = {
codeBasedSelections: segmentRanges.map((segmentRange) => ({
range: segmentRange,
type: 'default',
@ -730,7 +730,7 @@ describe('Testing button states', () => {
]
: [ast.end, ast.end] // empty line in the end of the code
const selectionRanges: Selections__old = {
const selectionRanges: Selections = {
codeBasedSelections: [
{
range,

View File

@ -31,7 +31,7 @@ import {
sketchLineHelperMap,
} from '../std/sketch'
import { err, trap } from 'lib/trap'
import { Selections__old, canFilletSelection } from 'lib/selections'
import { Selections, canFilletSelection } from 'lib/selections'
import { KclCommandValue } from 'lib/commandTypes'
import {
ArtifactGraph,
@ -45,7 +45,7 @@ import { kclManager, engineCommandManager, editorManager } from 'lib/singletons'
export function applyFilletToSelection(
ast: Program,
selection: Selections__old,
selection: Selections,
radius: KclCommandValue
): void | Error {
// 1. clone ast
@ -63,7 +63,7 @@ export function applyFilletToSelection(
export function modifyAstWithFilletAndTag(
ast: Program,
selection: Selections__old,
selection: Selections,
radius: KclCommandValue
): { modifiedAst: Program; pathToFilletNode: Array<PathToNode> } | Error {
const astResult = insertRadiusIntoAst(ast, radius)
@ -130,7 +130,7 @@ function insertRadiusIntoAst(
export function getPathToExtrudeForSegmentSelection(
ast: Program,
selection: Selections__old,
selection: Selections,
programMemory: ProgramMemory,
artifactGraph: ArtifactGraph
): { pathToSegmentNode: PathToNode; pathToExtrudeNode: PathToNode } | Error {
@ -447,7 +447,7 @@ export const hasValidFilletSelection = ({
ast,
code,
}: {
selectionRanges: Selections__old
selectionRanges: Selections
ast: Program
code: string
}) => {

View File

@ -1,5 +1,5 @@
import { ToolTip } from 'lang/langHelpers'
import { Selection__old, Selections__old } from 'lib/selections'
import { Selection, Selections } from 'lib/selections'
import {
ArrayExpression,
BinaryExpression,
@ -120,7 +120,7 @@ export function getNodeFromPathCurry(
function moreNodePathFromSourceRange(
node: Expr | ExpressionStatement | VariableDeclaration | ReturnStatement,
sourceRange: Selection__old['range'],
sourceRange: Selection['range'],
previousPath: PathToNode = [['body', '']]
): PathToNode {
const [start, end] = sourceRange
@ -315,7 +315,7 @@ function moreNodePathFromSourceRange(
export function getNodePathFromSourceRange(
node: Program,
sourceRange: Selection__old['range'],
sourceRange: Selection['range'],
previousPath: PathToNode = [['body', '']]
): PathToNode {
const [start, end] = sourceRange || []
@ -493,7 +493,7 @@ export function findAllPreviousVariablesPath(
export function findAllPreviousVariables(
ast: Program,
programMemory: ProgramMemory,
sourceRange: Selection__old['range'],
sourceRange: Selection['range'],
type: 'number' | 'string' = 'number'
): {
variables: PrevVariable<typeof type extends 'number' ? number : string>[]
@ -639,8 +639,8 @@ export function isValueZero(val?: Expr): boolean {
export function isLinesParallelAndConstrained(
ast: Program,
programMemory: ProgramMemory,
primaryLine: Selection__old,
secondaryLine: Selection__old
primaryLine: Selection,
secondaryLine: Selection
):
| {
isParallelAndConstrained: boolean
@ -735,7 +735,7 @@ export function doesPipeHaveCallExp({
}: {
calleeName: string
ast: Program
selection: Selection__old
selection: Selection
}): boolean {
const pathToNode = getNodePathFromSourceRange(ast, selection.range)
const pipeExpressionMeta = getNodeFromPath<PipeExpression>(
@ -762,7 +762,7 @@ export function hasExtrudeSketchGroup({
programMemory,
}: {
ast: Program
selection: Selection__old
selection: Selection
programMemory: ProgramMemory
}): boolean {
const pathToNode = getNodePathFromSourceRange(ast, selection.range)
@ -786,7 +786,7 @@ export function hasExtrudeSketchGroup({
}
export function isSingleCursorInPipe(
selectionRanges: Selections__old,
selectionRanges: Selections,
ast: Program
) {
if (selectionRanges.codeBasedSelections.length !== 1) return false
@ -860,10 +860,7 @@ export function findUsesOfTagInPipe(
return dependentRanges
}
export function hasSketchPipeBeenExtruded(
selection: Selection__old,
ast: Program
) {
export function hasSketchPipeBeenExtruded(selection: Selection, ast: Program) {
const path = getNodePathFromSourceRange(ast, selection.range)
const _node = getNodeFromPath<PipeExpression>(ast, path, 'PipeExpression')
if (err(_node)) return false

View File

@ -5,90 +5,86 @@ import { err } from 'lib/trap'
export type ArtifactId = string
interface BaseArtifact {
id: ArtifactId
}
export interface CodeRef {
interface CommonCommandProperties {
range: SourceRange
pathToNode: PathToNode
}
export interface PlaneArtifact extends BaseArtifact {
export interface PlaneArtifact {
type: 'plane'
pathIds: Array<ArtifactId>
codeRef: CodeRef
codeRef: CommonCommandProperties
}
export interface PlaneArtifactRich extends BaseArtifact {
export interface PlaneArtifactRich {
type: 'plane'
paths: Array<PathArtifact>
codeRef: CodeRef
codeRef: CommonCommandProperties
}
export interface PathArtifact extends BaseArtifact {
export interface PathArtifact {
type: 'path'
planeId: ArtifactId
segIds: Array<ArtifactId>
sweepId: ArtifactId
solid2dId?: ArtifactId
codeRef: CodeRef
codeRef: CommonCommandProperties
}
interface solid2D extends BaseArtifact {
interface solid2D {
type: 'solid2D'
pathId: ArtifactId
}
export interface PathArtifactRich extends BaseArtifact {
export interface PathArtifactRich {
type: 'path'
plane: PlaneArtifact | WallArtifact
segments: Array<SegmentArtifact>
sweep: SweepArtifact
codeRef: CodeRef
codeRef: CommonCommandProperties
}
interface SegmentArtifact extends BaseArtifact {
interface SegmentArtifact {
type: 'segment'
pathId: ArtifactId
surfaceId: ArtifactId
edgeIds: Array<ArtifactId>
edgeCutId?: ArtifactId
codeRef: CodeRef
codeRef: CommonCommandProperties
}
interface SegmentArtifactRich extends BaseArtifact {
interface SegmentArtifactRich {
type: 'segment'
path: PathArtifact
surf: WallArtifact
edges: Array<SweepEdge>
edgeCut?: EdgeCut
codeRef: CodeRef
codeRef: CommonCommandProperties
}
/** A Sweep is a more generic term for extrude, revolve, loft and sweep*/
interface SweepArtifact extends BaseArtifact {
interface SweepArtifact {
type: 'sweep'
subType: 'extrusion' | 'revolve'
pathId: string
surfaceIds: Array<string>
edgeIds: Array<string>
codeRef: CodeRef
codeRef: CommonCommandProperties
}
interface SweepArtifactRich extends BaseArtifact {
interface SweepArtifactRich {
type: 'sweep'
subType: 'extrusion' | 'revolve'
path: PathArtifact
surfaces: Array<WallArtifact | CapArtifact>
edges: Array<SweepEdge>
codeRef: CodeRef
codeRef: CommonCommandProperties
}
interface WallArtifact extends BaseArtifact {
interface WallArtifact {
type: 'wall'
segId: ArtifactId
edgeCutEdgeIds: Array<ArtifactId>
sweepId: ArtifactId
pathIds: Array<ArtifactId>
}
interface CapArtifact extends BaseArtifact {
interface CapArtifact {
type: 'cap'
subType: 'start' | 'end'
edgeCutEdgeIds: Array<ArtifactId>
@ -96,7 +92,7 @@ interface CapArtifact extends BaseArtifact {
pathIds: Array<ArtifactId>
}
interface SweepEdge extends BaseArtifact {
interface SweepEdge {
type: 'sweepEdge'
segId: ArtifactId
sweepId: ArtifactId
@ -104,16 +100,16 @@ interface SweepEdge extends BaseArtifact {
}
/** A edgeCut is a more generic term for both fillet or chamfer */
interface EdgeCut extends BaseArtifact {
interface EdgeCut {
type: 'edgeCut'
subType: 'fillet' | 'chamfer'
consumedEdgeId: ArtifactId
edgeIds: Array<ArtifactId>
surfaceId: ArtifactId
codeRef: CodeRef
codeRef: CommonCommandProperties
}
interface EdgeCutEdge extends BaseArtifact {
interface EdgeCutEdge {
type: 'edgeCutEdge'
edgeCutId: ArtifactId
surfaceId: ArtifactId
@ -262,7 +258,6 @@ export function getArtifactsToUpdate({
id: currentPlaneId,
artifact: {
type: 'wall',
id,
segId: existingPlane.segId,
edgeCutEdgeIds: existingPlane.edgeCutEdgeIds,
sweepId: existingPlane.sweepId,
@ -272,10 +267,7 @@ export function getArtifactsToUpdate({
]
} else {
return [
{
id: currentPlaneId,
artifact: { type: 'plane', id: currentPlaneId, pathIds, codeRef },
},
{ id: currentPlaneId, artifact: { type: 'plane', pathIds, codeRef } },
]
}
} else if (cmd.type === 'start_path') {
@ -283,7 +275,6 @@ export function getArtifactsToUpdate({
id,
artifact: {
type: 'path',
id,
segIds: [],
planeId: currentPlaneId,
sweepId: '',
@ -296,7 +287,7 @@ export function getArtifactsToUpdate({
if (plane?.type === 'plane') {
returnArr.push({
id: currentPlaneId,
artifact: { type: 'plane', id: currentPlaneId, pathIds: [id], codeRef },
artifact: { type: 'plane', pathIds: [id], codeRef },
})
}
if (plane?.type === 'wall') {
@ -304,7 +295,6 @@ export function getArtifactsToUpdate({
id: currentPlaneId,
artifact: {
type: 'wall',
id,
segId: plane.segId,
edgeCutEdgeIds: plane.edgeCutEdgeIds,
sweepId: plane.sweepId,
@ -319,7 +309,6 @@ export function getArtifactsToUpdate({
id,
artifact: {
type: 'segment',
id,
pathId,
surfaceId: '',
edgeIds: [],
@ -338,11 +327,7 @@ export function getArtifactsToUpdate({
) {
returnArr.push({
id: response.data.modeling_response.data.face_id,
artifact: {
type: 'solid2D',
id: response.data.modeling_response.data.face_id,
pathId,
},
artifact: { type: 'solid2D', pathId },
})
const path = getArtifact(pathId)
if (path?.type === 'path')
@ -362,7 +347,6 @@ export function getArtifactsToUpdate({
artifact: {
type: 'sweep',
subType: subType,
id,
pathId: cmd.target,
surfaceIds: [],
edgeIds: [],
@ -394,7 +378,6 @@ export function getArtifactsToUpdate({
id: face_id,
artifact: {
type: 'wall',
id: face_id,
segId: curve_id,
edgeCutEdgeIds: [],
sweepId: path.sweepId,
@ -427,7 +410,6 @@ export function getArtifactsToUpdate({
id: face_id,
artifact: {
type: 'cap',
id: face_id,
subType: cap === 'bottom' ? 'start' : 'end',
edgeCutEdgeIds: [],
sweepId: path.sweepId,
@ -474,7 +456,6 @@ export function getArtifactsToUpdate({
id: response.data.modeling_response.data.edge,
artifact: {
type: 'sweepEdge',
id: response.data.modeling_response.data.edge,
subType:
cmd.type === 'solid3d_get_prev_adjacent_edge'
? 'adjacent'
@ -503,7 +484,6 @@ export function getArtifactsToUpdate({
id,
artifact: {
type: 'edgeCut',
id,
subType: cmd.cut_type,
consumedEdgeId: cmd.edge_id,
edgeIds: [],
@ -594,7 +574,6 @@ export function expandPlane(
)
return {
type: 'plane',
id: plane.id,
paths: Array.from(paths.values()),
codeRef: plane.codeRef,
}
@ -623,7 +602,6 @@ export function expandPath(
if (err(plane)) return plane
return {
type: 'path',
id: path.id,
segments: Array.from(segs.values()),
sweep,
plane,
@ -651,7 +629,6 @@ export function expandSweep(
return {
type: 'sweep',
subType: 'extrusion',
id: sweep.id,
surfaces: Array.from(surfs.values()),
edges: Array.from(edges.values()),
path,
@ -687,7 +664,6 @@ export function expandSegment(
return {
type: 'segment',
id: segment.id,
path,
surf,
edges: Array.from(edges.values()),
@ -699,7 +675,7 @@ export function expandSegment(
export function getCapCodeRef(
cap: CapArtifact,
artifactGraph: ArtifactGraph
): CodeRef | Error {
): CommonCommandProperties | Error {
const sweep = getArtifactOfTypes(
{ key: cap.sweepId, types: ['sweep'] },
artifactGraph
@ -716,7 +692,7 @@ export function getCapCodeRef(
export function getSolid2dCodeRef(
solid2D: solid2D,
artifactGraph: ArtifactGraph
): CodeRef | Error {
): CommonCommandProperties | Error {
const path = getArtifactOfTypes(
{ key: solid2D.pathId, types: ['path'] },
artifactGraph
@ -728,7 +704,7 @@ export function getSolid2dCodeRef(
export function getWallCodeRef(
wall: WallArtifact,
artifactGraph: ArtifactGraph
): CodeRef | Error {
): CommonCommandProperties | Error {
const seg = getArtifactOfTypes(
{ key: wall.segId, types: ['segment'] },
artifactGraph
@ -740,7 +716,7 @@ export function getWallCodeRef(
export function getSweepEdgeCodeRef(
edge: SweepEdge,
artifactGraph: ArtifactGraph
): CodeRef | Error {
): CommonCommandProperties | Error {
const seg = getArtifactOfTypes(
{ key: edge.segId, types: ['segment'] },
artifactGraph
@ -775,33 +751,3 @@ export function getSweepFromSuspectedPath(
artifactGraph
)
}
export function getCodeRefsByArtifactId(
id: string,
artifactGraph: ArtifactGraph
): Array<CodeRef> | null {
const artifact = artifactGraph.get(id)
if (artifact?.type === 'solid2D') {
const codeRef = getSolid2dCodeRef(artifact, artifactGraph)
if (err(codeRef)) return null
return [codeRef]
// editorManager.setHighlightRange([codeRef.range])
} else if (artifact?.type === 'cap') {
const codeRef = getCapCodeRef(artifact, artifactGraph)
if (err(codeRef)) return null
return [codeRef]
} else if (artifact?.type === 'wall') {
const extrusion = getSweepFromSuspectedSweepSurface(id, artifactGraph)
const codeRef = getWallCodeRef(artifact, artifactGraph)
if (err(codeRef)) return null
return err(extrusion) ? [codeRef] : [codeRef, extrusion.codeRef]
} else if (artifact?.type === 'sweepEdge') {
const codeRef = getSweepEdgeCodeRef(artifact, artifactGraph)
if (err(codeRef)) return null
return [codeRef]
} else if (artifact?.type === 'segment') {
return [artifact.codeRef]
} else {
return null
}
}

View File

@ -1912,13 +1912,11 @@ export function getConstraintInfo(
): ConstrainInfo[] {
const fnName = callExpression?.callee?.name || ''
if (!(fnName in sketchLineHelperMap)) return []
const result = sketchLineHelperMap[fnName].getConstraintInfo(
return sketchLineHelperMap[fnName].getConstraintInfo(
callExpression,
code,
pathToNode
)
// console.log('result path', result[0].pathToNode)
return result
}
export function compareVec2Epsilon(

View File

@ -11,7 +11,7 @@ import {
transformAstSketchLines,
} from './sketchcombos'
import { getSketchSegmentFromSourceRange } from './sketchConstraints'
import { Selection__old } from 'lib/selections'
import { Selection } from 'lib/selections'
import { enginelessExecutor } from '../../lib/testHelpers'
import { err } from 'lib/trap'
@ -33,7 +33,7 @@ async function testingSwapSketchFnCall({
originalRange: [number, number]
}> {
const startIndex = inputCode.indexOf(callToSwap)
const range: Selection__old = {
const range: Selection = {
type: 'default',
range: [startIndex, startIndex + callToSwap.length],
}

View File

@ -9,7 +9,7 @@ import {
getConstraintLevelFromSourceRange,
} from './sketchcombos'
import { ToolTip } from 'lang/langHelpers'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { err } from 'lib/trap'
import { enginelessExecutor } from '../../lib/testHelpers'
@ -87,8 +87,8 @@ function getConstraintTypeFromSourceHelper2(
}
function makeSelections(
codeBaseSelections: Selections__old['codeBasedSelections']
): Selections__old {
codeBaseSelections: Selections['codeBasedSelections']
): Selections {
return {
codeBasedSelections: codeBaseSelections,
otherSelections: [],
@ -208,7 +208,7 @@ const part001 = startSketchOn('XY')
const ast = parse(inputScript)
if (err(ast)) return Promise.reject(ast)
const selectionRanges: Selections__old['codeBasedSelections'] = inputScript
const selectionRanges: Selections['codeBasedSelections'] = inputScript
.split('\n')
.filter((ln) => ln.includes('//'))
.map((ln) => {
@ -299,7 +299,7 @@ const part001 = startSketchOn('XY')
const ast = parse(inputScript)
if (err(ast)) return Promise.reject(ast)
const selectionRanges: Selections__old['codeBasedSelections'] = inputScript
const selectionRanges: Selections['codeBasedSelections'] = inputScript
.split('\n')
.filter((ln) => ln.includes('// select for horizontal constraint'))
.map((ln) => {
@ -361,7 +361,7 @@ const part001 = startSketchOn('XY')
const ast = parse(inputScript)
if (err(ast)) return Promise.reject(ast)
const selectionRanges: Selections__old['codeBasedSelections'] = inputScript
const selectionRanges: Selections['codeBasedSelections'] = inputScript
.split('\n')
.filter((ln) => ln.includes('// select for vertical constraint'))
.map((ln) => {
@ -434,7 +434,7 @@ const part001 = startSketchOn('XY')
segEndY(seg01) + 2.93
], %) // xRelative`)
})
it.only('testing for yRelative to horizontal distance', async () => {
it('testing for yRelative to horizontal distance', async () => {
const expectedCode = await helperThing(
inputScript,
['// base selection', '// yRelative'],
@ -456,7 +456,7 @@ async function helperThing(
const ast = parse(inputScript)
if (err(ast)) return Promise.reject(ast)
const selectionRanges: Selections__old['codeBasedSelections'] = inputScript
const selectionRanges: Selections['codeBasedSelections'] = inputScript
.split('\n')
.filter((ln) =>
linesOfInterest.some((lineOfInterest) => ln.includes(lineOfInterest))

View File

@ -7,7 +7,7 @@ import {
TransformInfo,
} from './stdTypes'
import { ToolTip, toolTips } from 'lang/langHelpers'
import { Selections__old, Selection__old } from 'lib/selections'
import { Selections, Selection } from 'lib/selections'
import { cleanErrs, err } from 'lib/trap'
import {
CallExpression,
@ -1470,7 +1470,7 @@ export function getConstraintType(
}
export function getTransformInfos(
selectionRanges: Selections__old,
selectionRanges: Selections,
ast: Program,
constraintType: ConstraintType
): TransformInfo[] {
@ -1502,7 +1502,7 @@ export function getTransformInfos(
}
export function getRemoveConstraintsTransforms(
selectionRanges: Selections__old,
selectionRanges: Selections,
ast: Program,
constraintType: ConstraintType
): TransformInfo[] | Error {
@ -1542,7 +1542,7 @@ export function transformSecondarySketchLinesTagFirst({
forceValueUsedInTransform,
}: {
ast: Program
selectionRanges: Selections__old
selectionRanges: Selections
transformInfos: TransformInfo[]
programMemory: ProgramMemory
forceSegName?: string
@ -1613,12 +1613,12 @@ export function transformAstSketchLines({
referencedSegmentRange,
}: {
ast: Program
selectionRanges: Selections__old | PathToNode[]
selectionRanges: Selections | PathToNode[]
transformInfos: TransformInfo[]
programMemory: ProgramMemory
referenceSegName: string
referencedSegmentRange?: Selection__old['range']
forceValueUsedInTransform?: BinaryPart
referencedSegmentRange?: Selection['range']
}):
| {
modifiedAst: Program
@ -1658,7 +1658,6 @@ export function transformAstSketchLines({
''
const inputs: InputArgs = []
console.log('getConstraintInfo', callExp.node, _pathToNode)
getConstraintInfo(callExp.node, '', _pathToNode).forEach((a) => {
if (
a.type === 'tangentialWithPrevious' ||
@ -1823,7 +1822,7 @@ function getArgLiteralVal(arg: Literal): number | Error {
export type ConstraintLevel = 'free' | 'partial' | 'full'
export function getConstraintLevelFromSourceRange(
cursorRange: Selection__old['range'],
cursorRange: Selection['range'],
ast: Program | Error
): Error | { range: [number, number]; level: ConstraintLevel } {
if (err(ast)) return ast

View File

@ -1,4 +1,4 @@
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { Program, PathToNode } from './wasm'
import { getNodeFromPath } from './queryAst'
import { ArtifactGraph, filterArtifacts } from 'lang/std/artifactGraph'
@ -7,10 +7,10 @@ import { err } from 'lib/trap'
export function pathMapToSelections(
ast: Program,
prevSelections: Selections__old,
prevSelections: Selections,
pathToNodeMap: { [key: number]: PathToNode }
): Selections__old {
const newSelections: Selections__old = {
): Selections {
const newSelections: Selections = {
...prevSelections,
codeBasedSelections: [],
}
@ -47,7 +47,7 @@ export function updatePathToNodeFromMap(
export function isCursorInSketchCommandRange(
artifactGraph: ArtifactGraph,
selectionRanges: Selections__old
selectionRanges: Selections
): string | false {
const overlappingEntries = filterArtifacts(
{

View File

@ -2,7 +2,7 @@ import { Models } from '@kittycad/lib'
import { StateMachineCommandSetConfig, KclCommandValue } from 'lib/commandTypes'
import { KCL_DEFAULT_LENGTH, KCL_DEFAULT_DEGREE } from 'lib/constants'
import { components } from 'lib/machine-api'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { machineManager } from 'lib/machineManager'
import { modelingMachine, SketchTool } from 'machines/modelingMachine'
@ -28,17 +28,17 @@ export type ModelingCommandSchema = {
machine: components['schemas']['MachineInfoResponse']
}
Extrude: {
selection: Selections__old // & { type: 'face' } would be cool to lock that down
selection: Selections // & { type: 'face' } would be cool to lock that down
// result: (typeof EXTRUSION_RESULTS)[number]
distance: KclCommandValue
}
Revolve: {
selection: Selections__old
selection: Selections
angle: KclCommandValue
}
Fillet: {
// todo
selection: Selections__old
selection: Selections
radius: KclCommandValue
}
'change tool': {

View File

@ -1,7 +1,7 @@
import { CustomIconName } from 'components/CustomIcon'
import { AllMachines } from 'hooks/useStateMachineCommands'
import { Actor, AnyStateMachine, ContextFrom, EventFrom } from 'xstate'
import { Selection__old } from './selections'
import { Selection } from './selections'
import { Identifier, Expr, VariableDeclaration } from 'lang/wasm'
import { commandBarMachine } from 'machines/commandBarMachine'
import { ReactNode } from 'react'
@ -140,7 +140,7 @@ export type CommandArgumentConfig<
}
| {
inputType: 'selection'
selectionTypes: Selection__old['type'][]
selectionTypes: Selection['type'][]
multiple: boolean
}
| { inputType: 'kcl'; defaultValue?: string } // KCL expression inputs have simple strings as default values
@ -213,7 +213,7 @@ export type CommandArgument<
}
| {
inputType: 'selection'
selectionTypes: Selection__old['type'][]
selectionTypes: Selection['type'][]
multiple: boolean
}
| { inputType: 'kcl'; defaultValue?: string } // KCL expression inputs have simple strings as default value

View File

@ -28,15 +28,12 @@ import { AXIS_GROUP, X_AXIS } from 'clientSideScene/sceneInfra'
import { PathToNodeMap } from 'lang/std/sketchcombos'
import { err } from 'lib/trap'
import {
Artifact,
getArtifactOfTypes,
getArtifactsOfTypes,
getCapCodeRef,
getSweepEdgeCodeRef,
getSolid2dCodeRef,
getWallCodeRef,
CodeRef,
getCodeRefsByArtifactId,
} from 'lang/std/artifactGraph'
export const X_AXIS_UUID = 'ad792545-7fd3-482a-a602-a93924e3055b'
@ -44,8 +41,7 @@ export const Y_AXIS_UUID = '680fd157-266f-4b8a-984f-cdf46b8bdf01'
export type Axis = 'y-axis' | 'x-axis' | 'z-axis'
/** @deprecated Use {@link Artifact} instead. */
export type Selection__old = {
export type Selection = {
type:
| 'default'
| 'line-end'
@ -62,129 +58,9 @@ export type Selection__old = {
| 'all'
range: SourceRange
}
/** @deprecated Use {@link Selection} instead. */
export type Selections__old = {
otherSelections: Axis[]
codeBasedSelections: Selection__old[]
}
export interface Selection {
artifact: Artifact
codeRef: CodeRef
}
export type Selections = {
otherSelections: Array<Axis>
graphSelections: Array<Selection>
}
/** @deprecated If you're writing a new function, it should use {@link Selection} and not {@link Selection__old}
* this function should only be used for backwards compatibility with old functions.
*/
export function convertSelectionToOld(
selection: Selection
): Selection__old | null {
// return {} as Selection__old
// TODO implementation
const _artifact = selection.artifact
if (_artifact.type === 'solid2D') {
const codeRef = getSolid2dCodeRef(
_artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return null
return { range: codeRef.range, type: 'solid2D' }
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: codeRef.range, type: 'solid2D' },
// },
// }
}
if (_artifact.type === 'cap') {
const codeRef = getCapCodeRef(_artifact, engineCommandManager.artifactGraph)
if (err(codeRef)) return null
return {
range: codeRef.range,
type: _artifact?.subType === 'end' ? 'end-cap' : 'start-cap',
}
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: {
// range: codeRef.range,
// type: _artifact?.subType === 'end' ? 'end-cap' : 'start-cap',
// },
// },
// }
}
if (_artifact.type === 'wall') {
const codeRef = getWallCodeRef(
_artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return null
return { range: codeRef.range, type: 'extrude-wall' }
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: codeRef.range, type: 'extrude-wall' },
// },
// }
}
if (_artifact.type === 'segment' || _artifact.type === 'path') {
return { range: _artifact.codeRef.range, type: 'default' }
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: _artifact.codeRef.range, type: 'default' },
// },
// }
}
if (_artifact.type === 'sweepEdge') {
const codeRef = getSweepEdgeCodeRef(
_artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return null
if (_artifact?.subType === 'adjacent') {
return { range: codeRef.range, type: 'adjacent-edge' }
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: codeRef.range, type: 'adjacent-edge' },
// },
// }
}
return { range: codeRef.range, type: 'edge' }
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: codeRef.range, type: 'edge' },
// },
// }
}
return null
}
/** @deprecated If you're writing a new function, it should use {@link Selection} and not {@link Selection__old}
* this function should only be used for backwards compatibility with old functions.
*/
export function convertSelectionsToOld(selection: Selections): Selections__old {
const selections: Selection__old[] = []
for (const artifact of selection.graphSelections) {
const converted = convertSelectionToOld(artifact)
if (converted) selections.push(converted)
}
const selectionsOld: Selections__old = {
otherSelections: selection.otherSelections,
codeBasedSelections: selections,
}
return selectionsOld
otherSelections: Axis[]
codeBasedSelections: Selection[]
}
export async function getEventForSelectWithPoint({
@ -209,102 +85,85 @@ export async function getEventForSelectWithPoint({
}
}
let _artifact = engineCommandManager.artifactGraph.get(data.entity_id)
const codeRefs = getCodeRefsByArtifactId(
data.entity_id,
engineCommandManager.artifactGraph
)
if (_artifact && codeRefs) {
if (!_artifact)
return {
type: 'Set selection',
data: { selectionType: 'singleCodeCursor' },
}
if (_artifact.type === 'solid2D') {
const codeRef = getSolid2dCodeRef(
_artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return null
return {
type: 'Set selection',
data: {
selectionType: 'singleCodeCursor',
selection: { range: codeRef.range, type: 'solid2D' },
},
}
}
if (_artifact.type === 'cap') {
const codeRef = getCapCodeRef(_artifact, engineCommandManager.artifactGraph)
if (err(codeRef)) return null
return {
type: 'Set selection',
data: {
selectionType: 'singleCodeCursor',
selection: {
artifact: _artifact,
codeRef: codeRefs[0],
range: codeRef.range,
type: _artifact?.subType === 'end' ? 'end-cap' : 'start-cap',
},
},
}
}
// if (!_artifact)
// return {
// type: 'Set selection',
// data: { selectionType: 'singleCodeCursor' },
// }
// if (_artifact.type === 'solid2D') {
// const codeRef = getSolid2dCodeRef(
// _artifact,
// engineCommandManager.artifactGraph
// )
// if (err(codeRef)) return null
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// // selection: { range: codeRef.range, type: 'solid2D' },
// },
// }
// }
// if (_artifact.type === 'cap') {
// const codeRef = getCapCodeRef(_artifact, engineCommandManager.artifactGraph)
// if (err(codeRef)) return null
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: {
// range: codeRef.range,
// type: _artifact?.subType === 'end' ? 'end-cap' : 'start-cap',
// },
// },
// }
// }
// if (_artifact.type === 'wall') {
// const codeRef = getWallCodeRef(
// _artifact,
// engineCommandManager.artifactGraph
// )
// if (err(codeRef)) return null
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: codeRef.range, type: 'extrude-wall' },
// },
// }
// }
// if (_artifact.type === 'segment' || _artifact.type === 'path') {
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: _artifact.codeRef.range, type: 'default' },
// },
// }
// }
// if (_artifact.type === 'sweepEdge') {
// const codeRef = getSweepEdgeCodeRef(
// _artifact,
// engineCommandManager.artifactGraph
// )
// if (err(codeRef)) return null
// if (_artifact?.subType === 'adjacent') {
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: codeRef.range, type: 'adjacent-edge' },
// },
// }
// }
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range: codeRef.range, type: 'edge' },
// },
// }
// }
if (_artifact.type === 'wall') {
const codeRef = getWallCodeRef(
_artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return null
return {
type: 'Set selection',
data: {
selectionType: 'singleCodeCursor',
selection: { range: codeRef.range, type: 'extrude-wall' },
},
}
}
if (_artifact.type === 'segment' || _artifact.type === 'path') {
return {
type: 'Set selection',
data: {
selectionType: 'singleCodeCursor',
selection: { range: _artifact.codeRef.range, type: 'default' },
},
}
}
if (_artifact.type === 'sweepEdge') {
const codeRef = getSweepEdgeCodeRef(
_artifact,
engineCommandManager.artifactGraph
)
if (err(codeRef)) return null
if (_artifact?.subType === 'adjacent') {
return {
type: 'Set selection',
data: {
selectionType: 'singleCodeCursor',
selection: { range: codeRef.range, type: 'adjacent-edge' },
},
}
}
return {
type: 'Set selection',
data: {
selectionType: 'singleCodeCursor',
selection: { range: codeRef.range, type: 'edge' },
},
}
}
return null
}
@ -323,56 +182,36 @@ export function getEventForSegmentSelection(
},
}
}
// console.log('group', group?.userData.)
const id = group?.userData?.id
if (!id) return null
const artifact = engineCommandManager.artifactGraph.get(id)
const codeRefs = getCodeRefsByArtifactId(
id,
engineCommandManager.artifactGraph
const pathToNode = group?.userData?.pathToNode
if (!pathToNode) return null
// previous drags don't update ast for efficiency reasons
// So we want to make sure we have and updated ast with
// accurate source ranges
const updatedAst = parse(codeManager.code)
if (err(updatedAst)) return null
const nodeMeta = getNodeFromPath<CallExpression>(
updatedAst,
pathToNode,
'CallExpression'
)
console.log('artifact', artifact, group.userData)
if (!artifact || !codeRefs) return null
if (err(nodeMeta)) return null
const node = nodeMeta.node
const range: SourceRange = [node.start, node.end]
return {
type: 'Set selection',
data: {
selectionType: 'singleCodeCursor',
selection: {
artifact,
codeRef: codeRefs[0],
},
selection: { range, type: 'default' },
},
}
// const pathToNode = group?.userData?.pathToNode
// if (!pathToNode) return null
// // previous drags don't update ast for efficiency reasons
// // So we want to make sure we have and updated ast with
// // accurate source ranges
// const updatedAst = parse(codeManager.code)
// if (err(updatedAst)) return null
// const nodeMeta = getNodeFromPath<CallExpression>(
// updatedAst,
// pathToNode,
// 'CallExpression'
// )
// if (err(nodeMeta)) return null
// const node = nodeMeta.node
// const range: SourceRange = [node.start, node.end]
// return {
// type: 'Set selection',
// data: {
// selectionType: 'singleCodeCursor',
// selection: { range, type: 'default' },
// },
// }
}
export function handleSelectionBatch({
selections,
}: {
selections: Selections__old
selections: Selections
}): {
engineEvents: Models['WebSocketRequest_type'][]
codeMirrorSelection: EditorSelection
@ -413,7 +252,7 @@ export function handleSelectionBatch({
}
}
type SelectionToEngine = { type: Selection__old['type']; id: string }
type SelectionToEngine = { type: Selection['type']; id: string }
export function processCodeMirrorRanges({
codeMirrorRanges,
@ -421,15 +260,14 @@ export function processCodeMirrorRanges({
isShiftDown,
}: {
codeMirrorRanges: readonly SelectionRange[]
selectionRanges: Selections__old
selectionRanges: Selections
isShiftDown: boolean
}): null | {
modelingEvent: ModelingMachineEvent
engineEvents: Models['WebSocketRequest_type'][]
} {
const isChange =
// todo should this take old or new selections?
codeMirrorRanges.length !== selectionRanges?.codeBasedSelections?.length ||
codeMirrorRanges.length !== selectionRanges.codeBasedSelections.length ||
codeMirrorRanges.some(({ from, to }, i) => {
return (
from !== selectionRanges.codeBasedSelections[i].range[0] ||
@ -438,7 +276,7 @@ export function processCodeMirrorRanges({
})
if (!isChange) return null
const codeBasedSelections: Selections__old['codeBasedSelections'] =
const codeBasedSelections: Selections['codeBasedSelections'] =
codeMirrorRanges.map(({ from, to }) => {
return {
type: 'default',
@ -447,15 +285,6 @@ export function processCodeMirrorRanges({
})
const idBasedSelections: SelectionToEngine[] =
codeToIdSelections(codeBasedSelections)
const artifacts: Selection[] = []
for (const { id } of idBasedSelections) {
const artifact = engineCommandManager.artifactGraph.get(id)
const codeRefs = getCodeRefsByArtifactId(
id,
engineCommandManager.artifactGraph
)
if (artifact && codeRefs) artifacts.push({ artifact, codeRef: codeRefs[0] })
}
if (!selectionRanges) return null
updateSceneObjectColors(codeBasedSelections)
@ -466,7 +295,7 @@ export function processCodeMirrorRanges({
selectionType: 'mirrorCodeMirrorSelections',
selection: {
otherSelections: isShiftDown ? selectionRanges.otherSelections : [],
graphSelections: artifacts,
codeBasedSelections,
},
},
},
@ -474,7 +303,7 @@ export function processCodeMirrorRanges({
}
}
function updateSceneObjectColors(codeBasedSelections: Selection__old[]) {
function updateSceneObjectColors(codeBasedSelections: Selection[]) {
const updated = kclManager.ast
Object.values(sceneEntitiesManager.activeSegments).forEach((segmentGroup) => {
@ -529,7 +358,7 @@ function resetAndSetEngineEntitySelectionCmds(
]
}
export function isSketchPipe(selectionRanges: Selections__old) {
export function isSketchPipe(selectionRanges: Selections) {
if (!isSingleCursorInPipe(selectionRanges, kclManager.ast)) return false
return isCursorInSketchCommandRange(
engineCommandManager.artifactGraph,
@ -538,14 +367,14 @@ export function isSketchPipe(selectionRanges: Selections__old) {
}
export function isSelectionLastLine(
selectionRanges: Selections__old,
selectionRanges: Selections,
code: string,
i = 0
) {
return selectionRanges.codeBasedSelections[i].range[1] === code.length
}
export function isRangeBetweenCharacters(selectionRanges: Selections__old) {
export function isRangeBetweenCharacters(selectionRanges: Selections) {
return (
selectionRanges.codeBasedSelections.length === 1 &&
selectionRanges.codeBasedSelections[0].range[0] === 0 &&
@ -554,14 +383,11 @@ export function isRangeBetweenCharacters(selectionRanges: Selections__old) {
}
export type CommonASTNode = {
selection: Selection__old
selection: Selection
ast: Program
}
function buildCommonNodeFromSelection(
selectionRanges: Selections__old,
i: number
) {
function buildCommonNodeFromSelection(selectionRanges: Selections, i: number) {
return {
selection: selectionRanges.codeBasedSelections[i],
ast: kclManager.ast,
@ -594,7 +420,7 @@ function nodeHasCircle(node: CommonASTNode) {
})
}
export function canSweepSelection(selection: Selections__old) {
export function canSweepSelection(selection: Selections) {
const commonNodes = selection.codeBasedSelections.map((_, i) =>
buildCommonNodeFromSelection(selection, i)
)
@ -607,7 +433,7 @@ export function canSweepSelection(selection: Selections__old) {
)
}
export function canFilletSelection(selection: Selections__old) {
export function canFilletSelection(selection: Selections) {
const commonNodes = selection.codeBasedSelections.map((_, i) =>
buildCommonNodeFromSelection(selection, i)
) // TODO FILLET DUMMY PLACEHOLDER
@ -618,7 +444,7 @@ export function canFilletSelection(selection: Selections__old) {
)
}
function canExtrudeSelectionItem(selection: Selections__old, i: number) {
function canExtrudeSelectionItem(selection: Selections, i: number) {
const isolatedSelection = {
...selection,
codeBasedSelections: [selection.codeBasedSelections[i]],
@ -633,7 +459,7 @@ function canExtrudeSelectionItem(selection: Selections__old, i: number) {
}
// This accounts for non-geometry selections under "other"
export type ResolvedSelectionType = [Selection__old['type'] | 'other', number]
export type ResolvedSelectionType = [Selection['type'] | 'other', number]
/**
* In the future, I'd like this function to properly return the type of each selected entity based on
@ -643,7 +469,7 @@ export type ResolvedSelectionType = [Selection__old['type'] | 'other', number]
* @returns
*/
export function getSelectionType(
selection?: Selections__old
selection?: Selections
): ResolvedSelectionType[] {
if (!selection) return []
const extrudableCount = selection.codeBasedSelections.filter((_, i) => {
@ -660,7 +486,7 @@ export function getSelectionType(
}
export function getSelectionTypeDisplayText(
selection?: Selections__old
selection?: Selections
): string | null {
const selectionsByType = getSelectionType(selection)
@ -692,7 +518,7 @@ export function canSubmitSelectionArg(
}
function codeToIdSelections(
codeBasedSelections: Selection__old[]
codeBasedSelections: Selection[]
): SelectionToEngine[] {
return codeBasedSelections
.flatMap(({ type, range, ...rest }): null | SelectionToEngine[] => {
@ -858,13 +684,13 @@ export async function sendSelectEventToEngine(
export function updateSelections(
pathToNodeMap: PathToNodeMap,
prevSelectionRanges: Selections__old,
prevSelectionRanges: Selections,
ast: Program | Error
): Selections__old | Error {
): Selections | Error {
if (err(ast)) return ast
const newSelections = Object.entries(pathToNodeMap)
.map(([index, pathToNode]): Selection__old | undefined => {
.map(([index, pathToNode]): Selection | undefined => {
const nodeMeta = getNodeFromPath<Expr>(ast, pathToNode)
if (err(nodeMeta)) return undefined
const node = nodeMeta.node
@ -873,7 +699,7 @@ export function updateSelections(
type: prevSelectionRanges.codeBasedSelections[Number(index)]?.type,
}
})
.filter((x?: Selection__old) => x !== undefined) as Selection__old[]
.filter((x?: Selection) => x !== undefined) as Selection[]
return {
codeBasedSelections:
@ -883,74 +709,3 @@ export function updateSelections(
otherSelections: prevSelectionRanges.otherSelections,
}
}
// using artifact as the selection is maybe not such a good idea.
// is the artifact stable, once you add a constrain, there will a new artifact graph
// then the ids will not match up
export function updateSelections2(
pathToNodeMap: PathToNodeMap,
prevSelectionRanges: Selections,
ast: Program | Error
): Selections | Error {
if (err(ast)) return ast
const newSelections = Object.entries(pathToNodeMap)
.map(([index, pathToNode]): Selection | undefined => {
const previousSelection =
prevSelectionRanges.graphSelections[Number(index)]
const nodeMeta = getNodeFromPath<Expr>(ast, pathToNode)
if (err(nodeMeta)) return undefined
const node = nodeMeta.node
let artifact: Artifact | null = null
for (const [id, a] of engineCommandManager.artifactGraph) {
if (previousSelection.artifact.type === a.type) {
const codeRefs = getCodeRefsByArtifactId(
id,
engineCommandManager.artifactGraph
)
console.log('codeRef', codeRefs)
if (!codeRefs) continue
if (
JSON.stringify(codeRefs[0].pathToNode) ===
JSON.stringify(pathToNode)
) {
artifact = a
console.log('found artifact', a)
break
}
}
// if (
// a.codeRef.range[0] === node.start &&
// a.codeRef.range[1] === node.end
// ) {
// artifact = a
// break
// }
}
if (!artifact) return undefined
return {
artifact: artifact,
codeRef: {
range: [node.start, node.end],
pathToNode: pathToNode,
},
// codeRef: {
// range: [node.start, node.end],
// pathToNode: pathToNode,
// },
}
// return {
// range: [node.start, node.end],
// type: prevSelectionRanges.codeBasedSelections[Number(index)]?.type,
// }
})
.filter((x?: Selection) => x !== undefined) as Selection[]
return {
graphSelections:
newSelections.length > 0
? newSelections
: prevSelectionRanges.graphSelections,
otherSelections: prevSelectionRanges.otherSelections,
}
}

View File

@ -7,7 +7,6 @@ import { ProgramMemory, Expr, parse } from 'lang/wasm'
import { useEffect, useRef, useState } from 'react'
import { executeAst } from 'lang/langHelpers'
import { err, trap } from 'lib/trap'
import { convertSelectionsToOld } from './selections'
const isValidVariableName = (name: string) =>
/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)
@ -35,10 +34,9 @@ export function useCalculateKclExpression({
} {
const { programMemory, code } = useKclContext()
const { context } = useModelingContext()
const selectionOld = convertSelectionsToOld(context.selectionRanges)
const selectionRange:
| (typeof selectionOld.codeBasedSelections)[number]['range']
| undefined = selectionOld.codeBasedSelections[0]?.range
| (typeof context.selectionRanges.codeBasedSelections)[number]['range']
| undefined = context.selectionRanges.codeBasedSelections[0]?.range
const inputRef = useRef<HTMLInputElement>(null)
const [availableVarInfo, setAvailableVarInfo] = useState<
ReturnType<typeof findAllPreviousVariables>

View File

@ -3,13 +3,12 @@ import { kclManager } from 'lib/singletons'
import { useKclContext } from 'lang/KclProvider'
import { findAllPreviousVariables } from 'lang/queryAst'
import { useEffect, useState } from 'react'
import { convertSelectionsToOld } from './selections'
export function usePreviousVariables() {
const { programMemory, code } = useKclContext()
const { context } = useModelingContext()
const selectionRange = convertSelectionsToOld(context.selectionRanges)
.codeBasedSelections[0]?.range || [code.length, code.length]
const selectionRange = context.selectionRanges.codeBasedSelections[0]
?.range || [code.length, code.length]
const [previousVariablesInfo, setPreviousVariablesInfo] = useState<
ReturnType<typeof findAllPreviousVariables>
>({

View File

@ -5,14 +5,14 @@ import {
CommandArgumentWithName,
KclCommandValue,
} from 'lib/commandTypes'
import { Selections__old } from 'lib/selections'
import { Selections } from 'lib/selections'
import { getCommandArgumentKclValuesOnly } from 'lib/commandUtils'
export type CommandBarContext = {
commands: Command[]
selectedCommand?: Command
currentArgument?: CommandArgument<unknown> & { name: string }
selectionRanges: Selections__old
selectionRanges: Selections
argumentsToSubmit: { [x: string]: unknown }
}

View File

@ -5,14 +5,7 @@ import {
parse,
recast,
} from 'lang/wasm'
import {
Axis,
convertSelectionsToOld,
convertSelectionToOld,
Selections,
Selection,
updateSelections,
} from 'lib/selections'
import { Axis, Selection, Selections, updateSelections } from 'lib/selections'
import { assign, fromPromise, setup } from 'xstate'
import { SidebarType } from 'components/ModelingSidebar/ModelingPanes'
import {
@ -306,7 +299,7 @@ export const modelingMachineDefaultContext: ModelingMachineContext = {
selection: [],
selectionRanges: {
otherSelections: [],
graphSelections: [],
codeBasedSelections: [],
},
sketchDetails: {
sketchPathToNode: [],
@ -357,24 +350,18 @@ export const modelingMachine = setup({
'is editing existing sketch': ({ context: { sketchDetails } }) =>
isEditingExistingSketch({ sketchDetails }),
'Can make selection horizontal': ({ context: { selectionRanges } }) => {
const info = horzVertInfo(
convertSelectionsToOld(selectionRanges),
'horizontal'
)
const info = horzVertInfo(selectionRanges, 'horizontal')
if (trap(info)) return false
return info.enabled
},
'Can make selection vertical': ({ context: { selectionRanges } }) => {
const info = horzVertInfo(
convertSelectionsToOld(selectionRanges),
'vertical'
)
const info = horzVertInfo(selectionRanges, 'vertical')
if (trap(info)) return false
return info.enabled
},
'Can constrain horizontal distance': ({ context: { selectionRanges } }) => {
const info = horzVertDistanceInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'setHorzDistance',
})
if (trap(info)) return false
@ -382,59 +369,47 @@ export const modelingMachine = setup({
},
'Can constrain vertical distance': ({ context: { selectionRanges } }) => {
const info = horzVertDistanceInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'setVertDistance',
})
if (trap(info)) return false
return info.enabled
},
'Can constrain ABS X': ({ context: { selectionRanges } }) => {
const info = absDistanceInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
constraint: 'xAbs',
})
const info = absDistanceInfo({ selectionRanges, constraint: 'xAbs' })
if (trap(info)) return false
return info.enabled
},
'Can constrain ABS Y': ({ context: { selectionRanges } }) => {
const info = absDistanceInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
constraint: 'yAbs',
})
const info = absDistanceInfo({ selectionRanges, constraint: 'yAbs' })
if (trap(info)) return false
return info.enabled
},
'Can constrain angle': ({ context: { selectionRanges } }) => {
const angleBetween = angleBetweenInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
})
const angleBetween = angleBetweenInfo({ selectionRanges })
if (trap(angleBetween)) return false
const angleLength = angleLengthInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
angleOrLength: 'setAngle',
})
if (trap(angleLength)) return false
return angleBetween.enabled || angleLength.enabled
},
'Can constrain length': ({ context: { selectionRanges } }) => {
const angleLength = angleLengthInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
})
const angleLength = angleLengthInfo({ selectionRanges })
if (trap(angleLength)) return false
return angleLength.enabled
},
'Can constrain perpendicular distance': ({
context: { selectionRanges },
}) => {
const info = intersectInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
})
const info = intersectInfo({ selectionRanges })
if (trap(info)) return false
return info.enabled
},
'Can constrain horizontally align': ({ context: { selectionRanges } }) => {
const info = horzVertDistanceInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'setHorzDistance',
})
if (trap(info)) return false
@ -442,7 +417,7 @@ export const modelingMachine = setup({
},
'Can constrain vertically align': ({ context: { selectionRanges } }) => {
const info = horzVertDistanceInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'setHorzDistance',
})
if (trap(info)) return false
@ -450,7 +425,7 @@ export const modelingMachine = setup({
},
'Can constrain snap to X': ({ context: { selectionRanges } }) => {
const info = absDistanceInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'snapToXAxis',
})
if (trap(info)) return false
@ -458,23 +433,19 @@ export const modelingMachine = setup({
},
'Can constrain snap to Y': ({ context: { selectionRanges } }) => {
const info = absDistanceInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'snapToYAxis',
})
if (trap(info)) return false
return info.enabled
},
'Can constrain equal length': ({ context: { selectionRanges } }) => {
const info = setEqualLengthInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
})
const info = setEqualLengthInfo({ selectionRanges })
if (trap(info)) return false
return info.enabled
},
'Can canstrain parallel': ({ context: { selectionRanges } }) => {
const info = equalAngleInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
})
const info = equalAngleInfo({ selectionRanges })
if (err(info)) return false
return info.enabled
},
@ -484,7 +455,7 @@ export const modelingMachine = setup({
}) => {
if (event.type !== 'Constrain remove constraints') return false
const info = removeConstrainingValuesInfo({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
pathToNodes: event.data && [event.data],
})
if (trap(info)) return false
@ -665,14 +636,10 @@ export const modelingMachine = setup({
'AST delete selection': ({ context: { selectionRanges } }) => {
;(async () => {
let ast = kclManager.ast
const oldSelection = convertSelectionToOld(
selectionRanges.graphSelections[0]
)
if (!oldSelection) return
const modifiedAst = await deleteFromSelection(
ast,
oldSelection,
selectionRanges.codeBasedSelections[0],
kclManager.programMemory,
getFaceDetails
)
@ -742,7 +709,7 @@ export const modelingMachine = setup({
up: sketchDetails.yAxis,
position: sketchDetails.origin,
maybeModdedAst: kclManager.ast,
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
})
sceneInfra.resetMouseListeners()
sceneEntitiesManager.setupSketchIdleCallbacks({
@ -972,7 +939,7 @@ export const modelingMachine = setup({
> & { data?: PathToNode }
}) => {
const constraint = applyRemoveConstrainingValues({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
pathToNodes: data && [data],
})
if (trap(constraint)) return
@ -991,7 +958,7 @@ export const modelingMachine = setup({
selectionType: 'completeSelection',
selection: updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
),
}
@ -1004,7 +971,7 @@ export const modelingMachine = setup({
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
}) => {
const constraint = applyConstraintHorzVert(
convertSelectionsToOld(selectionRanges),
selectionRanges,
'horizontal',
kclManager.ast,
kclManager.programMemory
@ -1025,7 +992,7 @@ export const modelingMachine = setup({
selectionType: 'completeSelection',
selection: updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
),
}
@ -1038,7 +1005,7 @@ export const modelingMachine = setup({
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
}) => {
const constraint = applyConstraintHorzVert(
convertSelectionsToOld(selectionRanges),
selectionRanges,
'vertical',
kclManager.ast,
kclManager.programMemory
@ -1059,7 +1026,7 @@ export const modelingMachine = setup({
selectionType: 'completeSelection',
selection: updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
),
}
@ -1072,7 +1039,7 @@ export const modelingMachine = setup({
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
}) => {
const constraint = applyConstraintHorzVertAlign({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'setVertDistance',
})
if (trap(constraint)) return
@ -1089,7 +1056,7 @@ export const modelingMachine = setup({
if (!updatedAst) return
const updatedSelectionRanges = updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
)
return {
@ -1105,7 +1072,7 @@ export const modelingMachine = setup({
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
}) => {
const constraint = applyConstraintHorzVertAlign({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'setHorzDistance',
})
if (trap(constraint)) return
@ -1122,7 +1089,7 @@ export const modelingMachine = setup({
if (!updatedAst) return
const updatedSelectionRanges = updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
)
return {
@ -1138,7 +1105,7 @@ export const modelingMachine = setup({
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
}) => {
const constraint = applyConstraintAxisAlign({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'snapToXAxis',
})
if (err(constraint)) return false
@ -1155,7 +1122,7 @@ export const modelingMachine = setup({
if (!updatedAst) return
const updatedSelectionRanges = updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
)
return {
@ -1171,7 +1138,7 @@ export const modelingMachine = setup({
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
}) => {
const constraint = applyConstraintAxisAlign({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
constraint: 'snapToYAxis',
})
if (trap(constraint)) return false
@ -1188,7 +1155,7 @@ export const modelingMachine = setup({
if (!updatedAst) return
const updatedSelectionRanges = updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
)
return {
@ -1204,7 +1171,7 @@ export const modelingMachine = setup({
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
}) => {
const constraint = applyConstraintEqualAngle({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
})
if (trap(constraint)) return false
const { modifiedAst, pathToNodeMap } = constraint
@ -1225,7 +1192,7 @@ export const modelingMachine = setup({
if (!updatedAst) return
const updatedSelectionRanges = updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
)
return {
@ -1241,7 +1208,7 @@ export const modelingMachine = setup({
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
}) => {
const constraint = applyConstraintEqualLength({
selectionRanges: convertSelectionsToOld(selectionRanges),
selectionRanges,
})
if (trap(constraint)) return false
const { modifiedAst, pathToNodeMap } = constraint
@ -1257,7 +1224,7 @@ export const modelingMachine = setup({
if (!updatedAst) return
const updatedSelectionRanges = updateSelections(
pathToNodeMap,
convertSelectionsToOld(selectionRanges),
selectionRanges,
updatedAst.newAst
)
return {

View File

@ -251,14 +251,18 @@ export function getAutoUpdater(): AppUpdater {
return autoUpdater
}
export async function checkForUpdates(autoUpdater: AppUpdater) {
// TODO: figure out how to get the update modal back
const result = await autoUpdater.checkForUpdatesAndNotify()
console.log(result)
}
app.on('ready', () => {
const autoUpdater = getAutoUpdater()
setTimeout(() => {
autoUpdater.checkForUpdates().catch(reportRejection)
}, 1000)
checkForUpdates(autoUpdater).catch(reportRejection)
const fifteenMinutes = 15 * 60 * 1000
setInterval(() => {
autoUpdater.checkForUpdates().catch(reportRejection)
checkForUpdates(autoUpdater).catch(reportRejection)
}, fifteenMinutes)
autoUpdater.on('update-available', (info) => {
@ -267,11 +271,6 @@ app.on('ready', () => {
autoUpdater.on('update-downloaded', (info) => {
console.log('update-downloaded', info)
mainWindow?.webContents.send('update-downloaded', info.version)
})
ipcMain.handle('app.restart', () => {
autoUpdater.quitAndInstall()
})
})

View File

@ -15,9 +15,6 @@ const startDeviceFlow = (host: string): Promise<string> =>
ipcRenderer.invoke('startDeviceFlow', host)
const loginWithDeviceFlow = (): Promise<string> =>
ipcRenderer.invoke('loginWithDeviceFlow')
const onUpdateDownloaded = (callback: (value: string) => void) =>
ipcRenderer.on('update-downloaded', (_event, value) => callback(value))
const appRestart = () => ipcRenderer.invoke('app.restart')
const isMac = os.platform() === 'darwin'
const isWindows = os.platform() === 'win32'
@ -126,6 +123,4 @@ contextBridge.exposeInMainWorld('electron', {
kittycad,
listMachines,
getMachineApiIp,
onUpdateDownloaded,
appRestart,
})

View File

@ -1526,9 +1526,8 @@ dependencies = [
[[package]]
name = "kittycad-modeling-cmds"
version = "0.2.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5128ba683e849388cac4214b65911c343842d559bec10827575c840a47733786"
version = "0.2.62"
source = "git+https://github.com/KittyCAD/modeling-api?branch=achalmers/no-more-jsonschema#a253330a9cd656afbc5ee04490acca5ea5337af0"
dependencies = [
"anyhow",
"chrono",
@ -1552,8 +1551,18 @@ dependencies = [
[[package]]
name = "kittycad-modeling-cmds-macros"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0cdc505a33bfffb87c317435ec41ced8f73474217cf30db685e479bf289757e"
source = "git+https://github.com/KittyCAD/modeling-api?branch=achalmers/no-more-jsonschema#a253330a9cd656afbc5ee04490acca5ea5337af0"
dependencies = [
"kittycad-modeling-cmds-macros-impl",
"proc-macro2",
"quote",
"syn 2.0.77",
]
[[package]]
name = "kittycad-modeling-cmds-macros-impl"
version = "0.1.9"
source = "git+https://github.com/KittyCAD/modeling-api?branch=achalmers/no-more-jsonschema#a253330a9cd656afbc5ee04490acca5ea5337af0"
dependencies = [
"proc-macro2",
"quote",

View File

@ -73,7 +73,7 @@ members = [
http = "0.2.12"
kittycad = { version = "0.3.20", default-features = false, features = ["js", "requests"] }
kittycad-modeling-session = "0.1.4"
kittycad-modeling-cmds = { version = "0.2.61", features = ["websocket"] }
kittycad-modeling-cmds = { version = "0.2.62", features = ["websocket"] }
[[test]]
name = "executor"
@ -84,6 +84,6 @@ name = "modify"
path = "tests/modify/main.rs"
# Example: how to point modeling-api at a different repo (e.g. a branch or a local clone)
#[patch."https://github.com/KittyCAD/modeling-api"]
#kittycad-modeling-cmds = { path = "../../../modeling-api/modeling-cmds" }
#kittycad-modeling-session = { path = "../../../modeling-api/modeling-session" }
[patch.crates-io]
kittycad-modeling-cmds = { git = "https://github.com/KittyCAD/modeling-api", branch = "achalmers/no-more-jsonschema" }

View File

@ -520,7 +520,7 @@ pub fn get_autocomplete_snippet_from_schema(
let mut fn_docs = String::new();
fn_docs.push_str("{\n");
// Let's print out the object's properties.
let mut i = index;
let mut i = 0;
for (prop_name, prop) in obj_val.properties.iter() {
if prop_name.starts_with('_') {
continue;
@ -532,15 +532,15 @@ pub fn get_autocomplete_snippet_from_schema(
continue;
}
if let Some((new_index, snippet)) = get_autocomplete_snippet_from_schema(prop, i)? {
if let Some((_, snippet)) = get_autocomplete_snippet_from_schema(prop, index + i)? {
fn_docs.push_str(&format!("\t{}: {},\n", prop_name, snippet));
i = new_index + 1;
i += 1;
}
}
fn_docs.push('}');
return Ok(Some((i - 1, fn_docs)));
return Ok(Some((index + i - 1, fn_docs)));
}
if let Some(array_val) = &o.array {
@ -589,7 +589,6 @@ pub fn get_autocomplete_snippet_from_schema(
if let Some(subschemas) = &o.subschemas {
let mut fn_docs = String::new();
let mut i = index;
if let Some(items) = &subschemas.one_of {
let mut had_enum_string = false;
let mut parsed_enum_values: Vec<String> = Vec::new();
@ -621,15 +620,13 @@ pub fn get_autocomplete_snippet_from_schema(
if had_enum_string && !parsed_enum_values.is_empty() {
return Ok(Some((index, parsed_enum_values[0].to_string())));
} else if let Some(item) = items.iter().next() {
if let Some((new_index, snippet)) = get_autocomplete_snippet_from_schema(item, index)? {
i = new_index + 1;
if let Some((_, snippet)) = get_autocomplete_snippet_from_schema(item, index)? {
fn_docs.push_str(&snippet);
}
}
} else if let Some(items) = &subschemas.any_of {
if let Some(item) = items.iter().next() {
if let Some((new_index, snippet)) = get_autocomplete_snippet_from_schema(item, index)? {
i = new_index + 1;
if let Some((_, snippet)) = get_autocomplete_snippet_from_schema(item, index)? {
fn_docs.push_str(&snippet);
}
}
@ -637,7 +634,7 @@ pub fn get_autocomplete_snippet_from_schema(
anyhow::bail!("unknown subschemas: {:#?}", subschemas);
}
return Ok(Some((i - 1, fn_docs)));
return Ok(Some((index, fn_docs)));
}
if let Some(schemars::schema::SingleOrVec::Single(single)) = &o.instance_type {
@ -918,10 +915,10 @@ mod tests {
r#"patternCircular3d({
arcDegrees: ${0:3.14},
axis: [${1:3.14}, ${2:3.14}, ${3:3.14}],
center: [${4:3.14}, ${5:3.14}, ${6:3.14}],
repetitions: ${7:10},
rotateDuplicates: ${8:false},
}, ${9:%})${}"#
center: [${2:3.14}, ${3:3.14}, ${4:3.14}],
repetitions: ${3:10},
rotateDuplicates: ${4:false},
}, ${5:%})${}"#
);
}
@ -945,36 +942,8 @@ mod tests {
snippet,
r#"circle({
center: [${0:3.14}, ${1:3.14}],
radius: ${2:3.14},
}, ${3:%})${}"#
);
}
#[test]
fn get_autocomplete_snippet_arc() {
let arc_fn: Box<dyn StdLibFn> = Box::new(crate::std::sketch::Arc);
let snippet = arc_fn.to_autocomplete_snippet().unwrap();
assert_eq!(
snippet,
r#"arc({
angleEnd: ${0:3.14},
angleStart: ${1:3.14},
radius: ${2:3.14},
}, ${3:%})${}"#
);
}
#[test]
fn get_autocomplete_snippet_pattern_linear_2d() {
let pattern_fn: Box<dyn StdLibFn> = Box::new(crate::std::patterns::PatternLinear2D);
let snippet = pattern_fn.to_autocomplete_snippet().unwrap();
assert_eq!(
snippet,
r#"patternLinear2d({
axis: [${0:3.14}, ${1:3.14}],
distance: ${2:3.14},
repetitions: ${3:10},
}, ${4:%})${}"#
radius: ${1:3.14},
}, ${2:%})${}"#
);
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 136 KiB