How can I extract a state's value and store it in a global variable?

How to extract value from a state function?

Hello, everyone. I encountered a problem about the syntax of state.

Here is a minimal example for what I’m trying to do.

// filename: template.typ

#let theme-color-final = context theme-color.final()

#let thmbox(color: theme-color-final, it) = figure(
// The line below throw a error: 
// expected color, gradient, or tiling, found auto
block()[#text(fill:color)[#it]]
)

#let definition(color:auto, it) = thmbox(color:color, it)

#let template(style: "minimal", color: rgb("#0088ff82"), doc) = {
  let theme-color = state("theme-color", color)
  doc
}

Use in another file

#import "template.typ":*
#show: template
//Work properly when put color:rgb("#000000") in definition's argument list
#definition()[some texts]

Problem

The template.typ fails to compile and I’m not able to identify the cause for it. Please provide some suggestions if you know how to solve this problem.

Hello @hexiongwu1995.

This is a very common question on this forum and you will find everything you need about state and context in posts like:

The important bit to understand is that context theme-color.final() does not produce a color value. It produces opaque contextual content.

See this very similar case for an example.

Edit:

To demonstrate how this works, especially with auto:

// template.typ
#let _theme-color = state("theme-color", red)
#let _update-theme-color(color) = _theme-color.update(color)

#let _thmbox(color: auto, it) = {
  let color = if color == auto {
    _theme-color.get()
  } else {
    color
  }

  figure(
    block()[#text(fill: color)[#it]],
  )
}

#let definition(color: auto, it) = context _thmbox(color: color, it)

#let template(color: auto, doc) = {
  if color != auto { _update-theme-color(color) }
  doc
}

// main.typ
#import "state-forum.typ": template, definition

#show: template
#definition()[Red]

#show: template.with(color: green)
#definition()[Green]

#definition(color: blue)[Blue]



Another method could be to use metadata.

Note that auto is not a color so you need special handling if you want to avoid getting the error you were reporting.

1 Like