Skip to content

Rules ​

A rule describes what handlers receive, so every handler created from it shares the same fields. A rule is built from a rule schema, made with VideState.schemas.new, and a metadata table. One rule can create many handlers, and the handlers do not affect each other.

Using a rule takes two steps, and the order matters:

  1. Make the rule's schema with VideState.schemas.new, and create the rule once with VideState.rules.dynamic.
  2. Call new on the rule it returns, once for each handler you need.

rules.dynamic is a function in the VideState.rules namespace. new is a method of the rule that rules.dynamic returns, so it does not exist until a rule has been created.

Creating a rule Added in 0.1.0 Changed in 0.8.0 ​

luau
VideState.rules.dynamic<Fields>(
    schema: RuleSchema<Fields>, -- The fields, made with VideState.schemas.new
    metadata: RuleMetadata -- Describes the rule and restricts its state names
) -> Rule<Fields>
luau
const VideState = require("@VideState")

const schemas = VideState.schemas
const rules = VideState.rules

const ButtonSchema = schemas.new({
    alpha = schemas.float({ min = 0, max = 1 }),
    size = schemas.udim2(),
})

return rules.dynamic(ButtonSchema, { name = "Button" })

The schema is a rule schema made with schemas.new, schemas.extend, or schemas.withDefaults, and one schema can make several rules. The states of a dynamic rule are Vide sources, so their values can change after the handler is made. For states of plain values that never change, use rules.static.

Creates a rule and registers its metadata under metadata.name.

Parameters

NameTypeDescription
schemaRuleSchema<Fields>The rule's fields. The rule's value type is inferred from them.
metadataRuleMetadataThe rule's name and optional details.

Returns

TypeDescription
Rule<Fields>A frozen table with the new constructor and the _schema built from the fields.

Errors

CauseMessage
ErrorA rule with the same metadata.name already existsDuplicate rule name: <name>
Errorschema is a plain table of fieldsrules.dynamic expects a schema, not a table of fields. Wrap the fields with VideState.schemas.new(fields)
Errorschema is not a tablerules.dynamic expects a schema made with VideState.schemas.new, got <type>

Creating handlers from a rule Added in 0.1.0 Changed in 0.8.0 ​

Call new on a rule that rules.dynamic has already returned. It is not a function of VideState.

luau
Rule.new(
    states: { [string]: Sources<T> }, -- Vide sources for each state, keyed by state name
    initialState: string -- The state the handler starts in
) -> Handler<T>

A state can leave out a field whose schema has a default value from withDefault, and the handler fills it in. See Default values.

Creates a handler from the rule. Every state must provide a Vide source for each field in the rule, and each state's values are validated when new runs. A rule needs at least two states.

Parameters

NameTypeDescription
states{ [string]: Sources<T> }A dictionary of states. Each value is a record of Vide sources with one source per field. When metadata.allowedStateNames is set, every key must be in that list.
initialStatestringThe name of the state the handler starts in. Must be a key of states.

Returns

TypeDescription
Handler<T>A new handler with its own state, sources, and cleanup.

Errors

CauseMessage
Errorstates is not a tablerule states must be a table
ErrorA state is not a table of Vide sourcesstate "<state>" must be a table of sources
ErrorA field of a state is not a Vide sourcestate "<state>" field "<field>" must be a Vide source
ErrorA state is missing a field that has no defaultstate "<state>" is missing source for field "<field>"
ErrorA state's values do not match the schemaInvalid state "<state>": followed by the schema issues
ErrorFewer than two statesrule requires at least 2 states
ErrorA state name is not in allowedStateNamesstate "<state>" is not in allowedStateNames
ErrorallowedTransitions names a state that is not one of the handler's statesallowedTransitions "<state>" lists "<state>", which is not a state of the handler
ErrorinitialState is not one of the statesunknown initial state "<state>"
ErrorA third argument is givennew takes only the states and the initial state. Pass tweenDefault to onTransition or animate instead

Checking states with the analyzer Added in 0.8.0 ​

