/
TemplateProvider.lua
400 lines (320 loc) · 9.53 KB
/
TemplateProvider.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
--[=[
Base of a template retrieval system. Templates can be retrieved from Roblox, or from the cloud,
and then retrieved by name. Folders are ignored, so assets may be organized however you want.
Templates can repliate to client if desired.
```lua
-- shared/Templates.lua
return TemplateProvider.new(182451181, script) -- Load from Roblox cloud
```
```lua
-- Server
local serviceBag = ServiceBag.new()
local templates = serviceBag:GetService(require("Templates"))
serviceBag:Init()
serviceBag:Start()
```
```lua
-- Client
local serviceBag = ServiceBag.new()
local templates = serviceBag:GetService(require("Templates"))
serviceBag:Init()
serviceBag:Start()
templates:PromiseClone("Crate"):Then(function(crate)
print("Got crate from the cloud!")
end)
```
@class TemplateProvider
]=]
local require = require(script.Parent.loader).load(script)
local RunService = game:GetService("RunService")
local StarterGui = game:GetService("StarterGui")
local Maid = require("Maid")
local String = require("String")
local InsertServiceUtils = require("InsertServiceUtils")
local Promise = require("Promise")
local TemplateProvider = {}
TemplateProvider.ClassName = "TemplateProvider"
TemplateProvider.ServiceName = "TemplateProvider"
TemplateProvider.__index = TemplateProvider
--[=[
Constructs a new [TemplateProvider].
@param container Instance | table | number -- Value
@param replicationParent Instance? -- Place to replicate instances to.
]=]
function TemplateProvider.new(container, replicationParent)
local self = setmetatable({}, TemplateProvider)
self._replicationParent = replicationParent
self._containersToInitializeSet = {}
self._containersToInitializeList = {}
if typeof(container) == "Instance" or type(container) == "number" then
self:_registerContainer(container)
elseif typeof(container) == "table" then
for _, item in pairs(container) do
assert(typeof(item) == "Instance" or type(item) == "number", "Bad item in initialization set")
self:_registerContainer(item)
-- For easy debugging/iteration loop
if typeof(item) == "Instance"
and item:IsDescendantOf(StarterGui)
and item:IsA("ScreenGui")
and RunService:IsRunning() then
item.Enabled = false
end
end
end
-- Make sure to replicate our parent
if self._replicationParent then
self:_registerContainer(self._replicationParent)
end
return self
end
function TemplateProvider:_registerContainer(container)
assert(typeof(container) == "Instance" or type(container) == "number", "Bad container")
if not self._containersToInitializeSet[container] then
self._containersToInitializeSet[container] = true
table.insert(self._containersToInitializeList, container)
end
end
--[=[
Initializes the container provider. Should be done via [ServiceBag].
]=]
function TemplateProvider:Init()
assert(not self._initialized, "Already initialized")
self._maid = Maid.new()
self._initialized = true
self._registry = {} -- [name] = rawTemplate
self._containersSet = {} -- [parentOrAssetId] = true
self._promises = {} -- [name] = Promise
for _, container in pairs(self._containersToInitializeList) do
self:AddContainer(container)
end
end
--[=[
Promises to clone the template as soon as it exists.
@param templateName string
@return Promise<Instance>
]=]
function TemplateProvider:PromiseClone(templateName)
assert(type(templateName) == "string", "templateName must be a string")
self:_verifyInit()
local template = self._registry[templateName]
if template then
return Promise.resolved(self:Clone(templateName))
end
if not self._promises[templateName] then
local promise = Promise.new()
self._promises[templateName] = promise
-- Make sure to clean up the promise afterwards
self._maid[promise] = promise
promise:Then(function()
self._maid[promise] = nil
end)
task.delay(5, function()
if promise:IsPending() then
warn(("[TemplateProvider.PromiseClone] - May fail to replicate template %q from cloud. %s")
:format(templateName, self:_getReplicationHint()))
end
end)
end
return self._promises[templateName]
:Then(function()
-- Get a new copy
return self:Clone(templateName)
end)
end
function TemplateProvider:_getReplicationHint()
local hint = ""
if RunService:IsClient() then
hint = "Make sure the template provider is initialized on the server."
end
return hint
end
--[=[
Clones the template.
:::info
If the template name has a prefix of "Template" then it will remove it on the cloned instance.
:::
@param templateName string
@return Instance?
]=]
function TemplateProvider:Clone(templateName)
assert(type(templateName) == "string", "templateName must be a string")
self:_verifyInit()
local template = self._registry[templateName]
if not template then
error(("[TemplateProvider.Clone] - Cannot provide %q"):format(tostring(templateName)))
return nil
end
local newItem = template:Clone()
newItem.Name = String.removePostfix(templateName, "Template")
return newItem
end
--[=[
Returns the raw template
@param templateName string
@return Instance?
]=]
function TemplateProvider:Get(templateName)
assert(type(templateName) == "string", "templateName must be a string")
self:_verifyInit()
return self._registry[templateName]
end
--[=[
Adds a new container to the provider for provision of assets.
@param container Instance | number
]=]
function TemplateProvider:AddContainer(container)
assert(typeof(container) == "Instance" or type(container) == "number", "Bad container")
self:_verifyInit()
if not self._containersSet[container] then
self._containersSet[container] = true
if type(container) == "number" then
self._maid[container] = self:_loadCloudAsset(container)
elseif typeof(container) == "Instance" then
self._maid[container] = self:_loadFolder(container)
else
error("Unknown container type to load")
end
end
end
--[=[
Removes a container from the provisioning set.
@param container Instance | number
]=]
function TemplateProvider:RemoveContainer(container)
assert(typeof(container) == "Instance", "Bad container")
self:_verifyInit()
self._containersSet[container] = nil
self._maid[container] = nil
end
--[=[
Returns whether or not a template is registered at the time
@param templateName string
@return boolean
]=]
function TemplateProvider:IsAvailable(templateName)
assert(type(templateName) == "string", "templateName must be a string")
self:_verifyInit()
return self._registry[templateName] ~= nil
end
--[=[
Returns all current registered items.
@return { Instance }
]=]
function TemplateProvider:GetAll()
self:_verifyInit()
local list = {}
for _, item in pairs(self._registry) do
table.insert(list, item)
end
return list
end
--[=[
Gets all current the containers.
@return { Instance | number }
]=]
function TemplateProvider:GetContainers()
self:_verifyInit()
local list = {}
for parent, _ in pairs(self._containersSet) do
table.insert(list, parent)
end
return list
end
function TemplateProvider:_verifyInit()
if not RunService:IsRunning() then
if not self._initialized then
-- Initialize for hoarcecat!
self:Init()
end
end
assert(self._initialized, "TemplateProvider is not initialized")
end
function TemplateProvider:_loadCloudAsset(assetId)
assert(type(assetId) == "number", "Bad assetId")
local maid = Maid.new()
-- Load on server
if RunService:IsServer() or not RunService:IsRunning() then
maid:GivePromise(InsertServiceUtils.promiseAsset(assetId)):Then(function(result)
if RunService:IsRunning() then
for _, item in pairs(result:GetChildren()) do
-- Replicate in children
item.Parent = self._replicationParent
end
else
-- Load without parenting
maid:GiveTask(self:_loadFolder(result))
end
end)
end
return maid
end
function TemplateProvider:_transformParent(getParent)
if typeof(getParent) == "Instance" then
return getParent
elseif type(getParent) == "function" then
local container = getParent()
assert(typeof(container) == "Instance", "Bad container")
return container
else
error("Bad getParent type")
end
end
function TemplateProvider:_loadFolder(parent)
local maid = Maid.new()
-- Only connect events if we're running
if RunService:IsRunning() then
maid:GiveTask(parent.ChildAdded:Connect(function(child)
self:_handleChildAdded(maid, child)
end))
maid:GiveTask(parent.ChildRemoved:Connect(function(child)
self:_handleChildRemoved(maid, child)
end))
end
for _, child in pairs(parent:GetChildren()) do
self:_handleChildAdded(maid, child)
end
maid:GiveTask(function()
maid:DoCleaning()
-- Deregister children
for _, child in pairs(parent:GetChildren()) do
self:_handleChildRemoved(maid, child)
end
end)
return maid
end
function TemplateProvider:_handleChildRemoved(maid, child)
maid[child] = nil
self:_removeFromRegistry(child)
end
function TemplateProvider:_handleChildAdded(maid, child)
if child:IsA("Folder") then
maid[child] = self:_loadFolder(child)
else
self:_addToRegistery(child)
end
end
function TemplateProvider:_addToRegistery(child)
local childName = child.Name
-- if self._registry[childName] then
-- warn(("[TemplateProvider._addToRegistery] - Duplicate %q in registery. Overridding")
-- :format(childName))
-- end
self._registry[childName] = child
if self._promises[childName] then
self._promises[childName]:Resolve(child)
self._promises[childName] = nil
end
end
function TemplateProvider:_removeFromRegistry(child)
local childName = child.Name
if self._registry[childName] == child then
self._registry[childName] = nil
end
end
--[=[
Cleans up the provider
]=]
function TemplateProvider:Destroy()
self._maid:DoCleaning()
end
return TemplateProvider