Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod
19.0 KB
Raw Blame
#import "/src/process.typ"
#import "/src/intersection.typ"
#import "/src/path-util.typ"
#import "/src/styles.typ"
#import "/src/drawable.typ"
#import "/src/vector.typ"
#import "/src/util.typ"
#import "/src/coordinate.typ"
#import "/src/aabb.typ"
#import "/src/anchor.typ" as anchor_
#import "/src/matrix.typ"
#import "/src/deps.typ"
#import deps.oxifmt: strfmt

#import "transformations.typ": move-to

/// Hides an element.
///
/// Hidden elements are not drawn to the canvas, are ignored when calculating bounding boxes and discarded by [`merge-path`](../shapes/merge-path). All other behaviours remain the same as a non-hidden element.
///
/// ```example
/// set-style(radius: .5)
/// intersections("i", {
///   circle((0,0), name: "a")
///   circle((1,2), name: "b")
///   // Use a hidden line to find the border intersections
///   hide(line("a.center", "b.center"))
/// })
/// line("i.0", "i.1")
/// ```
///
/// - body (element): One or more elements to hide
/// - bounds (bool): If true, respect the bounding box of the hidden elements for resizing the canvas
#let hide(body, bounds: false) = {
  if type(body) == array {
    return body.map(f => {
      (ctx) => {
        let element = f(ctx)
        if "drawables" in element {
          element.drawables = drawable.apply-tags(element.drawables,
            drawable.TAG.hidden, if not bounds { drawable.TAG.no-bounds })
        }
        return element
      }
    })
  }
  return body
}

/// Places an element without affecting bounding boxes.
///
/// Floating elements are drawn to the canvas but are ignored when calculating bounding boxes. All other behaviours remain the same.
///
/// ```example
/// group(name: "g", {
///   content((1,0), [Normal])
///   content((0,1), [Normal])
///   floating(content((.5,1.5), [Floating]))
/// })
/// set-style(stroke: red)
/// rect("g.north-west", "g.south-east")
/// ```
///
/// - body (element): One or more elements to place
#let floating(body) = {
  if type(body) == array {
    return body.map(f => {
      ctx => {
        let element = f(ctx)
        if "drawables" in element {
          element.drawables = drawable.apply-tags(element.drawables, drawable.TAG.no-bounds)
        }
        return element
      }
    })
  }
  return body
}

/// This element acts as a scope, all state changes such as transformations and styling only affect the elements in the scope.
/// Elements after the scope are not affected by the changes inside the scope.
/// In contrast to `group`, the `scope` element does not create a named element itself and "leaks" body elements and anchors to the outside.
///
/// - body (elements, function): Elements to group together. At least one is required. A function that accepts `ctx` and returns elements is also accepted.
#let scope(body) = (ctx => {
  let drawables = ()
  let group-ctx = ctx
  group-ctx.groups.push(())

  (ctx: group-ctx, drawables, bounds: _) = process.many(group-ctx, util.resolve-body(group-ctx, body), compute-bounds: false)

  // Pass-through nodes and shared context data
  ctx.nodes += group-ctx.nodes
  ctx.shared-state = group-ctx.shared-state

  return (
    ctx: ctx,
    drawables: drawables,
    leak-nodes: true,
  )
},)


