Skip to content

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:

luau
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 ​

luau
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 Instance or 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.

luau
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,
    }
end

The 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:

luau
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 ​

luau
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.

luau
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,
    }
end

The 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.

CauseMessage
Errorstates is not a tableVideState.staticHandler states must be a table, got <type>
ErrorA state is not a tablestate "<name>" must be a table of values
ErrorA field holds a function, such as a Vide sourcestate "<name>" field "<field>" is a function. VideState.staticHandler takes plain values, not Vide sources
ErrorFewer than two statesVideState.staticHandler requires at least 2 states
ErrorThe initial state is not one of the statesunknown initial state "<name>"
ErrorA source is written tocannot write to "<field>": the states of a static handler are fixed

Properties ​

sources Added in 0.1.0 ​

luau
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 ​

luau
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.

luau
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
end

Functions ​

currentState Added in 0.1.0 ​

luau
Handler.currentState() -> string

Returns the name of the active state. It is a function, so call it to read the name.

Returns

TypeDescription
stringThe name of the active state.

setState Added in 0.1.0 Changed in 0.8.0 ​

luau
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

NameTypeDescription
stateNamestringThe name of a state passed to new.
optionsSetStateOptions?Optional. Options for this call only.

Errors

CauseMessage
ErrorThe handler was destroyedsetState cannot be called after destroy
Erroroptions is not a tablesetState options must be a table
Erroroptions has an unknown keysetState options has an unknown key <key>
Erroroptions.instant is not a booleansetState instant must be a boolean
Erroroptions.delay is not a finite non-negative numbersetState delay must be a finite non-negative number
ErrorstateName is not a stringstate name must be a string, got <type>
ErrorThe state name is unknownunknown state "<state>"
ErrorThe rule's allowedTransitions do not let the active state change to itcannot change state from "<state>" to "<state>". Allowed: "<state>", ...
ErrorThe 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 ​

luau
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
    ) -> ()
) -> Disconnect

Runs callback once each time the state changes. A listener only receives changes made after it is registered.

Parameters

NameTypeDescription
callback(from: T, to: T) -> ()Called with the values of the previous and the next state.

Returns

TypeDescription
DisconnectCall it to stop receiving changes.

onEnter Added in 0.2.0 ​

luau
Handler.onEnter(
    stateName: string, -- The state to listen for
    callback: (
        previousState: string -- The state the handler left
    ) -> ()
) -> Disconnect

Runs 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

NameTypeDescription
stateNamestringThe name of a state passed to new.
callbackOnEnterCallbackCalled with the name of the state the handler left.

Returns

TypeDescription
DisconnectCall it to stop listening.

Errors

CauseMessage
ErrorstateName is not a stringonEnter state name must be a string, got <type>
ErrorstateName is not a state of the handleronEnter state "<state>" is not a state of this handler
Errorcallback is not a functiononEnter callback must be a function

onExit Added in 0.2.0 ​

luau
Handler.onExit(
    stateName: string, -- The state to listen for
    callback: (
        nextState: string -- The state the handler enters
    ) -> ()
) -> Disconnect

Runs callback each time the handler switches out of stateName, before any onEnter listener of the next state.

Parameters

NameTypeDescription
stateNamestringThe name of a state passed to new.
callbackOnExitCallbackCalled with the name of the state the handler enters.

Returns

TypeDescription
DisconnectCall it to stop listening.

Errors

CauseMessage
ErrorstateName is not a stringonExit state name must be a string, got <type>
ErrorstateName is not a state of the handleronExit state "<state>" is not a state of this handler
Errorcallback is not a functiononExit callback must be a function

onTransition Added in 0.1.0 Changed in 0.5.0 ​

luau
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
) -> Disconnect

Runs 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

NameTypeDescription
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.
optionsTransitionOptions?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

TypeDescription
DisconnectCall it to stop receiving updates.

Errors

