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:
- Make the rule's schema with
VideState.schemas.new, and create the rule once withVideState.rules.dynamic. - Call
newon 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
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>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
| Name | Type | Description |
|---|---|---|
schema | RuleSchema<Fields> | The rule's fields. The rule's value type is inferred from them. |
metadata | RuleMetadata | The rule's name and optional details. |
Returns
| Type | Description |
|---|---|
Rule<Fields> | A frozen table with the new constructor and the _schema built from the fields. |
Errors
| Cause | Message | |
|---|---|---|
| Error | A rule with the same metadata.name already exists | Duplicate rule name: <name> |
| Error | schema is a plain table of fields | rules.dynamic expects a schema, not a table of fields. Wrap the fields with VideState.schemas.new(fields) |
| Error | schema is not a table | rules.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.
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
| Name | Type | Description |
|---|---|---|
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. |
initialState | string | The name of the state the handler starts in. Must be a key of states. |
Returns
| Type | Description |
|---|---|
Handler<T> | A new handler with its own state, sources, and cleanup. |
Errors
| Cause | Message | |
|---|---|---|
| Error | states is not a table | rule states must be a table |
| Error | A state is not a table of Vide sources | state "<state>" must be a table of sources |
| Error | A field of a state is not a Vide source | state "<state>" field "<field>" must be a Vide source |
| Error | A state is missing a field that has no default | state "<state>" is missing source for field "<field>" |
| Error | A state's values do not match the schema | Invalid state "<state>": followed by the schema issues |
| Error | Fewer than two states | rule requires at least 2 states |
| Error | A state name is not in allowedStateNames | state "<state>" is not in allowedStateNames |
| Error | allowedTransitions names a state that is not one of the handler's states | allowedTransitions "<state>" lists "<state>", which is not a state of the handler |
| Error | initialState is not one of the states | unknown initial state "<state>" |
| Error | A third argument is given | new 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:
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:
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
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.
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.8A 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
sourcesfollow the active state, but writing to one raises an error, because the values are fixed. The table you pass tonewis copied, so changing it later changes nothing. - It has no
defaultsto write to. A field with awithDefaultthat a state leaves out takes the default value.
To change a value while the handler runs, use a dynamic rule.
Parameters of new
| Name | Type | Description |
|---|---|---|
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. |
initialState | string | The name of the state the handler starts in. Must be a key of states. |
Returns
| Type | Description |
|---|---|
StaticRule``<Fields> | A rule with the tag functions of a dynamic rule, isStatic, which returns true, and new(states, initialState). |
Errors
| Cause | Message | |
|---|---|---|
| Error | A rule with the same metadata.name already exists | Duplicate rule name: <name> |
| Error | schema is a plain table of fields | rules.static expects a schema, not a table of fields. Wrap the fields with VideState.schemas.new(fields) |
| Error | states is not a table | rule states must be a table |
| Error | A field of a state is a function, such as a Vide source | state "<state>" field "<field>" is a function. A static rule takes plain values, not Vide sources |
| Error | A state's values do not match the schema | Invalid state "<state>": followed by the schema issues |
| Error | Fewer than two states | rule requires at least 2 states |
| Error | A state name is not in allowedStateNames | state "<state>" is not in allowedStateNames |
| Error | initialState is not one of the states | unknown initial state "<state>" |
| Error | A third argument is given to new | new takes only the states and the initial state |
| Error | A source of a handler is written to | cannot 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.
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")
endDefault 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.
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()) -- 1The 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:
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:
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.
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.setStatechecks every handler first, and none changes state if one is blocked.
Extending a rule Added in 0.5.0 Changed in 0.8.0
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.
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:
| Part | Result |
|---|---|
| Fields | The base fields and extraFields. A field the base already has raises an error. |
name, description | From metadata. The name must be unique, like any rule's. |
tags | The base rule's current tags, then the new ones, without repeats. |
allowedStateNames | The base names and the new ones. If neither has a list, every name is allowed. |
allowedTransitions | The 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
| Name | Type | Description |
|---|---|---|
base | Rule<Fields> | A rule made with VideState.rules.dynamic or rules.extendDynamic. |
extraFields | RuleSchema<Extra> | The new fields, made with schemas.new. Each name must be new to the base rule. |
metadata | RuleMetadata | The new rule's name and the details it adds. |
Returns
| Type | Description |
|---|---|
Rule<Fields & Extra> | The new rule. |
Errors
| Cause | Message | |
|---|---|---|
| Error | base is not a rule | rules.extendDynamic expects a rule made with VideState.rules.dynamic as its first argument |
| Error | extraFields is not a table | rules.extendDynamic expects a schema of extra fields made with VideState.schemas.new, got <type> |
| Error | extraFields is a plain table of fields | rules.extendDynamic expects a schema of extra fields, not a table of fields. Wrap the fields with VideState.schemas.new(fields) |
| Error | A field is already in the base rule | rules.extendDynamic cannot redefine field "<field>" of rule <rule> |
| Error | base is a static rule | rules.extendDynamic expects a dynamic rule. Use VideState.rules.extendStatic to extend a static rule |
| Error | metadata is missing | rules.extendDynamic expects metadata with a name |
| Error | The name is already used | Duplicate 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
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.
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
| Cause | Message | |
|---|---|---|
| Error | base is not a rule | rules.extendStatic expects a rule made with VideState.rules.static as its first argument |
| Error | base is a dynamic rule | rules.extendStatic expects a static rule. Use VideState.rules.extendDynamic to extend a dynamic rule |
| Error | extraFields is not a table | rules.extendStatic expects a schema of extra fields made with VideState.schemas.new, got <type> |
| Error | A field is already in the base rule | rules.extendStatic cannot redefine field "<field>" of rule <rule> |
| Error | metadata is missing | rules.extendStatic expects metadata with a name |
| Error | The name is already used | Duplicate 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
rule.getTags() -> { string }Returns the rule's tags.
Returns
| Type | Description |
|---|---|
{ 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
rule.hasTag(tag: string) -> booleanChecks whether the rule has the tag.
Parameters
| Name | Type | Description |
|---|---|---|
tag | string | The tag to look for. |
Returns
| Type | Description |
|---|---|
boolean | true when the rule has the exact tag, false when it does not. |
Errors
| Cause | Message | |
|---|---|---|
| Error | tag is not a string | Tag must be a string, got <type> |
addTags Added in 0.4.0
rule.addTags(...: string) -> booleanAdds tags to the rule.
Parameters
| Name | Type | Description |
|---|---|---|
... | string | The tags to add. At least one is required. A tag that is repeated in one call counts once. |
Returns
| Type | Description |
|---|---|
boolean | true when at least one tag was new. false when the rule already had every tag. |
Errors
| Cause | Message | |
|---|---|---|
| Error | No tags are given | addTags requires at least one tag |
| Error | A tag is not a string | Tag <index> must be a string, got <type> |
removeTags Added in 0.4.0
rule.removeTags(...: string) -> booleanRemoves tags from the rule.
Parameters
| Name | Type | Description |
|---|---|---|
... | string | The tags to remove. At least one is required. |
Returns
| Type | Description |
|---|---|
boolean | true when at least one tag was removed. false when the rule had none of them. |
Errors
| Cause | Message | |
|---|---|---|
| Error | No tags are given | removeTags requires at least one tag |
| Error | A tag is not a string | Tag <index> must be a string, got <type> |
Types
RuleMetadata Added in 0.1.0 Changed in 0.5.0
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
}| Field | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Must be unique across all rules. A duplicate raises an error. |
description | string | No | Text describing the rule. |
tags | { string } | No | Strings for grouping rules. Tags are never formatted, so keep them consistent. Look them up with info. |
allowedStateNames | { string } | No | When set, handlers reject any other state name. When omitted, every state name is allowed. |
allowedTransitions | { [string]: { string } } | No | For 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
Rule.isStatic() -> booleanReturns true for a rule made with rules.static, and false for one made with rules.dynamic.
DynamicStates Added in 0.8.0
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.
| Name | Type | Description |
|---|---|---|
R | typeof(rule) | A rule made with rules.dynamic or rules.extendDynamic. |
Names | string, a string literal, or a union of them | The state names. string, the default, accepts any names. With literals, each of those states is required. |
StaticStates Added in 0.8.0
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.
| Name | Type | Description |
|---|---|---|
R | typeof(rule) | A rule made with rules.static or rules.extendStatic, or a dynamic rule for plain values of its states. |
Names | string, a string literal, or a union of them | The state names. string, the default, accepts any names. With literals, each of those states is required. |
InferRule Added in 0.1.0
type InferRule<R> = -- The value type of the rule RGives the value type of a rule. Use it instead of reading _schema directly, and pass the result to VideState.Handler to type a handler.
| Name | Type | Description |
|---|---|---|
R | typeof(rule) | The rule to read the value type from. |
Rule Added in 0.1.0 Changed in 0.8.0
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.
| Field | Type | Description |
|---|---|---|
_schema | Schema<Fields> | The schema that validates each state. Pass the rule to InferRule instead of reading this directly. |
new | function | Creates a handler. See new. |
getTags | function | Returns the rule's tags. See getTags. |
hasTag | function | Checks whether the rule has a tag. See hasTag. |
addTags | function | Adds tags to the rule. See addTags. |
removeTags | function | Removes tags from the rule. See removeTags. |
isStatic | function | Whether the rule was made with rules.static. See isStatic. |