@quenty/iris 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE.md +22 -0
  3. package/README.md +33 -0
  4. package/default.project.json +14 -0
  5. package/package.json +42 -0
  6. package/src/Shared/Iris.lua +702 -0
  7. package/src/Shared/iris_API.lua +231 -0
  8. package/src/Shared/iris_Internal.lua +923 -0
  9. package/src/Shared/iris_PubTypes.lua +44 -0
  10. package/src/Shared/iris_Types.lua +674 -0
  11. package/src/Shared/iris_WidgetTypes.lua +522 -0
  12. package/src/Shared/iris_config.lua +306 -0
  13. package/src/Shared/iris_demoWindow.lua +2148 -0
  14. package/src/Shared/widgets/iris_Button.lua +91 -0
  15. package/src/Shared/widgets/iris_Checkbox.lua +116 -0
  16. package/src/Shared/widgets/iris_Combo.lua +498 -0
  17. package/src/Shared/widgets/iris_Format.lua +141 -0
  18. package/src/Shared/widgets/iris_Image.lua +156 -0
  19. package/src/Shared/widgets/iris_Input.lua +1430 -0
  20. package/src/Shared/widgets/iris_Menu.lua +603 -0
  21. package/src/Shared/widgets/iris_Plot.lua +642 -0
  22. package/src/Shared/widgets/iris_RadioButton.lua +127 -0
  23. package/src/Shared/widgets/iris_Root.lua +148 -0
  24. package/src/Shared/widgets/iris_Tab.lua +334 -0
  25. package/src/Shared/widgets/iris_Table.lua +641 -0
  26. package/src/Shared/widgets/iris_Text.lua +133 -0
  27. package/src/Shared/widgets/iris_Tree.lua +291 -0
  28. package/src/Shared/widgets/iris_Window.lua +1158 -0
  29. package/src/Shared/widgets/iris_widgets.lua +487 -0
  30. package/src/jest.config.lua +3 -0
  31. package/src/node_modules.project.json +7 -0
  32. package/test/default.project.json +25 -0
  33. package/test/scripts/Server/ServerMain.server.lua +13 -0
