Files
modeling-app/src/lib/utils.ts

505 lines
15 KiB
TypeScript
Raw Normal View History

Sort imports (#6101) * add package.json Signed-off-by: Jess Frazelle <github@jessfraz.com> initial run; Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> more fixes Signed-off-by: Jess Frazelle <github@jessfraz.com> clientsidescne Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> paths Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> fix styles Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> combine Signed-off-by: Jess Frazelle <github@jessfraz.com> eslint rule Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> fixes Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> my ocd Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> constants file Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> no more import sceneInfra Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> try fix circular import Signed-off-by: Jess Frazelle <github@jessfraz.com> * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> --------- Signed-off-by: Jess Frazelle <github@jessfraz.com>
2025-04-01 23:54:26 -07:00
import type { Binary as BSONBinary } from 'bson'
import { v4 } from 'uuid'
Sort imports (#6101) * add package.json Signed-off-by: Jess Frazelle <github@jessfraz.com> initial run; Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> more fixes Signed-off-by: Jess Frazelle <github@jessfraz.com> clientsidescne Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> paths Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> fix styles Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> combine Signed-off-by: Jess Frazelle <github@jessfraz.com> eslint rule Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> fixes Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> my ocd Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> constants file Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> no more import sceneInfra Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> try fix circular import Signed-off-by: Jess Frazelle <github@jessfraz.com> * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> --------- Signed-off-by: Jess Frazelle <github@jessfraz.com>
2025-04-01 23:54:26 -07:00
import type { AnyMachineSnapshot } from 'xstate'
import type { CallExpressionKw, SourceRange } from '@src/lang/wasm'
Sort imports (#6101) * add package.json Signed-off-by: Jess Frazelle <github@jessfraz.com> initial run; Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> more fixes Signed-off-by: Jess Frazelle <github@jessfraz.com> clientsidescne Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> paths Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> fix styles Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> combine Signed-off-by: Jess Frazelle <github@jessfraz.com> eslint rule Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> fixes Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> my ocd Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> constants file Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> no more import sceneInfra Signed-off-by: Jess Frazelle <github@jessfraz.com> updates Signed-off-by: Jess Frazelle <github@jessfraz.com> try fix circular import Signed-off-by: Jess Frazelle <github@jessfraz.com> * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> --------- Signed-off-by: Jess Frazelle <github@jessfraz.com>
2025-04-01 23:54:26 -07:00
import { isDesktop } from '@src/lib/isDesktop'
import type { AsyncFn } from '@src/lib/types'
2024-04-03 19:38:16 +11:00
export const uuidv4 = v4
/**
* Get all labels for a keyword call expression.
*/
export function allLabels(callExpression: CallExpressionKw): string[] {
return callExpression.arguments.map((a) => a.label.name)
}
/**
* A safer type guard for arrays since the built-in Array.isArray() asserts `any[]`.
*/
export function isArray(val: any): val is unknown[] {
// eslint-disable-next-line no-restricted-syntax
return Array.isArray(val)
}
/**
* An alternative to `Object.keys()` that returns an array of keys with types.
*
* It's UNSAFE because because of TS's structural subtyping and how at runtime, you can
* extend a JS object with whatever keys you want.
*
* Why we shouldn't be extending objects with arbitrary keys at run time, the structural subtyping
* issue could be a confusing bug, for example, in the below snippet `myKeys` is typed as
* `('x' | 'y')[]` but is really `('x' | 'y' | 'name')[]`
* ```ts
* interface Point { x: number; y: number }
* interface NamedPoint { x: number; y: number; name: string }
*
* let point: Point = { x: 1, y: 2 }
* let namedPoint: NamedPoint = { x: 1, y: 2, name: 'A' }
*
* // Structural subtyping allows this assignment
* point = namedPoint // This is allowed because NamedPoint has all properties of Point
* const myKeys = unsafeTypedKeys(point) // typed as ('x' | 'y')[] but is really ('x' | 'y' | 'name')[]
* ```
*/
export function unsafeTypedKeys<T extends object>(obj: T): Array<keyof T> {
return Object.keys(obj) as Array<keyof T>
}
/*
* Predicate that checks if a value is not null and not undefined. This is
* useful for functions like Array::filter() and Array::find() that have
* overloads that accept a type guard.
*/
export function isNonNullable<T>(val: T): val is NonNullable<T> {
return val !== null && val !== undefined
}
export function isOverlap(a: SourceRange, b: SourceRange) {
const [startingRange, secondRange] = a[0] < b[0] ? [a, b] : [b, a]
const [lastOfFirst, firstOfSecond] = [startingRange[1], secondRange[0]]
return lastOfFirst >= firstOfSecond
}
export function getLength(a: [number, number], b: [number, number]): number {
const x = b[0] - a[0]
const y = b[1] - a[1]
return Math.sqrt(x * x + y * y)
}
Symbols overlay (#2033) * start of overlay work * add new icons * add constraint symbols * add three dots * add primary colours * refactor how we get constraint info for overlays * refactor how we get constraint info for overlays * get symbols working for tangential arc too * extra data on constraint info * add initial delete * fix types and circular dep issue after rebase * fix quirk with horz vert line overlays * fix setup and tear down of overlays * remove overlays that are too small * throttle overlay updates and prove tests selecting html instead of hardcoded px coords * initial show overaly on segment hover * remove overlays when tool is equipped * dounce overlay updates * tsc * make higlighting robust to small changes in source ranges * replace with variable for unconstrained values, and improve styles for popover * background tweak * make overlays unconstrain inputs * fix small regression * write query for finding related tag references * make delete segment safe * typo * un used imports * test deleteSegmentFromPipeExpression * add getConstraintInfo test * test removeSingleConstraintInfo * more tests * tsc * add tests for overlay buttons * rename tests * fmt * better naming structure * more reliablity * more test tweaks * fix selection test * add delete segments with overlays tests * dependant tag tests for segment delet * typo * test clean up * fix some perf issus * clean up * clean up * make things a little more dry * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * trigger ci * Make constraint hover popovers readable on light mode * Touch up the new variable dialog * Little touch-up to three-dot menu style * fix highlight issue * fmt * use optional chain * Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)" This reverts commit be3d61e4a303b0d9a792dddbfe8430cc58d46451. * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * disable var panel in sketch mode * fix overlay tests after mergi in main * test tweak * try fix ubuntu * fmt * more test tweaks * tweak * tweaks --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Frank Noirot <frank@kittycad.io>
2024-05-24 20:54:42 +10:00
/**
* Calculates the angle in degrees between two points in a 2D space.
* The angle is normalized to the range [-180, 180].
*
* @param a The first point as a tuple [x, y].
* @param b The second point as a tuple [x, y].
* @returns The normalized angle in degrees between point a and point b.
*/
export function getAngle(a: [number, number], b: [number, number]): number {
const x = b[0] - a[0]
const y = b[1] - a[1]
return normaliseAngle((Math.atan2(y, x) * 180) / Math.PI)
}
Symbols overlay (#2033) * start of overlay work * add new icons * add constraint symbols * add three dots * add primary colours * refactor how we get constraint info for overlays * refactor how we get constraint info for overlays * get symbols working for tangential arc too * extra data on constraint info * add initial delete * fix types and circular dep issue after rebase * fix quirk with horz vert line overlays * fix setup and tear down of overlays * remove overlays that are too small * throttle overlay updates and prove tests selecting html instead of hardcoded px coords * initial show overaly on segment hover * remove overlays when tool is equipped * dounce overlay updates * tsc * make higlighting robust to small changes in source ranges * replace with variable for unconstrained values, and improve styles for popover * background tweak * make overlays unconstrain inputs * fix small regression * write query for finding related tag references * make delete segment safe * typo * un used imports * test deleteSegmentFromPipeExpression * add getConstraintInfo test * test removeSingleConstraintInfo * more tests * tsc * add tests for overlay buttons * rename tests * fmt * better naming structure * more reliablity * more test tweaks * fix selection test * add delete segments with overlays tests * dependant tag tests for segment delet * typo * test clean up * fix some perf issus * clean up * clean up * make things a little more dry * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * trigger ci * Make constraint hover popovers readable on light mode * Touch up the new variable dialog * Little touch-up to three-dot menu style * fix highlight issue * fmt * use optional chain * Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)" This reverts commit be3d61e4a303b0d9a792dddbfe8430cc58d46451. * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * disable var panel in sketch mode * fix overlay tests after mergi in main * test tweak * try fix ubuntu * fmt * more test tweaks * tweak * tweaks --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Frank Noirot <frank@kittycad.io>
2024-05-24 20:54:42 +10:00
/**
* Normalizes an angle to the range [-180, 180].
*
* This function takes an angle in degrees and normalizes it so that the result is always within the range of -180 to 180 degrees. This is useful for ensuring consistent angle measurements where the direction (positive or negative) is significant.
*
* @param angle The angle in degrees to be normalized.
* @returns The normalized angle in the range [-180, 180].
*/
export function normaliseAngle(angle: number): number {
const result = ((angle % 360) + 360) % 360
return result > 180 ? result - 360 : result
2022-11-26 08:34:23 +11:00
}
export function throttle<T>(
func: (args: T) => any,
wait: number
): (args: T) => any {
let timeout: ReturnType<typeof setTimeout> | null
let latestArgs: T
let latestTimestamp: number
function later() {
timeout = null
func(latestArgs)
}
function throttled(args: T) {
const currentTimestamp = Date.now()
latestArgs = args
if (!latestTimestamp || currentTimestamp - latestTimestamp >= wait) {
latestTimestamp = currentTimestamp
func(latestArgs)
} else if (!timeout) {
timeout = setTimeout(later, wait - (currentTimestamp - latestTimestamp))
}
}
return throttled
}
2023-08-09 20:49:10 +10:00
// takes a function and executes it after the wait time, if the function is called again before the wait time is up, the timer is reset
export function deferExecution<T>(func: (args: T) => any, wait: number) {
let timeout: ReturnType<typeof setTimeout> | null
let latestArgs: T
function later() {
timeout = null
func(latestArgs)
}
function deferred(args: T) {
latestArgs = args
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(later, wait)
}
return deferred
}
/**
* Wrap an async function so that it can be called in a sync context, catching
* rejections.
*
* It's common to want to run an async function in a sync context, like an event
* handler or callback. But we want to catch errors.
*
* Note: The returned function doesn't block. This isn't magic.
*
* @param onReject This callback type is from Promise.prototype.catch.
*/
export function toSync<F extends AsyncFn<F>>(
fn: F,
onReject: (
reason: any
) => void | PromiseLike<void | null | undefined> | null | undefined
): (...args: Parameters<F>) => void {
return (...args: Parameters<F>) => {
void fn(...args).catch((...args) => {
console.error(...args)
return onReject(...args)
})
}
}
export function getNormalisedCoordinates(
e: PointerEvent | React.MouseEvent<HTMLDivElement, MouseEvent>,
elVideo: HTMLVideoElement,
streamDimensions: {
width: number
height: number
}
) {
const { left, top, width, height } = elVideo?.getBoundingClientRect()
const browserX = e.clientX - left
const browserY = e.clientY - top
2023-08-09 20:49:10 +10:00
return {
x: Math.round((browserX / width) * streamDimensions.width),
y: Math.round((browserY / height) * streamDimensions.height),
2023-08-09 20:49:10 +10:00
}
}
Client sketch scene (#1271) * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> * make tsc happ * better error msg * fix control point issue * basic code gen working for tangentialArc * partical fix for move with arcs * tangential arc move * fix * make eslint rules less annoying * inital refactor of some xstate stuff * more old tangential arc clean up stuff * more tweaks * add testing * tweak xstate inspect * temp remove test * update formating for less conflicts * fix state machine layout after merge * shrug, something weird with xstate typegen * renaming some xstate events * tweak numbers to make CI playwright happ * CI hacks * more CI hacks * more CI hacks * new hack strategy * run tests agian * make cmd bar less flaky * ci hacks * CI hacks * CI hacks * CI hacks * clean up * fix * still have constraint stuff to deal with * progress on move rules * update source ranges after no execute code-mod * typo * mvp working * hide show sketch overlay * match scaling * update arrow head style * animate line tool * bypass xstate for animations, much smoother * add new segment working with refactor needed for setup paper sketch * refactor setup paper sketch * tangantialArcTo drag animations working * tangential arc polish * cargo fmt * clippy * more clippy * mock canvas * last of clippy? * typo * more clippy stuff * move util function so they are shareable with typescript * migrate a bunch to rust and only rust * add arc center point for draft tangential ac * clippy tweak * delete uneeded test * Rough start to scaling arrow heads. The tangent arrow heads are basically nuked and replaced while the straight line sections are just rotated and repositioned, this means they miss out on updating scaling number after a screen size changes. Needs fixing * fix bug with tool tips * fix draft line start position Having drag the end of teh path before selecting a tooltip would result in the draft line starting where the path used to end, stale data * some progress with pan maybe * fmt * inital camera sync working For perspective camera at least * change three.js to use z-up * add grid * orthographic camera working with polish items TODO * fix zoom level when swapping camera * fix up camera/orbit changing on cam change (pan wasn't being respected) * tidy up * use orbit target instead of assuming scene center * dynamic fov working * animate orthographic to perspective and reverse * fix import * temp fix for batch commands * initial client side scene sketch working * remove hover log * FOV adjust fix * fix comment * tear down sketch and small tweaks * some progress with camera tweening * combine dollyZoom engine commands see https://github.com/KittyCAD/modeling-api/compare/kurt-perspective-settings?expand=1 and https://github.com/KittyCAD/engine/compare/kurt-perspective-settings?expand=1 * make tests happy (mocks) * fix tween to vertical/camera-up bug * tween to each axis with hacky solutions in there * fix startSketchOn planes * tidy startSketchOn * tweening okay for now I think * get sketching on default planes working * allow editing on all default planes * clean up enter and exit sketch logic * tidy * tidy * remove more default plane stuff * start of draft line * remove some annoying parts of the paper.js implementation * fix drag than equip line bug * comment * don't animate on skech tear down since it's used for draft line * remove more default plane shit * style draft line * refine dashed line * draft line set up and tear down mostly happy * add on click logic ready for draft lines * sketch mode with drag and draft mode working solidly now, straight segments only * default planes match colors, hover and select still TODO * hover and click logic working for default planes Now just need the code mode to fire to 'startSketchOn(...)' * select default planes * remove some logs * fix update infinite loop * start of orbitControls port to Franks control guards * hiding scenes at different times * scene hide on camera move should be respected by scroll zoom * basic hover working * Hook up user camera settings to ClientSideScene (#1334) * Refactor to not import utilities from Router.tsx * Stop tracking changes or formatting *.typegen.ts * Hook up cameraControls to ClientSideScene * Remove camera controls toggle from temp debug panel --------- Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch> * add select segment moves cursor * highlight segments yellow on hover * cursor ranges effect 2d line colors * fix constrainst i.e. make sure the sketch is rejiged * selecting nothing should remove selections * remove hardcoded strings * update get_tangential_arc_to_info rust util * initial drawing of tangential arcs in client scene * fix tangentialArc arrow head direction * correct userData types for tangential arcs * get tangential arc updates working Doesn't include draging the head of the tangential arc itself yet * spot of clean up * make selections work with tangential arcs * get draft tangential segment animated * fix initial click weirdness for adding new tangential line * couple tweaks * add grace pixels /threshold to raycast * redo arc dashes so that they spawn from the ccenter of the arc * fix multi drag bug * fmt * add temp solution for close * add default axis hover colors, still needs select logic * selection of axis works, just with out selection color * get axis selection colors working * fix outdate source ranges after drag problem * update moreNodePathFromSourceRange * fix ts-rs issue/workaround * fix default plane weirdness * fix tangential arc rounding issue * review clean up part 1 * review clean up part 2 Big state-diagram cull * clippy * typo * clippy * fix xstate types with typegen * fix types * clippy * catch error * fix test import issue Not sure exactly what was happening but guessing circular import that vite didn't like * add axis/plane info to sketch group tests * case changes because of rs-ts bug, can probably revert this later * start of playwright test fixes * reduce geo complexity for straight segments * fix cam adjust tests * Revert "Clean up vite build warnings (#1332)" This reverts commit c1f661ab5254458c3e9fdb396a31860a22c790f1. * selection e2e test fixed< * remove camToggle to allow playwright tests to pass * remove drag test too brittle and needs to be redone from the ground up anyway * trigger CI * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * fix last test * clean up part 3 * clean up part 4 * clean up part 5 * clean up sketch enter exit logic * fix engine side selections * default plane should not be selected form 'onDragEnd' i.e. rotating the camera should not mean the user acidently selects a plane * clean up state diagram around animating to sketch mode Embracing that the animation is async and puting the interdiate steps in the state diagram clean up some logic and solved some bugs at the same time * add test for multiple sketches * typo * make highlight more robust * type tweak * scale segmenst with distance from camera so they have a consistent pixel size/ screenspace size * Jess's advice * tsc and fmt * clean up part 6 remove integer from xstate names * clean up part 7 * integrate sequency in to camera moves * fix tests * update snapshot e2e * small snapshot change * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * trigger ci * Fix HomeLoaderData types * update std stuff * update kittycad rs client lib --------- Signed-off-by: Jess Frazelle <github@jessfraz.com> Co-authored-by: Jess Frazelle <github@jessfraz.com> Co-authored-by: Frank Noirot <frank@kittycad.io> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-02-11 12:59:00 +11:00
// TODO: Remove the empty platform type.
export type Platform = 'macos' | 'windows' | 'linux' | ''
export function platform(): Platform {
if (isDesktop()) {
const platform = window.electron.platform ?? ''
// https://nodejs.org/api/process.html#processplatform
switch (platform) {
case 'darwin':
return 'macos'
case 'win32':
return 'windows'
// We don't currently care to distinguish between these.
case 'android':
case 'freebsd':
case 'linux':
case 'openbsd':
case 'sunos':
return 'linux'
default:
2024-08-27 19:02:49 -04:00
console.error('Unknown desktop platform:', platform)
return ''
}
}
// navigator.platform is deprecated, but many browsers still support it, and
// it's more accurate than userAgent and userAgentData in Playwright.
if (
navigator.platform?.indexOf('Mac') === 0 ||
2024-08-27 19:02:49 -04:00
navigator.platform?.indexOf('iPhone') === 0 ||
navigator.platform?.indexOf('iPad') === 0 ||
// Vite tests running in HappyDOM.
navigator.platform?.indexOf('Darwin') >= 0
) {
return 'macos'
}
2024-08-27 19:02:49 -04:00
if (navigator.platform === 'Windows' || navigator.platform === 'Win32') {
return 'windows'
}
// Chrome only, but more accurate than userAgent.
let userAgentDataPlatform: unknown
if (
'userAgentData' in navigator &&
navigator.userAgentData &&
typeof navigator.userAgentData === 'object' &&
'platform' in navigator.userAgentData
) {
userAgentDataPlatform = navigator.userAgentData.platform
if (userAgentDataPlatform === 'macOS') return 'macos'
if (userAgentDataPlatform === 'Windows') return 'windows'
}
if (navigator.userAgent.indexOf('Mac') !== -1) {
return 'macos'
} else if (navigator.userAgent.indexOf('Win') !== -1) {
return 'windows'
} else if (navigator.userAgent.indexOf('Linux') !== -1) {
return 'linux'
}
console.error(
2024-08-27 19:02:49 -04:00
'Unknown web platform:',
navigator.platform,
userAgentDataPlatform,
navigator.userAgent
)
return ''
}
Client sketch scene (#1271) * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> * updates Signed-off-by: Jess Frazelle <github@jessfraz.com> * make tsc happ * better error msg * fix control point issue * basic code gen working for tangentialArc * partical fix for move with arcs * tangential arc move * fix * make eslint rules less annoying * inital refactor of some xstate stuff * more old tangential arc clean up stuff * more tweaks * add testing * tweak xstate inspect * temp remove test * update formating for less conflicts * fix state machine layout after merge * shrug, something weird with xstate typegen * renaming some xstate events * tweak numbers to make CI playwright happ * CI hacks * more CI hacks * more CI hacks * new hack strategy * run tests agian * make cmd bar less flaky * ci hacks * CI hacks * CI hacks * CI hacks * clean up * fix * still have constraint stuff to deal with * progress on move rules * update source ranges after no execute code-mod * typo * mvp working * hide show sketch overlay * match scaling * update arrow head style * animate line tool * bypass xstate for animations, much smoother * add new segment working with refactor needed for setup paper sketch * refactor setup paper sketch * tangantialArcTo drag animations working * tangential arc polish * cargo fmt * clippy * more clippy * mock canvas * last of clippy? * typo * more clippy stuff * move util function so they are shareable with typescript * migrate a bunch to rust and only rust * add arc center point for draft tangential ac * clippy tweak * delete uneeded test * Rough start to scaling arrow heads. The tangent arrow heads are basically nuked and replaced while the straight line sections are just rotated and repositioned, this means they miss out on updating scaling number after a screen size changes. Needs fixing * fix bug with tool tips * fix draft line start position Having drag the end of teh path before selecting a tooltip would result in the draft line starting where the path used to end, stale data * some progress with pan maybe * fmt * inital camera sync working For perspective camera at least * change three.js to use z-up * add grid * orthographic camera working with polish items TODO * fix zoom level when swapping camera * fix up camera/orbit changing on cam change (pan wasn't being respected) * tidy up * use orbit target instead of assuming scene center * dynamic fov working * animate orthographic to perspective and reverse * fix import * temp fix for batch commands * initial client side scene sketch working * remove hover log * FOV adjust fix * fix comment * tear down sketch and small tweaks * some progress with camera tweening * combine dollyZoom engine commands see https://github.com/KittyCAD/modeling-api/compare/kurt-perspective-settings?expand=1 and https://github.com/KittyCAD/engine/compare/kurt-perspective-settings?expand=1 * make tests happy (mocks) * fix tween to vertical/camera-up bug * tween to each axis with hacky solutions in there * fix startSketchOn planes * tidy startSketchOn * tweening okay for now I think * get sketching on default planes working * allow editing on all default planes * clean up enter and exit sketch logic * tidy * tidy * remove more default plane stuff * start of draft line * remove some annoying parts of the paper.js implementation * fix drag than equip line bug * comment * don't animate on skech tear down since it's used for draft line * remove more default plane shit * style draft line * refine dashed line * draft line set up and tear down mostly happy * add on click logic ready for draft lines * sketch mode with drag and draft mode working solidly now, straight segments only * default planes match colors, hover and select still TODO * hover and click logic working for default planes Now just need the code mode to fire to 'startSketchOn(...)' * select default planes * remove some logs * fix update infinite loop * start of orbitControls port to Franks control guards * hiding scenes at different times * scene hide on camera move should be respected by scroll zoom * basic hover working * Hook up user camera settings to ClientSideScene (#1334) * Refactor to not import utilities from Router.tsx * Stop tracking changes or formatting *.typegen.ts * Hook up cameraControls to ClientSideScene * Remove camera controls toggle from temp debug panel --------- Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch> * add select segment moves cursor * highlight segments yellow on hover * cursor ranges effect 2d line colors * fix constrainst i.e. make sure the sketch is rejiged * selecting nothing should remove selections * remove hardcoded strings * update get_tangential_arc_to_info rust util * initial drawing of tangential arcs in client scene * fix tangentialArc arrow head direction * correct userData types for tangential arcs * get tangential arc updates working Doesn't include draging the head of the tangential arc itself yet * spot of clean up * make selections work with tangential arcs * get draft tangential segment animated * fix initial click weirdness for adding new tangential line * couple tweaks * add grace pixels /threshold to raycast * redo arc dashes so that they spawn from the ccenter of the arc * fix multi drag bug * fmt * add temp solution for close * add default axis hover colors, still needs select logic * selection of axis works, just with out selection color * get axis selection colors working * fix outdate source ranges after drag problem * update moreNodePathFromSourceRange * fix ts-rs issue/workaround * fix default plane weirdness * fix tangential arc rounding issue * review clean up part 1 * review clean up part 2 Big state-diagram cull * clippy * typo * clippy * fix xstate types with typegen * fix types * clippy * catch error * fix test import issue Not sure exactly what was happening but guessing circular import that vite didn't like * add axis/plane info to sketch group tests * case changes because of rs-ts bug, can probably revert this later * start of playwright test fixes * reduce geo complexity for straight segments * fix cam adjust tests * Revert "Clean up vite build warnings (#1332)" This reverts commit c1f661ab5254458c3e9fdb396a31860a22c790f1. * selection e2e test fixed< * remove camToggle to allow playwright tests to pass * remove drag test too brittle and needs to be redone from the ground up anyway * trigger CI * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * fix last test * clean up part 3 * clean up part 4 * clean up part 5 * clean up sketch enter exit logic * fix engine side selections * default plane should not be selected form 'onDragEnd' i.e. rotating the camera should not mean the user acidently selects a plane * clean up state diagram around animating to sketch mode Embracing that the animation is async and puting the interdiate steps in the state diagram clean up some logic and solved some bugs at the same time * add test for multiple sketches * typo * make highlight more robust * type tweak * scale segmenst with distance from camera so they have a consistent pixel size/ screenspace size * Jess's advice * tsc and fmt * clean up part 6 remove integer from xstate names * clean up part 7 * integrate sequency in to camera moves * fix tests * update snapshot e2e * small snapshot change * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * trigger ci * Fix HomeLoaderData types * update std stuff * update kittycad rs client lib --------- Signed-off-by: Jess Frazelle <github@jessfraz.com> Co-authored-by: Jess Frazelle <github@jessfraz.com> Co-authored-by: Frank Noirot <frank@kittycad.io> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-02-11 12:59:00 +11:00
export function isReducedMotion(): boolean {
return (
typeof window !== 'undefined' &&
window.matchMedia &&
// TODO/Note I (Kurt) think '(prefers-reduced-motion: reduce)' and '(prefers-reduced-motion)' are equivalent, but not 100% sure
window.matchMedia('(prefers-reduced-motion)').matches
)
}
export function XOR(bool1: boolean, bool2: boolean): boolean {
return (bool1 || bool2) && !(bool1 && bool2)
}
Migrate to XState v5 (#3735) * migrate settingsMachine * Guard events with properties instead * migrate settingsMachine * Migrate auth machine * Migrate file machine * Migrate depracated types * Migrate home machine * Migrate command bar machine * Version fixes * Migrate command bar machine * Migrate modeling machine * Migrate types, state.can, state.matches and state.nextEvents * Fix syntax * Pass in modelingState into editor manager instead of modeling event * Fix issue with missing command bar provider * Fix state transition * Fix type issue in Home * Make sure no guards rely on event type * Fix up command bar submission logic * Home machine tweaks to get things running * Fix AST fillet function args * Handle "Set selection" when it is called by actor onDone * Remove unused imports * A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest) * Fix injectin project to the fileTree machine * Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest)" This reverts commit 4b43ff69d1572c10992ed4c29678acbb9abf96d7. * A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest) * Re-run CI * Restore success toasts on file/folder deletion * Replace casting with guarding against event.type * Remove console.log Co-authored-by: Jonathan Tran <jonnytran@gmail.com> * Replace all instances of event casting with guards against event.type --------- Co-authored-by: Frank Noirot <frank@kittycad.io> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch> Co-authored-by: Jonathan Tran <jonnytran@gmail.com> Co-authored-by: Frank Noirot <frank@zoo.dev>
2024-09-09 19:59:36 +03:00
export function getActorNextEvents(snapshot: AnyMachineSnapshot) {
return [...new Set([...snapshot._nodes.flatMap((sn) => sn.ownEvents)])]
}
export const onMouseDragRegex = /-?\.?\b\d+\.?\d*\b/g
export function simulateOnMouseDragMatch(text: string) {
return text.match(onMouseDragRegex)
}
export function roundOff(num: number, precision: number = 2): number {
const x = Math.pow(10, precision)
return Math.round(num * x) / x
}
/**
* Determine if the number as a string has any precision in the decimal places
* '1' -> 0
* '1.0' -> 1
* '1.01' -> 2
*/
function getPrecision(text: string): number {
const wholeFractionSplit = text.split('.')
const precision =
wholeFractionSplit.length === 2 ? wholeFractionSplit[1].split('').length : 0
return precision
}
/**
* Determines if a number string has a leading digit
* 0.1 -> yes
* -0.1 -> yes
* .1 -> no
* 10.1 -> no
* The text.split('.') should evaluate to ['','<decimals>']
*/
export function hasLeadingZero(text: string): boolean {
const wholeFractionSplit = text.split('.')
return wholeFractionSplit.length === 2
? wholeFractionSplit[0] === '0' || wholeFractionSplit[0] === '-0'
: false
}
export function hasDigitsLeftOfDecimal(text: string): boolean | undefined {
const wholeFractionSplit = text.split('.')
if (wholeFractionSplit.length === 2) {
const wholeNumber = wholeFractionSplit[0]
if (wholeNumber.length === 0) {
return false
} else {
return true
}
}
if (wholeFractionSplit.length === 1) {
return true
}
// What if someone passes in 1..2.3.1...1.1.43
return undefined
}
export function onDragNumberCalculation(text: string, e: MouseEvent) {
const multiplier =
e.shiftKey && e.metaKey ? 0.01 : e.metaKey ? 0.1 : e.shiftKey ? 10 : 1
const delta = e.movementX * multiplier
const hasPeriod = text.includes('.')
const leadsWithZero = hasLeadingZero(text)
const addition = Number(text) + delta
const positiveAddition = e.movementX > 0
const negativeAddition = e.movementX < 0
const containsDigitsLeftOfDecimal = hasDigitsLeftOfDecimal(text)
let precision = Math.max(
getPrecision(text),
getPrecision(multiplier.toString())
)
const newVal = roundOff(addition, precision)
if (Number.isNaN(newVal)) {
return
}
let formattedString = newVal.toString()
if (hasPeriod && !formattedString.includes('.')) {
// If the original number included a period lets add that back to the output string
// e.g. '1.0' add +1 then we get 2, we want to send '2.0' back since the original one had a decimal place
formattedString = formattedString.toString() + '.0'
}
/**
* Whenever you add two numbers you can always remove the the leading zero the result will make sense
* 1 + -0.01 = 0.99, the code would remove the leading 0 to make it .99 but since the number has a
* digit left of the decimal to begin with I want to make it 0.99.
* negativeAddition with fractional numbers will provide a leading 0.
*/
const removeZeros =
positiveAddition ||
(negativeAddition && multiplier < 1 && !containsDigitsLeftOfDecimal)
/**
* If the original value has no leading 0
* If if the new updated value has a leading zero
* If the math operation means you can actually remove the zero.
*/
if (!leadsWithZero && hasLeadingZero(formattedString) && removeZeros) {
if (formattedString[0] === '-') {
return ['-', formattedString.split('.')[1]].join('.')
} else {
return formattedString.substring(1)
}
}
return formattedString
}
export function onMouseDragMakeANewNumber(
text: string,
setText: (t: string) => void,
e: MouseEvent
) {
const newVal = onDragNumberCalculation(text, e)
if (!newVal) return
setText(newVal)
}
Add 3 point arc (#5722) * bare minimum * start of segment util added * remove redundant handle * some probably buggy handling of arc handles, can fix later * probably bug implementation of update args, but data flow through is mostly there can fix bugs after * fix update for arc * fix math for center handle * fix up length indicator * tweak math * stub out xState logic for arc * more progress on adding point and click, implemented more of sketchLineHelper for arc * small unrelated tweak * fix up draft arc bugs * fix arc last click * fix draft segment animation and add comment * add draft point snapping for arcs * add helper stuff to arc * clone arc point and click as base for arc-three-point * rust change for arc three point * can draw three point arc * make arcTo editable * can add new three point arc, so long as it continues existing profile * get overlays working * make snap to for continuing profile work for three point arcs * add draft animation * tangent issue fix * action rename * tmp test fix up * fix silly bug * fix couple problems causing tests to fail * A snapshot a day keeps the bugs away! 📷🐛 (OS: namespace-profile-ubuntu-8-cores) * fix up * add delet segment test for new segments * update docs * draft segments should look right * add test for dragging new segment handles * arc tools can be chained now * make three point arc can start a new profile (not only extend existing paths) * add test for equiping and unequiping the tool plus drawing with it * fix console noise * A snapshot a day keeps the bugs away! 📷🐛 (OS: namespace-profile-ubuntu-8-cores) * clean up * update rust/docs * put toolbar mode check into fixture * do thing for lee * use TEST_COLORSs * fix colors * don't await file write * remove commented code * remove unneeded template strings * power to **2 * remove magic numbers * more string templates * some odd bits of clean up * arc should be enable in dev * A snapshot a day keeps the bugs away! 📷🐛 (OS: namespace-profile-ubuntu-8-cores) * A snapshot a day keeps the bugs away! 📷🐛 (OS: namespace-profile-ubuntu-8-cores) * A snapshot a day keeps the bugs away! 📷🐛 (OS: namespace-profile-ubuntu-8-cores) * add new simulation test * fix test code from kwark migration * issues Frank found * fix deleting half complete ark * fix * small fix on dele index * tsc post main merge * fix up snaping to profile start * add cross hari for three point arc * block snapping if it's the only segment * add tests for canceling arcTo halfway through --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-03-18 11:14:12 +11:00
export function isClockwise(points: [number, number][]): boolean {
// Need at least 3 points to determine orientation
if (points.length < 3) {
return false
}
// Calculate the sum of (x2 - x1) * (y2 + y1) for all edges
// This is the "shoelace formula" for calculating the signed area
let sum = 0
for (let i = 0; i < points.length; i++) {
const current = points[i]
const next = points[(i + 1) % points.length]
sum += (next[0] - current[0]) * (next[1] + current[1])
}
// If sum is positive, the points are in clockwise order
return sum > 0
}
/**
* Converts a binary buffer to a UUID string.
*
* @param buffer - The binary buffer containing the UUID bytes.
* @returns A string representation of the UUID in the format 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.
*/
export function binaryToUuid(
binaryData: Buffer | Uint8Array | BSONBinary | string
): string {
if (typeof binaryData === 'string') {
return binaryData
}
let buffer: Uint8Array
// Handle MongoDB BSON Binary object
if (
binaryData &&
'_bsontype' in binaryData &&
binaryData._bsontype === 'Binary'
) {
// Extract the buffer from the BSON Binary object
buffer = binaryData.buffer
}
// Handle case where buffer property exists (some MongoDB drivers structure)
else if (binaryData && binaryData.buffer instanceof Uint8Array) {
buffer = binaryData.buffer
}
// Handle direct Buffer or Uint8Array
else if (binaryData instanceof Uint8Array || Buffer.isBuffer(binaryData)) {
buffer = binaryData
} else {
console.error(
'Invalid input type: expected MongoDB BSON Binary, Buffer, or Uint8Array'
)
return ''
}
// Ensure we have exactly 16 bytes (128 bits) for a UUID
if (buffer.length !== 16) {
// For debugging
console.log('Buffer length:', buffer.length)
console.log('Buffer content:', Array.from(buffer))
console.error('UUID must be exactly 16 bytes')
return ''
}
// Convert each byte to a hex string and pad with zeros if needed
const hexValues = Array.from(buffer).map((byte) =>
byte.toString(16).padStart(2, '0')
)
// Format into UUID structure (8-4-4-4-12 characters)
return [
hexValues.slice(0, 4).join(''),
hexValues.slice(4, 6).join(''),
hexValues.slice(6, 8).join(''),
hexValues.slice(8, 10).join(''),
hexValues.slice(10, 16).join(''),
].join('-')
}
export function getModuleId(sourceRange: SourceRange) {
return sourceRange[2]
}
export function getInVariableCase(name: string, prefixIfDigit = 'm') {
// As of 2025-04-08, standard case for KCL variables is camelCase
const startsWithANumber = !Number.isNaN(Number(name.charAt(0)))
const paddedName = startsWithANumber ? `${prefixIfDigit}${name}` : name
// From https://www.30secondsofcode.org/js/s/string-case-conversion/#word-boundary-identification
const r = /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
const boundaryIdentification = paddedName.match(r)
if (!boundaryIdentification) {
return undefined
}
const likelyPascalCase = boundaryIdentification
.map((x) => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.join('')
if (!likelyPascalCase) {
return undefined
}
return likelyPascalCase.slice(0, 1).toLowerCase() + likelyPascalCase.slice(1)
}