|
| 1 | +--!strict |
| 2 | +--!nolint LocalUnused |
| 3 | +--!nolint LocalShadow |
| 4 | +local task = nil -- Disable usage of Roblox's task scheduler |
| 5 | + |
| 6 | +--[[ |
| 7 | + A special key for property tables, which allows users to apply custom |
| 8 | + CollectionService tags to instances |
| 9 | +]] |
| 10 | + |
| 11 | +local Package = script.Parent.Parent |
| 12 | +local Types = require(Package.Types) |
| 13 | +-- Memory |
| 14 | +local checkLifetime = require(Package.Memory.checkLifetime) |
| 15 | +-- Graph |
| 16 | +local Observer = require(Package.Graph.Observer) |
| 17 | +-- State |
| 18 | +local castToState = require(Package.State.castToState) |
| 19 | +local peek = require(Package.State.peek) |
| 20 | + |
| 21 | +local keyCache: { [string]: Types.SpecialKey } = {} |
| 22 | + |
| 23 | +-- TODO: should this accept tagName: UsedAs<string>? |
| 24 | +local function Tag(tagName: string): Types.SpecialKey |
| 25 | + local key = keyCache[tagName] |
| 26 | + if key == nil then |
| 27 | + key = { |
| 28 | + type = "SpecialKey", |
| 29 | + kind = "Tag", |
| 30 | + stage = "self", |
| 31 | + apply = function(self: Types.SpecialKey, scope: Types.Scope<unknown>, value: unknown, applyTo: Instance) |
| 32 | + if castToState(value) then |
| 33 | + local value = value :: Types.StateObject<unknown> |
| 34 | + checkLifetime.bOutlivesA( |
| 35 | + scope, |
| 36 | + applyTo, |
| 37 | + value.scope, |
| 38 | + value.oldestTask, |
| 39 | + checkLifetime.formatters.boundTag, |
| 40 | + tagName |
| 41 | + ) |
| 42 | + Observer(scope, value :: any):onBind(function() |
| 43 | + if peek(value) == true then |
| 44 | + applyTo:AddTag(tagName) |
| 45 | + elseif applyTo:HasTag(tagName) then |
| 46 | + applyTo:RemoveTag(tagName) |
| 47 | + end |
| 48 | + end) |
| 49 | + else |
| 50 | + if value == true then |
| 51 | + applyTo:AddTag(tagName) |
| 52 | + end |
| 53 | + end |
| 54 | + end, |
| 55 | + } |
| 56 | + keyCache[tagName] = key |
| 57 | + end |
| 58 | + return key |
| 59 | +end |
| 60 | + |
| 61 | +return Tag |
0 commit comments