CauseMessage
Errorcallback is not a functiononTransition callback must be a function
Erroroptions is invalidSee TransitionOptions, such as onTransition easing must be a known easing name

animate Added in 0.4.0 ​

luau
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.

luau
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

NameTypeDescription
optionsTransitionOptions?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

TypeDescription
Sources<T>One animated source for each field, with the same keys as the handler's sources.
DisconnectCall it to stop the sources from following. They keep their last value.

Errors

CauseMessage
Erroroptions is invalidThe same messages as onTransition, such as onTransition easing must be a known easing name

progress Added in 0.5.0 ​

luau
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.

luau
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

NameTypeDescription
optionsTransitionOptions?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

TypeDescription
Source<number>The progress of the transition, from 0 to 1.
DisconnectCall it to stop the source from following. It keeps its last value.

Errors

CauseMessage
Erroroptions is invalidThe same messages as onTransition

playSequence Added in 0.5.0 ​

luau
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.

luau
-- 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.

luau
-- 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 setState from your code, or a sequence started later, ends the running one, so a sequence never fights your own state changes. A newer playSequence replaces the running one.
  • A hold is scaled time. pause holds it, and scaleSpeed shortens it. The hold after the last step only counts when another round follows.
  • loop counts the rounds. loop = true plays until the sequence is stopped, and a whole number plays the steps that many times in total, so loop = 3 is three rounds and loop = 1 is the same as no loop.
  • onLoop runs 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 allowedTransitions must 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, playSequence raises an error before anything changes.
  • finish ends the step's transition at once, and the sequence moves on to the hold.
  • destroy stops the sequence. A step that raises an error ends it, and the error is reported in the output.

Parameters

NameTypeDescription
steps{ SequenceStep }The states to play, in order. Must have at least one step.
optionsSequenceOptions?Optional. Options for this sequence.

Returns

TypeDescription
Source<number>The round that is being played, counted from 1.
DisconnectCall it to stop the sequence. The handler keeps the state it is in.

Errors

CauseMessage
ErrorThe handler was destroyedplaySequence cannot be called after destroy
Errorsteps is not a list, or is emptyplaySequence steps must be a non-empty list of steps
ErrorA step is not a tableplaySequence step <n> must be a table
ErrorA step has an unknown keyplaySequence step <n> has an unknown key <key>
ErrorA step has no state nameplaySequence step <n> needs a state name
ErrorA step's state is not a state of the handlerplaySequence step <n> has an unknown state "<state>"
ErrorA step's hold or delay is not a finite non-negative numberplaySequence step <n> hold must be a finite non-negative number, and the same for delay
ErrorA step's instant is not a booleanplaySequence step <n> instant must be a boolean
ErrorThe rule does not allow a change between two stepsplaySequence step <n> cannot change state from "<state>" to "<state>". Allowed: "<state>", ...
ErrorWith loop, the rule does not allow the change from the last step to the firstplaySequence cannot loop: cannot change state from "<state>" to "<state>". Allowed: "<state>", ...
Erroroptions is not a table, or has an unknown keyplaySequence options must be a table, playSequence options has an unknown key <key>
Erroroptions.loop is not a boolean or a whole number of at least 1playSequence loop must be a boolean or a whole number of rounds, at least 1
Erroroptions.onLoop is not a functionplaySequence onLoop must be a function

follow Added in 0.9.0 ​

luau
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
) -> Disconnect

Makes 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.

luau
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. follow reads the source before it returns, and changes to that state instantly, as if it were the initial state. Every later change is a normal setState, with its transition.
  • nil keeps the current state. A toState that returns nil for a value changes nothing.
  • toState is tracked. A source it reads also makes the handler change state when it changes. The listeners of the change, such as onEnter, are not tracked.
  • A handler follows one source at a time. A newer follow stops the one before.
  • It stops when you call the returned function, when the handler is destroyed, or, when follow is called inside a Vide scope such as a component, when that scope is cleaned up.
  • A setState from your code or a playSequence still works while the handler follows a source, and the next change of the source sets the state again.

