Skip to content

Commit

Permalink
coordinate: Add register function
Browse files Browse the repository at this point in the history
  • Loading branch information
johannes-wolf committed Oct 13, 2024
1 parent 7f8f456 commit c23e480
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/draw.typ
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
#import "draw/styling.typ": set-style, fill, stroke, register-mark
#import "draw/shapes.typ": circle, circle-through, arc, arc-through, mark, line, grid, content, rect, bezier, bezier-through, catmull, hobby, merge-path
#import "draw/projection.typ": ortho, on-xy, on-xz, on-yz
#import "draw/util.typ": assert-version
#import "draw/util.typ": assert-version, register-coordinate-resolver
38 changes: 38 additions & 0 deletions src/draw/util.typ
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,41 @@
return (ctx: ctx)
},)
}

/// Push a custom coordinate resolve function to the list of coordinate
/// resolvers. This resolver is scoped to the current context scope!
///
/// A coordinate resolver must be a function of the format `(context, coordinate) => coordinate`. And must _always_ return a valid coordinate or panic, in case of an error.
///
/// If multiple resolvers are registered, coordinates get passed through all
/// resolvers in reverse registering order. All coordinates get paased to cetz'
/// default coordinate resolvers.
///
/// ```typc example
/// register-coordinate-resolver((ctx, c) => {
/// if type(c) == dictionary and "log" in c {
/// c = c.log.map(n => calc.log(n, base: 10))
/// }
/// return c
/// })
///
/// circle((log: (10, 0)), radius: .25)
/// circle((log: (100, 0)), radius: .25)
/// circle((log: (1000, 0)), radius: .25)
/// ```
///
/// - resolver (function): The resolver function, taking a context and a single coordinate and returning a single coordinate
#let register-coordinate-resolver(resolver) = {
assert.eq(type(resolver), function,
message: "Coordinate resolver must be of type function (ctx, coordinate) => coordinate.")

return (ctx => {
if type(ctx.resolve-coordinate) == array {
ctx.resolve-coordinate.push(resolver)
} else {
ctx.resolve-coordinate = (resolver,)
}

return (ctx: ctx)
},)
}
5 changes: 1 addition & 4 deletions tests/coordinate/custom/test.typ
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@
return coordinate
}

set-ctx(ctx => {
ctx.resolve-coordinate = log-resolver
return ctx
})
register-coordinate-resolver(log-resolver)

set-style(circle: (radius: .1))
for i in (.1, 1, 10, 100, 1000, 10000) {
Expand Down

0 comments on commit c23e480

Please sign in to comment.