VideState checks every state when a handler is created, and raises an error that names the state and the field. To have the Luau analyzer catch the same mistakes while you write the code, annotate the table of states with DynamicStates or StaticStates before you pass it to new:

luau
const VideState = require("@VideState")
const Vide = require("@packages/Vide")

const schemas = VideState.schemas
const rules = VideState.rules

const ButtonSchema = schemas.withDefaults(schemas.new({
    alpha = schemas.float({ min = 0, max = 1 }),
    visible = schemas.boolean(),
}), { alpha = 1 })

const ButtonRule = rules.dynamic(ButtonSchema, { name = "Button" })

const states: VideState.DynamicStates<typeof(ButtonRule)> = {
    Idle = { visible = Vide.source(true) }, -- alpha has a default, so it can be left out
    Hover = { visible = Vide.source(true), alpha = Vide.source(0.8) },
}

const handler = ButtonRule.new(states, "Idle")

With the annotation, the analyzer reports a value of the wrong type and a missing field that has no default. Without it, a table written straight into the call to new is not checked: Luau's new type solver does not report a table literal passed to a parameter typed as { [string]: ... }. The runtime check catches the mistake either way, when the handler is created.

To also check the state names, pass them as a second type argument, as a string literal or a union of them. Each named state is then required, so the analyzer reports a missing state, and a misspelt one, because the correct name is then missing. Continuing the script above:

luau
type ButtonStates = VideState.DynamicStates<typeof(ButtonRule), "Idle" | "Hover">

const namedStates: ButtonStates = {
    Idle = { visible = Vide.source(true) },
    Hover = { visible = Vide.source(true), alpha = Vide.source(0.8) },
}

const namedHandler = ButtonRule.new(namedStates, "Idle")

Leaving the names out, or passing string, accepts any state names.

Static rules Added in 0.8.0 ​

luau
VideState.rules.static<Fields>(
    schema: RuleSchema<Fields>, -- The fields, made with VideState.schemas.new, as for rules.dynamic
    metadata: RuleMetadata -- Describes the rule and restricts its state names
) -> StaticRule<Fields>

StaticRule.new(
    states: { [string]: T }, -- Plain values for each state, keyed by state name
    initialState: string -- The state the handler starts in
) -> Handler<T>

A static rule makes handlers whose states hold plain values instead of Vide sources. Each handler passes its own values to new, the rule checks them there once, and they never change after that. Use it when a component's values are known when it is created, such as a button whose colours come from its props. The rule's fields and validation work as for a dynamic rule, and rules.extendStatic builds on it.

Because the values cannot change, a state change does not check them again, so changing the state of a static handler costs about the same as writing plain Vide sources by hand. A static rule also creates handlers and starts transitions faster than a dynamic rule. See Performance.

luau
const VideState = require("@VideState")
const Vide = require("@packages/Vide")

const schemas = VideState.schemas
const rules = VideState.rules

const ButtonRule = rules.static(schemas.new({
    alpha = schemas.float({ min = 0, max = 1 }),
    size = schemas.udim2(),
}), { name = "Button" })

const handler = ButtonRule.new({
    Idle = { alpha = 1, size = UDim2.fromScale(1, 1) },
    Hover = { alpha = 0.8, size = UDim2.fromScale(1.1, 1.1) },
}, "Idle")

handler.setState("Hover")
print(handler.sources.alpha()) -- 0.8

A handler of a static rule works like any other: it transitions, it has animate, onTransition, and the other handler functions, and everyHandler and the tag functions see it. Two things differ:

  • Its sources follow the active state, but writing to one raises an error, because the values are fixed. The table you pass to new is copied, so changing it later changes nothing.
  • It has no defaults to write to. A field with a withDefault that a state leaves out takes the default value.

To change a value while the handler runs, use a dynamic rule.

Parameters of new

NameTypeDescription
states{ [string]: T }A dictionary of states. Each value is a record with a plain value per field. When metadata.allowedStateNames is set, every key must be in that list.
initialStatestringThe name of the state the handler starts in. Must be a key of states.

Returns

TypeDescription
StaticRule``<Fields>A rule with the tag functions of a dynamic rule, isStatic, which returns true, and new(states, initialState).