/// Calculates the intersections between multiple paths and creates one anchor per intersection point.
///
/// All resulting anchors will be named numerically, starting at `0`. i.e., a call `intersections("a", ...)` will generate the anchors `"a.0"`, `"a.1"`, `"a.2"` to `"a.n"`, depending of the number of intersections.
///
/// ```example
/// intersections("i", {
///   circle((0, 0))
///   bezier((0,0), (3,0), (1,-1), (2,1))
///   line((0,-1), (0,1))
///   rect((1.5,-1),(2.5,1))
/// })
/// for-each-anchor("i", (name) => {
///   circle("i." + name, radius: .1, fill: blue)
/// })
/// ```
///
/// You can also use named elements:
///
/// ```example
/// circle((0,0), name: "a")
/// rect((0,0), (1,1), name: "b")
/// intersections("i", "a", "b")
/// for-each-anchor("i", (name) => {
///   circle("i." + name, radius: .1, fill: blue)
/// })
/// ```
///
/// You can calculate intersections with hidden elements by using [`hide`](./hide).
///
/// - name (str): Name to prepend to the generated anchors. (Not to be confused with other `name` arguments that allow the use of anchor coordinates.)
/// - ..elements (elements,str): Elements and/or element names to calculate intersections with. Elements referred to by name are (unlike elements passed) not drawn by the intersections function!
/// - samples (int): Number of samples to use for non-linear path segments. A higher sample count can give more precise results but worse performance.
/// - sort (none,function): A function of the form `(context, array<vector>) -> array<vector>`
///   that gets called with the list of intersection points.
/// - ignore-marks (bool): If true, ignore mark shapes.
///
///   CeTZ provides the following sorting functions:
///     - sorting.points-by-distace(points, reference: (0, 0, 0))
///     - sorting.points-by-angle(points, reference: (0, 0, 0))
#let intersections(name, ..elements, samples: 10, sort: none, ignore-marks: true) = {
  samples = calc.clamp(samples, 2, 2500)

  assert(type(name) == str and name != "",
    message: "Intersection must have a name, got:" + repr(name))
  assert(elements.pos() != (),
    message: "You must at least give one element to intersections.")

  return scope((ctx => {
    // List of drawables to calc intersections for;
    // grouped by element.
    let named-drawables = ()
    // List of drawables passed as elements to calc intersections for;
    // grouped by element.
    let drawables = ()

    for elem in elements.pos() {
      if type(elem) == str {
        assert(elem in ctx.nodes,
          message: "No such element '" + elem + "' in elements " + repr(ctx.nodes.keys()))
        named-drawables.push(ctx.nodes.at(elem).drawables)
      } else {
        for sub in elem {
          let sub-drawables = ()
          (ctx: ctx, drawables: sub-drawables, bounds: _) = process.element(ctx, sub, compute-bounds: false)
          if sub-drawables != none and sub-drawables != () {
            drawables.push(sub-drawables)
          }
        }
      }
    }

    let elems = named-drawables + drawables
    if ignore-marks { elems = drawable.filter-tagged(elems, drawable.TAG.mark) }

    let pts = ()
    if elems.len() > 1 {
      for (i, elem-1) in elems.enumerate() {
        for j in range(i + 1, elems.len()) {
          let elem-2 = elems.at(j)
          for path-1 in elem-1 {
            for path-2 in elem-2 {
              for pt in intersection.path-path(
                path-1,
                path-2,
                samples: samples
              ) {
                if pt not in pts { pts.push(pt) }
              }
            }
          }
        }
      }
    }

    if sort != none {
      pts = (sort)(ctx, pts)
    }

    let anchors = (:)
    for (i, pt) in pts.enumerate() {
      anchors.insert(str(i), pt)
    }

    return (
      ctx: ctx,
      name: name,
      anchors: anchor_.setup(
        anchor => {
          anchors.at(anchor)
        },
        anchors.keys(),
        transform: none,
        name: name
      ).last(),
      drawables: drawables.flatten()
    )
  },))
}