Parameters

NameTypeDescription
source() -> VThe 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

TypeDescription
DisconnectCall 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.

CauseMessage
Errorsource is not a functionfollow source must be a function
ErrortoState is not a functionfollow toState must be a function
ErrorThe state name is not a stringfollow expected a state name or nil, got <type>
ErrorThe state is not a state of the handlerfollow has an unknown state "<state>"
ErrorThe rule does not allow the changefollow 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 ​

luau
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 ​

luau
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 ​

luau
Handler.onPause(
    callback: (
        startedAt: number -- The os.clock() time at which the most recent transition started
    ) -> ()
) -> Disconnect

Runs callback each time the handler goes from running to paused. A repeated pause call does not run it again.

Parameters

NameTypeDescription
callbackOnPauseCallbackCalled 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

TypeDescription
DisconnectCall it to stop receiving pause events.

Errors

CauseMessage
Errorcallback is not a functiononPause callback must be a function

onResume Added in 0.2.0 ​

luau
Handler.onResume(
    callback: (
        startedAt: number -- The os.clock() time at which the most recent transition started
    ) -> ()
) -> Disconnect

Runs callback each time the handler goes from paused to running. A repeated resume call does not run it again.

Parameters

NameTypeDescription
callbackOnResumeCallbackCalled with the os.clock() time at which the most recent transition started.

Returns

TypeDescription
DisconnectCall it to stop receiving resume events.

Errors

CauseMessage
Errorcallback is not a functiononResume callback must be a function

scaleSpeed Changed in 0.3.0 ​

To scale every handler at once, use everyHandler.scaleSpeed.

luau
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

NameTypeDescription
optionsScaleSpeedOptionsRequired. The speed scale.

Errors

CauseMessage
Erroroptions is not a tablescaleSpeed options must be a table
Erroroptions has an unknown keyscaleSpeed options has an unknown key <key>
Erroroptions.speed is not a finite number above 0scaleSpeed speed must be a finite number above 0
Erroroptions.once is not a booleanscaleSpeed once must be a boolean

finish Added in 0.2.0 ​

luau
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 ​

luau
Handler.onFinish(
    callback: (
        startedAt: number -- The os.clock() time at which the transition started
    ) -> ()
) -> Disconnect

Runs 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

NameTypeDescription
callbackOnFinishCallbackCalled with the os.clock() time at which the transition started.

Returns

TypeDescription
DisconnectCall it to stop receiving finish events.

Errors

CauseMessage
Errorcallback is not a functiononFinish callback must be a function

waitForFinish Yields Added in 0.2.0 ​

luau
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 ​

luau
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.

luau
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,
    })
end

Types ​

Handler Added in 0.1.0 Changed in 0.9.0 ​

luau
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.

NameTypeDescription
TInferRule<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 ​

luau
type HandlerStates<T, Names = string> = -- A table of states, keyed by name, where each state has a Source for every field of T

The 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.

NameTypeDescription
T{ [string]: any }The value record, such as { transparency: number }. Each field becomes a Source of that field's type.
Namesstring, or a string literal or a union of themThe state names. With literals, every one of those states is required. Defaults to string.

ValuesOfStates Added in 0.9.0 ​

luau
type ValuesOfStates<States> = -- The value record that a table of states made of Vide sources holds

The value type that VideState.handler infers from its states. A state of { transparency = Vide.source(0) } gives { transparency: number }.

NameTypeDescription
StatesA table of statesThe table passed to VideState.handler.

StaticHandlerStates Added in 0.9.0 ​

luau
type StaticHandlerStates<T, Names = string> = -- A table of states, keyed by name, where each state has a value for every field of T

The 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.

NameTypeDescription
T{ [string]: any }The value record, such as { transparency: number }.
Namesstring, or a string literal or a union of themThe state names. With literals, every one of those states is required. Defaults to string.