Errors

CauseMessage
ErrorA rule with the same metadata.name already existsDuplicate rule name: <name>
Errorschema is a plain table of fieldsrules.static expects a schema, not a table of fields. Wrap the fields with VideState.schemas.new(fields)
Errorstates is not a tablerule states must be a table
ErrorA field of a state is a function, such as a Vide sourcestate "<state>" field "<field>" is a function. A static rule takes plain values, not Vide sources
ErrorA state's values do not match the schemaInvalid state "<state>": followed by the schema issues
ErrorFewer than two statesrule requires at least 2 states
ErrorA state name is not in allowedStateNamesstate "<state>" is not in allowedStateNames
ErrorinitialState is not one of the statesunknown initial state "<state>"
ErrorA third argument is given to newnew takes only the states and the initial state
ErrorA source of a handler is written tocannot write to "<field>": the states of a static rule are fixed

Sharing states between handlers ​

When many handlers have the same states, such as every button in a list, freeze the table and each state in it, and pass the same table to every new. The rule checks a table that is frozen all the way down once, and every handler made from it shares that check and its copy of the values, so creating each one costs about 40% less. A table that is not frozen could change, so it is checked again for every handler.

Annotate the table and freeze it afterwards, as below. The analyzer checks an annotated table, but it does not accept a table that is frozen where it is written, such as table.freeze({ ... }), for the states of new. A state that holds a table, such as a record field, needs that table frozen too.

luau
const VideState = require("@VideState")

const schemas = VideState.schemas
const rules = VideState.rules

const ListButtonRule = rules.static(schemas.new({
    alpha = schemas.float({ min = 0, max = 1 }),
}), { name = "ListButton" })

const LIST_BUTTON_STATES: VideState.StaticStates<typeof(ListButtonRule), "Idle" | "Hover"> = {
    Idle = { alpha = 1 },
    Hover = { alpha = 0.8 },
}

-- Frozen all the way down, so the rule checks the table once, the first time a handler is made from it.
for _, state in LIST_BUTTON_STATES do
    table.freeze(state)
end

table.freeze(LIST_BUTTON_STATES)

return function()
    return ListButtonRule.new(LIST_BUTTON_STATES, "Idle")
end

Default values Added in 0.8.0 ​

A field whose schema comes from withDefault can be left out of a state. When new runs, each state that leaves it out gets the handler's source for that default, so the handler sees a full value in every state. A transition between a state with the field and one without tweens from or to the default like any other value.

luau
const VideState = require("@VideState")
const Vide = require("@packages/Vide")

const schemas = VideState.schemas
const rules = VideState.rules

const ButtonRule = rules.dynamic(schemas.new({
    alpha = schemas.withDefault(schemas.float({ min = 0, max = 1 }), 1),
    visible = schemas.boolean(),
}), { name = "Button" })

const handler = ButtonRule.new({
    Idle = { visible = Vide.source(true) }, -- alpha is 1
    Faded = { visible = Vide.source(true), alpha = Vide.source(0.5) },
}, "Idle")

print(handler.sources.alpha()) -- 1

The handler makes one source for each defaulted field and gives it to every state that leaves the field out. It is exposed as handler.defaults, so writing to it changes the default for all of those states at once. Each handler has its own, and the table of states that you pass in is not changed. A field with no default is still required in every state.

To give several fields of a schema a default at once, use schemas.withDefaults, which takes the default of each field by name and returns a new schema:

luau
const VideState = require("@VideState")

const schemas = VideState.schemas
const rules = VideState.rules

const PanelSchema = schemas.new({
    alpha = schemas.float({ min = 0, max = 1 }),
    scale = schemas.float({ min = 0 }),
    visible = schemas.boolean(),
})

const PanelRule = rules.dynamic(
    schemas.withDefaults(PanelSchema, { alpha = 1, scale = 1 }),
    { name = "Panel" }
)

Allowed state changes Added in 0.5.0 ​

By default a handler can change from any state to any state. allowedTransitions limits that. Each key is a state, and its list holds the only states it can change to:

