From d54fdc18733555577af30eb826d3386118cbfe41 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:15:14 -0400 Subject: [PATCH 01/30] add hydrate --- src/instances/create.luau | 116 +----------------------------------- src/instances/hydrate.luau | 10 ++++ src/instances/types.luau | 118 +++++++++++++++++++++++++++++++++++++ 3 files changed, 131 insertions(+), 113 deletions(-) create mode 100644 src/instances/hydrate.luau create mode 100644 src/instances/types.luau diff --git a/src/instances/create.luau b/src/instances/create.luau index d5675e5..f86be61 100644 --- a/src/instances/create.luau +++ b/src/instances/create.luau @@ -1,4 +1,4 @@ -local action = require("./action") +local types = require("./types") local bind = require("./bind") type Instances = { @@ -86,59 +86,8 @@ type Instances = { Wire: Wire, } -type UnknownConnectCallback = (...any) -> () - -type Signal = RBXScriptSignal - -type function get_connect(v: type): type? - local connect = v:readproperty(types.singleton("Connect")) - - if connect and connect:is("function") then - local head = connect:parameters().head - - if not head then - return nil - end - local callback = head[2] - - if callback and callback:is("function") then - return callback - end - end - - return nil -end - -type function is_signal(v: type): type? - if v == Signal and v.tag == "extern" then - return UnknownConnectCallback - -- luau lsp types RBXScriptSignals as tables - elseif v.tag == "table" then - local connect = get_connect(v) - - if connect then - return connect - end - - -- i cba to test if this is needed or not - local metatable = v:metatable() - - if metatable then - connect = get_connect(metatable) - - if connect then - return connect - end - end - end - - return nil -end - type instance = Instance -type Action = action.Identity - type function GetInstance(class_name: type, instances: type): type if not class_name:is("singleton") then return instance @@ -147,66 +96,6 @@ type function GetInstance(class_name: type, instances: type): type return instances:readproperty(class_name) or instance end -export type function PropertiesFor(class_name: type): type - local object = GetInstance(class_name, Instances) - local head_table = {} - local args_table = { head = head_table } - local properties = types.newtable() - local current = object - local empty_table = {} - - local read_only_properties = table.freeze({ - types.singleton("RobloxLocked"), - types.singleton("ClassName"), - types.singleton("UniqueId"), - }) - - while current do - for property, value in current:properties() do - if table.find(read_only_properties, property) then - continue - end - - local value_read = value.read - local callback = is_signal(value_read) - - if callback then - properties:setproperty(property, types.optional(callback)) - elseif value_read.tag == "function" or value_read.tag == "intersection" then - continue - elseif value.write then - head_table[1] = value_read - - properties:setproperty( - property, - types.optional( - types.unionof(types.newfunction(empty_table :: any, args_table :: any), value.write) - ) - ) - end - end - - current = current:readparent() - end - - -- Functions returning a child can return an array of children, or alike functions, nested to any level - local function_returns_child = types.newfunction() - local child_only_union = types.unionof(function_returns_child, instance) - - -- TODO: Use a read only indexer when released to properly accept children which are subtypes of `Instance` - -- TODO: Nesting throws a type error, seemingly a solver bug caused whenever the keys are a union instead of direct type - -- Happens even with a union between `Instance` and `any`, but disappears when it's just `Instance` - local nested_table_or_function_or_child = types.newtable() - local nested_child_union = types.unionof(child_only_union, nested_table_or_function_or_child) - nested_table_or_function_or_child:setindexer(types.number, nested_child_union) - function_returns_child:setreturns({ nested_child_union }) - - local full_union = types.unionof(child_only_union, Action, properties) - properties:setindexer(types.number, types.optional(full_union)) - - return properties -end - local function try_create_instance(class_name: string): Instance local success, call_result = pcall(Instance.new, class_name) assert(success, call_result) @@ -214,9 +103,10 @@ local function try_create_instance(class_name: string): Instance return call_result end +--stylua: ignore local function create( class_name: ClassName | keyof | "" -): (props: PropertiesFor) -> GetInstance +): (props: types.PropertiesFor>) -> GetInstance return function(properties) return bind(try_create_instance(class_name), properties) :: any end diff --git a/src/instances/hydrate.luau b/src/instances/hydrate.luau new file mode 100644 index 0000000..80537d3 --- /dev/null +++ b/src/instances/hydrate.luau @@ -0,0 +1,10 @@ +local types = require("./types") +local bind = require("./bind") + +local function hydrate(instance: Instance): (props: types.PropertiesFor) -> Instance + return function(properties) + return bind(instance, properties) :: any + end +end + +return hydrate diff --git a/src/instances/types.luau b/src/instances/types.luau new file mode 100644 index 0000000..0356903 --- /dev/null +++ b/src/instances/types.luau @@ -0,0 +1,118 @@ +local action = require("./action") + +type UnknownConnectCallback = (...any) -> () + +type Signal = RBXScriptSignal + +type function get_connect(v: type): type? + local connect = v:readproperty(types.singleton("Connect")) + + if connect and connect:is("function") then + local head = connect:parameters().head + + if not head then + return nil + end + local callback = head[2] + + if callback and callback:is("function") then + return callback + end + end + + return nil +end + +type function is_signal(v: type): type? + if v == Signal and v.tag == "extern" then + return UnknownConnectCallback + -- luau lsp types RBXScriptSignals as tables + elseif v.tag == "table" then + local connect = get_connect(v) + + if connect then + return connect + end + + -- i cba to test if this is needed or not + local metatable = v:metatable() + + if metatable then + connect = get_connect(metatable) + + if connect then + return connect + end + end + end + + return nil +end + +type instance = Instance + +type Action = action.Identity + +export type function PropertiesFor(object: type): type + if not object:issubtypeof(instance) then + error("Cannot get properties of a non Instance type") + end + local head_table = {} + local args_table = { head = head_table } + local properties = types.newtable() + local current = object + local empty_table = {} + + local read_only_properties = table.freeze({ + types.singleton("RobloxLocked"), + types.singleton("ClassName"), + types.singleton("UniqueId"), + }) + + while current do + for property, value in current:properties() do + if table.find(read_only_properties, property) then + continue + end + + local value_read = value.read + local callback = is_signal(value_read) + + if callback then + properties:setproperty(property, types.optional(callback)) + elseif value_read.tag == "function" or value_read.tag == "intersection" then + continue + elseif value.write then + head_table[1] = value_read + + properties:setproperty( + property, + types.optional( + types.unionof(types.newfunction(empty_table :: any, args_table :: any), value.write) + ) + ) + end + end + + current = current:readparent() + end + + -- Functions returning a child can return an array of children, or alike functions, nested to any level + local function_returns_child = types.newfunction() + local child_only_union = types.unionof(function_returns_child, instance) + + -- TODO: Use a read only indexer when released to properly accept children which are subtypes of `Instance` + -- TODO: Nesting throws a type error, seemingly a solver bug caused whenever the keys are a union instead of direct type + -- Happens even with a union between `Instance` and `any`, but disappears when it's just `Instance` + local nested_table_or_function_or_child = types.newtable() + local nested_child_union = types.unionof(child_only_union, nested_table_or_function_or_child) + nested_table_or_function_or_child:setindexer(types.number, nested_child_union) + function_returns_child:setreturns({ nested_child_union }) + + local full_union = types.unionof(child_only_union, Action, properties) + properties:setindexer(types.number, types.optional(full_union)) + + return properties +end + +return nil From a50320eff2755128bd7fcb1c8c1f7a1677490957 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:46:34 -0400 Subject: [PATCH 02/30] oops i forgot to export hydrate, and fix the export for PropertiesFor --- src/init.luau | 5 +- src/instances/create.luau | 99 +---------------------------------- src/instances/types.luau | 106 ++++++++++++++++++++++++++++++++++++-- 3 files changed, 107 insertions(+), 103 deletions(-) diff --git a/src/init.luau b/src/init.luau index 34108a4..b9de033 100644 --- a/src/init.luau +++ b/src/init.luau @@ -25,11 +25,13 @@ local switch_delay = require("@self/utils/switch_delay") local tags = require("@self/utils/tags") local types = require("@self/reactive/types") local untrack = require("@self/reactive/untrack") +local hydrate = require("@self/instances/hydrate") +local instance_types = require("@self/instances/types") export type UsedAs = types.UsedAs export type Source = types.Source export type Action = action.Identity -export type PropertiesFor = create.PropertiesFor +export type PropertiesFor = instance_types.PropertiesFor local scheduler_thread: thread? = nil @@ -59,6 +61,7 @@ end local fluid = {} +fluid.hydrate = hydrate fluid.create = create fluid.mount = mount fluid.tags = tags diff --git a/src/instances/create.luau b/src/instances/create.luau index f86be61..0613f1b 100644 --- a/src/instances/create.luau +++ b/src/instances/create.luau @@ -1,101 +1,6 @@ local types = require("./types") local bind = require("./bind") -type Instances = { - PyramidHandleAdornment: PyramidHandleAdornment, - AudioChannelSplitter: AudioChannelSplitter, - AudioPitchShifter: AudioPitchShifter, - AudioDeviceOutput: AudioDeviceOutput, - AudioChannelMixer: AudioChannelMixer, - AudioTextToSpeech: AudioTextToSpeech, - AudioDeviceInput: AudioDeviceInput, - AudioDistortion: AudioDistortion, - AudioCompressor: AudioCompressor, - AudioEqualizer: AudioEqualizer, - AudioAnalyzer: AudioAnalyzer, - AudioListener: AudioListener, - AudioRecorder: AudioRecorder, - AudioLimiter: AudioLimiter, - AudioFlanger: AudioFlanger, - AudioEmitter: AudioEmitter, - AudioPlayer: AudioPlayer, - AudioReverb: AudioReverb, - AudioFilter: AudioFilter, - ArcHandles: ArcHandles, - AudioFader: AudioFader, - AudioEcho: AudioEcho, - AdGui: AdGui, - BoxHandleAdornment: BoxHandleAdornment, - BillboardGui: BillboardGui, - BlurEffect: BlurEffect, - CylinderHandleAdornment: CylinderHandleAdornment, - ConeHandleAdornment: ConeHandleAdornment, - CanvasGroup: CanvasGroup, - Camera: Camera, - DialogChoice: DialogChoice, - DragDetector: DragDetector, - Dialog: Dialog, - Folder: Folder, - Frame: Frame, - Highlight: Highlight, - Handles: Handles, - ImageHandLeAdornment: ImageHandleAdornment, - ImageButton: ImageButton, - ImageLabel: ImageLabel, - LineHandleAdornment: LineHandleAdornment, - ProximityPrompt: ProximityPrompt, - Path2D: Path2D, - Part: Part, - SphereHandLeAdornment: SphereHandleAdornment, - SelectionSphere: SelectionSphere, - ScrollingFrame: ScrollingFrame, - SelectionBox: SelectionBox, - StyleDerive: StyleDerive, - StyleQuery: StyleQuery, - SurfaceGui: SurfaceGui, - StyleSheet: StyleSheet, - SoundGroup: SoundGroup, - StyleLink: StyleLink, - ScreenGui: ScreenGui, - StyleBase: StyleBase, - StyleRule: StyleRule, - Sound: Sound, - TextButton: TextButton, - TextLabel: TextLabel, - TextBox: TextBox, - UIAspectRatioConstraint: UIAspectRatioConstraint, - UITextSizeConstraint: UITextSizeConstraint, - UISizeConstraint: UISizeConstraint, - UIDragDetector: UIDragDetector, - UITableLayout: UITableLayout, - UIPageLayout: UIPageLayout, - UIGridLayout: UIGridLayout, - UIListLayout: UIListLayout, - UIGradient: UIGradient, - UIFlexItem: UIFlexItem, - UIPadding: UIPadding, - UIStroke: UIStroke, - UICorner: UICorner, - UIShadow: UIShadow, - UIScale: UIScale, - ViewportFrame: ViewportFrame, - VideoDisplay: VideoDisplay, - VideoFrame: VideoFrame, - WireframeHandleAdornment: WireframeHandleAdornment, - WorldModel: WorldModel, - Wire: Wire, -} - -type instance = Instance - -type function GetInstance(class_name: type, instances: type): type - if not class_name:is("singleton") then - return instance - end - - return instances:readproperty(class_name) or instance -end - local function try_create_instance(class_name: string): Instance local success, call_result = pcall(Instance.new, class_name) assert(success, call_result) @@ -105,8 +10,8 @@ end --stylua: ignore local function create( - class_name: ClassName | keyof | "" -): (props: types.PropertiesFor>) -> GetInstance + class_name: ClassName | keyof | "" +): (props: types.PropertiesFor) -> types.GetInstance return function(properties) return bind(try_create_instance(class_name), properties) :: any end diff --git a/src/instances/types.luau b/src/instances/types.luau index 0356903..61e5916 100644 --- a/src/instances/types.luau +++ b/src/instances/types.luau @@ -1,5 +1,100 @@ local action = require("./action") +export type Instances = { + PyramidHandleAdornment: PyramidHandleAdornment, + AudioChannelSplitter: AudioChannelSplitter, + AudioPitchShifter: AudioPitchShifter, + AudioDeviceOutput: AudioDeviceOutput, + AudioChannelMixer: AudioChannelMixer, + AudioTextToSpeech: AudioTextToSpeech, + AudioDeviceInput: AudioDeviceInput, + AudioDistortion: AudioDistortion, + AudioCompressor: AudioCompressor, + AudioEqualizer: AudioEqualizer, + AudioAnalyzer: AudioAnalyzer, + AudioListener: AudioListener, + AudioRecorder: AudioRecorder, + AudioLimiter: AudioLimiter, + AudioFlanger: AudioFlanger, + AudioEmitter: AudioEmitter, + AudioPlayer: AudioPlayer, + AudioReverb: AudioReverb, + AudioFilter: AudioFilter, + ArcHandles: ArcHandles, + AudioFader: AudioFader, + AudioEcho: AudioEcho, + AdGui: AdGui, + BoxHandleAdornment: BoxHandleAdornment, + BillboardGui: BillboardGui, + BlurEffect: BlurEffect, + CylinderHandleAdornment: CylinderHandleAdornment, + ConeHandleAdornment: ConeHandleAdornment, + CanvasGroup: CanvasGroup, + Camera: Camera, + DialogChoice: DialogChoice, + DragDetector: DragDetector, + Dialog: Dialog, + Folder: Folder, + Frame: Frame, + Highlight: Highlight, + Handles: Handles, + ImageHandLeAdornment: ImageHandleAdornment, + ImageButton: ImageButton, + ImageLabel: ImageLabel, + LineHandleAdornment: LineHandleAdornment, + ProximityPrompt: ProximityPrompt, + Path2D: Path2D, + Part: Part, + SphereHandLeAdornment: SphereHandleAdornment, + SelectionSphere: SelectionSphere, + ScrollingFrame: ScrollingFrame, + SelectionBox: SelectionBox, + StyleDerive: StyleDerive, + StyleQuery: StyleQuery, + SurfaceGui: SurfaceGui, + StyleSheet: StyleSheet, + SoundGroup: SoundGroup, + StyleLink: StyleLink, + ScreenGui: ScreenGui, + StyleBase: StyleBase, + StyleRule: StyleRule, + Sound: Sound, + TextButton: TextButton, + TextLabel: TextLabel, + TextBox: TextBox, + UIAspectRatioConstraint: UIAspectRatioConstraint, + UITextSizeConstraint: UITextSizeConstraint, + UISizeConstraint: UISizeConstraint, + UIDragDetector: UIDragDetector, + UITableLayout: UITableLayout, + UIPageLayout: UIPageLayout, + UIGridLayout: UIGridLayout, + UIListLayout: UIListLayout, + UIGradient: UIGradient, + UIFlexItem: UIFlexItem, + UIPadding: UIPadding, + UIStroke: UIStroke, + UICorner: UICorner, + UIShadow: UIShadow, + UIScale: UIScale, + ViewportFrame: ViewportFrame, + VideoDisplay: VideoDisplay, + VideoFrame: VideoFrame, + WireframeHandleAdornment: WireframeHandleAdornment, + WorldModel: WorldModel, + Wire: Wire, +} + +type instance = Instance + +export type function GetInstance(class_name: type, instances: type): type + if not class_name:is("singleton") then + return instance + end + + return instances:readproperty(class_name) or instance +end + type UnknownConnectCallback = (...any) -> () type Signal = RBXScriptSignal @@ -49,18 +144,19 @@ type function is_signal(v: type): type? return nil end -type instance = Instance - type Action = action.Identity export type function PropertiesFor(object: type): type - if not object:issubtypeof(instance) then + if object.tag == "singleton" then + object = GetInstance(object, Instances) + elseif not object:issubtypeof(instance) then error("Cannot get properties of a non Instance type") end + local head_table = {} local args_table = { head = head_table } local properties = types.newtable() - local current = object + local current = object :: type local empty_table = {} local read_only_properties = table.freeze({ @@ -75,7 +171,7 @@ export type function PropertiesFor(object: type): type continue end - local value_read = value.read + local value_read = value.read :: type local callback = is_signal(value_read) if callback then From d7f90b90003a7afbb10b73e74dbb421f2e8ede63 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:49:50 -0400 Subject: [PATCH 03/30] format (i hate stylua mandating that requires need to be ascending instead of descending) --- src/init.luau | 4 ++-- src/instances/create.luau | 2 +- src/instances/hydrate.luau | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/init.luau b/src/init.luau index b9de033..33d12ee 100644 --- a/src/init.luau +++ b/src/init.luau @@ -10,6 +10,8 @@ local effect = require("@self/reactive/effect") local for_keys = require("@self/instances/for_keys") local for_values = require("@self/instances/for_values") local graph = require("@self/reactive/graph") +local hydrate = require("@self/instances/hydrate") +local instance_types = require("@self/instances/types") local interval = require("@self/utils/interval") local lerp = require("@self/anim/lerp") local mount = require("@self/instances/mount") @@ -25,8 +27,6 @@ local switch_delay = require("@self/utils/switch_delay") local tags = require("@self/utils/tags") local types = require("@self/reactive/types") local untrack = require("@self/reactive/untrack") -local hydrate = require("@self/instances/hydrate") -local instance_types = require("@self/instances/types") export type UsedAs = types.UsedAs export type Source = types.Source diff --git a/src/instances/create.luau b/src/instances/create.luau index 0613f1b..c7c3e55 100644 --- a/src/instances/create.luau +++ b/src/instances/create.luau @@ -1,5 +1,5 @@ -local types = require("./types") local bind = require("./bind") +local types = require("./types") local function try_create_instance(class_name: string): Instance local success, call_result = pcall(Instance.new, class_name) diff --git a/src/instances/hydrate.luau b/src/instances/hydrate.luau index 80537d3..2ba0acf 100644 --- a/src/instances/hydrate.luau +++ b/src/instances/hydrate.luau @@ -1,5 +1,5 @@ -local types = require("./types") local bind = require("./bind") +local types = require("./types") local function hydrate(instance: Instance): (props: types.PropertiesFor) -> Instance return function(properties) From 97c78a78916df746ff4be23351f4cfcf1998d92c Mon Sep 17 00:00:00 2001 From: nnullcolumn <264514568+nnullcolumn@users.noreply.github.com> Date: Wed, 23 Sep 2026 01:57:22 -0500 Subject: [PATCH 04/30] fix optional value source type errs (#65) --- src/reactive/types.luau | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/reactive/types.luau b/src/reactive/types.luau index 2ef0b0e..3984626 100644 --- a/src/reactive/types.luau +++ b/src/reactive/types.luau @@ -3,7 +3,9 @@ export type Callable = (value: T) -> () export type Effect = (value: T) -> T -export type Source = ((T) -> T) & Readable +-- somewhat misleading but will never produce invalid calls and has +-- less false positive type errors +export type Source = (...T) -> T export type UsedAs = T | Readable From 5b7f4574cbeaa5e9d558cd45ae457e92085e9710 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Wed, 23 Sep 2026 22:38:45 -0400 Subject: [PATCH 05/30] update instances list --- src/instances/types.luau | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/instances/types.luau b/src/instances/types.luau index 61e5916..953db92 100644 --- a/src/instances/types.luau +++ b/src/instances/types.luau @@ -39,10 +39,12 @@ export type Instances = { Highlight: Highlight, Handles: Handles, ImageHandLeAdornment: ImageHandleAdornment, + InputActionLabel: InputActionLabel, ImageButton: ImageButton, ImageLabel: ImageLabel, LineHandleAdornment: LineHandleAdornment, ProximityPrompt: ProximityPrompt, + Path3D: Path3D, Path2D: Path2D, Part: Part, SphereHandLeAdornment: SphereHandleAdornment, @@ -77,6 +79,7 @@ export type Instances = { UICorner: UICorner, UIShadow: UIShadow, UIScale: UIScale, + ViewportCamera: ViewportCamera, ViewportFrame: ViewportFrame, VideoDisplay: VideoDisplay, VideoFrame: VideoFrame, From f05a71c468670bfc63d6bf33fec288e6848791e2 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 13:00:14 -0400 Subject: [PATCH 06/30] add hydrate to docs --- docs/guides/getting-started.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md index 476bd10..b8633e0 100644 --- a/docs/guides/getting-started.md +++ b/docs/guides/getting-started.md @@ -19,6 +19,7 @@ fluid = "ffrostfall/fluid@" # API overview - fluid.create("Frame")({ property = value }) +- fluid.hydrate(Instance.new("Frame"))({ property = value }) - fluid.source() - fluid.async() - fluid.derive() From 4a0f4d531d441f51027e4776bfc49f229e988bda Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:16:19 -0400 Subject: [PATCH 07/30] * update bind to have better types * remove hydrate (its just bind) * export is_signal from the instances types.luau (so it can be used in my style sheet wrapper thingy) * make PropertiesFor accept intsersection types, mainly for use with fake generic constraints * make the properties table start off as an actual table, so each property set doesnt have to go through methods * use readindexers instead of indexers on the table types created by PropertiesFor * remove empty table from PropertiesFor * add a type function for getting an array of read only property indexers (this is so my style sheets wrapper branch doesnt have to duplicate the table) * rename first argument of bind to instance because inst is weird --- docs/guides/getting-started.md | 1 - src/init.luau | 4 +-- src/instances/bind.luau | 25 ++++++++--------- src/instances/hydrate.luau | 10 ------- src/instances/types.luau | 49 ++++++++++++++++++++-------------- 5 files changed, 43 insertions(+), 46 deletions(-) delete mode 100644 src/instances/hydrate.luau diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md index b8633e0..476bd10 100644 --- a/docs/guides/getting-started.md +++ b/docs/guides/getting-started.md @@ -19,7 +19,6 @@ fluid = "ffrostfall/fluid@" # API overview - fluid.create("Frame")({ property = value }) -- fluid.hydrate(Instance.new("Frame"))({ property = value }) - fluid.source() - fluid.async() - fluid.derive() diff --git a/src/init.luau b/src/init.luau index 33d12ee..40eb0a1 100644 --- a/src/init.luau +++ b/src/init.luau @@ -10,7 +10,6 @@ local effect = require("@self/reactive/effect") local for_keys = require("@self/instances/for_keys") local for_values = require("@self/instances/for_values") local graph = require("@self/reactive/graph") -local hydrate = require("@self/instances/hydrate") local instance_types = require("@self/instances/types") local interval = require("@self/utils/interval") local lerp = require("@self/anim/lerp") @@ -31,7 +30,7 @@ local untrack = require("@self/reactive/untrack") export type UsedAs = types.UsedAs export type Source = types.Source export type Action = action.Identity -export type PropertiesFor = instance_types.PropertiesFor +export type PropertiesFor = instance_types.PropertiesFor local scheduler_thread: thread? = nil @@ -61,7 +60,6 @@ end local fluid = {} -fluid.hydrate = hydrate fluid.create = create fluid.mount = mount fluid.tags = tags diff --git a/src/instances/bind.luau b/src/instances/bind.luau index f052a1d..5f480dd 100644 --- a/src/instances/bind.luau +++ b/src/instances/bind.luau @@ -1,6 +1,7 @@ local action = require("./action") local graph = require("../reactive/graph") -local types = require("../reactive/types") +local reactive_types = require("../reactive/types") +local instance_types = require("./types") local function set_property(inst: Instance, property: string, value: any) (inst :: any)[property] = value @@ -10,7 +11,7 @@ local function get_property(inst: Instance, property: string): any return (inst :: any)[property] end -local function bind_property(inst: Instance, property: string, value: types.Readable) +local function bind_property(inst: Instance, property: string, value: reactive_types.Readable) local property_node = graph.create_reactive_node(graph.assert_stable_parent(), function() set_property(inst, property, value()) return nil @@ -101,17 +102,17 @@ local function bind_reactive_child(inst: Instance, func: () -> Result) graph.evaluate_node(property_node) end -local function bind(inst: Instance, props: { [unknown & number]: unknown }) - for key: any, value: any in props do +local function bind(instance: I & Instance, props: instance_types.PropertiesFor): I + for key, value in props :: any do local key_type, value_type = type(key), typeof(value) if key_type == "string" then - local property_value = get_property(inst, key) + local property_value = get_property(instance, key) if typeof(property_value) ~= "RBXScriptSignal" then if value_type == "function" then - bind_property(inst, key, value) + bind_property(instance, key, value) else - set_property(inst, key, value) + set_property(instance, key, value) end elseif value_type == "function" then local connection = property_value:Connect(value) @@ -122,19 +123,19 @@ local function bind(inst: Instance, props: { [unknown & number]: unknown }) end else if value_type == "Instance" then - value.Parent = inst + value.Parent = instance elseif value_type == "table" then if value.__ACTION_SYMBOL == action.symbol then - value.callback(inst) + value.callback(instance) else - bind(inst, value) + bind(instance, value) end elseif value_type == "function" then - bind_reactive_child(inst, value) + bind_reactive_child(instance, value) end end end - return inst + return instance end return bind diff --git a/src/instances/hydrate.luau b/src/instances/hydrate.luau deleted file mode 100644 index 2ba0acf..0000000 --- a/src/instances/hydrate.luau +++ /dev/null @@ -1,10 +0,0 @@ -local bind = require("./bind") -local types = require("./types") - -local function hydrate(instance: Instance): (props: types.PropertiesFor) -> Instance - return function(properties) - return bind(instance, properties) :: any - end -end - -return hydrate diff --git a/src/instances/types.luau b/src/instances/types.luau index 953db92..35cf998 100644 --- a/src/instances/types.luau +++ b/src/instances/types.luau @@ -121,7 +121,7 @@ type function get_connect(v: type): type? return nil end -type function is_signal(v: type): type? +export type function is_signal(v: type): type? if v == Signal and v.tag == "extern" then return UnknownConnectCallback -- luau lsp types RBXScriptSignals as tables @@ -149,24 +149,37 @@ end type Action = action.Identity +export type function get_read_only_instance_properties(): { type } + return table.freeze({ + types.singleton("RobloxLocked"), + types.singleton("ClassName"), + types.singleton("UniqueId"), + }) +end + export type function PropertiesFor(object: type): type + -- support for fake generic constraints ie types like T & Instance + if object.tag == "intersection" then + local components = object:components() + + if #components == 2 then + object = components[1] + else + error("cannot provide an intersection type with more than 2 components to PropertiesFor") + end + end + if object.tag == "singleton" then object = GetInstance(object, Instances) elseif not object:issubtypeof(instance) then error("Cannot get properties of a non Instance type") end + local read_only_properties = get_read_only_instance_properties() local head_table = {} local args_table = { head = head_table } - local properties = types.newtable() + local properties = {} :: { [type]: type } local current = object :: type - local empty_table = {} - - local read_only_properties = table.freeze({ - types.singleton("RobloxLocked"), - types.singleton("ClassName"), - types.singleton("UniqueId"), - }) while current do for property, value in current:properties() do @@ -178,17 +191,14 @@ export type function PropertiesFor(object: type): type local callback = is_signal(value_read) if callback then - properties:setproperty(property, types.optional(callback)) + properties[property] = types.optional(callback) elseif value_read.tag == "function" or value_read.tag == "intersection" then continue elseif value.write then head_table[1] = value_read - properties:setproperty( - property, - types.optional( - types.unionof(types.newfunction(empty_table :: any, args_table :: any), value.write) - ) + properties[property] = types.optional( + types.unionof(types.newfunction(nil, args_table :: any), value.write) ) end end @@ -196,20 +206,19 @@ export type function PropertiesFor(object: type): type current = current:readparent() end + properties = types.newtable(properties) + -- Functions returning a child can return an array of children, or alike functions, nested to any level local function_returns_child = types.newfunction() local child_only_union = types.unionof(function_returns_child, instance) - -- TODO: Use a read only indexer when released to properly accept children which are subtypes of `Instance` - -- TODO: Nesting throws a type error, seemingly a solver bug caused whenever the keys are a union instead of direct type - -- Happens even with a union between `Instance` and `any`, but disappears when it's just `Instance` local nested_table_or_function_or_child = types.newtable() local nested_child_union = types.unionof(child_only_union, nested_table_or_function_or_child) - nested_table_or_function_or_child:setindexer(types.number, nested_child_union) + nested_table_or_function_or_child:setreadindexer(types.number, nested_child_union) function_returns_child:setreturns({ nested_child_union }) local full_union = types.unionof(child_only_union, Action, properties) - properties:setindexer(types.number, types.optional(full_union)) + properties:setreadindexer(types.number, types.optional(full_union)) return properties end From 6a9d0dc770f248465f495a0432c0878dd92284a1 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:18:49 -0400 Subject: [PATCH 08/30] formatting --- src/instances/bind.luau | 4 ++-- src/instances/types.luau | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/instances/bind.luau b/src/instances/bind.luau index 5f480dd..a81cb5b 100644 --- a/src/instances/bind.luau +++ b/src/instances/bind.luau @@ -1,7 +1,7 @@ -local action = require("./action") -local graph = require("../reactive/graph") local reactive_types = require("../reactive/types") +local graph = require("../reactive/graph") local instance_types = require("./types") +local action = require("./action") local function set_property(inst: Instance, property: string, value: any) (inst :: any)[property] = value diff --git a/src/instances/types.luau b/src/instances/types.luau index 35cf998..30b5836 100644 --- a/src/instances/types.luau +++ b/src/instances/types.luau @@ -197,6 +197,7 @@ export type function PropertiesFor(object: type): type elseif value.write then head_table[1] = value_read + --stylua: ignore properties[property] = types.optional( types.unionof(types.newfunction(nil, args_table :: any), value.write) ) From 5b5c01e3d7ff4958185565bbb72be0e6514335c2 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:20:05 -0400 Subject: [PATCH 09/30] appease stylua having the worst require formatting style --- src/instances/bind.luau | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/instances/bind.luau b/src/instances/bind.luau index a81cb5b..c816193 100644 --- a/src/instances/bind.luau +++ b/src/instances/bind.luau @@ -1,7 +1,7 @@ -local reactive_types = require("../reactive/types") +local action = require("./action") local graph = require("../reactive/graph") local instance_types = require("./types") -local action = require("./action") +local reactive_types = require("../reactive/types") local function set_property(inst: Instance, property: string, value: any) (inst :: any)[property] = value From b195e9d7d2b572fb86c482658a49379ba7ec7c33 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:21:33 -0400 Subject: [PATCH 10/30] initial commit --- src/instances/style_sheet.luau | 455 +++++++++++++++++++++++++++++++++ 1 file changed, 455 insertions(+) create mode 100644 src/instances/style_sheet.luau diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau new file mode 100644 index 0000000..928bc48 --- /dev/null +++ b/src/instances/style_sheet.luau @@ -0,0 +1,455 @@ +local action = require("./action") +local cleanup = require("../reactive/cleanup") +local graph = require("../reactive/graph") +local tags = require("../utils/tags") + +export type Transitions = { + Default: TweenInfo?, + [string]: TweenInfo, +} + +type Action = action.Identity +-- Do not name anything `StyleSheet` in this file — it late-binds over Roblox's extern. +type RobloxStyleSheet = StyleSheet +type RobloxGuiObject = GuiObject +type RobloxTweenInfo = TweenInfo +type RobloxSignal = RBXScriptSignal +type RobloxStyleQuery = StyleQuery + +type Instances = { + AdGui: AdGui, + ArcHandles: ArcHandles, + AudioAnalyzer: AudioAnalyzer, + AudioChannelMixer: AudioChannelMixer, + AudioChannelSplitter: AudioChannelSplitter, + AudioCompressor: AudioCompressor, + AudioDeviceInput: AudioDeviceInput, + AudioDeviceOutput: AudioDeviceOutput, + AudioDistortion: AudioDistortion, + AudioEcho: AudioEcho, + AudioEmitter: AudioEmitter, + AudioEqualizer: AudioEqualizer, + AudioFader: AudioFader, + AudioFilter: AudioFilter, + AudioFlanger: AudioFlanger, + AudioLimiter: AudioLimiter, + AudioListener: AudioListener, + AudioPitchShifter: AudioPitchShifter, + AudioPlayer: AudioPlayer, + AudioRecorder: AudioRecorder, + AudioReverb: AudioReverb, + AudioTextToSpeech: AudioTextToSpeech, + BillboardGui: BillboardGui, + BlurEffect: BlurEffect, + BoxHandleAdornment: BoxHandleAdornment, + Camera: Camera, + CanvasGroup: CanvasGroup, + ConeHandleAdornment: ConeHandleAdornment, + CylinderHandleAdornment: CylinderHandleAdornment, + Dialog: Dialog, + DialogChoice: DialogChoice, + DragDetector: DragDetector, + Folder: Folder, + Frame: Frame, + Handles: Handles, + Highlight: Highlight, + ImageButton: ImageButton, + ImageHandleAdornment: ImageHandleAdornment, + ImageLabel: ImageLabel, + InputActionLabel: InputActionLabel, + LineHandleAdornment: LineHandleAdornment, + Part: Part, + Path2D: Path2D, + Path3D: Path3D, + ProximityPrompt: ProximityPrompt, + PyramidHandleAdornment: PyramidHandleAdornment, + ScreenGui: ScreenGui, + ScrollingFrame: ScrollingFrame, + SelectionBox: SelectionBox, + SelectionSphere: SelectionSphere, + Sound: Sound, + SoundGroup: SoundGroup, + SphereHandleAdornment: SphereHandleAdornment, + StyleBase: StyleBase, + StyleDerive: StyleDerive, + StyleLink: StyleLink, + StyleQuery: StyleQuery, + StyleRule: StyleRule, + StyleSheet: RobloxStyleSheet, + SurfaceGui: SurfaceGui, + TextBox: TextBox, + TextButton: TextButton, + TextLabel: TextLabel, + UIAspectRatioConstraint: UIAspectRatioConstraint, + UICorner: UICorner, + UIDragDetector: UIDragDetector, + UIFlexItem: UIFlexItem, + UIGradient: UIGradient, + UIGridLayout: UIGridLayout, + UIListLayout: UIListLayout, + UIPadding: UIPadding, + UIPageLayout: UIPageLayout, + UIScale: UIScale, + UIShadow: UIShadow, + UISizeConstraint: UISizeConstraint, + UIStroke: UIStroke, + UITableLayout: UITableLayout, + UITextSizeConstraint: UITextSizeConstraint, + VideoDisplay: VideoDisplay, + VideoFrame: VideoFrame, + ViewportCamera: ViewportCamera, + ViewportFrame: ViewportFrame, + Wire: Wire, + WireframeHandleAdornment: WireframeHandleAdornment, + WorldModel: WorldModel, +} + +type function WritableProperties(class_type: type): type + local properties = types.newtable() + local current: type? = class_type + local read_only_properties = table.freeze({ + types.singleton("RobloxLocked"), + types.singleton("ClassName"), + types.singleton("UniqueId"), + types.singleton("Parent"), + types.singleton("Name"), + }) + + while current do + for property, value in current:properties() do + if table.find(read_only_properties, property) then + continue + end + + local value_read = value.read + if not value_read or value_read.tag == "function" or value_read.tag == "intersection" then + continue + end + -- Studio exposes signals as externs; luau-lsp uses tables with Connect. + if value_read == RobloxSignal then + continue + end + if value_read:is("table") then + local connect = value_read:readproperty(types.singleton("Connect")) + if connect and connect:is("function") then + continue + end + end + local value_write = value.write + if value_write then + properties:setproperty(property, value_write) + end + end + + current = current:readparent() + end + + return properties +end + +-- Later fields override earlier fields, matching token updates. +export type function Merge(base: type, overrides: type): type + local result = types.newtable() + for _, source in { base, overrides } do + if not source:is("table") then + continue + end + for key, property in source:properties() do + result:setproperty(key, property.read) + end + local indexer = source:indexer() + if indexer then + result:setindexer(indexer.index, indexer.readresult) + end + end + return result +end + +type function TokenRefsFor(tokens: type, property_type: type): type? + if not tokens:is("table") then + return nil + end + + local indexer = tokens:indexer() + if indexer and indexer.readresult:issubtypeof(property_type) then + return types.string + end + + local refs: type? = nil + + for key, property in tokens:properties() do + if not (key:is("singleton") and type(key:value()) == "string") then + continue + end + + local name = key:value() :: string + -- Token table keys are bare names; rule/query values reference them as "$Name". + local token_type = property.read + if not token_type then + continue + end + if token_type:issubtypeof(property_type) then + local reference = types.singleton("$" .. name) + refs = if refs then types.unionof(refs, reference) else reference + end + end + + return refs +end + +type function WithTokenValues(properties: type, tokens: type): type + local result = types.newtable() + + for key, property in properties:properties() do + local value_type = property.read + if not value_type then + continue + end + local token_refs = TokenRefsFor(tokens, value_type) + result:setproperty( + key, + types.optional(if token_refs then types.unionof(value_type, token_refs) else value_type) + ) + end + + return result +end + +type function SubjectClassName(selector: type): type + if not (selector:is("singleton") and type(selector:value()) == "string") then + return types.singleton("") + end + + local selector_text = selector:value() :: string + local subject = selector_text + + for piece in string.gmatch(selector_text, "[^>+~]+") do + local trimmed = string.gsub(piece, "^%s+", "") + trimmed = string.gsub(trimmed, "%s+$", "") + if trimmed ~= "" then + subject = trimmed + end + end + + local component: string? = nil + for name in string.gmatch(subject, "::([%w_]+)") do + component = name + end + if component then + return types.singleton(component) + end + + subject = string.gsub(subject, "::[%w_]+", "") + subject = string.gsub(subject, ":[%w_]+", "") + subject = string.gsub(subject, "@[%w_%-]+", "") + subject = string.gsub(subject, "%.[%w_%-]+", "") + subject = string.gsub(subject, "#[%w_%-]+", "") + subject = string.gsub(subject, "^%s+", "") + subject = string.gsub(subject, "%s+$", "") + + return types.singleton(subject) +end + +export type function TagsFrom(selector: type): type + local result = types.newtable() + if not (selector:is("singleton") and type(selector:value()) == "string") then + return result + end + + local text = selector:value() :: string + for name in string.gmatch(text, "%.([%w_%-]+)") do + result:setproperty(types.singleton(name), types.singleton(true)) + end + return result +end + +type function PropertiesForSelector(selector: type): type + if not (selector:is("singleton") and type(selector:value()) == "string") then + return WritableProperties(RobloxGuiObject) + end + + local text = selector:value() :: string + local properties = types.newtable() + local found = false + + for part in string.gmatch(text .. ",", "([^,]+),") do + local trimmed = string.gsub(part, "^%s+", "") + trimmed = string.gsub(trimmed, "%s+$", "") + if trimmed == "" then + continue + end + + local class_name = SubjectClassName(types.singleton(trimmed)) + local writable = WritableProperties(Instances:readproperty(class_name) or RobloxGuiObject) + -- Flatten selector lists into one property table. An intersection of tables + -- cannot be inspected with :properties() by WithTokenValues. + for key, property in writable:properties() do + local value = property.read + if value then + local previous = properties:readproperty(key) + properties:setproperty( + key, + if previous and previous ~= value then types.intersectionof(previous, value) else value + ) + end + end + found = true + end + + return if found then properties else WritableProperties(RobloxGuiObject) +end + +export type function StyleProperties(selector: type, tokens: type): type + local instance_properties = PropertiesForSelector(selector) + local properties = WithTokenValues(instance_properties, tokens) + local query = WithTokenValues(Merge(WritableProperties(RobloxStyleQuery), instance_properties), tokens) + local queries = types.newtable() + queries:setindexer(types.string, query) + + local transition = types.newtable() + transition:setproperty(types.singleton("Default"), types.optional(RobloxTweenInfo)) + for key in properties:properties() do + transition:setproperty(key, types.optional(RobloxTweenInfo)) + end + + properties:setproperty(types.singleton("Priority"), types.optional(types.number)) + properties:setproperty(types.singleton("Transition"), types.optional(transition)) + properties:setproperty(types.singleton("queries"), types.optional(queries)) + return properties +end + +-- Private type-only metadata carries the state accumulated by fluent calls. +type SheetData = { + instance: RobloxStyleSheet, + _tokens: Tokens, + _tags: Tags, +} + +type TokensOf = index +type TagsOf = index +type TagValue = keyof> | () -> keyof>? + +type TokenState = SheetData, NewTokens>, TagsOf> +type DerivedState = SheetData, TokensOf>, Merge, TagsOf>> +type RuleState = SheetData, Merge, TagsFrom>> + +-- Infer each method's state from Self, delaying property generation until the +-- receiver is known. Keep setmetatable returns inline: a recursive Sheet alias +-- here loses inference in Solver V2. +type SheetPrototype = { + __index: SheetPrototype, + tags: (self: Self, tags: { TagValue }) -> Action, + link: (self: { instance: RobloxStyleSheet }) -> Action, + tokens: ( + self: Self, + tokens: NewTokens + ) -> setmetatable, SheetPrototype>, + derive: (self: Self, from: Other) -> setmetatable, SheetPrototype>, + rule: ( + self: Self, + selector: Selector | "" + ) -> (StyleProperties>) -> setmetatable, SheetPrototype>, +} + +export type Sheet = setmetatable, SheetPrototype> + +local function create_rule(style_sheet: RobloxStyleSheet, selector: string, payload: { [string]: unknown }) + local rule = Instance.new("StyleRule") + rule.Selector = selector + rule.Name = selector + + local properties = {} :: { [string]: unknown } + local queries = payload.queries :: { [string]: { [string]: unknown } } + local transitions = payload.Transition :: { [string]: TweenInfo } + local priority = payload.Priority :: number? + + for key, value in payload do + if key == "Priority" or key == "Transition" or key == "queries" then + continue + end + properties[key] = value + end + + if priority then + rule.Priority = priority + end + rule:SetProperties(properties) + + if transitions then + local default_transition: TweenInfo? = nil + + for prop_name, tween_info_value in transitions do + if string.lower(prop_name) == "default" then + default_transition = tween_info_value + transitions[prop_name] = nil + end + end + + if default_transition then + rule:SetDefaultPropertyTransition(default_transition) + end + rule:SetPropertyTransitions(transitions) + end + + if queries then + for name, definition in queries :: { [string]: { [string]: unknown } } do + local query = Instance.new("StyleQuery") + query:SetConditions(definition) + query.Name = name + query.Parent = rule + end + end + + rule.Parent = style_sheet +end + +type RuntimeSheet = { instance: RobloxStyleSheet } + +local style_sheet_prototype = {} +style_sheet_prototype.__index = style_sheet_prototype + +function style_sheet_prototype.rule(self: RuntimeSheet, selector: string) + return function(payload: { [string]: unknown }) + create_rule(self.instance, selector, payload) + return self + end +end + +function style_sheet_prototype.tokens(self: RuntimeSheet, tokens: { [string]: unknown }) + local instance = self.instance + + for token_name, value in tokens do + instance:SetAttribute(token_name, value) + end + return self +end + +function style_sheet_prototype.derive(self: RuntimeSheet, other: RuntimeSheet) + local instance = self.instance + local derives = self.instance:GetDerives() + table.insert(derives, other.instance) + self.instance:SetDerives(next_derives) + return self +end + +function style_sheet_prototype.tags(_self: RuntimeSheet, selected_tags: { string | () -> string? }) + return tags(selected_tags) +end + +function style_sheet_prototype.link(self: RuntimeSheet) + return action.create(function(instance) + graph.assert_scope() + local link = Instance.new("StyleLink") + link.StyleSheet = self.instance + link.Parent = instance + cleanup(link) + end) +end + +local function style_sheet(): Sheet<{}, {}> + return table.freeze(setmetatable({ + instance = Instance.new("StyleSheet"), + }, style_sheet_prototype)) :: any +end + +return style_sheet From 341945c924371be532fc12050086b275d1e21631 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:26:36 -0400 Subject: [PATCH 11/30] copy over stuff from old stylesheet branch --- .vscode/settings.json | 4 +- src/init.luau | 4 + src/instances/style_sheet_test.luau | 145 ++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+), 3 deletions(-) create mode 100644 src/instances/style_sheet_test.luau diff --git a/.vscode/settings.json b/.vscode/settings.json index 7a4a07c..ffd3578 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -14,9 +14,7 @@ "prettier.useTabs": true, "luau-lsp.completion.imports.stringRequires.enabled": true, - - "luau-lsp.types.definitionFiles": ["types/globals.d.luau"], - + "luau-lsp.sourcemap.autogenerate": false, "luau-lsp.sourcemap.enabled": false, "luau-lsp.sourcemap.includeNonScripts": true, diff --git a/src/init.luau b/src/init.luau index 40eb0a1..140d424 100644 --- a/src/init.luau +++ b/src/init.luau @@ -1,3 +1,4 @@ +local style_sheet = require("@self/instances/style_sheet") local action = require("@self/instances/action") local async = require("@self/reactive/async") local bind = require("@self/instances/bind") @@ -27,6 +28,8 @@ local tags = require("@self/utils/tags") local types = require("@self/reactive/types") local untrack = require("@self/reactive/untrack") +export type StyleSheet = style_sheet.Sheet + export type UsedAs = types.UsedAs export type Source = types.Source export type Action = action.Identity @@ -60,6 +63,7 @@ end local fluid = {} +fluid.style_sheet = style_sheet fluid.create = create fluid.mount = mount fluid.tags = tags diff --git a/src/instances/style_sheet_test.luau b/src/instances/style_sheet_test.luau new file mode 100644 index 0000000..0f7faf0 --- /dev/null +++ b/src/instances/style_sheet_test.luau @@ -0,0 +1,145 @@ +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") + +local fluid = require("../../src") + +local other = fluid.style_sheet():rule("Frame.primary")({ + BackgroundTransparency = 0.5, +}) + +local sheet = fluid.style_sheet() + :tokens({ + BackgroundTween = TweenInfo.new(0.01), + PrimaryTransparency = 0.25, + SelectedTransparency = 0.75, + QueryTransparency = 0.375, + }) + :rule "Frame.primary" { + BackgroundTransparency = "$PrimaryTransparency", + Transition = { + Default = TweenInfo.new(0.01), + BackgroundTransparency = "$BackgroundTween", + }, + } + :rule "Frame.selected" { + BackgroundTransparency = "$SelectedTransparency", + TextSize = 10, -- Extra keys follow normal Luau table behavior. + } + :rule(".rounded::UICorner")({ + CornerRadius = UDim.new(0, 8), + }) + :rule(".phantom::StyleQuery #Wide")({ + MinSize = Vector2.new(400, 0), + }) + :rule(".responsive")({ + queries = { + Wide = { + MinSize = Vector2.new(400, 0), + BackgroundTransparency = "$QueryTransparency", + }, + }, + }) + +sheet:derive(other) + +sheet.instance.Parent = ReplicatedStorage +other.instance.Parent = ReplicatedStorage + +local typed_sheet: fluid.StyleSheet<{ + PrimaryTransparency: number, + SelectedTransparency: number, + QueryTransparency: number, +}, { + primary: true, + selected: true, + rounded: true, + responsive: true, + phantom: true, +}> = + sheet +local current = fluid.source("primary" :: "primary" | "selected" | nil) +local frame = Instance.new("Frame") +local other_frame = Instance.new("Frame") +local responsive_frame = Instance.new("Frame") +responsive_frame.Size = UDim2.fromOffset(200, 100) +local phantom_frame = Instance.new("Frame") +phantom_frame.Size = UDim2.fromOffset(200, 100) +local screen = Instance.new("ScreenGui") +local other_screen = Instance.new("ScreenGui") +frame.Parent = screen +responsive_frame.Parent = screen +phantom_frame.Parent = screen +other_frame.Parent = other_screen +local player_gui = Players.LocalPlayer:WaitForChild("PlayerGui") +screen.Parent = player_gui +other_screen.Parent = player_gui + +local function settle() + fluid.graph.flush_deferred_nodes() + RunService.PreRender:Wait() + RunService.PreRender:Wait() +end + +local destroy = fluid.root(function() + fluid.bind(screen, { typed_sheet:link() }) + fluid.bind(frame, { typed_sheet:tags({ "rounded", current }) }) + fluid.bind(responsive_frame, { typed_sheet:tags({ "responsive" }) }) + fluid.bind(phantom_frame, { typed_sheet:tags({ "phantom" }) }) +end) + +local destroy_other = fluid.root(function() + fluid.bind(other_screen, { other:link() }) + fluid.bind(other_frame, { other:tags({ "primary" }) }) +end) + +settle() + +assert(frame:HasTag("rounded"), "expected rounded tag") +assert(frame:HasTag("primary"), "expected primary tag from source") +assert(not frame:HasTag("selected"), "selected should be inactive") +assert(responsive_frame:HasTag("responsive"), "expected responsive tag") +assert(phantom_frame:HasTag("phantom"), "expected phantom tag") + +assert(frame.BackgroundTransparency == 0.25, `primary transparency {frame.BackgroundTransparency}`) +assert(other_frame.BackgroundTransparency == 0.5, `derived primary {other_frame.BackgroundTransparency}`) + +local corner = frame:FindFirstChildWhichIsA("UICorner") +assert(corner ~= nil and corner:IsA("UICorner"), "expected UICorner from .rounded::UICorner") +assert(corner.CornerRadius == UDim.new(0, 8), "expected CornerRadius") + +current("selected") +settle() +assert(frame:HasTag("selected"), "expected selected tag") +assert(not frame:HasTag("primary"), "primary should clear") +assert(frame.BackgroundTransparency == 0.75, `selected transparency {frame.BackgroundTransparency}`) + +responsive_frame.Size = UDim2.fromOffset(500, 100) +phantom_frame.Size = UDim2.fromOffset(500, 100) +settle() +assert( + responsive_frame.BackgroundTransparency == 0.375, + `responsive query transparency {responsive_frame.BackgroundTransparency}` +) +assert( + phantom_frame.BackgroundTransparency == 0.375, + `phantom query transparency {phantom_frame.BackgroundTransparency}` +) + +local style_link = screen:FindFirstChildWhichIsA("StyleLink") +local other_link = other_screen:FindFirstChildWhichIsA("StyleLink") +assert(style_link ~= nil, "expected StyleLink on screen") +assert(other_link ~= nil, "expected StyleLink on other_screen") +assert(style_link.StyleSheet == sheet.instance, "StyleLink should point at sheet") +assert(other_link.StyleSheet == other.instance, "other StyleLink should point at other") + +destroy() +destroy_other() +settle() + +assert(style_link.Parent == nil, "StyleLink cleaned up") +assert(other_link.Parent == nil, "other StyleLink cleaned up") +assert(not frame:HasTag("rounded"), "tags cleaned up") +assert(not frame:HasTag("selected"), "selected cleaned up") + +print("style_sheet.client ok") From 154fc009113ea48d7a79c2271ec6b9f151834eb5 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:27:53 -0400 Subject: [PATCH 12/30] sync --- src/instances/style_sheet.luau | 89 +--------------------------------- 1 file changed, 2 insertions(+), 87 deletions(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 928bc48..e0c66de 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -2,6 +2,7 @@ local action = require("./action") local cleanup = require("../reactive/cleanup") local graph = require("../reactive/graph") local tags = require("../utils/tags") +local instance_types = require("./types") export type Transitions = { Default: TweenInfo?, @@ -16,93 +17,7 @@ type RobloxTweenInfo = TweenInfo type RobloxSignal = RBXScriptSignal type RobloxStyleQuery = StyleQuery -type Instances = { - AdGui: AdGui, - ArcHandles: ArcHandles, - AudioAnalyzer: AudioAnalyzer, - AudioChannelMixer: AudioChannelMixer, - AudioChannelSplitter: AudioChannelSplitter, - AudioCompressor: AudioCompressor, - AudioDeviceInput: AudioDeviceInput, - AudioDeviceOutput: AudioDeviceOutput, - AudioDistortion: AudioDistortion, - AudioEcho: AudioEcho, - AudioEmitter: AudioEmitter, - AudioEqualizer: AudioEqualizer, - AudioFader: AudioFader, - AudioFilter: AudioFilter, - AudioFlanger: AudioFlanger, - AudioLimiter: AudioLimiter, - AudioListener: AudioListener, - AudioPitchShifter: AudioPitchShifter, - AudioPlayer: AudioPlayer, - AudioRecorder: AudioRecorder, - AudioReverb: AudioReverb, - AudioTextToSpeech: AudioTextToSpeech, - BillboardGui: BillboardGui, - BlurEffect: BlurEffect, - BoxHandleAdornment: BoxHandleAdornment, - Camera: Camera, - CanvasGroup: CanvasGroup, - ConeHandleAdornment: ConeHandleAdornment, - CylinderHandleAdornment: CylinderHandleAdornment, - Dialog: Dialog, - DialogChoice: DialogChoice, - DragDetector: DragDetector, - Folder: Folder, - Frame: Frame, - Handles: Handles, - Highlight: Highlight, - ImageButton: ImageButton, - ImageHandleAdornment: ImageHandleAdornment, - ImageLabel: ImageLabel, - InputActionLabel: InputActionLabel, - LineHandleAdornment: LineHandleAdornment, - Part: Part, - Path2D: Path2D, - Path3D: Path3D, - ProximityPrompt: ProximityPrompt, - PyramidHandleAdornment: PyramidHandleAdornment, - ScreenGui: ScreenGui, - ScrollingFrame: ScrollingFrame, - SelectionBox: SelectionBox, - SelectionSphere: SelectionSphere, - Sound: Sound, - SoundGroup: SoundGroup, - SphereHandleAdornment: SphereHandleAdornment, - StyleBase: StyleBase, - StyleDerive: StyleDerive, - StyleLink: StyleLink, - StyleQuery: StyleQuery, - StyleRule: StyleRule, - StyleSheet: RobloxStyleSheet, - SurfaceGui: SurfaceGui, - TextBox: TextBox, - TextButton: TextButton, - TextLabel: TextLabel, - UIAspectRatioConstraint: UIAspectRatioConstraint, - UICorner: UICorner, - UIDragDetector: UIDragDetector, - UIFlexItem: UIFlexItem, - UIGradient: UIGradient, - UIGridLayout: UIGridLayout, - UIListLayout: UIListLayout, - UIPadding: UIPadding, - UIPageLayout: UIPageLayout, - UIScale: UIScale, - UIShadow: UIShadow, - UISizeConstraint: UISizeConstraint, - UIStroke: UIStroke, - UITableLayout: UITableLayout, - UITextSizeConstraint: UITextSizeConstraint, - VideoDisplay: VideoDisplay, - VideoFrame: VideoFrame, - ViewportCamera: ViewportCamera, - ViewportFrame: ViewportFrame, - Wire: Wire, - WireframeHandleAdornment: WireframeHandleAdornment, - WorldModel: WorldModel, -} + type function WritableProperties(class_type: type): type local properties = types.newtable() From 403c63237a36632f0479efb664968782bf11af5b Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 17:54:50 -0400 Subject: [PATCH 13/30] Finalize style sheet wrapper * add style_sheet:underive() * add style_sheet:pseudo() * properly type style queries (i was stupid!!!) --- src/init.luau | 5 +- src/instances/style_sheet.luau | 555 +++++++++++++++++----------- src/instances/style_sheet_test.luau | 145 -------- 3 files changed, 332 insertions(+), 373 deletions(-) delete mode 100644 src/instances/style_sheet_test.luau diff --git a/src/init.luau b/src/init.luau index 140d424..b8b820c 100644 --- a/src/init.luau +++ b/src/init.luau @@ -1,4 +1,3 @@ -local style_sheet = require("@self/instances/style_sheet") local action = require("@self/instances/action") local async = require("@self/reactive/async") local bind = require("@self/instances/bind") @@ -22,14 +21,14 @@ local show = require("@self/utils/show") local show_delay = require("@self/utils/show_delay") local source = require("@self/reactive/source") local spring = require("@self/anim/spring/spring_file") +local style_sheet = require("@self/instances/style_sheet") local switch = require("@self/utils/switch") local switch_delay = require("@self/utils/switch_delay") local tags = require("@self/utils/tags") local types = require("@self/reactive/types") local untrack = require("@self/reactive/untrack") -export type StyleSheet = style_sheet.Sheet - +export type StyleSheet = style_sheet.Sheet export type UsedAs = types.UsedAs export type Source = types.Source export type Action = action.Identity diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index e0c66de..19d7859 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -1,333 +1,408 @@ local action = require("./action") local cleanup = require("../reactive/cleanup") local graph = require("../reactive/graph") -local tags = require("../utils/tags") local instance_types = require("./types") - -export type Transitions = { - Default: TweenInfo?, - [string]: TweenInfo, -} +local tags = require("../utils/tags") type Action = action.Identity +type Instances = instance_types.Instances -- Do not name anything `StyleSheet` in this file — it late-binds over Roblox's extern. type RobloxStyleSheet = StyleSheet type RobloxGuiObject = GuiObject +type RobloxInstance = Instance type RobloxTweenInfo = TweenInfo type RobloxSignal = RBXScriptSignal type RobloxStyleQuery = StyleQuery +type RuntimeSheet = { read instance: RobloxStyleSheet } + +-- `::StyleQuery` pseudo-instances take their conditions as properties, which StyleQuery doesn't declare. +type QueryConditions = { + AspectRatioRange: NumberRange, + MaxSize: Vector2, + MinSize: Vector2, + PreferredInput: Enum.PreferredInput, + PreferredTextSize: Enum.PreferredTextSize, + ReducedMotionEnabled: boolean, + ViewportDisplaySize: Enum.DisplaySize, +} +-- Queries Roblox always provides, named by a condition followed by its value. +type BuiltInQueries = { + PreferredInputKeyboardAndMouse: true, + PreferredInputGamepad: true, + PreferredInputTouch: true, + PreferredInputMicroGamepad: true, + ViewportDisplaySizeSmall: true, + ViewportDisplaySizeMedium: true, + ViewportDisplaySizeLarge: true, + PreferredTextSizeMedium: true, + PreferredTextSizeLarge: true, + PreferredTextSizeLarger: true, + PreferredTextSizeLargest: true, + ReducedMotionEnabledTrue: true, + ReducedMotionEnabledFalse: true, +} -type function WritableProperties(class_type: type): type - local properties = types.newtable() - local current: type? = class_type - local read_only_properties = table.freeze({ - types.singleton("RobloxLocked"), - types.singleton("ClassName"), - types.singleton("UniqueId"), - types.singleton("Parent"), - types.singleton("Name"), - }) - - while current do - for property, value in current:properties() do - if table.find(read_only_properties, property) then - continue - end +type Props = { + _transitions: { [string]: TweenInfo | string }?, + _queries: { [string]: Props }?, + _priority: number?, + [string | number]: PseudoInstance, +} - local value_read = value.read - if not value_read or value_read.tag == "function" or value_read.tag == "intersection" then - continue - end - -- Studio exposes signals as externs; luau-lsp uses tables with Connect. - if value_read == RobloxSignal then - continue - end - if value_read:is("table") then - local connect = value_read:readproperty(types.singleton("Connect")) - if connect and connect:is("function") then - continue - end - end - local value_write = value.write - if value_write then - properties:setproperty(property, value_write) - end - end +-- Made by `:pseudo`, styles a pseudo-instance from the array part of a rule. +export type PseudoInstance = { + read selector: string, + read props: Props, +} - current = current:readparent() +type function VALIDATE_STRINGLETON(s: type, string_type: string): type + if not (s.tag == "singleton" and type(s:value()) == "string") then + error(`{string_type} provided is not a string singleton`, 2) + elseif s:value() == "" then + error(`{string_type} provided can't be an empty string singleton`, 2) end - - return properties + return s end -- Later fields override earlier fields, matching token updates. -export type function Merge(base: type, overrides: type): type - local result = types.newtable() - for _, source in { base, overrides } do - if not source:is("table") then - continue - end +type function Merge(base: type, overrides: type): type + local properties = {} :: { [type]: type } + local keys = {} :: { [string]: type } + local source = base + + for index = 1, 2 do for key, property in source:properties() do - result:setproperty(key, property.read) - end - local indexer = source:indexer() - if indexer then - result:setindexer(indexer.index, indexer.readresult) + local name = key:value() :: string + local previous = keys[name] + + if previous then + properties[previous] = nil + end + + properties[key] = property.read + keys[name] = key end + source = overrides end - return result + + return types.newtable(properties, overrides:indexer() or source:indexer()) end -type function TokenRefsFor(tokens: type, property_type: type): type? +-- Maps each token type to a union of the "$Name" refs for every token of that type. +-- Equal types aren't the same userdata, so types are keyed by how they print. +type function TokenRefs(tokens: type): { [string]: type } + local refs = {} :: { [string]: type } if not tokens:is("table") then - return nil + return refs end - local indexer = tokens:indexer() - if indexer and indexer.readresult:issubtypeof(property_type) then - return types.string - end - - local refs: type? = nil - for key, property in tokens:properties() do - if not (key:is("singleton") and type(key:value()) == "string") then - continue - end - - local name = key:value() :: string - -- Token table keys are bare names; rule/query values reference them as "$Name". local token_type = property.read - if not token_type then - continue - end - if token_type:issubtypeof(property_type) then - local reference = types.singleton("$" .. name) - refs = if refs then types.unionof(refs, reference) else reference + if token_type then + local type_name = tostring(token_type) + local reference = types.singleton("$" .. (key:value() :: string)) + local existing = refs[type_name] + refs[type_name] = if existing then types.unionof(existing, reference) else reference end end + -- Token tables with an indexer can have any name. + local indexer = tokens:indexer() + if indexer then + refs[tostring(indexer.readresult)] = types.string + end + return refs end -type function WithTokenValues(properties: type, tokens: type): type - local result = types.newtable() - - for key, property in properties:properties() do - local value_type = property.read - if not value_type then - continue - end - local token_refs = TokenRefsFor(tokens, value_type) - result:setproperty( - key, - types.optional(if token_refs then types.unionof(value_type, token_refs) else value_type) - ) - end - - return result +type function StyleValue(value: type, refs: { [string]: type }): type + local value_refs = refs[tostring(value)] + return types.optional(if value_refs then types.unionof(value, value_refs) else value) end -type function SubjectClassName(selector: type): type +-- One instance type per comma separated selector: the last compound's `::` pseudo-instance, else its class. +-- Selectors without a known class style GuiObjects. +type function SelectorInstances(selector: type): { type } if not (selector:is("singleton") and type(selector:value()) == "string") then - return types.singleton("") + return { RobloxGuiObject } end - local selector_text = selector:value() :: string - local subject = selector_text + local instances = {} :: { type } + + for part in string.gmatch(selector:value() :: string, "[^,]+") do + -- Only the compound after the last `>` / `>>` combinator gets styled. + local compound = string.match(part, "[^>]*$") :: string + local class_name = string.match(compound, "^%s*([%a_][%w_]*)") - for piece in string.gmatch(selector_text, "[^>+~]+") do - local trimmed = string.gsub(piece, "^%s+", "") - trimmed = string.gsub(trimmed, "%s+$", "") - if trimmed ~= "" then - subject = trimmed + for pseudo_instance in string.gmatch(compound, "::%s*([%a_][%w_]*)") do + class_name = pseudo_instance end - end - local component: string? = nil - for name in string.gmatch(subject, "::([%w_]+)") do - component = name + local instance = if class_name then Instances:readproperty(types.singleton(class_name)) else nil + table.insert(instances, instance or RobloxGuiObject) end - if component then - return types.singleton(component) - end - - subject = string.gsub(subject, "::[%w_]+", "") - subject = string.gsub(subject, ":[%w_]+", "") - subject = string.gsub(subject, "@[%w_%-]+", "") - subject = string.gsub(subject, "%.[%w_%-]+", "") - subject = string.gsub(subject, "#[%w_%-]+", "") - subject = string.gsub(subject, "^%s+", "") - subject = string.gsub(subject, "%s+$", "") - return types.singleton(subject) + return if #instances > 0 then instances else { RobloxGuiObject } end -export type function TagsFrom(selector: type): type - local result = types.newtable() - if not (selector:is("singleton") and type(selector:value()) == "string") then - return result - end +-- Options are `_` prefixed so they can never collide with Roblox property names. +type function StyleProperties(selector: type, tokens: type, queries: type): type + local selector_value = VALIDATE_STRINGLETON(selector, "selector"):value() :: string + local read_only_properties = table.freeze({ + types.singleton("RobloxLocked"), + types.singleton("ClassName"), + types.singleton("UniqueId"), + }) - local text = selector:value() :: string - for name in string.gmatch(text, "%.([%w_%-]+)") do - result:setproperty(types.singleton(name), types.singleton(true)) + -- Every query that `@Name` selectors and `_queries` can use: the built-ins, plus ones added with `:query`. + local query_keys = {} :: { [string]: type } + local source = BuiltInQueries + for i = 1, 2 do + for key in source:properties() do + query_keys[key:value() :: string] = key + end + source = queries end - return result -end -type function PropertiesForSelector(selector: type): type - if not (selector:is("singleton") and type(selector:value()) == "string") then - return WritableProperties(RobloxGuiObject) + for name in string.gmatch(selector_value, "@([%w_%-]+)") do + if not query_keys[name] then + error(`unknown query @{name}, add it with :query()`) + end end - local text = selector:value() :: string - local properties = types.newtable() - local found = false + -- Rules can't reference instances, so Parent and other instance properties are left out. + local instance_value = types.optional(RobloxInstance) + local instance_values = {} :: { [string]: boolean } + -- Selector lists merge properties by name, intersecting the value types they share. + local keys = {} :: { [string]: type } + local values = {} :: { [string]: type } + + local function add(property: type, value: type) + local name = property:value() :: string + local previous = values[name] + if not previous then + keys[name] = property + values[name] = value + elseif previous ~= value then + values[name] = types.intersectionof(previous, value) + end + end - for part in string.gmatch(text .. ",", "([^,]+),") do - local trimmed = string.gsub(part, "^%s+", "") - trimmed = string.gsub(trimmed, "%s+$", "") - if trimmed == "" then - continue + for _, instance in SelectorInstances(selector) do + if instance == RobloxStyleQuery then + for property, condition in QueryConditions:properties() do + add(property, condition.read :: type) + end end - local class_name = SubjectClassName(types.singleton(trimmed)) - local writable = WritableProperties(Instances:readproperty(class_name) or RobloxGuiObject) - -- Flatten selector lists into one property table. An intersection of tables - -- cannot be inspected with :properties() by WithTokenValues. - for key, property in writable:properties() do - local value = property.read - if value then - local previous = properties:readproperty(key) - properties:setproperty( - key, - if previous and previous ~= value then types.intersectionof(previous, value) else value - ) + local current: type? = instance + + while current do + for property, value in current:properties() do + local value_write = value.write + local value_read = value.read + + if + not value_read + or not value_write + or value_read.tag == "function" + or value_read.tag == "intersection" + or value_read == RobloxSignal + or table.find(read_only_properties, property) + then + continue + end + + -- ignoring luau-lsp RBXScriptSignals, because luau-lsp uses table types for RBXScriptSignals + if value_read:is("table") then + local connect = value_read:readproperty(types.singleton("Connect")) + if connect and connect:is("function") then + continue + end + end + + local value_name = tostring(value_write) + local is_instance = instance_values[value_name] + + if is_instance == nil then + is_instance = value_write:issubtypeof(instance_value) + instance_values[value_name] = is_instance + end + + if not is_instance then + add(property, value_write) + end end + + current = current:readparent() end - found = true end - return if found then properties else WritableProperties(RobloxGuiObject) + local refs = TokenRefs(tokens) + local transition = StyleValue(RobloxTweenInfo, refs) + local transitions = {} + local style = {} + + for name, key in keys do + style[key] = StyleValue(values[name], refs) + transitions[key] = transition + end + + transitions[types.singleton("_default")] = transition + style[types.singleton("_priority")] = types.optional(types.number) + style[types.singleton("_transitions")] = types.optional(types.newtable(transitions)) + + -- pseudo-instances go in the array part, like instance children in the props table of fluid.bind + local props = + types.newtable(style, { index = types.number, readresult = PseudoInstance, writeresult = PseudoInstance }) + + -- `_queries` has a key for every query, holding the props of a nested `@Name` rule that applies while the + -- query is active. A nested rule takes the same props as this one, `_queries` included, so the props table + -- has to exist before `_queries` can point back at it. + local query_rule = types.optional(props) + local query_rules = {} :: { [type]: type } + + for _, key in query_keys do + query_rules[key] = query_rule + end + + props:setproperty(types.singleton("_queries"), types.optional(types.newtable(query_rules))) + return props end -export type function StyleProperties(selector: type, tokens: type): type - local instance_properties = PropertiesForSelector(selector) - local properties = WithTokenValues(instance_properties, tokens) - local query = WithTokenValues(Merge(WritableProperties(RobloxStyleQuery), instance_properties), tokens) - local queries = types.newtable() - queries:setindexer(types.string, query) - - local transition = types.newtable() - transition:setproperty(types.singleton("Default"), types.optional(RobloxTweenInfo)) - for key in properties:properties() do - transition:setproperty(key, types.optional(RobloxTweenInfo)) +type function QueryConditionValues(tokens: type): type + local refs = TokenRefs(tokens) + local conditions = {} + + for key, condition in QueryConditions:properties() do + conditions[key] = StyleValue(condition.read :: type, refs) end + return types.newtable(conditions) +end + +type function TagsFrom(selector: type): type + selector = VALIDATE_STRINGLETON(selector, "selector") + local true_singleton = types.singleton(true) + local tags = {} :: { [type]: type } - properties:setproperty(types.singleton("Priority"), types.optional(types.number)) - properties:setproperty(types.singleton("Transition"), types.optional(transition)) - properties:setproperty(types.singleton("queries"), types.optional(queries)) - return properties + for name in string.gmatch(selector:value() :: string, "%.([%w_%-]+)") do + tags[types.singleton(name)] = true_singleton + end + return types.newtable(tags) end --- Private type-only metadata carries the state accumulated by fluent calls. -type SheetData = { - instance: RobloxStyleSheet, - _tokens: Tokens, - _tags: Tags, +type function QueryFrom(name: type): type + name = VALIDATE_STRINGLETON(name, "query name") + return types.newtable({ [name] = types.singleton(true) }) +end + +type function PseudoSelector(selector: type): type + selector = VALIDATE_STRINGLETON(selector, "pseudo-instance selector") + return types.singleton("::" .. (selector:value() :: string)) +end + +type SheetData = { + read instance: RobloxStyleSheet, + read __I_DO_NOT_EXIST_AT_RUNTIME: { + read queries: Queries, + read tokens: Tokens, + read tags: Tags, + }, } -type TokensOf = index -type TagsOf = index +type TypeOnly = index +type TokensOf = index, "tokens"> +type TagsOf = index, "tags"> +type QueriesOf = index, "queries"> type TagValue = keyof> | () -> keyof>? -type TokenState = SheetData, NewTokens>, TagsOf> -type DerivedState = SheetData, TokensOf>, Merge, TagsOf>> -type RuleState = SheetData, Merge, TagsFrom>> +type TokenState = SheetData, NewTokens>, TagsOf, QueriesOf> +type QueryState = SheetData, TagsOf, Merge, QueryFrom>> +type DerivedState = SheetData< + Merge, TokensOf>, + Merge, TagsOf>, + Merge, QueriesOf> +> +type RuleState = SheetData, Merge, TagsFrom>, QueriesOf> --- Infer each method's state from Self, delaying property generation until the --- receiver is known. Keep setmetatable returns inline: a recursive Sheet alias --- here loses inference in Solver V2. +-- string generics are unioned with "" because otherwise luau widens them to `string`, type SheetPrototype = { __index: SheetPrototype, tags: (self: Self, tags: { TagValue }) -> Action, - link: (self: { instance: RobloxStyleSheet }) -> Action, + link: (self: RuntimeSheet) -> Action, tokens: ( self: Self, tokens: NewTokens ) -> setmetatable, SheetPrototype>, + query: ( + self: Self, + name: Name | "" + ) -> (QueryConditionValues>) -> setmetatable, SheetPrototype>, derive: (self: Self, from: Other) -> setmetatable, SheetPrototype>, + -- Keeps the sheet's type, it's meant for swapping between sheets with the same tokens, like themes. + underive: (self: Self, from: RuntimeSheet) -> Self, + pseudo: ( + self: Self, + selector: Selector | "" + ) -> (StyleProperties, TokensOf, QueriesOf>) -> PseudoInstance, rule: ( self: Self, selector: Selector | "" - ) -> (StyleProperties>) -> setmetatable, SheetPrototype>, + ) -> ( + StyleProperties, QueriesOf> + ) -> setmetatable, SheetPrototype>, } -export type Sheet = setmetatable, SheetPrototype> +export type Sheet = setmetatable, SheetPrototype> -local function create_rule(style_sheet: RobloxStyleSheet, selector: string, payload: { [string]: unknown }) +local function create_rule(parent: Instance, selector: string, props: Props) local rule = Instance.new("StyleRule") rule.Selector = selector rule.Name = selector - local properties = {} :: { [string]: unknown } - local queries = payload.queries :: { [string]: { [string]: unknown } } - local transitions = payload.Transition :: { [string]: TweenInfo } - local priority = payload.Priority :: number? - - for key, value in payload do - if key == "Priority" or key == "Transition" or key == "queries" then - continue - end - properties[key] = value - end - + local priority = props._priority if priority then rule.Priority = priority + props._priority = nil end - rule:SetProperties(properties) + local transitions = props._transitions if transitions then - local default_transition: TweenInfo? = nil + local default = transitions._default - for prop_name, tween_info_value in transitions do - if string.lower(prop_name) == "default" then - default_transition = tween_info_value - transitions[prop_name] = nil - end + if default then + rule:SetDefaultPropertyTransition(default) + transitions._default = nil end - if default_transition then - rule:SetDefaultPropertyTransition(default_transition) + for property, transition in transitions do + rule:SetPropertyTransition(property, transition) end - rule:SetPropertyTransitions(transitions) end + local queries = props._queries if queries then - for name, definition in queries :: { [string]: { [string]: unknown } } do - local query = Instance.new("StyleQuery") - query:SetConditions(definition) - query.Name = name - query.Parent = rule + for name, query_props in queries do + create_rule(rule, "@" .. name, query_props) end + props._queries = nil end - rule.Parent = style_sheet -end + for index, pseudo in ipairs(props :: any) do + create_rule(rule, pseudo.selector, pseudo.props) + end -type RuntimeSheet = { instance: RobloxStyleSheet } + rule:SetProperties(props) + rule.Parent = parent +end local style_sheet_prototype = {} style_sheet_prototype.__index = style_sheet_prototype -function style_sheet_prototype.rule(self: RuntimeSheet, selector: string) - return function(payload: { [string]: unknown }) - create_rule(self.instance, selector, payload) - return self - end +function style_sheet_prototype.tags(_self: RuntimeSheet, selected_tags: { string | () -> string? }) + return tags(selected_tags) end function style_sheet_prototype.tokens(self: RuntimeSheet, tokens: { [string]: unknown }) @@ -339,16 +414,46 @@ function style_sheet_prototype.tokens(self: RuntimeSheet, tokens: { [string]: un return self end +function style_sheet_prototype.rule(self: RuntimeSheet, selector: string) + return function(props: Props) + create_rule(self.instance, selector, props) + return self + end +end + +function style_sheet_prototype.pseudo(_self: RuntimeSheet, selector: string) + return function(props: Props): PseudoInstance + return { selector = "::" .. selector, props = props } + end +end + +function style_sheet_prototype.query(self: RuntimeSheet, name: string) + return function(conditions: Props) + -- A StyleQuery only activates under the instance it checks, so every GuiObject gets it as a pseudo-instance. + create_rule(self.instance, `GuiObject::StyleQuery`, conditions) + return self + end +end + function style_sheet_prototype.derive(self: RuntimeSheet, other: RuntimeSheet) local instance = self.instance - local derives = self.instance:GetDerives() + local derives = instance:GetDerives() table.insert(derives, other.instance) - self.instance:SetDerives(next_derives) + instance:SetDerives(derives) return self end -function style_sheet_prototype.tags(_self: RuntimeSheet, selected_tags: { string | () -> string? }) - return tags(selected_tags) +function style_sheet_prototype.underive(self: RuntimeSheet, other: RuntimeSheet) + local instance = self.instance + local derives = instance:GetDerives() + local index = table.find(derives, other.instance) + local total_derives = #derives + + if index then + derives[index], derives[total_derives] = derives[total_derives], nil + instance:SetDerives(derives) + end + return self end function style_sheet_prototype.link(self: RuntimeSheet) @@ -361,7 +466,7 @@ function style_sheet_prototype.link(self: RuntimeSheet) end) end -local function style_sheet(): Sheet<{}, {}> +local function style_sheet(): Sheet<{}, {}, {}> return table.freeze(setmetatable({ instance = Instance.new("StyleSheet"), }, style_sheet_prototype)) :: any diff --git a/src/instances/style_sheet_test.luau b/src/instances/style_sheet_test.luau deleted file mode 100644 index 0f7faf0..0000000 --- a/src/instances/style_sheet_test.luau +++ /dev/null @@ -1,145 +0,0 @@ -local Players = game:GetService("Players") -local ReplicatedStorage = game:GetService("ReplicatedStorage") -local RunService = game:GetService("RunService") - -local fluid = require("../../src") - -local other = fluid.style_sheet():rule("Frame.primary")({ - BackgroundTransparency = 0.5, -}) - -local sheet = fluid.style_sheet() - :tokens({ - BackgroundTween = TweenInfo.new(0.01), - PrimaryTransparency = 0.25, - SelectedTransparency = 0.75, - QueryTransparency = 0.375, - }) - :rule "Frame.primary" { - BackgroundTransparency = "$PrimaryTransparency", - Transition = { - Default = TweenInfo.new(0.01), - BackgroundTransparency = "$BackgroundTween", - }, - } - :rule "Frame.selected" { - BackgroundTransparency = "$SelectedTransparency", - TextSize = 10, -- Extra keys follow normal Luau table behavior. - } - :rule(".rounded::UICorner")({ - CornerRadius = UDim.new(0, 8), - }) - :rule(".phantom::StyleQuery #Wide")({ - MinSize = Vector2.new(400, 0), - }) - :rule(".responsive")({ - queries = { - Wide = { - MinSize = Vector2.new(400, 0), - BackgroundTransparency = "$QueryTransparency", - }, - }, - }) - -sheet:derive(other) - -sheet.instance.Parent = ReplicatedStorage -other.instance.Parent = ReplicatedStorage - -local typed_sheet: fluid.StyleSheet<{ - PrimaryTransparency: number, - SelectedTransparency: number, - QueryTransparency: number, -}, { - primary: true, - selected: true, - rounded: true, - responsive: true, - phantom: true, -}> = - sheet -local current = fluid.source("primary" :: "primary" | "selected" | nil) -local frame = Instance.new("Frame") -local other_frame = Instance.new("Frame") -local responsive_frame = Instance.new("Frame") -responsive_frame.Size = UDim2.fromOffset(200, 100) -local phantom_frame = Instance.new("Frame") -phantom_frame.Size = UDim2.fromOffset(200, 100) -local screen = Instance.new("ScreenGui") -local other_screen = Instance.new("ScreenGui") -frame.Parent = screen -responsive_frame.Parent = screen -phantom_frame.Parent = screen -other_frame.Parent = other_screen -local player_gui = Players.LocalPlayer:WaitForChild("PlayerGui") -screen.Parent = player_gui -other_screen.Parent = player_gui - -local function settle() - fluid.graph.flush_deferred_nodes() - RunService.PreRender:Wait() - RunService.PreRender:Wait() -end - -local destroy = fluid.root(function() - fluid.bind(screen, { typed_sheet:link() }) - fluid.bind(frame, { typed_sheet:tags({ "rounded", current }) }) - fluid.bind(responsive_frame, { typed_sheet:tags({ "responsive" }) }) - fluid.bind(phantom_frame, { typed_sheet:tags({ "phantom" }) }) -end) - -local destroy_other = fluid.root(function() - fluid.bind(other_screen, { other:link() }) - fluid.bind(other_frame, { other:tags({ "primary" }) }) -end) - -settle() - -assert(frame:HasTag("rounded"), "expected rounded tag") -assert(frame:HasTag("primary"), "expected primary tag from source") -assert(not frame:HasTag("selected"), "selected should be inactive") -assert(responsive_frame:HasTag("responsive"), "expected responsive tag") -assert(phantom_frame:HasTag("phantom"), "expected phantom tag") - -assert(frame.BackgroundTransparency == 0.25, `primary transparency {frame.BackgroundTransparency}`) -assert(other_frame.BackgroundTransparency == 0.5, `derived primary {other_frame.BackgroundTransparency}`) - -local corner = frame:FindFirstChildWhichIsA("UICorner") -assert(corner ~= nil and corner:IsA("UICorner"), "expected UICorner from .rounded::UICorner") -assert(corner.CornerRadius == UDim.new(0, 8), "expected CornerRadius") - -current("selected") -settle() -assert(frame:HasTag("selected"), "expected selected tag") -assert(not frame:HasTag("primary"), "primary should clear") -assert(frame.BackgroundTransparency == 0.75, `selected transparency {frame.BackgroundTransparency}`) - -responsive_frame.Size = UDim2.fromOffset(500, 100) -phantom_frame.Size = UDim2.fromOffset(500, 100) -settle() -assert( - responsive_frame.BackgroundTransparency == 0.375, - `responsive query transparency {responsive_frame.BackgroundTransparency}` -) -assert( - phantom_frame.BackgroundTransparency == 0.375, - `phantom query transparency {phantom_frame.BackgroundTransparency}` -) - -local style_link = screen:FindFirstChildWhichIsA("StyleLink") -local other_link = other_screen:FindFirstChildWhichIsA("StyleLink") -assert(style_link ~= nil, "expected StyleLink on screen") -assert(other_link ~= nil, "expected StyleLink on other_screen") -assert(style_link.StyleSheet == sheet.instance, "StyleLink should point at sheet") -assert(other_link.StyleSheet == other.instance, "other StyleLink should point at other") - -destroy() -destroy_other() -settle() - -assert(style_link.Parent == nil, "StyleLink cleaned up") -assert(other_link.Parent == nil, "other StyleLink cleaned up") -assert(not frame:HasTag("rounded"), "tags cleaned up") -assert(not frame:HasTag("selected"), "selected cleaned up") - -print("style_sheet.client ok") From a8b76fd5cbcbefbfc67d59c0d85668f3f2031908 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 18:02:29 -0400 Subject: [PATCH 14/30] add fluid.style_sheet to API Overview --- docs/guides/getting-started.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md index 476bd10..b196e86 100644 --- a/docs/guides/getting-started.md +++ b/docs/guides/getting-started.md @@ -19,6 +19,7 @@ fluid = "ffrostfall/fluid@" # API overview - fluid.create("Frame")({ property = value }) +- fluid.style_sheet() - fluid.source() - fluid.async() - fluid.derive() From cdc1d1ae891a5bd538ce79099ac00af8da1facba Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 19:04:53 -0400 Subject: [PATCH 15/30] * style_sheet bug fixes * add required name & parent arguments to the constructor * clean up comments * freeze style_sheet prototype table --- src/instances/style_sheet.luau | 67 +++++++++++++++++----------------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 19d7859..0892ef7 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -6,7 +6,6 @@ local tags = require("../utils/tags") type Action = action.Identity type Instances = instance_types.Instances --- Do not name anything `StyleSheet` in this file — it late-binds over Roblox's extern. type RobloxStyleSheet = StyleSheet type RobloxGuiObject = GuiObject type RobloxInstance = Instance @@ -16,7 +15,7 @@ type RobloxStyleQuery = StyleQuery type RuntimeSheet = { read instance: RobloxStyleSheet } --- `::StyleQuery` pseudo-instances take their conditions as properties, which StyleQuery doesn't declare. +-- `::StyleQuery` pseudo-instances take their conditions as properties type QueryConditions = { AspectRatioRange: NumberRange, MaxSize: Vector2, @@ -27,7 +26,6 @@ type QueryConditions = { ViewportDisplaySize: Enum.DisplaySize, } --- Queries Roblox always provides, named by a condition followed by its value. type BuiltInQueries = { PreferredInputKeyboardAndMouse: true, PreferredInputGamepad: true, @@ -51,7 +49,6 @@ type Props = { [string | number]: PseudoInstance, } --- Made by `:pseudo`, styles a pseudo-instance from the array part of a rule. export type PseudoInstance = { read selector: string, read props: Props, @@ -66,7 +63,6 @@ type function VALIDATE_STRINGLETON(s: type, string_type: string): type return s end --- Later fields override earlier fields, matching token updates. type function Merge(base: type, overrides: type): type local properties = {} :: { [type]: type } local keys = {} :: { [string]: type } @@ -90,17 +86,13 @@ type function Merge(base: type, overrides: type): type return types.newtable(properties, overrides:indexer() or source:indexer()) end --- Maps each token type to a union of the "$Name" refs for every token of that type. --- Equal types aren't the same userdata, so types are keyed by how they print. type function TokenRefs(tokens: type): { [string]: type } local refs = {} :: { [string]: type } - if not tokens:is("table") then - return refs - end for key, property in tokens:properties() do local token_type = property.read if token_type then + -- equal types aren't the same userdata, so types are keyed by what tostring gives for them local type_name = tostring(token_type) local reference = types.singleton("$" .. (key:value() :: string)) local existing = refs[type_name] @@ -108,7 +100,6 @@ type function TokenRefs(tokens: type): { [string]: type } end end - -- Token tables with an indexer can have any name. local indexer = tokens:indexer() if indexer then refs[tostring(indexer.readresult)] = types.string @@ -122,8 +113,6 @@ type function StyleValue(value: type, refs: { [string]: type }): type return types.optional(if value_refs then types.unionof(value, value_refs) else value) end --- One instance type per comma separated selector: the last compound's `::` pseudo-instance, else its class. --- Selectors without a known class style GuiObjects. type function SelectorInstances(selector: type): { type } if not (selector:is("singleton") and type(selector:value()) == "string") then return { RobloxGuiObject } @@ -147,7 +136,6 @@ type function SelectorInstances(selector: type): { type } return if #instances > 0 then instances else { RobloxGuiObject } end --- Options are `_` prefixed so they can never collide with Roblox property names. type function StyleProperties(selector: type, tokens: type, queries: type): type local selector_value = VALIDATE_STRINGLETON(selector, "selector"):value() :: string local read_only_properties = table.freeze({ @@ -156,7 +144,7 @@ type function StyleProperties(selector: type, tokens: type, queries: type): type types.singleton("UniqueId"), }) - -- Every query that `@Name` selectors and `_queries` can use: the built-ins, plus ones added with `:query`. + -- every query that `@Name` selectors and `_queries` can use local query_keys = {} :: { [string]: type } local source = BuiltInQueries for i = 1, 2 do @@ -172,10 +160,10 @@ type function StyleProperties(selector: type, tokens: type, queries: type): type end end - -- Rules can't reference instances, so Parent and other instance properties are left out. + -- rules can't reference instances, so Parent and other instance properties are left out. local instance_value = types.optional(RobloxInstance) local instance_values = {} :: { [string]: boolean } - -- Selector lists merge properties by name, intersecting the value types they share. + -- selector lists merge properties by name local keys = {} :: { [string]: type } local values = {} :: { [string]: type } @@ -357,10 +345,10 @@ type SheetPrototype = { export type Sheet = setmetatable, SheetPrototype> -local function create_rule(parent: Instance, selector: string, props: Props) +local function create_rule(parent: Instance, selector: string, props: Props, name: string?) local rule = Instance.new("StyleRule") rule.Selector = selector - rule.Name = selector + rule.Name = name or selector local priority = props._priority if priority then @@ -370,16 +358,14 @@ local function create_rule(parent: Instance, selector: string, props: Props) local transitions = props._transitions if transitions then - local default = transitions._default - - if default then - rule:SetDefaultPropertyTransition(default) - transitions._default = nil - end - for property, transition in transitions do - rule:SetPropertyTransition(property, transition) + if property == "_default" then + rule:SetDefaultPropertyTransition(transition) + else + rule:SetPropertyTransition(property, transition) + end end + props._transitions = nil end local queries = props._queries @@ -390,8 +376,10 @@ local function create_rule(parent: Instance, selector: string, props: Props) props._queries = nil end - for index, pseudo in ipairs(props :: any) do - create_rule(rule, pseudo.selector, pseudo.props) + for i = #props, 1, -1 do + local pseudo_instance = props[i] :: PseudoInstance + create_rule(rule, pseudo_instance.selector, pseudo_instance.props) + props[i] = nil end rule:SetProperties(props) @@ -423,14 +411,16 @@ end function style_sheet_prototype.pseudo(_self: RuntimeSheet, selector: string) return function(props: Props): PseudoInstance - return { selector = "::" .. selector, props = props } + return table.freeze({ selector = "::" .. selector, props = props }) end end function style_sheet_prototype.query(self: RuntimeSheet, name: string) return function(conditions: Props) - -- A StyleQuery only activates under the instance it checks, so every GuiObject gets it as a pseudo-instance. - create_rule(self.instance, `GuiObject::StyleQuery`, conditions) + -- a StyleQuery only activates under the instance it checks, so every GuiObject gets it as a pseudo-instance + -- because its the easiest way to do a global style query + -- #{name} is what names that pseudo-instance so @{name} selectors match it + create_rule(self.instance, `GuiObject::StyleQuery #{name}`, conditions, name) return self end end @@ -466,10 +456,19 @@ function style_sheet_prototype.link(self: RuntimeSheet) end) end -local function style_sheet(): Sheet<{}, {}, {}> +local function style_sheet(name: string, parent: Instance): Sheet<{}, {}, {}> + local instance = Instance.new("StyleSheet") + instance.Name = name + + -- defering parenting as to avoid datamodel change tracking whilst the style sheet is being built + task.defer(function(instance: Instance, parent: Instance) + instance.Parent = parent + end, instance, parent) + return table.freeze(setmetatable({ - instance = Instance.new("StyleSheet"), + instance = instance, }, style_sheet_prototype)) :: any end +table.freeze(style_sheet_prototype) return style_sheet From 850234937bb3452f5c7e20747c7de9e81f296498 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 22:58:26 -0400 Subject: [PATCH 16/30] fix typo & remove unnecessary code --- src/instances/style_sheet.luau | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 0892ef7..ac13687 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -114,10 +114,6 @@ type function StyleValue(value: type, refs: { [string]: type }): type end type function SelectorInstances(selector: type): { type } - if not (selector:is("singleton") and type(selector:value()) == "string") then - return { RobloxGuiObject } - end - local instances = {} :: { type } for part in string.gmatch(selector:value() :: string, "[^,]+") do @@ -329,7 +325,6 @@ type SheetPrototype = { name: Name | "" ) -> (QueryConditionValues>) -> setmetatable, SheetPrototype>, derive: (self: Self, from: Other) -> setmetatable, SheetPrototype>, - -- Keeps the sheet's type, it's meant for swapping between sheets with the same tokens, like themes. underive: (self: Self, from: RuntimeSheet) -> Self, pseudo: ( self: Self, @@ -415,6 +410,8 @@ function style_sheet_prototype.pseudo(_self: RuntimeSheet, selector: string) end end +-- TODO: optimize this in future if this ever becomes an issue, via making global queries be applied only to rules that use them +-- rather than just having them be a rule that applies to any GuiObject function style_sheet_prototype.query(self: RuntimeSheet, name: string) return function(conditions: Props) -- a StyleQuery only activates under the instance it checks, so every GuiObject gets it as a pseudo-instance @@ -460,7 +457,7 @@ local function style_sheet(name: string, parent: Instance): Sheet<{}, {}, {}> local instance = Instance.new("StyleSheet") instance.Name = name - -- defering parenting as to avoid datamodel change tracking whilst the style sheet is being built + -- deferring parenting as to avoid datamodel change tracking whilst the style sheet is being built task.defer(function(instance: Instance, parent: Instance) instance.Parent = parent end, instance, parent) From 8d26c159b365f095b057670517885fd1c4729def Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:00:27 -0400 Subject: [PATCH 17/30] add todo about read_only_properties --- src/instances/style_sheet.luau | 1 + 1 file changed, 1 insertion(+) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index ac13687..d728242 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -134,6 +134,7 @@ end type function StyleProperties(selector: type, tokens: type, queries: type): type local selector_value = VALIDATE_STRINGLETON(selector, "selector"):value() :: string + -- TODO: when luau allows use instance_types.get_read_only_properties so this table doesnt have to exist in 2 places local read_only_properties = table.freeze({ types.singleton("RobloxLocked"), types.singleton("ClassName"), From d04d210335754005d4afbe018ce20c000bff232a Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:16:51 -0400 Subject: [PATCH 18/30] fix props type kindof (i cannot be bothered to make a giant union of every roblox userdata) --- src/instances/style_sheet.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index d728242..2bd9273 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -46,7 +46,7 @@ type Props = { _transitions: { [string]: TweenInfo | string }?, _queries: { [string]: Props }?, _priority: number?, - [string | number]: PseudoInstance, + [string | number]: PseudoInstance | any, } export type PseudoInstance = { From 69a25929fa2f4a5358341db78697cb1090facc3a Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Tue, 29 Sep 2026 19:40:02 -0400 Subject: [PATCH 19/30] add PseudoInstances to instance_types --- src/instances/types.luau | 61 +++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 17 deletions(-) diff --git a/src/instances/types.luau b/src/instances/types.luau index 30b5836..d3114e1 100644 --- a/src/instances/types.luau +++ b/src/instances/types.luau @@ -1,6 +1,48 @@ local action = require("./action") -export type Instances = { +export type function Merge(base: type, overrides: type): type + local properties = {} :: { [type]: type } + local keys = {} :: { [string]: type } + local source = base + + for index = 1, 2 do + for key, property in source:properties() do + local name = key:value() :: string + local previous = keys[name] + + if previous then + properties[previous] = nil + end + + properties[key] = property.read + keys[name] = key + end + source = overrides + end + + return types.newtable(properties, overrides:indexer() or source:indexer()) +end + +-- Classes Roblox allows as pseudo-instances in style sheets +export type PseudoInstances = { + StyleQuery: StyleQuery, + UIAspectRatioConstraint: UIAspectRatioConstraint, + UITextSizeConstraint: UITextSizeConstraint, + UISizeConstraint: UISizeConstraint, + UITableLayout: UITableLayout, + UIPageLayout: UIPageLayout, + UIGridLayout: UIGridLayout, + UIListLayout: UIListLayout, + UIGradient: UIGradient, + UIFlexItem: UIFlexItem, + UIPadding: UIPadding, + UIStroke: UIStroke, + UICorner: UICorner, + UIShadow: UIShadow, + UIScale: UIScale, +} + +export type Instances = Merge type instance = Instance From f0e530984bdacbc37478567def3e0cb5785d2773 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Tue, 29 Sep 2026 20:11:55 -0400 Subject: [PATCH 20/30] * add _conditions to queries defined in _queries for rules, allowing for rule specific queries to be created * add type checking for pseudo instance class names * add verification for StyleRule selectors using a type function --- src/instances/style_sheet.luau | 518 ++++++++++++++++++++++++++------- 1 file changed, 416 insertions(+), 102 deletions(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 2bd9273..52b3139 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -4,8 +4,11 @@ local graph = require("../reactive/graph") local instance_types = require("./types") local tags = require("../utils/tags") +type PseduoInstanceNames = keyof + type Action = action.Identity type Instances = instance_types.Instances +type PseudoInstances = instance_types.PseudoInstances type RobloxStyleSheet = StyleSheet type RobloxGuiObject = GuiObject type RobloxInstance = Instance @@ -13,7 +16,10 @@ type RobloxTweenInfo = TweenInfo type RobloxSignal = RBXScriptSignal type RobloxStyleQuery = StyleQuery -type RuntimeSheet = { read instance: RobloxStyleSheet } +type RuntimeSheet = { + read instance: RobloxStyleSheet, + read _queries: { [string]: true? }, +} -- `::StyleQuery` pseudo-instances take their conditions as properties type QueryConditions = { @@ -26,66 +32,47 @@ type QueryConditions = { ViewportDisplaySize: Enum.DisplaySize, } -type BuiltInQueries = { - PreferredInputKeyboardAndMouse: true, - PreferredInputGamepad: true, - PreferredInputTouch: true, - PreferredInputMicroGamepad: true, - ViewportDisplaySizeSmall: true, - ViewportDisplaySizeMedium: true, - ViewportDisplaySizeLarge: true, - PreferredTextSizeMedium: true, - PreferredTextSizeLarge: true, - PreferredTextSizeLarger: true, - PreferredTextSizeLargest: true, - ReducedMotionEnabledTrue: true, - ReducedMotionEnabledFalse: true, -} - +-- Queries Roblox always provides, named by a condition followed by its value. +local BUILTIN_QUERIES = table.freeze({ + PreferredInputKeyboardAndMouse = true, + PreferredInputGamepad = true, + PreferredInputTouch = true, + PreferredInputMicroGamepad = true, + ViewportDisplaySizeSmall = true, + ViewportDisplaySizeMedium = true, + ViewportDisplaySizeLarge = true, + PreferredTextSizeMedium = true, + PreferredTextSizeLarge = true, + PreferredTextSizeLarger = true, + PreferredTextSizeLargest = true, + ReducedMotionEnabledTrue = true, + ReducedMotionEnabledFalse = true, +}) + +type BuiltInQueries = typeof(BUILTIN_QUERIES) + +-- this is not the most accurate type, but it suffices type Props = { _transitions: { [string]: TweenInfo | string }?, _queries: { [string]: Props }?, + _conditions: Props?, _priority: number?, [string | number]: PseudoInstance | any, } -export type PseudoInstance = { - read selector: string, +export type PseudoInstance = { + read selector: Selector, read props: Props, } -type function VALIDATE_STRINGLETON(s: type, string_type: string): type - if not (s.tag == "singleton" and type(s:value()) == "string") then - error(`{string_type} provided is not a string singleton`, 2) - elseif s:value() == "" then - error(`{string_type} provided can't be an empty string singleton`, 2) +-- errors with `pattern` formatted with the type if it isn't a non-empty string singleton, `%*` is where the type goes +type function VALIDATE_STRINGLETON(s: type, pattern: string): type + if not (s.tag == "singleton" and type(s:value()) == "string") or s:value() == "" then + error(string.format(pattern, s), 0) end return s end -type function Merge(base: type, overrides: type): type - local properties = {} :: { [type]: type } - local keys = {} :: { [string]: type } - local source = base - - for index = 1, 2 do - for key, property in source:properties() do - local name = key:value() :: string - local previous = keys[name] - - if previous then - properties[previous] = nil - end - - properties[key] = property.read - keys[name] = key - end - source = overrides - end - - return types.newtable(properties, overrides:indexer() or source:indexer()) -end - type function TokenRefs(tokens: type): { [string]: type } local refs = {} :: { [string]: type } @@ -113,28 +100,274 @@ type function StyleValue(value: type, refs: { [string]: type }): type return types.optional(if value_refs then types.unionof(value, value_refs) else value) end -type function SelectorInstances(selector: type): { type } +type function parse_selector(selector: string, queries: { [string]: type }): ({ type }, { string }?) + -- lowercase, because roblox matches gui states case-insensitively + local GUI_STATES = table.freeze({ "idle", "hover", "press", "noninteractable" }) + -- pseudo-instances roblox allows under each pseudo-instance; pseudo-instances missing from this list can't have any + local PSEUDO_INSTANCE_CHILDREN = table.freeze({ + UIGridLayout = table.freeze({ "UIAspectRatioConstraint", "UISizeConstraint" }), + UIStroke = table.freeze({ "UIGradient" }), + }) :: { [string]: { string } } + + local BYTE = string.byte + + local GREATER = BYTE(">") + local SPACE = BYTE(" ") + local COMMA = BYTE(",") + local COLON = BYTE(":") + local OPEN = BYTE("[") + local HASH = BYTE("#") + local DOT = BYTE(".") + local AT = BYTE("@") + + local has_inserted_gui_object = false local instances = {} :: { type } + local children: { string }? + local length = #selector + local position = 1 + + local function FAIL(at: number, message: string) + -- starting the error with a newline so the "TypeError: 'ParseSelector' type function errored at runtime:" isn't on the same line as the error + -- for better readability + error(`\n{message} at position {at}\n\t{selector}\n\t{string.rep(" ", at - 1)}^`, 0) + end + + local function SKIP_WHITESPACE() + local char = BYTE(selector, position) + + if char and char <= SPACE then + local next_char = BYTE(selector, position + 1) + + if char == SPACE and not (next_char and next_char <= SPACE) then + position += 1 + elseif char <= SPACE then + position = string.find(selector, "%S", position) or length + 1 + end + end + end + + local function SKIP_COMBINATOR(): string + local combinator = if BYTE(selector, position + 1) == GREATER then ">>" else ">" + position += #combinator + SKIP_WHITESPACE() + return combinator + end + + local function READ_IDENTIFIER(): string? + local identifier = string.match(selector, "^[%w_%-]+", position) + if identifier then + position += #identifier + end + return identifier + end + + -- skips a one character sigil like `.` or `#`, and returns the identifier that has to come right after it + local function parse_after_sigil(message: string): string? + position += 1 + local start = position + local identifier = READ_IDENTIFIER() + + if not identifier then + FAIL(start, message) + end + return identifier + end + + local function parse_state() + position += 1 + local start = position + local state = READ_IDENTIFIER() + + if not state then + FAIL(start, "':' has to be followed by a GuiState, like 'Hover'") + elseif not table.find(GUI_STATES, string.lower(state)) then + FAIL(start, `'{state}' is not a valid GuiState`) + end + end + + local function parse_query() + position += 1 + local start = position + local name = READ_IDENTIFIER() + + if not name then + FAIL(start, "'@' has to be followed by a query name") + elseif not queries[name] then + FAIL(start, `query '{name}' does not exist, add it with :query()`) + end + end + + -- only another `::Class` can follow a pseudo-instance, so they always end an element. Returns the instance and + -- class of the last one + local function parse_pseudo_instances(): (type?, string?) + local instance: type? = nil + local pseudo: string? = nil + -- the pseudo-instances Roblox allows under the last one + local allowed: { string }? = nil + local current: number? = nil + + repeat + position += 2 + SKIP_WHITESPACE() + + local class_start = position + local class_name = READ_IDENTIFIER() + local pseudo_instance = if class_name + then PseudoInstances:readproperty(types.singleton(class_name)) + else nil + + if not class_name then + FAIL(class_start, "'::' has to be followed by a ClassName") + elseif not pseudo_instance then + FAIL(class_start, `class '{class_name}' is not a valid pseudo-instance`) + elseif pseudo and not (allowed and table.find(allowed, class_name)) then + FAIL(class_start, `class '{class_name}' is not a valid pseudo-instance child for class '{pseudo}'`) + else + instance, pseudo, allowed = pseudo_instance, class_name, PSEUDO_INSTANCE_CHILDREN[class_name] + end + + SKIP_WHITESPACE() + current = BYTE(selector, position) + until not (current == COLON and BYTE(selector, position + 1) == COLON) + + if current == GREATER then + FAIL(position, `pseudo-instance '{pseudo}' cannot have children`) + elseif current and current ~= COMMA then + FAIL( + position, + if allowed + then `pseudo-instance '{pseudo}' can only be followed by '::{table.concat(allowed, "' or '::")}'` + else `pseudo-instance '{pseudo}' cannot be followed by anything` + ) + end + + return instance, pseudo + end + + -- whitespace doesn't separate elements, so an element goes on until a `,` or a `>` combinator. + -- returns the instance the element styles if it's known, and the pseudo-instance class it ends in + local function element(combinator: string?): (type?, string?) + local start = position + local instance: type? = nil + -- the class and name the element matches, since it can only match one of each + local element_class: string?, element_name: string? = nil, nil + + while true do + SKIP_WHITESPACE() + local current = BYTE(selector, position) + + if not current or current == COMMA or current == GREATER then + break + elseif current == COLON and BYTE(selector, position + 1) == COLON then + if combinator and position == start then + FAIL(position, `a pseudo-instance cannot come right after '{combinator}'`) + end + return parse_pseudo_instances() + elseif current == HASH then + local name_start = position + local name = parse_after_sigil("'#' has to be followed by a name") + if element_name then + FAIL( + name_start, + `name '{name}' cannot be used with name '{element_name}', put '>' or '>>' between them` + ) + end + element_name = name + elseif current == DOT then + parse_after_sigil("'.' has to be followed by a tag") + elseif current == COLON then + parse_state() + elseif current == AT then + parse_query() + elseif current == OPEN then + FAIL(position, "property filters are not supported") + else + local class_start = position + local class_name = READ_IDENTIFIER() + + if not class_name then + FAIL(class_start, `character '{string.char(current)}' is not valid in a selector`) + elseif element_class then + FAIL( + class_start, + `class '{class_name}' cannot be used with class '{element_class}', put '>' or '>>' between them` + ) + else + instance = Instances:readproperty(types.singleton(class_name)) + element_class = class_name + end + end + end + + if position == start then + FAIL(position, `'{combinator}' has to be followed by a selector`) + end + return instance, nil + end + + SKIP_WHITESPACE() + if position > length then + FAIL(1, `selector '{selector}' is only whitespace`) + end + + while position <= length do + local current = BYTE(selector, position) + + if current == COMMA then + FAIL(position, "',' has to come after a selector") + end + + local instance, pseudo = element(if current == GREATER then SKIP_COMBINATOR() else nil) + + while BYTE(selector, position) == GREATER do + instance, pseudo = element(SKIP_COMBINATOR()) + end - for part in string.gmatch(selector:value() :: string, "[^,]+") do - -- Only the compound after the last `>` / `>>` combinator gets styled. - local compound = string.match(part, "[^>]*$") :: string - local class_name = string.match(compound, "^%s*([%a_][%w_]*)") + --stylua: ignore + if (not instance) and (not has_inserted_gui_object) then + has_inserted_gui_object = true + instance = RobloxGuiObject + end + + table.insert(instances, instance) + + -- rules only take the pseudo-instances that can go under every pseudo-instance its selectors end in + if pseudo then + local allowed = PSEUDO_INSTANCE_CHILDREN[pseudo] + + if children then + local both = {} - for pseudo_instance in string.gmatch(compound, "::%s*([%a_][%w_]*)") do - class_name = pseudo_instance + if allowed then + for _, class_name in children do + if table.find(allowed, class_name) then + table.insert(both, class_name) + end + end + end + children = both + else + children = allowed or {} + end end - local instance = if class_name then Instances:readproperty(types.singleton(class_name)) else nil - table.insert(instances, instance or RobloxGuiObject) + -- a `,` starts the next selector + if position <= length then + position += 1 + SKIP_WHITESPACE() + + if position > length then + FAIL(position, "',' has to be followed by a selector") + end + end end - return if #instances > 0 then instances else { RobloxGuiObject } + return instances, children end type function StyleProperties(selector: type, tokens: type, queries: type): type - local selector_value = VALIDATE_STRINGLETON(selector, "selector"):value() :: string - -- TODO: when luau allows use instance_types.get_read_only_properties so this table doesnt have to exist in 2 places + local selector_value = VALIDATE_STRINGLETON(selector, "type %* is not a valid selector string"):value() :: string + -- TODO: when luau allows use instance_types.get_read_only_properties so this table doesn't have to exist in 2 places local read_only_properties = table.freeze({ types.singleton("RobloxLocked"), types.singleton("ClassName"), @@ -151,12 +384,6 @@ type function StyleProperties(selector: type, tokens: type, queries: type): type source = queries end - for name in string.gmatch(selector_value, "@([%w_%-]+)") do - if not query_keys[name] then - error(`unknown query @{name}, add it with :query()`) - end - end - -- rules can't reference instances, so Parent and other instance properties are left out. local instance_value = types.optional(RobloxInstance) local instance_values = {} :: { [string]: boolean } @@ -175,7 +402,9 @@ type function StyleProperties(selector: type, tokens: type, queries: type): type end end - for _, instance in SelectorInstances(selector) do + local styled, pseudo_children = parse_selector(selector_value, query_keys) + + for _, instance in styled do if instance == RobloxStyleQuery then for property, condition in QueryConditions:properties() do add(property, condition.read :: type) @@ -239,13 +468,41 @@ type function StyleProperties(selector: type, tokens: type, queries: type): type style[types.singleton("_priority")] = types.optional(types.number) style[types.singleton("_transitions")] = types.optional(types.newtable(transitions)) - -- pseudo-instances go in the array part, like instance children in the props table of fluid.bind - local props = - types.newtable(style, { index = types.number, readresult = PseudoInstance, writeresult = PseudoInstance }) + -- the array part holds the pseudo-instance children for the rule; which can be any pseudo-instance unless the + -- selector ends in one, which in that case only the pseudo-instances allowed under it can be children + local pseudo_instance + + if pseudo_children then + -- pseudo_children can be one of the frozen PSEUDO_INSTANCE_CHILDREN arrays, so the selectors go in a new array + local selectors = {} + for index, class_name in pseudo_children do + selectors[index] = types.singleton("::" .. class_name) + end + + pseudo_instance = PseudoInstance(types.unionof(table.unpack(selectors))) + elseif pseudo_children == false then + -- nothing is allowed under most pseudo-instances, like UICorner + pseudo_instance = types.never + else + -- including string because fluid might not always have a complete list of every Pseudo instance + pseudo_instance = PseudoInstance(types.unionof(PseduoInstanceNames, types.string)) + end + + local pseudo_instances_indexer = { + writeresult = pseudo_instance, + readresult = pseudo_instance, + index = types.number, + } + local props = types.newtable(style, pseudo_instances_indexer) - -- `_queries` has a key for every query, holding the props of a nested `@Name` rule that applies while the - -- query is active. A nested rule takes the same props as this one, `_queries` included, so the props table - -- has to exist before `_queries` can point back at it. + -- pseudo-instances can't contain queries + if pseudo_children ~= nil then + return props + end + + -- queries scoped to a rule take the same props, plus the conditions for their own StyleQuery + style[types.singleton("_conditions")] = QueryConditionValues(refs) + local scoped_query_rule = types.newtable(style, pseudo_instances_indexer) local query_rule = types.optional(props) local query_rules = {} :: { [type]: type } @@ -253,12 +510,17 @@ type function StyleProperties(selector: type, tokens: type, queries: type): type query_rules[key] = query_rule end - props:setproperty(types.singleton("_queries"), types.optional(types.newtable(query_rules))) + local queries_type = types.optional(types.newtable(query_rules, { + writeresult = scoped_query_rule, + readresult = scoped_query_rule, + index = types.string, + })) + props:setproperty(types.singleton("_queries"), queries_type) + scoped_query_rule:setproperty(types.singleton("_queries"), queries_type) return props end -type function QueryConditionValues(tokens: type): type - local refs = TokenRefs(tokens) +type function QueryConditionValues(refs: { [string]: type }): type local conditions = {} for key, condition in QueryConditions:properties() do @@ -267,8 +529,12 @@ type function QueryConditionValues(tokens: type): type return types.newtable(conditions) end +type function QueryConditionsFor(tokens: type): type + return QueryConditionValues(TokenRefs(tokens)) +end + type function TagsFrom(selector: type): type - selector = VALIDATE_STRINGLETON(selector, "selector") + selector = VALIDATE_STRINGLETON(selector, "type '%*' is not a valid selector string") local true_singleton = types.singleton(true) local tags = {} :: { [type]: type } @@ -279,19 +545,24 @@ type function TagsFrom(selector: type): type end type function QueryFrom(name: type): type - name = VALIDATE_STRINGLETON(name, "query name") + name = VALIDATE_STRINGLETON(name, "type %* is not a valid query name") return types.newtable({ [name] = types.singleton(true) }) end -type function PseudoSelector(selector: type): type - selector = VALIDATE_STRINGLETON(selector, "pseudo-instance selector") - return types.singleton("::" .. (selector:value() :: string)) +type function PseudoSelector(class_name: type): type + --stylua: ignore + local name = VALIDATE_STRINGLETON(class_name, "type %* is not a valid pseudo-instance class name"):value() :: string + + if not PseudoInstances:readproperty(class_name) then + error(`class '{name}' is not a valid pseudo-instance`, 0) + end + return types.singleton("::" .. name) end type SheetData = { read instance: RobloxStyleSheet, + read _queries: Queries, read __I_DO_NOT_EXIST_AT_RUNTIME: { - read queries: Queries, read tokens: Tokens, read tags: Tags, }, @@ -300,17 +571,29 @@ type SheetData = { type TypeOnly = index type TokensOf = index, "tokens"> type TagsOf = index, "tags"> -type QueriesOf = index, "queries"> +type QueriesOf = index type TagValue = keyof> | () -> keyof>? -type TokenState = SheetData, NewTokens>, TagsOf, QueriesOf> -type QueryState = SheetData, TagsOf, Merge, QueryFrom>> +type TokenState = SheetData< + instance_types.Merge, NewTokens>, + TagsOf, + QueriesOf +> +type QueryState = SheetData< + TokensOf, + TagsOf, + instance_types.Merge, QueryFrom> +> type DerivedState = SheetData< - Merge, TokensOf>, - Merge, TagsOf>, - Merge, QueriesOf> + instance_types.Merge, TokensOf>, + instance_types.Merge, TagsOf>, + instance_types.Merge, QueriesOf> +> +type RuleState = SheetData< + TokensOf, + instance_types.Merge, TagsFrom>, + QueriesOf > -type RuleState = SheetData, Merge, TagsFrom>, QueriesOf> -- string generics are unioned with "" because otherwise luau widens them to `string`, type SheetPrototype = { @@ -324,24 +607,32 @@ type SheetPrototype = { query: ( self: Self, name: Name | "" - ) -> (QueryConditionValues>) -> setmetatable, SheetPrototype>, + ) -> (conditions: QueryConditionsFor>) -> setmetatable, SheetPrototype>, derive: (self: Self, from: Other) -> setmetatable, SheetPrototype>, underive: (self: Self, from: RuntimeSheet) -> Self, - pseudo: ( + pseudo: ( self: Self, - selector: Selector | "" - ) -> (StyleProperties, TokensOf, QueriesOf>) -> PseudoInstance, + class_name: ClassName | PseduoInstanceNames + ) -> ( + props: StyleProperties, TokensOf, QueriesOf> + ) -> PseudoInstance>, rule: ( self: Self, selector: Selector | "" ) -> ( - StyleProperties, QueriesOf> + props: StyleProperties, QueriesOf> ) -> setmetatable, SheetPrototype>, } export type Sheet = setmetatable, SheetPrototype> -local function create_rule(parent: Instance, selector: string, props: Props, name: string?) +local function create_rule( + parent: Instance, + selector: string, + props: Props, + known_queries: { [string]: true? }, + name: string? +) local rule = Instance.new("StyleRule") rule.Selector = selector rule.Name = name or selector @@ -366,15 +657,31 @@ local function create_rule(parent: Instance, selector: string, props: Props, nam local queries = props._queries if queries then + -- roblox gives queries under pseudo-instances a SelectorError + if string.find(selector, "::", 1, true) then + error(`rule '{selector}' cannot have queries since it ends in a pseudo-instance, move it into the query`) + end + for name, query_props in queries do - create_rule(rule, "@" .. name, query_props) + local conditions = query_props._conditions + + if conditions then + -- a StyleQuery pseudo-instance under this rule only exists on the instances this rule styles + create_rule(rule, `::StyleQuery #{name}`, conditions, known_queries, name) + query_props._conditions = nil + elseif not ((BUILTIN_QUERIES :: any)[name] or known_queries[name]) then + error(`query '{name}' does not exist, add it with :query() or set _queries.{name}._conditions`) + end + + create_rule(rule, "@" .. name, query_props, known_queries) end props._queries = nil end for i = #props, 1, -1 do local pseudo_instance = props[i] :: PseudoInstance - create_rule(rule, pseudo_instance.selector, pseudo_instance.props) + create_rule(rule, pseudo_instance.selector, pseudo_instance.props, known_queries) + -- :SetProperties() will error if its given a mixed table props[i] = nil end @@ -400,25 +707,25 @@ end function style_sheet_prototype.rule(self: RuntimeSheet, selector: string) return function(props: Props) - create_rule(self.instance, selector, props) + create_rule(self.instance, selector, props, self._queries) return self end end -function style_sheet_prototype.pseudo(_self: RuntimeSheet, selector: string) +function style_sheet_prototype.pseudo(_self: RuntimeSheet, class_name: string) return function(props: Props): PseudoInstance - return table.freeze({ selector = "::" .. selector, props = props }) + return table.freeze({ selector = "::" .. class_name, props = props }) end end --- TODO: optimize this in future if this ever becomes an issue, via making global queries be applied only to rules that use them --- rather than just having them be a rule that applies to any GuiObject function style_sheet_prototype.query(self: RuntimeSheet, name: string) return function(conditions: Props) -- a StyleQuery only activates under the instance it checks, so every GuiObject gets it as a pseudo-instance -- because its the easiest way to do a global style query -- #{name} is what names that pseudo-instance so @{name} selectors match it - create_rule(self.instance, `GuiObject::StyleQuery #{name}`, conditions, name) + local queries = self._queries + create_rule(self.instance, `GuiObject::StyleQuery #{name}`, conditions, queries, name) + queries[name] = true return self end end @@ -428,6 +735,12 @@ function style_sheet_prototype.derive(self: RuntimeSheet, other: RuntimeSheet) local derives = instance:GetDerives() table.insert(derives, other.instance) instance:SetDerives(derives) + + -- derived sheets bring their queries along, so their names are valid here too + local queries = self._queries + for name in other._queries do + queries[name] = true + end return self end @@ -465,6 +778,7 @@ local function style_sheet(name: string, parent: Instance): Sheet<{}, {}, {}> return table.freeze(setmetatable({ instance = instance, + _queries = {}, }, style_sheet_prototype)) :: any end From b999b7e83978fb9e11c6884f387ec66a750804b9 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:53:32 -0400 Subject: [PATCH 21/30] change PseudoSelector non string type error message --- src/instances/style_sheet.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 52b3139..54c25e3 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -551,7 +551,7 @@ end type function PseudoSelector(class_name: type): type --stylua: ignore - local name = VALIDATE_STRINGLETON(class_name, "type %* is not a valid pseudo-instance class name"):value() :: string + local name = VALIDATE_STRINGLETON(class_name, "type %* is not a valid pseudo-instance class name string"):value() :: string if not PseudoInstances:readproperty(class_name) then error(`class '{name}' is not a valid pseudo-instance`, 0) From cf3920c5504df42c3ef98a024c016949a69709e3 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:54:43 -0400 Subject: [PATCH 22/30] add comment to underive about why it doesn't do any type function stuff --- src/instances/style_sheet.luau | 1 + 1 file changed, 1 insertion(+) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 54c25e3..2a52428 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -609,6 +609,7 @@ type SheetPrototype = { name: Name | "" ) -> (conditions: QueryConditionsFor>) -> setmetatable, SheetPrototype>, derive: (self: Self, from: Other) -> setmetatable, SheetPrototype>, + -- doesn't do any type function shennagigans because its meant to be used at runtime, for stuff like theme switching underive: (self: Self, from: RuntimeSheet) -> Self, pseudo: ( self: Self, From 6ccc4ef2acab651876f04c1fb7cca0c12c702084 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:54:53 -0400 Subject: [PATCH 23/30] typo fix --- src/instances/style_sheet.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 2a52428..64a514b 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -609,7 +609,7 @@ type SheetPrototype = { name: Name | "" ) -> (conditions: QueryConditionsFor>) -> setmetatable, SheetPrototype>, derive: (self: Self, from: Other) -> setmetatable, SheetPrototype>, - -- doesn't do any type function shennagigans because its meant to be used at runtime, for stuff like theme switching + -- doesn't do any type function shenanigans because its meant to be used at runtime, for stuff like theme switching underive: (self: Self, from: RuntimeSheet) -> Self, pseudo: ( self: Self, From 1b6803f2726b4c58e6e862f6c87837016bc4d01e Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:28:03 -0400 Subject: [PATCH 24/30] remove useless comments --- src/instances/style_sheet.luau | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 64a514b..94d0919 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -32,7 +32,6 @@ type QueryConditions = { ViewportDisplaySize: Enum.DisplaySize, } --- Queries Roblox always provides, named by a condition followed by its value. local BUILTIN_QUERIES = table.freeze({ PreferredInputKeyboardAndMouse = true, PreferredInputGamepad = true, @@ -65,7 +64,6 @@ export type PseudoInstance = { read props: Props, } --- errors with `pattern` formatted with the type if it isn't a non-empty string singleton, `%*` is where the type goes type function VALIDATE_STRINGLETON(s: type, pattern: string): type if not (s.tag == "singleton" and type(s:value()) == "string") or s:value() == "" then error(string.format(pattern, s), 0) From 5b313cc24f8175efbae719cbcf116ce1f39e654c Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:22:07 -0400 Subject: [PATCH 25/30] seperate query instance creation into its own function & improve errors for pseudo-instance creation at runtime --- src/instances/style_sheet.luau | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 94d0919..ff6f574 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -625,16 +625,28 @@ type SheetPrototype = { export type Sheet = setmetatable, SheetPrototype> +local function create_query( + parent: Instance, + name: string, + conditions: { [string]: any } +) + local instance = Instance.new("StyleRule") + instance.Selector = `::StyleQuery #{name}` + instance.Name = name + instance:SetProperties(conditions) + instance.Parent = parent +end + local function create_rule( parent: Instance, selector: string, props: Props, known_queries: { [string]: true? }, - name: string? + is_pseudo: boolean? ) local rule = Instance.new("StyleRule") rule.Selector = selector - rule.Name = name or selector + rule.Name = selector local priority = props._priority if priority then @@ -657,8 +669,12 @@ local function create_rule( local queries = props._queries if queries then -- roblox gives queries under pseudo-instances a SelectorError - if string.find(selector, "::", 1, true) then - error(`rule '{selector}' cannot have queries since it ends in a pseudo-instance, move it into the query`) + if is_pseudo then + error("pseudo-instances cannot have queries") + elseif string.find(selector, "::", 1, true) then + error( + `rule '{selector}' cannot have queries since it ends in a pseudo-instance, create the pseudo-instance using StyleSheet:pseudo() in the properties of the rule instead` + ) end for name, query_props in queries do @@ -666,8 +682,7 @@ local function create_rule( if conditions then -- a StyleQuery pseudo-instance under this rule only exists on the instances this rule styles - create_rule(rule, `::StyleQuery #{name}`, conditions, known_queries, name) - query_props._conditions = nil + create_query(rule, name, conditions) elseif not ((BUILTIN_QUERIES :: any)[name] or known_queries[name]) then error(`query '{name}' does not exist, add it with :query() or set _queries.{name}._conditions`) end @@ -723,7 +738,7 @@ function style_sheet_prototype.query(self: RuntimeSheet, name: string) -- because its the easiest way to do a global style query -- #{name} is what names that pseudo-instance so @{name} selectors match it local queries = self._queries - create_rule(self.instance, `GuiObject::StyleQuery #{name}`, conditions, queries, name) + create_query(self.instance, name, conditions) queries[name] = true return self end From 72ca4ea42e24aafeff2ad6a4c7f014177860fd41 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:25:17 -0400 Subject: [PATCH 26/30] add comment about _priority in pseudo-instances --- src/instances/style_sheet.luau | 1 + 1 file changed, 1 insertion(+) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index ff6f574..551c77d 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -463,6 +463,7 @@ type function StyleProperties(selector: type, tokens: type, queries: type): type end transitions[types.singleton("_default")] = transition + -- this does nothing for pseudo instances, but id rather just allow it incase roblox does have it do something in future style[types.singleton("_priority")] = types.optional(types.number) style[types.singleton("_transitions")] = types.optional(types.newtable(transitions)) From 73e9fbe348df685ca1f75215e4c212c08124fd46 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:28:21 -0400 Subject: [PATCH 27/30] fix StyleSheet:query() --- src/instances/style_sheet.luau | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index 551c77d..da1af03 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -628,11 +628,12 @@ export type Sheet = setmetatable Date: Thu, 1 Oct 2026 11:53:52 -0400 Subject: [PATCH 28/30] format --- src/instances/style_sheet.luau | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index da1af03..dde2c93 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -626,12 +626,7 @@ type SheetPrototype = { export type Sheet = setmetatable, SheetPrototype> -local function create_query( - parent: Instance, - selector: string, - name: string, - conditions: { [string]: any } -) +local function create_query(parent: Instance, selector: string, name: string, conditions: { [string]: any }) local instance = Instance.new("StyleRule") instance.Selector = selector instance.Name = name From 1359896f7abba54547c30dee881fabf64a007205 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:54:26 -0400 Subject: [PATCH 29/30] add UIGradient as an allowed pseudo-instance child to UIShadow --- src/instances/style_sheet.luau | 1 + 1 file changed, 1 insertion(+) diff --git a/src/instances/style_sheet.luau b/src/instances/style_sheet.luau index dde2c93..aa0e8cd 100644 --- a/src/instances/style_sheet.luau +++ b/src/instances/style_sheet.luau @@ -104,6 +104,7 @@ type function parse_selector(selector: string, queries: { [string]: type }): ({ -- pseudo-instances roblox allows under each pseudo-instance; pseudo-instances missing from this list can't have any local PSEUDO_INSTANCE_CHILDREN = table.freeze({ UIGridLayout = table.freeze({ "UIAspectRatioConstraint", "UISizeConstraint" }), + UIShadow = table.freeze({ "UIGradient" }), UIStroke = table.freeze({ "UIGradient" }), }) :: { [string]: { string } } From 7e79a0916ef24bdfdc18adb1b2480d74610ffcd4 Mon Sep 17 00:00:00 2001 From: gaymeowing <62822174+gaymeowing@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:18:18 -0400 Subject: [PATCH 30/30] add UIBlur to the PseudoInstances list --- src/instances/types.luau | 1 + 1 file changed, 1 insertion(+) diff --git a/src/instances/types.luau b/src/instances/types.luau index d3114e1..c52f0e6 100644 --- a/src/instances/types.luau +++ b/src/instances/types.luau @@ -40,6 +40,7 @@ export type PseudoInstances = { UICorner: UICorner, UIShadow: UIShadow, UIScale: UIScale, + UIBlur: UIBlur, } export type Instances = Merge