colight.core
Interactivity
State
Initializes state variables in the Plot widget.
Parameters
-
values
(dict[str, Any]): A dictionary mapping state variable names to their initial values. -
sync
(Union[set[str], bool, None]): Controls which state variables are synced between Python and JavaScript.If True, all variables are synced. If a set, only variables in the set are synced.
If None or False, no variables are synced. Defaults to None.
Returns
- An object that initializes the state variables when rendered. (Marker)
Examples:
Plot.State({"count": 0, "name": "foo"}) # Initialize without sync
Plot.State({"count": 0}, sync=True) # Sync all variables
Plot.State({"x": 0, "y": 1}, sync={"x"}) # Only sync "x"
onChange
Adds callbacks to be invoked when state changes.
Parameters
callbacks
(dict): A dictionary mapping state keys to callbacks, which are called with (widget, event) when the corresponding state changes.
Returns
- A Listener object that will be rendered to set up the event handlers.
Frames
Create an animated plot that cycles through a list of frames.
Parameters
-
frames
(list): A list of plot specifications or renderable objects to animate. -
key
(str | None): The state key to use for the frame index. If None, uses "frame". -
slider
(bool): Whether to show the slider control. Defaults to True. -
tail
(bool): Whether animation should stop at the end. Defaults to False. -
**opts
(Any): Additional options for the animation, such as fps (frames per second).
Returns
- A Hiccup-style representation of the animated plot. (LayoutItem)
Slider
Layout
Useful for layouts and custom views.
Note that syntax sugar exists for Column
(|
) and Row
(&
) using operator overloading.
(A & B) | C # A & B on one row, with C below.
Column
Render children in a column.
Parameters
-
*items
(Any): Items to render in the column -
**kwargs
: Additional options including:heights: List of flex sizes for each child. Can be:
- Numbers for flex ratios (e.g. [1, 2] means second item is twice as tall) - Strings with fractions (e.g. ["1/2", "1/2"] for equal halves) - Strings with explicit sizes (e.g. ["100px", "200px"])
gap: Gap size between items (default: 1)
className: Additional CSS classes
Grid
Creates a responsive grid layout that automatically arranges child elements in a grid pattern.
The grid adjusts the number of columns based on the available width and minimum width per item. Each item maintains consistent spacing controlled by gap parameters.
Parameters
-
*children
: Child elements to arrange in the grid. -
**opts
: Grid options including:-
minWidth (int): Minimum width for each grid item in pixels. Default is 165.
-
gap (int): Gap size for both row and column gaps. Default is 1.
-
rowGap (int): Vertical gap between rows. Overrides gap if specified.
-
colGap (int): Horizontal gap between columns. Overrides gap if specified.
-
cols (int): Fixed number of columns. If not set, columns are calculated based on minWidth.
-
minCols (int): Minimum number of columns. Default is 1.
-
maxCols (int): Maximum number of columns.
-
widths (List[Union[int, str]]): Array of column widths. Can be numbers (for fractions) or strings.
-
heights (List[Union[int, str]]): Array of row heights. Can be numbers (for fractions) or strings.
-
height (str): Container height.
-
style (dict): Additional CSS styles to apply to grid container.
-
className (str): Additional CSS classes to apply.
-
Returns
- A grid layout component that will be rendered in the JavaScript runtime.
Row
Render children in a row.
Parameters
-
*items
(Any): Items to render in the row -
**kwargs
: Additional options including:widths: List of flex sizes for each child. Can be:
- Numbers for flex ratios (e.g. [1, 2] means second item is twice as wide) - Strings with fractions (e.g. ["1/2", "1/2"] for equal halves) - Strings with explicit sizes (e.g. ["100px", "200px"])
gap: Gap size between items (default: 1)
className: Additional CSS classes
Flow Control
cond
Render content based on conditions, like Clojure's cond.
Takes pairs of test/expression arguments, evaluating each test in order. When a test is truthy, returns its corresponding expression. An optional final argument serves as the "else" expression.
Parameters
*args
: Alternating test/expression pairs, with optional final else expression
case
Render content based on matching a value against cases, like a switch statement.
Takes a value to match against, followed by pairs of case/expression arguments. When a case matches the value, returns its corresponding expression. An optional final argument serves as the default expression.
Parameters
-
value
(Union[JSCode, str, Any]): The value to match against cases -
*args
: Alternating case/expression pairs, with optional final default expression
JavaScript Interop
Import
Import JavaScript code into the Colight environment.
Parameters
-
source
(str): JavaScript source code. Can be:-
Inline JavaScript code
-
URL starting with http(s):// for remote modules
-
Local file path starting with path: prefix
-
-
alias
(Optional[str]): Namespace alias for the entire module -
default
(Optional[str]): Name for the default export -
refer
(Optional[list[str]]): Set of names to import directly, or True to import all -
refer_all
(bool): Alternative to refer=True -
rename
(Optional[dict[str, str]]): Dict of original->new names for referred imports -
exclude
(Optional[list[str]]): Set of names to exclude when using refer_all -
format
(str): Module format ('esm' or 'commonjs')
Imported JavaScript code can access:
- colight.imports
: Previous imports in the current plot (only for CommonJS imports)
- React
, d3
, html
(for hiccup) and colight.api
are defined globally
Examples:
# CDN import with namespace alias
Plot.Import(
source="https://cdn.skypack.dev/lodash-es",
alias="_",
refer=["flattenDeep", "partition"],
rename={"flattenDeep": "deepFlatten"}
)
# Local file import
Plot.Import(
source="path:src/app/utils.js", # relative to working directory
refer=["formatDate"]
)
# Inline source with refer_all
Plot.Import(
source='''
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
''',
refer_all=True,
exclude=["subtract"]
)
# Default export handling
Plot.Import(
source="https://cdn.skypack.dev/d3-scale",
default="createScale"
)
js
Represents raw JavaScript code to be evaluated as a LayoutItem.
The code will be evaluated in a scope that includes: - $state: Current plot state - html: render HTML using a JavaScript hiccup syntax - d3: D3.js library - colight.api: roughly, the api exposed via the colight.plot module - Any additional variables passed as kwargs
Parameters
-
txt
(str): JavaScript code with optional %1, %2, etc. placeholders -
*params
(Any): Values to substitute for %1, %2, etc. placeholders -
expression
(bool): Whether to evaluate as expression or statement -
**kwargs
(Any): Additional variables to include in the JavaScript scope
Formatting
html
md
Render a string as Markdown, in a LayoutItem.
katex
Render a TeX string, in a LayoutItem.