Make tag last optional param everywhere (#1739)

* Make tag last optional param

* Update all test assertions with correct tag format

* Format ts

* Some progress on tests and code mods

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

* More sketch fixes

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

* Only 1 test left

* Clean up console.log

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

* Fix last ts test

* Clean up fmt

* Fix clippy too

* Update docs and fix small oversight on angled lines

* Fix more rust tests

* Make typescript happy

* Fmt

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jess Frazelle <jessfraz@users.noreply.github.com>
This commit is contained in:
Adam Sunderland
2024-03-15 17:03:42 -04:00
committed by GitHub
parent 4987965731
commit 816870253e
60 changed files with 934 additions and 1539 deletions

View File

@ -17,7 +17,7 @@ angleToMatchLengthX(segment_name: string, to: number, sketch_group: SketchGroup)
```js ```js
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [1, 3.82], tag: 'seg01' }, %) |> line([1, 3.82], %, 'seg01')
|> angledLineToX([ |> angledLineToX([
-angleToMatchLengthX('seg01', 10, %), -angleToMatchLengthX('seg01', 10, %),
5 5

View File

@ -17,7 +17,7 @@ angleToMatchLengthY(segment_name: string, to: number, sketch_group: SketchGroup)
```js ```js
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [1, 3.82], tag: 'seg01' }, %) |> line([1, 3.82], %, 'seg01')
|> angledLineToX([ |> angledLineToX([
-angleToMatchLengthY('seg01', 10, %), -angleToMatchLengthY('seg01', 10, %),
5 5

View File

@ -9,7 +9,7 @@ Draw an angled line.
```js ```js
angledLine(data: AngledLineData, sketch_group: SketchGroup) -> SketchGroup angledLine(data: AngledLineData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,7 +17,7 @@ angledLine(data: AngledLineData, sketch_group: SketchGroup) -> SketchGroup
```js ```js
startSketchOn('XY') startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> angledLine({ angle: 45, length: 10, tag: "edge1" }, %) |> angledLine({ angle: 45, length: 10 }, %, "edge1")
|> line([10, 10], %) |> line([10, 10], %)
|> line([0, 10], %) |> line([0, 10], %)
|> close(%, "edge2") |> close(%, "edge2")
@ -33,8 +33,6 @@ startSketchOn('XY')
angle: number, angle: number,
// The length of the line. // The length of the line.
length: number, length: number,
// The tag.
tag: string,
} | } |
[number, number] [number, number]
``` ```
@ -202,6 +200,7 @@ startSketchOn('XY')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw an angled line of a given x length.
```js ```js
angledLineOfXLength(data: AngledLineData, sketch_group: SketchGroup) -> SketchGroup angledLineOfXLength(data: AngledLineData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,7 +17,7 @@ angledLineOfXLength(data: AngledLineData, sketch_group: SketchGroup) -> SketchGr
```js ```js
startSketchOn('XZ') startSketchOn('XZ')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> angledLineOfXLength({ angle: 45, length: 10, tag: "edge1" }, %) |> angledLineOfXLength({ angle: 45, length: 10 }, %, "edge1")
|> line([10, 10], %) |> line([10, 10], %)
|> line([0, 10], %) |> line([0, 10], %)
|> close(%, "edge2") |> close(%, "edge2")
@ -33,8 +33,6 @@ startSketchOn('XZ')
angle: number, angle: number,
// The length of the line. // The length of the line.
length: number, length: number,
// The tag.
tag: string,
} | } |
[number, number] [number, number]
``` ```
@ -202,6 +200,7 @@ startSketchOn('XZ')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw an angled line of a given y length.
```js ```js
angledLineOfYLength(data: AngledLineData, sketch_group: SketchGroup) -> SketchGroup angledLineOfYLength(data: AngledLineData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,7 +17,7 @@ angledLineOfYLength(data: AngledLineData, sketch_group: SketchGroup) -> SketchGr
```js ```js
startSketchOn('YZ') startSketchOn('YZ')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> angledLineOfYLength({ angle: 45, length: 10, tag: "edge1" }, %) |> angledLineOfYLength({ angle: 45, length: 10 }, %, "edge1")
|> line([10, 10], %) |> line([10, 10], %)
|> line([0, 10], %) |> line([0, 10], %)
|> close(%, "edge2") |> close(%, "edge2")
@ -34,8 +34,6 @@ startSketchOn('YZ')
angle: number, angle: number,
// The length of the line. // The length of the line.
length: number, length: number,
// The tag.
tag: string,
} | } |
[number, number] [number, number]
``` ```
@ -203,6 +201,7 @@ startSketchOn('YZ')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw an angled line that intersects with a given line.
```js ```js
angledLineThatIntersects(data: AngledLineThatIntersectsData, sketch_group: SketchGroup) -> SketchGroup angledLineThatIntersects(data: AngledLineThatIntersectsData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,14 +17,13 @@ angledLineThatIntersects(data: AngledLineThatIntersectsData, sketch_group: Sketc
```js ```js
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> lineTo({ to: [2, 2], tag: "yo" }, %) |> lineTo([2, 2], %, "yo")
|> lineTo([3, 1], %) |> lineTo([3, 1], %)
|> angledLineThatIntersects({ |> angledLineThatIntersects({
angle: 180, angle: 180,
intersectTag: 'yo', intersectTag: 'yo',
offset: 12, offset: 12
tag: "yo2" }, %, "yo2")
}, %)
|> line([4, 0], %) |> line([4, 0], %)
|> close(%, "yo3") |> close(%, "yo3")
|> extrude(10, %) |> extrude(10, %)
@ -41,8 +40,6 @@ const part001 = startSketchOn('XY')
intersectTag: string, intersectTag: string,
// The offset from the intersecting line. // The offset from the intersecting line.
offset: number, offset: number,
// The tag.
tag: string,
} }
``` ```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
@ -209,6 +206,7 @@ const part001 = startSketchOn('XY')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw an angled line to a given x coordinate.
```js ```js
angledLineToX(data: AngledLineToData, sketch_group: SketchGroup) -> SketchGroup angledLineToX(data: AngledLineToData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,7 +17,7 @@ angledLineToX(data: AngledLineToData, sketch_group: SketchGroup) -> SketchGroup
```js ```js
startSketchOn('XY') startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> angledLineToX({ angle: 45, to: 10, tag: "edge1" }, %) |> angledLineToX({ angle: 45, to: 10 }, %, "edge1")
|> line([10, 10], %) |> line([10, 10], %)
|> line([0, 10], %) |> line([0, 10], %)
|> close(%, "edge2") |> close(%, "edge2")
@ -32,12 +32,9 @@ startSketchOn('XY')
{ {
// The angle of the line. // The angle of the line.
angle: number, angle: number,
// The tag.
tag: string,
// The point to draw to. // The point to draw to.
to: number, to: number,
} | }
[number, number]
``` ```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
```js ```js
@ -203,6 +200,7 @@ startSketchOn('XY')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw an angled line to a given y coordinate.
```js ```js
angledLineToY(data: AngledLineToData, sketch_group: SketchGroup) -> SketchGroup angledLineToY(data: AngledLineToData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,7 +17,7 @@ angledLineToY(data: AngledLineToData, sketch_group: SketchGroup) -> SketchGroup
```js ```js
startSketchOn('XY') startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> angledLineToY({ angle: 45, to: 10, tag: "edge1" }, %) |> angledLineToY({ angle: 45, to: 10 }, %, "edge1")
|> line([10, 10], %) |> line([10, 10], %)
|> line([0, 10], %) |> line([0, 10], %)
|> close(%, "edge2") |> close(%, "edge2")
@ -31,12 +31,9 @@ startSketchOn('XY')
{ {
// The angle of the line. // The angle of the line.
angle: number, angle: number,
// The tag.
tag: string,
// The point to draw to. // The point to draw to.
to: number, to: number,
} | }
[number, number]
``` ```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
```js ```js
@ -202,6 +199,7 @@ startSketchOn('XY')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw an arc.
```js ```js
arc(data: ArcData, sketch_group: SketchGroup) -> SketchGroup arc(data: ArcData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -20,9 +20,8 @@ startSketchOn('-YZ')
|> arc({ |> arc({
angle_start: 0, angle_start: 0,
angle_end: 360, angle_end: 360,
radius: 10, radius: 10
tag: "edge1" }, %, "edge1")
}, %)
|> extrude(10, %) |> extrude(10, %)
``` ```
@ -37,16 +36,12 @@ startSketchOn('-YZ')
angle_start: number, angle_start: number,
// The radius. // The radius.
radius: number, radius: number,
// The tag.
tag: string,
} | } |
{ {
// The center. // The center.
center: [number, number], center: [number, number],
// The radius. // The radius.
radius: number, radius: number,
// The tag.
tag: string,
// The to point. // The to point.
to: [number, number], to: [number, number],
} }
@ -215,6 +210,7 @@ startSketchOn('-YZ')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw a bezier curve.
```js ```js
bezierCurve(data: BezierData, sketch_group: SketchGroup) -> SketchGroup bezierCurve(data: BezierData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -20,9 +20,8 @@ startSketchOn('XY')
|> bezierCurve({ |> bezierCurve({
to: [10, 10], to: [10, 10],
control1: [5, 0], control1: [5, 0],
control2: [5, 10], control2: [5, 10]
tag: "edge1" }, %, "edge1")
}, %)
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
``` ```
@ -36,8 +35,6 @@ startSketchOn('XY')
control1: [number, number], control1: [number, number],
// The second control point. // The second control point.
control2: [number, number], control2: [number, number],
// The tag.
tag: string,
// The to point. // The to point.
to: [number, number], to: [number, number],
} }
@ -206,6 +203,7 @@ startSketchOn('XY')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -17,9 +17,9 @@ fillet(data: FilletData, extrude_group: ExtrudeGroup) -> ExtrudeGroup
```js ```js
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [0, 10], tag: "thing" }, %) |> line([0, 10], %, "thing")
|> line([10, 0], %) |> line([10, 0], %)
|> line({ to: [0, -10], tag: "thing2" }, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({ radius: 2, tags: ["thing", "thing2"] }, %) |> fillet({ radius: 2, tags: ["thing", "thing2"] }, %)

View File

@ -19,7 +19,7 @@ const box = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line([0, 10], %) |> line([0, 10], %)
|> line([10, 0], %) |> line([10, 0], %)
|> line({ to: [0, -10], tag: "surface" }, %) |> line([0, -10], %, "surface")
|> close(%) |> close(%)
|> extrude(5, %) |> extrude(5, %)

View File

@ -17,9 +17,9 @@ getNextAdjacentEdge(tag: String, extrude_group: ExtrudeGroup) -> Uuid
```js ```js
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [0, 10], tag: "thing" }, %) |> line([0, 10], %, "thing")
|> line({ to: [10, 0], tag: "thing1" }, %) |> line([10, 0], %, "thing1")
|> line({ to: [0, -10], tag: "thing2" }, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({ |> fillet({

View File

@ -17,9 +17,9 @@ getOppositeEdge(tag: String, extrude_group: ExtrudeGroup) -> Uuid
```js ```js
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [0, 10], tag: "thing" }, %) |> line([0, 10], %, "thing")
|> line([10, 0], %) |> line([10, 0], %)
|> line({ to: [0, -10], tag: "thing2" }, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({ |> fillet({

View File

@ -17,9 +17,9 @@ getPreviousAdjacentEdge(tag: String, extrude_group: ExtrudeGroup) -> Uuid
```js ```js
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [0, 10], tag: "thing" }, %) |> line([0, 10], %, "thing")
|> line({ to: [10, 0], tag: "thing1" }, %) |> line([10, 0], %, "thing1")
|> line({ to: [0, -10], tag: "thing2" }, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({ |> fillet({

View File

@ -17,7 +17,7 @@ lastSegX(sketch_group: SketchGroup) -> number
```js ```js
startSketchOn("YZ") startSketchOn("YZ")
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [5, 0], tag: "thing" }, %) |> line([5, 0], %, "thing")
|> line([5, 5], %) |> line([5, 5], %)
|> line([0, lastSegX(%)], %) |> line([0, lastSegX(%)], %)
|> close(%) |> close(%)

View File

@ -17,7 +17,7 @@ lastSegY(sketch_group: SketchGroup) -> number
```js ```js
startSketchOn("YZ") startSketchOn("YZ")
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [5, 0], tag: "thing" }, %) |> line([5, 0], %, "thing")
|> line([5, 5], %) |> line([5, 5], %)
|> line([0, lastSegY(%)], %) |> line([0, lastSegY(%)], %)
|> close(%) |> close(%)

View File

@ -9,7 +9,7 @@ Draw a line.
```js ```js
line(data: LineData, sketch_group: SketchGroup) -> SketchGroup line(delta: [number], sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -18,23 +18,14 @@ line(data: LineData, sketch_group: SketchGroup) -> SketchGroup
startSketchOn('-XY') startSketchOn('-XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line([10, 10], %) |> line([10, 10], %)
|> line({ to: [20, 10], tag: "edge1" }, %) |> line([20, 10], %, "edge1")
|> close(%, "edge2") |> close(%, "edge2")
|> extrude(10, %) |> extrude(10, %)
``` ```
### Arguments ### Arguments
* `data`: `LineData` - Data to draw a line. (REQUIRED) * `delta`: `[number]` (REQUIRED)
```js
{
// The tag.
tag: string,
// The to point.
to: [number, number],
} |
[number, number]
```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
```js ```js
{ {
@ -199,6 +190,7 @@ startSketchOn('-XY')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw a line to a point.
```js ```js
lineTo(data: LineToData, sketch_group: SketchGroup) -> SketchGroup lineTo(to: [number], sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -18,18 +18,9 @@ lineTo(data: LineToData, sketch_group: SketchGroup) -> SketchGroup
fn rectShape = (pos, w, l) => { fn rectShape = (pos, w, l) => {
const rr = startSketchOn('YZ') const rr = startSketchOn('YZ')
|> startProfileAt([pos[0] - (w / 2), pos[1] - (l / 2)], %) |> startProfileAt([pos[0] - (w / 2), pos[1] - (l / 2)], %)
|> lineTo({ |> lineTo([pos[0] + w / 2, pos[1] - (l / 2)], %, "edge1")
to: [pos[0] + w / 2, pos[1] - (l / 2)], |> lineTo([pos[0] + w / 2, pos[1] + l / 2], %, "edge2")
tag: "edge1" |> lineTo([pos[0] - (w / 2), pos[1] + l / 2], %, "edge3")
}, %)
|> lineTo({
to: [pos[0] + w / 2, pos[1] + l / 2],
tag: "edge2"
}, %)
|> lineTo({
to: [pos[0] - (w / 2), pos[1] + l / 2],
tag: "edge3"
}, %)
|> close(%, "edge4") |> close(%, "edge4")
return rr return rr
} }
@ -40,16 +31,7 @@ const part = rectShape([0, 0], 20, 20)
### Arguments ### Arguments
* `data`: `LineToData` - Data to draw a line to a point. (REQUIRED) * `to`: `[number]` (REQUIRED)
```js
{
// The tag.
tag: string,
// The to point.
to: [number, number],
} |
[number, number]
```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
```js ```js
{ {
@ -214,6 +196,7 @@ const part = rectShape([0, 0], 20, 20)
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -18,7 +18,7 @@ segAng(segment_name: string, sketch_group: SketchGroup) -> number
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([4.83, 12.56], %) |> startProfileAt([4.83, 12.56], %)
|> line([15.1, 2.48], %) |> line([15.1, 2.48], %)
|> line({ to: [3.15, -9.85], tag: 'seg01' }, %) |> line([3.15, -9.85], %, 'seg01')
|> line([-15.17, -4.1], %) |> line([-15.17, -4.1], %)
|> angledLine([segAng('seg01', %), 12.35], %) |> angledLine([segAng('seg01', %), 12.35], %)
|> line([-13.02, 10.03], %) |> line([-13.02, 10.03], %)

View File

@ -17,7 +17,7 @@ segEndX(segment_name: string, sketch_group: SketchGroup) -> number
```js ```js
startSketchOn("YZ") startSketchOn("YZ")
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [5, 0], tag: "thing" }, %) |> line([5, 0], %, "thing")
|> line([5, 5], %) |> line([5, 5], %)
|> line([segEndX("thing", %), 5], %) |> line([segEndX("thing", %), 5], %)
|> close(%) |> close(%)

View File

@ -17,7 +17,7 @@ segEndY(segment_name: string, sketch_group: SketchGroup) -> number
```js ```js
startSketchOn("YZ") startSketchOn("YZ")
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [5, 0], tag: "thing" }, %) |> line([5, 0], %, "thing")
|> line([5, 5], %) |> line([5, 5], %)
|> line([segEndY("thing", %), 5], %) |> line([segEndY("thing", %), 5], %)
|> close(%) |> close(%)

View File

@ -17,7 +17,7 @@ segLen(segment_name: string, sketch_group: SketchGroup) -> number
```js ```js
startSketchOn("YZ") startSketchOn("YZ")
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [5, 0], tag: "thing" }, %) |> line([5, 0], %, "thing")
|> line([5, 5], %) |> line([5, 5], %)
|> line([0, segLen("thing", %)], %) |> line([0, segLen("thing", %)], %)
|> close(%) |> close(%)

View File

@ -9,7 +9,7 @@ Start a profile at a given point.
```js ```js
startProfileAt(data: LineData, sketch_surface: SketchSurface) -> SketchGroup startProfileAt(to: [number], sketch_surface: SketchSurface, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -22,16 +22,7 @@ startSketchOn('XY')
### Arguments ### Arguments
* `data`: `LineData` - Data to draw a line. (REQUIRED) * `to`: `[number]` (REQUIRED)
```js
{
// The tag.
tag: string,
// The to point.
to: [number, number],
} |
[number, number]
```
* `sketch_surface`: `SketchSurface` - A sketch group type. (REQUIRED) * `sketch_surface`: `SketchSurface` - A sketch group type. (REQUIRED)
```js ```js
{ {
@ -93,6 +84,7 @@ startSketchOn('XY')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Start a sketch at a given point on the 'XY' plane.
```js ```js
startSketchAt(data: LineData) -> SketchGroup startSketchAt(data: [number]) -> SketchGroup
``` ```
### Examples ### Examples
@ -21,16 +21,7 @@ startSketchAt([0, 0])
### Arguments ### Arguments
* `data`: `LineData` - Data to draw a line. (REQUIRED) * `data`: `[number]` (REQUIRED)
```js
{
// The tag.
tag: string,
// The to point.
to: [number, number],
} |
[number, number]
```
### Returns ### Returns

View File

@ -18,7 +18,7 @@ startSketchOn(data: SketchData, tag?: SketchOnFaceTag) -> SketchSurface
startSketchOn('XY') startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line([10, 10], %) |> line([10, 10], %)
|> line({ to: [20, 10], tag: "edge1" }, %) |> line([20, 10], %, "edge1")
|> close(%, "edge2") |> close(%, "edge2")
``` ```
@ -40,7 +40,7 @@ const box = cube([0, 0], 20)
const part001 = startSketchOn(box, "start") const part001 = startSketchOn(box, "start")
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line([10, 10], %) |> line([10, 10], %)
|> line({ to: [20, 10], tag: "edge1" }, %) |> line([20, 10], %, "edge1")
|> close(%) |> close(%)
|> extrude(20, %) |> extrude(20, %)
``` ```

File diff suppressed because it is too large Load Diff

View File

@ -9,7 +9,7 @@ Draw an arc.
```js ```js
tangentialArc(data: TangentialArcData, sketch_group: SketchGroup) -> SketchGroup tangentialArc(data: TangentialArcData, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,8 +17,8 @@ tangentialArc(data: TangentialArcData, sketch_group: SketchGroup) -> SketchGroup
```js ```js
startSketchOn('-YZ') startSketchOn('-YZ')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [10, 10], tag: "edge0" }, %) |> line([10, 10], %, "edge1")
|> tangentialArc({ radius: 10, offset: 90, tag: "edge1" }, %) |> tangentialArc({ radius: 10, offset: 90 }, %, "edge1")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
``` ```
@ -33,12 +33,6 @@ startSketchOn('-YZ')
// Radius of the arc. Not to be confused with Raiders of the Lost Ark. // Radius of the arc. Not to be confused with Raiders of the Lost Ark.
radius: number, radius: number,
} | } |
{
// The tag.
tag: string,
// Where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position.
to: [number, number],
} |
[number, number] [number, number]
``` ```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
@ -205,6 +199,7 @@ startSketchOn('-YZ')
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -17,7 +17,7 @@ tangentialArcTo(to: [number], sketch_group: SketchGroup, tag?: String) -> Sketch
```js ```js
startSketchOn('-YZ') startSketchOn('-YZ')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [10, 10], tag: "edge0" }, %) |> line([10, 10], %, "edge0")
|> tangentialArcTo([10, 0], %) |> tangentialArcTo([10, 0], %)
|> close(%) |> close(%)
``` ```

View File

@ -9,7 +9,7 @@ Draw a line on the x-axis.
```js ```js
xLine(data: AxisLineData, sketch_group: SketchGroup) -> SketchGroup xLine(length: number, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -25,16 +25,7 @@ startSketchOn('YZ')
### Arguments ### Arguments
* `data`: `AxisLineData` - Data to draw a line on an axis. (REQUIRED) * `length`: `number` (REQUIRED)
```js
{
// The length of the line.
length: number,
// The tag.
tag: string,
} |
number
```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
```js ```js
{ {
@ -199,6 +190,7 @@ number
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw a line to a point on the x-axis.
```js ```js
xLineTo(data: AxisLineToData, sketch_group: SketchGroup) -> SketchGroup xLineTo(to: number, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,7 +17,7 @@ xLineTo(data: AxisLineToData, sketch_group: SketchGroup) -> SketchGroup
```js ```js
startSketchOn('XY') startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> xLineTo({ to: 10, tag: "edge1" }, %) |> xLineTo(10, %, "edge1")
|> line([10, 10], %) |> line([10, 10], %)
|> close(%, "edge2") |> close(%, "edge2")
|> extrude(10, %) |> extrude(10, %)
@ -25,16 +25,7 @@ startSketchOn('XY')
### Arguments ### Arguments
* `data`: `AxisLineToData` - Data to draw a line to a point on an axis. (REQUIRED) * `to`: `number` (REQUIRED)
```js
{
// The tag.
tag: string,
// The to point.
to: number,
} |
number
```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
```js ```js
{ {
@ -199,6 +190,7 @@ number
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw a line on the y-axis.
```js ```js
yLine(data: AxisLineData, sketch_group: SketchGroup) -> SketchGroup yLine(length: number, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -25,16 +25,7 @@ startSketchOn('XY')
### Arguments ### Arguments
* `data`: `AxisLineData` - Data to draw a line on an axis. (REQUIRED) * `length`: `number` (REQUIRED)
```js
{
// The length of the line.
length: number,
// The tag.
tag: string,
} |
number
```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
```js ```js
{ {
@ -199,6 +190,7 @@ number
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -9,7 +9,7 @@ Draw a line to a point on the y-axis.
```js ```js
yLineTo(data: AxisLineToData, sketch_group: SketchGroup) -> SketchGroup yLineTo(to: number, sketch_group: SketchGroup, tag?: String) -> SketchGroup
``` ```
### Examples ### Examples
@ -17,7 +17,7 @@ yLineTo(data: AxisLineToData, sketch_group: SketchGroup) -> SketchGroup
```js ```js
startSketchOn('XZ') startSketchOn('XZ')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> yLineTo({ to: 10, tag: "edge1" }, %) |> yLineTo(10, %, "edge1")
|> line([10, 10], %) |> line([10, 10], %)
|> close(%, "edge2") |> close(%, "edge2")
|> extrude(10, %) |> extrude(10, %)
@ -26,16 +26,7 @@ startSketchOn('XZ')
### Arguments ### Arguments
* `data`: `AxisLineToData` - Data to draw a line to a point on an axis. (REQUIRED) * `to`: `number` (REQUIRED)
```js
{
// The tag.
tag: string,
// The to point.
to: number,
} |
number
```
* `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED) * `sketch_group`: `SketchGroup` - A sketch group is a collection of paths. (REQUIRED)
```js ```js
{ {
@ -200,6 +191,7 @@ number
}, },
} }
``` ```
* `tag`: `String` (OPTIONAL)
### Returns ### Returns

View File

@ -130,7 +130,7 @@ test('Basic sketch', async ({ page }) => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ') .toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${commonPoints.startAt}, %) |> startProfileAt(${commonPoints.startAt}, %)
|> line({ to: [${commonPoints.num1}, 0], tag: 'seg01' }, %) |> line([${commonPoints.num1}, 0], %, 'seg01')
|> line([0, ${commonPoints.num1}], %) |> line([0, ${commonPoints.num1}], %)
|> angledLine([180, segLen('seg01', %)], %)`) |> angledLine([180, segLen('seg01', %)], %)`)
}) })

View File

@ -55,10 +55,9 @@ const part001 = startSketchOn('-XZ')
|> angledLineToY({ |> angledLineToY({
angle: topAng, angle: topAng,
to: totalHeightHalf, to: totalHeightHalf,
tag: 'seg04' }, %, 'seg04')
}, %) |> xLineTo(totalLen, %, 'seg03')
|> xLineTo({ to: totalLen, tag: 'seg03' }, %) |> yLine(-armThick, %, 'seg01')
|> yLine({ length: -armThick, tag: 'seg01' }, %)
|> angledLineThatIntersects({ |> angledLineThatIntersects({
angle: HALF_TURN, angle: HALF_TURN,
offset: -armThick, offset: -armThick,
@ -68,8 +67,7 @@ const part001 = startSketchOn('-XZ')
|> angledLineToY({ |> angledLineToY({
angle: -bottomAng, angle: -bottomAng,
to: -totalHeightHalf - armThick, to: -totalHeightHalf - armThick,
tag: 'seg02' }, %, 'seg02')
}, %)
|> xLineTo(segEndX('seg03', %) + 0, %) |> xLineTo(segEndX('seg03', %) + 0, %)
|> yLine(-segLen('seg01', %), %) |> yLine(-segLen('seg01', %), %)
|> angledLineThatIntersects({ |> angledLineThatIntersects({

View File

@ -360,7 +360,7 @@ describe('testing pipe operator special', () => {
test('pipe operator with sketch', () => { test('pipe operator with sketch', () => {
let code = `const mySketch = startSketchAt([0, 0]) let code = `const mySketch = startSketchAt([0, 0])
|> lineTo([2, 3], %) |> lineTo([2, 3], %)
|> lineTo({ to: [0, 1], tag: "myPath" }, %) |> lineTo([0, 1], %, "myPath")
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
|> rx(45, %) |> rx(45, %)
` `
@ -370,18 +370,18 @@ describe('testing pipe operator special', () => {
{ {
type: 'VariableDeclaration', type: 'VariableDeclaration',
start: 0, start: 0,
end: 145, end: 132,
kind: 'const', kind: 'const',
declarations: [ declarations: [
{ {
type: 'VariableDeclarator', type: 'VariableDeclarator',
start: 6, start: 6,
end: 145, end: 132,
id: { type: 'Identifier', start: 6, end: 14, name: 'mySketch' }, id: { type: 'Identifier', start: 6, end: 14, name: 'mySketch' },
init: { init: {
type: 'PipeExpression', type: 'PipeExpression',
start: 17, start: 17,
end: 145, end: 132,
body: [ body: [
{ {
type: 'CallExpression', type: 'CallExpression',
@ -457,7 +457,7 @@ describe('testing pipe operator special', () => {
{ {
type: 'CallExpression', type: 'CallExpression',
start: 67, start: 67,
end: 107, end: 94,
callee: { callee: {
type: 'Identifier', type: 'Identifier',
start: 67, start: 67,
@ -466,121 +466,92 @@ describe('testing pipe operator special', () => {
}, },
arguments: [ arguments: [
{ {
type: 'ObjectExpression',
start: 74,
end: 103,
properties: [
{
type: 'ObjectProperty',
start: 76,
end: 86,
key: {
type: 'Identifier',
start: 76,
end: 78,
name: 'to',
},
value: {
type: 'ArrayExpression', type: 'ArrayExpression',
start: 80, start: 74,
end: 86, end: 80,
elements: [ elements: [
{ {
type: 'Literal', type: 'Literal',
start: 81, start: 75,
end: 82, end: 76,
value: 0, value: 0,
raw: '0', raw: '0',
}, },
{ {
type: 'Literal', type: 'Literal',
start: 84, start: 78,
end: 85, end: 79,
value: 1, value: 1,
raw: '1', raw: '1',
}, },
], ],
}, },
}, { type: 'PipeSubstitution', start: 82, end: 83 },
{ {
type: 'ObjectProperty',
start: 88,
end: 101,
key: {
type: 'Identifier',
start: 88,
end: 91,
name: 'tag',
},
value: {
type: 'Literal', type: 'Literal',
start: 93, start: 85,
end: 101, end: 93,
value: 'myPath', value: 'myPath',
raw: '"myPath"', raw: '"myPath"',
}, },
},
],
},
{ type: 'PipeSubstitution', start: 105, end: 106 },
], ],
optional: false, optional: false,
}, },
{ {
type: 'CallExpression', type: 'CallExpression',
start: 113, start: 100,
end: 130, end: 117,
callee: { callee: {
type: 'Identifier', type: 'Identifier',
start: 113, start: 100,
end: 119, end: 106,
name: 'lineTo', name: 'lineTo',
}, },
arguments: [ arguments: [
{ {
type: 'ArrayExpression', type: 'ArrayExpression',
start: 120, start: 107,
end: 126, end: 113,
elements: [ elements: [
{ {
type: 'Literal', type: 'Literal',
start: 121, start: 108,
end: 122, end: 109,
value: 1, value: 1,
raw: '1', raw: '1',
}, },
{ {
type: 'Literal', type: 'Literal',
start: 124, start: 111,
end: 125, end: 112,
value: 1, value: 1,
raw: '1', raw: '1',
}, },
], ],
}, },
{ type: 'PipeSubstitution', start: 128, end: 129 }, { type: 'PipeSubstitution', start: 115, end: 116 },
], ],
optional: false, optional: false,
}, },
{ {
type: 'CallExpression', type: 'CallExpression',
start: 136, start: 123,
end: 145, end: 132,
callee: { callee: {
type: 'Identifier', type: 'Identifier',
start: 136, start: 123,
end: 138, end: 125,
name: 'rx', name: 'rx',
}, },
arguments: [ arguments: [
{ {
type: 'Literal', type: 'Literal',
start: 139, start: 126,
end: 141, end: 128,
value: 45, value: 45,
raw: '45', raw: '45',
}, },
{ type: 'PipeSubstitution', start: 143, end: 144 }, { type: 'PipeSubstitution', start: 130, end: 131 },
], ],
optional: false, optional: false,
}, },
@ -1502,11 +1473,11 @@ const key = 'c'`
}) })
it('comments nested within a block statement', () => { it('comments nested within a block statement', () => {
const code = `const mySketch = startSketchAt([0,0]) const code = `const mySketch = startSketchAt([0,0])
|> lineTo({ to: [0, 1], tag: 'myPath' }, %) |> lineTo([0, 1], %, 'myPath')
|> lineTo([1, 1], %) /* this is |> lineTo([1, 1], %) /* this is
a comment a comment
spanning a few lines */ spanning a few lines */
|> lineTo({ to: [1,0], tag: "rightPath" }, %) |> lineTo([1,0], %, "rightPath")
|> close(%) |> close(%)
` `
@ -1516,8 +1487,8 @@ const key = 'c'`
.nonCodeNodes .nonCodeNodes
expect(sketchNonCodeMeta[indexOfSecondLineToExpression][0]).toEqual({ expect(sketchNonCodeMeta[indexOfSecondLineToExpression][0]).toEqual({
type: 'NonCodeNode', type: 'NonCodeNode',
start: 106, start: 93,
end: 163, end: 150,
value: { value: {
type: 'inlineComment', type: 'inlineComment',
style: 'block', style: 'block',
@ -1529,7 +1500,7 @@ const key = 'c'`
const code = [ const code = [
'const mySk1 = startSketchAt([0, 0])', 'const mySk1 = startSketchAt([0, 0])',
' |> lineTo([1, 1], %)', ' |> lineTo([1, 1], %)',
' |> lineTo({to: [0, 1], tag: "myPath"}, %)', ' |> lineTo([0, 1], %, "myPath")',
' |> lineTo([1, 1], %)', ' |> lineTo([1, 1], %)',
'// a comment', '// a comment',
' |> rx(90, %)', ' |> rx(90, %)',
@ -1540,8 +1511,8 @@ const key = 'c'`
.nonCodeNodes[3][0] .nonCodeNodes[3][0]
expect(sketchNonCodeMeta).toEqual({ expect(sketchNonCodeMeta).toEqual({
type: 'NonCodeNode', type: 'NonCodeNode',
start: 125, start: 114,
end: 138, end: 127,
value: { value: {
type: 'blockComment', type: 'blockComment',
value: 'a comment', value: 'a comment',

View File

@ -94,7 +94,7 @@ const mySketch001 = startSketchOn('XY')
const sk1 = startSketchOn('XY') const sk1 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> lineTo([-2.5, 0], %) |> lineTo([-2.5, 0], %)
|> lineTo({ to: [0, 10], tag: "p" }, %) |> lineTo([0, 10], %, "p")
|> lineTo([2.5, 0], %) |> lineTo([2.5, 0], %)
// |> rx(45, %) // |> rx(45, %)
// |> translate([1,0,1], %) // |> translate([1,0,1], %)
@ -104,7 +104,7 @@ const theExtrude = extrude(2, sk1)
const sk2 = startSketchOn('XY') const sk2 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> lineTo([-2.5, 0], %) |> lineTo([-2.5, 0], %)
|> lineTo({ to: [0, 3], tag: "p" }, %) |> lineTo([0, 3], %, "p")
|> lineTo([2.5, 0], %) |> lineTo([2.5, 0], %)
// |> transform(theTransf, %) // |> transform(theTransf, %)
|> extrude(2, %) |> extrude(2, %)
@ -143,7 +143,7 @@ const sk2 = startSketchOn('XY')
xAxis: { x: 1, y: 0, z: 0 }, xAxis: { x: 1, y: 0, z: 0 },
yAxis: { x: 0, y: 1, z: 0 }, yAxis: { x: 0, y: 1, z: 0 },
zAxis: { x: 0, y: 0, z: 1 }, zAxis: { x: 0, y: 0, z: 1 },
__meta: [{ sourceRange: [356, 381] }], __meta: [{ sourceRange: [343, 368] }],
}, },
]) ])
}) })

View File

@ -43,9 +43,9 @@ const newVar = myVar + 1`
it('sketch declaration', async () => { it('sketch declaration', async () => {
let code = `const mySketch = startSketchOn('XY') let code = `const mySketch = startSketchOn('XY')
|> startProfileAt([0,0], %) |> startProfileAt([0,0], %)
|> lineTo({to: [0,2], tag: "myPath"}, %) |> lineTo([0,2], %, "myPath")
|> lineTo([2,3], %) |> lineTo([2,3], %)
|> lineTo({ to: [5,-1], tag: "rightPath" }, %) |> lineTo([5,-1], %, "rightPath")
// |> close(%) // |> close(%)
` `
const { root } = await exe(code) const { root } = await exe(code)
@ -57,7 +57,7 @@ const newVar = myVar + 1`
to: [0, 2], to: [0, 2],
from: [0, 0], from: [0, 0],
__geoMeta: { __geoMeta: {
sourceRange: [72, 109], sourceRange: [72, 98],
id: expect.any(String), id: expect.any(String),
}, },
name: 'myPath', name: 'myPath',
@ -68,7 +68,7 @@ const newVar = myVar + 1`
from: [0, 2], from: [0, 2],
name: '', name: '',
__geoMeta: { __geoMeta: {
sourceRange: [115, 131], sourceRange: [104, 120],
id: expect.any(String), id: expect.any(String),
}, },
}, },
@ -77,7 +77,7 @@ const newVar = myVar + 1`
to: [5, -1], to: [5, -1],
from: [2, 3], from: [2, 3],
__geoMeta: { __geoMeta: {
sourceRange: [137, 180], sourceRange: [126, 156],
id: expect.any(String), id: expect.any(String),
}, },
name: 'rightPath', name: 'rightPath',
@ -99,7 +99,7 @@ const newVar = myVar + 1`
// const code = [ // const code = [
// 'const mySk1 = startSketchAt([0,0])', // 'const mySk1 = startSketchAt([0,0])',
// ' |> lineTo([1,1], %)', // ' |> lineTo([1,1], %)',
// ' |> lineTo({to: [0, 1], tag: "myPath"}, %)', // ' |> lineTo([0, 1], %, "myPath")',
// ' |> lineTo([1, 1], %)', // ' |> lineTo([1, 1], %)',
// 'const rotated = rx(90, mySk1)', // 'const rotated = rx(90, mySk1)',
// ].join('\n') // ].join('\n')
@ -126,7 +126,7 @@ const newVar = myVar + 1`
"const mySk1 = startSketchOn('XY')", "const mySk1 = startSketchOn('XY')",
' |> startProfileAt([0,0], %)', ' |> startProfileAt([0,0], %)',
' |> lineTo([1,1], %)', ' |> lineTo([1,1], %)',
' |> lineTo({to: [0, 1], tag: "myPath"}, %)', ' |> lineTo([0, 1], %, "myPath")',
' |> lineTo([1,1], %)', ' |> lineTo([1,1], %)',
// ' |> rx(90, %)', // ' |> rx(90, %)',
].join('\n') ].join('\n')
@ -159,7 +159,7 @@ const newVar = myVar + 1`
to: [0, 1], to: [0, 1],
from: [1, 1], from: [1, 1],
__geoMeta: { __geoMeta: {
sourceRange: [91, 129], sourceRange: [91, 118],
id: expect.any(String), id: expect.any(String),
}, },
name: 'myPath', name: 'myPath',
@ -170,7 +170,7 @@ const newVar = myVar + 1`
from: [0, 1], from: [0, 1],
name: '', name: '',
__geoMeta: { __geoMeta: {
sourceRange: [135, 151], sourceRange: [124, 140],
id: expect.any(String), id: expect.any(String),
}, },
}, },
@ -341,7 +341,7 @@ describe('testing math operators', () => {
`const myVar = 3`, `const myVar = 3`,
`const part001 = startSketchOn('XY')`, `const part001 = startSketchOn('XY')`,
` |> startProfileAt([0, 0], %)`, ` |> startProfileAt([0, 0], %)`,
` |> line({ to: [3, 4], tag: 'seg01' }, %)`, ` |> line([3, 4], %, 'seg01')`,
` |> line([`, ` |> line([`,
` min(segLen('seg01', %), myVar),`, ` min(segLen('seg01', %), myVar),`,
` -legLen(segLen('seg01', %), myVar)`, ` -legLen(segLen('seg01', %), myVar)`,

View File

@ -9,10 +9,10 @@ describe('testing getNodePathFromSourceRange', () => {
const myVar = 5 const myVar = 5
const sk3 = startSketchAt([0, 0]) const sk3 = startSketchAt([0, 0])
|> lineTo([1, 2], %) |> lineTo([1, 2], %)
|> lineTo({ to: [3, 4], tag: 'yo' }, %) |> lineTo([3, 4], %, 'yo')
|> close(%) |> close(%)
` `
const subStr = "lineTo({ to: [3, 4], tag: 'yo' }, %)" const subStr = "lineTo([3, 4], %, 'yo')"
const lineToSubstringIndex = code.indexOf(subStr) const lineToSubstringIndex = code.indexOf(subStr)
const sourceRange: [number, number] = [ const sourceRange: [number, number] = [
lineToSubstringIndex, lineToSubstringIndex,

View File

@ -152,25 +152,25 @@ describe('Testing giveSketchFnCallTag', () => {
code, code,
'line([0, 0.83], %)' 'line([0, 0.83], %)'
) )
expect(newCode).toContain("line({ to: [0, 0.83], tag: 'seg01' }, %)") expect(newCode).toContain("line([0, 0.83], %, 'seg01')")
expect(tag).toBe('seg01') expect(tag).toBe('seg01')
expect(isTagExisting).toBe(false) expect(isTagExisting).toBe(false)
}) })
it('Should create a unique tag if seg01 already exists', () => { it('Should create a unique tag if seg01 already exists', () => {
let _code = code.replace( let _code = code.replace(
'line([-2.57, -0.13], %)', 'line([-2.57, -0.13], %)',
"line({ to: [-2.57, -0.13], tag: 'seg01' }, %)" "line([-2.57, -0.13], %, 'seg01')"
) )
const { newCode, tag, isTagExisting } = giveSketchFnCallTagTestHelper( const { newCode, tag, isTagExisting } = giveSketchFnCallTagTestHelper(
_code, _code,
'line([0, 0.83], %)' 'line([0, 0.83], %)'
) )
expect(newCode).toContain("line({ to: [0, 0.83], tag: 'seg02' }, %)") expect(newCode).toContain("line([0, 0.83], %, 'seg02')")
expect(tag).toBe('seg02') expect(tag).toBe('seg02')
expect(isTagExisting).toBe(false) expect(isTagExisting).toBe(false)
}) })
it('Should return existing tag if it already exists', () => { it('Should return existing tag if it already exists', () => {
const lineButWithTag = "line({ to: [-2.57, -0.13], tag: 'butts' }, %)" const lineButWithTag = "line([-2.57, -0.13], %, 'butts')"
let _code = code.replace('line([-2.57, -0.13], %)', lineButWithTag) let _code = code.replace('line([-2.57, -0.13], %)', lineButWithTag)
const { newCode, tag, isTagExisting } = giveSketchFnCallTagTestHelper( const { newCode, tag, isTagExisting } = giveSketchFnCallTagTestHelper(
_code, _code,

View File

@ -23,11 +23,7 @@ import {
getNodePathFromSourceRange, getNodePathFromSourceRange,
isNodeSafeToReplace, isNodeSafeToReplace,
} from './queryAst' } from './queryAst'
import { import { addTagForSketchOnFace } from './std/sketch'
addTagForSketchOnFace,
getFirstArg,
createFirstArg,
} from './std/sketch'
import { isLiteralArrayOrStatic } from './std/sketchcombos' import { isLiteralArrayOrStatic } from './std/sketchcombos'
import { DefaultPlaneStr } from 'clientSideScene/sceneEntities' import { DefaultPlaneStr } from 'clientSideScene/sceneEntities'
import { roundOff } from 'lib/utils' import { roundOff } from 'lib/utils'
@ -606,23 +602,26 @@ export function giveSketchFnCallTag(
path, path,
'CallExpression' 'CallExpression'
) )
const firstArg = getFirstArg(primaryCallExp) // Tag is always 3rd expression now, using arg index feels brittle
const isTagExisting = !!firstArg.tag // but we can come up with a better way to identify tag later.
const tagValue = (firstArg.tag || const thirdArg = primaryCallExp.arguments?.[2]
createLiteral(tag || findUniqueName(ast, 'seg', 2))) as Literal const tagLiteral =
const tagStr = String(tagValue.value) thirdArg || (createLiteral(tag || findUniqueName(ast, 'seg', 2)) as Literal)
const newFirstArg = createFirstArg( const isTagExisting = !!thirdArg
primaryCallExp.callee.name as ToolTip, if (!isTagExisting) {
firstArg.val, primaryCallExp.arguments[2] = tagLiteral
tagValue }
) if ('value' in tagLiteral) {
primaryCallExp.arguments[0] = newFirstArg // Now TypeScript knows tagLiteral has a value property
return { return {
modifiedAst: ast, modifiedAst: ast,
tag: tagStr, tag: String(tagLiteral.value),
isTagExisting, isTagExisting,
pathToNode: path, pathToNode: path,
} }
} else {
throw new Error('Unable to assign tag without value')
}
} }
export function moveValueIntoNewVariable( export function moveValueIntoNewVariable(

View File

@ -250,7 +250,7 @@ describe('testing doesPipeHave', () => {
it('finds close', () => { it('finds close', () => {
const exampleCode = `const length001 = 2 const exampleCode = `const length001 = 2
const part001 = startSketchAt([-1.41, 3.46]) const part001 = startSketchAt([-1.41, 3.46])
|> line({ to: [19.49, 1.16], tag: 'seg01' }, %) |> line([19.49, 1.16], %, 'seg01')
|> angledLine([-35, length001], %) |> angledLine([-35, length001], %)
|> line([-3.22, -7.36], %) |> line([-3.22, -7.36], %)
|> angledLine([-175, segLen('seg01', %)], %) |> angledLine([-175, segLen('seg01', %)], %)
@ -267,7 +267,7 @@ const part001 = startSketchAt([-1.41, 3.46])
it('finds extrude', () => { it('finds extrude', () => {
const exampleCode = `const length001 = 2 const exampleCode = `const length001 = 2
const part001 = startSketchAt([-1.41, 3.46]) const part001 = startSketchAt([-1.41, 3.46])
|> line({ to: [19.49, 1.16], tag: 'seg01' }, %) |> line([19.49, 1.16], %, 'seg01')
|> angledLine([-35, length001], %) |> angledLine([-35, length001], %)
|> line([-3.22, -7.36], %) |> line([-3.22, -7.36], %)
|> angledLine([-175, segLen('seg01', %)], %) |> angledLine([-175, segLen('seg01', %)], %)
@ -285,7 +285,7 @@ const part001 = startSketchAt([-1.41, 3.46])
it('does NOT find close', () => { it('does NOT find close', () => {
const exampleCode = `const length001 = 2 const exampleCode = `const length001 = 2
const part001 = startSketchAt([-1.41, 3.46]) const part001 = startSketchAt([-1.41, 3.46])
|> line({ to: [19.49, 1.16], tag: 'seg01' }, %) |> line([19.49, 1.16], %, 'seg01')
|> angledLine([-35, length001], %) |> angledLine([-35, length001], %)
|> line([-3.22, -7.36], %) |> line([-3.22, -7.36], %)
|> angledLine([-175, segLen('seg01', %)], %) |> angledLine([-175, segLen('seg01', %)], %)
@ -314,7 +314,7 @@ describe('testing hasExtrudeSketchGroup', () => {
it('find sketch group', async () => { it('find sketch group', async () => {
const exampleCode = `const length001 = 2 const exampleCode = `const length001 = 2
const part001 = startSketchAt([-1.41, 3.46]) const part001 = startSketchAt([-1.41, 3.46])
|> line({ to: [19.49, 1.16], tag: 'seg01' }, %) |> line([19.49, 1.16], %, 'seg01')
|> angledLine([-35, length001], %) |> angledLine([-35, length001], %)
|> line([-3.22, -7.36], %) |> line([-3.22, -7.36], %)
|> angledLine([-175, segLen('seg01', %)], %)` |> angledLine([-175, segLen('seg01', %)], %)`
@ -330,7 +330,7 @@ const part001 = startSketchAt([-1.41, 3.46])
it('find extrude group', async () => { it('find extrude group', async () => {
const exampleCode = `const length001 = 2 const exampleCode = `const length001 = 2
const part001 = startSketchAt([-1.41, 3.46]) const part001 = startSketchAt([-1.41, 3.46])
|> line({ to: [19.49, 1.16], tag: 'seg01' }, %) |> line([19.49, 1.16], %, 'seg01')
|> angledLine([-35, length001], %) |> angledLine([-35, length001], %)
|> line([-3.22, -7.36], %) |> line([-3.22, -7.36], %)
|> angledLine([-175, segLen('seg01', %)], %) |> angledLine([-175, segLen('seg01', %)], %)

View File

@ -64,9 +64,9 @@ log(5, myVar)
}) })
it('recast sketch declaration', () => { it('recast sketch declaration', () => {
let code = `const mySketch = startSketchAt([0, 0]) let code = `const mySketch = startSketchAt([0, 0])
|> lineTo({ to: [0, 1], tag: "myPath" }, %) |> lineTo([0, 1], %, "myPath")
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
|> lineTo({ to: [1, 0], tag: "rightPath" }, %) |> lineTo([1, 0], %, "rightPath")
|> close(%) |> close(%)
` `
const { ast } = code2ast(code) const { ast } = code2ast(code)
@ -77,7 +77,7 @@ log(5, myVar)
const code = [ const code = [
'const mySk1 = startSketchAt([0, 0])', 'const mySk1 = startSketchAt([0, 0])',
' |> lineTo([1, 1], %)', ' |> lineTo([1, 1], %)',
' |> lineTo({ to: [0, 1], tag: "myTag" }, %)', ' |> lineTo([0, 1], %, "myTag")',
' |> lineTo([1, 1], %)', ' |> lineTo([1, 1], %)',
' |> rx(90, %)', ' |> rx(90, %)',
].join('\n') ].join('\n')
@ -237,7 +237,7 @@ const key = 'c'
const code = [ const code = [
'const mySk1 = startSketchAt([0, 0])', 'const mySk1 = startSketchAt([0, 0])',
' |> lineTo([1, 1], %)', ' |> lineTo([1, 1], %)',
' |> lineTo({ to: [0, 1], tag: "myTag" }, %)', ' |> lineTo([0, 1], %, "myTag")',
' |> lineTo([1, 1], %)', ' |> lineTo([1, 1], %)',
' // a comment', ' // a comment',
' |> rx(90, %)', ' |> rx(90, %)',
@ -253,7 +253,7 @@ const key = 'c'
const mySk1 = startSketchAt([0, 0]) const mySk1 = startSketchAt([0, 0])
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
// comment here // comment here
|> lineTo({ to: [0, 1], tag: 'myTag' }, %) |> lineTo([0, 1], %, 'myTag')
|> lineTo([1, 1], %) /* and |> lineTo([1, 1], %) /* and
here here
*/ */
@ -275,7 +275,7 @@ const mySk1 = startSketchAt([0, 0])
const mySk1 = startSketchAt([0, 0]) const mySk1 = startSketchAt([0, 0])
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
// comment here // comment here
|> lineTo({ to: [0, 1], tag: 'myTag' }, %) |> lineTo([0, 1], %, 'myTag')
|> lineTo([1, 1], %) /* and |> lineTo([1, 1], %) /* and
here */ here */
// a comment between pipe expression statements // a comment between pipe expression statements
@ -321,7 +321,7 @@ describe('testing call Expressions in BinaryExpressions and UnaryExpressions', (
describe('it recasts wrapped object expressions in pipe bodies with correct indentation', () => { describe('it recasts wrapped object expressions in pipe bodies with correct indentation', () => {
it('with a single line', () => { it('with a single line', () => {
const code = `const part001 = startSketchAt([-0.01, -0.08]) const code = `const part001 = startSketchAt([-0.01, -0.08])
|> line({ to: [0.62, 4.15], tag: 'seg01' }, %) |> line([0.62, 4.15], %, 'seg01')
|> line([2.77, -1.24], %) |> line([2.77, -1.24], %)
|> angledLineThatIntersects({ |> angledLineThatIntersects({
angle: 201, angle: 201,

View File

@ -206,9 +206,7 @@ describe('testing addTagForSketchOnFace', () => {
}, },
'lineTo' 'lineTo'
) )
const expectedCode = genCode( const expectedCode = genCode("lineTo([-1.59, -1.54], %, 'seg01')")
"lineTo({ to: [-1.59, -1.54], tag: 'seg01' }, %)"
)
expect(recast(modifiedAst)).toBe(expectedCode) expect(recast(modifiedAst)).toBe(expectedCode)
}) })
}) })

View File

@ -53,40 +53,34 @@ export function getCoordsFromPaths(skGroup: SketchGroup, index = 0): Coords2d {
export function createFirstArg( export function createFirstArg(
sketchFn: ToolTip, sketchFn: ToolTip,
val: Value | [Value, Value] | [Value, Value, Value], val: Value | [Value, Value] | [Value, Value, Value]
tag?: Value
): Value { ): Value {
if (!tag) {
if (Array.isArray(val)) { if (Array.isArray(val)) {
return createArrayExpression(val)
}
return val
}
if (Array.isArray(val)) {
if (['line', 'lineTo'].includes(sketchFn))
return createObjectExpression({ to: createArrayExpression(val), tag })
if ( if (
['angledLine', 'angledLineOfXLength', 'angledLineOfYLength'].includes( [
sketchFn 'angledLine',
'angledLineOfXLength',
'angledLineOfYLength',
'angledLineToX',
'angledLineToY',
'line',
'lineTo',
].includes(sketchFn)
) )
) return createArrayExpression(val)
return createObjectExpression({ angle: val[0], length: val[1], tag })
if (['angledLineToX', 'angledLineToY'].includes(sketchFn))
return createObjectExpression({ angle: val[0], to: val[1], tag })
if (['angledLineThatIntersects'].includes(sketchFn) && val[2]) if (['angledLineThatIntersects'].includes(sketchFn) && val[2])
return createObjectExpression({ return createObjectExpression({
angle: val[0], angle: val[0],
offset: val[1], offset: val[1],
intersectTag: val[2], intersectTag: val[2],
tag,
}) })
} else { } else {
if (['xLine', 'yLine'].includes(sketchFn)) if (
return createObjectExpression({ length: val, tag }) ['startSketchAt', 'xLine', 'xLineTo', 'yLine', 'yLineTo'].includes(
if (['xLineTo', 'yLineTo'].includes(sketchFn)) sketchFn
return createObjectExpression({ to: val, tag }) )
if (['startSketchAt'].includes(sketchFn)) )
return createObjectExpression({ to: val, tag }) return val
} }
throw new Error('all sketch line types should have been covered') throw new Error('all sketch line types should have been covered')
} }
@ -1190,67 +1184,20 @@ function addTagWithTo(
_node, _node,
pathToNode pathToNode
) )
const firstArg = callExpression.arguments?.[0] const tagArg = callExpression.arguments?.[2]
if (firstArg.type === 'ObjectExpression') { if (tagArg) {
const existingTagName = firstArg.properties?.find( return {
(prop) => prop.key.name === 'tag' modifiedAst: _node,
) tag: String(tagArg),
if (!existingTagName) { }
mutateObjExpProp(
callExpression.arguments?.[0],
createLiteral(tagName),
'tag'
)
} else { } else {
tagName = `${(existingTagName.value as Literal).value}` callExpression.arguments[2] = createLiteral(tagName)
}
return { return {
modifiedAst: _node, modifiedAst: _node,
tag: tagName, tag: tagName,
} }
} }
if (firstArg.type === 'ArrayExpression') {
const objExp =
argType === 'default'
? createObjectExpression({
to: firstArg,
tag: createLiteral(tagName),
})
: argType === 'angleLength'
? createObjectExpression({
angle: firstArg.elements[0],
length: firstArg.elements[1],
tag: createLiteral(tagName),
})
: createObjectExpression({
angle: firstArg.elements[0],
to: firstArg.elements[1],
tag: createLiteral(tagName),
})
callExpression.arguments[0] = objExp
return {
modifiedAst: _node,
tag: tagName,
}
}
if (firstArg.type === 'Literal') {
const objExp =
argType === 'length'
? createObjectExpression({
length: firstArg,
tag: createLiteral(tagName),
})
: createObjectExpression({
to: firstArg,
tag: createLiteral(tagName),
})
callExpression.arguments[0] = objExp
return {
modifiedAst: _node,
tag: tagName,
}
}
throw new Error('lineTo must be called with an object or array')
} }
} }

View File

@ -54,29 +54,17 @@ describe('testing swapping out sketch calls with xLine/xLineTo', () => {
const bigExampleArr = [ const bigExampleArr = [
`const part001 = startSketchOn('XY')`, `const part001 = startSketchOn('XY')`,
` |> startProfileAt([0, 0], %)`, ` |> startProfileAt([0, 0], %)`,
` |> lineTo({ to: [1, 1], tag: 'abc1' }, %)`, ` |> lineTo([1, 1], %, 'abc1')`,
` |> line({ to: [-2.04, -0.7], tag: 'abc2' }, %)`, ` |> line([-2.04, -0.7], %, 'abc2')`,
` |> angledLine({`, ` |> angledLine({ angle: 157, length: 1.69 }, %, 'abc3')`,
` angle: 157,`, ` |> angledLineOfXLength({ angle: 217, length: 0.86 }, %, 'abc4')`,
` length: 1.69,`, ` |> angledLineOfYLength({ angle: 104, length: 1.58 }, %, 'abc5')`,
` tag: 'abc3'`, ` |> angledLineToX({ angle: 55, to: -2.89 }, %, 'abc6')`,
` }, %)`, ` |> angledLineToY({ angle: 330, to: 2.53 }, %, 'abc7')`,
` |> angledLineOfXLength({`, ` |> xLine(1.47, %, 'abc8')`,
` angle: 217,`, ` |> yLine(1.57, %, 'abc9')`,
` length: 0.86,`, ` |> xLineTo(1.49, %, 'abc10')`,
` tag: 'abc4'`, ` |> yLineTo(2.64, %, 'abc11')`,
` }, %)`,
` |> angledLineOfYLength({`,
` angle: 104,`,
` length: 1.58,`,
` tag: 'abc5'`,
` }, %)`,
` |> angledLineToX({ angle: 55, to: -2.89, tag: 'abc6' }, %)`,
` |> angledLineToY({ angle: 330, to: 2.53, tag: 'abc7' }, %)`,
` |> xLine({ length: 1.47, tag: 'abc8' }, %)`,
` |> yLine({ length: 1.57, tag: 'abc9' }, %)`,
` |> xLineTo({ to: 1.49, tag: 'abc10' }, %)`,
` |> yLineTo({ to: 2.64, tag: 'abc11' }, %)`,
` |> lineTo([2.55, 3.58], %) // lineTo`, ` |> lineTo([2.55, 3.58], %) // lineTo`,
` |> line([0.73, -0.75], %)`, ` |> line([0.73, -0.75], %)`,
` |> angledLine([63, 1.38], %) // angledLine`, ` |> angledLine([63, 1.38], %) // angledLine`,
@ -91,8 +79,8 @@ describe('testing swapping out sketch calls with xLine/xLineTo', () => {
] ]
const bigExample = bigExampleArr.join('\n') const bigExample = bigExampleArr.join('\n')
it('line with tag converts to xLine', async () => { it('line with tag converts to xLine', async () => {
const callToSwap = "line({ to: [-2.04, -0.7], tag: 'abc2' }, %)" const callToSwap = "line([-2.04, -0.7], %, 'abc2')"
const expectedLine = "xLine({ length: -2.04, tag: 'abc2' }, %)" const expectedLine = "xLine(-2.04, %, 'abc2')"
const { newCode, originalRange } = await testingSwapSketchFnCall({ const { newCode, originalRange } = await testingSwapSketchFnCall({
inputCode: bigExample, inputCode: bigExample,
callToSwap, callToSwap,
@ -117,10 +105,10 @@ describe('testing swapping out sketch calls with xLine/xLineTo', () => {
it('lineTo with tag converts to xLineTo', async () => { it('lineTo with tag converts to xLineTo', async () => {
const { newCode, originalRange } = await testingSwapSketchFnCall({ const { newCode, originalRange } = await testingSwapSketchFnCall({
inputCode: bigExample, inputCode: bigExample,
callToSwap: "lineTo({ to: [1, 1], tag: 'abc1' }, %)", callToSwap: "lineTo([1, 1], %, 'abc1')",
constraintType: 'horizontal', constraintType: 'horizontal',
}) })
const expectedLine = "xLineTo({ to: 1, tag: 'abc1' }, %)" const expectedLine = "xLineTo(1, %, 'abc1')"
expect(newCode).toContain(expectedLine) expect(newCode).toContain(expectedLine)
// new line should start at the same place as the old line // new line should start at the same place as the old line
expect(originalRange[0]).toBe(newCode.indexOf(expectedLine)) expect(originalRange[0]).toBe(newCode.indexOf(expectedLine))
@ -139,16 +127,11 @@ describe('testing swapping out sketch calls with xLine/xLineTo', () => {
it('angledLine with tag converts to xLine', async () => { it('angledLine with tag converts to xLine', async () => {
const { newCode, originalRange } = await testingSwapSketchFnCall({ const { newCode, originalRange } = await testingSwapSketchFnCall({
inputCode: bigExample, inputCode: bigExample,
callToSwap: [ callToSwap: "angledLine({ angle: 157, length: 1.69 }, %, 'abc3')",
`angledLine({`,
` angle: 157,`,
` length: 1.69,`,
` tag: 'abc3'`,
` }, %)`,
].join('\n'),
constraintType: 'horizontal', constraintType: 'horizontal',
}) })
const expectedLine = "xLine({ length: -1.56, tag: 'abc3' }, %)" const expectedLine = "xLine(-1.56, %, 'abc3')"
console.log(newCode)
expect(newCode).toContain(expectedLine) expect(newCode).toContain(expectedLine)
// new line should start at the same place as the old line // new line should start at the same place as the old line
expect(originalRange[0]).toBe(newCode.indexOf(expectedLine)) expect(originalRange[0]).toBe(newCode.indexOf(expectedLine))
@ -167,16 +150,11 @@ describe('testing swapping out sketch calls with xLine/xLineTo', () => {
it('angledLineOfXLength with tag converts to xLine', async () => { it('angledLineOfXLength with tag converts to xLine', async () => {
const { newCode, originalRange } = await testingSwapSketchFnCall({ const { newCode, originalRange } = await testingSwapSketchFnCall({
inputCode: bigExample, inputCode: bigExample,
callToSwap: [ callToSwap:
`angledLineOfXLength({`, "angledLineOfXLength({ angle: 217, length: 0.86 }, %, 'abc4')",
` angle: 217,`,
` length: 0.86,`,
` tag: 'abc4'`,
` }, %)`,
].join('\n'),
constraintType: 'horizontal', constraintType: 'horizontal',
}) })
const expectedLine = "xLine({ length: -0.86, tag: 'abc4' }, %)" const expectedLine = "xLine(-0.86, %, 'abc4')"
// hmm "-0.86" is correct since the angle is 104, but need to make sure this is compatible `-myVar` // hmm "-0.86" is correct since the angle is 104, but need to make sure this is compatible `-myVar`
expect(newCode).toContain(expectedLine) expect(newCode).toContain(expectedLine)
// new line should start at the same place as the old line // new line should start at the same place as the old line
@ -196,16 +174,11 @@ describe('testing swapping out sketch calls with xLine/xLineTo', () => {
it('angledLineOfYLength with tag converts to yLine', async () => { it('angledLineOfYLength with tag converts to yLine', async () => {
const { newCode, originalRange } = await testingSwapSketchFnCall({ const { newCode, originalRange } = await testingSwapSketchFnCall({
inputCode: bigExample, inputCode: bigExample,
callToSwap: [ callToSwap:
`angledLineOfYLength({`, "angledLineOfYLength({ angle: 104, length: 1.58 }, %, 'abc5')",
` angle: 104,`,
` length: 1.58,`,
` tag: 'abc5'`,
` }, %)`,
].join('\n'),
constraintType: 'vertical', constraintType: 'vertical',
}) })
const expectedLine = "yLine({ length: 1.58, tag: 'abc5' }, %)" const expectedLine = "yLine(1.58, %, 'abc5')"
expect(newCode).toContain(expectedLine) expect(newCode).toContain(expectedLine)
// new line should start at the same place as the old line // new line should start at the same place as the old line
expect(originalRange[0]).toBe(newCode.indexOf(expectedLine)) expect(originalRange[0]).toBe(newCode.indexOf(expectedLine))
@ -224,10 +197,10 @@ describe('testing swapping out sketch calls with xLine/xLineTo', () => {
it('angledLineToX with tag converts to xLineTo', async () => { it('angledLineToX with tag converts to xLineTo', async () => {
const { newCode, originalRange } = await testingSwapSketchFnCall({ const { newCode, originalRange } = await testingSwapSketchFnCall({
inputCode: bigExample, inputCode: bigExample,
callToSwap: "angledLineToX({ angle: 55, to: -2.89, tag: 'abc6' }, %)", callToSwap: "angledLineToX({ angle: 55, to: -2.89 }, %, 'abc6')",
constraintType: 'horizontal', constraintType: 'horizontal',
}) })
const expectedLine = "xLineTo({ to: -2.89, tag: 'abc6' }, %)" const expectedLine = "xLineTo(-2.89, %, 'abc6')"
expect(newCode).toContain(expectedLine) expect(newCode).toContain(expectedLine)
// new line should start at the same place as the old line // new line should start at the same place as the old line
expect(originalRange[0]).toBe(newCode.indexOf(expectedLine)) expect(originalRange[0]).toBe(newCode.indexOf(expectedLine))
@ -246,10 +219,10 @@ describe('testing swapping out sketch calls with xLine/xLineTo', () => {
it('angledLineToY with tag converts to yLineTo', async () => { it('angledLineToY with tag converts to yLineTo', async () => {
const { newCode, originalRange } = await testingSwapSketchFnCall({ const { newCode, originalRange } = await testingSwapSketchFnCall({
inputCode: bigExample, inputCode: bigExample,
callToSwap: "angledLineToY({ angle: 330, to: 2.53, tag: 'abc7' }, %)", callToSwap: "angledLineToY({ angle: 330, to: 2.53 }, %, 'abc7')",
constraintType: 'vertical', constraintType: 'vertical',
}) })
const expectedLine = "yLineTo({ to: 2.53, tag: 'abc7' }, %)" const expectedLine = "yLineTo(2.53, %, 'abc7')"
expect(newCode).toContain(expectedLine) expect(newCode).toContain(expectedLine)
// new line should start at the same place as the old line // new line should start at the same place as the old line
expect(originalRange[0]).toBe(newCode.indexOf(expectedLine)) expect(originalRange[0]).toBe(newCode.indexOf(expectedLine))

View File

@ -131,7 +131,7 @@ const myAng = 40
const myAng2 = 134 const myAng2 = 134
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [1, 3.82], tag: 'seg01' }, %) // ln-should-get-tag |> line([1, 3.82], %, 'seg01') // ln-should-get-tag
|> angledLineToX([ |> angledLineToX([
-angleToMatchLengthX('seg01', myVar, %), -angleToMatchLengthX('seg01', myVar, %),
myVar myVar
@ -485,8 +485,7 @@ const part001 = startSketchOn('XY')
|> angledLine({ |> angledLine({
angle: halfArmAngle, angle: halfArmAngle,
length: 2.45, length: 2.45,
tag: 'seg01bing' }, %, 'seg01bing') // partial
}, %) // partial
|> xLine(4.4, %) // partial |> xLine(4.4, %) // partial
|> yLine(-1, %) // partial |> yLine(-1, %) // partial
|> xLine(-4.2 + 0, %) // full |> xLine(-4.2 + 0, %) // full

View File

@ -60,11 +60,12 @@ function createCallWrapper(
tag?: Value, tag?: Value,
valueUsedInTransform?: number valueUsedInTransform?: number
): ReturnType<TransformCallback> { ): ReturnType<TransformCallback> {
const args = [createFirstArg(a, val), createPipeSubstitution()]
if (tag) {
args.push(tag)
}
return { return {
callExp: createCallExpression(a, [ callExp: createCallExpression(a, args),
createFirstArg(a, val, tag),
createPipeSubstitution(),
]),
valueUsedInTransform, valueUsedInTransform,
} }
} }
@ -89,14 +90,15 @@ function intersectCallWrapper({
offset: offsetVal, offset: offsetVal,
intersectTag, intersectTag,
} }
if (tag) { const args: Value[] = [
firstArg['tag'] = tag
}
return {
callExp: createCallExpression(fnName, [
createObjectExpression(firstArg), createObjectExpression(firstArg),
createPipeSubstitution(), createPipeSubstitution(),
]), ]
if (tag) {
args.push(tag)
}
return {
callExp: createCallExpression(fnName, args),
valueUsedInTransform, valueUsedInTransform,
} }
} }
@ -1419,7 +1421,8 @@ export function transformAstSketchLines({
const callExp = getNode<CallExpression>('CallExpression')?.node const callExp = getNode<CallExpression>('CallExpression')?.node
const varDec = getNode<VariableDeclarator>('VariableDeclarator').node const varDec = getNode<VariableDeclarator>('VariableDeclarator').node
const { val, tag: callBackTag } = getFirstArg(callExp) const { val } = getFirstArg(callExp)
const callBackTag = callExp.arguments[2]
const _referencedSegmentNameVal = const _referencedSegmentNameVal =
callExp.arguments[0]?.type === 'ObjectExpression' && callExp.arguments[0]?.type === 'ObjectExpression' &&
callExp.arguments[0].properties?.find( callExp.arguments[0].properties?.find(

View File

@ -7,14 +7,13 @@ describe('testing angledLineThatIntersects', () => {
it('angledLineThatIntersects should intersect with another line', async () => { it('angledLineThatIntersects should intersect with another line', async () => {
const code = (offset: string) => `const part001 = startSketchOn('XY') const code = (offset: string) => `const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> lineTo({to:[2, 2], tag: "yo"}, %) |> lineTo([2, 2], %, "yo")
|> lineTo([3, 1], %) |> lineTo([3, 1], %)
|> angledLineThatIntersects({ |> angledLineThatIntersects({
angle: 180, angle: 180,
intersectTag: 'yo', intersectTag: 'yo',
offset: ${offset}, offset: ${offset},
tag: "yo2" }, %, "yo2")
}, %)
const intersect = segEndX('yo2', part001)` const intersect = segEndX('yo2', part001)`
const { root } = await enginelessExecutor(parse(code('-1'))) const { root } = await enginelessExecutor(parse(code('-1')))
expect(root.intersect.value).toBe(1 + Math.sqrt(2)) expect(root.intersect.value).toBe(1 + Math.sqrt(2))

View File

@ -3351,7 +3351,7 @@ const mySk1 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
// comment here // comment here
|> lineTo({ to: [0, 1], tag: 'myTag' }, %) |> lineTo([0, 1], %, 'myTag')
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
/* and /* and
here here
@ -3374,7 +3374,7 @@ const mySk1 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
// comment here // comment here
|> lineTo({ to: [0, 1], tag: 'myTag' }, %) |> lineTo([0, 1], %, 'myTag')
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
/* and /* and
here */ here */
@ -3392,7 +3392,7 @@ const mySk1 = startSketchOn('XY')
fn test_recast_multiline_object() { fn test_recast_multiline_object() {
let some_program_string = r#"const part001 = startSketchOn('XY') let some_program_string = r#"const part001 = startSketchOn('XY')
|> startProfileAt([-0.01, -0.08], %) |> startProfileAt([-0.01, -0.08], %)
|> line({ to: [0.62, 4.15], tag: 'seg01' }, %) |> line([0.62, 4.15], %, 'seg01')
|> line([2.77, -1.24], %) |> line([2.77, -1.24], %)
|> angledLineThatIntersects({ |> angledLineThatIntersects({
angle: 201, angle: 201,
@ -3482,7 +3482,7 @@ const myAng = 40
const myAng2 = 134 const myAng2 = 134
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [1, 3.82], tag: 'seg01' }, %) // ln-should-get-tag |> line([1, 3.82], %, 'seg01') // ln-should-get-tag
|> angledLineToX([ |> angledLineToX([
-angleToMatchLengthX('seg01', myVar, %), -angleToMatchLengthX('seg01', myVar, %),
myVar myVar
@ -3508,7 +3508,7 @@ const myAng = 40
const myAng2 = 134 const myAng2 = 134
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [1, 3.82], tag: 'seg01' }, %) // ln-should-get-tag |> line([1, 3.82], %, 'seg01') // ln-should-get-tag
|> angledLineToX([ |> angledLineToX([
-angleToMatchLengthX('seg01', myVar, %), -angleToMatchLengthX('seg01', myVar, %),
myVar myVar

View File

@ -1323,14 +1323,13 @@ const newVar = myVar + 1"#;
format!( format!(
r#"const part001 = startSketchOn('XY') r#"const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> lineTo({{to:[2, 2], tag: "yo"}}, %) |> lineTo([2, 2], %, "yo")
|> lineTo([3, 1], %) |> lineTo([3, 1], %)
|> angledLineThatIntersects({{ |> angledLineThatIntersects({{
angle: 180, angle: 180,
intersectTag: 'yo', intersectTag: 'yo',
offset: {}, offset: {},
tag: "yo2" }}, %, 'yo2')
}}, %)
const intersect = segEndX('yo2', part001)"#, const intersect = segEndX('yo2', part001)"#,
offset offset
) )
@ -1387,7 +1386,7 @@ const yo2 = hmm([identifierGuy + 5])"#;
let ast = r#"const myVar = 3 let ast = r#"const myVar = 3
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [3, 4], tag: 'seg01' }, %) |> line([3, 4], %, 'seg01')
|> line([ |> line([
min(segLen('seg01', %), myVar), min(segLen('seg01', %), myVar),
-legLen(segLen('seg01', %), myVar) -legLen(segLen('seg01', %), myVar)
@ -1402,7 +1401,7 @@ const part001 = startSketchOn('XY')
let ast = r#"const myVar = 3 let ast = r#"const myVar = 3
const part001 = startSketchOn('XY') const part001 = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line({ to: [3, 4], tag: 'seg01' }, %) |> line([3, 4], %, 'seg01')
|> line([ |> line([
min(segLen('seg01', %), myVar), min(segLen('seg01', %), myVar),
legLen(segLen('seg01', %), myVar) legLen(segLen('seg01', %), myVar)

View File

@ -2903,9 +2903,9 @@ mod snapshot_tests {
snapshot_test!( snapshot_test!(
af, af,
r#"const mySketch = startSketchAt([0,0]) r#"const mySketch = startSketchAt([0,0])
|> lineTo({ to: [0, 1], tag: 'myPath' }, %) |> lineTo([0, 1], %, 'myPath')
|> lineTo([1, 1], %) |> lineTo([1, 1], %)
|> lineTo({ to: [1,0], tag: "rightPath" }, %) |> lineTo([1, 0], %, 'rightPath')
|> close(%)"# |> close(%)"#
); );
snapshot_test!( snapshot_test!(

View File

@ -4,18 +4,18 @@ expression: actual
--- ---
{ {
"start": 0, "start": 0,
"end": 192, "end": 167,
"body": [ "body": [
{ {
"type": "VariableDeclaration", "type": "VariableDeclaration",
"type": "VariableDeclaration", "type": "VariableDeclaration",
"start": 0, "start": 0,
"end": 192, "end": 167,
"declarations": [ "declarations": [
{ {
"type": "VariableDeclarator", "type": "VariableDeclarator",
"start": 6, "start": 6,
"end": 192, "end": 167,
"id": { "id": {
"type": "Identifier", "type": "Identifier",
"start": 6, "start": 6,
@ -26,7 +26,7 @@ expression: actual
"type": "PipeExpression", "type": "PipeExpression",
"type": "PipeExpression", "type": "PipeExpression",
"start": 17, "start": 17,
"end": 192, "end": 167,
"body": [ "body": [
{ {
"type": "CallExpression", "type": "CallExpression",
@ -71,7 +71,7 @@ expression: actual
"type": "CallExpression", "type": "CallExpression",
"type": "CallExpression", "type": "CallExpression",
"start": 49, "start": 49,
"end": 89, "end": 76,
"callee": { "callee": {
"type": "Identifier", "type": "Identifier",
"start": 49, "start": 49,
@ -80,107 +80,77 @@ expression: actual
}, },
"arguments": [ "arguments": [
{ {
"type": "ObjectExpression", "type": "ArrayExpression",
"type": "ObjectExpression", "type": "ArrayExpression",
"start": 56, "start": 56,
"end": 85, "end": 62,
"properties": [
{
"type": "ObjectProperty",
"start": 58,
"end": 68,
"key": {
"type": "Identifier",
"start": 58,
"end": 60,
"name": "to"
},
"value": {
"type": "ArrayExpression",
"type": "ArrayExpression",
"start": 62,
"end": 68,
"elements": [ "elements": [
{ {
"type": "Literal", "type": "Literal",
"type": "Literal", "type": "Literal",
"start": 63, "start": 57,
"end": 64, "end": 58,
"value": 0, "value": 0,
"raw": "0" "raw": "0"
}, },
{ {
"type": "Literal", "type": "Literal",
"type": "Literal", "type": "Literal",
"start": 66, "start": 60,
"end": 67, "end": 61,
"value": 1, "value": 1,
"raw": "1" "raw": "1"
} }
] ]
}
}, },
{ {
"type": "ObjectProperty", "type": "PipeSubstitution",
"start": 70, "type": "PipeSubstitution",
"end": 83, "start": 64,
"key": { "end": 65
"type": "Identifier",
"start": 70,
"end": 73,
"name": "tag"
}, },
"value": { {
"type": "Literal", "type": "Literal",
"type": "Literal", "type": "Literal",
"start": 75, "start": 67,
"end": 83, "end": 75,
"value": "myPath", "value": "myPath",
"raw": "'myPath'" "raw": "'myPath'"
} }
}
]
},
{
"type": "PipeSubstitution",
"type": "PipeSubstitution",
"start": 87,
"end": 88
}
], ],
"optional": false "optional": false
}, },
{ {
"type": "CallExpression", "type": "CallExpression",
"type": "CallExpression", "type": "CallExpression",
"start": 101, "start": 88,
"end": 118, "end": 105,
"callee": { "callee": {
"type": "Identifier", "type": "Identifier",
"start": 101, "start": 88,
"end": 107, "end": 94,
"name": "lineTo" "name": "lineTo"
}, },
"arguments": [ "arguments": [
{ {
"type": "ArrayExpression", "type": "ArrayExpression",
"type": "ArrayExpression", "type": "ArrayExpression",
"start": 108, "start": 95,
"end": 114, "end": 101,
"elements": [ "elements": [
{ {
"type": "Literal", "type": "Literal",
"type": "Literal", "type": "Literal",
"start": 109, "start": 96,
"end": 110, "end": 97,
"value": 1, "value": 1,
"raw": "1" "raw": "1"
}, },
{ {
"type": "Literal", "type": "Literal",
"type": "Literal", "type": "Literal",
"start": 112, "start": 99,
"end": 113, "end": 100,
"value": 1, "value": 1,
"raw": "1" "raw": "1"
} }
@ -189,8 +159,8 @@ expression: actual
{ {
"type": "PipeSubstitution", "type": "PipeSubstitution",
"type": "PipeSubstitution", "type": "PipeSubstitution",
"start": 116, "start": 103,
"end": 117 "end": 104
} }
], ],
"optional": false "optional": false
@ -198,82 +168,52 @@ expression: actual
{ {
"type": "CallExpression", "type": "CallExpression",
"type": "CallExpression", "type": "CallExpression",
"start": 130, "start": 117,
"end": 172,
"callee": {
"type": "Identifier",
"start": 130,
"end": 136,
"name": "lineTo"
},
"arguments": [
{
"type": "ObjectExpression",
"type": "ObjectExpression",
"start": 137,
"end": 168,
"properties": [
{
"type": "ObjectProperty",
"start": 139,
"end": 148,
"key": {
"type": "Identifier",
"start": 139,
"end": 141,
"name": "to"
},
"value": {
"type": "ArrayExpression",
"type": "ArrayExpression",
"start": 143,
"end": 148,
"elements": [
{
"type": "Literal",
"type": "Literal",
"start": 144,
"end": 145,
"value": 1,
"raw": "1"
},
{
"type": "Literal",
"type": "Literal",
"start": 146,
"end": 147, "end": 147,
"callee": {
"type": "Identifier",
"start": 117,
"end": 123,
"name": "lineTo"
},
"arguments": [
{
"type": "ArrayExpression",
"type": "ArrayExpression",
"start": 124,
"end": 130,
"elements": [
{
"type": "Literal",
"type": "Literal",
"start": 125,
"end": 126,
"value": 1,
"raw": "1"
},
{
"type": "Literal",
"type": "Literal",
"start": 128,
"end": 129,
"value": 0, "value": 0,
"raw": "0" "raw": "0"
} }
] ]
}
}, },
{ {
"type": "ObjectProperty", "type": "PipeSubstitution",
"start": 150, "type": "PipeSubstitution",
"end": 166, "start": 132,
"key": { "end": 133
"type": "Identifier",
"start": 150,
"end": 153,
"name": "tag"
}, },
"value": { {
"type": "Literal", "type": "Literal",
"type": "Literal", "type": "Literal",
"start": 155, "start": 135,
"end": 166, "end": 146,
"value": "rightPath", "value": "rightPath",
"raw": "\"rightPath\"" "raw": "'rightPath'"
}
}
]
},
{
"type": "PipeSubstitution",
"type": "PipeSubstitution",
"start": 170,
"end": 171
} }
], ],
"optional": false "optional": false
@ -281,20 +221,20 @@ expression: actual
{ {
"type": "CallExpression", "type": "CallExpression",
"type": "CallExpression", "type": "CallExpression",
"start": 184, "start": 159,
"end": 192, "end": 167,
"callee": { "callee": {
"type": "Identifier", "type": "Identifier",
"start": 184, "start": 159,
"end": 189, "end": 164,
"name": "close" "name": "close"
}, },
"arguments": [ "arguments": [
{ {
"type": "PipeSubstitution", "type": "PipeSubstitution",
"type": "PipeSubstitution", "type": "PipeSubstitution",
"start": 190, "start": 165,
"end": 191 "end": 166
} }
], ],
"optional": false "optional": false

View File

@ -196,7 +196,7 @@ pub async fn get_extrude_wall_transform(args: Args) -> Result<MemoryItem, KclErr
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line([0, 10], %) /// |> line([0, 10], %)
/// |> line([10, 0], %) /// |> line([10, 0], %)
/// |> line({to: [0, -10], tag: "surface"}, %) /// |> line([0, -10], %, "surface")
/// |> close(%) /// |> close(%)
/// |> extrude(5, %) /// |> extrude(5, %)
/// ///

View File

@ -48,9 +48,9 @@ pub async fn fillet(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// const part001 = startSketchOn('XY') /// const part001 = startSketchOn('XY')
/// |> startProfileAt([0,0], %) /// |> startProfileAt([0,0], %)
/// |> line({to: [0, 10], tag: "thing"}, %) /// |> line([0, 10], %, "thing")
/// |> line([10, 0], %) /// |> line([10, 0], %)
/// |> line({to: [0, -10], tag: "thing2"}, %) /// |> line([0, -10], %, "thing2")
/// |> close(%) /// |> close(%)
/// |> extrude(10, %) /// |> extrude(10, %)
/// |> fillet({radius: 2, tags: ["thing", "thing2"]}, %) /// |> fillet({radius: 2, tags: ["thing", "thing2"]}, %)
@ -130,9 +130,9 @@ pub async fn get_opposite_edge(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// const part001 = startSketchOn('XY') /// const part001 = startSketchOn('XY')
/// |> startProfileAt([0,0], %) /// |> startProfileAt([0,0], %)
/// |> line({to: [0, 10], tag: "thing"}, %) /// |> line([0, 10], %, "thing")
/// |> line([10, 0], %) /// |> line([10, 0], %)
/// |> line({to: [0, -10], tag: "thing2"}, %) /// |> line([0, -10], %, "thing2")
/// |> close(%) /// |> close(%)
/// |> extrude(10, %) /// |> extrude(10, %)
/// |> fillet({radius: 2, tags: ["thing", getOppositeEdge("thing", %)]}, %) /// |> fillet({radius: 2, tags: ["thing", getOppositeEdge("thing", %)]}, %)
@ -199,9 +199,9 @@ pub async fn get_next_adjacent_edge(args: Args) -> Result<MemoryItem, KclError>
/// ```no_run /// ```no_run
/// const part001 = startSketchOn('XY') /// const part001 = startSketchOn('XY')
/// |> startProfileAt([0,0], %) /// |> startProfileAt([0,0], %)
/// |> line({to: [0, 10], tag: "thing"}, %) /// |> line([0, 10], %, "thing")
/// |> line({to: [10, 0], tag: "thing1"}, %) /// |> line([10, 0], %, "thing1")
/// |> line({to: [0, -10], tag: "thing2"}, %) /// |> line([0, -10], %, "thing2")
/// |> close(%) /// |> close(%)
/// |> extrude(10, %) /// |> extrude(10, %)
/// |> fillet({radius: 2, tags: [getNextAdjacentEdge("thing", %)]}, %) /// |> fillet({radius: 2, tags: [getNextAdjacentEdge("thing", %)]}, %)
@ -277,9 +277,9 @@ pub async fn get_previous_adjacent_edge(args: Args) -> Result<MemoryItem, KclErr
/// ```no_run /// ```no_run
/// const part001 = startSketchOn('XY') /// const part001 = startSketchOn('XY')
/// |> startProfileAt([0,0], %) /// |> startProfileAt([0,0], %)
/// |> line({to: [0, 10], tag: "thing"}, %) /// |> line([0, 10], %, "thing")
/// |> line({to: [10, 0], tag: "thing1"}, %) /// |> line([10, 0], %, "thing1")
/// |> line({to: [0, -10], tag: "thing2"}, %) /// |> line([0, -10], %, "thing2")
/// |> close(%) /// |> close(%)
/// |> extrude(10, %) /// |> extrude(10, %)
/// |> fillet({radius: 2, tags: [getPreviousAdjacentEdge("thing2", %)]}, %) /// |> fillet({radius: 2, tags: [getPreviousAdjacentEdge("thing2", %)]}, %)

View File

@ -622,7 +622,54 @@ impl Args {
Ok((data, sketch_group)) Ok((data, sketch_group))
} }
fn get_data_and_sketch_surface<T: serde::de::DeserializeOwned>(&self) -> Result<(T, SketchSurface), KclError> { fn get_data_and_sketch_group_and_tag<T: serde::de::DeserializeOwned>(
&self,
) -> Result<(T, Box<SketchGroup>, Option<String>), KclError> {
let first_value = self
.args
.first()
.ok_or_else(|| {
KclError::Type(KclErrorDetails {
message: format!("Expected a struct as the first argument, found `{:?}`", self.args),
source_ranges: vec![self.source_range],
})
})?
.get_json_value()?;
let data: T = serde_json::from_value(first_value).map_err(|e| {
KclError::Type(KclErrorDetails {
message: format!("Failed to deserialize struct from JSON: {}", e),
source_ranges: vec![self.source_range],
})
})?;
let second_value = self.args.get(1).ok_or_else(|| {
KclError::Type(KclErrorDetails {
message: format!("Expected a SketchGroup as the second argument, found `{:?}`", self.args),
source_ranges: vec![self.source_range],
})
})?;
let sketch_group = if let MemoryItem::SketchGroup(sg) = second_value {
sg.clone()
} else {
return Err(KclError::Type(KclErrorDetails {
message: format!("Expected a SketchGroup as the second argument, found `{:?}`", self.args),
source_ranges: vec![self.source_range],
}));
};
let tag = if let Some(tag) = self.args.get(2) {
tag.get_json_opt()?
} else {
None
};
Ok((data, sketch_group, tag))
}
fn get_data_and_sketch_surface<T: serde::de::DeserializeOwned>(
&self,
) -> Result<(T, SketchSurface, Option<String>), KclError> {
let first_value = self let first_value = self
.args .args
.first() .first()
@ -661,8 +708,13 @@ impl Args {
source_ranges: vec![self.source_range], source_ranges: vec![self.source_range],
})); }));
}; };
let tag = if let Some(tag) = self.args.get(2) {
tag.get_json_opt()?
} else {
None
};
Ok((data, sketch_surface)) Ok((data, sketch_surface, tag))
} }
fn get_data_and_extrude_group<T: serde::de::DeserializeOwned>(&self) -> Result<(T, Box<ExtrudeGroup>), KclError> { fn get_data_and_extrude_group<T: serde::de::DeserializeOwned>(&self) -> Result<(T, Box<ExtrudeGroup>), KclError> {

View File

@ -24,7 +24,7 @@ pub async fn segment_end_x(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn("YZ") /// startSketchOn("YZ")
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({ to: [5, 0], tag: "thing" }, %) /// |> line([5, 0], %, "thing")
/// |> line([5, 5], %) /// |> line([5, 5], %)
/// |> line([segEndX("thing", %), 5], %) /// |> line([segEndX("thing", %), 5], %)
/// |> close(%) /// |> close(%)
@ -60,7 +60,7 @@ pub async fn segment_end_y(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn("YZ") /// startSketchOn("YZ")
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({ to: [5, 0], tag: "thing" }, %) /// |> line([5, 0], %, "thing")
/// |> line([5, 5], %) /// |> line([5, 5], %)
/// |> line([segEndY("thing", %), 5], %) /// |> line([segEndY("thing", %), 5], %)
/// |> close(%) /// |> close(%)
@ -96,7 +96,7 @@ pub async fn last_segment_x(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn("YZ") /// startSketchOn("YZ")
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({ to: [5, 0], tag: "thing" }, %) /// |> line([5, 0], %, "thing")
/// |> line([5, 5], %) /// |> line([5, 5], %)
/// |> line([0, lastSegX(%)], %) /// |> line([0, lastSegX(%)], %)
/// |> close(%) /// |> close(%)
@ -136,7 +136,7 @@ pub async fn last_segment_y(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn("YZ") /// startSketchOn("YZ")
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({ to: [5, 0], tag: "thing" }, %) /// |> line([5, 0], %, "thing")
/// |> line([5, 5], %) /// |> line([5, 5], %)
/// |> line([0, lastSegY(%)], %) /// |> line([0, lastSegY(%)], %)
/// |> close(%) /// |> close(%)
@ -175,7 +175,7 @@ pub async fn segment_length(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn("YZ") /// startSketchOn("YZ")
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({ to: [5, 0], tag: "thing" }, %) /// |> line([5, 0], %, "thing")
/// |> line([5, 5], %) /// |> line([5, 5], %)
/// |> line([0, segLen("thing", %)], %) /// |> line([0, segLen("thing", %)], %)
/// |> close(%) /// |> close(%)
@ -215,7 +215,7 @@ pub async fn segment_angle(args: Args) -> Result<MemoryItem, KclError> {
/// const part001 = startSketchOn('XY') /// const part001 = startSketchOn('XY')
/// |> startProfileAt([4.83, 12.56], %) /// |> startProfileAt([4.83, 12.56], %)
/// |> line([15.1, 2.48], %) /// |> line([15.1, 2.48], %)
/// |> line({ to: [3.15, -9.85], tag: 'seg01' }, %) /// |> line([3.15, -9.85], %, 'seg01')
/// |> line([-15.17, -4.1], %) /// |> line([-15.17, -4.1], %)
/// |> angledLine([segAng('seg01', %), 12.35], %) /// |> angledLine([segAng('seg01', %), 12.35], %)
/// |> line([-13.02, 10.03], %) /// |> line([-13.02, 10.03], %)
@ -254,7 +254,7 @@ pub async fn angle_to_match_length_x(args: Args) -> Result<MemoryItem, KclError>
/// ```no_run /// ```no_run
/// const part001 = startSketchOn('XY') /// const part001 = startSketchOn('XY')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({ to: [1, 3.82], tag: 'seg01' }, %) /// |> line([1, 3.82], %, 'seg01')
/// |> angledLineToX([ /// |> angledLineToX([
/// -angleToMatchLengthX('seg01', 10, %), /// -angleToMatchLengthX('seg01', 10, %),
/// 5 /// 5
@ -320,7 +320,7 @@ pub async fn angle_to_match_length_y(args: Args) -> Result<MemoryItem, KclError>
/// ```no_run /// ```no_run
/// const part001 = startSketchOn('XY') /// const part001 = startSketchOn('XY')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({ to: [1, 3.82], tag: 'seg01' }, %) /// |> line([1, 3.82], %, 'seg01')
/// |> angledLineToX([ /// |> angledLineToX([
/// -angleToMatchLengthY('seg01', 10, %), /// -angleToMatchLengthY('seg01', 10, %),
/// 5 /// 5

View File

@ -58,11 +58,8 @@ async fn inner_circle(
SketchSurfaceOrGroup::SketchSurface(surface) => surface, SketchSurfaceOrGroup::SketchSurface(surface) => surface,
SketchSurfaceOrGroup::SketchGroup(group) => group.on, SketchSurfaceOrGroup::SketchGroup(group) => group.on,
}; };
let mut sketch_group = crate::std::sketch::inner_start_profile_at( let mut sketch_group =
crate::std::sketch::LineData::Point([center[0] + radius, center[1]]), crate::std::sketch::inner_start_profile_at([center[0] + radius, center[1]], sketch_surface, None, args.clone())
sketch_surface,
args.clone(),
)
.await?; .await?;
// Call arc. // Call arc.
@ -71,9 +68,9 @@ async fn inner_circle(
angle_start: 0.0, angle_start: 0.0,
angle_end: 360.0, angle_end: 360.0,
radius, radius,
tag,
}, },
sketch_group, sketch_group,
tag,
args.clone(), args.clone(),
) )
.await?; .await?;

View File

@ -23,27 +23,12 @@ use crate::{
}, },
}; };
/// Data to draw a line to a point.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum LineToData {
/// A point with a tag.
PointWithTag {
/// The to point.
to: [f64; 2],
/// The tag.
tag: String,
},
/// A point.
Point([f64; 2]),
}
/// Draw a line to a point. /// Draw a line to a point.
pub async fn line_to(args: Args) -> Result<MemoryItem, KclError> { pub async fn line_to(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (LineToData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (to, sketch_group, tag): ([f64; 2], Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_line_to(data, sketch_group, args).await?; let new_sketch_group = inner_line_to(to, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -53,18 +38,9 @@ pub async fn line_to(args: Args) -> Result<MemoryItem, KclError> {
/// fn rectShape = (pos, w, l) => { /// fn rectShape = (pos, w, l) => {
/// const rr = startSketchOn('YZ') /// const rr = startSketchOn('YZ')
/// |> startProfileAt([pos[0] - (w / 2), pos[1] - (l / 2)], %) /// |> startProfileAt([pos[0] - (w / 2), pos[1] - (l / 2)], %)
/// |> lineTo({ /// |> lineTo([pos[0] + w / 2, pos[1] - (l / 2)], %, "edge1")
/// to: [pos[0] + w / 2, pos[1] - (l / 2)], /// |> lineTo([pos[0] + w / 2, pos[1] + l / 2], %, "edge2")
/// tag: "edge1" /// |> lineTo([pos[0] - (w / 2), pos[1] + l / 2], %, "edge3")
/// }, %)
/// |> lineTo({
/// to: [pos[0] + w / 2, pos[1] + l / 2],
/// tag: "edge2"
/// }, %)
/// |> lineTo({
/// to: [pos[0] - (w / 2), pos[1] + l / 2],
/// tag: "edge3"
/// }, %)
/// |> close(%, "edge4") /// |> close(%, "edge4")
/// return rr /// return rr
/// } /// }
@ -76,16 +52,12 @@ pub async fn line_to(args: Args) -> Result<MemoryItem, KclError> {
name = "lineTo", name = "lineTo",
}] }]
async fn inner_line_to( async fn inner_line_to(
data: LineToData, to: [f64; 2],
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?; let from = sketch_group.get_coords_from_paths()?;
let to = match data {
LineToData::PointWithTag { to, .. } => to,
LineToData::Point(to) => to,
};
let id = uuid::Uuid::new_v4(); let id = uuid::Uuid::new_v4();
args.send_modeling_cmd( args.send_modeling_cmd(
@ -108,11 +80,7 @@ async fn inner_line_to(
base: BasePath { base: BasePath {
from: from.into(), from: from.into(),
to, to,
name: if let LineToData::PointWithTag { tag, .. } = data { name: tag.unwrap_or("".to_string()),
tag.to_string()
} else {
"".to_string()
},
geo_meta: GeoMeta { geo_meta: GeoMeta {
id, id,
metadata: args.source_range.into(), metadata: args.source_range.into(),
@ -126,27 +94,11 @@ async fn inner_line_to(
Ok(new_sketch_group) Ok(new_sketch_group)
} }
/// Data to draw a line to a point on an axis.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum AxisLineToData {
/// A point with a tag.
PointWithTag {
/// The to point.
to: f64,
/// The tag.
tag: String,
},
/// A point.
Point(f64),
}
/// Draw a line to a point on the x-axis. /// Draw a line to a point on the x-axis.
pub async fn x_line_to(args: Args) -> Result<MemoryItem, KclError> { pub async fn x_line_to(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AxisLineToData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (to, sketch_group, tag): (f64, Box<SketchGroup>, Option<String>) = args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_x_line_to(data, sketch_group, args).await?; let new_sketch_group = inner_x_line_to(to, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -155,10 +107,7 @@ pub async fn x_line_to(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn('XY') /// startSketchOn('XY')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> xLineTo({ /// |> xLineTo(10, %, "edge1")
/// to: 10,
/// tag: "edge1"
/// }, %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> close(%, "edge2") /// |> close(%, "edge2")
/// |> extrude(10, %) /// |> extrude(10, %)
@ -167,27 +116,23 @@ pub async fn x_line_to(args: Args) -> Result<MemoryItem, KclError> {
name = "xLineTo", name = "xLineTo",
}] }]
async fn inner_x_line_to( async fn inner_x_line_to(
data: AxisLineToData, to: f64,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?; let from = sketch_group.get_coords_from_paths()?;
let line_to_data = match data { let new_sketch_group = inner_line_to([to, from.y], sketch_group, tag, args).await?;
AxisLineToData::PointWithTag { to, tag } => LineToData::PointWithTag { to: [to, from.y], tag },
AxisLineToData::Point(data) => LineToData::Point([data, from.y]),
};
let new_sketch_group = inner_line_to(line_to_data, sketch_group, args).await?;
Ok(new_sketch_group) Ok(new_sketch_group)
} }
/// Draw a line to a point on the y-axis. /// Draw a line to a point on the y-axis.
pub async fn y_line_to(args: Args) -> Result<MemoryItem, KclError> { pub async fn y_line_to(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AxisLineToData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (to, sketch_group, tag): (f64, Box<SketchGroup>, Option<String>) = args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_y_line_to(data, sketch_group, args).await?; let new_sketch_group = inner_y_line_to(to, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -196,10 +141,7 @@ pub async fn y_line_to(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn('XZ') /// startSketchOn('XZ')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> yLineTo({ /// |> yLineTo(10, %, "edge1")
/// to: 10,
/// tag: "edge1"
/// }, %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> close(%, "edge2") /// |> close(%, "edge2")
/// |> extrude(10, %) /// |> extrude(10, %)
@ -209,42 +151,23 @@ pub async fn y_line_to(args: Args) -> Result<MemoryItem, KclError> {
name = "yLineTo", name = "yLineTo",
}] }]
async fn inner_y_line_to( async fn inner_y_line_to(
data: AxisLineToData, to: f64,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?; let from = sketch_group.get_coords_from_paths()?;
let line_to_data = match data { let new_sketch_group = inner_line_to([from.x, to], sketch_group, tag, args).await?;
AxisLineToData::PointWithTag { to, tag } => LineToData::PointWithTag { to: [from.x, to], tag },
AxisLineToData::Point(data) => LineToData::Point([from.x, data]),
};
let new_sketch_group = inner_line_to(line_to_data, sketch_group, args).await?;
Ok(new_sketch_group) Ok(new_sketch_group)
} }
/// Data to draw a line.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum LineData {
/// A point with a tag.
PointWithTag {
/// The to point.
to: [f64; 2],
/// The tag.
tag: String,
},
/// A point.
Point([f64; 2]),
}
/// Draw a line. /// Draw a line.
pub async fn line(args: Args) -> Result<MemoryItem, KclError> { pub async fn line(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (LineData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (delta, sketch_group, tag): ([f64; 2], Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_line(data, sketch_group, args).await?; let new_sketch_group = inner_line(delta, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -254,22 +177,21 @@ pub async fn line(args: Args) -> Result<MemoryItem, KclError> {
/// startSketchOn('-XY') /// startSketchOn('-XY')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> line({to: [20, 10], tag: "edge1"}, %) /// |> line([20, 10], %, "edge1")
/// |> close(%, "edge2") /// |> close(%, "edge2")
/// |> extrude(10, %) /// |> extrude(10, %)
/// ``` /// ```
#[stdlib { #[stdlib {
name = "line", name = "line",
}] }]
async fn inner_line(data: LineData, sketch_group: Box<SketchGroup>, args: Args) -> Result<Box<SketchGroup>, KclError> { async fn inner_line(
delta: [f64; 2],
sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args,
) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?; let from = sketch_group.get_coords_from_paths()?;
let inner_args = match &data { let to = [from.x + delta[0], from.y + delta[1]];
LineData::PointWithTag { to, .. } => *to,
LineData::Point(to) => *to,
};
let delta = inner_args;
let to = [from.x + inner_args[0], from.y + inner_args[1]];
let id = uuid::Uuid::new_v4(); let id = uuid::Uuid::new_v4();
@ -293,11 +215,7 @@ async fn inner_line(data: LineData, sketch_group: Box<SketchGroup>, args: Args)
base: BasePath { base: BasePath {
from: from.into(), from: from.into(),
to, to,
name: if let LineData::PointWithTag { tag, .. } = data { name: tag.unwrap_or("".to_string()),
tag.to_string()
} else {
"".to_string()
},
geo_meta: GeoMeta { geo_meta: GeoMeta {
id, id,
metadata: args.source_range.into(), metadata: args.source_range.into(),
@ -311,27 +229,12 @@ async fn inner_line(data: LineData, sketch_group: Box<SketchGroup>, args: Args)
Ok(new_sketch_group) Ok(new_sketch_group)
} }
/// Data to draw a line on an axis.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)]
#[serde(rename_all = "camelCase", untagged)]
pub enum AxisLineData {
/// The length with a tag.
LengthWithTag {
/// The length of the line.
length: f64,
/// The tag.
tag: String,
},
/// The length.
Length(f64),
}
/// Draw a line on the x-axis. /// Draw a line on the x-axis.
pub async fn x_line(args: Args) -> Result<MemoryItem, KclError> { pub async fn x_line(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AxisLineData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (length, sketch_group, tag): (f64, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_x_line(data, sketch_group, args).await?; let new_sketch_group = inner_x_line(length, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -349,24 +252,20 @@ pub async fn x_line(args: Args) -> Result<MemoryItem, KclError> {
name = "xLine", name = "xLine",
}] }]
async fn inner_x_line( async fn inner_x_line(
data: AxisLineData, length: f64,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let line_data = match data { inner_line([length, 0.0], sketch_group, tag, args).await
AxisLineData::LengthWithTag { length, tag } => LineData::PointWithTag { to: [length, 0.0], tag },
AxisLineData::Length(length) => LineData::Point([length, 0.0]),
};
let new_sketch_group = inner_line(line_data, sketch_group, args).await?;
Ok(new_sketch_group)
} }
/// Draw a line on the y-axis. /// Draw a line on the y-axis.
pub async fn y_line(args: Args) -> Result<MemoryItem, KclError> { pub async fn y_line(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AxisLineData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (length, sketch_group, tag): (f64, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_y_line(data, sketch_group, args).await?; let new_sketch_group = inner_y_line(length, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -384,17 +283,12 @@ pub async fn y_line(args: Args) -> Result<MemoryItem, KclError> {
name = "yLine", name = "yLine",
}] }]
async fn inner_y_line( async fn inner_y_line(
data: AxisLineData, length: f64,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let line_data = match data { inner_line([0.0, length], sketch_group, tag, args).await
AxisLineData::LengthWithTag { length, tag } => LineData::PointWithTag { to: [0.0, length], tag },
AxisLineData::Length(length) => LineData::Point([0.0, length]),
};
let new_sketch_group = inner_line(line_data, sketch_group, args).await?;
Ok(new_sketch_group)
} }
/// Data to draw an angled line. /// Data to draw an angled line.
@ -402,34 +296,23 @@ async fn inner_y_line(
#[ts(export)] #[ts(export)]
#[serde(rename_all = "camelCase", untagged)] #[serde(rename_all = "camelCase", untagged)]
pub enum AngledLineData { pub enum AngledLineData {
/// An angle and length with a tag. /// An angle and length with explicitly named parameters
AngleWithTag { AngleAndLengthNamed {
/// The angle of the line. /// The angle of the line.
angle: f64, angle: f64,
/// The length of the line. /// The length of the line.
length: f64, length: f64,
/// The tag.
tag: String,
}, },
/// An angle and length. /// An angle and length given as a pair
AngleAndLength([f64; 2]), AngleAndLengthPair([f64; 2]),
}
impl AngledLineData {
pub fn into_inner_line(self, to: [f64; 2]) -> LineData {
if let AngledLineData::AngleWithTag { tag, .. } = self {
LineData::PointWithTag { to, tag }
} else {
LineData::Point(to)
}
}
} }
/// Draw an angled line. /// Draw an angled line.
pub async fn angled_line(args: Args) -> Result<MemoryItem, KclError> { pub async fn angled_line(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AngledLineData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (AngledLineData, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_angled_line(data, sketch_group, args).await?; let new_sketch_group = inner_angled_line(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -441,8 +324,7 @@ pub async fn angled_line(args: Args) -> Result<MemoryItem, KclError> {
/// |> angledLine({ /// |> angledLine({
/// angle: 45, /// angle: 45,
/// length: 10, /// length: 10,
/// tag: "edge1" /// }, %, "edge1")
/// }, %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> line([0, 10], %) /// |> line([0, 10], %)
/// |> close(%, "edge2") /// |> close(%, "edge2")
@ -454,12 +336,13 @@ pub async fn angled_line(args: Args) -> Result<MemoryItem, KclError> {
async fn inner_angled_line( async fn inner_angled_line(
data: AngledLineData, data: AngledLineData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?; let from = sketch_group.get_coords_from_paths()?;
let (angle, length) = match &data { let (angle, length) = match data {
AngledLineData::AngleWithTag { angle, length, .. } => (*angle, *length), AngledLineData::AngleAndLengthNamed { angle, length } => (angle, length),
AngledLineData::AngleAndLength(angle_and_length) => (angle_and_length[0], angle_and_length[1]), AngledLineData::AngleAndLengthPair(pair) => (pair[0], pair[1]),
}; };
//double check me on this one - mike //double check me on this one - mike
@ -477,11 +360,7 @@ async fn inner_angled_line(
base: BasePath { base: BasePath {
from: from.into(), from: from.into(),
to, to,
name: if let AngledLineData::AngleWithTag { tag, .. } = data { name: tag.unwrap_or("".to_string()),
tag.to_string()
} else {
"".to_string()
},
geo_meta: GeoMeta { geo_meta: GeoMeta {
id, id,
metadata: args.source_range.into(), metadata: args.source_range.into(),
@ -512,9 +391,10 @@ async fn inner_angled_line(
/// Draw an angled line of a given x length. /// Draw an angled line of a given x length.
pub async fn angled_line_of_x_length(args: Args) -> Result<MemoryItem, KclError> { pub async fn angled_line_of_x_length(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AngledLineData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (AngledLineData, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_angled_line_of_x_length(data, sketch_group, args).await?; let new_sketch_group = inner_angled_line_of_x_length(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -526,8 +406,7 @@ pub async fn angled_line_of_x_length(args: Args) -> Result<MemoryItem, KclError>
/// |> angledLineOfXLength({ /// |> angledLineOfXLength({
/// angle: 45, /// angle: 45,
/// length: 10, /// length: 10,
/// tag: "edge1" /// }, %, "edge1")
/// }, %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> line([0, 10], %) /// |> line([0, 10], %)
/// |> close(%, "edge2") /// |> close(%, "edge2")
@ -539,16 +418,17 @@ pub async fn angled_line_of_x_length(args: Args) -> Result<MemoryItem, KclError>
async fn inner_angled_line_of_x_length( async fn inner_angled_line_of_x_length(
data: AngledLineData, data: AngledLineData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let (angle, length) = match &data { let (angle, length) = match data {
AngledLineData::AngleWithTag { angle, length, .. } => (*angle, *length), AngledLineData::AngleAndLengthNamed { angle, length } => (angle, length),
AngledLineData::AngleAndLength(angle_and_length) => (angle_and_length[0], angle_and_length[1]), AngledLineData::AngleAndLengthPair(pair) => (pair[0], pair[1]),
}; };
let to = get_y_component(Angle::from_degrees(angle), length); let to = get_y_component(Angle::from_degrees(angle), length);
let new_sketch_group = inner_line(data.into_inner_line(to.into()), sketch_group, args).await?; let new_sketch_group = inner_line(to.into(), sketch_group, tag, args).await?;
Ok(new_sketch_group) Ok(new_sketch_group)
} }
@ -556,36 +436,20 @@ async fn inner_angled_line_of_x_length(
/// Data to draw an angled line to a point. /// Data to draw an angled line to a point.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)] #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
#[ts(export)] #[ts(export)]
#[serde(rename_all = "camelCase", untagged)] #[serde(rename_all = "camelCase")]
pub enum AngledLineToData { pub struct AngledLineToData {
/// An angle and point with a tag.
AngleWithTag {
/// The angle of the line. /// The angle of the line.
angle: f64, angle: f64,
/// The point to draw to. /// The point to draw to.
to: f64, to: f64,
/// The tag.
tag: String,
},
/// An angle and point to draw to.
AngleAndPoint([f64; 2]),
}
impl AngledLineToData {
pub fn into_inner_line(self, x_to: f64, y_to: f64) -> LineToData {
if let AngledLineToData::AngleWithTag { tag, .. } = self {
LineToData::PointWithTag { to: [x_to, y_to], tag }
} else {
LineToData::Point([x_to, y_to])
}
}
} }
/// Draw an angled line to a given x coordinate. /// Draw an angled line to a given x coordinate.
pub async fn angled_line_to_x(args: Args) -> Result<MemoryItem, KclError> { pub async fn angled_line_to_x(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AngledLineToData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (AngledLineToData, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_angled_line_to_x(data, sketch_group, args).await?; let new_sketch_group = inner_angled_line_to_x(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -597,8 +461,7 @@ pub async fn angled_line_to_x(args: Args) -> Result<MemoryItem, KclError> {
/// |> angledLineToX({ /// |> angledLineToX({
/// angle: 45, /// angle: 45,
/// to: 10, /// to: 10,
/// tag: "edge1" /// }, %, "edge1")
/// }, %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> line([0, 10], %) /// |> line([0, 10], %)
/// |> close(%, "edge2") /// |> close(%, "edge2")
@ -611,27 +474,26 @@ pub async fn angled_line_to_x(args: Args) -> Result<MemoryItem, KclError> {
async fn inner_angled_line_to_x( async fn inner_angled_line_to_x(
data: AngledLineToData, data: AngledLineToData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?; let from = sketch_group.get_coords_from_paths()?;
let (angle, x_to) = match &data { let AngledLineToData { angle, to: x_to } = data;
AngledLineToData::AngleWithTag { angle, to, .. } => (*angle, *to),
AngledLineToData::AngleAndPoint(angle_and_to) => (angle_and_to[0], angle_and_to[1]),
};
let x_component = x_to - from.x; let x_component = x_to - from.x;
let y_component = x_component * f64::tan(angle.to_radians()); let y_component = x_component * f64::tan(angle.to_radians());
let y_to = from.y + y_component; let y_to = from.y + y_component;
let new_sketch_group = inner_line_to(data.into_inner_line(x_to, y_to), sketch_group, args).await?; let new_sketch_group = inner_line_to([x_to, y_to], sketch_group, tag, args).await?;
Ok(new_sketch_group) Ok(new_sketch_group)
} }
/// Draw an angled line of a given y length. /// Draw an angled line of a given y length.
pub async fn angled_line_of_y_length(args: Args) -> Result<MemoryItem, KclError> { pub async fn angled_line_of_y_length(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AngledLineData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (AngledLineData, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_angled_line_of_y_length(data, sketch_group, args).await?; let new_sketch_group = inner_angled_line_of_y_length(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -644,8 +506,7 @@ pub async fn angled_line_of_y_length(args: Args) -> Result<MemoryItem, KclError>
/// |> angledLineOfYLength({ /// |> angledLineOfYLength({
/// angle: 45, /// angle: 45,
/// length: 10, /// length: 10,
/// tag: "edge1" /// }, %, "edge1")
/// }, %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> line([0, 10], %) /// |> line([0, 10], %)
/// |> close(%, "edge2") /// |> close(%, "edge2")
@ -658,25 +519,27 @@ pub async fn angled_line_of_y_length(args: Args) -> Result<MemoryItem, KclError>
async fn inner_angled_line_of_y_length( async fn inner_angled_line_of_y_length(
data: AngledLineData, data: AngledLineData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let (angle, length) = match &data { let (angle, length) = match data {
AngledLineData::AngleWithTag { angle, length, .. } => (*angle, *length), AngledLineData::AngleAndLengthNamed { angle, length } => (angle, length),
AngledLineData::AngleAndLength(angle_and_length) => (angle_and_length[0], angle_and_length[1]), AngledLineData::AngleAndLengthPair(pair) => (pair[0], pair[1]),
}; };
let to = get_x_component(Angle::from_degrees(angle), length); let to = get_x_component(Angle::from_degrees(angle), length);
let new_sketch_group = inner_line(data.into_inner_line(to.into()), sketch_group, args).await?; let new_sketch_group = inner_line(to.into(), sketch_group, tag, args).await?;
Ok(new_sketch_group) Ok(new_sketch_group)
} }
/// Draw an angled line to a given y coordinate. /// Draw an angled line to a given y coordinate.
pub async fn angled_line_to_y(args: Args) -> Result<MemoryItem, KclError> { pub async fn angled_line_to_y(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AngledLineToData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (AngledLineToData, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_angled_line_to_y(data, sketch_group, args).await?; let new_sketch_group = inner_angled_line_to_y(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -688,8 +551,7 @@ pub async fn angled_line_to_y(args: Args) -> Result<MemoryItem, KclError> {
/// |> angledLineToY({ /// |> angledLineToY({
/// angle: 45, /// angle: 45,
/// to: 10, /// to: 10,
/// tag: "edge1" /// }, %, "edge1")
/// }, %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> line([0, 10], %) /// |> line([0, 10], %)
/// |> close(%, "edge2") /// |> close(%, "edge2")
@ -701,19 +563,17 @@ pub async fn angled_line_to_y(args: Args) -> Result<MemoryItem, KclError> {
async fn inner_angled_line_to_y( async fn inner_angled_line_to_y(
data: AngledLineToData, data: AngledLineToData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?; let from = sketch_group.get_coords_from_paths()?;
let (angle, y_to) = match &data { let AngledLineToData { angle, to: y_to } = data;
AngledLineToData::AngleWithTag { angle, to, .. } => (*angle, *to),
AngledLineToData::AngleAndPoint(angle_and_to) => (angle_and_to[0], angle_and_to[1]),
};
let y_component = y_to - from.y; let y_component = y_to - from.y;
let x_component = y_component / f64::tan(angle.to_radians()); let x_component = y_component / f64::tan(angle.to_radians());
let x_to = from.x + x_component; let x_to = from.x + x_component;
let new_sketch_group = inner_line_to(data.into_inner_line(x_to, y_to), sketch_group, args).await?; let new_sketch_group = inner_line_to([x_to, y_to], sketch_group, tag, args).await?;
Ok(new_sketch_group) Ok(new_sketch_group)
} }
@ -729,14 +589,13 @@ pub struct AngledLineThatIntersectsData {
pub intersect_tag: String, pub intersect_tag: String,
/// The offset from the intersecting line. /// The offset from the intersecting line.
pub offset: Option<f64>, pub offset: Option<f64>,
/// The tag.
pub tag: Option<String>,
} }
/// Draw an angled line that intersects with a given line. /// Draw an angled line that intersects with a given line.
pub async fn angled_line_that_intersects(args: Args) -> Result<MemoryItem, KclError> { pub async fn angled_line_that_intersects(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (AngledLineThatIntersectsData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (AngledLineThatIntersectsData, Box<SketchGroup>, Option<String>) =
let new_sketch_group = inner_angled_line_that_intersects(data, sketch_group, args).await?; args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_angled_line_that_intersects(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -745,14 +604,13 @@ pub async fn angled_line_that_intersects(args: Args) -> Result<MemoryItem, KclEr
/// ```no_run /// ```no_run
/// const part001 = startSketchOn('XY') /// const part001 = startSketchOn('XY')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> lineTo({to:[2, 2], tag: "yo"}, %) /// |> lineTo([2, 2], %, "yo")
/// |> lineTo([3, 1], %) /// |> lineTo([3, 1], %)
/// |> angledLineThatIntersects({ /// |> angledLineThatIntersects({
/// angle: 180, /// angle: 180,
/// intersectTag: 'yo', /// intersectTag: 'yo',
/// offset: 12, /// offset: 12,
/// tag: "yo2" /// }, %, "yo2")
/// }, %)
/// |> line([4, 0], %) /// |> line([4, 0], %)
/// |> close(%, "yo3") /// |> close(%, "yo3")
/// |> extrude(10, %) /// |> extrude(10, %)
@ -763,6 +621,7 @@ pub async fn angled_line_that_intersects(args: Args) -> Result<MemoryItem, KclEr
async fn inner_angled_line_that_intersects( async fn inner_angled_line_that_intersects(
data: AngledLineThatIntersectsData, data: AngledLineThatIntersectsData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let intersect_path = sketch_group let intersect_path = sketch_group
@ -786,19 +645,13 @@ async fn inner_angled_line_that_intersects(
from, from,
); );
let line_to_data = if let Some(tag) = data.tag { let new_sketch_group = inner_line_to(to.into(), sketch_group, tag, args).await?;
LineToData::PointWithTag { to: to.into(), tag }
} else {
LineToData::Point(to.into())
};
let new_sketch_group = inner_line_to(line_to_data, sketch_group, args).await?;
Ok(new_sketch_group) Ok(new_sketch_group)
} }
/// Start a sketch at a given point. /// Start a sketch at a given point.
pub async fn start_sketch_at(args: Args) -> Result<MemoryItem, KclError> { pub async fn start_sketch_at(args: Args) -> Result<MemoryItem, KclError> {
let data: LineData = args.get_data()?; let data: [f64; 2] = args.get_data()?;
let sketch_group = inner_start_sketch_at(data, args).await?; let sketch_group = inner_start_sketch_at(data, args).await?;
Ok(MemoryItem::SketchGroup(sketch_group)) Ok(MemoryItem::SketchGroup(sketch_group))
@ -813,11 +666,11 @@ pub async fn start_sketch_at(args: Args) -> Result<MemoryItem, KclError> {
#[stdlib { #[stdlib {
name = "startSketchAt", name = "startSketchAt",
}] }]
async fn inner_start_sketch_at(data: LineData, args: Args) -> Result<Box<SketchGroup>, KclError> { async fn inner_start_sketch_at(data: [f64; 2], args: Args) -> Result<Box<SketchGroup>, KclError> {
// Let's assume it's the XY plane for now, this is just for backwards compatibility. // Let's assume it's the XY plane for now, this is just for backwards compatibility.
let xy_plane = PlaneData::XY; let xy_plane = PlaneData::XY;
let sketch_surface = inner_start_sketch_on(SketchData::Plane(xy_plane), None, args.clone()).await?; let sketch_surface = inner_start_sketch_on(SketchData::Plane(xy_plane), None, args.clone()).await?;
let sketch_group = inner_start_profile_at(data, sketch_surface, args).await?; let sketch_group = inner_start_profile_at(data, sketch_surface, None, args).await?;
Ok(sketch_group) Ok(sketch_group)
} }
@ -959,7 +812,7 @@ pub async fn start_sketch_on(args: Args) -> Result<MemoryItem, KclError> {
/// startSketchOn('XY') /// startSketchOn('XY')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> line({to: [20, 10], tag: "edge1"}, %) /// |> line([20, 10], %, "edge1")
/// |> close(%, "edge2") /// |> close(%, "edge2")
/// ``` /// ```
/// ///
@ -981,7 +834,7 @@ pub async fn start_sketch_on(args: Args) -> Result<MemoryItem, KclError> {
/// const part001 = startSketchOn(box, "start") /// const part001 = startSketchOn(box, "start")
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line([10, 10], %) /// |> line([10, 10], %)
/// |> line({to: [20, 10], tag: "edge1"}, %) /// |> line([20, 10], %, "edge1")
/// |> close(%) /// |> close(%)
/// |> extrude(20, %) /// |> extrude(20, %)
/// ``` /// ```
@ -1204,9 +1057,9 @@ async fn start_sketch_on_plane(data: PlaneData, args: Args) -> Result<Box<Plane>
/// Start a profile at a given point. /// Start a profile at a given point.
pub async fn start_profile_at(args: Args) -> Result<MemoryItem, KclError> { pub async fn start_profile_at(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_surface): (LineData, SketchSurface) = args.get_data_and_sketch_surface()?; let (start, sketch_surface, tag): ([f64; 2], SketchSurface, Option<String>) = args.get_data_and_sketch_surface()?;
let sketch_group = inner_start_profile_at(data, sketch_surface, args).await?; let sketch_group = inner_start_profile_at(start, sketch_surface, tag, args).await?;
Ok(MemoryItem::SketchGroup(sketch_group)) Ok(MemoryItem::SketchGroup(sketch_group))
} }
@ -1221,15 +1074,11 @@ pub async fn start_profile_at(args: Args) -> Result<MemoryItem, KclError> {
name = "startProfileAt", name = "startProfileAt",
}] }]
pub(crate) async fn inner_start_profile_at( pub(crate) async fn inner_start_profile_at(
data: LineData, to: [f64; 2],
sketch_surface: SketchSurface, sketch_surface: SketchSurface,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let to = match &data {
LineData::PointWithTag { to, .. } => *to,
LineData::Point(to) => *to,
};
let id = uuid::Uuid::new_v4(); let id = uuid::Uuid::new_v4();
let path_id = uuid::Uuid::new_v4(); let path_id = uuid::Uuid::new_v4();
@ -1250,11 +1099,7 @@ pub(crate) async fn inner_start_profile_at(
let current_path = BasePath { let current_path = BasePath {
from: to, from: to,
to, to,
name: if let LineData::PointWithTag { tag, .. } = data { name: tag.unwrap_or("".to_string()),
tag.to_string()
} else {
"".to_string()
},
geo_meta: GeoMeta { geo_meta: GeoMeta {
id, id,
metadata: args.source_range.into(), metadata: args.source_range.into(),
@ -1360,9 +1205,6 @@ pub enum ArcData {
angle_end: f64, angle_end: f64,
/// The radius. /// The radius.
radius: f64, radius: f64,
/// The tag.
#[serde(default)]
tag: Option<String>,
}, },
/// Center, to and radius with an optional tag. /// Center, to and radius with an optional tag.
CenterToRadius { CenterToRadius {
@ -1372,17 +1214,15 @@ pub enum ArcData {
to: [f64; 2], to: [f64; 2],
/// The radius. /// The radius.
radius: f64, radius: f64,
/// The tag.
#[serde(default)]
tag: Option<String>,
}, },
} }
/// Draw an arc. /// Draw an arc.
pub async fn arc(args: Args) -> Result<MemoryItem, KclError> { pub async fn arc(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (ArcData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (ArcData, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_arc(data, sketch_group, args).await?; let new_sketch_group = inner_arc(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -1395,8 +1235,7 @@ pub async fn arc(args: Args) -> Result<MemoryItem, KclError> {
/// angle_start: 0, /// angle_start: 0,
/// angle_end: 360, /// angle_end: 360,
/// radius: 10, /// radius: 10,
/// tag: "edge1" /// }, %, "edge1")
/// }, %)
/// |> extrude(10, %) /// |> extrude(10, %)
/// ``` /// ```
#[stdlib { #[stdlib {
@ -1405,6 +1244,7 @@ pub async fn arc(args: Args) -> Result<MemoryItem, KclError> {
pub(crate) async fn inner_arc( pub(crate) async fn inner_arc(
data: ArcData, data: ArcData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from: Point2d = sketch_group.get_coords_from_paths()?; let from: Point2d = sketch_group.get_coords_from_paths()?;
@ -1414,14 +1254,13 @@ pub(crate) async fn inner_arc(
angle_start, angle_start,
angle_end, angle_end,
radius, radius,
..
} => { } => {
let a_start = Angle::from_degrees(*angle_start); let a_start = Angle::from_degrees(*angle_start);
let a_end = Angle::from_degrees(*angle_end); let a_end = Angle::from_degrees(*angle_end);
let (center, end) = arc_center_and_end(from, a_start, a_end, *radius); let (center, end) = arc_center_and_end(from, a_start, a_end, *radius);
(center, a_start, a_end, *radius, end) (center, a_start, a_end, *radius, end)
} }
ArcData::CenterToRadius { center, to, radius, .. } => { ArcData::CenterToRadius { center, to, radius } => {
let (angle_start, angle_end) = arc_angles(from, center.into(), to.into(), *radius, args.source_range)?; let (angle_start, angle_end) = arc_angles(from, center.into(), to.into(), *radius, args.source_range)?;
(center.into(), angle_start, angle_end, *radius, to.into()) (center.into(), angle_start, angle_end, *radius, to.into())
} }
@ -1448,10 +1287,7 @@ pub(crate) async fn inner_arc(
base: BasePath { base: BasePath {
from: from.into(), from: from.into(),
to: end.into(), to: end.into(),
name: match data { name: tag.unwrap_or("".to_string()),
ArcData::AnglesAndRadius { tag, .. } => tag.unwrap_or_default().to_string(),
ArcData::CenterToRadius { tag, .. } => tag.unwrap_or_default().to_string(),
},
geo_meta: GeoMeta { geo_meta: GeoMeta {
id, id,
metadata: args.source_range.into(), metadata: args.source_range.into(),
@ -1477,22 +1313,16 @@ pub enum TangentialArcData {
/// Offset of the arc, in degrees. /// Offset of the arc, in degrees.
offset: f64, offset: f64,
}, },
/// A point with a tag.
PointWithTag {
/// Where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position.
to: [f64; 2],
/// The tag.
tag: String,
},
/// A point where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position. /// A point where the arc should end. Must lie in the same plane as the current path pen position. Must not be colinear with current path pen position.
Point([f64; 2]), Point([f64; 2]),
} }
/// Draw a tangential arc. /// Draw a tangential arc.
pub async fn tangential_arc(args: Args) -> Result<MemoryItem, KclError> { pub async fn tangential_arc(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (TangentialArcData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (TangentialArcData, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_tangential_arc(data, sketch_group, args).await?; let new_sketch_group = inner_tangential_arc(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -1501,12 +1331,11 @@ pub async fn tangential_arc(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn('-YZ') /// startSketchOn('-YZ')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({to: [10, 10], tag: "edge0"}, %) /// |> line([10, 10], %, "edge1")
/// |> tangentialArc({ /// |> tangentialArc({
/// radius: 10, /// radius: 10,
/// offset: 90, /// offset: 90,
/// tag: "edge1" /// }, %, "edge1")
/// }, %)
/// |> close(%) /// |> close(%)
/// |> extrude(10, %) /// |> extrude(10, %)
/// ``` /// ```
@ -1516,6 +1345,7 @@ pub async fn tangential_arc(args: Args) -> Result<MemoryItem, KclError> {
async fn inner_tangential_arc( async fn inner_tangential_arc(
data: TangentialArcData, data: TangentialArcData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from: Point2d = sketch_group.get_coords_from_paths()?; let from: Point2d = sketch_group.get_coords_from_paths()?;
@ -1545,11 +1375,6 @@ async fn inner_tangential_arc(
.await?; .await?;
to.into() to.into()
} }
TangentialArcData::PointWithTag { to, .. } => {
args.send_modeling_cmd(id, tan_arc_to(&sketch_group, to)).await?;
*to
}
TangentialArcData::Point(to) => { TangentialArcData::Point(to) => {
args.send_modeling_cmd(id, tan_arc_to(&sketch_group, to)).await?; args.send_modeling_cmd(id, tan_arc_to(&sketch_group, to)).await?;
@ -1563,10 +1388,7 @@ async fn inner_tangential_arc(
base: BasePath { base: BasePath {
from: from.into(), from: from.into(),
to, to,
name: match data { name: tag.unwrap_or("".to_string()),
TangentialArcData::PointWithTag { tag, .. } => tag.to_string(),
TangentialArcData::Point(_) | TangentialArcData::RadiusAndOffset { .. } => "".to_string(),
},
geo_meta: GeoMeta { geo_meta: GeoMeta {
id, id,
metadata: args.source_range.into(), metadata: args.source_range.into(),
@ -1628,7 +1450,7 @@ pub async fn tangential_arc_to(args: Args) -> Result<MemoryItem, KclError> {
/// ```no_run /// ```no_run
/// startSketchOn('-YZ') /// startSketchOn('-YZ')
/// |> startProfileAt([0, 0], %) /// |> startProfileAt([0, 0], %)
/// |> line({to: [10, 10], tag: "edge0"}, %) /// |> line([10, 10], %, "edge0")
/// |> tangentialArcTo([10, 0], %) /// |> tangentialArcTo([10, 0], %)
/// |> close(%) /// |> close(%)
/// ``` /// ```
@ -1691,15 +1513,14 @@ pub struct BezierData {
control1: [f64; 2], control1: [f64; 2],
/// The second control point. /// The second control point.
control2: [f64; 2], control2: [f64; 2],
/// The tag.
tag: Option<String>,
} }
/// Draw a bezier curve. /// Draw a bezier curve.
pub async fn bezier_curve(args: Args) -> Result<MemoryItem, KclError> { pub async fn bezier_curve(args: Args) -> Result<MemoryItem, KclError> {
let (data, sketch_group): (BezierData, Box<SketchGroup>) = args.get_data_and_sketch_group()?; let (data, sketch_group, tag): (BezierData, Box<SketchGroup>, Option<String>) =
args.get_data_and_sketch_group_and_tag()?;
let new_sketch_group = inner_bezier_curve(data, sketch_group, args).await?; let new_sketch_group = inner_bezier_curve(data, sketch_group, tag, args).await?;
Ok(MemoryItem::SketchGroup(new_sketch_group)) Ok(MemoryItem::SketchGroup(new_sketch_group))
} }
@ -1712,8 +1533,7 @@ pub async fn bezier_curve(args: Args) -> Result<MemoryItem, KclError> {
/// to: [10, 10], /// to: [10, 10],
/// control1: [5, 0], /// control1: [5, 0],
/// control2: [5, 10], /// control2: [5, 10],
/// tag: "edge1" /// }, %, "edge1")
/// }, %)
/// |> close(%) /// |> close(%)
/// |> extrude(10, %) /// |> extrude(10, %)
/// ``` /// ```
@ -1723,6 +1543,7 @@ pub async fn bezier_curve(args: Args) -> Result<MemoryItem, KclError> {
async fn inner_bezier_curve( async fn inner_bezier_curve(
data: BezierData, data: BezierData,
sketch_group: Box<SketchGroup>, sketch_group: Box<SketchGroup>,
tag: Option<String>,
args: Args, args: Args,
) -> Result<Box<SketchGroup>, KclError> { ) -> Result<Box<SketchGroup>, KclError> {
let from = sketch_group.get_coords_from_paths()?; let from = sketch_group.get_coords_from_paths()?;
@ -1763,7 +1584,7 @@ async fn inner_bezier_curve(
base: BasePath { base: BasePath {
from: from.into(), from: from.into(),
to, to,
name: data.tag.unwrap_or_default().to_string(), name: tag.unwrap_or_default().to_string(),
geo_meta: GeoMeta { geo_meta: GeoMeta {
id, id,
metadata: args.source_range.into(), metadata: args.source_range.into(),
@ -1863,28 +1684,7 @@ mod tests {
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use crate::std::sketch::{LineData, PlaneData}; use crate::std::sketch::PlaneData;
#[test]
fn test_deserialize_line_data() {
let data = LineData::Point([0.0, 1.0]);
let mut str_json = serde_json::to_string(&data).unwrap();
assert_eq!(str_json, "[0.0,1.0]");
str_json = "[0, 1]".to_string();
let data: LineData = serde_json::from_str(&str_json).unwrap();
assert_eq!(data, LineData::Point([0.0, 1.0]));
str_json = "{ \"to\": [0.0, 1.0], \"tag\": \"thing\" }".to_string();
let data: LineData = serde_json::from_str(&str_json).unwrap();
assert_eq!(
data,
LineData::PointWithTag {
to: [0.0, 1.0],
tag: "thing".to_string()
}
);
}
#[test] #[test]
fn test_deserialize_plane_data() { fn test_deserialize_plane_data() {

View File

@ -87,7 +87,7 @@ async fn execute_and_snapshot(code: &str, units: kittycad::types::UnitLength) ->
async fn serial_test_sketch_on_face() { async fn serial_test_sketch_on_face() {
let code = r#"const part001 = startSketchOn('XY') let code = r#"const part001 = startSketchOn('XY')
|> startProfileAt([11.19, 28.35], %) |> startProfileAt([11.19, 28.35], %)
|> line({to: [28.67, -13.25], tag: "here"}, %) |> line([28.67, -13.25], %, "here")
|> line([-4.12, -22.81], %) |> line([-4.12, -22.81], %)
|> line([-33.24, 14.55], %) |> line([-33.24, 14.55], %)
|> close(%) |> close(%)
@ -206,9 +206,9 @@ const part002 = startSketchOn(part001, "END")
async fn serial_test_fillet_duplicate_tags() { async fn serial_test_fillet_duplicate_tags() {
let code = r#"const part001 = startSketchOn('XY') let code = r#"const part001 = startSketchOn('XY')
|> startProfileAt([0,0], %) |> startProfileAt([0,0], %)
|> line({to: [0, 10], tag: "thing"}, %) |> line([0, 10], %, "thing")
|> line([10, 0], %) |> line([10, 0], %)
|> line({to: [0, -10], tag: "thing2"}, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({radius: 0.5, tags: ["thing", "thing"]}, %) |> fillet({radius: 0.5, tags: ["thing", "thing"]}, %)
@ -218,7 +218,7 @@ async fn serial_test_fillet_duplicate_tags() {
assert!(result.is_err()); assert!(result.is_err());
assert_eq!( assert_eq!(
result.err().unwrap().to_string(), result.err().unwrap().to_string(),
r#"type: KclErrorDetails { source_ranges: [SourceRange([227, 277])], message: "Duplicate tags are not allowed." }"#, r#"type: KclErrorDetails { source_ranges: [SourceRange([205, 255])], message: "Duplicate tags are not allowed." }"#,
); );
} }
@ -226,9 +226,9 @@ async fn serial_test_fillet_duplicate_tags() {
async fn serial_test_basic_fillet_cube_start() { async fn serial_test_basic_fillet_cube_start() {
let code = r#"const part001 = startSketchOn('XY') let code = r#"const part001 = startSketchOn('XY')
|> startProfileAt([0,0], %) |> startProfileAt([0,0], %)
|> line({to: [0, 10], tag: "thing"}, %) |> line([0, 10], %, "thing")
|> line([10, 0], %) |> line([10, 0], %)
|> line({to: [0, -10], tag: "thing2"}, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({radius: 2, tags: ["thing", "thing2"]}, %) |> fillet({radius: 2, tags: ["thing", "thing2"]}, %)
@ -244,9 +244,9 @@ async fn serial_test_basic_fillet_cube_start() {
async fn serial_test_basic_fillet_cube_end() { async fn serial_test_basic_fillet_cube_end() {
let code = r#"const part001 = startSketchOn('XY') let code = r#"const part001 = startSketchOn('XY')
|> startProfileAt([0,0], %) |> startProfileAt([0,0], %)
|> line({to: [0, 10], tag: "thing"}, %) |> line([0, 10], %, "thing")
|> line([10, 0], %) |> line([10, 0], %)
|> line({to: [0, -10], tag: "thing2"}, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({radius: 2, tags: ["thing", getOppositeEdge("thing", %)]}, %) |> fillet({radius: 2, tags: ["thing", getOppositeEdge("thing", %)]}, %)
@ -263,9 +263,9 @@ async fn serial_test_basic_fillet_cube_end() {
async fn serial_test_basic_fillet_cube_close_opposite() { async fn serial_test_basic_fillet_cube_close_opposite() {
let code = r#"const part001 = startSketchOn('XY') let code = r#"const part001 = startSketchOn('XY')
|> startProfileAt([0,0], %) |> startProfileAt([0,0], %)
|> line({to: [0, 10], tag: "thing"}, %) |> line([0, 10], %, "thing")
|> line([10, 0], %) |> line([10, 0], %)
|> line({to: [0, -10], tag: "thing2"}, %) |> line([0, -10], %, "thing2")
|> close(%, "thing3") |> close(%, "thing3")
|> extrude(10, %) |> extrude(10, %)
|> fillet({radius: 2, tags: ["thing3", getOppositeEdge("thing3", %)]}, %) |> fillet({radius: 2, tags: ["thing3", getOppositeEdge("thing3", %)]}, %)
@ -286,9 +286,9 @@ async fn serial_test_basic_fillet_cube_close_opposite() {
async fn serial_test_basic_fillet_cube_next_adjacent() { async fn serial_test_basic_fillet_cube_next_adjacent() {
let code = r#"const part001 = startSketchOn('XY') let code = r#"const part001 = startSketchOn('XY')
|> startProfileAt([0,0], %) |> startProfileAt([0,0], %)
|> line({to: [0, 10], tag: "thing"}, %) |> line([0, 10], %, "thing")
|> line({to: [10, 0], tag: "thing1"}, %) |> line([10, 0], %, "thing1")
|> line({to: [0, -10], tag: "thing2"}, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({radius: 2, tags: [getNextAdjacentEdge("thing", %)]}, %) |> fillet({radius: 2, tags: [getNextAdjacentEdge("thing", %)]}, %)
@ -308,9 +308,9 @@ async fn serial_test_basic_fillet_cube_next_adjacent() {
async fn serial_test_basic_fillet_cube_previous_adjacent() { async fn serial_test_basic_fillet_cube_previous_adjacent() {
let code = r#"const part001 = startSketchOn('XY') let code = r#"const part001 = startSketchOn('XY')
|> startProfileAt([0,0], %) |> startProfileAt([0,0], %)
|> line({to: [0, 10], tag: "thing"}, %) |> line([0, 10], %, "thing")
|> line({to: [10, 0], tag: "thing1"}, %) |> line([10, 0], %, "thing1")
|> line({to: [0, -10], tag: "thing2"}, %) |> line([0, -10], %, "thing2")
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
|> fillet({radius: 2, tags: [getPreviousAdjacentEdge("thing2", %)]}, %) |> fillet({radius: 2, tags: [getPreviousAdjacentEdge("thing2", %)]}, %)
@ -380,7 +380,7 @@ async fn serial_test_execute_with_angled_line() {
let code = r#"const part001 = startSketchOn('XY') let code = r#"const part001 = startSketchOn('XY')
|> startProfileAt([4.83, 12.56], %) |> startProfileAt([4.83, 12.56], %)
|> line([15.1, 2.48], %) |> line([15.1, 2.48], %)
|> line({ to: [3.15, -9.85], tag: 'seg01' }, %) |> line([3.15, -9.85], %, 'seg01')
|> line([-15.17, -4.1], %) |> line([-15.17, -4.1], %)
|> angledLine([segAng('seg01', %), 12.35], %) |> angledLine([segAng('seg01', %), 12.35], %)
|> line([-13.02, 10.03], %) |> line([-13.02, 10.03], %)
@ -1177,7 +1177,7 @@ async fn serial_test_error_sketch_on_arc_face() {
let code = r#"fn cube = (pos, scale) => { let code = r#"fn cube = (pos, scale) => {
const sg = startSketchOn('XY') const sg = startSketchOn('XY')
|> startProfileAt(pos, %) |> startProfileAt(pos, %)
|> tangentialArc({ to: [0, scale], tag: "here" }, %) |> tangentialArc([0, scale], %, "here")
|> line([scale, 0], %) |> line([scale, 0], %)
|> line([0, -scale], %) |> line([0, -scale], %)
@ -1201,7 +1201,7 @@ const part002 = startSketchOn(part001, "here")
assert!(result.is_err()); assert!(result.is_err());
assert_eq!( assert_eq!(
result.err().unwrap().to_string(), result.err().unwrap().to_string(),
r#"type: KclErrorDetails { source_ranges: [SourceRange([294, 324])], message: "Cannot sketch on a non-planar surface: `here`" }"# r#"type: KclErrorDetails { source_ranges: [SourceRange([281, 311])], message: "Cannot sketch on a non-planar surface: `here`" }"#
); );
} }
@ -1325,18 +1325,9 @@ async fn serial_test_stdlib_kcl_error_circle() {
fn rectShape = (pos, w, l) => { fn rectShape = (pos, w, l) => {
const rr = startSketchOn('XY') const rr = startSketchOn('XY')
|> startProfileAt([pos[0] - (w / 2), pos[1] - (l / 2)], %) |> startProfileAt([pos[0] - (w / 2), pos[1] - (l / 2)], %)
|> lineTo({ |> lineTo([pos[0] + w / 2, pos[1] - (l / 2)], %, "edge1")
to: [pos[0] + w / 2, pos[1] - (l / 2)], |> lineTo([pos[0] + w / 2, pos[1] + l / 2], %, "edge2")
tag: "edge1" |> lineTo([pos[0] - (w / 2), pos[1] + l / 2], %, "edge3")
}, %)
|> lineTo({
to: [pos[0] + w / 2, pos[1] + l / 2],
tag: "edge2"
}, %)
|> lineTo({
to: [pos[0] - (w / 2), pos[1] + l / 2],
tag: "edge3"
}, %)
|> close(%, "edge4") |> close(%, "edge4")
return rr return rr
} }
@ -1367,6 +1358,6 @@ const part = rectShape([0, 0], 20, 20)
assert!(result.is_err()); assert!(result.is_err());
assert_eq!( assert_eq!(
result.err().unwrap().to_string(), result.err().unwrap().to_string(),
r#"type: KclErrorDetails { source_ranges: [SourceRange([987, 1036])], message: "Expected a [number, number] as the first argument, found `[UserVal(UserVal { value: String(\"XY\"), meta: [Metadata { source_range: SourceRange([994, 998]) }] }), UserVal(UserVal { value: Array [Number(-6.0), Number(6)], meta: [Metadata { source_range: SourceRange([1000, 1023]) }] }), UserVal(UserVal { value: Number(1), meta: [Metadata { source_range: SourceRange([856, 857]) }] })]`" }"# r#"type: KclErrorDetails { source_ranges: [SourceRange([891, 940])], message: "Expected a [number, number] as the first argument, found `[UserVal(UserVal { value: String(\"XY\"), meta: [Metadata { source_range: SourceRange([898, 902]) }] }), UserVal(UserVal { value: Array [Number(-6.0), Number(6)], meta: [Metadata { source_range: SourceRange([904, 927]) }] }), UserVal(UserVal { value: Number(1), meta: [Metadata { source_range: SourceRange([760, 761]) }] })]`" }"#
); );
} }