/
init.lua
759 lines (635 loc) · 20.5 KB
/
init.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
-- Component
-- Stephen Leitnick
-- November 26, 2021
type AncestorList = { Instance }
--[=[
@type ExtensionFn (component) -> ()
@within Component
]=]
type ExtensionFn = (any) -> ()
--[=[
@type ExtensionShouldFn (component) -> boolean
@within Component
]=]
type ExtensionShouldFn = (any) -> boolean
--[=[
@interface Extension
@within Component
.ShouldExtend ExtensionShouldFn?
.ShouldConstruct ExtensionShouldFn?
.Constructing ExtensionFn?
.Constructed ExtensionFn?
.Starting ExtensionFn?
.Started ExtensionFn?
.Stopping ExtensionFn?
.Stopped ExtensionFn?
An extension allows the ability to extend the behavior of
components. This is useful for adding injection systems or
extending the behavior of components by wrapping around
component lifecycle methods.
The `ShouldConstruct` function can be used to indicate
if the component should actually be created. This must
return `true` or `false`. A component with multiple
`ShouldConstruct` extension functions must have them _all_
return `true` in order for the component to be constructed.
The `ShouldConstruct` function runs _before_ all other
extension functions and component lifecycle methods.
The `ShouldExtend` function can be used to indicate if
the extension itself should be used. This can be used in
order to toggle an extension on/off depending on whatever
logic is appropriate. If no `ShouldExtend` function is
provided, the extension will always be used if provided
as an extension to the component.
As an example, an extension could be created to simply log
when the various lifecycle stages run on the component:
```lua
local Logger = {}
function Logger.Constructing(component) print("Constructing", component) end
function Logger.Constructed(component) print("Constructed", component) end
function Logger.Starting(component) print("Starting", component) end
function Logger.Started(component) print("Started", component) end
function Logger.Stopping(component) print("Stopping", component) end
function Logger.Stopped(component) print("Stopped", component) end
local MyComponent = Component.new({Tag = "MyComponent", Extensions = {Logger}})
```
Sometimes it is useful for an extension to control whether or
not a component should be constructed. For instance, if a
component on the client should only be instantiated for the
local player, an extension might look like this, assuming the
instance has an attribute linking it to the player's UserId:
```lua
local player = game:GetService("Players").LocalPlayer
local OnlyLocalPlayer = {}
function OnlyLocalPlayer.ShouldConstruct(component)
local ownerId = component.Instance:GetAttribute("OwnerId")
return ownerId == player.UserId
end
local MyComponent = Component.new({Tag = "MyComponent", Extensions = {OnlyLocalPlayer}})
```
It can also be useful for an extension itself to turn on/off
depending on various contexts. For example, let's take the
Logger from the first example, and only use that extension
if the bound instance has a Log attribute set to `true`:
```lua
function Logger.ShouldExtend(component)
return component.Instance:GetAttribute("Log") == true
end
```
]=]
type Extension = {
ShouldExtend: ExtensionShouldFn?,
ShouldConstruct: ExtensionShouldFn?,
Constructing: ExtensionFn?,
Constructed: ExtensionFn?,
Starting: ExtensionFn?,
Started: ExtensionFn?,
Stopping: ExtensionFn?,
Stopped: ExtensionFn?,
}
--[=[
@interface ComponentConfig
@within Component
.Tag string -- CollectionService tag to use
.Ancestors {Instance}? -- Optional array of ancestors in which components will be started
.Extensions {Extension}? -- Optional array of extension objects
Component configuration passed to `Component.new`.
- If no Ancestors option is included, it defaults to `{workspace, game.Players}`.
- If no Extensions option is included, it defaults to a blank table `{}`.
]=]
type ComponentConfig = {
Tag: string,
Ancestors: AncestorList?,
Extensions: { Extension }?,
}
--[=[
@within Component
@prop Started Signal
@tag Event
@tag Component Class
Fired when a new instance of a component is started.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
MyComponent.Started:Connect(function(component) end)
```
]=]
--[=[
@within Component
@prop Stopped Signal
@tag Event
@tag Component Class
Fired when an instance of a component is stopped.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
MyComponent.Stopped:Connect(function(component) end)
```
]=]
--[=[
@tag Component Instance
@within Component
@prop Instance Instance
A reference back to the _Roblox_ instance from within a _component_ instance. When
a component instance is created, it is bound to a specific Roblox instance, which
will always be present through the `Instance` property.
```lua
MyComponent.Started:Connect(function(component)
local robloxInstance: Instance = component.Instance
print("Component is bound to " .. robloxInstance:GetFullName())
end)
```
]=]
local CollectionService = game:GetService("CollectionService")
local RunService = game:GetService("RunService")
local Promise = require(script.Parent.Promise)
local Signal = require(script.Parent.Signal)
local Symbol = require(script.Parent.Symbol)
local Trove = require(script.Parent.Trove)
local IS_SERVER = RunService:IsServer()
local DEFAULT_ANCESTORS = { workspace, game:GetService("Players") }
local DEFAULT_TIMEOUT = 60
-- Symbol keys:
local KEY_ANCESTORS = Symbol("Ancestors")
local KEY_INST_TO_COMPONENTS = Symbol("InstancesToComponents")
local KEY_LOCK_CONSTRUCT = Symbol("LockConstruct")
local KEY_COMPONENTS = Symbol("Components")
local KEY_TROVE = Symbol("Trove")
local KEY_EXTENSIONS = Symbol("Extensions")
local KEY_ACTIVE_EXTENSIONS = Symbol("ActiveExtensions")
local KEY_STARTING = Symbol("Starting")
local KEY_STARTED = Symbol("Started")
local renderId = 0
local function NextRenderName(): string
renderId += 1
return "ComponentRender" .. tostring(renderId)
end
local function InvokeExtensionFn(component, fnName: string)
for _, extension in ipairs(component[KEY_ACTIVE_EXTENSIONS]) do
local fn = extension[fnName]
if type(fn) == "function" then
fn(component)
end
end
end
local function ShouldConstruct(component): boolean
for _, extension in ipairs(component[KEY_ACTIVE_EXTENSIONS]) do
local fn = extension.ShouldConstruct
if type(fn) == "function" then
local shouldConstruct = fn(component)
if not shouldConstruct then
return false
end
end
end
return true
end
local function GetActiveExtensions(component, extensionList)
local activeExtensions = table.create(#extensionList)
local allActive = true
for _, extension in ipairs(extensionList) do
local fn = extension.ShouldExtend
local shouldExtend = type(fn) ~= "function" or not not fn(component)
if shouldExtend then
table.insert(activeExtensions, extension)
else
allActive = false
end
end
return if allActive then extensionList else activeExtensions
end
--[=[
@class Component
Bind components to Roblox instances using the Component class and CollectionService tags.
To avoid confusion of terms:
- `Component` refers to this module.
- `Component Class` (e.g. `MyComponent` through this documentation) refers to a class created via `Component.new`
- `Component Instance` refers to an instance of a component class.
- `Roblox Instance` refers to the Roblox instance to which the component instance is bound.
Methods and properties are tagged with the above terms to help clarify the level at which they are used.
]=]
local Component = {}
Component.__index = Component
--[=[
@tag Component
@param config ComponentConfig
@return ComponentClass
Create a new custom Component class.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
```
A full example might look like this:
```lua
local MyComponent = Component.new({
Tag = "MyComponent",
Ancestors = {workspace},
Extensions = {Logger}, -- See Logger example within the example for the Extension type
})
local AnotherComponent = require(somewhere.AnotherComponent)
-- Optional if UpdateRenderStepped should use BindToRenderStep:
MyComponent.RenderPriority = Enum.RenderPriority.Camera.Value
function MyComponent:Construct()
self.MyData = "Hello"
end
function MyComponent:Start()
local another = self:GetComponent(AnotherComponent)
another:DoSomething()
end
function MyComponent:Stop()
self.MyData = "Goodbye"
end
function MyComponent:HeartbeatUpdate(dt)
end
function MyComponent:SteppedUpdate(dt)
end
function MyComponent:RenderSteppedUpdate(dt)
end
```
]=]
function Component.new(config: ComponentConfig)
local customComponent = {}
customComponent.__index = customComponent
customComponent.__tostring = function()
return "Component<" .. config.Tag .. ">"
end
customComponent[KEY_ANCESTORS] = config.Ancestors or DEFAULT_ANCESTORS
customComponent[KEY_INST_TO_COMPONENTS] = {}
customComponent[KEY_COMPONENTS] = {}
customComponent[KEY_LOCK_CONSTRUCT] = {}
customComponent[KEY_TROVE] = Trove.new()
customComponent[KEY_EXTENSIONS] = config.Extensions or {}
customComponent[KEY_STARTED] = false
customComponent.Tag = config.Tag
customComponent.Started = customComponent[KEY_TROVE]:Construct(Signal)
customComponent.Stopped = customComponent[KEY_TROVE]:Construct(Signal)
setmetatable(customComponent, Component)
customComponent:_setup()
return customComponent
end
function Component:_instantiate(instance: Instance)
local component = setmetatable({}, self)
component.Instance = instance
component[KEY_ACTIVE_EXTENSIONS] = GetActiveExtensions(component, self[KEY_EXTENSIONS])
if not ShouldConstruct(component) then
return nil
end
InvokeExtensionFn(component, "Constructing")
if type(component.Construct) == "function" then
component:Construct()
end
InvokeExtensionFn(component, "Constructed")
return component
end
function Component:_setup()
local watchingInstances = {}
local function StartComponent(component)
component[KEY_STARTING] = coroutine.running()
InvokeExtensionFn(component, "Starting")
component:Start()
if component[KEY_STARTING] == nil then
-- Component's Start method stopped the component
return
end
InvokeExtensionFn(component, "Started")
local hasHeartbeatUpdate = typeof(component.HeartbeatUpdate) == "function"
local hasSteppedUpdate = typeof(component.SteppedUpdate) == "function"
local hasRenderSteppedUpdate = typeof(component.RenderSteppedUpdate) == "function"
if hasHeartbeatUpdate then
component._heartbeatUpdate = RunService.Heartbeat:Connect(function(dt)
component:HeartbeatUpdate(dt)
end)
end
if hasSteppedUpdate then
component._steppedUpdate = RunService.Stepped:Connect(function(_, dt)
component:SteppedUpdate(dt)
end)
end
if hasRenderSteppedUpdate and not IS_SERVER then
if component.RenderPriority then
component._renderName = NextRenderName()
RunService:BindToRenderStep(component._renderName, component.RenderPriority, function(dt)
component:RenderSteppedUpdate(dt)
end)
else
component._renderSteppedUpdate = RunService.RenderStepped:Connect(function(dt)
component:RenderSteppedUpdate(dt)
end)
end
end
component[KEY_STARTED] = true
component[KEY_STARTING] = nil
self.Started:Fire(component)
end
local function StopComponent(component)
if component[KEY_STARTING] then
-- Stop the component during its start method invocation:
local startThread = component[KEY_STARTING]
if coroutine.status(startThread) ~= "normal" then
pcall(function()
task.cancel(startThread)
end)
else
task.defer(function()
pcall(function()
task.cancel(startThread)
end)
end)
end
component[KEY_STARTING] = nil
end
if component._heartbeatUpdate then
component._heartbeatUpdate:Disconnect()
end
if component._steppedUpdate then
component._steppedUpdate:Disconnect()
end
if component._renderSteppedUpdate then
component._renderSteppedUpdate:Disconnect()
elseif component._renderName then
RunService:UnbindFromRenderStep(component._renderName)
end
InvokeExtensionFn(component, "Stopping")
component:Stop()
InvokeExtensionFn(component, "Stopped")
self.Stopped:Fire(component)
end
local function SafeConstruct(instance, id)
if self[KEY_LOCK_CONSTRUCT][instance] ~= id then
return nil
end
local component = self:_instantiate(instance)
if self[KEY_LOCK_CONSTRUCT][instance] ~= id then
return nil
end
return component
end
local function TryConstructComponent(instance)
if self[KEY_INST_TO_COMPONENTS][instance] then
return
end
local id = self[KEY_LOCK_CONSTRUCT][instance] or 0
id += 1
self[KEY_LOCK_CONSTRUCT][instance] = id
task.defer(function()
local component = SafeConstruct(instance, id)
if not component then
return
end
self[KEY_INST_TO_COMPONENTS][instance] = component
table.insert(self[KEY_COMPONENTS], component)
task.defer(function()
if self[KEY_INST_TO_COMPONENTS][instance] == component then
StartComponent(component)
end
end)
end)
end
local function TryDeconstructComponent(instance)
local component = self[KEY_INST_TO_COMPONENTS][instance]
if not component then
return
end
self[KEY_INST_TO_COMPONENTS][instance] = nil
self[KEY_LOCK_CONSTRUCT][instance] = nil
local components = self[KEY_COMPONENTS]
local index = table.find(components, component)
if index then
local n = #components
components[index] = components[n]
components[n] = nil
end
if component[KEY_STARTED] or component[KEY_STARTING] then
task.spawn(StopComponent, component)
end
end
local function StartWatchingInstance(instance)
if watchingInstances[instance] then
return
end
local function IsInAncestorList(): boolean
for _, parent in ipairs(self[KEY_ANCESTORS]) do
if instance:IsDescendantOf(parent) then
return true
end
end
return false
end
local ancestryChangedHandle = self[KEY_TROVE]:Connect(instance.AncestryChanged, function(_, parent)
if parent and IsInAncestorList() then
TryConstructComponent(instance)
else
TryDeconstructComponent(instance)
end
end)
watchingInstances[instance] = ancestryChangedHandle
if IsInAncestorList() then
TryConstructComponent(instance)
end
end
local function InstanceTagged(instance: Instance)
StartWatchingInstance(instance)
end
local function InstanceUntagged(instance: Instance)
local watchHandle = watchingInstances[instance]
if watchHandle then
watchingInstances[instance] = nil
self[KEY_TROVE]:Remove(watchHandle)
end
TryDeconstructComponent(instance)
end
self[KEY_TROVE]:Connect(CollectionService:GetInstanceAddedSignal(self.Tag), InstanceTagged)
self[KEY_TROVE]:Connect(CollectionService:GetInstanceRemovedSignal(self.Tag), InstanceUntagged)
local tagged = CollectionService:GetTagged(self.Tag)
for _, instance in ipairs(tagged) do
task.defer(InstanceTagged, instance)
end
end
--[=[
@tag Component Class
@return {Component}
Gets a table array of all existing component objects. For example,
if there was a component class linked to the "MyComponent" tag,
and three Roblox instances in your game had that same tag, then
calling `GetAll` would return the three component instances.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
-- ...
local components = MyComponent:GetAll()
for _,component in ipairs(components) do
component:DoSomethingHere()
end
```
]=]
function Component:GetAll()
return self[KEY_COMPONENTS]
end
--[=[
@tag Component Class
@return Component?
Gets an instance of a component class from the given Roblox
instance. Returns `nil` if not found.
```lua
local MyComponent = require(somewhere.MyComponent)
local myComponentInstance = MyComponent:FromInstance(workspace.SomeInstance)
```
]=]
function Component:FromInstance(instance: Instance)
return self[KEY_INST_TO_COMPONENTS][instance]
end
--[=[
@tag Component Class
@return Promise<ComponentInstance>
Resolves a promise once the component instance is present on a given
Roblox instance.
An optional `timeout` can be provided to reject the promise if it
takes more than `timeout` seconds to resolve. If no timeout is
supplied, `timeout` defaults to 60 seconds.
```lua
local MyComponent = require(somewhere.MyComponent)
MyComponent:WaitForInstance(workspace.SomeInstance):andThen(function(myComponentInstance)
-- Do something with the component class
end)
```
]=]
function Component:WaitForInstance(instance: Instance, timeout: number?)
local componentInstance = self:FromInstance(instance)
if componentInstance and componentInstance[KEY_STARTED] then
return Promise.resolve(componentInstance)
end
return Promise.fromEvent(self.Started, function(c)
local match = c.Instance == instance
if match then
componentInstance = c
end
return match
end)
:andThen(function()
return componentInstance
end)
:timeout(if type(timeout) == "number" then timeout else DEFAULT_TIMEOUT)
end
--[=[
@tag Component Class
`Construct` is called before the component is started, and should be used
to construct the component instance.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
function MyComponent:Construct()
self.SomeData = 32
self.OtherStuff = "HelloWorld"
end
```
]=]
function Component:Construct() end
--[=[
@tag Component Class
`Start` is called when the component is started. At this point in time, it
is safe to grab other components also bound to the same instance.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
local AnotherComponent = require(somewhere.AnotherComponent)
function MyComponent:Start()
-- e.g., grab another component:
local another = self:GetComponent(AnotherComponent)
end
```
]=]
function Component:Start() end
--[=[
@tag Component Class
`Stop` is called when the component is stopped. This occurs either when the
bound instance is removed from one of the whitelisted ancestors _or_ when
the matching tag is removed from the instance. This also means that the
instance _might_ be destroyed, and thus it is not safe to continue using
the bound instance (e.g. `self.Instance`) any longer.
This should be used to clean up the component.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
function MyComponent:Stop()
self.SomeStuff:Destroy()
end
```
]=]
function Component:Stop() end
--[=[
@tag Component Instance
@param componentClass ComponentClass
@return Component?
Retrieves another component instance bound to the same
Roblox instance.
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
local AnotherComponent = require(somewhere.AnotherComponent)
function MyComponent:Start()
local another = self:GetComponent(AnotherComponent)
end
```
]=]
function Component:GetComponent(componentClass)
return componentClass[KEY_INST_TO_COMPONENTS][self.Instance]
end
--[=[
@tag Component Class
@function HeartbeatUpdate
@param dt number
@within Component
If this method is present on a component, then it will be
automatically connected to `RunService.Heartbeat`.
:::note Method
This is a method, not a function. This is a limitation
of the documentation tool which should be fixed soon.
:::
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
function MyComponent:HeartbeatUpdate(dt)
end
```
]=]
--[=[
@tag Component Class
@function SteppedUpdate
@param dt number
@within Component
If this method is present on a component, then it will be
automatically connected to `RunService.Stepped`.
:::note Method
This is a method, not a function. This is a limitation
of the documentation tool which should be fixed soon.
:::
```lua
local MyComponent = Component.new({Tag = "MyComponent"})
function MyComponent:SteppedUpdate(dt)
end
```
]=]
--[=[
@tag Component Class
@function RenderSteppedUpdate
@param dt number
@within Component
@client
If this method is present on a component, then it will be
automatically connected to `RunService.RenderStepped`. If
the `[Component].RenderPriority` field is found, then the
component will instead use `RunService:BindToRenderStep()`
to bind the function.
:::note Method
This is a method, not a function. This is a limitation
of the documentation tool which should be fixed soon.
:::
```lua
-- Example that uses `RunService.RenderStepped` automatically:
local MyComponent = Component.new({Tag = "MyComponent"})
function MyComponent:RenderSteppedUpdate(dt)
end
```
```lua
-- Example that uses `RunService:BindToRenderStep` automatically:
local MyComponent = Component.new({Tag = "MyComponent"})
-- Defining a RenderPriority will force the component to use BindToRenderStep instead
MyComponent.RenderPriority = Enum.RenderPriority.Camera.Value
function MyComponent:RenderSteppedUpdate(dt)
end
```
]=]
function Component:Destroy()
self[KEY_TROVE]:Destroy()
end
return Component