Handlers
A handler is created by calling new on a rule, or by VideState.handler or VideState.staticHandler without one. Each handler owns its own current state, sources, and cleanup. Handlers do not share state, so changing one does not affect another, and different handlers may use different state names.
The examples on this page use a handler made from a rule for a popup, like this:
const Vide = require("@packages/Vide")
const VideState = require("@VideState")
const schemas = VideState.schemas
const rules = VideState.rules
const PopupRule = rules.dynamic(schemas.new({
transparency = schemas.float({ min = 0, max = 1 }),
}), { name = "Popup" })
const handler = PopupRule.new({
Hidden = { transparency = Vide.source(1) },
Shown = { transparency = Vide.source(0) },
}, "Hidden")Handler without a rule
handler Added in 0.9.0
VideState.handler<States>(states: States, initialState: string): Handler<ValuesOfStates<States>>Creates a handler without a rule. The states are a table keyed by state name, where each state has one Vide source per field, as for a dynamic rule. The handler has every function on this page, and its sources, transitions, and events work the same way.
There is no schema, so nothing checks the values. The fields are the ones of the initial state, and the other states are compared with it once, when the handler is created. When something does not match, the handler still works, and one warning in the output lists every problem:
- A field holds a value that a transition cannot tween or switch, such as an
Instanceor a table. - A field holds a value of a different type in another state, so it switches at the start of a transition instead of tweening.
- A field cannot tween between two states, such as sequences with different keypoint counts.
- A state has no source for a field, so it uses the source of the initial state.
- A state has a field that the initial state does not have, so it is ignored.
Numbers, UDim, UDim2, Vector2, Color3, NumberRange, NumberSequence, and ColorSequence tween. Booleans, strings, enum items, and nil switch at the start of a transition, as they do for a rule. A state change reads the sources as they are, so a value written to a source later is never checked.
A handler without a rule has no allowed state changes and no tags. It appears as VideState.handler in the debug tools and in the errors of everyHandler, and everyHandler.withRule("VideState.handler") selects every handler without a rule.
const Vide = require("@packages/Vide")
const VideState = require("@VideState")
return function()
const handler = VideState.handler({
Idle = { transparency = Vide.source(0.4), size = Vide.source(UDim2.fromOffset(40, 40)) },
Hover = { transparency = Vide.source(0), size = Vide.source(UDim2.fromOffset(44, 44)) },
}, "Idle")
const animated = handler.animate({
tweenDefault = {
duration = 0.15,
},
})
return Vide.create "ImageButton" {
Size = animated.size,
ImageTransparency = animated.transparency,
MouseEnter = function()
handler.setState("Hover")
end,
MouseLeave = function()
handler.setState("Idle")
end,
}
endThe analyzer infers the type of each field from the sources, so handler.sources.transparency is a Source<number>. To write down what each state must hold, annotate the table with HandlerStates. The analyzer then reports a source of the wrong type, and with the state names, a state that is missing:
const Vide = require("@packages/Vide")
const VideState = require("@VideState")
type Look = { transparency: number, size: UDim2 }
const states: VideState.HandlerStates<Look, "Idle" | "Hover"> = {
Idle = { transparency = Vide.source(0.4), size = Vide.source(UDim2.fromOffset(40, 40)) },
Hover = { transparency = Vide.source(0), size = Vide.source(UDim2.fromOffset(44, 44)) },
}
const handler = VideState.handler(states, "Idle")Use a rule when the values must be checked, when several components share the same fields, or when you need allowedTransitions or tags.
staticHandler Added in 0.9.0
VideState.staticHandler<States>(states: States, initialState: string): Handler<StaticValuesOfStates<States>>Creates a handler without a rule whose states hold plain values instead of Vide sources, for a component whose looks never change while it exists. It is to handler what a static rule is to a dynamic one: the values are copied and frozen once, when the handler is created, and its sources follow the active state but raise an error when written to. handler.defaults is empty.
The states are compared with the initial state once, and one warning lists the same problems as for handler. A state that leaves out a field uses the initial state's value. A field that holds a function raises an error, because a static handler takes plain values, not Vide sources.
Handlers made from the same states table share one check, one warning, and one copy of the values when the table is frozen all the way down, as with a static rule. A table that is not frozen could change, so it is checked again for each handler.
const Vide = require("@packages/Vide")
const VideState = require("@VideState")
-- Frozen all the way down, so every tab shares one check.
const TAB_LOOKS = table.freeze({
Idle = table.freeze({ transparency = 0.6, size = UDim2.fromOffset(80, 32) }),
Selected = table.freeze({ transparency = 0, size = UDim2.fromOffset(88, 36) }),
})
return function(isSelected: () -> boolean)
const handler = VideState.staticHandler(TAB_LOOKS, "Idle")
handler.follow(isSelected, function(selected)
return if selected then "Selected" else "Idle"
end)
const animated = handler.animate({
tweenDefault = {
duration = 0.2,
},
})
return Vide.create "TextButton" {
Size = animated.size,
BackgroundTransparency = animated.transparency,
}
endThe analyzer infers the type of each field from the values, and widens a literal such as "Play" to string. To write down what each state must hold, annotate the table with StaticHandlerStates.
| Cause | Message | |
|---|---|---|
| Error | states is not a table | VideState.staticHandler states must be a table, got <type> |
| Error | A state is not a table | state "<name>" must be a table of values |
| Error | A field holds a function, such as a Vide source | state "<name>" field "<field>" is a function. VideState.staticHandler takes plain values, not Vide sources |
| Error | Fewer than two states | VideState.staticHandler requires at least 2 states |
| Error | The initial state is not one of the states | unknown initial state "<name>" |
| Error | A source is written to | cannot write to "<field>": the states of a static handler are fixed |
Properties
sources Added in 0.1.0
Handler.sources: Sources<T>A frozen record with one Vide source per field in the rule. Each source reads and writes the active state's source, so pass them to Vide properties to bind them. When the state changes, the bindings update automatically.
Writing to a source updates the source of the active state. To change another state's values before switching to it, write to that state's own source. The sources of a handler made from a static rule cannot be written to, and writing raises an error.
defaults Added in 0.8.0
Handler.defaults: DefaultSources<T>A frozen record with the one Vide source that holds the default of each field that has a withDefault and that at least one state leaves out. Every state that leaves the field out uses this source, so writing to it changes the default for all of them. A field whose default no state needs has no entry, and neither has a field without a default.
Each handler has its own, so writing to one handler's default never changes another handler. A write changes the value at once, and it does not start a transition. A transition tweens when the state changes, so it reads the new default the next time a state change starts.
const VideState = require("@VideState")
const Vide = require("@packages/Vide")
const schemas = VideState.schemas
const rules = VideState.rules
const PanelRule = rules.dynamic(schemas.new({
alpha = schemas.withDefault(schemas.float({ min = 0, max = 1 }), 1),
visible = schemas.boolean(),
}), { name = "Panel" })
const handler = PanelRule.new({
Idle = { visible = Vide.source(true) },
Hidden = { visible = Vide.source(false) },
}, "Idle")
-- An entry exists only when a state leaves the field out, so its type is optional.
const alphaDefault = handler.defaults.alpha
if alphaDefault then
alphaDefault(0.8) -- Idle and Hidden both read 0.8 now
endFunctions
currentState Added in 0.1.0
Handler.currentState() -> stringReturns the name of the active state. It is a function, so call it to read the name.
Returns
| Type | Description |
|---|---|
string | The name of the active state. |
setState Added in 0.1.0 Changed in 0.8.0
Handler.setState(
stateName: string, -- The state to switch to
options: SetStateOptions? -- Options for this call only
) -> ()Switches to a state. Later reads and writes of sources use that state's sources, and onChange and onTransition listeners are called.
With instant = true, the change is not animated. Every onTransition connection receives one frame with the next state's values and an alpha of 1 before setState returns, and onFinish runs. Use it to set the first layout of a component, or to snap it back without an animation.
Parameters
| Name | Type | Description |
|---|---|---|
stateName | string | The name of a state passed to new. |
options | SetStateOptions? | Optional. Options for this call only. |
Errors
| Cause | Message | |
|---|---|---|
| Error | The handler was destroyed | setState cannot be called after destroy |
| Error | options is not a table | setState options must be a table |
| Error | options has an unknown key | setState options has an unknown key <key> |
| Error | options.instant is not a boolean | setState instant must be a boolean |
| Error | options.delay is not a finite non-negative number | setState delay must be a finite non-negative number |
| Error | stateName is not a string | state name must be a string, got <type> |
| Error | The state name is unknown | unknown state "<state>" |
| Error | The rule's allowedTransitions do not let the active state change to it | cannot change state from "<state>" to "<state>". Allowed: "<state>", ... |
| Error | The values of the state it changes to no longer match the schema. The state it leaves is not checked again. | Invalid state "<state>": followed by the schema issues |
A failed setState leaves the handler unchanged.
onChange Added in 0.1.0
Handler.onChange(
callback: (
from: T, -- A frozen copy of the previous state's values
to: T -- A frozen copy of the next state's values
) -> ()
) -> DisconnectRuns callback once each time the state changes. A listener only receives changes made after it is registered.
Parameters
| Name | Type | Description |
|---|---|---|
callback | (from: T, to: T) -> () | Called with the values of the previous and the next state. |
Returns
| Type | Description |
|---|---|
Disconnect | Call it to stop receiving changes. |
onEnter Added in 0.2.0
Handler.onEnter(
stateName: string, -- The state to listen for
callback: (
previousState: string -- The state the handler left
) -> ()
) -> DisconnectRuns callback each time the handler switches into stateName. It does not run for the initial state, or when setState is called with the state that is already active.
On a state change, the listeners run in this order: onExit of the old state, onEnter of the new state, onChange, then the onTransition connections.
Parameters
| Name | Type | Description |
|---|---|---|
stateName | string | The name of a state passed to new. |
callback | OnEnterCallback | Called with the name of the state the handler left. |
Returns
| Type | Description |
|---|---|
Disconnect | Call it to stop listening. |
Errors
| Cause | Message | |
|---|---|---|
| Error | stateName is not a string | onEnter state name must be a string, got <type> |
| Error | stateName is not a state of the handler | onEnter state "<state>" is not a state of this handler |
| Error | callback is not a function | onEnter callback must be a function |
onExit Added in 0.2.0
Handler.onExit(
stateName: string, -- The state to listen for
callback: (
nextState: string -- The state the handler enters
) -> ()
) -> DisconnectRuns callback each time the handler switches out of stateName, before any onEnter listener of the next state.
Parameters
| Name | Type | Description |
|---|---|---|
stateName | string | The name of a state passed to new. |
callback | OnExitCallback | Called with the name of the state the handler enters. |
Returns
| Type | Description |
|---|---|
Disconnect | Call it to stop listening. |
Errors
| Cause | Message | |
|---|---|---|
| Error | stateName is not a string | onExit state name must be a string, got <type> |
| Error | stateName is not a state of the handler | onExit state "<state>" is not a state of this handler |
| Error | callback is not a function | onExit callback must be a function |
onTransition Added in 0.1.0 Changed in 0.5.0
Handler.onTransition(
callback: (
from: T, -- The previous state's values
to: T, -- The next state's values
current: T, -- The values to render on this frame
alpha: number, -- The eased progress, from 0 to 1
round: number -- The round of the sequence that started the transition, or 0
) -> (),
options: TransitionOptions? -- Tween settings for this connection only
) -> DisconnectRuns callback with a current value that moves from the previous state to the next one, and the alpha that shows how far along it is. Each animatable field is tweened. Fields that cannot be tweened, such as strings, booleans, and enums, are not transitioned: they switch to their next value at the start of the transition. Each connection has its own tween. Its settings come from the tweenDefault of options, and any setting it leaves out takes the built-in default. See Transitions for the full behavior.
Parameters
| Name | Type | Description |
|---|---|---|
callback | (from: T, to: T, current: T, alpha: number, round: number) -> () | Called at the start of a transition and on every frame until the transition ends. |
options | TransitionOptions? | Optional. The tween settings of this connection, inside tweenDefault, and tweenOverrides for particular state changes. Each setting left out takes the built-in default. |
Returns
| Type | Description |
|---|---|
Disconnect | Call it to stop receiving updates. |
Errors
| Cause | Message | |
|---|---|---|
| Error | callback is not a function | onTransition callback must be a function |
| Error | options is invalid | See TransitionOptions, such as onTransition easing must be a known easing name |
animate Added in 0.4.0
Handler.animate(
options: TransitionOptions? -- Tween settings for this connection only
) -> (Sources<T>, Disconnect)Returns a Vide source for every field, and the sources follow the transition. It is onTransition in the form Vide expects: onTransition pushes each frame into a callback that you write, while animate gives you sources to bind to properties, so Vide updates them for you. Both are the same transition underneath, with the same tween, the same options, and the same behavior for non-animatable fields. They differ only in how you receive the value.
const Vide = require("@packages/Vide")
-- The popup fades over 0.2 seconds when its state changes.
const animated = handler.animate({
tweenDefault = {
duration = 0.2,
easing = "quadOut",
},
})
Vide.create "Frame" {
BackgroundTransparency = animated.transparency,
}The sources start at the values of the current state. They are separate from sources, which switch to the next state at once and are not animated, and writing to them does nothing to the handler. Every call opens its own connection with its own tween, so call it once for each animation you need, not once for each property. Pause, scaleSpeed, and finish act on it like on any other connection. After destroy the sources keep their last value.
Parameters
| Name | Type | Description |
|---|---|---|
options | TransitionOptions? | Optional. The tween settings of this connection, inside tweenDefault, and tweenOverrides for particular state changes. Each setting left out takes the built-in default. |
Returns
| Type | Description |
|---|---|
Sources<T> | One animated source for each field, with the same keys as the handler's sources. |
Disconnect | Call it to stop the sources from following. They keep their last value. |
Errors
| Cause | Message | |
|---|---|---|
| Error | options is invalid | The same messages as onTransition, such as onTransition easing must be a known easing name |
progress Added in 0.5.0
Handler.progress(
options: TransitionOptions? -- Tween settings for this connection
) -> (Source<number>, Disconnect)Returns a Vide source that holds the progress of the transition, so a progress bar or a ring can bind to it without a callback. It is onTransition in the form Vide expects, like animate, but it follows only the alpha. The source is 1 when no transition is running, goes from 0 to 1 during each state change, and stays at 1 when the transition ends.
const Vide = require("@packages/Vide")
-- A bar that fills over 2 seconds each time the state changes.
const progress = handler.progress({
tweenDefault = {
duration = 2,
},
})
Vide.create "Frame" {
Size = function()
return UDim2.fromScale(progress(), 1)
end,
}It is a thin layer over one onTransition connection, so it takes the same options and has its own tween. An easing that overshoots, such as back, takes the alpha below 0 or above 1 in between, so clamp it with math.clamp(progress(), 0, 1) when a bar must stay inside its frame. finish, pause, and scaleSpeed act on it like on any other connection. After destroy the source keeps its last value.
Parameters
| Name | Type | Description |
|---|---|---|
options | TransitionOptions? | Optional. The tween settings of this connection, inside tweenDefault, and tweenOverrides for particular state changes. Each setting left out takes the built-in default. |
Returns
| Type | Description |
|---|---|
Source<number> | The progress of the transition, from 0 to 1. |
Disconnect | Call it to stop the source from following. It keeps its last value. |
Errors
| Cause | Message | |
|---|---|---|
| Error | options is invalid | The same messages as onTransition |
playSequence Added in 0.5.0
Handler.playSequence(
steps: { SequenceStep }, -- The states to play, in order
options: SequenceOptions? -- Options for this sequence
) -> (Source<number>, Disconnect)Changes the state step by step. Each step calls setState, waits until its transition has finished, then waits for the step's hold before the next one. Use it for a notification that slides in, stays, and slides out, or a button that flashes and settles.
-- The popup appears, stays for 3 seconds, and disappears.
handler.playSequence({
{ state = "Shown", hold = 3 },
{ state = "Hidden" },
})The first step starts before playSequence returns. The sequence ends after the last step's transition, or goes on from the first step again with loop. One pass over the steps is a round.
-- Flashes three times, then stops. It plays Shown and Hidden in turn, three rounds in total.
local round = handler.playSequence({
{ state = "Shown", hold = 0.2 },
{ state = "Hidden", hold = 0.2 },
}, {
loop = 3,
onLoop = function(rounds)
print("rounds completed:", rounds)
end,
})The returned source holds the round that is being played, counted from 1, so a label or a bar can bind to it. It stays at the last round when the sequence ends or is stopped. onTransition callbacks also receive the round of the sequence that started their transition, in their fifth argument.
- Anything else that changes the state stops it. A
setStatefrom your code, or a sequence started later, ends the running one, so a sequence never fights your own state changes. A newerplaySequencereplaces the running one. - A hold is scaled time.
pauseholds it, andscaleSpeedshortens it. The hold after the last step only counts when another round follows. loopcounts the rounds.loop = trueplays until the sequence is stopped, and a whole number plays the steps that many times in total, soloop = 3is three rounds andloop = 1is the same as no loop.onLoopruns at the end of every round, including the last one, with the number of rounds completed. It must not yield, because the sequence waits for it. A stopped sequence does not call it.- Between rounds the sequence waits one frame, so a loop of instant steps cannot hold up the game.
- A step that is already the current state has no transition, so it goes straight to its hold.
- Reduced motion makes each step instant, but the holds still apply.
- The states are checked first. Every state must exist, and the rule's
allowedTransitionsmust allow each change from one step to the next. With more than one round, they must also allow the change from the last step back to the first. If not,playSequenceraises an error before anything changes. finishends the step's transition at once, and the sequence moves on to the hold.destroystops the sequence. A step that raises an error ends it, and the error is reported in the output.
Parameters
| Name | Type | Description |
|---|---|---|
steps | { SequenceStep } | The states to play, in order. Must have at least one step. |
options | SequenceOptions? | Optional. Options for this sequence. |
Returns
| Type | Description |
|---|---|
Source<number> | The round that is being played, counted from 1. |
Disconnect | Call it to stop the sequence. The handler keeps the state it is in. |
Errors
| Cause | Message | |
|---|---|---|
| Error | The handler was destroyed | playSequence cannot be called after destroy |
| Error | steps is not a list, or is empty | playSequence steps must be a non-empty list of steps |
| Error | A step is not a table | playSequence step <n> must be a table |
| Error | A step has an unknown key | playSequence step <n> has an unknown key <key> |
| Error | A step has no state name | playSequence step <n> needs a state name |
| Error | A step's state is not a state of the handler | playSequence step <n> has an unknown state "<state>" |
| Error | A step's hold or delay is not a finite non-negative number | playSequence step <n> hold must be a finite non-negative number, and the same for delay |
| Error | A step's instant is not a boolean | playSequence step <n> instant must be a boolean |
| Error | The rule does not allow a change between two steps | playSequence step <n> cannot change state from "<state>" to "<state>". Allowed: "<state>", ... |
| Error | With loop, the rule does not allow the change from the last step to the first | playSequence cannot loop: cannot change state from "<state>" to "<state>". Allowed: "<state>", ... |
| Error | options is not a table, or has an unknown key | playSequence options must be a table, playSequence options has an unknown key <key> |
| Error | options.loop is not a boolean or a whole number of at least 1 | playSequence loop must be a boolean or a whole number of rounds, at least 1 |
| Error | options.onLoop is not a function | playSequence onLoop must be a function |
follow Added in 0.9.0
Handler.follow<V>(
source: () -> V, -- The value to follow, such as a Vide source
toState: ((value: V) -> string?)? -- Maps each value to a state name
) -> DisconnectMakes the state follow a source. Each time the source changes, the handler changes to the state that toState returns for its value. Without toState, the source holds the state name itself. Use it in place of an effect that calls setState, when the state is worked out from other state, such as whether a button is hovered or pressed.
const isOpen = Vide.source(false)
-- The popup is shown while isOpen is true.
handler.follow(isOpen, function(open)
return if open then "Shown" else "Hidden"
end)
isOpen(true) -- The popup changes to Shown, with its transition.- The first value is applied at once.
followreads the source before it returns, and changes to that state instantly, as if it were the initial state. Every later change is a normalsetState, with its transition. nilkeeps the current state. AtoStatethat returnsnilfor a value changes nothing.toStateis tracked. A source it reads also makes the handler change state when it changes. The listeners of the change, such asonEnter, are not tracked.- A handler follows one source at a time. A newer
followstops the one before. - It stops when you call the returned function, when the handler is destroyed, or, when
followis called inside a Vide scope such as a component, when that scope is cleaned up. - A
setStatefrom your code or aplaySequencestill works while the handler follows a source, and the next change of the source sets the state again.
Parameters
| Name | Type | Description |
|---|---|---|
source | () -> V | The value to follow, usually a Vide source or a derived source. |
toState | ((value: V) -> string?)? | Optional. Returns the state for a value, or nil to keep the current state. Without it, the source must hold a state name. |
Returns
| Type | Description |
|---|---|
Disconnect | Call it to stop following. The handler keeps the state it is in. |
Errors
A problem with the first value is raised by follow, and the handler does not follow the source. A problem with a later value is raised where the source was changed.
| Cause | Message | |
|---|---|---|
| Error | source is not a function | follow source must be a function |
| Error | toState is not a function | follow toState must be a function |
| Error | The state name is not a string | follow expected a state name or nil, got <type> |
| Error | The state is not a state of the handler | follow has an unknown state "<state>" |
| Error | The rule does not allow the change | follow cannot change state from "<state>" to "<state>". Allowed: "<state>", ... |
After destroy, follow does nothing and returns a function that does nothing.
pause Added in 0.2.0
Handler.pause() -> ()Pauses every transition of the handler at once, across all of its onTransition connections. Each transition keeps its current values and its listeners are not called again until resume. Calling it while the handler is already paused does nothing.
A transition that starts while the handler is paused sends its first frame, then waits for resume. See Pausing for how this differs from a speed of 0.
resume Added in 0.2.0
Handler.resume() -> ()Continues the transitions that pause stopped, from the values they had reached. Calling it while the handler is not paused does nothing.
onPause Added in 0.2.0
Handler.onPause(
callback: (
startedAt: number -- The os.clock() time at which the most recent transition started
) -> ()
) -> DisconnectRuns callback each time the handler goes from running to paused. A repeated pause call does not run it again.
Parameters
| Name | Type | Description |
|---|---|---|
callback | OnPauseCallback | Called with the os.clock() time at which the most recent transition started. If no transition has started yet, it is the time of the pause call. |
Returns
| Type | Description |
|---|---|
Disconnect | Call it to stop receiving pause events. |
Errors
| Cause | Message | |
|---|---|---|
| Error | callback is not a function | onPause callback must be a function |
onResume Added in 0.2.0
Handler.onResume(
callback: (
startedAt: number -- The os.clock() time at which the most recent transition started
) -> ()
) -> DisconnectRuns callback each time the handler goes from paused to running. A repeated resume call does not run it again.
Parameters
| Name | Type | Description |
|---|---|---|
callback | OnResumeCallback | Called with the os.clock() time at which the most recent transition started. |
Returns
| Type | Description |
|---|---|
Disconnect | Call it to stop receiving resume events. |
Errors
| Cause | Message | |
|---|---|---|
| Error | callback is not a function | onResume callback must be a function |
scaleSpeed Changed in 0.3.0
To scale every handler at once, use everyHandler.scaleSpeed.
Handler.scaleSpeed(
options: ScaleSpeedOptions -- How much to scale the speed of the running transition
) -> ()Speeds up or slows down the transitions of the handler. It affects every onTransition connection of the handler, and it multiplies each connection's own speed. A connection with a speed of 0.5 scaled by 4 plays at 2, and scaled by 0.5 plays at 0.25.
By default the scale stays for every following transition, until you call scaleSpeed again. A speed of 1 removes it. With once = true the scale applies only to the running transition, and the next setState starts a transition at normal speed again. A kept scale and a once scale multiply.
To jump straight to the end, use finish.
Parameters
| Name | Type | Description |
|---|---|---|
options | ScaleSpeedOptions | Required. The speed scale. |
Errors
| Cause | Message | |
|---|---|---|
| Error | options is not a table | scaleSpeed options must be a table |
| Error | options has an unknown key | scaleSpeed options has an unknown key <key> |
| Error | options.speed is not a finite number above 0 | scaleSpeed speed must be a finite number above 0 |
| Error | options.once is not a boolean | scaleSpeed once must be a boolean |
finish Added in 0.2.0
Handler.finish() -> ()Ends every running transition at once. Each connection receives its last frame, with current equal to the next state's values and an alpha of 1, before finish returns. Then onFinish runs. It works while the handler is paused. It does nothing when no transition is running.
onFinish Added in 0.2.0
Handler.onFinish(
callback: (
startedAt: number -- The os.clock() time at which the transition started
) -> ()
) -> DisconnectRuns callback once per transition, when every connection that was playing it has ended and at least one of them reached its end. This includes a transition that finish ended. A transition that another setState replaces does not finish. A transition with no onTransition connection does not run, so it does not finish either.
Parameters
| Name | Type | Description |
|---|---|---|
callback | OnFinishCallback | Called with the os.clock() time at which the transition started. |
Returns
| Type | Description |
|---|---|
Disconnect | Call it to stop receiving finish events. |
Errors
| Cause | Message | |
|---|---|---|
| Error | callback is not a function | onFinish callback must be a function |
waitForFinish Yields Added in 0.2.0
Handler.waitForFinish() -> ()Yields the calling thread until the handler has no running transition, then returns. It returns at once when nothing is running. Use it in sequential code instead of an onFinish connection.
The wait ends when the transition reaches its end, when finish ends it, or when every onTransition connection has disconnected. If a newer setState replaces the transition, the wait goes on until the newer one ends. While the handler is paused, it keeps waiting.
destroy Added in 0.2.0 Changed in 0.9.0
Handler.destroy() -> ()Stops the handler for good. Every running transition stops without sending another frame, and onFinish does not run. Every listener is removed, including onChange, onEnter, onExit, onTransition, onPause, onResume, and onFinish. Threads waiting in waitForFinish continue.
Afterwards, setState raises an error, and pause, resume, and finish do nothing. sources and currentState can still be read. Calling destroy again does nothing.
A handler made inside a Vide scope, such as a component or a Vide.root, is destroyed when that scope is cleaned up, so a component's handler needs no cleanup of its own. To keep a handler after the component that made it is gone, make it outside any scope, such as at the top of a module.
Handlers made inside an effect
An effect, a Vide.derive, and a property bound to a function are scopes that run again whenever a source they read changes. A handler made inside one is destroyed each time it runs again, and a new one is made in its place. The new handler starts in its initial state, its listeners and animate sources are new, and anything that still holds the old handler finds it destroyed. Make the handler in the body of the component, which runs once, and read sources in the effect instead.
const Vide = require("@packages/Vide")
const VideState = require("@VideState")
const schemas = VideState.schemas
const rules = VideState.rules
const PopupRule = rules.dynamic(schemas.new({
transparency = schemas.float({ min = 0, max = 1 }),
}), { name = "Popup" })
return function(isOpen: () -> boolean)
-- Made inside the component, so it is destroyed when the component is.
const handler = PopupRule.new({
Hidden = { transparency = Vide.source(1) },
Shown = { transparency = Vide.source(0) },
}, "Hidden")
handler.follow(isOpen, function(open)
return if open then "Shown" else "Hidden"
end)
return Vide.create("Frame")({
BackgroundTransparency = handler.sources.transparency,
})
endTypes
Handler Added in 0.1.0 Changed in 0.9.0
type Handler<T> = {
sources: Sources<T>,
defaults: DefaultSources<T>,
currentState: () -> string,
setState: (stateName: string, options: SetStateOptions?) -> (),
onChange: (callback: OnChangeCallback<T>) -> Disconnect,
onEnter: (stateName: string, callback: OnEnterCallback) -> Disconnect,
onExit: (stateName: string, callback: OnExitCallback) -> Disconnect,
onTransition: (callback: OnTransitionCallback<T>, options: TransitionOptions?) -> Disconnect,
animate: (options: TransitionOptions?) -> (Sources<T>, Disconnect),
progress: (options: TransitionOptions?) -> (Source<number>, Disconnect),
playSequence: (steps: { SequenceStep }, options: SequenceOptions?) -> (Source<number>, Disconnect),
follow: <V>(source: () -> V, toState: ((value: V) -> string?)?) -> Disconnect,
pause: () -> (),
resume: () -> (),
onPause: (callback: OnPauseCallback) -> Disconnect,
onResume: (callback: OnResumeCallback) -> Disconnect,
scaleSpeed: (options: ScaleSpeedOptions) -> (),
finish: () -> (),
onFinish: (callback: OnFinishCallback) -> Disconnect,
waitForFinish: () -> (),
destroy: () -> (),
}The type of a handler. Pass it the value type from InferRule so the handler matches its rule.
| Name | Type | Description |
|---|---|---|
T | InferRule<typeof(rule)> | The value type of the rule that created the handler. For a handler without a rule, the record of values, such as { transparency: number }. |
HandlerStates Added in 0.9.0
type HandlerStates<T, Names = string> = -- A table of states, keyed by name, where each state has a Source for every field of TThe states of a handler without a rule, for annotating the table you pass to VideState.handler. The analyzer then reports a source that holds the wrong type, and with Names a state that is missing.
| Name | Type | Description |
|---|---|---|
T | { [string]: any } | The value record, such as { transparency: number }. Each field becomes a Source of that field's type. |
Names | string, or a string literal or a union of them | The state names. With literals, every one of those states is required. Defaults to string. |
ValuesOfStates Added in 0.9.0
type ValuesOfStates<States> = -- The value record that a table of states made of Vide sources holdsThe value type that VideState.handler infers from its states. A state of { transparency = Vide.source(0) } gives { transparency: number }.
| Name | Type | Description |
|---|---|---|
States | A table of states | The table passed to VideState.handler. |
StaticHandlerStates Added in 0.9.0
type StaticHandlerStates<T, Names = string> = -- A table of states, keyed by name, where each state has a value for every field of TThe states of a static handler, for annotating the table you pass to VideState.staticHandler. The analyzer then reports a value of the wrong type, and with Names a state that is missing.
| Name | Type | Description |
|---|---|---|
T | { [string]: any } | The value record, such as { transparency: number }. |
Names | string, or a string literal or a union of them | The state names. With literals, every one of those states is required. Defaults to string. |
StaticValuesOfStates Added in 0.9.0
type StaticValuesOfStates<States> = -- The value record that a table of states made of plain values holdsThe value type that VideState.staticHandler infers from its states. A state of { transparency = 0, label = "Play" } gives { transparency: number, label: string }.
| Name | Type | Description |
|---|---|---|
States | A table of states | The table passed to VideState.staticHandler. |
DefaultSources Added in 0.8.0
type DefaultSources<T> = -- A record of Vide sources, each optional, one per field of T that can have a default| Name | Type | Description |
|---|---|---|
T | { [string]: any } | The value record. Each field becomes an optional Source of that field's type. |
Sources Added in 0.1.0
type Sources<T> = -- A record of Vide sources, one per field of T| Name | Type | Description |
|---|---|---|
T | { [string]: any } | The value record. Each field becomes a Source of that field's type. |
OnChangeCallback Added in 0.1.0
type OnChangeCallback<T> = (from: T, to: T) -> ()OnEnterCallback Added in 0.2.0
type OnEnterCallback = (previousState: string) -> ()| Name | Type | Description |
|---|---|---|
previousState | string | The name of the state the handler left. |
OnExitCallback Added in 0.2.0
type OnExitCallback = (nextState: string) -> ()| Name | Type | Description |
|---|---|---|
nextState | string | The name of the state the handler enters. |
OnTransitionCallback Added in 0.1.0 Changed in 0.5.0
type OnTransitionCallback<T> = (from: T, to: T, current: T, alpha: number, round: number) -> ()| Name | Type | Description |
|---|---|---|
from | T | The previous state's values. |
to | T | The next state's values. |
current | T | The values to render on this frame. |
alpha | number | The eased progress, from 0 to 1. With back and elastic easings it can go below 0 or above 1. See alpha. |
round | number | The round of the playSequence that started the transition, counted from 1. 0 when no sequence started it. |
OnPauseCallback Added in 0.2.0
type OnPauseCallback = (startedAt: number) -> ()| Name | Type | Description |
|---|---|---|
startedAt | number | The os.clock() time at which the handler's most recent transition started. If no transition has started yet, it is the time of the pause call. |
OnResumeCallback Added in 0.2.0
type OnResumeCallback = (startedAt: number) -> ()| Name | Type | Description |
|---|---|---|
startedAt | number | The os.clock() time at which the handler's most recent transition started. |
OnFinishCallback Added in 0.2.0
type OnFinishCallback = (startedAt: number) -> ()| Name | Type | Description |
|---|---|---|
startedAt | number | The os.clock() time at which the transition that finished started. |
SetStateOptions Added in 0.2.0 Changed in 0.5.0
type SetStateOptions = {
instant: boolean?, -- Skips the animation of this change
delay: number?, -- Seconds every connection waits before it starts
}| Field | Type | Required | Default | Description |
|---|---|---|---|---|
instant | boolean | No | false | When true, every onTransition connection receives the next state's values at once, with an alpha of 1. |
delay | number | No | 0 | Seconds every connection of this change waits before its first frame, added to the connection's own delay. It is scaled time, so pause holds it. An instant change ignores it. Must be finite and non-negative. |
SequenceStep Added in 0.5.0
type SequenceStep = {
state: string, -- The state to change to
hold: number?, -- Seconds to wait after the transition has finished
instant: boolean?, -- Skips the animation of this step
delay: number?, -- Seconds every connection waits before this step starts
}One step of playSequence.
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
state | string | Yes | The state to change to. It must be a state of the handler. | |
hold | number | No | 0 | Seconds to wait after the step's transition has finished, before the next step. It is scaled time, so pause holds it. Must be finite and non-negative. |
instant | boolean | No | false | The same as in SetStateOptions. |
delay | number | No | 0 | The same as in SetStateOptions. |
SequenceOptions Added in 0.5.0
type SequenceOptions = {
loop: (boolean | number)?, -- How many rounds to play
onLoop: ((round: number) -> ())?, -- Called at the end of every round
}The options of playSequence.
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
loop | boolean or number | No | false | How many times the steps play. true plays them until the sequence is stopped, a whole number of at least 1 plays them that many times in total, and false plays them once. |
onLoop | (round: number) -> () | No | Called when a round ends, with how many rounds have been completed, including after the last round. It must not yield. |
ScaleSpeedOptions Changed in 0.3.0
type ScaleSpeedOptions = {
speed: number, -- How many times the speed of the running transition is multiplied
once: boolean?, -- Apply the scale only to the running transition, and not to the next ones
}| Field | Type | Required | Default | Description |
|---|---|---|---|---|
speed | number | Yes | None | The speed scale. Must be a finite number above 0. Above 1 plays faster, 1 is normal speed, and below 1 plays slower. |
once | boolean | No | false | When true, the scale applies only to the running transition. When false, it stays for every following transition. |
Disconnect Added in 0.1.0
type Disconnect = () -> ()Removes the listener it was returned for. Calling it more than once has no effect.