-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathinit.lua
More file actions
1271 lines (1114 loc) · 37.5 KB
/
Copy pathinit.lua
File metadata and controls
1271 lines (1114 loc) · 37.5 KB
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--!nonstrict
--[[
The majority of this code is an interface designed to make it easy for you to
work with TopbarPlus (most methods for instance reference :modifyTheme()).
The processing overhead mainly consists of applying themes and calculating
appearance (such as size and width of labels) which is handled in about
200 lines of code here and the Widget UI module. This has been achieved
in v3 by outsourcing a majority of previous calculations to inbuilt Roblox
features like UIListLayouts.
v3 provides inbuilt support for controllers (simply press DPadUp),
touch devices (phones, tablets , etc), localization (automatic resizing
of widgets, autolocalize for relevant labels), backwards compatability
with the old topbar, and more.
My primary goals for the v3 re-write have been to:
1. Improve code readability and organisation (reduced lines of code within
Icon+IconController from 3200 to ~950, separated UI elements, etc)
2. Improve ease-of-use (themes now actually make sense and can account
for any modifications you want, converted to a package for
quick installation and easy-comparisons of new updates, etc)
3. Provide support for all key features of the new Roblox topbar
while improving performance of the module (deferring and collecting
changes then calling as a singular, utilizing inbuilt Roblox features
such as UILIstLayouts, etc)
--]]
-- SERVICES
local UserInputService = game:GetService("UserInputService")
local ContentProvider = game:GetService("ContentProvider")
local StarterGui = game:GetService("StarterGui")
local Players = game:GetService("Players")
local Types = require(script.Types)
-- TYPES
export type Icon = Types.Icon
-- REFERENCE HANDLER
-- Multiple Icons packages may exist at runtime (for instance if the developer additionally uses HD Admin)
-- therefore this ensures that the first required package becomes the dominant and only functioning module
local iconModule = script
local Reference = require(iconModule.Reference)
local referenceObject = Reference.getObject()
local leadPackage = referenceObject and referenceObject.Value
if leadPackage and leadPackage ~= iconModule then
return require(leadPackage) :: Types.StaticIcon
end
if not referenceObject then
Reference.addToReplicatedStorage()
end
-- MODULES
local Signal = require(iconModule.Packages.GoodSignal)
local Janitor = require(iconModule.Packages.Janitor)
local Utility = require(iconModule.Utility)
local Themes = require(iconModule.Features.Themes)
local Gamepad = require(iconModule.Features.Gamepad)
local Overflow = require(iconModule.Features.Overflow)
local Icon = {}
Icon.__index = Icon
--- LOCAL
local localPlayer = Players.LocalPlayer
local themes = iconModule.Features.Themes
local iconsDict = {}
local anyIconSelected = Signal.new()
local elements = iconModule.Elements
local totalCreatedIcons = 0
local preferredInput = {
mobile = Enum.PreferredInput.Touch,
desktop = Enum.PreferredInput.KeyboardAndMouse,
console = Enum.PreferredInput.Gamepad
}
-- PUBLIC VARIABLES
Icon.baseDisplayOrderChanged = Signal.new()
Icon.baseDisplayOrder = 10
Icon.baseTheme = require(themes.Default)
Icon.isOldTopbar = false -- Logic has been moved to Container
Icon.iconsDictionary = iconsDict
Icon.insetHeightChanged = Signal.new()
Icon.container = require(elements.Container)(Icon)
Icon.topbarEnabled = true
Icon.iconAdded = Signal.new()
Icon.iconRemoved = Signal.new()
Icon.iconChanged = Signal.new()
-- PUBLIC FUNCTIONS
function Icon.getIcons()
return Icon.iconsDictionary
end
function Icon.getIconByUID(UID)
local match = Icon.iconsDictionary[UID]
if match then
return match
end
return nil
end
function Icon.getIcon(nameOrUID)
local match = Icon.getIconByUID(nameOrUID)
if match then
return match
end
for _, icon in pairs(iconsDict) do
if icon.name == nameOrUID then
return icon
end
end
return nil
end
function Icon.setTopbarEnabled(bool, isInternal)
if typeof(bool) ~= "boolean" then
bool = Icon.topbarEnabled
end
if not isInternal then
Icon.topbarEnabled = bool
end
for _, screenGui in pairs(Icon.container) do
screenGui.Enabled = bool
end
end
function Icon.modifyBaseTheme(modifications)
modifications = Themes.getModifications(modifications)
for _, modification in pairs(modifications) do
for _, detail in pairs(Icon.baseTheme) do
Themes.merge(detail, modification)
end
end
for _, icon in pairs(iconsDict) do
icon:setTheme(Icon.baseTheme)
end
end
function Icon.setDisplayOrder(int)
Icon.baseDisplayOrder = int
Icon.baseDisplayOrderChanged:Fire(int)
end
-- SETUP
task.defer(Gamepad.start, Icon)
task.defer(Overflow.start, Icon)
task.defer(function()
local playerGui = localPlayer:WaitForChild("PlayerGui")
for _, screenGui in pairs(Icon.container) do
screenGui.Parent = playerGui
end
require(iconModule.Attribute)
end)
-- CONSTRUCTOR
function Icon.new()
local self = {}
setmetatable(self, Icon)
--- Janitors (for cleanup)
local janitor = Janitor.new()
self.janitor = janitor
self.themesJanitor = janitor:add(Janitor.new())
self.singleClickJanitor = janitor:add(Janitor.new())
self.captionJanitor = janitor:add(Janitor.new())
self.joinJanitor = janitor:add(Janitor.new())
self.menuJanitor = janitor:add(Janitor.new())
self.dropdownJanitor = janitor:add(Janitor.new())
-- Register
local iconUID = Utility.generateUID()
iconsDict[iconUID] = self
janitor:add(function()
iconsDict[iconUID] = nil
end)
-- Signals (events)
self.selected = janitor:add(Signal.new())
self.deselected = janitor:add(Signal.new())
self.toggled = janitor:add(Signal.new())
self.viewingStarted = janitor:add(Signal.new())
self.viewingEnded = janitor:add(Signal.new())
self.stateChanged = janitor:add(Signal.new())
self.notified = janitor:add(Signal.new())
self.noticeStarted = janitor:add(Signal.new())
self.noticeChanged = janitor:add(Signal.new())
self.endNotices = janitor:add(Signal.new())
self.toggleKeyAdded = janitor:add(Signal.new())
self.fakeToggleKeyChanged = janitor:add(Signal.new())
self.alignmentChanged = janitor:add(Signal.new())
self.updateSize = janitor:add(Signal.new())
self.resizingComplete = janitor:add(Signal.new())
self.joinedParent = janitor:add(Signal.new())
self.menuSet = janitor:add(Signal.new())
self.dropdownSet = janitor:add(Signal.new())
self.updateMenu = janitor:add(Signal.new())
self.startMenuUpdate = janitor:add(Signal.new())
self.childThemeModified = janitor:add(Signal.new())
self.indicatorSet = janitor:add(Signal.new())
self.dropdownChildAdded = janitor:add(Signal.new())
self.menuChildAdded = janitor:add(Signal.new())
-- Properties
self.iconModule = iconModule
self.UID = iconUID
self.isEnabled = true
self.enabled = self.isEnabled -- Backwards compatability
self.isSelected = false
self.isViewing = false
self.joinedFrame = false
self.parentIconUID = false
self.deselectWhenOtherIconSelected = true
self.totalNotices = 0
self.activeState = "Deselected"
self.alignment = ""
self.originalAlignment = ""
self.appliedTheme = {}
self.appearance = {}
self.cachedInstances = {}
self.cachedNamesToInstances = {}
self.cachedCollectives = {}
self.bindedToggleKeys = {}
self.customBehaviours = {}
self.toggleItems = {}
self.bindedEvents = {}
self.notices = {}
self.menuIcons = {}
self.dropdownIcons = {}
self.childIconsDict = {}
self.creationTime = os.clock()
self.bindedSignalEvents = {}
-- Widget is the new name for an icon
local widget = janitor:add(require(elements.Widget)(self, Icon))
self.widget = widget
self:setAlignment()
-- It's important we set an order otherwise icons will not align
-- correctly within menus
totalCreatedIcons += 1
local ourOrder = 1+(totalCreatedIcons*0.01)
self:setOrder(ourOrder, "deselected")
self:setOrder(ourOrder, "selected")
-- This applies the default them
self:setTheme(Icon.baseTheme)
-- Button Clicked (for states "Selected" and "Deselected")
local clickRegion = self:getInstance("ClickRegion")
local hasUsedMouseButton1Click = false
local lastToggleTime = 0
local DEBOUNCE_TIME = 0.1 -- 100ms debounce to prevent rapid toggles
local function handleToggle()
if self.locked then
return
end
-- Debounce logic to prevent rapid toggling
local currentTime = tick()
if currentTime - lastToggleTime < DEBOUNCE_TIME then
return
end
lastToggleTime = currentTime
if self.isSelected then
self:deselect("User", self)
else
self:select("User", self)
end
end
clickRegion.MouseButton1Click:Connect(function()
hasUsedMouseButton1Click = true
handleToggle()
end)
clickRegion.TouchTap:Connect(function()
-- This resolves the bug report by @28Pixels:
-- https://devforum.roblox.com/t/topbarplus/1017485/1104
-- Only use TouchTap if MouseButton1Click has never fired
-- This handles edge cases where ONLY TouchTap works
-- Also prevents double-toggle bug with multi-touch on mobile
-- Credit to @sayer80 for this fix
if not hasUsedMouseButton1Click then
handleToggle()
end
end)
-- Keys can be bound to toggle between Selected and Deselected
janitor:add(UserInputService.InputBegan:Connect(function(input, touchingAnObject)
if self.locked then
return
end
if self.bindedToggleKeys[input.KeyCode] and not touchingAnObject then
handleToggle()
end
end))
-- Button Hovering (for state "Viewing")
-- Hovering is a state only for devices with keyboards
-- and controllers (not touchpads)
local function viewingStarted(dontSetState)
if self.locked then
return
end
self.isViewing = true
self.viewingStarted:Fire(true)
if not dontSetState then
self:setState("Viewing", "User", self)
end
end
local function viewingEnded()
if self.locked then
return
end
self.isViewing = false
self.viewingEnded:Fire(true)
self:setState(nil, "User", self)
end
self.joinedParent:Connect(function()
if self.isViewing then
viewingEnded()
end
end)
clickRegion.MouseEnter:Connect(function()
local dontSetState = UserInputService.PreferredInput ~= preferredInput.desktop
viewingStarted(dontSetState)
end)
local touchCount = 0
janitor:add(UserInputService.TouchEnded:Connect(viewingEnded))
clickRegion.MouseLeave:Connect(viewingEnded)
clickRegion.SelectionGained:Connect(viewingStarted)
clickRegion.SelectionLost:Connect(viewingEnded)
clickRegion.MouseButton1Down:Connect(function()
if not self.locked and UserInputService.PreferredInput == preferredInput.mobile then
touchCount += 1
local myTouchCount = touchCount
task.delay(0.2, function()
if myTouchCount == touchCount then
viewingStarted()
end
end)
end
end)
clickRegion.MouseButton1Up:Connect(function()
touchCount += 1
end)
-- Handle overlay on viewing
local iconOverlay = self:getInstance("IconOverlay")
self.viewingStarted:Connect(function()
iconOverlay.Visible = not self.overlayDisabled
end)
self.viewingEnded:Connect(function()
iconOverlay.Visible = false
end)
-- Deselect when another icon is selected
janitor:add(anyIconSelected:Connect(function(incomingIcon)
if incomingIcon ~= self and self.deselectWhenOtherIconSelected and incomingIcon.deselectWhenOtherIconSelected then
self:deselect("AutoDeselect", incomingIcon)
end
end))
-- This checks if the script calling this module is a descendant of a ScreenGui
-- with 'ResetOnSpawn' set to true. If it is, then we destroy the icon the
-- client respawns. This solves one of the most asked about questions on the post
-- The only caveat this may not work if the player doesn't uniquely name their ScreenGui and the frames
-- the LocalScript rests within
local source = debug.info(2, "s")
local sourcePath = string.split(source, ".")
local origin = game
local originsScreenGui
for i, sourceName in pairs(sourcePath) do
origin = origin:FindFirstChild(sourceName)
if not origin then
break
end
if origin:IsA("ScreenGui") then
originsScreenGui = origin
end
end
if origin and originsScreenGui and originsScreenGui.ResetOnSpawn == true then
self.originsScreenGui = originsScreenGui
Utility.localPlayerRespawned(function()
self:destroy()
end)
end
-- Additional children behaviour when toggled (mostly notices)
self.toggled:Connect(function(isSelected)
self.noticeChanged:Fire(self.totalNotices)
for childIconUID, _ in pairs(self.childIconsDict) do
local childIcon = Icon.getIconByUID(childIconUID)
childIcon.noticeChanged:Fire(childIcon.totalNotices)
if not isSelected and childIcon.isSelected then
-- If an icon within a menu or dropdown is also
-- a dropdown or menu, then close it
for _, _ in pairs(childIcon.childIconsDict) do
childIcon:deselect("HideParentFeature", self)
end
end
end
end)
-- This closes/reopens the chat or playerlist if the icon is a dropdown
-- In the future I'd prefer to use the position+size of the chat
-- to determine whether to close dropdown (instead of non-right-set)
-- but for reasons mentioned here it's unreliable at the time of
-- writing this: https://devforum.roblox.com/t/here/2794915
-- I could also make this better by accounting for multiple
-- dropdowns being open (not just this one) but this will work
-- fine for almost every use case for now.
self.selected:Connect(function()
local isDropdown = #self.dropdownIcons > 0
if isDropdown then
if StarterGui:GetCore("ChatActive") and self.alignment ~= "Right" then
self.chatWasPreviouslyActive = true
StarterGui:SetCore("ChatActive", false)
end
if StarterGui:GetCoreGuiEnabled("PlayerList") and self.alignment ~= "Left" then
self.playerlistWasPreviouslyActive = true
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.PlayerList, false)
end
end
end)
self.deselected:Connect(function()
if self.chatWasPreviouslyActive then
self.chatWasPreviouslyActive = nil
StarterGui:SetCore("ChatActive", true)
end
if self.playerlistWasPreviouslyActive then
self.playerlistWasPreviouslyActive = nil
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.PlayerList, true)
end
end)
-- There's a rare occassion where the appearance is not
-- fully set to deselected so this ensures the icons
-- appearance is fully as it should be
task.delay(0.1, function()
if self.activeState == "Deselected" then
self.stateChanged:Fire("Deselected")
self:refresh()
end
end)
-- Call icon added
Icon.iconAdded:Fire(self)
return self
end
-- METHODS
function Icon:setName(name)
self.widget.Name = name
self.name = name
return self
end
function Icon:setState(incomingStateName, fromSource, sourceIcon)
-- This is responsible for acknowleding a change in stage (such as from "Deselected" to "Viewing" when
-- a users mouse enters the widget), then informing other systems of this state change to then act upon
-- (such as the theme handler applying the theme which corresponds to that state).
if not incomingStateName then
incomingStateName = (self.isSelected and "Selected") or "Deselected"
end
local stateName = Utility.formatStateName(incomingStateName)
local previousStateName = self.activeState
if previousStateName == stateName then
return
end
local currentIsSelected = self.isSelected
self.activeState = stateName
if stateName == "Deselected" then
self.isSelected = false
if currentIsSelected then
self.toggled:Fire(false, fromSource, sourceIcon)
self.deselected:Fire(fromSource, sourceIcon)
end
self:_setToggleItemsVisible(false, fromSource, sourceIcon)
elseif stateName == "Selected" then
self.isSelected = true
if not currentIsSelected then
self.toggled:Fire(true, fromSource, sourceIcon)
self.selected:Fire(fromSource, sourceIcon)
anyIconSelected:Fire(self, fromSource, sourceIcon)
end
self:_setToggleItemsVisible(true, fromSource, sourceIcon)
end
self.stateChanged:Fire(stateName, fromSource, sourceIcon)
end
function Icon:getInstance(name)
-- This enables us to easily retrieve instances located within the icon simply by passing its name.
-- Every important/significant instance is named uniquely therefore this is no worry of overlap.
-- We cache the result for more performant retrieval in the future.
local instance = self.cachedNamesToInstances[name]
if instance then
return instance
end
local function cacheInstance(childName, child)
local currentCache = self.cachedInstances[child]
if not currentCache then
local collectiveName = child:GetAttribute("Collective")
local cachedCollective = collectiveName and self.cachedCollectives[collectiveName]
if cachedCollective then
table.insert(cachedCollective, child)
end
self.cachedNamesToInstances[childName] = child
self.cachedInstances[child] = true
child.Destroying:Once(function()
self.cachedNamesToInstances[childName] = nil
self.cachedInstances[child] = nil
end)
end
end
local widget = self.widget
cacheInstance("Widget", widget)
if name == "Widget" then
return widget
end
local returnChild
local function scanChildren(parentInstance)
for _, child in pairs(parentInstance:GetChildren()) do
local widgetUID = child:GetAttribute("WidgetUID")
if widgetUID and widgetUID ~= self.UID then
-- This prevents instances within other icons from being recorded
-- (for instance when other icons are added to this icons menu)
continue
end
-- If the child is a fake placeholder instance (such as dropdowns, notices, etc)
-- then its important we scan the real original instance instead of this clone
local realChild = Themes.getRealInstance(child)
if realChild then
child = realChild
end
-- Finally scan its children
scanChildren(child)
if child:IsA("GuiBase") or child:IsA("UIBase") or child:IsA("ValueBase") then
local childName = child.Name
cacheInstance(childName, child)
if childName == name then
returnChild = child
end
end
end
end
scanChildren(widget)
return returnChild
end
function Icon:getCollective(name)
-- A collective is an array of instances within the Widget that have been
-- grouped together based on a given name. This just makes it easy
-- to act on multiple instances at once which share similar behaviours.
-- For instance, if we want to change the icons corner size, all corner instances
-- with the attribute "Collective" and value "WidgetCorner" could be updated
-- instantly by doing Themes.apply(icon, "WidgetCorner", newSize)
local collective = self.cachedCollectives[name]
if collective then
return collective
end
collective = {}
for instance, _ in pairs(self.cachedInstances) do
if instance:GetAttribute("Collective") == name then
table.insert(collective, instance)
end
end
self.cachedCollectives[name] = collective
return collective
end
function Icon:getInstanceOrCollective(collectiveOrInstanceName)
-- Similar to :getInstance but also accounts for 'Collectives', such as UICorners and returns
-- an array of instances instead of a single instance
local instances = {}
local instance = self:getInstance(collectiveOrInstanceName)
if instance then
table.insert(instances, instance)
end
if #instances == 0 then
instances = self:getCollective(collectiveOrInstanceName)
end
return instances
end
function Icon:getStateGroup(iconState)
local chosenState = iconState or self.activeState
local stateGroup = self.appearance[chosenState]
if not stateGroup then
stateGroup = {}
self.appearance[chosenState] = stateGroup
end
return stateGroup
end
function Icon:refreshAppearance(instance, specificProperty)
Themes.refresh(self, instance, specificProperty)
return self
end
function Icon:refresh()
self:refreshAppearance(self.widget)
self.updateSize:Fire()
return self
end
function Icon:updateParent()
local parentIcon = Icon.getIconByUID(self.parentIconUID)
if parentIcon then
parentIcon.updateSize:Fire()
end
end
function Icon:setBehaviour(collectiveOrInstanceName, property, callback, refreshAppearance)
-- You can specify your own custom callback to handle custom logic just before
-- an instances property is changed by using :setBehaviour()
local key = collectiveOrInstanceName.."-"..property
self.customBehaviours[key] = callback
if refreshAppearance then
local instances = self:getInstanceOrCollective(collectiveOrInstanceName)
for _, instance in pairs(instances) do
self:refreshAppearance(instance, property)
end
end
end
function Icon:modifyTheme(modifications, customModificationUID)
local modificationUID = Themes.modify(self, modifications, customModificationUID)
return self, modificationUID
end
function Icon:modifyChildTheme(modifications, modificationUID)
-- Same as modifyTheme except for its children (i.e. icons
-- within its dropdown or menu)
self.childModifications = modifications
self.childModificationsUID = modificationUID
for childIconUID, _ in pairs(self.childIconsDict) do
local childIcon = Icon.getIconByUID(childIconUID)
childIcon:modifyTheme(modifications, modificationUID)
end
self.childThemeModified:Fire()
return self
end
function Icon:removeModification(modificationUID)
Themes.remove(self, modificationUID)
return self
end
function Icon:removeModificationWith(instanceName, property, state)
Themes.removeWith(self, instanceName, property, state)
return self
end
function Icon:setTheme(theme)
Themes.set(self, theme)
return self
end
function Icon:setEnabled(bool)
self.isEnabled = bool
self.enabled = self.isEnabled
self.widget.Visible = bool
self:updateParent()
return self
end
function Icon:select(fromSource, sourceIcon)
self:setState("Selected", fromSource, sourceIcon)
return self
end
function Icon:deselect(fromSource, sourceIcon)
self:setState("Deselected", fromSource, sourceIcon)
return self
end
function Icon:notify(customClearSignal, noticeId)
-- Generates a notification which appears in the top right of the icon. Useful for example for prompting
-- users of changes/updates within your UI such as a Catalog
-- 'customClearSignal' is a signal object (e.g. icon.deselected) or
-- Roblox event (e.g. Instance.new("BindableEvent").Event)
local notice = self.notice
if not notice then
notice = require(elements.Notice)(self, Icon)
self.notice = notice
end
self.noticeStarted:Fire(customClearSignal, noticeId)
return self
end
function Icon:clearNotices()
self.endNotices:Fire()
return self
end
function Icon:disableOverlay(bool)
self.overlayDisabled = bool
return self
end
Icon.disableStateOverlay = Icon.disableOverlay
function Icon:setImage(imageId, iconState)
self:modifyTheme({"IconImage", "Image", imageId, iconState})
-- This code ensures icon images are preloaded if they haven't been fetched yet
task.spawn(function()
local newIdContent = if tonumber(imageId) then `rbxassetid://{imageId}` else imageId
local initialAssetFetchStatus = ContentProvider:GetAssetFetchStatus(newIdContent)
if initialAssetFetchStatus ~= Enum.AssetFetchStatus.Success then
pcall(ContentProvider.PreloadAsync, ContentProvider, { newIdContent })
end
end)
return self
end
function Icon:setLabel(text, iconState)
self:modifyTheme({"IconLabel", "Text", text, iconState})
return self
end
function Icon:setOrder(int, iconState)
-- We multiply by 100 to allow for custom increments inbetween
-- (.01, .02, etc) as LayoutOrders only support integers
local newInt = int*100
self:modifyTheme({"IconSpot", "LayoutOrder", newInt, iconState})
self:modifyTheme({"Widget", "LayoutOrder", newInt, iconState})
return self
end
function Icon:setCornerRadius(udim, iconState)
self:modifyTheme({"IconCorners", "CornerRadius", udim, iconState})
return self
end
function Icon:align(leftCenterOrRight, isFromParentIcon)
-- Determines the side of the screen the icon will be ordered
local direction = tostring(leftCenterOrRight):lower()
if direction == "mid" or direction == "centre" then
direction = "center"
end
if direction ~= "left" and direction ~= "center" and direction ~= "right" then
direction = "left"
end
local screenGui = (direction == "center" and Icon.container.TopbarCentered) or Icon.container.TopbarStandard
local holders = screenGui.Holders
local finalDirection = string.upper(string.sub(direction, 1, 1))..string.sub(direction, 2)
if not isFromParentIcon then
self.originalAlignment = finalDirection
end
local joinedFrame = self.joinedFrame
local alignmentHolder = holders[finalDirection]
self.screenGui = screenGui
self.alignmentHolder = alignmentHolder
if not self.isDestroyed then
self.widget.Parent = joinedFrame or alignmentHolder
end
self.alignment = finalDirection
self.alignmentChanged:Fire(finalDirection)
Icon.iconChanged:Fire(self)
return self
end
Icon.setAlignment = Icon.align
function Icon:setLeft()
self:setAlignment("Left")
return self
end
function Icon:setMid()
self:setAlignment("Center")
return self
end
function Icon:setRight()
self:setAlignment("Right")
return self
end
function Icon:setWidth(offsetMinimum, iconState)
-- This sets a minimum X offset size for the widget, useful
-- for example if you're constantly changing the label
-- but don't want the icon to resize every time
self:modifyTheme({"Widget", "DesiredWidth", offsetMinimum, iconState})
return self
end
function Icon:setImageScale(number, iconState)
self:modifyTheme({"IconImageScale", "Value", number, iconState})
return self
end
function Icon:setImageRatio(number, iconState)
self:modifyTheme({"IconImageRatio", "AspectRatio", number, iconState})
return self
end
function Icon:setTextSize(number, iconState)
self:modifyTheme({"IconLabel", "TextSize", number, iconState})
return self
end
function Icon:setTextFont(font, fontWeight, fontStyle, iconState)
fontWeight = fontWeight or Enum.FontWeight.Regular
fontStyle = fontStyle or Enum.FontStyle.Normal
local fontFace
local fontType = typeof(font)
if fontType == "number" then
fontFace = Font.fromId(font, fontWeight, fontStyle)
elseif fontType == "EnumItem" then
fontFace = Font.fromEnum(font)
elseif fontType == "string" then
if not font:match("rbxasset") then
fontFace = Font.fromName(font, fontWeight, fontStyle)
end
end
if not fontFace then
fontFace = Font.new(font, fontWeight, fontStyle)
end
self:modifyTheme({"IconLabel", "FontFace", fontFace, iconState})
return self
end
function Icon:setTextColor(Color, iconState)
if Color == nil or Color == "" or (type(Color) ~= "userdata" or typeof(Color) ~= "Color3") then
if Color ~= nil and Color ~= "" then
warn("setTextColor item must be a Color3 value! Changed the color to white.")
end
Color = Color3.fromRGB(255, 255, 255)
end
self:modifyTheme({"IconLabel", "TextColor3", Color, iconState})
return self
end
function Icon:bindToggleItem(guiObjectOrLayerCollector)
if not guiObjectOrLayerCollector:IsA("GuiObject") and not guiObjectOrLayerCollector:IsA("LayerCollector") then
error("Toggle item must be a GuiObject or LayerCollector!")
end
self.toggleItems[guiObjectOrLayerCollector] = true
self:_updateSelectionInstances()
return self
end
function Icon:unbindToggleItem(guiObjectOrLayerCollector)
self.toggleItems[guiObjectOrLayerCollector] = nil
self:_updateSelectionInstances()
return self
end
function Icon:_updateSelectionInstances()
-- This is to assist with controller navigation and selection
-- It converts the value true to an array
for guiObjectOrLayerCollector, _ in pairs(self.toggleItems) do
local buttonInstancesArray = {}
for _, instance in pairs(guiObjectOrLayerCollector:GetDescendants()) do
if (instance:IsA("TextButton") or instance:IsA("ImageButton")) and instance.Active then
table.insert(buttonInstancesArray, instance)
end
end
self.toggleItems[guiObjectOrLayerCollector] = buttonInstancesArray
end
end
function Icon:_setToggleItemsVisible(bool, fromSource, sourceIcon)
for toggleItem, _ in pairs(self.toggleItems) do
if not sourceIcon or sourceIcon == self or sourceIcon.toggleItems[toggleItem] == nil then
local property = "Visible"
if toggleItem:IsA("LayerCollector") then
property = "Enabled"
end
toggleItem[property] = bool
end
end
end
function Icon:bindEvent(iconEventName, eventFunction)
local event = self[iconEventName]
assert(event and typeof(event) == "table" and event.Connect, "argument[1] must be a valid topbarplus icon event name!")
assert(typeof(eventFunction) == "function", "argument[2] must be a function!")
self.bindedEvents[iconEventName] = event:Connect(function(...)
eventFunction(self, ...)
end)
return self
end
function Icon:unbindEvent(iconEventName)
local eventConnection = self.bindedEvents[iconEventName]
if eventConnection then
eventConnection:Disconnect()
self.bindedEvents[iconEventName] = nil
end
return self
end
function Icon:bindSignal(signal, signalFunction)
assert(typeof(signal) == "RBXScriptSignal", "argument[1] must be a valid RBXScriptSignal!")
assert(typeof(signalFunction) == "function", "argument[2] must be a function!")
local connection = signal:Connect(function(...)
signalFunction(self, ...)
end)
self.bindSignalEvents[signal] = connection
return self
end
function Icon:unbindSignal(signal)
local connection = self.bindSignalEvents[signal]
if connection then
connection:Disconnect()
self.bindSignalEvents[signal] = nil
end
return self
end
function Icon:bindToggleKey(keyCodeEnum)
assert(typeof(keyCodeEnum) == "EnumItem", "argument[1] must be a KeyCode EnumItem!")
self.bindedToggleKeys[keyCodeEnum] = true
self.toggleKeyAdded:Fire(keyCodeEnum)
self:setCaption("_hotkey_")
return self
end
function Icon:unbindToggleKey(keyCodeEnum)
assert(typeof(keyCodeEnum) == "EnumItem", "argument[1] must be a KeyCode EnumItem!")
self.bindedToggleKeys[keyCodeEnum] = nil
return self
end
function Icon:call(callback, ...)
local packedArgs = table.pack(...)
task.spawn(function()
callback(self, table.unpack(packedArgs))
end)
return self
end
function Icon:addToJanitor(callback, methodName, index)
self.janitor:add(callback, methodName, index)
return self
end
function Icon:lock()
-- This disables all user inputs related to the icon (such as clicking buttons, pressing keys, etc)
local clickRegion = self:getInstance("ClickRegion")
clickRegion.Visible = false
self.locked = true
return self
end
function Icon:unlock()
local clickRegion = self:getInstance("ClickRegion")
clickRegion.Visible = true
self.locked = false
return self
end
function Icon:debounce(seconds)
self:lock()
task.wait(seconds)
self:unlock()
return self
end
function Icon:autoDeselect(bool)
-- When set to true the icon will deselect itself automatically whenever
-- another icon is selected