luau
const VideState = require("@VideState")

const schemas = VideState.schemas
const rules = VideState.rules

const ButtonRule = rules.dynamic(schemas.new({
    backgroundColor = schemas.color3(),
}), {
    name = "Button",
    allowedStateNames = { "Idle", "Hovered", "Pressed", "Disabled" },
    allowedTransitions = {
        -- A disabled button can only become idle again.
        Disabled = { "Idle" },
    },
})

A setState to a state that the current state does not list raises an error, and the handler stays where it was. No event runs and no transition starts.

luau
const Vide = require("@packages/Vide")

-- `handler` comes from the `ButtonRule` above.
const handler = ButtonRule.new({
    Idle = { backgroundColor = Vide.source(Color3.fromRGB(60, 60, 70)) },
    Hovered = { backgroundColor = Vide.source(Color3.fromRGB(80, 80, 95)) },
    Pressed = { backgroundColor = Vide.source(Color3.fromRGB(40, 40, 50)) },
    Disabled = { backgroundColor = Vide.source(Color3.fromRGB(35, 35, 35)) },
}, "Idle")

handler.setState("Disabled")
handler.setState("Pressed")
-- Raises: cannot change state from "Disabled" to "Pressed". Allowed: "Idle"
  • A state that is not a key can change to any state.
  • Changing to the state the handler is already in does nothing, as before.
  • The initial state is not checked, and the rule applies to every following change.
  • The names must be states. With allowedStateNames, the rule checks them when it is made. Without it, each handler checks them against its own states when it is created.
  • everyHandler.setState checks every handler first, and none changes state if one is blocked.

Extending a rule Added in 0.5.0 Changed in 0.8.0 ​

luau
VideState.rules.extendDynamic<Fields, Extra>(
    base: Rule<Fields>, -- The rule to build on
    extraFields: RuleSchema<Extra>, -- The fields the new rule adds, made with VideState.schemas.new
    metadata: RuleMetadata -- The new rule's name and what it adds
) -> Rule<Fields & Extra>

Makes a new rule from a base rule. The new rule has every field of the base and the ones in extraFields, so a component that needs one more property does not repeat the base rule's fields. The fields are merged with schemas.extend, and the rest of the rule as the table below shows. To merge only fields, without a rule, use schemas.extend itself.

luau
const VideState = require("@VideState")

const schemas = VideState.schemas
const rules = VideState.rules

const ButtonRule = rules.dynamic(schemas.new({
    backgroundColor = schemas.color3(),
    textColor = schemas.color3(),
}), {
    name = "Button",
    tags = { "Button" },
    allowedStateNames = { "Idle", "Hovered", "Pressed", "Disabled" },
})

-- A button that can also show a loading state, with an icon on top.
const LoadingButtonRule = rules.extendDynamic(ButtonRule, schemas.new({
    iconTransparency = schemas.float({ min = 0, max = 1 }),
}), {
    name = "LoadingButton",
    allowedStateNames = { "Loading" },
})

A handler of LoadingButtonRule needs backgroundColor, textColor, and iconTransparency in every state, and can use the states Idle, Hovered, Pressed, Disabled, and Loading.

How the new rule is put together:

PartResult
FieldsThe base fields and extraFields. A field the base already has raises an error.
name, descriptionFrom metadata. The name must be unique, like any rule's.
tagsThe base rule's current tags, then the new ones, without repeats.
allowedStateNamesThe base names and the new ones. If neither has a list, every name is allowed.
allowedTransitionsThe base transitions and the new ones. A state the new rule lists replaces the base list for that state.

The base rule does not change, and handlers made from it are not affected. rules.extendDynamic can be called on an extended rule again.

Parameters

NameTypeDescription
baseRule<Fields>A rule made with VideState.rules.dynamic or rules.extendDynamic.
extraFieldsRuleSchema<Extra>The new fields, made with schemas.new. Each name must be new to the base rule.
metadataRuleMetadataThe new rule's name and the details it adds.

Returns

TypeDescription
Rule<Fields & Extra>The new rule.

Errors