@@ -0,0 +1,923 @@
1
+ --!nocheck
2
+ local Types = require(script.Parent.iris_Types)
3
+
4
+ return function(Iris: Types.Iris): Types.Internal
5
+ --[=[
6
+ @class Internal
7
+ An internal class within Iris containing all the backend data and functions for Iris to operate.
8
+ It is recommended that you don't generally interact with Internal unless you understand what you are doing.
9
+ ]=]
10
+ local Internal = {} :: Types.Internal
11
+
12
+ --[[
13
+ ---------------------------------
14
+ [SECTION] Properties
15
+ ---------------------------------
16
+ ]]
17
+
18
+ Internal._version = [[ 2.5.1 ]]
19
+
20
+ Internal._started = false -- has Iris.connect been called yet
21
+ Internal._shutdown = false
22
+ Internal._cycleTick = 0 -- increments for each call to Cycle, used to determine the relative age and freshness of generated widgets
23
+ Internal._deltaTime = 0
24
+
25
+ -- Refresh
26
+ Internal._globalRefreshRequested = false -- refresh means that all GUI is destroyed and regenerated, usually because a style change was made and needed to be propogated to all UI
27
+ Internal._refreshCounter = 0 -- if true, when _Insert is called, the widget called will be regenerated
28
+ Internal._refreshLevel = 1
29
+ Internal._refreshStack = table.create(16)
30
+
31
+ -- Widgets & Instances
32
+ Internal._widgets = {}
33
+ Internal._stackIndex = 1 -- Points to the index that IDStack is currently in, when computing cycle
34
+ Internal._rootInstance = nil
35
+ Internal._rootWidget = {
36
+ ID = "R",
37
+ type = "Root",
38
+ Instance = Internal._rootInstance,
39
+ ZIndex = 0,
40
+ ZOffset = 0,
41
+ }
42
+ Internal._lastWidget = Internal._rootWidget -- widget which was most recently rendered
43
+
44
+ -- Config
45
+ Internal._rootConfig = {} -- root style which all widgets derive from
46
+ Internal._config = Internal._rootConfig
47
+
48
+ -- ID
49
+ Internal._IDStack = { "R" }
50
+ Internal._usedIDs = {} -- hash of IDs which are already used in a cycle, value is the # of occurances so that getID can assign a unique ID for each occurance
51
+ Internal._pushedIds = {}
52
+ Internal._newID = false
53
+ Internal._nextWidgetId = nil
54
+
55
+ -- State
56
+ Internal._states = {} -- Iris.States
57
+
58
+ -- Callback
59
+ Internal._postCycleCallbacks = {}
60
+ Internal._connectedFunctions = {} -- functions which run each Iris cycle, connected by the user
61
+ Internal._connections = {}
62
+ Internal._initFunctions = {}
63
+
64
+ -- Error
65
+ Internal._fullErrorTracebacks = game:GetService("RunService"):IsStudio()
66
+
67
+ --[=[
68
+ @within Internal
69
+ @prop _cycleCoroutine thread
70
+
71
+ The thread which handles all connected functions. Each connection is within a pcall statement which prevents
72
+ Iris from crashing and instead stopping at the error.
73
+ ]=]
74
+ Internal._cycleCoroutine = coroutine.create(function()
75
+ while Internal._started do
76
+ for _, callback in Internal._connectedFunctions do
77
+ debug.profilebegin("Iris/Connection")
78
+ local status, _error: string = pcall(callback)
79
+ debug.profileend()
80
+ if not status then
81
+ -- any error reserts the _stackIndex for the next frame and yields the error.
82
+ Internal._stackIndex = 1
83
+ coroutine.yield(false, _error)
84
+ end
85
+ end
86
+ -- after all callbacks, we yield so it only runs once a frame.
87
+ coroutine.yield(true)
88
+ end
89
+ end)
90
+
91
+ --[[
92
+ -----------------------
93
+ [SECTION] State
94
+ -----------------------
95
+ ]]
96
+
97
+ --[=[
98
+ @class State
99
+ This class wraps a value in getters and setters, its main purpose is to allow primatives to be passed as objects.
100
+ Constructors for this class are available in [Iris]
101
+
102
+ ```lua
103
+ local state = Iris.State(0) -- we initialise the state with a value of 0
104
+
105
+ -- these are equivalent. Ideally you should use `:get()` and ignore `.value`.
106
+ print(state:get())
107
+ print(state.value)
108
+
109
+ state:set(state:get() + 1) -- increments the state by getting the current value and adding 1.
110
+
111
+ state:onChange(function(newValue)
112
+ print(`The value of the state is now: {newValue}`)
113
+ end)
114
+ ```
115
+
116
+ :::caution Caution: Callbacks
117
+ Never call `:set()` on a state when inside the `:onChange()` callback of the same state. This will cause a continous callback.
118
+
119
+ Never chain states together so that each state changes the value of another state in a cyclic nature. This will cause a continous callback.
120
+ :::
121
+ ]=]
122
+ local StateClass = {}
123
+ StateClass.__index = StateClass
124
+
125
+ --[=[
126
+ @within State
127
+ @method get<T>
128
+ @return T
129
+
130
+ Returns the states current value.
131
+ ]=]
132
+ function StateClass:get<T>() -- you can also simply use .value
133
+ return self.value
134
+ end
135
+
136
+ --[=[
137
+ @within State
138
+ @method set<T>
139
+ @param newValue T
140
+ @param force boolean? -- force an update to all connections
141
+ @return T
142
+
143
+ Allows the caller to assign the state object a new value, and returns the new value.
144
+ ]=]
145
+ function StateClass:set<T>(newValue: T, force: true?)
146
+ if newValue == self.value and force ~= true then
147
+ -- no need to update on no change.
148
+ return self.value
149
+ end
150
+ self.value = newValue
151
+ self.lastChangeTick = Iris.Internal._cycleTick
152
+ for _, thisWidget: Types.Widget in self.ConnectedWidgets do
153
+ if thisWidget.lastCycleTick ~= -1 then
154
+ Internal._widgets[thisWidget.type].UpdateState(thisWidget)
155
+ end
156
+ end
157
+
158
+ for _, callback in self.ConnectedFunctions do
159
+ callback(newValue)
160
+ end
161
+ return self.value
162
+ end
163
+
164
+ --[=[
165
+ @within State
166
+ @method onChange<T>
167
+ @param callback (newValue: T) -> ()
168
+ @return () -> ()
169
+
170
+ Allows the caller to connect a callback which is called when the states value is changed.
171
+
172
+ :::caution Caution: Single
173
+ Calling `:onChange()` every frame will add a new function every frame.
174
+ You must ensure you are only calling `:onChange()` once for each callback for the state's entire lifetime.
175
+ :::
176
+ ]=]
177
+ function StateClass:onChange<T>(callback: (newValue: T) -> ())
178
+ local connectionIndex: number = #self.ConnectedFunctions + 1
179
+ self.ConnectedFunctions[connectionIndex] = callback
180
+ return function()
181
+ self.ConnectedFunctions[connectionIndex] = nil
182
+ end
183
+ end
184
+
185
+ --[=[
186
+ @within State
187
+ @method changed<T>
188
+ @return boolean
189
+
190
+ Returns true if the state was changed on this frame.
191
+ ]=]
192
+ function StateClass:changed<T>()
193
+ return self.lastChangeTick + 1 == Internal._cycleTick
194
+ end
195
+
196
+ Internal.StateClass = StateClass
197
+
198
+ --[[
199
+ ---------------------------
200
+ [SECTION] Functions
201
+ ---------------------------
202
+ ]]
203
+
204
+ --[=[
205
+ @within Internal
206
+ @function _cycle
207
+
208
+ Called every frame to handle all of the widget management. Any previous frame data is ammended and everything updates.
209
+ ]=]
210
+ function Internal._cycle(deltaTime: number)
211
+ -- debug.profilebegin("Iris/Cycle")
212
+ if Iris.Disabled then
213
+ return -- Stops all rendering, effectively freezes the current frame with no interaction.
214
+ end
215
+
216
+ Internal._rootWidget.lastCycleTick = Internal._cycleTick
217
+ if Internal._rootInstance == nil or Internal._rootInstance.Parent == nil then
218
+ Iris.ForceRefresh()
219
+ end
220
+
221
+ for _, widget in Internal._lastVDOM do
222
+ if widget.lastCycleTick ~= Internal._cycleTick and (widget.lastCycleTick ~= -1) then
223
+ -- a widget which used to be rendered was not called last frame, so we discard it.
224
+ -- if the cycle tick is -1 we have already discarded it.
225
+ Internal._DiscardWidget(widget)
226
+ end
227
+ end
228
+
229
+ -- represents all widgets created last frame. We keep the _lastVDOM to reuse widgets from the previous frame
230
+ -- rather than creating a new instance every frame.
231
+ setmetatable(Internal._lastVDOM, { __mode = "kv" })
232
+ Internal._lastVDOM = Internal._VDOM
233
+ Internal._VDOM = Internal._generateEmptyVDOM()
234
+
235
+ -- anything that wnats to run before the frame.
236
+ task.spawn(function()
237
+ -- debug.profilebegin("Iris/PostCycleCallbacks")
238
+ for _, callback in Internal._postCycleCallbacks do
239
+ callback()
240
+ end
241
+ -- debug.profileend()
242
+ end)
243
+
244
+ if Internal._globalRefreshRequested then
245
+ -- rerender every widget
246
+ --debug.profilebegin("Iris Refresh")
247
+ Internal._generateSelectionImageObject()
248
+ Internal._globalRefreshRequested = false
249
+ for _, widget in Internal._lastVDOM do
250
+ Internal._DiscardWidget(widget)
251
+ end
252
+ Internal._generateRootInstance()
253
+ Internal._lastVDOM = Internal._generateEmptyVDOM()
254
+ --debug.profileend()
255
+ end
256
+
257
+ -- update counters
258
+ Internal._cycleTick += 1
259
+ Internal._deltaTime = deltaTime
260
+ table.clear(Internal._usedIDs)
261
+
262
+ -- if Internal.parentInstance:IsA("GuiBase2d") and math.min(Internal.parentInstance.AbsoluteSize.X, Internal.parentInstance.AbsoluteSize.Y) < 100 then
263
+ -- error("Iris Parent Instance is too small")
264
+ -- end
265
+ local compatibleParent = (
266
+ Internal.parentInstance:IsA("GuiBase2d") or Internal.parentInstance:IsA("BasePlayerGui")
267
+ )
268
+ if compatibleParent == false then
269
+ error("The Iris parent instance will not display any GUIs.")
270
+ end
271
+
272
+ -- if we are running in Studio, we want full error tracebacks, so we don't have
273
+ -- any pcall to protect from an error.
274
+ if Internal._fullErrorTracebacks then
275
+ -- debug.profilebegin("Iris/Cycle/Callback")
276
+ for _, callback in Internal._connectedFunctions do
277
+ callback()
278
+ end
279
+ else
280
+ -- debug.profilebegin("Iris/Cycle/Coroutine")
281
+
282
+ -- each frame we check on our thread status.
283
+ local coroutineStatus = coroutine.status(Internal._cycleCoroutine)
284
+ if coroutineStatus == "suspended" then
285
+ -- suspended means it yielded, either because it was a complete success
286
+ -- or it caught an error in the code. We run it again for this frame.
287
+ local _, success, result = coroutine.resume(Internal._cycleCoroutine)
288
+ if success == false then
289
+ -- Connected function code errored
290
+ error(result, 0)
291
+ end
292
+ elseif coroutineStatus == "running" then
293
+ -- still running (probably because of an asynchronous method inside a connection).
294
+ error("Iris cycleCoroutine took to long to yield. Connected functions should not yield.")
295
+ else
296
+ -- should never reach this (nothing you can do).
297
+ error("unrecoverable state")
298
+ end
299
+ -- debug.profileend()
300
+ end
301
+
302
+ if Internal._stackIndex ~= 1 then
303
+ -- has to be larger than 1 because of the check that it isnt below 1 in Iris.End
304
+ Internal._stackIndex = 1
305
+ error("Too few calls to Iris.End().", 0)
306
+ end
307
+
308
+ -- Errors if the end user forgot to pop all their ids as they would leak over into the next frame
309
+ -- could also just clear, but that might be confusing behaviour.
310
+ if #Internal._pushedIds ~= 0 then
311
+ error("Too few calls to Iris.PopId().", 0)
312
+ end
313
+
314
+ -- debug.profileend()
315
+ end
316
+
317
+ --[=[
318
+ @within Internal
319
+ @ignore
320
+ @function _NoOp
321
+
322
+ A dummy function which does nothing. Used as a placeholder for optional methods in a widget class.
323
+ Used in `Internal.WidgetConstructor`
324
+ ]=]
325
+ function Internal._NoOp() end
326
+
327
+ -- Widget
328
+
329
+ --[=[
330
+ @within Internal
331
+ @function WidgetConstructor
332
+ @param type string -- name used to denote the widget class.
333
+ @param widgetClass Types.WidgetClass -- table of methods for the new widget.
334
+
335
+ For each widget, a widget class is created which handles all the operations of a widget. This removes the class nature
336
+ of widgets, and simplifies the available functions which can be applied to any widget. The widgets themselves are
337
+ dumb tables containing all the data but no methods to handle any of the data apart from events.
338
+ ]=]
339
+ function Internal.WidgetConstructor(type: string, widgetClass: Types.WidgetClass)
340
+ local Fields = {
341
+ All = {
342
+ Required = {
343
+ "Generate", -- generates the instance.
344
+ "Discard",
345
+ "Update",
346
+
347
+ -- not methods !
348
+ "Args",
349
+ "Events",
350
+ "hasChildren",
351
+ "hasState",
352
+ },
353
+ Optional = {},
354
+ },
355
+ IfState = {
356
+ Required = {
357
+ "GenerateState",
358
+ "UpdateState",
359
+ },
360
+ Optional = {},
361
+ },
362
+ IfChildren = {
363
+ Required = {
364
+ "ChildAdded", -- returns the parent of the child widget.
365
+ },
366
+ Optional = {
367
+ "ChildDiscarded",
368
+ },
369
+ },
370
+ }
371
+
372
+ -- we ensure all essential functions and properties are present, otherwise the code will break later.
373
+ -- some functions will only be needed if the widget has children or has state.
374
+ local thisWidget = {} :: Types.WidgetClass
375
+ for _, field in Fields.All.Required do
376
+ assert(
377
+ widgetClass[field] ~= nil,
378
+ `field {field} is missing from widget {type}, it is required for all widgets`
379
+ )
380
+ thisWidget[field] = widgetClass[field]
381
+ end
382
+
383
+ for _, field in Fields.All.Optional do
384
+ if widgetClass[field] == nil then
385
+ -- assign a dummy function which does nothing.
386
+ thisWidget[field] = Internal._NoOp
387
+ else
388
+ thisWidget[field] = widgetClass[field]
389
+ end
390
+ end
391
+
392
+ if widgetClass.hasState then
393
+ for _, field in Fields.IfState.Required do
394
+ assert(
395
+ widgetClass[field] ~= nil,
396
+ `field {field} is missing from widget {type}, it is required for all widgets with state`
397
+ )
398
+ thisWidget[field] = widgetClass[field]
399
+ end
400
+ for _, field in Fields.IfState.Optional do
401
+ if widgetClass[field] == nil then
402
+ thisWidget[field] = Internal._NoOp
403
+ else
404
+ thisWidget[field] = widgetClass[field]
405
+ end
406
+ end
407
+ end
408
+
409
+ if widgetClass.hasChildren then
410
+ for _, field in Fields.IfChildren.Required do
411
+ assert(
412
+ widgetClass[field] ~= nil,
413
+ `field {field} is missing from widget {type}, it is required for all widgets with children`
414
+ )
415
+ thisWidget[field] = widgetClass[field]
416
+ end
417
+ for _, field in Fields.IfChildren.Optional do
418
+ if widgetClass[field] == nil then
419
+ thisWidget[field] = Internal._NoOp
420
+ else
421
+ thisWidget[field] = widgetClass[field]
422
+ end
423
+ end
424
+ end
425
+
426
+ -- an internal table of all widgets to the widget class.
427
+ Internal._widgets[type] = thisWidget
428
+ -- allowing access to the index for each widget argument.
429
+ Iris.Args[type] = thisWidget.Args
430
+
431
+ local ArgNames = {}
432
+ for index, argument in thisWidget.Args do
433
+ ArgNames[argument] = index
434
+ end
435
+ thisWidget.ArgNames = ArgNames
436
+
437
+ for index, _ in thisWidget.Events do
438
+ if Iris.Events[index] == nil then
439
+ Iris.Events[index] = function()
440
+ return Internal._EventCall(Internal._lastWidget, index)
441
+ end
442
+ end
443
+ end
444
+ end
445
+
446
+ --[=[
447
+ @within Internal
448
+ @function _Insert
449
+ @param widgetType: string -- name of widget class.
450
+ @param arguments { [string]: number } -- arguments of the widget.
451
+ @param states { [string]: States<any> }? -- states of the widget.
452
+ @return Widget -- the widget.
453
+
454
+ Every widget is created through _Insert. An ID is generated based on the line of the calling code and is used to
455
+ find the previous frame widget if it exists. If no widget exists, a new one is created.
456
+ ]=]
457
+ function Internal._Insert(widgetType: string, args: Types.WidgetArguments?, states: Types.WidgetStates?)
458
+ local ID = Internal._getID(3)
459
+ --debug.profilebegin(ID)
460
+
461
+ -- fetch the widget class which contains all the functions for the widget.
462
+ local thisWidgetClass = Internal._widgets[widgetType]
463
+
464
+ if Internal._VDOM[ID] then
465
+ -- widget already created once this frame, so we can append to it.
466
+ return Internal._ContinueWidget(ID, widgetType)
467
+ end
468
+
469
+ local arguments = {} :: Types.Arguments
470
+ if args ~= nil then
471
+ if type(args) ~= "table" then
472
+ args = { args }
473
+ end
474
+
475
+ -- convert the arguments to a key-value dictionary so arguments can be referred to by their name and not index.
476
+ for index, argument in args do
477
+ assert(
478
+ index > 0,
479
+ `Widget Arguments must be a positive number, not {index} of type {typeof(index)} for {argument}.`
480
+ )
481
+ arguments[thisWidgetClass.ArgNames[index]] = argument
482
+ end
483
+ end
484
+ -- prevents tampering with the arguments which are used to check for changes.
485
+ table.freeze(arguments)
486
+
487
+ local lastWidget = Internal._lastVDOM[ID]
488
+ if lastWidget and widgetType == lastWidget.type then
489
+ -- found a matching widget from last frame.
490
+ if Internal._refreshCounter > 0 then
491
+ -- we are redrawing every widget.
492
+ Internal._DiscardWidget(lastWidget)
493
+ lastWidget = nil
494
+ end
495
+ end
496
+ local thisWidget = if lastWidget == nil
497
+ then Internal._GenNewWidget(widgetType, arguments, states, ID)
498
+ else lastWidget
499
+
500
+ local parentWidget = thisWidget.parentWidget
501
+
502
+ if thisWidget.type ~= "Window" and thisWidget.type ~= "Tooltip" then
503
+ if thisWidget.ZIndex ~= parentWidget.ZOffset then
504
+ parentWidget.ZUpdate = true
505
+ end
506
+
507
+ if parentWidget.ZUpdate then
508
+ thisWidget.ZIndex = parentWidget.ZOffset
509
+ if thisWidget.Instance then
510
+ thisWidget.Instance.ZIndex = thisWidget.ZIndex
511
+ thisWidget.Instance.LayoutOrder = thisWidget.ZIndex
512
+ end
513
+ end
514
+ end
515
+
516
+ -- since rows are not instances, but will be removed if not updated, we have to add specific table code.
517
+ if parentWidget.type == "Table" then
518
+ local Table = parentWidget :: Types.Table
519
+ Table._rowCycles[Table._rowIndex] = Internal._cycleTick
520
+ end
521
+
522
+ if Internal._deepCompare(thisWidget.providedArguments, arguments) == false then
523
+ -- the widgets arguments have changed, the widget should update to reflect changes.
524
+ -- providedArguments is the frozen table which will not change.
525
+ -- the arguments can be altered internally, which happens for the input widgets.
526
+ thisWidget.arguments = Internal._deepCopy(arguments)
527
+ thisWidget.providedArguments = arguments
528
+ thisWidgetClass.Update(thisWidget)
529
+ end
530
+
531
+ thisWidget.lastCycleTick = Internal._cycleTick
532
+ parentWidget.ZOffset += 1
533
+
534
+ if thisWidgetClass.hasChildren then
535
+ local thisParent = thisWidget :: Types.ParentWidget
536
+ -- a parent widget, so we increase our depth.
537
+ thisParent.ZOffset = 0
538
+ thisParent.ZUpdate = false
539
+ Internal._stackIndex += 1
540
+ Internal._IDStack[Internal._stackIndex] = thisWidget.ID
541
+ end
542
+
543
+ Internal._VDOM[ID] = thisWidget
544
+ Internal._lastWidget = thisWidget
545
+
546
+ --debug.profileend()
547
+
548
+ return thisWidget
549
+ end
550
+
551
+ --[=[
552
+ @within Internal
553
+ @function _GenNewWidget
554
+ @param widgetType string
555
+ @param arguments { [string]: any } -- arguments of the widget.
556
+ @param states { [string]: State<any> }? -- states of the widget.
557
+ @param ID ID -- id of the new widget. Determined in `Internal._Insert`
558
+ @return Widget -- the newly created widget.
559
+
560
+ All widgets are created as tables with properties. The widget class contains the functions to create the UI instances and
561
+ update the widget or change state.
562
+ ]=]
563
+ function Internal._GenNewWidget(
564
+ widgetType: string,
565
+ arguments: Types.Arguments,
566
+ states: Types.WidgetStates?,
567
+ ID: Types.ID
568
+ )
569
+ local parentId = Internal._IDStack[Internal._stackIndex]
570
+ local parentWidget: Types.ParentWidget = Internal._VDOM[parentId]
571
+ local thisWidgetClass = Internal._widgets[widgetType]
572
+
573
+ -- widgets are just tables with properties.
574
+ local thisWidget = {} :: Types.Widget
575
+ setmetatable(thisWidget, thisWidget)
576
+
577
+ thisWidget.ID = ID
578
+ thisWidget.type = widgetType
579
+ thisWidget.parentWidget = parentWidget
580
+ thisWidget.trackedEvents = {}
581
+ -- thisWidget.UID = HttpService:GenerateGUID(false):sub(0, 8)
582
+
583
+ -- widgets have lots of space to ensure they are always visible.
584
+ thisWidget.ZIndex = parentWidget.ZOffset
585
+
586
+ thisWidget.Instance = thisWidgetClass.Generate(thisWidget)
587
+ -- tooltips set their parent in the generation method, so we need to udpate it here
588
+ parentWidget = thisWidget.parentWidget
589
+
590
+ if Internal._config.Parent then
591
+ thisWidget.Instance.Parent = Internal._config.Parent
592
+ else
593
+ thisWidget.Instance.Parent = Internal._widgets[parentWidget.type].ChildAdded(parentWidget, thisWidget)
594
+ end
595
+
596
+ -- we can modify the arguments table, but keep a frozen copy to compare for user-end changes.
597
+ thisWidget.providedArguments = arguments
598
+ thisWidget.arguments = Internal._deepCopy(arguments)
599
+ thisWidgetClass.Update(thisWidget)
600
+
601
+ local eventMTParent
602
+ if thisWidgetClass.hasState then
603
+ local stateWidget = thisWidget :: Types.StateWidget
604
+ if states then
605
+ for index, state in states do
606
+ if not (type(state) == "table" and getmetatable(state :: any) == Internal.StateClass) then
607
+ -- generate a new state.
608
+ states[index] = Internal._widgetState(stateWidget, index, state)
609
+ end
610
+ states[index].lastChangeTick = Internal._cycleTick
611
+ end
612
+
613
+ stateWidget.state = states
614
+ for _, state in states do
615
+ state.ConnectedWidgets[stateWidget.ID] = stateWidget
616
+ end
617
+ else
618
+ stateWidget.state = {}
619
+ end
620
+
621
+ thisWidgetClass.GenerateState(stateWidget)
622
+ thisWidgetClass.UpdateState(stateWidget)
623
+
624
+ -- the state MT can't be itself because state has to explicitly only contain stateClass objects
625
+ stateWidget.stateMT = {}
626
+ setmetatable(stateWidget.state, stateWidget.stateMT)
627
+
628
+ stateWidget.__index = stateWidget.state
629
+ eventMTParent = stateWidget.stateMT
630
+ else
631
+ eventMTParent = thisWidget
632
+ end
633
+
634
+ eventMTParent.__index = function(_, eventName)
635
+ return function()
636
+ return Internal._EventCall(thisWidget, eventName)
637
+ end
638
+ end
639
+ return thisWidget
640
+ end
641
+
642
+ --[=[
643
+ @within Internal
644
+ @function _ContinueWidget
645
+ @param ID ID -- id of the widget.
646
+ @param widgetType string
647
+ @return Widget -- the widget.
648
+
649
+ Since the widget has already been created this frame, we can just add it back to the stack. There is no checking of
650
+ arguments or states.
651
+ Basically equivalent to the end of `Internal._Insert`.
652
+ ]=]
653
+ function Internal._ContinueWidget(ID: Types.ID, widgetType: string)
654
+ local thisWidgetClass = Internal._widgets[widgetType]
655
+ local thisWidget = Internal._VDOM[ID]
656
+
657
+ if thisWidgetClass.hasChildren then
658
+ -- a parent widget so we increase our depth.
659
+ Internal._stackIndex += 1
660
+ Internal._IDStack[Internal._stackIndex] = thisWidget.ID
661
+ end
662
+
663
+ Internal._lastWidget = thisWidget
664
+ return thisWidget
665
+ end
666
+
667
+ --[=[
668
+ @within Internal
669
+ @function _DiscardWidget
670
+ @param widgetToDiscard Widget
671
+
672
+ Destroys the widget instance and updates any parent. This happens if the widget was not called in the
673
+ previous frame. There is no code which needs to update any widget tables since they are already reset
674
+ at the start before discarding happens.
675
+ ]=]
676
+ function Internal._DiscardWidget(widgetToDiscard: Types.Widget)
677
+ local widgetParent = widgetToDiscard.parentWidget
678
+ if widgetParent then
679
+ -- if the parent needs to update it's children.
680
+ Internal._widgets[widgetParent.type].ChildDiscarded(widgetParent, widgetToDiscard)
681
+ end
682
+
683
+ -- using the widget class discard function.
684
+ Internal._widgets[widgetToDiscard.type].Discard(widgetToDiscard)
685
+
686
+ -- mark as discarded
687
+ widgetToDiscard.lastCycleTick = -1
688
+ end
689
+
690
+ --[=[
691
+ @within Internal
692
+ @function _widgetState
693
+ @param thisWidget Widget -- widget the state belongs to.
694
+ @param stateName string
695
+ @param initialValue any
696
+ @return State<any> -- the state for the widget.
697
+
698
+ Connects the state to the widget. If no state exists then a new one is created. Called for every state in every
699
+ widget if the user does not provide a state.
700
+ ]=]
701
+ function Internal._widgetState<T>(thisWidget: Types.StateWidget, stateName: string, initialValue: T)
702
+ local ID = thisWidget.ID .. stateName
703
+ if Internal._states[ID] then
704
+ Internal._states[ID].ConnectedWidgets[thisWidget.ID] = thisWidget
705
+ Internal._states[ID].lastChangeTick = Internal._cycleTick
706
+ return Internal._states[ID]
707
+ else
708
+ local newState = {
709
+ ID = ID,
710
+ value = initialValue,
711
+ lastChangeTick = Internal._cycleTick,
712
+ ConnectedWidgets = { [thisWidget.ID] = thisWidget },
713
+ ConnectedFunctions = {},
714
+ } :: Types.State<T>
715
+ setmetatable(newState, Internal.StateClass)
716
+ Internal._states[ID] = newState
717
+ return newState
718
+ end
719
+ end
720
+
721
+ --[=[
722
+ @within Internal
723
+ @function _EventCall
724
+ @param thisWidget Widget
725
+ @param evetName string
726
+ @return boolean -- the value of the event.
727
+
728
+ A wrapper for any event on any widget. Automatically, Iris does not initialize events unless they are explicitly
729
+ called so in the first frame, the event connections are set up. Every event is a function which returns a boolean.
730
+ ]=]
731
+ function Internal._EventCall(thisWidget: Types.Widget, eventName: string)
732
+ local Events = Internal._widgets[thisWidget.type].Events
733
+ local Event = Events[eventName]
734
+ assert(Event ~= nil, `widget {thisWidget.type} has no event of name {eventName}`)
735
+
736
+ if thisWidget.trackedEvents[eventName] == nil then
737
+ Event.Init(thisWidget)
738
+ thisWidget.trackedEvents[eventName] = true
739
+ end
740
+ return Event.Get(thisWidget)
741
+ end
742
+
743
+ --[=[
744
+ @within Internal
745
+ @function _GetParentWidget
746
+ @return Widget -- the parent widget
747
+
748
+ Returns the parent widget of the currently active widget, based on the stack depth.
749
+ ]=]
750
+ function Internal._GetParentWidget(): Types.ParentWidget
751
+ return Internal._VDOM[Internal._IDStack[Internal._stackIndex]]
752
+ end
753
+
754
+ -- Generate
755
+
756
+ --[=[
757
+ @ignore
758
+ @within Internal
759
+ @function _generateEmptyVDOM
760
+ @return { [ID]: Widget }
761
+
762
+ Creates the VDOM at the start of each frame containing just the root instance.
763
+ ]=]
764
+ function Internal._generateEmptyVDOM()
765
+ return {
766
+ ["R"] = Internal._rootWidget,
767
+ }
768
+ end
769
+
770
+ --[=[
771
+ @ignore
772
+ @within Internal
773
+ @function _generateRootInstance
774
+
775
+ Creates the root instance.
776
+ ]=]
777
+ function Internal._generateRootInstance()
778
+ -- unsafe to call before Internal.connect
779
+ Internal._rootInstance = Internal._widgets["Root"].Generate(Internal._widgets["Root"])
780
+ Internal._rootInstance.Parent = Internal.parentInstance
781
+ Internal._rootWidget.Instance = Internal._rootInstance
782
+ end
783
+
784
+ --[=[
785
+ @ignore
786
+ @within Internal
787
+ @function _generateSelctionImageObject
788
+
789
+ Creates the selection object for buttons.
790
+ ]=]
791
+ function Internal._generateSelectionImageObject()
792
+ if Internal.SelectionImageObject then
793
+ Internal.SelectionImageObject:Destroy()
794
+ end
795
+
796
+ local SelectionImageObject = Instance.new("Frame")
797
+ SelectionImageObject.Position = UDim2.fromOffset(-1, -1)
798
+ SelectionImageObject.Size = UDim2.new(1, 2, 1, 2)
799
+ SelectionImageObject.BackgroundColor3 = Internal._config.SelectionImageObjectColor
800
+ SelectionImageObject.BackgroundTransparency = Internal._config.SelectionImageObjectTransparency
801
+ SelectionImageObject.BorderSizePixel = 0
802
+
803
+ Internal._utility.UIStroke(
804
+ SelectionImageObject,
805
+ 1,
806
+ Internal._config.SelectionImageObjectBorderColor,
807
+ Internal._config.SelectionImageObjectBorderTransparency
808
+ )
809
+ Internal._utility.UICorner(SelectionImageObject, 2)
810
+
811
+ Internal.SelectionImageObject = SelectionImageObject
812
+ end
813
+
814
+ -- Utility
815
+
816
+ --[=[
817
+ @within Internal
818
+ @function _getID
819
+ @param levelsToIgnore number -- used to skip over internal calls to `_getID`.
820
+ @return ID
821
+
822
+ Generates a unique ID for each widget which is based on the line that the widget is
823
+ created from. This ensures that the function is heuristic and always returns the same
824
+ id for the same widget.
825
+ ]=]
826
+ function Internal._getID(levelsToIgnore: number)
827
+ if Internal._nextWidgetId then
828
+ local ID = Internal._nextWidgetId
829
+ Internal._nextWidgetId = nil
830
+ return ID
831
+ end
832
+
833
+ local i = 1 + (levelsToIgnore or 1)
834
+ local ID = ""
835
+ local levelInfo = debug.info(i, "l")
836
+ while levelInfo ~= -1 and levelInfo ~= nil do
837
+ ID ..= "+" .. levelInfo
838
+ i += 1
839
+ levelInfo = debug.info(i, "l")
840
+ end
841
+
842
+ local discriminator = Internal._usedIDs[ID]
843
+ if discriminator then
844
+ Internal._usedIDs[ID] += 1
845
+ discriminator += 1
846
+ else
847
+ Internal._usedIDs[ID] = 1
848
+ discriminator = 1
849
+ end
850
+
851
+ if #Internal._pushedIds == 0 then
852
+ return ID .. ":" .. discriminator
853
+ elseif Internal._newID then
854
+ Internal._newID = false
855
+ return ID .. "::" .. table.concat(Internal._pushedIds, "\\")
856
+ else
857
+ return ID .. ":" .. discriminator .. ":" .. table.concat(Internal._pushedIds, "\\")
858
+ end
859
+ end
860
+
861
+ --[=[
862
+ @ignore
863
+ @within Internal
864
+ @function _deepCompare
865
+ @param t1 {}
866
+ @param t2 {}
867
+ @return boolean
868
+
869
+ Compares two tables to check if they are the same. It uses a recursive iteration through one table
870
+ to compare against the other. Used to determine if the arguments of a widget have changed since last
871
+ frame.
872
+ ]=]
873
+ function Internal._deepCompare(t1: {}, t2: {})
874
+ -- unoptimized ?
875
+ for i, v1 in t1 do
876
+ local v2 = t2[i]
877
+ if type(v1) == "table" then
878
+ if v2 and type(v2) == "table" then
879
+ if Internal._deepCompare(v1, v2) == false then
880
+ return false
881
+ end
882
+ else
883
+ return false
884
+ end
885
+ else
886
+ if type(v1) ~= type(v2) or v1 ~= v2 then
887
+ return false
888
+ end
889
+ end
890
+ end
891
+
892
+ return true
893
+ end
894
+
895
+ --[=[
896
+ @ignore
897
+ @within Internal
898
+ @function _deepCopy
899
+ @param t {}
900
+ @return {}
901
+
902
+ Performs a deep copy of a table so that neither table contains a shared reference.
903
+ ]=]
904
+ function Internal._deepCopy(t: {}): {}
905
+ local copy: {} = table.clone(t)
906
+
907
+ for k, v in t do
908
+ if type(v) == "table" then
909
+ copy[k] = Internal._deepCopy(v)
910
+ end
911
+ end
912
+
913
+ return copy
914
+ end
915
+
916
+ -- VDOM
917
+ Internal._lastVDOM = Internal._generateEmptyVDOM()
918
+ Internal._VDOM = Internal._generateEmptyVDOM()
919
+
920
+ Iris.Internal = Internal
921
+ Iris._config = Internal._config
922
+ return Internal
923
+ end