StaticValuesOfStates Added in 0.9.0 ​

luau
type StaticValuesOfStates<States> = -- The value record that a table of states made of plain values holds

The value type that VideState.staticHandler infers from its states. A state of { transparency = 0, label = "Play" } gives { transparency: number, label: string }.

NameTypeDescription
StatesA table of statesThe table passed to VideState.staticHandler.

DefaultSources Added in 0.8.0 ​

luau
type DefaultSources<T> = -- A record of Vide sources, each optional, one per field of T that can have a default
NameTypeDescription
T{ [string]: any }The value record. Each field becomes an optional Source of that field's type.

Sources Added in 0.1.0 ​

luau
type Sources<T> = -- A record of Vide sources, one per field of T
NameTypeDescription
T{ [string]: any }The value record. Each field becomes a Source of that field's type.

OnChangeCallback Added in 0.1.0 ​

luau
type OnChangeCallback<T> = (from: T, to: T) -> ()

OnEnterCallback Added in 0.2.0 ​

luau
type OnEnterCallback = (previousState: string) -> ()
NameTypeDescription
previousStatestringThe name of the state the handler left.

OnExitCallback Added in 0.2.0 ​

luau
type OnExitCallback = (nextState: string) -> ()
NameTypeDescription
nextStatestringThe name of the state the handler enters.

OnTransitionCallback Added in 0.1.0 Changed in 0.5.0 ​

luau
type OnTransitionCallback<T> = (from: T, to: T, current: T, alpha: number, round: number) -> ()
NameTypeDescription
fromTThe previous state's values.
toTThe next state's values.
currentTThe values to render on this frame.
alphanumberThe eased progress, from 0 to 1. With back and elastic easings it can go below 0 or above 1. See alpha.
roundnumberThe round of the playSequence that started the transition, counted from 1. 0 when no sequence started it.

OnPauseCallback Added in 0.2.0 ​

luau
type OnPauseCallback = (startedAt: number) -> ()
NameTypeDescription
startedAtnumberThe 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 ​

luau
type OnResumeCallback = (startedAt: number) -> ()
NameTypeDescription
startedAtnumberThe os.clock() time at which the handler's most recent transition started.

OnFinishCallback Added in 0.2.0 ​

luau
type OnFinishCallback = (startedAt: number) -> ()
NameTypeDescription
startedAtnumberThe os.clock() time at which the transition that finished started.

SetStateOptions Added in 0.2.0 Changed in 0.5.0 ​

luau
type SetStateOptions = {
    instant: boolean?, -- Skips the animation of this change
    delay: number?, -- Seconds every connection waits before it starts
}
FieldTypeRequiredDefaultDescription
instantbooleanNofalseWhen true, every onTransition connection receives the next state's values at once, with an alpha of 1.
delaynumberNo0Seconds 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 ​

luau
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.

FieldTypeRequiredDefaultDescription
statestringYesThe state to change to. It must be a state of the handler.
holdnumberNo0Seconds 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.
instantbooleanNofalseThe same as in SetStateOptions.
delaynumberNo0The same as in SetStateOptions.

SequenceOptions Added in 0.5.0 ​

luau
type SequenceOptions = {
    loop: (boolean | number)?, -- How many rounds to play
    onLoop: ((round: number) -> ())?, -- Called at the end of every round
}

The options of playSequence.

FieldTypeRequiredDefaultDescription
loopboolean or numberNofalseHow 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) -> ()NoCalled 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 ​

luau
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
}
FieldTypeRequiredDefaultDescription
speednumberYesNoneThe speed scale. Must be a finite number above 0. Above 1 plays faster, 1 is normal speed, and below 1 plays slower.
oncebooleanNofalseWhen true, the scale applies only to the running transition. When false, it stays for every following transition.

Disconnect Added in 0.1.0 ​

luau
type Disconnect = () -> ()

Removes the listener it was returned for. Calling it more than once has no effect.