/// Groups one or more elements together. This element acts as a scope, all state changes such as transformations and styling only affect the elements in the group. Elements after the group are not affected by the changes inside the group.
///
/// ```example
/// // Create group
/// group({
///   stroke(5pt)
///   scale(.5); rotate(45deg)
///   rect((-1,-1),(1,1))
/// })
/// rect((-1,-1),(1,1))
/// ```
///
/// - body (elements, function): Elements to group together. At least one is required. A function that accepts `ctx` and returns elements is also accepted.
/// - anchor (none, str): Anchor to position the group and it's children relative to. For translation the difference between the groups `"default"` anchor and the passed anchor is used.
/// - name (none, str):
/// - ..style (style):
///
/// == Styling
/// *Root:* `group`
///
/// - padding (none, number, array, dictionary) = none: How much padding to add around the group's bounding box. `none` applies no padding. A number applies padding to all sides equally. A dictionary applies padding following Typst's `pad` function: https://typst.app/docs/reference/layout/pad/. An array follows CSS like padding: `(y, x)`, `(top, x, bottom)` or `(top, right, bottom, left)`.
///
/// == Anchors
/// Supports border and path anchors of the axis aligned bounding box of all the child elements of the group.
///
/// You can add custom named anchors to the group by using the [anchor](./anchor) element while in the scope of said group, see [anchor](./anchor) for more details.
///
/// The default anchor is `"center"` but this can be overridden by using [anchor](./anchor) to place a new anchor called `"default"`.
///
/// When using named elements within a group, you can access the element's anchors outside of the group by using the implicit anchor coordinate. e.g. `"a.b.north"`
/// ```example
/// group(name: "a", {
///   circle((), name: "b")
/// })
/// circle("a.b.south", radius: 0.2)
/// circle((name: "a", anchor: "b.north"), radius: 0.2)
/// ```
#let group(body, name: none, anchor: none, ..style) = {
  // No extra positional arguments from the style sink
  if style.pos().len() > 0 {
    panic("Unexpected positional arguments: " + repr(style.pos()),)
  }
  util.assert-body(body)

  (ctx => {
    let style = styles.resolve(ctx.style, merge: style.named(), root: "group")

    let bounds = none
    let drawables = ()
    let group-ctx = ctx
    group-ctx.groups.push(())

    let wants-bounds = name != none or anchor != none
    (ctx: group-ctx, drawables, bounds) = process.many(group-ctx, util.resolve-body(group-ctx, body), compute-bounds: wants-bounds)

    // Pass-through shared context data
    ctx.shared-state = group-ctx.shared-state

    // Fast path for anonymous groups
    if name == none and anchor == none {
      return (ctx: ctx, drawables: drawables)
    }

    // Apply bounds padding
    bounds = if bounds != none {
      let padding = util.map-dict(util.as-padding-dict(style.padding), (_, v) => {
        util.resolve-number(ctx, v)
      })
      aabb.padded(bounds, padding)
    }

    // Calculate a bounding box path used for border anchor calculation.
    let center = none
    let width = none
    let height = none
    let path = none
    if bounds != none {
      (bounds.low.at(1), bounds.high.at(1)) = (bounds.high.at(1), bounds.low.at(1))
      center = aabb.mid(bounds)
      (width, height, ..) = aabb.size(bounds)

      path = drawable.line-strip(aabb.corner-points(bounds), close: true)
    }

    // Children can be none if the groups array is empty
    let anchors = (:)
    for name in group-ctx.groups.last() {
      let child = group-ctx.nodes.at(name)
      if "anchors" in child {
        anchors.insert(name, child.anchors)
      }
    }

    let is-degenerate = (width != none and util.float-eq(width, 0)) or (height != none and util.float-eq(height, 0))

    let all-anchors = if bounds != none {
      (default: center, center: center)
    } + anchors

    let (transform, anchors) = anchor_.setup(
      anchor => {
        let (name, ..nested-anchors) = if type(anchor) == array {
          anchor
        } else {
          (anchor,)
        }
        anchor = all-anchors.at(name)
        if type(anchor) == function {
          anchor(if nested-anchors == () { "default" } else { nested-anchors })
        } else {
          anchor
        }
      },
      (anchors.keys() + if bounds != none { ("center",) }).dedup(),
      name: name,
      default: if bounds != none or "default" in anchors { "default" },
      offset-anchor: anchor,
      path-anchors: bounds != none,
      border-anchors: bounds != none,
      radii: (width, height),
      path: path,
      nested-anchors: true,
      border-anchor-callback: if is-degenerate {
        (center, angle) => {
          let x = if util.float-eq(width, 0) { 0 } else { calc.cos(angle) }
          let y = if util.float-eq(height, 0) { 0 } else { calc.sin(angle) }
          return vector.add(center, (x * width / 2, y * height / 2))
        }
      } else {
        none
      }
    )

    return (
      ctx: ctx,
      name: name,
      anchors: anchors,
      drawables: drawable.apply-transform(transform, drawables),
    )
  },)
}

/// Creates a new anchor for the current group. The new anchor will be accessible from inside the group by using just the anchor's name as a coordinate.
///
/// ```example
/// // Inside a group
/// group(name: "g", {
///   circle((0,0))
///   anchor("x", (.4, .1))
///   circle("x", radius: .2)
/// })
/// circle("g.x", radius: .1)
/// ```
///
/// ```example
/// // At the root scope
/// anchor("x", (1, 1))
/// // ...
/// circle("x", radius: .1)
/// ```
///
/// - name (str): The name of the anchor
/// - position (coordinate): The position of the anchor
#let anchor(name, position) = {
  assert(name != none and name != "" and not name.starts-with("."),
    message: "Anchors must not be none, \"\" or start with \".\"!")

  return (ctx => {
    let (ctx, position) = coordinate.resolve(ctx, position)
    position = util.apply-transform(ctx.transform, position)
    return (
      ctx: ctx,
      name: name,
      anchors: anchor_.setup(
        anchor => position,
        ("default",),
        default: "default",
        name: name,
        transform: none
      ).last()
    )
  },)
}

/// Copies multiple anchors from one element into the current group. Panics when used outside of a group. Copied anchors will be accessible in the same way anchors created by the `anchor` element are.
///
/// - element (str): The name of the element to copy anchors from.
/// - filter (auto,array): When set to `auto` all anchors will be copied to the group. An array of anchor names can instead be given so only the anchors that are in the element and the list will be copied over.
#let copy-anchors(element, filter: auto) = {
  (ctx => {
    assert(
      ctx.groups.len() > 0,
      message: "copy-anchors cannot be used outside of a group.",
    )
    assert(
      element in ctx.nodes,
      message: "copy-anchors: Could not find element '" + element + "'",
    )

    let calc-anchors = ctx.nodes.at(element).anchors
    let anchors = calc-anchors(())
    if filter != auto {
      anchors = anchors.filter(a => a in filter)
    }

    // Add each anchor as own element
    for anchor in anchors {
      ctx.nodes.insert(
        anchor,
        (anchors: name => {
          if name == "default" {
            calc-anchors(anchor)
          } else if name == () {
            ("default",)
          } else {
            calc-anchors((anchor,) + name)
          }
        })
      )
      ctx.groups.last().push(anchor)
    }

    return (ctx: ctx)
  },)
}