CauseMessage
Errorbase is not a rulerules.extendDynamic expects a rule made with VideState.rules.dynamic as its first argument
ErrorextraFields is not a tablerules.extendDynamic expects a schema of extra fields made with VideState.schemas.new, got <type>
ErrorextraFields is a plain table of fieldsrules.extendDynamic expects a schema of extra fields, not a table of fields. Wrap the fields with VideState.schemas.new(fields)
ErrorA field is already in the base rulerules.extendDynamic cannot redefine field "<field>" of rule <rule>
Errorbase is a static rulerules.extendDynamic expects a dynamic rule. Use VideState.rules.extendStatic to extend a static rule
Errormetadata is missingrules.extendDynamic expects metadata with a name
ErrorThe name is already usedDuplicate rule name: <name>

The new rule's metadata is checked like the metadata of VideState.rules.dynamic.

Extending a static rule Added in 0.8.0 ​

luau
VideState.rules.extendStatic<Fields, Extra>(
    base: StaticRule<Fields>, -- The static rule to build on
    extraFields: RuleSchema<Extra>, -- The fields the new rule adds, made with VideState.schemas.new
    metadata: RuleMetadata -- The new rule's name and what it adds
) -> StaticRule<Fields & Extra>

Makes a new static rule from a static base rule. It merges the fields, state names, transitions, and tags exactly as rules.extendDynamic does, takes its extra fields as a rule schema in the same way, and its handlers take plain values like the base's. rules.extendDynamic is for a dynamic base, and each raises an error that names the other when it is given the wrong kind.

luau
const VideState = require("@VideState")

const schemas = VideState.schemas
const rules = VideState.rules

const ButtonRule = rules.static(schemas.new({
    alpha = schemas.float({ min = 0, max = 1 }),
}), { name = "Button" })

const IconButtonRule = rules.extendStatic(ButtonRule, schemas.new({
    iconRotation = schemas.float(),
}), { name = "IconButton" })

const handler = IconButtonRule.new({
    Idle = { alpha = 1, iconRotation = 0 },
    Hover = { alpha = 0.8, iconRotation = 15 },
}, "Idle")

Errors

CauseMessage
Errorbase is not a rulerules.extendStatic expects a rule made with VideState.rules.static as its first argument
Errorbase is a dynamic rulerules.extendStatic expects a static rule. Use VideState.rules.extendDynamic to extend a dynamic rule
ErrorextraFields is not a tablerules.extendStatic expects a schema of extra fields made with VideState.schemas.new, got <type>
ErrorA field is already in the base rulerules.extendStatic cannot redefine field "<field>" of rule <rule>
Errormetadata is missingrules.extendStatic expects metadata with a name
ErrorThe name is already usedDuplicate rule name: <name>

Tags ​

Tags group rules, and are set in the tags field of the metadata. These methods read and change a rule's tags after it was created. Tags are compared exactly as written, so they are never trimmed or lowercased. info and the everyHandler filters read the tags each time they run, so a change reaches them at once.

getTags Added in 0.4.0 ​

luau
rule.getTags() -> { string }

Returns the rule's tags.

Returns

TypeDescription
{ string }A frozen copy of the tags in the order they were added. It is empty when the rule has none. Later changes do not affect it, so call getTags again to read them.

hasTag Added in 0.4.0 ​

luau
rule.hasTag(tag: string) -> boolean

Checks whether the rule has the tag.

Parameters

NameTypeDescription
tagstringThe tag to look for.

Returns

TypeDescription
booleantrue when the rule has the exact tag, false when it does not.

Errors

CauseMessage
Errortag is not a stringTag must be a string, got <type>

addTags Added in 0.4.0 ​

luau
rule.addTags(...: string) -> boolean

Adds tags to the rule.

Parameters

NameTypeDescription
...stringThe tags to add. At least one is required. A tag that is repeated in one call counts once.

Returns

TypeDescription
booleantrue when at least one tag was new. false when the rule already had every tag.

Errors

CauseMessage
ErrorNo tags are givenaddTags requires at least one tag
ErrorA tag is not a stringTag <index> must be a string, got <type>

