xnano.components
xnano.components
¶
xnano.components
Components: functions and objects that draw or play themselves, and run again only when something they read changes.
Classes:
-
SupportsPlay–Anything that can be played: an object with a
__xnano_play__method. -
SupportsRender–Anything with a screen of its own: an object with a
__xnano_render__method. -
SupportsWrite–Anything that draws itself: an object with a
__xnano_write__method. -
ComponentContext–What a component's hook receives besides the hook's own context.
-
ComponentHook–What
component.hook(...)returns: a hook on every placement of a component. -
WritableComponent–A writable function with its own parameters given:
gauge(ratio=0.7). -
PlayableComponent–A playable function with its own parameters given:
arpeggio(root='C4'). -
WritableFunction–A function that draws itself: what
writablereturns. -
PlayableFunction–A function that plays itself: what
playablereturns. -
RenderableComponent–A renderable function with its own parameters given:
meter(limit=0.9). -
RenderableFunction–A function with a screen of its own: what
renderablereturns.
Functions:
-
writable–Turn a function into a component that draws itself.
-
renderable–Turn a function into a component with a screen of its own, which draws and plays.
-
playable–Turn a function into a component that plays itself.
Attributes:
-
Content(TypeAlias) –Anything a canvas can show or play: a
Writableor aPlayable. -
Playable(TypeAlias) –Anything
playandSpeaker.playaccept: a -
PlaySource(TypeAlias) –Anything
playandSpeaker.playaccept: a -
Writable(TypeAlias) –Anything
Screen.writeaccepts: text, styled text (a
Content
module-attribute
¶
Content: TypeAlias = 'Writable | Playable'
Anything a canvas can show or play: a Writable or a Playable.
Playable
module-attribute
¶
Playable: TypeAlias = 'str | Note | Melody | Audio | SupportsPlay | Sequence[Playable]'
Anything play and Speaker.play accept: a
Note, a Melody, an Audio, an object
with __xnano_play__, a sequence of those that plays one after another, or a str: the
name of a registered symbol, a note name such as 'C#4', or melody text such as
'C4 E4 G4:2'.
PlaySource
module-attribute
¶
PlaySource: TypeAlias = 'Playable | int | float | TerminalSound | TerminalNote | TerminalMelody'
Writable
module-attribute
¶
Writable: TypeAlias = 'str | StyledText | Region | Art | Pixel | Image | Buffer | SupportsWrite | SupportsRender | Sequence[Writable]'
Anything Screen.write accepts: text, styled text (a
StyledText, such as one from StyledText.from_ansi()), a
Region, an Art, a Pixel, an
Image, a core Buffer, an object with
__xnano_write__, or a sequence of those, which is stacked from top to bottom; or a
renderable, an object with __xnano_render__, which is written on its own.
SupportsPlay
¶
Bases: Protocol[DepsT_contra, StateT_contra]
Anything that can be played: an object with a __xnano_play__ method.
The method receives the Context and returns what to play.
No base class is needed; a dataclass or a plain class qualifies. The context may be
annotated with the dependency and state types the component reads, such as
Context[Services].
Methods:
-
__xnano_play__–Return what to play.
SupportsRender
¶
Bases: Protocol[DepsT_contra, StateT_contra]
Anything with a screen of its own: an object with a __xnano_render__ method.
The method receives the Context, draws on context.screen
(its own screen, where it is written) and plays on context.speaker, and returns
nothing. Each run starts from an empty screen. No base class is needed; a dataclass or a
plain class qualifies. The method runs again, on the next frame, only when it read
something that changes (the time, the size, state or an input).
Methods:
-
__xnano_render__–Draw on
context.screenand play oncontext.speaker.
SupportsWrite
¶
Bases: Protocol[DepsT_contra, StateT_contra]
Anything that draws itself: an object with a __xnano_write__ method.
The method receives the Context and returns what to draw, which
is any Writable. No base class is needed; a dataclass or a
plain class qualifies. The context may be annotated with the dependency and state types
the component reads, such as Context[Services]. The method runs again, on the next
frame, only when it read something that changes (the time, the size, state or an input).
Methods:
-
__xnano_write__–Return what to draw.
ComponentContext
dataclass
¶
ComponentContext(component: WritableComponent[DepsT, StateT] | PlayableComponent[DepsT, StateT], placement: Placement[DepsT, StateT] | None, arguments: Mapping[str, object])
Bases: Generic[DepsT, StateT]
What a component's hook receives besides the hook's own context.
Attributes:
-
component(WritableComponent[DepsT, StateT] | PlayableComponent[DepsT, StateT]) –The component the hook belongs to.
-
placement(Placement[DepsT, StateT] | None) –The placement the component is drawn in, or
Nonefor a playable component, which has no placement. -
arguments(Mapping[str, object]) –The component's own parameters, by name.
Examples:
import xnano
@xnano.writable
def gauge(context: xnano.Context, ratio: float = 0.0) -> str:
return '#' * round(ratio * 10)
with xnano.new(width=12, height=1) as canvas:
seen = []
gauge.hook(
lambda context, component_context: seen.append(
component_context.arguments['ratio']
),
on='tick',
)
canvas.screen.write(gauge(ratio=0.5))
canvas.clock.step(delta_seconds=0.1)
assert seen == [0.5]
component
instance-attribute
¶
component: WritableComponent[DepsT, StateT] | PlayableComponent[DepsT, StateT]
The component the hook belongs to.
ComponentHook
¶
What component.hook(...) returns: a hook on every placement of a component.
The hook is installed on the placements that exist now and on those created later;
remove takes it off all of them. It never starts a placement of its own.
Attributes:
-
handles(tuple[HookHandle[object, object], ...]) –The
HookHandleon each placement it is installed on right now. -
is_removed(bool) –Whether
removewas called.
Create the hook. Use component.hook(...) instead of calling this.
Parameters:
-
owner(_HookSource) –The component or component function the hook was added to.
-
function(Callable[..., object]) –The function to call with a context and a component context.
-
settings(_HookSettings) –The keywords of
hook.
Methods:
-
remove–Take the hook off every placement. Removing twice does nothing.
Source code in xnano/components.py
def __init__(
self,
owner: _HookSource,
function: Callable[..., object],
settings: _HookSettings,
) -> None:
"""
Create the hook. Use ``component.hook(...)`` instead of calling this.
Args:
owner: The component or component function the hook was added to.
function: The function to call with a context and a component context.
settings: The keywords of ``hook``.
"""
self._owner = owner
self._function = function
self._settings = settings
self._handles: list[tuple[object, HookHandle[object, object]]] = []
self._is_removed = False
WritableComponent
¶
WritableComponent(function: _ComponentFunction[..., object, object], bound: BoundArguments)
Bases: _BoundComponent, Generic[DepsT, StateT]
A writable function with its own parameters given: gauge(ratio=0.7).
Write it with canvas.screen.write(component). It is evaluated once, and again only when it
read something that changes. See writable.
Attributes:
Keep the function and its arguments. Call the decorated function instead.
Methods:
-
__xnano_write__–Draw the component with the parameters it was given.
-
hook–Call a function when something happens to a placement of this component.
Source code in xnano/components.py
__xnano_write__
¶
hook
¶
hook(function: Callable[..., object] | None = None, /, *, on: HookTrigger[object, object] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]
Call a function when something happens to a placement of this component.
The function receives the hook's Context and a
ComponentContext. The arguments are those of
hook on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Parameters:
-
function(Callable[..., object] | None, default:None) –The function to call, or
Noneto use this as a decorator. -
on(HookTrigger[object, object] | None, default:None) –When the hook runs: a kind of event, the name of a custom event, or a condition; see
HookTrigger. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds or beats.
-
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). Checked each time the hook is installed.
Returns:
-
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–A
ComponentHook, whoseremovetakes the -
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–hook off every placement; or, without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense; see
hook. -
TerminalError–requires_depsis true and the canvas was created withoutdeps.
Examples:
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
Source code in xnano/components.py
def hook(
self,
function: Callable[..., object] | None = None,
/,
*,
on: HookTrigger[object, object] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]:
"""
Call a function when something happens to a placement of this component.
The function receives the hook's [`Context`][xnano.hooks.Context] and a
[`ComponentContext`][xnano.components.ComponentContext]. The arguments are those of
``hook`` on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Args:
function: The function to call, or ``None`` to use this as a decorator.
on: When the hook runs: a kind of event, the name of a custom event, or a
condition; see [`HookTrigger`][xnano.hooks.HookTrigger].
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds or beats.
keys: The key or keys an ``on='key'`` hook reacts to.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``. Checked each time the hook is installed.
Returns:
A [`ComponentHook`][xnano.components.ComponentHook], whose ``remove`` takes the
hook off every placement; or, without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense; see
[`hook`][xnano.canvas.Canvas.hook].
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``.
Examples:
```python
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
```
"""
from xnano.hooks._handles import (
_check_hook_arguments,
_check_hook_function,
resolve_trigger,
)
from xnano.hooks._triggers import compile_when
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
_check_hook_arguments(
cast('_Hooked[object, object]', _PlacementLike()), kind, every, after, keys
)
compile_when(condition)
settings = _HookSettings(on, every, after, keys, requires_deps)
def attach(callback: Callable[..., object]) -> ComponentHook:
component_hook = ComponentHook(
self, _check_hook_function(callback, arguments=2), settings
)
self._hooks.append(component_hook)
try:
self._install_everywhere(component_hook)
except BaseException:
component_hook.remove()
raise
return component_hook
if function is None:
return attach
return attach(function)
PlayableComponent
¶
PlayableComponent(function: _ComponentFunction[..., object, object], bound: BoundArguments)
Bases: _BoundComponent, Generic[DepsT, StateT]
A playable function with its own parameters given: arpeggio(root='C4').
Play it with canvas.speaker.play(component). See playable.
Attributes:
Keep the function and its arguments. Call the decorated function instead.
Methods:
-
__xnano_play__–Return what to play, with the parameters the component was given.
-
hook–Call a function when something happens to a placement of this component.
Source code in xnano/components.py
__xnano_play__
¶
hook
¶
hook(function: Callable[..., object] | None = None, /, *, on: HookTrigger[object, object] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]
Call a function when something happens to a placement of this component.
The function receives the hook's Context and a
ComponentContext. The arguments are those of
hook on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Parameters:
-
function(Callable[..., object] | None, default:None) –The function to call, or
Noneto use this as a decorator. -
on(HookTrigger[object, object] | None, default:None) –When the hook runs: a kind of event, the name of a custom event, or a condition; see
HookTrigger. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds or beats.
-
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). Checked each time the hook is installed.
Returns:
-
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–A
ComponentHook, whoseremovetakes the -
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–hook off every placement; or, without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense; see
hook. -
TerminalError–requires_depsis true and the canvas was created withoutdeps.
Examples:
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
Source code in xnano/components.py
def hook(
self,
function: Callable[..., object] | None = None,
/,
*,
on: HookTrigger[object, object] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]:
"""
Call a function when something happens to a placement of this component.
The function receives the hook's [`Context`][xnano.hooks.Context] and a
[`ComponentContext`][xnano.components.ComponentContext]. The arguments are those of
``hook`` on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Args:
function: The function to call, or ``None`` to use this as a decorator.
on: When the hook runs: a kind of event, the name of a custom event, or a
condition; see [`HookTrigger`][xnano.hooks.HookTrigger].
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds or beats.
keys: The key or keys an ``on='key'`` hook reacts to.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``. Checked each time the hook is installed.
Returns:
A [`ComponentHook`][xnano.components.ComponentHook], whose ``remove`` takes the
hook off every placement; or, without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense; see
[`hook`][xnano.canvas.Canvas.hook].
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``.
Examples:
```python
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
```
"""
from xnano.hooks._handles import (
_check_hook_arguments,
_check_hook_function,
resolve_trigger,
)
from xnano.hooks._triggers import compile_when
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
_check_hook_arguments(
cast('_Hooked[object, object]', _PlacementLike()), kind, every, after, keys
)
compile_when(condition)
settings = _HookSettings(on, every, after, keys, requires_deps)
def attach(callback: Callable[..., object]) -> ComponentHook:
component_hook = ComponentHook(
self, _check_hook_function(callback, arguments=2), settings
)
self._hooks.append(component_hook)
try:
self._install_everywhere(component_hook)
except BaseException:
component_hook.remove()
raise
return component_hook
if function is None:
return attach
return attach(function)
WritableFunction
¶
WritableFunction(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], object])
Bases: _ComponentFunction[ParametersT, DepsT, StateT]
A function that draws itself: what writable returns.
The function is the component. canvas.screen.write(function) draws it with its default
parameters, and canvas.screen.write(function(ratio=0.7)) gives it its own parameters
first. Calling it does not run it; it makes a
WritableComponent.
Attributes:
Keep the function. Use @xnano.writable, @xnano.renderable or @xnano.playable.
Methods:
-
__call__–Give the component its own parameters; the context is passed for you.
-
__xnano_write__–Draw the component with its default parameters.
-
hook–Call a function when something happens to a placement of this component.
Source code in xnano/components.py
def __init__(
self,
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], object],
) -> None:
"""Keep the function. Use ``@xnano.writable``, ``@xnano.renderable`` or ``@xnano.playable``."""
super().__init__()
self._function = function
self._signature, self._takes_context = _own_signature(function, self._decorator)
functools.update_wrapper(self, function) # pyright: ignore[reportArgumentType]
arguments
property
¶
The parameters the component is written with: none, so the defaults apply.
__call__
¶
__call__(*arguments: args, **keywords: kwargs) -> WritableComponent[DepsT, StateT]
Give the component its own parameters; the context is passed for you.
Source code in xnano/components.py
__xnano_write__
¶
hook
¶
hook(function: Callable[..., object] | None = None, /, *, on: HookTrigger[object, object] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]
Call a function when something happens to a placement of this component.
The function receives the hook's Context and a
ComponentContext. The arguments are those of
hook on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Parameters:
-
function(Callable[..., object] | None, default:None) –The function to call, or
Noneto use this as a decorator. -
on(HookTrigger[object, object] | None, default:None) –When the hook runs: a kind of event, the name of a custom event, or a condition; see
HookTrigger. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds or beats.
-
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). Checked each time the hook is installed.
Returns:
-
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–A
ComponentHook, whoseremovetakes the -
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–hook off every placement; or, without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense; see
hook. -
TerminalError–requires_depsis true and the canvas was created withoutdeps.
Examples:
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
Source code in xnano/components.py
def hook(
self,
function: Callable[..., object] | None = None,
/,
*,
on: HookTrigger[object, object] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]:
"""
Call a function when something happens to a placement of this component.
The function receives the hook's [`Context`][xnano.hooks.Context] and a
[`ComponentContext`][xnano.components.ComponentContext]. The arguments are those of
``hook`` on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Args:
function: The function to call, or ``None`` to use this as a decorator.
on: When the hook runs: a kind of event, the name of a custom event, or a
condition; see [`HookTrigger`][xnano.hooks.HookTrigger].
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds or beats.
keys: The key or keys an ``on='key'`` hook reacts to.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``. Checked each time the hook is installed.
Returns:
A [`ComponentHook`][xnano.components.ComponentHook], whose ``remove`` takes the
hook off every placement; or, without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense; see
[`hook`][xnano.canvas.Canvas.hook].
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``.
Examples:
```python
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
```
"""
from xnano.hooks._handles import (
_check_hook_arguments,
_check_hook_function,
resolve_trigger,
)
from xnano.hooks._triggers import compile_when
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
_check_hook_arguments(
cast('_Hooked[object, object]', _PlacementLike()), kind, every, after, keys
)
compile_when(condition)
settings = _HookSettings(on, every, after, keys, requires_deps)
def attach(callback: Callable[..., object]) -> ComponentHook:
component_hook = ComponentHook(
self, _check_hook_function(callback, arguments=2), settings
)
self._hooks.append(component_hook)
try:
self._install_everywhere(component_hook)
except BaseException:
component_hook.remove()
raise
return component_hook
if function is None:
return attach
return attach(function)
PlayableFunction
¶
PlayableFunction(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], object])
Bases: _ComponentFunction[ParametersT, DepsT, StateT]
A function that plays itself: what playable returns.
canvas.speaker.play(function) plays it with its default parameters, and
canvas.speaker.play(function(root='C4')) gives it its own parameters first.
Attributes:
Keep the function. Use @xnano.writable, @xnano.renderable or @xnano.playable.
Methods:
-
__call__–Give the component its own parameters; the context is passed for you.
-
__xnano_play__–Return what to play with the default parameters.
-
hook–Call a function when something happens to a placement of this component.
Source code in xnano/components.py
def __init__(
self,
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], object],
) -> None:
"""Keep the function. Use ``@xnano.writable``, ``@xnano.renderable`` or ``@xnano.playable``."""
super().__init__()
self._function = function
self._signature, self._takes_context = _own_signature(function, self._decorator)
functools.update_wrapper(self, function) # pyright: ignore[reportArgumentType]
arguments
property
¶
The parameters the component is written with: none, so the defaults apply.
__call__
¶
__call__(*arguments: args, **keywords: kwargs) -> PlayableComponent[DepsT, StateT]
Give the component its own parameters; the context is passed for you.
Source code in xnano/components.py
__xnano_play__
¶
hook
¶
hook(function: Callable[..., object] | None = None, /, *, on: HookTrigger[object, object] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]
Call a function when something happens to a placement of this component.
The function receives the hook's Context and a
ComponentContext. The arguments are those of
hook on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Parameters:
-
function(Callable[..., object] | None, default:None) –The function to call, or
Noneto use this as a decorator. -
on(HookTrigger[object, object] | None, default:None) –When the hook runs: a kind of event, the name of a custom event, or a condition; see
HookTrigger. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds or beats.
-
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). Checked each time the hook is installed.
Returns:
-
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–A
ComponentHook, whoseremovetakes the -
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–hook off every placement; or, without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense; see
hook. -
TerminalError–requires_depsis true and the canvas was created withoutdeps.
Examples:
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
Source code in xnano/components.py
def hook(
self,
function: Callable[..., object] | None = None,
/,
*,
on: HookTrigger[object, object] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]:
"""
Call a function when something happens to a placement of this component.
The function receives the hook's [`Context`][xnano.hooks.Context] and a
[`ComponentContext`][xnano.components.ComponentContext]. The arguments are those of
``hook`` on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Args:
function: The function to call, or ``None`` to use this as a decorator.
on: When the hook runs: a kind of event, the name of a custom event, or a
condition; see [`HookTrigger`][xnano.hooks.HookTrigger].
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds or beats.
keys: The key or keys an ``on='key'`` hook reacts to.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``. Checked each time the hook is installed.
Returns:
A [`ComponentHook`][xnano.components.ComponentHook], whose ``remove`` takes the
hook off every placement; or, without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense; see
[`hook`][xnano.canvas.Canvas.hook].
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``.
Examples:
```python
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
```
"""
from xnano.hooks._handles import (
_check_hook_arguments,
_check_hook_function,
resolve_trigger,
)
from xnano.hooks._triggers import compile_when
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
_check_hook_arguments(
cast('_Hooked[object, object]', _PlacementLike()), kind, every, after, keys
)
compile_when(condition)
settings = _HookSettings(on, every, after, keys, requires_deps)
def attach(callback: Callable[..., object]) -> ComponentHook:
component_hook = ComponentHook(
self, _check_hook_function(callback, arguments=2), settings
)
self._hooks.append(component_hook)
try:
self._install_everywhere(component_hook)
except BaseException:
component_hook.remove()
raise
return component_hook
if function is None:
return attach
return attach(function)
RenderableComponent
¶
RenderableComponent(function: _ComponentFunction[..., object, object], bound: BoundArguments)
Bases: _BoundComponent, Generic[DepsT, StateT]
A renderable function with its own parameters given: meter(limit=0.9).
Write it with canvas.screen.write(component). See renderable.
Attributes:
Keep the function and its arguments. Call the decorated function instead.
Methods:
-
__xnano_render__–Draw on
context.screenand play oncontext.speaker, with the parameters given. -
hook–Call a function when something happens to a placement of this component.
Source code in xnano/components.py
__xnano_render__
¶
__xnano_render__(context: Context[DepsT, StateT]) -> None
Draw on context.screen and play on context.speaker, with the parameters given.
hook
¶
hook(function: Callable[..., object] | None = None, /, *, on: HookTrigger[object, object] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]
Call a function when something happens to a placement of this component.
The function receives the hook's Context and a
ComponentContext. The arguments are those of
hook on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Parameters:
-
function(Callable[..., object] | None, default:None) –The function to call, or
Noneto use this as a decorator. -
on(HookTrigger[object, object] | None, default:None) –When the hook runs: a kind of event, the name of a custom event, or a condition; see
HookTrigger. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds or beats.
-
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). Checked each time the hook is installed.
Returns:
-
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–A
ComponentHook, whoseremovetakes the -
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–hook off every placement; or, without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense; see
hook. -
TerminalError–requires_depsis true and the canvas was created withoutdeps.
Examples:
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
Source code in xnano/components.py
def hook(
self,
function: Callable[..., object] | None = None,
/,
*,
on: HookTrigger[object, object] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]:
"""
Call a function when something happens to a placement of this component.
The function receives the hook's [`Context`][xnano.hooks.Context] and a
[`ComponentContext`][xnano.components.ComponentContext]. The arguments are those of
``hook`` on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Args:
function: The function to call, or ``None`` to use this as a decorator.
on: When the hook runs: a kind of event, the name of a custom event, or a
condition; see [`HookTrigger`][xnano.hooks.HookTrigger].
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds or beats.
keys: The key or keys an ``on='key'`` hook reacts to.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``. Checked each time the hook is installed.
Returns:
A [`ComponentHook`][xnano.components.ComponentHook], whose ``remove`` takes the
hook off every placement; or, without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense; see
[`hook`][xnano.canvas.Canvas.hook].
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``.
Examples:
```python
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
```
"""
from xnano.hooks._handles import (
_check_hook_arguments,
_check_hook_function,
resolve_trigger,
)
from xnano.hooks._triggers import compile_when
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
_check_hook_arguments(
cast('_Hooked[object, object]', _PlacementLike()), kind, every, after, keys
)
compile_when(condition)
settings = _HookSettings(on, every, after, keys, requires_deps)
def attach(callback: Callable[..., object]) -> ComponentHook:
component_hook = ComponentHook(
self, _check_hook_function(callback, arguments=2), settings
)
self._hooks.append(component_hook)
try:
self._install_everywhere(component_hook)
except BaseException:
component_hook.remove()
raise
return component_hook
if function is None:
return attach
return attach(function)
RenderableFunction
¶
RenderableFunction(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], object])
Bases: _ComponentFunction[ParametersT, DepsT, StateT]
A function with a screen of its own: what renderable returns.
The function is the component. canvas.screen.write(function) runs it with its default
parameters, and canvas.screen.write(function(limit=0.9)) gives it its own parameters
first. Calling it does not run it; it makes a
RenderableComponent.
Attributes:
Keep the function. Use @xnano.writable, @xnano.renderable or @xnano.playable.
Methods:
-
__call__–Give the component its own parameters; the context is passed for you.
-
__xnano_render__–Draw on
context.screenand play oncontext.speaker, with the defaults. -
hook–Call a function when something happens to a placement of this component.
Source code in xnano/components.py
def __init__(
self,
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], object],
) -> None:
"""Keep the function. Use ``@xnano.writable``, ``@xnano.renderable`` or ``@xnano.playable``."""
super().__init__()
self._function = function
self._signature, self._takes_context = _own_signature(function, self._decorator)
functools.update_wrapper(self, function) # pyright: ignore[reportArgumentType]
arguments
property
¶
The parameters the component is written with: none, so the defaults apply.
__call__
¶
__call__(*arguments: args, **keywords: kwargs) -> RenderableComponent[DepsT, StateT]
Give the component its own parameters; the context is passed for you.
Source code in xnano/components.py
__xnano_render__
¶
__xnano_render__(context: Context[DepsT, StateT]) -> None
Draw on context.screen and play on context.speaker, with the defaults.
hook
¶
hook(function: Callable[..., object] | None = None, /, *, on: HookTrigger[object, object] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]
Call a function when something happens to a placement of this component.
The function receives the hook's Context and a
ComponentContext. The arguments are those of
hook on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Parameters:
-
function(Callable[..., object] | None, default:None) –The function to call, or
Noneto use this as a decorator. -
on(HookTrigger[object, object] | None, default:None) –When the hook runs: a kind of event, the name of a custom event, or a condition; see
HookTrigger. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds or beats.
-
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). Checked each time the hook is installed.
Returns:
-
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–A
ComponentHook, whoseremovetakes the -
ComponentHook | Callable[[Callable[..., object]], ComponentHook]–hook off every placement; or, without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense; see
hook. -
TerminalError–requires_depsis true and the canvas was created withoutdeps.
Examples:
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
Source code in xnano/components.py
def hook(
self,
function: Callable[..., object] | None = None,
/,
*,
on: HookTrigger[object, object] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
) -> ComponentHook | Callable[[Callable[..., object]], ComponentHook]:
"""
Call a function when something happens to a placement of this component.
The function receives the hook's [`Context`][xnano.hooks.Context] and a
[`ComponentContext`][xnano.components.ComponentContext]. The arguments are those of
``hook`` on a placement, and a mouse, scroll or drag hook hears only the pointer
inside the placement. Keys are not consumed: while nothing has focus, every key hook
hears a key. On a component function the hook is installed on every
placement of that function, those that exist now and those created later; on a
component made by calling it, only on its placements. A playable component has no
placement: its hook is installed on the canvas when the component is played.
Args:
function: The function to call, or ``None`` to use this as a decorator.
on: When the hook runs: a kind of event, the name of a custom event, or a
condition; see [`HookTrigger`][xnano.hooks.HookTrigger].
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds or beats.
keys: The key or keys an ``on='key'`` hook reacts to.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``. Checked each time the hook is installed.
Returns:
A [`ComponentHook`][xnano.components.ComponentHook], whose ``remove`` takes the
hook off every placement; or, without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense; see
[`hook`][xnano.canvas.Canvas.hook].
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``.
Examples:
```python
import xnano
from xnano_core import Event
@xnano.writable
def label(context: xnano.Context, text: str = 'x') -> str:
return text
with xnano.new(width=10, height=1) as canvas:
pressed = []
@label.hook(on='key', keys='a')
def heard(
context: xnano.Context,
component_context: xnano.components.ComponentContext,
) -> None:
pressed.append(component_context.arguments['text'])
canvas.screen.write(label(text='hi'))
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert pressed == ['hi']
```
"""
from xnano.hooks._handles import (
_check_hook_arguments,
_check_hook_function,
resolve_trigger,
)
from xnano.hooks._triggers import compile_when
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
_check_hook_arguments(
cast('_Hooked[object, object]', _PlacementLike()), kind, every, after, keys
)
compile_when(condition)
settings = _HookSettings(on, every, after, keys, requires_deps)
def attach(callback: Callable[..., object]) -> ComponentHook:
component_hook = ComponentHook(
self, _check_hook_function(callback, arguments=2), settings
)
self._hooks.append(component_hook)
try:
self._install_everywhere(component_hook)
except BaseException:
component_hook.remove()
raise
return component_hook
if function is None:
return attach
return attach(function)
writable
¶
writable(function: Callable[[], Writable]) -> WritableFunction[[], None, None]
writable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable]) -> WritableFunction[ParametersT, DepsT, StateT]
writable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable] | Callable[[], Writable]) -> WritableFunction[ParametersT, DepsT, StateT] | WritableFunction[[], None, None]
Turn a function into a component that draws itself.
The function takes the Context first, then its own parameters,
and returns anything canvas.screen.write accepts; a function with no parameters at all is
called without the context. The decorated object is the component:
canvas.screen.write(gauge) draws it with its defaults, canvas.screen.write(gauge(ratio=0.7)) gives
it parameters, and gauge.hook(...) adds behavior to its placements.
A component is evaluated once, and again only when it read something that changes: the
time or the event (every frame), the size of its buffer, the parent or the canvas (when
the screen is resized), a state path (when it changes), or an input such as
context.keyboard (when it arrives). What it reads is recorded as it runs. Reads of
context.deps and of mutable fields on self are not tracked: when they change, call
placement.refresh().
Parameters:
-
function(Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable] | Callable[[], Writable]) –The function
(context, **own_parameters) -> content.
Raises:
-
TypeError–The decorated object is a class or is not callable, or the function's first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
import xnano
@xnano.writable
def gauge(context: xnano.Context, ratio: float = 0.5) -> str:
return '#' * round(ratio * 10)
with xnano.new(width=12, height=1) as canvas:
canvas.screen.write(gauge(ratio=0.3))
assert canvas.screen.render().strip() == '###'
Source code in xnano/components.py
def writable( # pyright: ignore[reportGeneralTypeIssues]
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable]
| Callable[[], Writable],
/,
) -> WritableFunction[ParametersT, DepsT, StateT] | WritableFunction[[], None, None]:
"""
Turn a function into a component that draws itself.
The function takes the [`Context`][xnano.hooks.Context] first, then its own parameters,
and returns anything ``canvas.screen.write`` accepts; a function with no parameters at all is
called without the context. The decorated object is the component:
``canvas.screen.write(gauge)`` draws it with its defaults, ``canvas.screen.write(gauge(ratio=0.7))`` gives
it parameters, and ``gauge.hook(...)`` adds behavior to its placements.
A component is evaluated once, and again only when it read something that changes: the
time or the event (every frame), the size of its buffer, the parent or the canvas (when
the screen is resized), a state path (when it changes), or an input such as
``context.keyboard`` (when it arrives). What it reads is recorded as it runs. Reads of
``context.deps`` and of mutable fields on ``self`` are not tracked: when they change, call
[`placement.refresh()`][xnano.layout.Placement.refresh].
Args:
function: The function ``(context, **own_parameters) -> content``.
Raises:
TypeError: The decorated object is a class or is not callable, or the function's
first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
```python
import xnano
@xnano.writable
def gauge(context: xnano.Context, ratio: float = 0.5) -> str:
return '#' * round(ratio * 10)
with xnano.new(width=12, height=1) as canvas:
canvas.screen.write(gauge(ratio=0.3))
assert canvas.screen.render().strip() == '###'
```
"""
return WritableFunction(
cast(
'Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable]',
function,
)
)
renderable
¶
renderable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], None]) -> RenderableFunction[ParametersT, DepsT, StateT]
Turn a function into a component with a screen of its own, which draws and plays.
The function takes the Context first, then its own parameters,
and returns nothing. Its context.screen is its own: a screen where the component is
written, as large as what the function writes on it unless the component was written
with a width or a height. Its context.speaker, context.clock,
context.keyboard and context.mouse are the canvas's. Write it with
canvas.screen.write(meter), or canvas.screen.write(meter(limit=0.9)) to give it
parameters; meter.hook(...) adds behavior to where it is written.
The function runs once, and again only when it read something that changes, as a
writable does. Each run starts from an empty screen: what the run
before wrote is removed first, so the screen shows what the latest run wrote. What a run
plays starts when that run plays it.
Parameters:
-
function(Callable[Concatenate[Context[DepsT, StateT], ParametersT], None]) –The function
(context, **own_parameters) -> None.
Raises:
-
TypeError–The decorated object is a class or is not callable, or the function takes no parameters or its first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
import xnano
@xnano.renderable
def meter(context: xnano.Context, level: float = 0.5) -> None:
context.screen.write('level')
context.screen.write('#' * round(level * 10))
with xnano.new(width=12, height=3) as canvas:
placement = canvas.screen.write(meter(level=0.3), y=1)
assert canvas.screen.render().splitlines()[1:] == ['level', '###']
assert (placement.width, placement.height) == (5, 2)
Source code in xnano/components.py
def renderable( # pyright: ignore[reportGeneralTypeIssues]
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], None], /
) -> RenderableFunction[ParametersT, DepsT, StateT]:
"""
Turn a function into a component with a screen of its own, which draws and plays.
The function takes the [`Context`][xnano.hooks.Context] first, then its own parameters,
and returns nothing. Its ``context.screen`` is its own: a screen where the component is
written, as large as what the function writes on it unless the component was written
with a ``width`` or a ``height``. Its ``context.speaker``, ``context.clock``,
``context.keyboard`` and ``context.mouse`` are the canvas's. Write it with
``canvas.screen.write(meter)``, or ``canvas.screen.write(meter(limit=0.9))`` to give it
parameters; ``meter.hook(...)`` adds behavior to where it is written.
The function runs once, and again only when it read something that changes, as a
[`writable`][xnano.writable] does. Each run starts from an empty screen: what the run
before wrote is removed first, so the screen shows what the latest run wrote. What a run
plays starts when that run plays it.
Args:
function: The function ``(context, **own_parameters) -> None``.
Raises:
TypeError: The decorated object is a class or is not callable, or the function takes
no parameters or its first parameter is keyword-only or variadic, so it cannot
take the context.
Examples:
```python
import xnano
@xnano.renderable
def meter(context: xnano.Context, level: float = 0.5) -> None:
context.screen.write('level')
context.screen.write('#' * round(level * 10))
with xnano.new(width=12, height=3) as canvas:
placement = canvas.screen.write(meter(level=0.3), y=1)
assert canvas.screen.render().splitlines()[1:] == ['level', '###']
assert (placement.width, placement.height) == (5, 2)
```
"""
return RenderableFunction(function)
playable
¶
playable(function: Callable[[], Playable]) -> PlayableFunction[[], None, None]
playable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable]) -> PlayableFunction[ParametersT, DepsT, StateT]
playable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable] | Callable[[], Playable]) -> PlayableFunction[ParametersT, DepsT, StateT] | PlayableFunction[[], None, None]
Turn a function into a component that plays itself.
The function takes the Context first, then its own parameters,
and returns anything canvas.play accepts; a function with no parameters at all is
called without the context. It is evaluated once when played, and again
on a beat only when it read something that changes (the time or the beat, a state path or
an input), playing the new result each time. canvas.play returns a
PlayHandle whose remove() stops it.
Parameters:
-
function(Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable] | Callable[[], Playable]) –The function
(context, **own_parameters) -> playable.
Raises:
-
TypeError–The decorated object is a class or is not callable, or the function's first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
import xnano
@xnano.playable
def chord(context: xnano.Context, root: str = 'C4') -> xnano.Note:
return xnano.Note(root, beats=0.5)
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play(chord(root='E4'))
canvas.clock.step(delta_seconds=0.5)
assert canvas.speaker.render().peak > 0.0
Source code in xnano/components.py
def playable( # pyright: ignore[reportGeneralTypeIssues]
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable]
| Callable[[], Playable],
/,
) -> PlayableFunction[ParametersT, DepsT, StateT] | PlayableFunction[[], None, None]:
"""
Turn a function into a component that plays itself.
The function takes the [`Context`][xnano.hooks.Context] first, then its own parameters,
and returns anything ``canvas.play`` accepts; a function with no parameters at all is
called without the context. It is evaluated once when played, and again
on a beat only when it read something that changes (the time or the beat, a state path or
an input), playing the new result each time. ``canvas.play`` returns a
[`PlayHandle`][xnano.audio.PlayHandle] whose ``remove()`` stops it.
Args:
function: The function ``(context, **own_parameters) -> playable``.
Raises:
TypeError: The decorated object is a class or is not callable, or the function's
first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
```python
import xnano
@xnano.playable
def chord(context: xnano.Context, root: str = 'C4') -> xnano.Note:
return xnano.Note(root, beats=0.5)
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play(chord(root='E4'))
canvas.clock.step(delta_seconds=0.5)
assert canvas.speaker.render().peak > 0.0
```
"""
return PlayableFunction(
cast(
'Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable]',
function,
)
)