/// An advanced element that allows you to modify the current canvas type:context.
/// Note: The transformation matrix (`transform`) is rounded after calling the `callback` function and therefore might be not exactly the matrix specified. This is due to rounding errors and should not cause any problems.
///
/// ```example
/// // Setting custom shared state
/// set-ctx(ctx => {
///   ctx.shared-state.my-state = (
///     key: 123
///   )
///   return ctx
/// })
///
/// // ...
///
/// // Access the context object
/// get-ctx(ctx => content((), [#repr(ctx.shared-state)]))
/// ```
///
/// You can store shared context data under a key in the `ctx.shared-state`
/// dictionary. Note: the `ctx.shared-state` dictionary is not scoped by
/// `group` or `scope` elements and can be used for canvas global state.
///
/// - callback (function): A function that accepts the type:context dictionary and only returns a new one.
#let set-ctx(callback) = {
  assert(type(callback) == function)
  return (ctx => {
    let new-ctx = callback(ctx)
    assert(new-ctx != none, message: "set-ctx must return a context!")

    if new-ctx.transform != ctx.transform {
      // User supplied matrices can cause rounding issues
      new-ctx.transform = matrix.round(new-ctx.transform)
    }
    (ctx: new-ctx)
  },)
}

/// An advanced element that allows you to read the current `context` through a callback and return `element`s based on it.
///
/// ```example
/// // Print the transformation matrix
/// get-ctx(ctx => {
///   content((), [#repr(ctx.transform)])
/// })
/// ```
///
/// - callback (function): A function that accepts the type:context and can return elements.
#let get-ctx(callback) = {
  assert(type(callback) == function)
  (ctx => {
    let body = callback(ctx)
    if body != none {
      let (ctx, drawables) = process.many(ctx, body, compute-bounds: false)
      return (ctx: ctx, drawables: drawables)
    }
    return (ctx: ctx)
  },)
}

/// Iterates through all named anchors of an element and calls a callback for each one.
///
/// ```example
/// // Label nodes anchors
/// rect((0, 0), (2,2), name: "my-rect")
/// for-each-anchor("my-rect", exclude: ("start", "mid", "end"), (name) => {
///    content((), box(inset: 1pt, fill: white, text(8pt, [#name])), angle: -30deg)
/// })
/// ```
///
/// - name (str): The name of the element with the anchors to loop through.
/// - callback (function): A function that takes the anchor name and can return elements.
/// - exclude (array): An array of anchor names to not include in the loop.
#let for-each-anchor(name, callback, exclude: ()) = {
  get-ctx(ctx => {
    if not name in ctx.nodes {
      panic(strfmt("Unknown element {} in elements {}", name, repr(ctx.nodes.keys())))
    }

    for anchor in (ctx.nodes.at(name).anchors)(()) {
      if anchor == none or (anchor in exclude) { continue }
      move-to(name + "." + anchor)
      callback(anchor)
    }
  })
}

/// Places elements on a specific layer.
///
/// A layer determines the position of an element in the draw queue. A lower layer is drawn before a higher layer.
///
/// Layers can be used to draw behind or in front of other elements, even if the other elements were created before or after. An example would be drawing a background behind a text, but using the text's calculated bounding box for positioning the background.
///
/// ```example
/// // Draw something behind text
/// set-style(stroke: none)
/// content((0, 0), [This is an example.], name: "text")
/// on-layer(-1, {
///   circle("text.north-east", radius: .3, fill: red)
///   circle("text.south", radius: .4, fill: green)
///   circle("text.north-west", radius: .2, fill: blue)
/// })
/// ```
///
/// - layer (float, int): The layer to place the elements on. Elements placed without `on-layer` are always placed on layer 0.
/// - body (elements, function): Elements to draw on the layer specified. A function that accepts `ctx` and returns elements is also accepted.
#let on-layer(layer, body) = {
  util.assert-body(body)
  assert(type(layer) in (int, float),
    message: "Layer must be a float or integer, 0 being the default layer. Got: " + repr(layer))

  return (ctx => {
    let (ctx, drawables, bounds: _) = process.many(ctx, util.resolve-body(ctx, body), compute-bounds: false)
    drawables = drawables.map(d => {
      if d.at("z-index", default: none) == none {
        d.z-index = layer
      }
      return d
    })

    return (
      ctx: ctx,
      drawables: drawables
    )
  },)
}