removeTags Added in 0.4.0 ​

luau
rule.removeTags(...: string) -> boolean

Removes tags from the rule.

Parameters

NameTypeDescription
...stringThe tags to remove. At least one is required.

Returns

TypeDescription
booleantrue when at least one tag was removed. false when the rule had none of them.

Errors

CauseMessage
ErrorNo tags are givenremoveTags requires at least one tag
ErrorA tag is not a stringTag <index> must be a string, got <type>

Types ​

RuleMetadata Added in 0.1.0 Changed in 0.5.0 ​

luau
type RuleMetadata = {
    name: string, -- Unique name of the rule
    description: string?, -- Describes what the rule is for
    tags: { string }?, -- Groups rules together
    allowedStateNames: { string }?, -- Restricts the state names handlers may use
    allowedTransitions: { [string]: { string } }?, -- For a state, the only states it can change to
}
FieldTypeRequiredDescription
namestringYesMust be unique across all rules. A duplicate raises an error.
descriptionstringNoText describing the rule.
tags{ string }NoStrings for grouping rules. Tags are never formatted, so keep them consistent. Look them up with info.
allowedStateNames{ string }NoWhen set, handlers reject any other state name. When omitted, every state name is allowed.
allowedTransitions{ [string]: { string } }NoFor a state, the only states it can change to. A state that is not listed can change to any state. See Allowed state changes.

isStatic Added in 0.8.0 ​

luau
Rule.isStatic() -> boolean

Returns true for a rule made with rules.static, and false for one made with rules.dynamic.

DynamicStates Added in 0.8.0 ​

luau
type DynamicStates<R, Names = string> = { [Names]: { [field]: Source<value> } }

The type of the states that new of a dynamic rule takes, worked out from the rule R. Each state has a Vide source for every field, and a field with a default from withDefault or schemas.withDefaults is optional. Use it to annotate a table of states, as shown in Checking states with the analyzer.

NameTypeDescription
Rtypeof(rule)A rule made with rules.dynamic or rules.extendDynamic.
Namesstring, a string literal, or a union of themThe state names. string, the default, accepts any names. With literals, each of those states is required.

StaticStates Added in 0.8.0 ​

luau
type StaticStates<R, Names = string> = { [Names]: { [field]: value } }

The type of the states that new of a static rule takes: a plain value for every field, and a field with a default is optional. It reads only the fields of the rule, so it also types plain values for the states of a dynamic rule, such as a table of designs that are turned into sources later. See Components.

NameTypeDescription
Rtypeof(rule)A rule made with rules.static or rules.extendStatic, or a dynamic rule for plain values of its states.
Namesstring, a string literal, or a union of themThe state names. string, the default, accepts any names. With literals, each of those states is required.

InferRule Added in 0.1.0 ​

luau
type InferRule<R> = -- The value type of the rule R

Gives the value type of a rule. Use it instead of reading _schema directly, and pass the result to VideState.Handler to type a handler.

NameTypeDescription
Rtypeof(rule)The rule to read the value type from.

Rule Added in 0.1.0 Changed in 0.8.0 ​

luau
type Rule<Fields> = {
    _schema: Schema<Fields>, -- The schema built from the fields
    new: (states: { [string]: Sources<T> }, initialState: string) -> Handler<T>,
    getTags: () -> { string },
    hasTag: (tag: string) -> boolean,
    addTags: (...string) -> boolean,
    removeTags: (...string) -> boolean,
    isStatic: () -> boolean,
}

A rule returned by rules.dynamic. It is frozen, so it cannot be changed after creation.

FieldTypeDescription
_schemaSchema<Fields>The schema that validates each state. Pass the rule to InferRule instead of reading this directly.
newfunctionCreates a handler. See new.
getTagsfunctionReturns the rule's tags. See getTags.
hasTagfunctionChecks whether the rule has a tag. See hasTag.
addTagsfunctionAdds tags to the rule. See addTags.
removeTagsfunctionRemoves tags from the rule. See removeTags.
isStaticfunctionWhether the rule was made with rules.static. See isStatic.