repo stringclasses 245
values | file_path stringlengths 29 241 | code stringlengths 100 233k | tokens int64 14 69.4k |
|---|---|---|---|
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/unbind.luau | return {
Name = "unbind",
Aliases = {},
Description = "Unbinds an input previously bound with Bind",
Group = "DefaultUtil",
Args = {
{
Type = "userInput ! bindableResource @ player",
Name = "Input/Key",
Description = "The key or input type you'd like to unbind.",
},
},
ClientRun = function(context, inputEnum)
local binds = context:GetStore("CMDR_Binds")
if binds[inputEnum] then
binds[inputEnum]:Disconnect()
binds[inputEnum] = nil
return "Unbound command from input."
else
return "That input wasn't bound."
end
end,
}
| 154 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/var.luau | return {
Name = "var",
Aliases = {},
Description = "Gets a stored variable.",
Group = "DefaultUtil",
AutoExec = {
'alias "init-edit|Edit your initialization script" edit ${var init} \\\\\n && var= init ||',
'alias "init-run|Re-runs the initialization script manually." run-lines ${var init}',
"init-run",
},
Args = {
{
Type = "storedKey",
Name = "Key",
Description = "The key to get, retrieved from your user data store. Keys prefixed with . are not saved. Keys prefixed with $ are game-wide. Keys prefixed with $. are game-wide and non-saved.",
},
},
ClientRun = function(context, key)
context:GetStore("vars_used")[key] = true
end,
}
| 181 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/varSet.luau | return {
Name = "var=",
Aliases = {},
Description = "Sets a stored value.",
Group = "DefaultUtil",
Args = {
{
Type = "storedKey",
Name = "Key",
Description = "The key to set, saved in your user data store. Keys prefixed with . are not saved. Keys prefixed with $ are game-wide. Keys prefixed with $. are game-wide and non-saved.",
},
{
Type = "string",
Name = "Value",
Description = "Value or values to set.",
Default = "",
},
},
ClientRun = function(context, key)
context:GetStore("vars_used")[key] = true
end,
}
| 152 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/help.luau | local ARGUMENT_SHORTHANDS = [[
Argument Shorthands
-------------------
. Me/Self
* All/Everyone
** Others
? Random
?N List of N random values
]]
local TIPS = [[
Tips
----
• Utilize the Tab key to automatically complete commands
• Easily select and copy command output
]]
return {
Name = "help",
Aliases = { "cmds", "commands" },
Description = "Displays a list of all commands, or inspects one command.",
Group = "Help",
Args = {
{
Type = "command",
Name = "Command",
Description = "The command to view information on",
Optional = true,
},
},
ClientRun = function(context, commandName)
if commandName then
local command = context.Cmdr.Registry:GetCommand(commandName)
context:Reply(`Command: {command.Name}`, Color3.fromRGB(230, 126, 34))
if command.Aliases and #command.Aliases > 0 then
context:Reply(`Aliases: {table.concat(command.Aliases, ", ")}`, Color3.fromRGB(230, 230, 230))
end
if command.Description then
context:Reply(`Description: {command.Description}`, Color3.fromRGB(230, 230, 230))
end
if command.Group then
context:Reply(`Group: {command.Group}`, Color3.fromRGB(230, 230, 230))
end
if command.Args then
for i, arg in ipairs(command.Args) do
context:Reply(
`#{i} {if type(arg) == "table"
then `{arg.Name}{if arg.Optional == true then "?" else ""}: {arg.Type} - {arg.Description}`
else "Unknown (inline argument)"}`
)
end
end
else
context:Reply(ARGUMENT_SHORTHANDS)
context:Reply(TIPS)
local commands = context.Cmdr.Registry:GetCommands()
table.sort(commands, function(a, b)
return if a.Group and b.Group then a.Group < b.Group else a.Group
end)
local lastGroup
for _, command in ipairs(commands) do
local group = command.Group or "No Group"
if lastGroup ~= group then
context:Reply(`\n{group}\n{string.rep("-", #group)}`)
lastGroup = group
end
context:Reply(if command.Description then `{command.Name} - {command.Description}` else command.Name)
end
end
return ""
end,
}
| 563 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/BindableResource.luau | return function(registry)
registry:RegisterType("bindableResource", registry.Cmdr.Util.MakeEnumType("BindableResource", { "Chat" }))
end
| 32 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/BrickColor.luau | local Util = require(script.Parent.Parent.Shared.Util)
local brickColorNames = {
"White",
"Grey",
"Light yellow",
"Brick yellow",
"Light green (Mint)",
"Light reddish violet",
"Pastel Blue",
"Light orange brown",
"Nougat",
"Bright red",
"Med. reddish violet",
"Bright blue",
"Bright yellow",
"Earth orange",
"Black",
"Dark grey",
"Dark green",
"Medium green",
"Lig. Yellowich orange",
"Bright green",
"Dark orange",
"Light bluish violet",
"Transparent",
"Tr. Red",
"Tr. Lg blue",
"Tr. Blue",
"Tr. Yellow",
"Light blue",
"Tr. Flu. Reddish orange",
"Tr. Green",
"Tr. Flu. Green",
"Phosph. White",
"Light red",
"Medium red",
"Medium blue",
"Light grey",
"Bright violet",
"Br. yellowish orange",
"Bright orange",
"Bright bluish green",
"Earth yellow",
"Bright bluish violet",
"Tr. Brown",
"Medium bluish violet",
"Tr. Medi. reddish violet",
"Med. yellowish green",
"Med. bluish green",
"Light bluish green",
"Br. yellowish green",
"Lig. yellowish green",
"Med. yellowish orange",
"Br. reddish orange",
"Bright reddish violet",
"Light orange",
"Tr. Bright bluish violet",
"Gold",
"Dark nougat",
"Silver",
"Neon orange",
"Neon green",
"Sand blue",
"Sand violet",
"Medium orange",
"Sand yellow",
"Earth blue",
"Earth green",
"Tr. Flu. Blue",
"Sand blue metallic",
"Sand violet metallic",
"Sand yellow metallic",
"Dark grey metallic",
"Black metallic",
"Light grey metallic",
"Sand green",
"Sand red",
"Dark red",
"Tr. Flu. Yellow",
"Tr. Flu. Red",
"Gun metallic",
"Red flip/flop",
"Yellow flip/flop",
"Silver flip/flop",
"Curry",
"Fire Yellow",
"Flame yellowish orange",
"Reddish brown",
"Flame reddish orange",
"Medium stone grey",
"Royal blue",
"Dark Royal blue",
"Bright reddish lilac",
"Dark stone grey",
"Lemon metalic",
"Light stone grey",
"Dark Curry",
"Faded green",
"Turquoise",
"Light Royal blue",
"Medium Royal blue",
"Rust",
"Brown",
"Reddish lilac",
"Lilac",
"Light lilac",
"Bright purple",
"Light purple",
"Light pink",
"Light brick yellow",
"Warm yellowish orange",
"Cool yellow",
"Dove blue",
"Medium lilac",
"Slime green",
"Smoky grey",
"Dark blue",
"Parsley green",
"Steel blue",
"Storm blue",
"Lapis",
"Dark indigo",
"Sea green",
"Shamrock",
"Fossil",
"Mulberry",
"Forest green",
"Cadet blue",
"Electric blue",
"Eggplant",
"Moss",
"Artichoke",
"Sage green",
"Ghost grey",
"Lilac",
"Plum",
"Olivine",
"Laurel green",
"Quill grey",
"Crimson",
"Mint",
"Baby blue",
"Carnation pink",
"Persimmon",
"Maroon",
"Gold",
"Daisy orange",
"Pearl",
"Fog",
"Salmon",
"Terra Cotta",
"Cocoa",
"Wheat",
"Buttermilk",
"Mauve",
"Sunrise",
"Tawny",
"Rust",
"Cashmere",
"Khaki",
"Lily white",
"Seashell",
"Burgundy",
"Cork",
"Burlap",
"Beige",
"Oyster",
"Pine Cone",
"Fawn brown",
"Hurricane grey",
"Cloudy grey",
"Linen",
"Copper",
"Dirt brown",
"Bronze",
"Flint",
"Dark taupe",
"Burnt Sienna",
"Institutional white",
"Mid gray",
"Really black",
"Really red",
"Deep orange",
"Alder",
"Dusty Rose",
"Olive",
"New Yeller",
"Really blue",
"Navy blue",
"Deep blue",
"Cyan",
"CGA brown",
"Magenta",
"Pink",
"Deep orange",
"Teal",
"Toothpaste",
"Lime green",
"Camo",
"Grime",
"Lavender",
"Pastel light blue",
"Pastel orange",
"Pastel violet",
"Pastel blue-green",
"Pastel green",
"Pastel yellow",
"Pastel brown",
"Royal purple",
"Hot pink",
}
local brickColorFinder = Util.MakeFuzzyFinder(brickColorNames)
local brickColorType = {
Prefixes = "% teamColor",
Transform = function(text)
local brickColors = {}
for i, name in pairs(brickColorFinder(text)) do
brickColors[i] = BrickColor.new(name)
end
return brickColors
end,
Validate = function(brickColors)
return #brickColors > 0, "No valid brick colors with that name could be found."
end,
Autocomplete = function(brickColors)
return Util.GetNames(brickColors)
end,
Parse = function(brickColors)
return brickColors[1]
end,
}
local brickColor3Type = {
Transform = brickColorType.Transform,
Validate = brickColorType.Validate,
Autocomplete = brickColorType.Autocomplete,
Parse = function(brickColors)
return brickColors[1].Color
end,
}
return function(registry)
registry:RegisterType("brickColor", brickColorType)
registry:RegisterType(
"brickColors",
Util.MakeListableType(brickColorType, {
Prefixes = "% teamColors",
})
)
registry:RegisterType("brickColor3", brickColor3Type)
registry:RegisterType("brickColor3s", Util.MakeListableType(brickColor3Type))
end
| 1,478 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/Color3.luau | local Util = require(script.Parent.Parent.Shared.Util)
local color3Type = Util.MakeSequenceType({
Prefixes = "# hexColor3 ! brickColor3",
ValidateEach = function(value, i)
if value == nil then
return false, ("Invalid or missing number at position %d in Color3 type."):format(i)
elseif value < 0 or value > 255 then
return false, ("Number out of acceptable range 0-255 at position %d in Color3 type."):format(i)
elseif value % 1 ~= 0 then
return false, ("Number is not an integer at position %d in Color3 type."):format(i)
end
return true
end,
TransformEach = tonumber,
Constructor = Color3.fromRGB,
Length = 3,
})
local function parseHexDigit(x)
if #x == 1 then
x = x .. x
end
return tonumber(x, 16)
end
local hexColor3Type = {
Transform = function(text)
local r, g, b = text:match("^#?(%x%x?)(%x%x?)(%x%x?)$")
return Util.Each(parseHexDigit, r, g, b)
end,
Validate = function(r, g, b)
return r ~= nil and g ~= nil and b ~= nil, "Invalid hex color"
end,
Parse = function(...)
return Color3.fromRGB(...)
end,
}
return function(cmdr)
cmdr:RegisterType("color3", color3Type)
cmdr:RegisterType(
"color3s",
Util.MakeListableType(color3Type, {
Prefixes = "# hexColor3s ! brickColor3s",
})
)
cmdr:RegisterType("hexColor3", hexColor3Type)
cmdr:RegisterType("hexColor3s", Util.MakeListableType(hexColor3Type))
end
| 409 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/Command.luau | local Util = require(script.Parent.Parent.Shared.Util)
return function(cmdr)
local commandType = {
Transform = function(text)
local findCommand = Util.MakeFuzzyFinder(cmdr:GetCommandNames())
return findCommand(text)
end,
Validate = function(commands)
return #commands > 0, "No command with that name could be found."
end,
Autocomplete = function(commands)
return commands
end,
Parse = function(commands)
return commands[1]
end,
}
cmdr:RegisterType("command", commandType)
cmdr:RegisterType("commands", Util.MakeListableType(commandType))
end
| 139 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/ConditionFunction.luau | return function(registry)
registry:RegisterType("conditionFunction", registry.Cmdr.Util.MakeEnumType("ConditionFunction", { "startsWith" }))
end
| 31 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/Duration.luau | local Util = require(script.Parent.Parent.Shared.Util)
local unitTable = {
Years = 31556926,
Months = 2629744,
Weeks = 604800,
Days = 86400,
Hours = 3600,
Minutes = 60,
Seconds = 1,
}
local searchKeyTable = {}
for key, _ in pairs(unitTable) do
table.insert(searchKeyTable, key)
end
local unitFinder = Util.MakeFuzzyFinder(searchKeyTable)
local function stringToSecondDuration(stringDuration)
-- The duration cannot be null or an empty string.
if stringDuration == nil or stringDuration == "" then
return nil
end
-- Allow 0 by itself (without a unit) to indicate 0 seconds
local durationNum = tonumber(stringDuration)
if durationNum and durationNum == 0 then
return 0, 0, true
end
-- The duration must end with a unit,
-- if it doesn't then return true as the fourth value to indicate the need to offer autocomplete for units.
local endOnlyString = stringDuration:gsub("-?%d+%a+", "")
local endNumber = endOnlyString:match("-?%d+")
if endNumber then
return nil, tonumber(endNumber), true
end
local seconds = nil
local rawNum, rawUnit
for rawComponent in stringDuration:gmatch("-?%d+%a+") do
rawNum, rawUnit = rawComponent:match("(-?%d+)(%a+)")
local unitNames = unitFinder(rawUnit, false, true)
-- There were no matching units, it's invalid. Return the parsed number to be used for autocomplete
if #unitNames == 0 then
return nil, tonumber(rawNum)
end
if seconds == nil then
seconds = 0
end
-- While it was already defaulting to use minutes when using just "m", this does it without worrying
-- about any consistency between list ordering.
seconds = seconds + (rawUnit:lower() == "m" and 60 or unitTable[unitNames[1]]) * tonumber(rawNum)
end
-- If no durations were provided, return nil.
if seconds == nil then
return nil
else
return seconds, tonumber(rawNum)
end
end
local function mapUnits(units, rawText, lastNumber, subStart)
subStart = subStart or 1
local returnTable = {}
for i, unit in pairs(units) do
if lastNumber == 1 then
returnTable[i] = rawText .. unit:sub(subStart, #unit - 1)
else
returnTable[i] = rawText .. unit:sub(subStart)
end
end
return returnTable
end
local durationType = {
Transform = function(text)
return text, stringToSecondDuration(text)
end,
Validate = function(_, duration)
return duration ~= nil
end,
Autocomplete = function(rawText, duration, lastNumber, isUnitMissing, matchedUnits)
local returnTable = {}
if isUnitMissing or matchedUnits then
local unitsTable = isUnitMissing == true and unitFinder("", false, true) or matchedUnits
if isUnitMissing == true then
-- Concat the entire unit name to existing text.
returnTable = mapUnits(unitsTable, rawText, lastNumber)
else
-- Concat the rest of the unit based on what already exists of the unit name.
local existingUnitLength = rawText:match("^.*(%a+)$"):len()
returnTable = mapUnits(unitsTable, rawText, existingUnitLength + 1)
end
elseif duration ~= nil then
local endingUnit = rawText:match("^.*-?%d+(%a+)%s?$")
-- Assume there is a singular match at this point
local fuzzyUnits = unitFinder(endingUnit, false, true)
-- List all possible fuzzy matches. This is for the Minutes/Months ambiguity case.
returnTable = mapUnits(fuzzyUnits, rawText, lastNumber, #endingUnit + 1)
-- Sort alphabetically in the Minutes/Months case, so Minutes are displayed on top.
table.sort(returnTable)
end
return returnTable
end,
Parse = function(_, duration)
return duration
end,
}
return function(registry)
registry:RegisterType("duration", durationType)
registry:RegisterType("durations", Util.MakeListableType(durationType))
end
| 983 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/JSON.luau | local HttpService = game:GetService("HttpService")
return function(registry)
registry:RegisterType("json", {
Validate = function(text)
return pcall(HttpService.JSONDecode, HttpService, text)
end,
Parse = function(text)
return HttpService:JSONDecode(text)
end,
})
end
| 71 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/MathOperator.luau | return function(registry)
registry:RegisterType(
"mathOperator",
registry.Cmdr.Util.MakeEnumType("Math Operator", {
{
Name = "+",
Perform = function(a, b)
return a + b
end,
},
{
Name = "-",
Perform = function(a, b)
return a - b
end,
},
{
Name = "*",
Perform = function(a, b)
return a * b
end,
},
{
Name = "/",
Perform = function(a, b)
return a / b
end,
},
{
Name = "**",
Perform = function(a, b)
return a ^ b
end,
},
{
Name = "%",
Perform = function(a, b)
return a % b
end,
},
})
)
end
| 210 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/Player.luau | local Util = require(script.Parent.Parent.Shared.Util)
local Players = game:GetService("Players")
local playerType = {
Transform = function(text)
local findPlayer = Util.MakeFuzzyFinder(Players:GetPlayers())
return findPlayer(text)
end,
Validate = function(players)
return #players > 0, "No player with that name could be found."
end,
Autocomplete = function(players)
return Util.GetNames(players)
end,
Parse = function(players)
return players[1]
end,
Default = function(player)
return player.Name
end,
ArgumentOperatorAliases = {
me = ".",
all = "*",
others = "**",
random = "?",
},
}
return function(cmdr)
cmdr:RegisterType("player", playerType)
cmdr:RegisterType(
"players",
Util.MakeListableType(playerType, {
Prefixes = "% teamPlayers",
})
)
end
| 202 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/PlayerId.luau | local Util = require(script.Parent.Parent.Shared.Util)
local Players = game:GetService("Players")
local nameCache = {}
local function getUserId(name)
if nameCache[name] then
return nameCache[name]
elseif Players:FindFirstChild(name) then
nameCache[name] = Players[name].UserId
return Players[name].UserId
else
local ok, userid = pcall(Players.GetUserIdFromNameAsync, Players, name)
if not ok then
return nil
end
nameCache[name] = userid
return userid
end
end
local playerIdType = {
DisplayName = "Full Player Name",
Prefixes = "# positiveInteger",
Transform = function(text)
local findPlayer = Util.MakeFuzzyFinder(Players:GetPlayers())
return text, findPlayer(text)
end,
ValidateOnce = function(text)
return getUserId(text) ~= nil, "No player with that name could be found."
end,
Autocomplete = function(_, players)
return Util.GetNames(players)
end,
Parse = function(text)
return getUserId(text)
end,
Default = function(player)
return player.Name
end,
ArgumentOperatorAliases = {
me = ".",
all = "*",
others = "**",
random = "?",
},
}
return function(cmdr)
cmdr:RegisterType("playerId", playerIdType)
cmdr:RegisterType(
"playerIds",
Util.MakeListableType(playerIdType, {
Prefixes = "# positiveIntegers",
})
)
end
| 326 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/Primitives.luau | local Util = require(script.Parent.Parent.Shared.Util)
local stringType = {
Validate = function(value)
return value ~= nil
end,
Parse = function(value)
return tostring(value)
end,
}
local numberType = {
Transform = function(text)
return tonumber(text)
end,
Validate = function(value)
return value ~= nil
end,
Parse = function(value)
return value
end,
}
local intType = {
Transform = function(text)
return tonumber(text)
end,
Validate = function(value)
return value ~= nil and value == math.floor(value), "Only whole numbers are valid."
end,
Parse = function(value)
return value
end,
}
local positiveIntType = {
Transform = function(text)
return tonumber(text)
end,
Validate = function(value)
return value ~= nil and value == math.floor(value) and value > 0, "Only positive whole numbers are valid."
end,
Parse = function(value)
return value
end,
}
local nonNegativeIntType = {
Transform = function(text)
return tonumber(text)
end,
Validate = function(value)
return value ~= nil and value == math.floor(value) and value >= 0, "Only non-negative whole numbers are valid."
end,
Parse = function(value)
return value
end,
}
local byteType = {
Transform = function(text)
return tonumber(text)
end,
Validate = function(value)
return value ~= nil and value == math.floor(value) and value >= 0 and value <= 255, "Only bytes are valid."
end,
Parse = function(value)
return value
end,
}
local digitType = {
Transform = function(text)
return tonumber(text)
end,
Validate = function(value)
return value ~= nil and value == math.floor(value) and value >= 0 and value <= 9, "Only digits are valid."
end,
Parse = function(value)
return value
end,
}
local boolType
do
local truthy = Util.MakeDictionary({ "true", "t", "yes", "y", "on", "enable", "enabled", "1", "+" })
local falsy = Util.MakeDictionary({ "false", "f", "no", "n", "off", "disable", "disabled", "0", "-" })
boolType = {
Transform = function(text)
return text:lower()
end,
Validate = function(value)
return truthy[value] ~= nil or falsy[value] ~= nil, "Please use true/yes/on or false/no/off."
end,
Parse = function(value)
if truthy[value] then
return true
elseif falsy[value] then
return false
else
return nil
end
end,
}
end
return function(cmdr)
cmdr:RegisterType("string", stringType)
cmdr:RegisterType("number", numberType)
cmdr:RegisterType("integer", intType)
cmdr:RegisterType("positiveInteger", positiveIntType)
cmdr:RegisterType("nonNegativeInteger", nonNegativeIntType)
cmdr:RegisterType("byte", byteType)
cmdr:RegisterType("digit", digitType)
cmdr:RegisterType("boolean", boolType)
cmdr:RegisterType("strings", Util.MakeListableType(stringType))
cmdr:RegisterType("numbers", Util.MakeListableType(numberType))
cmdr:RegisterType("integers", Util.MakeListableType(intType))
cmdr:RegisterType("positiveIntegers", Util.MakeListableType(positiveIntType))
cmdr:RegisterType("nonNegativeIntegers", Util.MakeListableType(nonNegativeIntType))
cmdr:RegisterType("bytes", Util.MakeListableType(byteType))
cmdr:RegisterType("digits", Util.MakeListableType(digitType))
cmdr:RegisterType("booleans", Util.MakeListableType(boolType))
end
| 814 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/StoredKey.luau | local Util = require(script.Parent.Parent.Shared.Util)
local VALID_STORED_KEY_NAME_PATTERNS = {
"^%a[%w_]*$",
"^%$%a[%w_]*$",
"^%.%a[%w_]*$",
"^%$%.%a[%w_]*$",
}
return function(registry)
local storedKeyType = {
Autocomplete = function(text)
local find = registry.Cmdr.Util.MakeFuzzyFinder(
registry.Cmdr.Util.DictionaryKeys(registry:GetStore("vars_used") or {})
)
return find(text)
end,
Validate = function(text)
for _, pattern in ipairs(VALID_STORED_KEY_NAME_PATTERNS) do
if text:match(pattern) then
return true
end
end
return false, "Key names must start with an optional modifier: . $ or $. and must begin with a letter."
end,
Parse = function(text)
return text
end,
}
registry:RegisterType("storedKey", storedKeyType)
registry:RegisterType("storedKeys", Util.MakeListableType(storedKeyType))
end
| 246 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/Team.luau | local Teams = game:GetService("Teams")
local Util = require(script.Parent.Parent.Shared.Util)
local teamType = {
Transform = function(text)
local findTeam = Util.MakeFuzzyFinder(Teams:GetTeams())
return findTeam(text)
end,
Validate = function(teams)
return #teams > 0, "No team with that name could be found."
end,
Autocomplete = function(teams)
return Util.GetNames(teams)
end,
Parse = function(teams)
return teams[1]
end,
}
local teamPlayersType = {
Listable = true,
Transform = teamType.Transform,
Validate = teamType.Validate,
Autocomplete = teamType.Autocomplete,
Parse = function(teams)
return teams[1]:GetPlayers()
end,
}
local teamColorType = {
Transform = teamType.Transform,
Validate = teamType.Validate,
Autocomplete = teamType.Autocomplete,
Parse = function(teams)
return teams[1].TeamColor
end,
}
return function(cmdr)
cmdr:RegisterType("team", teamType)
cmdr:RegisterType("teams", Util.MakeListableType(teamType))
cmdr:RegisterType("teamPlayers", teamPlayersType)
cmdr:RegisterType("teamColor", teamColorType)
cmdr:RegisterType("teamColors", Util.MakeListableType(teamColorType))
end
| 288 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/Type.luau | local Util = require(script.Parent.Parent.Shared.Util)
return function(cmdr)
local typeType = {
Transform = function(text)
local findCommand = Util.MakeFuzzyFinder(cmdr:GetTypeNames())
return findCommand(text)
end,
Validate = function(commands)
return #commands > 0, "No type with that name could be found."
end,
Autocomplete = function(commands)
return commands
end,
Parse = function(commands)
return commands[1]
end,
}
cmdr:RegisterType("type", typeType)
cmdr:RegisterType("types", Util.MakeListableType(typeType))
end
| 139 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/URL.luau | local Util = require(script.Parent.Parent.Shared.Util)
local storedKeyType = {
Validate = function(text)
if text:match("^https?://.+$") then
return true
end
return false, "URLs must begin with http:// or https://"
end,
Parse = function(text)
return text
end,
}
return function(cmdr)
cmdr:RegisterType("url", storedKeyType)
cmdr:RegisterType("urls", Util.MakeListableType(storedKeyType))
end
| 106 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/UserInput.luau | local Util = require(script.Parent.Parent.Shared.Util)
local combinedInputEnums = Enum.UserInputType:GetEnumItems()
for _, e in pairs(Enum.KeyCode:GetEnumItems()) do
combinedInputEnums[#combinedInputEnums + 1] = e
end
local userInputType = {
Transform = function(text)
local findEnum = Util.MakeFuzzyFinder(combinedInputEnums)
return findEnum(text)
end,
Validate = function(enums)
return #enums > 0
end,
Autocomplete = function(enums)
return Util.GetNames(enums)
end,
Parse = function(enums)
return enums[1]
end,
}
return function(cmdr)
cmdr:RegisterType("userInput", userInputType)
cmdr:RegisterType("userInputs", Util.MakeListableType(userInputType))
end
| 172 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/BuiltInTypes/Vector.luau | local Util = require(script.Parent.Parent.Shared.Util)
local function validateVector(value, i)
if value == nil then
return false, ("Invalid or missing number at position %d in Vector type."):format(i)
end
return true
end
local vector3Type = Util.MakeSequenceType({
ValidateEach = validateVector,
TransformEach = tonumber,
Constructor = Vector3.new,
Length = 3,
})
local vector2Type = Util.MakeSequenceType({
ValidateEach = validateVector,
TransformEach = tonumber,
Constructor = Vector2.new,
Length = 2,
})
return function(cmdr)
cmdr:RegisterType("vector3", vector3Type)
cmdr:RegisterType("vector3s", Util.MakeListableType(vector3Type))
cmdr:RegisterType("vector2", vector2Type)
cmdr:RegisterType("vector2s", Util.MakeListableType(vector2Type))
end
| 191 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/CmdrClient/CmdrInterface/AutoComplete.luau | local Players = game:GetService("Players")
local Player = Players.LocalPlayer
return function(Cmdr)
local AutoComplete = {
Items = {},
ItemOptions = {},
SelectedItem = 0,
}
local Util = Cmdr.Util
local Gui = Player:WaitForChild("PlayerGui"):WaitForChild("Cmdr"):WaitForChild("Autocomplete")
local AutoItem = Gui:WaitForChild("TextButton")
local Title = Gui:WaitForChild("Title")
local Description = Gui:WaitForChild("Description")
local Entry = Gui.Parent:WaitForChild("Frame"):WaitForChild("Entry")
AutoItem.Parent = nil
local defaultBarThickness = Gui.ScrollBarThickness
-- Helper function that sets text and resizes labels
local function SetText(obj, textObj, text, sizeFromContents)
obj.Visible = text ~= nil
textObj.Text = text or ""
if sizeFromContents then
textObj.Size = UDim2.new(
0,
Util.GetTextSize(text or "", textObj, Vector2.new(1000, 1000), 1, 0).X,
obj.Size.Y.Scale,
obj.Size.Y.Offset
)
end
end
local function UpdateContainerSize()
Gui.Size = UDim2.new(
0,
math.max(Title.Field.TextBounds.X + Title.Field.Type.TextBounds.X, Gui.Size.X.Offset),
0,
math.min(Gui.UIListLayout.AbsoluteContentSize.Y, Gui.Parent.AbsoluteSize.Y - Gui.AbsolutePosition.Y - 10)
)
end
-- Update the info display (Name, type, and description) based on given options.
local function UpdateInfoDisplay(options)
-- Update the objects' text and sizes
SetText(Title, Title.Field, options.name, true)
SetText(
Title.Field.Type,
Title.Field.Type,
options.type and ": " .. options.type:sub(1, 1):upper() .. options.type:sub(2)
)
SetText(Description, Description.Label, options.description)
Description.Label.TextColor3 = options.invalid and Color3.fromRGB(255, 73, 73) or Color3.fromRGB(255, 255, 255)
Description.Size = UDim2.new(1, 0, 0, 40)
-- Flow description text
while not Description.Label.TextFits do
Description.Size = Description.Size + UDim2.new(0, 0, 0, 2)
if Description.Size.Y.Offset > 500 then
break
end
end
-- Update container
task.wait()
Gui.UIListLayout:ApplyLayout()
UpdateContainerSize()
Gui.ScrollBarThickness = defaultBarThickness
end
-- Shows the auto complete menu with the given list and possible options
-- item = {typedText, suggestedText, options?=options}
-- The options table is optional. `at` should only be passed into AutoComplete::Show
-- name, type, and description may be passed in an options dictionary inside the items as well
-- options.at?: the character index at which to show the menu
-- options.name?: The name to display in the info box
-- options.type?: The type to display in the info box
-- options.prefix?: The current type prefix (%Team)
-- options.description?: The description for the currently active info box
-- options.invalid?: If true, description is shown in red.
-- options.isLast?: If true, auto complete won't keep going after this argument.
function AutoComplete:Show(items, options)
options = options or {}
-- Remove old options.
for _, item in pairs(self.Items) do
if item.gui then
item.gui:Destroy()
end
end
-- Reset state
self.SelectedItem = 1
self.Items = items
self.Prefix = options.prefix or ""
self.LastItem = options.isLast or false
self.Command = options.command
self.Arg = options.arg
self.NumArgs = options.numArgs
self.IsPartial = options.isPartial
-- Generate the new option labels
local autocompleteWidth = 200
Gui.ScrollBarThickness = 0
for i, item in pairs(self.Items) do
local leftText = item[1]
local rightText = item[2]
local btn = AutoItem:Clone()
btn.Name = leftText .. rightText
btn.BackgroundTransparency = i == self.SelectedItem and 0.5 or 1
local start, stop = string.find(rightText:lower(), leftText:lower(), 1, true)
if start == nil and stop == nil then
--start and stop are nil when the type returns an autocomplete result that is completely different (such as a custom alias hanlded within the type).
--One should never be nil without the other.
start, stop = 1, string.len(rightText)
end
btn.Typed.Text = string.rep(" ", start - 1) .. leftText
btn.Suggest.Text = string.sub(rightText, 0, start - 1)
.. string.rep(" ", #leftText)
.. string.sub(rightText, stop + 1)
btn.Parent = Gui
btn.LayoutOrder = i
local maxBounds = math.max(btn.Typed.TextBounds.X, btn.Suggest.TextBounds.X) + 20
if maxBounds > autocompleteWidth then
autocompleteWidth = maxBounds
end
item.gui = btn
end
Gui.UIListLayout:ApplyLayout()
-- Todo: Use TextService to find accurate position for auto complete box
local text = Entry.TextBox.Text
local words = Util.SplitString(text)
if text:sub(#text, #text) == " " and not options.at then
words[#words + 1] = "e"
end
table.remove(words, #words)
local extra = (options.at and options.at or (#table.concat(words, " ") + 1)) * 7
-- Update the auto complete container
Gui.Position =
UDim2.new(0, Entry.TextBox.AbsolutePosition.X - 10 + extra, 0, Entry.TextBox.AbsolutePosition.Y + 30)
Gui.Size = UDim2.new(0, autocompleteWidth, 0, Gui.UIListLayout.AbsoluteContentSize.Y)
Gui.Visible = true
-- Finally, update thge info display
UpdateInfoDisplay(self.Items[1] and self.Items[1].options or options)
end
-- Returns the selected item in the auto complete
function AutoComplete:GetSelectedItem()
if Gui.Visible == false then
return nil
end
return AutoComplete.Items[AutoComplete.SelectedItem]
end
-- Hides the auto complete
function AutoComplete:Hide()
Gui.Visible = false
end
-- Returns if the menu is visible
function AutoComplete:IsVisible()
return Gui.Visible
end
-- Changes the user's item selection by the given delta
function AutoComplete:Select(delta)
if not Gui.Visible then
return
end
self.SelectedItem = self.SelectedItem + delta
if self.SelectedItem > #self.Items then
self.SelectedItem = 1
elseif self.SelectedItem < 1 then
self.SelectedItem = #self.Items
end
for i, item in pairs(self.Items) do
item.gui.BackgroundTransparency = i == self.SelectedItem and 0.5 or 1
end
Gui.CanvasPosition = Vector2.new(
0,
math.max(
0,
Title.Size.Y.Offset
+ Description.Size.Y.Offset
+ self.SelectedItem * AutoItem.Size.Y.Offset
- Gui.Size.Y.Offset
)
)
if self.Items[self.SelectedItem] and self.Items[self.SelectedItem].options then
UpdateInfoDisplay(self.Items[self.SelectedItem].options or {})
end
end
Gui.Parent:GetPropertyChangedSignal("AbsoluteSize"):Connect(UpdateContainerSize)
return AutoComplete
end
| 1,762 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/CmdrClient/CmdrInterface/Window.luau | -- Here be dragons
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
local TextChatService = game:GetService("TextChatService")
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local WINDOW_MAX_HEIGHT = 300
local MOUSE_TOUCH_ENUM = { Enum.UserInputType.MouseButton1, Enum.UserInputType.MouseButton2, Enum.UserInputType.Touch }
-- Window handles the command bar GUI
local Window = {
Valid = true,
AutoComplete = nil,
ProcessEntry = nil,
OnTextChanged = nil,
Cmdr = nil,
HistoryState = nil,
}
local Gui = Player:WaitForChild("PlayerGui"):WaitForChild("Cmdr"):WaitForChild("Frame")
local Line = Gui:WaitForChild("Line")
local Entry = Gui:WaitForChild("Entry")
Line.Parent = nil
-- Update the text entry label
function Window:UpdateLabel()
Entry.TextLabel.Text =
`{Player.Name}{if self.Cmdr.PlaceName and self.Cmdr.PlaceName ~= "" then `@{self.Cmdr.PlaceName}` else ""}$`
end
-- Get the text entry label
function Window:GetLabel()
return Entry.TextLabel.Text
end
-- Recalculate the window height
function Window:UpdateWindowHeight()
local windowHeight = Gui.UIListLayout.AbsoluteContentSize.Y
+ Gui.UIPadding.PaddingTop.Offset
+ Gui.UIPadding.PaddingBottom.Offset
Gui.Size = UDim2.new(Gui.Size.X.Scale, Gui.Size.X.Offset, 0, math.clamp(windowHeight, 0, WINDOW_MAX_HEIGHT))
Gui.CanvasPosition = Vector2.new(0, windowHeight)
end
-- Add a line to the command bar
function Window:AddLine(text, options)
options = options or {}
text = tostring(text)
if typeof(options) == "Color3" then
options = { Color = options }
end
if #text == 0 then
Window:UpdateWindowHeight()
return
end
local str = self.Cmdr.Util.EmulateTabstops(text or "nil", 8)
local line = Line:Clone()
line.Text = str
line.TextColor3 = options.Color or line.TextColor3
line.RichText = options.RichText or false
line.Parent = Gui
end
-- Returns if the command bar is visible
function Window:IsVisible()
return Gui.Visible
end
-- Sets the command bar visible or not
function Window:SetVisible(visible)
Gui.Visible = visible
if visible then
self.PreviousChatWindowConfigurationEnabled = TextChatService.ChatWindowConfiguration.Enabled
self.PreviousChatInputBarConfigurationEnabled = TextChatService.ChatInputBarConfiguration.Enabled
self.PreviousChannelTabsConfigurationEnabled = TextChatService.ChannelTabsConfiguration.Enabled
TextChatService.ChatWindowConfiguration.Enabled = false
TextChatService.ChatInputBarConfiguration.Enabled = false
TextChatService.ChannelTabsConfiguration.Enabled = false
Entry.TextBox:CaptureFocus()
self:SetEntryText("")
if self.Cmdr.ActivationUnlocksMouse then
self.PreviousMouseBehavior = UserInputService.MouseBehavior
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
end
else
TextChatService.ChatWindowConfiguration.Enabled = if self.PreviousChatWindowConfigurationEnabled ~= nil
then self.PreviousChatWindowConfigurationEnabled
else true
TextChatService.ChatInputBarConfiguration.Enabled = if self.PreviousChatInputBarConfigurationEnabled
~= nil
then self.PreviousChatInputBarConfigurationEnabled
else true
TextChatService.ChannelTabsConfiguration.Enabled = if self.PreviousChannelTabsConfigurationEnabled ~= nil
then self.PreviousChannelTabsConfigurationEnabled
else true
Entry.TextBox:ReleaseFocus()
self.AutoComplete:Hide()
if self.PreviousMouseBehavior then
UserInputService.MouseBehavior = self.PreviousMouseBehavior
self.PreviousMouseBehavior = nil
end
end
end
-- Hides the command bar
function Window:Hide()
return self:SetVisible(false)
end
-- Shows the command bar
function Window:Show()
return self:SetVisible(true)
end
-- Sets the text in the command bar text box, and captures focus
function Window:SetEntryText(text)
Entry.TextBox.Text = text
if self:IsVisible() then
Entry.TextBox:CaptureFocus()
Entry.TextBox.CursorPosition = #text + 1
Window:UpdateWindowHeight()
end
end
-- Gets the text in the command bar text box
function Window:GetEntryText()
return Entry.TextBox.Text:gsub("\t", "")
end
-- Sets whether the command is in a valid state or not.
-- Cannot submit if in invalid state.
function Window:SetIsValidInput(isValid, errorText)
Entry.TextBox.TextColor3 = isValid and Color3.fromRGB(255, 255, 255) or Color3.fromRGB(255, 73, 73)
self.Valid = isValid
self._errorText = errorText
end
function Window:HideInvalidState()
Entry.TextBox.TextColor3 = Color3.fromRGB(255, 255, 255)
end
-- Event handler for text box focus lost
function Window:LoseFocus(submit)
local text = Entry.TextBox.Text
self:ClearHistoryState()
if Gui.Visible and not GuiService.MenuIsOpen and not UserInputService.TouchEnabled then
-- self:SetEntryText("")
Entry.TextBox:CaptureFocus()
elseif GuiService.MenuIsOpen and Gui.Visible then
self:Hide()
end
if submit and self.Valid then
wait()
self:SetEntryText("")
self.ProcessEntry(text)
elseif submit then
self:AddLine(self._errorText, Color3.fromRGB(255, 153, 153))
end
end
function Window:TraverseHistory(delta)
local history = self.Cmdr.Dispatcher:GetHistory()
if self.HistoryState == nil then
self.HistoryState = {
Position = #history + 1,
InitialText = self:GetEntryText(),
}
end
self.HistoryState.Position = math.clamp(self.HistoryState.Position + delta, 1, #history + 1)
self:SetEntryText(
self.HistoryState.Position == #history + 1 and self.HistoryState.InitialText
or history[self.HistoryState.Position]
)
end
function Window:ClearHistoryState()
self.HistoryState = nil
end
function Window:SelectVertical(delta)
if self.AutoComplete:IsVisible() and not self.HistoryState then
self.AutoComplete:Select(delta)
else
self:TraverseHistory(delta)
end
end
local lastPressTime = 0
local pressCount = 0
-- Handles user input when the box is focused
function Window:BeginInput(input, gameProcessed)
if GuiService.MenuIsOpen then
self:Hide()
end
if gameProcessed and self:IsVisible() == false then
return
end
if self.Cmdr.ActivationKeys[input.KeyCode] then -- Activate the command bar
if self.Cmdr.MashToEnable and not self.Cmdr.Enabled then
if tick() - lastPressTime < 1 then
if pressCount >= 5 then
return self.Cmdr:SetEnabled(true)
else
pressCount = pressCount + 1
end
else
pressCount = 1
end
lastPressTime = tick()
elseif self.Cmdr.Enabled then
self:SetVisible(not self:IsVisible())
wait()
self:SetEntryText("")
if GuiService.MenuIsOpen then -- Special case for menu getting stuck open (roblox bug)
self:Hide()
end
end
return
end
if self.Cmdr.Enabled == false or not self:IsVisible() then
if self:IsVisible() then
self:Hide()
end
return
end
if self.Cmdr.HideOnLostFocus and table.find(MOUSE_TOUCH_ENUM, input.UserInputType) then
local ps = input.Position
local ap = Gui.AbsolutePosition
local as = Gui.AbsoluteSize
if ps.X < ap.X or ps.X > ap.X + as.X or ps.Y < ap.Y or ps.Y > ap.Y + as.Y then
self:Hide()
end
elseif input.KeyCode == Enum.KeyCode.Down then -- Auto Complete Down
self:SelectVertical(1)
elseif input.KeyCode == Enum.KeyCode.Up then -- Auto Complete Up
self:SelectVertical(-1)
elseif input.KeyCode == Enum.KeyCode.Return then -- Eat new lines
wait()
self:SetEntryText(self:GetEntryText():gsub("\n", ""):gsub("\r", ""))
elseif input.KeyCode == Enum.KeyCode.Tab then -- Auto complete
local item = self.AutoComplete:GetSelectedItem()
local text = self:GetEntryText()
if item and not (text:sub(#text, #text):match("%s") and self.AutoComplete.LastItem) then
local replace = item[2]
local newText
local insertSpace = true
local command = self.AutoComplete.Command
if command then
local lastArg = self.AutoComplete.Arg
newText = command.Alias
insertSpace = self.AutoComplete.NumArgs ~= #command.ArgumentDefinitions
and self.AutoComplete.IsPartial == false
local args = command.Arguments
for i = 1, #args do
local arg = args[i]
local segments = arg.RawSegments
if arg == lastArg then
segments[#segments] = replace
end
local argText = arg.Prefix .. table.concat(segments, ",")
-- Put auto completion options in quotation marks if they have a space
if argText:find(" ") or argText == "" then
argText = ("%q"):format(argText)
end
newText = ("%s %s"):format(newText, argText)
if arg == lastArg then
break
end
end
else
newText = replace
end
-- need to wait a frame so we can eat the \t
wait()
-- Update the text box
self:SetEntryText(newText .. (insertSpace and " " or ""))
else
-- Still need to eat the \t even if there is no auto-complete to show
wait()
self:SetEntryText(self:GetEntryText())
end
else
self:ClearHistoryState()
end
end
-- Hook events
Entry.TextBox.FocusLost:Connect(function(submit)
return Window:LoseFocus(submit)
end)
UserInputService.InputBegan:Connect(function(input, gameProcessed)
return Window:BeginInput(input, gameProcessed)
end)
Entry.TextBox:GetPropertyChangedSignal("Text"):Connect(function()
Gui.CanvasPosition = Vector2.new(0, Gui.AbsoluteCanvasSize.Y)
if Entry.TextBox.Text:match("\t") then -- Eat \t
Entry.TextBox.Text = Entry.TextBox.Text:gsub("\t", "")
return
end
if Window.OnTextChanged then
return Window.OnTextChanged(Entry.TextBox.Text)
end
end)
Gui.ChildAdded:Connect(function()
task.defer(Window.UpdateWindowHeight)
end)
return Window
| 2,381 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/CmdrClient/CmdrInterface/init.luau | -- Here be dragons
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
return function(Cmdr)
local Util = Cmdr.Util
local Window = require(script:WaitForChild("Window"))
Window.Cmdr = Cmdr
local AutoComplete = require(script:WaitForChild("AutoComplete"))(Cmdr)
Window.AutoComplete = AutoComplete
-- Sets the Window.ProcessEntry callback so that we can dispatch our commands out
function Window.ProcessEntry(text)
text = Util.TrimString(text)
if #text == 0 then
return
end
Window:AddLine(Window:GetLabel() .. " " .. text, Color3.fromRGB(255, 223, 93))
Window:AddLine(Cmdr.Dispatcher:EvaluateAndRun(text, Player, {
IsHuman = true,
}))
end
-- Sets the Window.OnTextChanged callback so we can update the auto complete
function Window.OnTextChanged(text)
local command = Cmdr.Dispatcher:Evaluate(text, Player, true)
local arguments = Util.SplitString(text)
local commandText = table.remove(arguments, 1)
local atEnd = false
if command then
arguments = Util.MashExcessArguments(arguments, #command.Object.Args)
atEnd = #arguments == #command.Object.Args
end
local entryComplete = commandText and #arguments > 0
if text:sub(#text, #text):match("%s") and not atEnd then
entryComplete = true
arguments[#arguments + 1] = ""
end
if command and entryComplete then
local commandValid, errorText = command:Validate()
Window:SetIsValidInput(commandValid, ("Validation errors: %s"):format(errorText or ""))
local acItems = {}
local lastArgument = command:GetArgument(#arguments)
if lastArgument then
local typedText = lastArgument.TextSegmentInProgress
local isPartial = false
if lastArgument.RawSegmentsAreAutocomplete then
for i, segment in ipairs(lastArgument.RawSegments) do
acItems[i] = { segment, segment }
end
else
local items, options = lastArgument:GetAutocomplete()
options = options or {}
isPartial = options.IsPartial or false
for i, item in pairs(items) do
acItems[i] = { typedText, item }
end
end
local valid = true
if #typedText > 0 then
valid, errorText = lastArgument:Validate()
end
if not atEnd and valid then
Window:HideInvalidState()
end
return AutoComplete:Show(acItems, {
at = atEnd and #text - #typedText + (text:sub(#text, #text):match("%s") and -1 or 0),
prefix = #lastArgument.RawSegments == 1 and lastArgument.Prefix or "",
isLast = #command.Arguments == #command.ArgumentDefinitions and #typedText > 0,
numArgs = #arguments,
command = command,
arg = lastArgument,
name = lastArgument.Name .. (lastArgument.Required and "" or "?"),
type = lastArgument.Type.DisplayName,
description = (valid == false and errorText) or lastArgument.Object.Description,
invalid = not valid,
isPartial = isPartial,
})
end
elseif commandText and #arguments == 0 then
Window:SetIsValidInput(true)
local exactCommand = Cmdr.Registry:GetCommand(commandText)
local exactMatch
if exactCommand then
exactMatch = {
exactCommand.Name,
exactCommand.Name,
options = {
name = exactCommand.Name,
description = exactCommand.Description,
},
}
local arg = exactCommand.Args and exactCommand.Args[1]
if type(arg) == "function" then
arg = arg(command)
end
if arg and (not arg.Optional and arg.Default == nil) then
Window:SetIsValidInput(false, "This command has required arguments.")
Window:HideInvalidState()
end
else
Window:SetIsValidInput(
false,
("%q is not a valid command name. Use the help command to see all available commands."):format(
commandText
)
)
end
local acItems = { exactMatch }
for _, cmd in pairs(Cmdr.Registry:GetCommandNames()) do
if
commandText:lower() == cmd:lower():sub(1, #commandText)
and (exactMatch == nil or exactMatch[1] ~= commandText)
then
local commandObject = Cmdr.Registry:GetCommand(cmd)
acItems[#acItems + 1] = {
commandText,
cmd,
options = {
name = commandObject.Name,
description = commandObject.Description,
},
}
end
end
return AutoComplete:Show(acItems)
end
Window:SetIsValidInput(false, "Use the help command to see all available commands.")
AutoComplete:Hide()
end
Window:UpdateLabel()
Window:UpdateWindowHeight()
return {
Window = Window,
AutoComplete = AutoComplete,
}
end
| 1,147 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/CmdrClient/DefaultEventHandlers.luau | local StarterGui = game:GetService("StarterGui")
local TextChatService = game:GetService("TextChatService")
local Window = require(script.Parent.CmdrInterface.Window)
return function(Cmdr)
Cmdr:HandleEvent("Message", function(text)
if TextChatService.ChatVersion == Enum.ChatVersion.LegacyChatService then
StarterGui:SetCore("ChatMakeSystemMessage", {
Text = ("[Announcement] %s"):format(text),
Color = Color3.fromRGB(249, 217, 56),
})
else
TextChatService.TextChannels.RBXSystem:DisplaySystemMessage(
`<font color="rgb(249, 217, 56)">[Announcement] {text}</font>`
)
end
end)
Cmdr:HandleEvent("AddLine", function(...)
Window:AddLine(...)
end)
end
| 192 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/CmdrClient/init.luau | local RunService = game:GetService("RunService")
local StarterGui = game:GetService("StarterGui")
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Shared = script:WaitForChild("Shared")
local Util = require(Shared:WaitForChild("Util"))
if RunService:IsClient() == false then
error(
"[Cmdr] Server scripts cannot require the client library. Please require the server library from the server to use Cmdr in your own code."
)
end
--[=[
@class CmdrClient
@client
The Cmdr client singleton and entry point.
]=]
--[=[
@within CmdrClient
@prop Registry Registry
@readonly
Refers to the current command Registry.
]=]
--[=[
@within CmdrClient
@prop Dispatcher Dispatcher
@readonly
Refers to the current command Dispatcher.
]=]
--[=[
@within CmdrClient
@prop Util Util
@readonly
Refers to a table containing many useful utility functions.
]=]
--[=[
@within CmdrClient
@prop Enabled boolean
@readonly
Whether or not Cmdr is enabled (will show via the defined activation keys). Use [`CmdrClient:SetEnabled`](#SetEnabled) to change.
]=]
--[=[
@within CmdrClient
@prop PlaceName string
@readonly
The current place name, displayed on the interface. Use [`CmdrClient:SetPlaceName`](#SetPlaceName) to change.
]=]
--[=[
@within CmdrClient
@prop ActivationKeys { [Enum.KeyCode] = true }
@readonly
The list of key codes that will show or hide Cmdr. Use [`CmdrClient:SetActivationKeys`](#SetActivationKeys) to change.
]=]
local Cmdr
do
Cmdr = setmetatable({
ReplicatedRoot = script,
RemoteFunction = script:WaitForChild("CmdrFunction"),
RemoteEvent = script:WaitForChild("CmdrEvent"),
ActivationKeys = { [Enum.KeyCode.F2] = true },
Enabled = true,
MashToEnable = false,
ActivationUnlocksMouse = false,
HideOnLostFocus = true,
PlaceName = "Cmdr",
Util = Util,
Events = {},
}, {
-- This sucks, and may be redone or removed
-- Proxies dispatch methods on to main Cmdr object
__index = function(self, k)
local r = self.Dispatcher[k]
if r and type(r) == "function" then
return function(_, ...)
return r(self.Dispatcher, ...)
end
end
end,
})
Cmdr.Registry = require(Shared.Registry)(Cmdr)
Cmdr.Dispatcher = require(Shared.Dispatcher)(Cmdr)
end
if StarterGui:WaitForChild("Cmdr") and wait() and Player:WaitForChild("PlayerGui"):FindFirstChild("Cmdr") == nil then
StarterGui.Cmdr:Clone().Parent = Player.PlayerGui
end
local Interface = require(script.CmdrInterface)(Cmdr)
--[=[
Sets the key codes that will used to show or hide Cmdr.
@within CmdrClient
]=]
function Cmdr:SetActivationKeys(keys: { Enum.KeyCode })
self.ActivationKeys = Util.MakeDictionary(keys)
end
--[=[
Sets the place name label on the interface. This is useful for a quick way to tell what game you're playing in a universe game.
@within CmdrClient
]=]
function Cmdr:SetPlaceName(name: string)
self.PlaceName = name
Interface.Window:UpdateLabel()
end
--[=[
Sets whether or not Cmdr can be shown via the defined activation keys. Useful for when you want users to opt-in to show the console, for instance in a settings menu.
@within CmdrClient
]=]
function Cmdr:SetEnabled(enabled: boolean)
self.Enabled = enabled
end
--[=[
Sets if activation will free the mouse.
@within CmdrClient
]=]
function Cmdr:SetActivationUnlocksMouse(enabled: boolean)
self.ActivationUnlocksMouse = enabled
end
--[=[
Shows the Cmdr window. Does nothing if Cmdr isn't enabled.
@within CmdrClient
]=]
function Cmdr:Show()
if not self.Enabled then
return
end
Interface.Window:Show()
end
--[=[
Hides the Cmdr window.
@within CmdrClient
]=]
function Cmdr:Hide()
Interface.Window:Hide()
end
--[=[
Toggles the Cmdr window. Does nothing if Cmdr isn't enabled.
@within CmdrClient
]=]
function Cmdr:Toggle()
if not self.Enabled then
self:Hide()
return
end
Interface.Window:SetVisible(not Interface.Window:IsVisible())
end
--[=[
Enables the "Mash to open" feature.
This feature, when enabled, requires the activation key to be pressed 5 times within a second to [enable](#SetEnabled) Cmdr.
This may be helpful to guard against mispresses from opening the window, for example.
@within CmdrClient
]=]
function Cmdr:SetMashToEnable(enabled: boolean)
self.MashToEnable = enabled
if enabled then
self:SetEnabled(false)
end
end
--[=[
Sets the hide on 'lost focus' feature.
This feature, which is enabled by default, will cause Cmdr to [hide](#Hide) when the user clicks off the window.
@within CmdrClient
]=]
function Cmdr:SetHideOnLostFocus(enabled: boolean)
self.HideOnLostFocus = enabled
end
--[=[
Sets the [network event handler](/docs/networkeventhandlers) for a certain event type.
@within CmdrClient
]=]
function Cmdr:HandleEvent(name: string, callback: (...any) -> ())
self.Events[name] = callback
end
-- "Only register when we aren't in studio because don't want to overwrite what the server portion did"
-- This is legacy code which predates Accurate Play Solo (which is now the only way to test in studio), this code will never run.
if RunService:IsServer() == false then
Cmdr.Registry:RegisterTypesIn(script:WaitForChild("Types"))
Cmdr.Registry:RegisterCommandsIn(script:WaitForChild("Commands"))
end
-- Hook up event listener
Cmdr.RemoteEvent.OnClientEvent:Connect(function(name, ...)
if Cmdr.Events[name] then
Cmdr.Events[name](...)
end
end)
require(script.DefaultEventHandlers)(Cmdr)
return Cmdr
| 1,430 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/CreateGui.luau | return function()
local Cmdr = Instance.new("ScreenGui")
Cmdr.DisplayOrder = 1000
Cmdr.Name = "Cmdr"
Cmdr.ResetOnSpawn = false
Cmdr.AutoLocalize = false
local Frame = Instance.new("ScrollingFrame")
Frame.BackgroundColor3 = Color3.fromRGB(17, 17, 17)
Frame.BackgroundTransparency = 0.4
Frame.BorderSizePixel = 0
Frame.CanvasSize = UDim2.new(0, 0, 0, 0)
Frame.Name = "Frame"
Frame.Position = UDim2.new(0.025, 0, 0, 25)
Frame.ScrollBarThickness = 6
Frame.ScrollingDirection = Enum.ScrollingDirection.Y
Frame.Selectable = false
Frame.Size = UDim2.new(0.95, 0, 0, 0)
Frame.Visible = false
Frame.AutomaticCanvasSize = Enum.AutomaticSize.Y
Frame.Parent = Cmdr
local Autocomplete = Instance.new("ScrollingFrame")
Autocomplete.BackgroundColor3 = Color3.fromRGB(59, 59, 59)
Autocomplete.BackgroundTransparency = 0.5
Autocomplete.BorderSizePixel = 0
Autocomplete.CanvasSize = UDim2.new(0, 0, 0, 0)
Autocomplete.Name = "Autocomplete"
Autocomplete.Position = UDim2.new(0, 167, 0, 75)
Autocomplete.ScrollBarThickness = 6
Autocomplete.ScrollingDirection = Enum.ScrollingDirection.Y
Autocomplete.Selectable = false
Autocomplete.Size = UDim2.new(0, 200, 0, 200)
Autocomplete.Visible = false
Autocomplete.AutomaticCanvasSize = Enum.AutomaticSize.Y
Autocomplete.Parent = Cmdr
local UIListLayout = Instance.new("UIListLayout")
UIListLayout.SortOrder = Enum.SortOrder.LayoutOrder
UIListLayout.Parent = Frame
local Line = Instance.new("TextBox")
Line.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Line.BackgroundTransparency = 1
Line.Font = Enum.Font.Code
Line.Name = "Line"
Line.Size = UDim2.new(1, 0, 0, 20)
Line.AutomaticSize = Enum.AutomaticSize.Y
Line.TextColor3 = Color3.fromRGB(255, 255, 255)
Line.TextSize = 14
Line.TextXAlignment = Enum.TextXAlignment.Left
Line.TextEditable = false
Line.ClearTextOnFocus = false
Line.Parent = Frame
local UIPadding = Instance.new("UIPadding")
UIPadding.PaddingBottom = UDim.new(0, 10)
UIPadding.PaddingLeft = UDim.new(0, 10)
UIPadding.PaddingRight = UDim.new(0, 10)
UIPadding.PaddingTop = UDim.new(0, 10)
UIPadding.Parent = Frame
local Entry = Instance.new("Frame")
Entry.BackgroundTransparency = 1
Entry.LayoutOrder = 999999999
Entry.Name = "Entry"
Entry.Size = UDim2.new(1, 0, 0, 20)
Entry.Parent = Frame
local UIListLayout2 = Instance.new("UIListLayout")
UIListLayout2.SortOrder = Enum.SortOrder.LayoutOrder
UIListLayout2.Parent = Autocomplete
local Title = Instance.new("Frame")
Title.BackgroundColor3 = Color3.fromRGB(59, 59, 59)
Title.BackgroundTransparency = 0.2
Title.BorderSizePixel = 0
Title.LayoutOrder = -2
Title.Name = "Title"
Title.Size = UDim2.new(1, 0, 0, 40)
Title.Parent = Autocomplete
local Description = Instance.new("Frame")
Description.BackgroundColor3 = Color3.fromRGB(59, 59, 59)
Description.BackgroundTransparency = 0.2
Description.BorderSizePixel = 0
Description.LayoutOrder = -1
Description.Name = "Description"
Description.Size = UDim2.new(1, 0, 0, 20)
Description.Parent = Autocomplete
local TextButton = Instance.new("TextButton")
TextButton.BackgroundColor3 = Color3.fromRGB(59, 59, 59)
TextButton.BackgroundTransparency = 0.5
TextButton.BorderSizePixel = 0
TextButton.Font = Enum.Font.Code
TextButton.Size = UDim2.new(1, 0, 0, 30)
TextButton.Text = ""
TextButton.TextColor3 = Color3.fromRGB(255, 255, 255)
TextButton.TextSize = 14
TextButton.TextXAlignment = Enum.TextXAlignment.Left
TextButton.Parent = Autocomplete
local UIListLayout3 = Instance.new("UIListLayout")
UIListLayout3.FillDirection = Enum.FillDirection.Horizontal
UIListLayout3.SortOrder = Enum.SortOrder.LayoutOrder
UIListLayout3.Padding = UDim.new(0, 7)
UIListLayout3.Parent = Entry
local TextBox = Instance.new("TextBox")
TextBox.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
TextBox.BackgroundTransparency = 1
TextBox.ClearTextOnFocus = false
TextBox.Font = Enum.Font.Code
TextBox.LayoutOrder = 999999999
TextBox.Position = UDim2.new(0, 140, 0, 0)
TextBox.Size = UDim2.new(1, 0, 0, 20)
TextBox.Text = "x"
TextBox.TextColor3 = Color3.fromRGB(255, 255, 255)
TextBox.TextSize = 14
TextBox.TextXAlignment = Enum.TextXAlignment.Left
TextBox.Selectable = false
TextBox.Parent = Entry
local TextLabel = Instance.new("TextLabel")
TextLabel.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
TextLabel.BackgroundTransparency = 1
TextLabel.Font = Enum.Font.Code
TextLabel.Size = UDim2.new(0, 0, 0, 20)
TextLabel.AutomaticSize = Enum.AutomaticSize.X
TextLabel.Text = ""
TextLabel.TextColor3 = Color3.fromRGB(255, 223, 93)
TextLabel.TextSize = 14
TextLabel.TextXAlignment = Enum.TextXAlignment.Left
TextLabel.Parent = Entry
local Field = Instance.new("TextLabel")
Field.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Field.BackgroundTransparency = 1
Field.Font = Enum.Font.SourceSansBold
Field.Name = "Field"
Field.Size = UDim2.new(0, 37, 1, 0)
Field.Text = "from"
Field.TextColor3 = Color3.fromRGB(255, 255, 255)
Field.TextSize = 20
Field.TextXAlignment = Enum.TextXAlignment.Left
Field.Parent = Title
local UIPadding2 = Instance.new("UIPadding")
UIPadding2.PaddingLeft = UDim.new(0, 10)
UIPadding2.Parent = Title
local Label = Instance.new("TextLabel")
Label.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Label.BackgroundTransparency = 1
Label.Font = Enum.Font.SourceSansLight
Label.Name = "Label"
Label.Size = UDim2.new(1, 0, 1, 0)
Label.Text = "The players to teleport. The players to teleport. The players to teleport. The players to teleport. "
Label.TextColor3 = Color3.fromRGB(255, 255, 255)
Label.TextSize = 16
Label.TextWrapped = true
Label.TextXAlignment = Enum.TextXAlignment.Left
Label.TextYAlignment = Enum.TextYAlignment.Top
Label.Parent = Description
local UIPadding3 = Instance.new("UIPadding")
UIPadding3.PaddingBottom = UDim.new(0, 10)
UIPadding3.PaddingLeft = UDim.new(0, 10)
UIPadding3.PaddingRight = UDim.new(0, 10)
UIPadding3.Parent = Description
local Typed = Instance.new("TextLabel")
Typed.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Typed.BackgroundTransparency = 1
Typed.Font = Enum.Font.Code
Typed.Name = "Typed"
Typed.Size = UDim2.new(1, 0, 1, 0)
Typed.Text = "Lab"
Typed.TextColor3 = Color3.fromRGB(131, 222, 255)
Typed.TextSize = 14
Typed.TextXAlignment = Enum.TextXAlignment.Left
Typed.Parent = TextButton
local UIPadding4 = Instance.new("UIPadding")
UIPadding4.PaddingLeft = UDim.new(0, 10)
UIPadding4.Parent = TextButton
local Suggest = Instance.new("TextLabel")
Suggest.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Suggest.BackgroundTransparency = 1
Suggest.Font = Enum.Font.Code
Suggest.Name = "Suggest"
Suggest.Size = UDim2.new(1, 0, 1, 0)
Suggest.Text = " el"
Suggest.TextColor3 = Color3.fromRGB(255, 255, 255)
Suggest.TextSize = 14
Suggest.TextXAlignment = Enum.TextXAlignment.Left
Suggest.Parent = TextButton
local Type = Instance.new("TextLabel")
Type.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
Type.BackgroundTransparency = 1
Type.BorderColor3 = Color3.fromRGB(255, 153, 153)
Type.Font = Enum.Font.SourceSans
Type.Name = "Type"
Type.Position = UDim2.new(1, 0, 0, 0)
Type.Size = UDim2.new(0, 0, 1, 0)
Type.Text = ": Players"
Type.TextColor3 = Color3.fromRGB(255, 255, 255)
Type.TextSize = 15
Type.TextXAlignment = Enum.TextXAlignment.Left
Type.Parent = Field
Cmdr.Parent = game:GetService("StarterGui")
return Cmdr
end
| 2,201 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/Initialize.luau | local ReplicatedStorage = game:GetService("ReplicatedStorage")
local StarterGui = game:GetService("StarterGui")
local CreateGui = require(script.Parent.CreateGui)
-- Handles initial preparation of the game server-side.
return function(cmdr)
local ReplicatedRoot, RemoteFunction, RemoteEvent
local function Create(class, name, parent)
local object = Instance.new(class)
object.Name = name
object.Parent = parent or ReplicatedRoot
return object
end
ReplicatedRoot = script.Parent.CmdrClient
ReplicatedRoot.Parent = ReplicatedStorage
RemoteFunction = Create("RemoteFunction", "CmdrFunction")
RemoteEvent = Create("RemoteEvent", "CmdrEvent")
Create("Folder", "Commands")
Create("Folder", "Types")
script.Parent.Shared.Parent = ReplicatedRoot
cmdr.ReplicatedRoot = ReplicatedRoot
cmdr.RemoteFunction = RemoteFunction
cmdr.RemoteEvent = RemoteEvent
cmdr:RegisterTypesIn(script.Parent.BuiltInTypes)
script.Parent.BuiltInTypes:Destroy()
script.Parent.BuiltInCommands.Name = "Server commands"
if StarterGui:FindFirstChild("Cmdr") == nil then
CreateGui()
end
end
| 254 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/Shared/Registry.luau | local RunService = game:GetService("RunService")
local Util = require(script.Parent.Util)
--[=[
@class Registry
The registry keeps track of all the commands and types that Cmdr knows about.
]=]
--[=[
@type HookType "BeforeRun" | "AfterRun"
@within Registry
]=]
--[=[
@interface ArgumentDefinition
@within Registry
.Type string | TypeDefinition -- The argument type (case sensitive), or an [inline TypeDefinition object](/docs/commands#dynamic-arguments-and-inline-types).
.Name string -- The argument name, this is displayed to the user as they type.
.Description string? -- A description of what the argument is, this is also displayed to the user.
.Optional boolean? -- If this is set to `true`, then the user can run the command without filling out the value. In which case, the argument will be sent to implementations as `nil`.
.Default any? -- If present, the argument will be automatically made optional, so if the user doesn't supply a value, implementations will receive whatever the value of `Default` is.
The `table` definition, usually contained in a [CommandDefinition](#CommandDefinition), which 'defines' the argument.
]=]
--[=[
@interface CommandDefinition
@within Registry
.Name string -- The name of the command
.Aliases {string}? -- Aliases which aren't part of auto-complete, but if matched will run this command just the same. For example, `m` might be an alias of `announce`.
.Description string? -- A description of the command, displayed to the user in the `help` command and auto-complete menu.
.Group string? -- This property is intended to be used in hooks, so that you can categorise commands and decide if you want a specific user to be able to run them or not. But the `help` command will use them as headings.
.Args {ArgumentDefinition | (CommandContext) -> (ArgumentDefinition)} -- Arguments for the command; this is technically optional but if you have no args, set it to `{}` or you may experience some interface weirdness.
.Data (CommandContext, ...) -> any -- If your command needs to gather some extra data from the client that's only available on the client, then you can define this function. It should accept the command context and tuple of transformed arguments, and return a single value which will be available in the command with [CommandContext:GetData](/api/CommandContext#GetData).
.ClientRun (CommandContext, ...) -> string? -- If you want your command to run on the client, you can add this function to the command definition itself. It works exactly like the function that you would return from the Server module. If this function returns a string, the command will run entirely on the client and won't touch the server (which means server-only hooks won't run). If this function doesn't return anything, it will fall back to executing the Server module on the server.
.Run (CommandContext, ...) -> string? -- An older version of ClientRun. There are very few scenarios where this is preferred to ClientRun (so, in other words, don't use it!). These days, `Run` is only used for some dark magic involving server-sided command objects.
]=]
--[=[
@interface TypeDefinition
@within Registry
.Prefixes string? -- String containing [prefixed union types](/docs/commands#prefixed-union-types) for this type. This property should omit the inital type, so the string should begin with a prefix character, e.g. `Prefixes = "# integer ! boolean"`
.DisplayName string? -- Overrides the user-facing name of this type in the autocomplete menu. Otherwise, the registered name of the type will be used.
.Default ((Player) -> string)? -- Should return the "default" value for this type as a string. For example, the default value of the `player` type is the name of the player who ran the command.
.Listable boolean? -- If true, this will tell Cmdr that comma-separated lists are allowed for this type. Cmdr will automatically split the list and parse each segment through your `Transform`, `Validate`, `Autocomplete` and `Parse` functions individually, so you don't have to change the logic of your type at all. The only limitation is that your `Parse` function **must return a table**, the tables from each individual segment's `Parse` functions will be merged into one table at the end of the parsing step. The uniqueness of values is ensured upon merging, so even if the user lists the same value several times, it will only appear once in the final table.
.Transform (string, Player) -> T? -- Transform is an optional function that is passed two values: the raw text, and the player running the command. Then, whatever values this function returns will be passed to all other functions in the type (`Validate`, `Autocomplete` and `Parse`).
.Validate (T) -> (boolean, string?) -- The `Validate` function is passed whatever is returned from the `Transform` function (or the raw value if there is no `Transform` function). If the value is valid for the type, it should return `true`. If the value is invalid, it should return two values: `false` and a string containing an error message. If this function is omitted, anything will be considered valid.
.ValidateOnce (T) -> (boolean, string?) -- This function works exactly the same as the normal `Validate` function, except it only runs once (after the user presses Enter). This should only be used if the validation process is relatively expensive or needs to yield. For example, the `playerId` type uses this because it needs to call `GetUserIdFromNameAsync` in order to validate. For the vast majority of types, you should just use `Validate` instead.
.Autocomplete (T) -> ({string}, {IsPartial: boolean?}?)? -- Should only be present for types that are possible to be auto-completed. It should return an array of strings that will be displayed in the auto-complete menu. It can also return a second value, containing a dictionary of options (currently, `IsPartial`: if true then pressing Tab to auto-complete won't continue onwards to the next argument.)
.Parse (T) -> any -- Parse is the only required function in a type definition. It is the final step before the value is considered finalised. This function should return the actual parsed value that will be sent to implementations.
The `table` definition, contained in an [ArgumentDefinition](#ArgumentDefinition) or [registered](#RegisterType), which 'defines' the argument.
]=]
--[=[
@prop TypeMethods { [string]: true }
@within Registry
@readonly
@private
]=]
--[=[
@prop CommandMethods { [string]: true }
@within Registry
@readonly
@private
]=]
--[=[
@prop CommandArgProps { [string]: true }
@within Registry
@readonly
@private
]=]
--[=[
@prop Types table
@within Registry
@readonly
@private
]=]
--[=[
@prop TypeAliases table
@within Registry
@readonly
@private
]=]
--[=[
@prop Commands table
@within Registry
@readonly
@private
]=]
--[=[
@prop CommandsArray table
@within Registry
@readonly
@private
]=]
--[=[
@prop Cmdr Cmdr | CmdrClient
@within Registry
@readonly
A reference to Cmdr. This may either be the server or client version of Cmdr depending on where the code is running.
]=]
--[=[
@prop Hooks { [HookType]: table }
@within Registry
@readonly
@private
]=]
--[=[
@prop Stores table
@within Registry
@readonly
@private
]=]
--[=[
@prop AutoExecBuffer table
@within Registry
@readonly
@private
]=]
local Registry = {
TypeMethods = Util.MakeDictionary({
"Transform",
"Validate",
"Autocomplete",
"Parse",
"DisplayName",
"Listable",
"ValidateOnce",
"Prefixes",
"Default",
"ArgumentOperatorAliases",
}),
CommandMethods = Util.MakeDictionary({
"Name",
"Aliases",
"AutoExec",
"Description",
"Args",
"Run",
"ClientRun",
"Data",
"Group",
"Guards",
}),
CommandArgProps = Util.MakeDictionary({ "Name", "Type", "Description", "Optional", "Default" }),
Types = {},
TypeAliases = {},
Commands = {},
CommandsArray = {},
Cmdr = nil,
Hooks = {
BeforeRun = {},
AfterRun = {},
},
Stores = setmetatable({}, {
__index = function(self, k)
self[k] = {}
return self[k]
end,
}),
AutoExecBuffer = {},
}
--[=[
Registers a type on the current realm (server/client), this function should be called from within the type definition ModuleScript.
@param name -- The name of the type, this must be unique, alphanumeric, and start with a lower-case letter or digit.
@param typeObject TypeDefinition
@within Registry
]=]
function Registry:RegisterType(name: string, typeObject)
if not name or typeof(name) ~= "string" then
error("[Cmdr] Invalid type name provided: nil")
end
if not name:find("^[%d%l]%w*$") then
error(
`[Cmdr] Invalid type name provided: "{name}", type names must be alphanumeric and start with a lower-case letter or a digit.`
)
end
for key in pairs(typeObject) do
if self.TypeMethods[key] == nil then
error(`[Cmdr] Unknown key/method in type "{name}": {key}`)
end
end
if self.Types[name] ~= nil then
error(`[Cmdr] Type {name} has already been registered.`)
end
typeObject.Name = name
typeObject.DisplayName = typeObject.DisplayName or name
self.Types[name] = typeObject
if typeObject.Prefixes then
self:RegisterTypePrefix(name, typeObject.Prefixes)
end
end
--[=[
Registers a Prefixed Union Type string on the current realm (server/client), this function should be called from within the type definition ModuleScript.
If there are already type prefixes for the given type name, they will be concatenated. This allows you to add prefixes to default types, like `players`.
@param name -- The name of the type.
@param union -- The string should omit the initial type name, so this string should begin with a prefix character, e.g. `# integer ! boolean`
@within Registry
]=]
function Registry:RegisterTypePrefix(name: string, union: string)
if not self.TypeAliases[name] then
self.TypeAliases[name] = name
end
self.TypeAliases[name] = ("%s %s"):format(self.TypeAliases[name], union)
end
--[=[
Allows you to register a name which will be expanded into a longer type which can be used as a command argument type.
For example, if you register the alias `stringOrNumber` it could be interpreted as `string # number` when used.
@param name -- The name of the type, this must be unique, alphanumeric, and start with a lower-case letter or digit.
@param alias -- The string should *include* the initial type name, e.g. `string # integer ! boolean`
@within Registry
]=]
function Registry:RegisterTypeAlias(name: string, alias: string)
assert(self.TypeAliases[name] == nil, `[Cmdr] Type alias {alias} already exists!`)
self.TypeAliases[name] = alias
end
--[=[
Registers all types from within a container on both the server and client.
@server
@within Registry
]=]
function Registry:RegisterTypesIn(container: Instance)
for _, object in pairs(container:GetChildren()) do
if object:IsA("ModuleScript") then
object.Parent = self.Cmdr.ReplicatedRoot.Types
require(object)(self)
else
self:RegisterTypesIn(object)
end
end
end
-- These are exactly the same thing. No one will notice. Except for you, dear reader.
--[=[
@method RegisterHooksIn
Registers all hooks from within a container on both the server and client.
If you want to add a hook only on the server or client – e.g. for logging – then you should use the Register.RegisterHook method instead.
@param container Instance
@server
@within Registry
]=]
Registry.RegisterHooksIn = Registry.RegisterTypesIn
--[=[
Register a command purely based on its definition.
Prefer using Registry:RegisterCommand for proper handling of client/server model.
@param commandObject CommandDefinition
@private
@within Registry
]=]
function Registry:RegisterCommandObject(commandObject)
for key in pairs(commandObject) do
if self.CommandMethods[key] == nil then
error(`[Cmdr] Unknown key/method in command "{commandObject.Name or "unknown command"}": {key}`)
end
end
if commandObject.Args then
for i, arg in pairs(commandObject.Args) do
if type(arg) == "table" then
for key in pairs(arg) do
if self.CommandArgProps[key] == nil then
error(
`[Cmdr] Unknown property in command "{commandObject.Name or "unknown"}" argument #{i}: {key}`
)
end
end
end
end
end
if commandObject.AutoExec and RunService:IsClient() then
table.insert(self.AutoExecBuffer, commandObject.AutoExec)
self:FlushAutoExecBufferDeferred()
end
-- Unregister the old command if it exists...
local oldCommand = self.Commands[commandObject.Name:lower()]
if oldCommand and oldCommand.Aliases then
for _, alias in pairs(oldCommand.Aliases) do
self.Commands[alias:lower()] = nil
end
elseif not oldCommand then
table.insert(self.CommandsArray, commandObject)
end
self.Commands[commandObject.Name:lower()] = commandObject
if commandObject.Aliases then
for _, alias in pairs(commandObject.Aliases) do
self.Commands[alias:lower()] = commandObject
end
end
end
--[=[
Registers a command definition and its server equivalent. Handles replicating the definition to the client.
@param filter (CommandDefinition -> boolean)? -- If present, will be passed a command definition which will then only be registered if the function returns `true`.
@server
@within Registry
]=]
function Registry:RegisterCommand(
commandScript: ModuleScript,
commandServerScript: ModuleScript?,
filter: ((any) -> boolean)?
)
local commandObject = require(commandScript)
assert(
typeof(commandObject) == "table",
`[Cmdr] Invalid return value from command script "{commandScript.Name}" (CommandDefinition expected, got {typeof(commandObject)})`
)
if commandServerScript then
assert(RunService:IsServer(), "[Cmdr] The commandServerScript parameter is not valid for client usage.")
commandObject.Run = require(commandServerScript)
end
if filter and not filter(commandObject) then
return
end
self:RegisterCommandObject(commandObject)
commandScript.Parent = self.Cmdr.ReplicatedRoot.Commands
end
--[=[
Registers all commands from within a container on both the server and client.
Module scripts which include `Server` in their name will not be sent to the client.
@param filter ((CommandDefinition) -> boolean)? -- If present, will be passed a command definition which will then only be registered if the function returns `true`.
@server
@within Registry
]=]
function Registry:RegisterCommandsIn(container: Instance, filter: ((any) -> boolean)?)
local skippedServerScripts = {}
local usedServerScripts = {}
for _, commandScript in pairs(container:GetChildren()) do
if commandScript:IsA("ModuleScript") then
if not commandScript.Name:find("Server") then
local serverCommandScript = container:FindFirstChild(commandScript.Name .. "Server")
if serverCommandScript then
usedServerScripts[serverCommandScript] = true
end
self:RegisterCommand(commandScript, serverCommandScript, filter)
else
skippedServerScripts[commandScript] = true
end
else
self:RegisterCommandsIn(commandScript, filter)
end
end
for skippedScript in pairs(skippedServerScripts) do
if not usedServerScripts[skippedScript] then
warn(
`[Cmdr] Command script {skippedScript.Name} was skipped because it has 'Server' in its name, and has no equivalent shared script.`
)
end
end
end
--[=[
Registers the default commands on both the server and client.
The optional `arrayOrFunc` parameter can be provided with:
1. an array of strings — this will limit registration to only commands which have their `Group` property set to this
2. a function which takes in a CommandDefinition and returns a `boolean` — only if `true` is returned will the command be registered
@param arrayOrFunc {string} | (CommandDefinition) -> boolean | nil
@server
@within Registry
]=]
function Registry:RegisterDefaultCommands(arrayOrFunc: { string } | (any) -> boolean | nil)
assert(RunService:IsServer(), "[Cmdr] RegisterDefaultCommands cannot be called from the client.")
local dictionary = if type(arrayOrFunc) == "table" then Util.MakeDictionary(arrayOrFunc) else nil
self:RegisterCommandsIn(self.Cmdr.DefaultCommandsFolder, dictionary ~= nil and function(command)
return dictionary[command.Group] or false
end or arrayOrFunc)
end
--[=[
Returns the CommandDefinition from the given name, or nil if no command is found. Command aliases are also accepted.
@return CommandDefinition?
@within Registry
]=]
function Registry:GetCommand(name: string)
name = name or ""
return self.Commands[name:lower()]
end
--[=[
Returns an array of all registers commands, not including aliases.
@return {CommandDefinition}
@within Registry
]=]
function Registry:GetCommands(): { any }
return self.CommandsArray
end
--[=[
Returns an array of containing the names of all registered commands, not including aliases.
@within Registry
]=]
function Registry:GetCommandNames(): { string }
local commands = {}
for _, command in pairs(self.CommandsArray) do
table.insert(commands, command.Name)
end
return commands
end
--[=[
@method GetCommandsAsStrings
@deprecated v1.8.0 -- This method was renamed to GetCommandNames in v1.8.0. The old name exists for backwards compatibility and should not be used for new work.
@within Registry
]=]
Registry.GetCommandsAsStrings = Registry.GetCommandNames
--[=[
Returns an array of containing the names of all registered types, not including aliases.
@within Registry
]=]
function Registry:GetTypeNames(): { string }
local typeNames = {}
for typeName in pairs(self.Types) do
table.insert(typeNames, typeName)
end
return typeNames
end
--[=[
Returns the type definition from the given name, or nil if no argument is found.
@return TypeDefinition?
@within Registry
]=]
function Registry:GetType(name: string)
return self.Types[name]
end
--[=[
Returns a type name taking aliases into account. If there is no alias, the name parameter is simply returned as a pass through.
@return TypeDefinition | string
@within Registry
]=]
function Registry:GetTypeName(name: string): string | any
return self.TypeAliases[name] or name
end
--[=[
Registers a hook on the current realm (server/client). This should probably be ran on the server or in a hook module script, but can also work on the client.
Hooks run in order of priority from lowest (running first) to highest.
@param hookName HookType
@param callback (CommandContext) -> string? -- returns nil for ok, string (errorText) for cancellation
@param priority -- If unspecified, the priority will default to `0`.
@within Registry
]=]
function Registry:RegisterHook(hookName: string, callback: (any) -> string?, priority: number)
if not self.Hooks[hookName] then
error(("[Cmdr] Invalid hook name: %q"):format(hookName), 2)
end
table.insert(self.Hooks[hookName], { callback = callback, priority = priority or 0 })
table.sort(self.Hooks[hookName], function(a, b)
return a.priority < b.priority
end)
end
--[=[
@method AddHook
@deprecated v1.1.2 -- This method was renamed to RegisterHook in v1.1.2. The old name exists for backwards compatibility and should not be used for new work.
@param hookName HookType
@param callback (CommandContext) -> string? -- returns nil for ok, string (errorText) for cancellation
@param priority number -- If unspecified, the priority will default to `0`.
@within Registry
]=]
Registry.AddHook = Registry.RegisterHook
--[=[
Returns a table saved with the given name. Always returns the same table on subsequent calls. Useful for commands that require persistent state, like bind or ban.
This is the same as CommandContext.GetStore.
@return table
@within Registry
]=]
function Registry:GetStore(name: string)
return self.Stores[name]
end
--[=[
Calls Registry.FlushAutoExecBuffer at the end of the frame.
@private
@within Registry
]=]
function Registry:FlushAutoExecBufferDeferred()
if self.AutoExecFlushConnection then
return
end
self.AutoExecFlushConnection = RunService.Heartbeat:Connect(function()
self.AutoExecFlushConnection:Disconnect()
self.AutoExecFlushConnection = nil
self:FlushAutoExecBuffer()
end)
end
--[=[
Runs all pending auto exec commands in Registry.AutoExecBuffer.
@private
@within Registry
]=]
function Registry:FlushAutoExecBuffer()
for _, commandGroup in ipairs(self.AutoExecBuffer) do
for _, command in ipairs(commandGroup) do
self.Cmdr.Dispatcher:EvaluateAndRun(command)
end
end
self.AutoExecBuffer = {}
end
return function(cmdr)
Registry.Cmdr = cmdr
return Registry
end
| 4,860 |
evaera/Cmdr | evaera-Cmdr-030e1a6/Cmdr/init.luau | local RunService = game:GetService("RunService")
local Util = require(script.Shared:WaitForChild("Util"))
if RunService:IsServer() == false then
error(
"[Cmdr] Client scripts cannot require the server library. Please require the client library from the client to use Cmdr in your own code."
)
end
--[=[
@class Cmdr
@server
The Cmdr server singleton and entry point.
]=]
--[=[
@within Cmdr
@prop Registry Registry
@readonly
Refers to the current command Registry.
]=]
--[=[
@within Cmdr
@prop Dispatcher Dispatcher
@readonly
Refers to the current command Dispatcher.
]=]
--[=[
@within Cmdr
@prop Util Util
@readonly
Refers to a table containing many useful utility functions.
]=]
local Cmdr
do
Cmdr = setmetatable({
ReplicatedRoot = nil,
RemoteFunction = nil,
RemoteEvent = nil,
Util = Util,
DefaultCommandsFolder = script.BuiltInCommands,
}, {
__index = function(self, k)
local r = self.Registry[k]
if r and type(r) == "function" then
return function(_, ...)
return r(self.Registry, ...)
end
end
end,
})
Cmdr.Registry = require(script.Shared.Registry)(Cmdr)
Cmdr.Dispatcher = require(script.Shared.Dispatcher)(Cmdr)
require(script.Initialize)(Cmdr)
end
-- Handle command invocations from the clients.
Cmdr.RemoteFunction.OnServerInvoke = function(player, text, options)
if #text > 10000 then
return "Input too long"
end
return Cmdr.Dispatcher:EvaluateAndRun(text, player, options)
end
return Cmdr
| 389 |
centau/vide | centau-vide-7deae9c/init.luau | local vide = require "@self/src/lib"
export type source<T> = vide.source<T>
export type Source<T> = vide.Source<T>
export type context<T> = vide.context<T>
export type Context<T> = vide.Context<T>
return vide
| 52 |
centau/vide | centau-vide-7deae9c/src/action.luau | type Action = {
priority: number,
callback: (Instance) -> ()
}
local ActionMT = table.freeze {}
local function is_action(v: any)
return getmetatable(v) == ActionMT
end
local function action(callback: (Instance) -> (), priority: number?): Action
local a = {
priority = priority or 1,
callback = callback
}
setmetatable(a :: any, ActionMT)
return table.freeze(a)
end
return function()
return action, is_action
end
| 111 |
centau/vide | centau-vide-7deae9c/src/apply.luau | local typeof = game and typeof or require "../test/mock".typeof :: never
local flags = require "./flags"
local implicit_effect = require "./implicit_effect"
local _, is_action = require "./action"()
local graph = require "./graph"
type Node<T> = graph.Node<T>
type Array<V> = { V }
type ArrayOrV<V> = {ArrayOrV<V>} | V
type Map<K, V> = { [K]: V }
type Cache = {
-- event listeners to connect after properties are set
events: Array<
| string -- 1. event name
| () -> () -- 2. listener
>,
-- actions to run after events are connected
actions: Map<
number, -- priority
Array<(Instance) -> ()> -- action callbacks
>,
-- what to parent the instance to after running actions
parent: unknown,
-- cache to detect duplicate property setting at same nesting depth
nested_debug: Map<
number, -- depth
Map<string, true> -- set of property names
>,
-- each nested layer occupies two indexes: 1. table ref 2. nested depth
-- e.g. { t1 = { t3 = {} }, t2 = {} } -> { t1, 1, t2, 1, t3, 2 }
nested_stack: { {} | number }
}
local free_cache: Cache?
local function borrow_cache(): Cache
if free_cache then
local cache = free_cache
free_cache = nil
return cache
else
return {
events = {},
actions = setmetatable({} :: any, { -- lazy init
__index = function(self, i) self[i] = {}; return self[i] end
}),
parent = nil,
nested_debug = setmetatable({} :: any, {
__index = function(self, i: number) self[i] = {}; return self[i] end
}),
nested_stack = {}
}
end
end
local function return_cache(cache: Cache )
free_cache = cache
end
local function process_properties(properties: Map<unknown, unknown>, instance: Instance, cache: Cache, depth: number)
for property, value in properties do
if type(property) == "string" then
if flags.strict then -- check for duplicate property assignment at nesting depth
if cache.nested_debug[depth][property] then
error(`duplicate property {property} at depth {depth}`, 0)
end
cache.nested_debug[depth][property] = true
end
if property == "Parent" then
cache.parent = value
continue
end
if type(value) == "function" then
if typeof((instance :: any)[property]) == "RBXScriptSignal" then
table.insert(cache.events, property) -- add event name to buffer
table.insert(cache.events, value :: () -> ()) -- add event listener to buffer
else
implicit_effect.property(instance, property, value :: () -> ()) -- create implicit effect for property
end
else
(instance :: any)[property] = value -- set property
end
elseif type(property) == "number" then
if type(value) == "function" then
implicit_effect.children(instance, value :: () -> ArrayOrV<Instance>) -- bind children
elseif type(value) == "table" then
if is_action(value) then
table.insert(cache.actions[(value :: any).priority], (value :: any).callback :: () -> ()) -- add action to buffer
elseif flags.defer_nested_properties then
table.insert(cache.nested_stack, value :: {})
table.insert(cache.nested_stack, depth + 1) -- push table to stack for later processing
else
process_properties(value :: Map<unknown, unknown>, instance, cache, depth + 1)
end
elseif type(value) == "userdata" then
(value :: Instance).Parent = instance -- parent child
end
end
end
end
-- applies table of nested properties to an instance using full vide semantics
local function apply<T>(instance: T & Instance, properties: { [unknown]: unknown }): T
if not properties then
error "attempt to call a constructor returned by create() with no properties"
end
local caches = borrow_cache()
local events = caches.events
local actions = caches.actions
local nested_debug = caches.nested_debug
local nested_stack = caches.nested_stack
-- process all properties
local depth = 1
repeat
process_properties(properties, instance, caches, depth)
depth = table.remove(nested_stack) :: number
properties = table.remove(nested_stack) :: {}
until not properties
for i = 1, #events, 2 do
local event_name = events[i]
local event_listener = events[i + 1]
;(instance :: any)[event_name]:Connect(event_listener)
end
for _, queued in actions do
for _, callback in queued do
callback(instance)
end
end
local parent = caches.parent
if parent then
if type(parent) == "function" then
implicit_effect.parent(instance, parent :: () -> Instance)
else
instance.Parent = parent :: Instance
end
end
table.clear(events)
for _, queued in actions do table.clear(queued) end
caches.parent = nil
if flags.strict then table.clear(nested_debug) end
table.clear(nested_stack)
return_cache(caches)
return instance
end
return apply
| 1,226 |
centau/vide | centau-vide-7deae9c/src/batch.luau | local flags = require "./flags"
local graph = require "./graph"
local function batch(setter: () -> ())
local already_batching = flags.batch
local from
if not already_batching then
flags.batch = true
from = graph.get_update_queue_length()
end
local ok, err: string? = xpcall(setter, debug.traceback)
if not already_batching then
flags.batch = false
graph.flush_update_queue(from)
end
if not ok then error(`error occured while batching updates: {err}`, 0) end
end
return batch
| 131 |
centau/vide | centau-vide-7deae9c/src/branch.luau | local graph = require "./graph"
type Node<T> = graph.Node<T>
local create_node = graph.create_node
local push_scope = graph.push_scope
local pop_scope = graph.pop_scope
local destroy = graph.destroy
local get_scope = graph.get_scope
local function branch<T>(fn: () -> T): (() -> (), T)
local current = get_scope()
if not current then
error(`cannot use branch() outside a stable or reactive scope`, 0)
end
local parent = current.owner
if not parent then
error(`current scope is not owned by a scope`, 0)
end
local node = create_node(parent, false, false)
local destroy = function()
destroy(node)
end
push_scope(node)
local ok, result = xpcall(fn, debug.traceback)
pop_scope()
if not ok then
destroy()
error(`error while running branch():\n\n{result}`, 0)
end
return destroy, result
end
return branch
| 223 |
centau/vide | centau-vide-7deae9c/src/changed.luau | local action = require "./action"()
local cleanup = require "./cleanup"
local function changed<T>(property: string, callback: (T) -> ())
return action(function(instance)
local con = instance:GetPropertyChangedSignal(property):Connect(function()
callback((instance :: any)[property])
end)
cleanup(function()
con:Disconnect()
end)
callback((instance :: any)[property])
end)
end
return changed
| 91 |
centau/vide | centau-vide-7deae9c/src/cleanup.luau | local typeof = game and typeof or require "../test/mock".typeof :: never
local graph = require "./graph"
local get_scope = graph.get_scope
local push_cleanup = graph.push_cleanup
local function helper(obj: any)
return
if typeof(obj) == "RBXScriptConnection" then function() obj:Disconnect() end
elseif type(obj) == "thread" then function() task.cancel(obj) end
elseif typeof(obj) == "Instance" then function() obj:Destroy() end
elseif obj.destroy then function() obj:destroy() end
elseif obj.disconnect then function() obj:disconnect() end
elseif obj.Destroy then function() obj:Destroy() end
elseif obj.Disconnect then function() obj:Disconnect() end
else error "cannot cleanup given object"
end
local function cleanup(value: unknown)
local scope = get_scope()
if not scope then
error "cannot cleanup outside a stable or reactive scope"
end; assert(scope)
if type(value) == "function" then
push_cleanup(scope, value :: () -> ())
else
push_cleanup(scope, helper(value))
end
end
type Destroyable = { destroy: (any) -> () } | { Destroy: (any) -> () }
type Disconnectable = { disconnect: (any) -> () } | { Disconnect: (any) -> () }
return cleanup ::
( (callback: () -> ()) -> () ) &
( (thread: thread) -> () ) &
( (instance: Destroyable) -> () ) &
( (connection: Disconnectable) -> () ) &
( (instance: Instance) -> () ) &
( (connection: RBXScriptConnection) -> () )
| 365 |
centau/vide | centau-vide-7deae9c/src/context.luau | local graph = require "./graph"
type Node<T> = graph.Node<T>
local create_node = graph.create_node
local get_scope = graph.get_scope
local push_scope = graph.push_scope
local pop_scope = graph.pop_scope
local set_context = graph.set_context
export type Context<T> = (() -> T) & (<U>(T, () -> U) -> U)
local nil_symbol = newproxy()
local count = 0
local function context<T>(...: T): Context<T>
count += 1
local id = count
local has_default = select("#", ...) > 0
local default_value = ...
return function<T>(...): any -- todo: fix type error
local scope: Node<unknown>? | false = get_scope()
if select("#", ...) == 0 then -- get
while scope do
local ctx = scope.context
if not ctx then
scope = scope.owner
continue
end
local value = (ctx :: { unknown })[id]
if value == nil then
scope = scope.owner
continue
end
return (if value ~= nil_symbol then value else nil) :: T
end
if has_default ~= nil then
return default_value
else
error("attempt to get context when no context is set and no default context is set", 0)
end
else -- set
if not scope then return error("attempt to set context outside of a vide scope", 0) end
local value, component = ...
local new_scope = create_node(scope, false, false)
set_context(new_scope, id, if value == nil then nil_symbol else value)
push_scope(new_scope)
local function efn(err: string) return debug.traceback(err, 3) end
local ok, result = xpcall(component, efn)
pop_scope()
if not ok then
error(`error while running context:\n\n{result}`, 0)
end
return result
end
return nil :: any
end
end
return context
| 456 |
centau/vide | centau-vide-7deae9c/src/create.luau | local typeof = game and typeof or require "../test/mock".typeof :: never
local Instance = game and Instance or require "../test/mock".Instance :: never
local defaults = require "./defaults"
local apply = require "./apply"
local flags = require "./flags"
local ctor_cache = {} :: { [string]: (AnyProps) -> Instance }
local function lazy_init(_, class: string)
local function ctor(properties: AnyProps): Instance
local ok, instance: Instance = pcall(Instance.new, class :: any)
if not ok then error(`invalid class name { class }`, 0) end
if flags.defaults then
local default: { [string]: unknown }? = defaults[class]
if default then
for i, v in default do
(instance :: any)[i] = v
end
end
end
return apply(instance, properties)
end
ctor_cache[class] = ctor
return ctor
end
setmetatable(ctor_cache, { __index = lazy_init })
-- todo: remove support for different overloads
local function create(class_or_instance: string|Instance, properties: AnyProps?): ((AnyProps) -> Instance) | Instance
if type(class_or_instance) ~= "string" and typeof(class_or_instance) ~= "Instance" then
error("bad argument #1, expected string or instance, got " .. typeof(class_or_instance), 0)
end
local ctor = if type(class_or_instance) == "string"
then ctor_cache[class_or_instance]
else function(properties)
local clone = class_or_instance:Clone()
if not clone then error "attempt to clone a non-archivable instance" end
return apply(clone, properties)
end
return if properties
then ctor(properties)
else ctor
end
type Instances = {
Folder: Folder,
BillboardGui: BillboardGui,
CanvasGroup: CanvasGroup,
Frame: Frame,
ImageButton: ImageButton,
ImageLabel: ImageLabel,
ScreenGui: ScreenGui,
ScrollingFrame: ScrollingFrame,
SurfaceGui: SurfaceGui,
TextBox: TextBox,
TextButton: TextButton,
TextLabel: TextLabel,
UIAspectRatioConstraint: UIAspectRatioConstraint,
UICorner: UICorner,
UIGradient: UIGradient,
UIGridLayout: UIGridLayout,
UIListLayout: UIListLayout,
Camera: Camera,
WorldModel: WorldModel,
}
type function Properties(instance: type?)
local properties = types.newtable()
while instance do
for i, v in instance:properties() do
local connector = v.read and v.read.tag == "table" and v.read:readproperty(types.singleton("Connect"))
if connector then
local params = connector:parameters().head
if not params then continue end
local listener = params[2]
if not listener then continue end
properties:setproperty(i, types.optional(listener))
elseif v.write then
properties:setproperty(i, types.optional(types.unionof(
v.write,
types.newfunction({}, { head = { v.write } })
)))
end
end
instance = instance:readparent()
end
properties:setindexer(types.number, types.any)
return properties
end
type AnyProps = { [any]: any }
type Create = (
(Instance) -> (AnyProps) -> Instance
) & (
(string, AnyProps) -> Instance
) & (
<Name>(Name|keyof<Instances>) -> (Properties<index<Instances, Name>>) -> index<Instances, Name>
)
return (create :: any) :: Create
| 785 |
centau/vide | centau-vide-7deae9c/src/defaults.luau | local Enum = game and Enum or require "../test/mock".Enum :: never
local Color3 = game and Color3 or require "../test/mock".Color3 :: never
return {
Part = {
Material = Enum.Material.SmoothPlastic,
Size = vector.create(1, 1, 1),
Anchored = true
},
BillboardGui = {
ResetOnSpawn = false,
ZIndexBehavior = Enum.ZIndexBehavior.Sibling
},
CanvasGroup = nil,
Frame = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0
},
ImageButton = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0,
AutoButtonColor = false
},
ImageLabel = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0,
},
ScreenGui = {
ResetOnSpawn = false,
ZIndexBehavior = Enum.ZIndexBehavior.Sibling
},
ScrollingFrame = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0,
ScrollBarImageColor3 = Color3.new(0, 0, 0)
},
SurfaceGui = {
ResetOnSpawn = false,
ZIndexBehavior = Enum.ZIndexBehavior.Sibling,
PixelsPerStud = 50,
SizingMode = Enum.SurfaceGuiSizingMode.PixelsPerStud
},
TextBox = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0,
ClearTextOnFocus = false,
Font = Enum.Font.SourceSans,
Text = "",
TextColor3 = Color3.new(0, 0, 0)
},
TextButton = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0,
AutoButtonColor = false,
Font = Enum.Font.SourceSans,
Text = "",
TextColor3 = Color3.new(0, 0, 0)
},
TextLabel = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0,
Font = Enum.Font.SourceSans,
Text = "",
TextColor3 = Color3.new(0, 0, 0)
},
UIListLayout = {
SortOrder = Enum.SortOrder.LayoutOrder
},
UIGridLayout = {
SortOrder = Enum.SortOrder.LayoutOrder
},
UITableLayout = {
SortOrder = Enum.SortOrder.LayoutOrder
},
UIPageLayout = {
SortOrder = Enum.SortOrder.LayoutOrder
},
VideoFrame = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0
},
ViewportFrame = {
BackgroundColor3 = Color3.new(1, 1, 1),
BorderColor3 = Color3.new(0, 0, 0),
BorderSizePixel = 0
}
}
| 831 |
centau/vide | centau-vide-7deae9c/src/derive.luau | local graph = require "./graph"
local create_node = graph.create_node
local push_scope_as_child_of = graph.push_scope_as_child_of
local assert_stable_scope = graph.assert_stable_scope
local evaluate_node = graph.evaluate_node
local function derive<T>(source: () -> T): () -> T
local node = create_node(assert_stable_scope(), source, false :: any)
evaluate_node(node)
return function()
push_scope_as_child_of(node)
return node.cache
end
end
return derive
| 111 |
centau/vide | centau-vide-7deae9c/src/effect.luau | local graph = require "./graph"
local create_node = graph.create_node
local assert_stable_scope = graph.assert_stable_scope
local evaluate_node = graph.evaluate_node
local function effect<T>(callback: (T) -> T, initial_value: T)
local node = create_node(assert_stable_scope(), callback, initial_value)
evaluate_node(node)
end
return effect :: (<T>(callback: (T) -> T, initial_value: T) -> ()) & ((callback: () -> ()) -> ())
| 106 |
centau/vide | centau-vide-7deae9c/src/flags.luau | local function inline_test(): string
return debug.info(1, "n")
end
local is_O2 = inline_test() ~= "inline_test"
return {
strict = not is_O2,
defaults = true,
defer_nested_properties = true,
batch = false,
}
| 60 |
centau/vide | centau-vide-7deae9c/src/graph.luau | local flags = require "./flags"
export type SourceNode<T> = {
cache: T,
[number]: Node<T>
}
export type Node<T> = {
cache: T,
effect: ((T) -> T) | false,
cleanups: { () -> () } | false,
context: { [number]: unknown } | false,
owned: { Node<T> } | false,
owner: Node<T> | false,
parents: { SourceNode<T> },
[number]: Node<T> -- children
}
local scopes = { n = 0 } :: { [number]: Node<any>, n: number } -- scopes stack
local function efn(err: string)
local trace = debug.traceback(err, 2)
if string.find(err, "^effect error stacktrace") then -- if effect error is nested
trace = string.gsub(" " .. trace, "\n", function() -- indent entire error
return "\n "
end)
end
trace ..= "\nsource update stacktrace:"
return trace
end
local function ycall<T, U>(fn: (T) -> U, arg: T): (boolean, string|U)
local thread = coroutine.create(xpcall)
--local function efn(err: string) return debug.traceback(err, 3) end
local resume_ok, run_ok, result = coroutine.resume(thread, fn, efn, arg)
assert(resume_ok)
if coroutine.status(thread) ~= "dead" then
return false, debug.traceback(thread, "attempt to yield in reactive scope")
end
return run_ok, result
end
local function get_scope(): Node<unknown>?
return scopes[scopes.n]
end
local function assert_stable_scope(): Node<unknown>
local scope = get_scope()
if not scope then
local caller_name = debug.info(2, "n")
return error(`cannot use {caller_name}() outside a stable or reactive scope`, 0)
elseif scope.effect then
error("cannot create a new reactive scope inside another reactive scope", 0)
end
return scope
end
local function push_child<T>(parent: SourceNode<any>, child: Node<any>)
table.insert(parent, child)
table.insert(child.parents, parent)
end
local function push_scope<T>(node: Node<T>)
local n = scopes.n + 1
scopes.n = n
scopes[n] = node
end
local function pop_scope()
local n = scopes.n
scopes.n = n - 1
scopes[n] = nil
end
local function push_cleanup<T>(node: Node<T>, cleanup: () -> ())
if node.cleanups then
table.insert(node.cleanups, cleanup)
else
node.cleanups = { cleanup }
end
end
local function flush_cleanups<T>(node: Node<T>)
if node.cleanups then
for _, fn in node.cleanups do
local ok, err: string? = xpcall(fn, debug.traceback)
if not ok then error(`cleanup error: {err}`, 0) end
end
table.clear(node.cleanups)
end
end
local function find_and_swap_pop<T>(t: { T }, v: T)
local i = table.find(t, v) :: number
local n = #t
t[i] = t[n]
t[n] = nil
end
local function unparent<T>(node: Node<T>)
local parents = node.parents
for i, parent in parents do
find_and_swap_pop(parent, node)
parents[i] = nil
end
end
local function destroy<T>(node: Node<T>)
if flags.strict and table.find(scopes, node) then
error("attempt to destroy an active scope", 0)
end
flush_cleanups(node)
unparent(node)
if node.owner then
find_and_swap_pop(node.owner.owned :: { Node<T> }, node)
node.owner = false
end
if node.owned then
local owned = node.owned
while owned[1] do destroy(owned[1]) end
end
end
local function destroy_owned<T>(node: Node<T>)
if node.owned then
local owned = node.owned
while owned[1] do destroy(owned[1]) end
end
end
local update_queue = { n = 0 } :: { n: number, [number]: Node<any> }
local function evaluate_node<T>(node: Node<T>)
if flags.strict then
if table.find(scopes, node) then
error("a scope, that should rerun due to the update of a source, is already active", 0)
end
local initial_value = node.cache
for i = 1, 2 do
local cur_value = node.cache
flush_cleanups(node)
destroy_owned(node)
push_scope(node)
local ok, new_value = ycall(node.effect :: (T) -> T, cur_value)
pop_scope()
if not ok then
table.clear(update_queue)
update_queue.n = 0
error(`effect error stacktrace\n{new_value :: string}`, 0)
end
node.cache = new_value :: T
end
return initial_value ~= node.cache
else
local cur_value = node.cache
flush_cleanups(node)
destroy_owned(node)
push_scope(node)
local ok, new_value = pcall(node.effect :: (T) -> T, node.cache)
pop_scope()
if not ok then
table.clear(update_queue)
update_queue.n = 0
error(`effect error:\n{new_value}\n`, 0)
end
node.cache = new_value
return cur_value ~= new_value
end
end
local function queue_children_for_update<T>(node: SourceNode<T>)
local i = update_queue.n
while node[1] do
i += 1
update_queue[i] = node[1]
unparent(node[1])
end
update_queue.n = i
end
local function get_update_queue_length()
return update_queue.n
end
local function flush_update_queue(from: number)
local i = from + 1
while i <= update_queue.n do
local node = update_queue[i]
--assert(node.effect)
if node.owner and evaluate_node(node) then
queue_children_for_update(node)
end
update_queue[i] = false :: any
i += 1
end
update_queue.n = from
end
local function update_descendants<T>(root: SourceNode<T>)
local n0 = update_queue.n
queue_children_for_update(root)
if flags.batch then return end
local i = n0 + 1
while i <= update_queue.n do
local node = update_queue[i]
--assert(node.effect)
-- check if node is still owned in case destroyed after queued
if node.owner and evaluate_node(node) then
queue_children_for_update(node)
end
update_queue[i] = false :: any -- false instead of nil to avoid sparse
i += 1
end
update_queue.n = n0
end
local function push_scope_as_child_of<T>(node: SourceNode<T>)
local scope = get_scope()
if scope and scope.effect then -- do not track nodes with no effect
push_child(node, scope)
end
end
local function create_node<T>(owner: false | Node<any>, effect: false | (T) -> T, value: T): Node<T>
local node: Node<T> = {
cache = value,
effect = effect,
cleanups = false,
context = false,
owner = owner,
owned = false,
parents = {},
}
if owner then
if owner.owned then
table.insert(owner.owned, node)
else
owner.owned = { node }
end
end
return node
end
local function create_source_node<T>(value: T): SourceNode<T>
return { cache = value }
end
local function get_children<T>(node: Node<T>): { Node<unknown> }
return { unpack(node) } :: { Node<any> }
end
local function set_context<T>(node: Node<T>, key: number, value: unknown)
if node.context then
node.context[key] = value
else
node.context = { [key] = value }
end
end
return table.freeze {
push_scope = push_scope,
pop_scope = pop_scope,
evaluate_node = evaluate_node,
get_scope = get_scope,
assert_stable_scope = assert_stable_scope,
push_cleanup = push_cleanup,
destroy = destroy,
flush_cleanups = flush_cleanups,
push_scope_as_child_of = push_scope_as_child_of,
update_descendants = update_descendants,
push_child = push_child,
create_node = create_node,
create_source_node = create_source_node,
get_children = get_children,
flush_update_queue = flush_update_queue,
get_update_queue_length = get_update_queue_length,
set_context = set_context,
scopes = scopes,
q = update_queue
}
| 2,028 |
centau/vide | centau-vide-7deae9c/src/implicit_effect.luau | local graph = require "./graph"
type Node<T> = graph.Node<T>
local create_node = graph.create_node
local assert_stable_scope = graph.assert_stable_scope
local get_scope = graph.get_scope
local evaluate_node = graph.evaluate_node
local push_cleanup = graph.push_cleanup
local function update_property_effect(p: {
instance: Instance,
property: string,
source: () -> unknown
})
(p.instance :: any)[p.property] = p.source()
return p
end
local function update_parent_effect(p: {
instance: Instance,
source: () -> Instance
})
p.instance.Parent = p.source()
return p
end
-- todo: investigate if "count" method used in indexes() and values() can improve performance here
local function update_children_effect(p: {
instance: Instance,
cur_children_set: { [Instance]: true },
new_children_set: { [Instance]: true },
source: () -> Instance | { Instance }
})
local cur_children_set: { [Instance]: true } = p.cur_children_set -- cache of all children parented before update
local new_children_set: { [Instance]: true } = p.new_children_set -- cache of all children parented after update
local new_children = p.source() -- all (and only) children that should be parented after this update
local function process_child(child: Instance | { Instance })
if type(child) == "userdata" then
if new_children_set[child] then return end -- stops redundant reparenting
new_children_set[child] = true -- record child set from this update
if not cur_children_set[child] then
child.Parent = p.instance -- if child wasn't already parented then parent it
else
cur_children_set[child] = nil -- remove child from cache if it was already in cache
end
elseif type(child) == "table" then
for _, child in child do
process_child(child)
end
elseif type(child) == "function" then
local node = create_node(assert(get_scope()), update_children_effect, {
instance = p.instance,
cur_children_set = {},
new_children_set = {},
source = child
})
evaluate_node(node)
push_cleanup(assert(get_scope()), function()
for child in node.cache.cur_children_set do
child.Parent = nil
end
end)
end
end
process_child(new_children)
for child in cur_children_set do
child.Parent = nil -- unparent all children that weren't in the new children set
end
table.clear(cur_children_set) -- clear cache, preserve capacity
p.cur_children_set, p.new_children_set = new_children_set, cur_children_set
return p
end
return {
property = function(instance, property, source)
local node = create_node(assert_stable_scope(), update_property_effect, {
instance = instance,
property = property,
source = source
})
evaluate_node(node)
return node
end,
parent = function(instance, parent)
local node = create_node(assert_stable_scope(), update_parent_effect, {
instance = instance,
source = parent
})
evaluate_node(node)
return node
end,
children = function(instance, children)
local node = create_node(assert_stable_scope(), update_children_effect, {
instance = instance,
cur_children_set = {},
new_children_set = {},
source = children
})
evaluate_node(node)
push_cleanup(assert_stable_scope(), function()
for child in node.cache.cur_children_set do
child.Parent = nil
end
end)
return node
end
}
| 794 |
centau/vide | centau-vide-7deae9c/src/indexes.luau | local flags = require "./flags"
local branch = require "./branch"
local source = require "./source"
local effect = require "./effect"
local timeout = require "./timeout" ()
type Array<T> = { T }
type Map<K, V> = { [K]: V }
type Source<T> = () -> T
local function indexes<K, V, Obj>(
input: Source<Map<K, V>>,
component: (Source<V>, K, Source<boolean>) -> (Obj, ...number)
): Source<Array<Obj>>
local update_count = 0
local scopes = {} :: Map<K, {
destroy: () -> (),
object: Obj,
value: V?,
value_source: (V?) -> V,
count: number,
delay: number,
present: (boolean?) -> boolean,
timeout: { cancel: boolean }?,
}>
local output = source({} :: Array<Obj>)
local function update_output()
local objects = table.create(4)
for _, scope in scopes do
table.insert(objects, scope.object)
end
output(objects)
end
effect(function()
local data = input()
local count = update_count
update_count += 1
local children_need_update = false -- set to true if a scope is created or destroyed
-- create or update scopes
for i, v in data do
local scope = scopes[i]
if scope == nil then -- create new scope and create component
local value_source = source(v)
local present = source(false)
local delay = nil :: number?
local destroy, object = branch(function()
local object, t = component(value_source, i, present)
delay = t
return object
end)
present(true)
children_need_update = true
scopes[i] = {
destroy = destroy,
object = object,
value = v,
value_source = value_source,
count = count,
delay = delay or 0,
present = present,
timeout = nil,
}
else -- update scope
scope.count = count
if scope.value ~= v then
if scope.timeout then -- index is in input table again; cancel destruction
scope.timeout.cancel = true
scope.timeout = nil
scope.present(true)
end
scope.value = v
scope.value_source(v)
end
end
end
-- destroy scopes
for i, scope in scopes do
if scope.count < count then -- if count is not latest then index is no longer in the input table
scope.present(false)
if scope.delay == 0 then
scope.destroy()
scopes[i] = nil
children_need_update = true
else
scope.value = nil -- set to nil for the `scope.value ~= v` check
if scope.timeout == nil then
scope.timeout = timeout(scope.delay, function() -- todo: possible redundant updates
scope.destroy()
scopes[i] = nil
update_output()
end)
end
end
end
end
if children_need_update then
update_output()
end
end)
return output
end
return indexes
| 690 |
centau/vide | centau-vide-7deae9c/src/init.luau | assert(game, "when using vide outside of Roblox, require lib.luau instead")
local vide = require(script.lib)
export type source<T> = vide.source<T>
export type Source<T> = vide.Source<T>
export type context<T> = vide.context<T>
export type Context<T> = vide.Context<T>
return vide
| 68 |
centau/vide | centau-vide-7deae9c/src/lib.luau | local version = { major = 0, minor = 4, patch = 0 }
local root = require "./root"
local branch = require "./branch"
local mount = require "./mount"
local create = require "./create"
local apply = require "./apply"
local source = require "./source"
local effect = require "./effect"
local derive = require "./derive"
local cleanup = require "./cleanup"
local untrack = require "./untrack"
local read = require "./read"
local batch = require "./batch"
local context = require "./context"
local switch = require "./switch"
local show = require "./show"
local indexes = require "./indexes"
local values = require "./values"
local spring, update_springs = require "./spring"()
local action = require "./action"()
local changed = require "./changed"
local timeout, update_timeouts = require "./timeout"()
local flags = require "./flags"
export type Source<T> = source.Source<T>
export type source<T> = Source<T>
export type Context<T> = context.Context<T>
export type context<T> = Context<T>
local function step(dt: number)
if game then debug.profilebegin("VIDE STEP") end
if game then debug.profilebegin("VIDE SPRING") end
update_springs(dt)
if game then debug.profileend() end
if game then debug.profilebegin("VIDE SCHEDULER") end
update_timeouts(dt)
if game then debug.profileend() end
if game then debug.profileend() end
end
local stepped = game and game:GetService("RunService").Heartbeat:Connect(function(dt: number)
task.defer(step, dt)
end)
local vide = {
version = version,
-- core
root = root,
--branch = branch,
mount = mount,
create = create,
source = source,
effect = effect,
derive = derive,
switch = switch,
show = show,
indexes = indexes,
values = values,
-- util
cleanup = cleanup,
untrack = untrack,
read = read,
batch = batch,
context = context,
-- animations
spring = spring,
-- actions
action = action,
changed = changed,
-- flags
strict = (nil :: any) :: boolean,
defaults = (nil :: any) :: boolean,
defer_nested_properties = (nil :: any) :: boolean,
-- temporary
apply = function(instance: Instance)
return function(props: { [any]: any })
apply(instance, props)
return instance
end
end,
-- runtime
step = function(dt: number)
if stepped then
stepped:Disconnect()
stepped = nil
end
step(dt)
end
}
setmetatable(vide :: any, {
__index = function(_, index: unknown): ()
if flags[index] == nil then
error(`{tostring(index)} is not a valid member of vide`, 0)
else
return flags[index]
end
end,
__newindex = function(_, index: unknown, value: unknown)
if flags[index] == nil then
error(`{tostring(index)} is not a valid member of vide, 0`)
else
flags[index] = value
end
end
})
return vide
| 715 |
centau/vide | centau-vide-7deae9c/src/mount.luau | local root = require "./root"
local apply = require "./apply"
local function mount<T>(component: () -> T, target: Instance?): () -> ()
return root(function()
local result = component()
if target then apply(target, { result }) end
end)
end
return mount :: (<T>(component: () -> T, target: Instance) -> () -> ()) & ((component: () -> ()) -> () -> ())
| 91 |
centau/vide | centau-vide-7deae9c/src/read.luau | local function read<T>(value: T | () -> T): T
return if type(value) == "function" then value() else value
end
return read
| 36 |
centau/vide | centau-vide-7deae9c/src/root.luau | local graph = require "./graph"
type Node<T> = graph.Node<T>
local create_node = graph.create_node
local push_scope = graph.push_scope
local pop_scope = graph.pop_scope
local destroy = graph.destroy
local refs = {}
local function root<T...>(fn: (destroy: () -> ()) -> T...): (() -> (), T...)
local node = create_node(false, false, false)
refs[node] = true -- prevent gc of root node
local destroy = function()
if not refs[node] then error "root already destroyed" end
refs[node] = nil
destroy(node)
end
push_scope(node)
local result = { xpcall(fn, debug.traceback, destroy) }
pop_scope()
if not result[1] then
destroy()
error(`error while running root():\n\n{result[2]}`, 0)
end
return destroy, unpack(result :: any, 2)
end
return root :: <T...>(fn: (destroy: () -> ()) -> T...) -> (() -> (), T...)
| 232 |
centau/vide | centau-vide-7deae9c/src/show.luau | local source = require "./source"
local derive = require "./derive"
local effect = require "./effect"
local untrack = require "./untrack"
local switch = require "./switch"
type Array<T> = { T }
type Source<T> = () -> T
local function show<T, Obj>(
input: Source<T?>,
component: (Source<T>, Source<boolean>) -> (Obj, ...number),
fallback: ((Source<boolean>) -> (Obj, ...number))?
): Source<nil | Obj | Array<Obj>>
local filtered_input = source()
effect(function()
local v = input()
if v then
filtered_input(v)
end
end)
local input_is_truthy = derive(function()
return not not input()
end)
return switch(input_is_truthy) {
[true] = function(present)
return component(filtered_input, present)
end,
[false] = fallback
}
end
return show
| 207 |
centau/vide | centau-vide-7deae9c/src/source.luau | local graph = require "./graph"
type Node<T> = graph.Node<T>
local create_source_node = graph.create_source_node
local push_scope_as_child_of = graph.push_scope_as_child_of
local update_descendants = graph.update_descendants
export type Source<T> = (() -> T) & ((value: T) -> T)
local function source<T>(initial_value: T): Source<T>
local node = create_source_node(initial_value)
local function update_source(...): T
if select("#", ...) == 0 then -- no args were given
push_scope_as_child_of(node)
return node.cache
end
local v = ... :: T
if node.cache == v and (type(v) ~= "table" or table.isfrozen(v)) then
return v
end
node.cache = v
update_descendants(node)
return v
end
return update_source
end
return source :: (<T>(initial_value: T) -> Source<T>) & (<T>() -> Source<T>)
| 221 |
centau/vide | centau-vide-7deae9c/src/switch.luau | local branch = require "./branch"
local source = require "./source"
local effect = require "./effect"
local timeout = require "./timeout" ()
type Array<T> = { T }
type Map<K, V> = { [K]: V }
type Source<T> = () -> T
type Component<T> = (Source<boolean>) -> (T, ...number)
local function switch_map<K, Obj>(
input: Source<K>,
map: Map<K, Component<Obj>>
): Source<nil | Obj | Array<Obj>>
local scopes = {} :: Map<K, {
destroy: () -> (),
object: Obj,
delay: number,
present: (boolean?) -> boolean,
timeout: { cancel: boolean }?
}>
local output = source(nil :: nil | Obj | Array<Obj>)
local function update_output()
local objects = {}
for _, scope in scopes do
table.insert(objects, scope.object)
end
output(
if objects[2] then objects
elseif objects[1] then objects[1]
else nil
)
end
effect(function()
local key: K? = input()
-- destroy (or queue destroy) all scopes not associated with the input key
for k, scope in scopes do
if k == key then continue end
scope.present(false)
if scope.delay == 0 then
scope.destroy()
scopes[k] = nil
else
if scope.timeout == nil then
scope.timeout = timeout(scope.delay, function()
scope.destroy()
scopes[k] = nil
update_output()
end)
end
end
end
-- create new scope or abort destruction of existing scope if key exists
if key ~= nil then
local scope = scopes[key]
if scope then
scope.present(true)
if scope.timeout then
scope.timeout.cancel = true
scope.timeout = nil
end
else
local component = map[key]
if component ~= nil then
if type(component) ~= "function" then
error("map must map a value to a function", 0)
end
local present = source(false)
local delay = nil :: number?
local destroy, object = branch(function()
local object, t = component(present)
delay = t
return object
end)
present(true)
scopes[key] = {
destroy = destroy,
object = object,
delay = delay or 0,
present = present,
timeout = nil
}
end
end
end
update_output()
end)
return output
end
local function switch<K, Obj>(input: Source<K>): (map: Map<K, Component<Obj>>) -> Source<nil | Obj | Array<Obj>>
return function(map)
return switch_map(input, map)
end
end
return switch
| 624 |
centau/vide | centau-vide-7deae9c/src/timeout.luau | local queue = {} :: {
{ t: number, fn: () -> (), cancel: boolean }
}
local function timeout(t: number, fn: () -> ())
local handle = { t = t, fn = fn, cancel = false }
table.insert(queue, handle)
return handle
end
local function update_timeouts(dt: number)
for i = #queue, 1, -1 do
local handle = queue[i]
handle.t -= dt
if handle.cancel or handle.t <= 0 then
queue[i] = queue[#queue]
queue[#queue] = nil
if not handle.cancel then
handle.fn()
end
end
end
end
return function() return timeout, update_timeouts end
| 162 |
centau/vide | centau-vide-7deae9c/src/untrack.luau | local graph = require "./graph"
type Node<T> = graph.Node<T>
local get_scope = graph.get_scope
local function untrack<T>(source: () -> T): T
local scope = get_scope()
if scope then
-- sources are only tracked if the node in scope has an effect
local effect = scope.effect
scope.effect = false
local ok, result = xpcall(source, debug.traceback)
scope.effect = effect :: () -> ()
if not ok then error(result, 0) end
return result :: T
else
return source()
end
end
return untrack :: ( <T>(fn: () -> T) -> T ) & ( (fn: () -> ()) -> () )
| 162 |
centau/vide | centau-vide-7deae9c/src/values.luau | local flags = require "./flags"
local branch = require "./branch"
local source = require "./source"
local effect = require "./effect"
local timeout = require "./timeout" ()
type Array<T> = { T }
type Map<K, V> = { [K]: V }
type Source<T> = () -> T
local function values<K, V, Obj>(
input: Source<Map<K, V>>,
component: (V, Source<K>, Source<boolean>) -> (Obj, ...number)
): Source<Array<Obj>>
local update_count = 0
local scopes = {} :: Map<V, {
destroy: () -> (),
object: Obj,
index: K?,
index_source: (K?) -> K,
count: number,
delay: number,
present: (boolean?) -> boolean,
timeout: { cancel: boolean }?,
}>
local output = source({} :: Array<Obj>)
local function update_output()
local objects = table.create(4)
for _, scope in scopes do
table.insert(objects, scope.object)
end
output(objects)
end
effect(function()
local data = input()
local count = update_count
update_count += 1
local children_need_update = false -- set to true if a scope is created or destroyed
if flags.strict then -- check for duplicate values
local map = {}
for _, v in data do
if map[v] then
error("table source passed to `values()` contains duplicate values", 0)
end
map[v] = true
end
end
-- create or update scopes
for i, v in data do
local scope = scopes[v]
if scope == nil then -- create new scope and create component
local index_source = source(i)
local present = source(false)
local delay = nil :: number?
local destroy, object = branch(function()
local object, t = component(v, index_source, present)
delay = t
return object
end)
present(true)
children_need_update = true
scopes[v] = {
destroy = destroy,
object = object,
index = i,
index_source = index_source,
count = count,
delay = delay or 0,
present = present,
timeout = nil,
}
else -- update scope
scope.count = count
if scope.index ~= i then
if scope.timeout then -- value is in input table again; cancel destruction
scope.timeout.cancel = true
scope.timeout = nil
scope.present(true)
end
scope.index = i
scope.index_source(i)
end
end
end
-- destroy scopes
for v, scope in scopes do
if scope.count < count then -- if count is not latest then value is no longer in the input table
scope.present(false)
if scope.delay == 0 then
scope.destroy()
scopes[v] = nil
children_need_update = true
else
scope.index = nil -- set to nil for the `scope.index ~= i` check
if scope.timeout == nil then
scope.timeout = timeout(scope.delay, function() -- todo: possible redundant updates
scope.destroy()
scopes[v] = nil
update_output()
end)
end
end
end
end
if children_need_update then
update_output()
end
end)
return output
end
return values
| 754 |
Sleitnick/Knit | Sleitnick-Knit-bb1ecf3/publish.luau | -- Remodel Publish script
local KNIT_ASSET_ID = "5530714855"
print("Loading Knit")
local place = remodel.readPlaceFile("Knit.rbxl")
local Packages = place.ReplicatedStorage.Packages
Packages.Knit.Packages:Destroy()
print("Writing Knit module to model file...")
remodel.writeModelFile("Knit.rbxm", Packages)
print("Knit model written")
print("Publishing Knit module to Roblox...")
remodel.writeExistingModelAsset(Packages, KNIT_ASSET_ID)
print("Knit asset published")
| 122 |
Sleitnick/Knit | Sleitnick-Knit-bb1ecf3/src/init.luau | local RunService = game:GetService("RunService")
if RunService:IsServer() then
return require(script.KnitServer)
else
local KnitServer = script:FindFirstChild("KnitServer")
if KnitServer and RunService:IsRunning() then
KnitServer:Destroy()
end
return require(script.KnitClient)
end
| 73 |
littensy/charm | littensy-charm-d0b7cff/packages/charm-sync/src/client.luau | local Charm = require(script.Parent.Parent.Charm)
local patch = require(script.Parent.patch)
local types = require(script.Parent.types)
type AtomMap = types.AtomMap
type SyncPayload = types.SyncPayload
type ClientOptions = {
--[=[
The atoms to synchronize with the server.
]=]
atoms: AtomMap,
--[=[
Whether to ignore patches sent before the client has been hydrated.
Default is `true`.
]=]
ignoreUnhydrated: boolean?,
}
type ClientSyncer = {
--[=[
Applies a patch or initializes the state of the atoms with the given
payload from the server.
@param ...payloads The patches or hydration payloads to apply.
]=]
sync: (self: ClientSyncer, ...SyncPayload) -> (),
}
--[=[
Creates a `ClientSyncer` object that receives patches from the server and
applies them to the local state.
@param options The atoms to synchronize with the server.
@return A `ClientSyncer` object.
]=]
local function client(options: ClientOptions): ClientSyncer
local atoms = options.atoms
local ignoreUnhydrated = options.ignoreUnhydrated ~= false
local self = {} :: ClientSyncer
local hydrated = false
local function hydrate(state: { [string | number]: any })
hydrated = true
for key, value in next, state do
local atom = atoms[key]
atom(value)
end
end
local function apply(data: { [string | number]: any })
local target = {}
for key, atom in next, atoms do
target[key] = atom()
end
target = patch.apply(target, data)
for key, atom in next, atoms do
atom(target[key])
end
end
function self:sync(...)
for index = 1, select("#", ...) do
local payload: SyncPayload = select(index, ...)
Charm.batch(function()
if payload.type == "init" then
hydrate(payload.data)
elseif not ignoreUnhydrated or hydrated then
apply(payload.data)
end
end)
end
end
return self
end
return client
| 478 |
littensy/charm | littensy-charm-d0b7cff/packages/charm-sync/src/flatten.luau | local types = require(script.Parent.types)
type AtomMap = types.AtomMap
type NestedAtomMap = {
[string]: NestedAtomMap | () -> (),
}
local function flatten(atoms: NestedAtomMap): AtomMap
local result: AtomMap = {}
local function visit(node: NestedAtomMap, path: string)
for key, value in node do
local location = if path == "" then key else path .. "/" .. key
if type(value) == "table" then
visit(value, location)
else
result[location] = value
end
end
end
visit(atoms, "")
return result
end
return flatten
| 144 |
littensy/charm | littensy-charm-d0b7cff/packages/charm-sync/src/init.luau | local client = require(script.client)
local flatten = require(script.flatten)
local patch = require(script.patch)
local server = require(script.server)
local types = require(script.types)
export type SyncPayload = types.SyncPayload
--[=[
Synchronizes state between the client and server. The server sends patches
to the client, which applies them to its local state.
]=]
return {
client = client,
server = server,
flatten = flatten,
isNone = patch.isNone,
}
| 99 |
littensy/charm | littensy-charm-d0b7cff/packages/charm-sync/src/interval.luau | local RunService = game:GetService("RunService")
--[=[
Schedules a function to be called at a fixed interval of `seconds`.
@param callback The function to call.
@param seconds The interval in seconds.
@return A function that cancels the interval.
]=]
local function interval(callback: () -> (), seconds: number): () -> ()
if seconds < 0 then
return function() end
end
local clock = 0
local connection = RunService.Heartbeat:Connect(function(delta)
clock += delta
if clock >= seconds then
clock = 0
callback()
end
end)
return function()
connection:Disconnect()
end
end
return interval
| 147 |
littensy/charm | littensy-charm-d0b7cff/packages/charm-sync/src/patch.luau | local validate = require(script.Parent.validate)
local __DEV__ = _G.__DEV__
--[=[
A special symbol that denotes the absence of a value. Used to represent
deleted values in patches.
]=]
local None = { __none = "__none" }
local function isNone(value: any): boolean
return type(value) == "table" and value.__none == "__none"
end
--[=[
JSON serialization can drop the last values of a sparse array. For example,
`{ [1] = 1, [3] = 3 }` becomes `[1]` in some cases. Ambiguity in the
serialization of sparse arrays can be resolved by converting them to
dictionaries with string keys.
The `apply` function will convert these dictionaries back into arrays as
long as the target array is not sparse. This function ensures that the diff
function produces a patch that can be correctly applied.
]=]
local function stringifySparseArray(object: { any }): { [string | number]: any }
local maxn = table.maxn(object)
if maxn == 0 or maxn == #object then
-- The object is either not an array or a dense array
return object
end
local dictionary = {}
for index, value in next, object do
dictionary[tostring(index)] = value
end
return dictionary
end
--[=[
Compares two states and returns a patch that can be applied to the previous
state to produce the next state.
@param prevState The previous state.
@param nextState The next state.
@param serialize Whether to convert sparse arrays into dictionaries. Defaults to `true`.
@returns A patch that can be applied to the previous state.
]=]
local function diff(prevState: { [any]: any }, nextState: { [any]: any }, serialize: boolean?)
serialize = serialize ~= false
local patches = table.clone(nextState)
for key, previous in next, prevState do
local current = nextState[key]
if previous == current then
patches[key] = nil
elseif current == nil then
patches[key] = None
elseif type(previous) == "table" and type(current) == "table" then
patches[key] = diff(previous, current, serialize)
end
end
-- Coerce sparse array patches into dictionaries
if serialize and (prevState[1] ~= nil or nextState[1] ~= nil) then
patches = stringifySparseArray(patches)
end
if serialize and __DEV__ then
for key, value in next, patches do
validate(value, key)
end
end
return patches
end
--[=[
Applies a patch to a state and returns the next state.
@param state The current state.
@param patches The patches to apply.
@returns The next state.
]=]
local function apply(state: any, patches: any): any
if type(patches) == "table" and patches.__none == "__none" then
return nil
elseif type(state) ~= "table" or type(patches) ~= "table" then
return patches
end
local nextState = table.clone(state)
local stateIsArray = state[1] ~= nil
for key, patch in next, patches do
-- Diff-checking an array produces a sparse array, which will not be
-- preserved when converted to JSON. To prevent this, we turn string
-- keys back into numeric keys.
if stateIsArray and type(key) == "string" then
key = tonumber(key) or key
end
nextState[key] = apply(nextState[key], patch)
end
return nextState
end
return {
isNone = isNone,
diff = diff,
apply = apply,
}
| 799 |
littensy/charm | littensy-charm-d0b7cff/packages/charm-sync/src/server.luau | local Players = game:GetService("Players")
local Charm = require(script.Parent.Parent.Charm)
local interval = require(script.Parent.interval)
local patch = require(script.Parent.patch)
local types = require(script.Parent.types)
type AtomMap = types.AtomMap
type SyncPayload = types.SyncPayload
type ServerOptions = {
--[=[
The atoms to synchronize with the client.
]=]
atoms: AtomMap,
--[=[
The interval at which to send patches to the client, in seconds.
Defaults to `0` (patches are sent up to once per frame). Set to a
negative value to disable automatic syncing.
]=]
interval: number?,
--[=[
Whether the history of state changes since the client's last update
should be preserved. This is useful for values that change multiple times
per frame, where each individual change is important. Defaults to `false`.
]=]
preserveHistory: boolean?,
--[=[
When `true`, Charm will apply validation and serialize unsafe arrays
to address remote event argument limitations. Defaults to `true`.
This option should be disabled if your network library uses a custom
serialization method (i.e. Zap, ByteNet) to prevent interference.
]=]
autoSerialize: boolean?,
}
type ServerSyncer = {
--[=[
Sets up a subscription to each atom that schedules a patch to be sent to
the client whenever the state changes. When a change occurs, the `callback`
is called with the player and the payload to send.
Note that the `payload` object should not be mutated. If you need to
modify the payload, apply the changes to a copy of the object.
@param callback The function to call when the state changes.
@return A cleanup function that unsubscribes all listeners.
]=]
connect: (self: ServerSyncer, callback: (player: Player, ...SyncPayload) -> ()) -> () -> (),
--[=[
Hydrates the client's state with the server's state. This should be
called when a player joins the game and requires the server's state.
@param player The player to hydrate.
]=]
hydrate: (self: ServerSyncer, player: Player) -> (),
--[=[
@deprecated For internal use only.
]=]
_sendPatch: (self: ServerSyncer, player: Player) -> (),
}
--[=[
Creates a `ServerSyncer` object that sends patches to the client and
hydrates the client's state.
@param options The atoms to synchronize with the client.
@return A `ServerSyncer` object.
]=]
local function server(options: ServerOptions): ServerSyncer
local atoms = options.atoms
local autoSerialize = options.autoSerialize ~= false
local preserveHistory = options.preserveHistory
local syncRate = options.interval or 0
local self = {} :: ServerSyncer
local sync: (player: Player, payload: SyncPayload) -> ()
local function createSnapshot()
local snapshot = {}
for key, atom in next, atoms do
snapshot[key] = atom()
end
return snapshot
end
-- Send the initial state to a player when they join the server.
function self:hydrate(player)
assert(sync, "connect() must be called before hydrate()")
sync(player, {
type = "init",
data = createSnapshot(),
})
end
-- If the history of state changes should be preserved, keep a list of
-- previous snapshots and diff-check each one from the last.
if preserveHistory then
local snapshots = { createSnapshot() }
local changed = false
function self:connect(callback)
local subscriptions = {}
sync = callback
local function pushSnapshot(key: string | number, current: any, previous: any)
local lastSnapshot = snapshots[#snapshots]
local previousSnapshot = snapshots[#snapshots - 1]
-- Optimize snapshots by updating the most recent snapshot if the
-- previous and current values are the same, since this allows us
-- to group multiple changes into a single snapshot.
if previousSnapshot and previousSnapshot[key] == previous and lastSnapshot[key] == previous then
lastSnapshot[key] = current
else
local nextSnapshot = table.clone(lastSnapshot)
nextSnapshot[key] = current
table.insert(snapshots, nextSnapshot)
end
end
-- Populate the snapshot with the initial state of each atom.
-- Subscribe to each atom and update the state when it changes.
for key, atom in next, atoms do
subscriptions[key] = Charm.subscribe(atom, function(current, previous)
pushSnapshot(key, current, previous)
changed = true
end)
end
local disconnect = interval(function()
if not changed then
return
end
local payloads: { SyncPayload } = {}
local lastSnapshot
for index, snapshot in next, snapshots do
lastSnapshot = snapshot
if index == 1 then
continue
end
table.insert(payloads, {
type = "patch",
data = patch.diff(snapshots[index - 1], snapshot, autoSerialize),
})
end
snapshots = { lastSnapshot }
changed = false
for _, player in next, Players:GetPlayers() do
callback(player, unpack(payloads))
end
end, syncRate)
return function()
disconnect()
for _, unsubscribe in next, subscriptions do
unsubscribe()
end
end
end
function self:_sendPatch(player: Player)
assert(sync, "connect() must be called before _sendPatch()")
if not changed then
return
end
local payloads: { SyncPayload } = {}
for index, snapshot in next, snapshots do
if index == 1 then
continue
end
table.insert(payloads, {
type = "patch",
data = patch.diff(snapshots[index - 1], snapshot, autoSerialize),
})
end
snapshots = { snapshots[#snapshots] }
changed = false
sync(player, unpack(payloads))
end
return self
end
local previousSnapshot = createSnapshot()
local currentSnapshot = table.clone(previousSnapshot)
local changed = false
function self:connect(callback)
local subscriptions = {}
sync = callback
-- Subscribe to each atom and update the state when one changes.
for key, atom in next, atoms do
subscriptions[key] = Charm.subscribe(atom, function(state)
currentSnapshot[key] = state
changed = true
end)
end
local disconnect = interval(function()
if not changed then
return
end
local payload: SyncPayload = {
type = "patch",
data = patch.diff(previousSnapshot, currentSnapshot, autoSerialize),
}
previousSnapshot = table.clone(currentSnapshot)
changed = false
for _, player in next, Players:GetPlayers() do
callback(player, payload)
end
end, syncRate)
return function()
disconnect()
for _, unsubscribe in next, subscriptions do
unsubscribe()
end
end
end
function self:_sendPatch(player)
assert(sync, "connect() must be called before _sendPatch()")
if not changed then
return
end
local payload: SyncPayload = {
type = "patch",
data = patch.diff(previousSnapshot, currentSnapshot, autoSerialize),
}
previousSnapshot = table.clone(currentSnapshot)
changed = false
sync(player, payload)
end
return self
end
return server
| 1,678 |
littensy/charm | littensy-charm-d0b7cff/packages/charm-sync/src/types.luau | local Charm = require(script.Parent.Parent.Charm)
type Atom<T> = Charm.Atom<T>
--[=[
A payload that can be sent from the server to the client to synchronize
state between the two.
]=]
export type SyncPayload = {
type: "init",
data: { [string | number]: any },
} | {
type: "patch",
data: { [string | number]: any },
}
export type AtomMap = {
[string | number]: Atom<any>,
}
return nil
| 102 |
littensy/charm | littensy-charm-d0b7cff/packages/charm-sync/src/validate.luau | local SAFE_KEYS = { string = true, number = true }
local UNSAFE_VALUES = { ["function"] = true, thread = true }
local function isTableUnsafe(object: { [any]: any })
local keyType = nil
local objectSize = 0
-- All keys must have the same type
for key in next, object do
local currentType = type(key)
if not keyType and SAFE_KEYS[currentType] then
keyType = currentType
elseif keyType ~= currentType then
return true
end
objectSize += 1
end
-- If there are more keys than the length of the array, it's an array with
-- non-sequential keys.
if objectSize > #object and keyType == "number" then
return true
end
return false
end
--[=[
Validates a value to ensure it can be synced over a remote event.
@param value The value to validate.
@param key The key of the value in the table.
@error Throws an error if the value cannot be synced.
]=]
local function validate(value: any, key: any)
local typeOfKey = type(key)
local typeOfValue = type(value)
if not SAFE_KEYS[typeOfKey] then
error(`Invalid key type '{typeOfKey}' at key '{key}'`)
elseif UNSAFE_VALUES[typeOfValue] then
error(`Invalid value type '{typeOfValue}' at key '{key}'`)
elseif typeOfValue == "table" then
if getmetatable(value) ~= nil then
error(`Cannot sync tables with metatables! Got {value} at key '{key}'`)
elseif isTableUnsafe(value) then
error(
`Cannot sync tables unsupported by remote events! The value has the key '{key}'.\n\n`
.. "This can be for the following reasons:\n"
.. "1. The object is an array with non-sequential keys\n"
.. "2. The object is a dictionary with mixed key types (e.g. string and number)\n\n"
.. "Read more: https://create.roblox.com/docs/scripting/events/remote#argument-limitations"
)
end
end
if typeOfKey == "number" then
if key == math.huge or key == -math.huge then
error("Cannot sync infinity as key")
elseif key ~= math.floor(key) then
error("Cannot sync non-integer number as key")
end
end
end
return validate
| 546 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/atom.luau | local store = require(script.Parent.store)
local types = require(script.Parent.types)
type Atom<T> = types.Atom<T>
type AtomOptions<T> = types.AtomOptions<T>
--[=[
Creates a new atom with the given state.
@param state The initial state.
@param options Optional configuration.
@return A new atom.
]=]
local function atom<T>(state: T, options: AtomOptions<T>?): Atom<T>
local equals = options and options.equals
local function atom(...)
if select("#", ...) == 0 then
local index = store.capturing.index
if index > 0 then
store.capturing.stack[index][atom] = true
end
return state
end
local nextState = store.peek(..., state)
if state ~= nextState and not (equals and equals(state, nextState)) then
state = nextState
store.notify(atom)
end
return state
end
store.listeners[atom] = setmetatable({}, { __mode = "v" })
return atom
end
return atom
| 227 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/computed.luau | local atom = require(script.Parent.atom)
local store = require(script.Parent.store)
local types = require(script.Parent.types)
type AtomOptions<T> = types.AtomOptions<T>
type Selector<T> = types.Selector<T>
--[=[
Creates a read-only atom that derives its state from one or more atoms.
Used to avoid unnecessary recomputations if multiple listeners depend on
the same atoms.
@param callback The function that produces the state.
@param options Optional configuration.
@return A new read-only atom.
]=]
local function computed<T>(callback: Selector<T>, options: AtomOptions<T>?): Selector<T>
local dependencies, state = store.capture(callback)
local computedAtom = atom(state, options)
local computedRef = setmetatable({ current = computedAtom }, { __mode = "v" })
local function listener()
local computedAtom = computedRef.current
if computedAtom then
store.disconnect(dependencies, listener)
dependencies, state = store.capture(callback)
store.connect(dependencies, listener, computedAtom)
computedAtom(state)
end
end
store.connect(dependencies, listener, computedAtom)
return computedAtom
end
return computed
| 245 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/effect.luau | local store = require(script.Parent.store)
type Cleanup = () -> ()
--[=[
Runs the given callback immediately and whenever any atom it depends on
changes. Returns a cleanup function that unsubscribes the callback.
@param callback The function to run.
@return A function that unsubscribes the callback.
]=]
local function effect(callback: (cleanup: Cleanup) -> Cleanup?): Cleanup
local dependencies = {}
local cleanup: Cleanup?
local disconnected = false
local disconnect
local function listener()
if cleanup then
cleanup()
end
store.disconnect(dependencies, listener)
dependencies, cleanup = store.capture(callback, disconnect)
if not disconnected then
store.connect(dependencies, listener)
end
end
function disconnect()
if disconnected then
return
end
disconnected = true
store.disconnect(dependencies, listener)
if cleanup then
cleanup()
end
end
dependencies, cleanup = store.capture(callback, disconnect)
if not disconnected then
store.connect(dependencies, listener)
end
return disconnect
end
return effect :: (callback: ((cleanup: Cleanup) -> ()) | ((cleanup: Cleanup) -> Cleanup?)) -> Cleanup
| 252 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/init.luau | local atom = require(script.atom)
local computed = require(script.computed)
local effect = require(script.effect)
local mapped = require(script.mapped)
local observe = require(script.observe)
local store = require(script.store)
local subscribe = require(script.subscribe)
local types = require(script.types)
export type Atom<State> = types.Atom<State>
export type Selector<State> = types.Selector<State>
export type Molecule<State> = types.Selector<State>
export type SyncPayload = types.SyncPayload
return {
atom = atom,
computed = computed,
effect = effect,
mapped = mapped,
observe = observe,
subscribe = subscribe,
batch = store.batch,
capture = store.capture,
isAtom = store.isAtom,
notify = store.notify,
peek = store.peek,
}
| 164 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/mapped.luau | local atom = require(script.Parent.atom)
local store = require(script.Parent.store)
local subscribe = require(script.Parent.subscribe)
local types = require(script.Parent.types)
type Atom<T> = types.Atom<T>
type Selector<T> = types.Selector<T>
type Map =
(<K0, V0, K1, V1>(fn: Selector<{ [K0]: V0 }>, mapper: (V0, K0) -> (V1?, K1)) -> Selector<{ [K1]: V1 }>)
& (<K0, V0, V1>(fn: Selector<{ [K0]: V0 }>, mapper: (V0, K0) -> V1?) -> Selector<{ [K0]: V1 }>)
& (<K0, V0, K1, V1>(fn: Selector<{ [K0]: V0 }>, mapper: (V0, K0) -> (V1?, K1?)) -> Selector<{ [K1]: V1 }>)
--[=[
Maps each entry in the atom's state to a new key-value pair. If the `mapper`
function returns `undefined`, the entry is omitted from the resulting map.
When the atom changes, the `mapper` is called for each entry in the state
to compute the new state.
@param callback The atom or selector to map.
@param mapper The function that maps each entry.
@return A new atom with the mapped state.
]=]
local function mapped<K0, V0, K1, V1>(callback: Selector<{ [K0]: V0 }>, mapper: (V0, K0) -> (V1?, K1?)): Selector<{ [K1]: V1 }>
local mappedAtom = atom({})
local mappedAtomRef = setmetatable({ current = mappedAtom }, { __mode = "v" })
local prevMappedItems: { [K1]: V1 } = {}
local unsubscribe
local function listener(items: { [K0]: V0 })
local mappedAtom = mappedAtomRef.current
if not mappedAtom then
return unsubscribe()
end
local mappedItems = table.clone(mappedAtom())
local mappedKeys = {}
-- TODO: Only call mapper if the item has changed.
for key, item in next, items do
local newItem, newKey = mapper(item, key)
if newKey == nil then
newKey = key :: any
end
if mappedItems[newKey :: K1] ~= newItem then
mappedItems[newKey :: K1] = newItem :: V1
else
mappedKeys[newKey] = key
end
end
for key in next, prevMappedItems do
if mappedKeys[key] == nil and mappedItems[key] == prevMappedItems[key] then
mappedItems[key] = nil
end
end
prevMappedItems = mappedItems
mappedAtom(mappedItems)
end
unsubscribe = subscribe(callback, listener)
store.peek(function(): ()
listener(callback())
end)
return mappedAtom
end
return mapped :: Map
| 660 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/observe.luau | local store = require(script.Parent.store)
local subscribe = require(script.Parent.subscribe)
local types = require(script.Parent.types)
type Selector<T> = types.Selector<T>
local function noop() end
--[=[
Creates an instance of `factory` for each item in the atom's state, and
cleans up the instance when the item is removed. Returns a cleanup function
that unsubscribes all instances.
@param callback The atom or selector to observe.
@param factory The function that tracks the lifecycle of each item.
@return A function that unsubscribes all instances.
]=]
local function observe<K, V>(callback: Selector<{ [K]: V }>, factory: (value: V, key: K) -> (() -> ())?): () -> ()
local connections: { [K]: () -> () } = {}
local function listener(state: { [K]: V })
for key, disconnect in next, connections do
if state[key] == nil then
connections[key] = nil
disconnect()
end
end
for key, value in next, state do
if not connections[key] then
connections[key] = factory(value, key) or noop
end
end
end
local unsubscribe = subscribe(callback, listener)
store.peek(function(): ()
listener(callback())
end)
return function()
unsubscribe()
for _, disconnect in next, connections do
disconnect()
end
table.clear(connections)
end
end
return observe
| 318 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/store.luau | local types = require(script.Parent.types)
type Atom<T> = types.Atom<T>
type Set<T> = types.Set<T>
type WeakMap<K, V> = types.WeakMap<K, V>
local __DEV__ = _G.__DEV__
local listeners: WeakMap<Atom<any>, WeakMap<() -> (), unknown>> = setmetatable({}, { __mode = "k" })
local batched: Set<() -> ()> = {}
local batching = false
local capturing = {
stack = {} :: { Set<Atom<any>> },
index = 0,
}
--[=[
Calls the given function and returns the result. If the function yields or
throws an error, the thread is closed and an error is thrown. Regardless of
the outcome, the `finally` function is called to clean up any resources.
@param callback The function to run.
@param finally Cleanup logic to run before error handling.
@param ... Arguments to pass to the callback.
@return The result of the callback.
]=]
local function try<T, U...>(callback: (U...) -> T | any, finally: (() -> ())?, ...: U...): T
if __DEV__ then
local thread = coroutine.create(callback)
local success, result = coroutine.resume(thread, ...)
if finally then
finally()
end
if coroutine.status(thread) == "suspended" then
local source, line, name = debug.info(callback, "sln")
coroutine.close(thread)
error(
"Yielding is not allowed in atom functions. Consider wrapping this code in a Promise or task.defer instead."
.. `\nFunction defined at: {source}:{line}`
.. if name == "" then "" else ` function {name}`
)
elseif not success then
local source, line, name = debug.info(callback, "sln")
error(
"An error occurred while running an atom function"
.. `\nFunction defined at: {source}:{line}`
.. (if name == "" then "" else ` function {name}`)
.. `\nError: {result}`
)
end
return result
end
if not finally then
return callback(...)
end
local success, result = pcall(callback, ...)
finally()
assert(success, result)
return result
end
--[=[
Returns whether the given value is an atom.
@param value The value to check.
@return `true` if the value is an atom, otherwise `false`.
]=]
local function isAtom(value: any): boolean
return not not (value and listeners[value])
end
--[=[
Notifies all subscribers of the given atom that the state has changed.
@param atom The atom to notify.
]=]
local function notify(atom: Atom<any>)
if batching then
for listener in next, listeners[atom] do
batched[listener] = true
end
return
end
for listener in next, table.clone(listeners[atom]) do
try(listener)
end
end
--[=[
Returns the result of the function without subscribing to changes. If a
non-function value is provided, it is returned as is.
@param callback The atom or selector to get the state of.
@param args Arguments to pass to the function.
@return The current state.
]=]
local function peek<T, U...>(callback: ((U...) -> T) | T, ...: U...): T
if type(callback) ~= "function" then
return callback
end
if capturing.index == 0 then
return callback(...)
end
capturing.index += 1
capturing.stack[capturing.index] = {}
local result = try(callback, function()
capturing.stack[capturing.index] = nil
capturing.index -= 1
end, ...)
return result
end
--[=[
Captures all atoms that are read during the function call and returns them
along with the result of the function. Useful for tracking dependencies.
@param callback The function to run.
@return A tuple containing the captured atoms and the result of the function.
]=]
local function capture<T, U...>(callback: (U...) -> T, ...: U...): (Set<Atom<any>>, T)
-- If the callback is an atom, return it immediately
if listeners[callback :: any] then
return { [callback :: any] = true }, peek(callback)
end
local dependencies: Set<Atom<any>> = {}
capturing.index += 1
capturing.stack[capturing.index] = dependencies
local result = try(callback, function()
capturing.stack[capturing.index] = nil
capturing.index -= 1
end, ...)
return dependencies, result
end
--[=[
Runs the given function and schedules listeners to be notified only once
after the function has completed. Useful for batching multiple changes.
@param callback The function to run.
]=]
local function batch(callback: () -> ())
if batching then
return callback()
end
batching = true
try(callback, function()
batching = false
end)
for listener in next, batched do
try(listener)
end
table.clear(batched)
end
--[=[
Subscribes the listener to the changes of the given atoms.
@param atoms The atoms to listen to.
@param listener The function to call when the atoms change.
@param ref Optionally bind the lifetime of the listener to a value.
]=]
local function connect(atoms: Set<Atom<any>>, listener: () -> (), ref: unknown?)
for atom in next, atoms do
listeners[atom][listener] = ref or true
end
end
--[=[
Unsubscribes the listener from every atom it was connected to.
@param atoms The atoms to stop listening to.
@param listener The function to stop calling when the atoms change.
]=]
local function disconnect(atoms: Set<Atom<any>>, listener: () -> ())
for atom in next, atoms do
listeners[atom][listener] = nil
end
end
return {
listeners = listeners,
capturing = capturing,
isAtom = isAtom,
notify = notify,
capture = capture,
batch = batch,
peek = peek,
connect = connect,
disconnect = disconnect,
}
| 1,345 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/subscribe.luau | local store = require(script.Parent.store)
local types = require(script.Parent.types)
type Selector<T> = types.Selector<T>
--[=[
Subscribes to changes in the given atom or selector. The callback is
called with the current state and the previous state immediately after a
change occurs.
@param callback The atom or selector to subscribe to.
@param listener The function to call when the state changes.
@return A function that unsubscribes the callback.
]=]
local function subscribe<T>(callback: Selector<T>, listener: (state: T, prev: T) -> ()): () -> ()
local dependencies, state = store.capture(callback)
local disconnected = false
local function handler()
local prevState = state
store.disconnect(dependencies, handler)
dependencies, state = store.capture(callback)
if not disconnected then
store.connect(dependencies, handler)
end
if state ~= prevState then
listener(state, prevState)
end
end
store.connect(dependencies, handler)
return function()
if not disconnected then
disconnected = true
store.disconnect(dependencies, handler)
end
end
end
return subscribe
| 244 |
littensy/charm | littensy-charm-d0b7cff/packages/charm/src/types.luau | export type Set<T> = { [T]: true }
export type WeakMap<K, V> = typeof(setmetatable({} :: { [K]: V }, { __mode = "k" }))
--[=[
A primitive state container that can be read from and written to. When the
state changes, all subscribers are notified.
@param state The next state or a function that produces the next state.
@return The current state, if no arguments are provided.
]=]
export type Atom<T> = (state: (T | (T) -> T)?) -> T
--[=[
A function that depends on one or more atoms and produces a state. Can be
used to derive state from atoms.
@template State The type of the state.
@return The current state.
]=]
export type Selector<T> = () -> T
--[=[
Optional configuration for creating an atom.
]=]
export type AtomOptions<T> = {
--[=[
A function that determines whether the state has changed. By default,
a strict equality check (`===`) is used.
]=]
equals: (prev: T, next: T) -> boolean,
}
--[=[
A payload that can be sent from the server to the client to synchronize
state between the two.
]=]
export type SyncPayload = {
type: "patch" | "init",
data: { [any]: any },
}
return nil
| 291 |
littensy/charm | littensy-charm-d0b7cff/packages/react/src/init.luau | local Charm = require(script.Parent.Charm)
local React = if script.Parent:FindFirstChild("react")
then require(script.Parent.react) :: never
else require(script.Parent.React)
--[=[
A hook that subscribes to changes in the given atom or selector. The
component is re-rendered whenever the state changes.
If the `dependencies` array is provided, the subscription to the atom or
selector is re-created whenever the dependencies change. Otherwise, the
subscription is created once when the component is mounted.
@param callback The atom or selector to subscribe to.
@param dependencies An array of values that the subscription depends on.
@return The current state.
]=]
local function useAtom<State>(callback: Charm.Selector<State>, dependencies: { any }?): State
local state, setState = React.useState(callback)
React.useEffect(function()
setState(callback())
return Charm.subscribe(callback, setState)
end, dependencies or {})
return state
end
return {
useAtom = useAtom,
}
| 207 |
littensy/charm | littensy-charm-d0b7cff/packages/vide/src/init.luau | local Charm = require(script.Parent.Charm)
local Vide = if script.Parent:FindFirstChild("vide")
then require(script.Parent.vide.src) :: never
else require(script.Parent.Vide)
--[=[
Subscribes to the state of an atom and returns a Vide source.
@param callback The atom or selector to subscribe to.
@return The reactive source.
]=]
local function useAtom<State>(callback: () -> State): () -> State
local state = Vide.source(callback())
local unsubscribe = Charm.subscribe(callback, function(value)
task.spawn(state :: (State) -> State, value)
end)
Vide.cleanup(unsubscribe)
return state
end
return {
useAtom = useAtom,
}
| 145 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/API.lua | local Types = require(script.Parent.Types)
return function(Iris: Types.Iris)
-- basic wrapper for nearly every widget, saves space.
local function wrapper(name)
return function(arguments, states)
return Iris.Internal._Insert(name, arguments, states)
end
end
--[[
----------------------------
[SECTION] Window API
----------------------------
]]
--[=[
@class Window
Windows are the fundamental widget for Iris. Every other widget must be a descendant of a window.
```lua
Iris.Window({ "Example Window" })
Iris.Text({ "This is an example window!" })
Iris.End()
```

If you do not want the code inside a window to run unless it is open then you can use the following:
```lua
local window = Iris.Window({ "Many Widgets Window" })
if window.state.isOpened.value and window.state.isUncollapsed.value then
Iris.Text({ "I will only be created when the window is open." })
end
Iris.End() -- must always call Iris.End(), regardless of whether the window is open or not.
```
]=]
--[=[
@within Window
@prop Window Iris.Window
@tag Widget
@tag HasChildren
@tag HasState
The top-level container for all other widgets to be created within.
Can be moved and resized across the screen. Cannot contain embedded windows.
Menus can be appended to windows creating a menubar.
```lua
hasChildren = true
hasState = true
Arguments = {
Title: string,
NoTitleBar: boolean? = false,
NoBackground: boolean? = false, -- the background behind the widget container.
NoCollapse: boolean? = false,
NoClose: boolean? = false,
NoMove: boolean? = false,
NoScrollbar: boolean? = false, -- the scrollbar if the window is too short for all widgets.
NoResize: boolean? = false,
NoNav: boolean? = false, -- unimplemented.
NoMenu: boolean? = false -- whether the menubar will show if created.
}
Events = {
opened: () -> boolean, -- once when opened.
closed: () -> boolean, -- once when closed.
collapsed: () -> boolean, -- once when collapsed.
uncollapsed: () -> boolean, -- once when uncollapsed.
hovered: () -> boolean -- fires when the mouse hovers over any of the window.
}
States = {
size: State<Vector2>? = Vector2.new(400, 300),
position: State<Vector2>?,
isUncollapsed: State<boolean>? = true,
isOpened: State<boolean>? = true,
scrollDistance: State<number>? -- vertical scroll distance, if too short.
}
```
]=]
Iris.Window = wrapper("Window")
--[=[
@within Iris
@function SetFocusedWindow
@param window Types.Window -- the window to focus.
Sets the focused window to the window provided, which brings it to the front and makes it active.
]=]
Iris.SetFocusedWindow = Iris.Internal.SetFocusedWindow
--[=[
@within Window
@prop Tooltip Iris.Tooltip
@tag Widget
Displays a text label next to the cursor
```lua
Iris.Tooltip({"My custom tooltip"})
```

```lua
hasChildren = false
hasState = false
Arguments = {
Text: string
}
```
]=]
Iris.Tooltip = wrapper("Tooltip")
--[[
---------------------------------
[SECTION] Menu Widget API
---------------------------------
]]
--[=[
@class Menu
Menu API
]=]
--[=[
@within Menu
@prop MenuBar Iris.MenuBar
@tag Widget
@tag HasChildren
Creates a MenuBar for the current window. Must be called directly under a Window and not within a child widget.
:::info
This does not create any menus, just tells the window that we going to add menus within.
:::
```lua
hasChildren = true
hasState = false
```
]=]
Iris.MenuBar = wrapper("MenuBar")
--[=[
@within Menu
@prop Menu Iris.Menu
@tag Widget
@tag HasChildren
@tag HasState
Creates an collapsable menu. If the Menu is created directly under a MenuBar, then the widget will
be placed horizontally below the window title. If the menu Menu is created within another menu, then
it will be placed vertically alongside MenuItems and display an arrow alongside.
The opened menu will be a vertically listed box below or next to the button.
```lua
Iris.Window({"Menu Demo"})
Iris.MenuBar()
Iris.Menu({"Test Menu"})
Iris.Button({"Menu Option 1"})
Iris.Button({"Menu Option 2"})
Iris.End()
Iris.End()
Iris.End()
```

:::info
There are widgets which are designed for being parented to a menu whilst other happens to work. There is nothing
preventing you from adding any widget as a child, but the behaviour is unexplained and not intended.
:::
```lua
hasChildren = true
hasState = true
Arguments = {
Text: string -- menu text.
}
Events = {
clicked: () -> boolean,
opened: () -> boolean, -- once when opened.
closed: () -> boolean, -- once when closed.
hovered: () -> boolean
}
States = {
isOpened: State<boolean>? -- whether the menu is open, including any sub-menus within.
}
```
]=]
Iris.Menu = wrapper("Menu")
--[=[
@within Menu
@prop MenuItem Iris.MenuItem
@tag Widget
Creates a button within a menu. The optional KeyCode and ModiferKey arguments will show the keys next
to the title, but **will not** bind any connection to them. You will need to do this yourself.
```lua
Iris.Window({"MenuToggle Demo"})
Iris.MenuBar()
Iris.MenuToggle({"Menu Item"})
Iris.End()
Iris.End()
```

```lua
hasChildren = false
hasState = false
Arguments = {
Text: string,
KeyCode: Enum.KeyCode? = nil, -- an optional keycode, does not actually connect an event.
ModifierKey: Enum.ModifierKey? = nil -- an optional modifer key for the key code.
}
Events = {
clicked: () -> boolean,
hovered: () -> boolean
}
```
]=]
Iris.MenuItem = wrapper("MenuItem")
--[=[
@within Menu
@prop MenuToggle Iris.MenuToggle
@tag Widget
@tag HasState
Creates a togglable button within a menu. The optional KeyCode and ModiferKey arguments act the same
as the MenuItem. It is not visually the same as a checkbox, but has the same functionality.
```lua
Iris.Window({"MenuToggle Demo"})
Iris.MenuBar()
Iris.MenuToggle({"Menu Toggle"})
Iris.End()
Iris.End()
```

```lua
hasChildren = false
hasState = true
Arguments = {
Text: string,
KeyCode: Enum.KeyCode? = nil, -- an optional keycode, does not actually connect an event.
ModifierKey: Enum.ModifierKey? = nil -- an optional modifer key for the key code.
}
Events = {
checked: () -> boolean, -- once on check.
unchecked: () -> boolean, -- once on uncheck.
hovered: () -> boolean
}
States = {
isChecked: State<boolean>?
}
```
]=]
Iris.MenuToggle = wrapper("MenuToggle")
--[[
-----------------------------------
[SECTION] Format Widget Iris
-----------------------------------
]]
--[=[
@class Format
Format API
]=]
--[=[
@within Format
@prop Separator Iris.Separator
@tag Widget
A vertical or horizonal line, depending on the context, which visually seperates widgets.
```lua
Iris.Window({"Separator Demo"})
Iris.Text({"Some text here!"})
Iris.Separator()
Iris.Text({"This text has been separated!"})
Iris.End()
```

```lua
hasChildren = false
hasState = false
```
]=]
Iris.Separator = wrapper("Separator")
--[=[
@within Format
@prop Indent Iris.Indent
@tag Widget
@tag HasChildren
Indents its child widgets.
```lua
Iris.Window({"Indent Demo"})
Iris.Text({"Unindented text!"})
Iris.Indent()
Iris.Text({"This text has been indented!"})
Iris.End()
Iris.End()
```

```lua
hasChildren = true
hasState = false
Arguments = {
Width: number? = Iris._config.IndentSpacing -- indent width ammount.
}
```
]=]
Iris.Indent = wrapper("Indent")
--[=[
@within Format
@prop SameLine Iris.SameLine
@tag Widget
@tag HasChildren
Positions its children in a row, horizontally.
```lua
Iris.Window({"Same Line Demo"})
Iris.Text({"All of these buttons are on the same line!"})
Iris.SameLine()
Iris.Button({"Button 1"})
Iris.Button({"Button 2"})
Iris.Button({"Button 3"})
Iris.End()
Iris.End()
```

```lua
hasChildren = true
hasState = false
Arguments = {
Width: number? = Iris._config.ItemSpacing.X, -- horizontal spacing between child widgets.
VerticalAlignment: Enum.VerticalAlignment? = Enum.VerticalAlignment.Center -- how widgets vertically to each other.
HorizontalAlignment: Enum.HorizontalAlignment? = Enum.HorizontalAlignment.Center -- how widgets are horizontally.
}
```
]=]
Iris.SameLine = wrapper("SameLine")
--[=[
@within Format
@prop Group Iris.Group
@tag Widget
@tag HasChildren
Layout widget which contains its children as a single group.
```lua
hasChildren = true
hasState = false
```
]=]
Iris.Group = wrapper("Group")
--[[
---------------------------------
[SECTION] Text Widget API
---------------------------------
]]
--[=[
@class Text
Text Widget API
]=]
--[=[
@within Text
@prop Text Iris.Text
@tag Widget
A text label to display the text argument.
The Wrapped argument will make the text wrap around if it is cut off by its parent.
The Color argument will change the color of the text, by default it is defined in the configuration file.
```lua
Iris.Window({"Text Demo"})
Iris.Text({"This is regular text"})
Iris.End()
```

```lua
hasChildren = false
hasState = false
Arguments = {
Text: string,
Wrapped: boolean? = [CONFIG] = false, -- whether the text will wrap around inside the parent container. If not specified, then equal to the config
Color: Color3? = Iris._config.TextColor, -- the colour of the text.
RichText: boolean? = [CONFIG] = false -- enable RichText. If not specified, then equal to the config
}
Events = {
hovered: () -> boolean
}
```
]=]
Iris.Text = wrapper("Text")
--[=[
@within Text
@prop TextWrapped Iris.Text
@tag Widget
@deprecated v2.0.0 -- Use 'Text' with the Wrapped argument or change the config.
An alias for [Iris.Text](Text#Text) with the Wrapped argument set to true, and the text will wrap around if cut off by its parent.
```lua
hasChildren = false
hasState = false
Arguments = {
Text: string,
}
Events = {
hovered: () -> boolean
}
```
]=]
Iris.TextWrapped = function(arguments: Types.WidgetArguments)
arguments[2] = true
return Iris.Internal._Insert("Text", arguments)
end
--[=[
@within Text
@prop TextColored Iris.Text
@tag Widget
@deprecated v2.0.0 -- Use 'Text' with the Color argument or change the config.
An alias for [Iris.Text](Text#Text) with the color set by the Color argument.
```lua
hasChildren = false
hasState = false
Arguments = {
Text: string,
Color: Color3 -- the colour of the text.
}
Events = {
hovered: () -> boolean
}
```
]=]
Iris.TextColored = function(arguments: Types.WidgetArguments)
arguments[3] = arguments[2]
arguments[2] = nil
return Iris.Internal._Insert("Text", arguments)
end
--[=[
@within Text
@prop SeparatorText Iris.SeparatorText
@tag Widget
Similar to [Iris.Separator](Format#Separator) but with a text label to be used as a header
when an [Iris.Tree](Tree#Tree) or [Iris.CollapsingHeader](Tree#CollapsingHeader) is not appropriate.
Visually a full width thin line with a text label clipping out part of the line.
```lua
Iris.Window({"Separator Text Demo"})
Iris.Text({"Regular Text"})
Iris.SeparatorText({"This is a separator with text"})
Iris.Text({"More Regular Text"})
Iris.End()
```

```lua
hasChildren = false
hasState = false
Arguments = {
Text: string
}
```
]=]
Iris.SeparatorText = wrapper("SeparatorText")
--[=[
@within Text
@prop InputText Iris.InputText
@tag Widget
@tag HasState
A field which allows the user to enter text.
```lua
Iris.Window({"Input Text Demo"})
local inputtedText = Iris.State("")
Iris.InputText({"Enter text here:"}, {text = inputtedText})
Iris.Text({"You entered: " .. inputtedText:get()})
Iris.End()
```

```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputText",
TextHint: string? = "", -- a hint to display when the text box is empty.
ReadOnly: boolean? = false,
MultiLine: boolean? = false
}
Events = {
textChanged: () -> boolean, -- whenever the textbox looses focus and a change was made.
hovered: () -> boolean
}
States = {
text: State<string>?
}
```
]=]
Iris.InputText = wrapper("InputText")
--[[
----------------------------------
[SECTION] Basic Widget API
----------------------------------
]]
--[=[
@class Basic
Basic Widget API
]=]
--[=[
@within Basic
@prop Button Iris.Button
@tag Widget
A clickable button the size of the text with padding. Can listen to the `clicked()` event to determine if it was pressed.
```lua
hasChildren = false
hasState = false
Arguments = {
Text: string,
Size: UDim2? = UDim2.fromOffset(0, 0),
}
Events = {
clicked: () -> boolean,
rightClicked: () -> boolean,
doubleClicked: () -> boolean,
ctrlClicked: () -> boolean, -- when the control key is down and clicked.
hovered: () -> boolean
}
```
]=]
Iris.Button = wrapper("Button")
--[=[
@within Basic
@prop SmallButton Iris.SmallButton
@tag Widget
A smaller clickable button, the same as a [Iris.Button](Basic#Button) but without padding. Can listen to the `clicked()` event to determine if it was pressed.
```lua
hasChildren = false
hasState = false
Arguments = {
Text: string,
Size: UDim2? = 0,
}
Events = {
clicked: () -> boolean,
rightClicked: () -> boolean,
doubleClicked: () -> boolean,
ctrlClicked: () -> boolean, -- when the control key is down and clicked.
hovered: () -> boolean
}
```
]=]
Iris.SmallButton = wrapper("SmallButton")
--[=[
@within Basic
@prop Checkbox Iris.Checkbox
@tag Widget
@tag HasState
A checkable box with a visual tick to represent a boolean true or false state.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string
}
Events = {
checked: () -> boolean, -- once when checked.
unchecked: () -> boolean, -- once when unchecked.
hovered: () -> boolean
}
State = {
isChecked = State<boolean>? -- whether the box is checked.
}
```
]=]
Iris.Checkbox = wrapper("Checkbox")
--[=[
@within Basic
@prop RadioButton Iris.RadioButton
@tag Widget
@tag HasState
A circular selectable button, changing the state to its index argument. Used in conjunction with multiple other RadioButtons sharing the same state to represent one value from multiple options.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string,
Index: any -- the state object is set to when clicked.
}
Events = {
selected: () -> boolean,
unselected: () -> boolean,
active: () -> boolean, -- if the state index equals the RadioButton's index.
hovered: () -> boolean
}
State = {
index = State<any>? -- the state set by the index of a RadioButton.
}
```
]=]
Iris.RadioButton = wrapper("RadioButton")
--[[
----------------------------------
[SECTION] Image Widget API
----------------------------------
]]
--[=[
@class Image
Image Widget API
Provides two widgets for Images and ImageButtons, which provide the same control as a an ImageLabel instance.
]=]
--[=[
@within Image
@prop Image Iris.Image
@tag Widget
An image widget for displaying an image given its texture ID and a size. The widget also supports Rect Offset and Size allowing cropping of the image and the rest of the ScaleType properties.
Some of the arguments are only used depending on the ScaleType property, such as TileSize or Slice which will be ignored.
```lua
hasChildren = false
hasState = false
Arguments = {
Image: string, -- the texture asset id
Size: UDim2,
Rect: Rect? = Rect.new(), -- Rect structure which is used to determine the offset or size. An empty, zeroed rect is equivalent to nil
ScaleType: Enum.ScaleType? = Enum.ScaleType.Stretch, -- used to determine whether the TileSize, SliceCenter and SliceScale arguments are used
ResampleMode: Enum.ResampleMode? = Enum.ResampleMode.Default,
TileSize: UDim2? = UDim2.fromScale(1, 1), -- only used if the ScaleType is set to Tile
SliceCenter: Rect? = Rect.new(), -- only used if the ScaleType is set to Slice
SliceScale: number? = 1 -- only used if the ScaleType is set to Slice
}
Events = {
hovered: () -> boolean
}
```
]=]
Iris.Image = wrapper("Image")
--[=[
@within Image
@prop ImageButton Iris.ImageButton
@tag Widget
An image button widget for a button as an image given its texture ID and a size. The widget also supports Rect Offset and Size allowing cropping of the image, and the rest of the ScaleType properties.
Supports all of the events of a regular button.
```lua
hasChildren = false
hasState = false
Arguments = {
Image: string, -- the texture asset id
Size: UDim2,
Rect: Rect? = Rect.new(), -- Rect structure which is used to determine the offset or size. An empty, zeroed rect is equivalent to nil
ScaleType: Enum.ScaleType? = Enum.ScaleType.Stretch, -- used to determine whether the TileSize, SliceCenter and SliceScale arguments are used
ResampleMode: Enum.ResampleMode? = Enum.ResampleMode.Default,
TileSize: UDim2? = UDim2.fromScale(1, 1), -- only used if the ScaleType is set to Tile
SliceCenter: Rect? = Rect.new(), -- only used if the ScaleType is set to Slice
SliceScale: number? = 1 -- only used if the ScaleType is set to Slice
}
Events = {
clicked: () -> boolean,
rightClicked: () -> boolean,
doubleClicked: () -> boolean,
ctrlClicked: () -> boolean, -- when the control key is down and clicked.
hovered: () -> boolean
}
```
]=]
Iris.ImageButton = wrapper("ImageButton")
--[[
---------------------------------
[SECTION] Tree Widget API
---------------------------------
]]
--[=[
@class Tree
Tree Widget API
]=]
--[=[
@within Tree
@prop Tree Iris.Tree
@tag Widget
@tag HasChildren
@tag HasState
A collapsable container for other widgets, to organise and hide widgets when not needed. The state determines whether the child widgets are visible or not. Clicking on the widget will collapse or uncollapse it.
```lua
hasChildren: true
hasState: true
Arguments = {
Text: string,
SpanAvailWidth: boolean? = false, -- the tree title will fill all horizontal space to the end its parent container.
NoIndent: boolean? = false, -- the child widgets will not be indented underneath.
DefaultOpen: boolean? = false -- initially opens the tree if no state is provided
}
Events = {
collapsed: () -> boolean,
uncollapsed: () -> boolean,
hovered: () -> boolean
}
State = {
isUncollapsed: State<boolean>? -- whether the widget is collapsed.
}
```
]=]
Iris.Tree = wrapper("Tree")
--[=[
@within Tree
@prop CollapsingHeader Iris.CollapsingHeader
@tag Widget
@tag HasChildren
@tag HasState
The same as a Tree Widget, but with a larger title and clearer, used mainly for organsing widgets on the first level of a window.
```lua
hasChildren: true
hasState: true
Arguments = {
Text: string,
DefaultOpen: boolean? = false -- initially opens the tree if no state is provided
}
Events = {
collapsed: () -> boolean,
uncollapsed: () -> boolean,
hovered: () -> boolean
}
State = {
isUncollapsed: State<boolean>? -- whether the widget is collapsed.
}
```
]=]
Iris.CollapsingHeader = wrapper("CollapsingHeader")
--[[
--------------------------------
[SECTION] Tab Widget API
--------------------------------
]]
--[=[
@class Tab
Tab Widget API
]=]
--[=[
@within Tab
@prop TabBar Iris.TabBar
@tag Widget
@tag HasChildren
@tag HasState
Creates a TabBar for putting tabs under. This does not create the tabs but just the container for them to be in.
The index state is used to control the current tab and is based on an index starting from 1 rather than the
text provided to a Tab. The TabBar will replicate the index to the Tab children .
```lua
hasChildren: true
hasState: true
Arguments = {}
Events = {}
State = {
index: State<number>? -- whether the widget is collapsed.
}
```
]=]
Iris.TabBar = wrapper("TabBar")
--[=[
@within Tab
@prop Tab Iris.Tab
@tag Widget
@tag HasChildren
@tag HasState
The tab item for use under a TabBar. The TabBar must be the parent and determines the index value. You cannot
provide a state for this tab. The optional Hideable argument determines if a tab can be closed, which is
controlled by the isOpened state.
A tab will take up the full horizontal width of the parent and hide any other tabs in the TabBar.
```lua
hasChildren: true
hasState: true
Arguments = {
Text: string,
Hideable: boolean? = nil -- determines whether a tab can be closed/hidden
}
Events = {
clicked: () -> boolean,
hovered: () -> boolean
selected: () -> boolean
unselected: () -> boolean
active: () -> boolean
opened: () -> boolean
closed: () -> boolean
}
State = {
isOpened: State<boolean>?
}
```
]=]
Iris.Tab = wrapper("Tab")
--[[
----------------------------------
[SECTION] Input Widget API
----------------------------------
]]
--[=[
@class Input
Input Widget API
Input Widgets are textboxes for typing in specific number values. See [Drag], [Slider] or [InputText](Text#InputText) for more input types.
Iris provides a set of specific inputs for the datatypes:
Number,
[Vector2](https://create.roblox.com/docs/reference/engine/datatypes/Vector2),
[Vector3](https://create.roblox.com/docs/reference/engine/datatypes/Vector3),
[UDim](https://create.roblox.com/docs/reference/engine/datatypes/UDim),
[UDim2](https://create.roblox.com/docs/reference/engine/datatypes/UDim2),
[Rect](https://create.roblox.com/docs/reference/engine/datatypes/Rect),
[Color3](https://create.roblox.com/docs/reference/engine/datatypes/Color3)
and the custom [Color4](https://create.roblox.com/docs/reference/engine/datatypes/Color3).
Each Input widget has the same arguments but the types depend of the DataType:
1. Text: string? = "Input{type}" -- the text to be displayed to the right of the textbox.
2. Increment: DataType? = nil, -- the increment argument determines how a value will be rounded once the textbox looses focus.
3. Min: DataType? = nil, -- the minimum value that the widget will allow, no clamping by default.
4. Max: DataType? = nil, -- the maximum value that the widget will allow, no clamping by default.
5. Format: string | { string }? = [DYNAMIC] -- uses `string.format` to customise visual display.
The format string can either by a single value which will apply to every box, or a table allowing specific text.
:::note
If you do not specify a format option then Iris will dynamically calculate a relevant number of sigifs and format option.
For example, if you have Increment, Min and Max values of 1, 0 and 100, then Iris will guess that you are only using integers
and will format the value as an integer.
As another example, if you have Increment, Min and max values of 0.005, 0, 1, then Iris will guess you are using a float of 3
significant figures.
Additionally, for certain DataTypes, Iris will append an prefix to each box if no format option is provided.
For example, a Vector3 box will have the append values of "X: ", "Y: " and "Z: " to the relevant input box.
:::
]=]
--[=[
@within Input
@prop InputNum Iris.InputNum
@tag Widget
@tag HasState
An input box for numbers. The number can be either an integer or a float.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputNum",
Increment: number? = nil,
Min: number? = nil,
Max: number? = nil,
Format: string? | { string }? = [DYNAMIC], -- Iris will dynamically generate an approriate format.
NoButtons: boolean? = false -- whether to display + and - buttons next to the input box.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<number>?,
editingText: State<boolean>?
}
```
]=]
Iris.InputNum = wrapper("InputNum")
--[=[
@within Input
@prop InputVector2 Iris.InputVector2
@tag Widget
@tag HasState
An input box for Vector2. The numbers can be either integers or floats.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputVector2",
Increment: Vector2? = nil,
Min: Vector2? = nil,
Max: Vector2? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Vector2>?,
editingText: State<boolean>?
}
```
]=]
Iris.InputVector2 = wrapper("InputVector2")
--[=[
@within Input
@prop InputVector3 Iris.InputVector3
@tag Widget
@tag HasState
An input box for Vector3. The numbers can be either integers or floats.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputVector3",
Increment: Vector3? = nil,
Min: Vector3? = nil,
Max: Vector3? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Vector3>?,
editingText: State<boolean>?
}
```
]=]
Iris.InputVector3 = wrapper("InputVector3")
--[=[
@within Input
@prop InputUDim Iris.InputUDim
@tag Widget
@tag HasState
An input box for UDim. The Scale box will be a float and the Offset box will be
an integer, unless specified differently.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputUDim",
Increment: UDim? = nil,
Min: UDim? = nil,
Max: UDim? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<UDim>?,
editingText: State<boolean>?
}
```
]=]
Iris.InputUDim = wrapper("InputUDim")
--[=[
@within Input
@prop InputUDim2 Iris.InputUDim2
@tag Widget
@tag HasState
An input box for UDim2. The Scale boxes will be floats and the Offset boxes will be
integers, unless specified differently.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputUDim2",
Increment: UDim2? = nil,
Min: UDim2? = nil,
Max: UDim2? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<UDim2>?,
editingText: State<boolean>?
}
```
]=]
Iris.InputUDim2 = wrapper("InputUDim2")
--[=[
@within Input
@prop InputRect Iris.InputRect
@tag Widget
@tag HasState
An input box for Rect. The numbers will default to integers, unless specified differently.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputRect",
Increment: Rect? = nil,
Min: Rect? = nil,
Max: Rect? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Rect>?,
editingText: State<boolean>?
}
```
]=]
Iris.InputRect = wrapper("InputRect")
--[[
---------------------------------
[SECTION] Drag Widget API
---------------------------------
]]
--[=[
@class Drag
Drag Widget API
A draggable widget for each datatype. Allows direct typing input but also dragging values by clicking and holding.
See [Input] for more details on the arguments.
]=]
--[=[
@within Drag
@prop DragNum Iris.DragNum
@tag Widget
@tag HasState
A field which allows the user to click and drag their cursor to enter a number.
You can ctrl + click to directly input a number, like InputNum.
You can hold Shift to increase speed, and Alt to decrease speed when dragging.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "DragNum",
Increment: number? = nil,
Min: number? = nil,
Max: number? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<number>?,
editingText: State<boolean>?
}
```
]=]
Iris.DragNum = wrapper("DragNum")
--[=[
@within Drag
@prop DragVector2 Iris.DragVector2
@tag Widget
@tag HasState
A field which allows the user to click and drag their cursor to enter a Vector2.
You can ctrl + click to directly input a Vector2, like InputVector2.
You can hold Shift to increase speed, and Alt to decrease speed when dragging.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "DragVector2",
Increment: Vector2? = nil,
Min: Vector2? = nil,
Max: Vector2? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Vector2>?,
editingText: State<boolean>?
}
```
]=]
Iris.DragVector2 = wrapper("DragVector2")
--[=[
@within Drag
@prop DragVector3 Iris.DragVector3
@tag Widget
@tag HasState
A field which allows the user to click and drag their cursor to enter a Vector3.
You can ctrl + click to directly input a Vector3, like InputVector3.
You can hold Shift to increase speed, and Alt to decrease speed when dragging.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "DragVector3",
Increment: Vector3? = nil,
Min: Vector3? = nil,
Max: Vector3? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Vector3>?,
editingText: State<boolean>?
}
```
]=]
Iris.DragVector3 = wrapper("DragVector3")
--[=[
@within Drag
@prop DragUDim Iris.DragUDim
@tag Widget
@tag HasState
A field which allows the user to click and drag their cursor to enter a UDim.
You can ctrl + click to directly input a UDim, like InputUDim.
You can hold Shift to increase speed, and Alt to decrease speed when dragging.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "DragUDim",
Increment: UDim? = nil,
Min: UDim? = nil,
Max: UDim? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<UDim>?,
editingText: State<boolean>?
}
```
]=]
Iris.DragUDim = wrapper("DragUDim")
--[=[
@within Drag
@prop DragUDim2 Iris.DragUDim2
@tag Widget
@tag HasState
A field which allows the user to click and drag their cursor to enter a UDim2.
You can ctrl + click to directly input a UDim2, like InputUDim2.
You can hold Shift to increase speed, and Alt to decrease speed when dragging.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "DragUDim2",
Increment: UDim2? = nil,
Min: UDim2? = nil,
Max: UDim2? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<UDim2>?,
editingText: State<boolean>?
}
```
]=]
Iris.DragUDim2 = wrapper("DragUDim2")
--[=[
@within Drag
@prop DragRect Iris.DragRect
@tag Widget
@tag HasState
A field which allows the user to click and drag their cursor to enter a Rect.
You can ctrl + click to directly input a Rect, like InputRect.
You can hold Shift to increase speed, and Alt to decrease speed when dragging.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "DragRect",
Increment: Rect? = nil,
Min: Rect? = nil,
Max: Rect? = nil,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Rect>?,
editingText: State<boolean>?
}
```
]=]
Iris.DragRect = wrapper("DragRect")
--[=[
@within Input
@prop InputColor3 Iris.InputColor3
@tag Widget
@tag HasState
An input box for Color3. The input boxes are draggable between 0 and 255 or if UseFloats then between 0 and 1.
Input can also be done using HSV instead of the default RGB.
If no format argument is provided then a default R, G, B or H, S, V prefix is applied.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputColor3",
UseFloats: boolean? = false, -- constrain the values between floats 0 and 1 or integers 0 and 255.
UseHSV: boolean? = false, -- input using HSV instead.
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
color: State<Color3>?,
editingText: State<boolean>?
}
```
]=]
Iris.InputColor3 = wrapper("InputColor3")
--[=[
@within Input
@prop InputColor4 Iris.InputColor4
@tag Widget
@tag HasState
An input box for Color4. Color4 is a combination of Color3 and a fourth transparency argument.
It has two states for this purpose.
The input boxes are draggable between 0 and 255 or if UseFloats then between 0 and 1.
Input can also be done using HSV instead of the default RGB.
If no format argument is provided then a default R, G, B, T or H, S, V, T prefix is applied.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputColor4",
UseFloats: boolean? = false, -- constrain the values between floats 0 and 1 or integers 0 and 255.
UseHSV: boolean? = false, -- input using HSV instead.
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
color: State<Color3>?,
transparency: State<number>?,
editingText: State<boolean>?
}
```
]=]
Iris.InputColor4 = wrapper("InputColor4")
--[[
-----------------------------------
[SECTION] Slider Widget API
-----------------------------------
]]
--[=[
@class Slider
Slider Widget API
A draggable widget with a visual bar constrained between a min and max for each datatype.
Allows direct typing input but also dragging the slider by clicking and holding anywhere in the box.
See [Input] for more details on the arguments.
]=]
--[=[
@within Slider
@prop SliderNum Iris.SliderNum
@tag Widget
@tag HasState
A field which allows the user to slide a grip to enter a number within a range.
You can ctrl + click to directly input a number, like InputNum.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "SliderNum",
Increment: number? = 1,
Min: number? = 0,
Max: number? = 100,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<number>?,
editingText: State<boolean>?
}
```
]=]
Iris.SliderNum = wrapper("SliderNum")
--[=[
@within Slider
@prop SliderVector2 Iris.SliderVector2
@tag Widget
@tag HasState
A field which allows the user to slide a grip to enter a Vector2 within a range.
You can ctrl + click to directly input a Vector2, like InputVector2.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "SliderVector2",
Increment: Vector2? = { 1, 1 },
Min: Vector2? = { 0, 0 },
Max: Vector2? = { 100, 100 },
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Vector2>?,
editingText: State<boolean>?
}
```
]=]
Iris.SliderVector2 = wrapper("SliderVector2")
--[=[
@within Slider
@prop SliderVector3 Iris.SliderVector3
@tag Widget
@tag HasState
A field which allows the user to slide a grip to enter a Vector3 within a range.
You can ctrl + click to directly input a Vector3, like InputVector3.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "SliderVector3",
Increment: Vector3? = { 1, 1, 1 },
Min: Vector3? = { 0, 0, 0 },
Max: Vector3? = { 100, 100, 100 },
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Vector3>?,
editingText: State<boolean>?
}
```
]=]
Iris.SliderVector3 = wrapper("SliderVector3")
--[=[
@within Slider
@prop SliderUDim Iris.SliderUDim
@tag Widget
@tag HasState
A field which allows the user to slide a grip to enter a UDim within a range.
You can ctrl + click to directly input a UDim, like InputUDim.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "SliderUDim",
Increment: UDim? = { 0.01, 1 },
Min: UDim? = { 0, 0 },
Max: UDim? = { 1, 960 },
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<UDim>?,
editingText: State<boolean>?
}
```
]=]
Iris.SliderUDim = wrapper("SliderUDim")
--[=[
@within Slider
@prop SliderUDim2 Iris.SliderUDim2
@tag Widget
@tag HasState
A field which allows the user to slide a grip to enter a UDim2 within a range.
You can ctrl + click to directly input a UDim2, like InputUDim2.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "SliderUDim2",
Increment: UDim2? = { 0.01, 1, 0.01, 1 },
Min: UDim2? = { 0, 0, 0, 0 },
Max: UDim2? = { 1, 960, 1, 960 },
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<UDim2>?,
editingText: State<boolean>?
}
```
]=]
Iris.SliderUDim2 = wrapper("SliderUDim2")
--[=[
@within Slider
@prop SliderRect Iris.SliderRect
@tag Widget
@tag HasState
A field which allows the user to slide a grip to enter a Rect within a range.
You can ctrl + click to directly input a Rect, like InputRect.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "SliderRect",
Increment: Rect? = { 1, 1, 1, 1 },
Min: Rect? = { 0, 0, 0, 0 },
Max: Rect? = { 960, 960, 960, 960 },
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<Rect>?,
editingText: State<boolean>?
}
```
]=]
Iris.SliderRect = wrapper("SliderRect")
--[[
----------------------------------
[SECTION] Combo Widget API
----------------------------------
]]
--[=[
@class Combo
Combo Widget API
]=]
--[=[
@within Combo
@prop Selectable Iris.Selectable
@tag Widget
@tag HasState
An object which can be selected.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string,
Index: any, -- index of selectable value.
NoClick: boolean? = false -- prevents the selectable from being clicked by the user.
}
Events = {
selected: () -> boolean,
unselected: () -> boolean,
active: () -> boolean,
clicked: () -> boolean,
rightClicked: () -> boolean,
doubleClicked: () -> boolean,
ctrlClicked: () -> boolean,
hovered: () -> boolean,
}
States = {
index: State<any> -- a shared state between all selectables.
}
```
]=]
Iris.Selectable = wrapper("Selectable")
--[=[
@within Combo
@prop Combo Iris.Combo
@tag Widget
@tag HasChildren
@tag HasState
A dropdown menu box to make a selection from a list of values.
```lua
hasChildren = true
hasState = true
Arguments = {
Text: string,
NoButton: boolean? = false, -- hide the dropdown button.
NoPreview: boolean? = false -- hide the preview field.
}
Events = {
opened: () -> boolean,
closed: () -> boolean,
changed: () -> boolean,
clicked: () -> boolean,
hovered: () -> boolean
}
States = {
index: State<any>,
isOpened: State<boolean>?
}
```
]=]
Iris.Combo = wrapper("Combo")
--[=[
@within Combo
@prop ComboArray Iris.Combo
@tag Widget
@tag HasChildren
@tag HasState
A selection box to choose a value from an array.
```lua
hasChildren = true
hasState = true
Arguments = {
Text: string,
NoButton: boolean? = false, -- hide the dropdown button.
NoPreview: boolean? = false -- hide the preview field.
}
Events = {
opened: () -> boolean,
closed: () -> boolean,
clicked: () -> boolean,
hovered: () -> boolean
}
States = {
index: State<any>,
isOpened: State<boolean>?
}
Extra = {
selectionArray: { any } -- the array to generate a combo from.
}
```
]=]
Iris.ComboArray = function<T>(arguments: Types.WidgetArguments, states: Types.WidgetStates?, selectionArray: { T })
local defaultState
if states == nil then
defaultState = Iris.State(selectionArray[1])
else
defaultState = states
end
local thisWidget = Iris.Internal._Insert("Combo", arguments, defaultState)
local sharedIndex = thisWidget.state.index
for _, Selection in selectionArray do
Iris.Internal._Insert("Selectable", { Selection, Selection }, { index = sharedIndex })
end
Iris.End()
return thisWidget
end
--[=[
@within Combo
@prop ComboEnum Iris.Combo
@tag Widget
@tag HasChildren
@tag HasState
A selection box to choose a value from an Enum.
```lua
hasChildren = true
hasState = true
Arguments = {
Text: string,
NoButton: boolean? = false, -- hide the dropdown button.
NoPreview: boolean? = false -- hide the preview field.
}
Events = {
opened: () -> boolean,
closed: () -> boolean,
clicked: () -> boolean,
hovered: () -> boolean
}
States = {
index: State<any>,
isOpened: State<boolean>?
}
Extra = {
enumType: Enum -- the enum to generate a combo from.
}
```
]=]
Iris.ComboEnum = function(arguments: Types.WidgetArguments, states: Types.WidgetStates?, enumType: Enum)
local defaultState
if states == nil then
defaultState = Iris.State(enumType:GetEnumItems()[1])
else
defaultState = states
end
local thisWidget = Iris.Internal._Insert("Combo", arguments, defaultState)
local sharedIndex = thisWidget.state.index
for _, Selection in enumType:GetEnumItems() do
Iris.Internal._Insert("Selectable", { Selection.Name, Selection }, { index = sharedIndex })
end
Iris.End()
return thisWidget
end
--[=[
@private
@within Slider
@prop InputEnum Iris.InputEnum
@tag Widget
@tag HasState
A field which allows the user to slide a grip to enter a number within a range.
You can ctrl + click to directly input a number, like InputNum.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "InputEnum",
Increment: number? = 1,
Min: number? = 0,
Max: number? = 100,
Format: string? | { string }? = [DYNAMIC] -- Iris will dynamically generate an approriate format.
}
Events = {
numberChanged: () -> boolean,
hovered: () -> boolean
}
States = {
number: State<number>?,
editingText: State<boolean>?,
enumItem: EnumItem
}
```
]=]
Iris.InputEnum = Iris.ComboEnum
--[[
---------------------------------
[SECTION] Plot Widget API
---------------------------------
]]
--[=[
@class Plot
Plot Widget API
]=]
--[=[
@within Plot
@prop ProgressBar Iris.ProgressBar
@tag Widget
@tag HasState
A progress bar line with a state value to show the current state.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "Progress Bar",
Format: string? = nil -- optional to override with a custom progress such as `29/54`
}
Events = {
hovered: () -> boolean,
changed: () -> boolean
}
States = {
progress: State<number>?
}
```
]=]
Iris.ProgressBar = wrapper("ProgressBar")
--[=[
@within Plot
@prop PlotLines Iris.PlotLines
@tag Widget
@tag HasState
A line graph for plotting a single line. Includes hovering to see a specific value on the graph,
and automatic scaling. Has an overlay text option at the top of the plot for displaying any
information.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "Plot Lines",
Height: number? = 0,
Min: number? = min, -- Iris will use the minimum value from the values
Max: number? = max, -- Iris will use the maximum value from the values
TextOverlay: string? = ""
}
Events = {
hovered: () -> boolean
}
States = {
values: State<{number}>?,
hovered: State<{number}>? -- read-only property
}
```
]=]
Iris.PlotLines = wrapper("PlotLines")
--[=[
@within Plot
@prop PlotHistogram Iris.PlotHistogram
@tag Widget
@tag HasState
A hisogram graph for showing values. Includes hovering to see a specific block on the graph,
and automatic scaling. Has an overlay text option at the top of the plot for displaying any
information. Also supports a baseline option, which determines where the blocks start from.
```lua
hasChildren = false
hasState = true
Arguments = {
Text: string? = "Plot Histogram",
Height: number? = 0,
Min: number? = min, -- Iris will use the minimum value from the values
Max: number? = max, -- Iris will use the maximum value from the values
TextOverlay: string? = "",
BaseLine: number? = 0 -- by default, blocks swap side at 0
}
Events = {
hovered: () -> boolean
}
States = {
values: State<{number}>?,
hovered: State<{number}>? -- read-only property
}
```
]=]
Iris.PlotHistogram = wrapper("PlotHistogram")
--[[
----------------------------------
[SECTION] Table Widget API
----------------------------------
]]
--[=[
@class Table
Table Widget API
Example usage for creating a simple table:
```lua
Iris.Table({ 4, true })
do
Iris.SetHeaderColumnIndex(1)
-- for each row
for i = 0, 10 do
-- for each column
for j = 1, 4 do
if i == 0 then
--
Iris.Text({ `H: {j}` })
else
Iris.Text({ `R: {i}, C: {j}` })
end
-- move the next column (and row when necessary)
Iris.NextColumn()
end
end
```
]=]
--[=[
@within Table
@prop Table Iris.Table
@tag Widget
@tag HasChildren
A layout widget which allows children to be displayed in configurable columns and rows. Highly configurable for many different
options, with options for custom width columns as configured by the user, or automatically use the best size.
When Resizable is enabled, the vertical columns can be dragged horizontally to increase or decrease space. This is linked to
the widths state, which controls the width of each column. This is also dependent on whether the FixedWidth argument is enabled.
By default, the columns will scale with the width of the table overall, therefore taking up a percentage, and the widths will be
in the range of 0 to 1 as a float. If FixedWidth is enabled, then the widths will be in pixels and have a value of > 2 as an
integer.
ProportionalWidth determines whether each column has the same width, or individual. By default, each column will take up an equal
proportion of the total table width. If true, then the columns will be allocated a width proportional to their total content size,
meaning wider columns take up a greater share of the total available space. For a fixed width table, by default each column will
take the max width of all the columns. When true, each column width will the minimum to fit the children within.
LimitTableWidth is used when FixedWidth is true. It will cut off the table horizontally after the last column.
:::info
Once the NumColumns is set, it is not possible to change it without some extra code. The best way to do this is by using
`Iris.PushConfig()` and `Iris.PopConfig()` which will automatically redraw the widget when the columns change.
```lua
local numColumns = 4
Iris.PushConfig({ columns = numColumns })
Iris.Table({ numColumns, ...})
do
...
end
Iris.End()
Iris.PopConfig()
```
:::danger Error: nil
Always ensure that the number of elements in the widths state is greater or equal to the
new number of columns when changing the number of columns.
:::
:::
```lua
hasChildren = true
hasState = false
Arguments = {
NumColumns: number, -- number of columns in the table, cannot be changed
Header: boolean? = false, -- display a header row for each column
RowBackground: boolean? = false, -- alternating row background colours
OuterBorders: boolean? = false, -- outer border on the entire table
InnerBorders: boolean? = false, -- inner bordres on the entire table
Resizable: boolean? = false, -- the columns can be resized by dragging or state
FixedWidth: boolean? = false, -- columns takes up a fixed pixel width, rather than a proportion of the total available
ProportionalWidth: boolean? = false, -- minimises the width of each column individually
LimitTableWidth: boolean? = false, -- when a fixed width, cut of any unused space
}
Events = {
hovered: () -> boolean
}
States = {
widths: State<{ number }>? -- the widths of each column if Resizable
}
```
]=]
Iris.Table = wrapper("Table")
--[=[
@within Table
@function NextColumn
In a table, moves to the next available cell. If the current cell is in the last column,
then moves to the cell in the first column of the next row.
]=]
Iris.NextColumn = function()
local Table = Iris.Internal._GetParentWidget() :: Types.Table
assert(Table ~= nil, "Iris.NextColumn() can only called when directly within a table.")
local columnIndex = Table._columnIndex
if columnIndex == Table.arguments.NumColumns then
Table._columnIndex = 1
Table._rowIndex += 1
else
Table._columnIndex += 1
end
return Table._columnIndex
end
--[=[
@within Table
@function NextRow
In a table, moves to the cell in the first column of the next row.
]=]
Iris.NextRow = function()
local Table = Iris.Internal._GetParentWidget() :: Types.Table
assert(Table ~= nil, "Iris.NextRow() can only called when directly within a table.")
Table._columnIndex = 1
Table._rowIndex += 1
return Table._rowIndex
end
--[=[
@within Table
@function SetColumnIndex
@param index number
In a table, moves to the cell in the given column in the same previous row.
Will erorr if the given index is not in the range of 1 to NumColumns.
]=]
Iris.SetColumnIndex = function(index: number)
local Table = Iris.Internal._GetParentWidget() :: Types.Table
assert(Table ~= nil, "Iris.SetColumnIndex() can only called when directly within a table.")
assert((index >= 1) and (index <= Table.arguments.NumColumns), `The index must be between 1 and {Table.arguments.NumColumns}, inclusive.`)
Table._columnIndex = index
end
--[=[
@within Table
@function SetRowIndex
@param index number
In a table, moves to the cell in the given row with the same previous column.
]=]
Iris.SetRowIndex = function(index: number)
local Table = Iris.Internal._GetParentWidget() :: Types.Table
assert(Table ~= nil, "Iris.SetRowIndex() can only called when directly within a table.")
assert(index >= 1, "The index must be greater or equal to 1.")
Table._rowIndex = index
end
--[=[
@within Table
@function NextHeaderColumn
In a table, moves to the cell in the next column in the header row (row index 0). Will loop around
from the last column to the first.
]=]
Iris.NextHeaderColumn = function()
local Table = Iris.Internal._GetParentWidget() :: Types.Table
assert(Table ~= nil, "Iris.NextHeaderColumn() can only called when directly within a table.")
Table._rowIndex = 0
Table._columnIndex = (Table._columnIndex % Table.arguments.NumColumns) + 1
return Table._columnIndex
end
--[=[
@within Table
@function SetHeaderColumnIndex
@param index number
In a table, moves to the cell in the given column in the header row (row index 0).
Will erorr if the given index is not in the range of 1 to NumColumns.
]=]
Iris.SetHeaderColumnIndex = function(index: number)
local Table = Iris.Internal._GetParentWidget() :: Types.Table
assert(Table ~= nil, "Iris.SetHeaderColumnIndex() can only called when directly within a table.")
assert((index >= 1) and (index <= Table.arguments.NumColumns), `The index must be between 1 and {Table.arguments.NumColumns}, inclusive.`)
Table._rowIndex = 0
Table._columnIndex = index
end
--[=[
@within Table
@function SetColumnWidth
@param index number
@param width number
In a table, sets the width of the given column to the given value by changing the
Table's widths state. When the FixedWidth argument is true, the width should be in
pixels >2, otherwise as a float between 0 and 1.
Will erorr if the given index is not in the range of 1 to NumColumns.
]=]
Iris.SetColumnWidth = function(index: number, width: number)
local Table = Iris.Internal._GetParentWidget() :: Types.Table
assert(Table ~= nil, "Iris.SetColumnWidth() can only called when directly within a table.")
assert((index >= 1) and (index <= Table.arguments.NumColumns), `The index must be between 1 and {Table.arguments.NumColumns}, inclusive.`)
local oldValue = Table.state.widths.value[index]
Table.state.widths.value[index] = width
Table.state.widths:set(Table.state.widths.value, width ~= oldValue)
end
end
| 15,280 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/Internal.lua | local Types = require(script.Parent.Types)
return function(Iris: Types.Iris): Types.Internal
--[=[
@class Internal
An internal class within Iris containing all the backend data and functions for Iris to operate.
It is recommended that you don't generally interact with Internal unless you understand what you are doing.
]=]
local Internal = {} :: Types.Internal
--[[
---------------------------------
[SECTION] Properties
---------------------------------
]]
Internal._version = [[ 2.5.0 ]]
Internal._started = false -- has Iris.connect been called yet
Internal._shutdown = false
Internal._cycleTick = 0 -- increments for each call to Cycle, used to determine the relative age and freshness of generated widgets
Internal._deltaTime = 0
-- Refresh
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
Internal._refreshCounter = 0 -- if true, when _Insert is called, the widget called will be regenerated
Internal._refreshLevel = 1
Internal._refreshStack = table.create(16)
-- Widgets & Instances
Internal._widgets = {}
Internal._stackIndex = 1 -- Points to the index that IDStack is currently in, when computing cycle
Internal._rootInstance = nil
Internal._rootWidget = {
ID = "R",
type = "Root",
Instance = Internal._rootInstance,
ZIndex = 0,
ZOffset = 0,
}
Internal._lastWidget = Internal._rootWidget -- widget which was most recently rendered
-- Config
Internal._rootConfig = {} -- root style which all widgets derive from
Internal._config = Internal._rootConfig
-- ID
Internal._IDStack = { "R" }
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
Internal._pushedIds = {}
Internal._newID = false
Internal._nextWidgetId = nil
-- State
Internal._states = {} -- Iris.States
-- Callback
Internal._postCycleCallbacks = {}
Internal._connectedFunctions = {} -- functions which run each Iris cycle, connected by the user
Internal._connections = {}
Internal._initFunctions = {}
-- Error
Internal._fullErrorTracebacks = game:GetService("RunService"):IsStudio()
--[=[
@within Internal
@prop _cycleCoroutine thread
The thread which handles all connected functions. Each connection is within a pcall statement which prevents
Iris from crashing and instead stopping at the error.
]=]
Internal._cycleCoroutine = coroutine.create(function()
while Internal._started do
for _, callback in Internal._connectedFunctions do
debug.profilebegin("Iris/Connection")
local status, _error: string = pcall(callback)
debug.profileend()
if not status then
-- any error reserts the _stackIndex for the next frame and yields the error.
Internal._stackIndex = 1
coroutine.yield(false, _error)
end
end
-- after all callbacks, we yield so it only runs once a frame.
coroutine.yield(true)
end
end)
--[[
-----------------------
[SECTION] State
-----------------------
]]
--[=[
@class State
This class wraps a value in getters and setters, its main purpose is to allow primatives to be passed as objects.
Constructors for this class are available in [Iris]
```lua
local state = Iris.State(0) -- we initialise the state with a value of 0
-- these are equivalent. Ideally you should use `:get()` and ignore `.value`.
print(state:get())
print(state.value)
state:set(state:get() + 1) -- increments the state by getting the current value and adding 1.
state:onChange(function(newValue)
print(`The value of the state is now: {newValue}`)
end)
```
:::caution Caution: Callbacks
Never call `:set()` on a state when inside the `:onChange()` callback of the same state. This will cause a continous callback.
Never chain states together so that each state changes the value of another state in a cyclic nature. This will cause a continous callback.
:::
]=]
local StateClass = {}
StateClass.__index = StateClass
--[=[
@within State
@method get<T>
@return T
Returns the states current value.
]=]
function StateClass:get<T>() -- you can also simply use .value
return self.value
end
--[=[
@within State
@method set<T>
@param newValue T
@param force boolean? -- force an update to all connections
@return T
Allows the caller to assign the state object a new value, and returns the new value.
]=]
function StateClass:set<T>(newValue: T, force: true?)
if newValue == self.value and force ~= true then
-- no need to update on no change.
return self.value
end
self.value = newValue
self.lastChangeTick = Iris.Internal._cycleTick
for _, thisWidget: Types.Widget in self.ConnectedWidgets do
if thisWidget.lastCycleTick ~= -1 then
Internal._widgets[thisWidget.type].UpdateState(thisWidget)
end
end
for _, callback in self.ConnectedFunctions do
callback(newValue)
end
return self.value
end
--[=[
@within State
@method onChange<T>
@param callback (newValue: T) -> ()
@return () -> ()
Allows the caller to connect a callback which is called when the states value is changed.
:::caution Caution: Single
Calling `:onChange()` every frame will add a new function every frame.
You must ensure you are only calling `:onChange()` once for each callback for the state's entire lifetime.
:::
]=]
function StateClass:onChange<T>(callback: (newValue: T) -> ())
local connectionIndex: number = #self.ConnectedFunctions + 1
self.ConnectedFunctions[connectionIndex] = callback
return function()
self.ConnectedFunctions[connectionIndex] = nil
end
end
--[=[
@within State
@method changed<T>
@return boolean
Returns true if the state was changed on this frame.
]=]
function StateClass:changed<T>()
return self.lastChangeTick + 1 == Internal._cycleTick
end
Internal.StateClass = StateClass
--[[
---------------------------
[SECTION] Functions
---------------------------
]]
--[=[
@within Internal
@function _cycle
Called every frame to handle all of the widget management. Any previous frame data is ammended and everything updates.
]=]
function Internal._cycle(deltaTime: number)
-- debug.profilebegin("Iris/Cycle")
if Iris.Disabled then
return -- Stops all rendering, effectively freezes the current frame with no interaction.
end
Internal._rootWidget.lastCycleTick = Internal._cycleTick
if Internal._rootInstance == nil or Internal._rootInstance.Parent == nil then
Iris.ForceRefresh()
end
for _, widget in Internal._lastVDOM do
if widget.lastCycleTick ~= Internal._cycleTick and (widget.lastCycleTick ~= -1) then
-- a widget which used to be rendered was not called last frame, so we discard it.
-- if the cycle tick is -1 we have already discarded it.
Internal._DiscardWidget(widget)
end
end
-- represents all widgets created last frame. We keep the _lastVDOM to reuse widgets from the previous frame
-- rather than creating a new instance every frame.
setmetatable(Internal._lastVDOM, { __mode = "kv" })
Internal._lastVDOM = Internal._VDOM
Internal._VDOM = Internal._generateEmptyVDOM()
-- anything that wnats to run before the frame.
task.spawn(function()
-- debug.profilebegin("Iris/PostCycleCallbacks")
for _, callback in Internal._postCycleCallbacks do
callback()
end
-- debug.profileend()
end)
if Internal._globalRefreshRequested then
-- rerender every widget
--debug.profilebegin("Iris Refresh")
Internal._generateSelectionImageObject()
Internal._globalRefreshRequested = false
for _, widget in Internal._lastVDOM do
Internal._DiscardWidget(widget)
end
Internal._generateRootInstance()
Internal._lastVDOM = Internal._generateEmptyVDOM()
--debug.profileend()
end
-- update counters
Internal._cycleTick += 1
Internal._deltaTime = deltaTime
table.clear(Internal._usedIDs)
-- if Internal.parentInstance:IsA("GuiBase2d") and math.min(Internal.parentInstance.AbsoluteSize.X, Internal.parentInstance.AbsoluteSize.Y) < 100 then
-- error("Iris Parent Instance is too small")
-- end
local compatibleParent = (Internal.parentInstance:IsA("GuiBase2d") or Internal.parentInstance:IsA("BasePlayerGui"))
if compatibleParent == false then
error("The Iris parent instance will not display any GUIs.")
end
-- if we are running in Studio, we want full error tracebacks, so we don't have
-- any pcall to protect from an error.
if Internal._fullErrorTracebacks then
-- debug.profilebegin("Iris/Cycle/Callback")
for _, callback in Internal._connectedFunctions do
callback()
end
else
-- debug.profilebegin("Iris/Cycle/Coroutine")
-- each frame we check on our thread status.
local coroutineStatus = coroutine.status(Internal._cycleCoroutine)
if coroutineStatus == "suspended" then
-- suspended means it yielded, either because it was a complete success
-- or it caught an error in the code. We run it again for this frame.
local _, success, result = coroutine.resume(Internal._cycleCoroutine)
if success == false then
-- Connected function code errored
error(result, 0)
end
elseif coroutineStatus == "running" then
-- still running (probably because of an asynchronous method inside a connection).
error("Iris cycleCoroutine took to long to yield. Connected functions should not yield.")
else
-- should never reach this (nothing you can do).
error("unrecoverable state")
end
-- debug.profileend()
end
if Internal._stackIndex ~= 1 then
-- has to be larger than 1 because of the check that it isnt below 1 in Iris.End
Internal._stackIndex = 1
error("Too few calls to Iris.End().", 0)
end
-- Errors if the end user forgot to pop all their ids as they would leak over into the next frame
-- could also just clear, but that might be confusing behaviour.
if #Internal._pushedIds ~= 0 then
error("Too few calls to Iris.PopId().", 0)
end
-- debug.profileend()
end
--[=[
@within Internal
@ignore
@function _NoOp
A dummy function which does nothing. Used as a placeholder for optional methods in a widget class.
Used in `Internal.WidgetConstructor`
]=]
function Internal._NoOp() end
-- Widget
--[=[
@within Internal
@function WidgetConstructor
@param type string -- name used to denote the widget class.
@param widgetClass Types.WidgetClass -- table of methods for the new widget.
For each widget, a widget class is created which handles all the operations of a widget. This removes the class nature
of widgets, and simplifies the available functions which can be applied to any widget. The widgets themselves are
dumb tables containing all the data but no methods to handle any of the data apart from events.
]=]
function Internal.WidgetConstructor(type: string, widgetClass: Types.WidgetClass)
local Fields = {
All = {
Required = {
"Generate", -- generates the instance.
"Discard",
"Update",
-- not methods !
"Args",
"Events",
"hasChildren",
"hasState",
},
Optional = {},
},
IfState = {
Required = {
"GenerateState",
"UpdateState",
},
Optional = {},
},
IfChildren = {
Required = {
"ChildAdded", -- returns the parent of the child widget.
},
Optional = {
"ChildDiscarded",
},
},
}
-- we ensure all essential functions and properties are present, otherwise the code will break later.
-- some functions will only be needed if the widget has children or has state.
local thisWidget = {} :: Types.WidgetClass
for _, field in Fields.All.Required do
assert(widgetClass[field] ~= nil, `field {field} is missing from widget {type}, it is required for all widgets`)
thisWidget[field] = widgetClass[field]
end
for _, field in Fields.All.Optional do
if widgetClass[field] == nil then
-- assign a dummy function which does nothing.
thisWidget[field] = Internal._NoOp
else
thisWidget[field] = widgetClass[field]
end
end
if widgetClass.hasState then
for _, field in Fields.IfState.Required do
assert(widgetClass[field] ~= nil, `field {field} is missing from widget {type}, it is required for all widgets with state`)
thisWidget[field] = widgetClass[field]
end
for _, field in Fields.IfState.Optional do
if widgetClass[field] == nil then
thisWidget[field] = Internal._NoOp
else
thisWidget[field] = widgetClass[field]
end
end
end
if widgetClass.hasChildren then
for _, field in Fields.IfChildren.Required do
assert(widgetClass[field] ~= nil, `field {field} is missing from widget {type}, it is required for all widgets with children`)
thisWidget[field] = widgetClass[field]
end
for _, field in Fields.IfChildren.Optional do
if widgetClass[field] == nil then
thisWidget[field] = Internal._NoOp
else
thisWidget[field] = widgetClass[field]
end
end
end
-- an internal table of all widgets to the widget class.
Internal._widgets[type] = thisWidget
-- allowing access to the index for each widget argument.
Iris.Args[type] = thisWidget.Args
local ArgNames = {}
for index, argument in thisWidget.Args do
ArgNames[argument] = index
end
thisWidget.ArgNames = ArgNames
for index, _ in thisWidget.Events do
if Iris.Events[index] == nil then
Iris.Events[index] = function()
return Internal._EventCall(Internal._lastWidget, index)
end
end
end
end
--[=[
@within Internal
@function _Insert
@param widgetType: string -- name of widget class.
@param arguments { [string]: number } -- arguments of the widget.
@param states { [string]: States<any> }? -- states of the widget.
@return Widget -- the widget.
Every widget is created through _Insert. An ID is generated based on the line of the calling code and is used to
find the previous frame widget if it exists. If no widget exists, a new one is created.
]=]
function Internal._Insert(widgetType: string, args: Types.WidgetArguments?, states: Types.WidgetStates?)
local ID = Internal._getID(3)
--debug.profilebegin(ID)
-- fetch the widget class which contains all the functions for the widget.
local thisWidgetClass = Internal._widgets[widgetType]
if Internal._VDOM[ID] then
-- widget already created once this frame, so we can append to it.
return Internal._ContinueWidget(ID, widgetType)
end
local arguments = {} :: Types.Arguments
if args ~= nil then
if type(args) ~= "table" then
args = { args }
end
-- convert the arguments to a key-value dictionary so arguments can be referred to by their name and not index.
for index, argument in args do
assert(index > 0, `Widget Arguments must be a positive number, not {index} of type {typeof(index)} for {argument}.`)
arguments[thisWidgetClass.ArgNames[index]] = argument
end
end
-- prevents tampering with the arguments which are used to check for changes.
table.freeze(arguments)
local lastWidget = Internal._lastVDOM[ID]
if lastWidget and widgetType == lastWidget.type then
-- found a matching widget from last frame.
if Internal._refreshCounter > 0 then
-- we are redrawing every widget.
Internal._DiscardWidget(lastWidget)
lastWidget = nil
end
end
local thisWidget = if lastWidget == nil then Internal._GenNewWidget(widgetType, arguments, states, ID) else lastWidget
local parentWidget = thisWidget.parentWidget
if thisWidget.type ~= "Window" and thisWidget.type ~= "Tooltip" then
if thisWidget.ZIndex ~= parentWidget.ZOffset then
parentWidget.ZUpdate = true
end
if parentWidget.ZUpdate then
thisWidget.ZIndex = parentWidget.ZOffset
if thisWidget.Instance then
thisWidget.Instance.ZIndex = thisWidget.ZIndex
thisWidget.Instance.LayoutOrder = thisWidget.ZIndex
end
end
end
-- since rows are not instances, but will be removed if not updated, we have to add specific table code.
if parentWidget.type == "Table" then
local Table = parentWidget :: Types.Table
Table._rowCycles[Table._rowIndex] = Internal._cycleTick
end
if Internal._deepCompare(thisWidget.providedArguments, arguments) == false then
-- the widgets arguments have changed, the widget should update to reflect changes.
-- providedArguments is the frozen table which will not change.
-- the arguments can be altered internally, which happens for the input widgets.
thisWidget.arguments = Internal._deepCopy(arguments)
thisWidget.providedArguments = arguments
thisWidgetClass.Update(thisWidget)
end
thisWidget.lastCycleTick = Internal._cycleTick
parentWidget.ZOffset += 1
if thisWidgetClass.hasChildren then
local thisParent = thisWidget :: Types.ParentWidget
-- a parent widget, so we increase our depth.
thisParent.ZOffset = 0
thisParent.ZUpdate = false
Internal._stackIndex += 1
Internal._IDStack[Internal._stackIndex] = thisWidget.ID
end
Internal._VDOM[ID] = thisWidget
Internal._lastWidget = thisWidget
--debug.profileend()
return thisWidget
end
--[=[
@within Internal
@function _GenNewWidget
@param widgetType string
@param arguments { [string]: any } -- arguments of the widget.
@param states { [string]: State<any> }? -- states of the widget.
@param ID ID -- id of the new widget. Determined in `Internal._Insert`
@return Widget -- the newly created widget.
All widgets are created as tables with properties. The widget class contains the functions to create the UI instances and
update the widget or change state.
]=]
function Internal._GenNewWidget(widgetType: string, arguments: Types.Arguments, states: Types.WidgetStates?, ID: Types.ID)
local parentId = Internal._IDStack[Internal._stackIndex]
local parentWidget: Types.ParentWidget = Internal._VDOM[parentId]
local thisWidgetClass = Internal._widgets[widgetType]
-- widgets are just tables with properties.
local thisWidget = {} :: Types.Widget
setmetatable(thisWidget, thisWidget)
thisWidget.ID = ID
thisWidget.type = widgetType
thisWidget.parentWidget = parentWidget
thisWidget.trackedEvents = {}
-- thisWidget.UID = HttpService:GenerateGUID(false):sub(0, 8)
-- widgets have lots of space to ensure they are always visible.
thisWidget.ZIndex = parentWidget.ZOffset
thisWidget.Instance = thisWidgetClass.Generate(thisWidget)
-- tooltips set their parent in the generation method, so we need to udpate it here
parentWidget = thisWidget.parentWidget
if Internal._config.Parent then
thisWidget.Instance.Parent = Internal._config.Parent
else
thisWidget.Instance.Parent = Internal._widgets[parentWidget.type].ChildAdded(parentWidget, thisWidget)
end
-- we can modify the arguments table, but keep a frozen copy to compare for user-end changes.
thisWidget.providedArguments = arguments
thisWidget.arguments = Internal._deepCopy(arguments)
thisWidgetClass.Update(thisWidget)
local eventMTParent
if thisWidgetClass.hasState then
local stateWidget = thisWidget :: Types.StateWidget
if states then
for index, state in states do
if not (type(state) == "table" and getmetatable(state :: any) == Internal.StateClass) then
-- generate a new state.
states[index] = Internal._widgetState(stateWidget, index, state)
end
states[index].lastChangeTick = Internal._cycleTick
end
stateWidget.state = states
for _, state in states do
state.ConnectedWidgets[stateWidget.ID] = stateWidget
end
else
stateWidget.state = {}
end
thisWidgetClass.GenerateState(stateWidget)
thisWidgetClass.UpdateState(stateWidget)
-- the state MT can't be itself because state has to explicitly only contain stateClass objects
stateWidget.stateMT = {}
setmetatable(stateWidget.state, stateWidget.stateMT)
stateWidget.__index = stateWidget.state
eventMTParent = stateWidget.stateMT
else
eventMTParent = thisWidget
end
eventMTParent.__index = function(_, eventName)
return function()
return Internal._EventCall(thisWidget, eventName)
end
end
return thisWidget
end
--[=[
@within Internal
@function _ContinueWidget
@param ID ID -- id of the widget.
@param widgetType string
@return Widget -- the widget.
Since the widget has already been created this frame, we can just add it back to the stack. There is no checking of
arguments or states.
Basically equivalent to the end of `Internal._Insert`.
]=]
function Internal._ContinueWidget(ID: Types.ID, widgetType: string)
local thisWidgetClass = Internal._widgets[widgetType]
local thisWidget = Internal._VDOM[ID]
if thisWidgetClass.hasChildren then
-- a parent widget so we increase our depth.
Internal._stackIndex += 1
Internal._IDStack[Internal._stackIndex] = thisWidget.ID
end
Internal._lastWidget = thisWidget
return thisWidget
end
--[=[
@within Internal
@function _DiscardWidget
@param widgetToDiscard Widget
Destroys the widget instance and updates any parent. This happens if the widget was not called in the
previous frame. There is no code which needs to update any widget tables since they are already reset
at the start before discarding happens.
]=]
function Internal._DiscardWidget(widgetToDiscard: Types.Widget)
local widgetParent = widgetToDiscard.parentWidget
if widgetParent then
-- if the parent needs to update it's children.
Internal._widgets[widgetParent.type].ChildDiscarded(widgetParent, widgetToDiscard)
end
-- using the widget class discard function.
Internal._widgets[widgetToDiscard.type].Discard(widgetToDiscard)
-- mark as discarded
widgetToDiscard.lastCycleTick = -1
end
--[=[
@within Internal
@function _widgetState
@param thisWidget Widget -- widget the state belongs to.
@param stateName string
@param initialValue any
@return State<any> -- the state for the widget.
Connects the state to the widget. If no state exists then a new one is created. Called for every state in every
widget if the user does not provide a state.
]=]
function Internal._widgetState<T>(thisWidget: Types.StateWidget, stateName: string, initialValue: T)
local ID = thisWidget.ID .. stateName
if Internal._states[ID] then
Internal._states[ID].ConnectedWidgets[thisWidget.ID] = thisWidget
Internal._states[ID].lastChangeTick = Internal._cycleTick
return Internal._states[ID]
else
local newState = {
ID = ID,
value = initialValue,
lastChangeTick = Internal._cycleTick,
ConnectedWidgets = { [thisWidget.ID] = thisWidget },
ConnectedFunctions = {},
} :: Types.State<T>
setmetatable(newState, Internal.StateClass)
Internal._states[ID] = newState
return newState
end
end
--[=[
@within Internal
@function _EventCall
@param thisWidget Widget
@param evetName string
@return boolean -- the value of the event.
A wrapper for any event on any widget. Automatically, Iris does not initialize events unless they are explicitly
called so in the first frame, the event connections are set up. Every event is a function which returns a boolean.
]=]
function Internal._EventCall(thisWidget: Types.Widget, eventName: string)
local Events = Internal._widgets[thisWidget.type].Events
local Event = Events[eventName]
assert(Event ~= nil, `widget {thisWidget.type} has no event of name {eventName}`)
if thisWidget.trackedEvents[eventName] == nil then
Event.Init(thisWidget)
thisWidget.trackedEvents[eventName] = true
end
return Event.Get(thisWidget)
end
--[=[
@within Internal
@function _GetParentWidget
@return Widget -- the parent widget
Returns the parent widget of the currently active widget, based on the stack depth.
]=]
function Internal._GetParentWidget(): Types.ParentWidget
return Internal._VDOM[Internal._IDStack[Internal._stackIndex]]
end
-- Generate
--[=[
@ignore
@within Internal
@function _generateEmptyVDOM
@return { [ID]: Widget }
Creates the VDOM at the start of each frame containing just the root instance.
]=]
function Internal._generateEmptyVDOM()
return {
["R"] = Internal._rootWidget,
}
end
--[=[
@ignore
@within Internal
@function _generateRootInstance
Creates the root instance.
]=]
function Internal._generateRootInstance()
-- unsafe to call before Internal.connect
Internal._rootInstance = Internal._widgets["Root"].Generate(Internal._widgets["Root"])
Internal._rootInstance.Parent = Internal.parentInstance
Internal._rootWidget.Instance = Internal._rootInstance
end
--[=[
@ignore
@within Internal
@function _generateSelctionImageObject
Creates the selection object for buttons.
]=]
function Internal._generateSelectionImageObject()
if Internal.SelectionImageObject then
Internal.SelectionImageObject:Destroy()
end
local SelectionImageObject = Instance.new("Frame")
SelectionImageObject.Position = UDim2.fromOffset(-1, -1)
SelectionImageObject.Size = UDim2.new(1, 2, 1, 2)
SelectionImageObject.BackgroundColor3 = Internal._config.SelectionImageObjectColor
SelectionImageObject.BackgroundTransparency = Internal._config.SelectionImageObjectTransparency
SelectionImageObject.BorderSizePixel = 0
Internal._utility.UIStroke(SelectionImageObject, 1, Internal._config.SelectionImageObjectBorderColor, Internal._config.SelectionImageObjectBorderTransparency)
Internal._utility.UICorner(SelectionImageObject, 2)
Internal.SelectionImageObject = SelectionImageObject
end
-- Utility
--[=[
@within Internal
@function _getID
@param levelsToIgnore number -- used to skip over internal calls to `_getID`.
@return ID
Generates a unique ID for each widget which is based on the line that the widget is
created from. This ensures that the function is heuristic and always returns the same
id for the same widget.
]=]
function Internal._getID(levelsToIgnore: number)
if Internal._nextWidgetId then
local ID = Internal._nextWidgetId
Internal._nextWidgetId = nil
return ID
end
local i = 1 + (levelsToIgnore or 1)
local ID = ""
local levelInfo = debug.info(i, "l")
while levelInfo ~= -1 and levelInfo ~= nil do
ID ..= "+" .. levelInfo
i += 1
levelInfo = debug.info(i, "l")
end
local discriminator = Internal._usedIDs[ID]
if discriminator then
Internal._usedIDs[ID] += 1
discriminator += 1
else
Internal._usedIDs[ID] = 1
discriminator = 1
end
if #Internal._pushedIds == 0 then
return ID .. ":" .. discriminator
elseif Internal._newID then
Internal._newID = false
return ID .. "::" .. table.concat(Internal._pushedIds, "\\")
else
return ID .. ":" .. discriminator .. ":" .. table.concat(Internal._pushedIds, "\\")
end
end
--[=[
@ignore
@within Internal
@function _deepCompare
@param t1 {}
@param t2 {}
@return boolean
Compares two tables to check if they are the same. It uses a recursive iteration through one table
to compare against the other. Used to determine if the arguments of a widget have changed since last
frame.
]=]
function Internal._deepCompare(t1: {}, t2: {})
-- unoptimized ?
for i, v1 in t1 do
local v2 = t2[i]
if type(v1) == "table" then
if v2 and type(v2) == "table" then
if Internal._deepCompare(v1, v2) == false then
return false
end
else
return false
end
else
if type(v1) ~= type(v2) or v1 ~= v2 then
return false
end
end
end
return true
end
--[=[
@ignore
@within Internal
@function _deepCopy
@param t {}
@return {}
Performs a deep copy of a table so that neither table contains a shared reference.
]=]
function Internal._deepCopy(t: {}): {}
local copy: {} = table.clone(t)
for k, v in t do
if type(v) == "table" then
copy[k] = Internal._deepCopy(v)
end
end
return copy
end
-- VDOM
Internal._lastVDOM = Internal._generateEmptyVDOM()
Internal._VDOM = Internal._generateEmptyVDOM()
Iris.Internal = Internal
Iris._config = Internal._config
return Internal
end
| 7,083 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/PubTypes.lua | local Types = require(script.Parent.Types)
export type ID = Types.ID
export type State<T> = Types.State<T>
export type Widget = Types.Widget
export type Root = Types.Root
export type Window = Types.Window
export type Tooltip = Types.Tooltip
export type MenuBar = Types.MenuBar
export type Menu = Types.Menu
export type MenuItem = Types.MenuItem
export type MenuToggle = Types.MenuToggle
export type Separator = Types.Separator
export type Indent = Types.Indent
export type SameLine = Types.SameLine
export type Group = Types.Group
export type Text = Types.Text
export type SeparatorText = Types.SeparatorText
export type Button = Types.Button
export type Checkbox = Types.Checkbox
export type RadioButton = Types.RadioButton
export type Image = Types.Image
export type ImageButton = Types.ImageButton
export type Tree = Types.Tree
export type CollapsingHeader = Types.CollapsingHeader
export type TabBar = Types.TabBar
export type Tab = Types.Tab
export type Input<T> = Types.Input<T>
export type InputColor3 = Types.InputColor3
export type InputColor4 = Types.InputColor4
export type InputEnum = Types.InputEnum
export type InputText = Types.InputText
export type Selectable = Types.Selectable
export type Combo = Types.Combo
export type ProgressBar = Types.ProgressBar
export type PlotLines = Types.PlotLines
export type PlotHistogram = Types.PlotHistogram
export type Table = Types.Table
export type Iris = Types.Iris
return {}
| 322 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/Types.lua | local WidgetTypes = require(script.Parent.WidgetTypes)
export type ID = WidgetTypes.ID
export type State<T> = WidgetTypes.State<T>
export type Hovered = WidgetTypes.Hovered
export type Clicked = WidgetTypes.Clicked
export type RightClicked = WidgetTypes.RightClicked
export type DoubleClicked = WidgetTypes.DoubleClicked
export type CtrlClicked = WidgetTypes.CtrlClicked
export type Active = WidgetTypes.Active
export type Checked = WidgetTypes.Checked
export type Unchecked = WidgetTypes.Unchecked
export type Opened = WidgetTypes.Opened
export type Closed = WidgetTypes.Closed
export type Collapsed = WidgetTypes.Collapsed
export type Uncollapsed = WidgetTypes.Uncollapsed
export type Selected = WidgetTypes.Selected
export type Unselected = WidgetTypes.Unselected
export type Changed = WidgetTypes.Changed
export type NumberChanged = WidgetTypes.NumberChanged
export type TextChanged = WidgetTypes.TextChanged
export type Widget = WidgetTypes.Widget
export type ParentWidget = WidgetTypes.ParentWidget
export type StateWidget = WidgetTypes.StateWidget
export type Root = WidgetTypes.Root
export type Window = WidgetTypes.Window
export type Tooltip = WidgetTypes.Tooltip
export type MenuBar = WidgetTypes.MenuBar
export type Menu = WidgetTypes.Menu
export type MenuItem = WidgetTypes.MenuItem
export type MenuToggle = WidgetTypes.MenuToggle
export type Separator = WidgetTypes.Separator
export type Indent = WidgetTypes.Indent
export type SameLine = WidgetTypes.SameLine
export type Group = WidgetTypes.Group
export type Text = WidgetTypes.Text
export type SeparatorText = WidgetTypes.SeparatorText
export type Button = WidgetTypes.Button
export type Checkbox = WidgetTypes.Checkbox
export type RadioButton = WidgetTypes.RadioButton
export type Image = WidgetTypes.Image
export type ImageButton = WidgetTypes.ImageButton
export type Tree = WidgetTypes.Tree
export type CollapsingHeader = WidgetTypes.CollapsingHeader
export type TabBar = WidgetTypes.TabBar
export type Tab = WidgetTypes.Tab
export type Input<T> = WidgetTypes.Input<T>
export type InputColor3 = WidgetTypes.InputColor3
export type InputColor4 = WidgetTypes.InputColor4
export type InputEnum = WidgetTypes.InputEnum
export type InputText = WidgetTypes.InputText
export type Selectable = WidgetTypes.Selectable
export type Combo = WidgetTypes.Combo
export type ProgressBar = WidgetTypes.ProgressBar
export type PlotLines = WidgetTypes.PlotLines
export type PlotHistogram = WidgetTypes.PlotHistogram
export type Table = WidgetTypes.Table
export type InputDataType = number | Vector2 | Vector3 | UDim | UDim2 | Color3 | Rect | { number }
export type Argument = any
export type Arguments = {
[string]: Argument,
Text: string,
TextHint: string,
TextOverlay: string,
ReadOnly: boolean,
MultiLine: boolean,
Wrapped: boolean,
Color: Color3,
RichText: boolean,
Increment: InputDataType,
Min: InputDataType,
Max: InputDataType,
Format: { string },
UseFloats: boolean,
UseHSV: boolean,
UseHex: boolean,
Prefix: { string },
BaseLine: number,
Width: number,
Height: number,
VerticalAlignment: Enum.VerticalAlignment,
HorizontalAlignment: Enum.HorizontalAlignment,
Index: any,
Image: string,
Size: UDim2,
Rect: Rect,
ScaleType: Enum.ScaleType,
TileSize: UDim2,
SliceCenter: Rect,
SliceScale: number,
ResampleMode: Enum.ResamplerMode,
SpanAvailWidth: boolean,
NoIdent: boolean,
NoClick: boolean,
NoButtons: boolean,
NoButton: boolean,
NoPreview: boolean,
NumColumns: number,
RowBg: boolean,
BordersOuter: boolean,
BordersInner: boolean,
Title: string,
NoTitleBar: boolean,
NoBackground: boolean,
NoCollapse: boolean,
NoClose: boolean,
NoMove: boolean,
NoScrollbar: boolean,
NoResize: boolean,
NoMenu: boolean,
KeyCode: Enum.KeyCode,
ModifierKey: Enum.ModifierKey,
Disabled: boolean,
}
export type States = {
[string]: State<any>,
number: State<number>,
color: State<Color3>,
transparency: State<number>,
editingText: State<boolean>,
index: State<any>,
size: State<Vector2>,
position: State<Vector2>,
progress: State<number>,
scrollDistance: State<number>,
isChecked: State<boolean>,
isOpened: State<boolean>,
isUncollapsed: State<boolean>,
}
export type Event = {
Init: (Widget) -> (),
Get: (Widget) -> boolean,
}
export type Events = { [string]: Event }
-- Widgets
export type WidgetArguments = { [number]: Argument }
export type WidgetStates = {
[string]: State<any>,
number: State<number>?,
color: State<Color3>?,
transparency: State<number>?,
editingText: State<boolean>?,
index: State<any>?,
size: State<Vector2>?,
position: State<Vector2>?,
progress: State<number>?,
scrollDistance: State<number>?,
values: State<number>?,
isChecked: State<boolean>?,
isOpened: State<boolean>?,
isUncollapsed: State<boolean>?,
}
export type WidgetClass = {
Generate: (thisWidget: Widget) -> GuiObject,
Discard: (thisWidget: Widget) -> (),
Update: (thisWidget: Widget, ...any) -> (),
Args: { [string]: number },
Events: Events,
hasChildren: boolean,
hasState: boolean,
ArgNames: { [number]: string },
GenerateState: (thisWidget: Widget) -> (),
UpdateState: (thisWidget: Widget) -> (),
ChildAdded: (thisWidget: Widget, thisChild: Widget) -> GuiObject,
ChildDiscarded: (thisWidget: Widget, thisChild: Widget) -> (),
}
-- Iris
export type Internal = {
--[[
--------------
PROPERTIES
--------------
]]
_version: string,
_started: boolean,
_shutdown: boolean,
_cycleTick: number,
_deltaTime: number,
_eventConnection: RBXScriptConnection?,
-- Refresh
_globalRefreshRequested: boolean,
_refreshCounter: number,
_refreshLevel: number,
_refreshStack: { boolean },
-- Widgets & Instances
_widgets: { [string]: WidgetClass },
_widgetCount: number,
_stackIndex: number,
_rootInstance: GuiObject?,
_rootWidget: ParentWidget,
_lastWidget: Widget,
SelectionImageObject: Frame,
parentInstance: BasePlayerGui | GuiBase2d,
_utility: WidgetUtility,
-- Config
_rootConfig: Config,
_config: Config,
-- ID
_IDStack: { ID },
_usedIDs: { [ID]: number },
_newID: boolean,
_pushedIds: { ID },
_nextWidgetId: ID?,
-- VDOM
_lastVDOM: { [ID]: Widget },
_VDOM: { [ID]: Widget },
-- State
_states: { [ID]: State<any> },
-- Callback
_postCycleCallbacks: { () -> () },
_connectedFunctions: { () -> () },
_connections: { RBXScriptConnection },
_initFunctions: { () -> () },
_cycleCoroutine: thread?,
--[[
---------
STATE
---------
]]
StateClass: {
__index: any,
get: <T>(self: State<T>) -> any,
set: <T>(self: State<T>, newValue: any) -> any,
onChange: <T>(self: State<T>, callback: (newValue: any) -> ()) -> (),
},
--[[
-------------
FUNCTIONS
-------------
]]
_cycle: (deltaTime: number) -> (),
_NoOp: () -> (),
-- Widget
WidgetConstructor: (type: string, widgetClass: WidgetClass) -> (),
_Insert: (widgetType: string, arguments: WidgetArguments?, states: WidgetStates?) -> Widget,
_GenNewWidget: (widgetType: string, arguments: Arguments, states: WidgetStates?, ID: ID) -> Widget,
_ContinueWidget: (ID: ID, widgetType: string) -> Widget,
_DiscardWidget: (widgetToDiscard: Widget) -> (),
_widgetState: (thisWidget: Widget, stateName: string, initialValue: any) -> State<any>,
_EventCall: (thisWidget: Widget, eventName: string) -> boolean,
_GetParentWidget: () -> ParentWidget,
SetFocusedWindow: (thisWidget: WidgetTypes.Window?) -> (),
-- Generate
_generateEmptyVDOM: () -> { [ID]: Widget },
_generateRootInstance: () -> (),
_generateSelectionImageObject: () -> (),
-- Utility
_getID: (levelsToIgnore: number) -> ID,
_deepCompare: (t1: {}, t2: {}) -> boolean,
_deepCopy: (t: {}) -> {},
}
export type WidgetUtility = {
GuiService: GuiService,
RunService: RunService,
TextService: TextService,
UserInputService: UserInputService,
ContextActionService: ContextActionService,
getTime: () -> number,
getMouseLocation: () -> Vector2,
ICONS: {
BLANK_SQUARE: string,
RIGHT_POINTING_TRIANGLE: string,
DOWN_POINTING_TRIANGLE: string,
MULTIPLICATION_SIGN: string,
BOTTOM_RIGHT_CORNER: string,
CHECKMARK: string,
BORDER: string,
ALPHA_BACKGROUND_TEXTURE: string,
UNKNOWN_TEXTURE: string,
},
GuiOffset: Vector2,
MouseOffset: Vector2,
findBestWindowPosForPopup: (refPos: Vector2, size: Vector2, outerMin: Vector2, outerMax: Vector2) -> Vector2,
getScreenSizeForWindow: (thisWidget: Widget) -> Vector2,
isPosInsideRect: (pos: Vector2, rectMin: Vector2, rectMax: Vector2) -> boolean,
extend: (superClass: WidgetClass, { [any]: any }) -> WidgetClass,
discardState: (thisWidget: Widget) -> (),
UIPadding: (Parent: GuiObject, PxPadding: Vector2) -> UIPadding,
UIListLayout: (Parent: GuiObject, FillDirection: Enum.FillDirection, Padding: UDim) -> UIListLayout,
UIStroke: (Parent: GuiObject, Thickness: number, Color: Color3, Transparency: number) -> UIStroke,
UICorner: (Parent: GuiObject, PxRounding: number?) -> UICorner,
UISizeConstraint: (Parent: GuiObject, MinSize: Vector2?, MaxSize: Vector2?) -> UISizeConstraint,
applyTextStyle: (thisInstance: TextLabel | TextButton | TextBox) -> (),
applyInteractionHighlights: (Property: string, Button: GuiButton, Highlightee: GuiObject, Colors: { [string]: any }) -> (),
applyInteractionHighlightsWithMultiHighlightee: (Property: string, Button: GuiButton, Highlightees: { { GuiObject | { [string]: Color3 | number } } }) -> (),
applyFrameStyle: (thisInstance: GuiObject, noPadding: boolean?, noCorner: boolean?) -> (),
applyButtonClick: (thisInstance: GuiButton, callback: () -> ()) -> (),
applyButtonDown: (thisInstance: GuiButton, callback: (x: number, y: number) -> ()) -> (),
applyMouseEnter: (thisInstance: GuiObject, callback: (x: number, y: number) -> ()) -> (),
applyMouseMoved: (thisInstance: GuiObject, callback: (x: number, y: number) -> ()) -> (),
applyMouseLeave: (thisInstance: GuiObject, callback: (x: number, y: number) -> ()) -> (),
applyInputBegan: (thisInstance: GuiObject, callback: (input: InputObject) -> ()) -> (),
applyInputEnded: (thisInstance: GuiObject, callback: (input: InputObject) -> ()) -> (),
registerEvent: (event: string, callback: (...any) -> ()) -> (),
EVENTS: {
hover: (pathToHovered: (thisWidget: Widget & Hovered) -> GuiObject) -> Event,
click: (pathToClicked: (thisWidget: Widget & Clicked) -> GuiButton) -> Event,
rightClick: (pathToClicked: (thisWidget: Widget & RightClicked) -> GuiButton) -> Event,
doubleClick: (pathToClicked: (thisWidget: Widget & DoubleClicked) -> GuiButton) -> Event,
ctrlClick: (pathToClicked: (thisWidget: Widget & CtrlClicked) -> GuiButton) -> Event,
},
abstractButton: WidgetClass,
}
export type Config = {
TextColor: Color3,
TextTransparency: number,
TextDisabledColor: Color3,
TextDisabledTransparency: number,
BorderColor: Color3,
BorderActiveColor: Color3,
BorderTransparency: number,
BorderActiveTransparency: number,
WindowBgColor: Color3,
WindowBgTransparency: number,
ScrollbarGrabColor: Color3,
ScrollbarGrabTransparency: number,
PopupBgColor: Color3,
PopupBgTransparency: number,
TitleBgColor: Color3,
TitleBgTransparency: number,
TitleBgActiveColor: Color3,
TitleBgActiveTransparency: number,
TitleBgCollapsedColor: Color3,
TitleBgCollapsedTransparency: number,
MenubarBgColor: Color3,
MenubarBgTransparency: number,
FrameBgColor: Color3,
FrameBgTransparency: number,
FrameBgHoveredColor: Color3,
FrameBgHoveredTransparency: number,
FrameBgActiveColor: Color3,
FrameBgActiveTransparency: number,
ButtonColor: Color3,
ButtonTransparency: number,
ButtonHoveredColor: Color3,
ButtonHoveredTransparency: number,
ButtonActiveColor: Color3,
ButtonActiveTransparency: number,
ImageColor: Color3,
ImageTransparency: number,
SliderGrabColor: Color3,
SliderGrabTransparency: number,
SliderGrabActiveColor: Color3,
SliderGrabActiveTransparency: number,
HeaderColor: Color3,
HeaderTransparency: number,
HeaderHoveredColor: Color3,
HeaderHoveredTransparency: number,
HeaderActiveColor: Color3,
HeaderActiveTransparency: number,
TabColor: Color3,
TabTransparency: number,
TabHoveredColor: Color3,
TabHoveredTransparency: number,
TabActiveColor: Color3,
TabActiveTransparency: number,
SelectionImageObjectColor: Color3,
SelectionImageObjectTransparency: number,
SelectionImageObjectBorderColor: Color3,
SelectionImageObjectBorderTransparency: number,
TableBorderStrongColor: Color3,
TableBorderStrongTransparency: number,
TableBorderLightColor: Color3,
TableBorderLightTransparency: number,
TableRowBgColor: Color3,
TableRowBgTransparency: number,
TableRowBgAltColor: Color3,
TableRowBgAltTransparency: number,
TableHeaderColor: Color3,
TableHeaderTransparency: number,
NavWindowingHighlightColor: Color3,
NavWindowingHighlightTransparency: number,
NavWindowingDimBgColor: Color3,
NavWindowingDimBgTransparency: number,
SeparatorColor: Color3,
SeparatorTransparency: number,
CheckMarkColor: Color3,
CheckMarkTransparency: number,
PlotLinesColor: Color3,
PlotLinesTransparency: number,
PlotLinesHoveredColor: Color3,
PlotLinesHoveredTransparency: number,
PlotHistogramColor: Color3,
PlotHistogramTransparency: number,
PlotHistogramHoveredColor: Color3,
PlotHistogramHoveredTransparency: number,
ResizeGripColor: Color3,
ResizeGripTransparency: number,
ResizeGripHoveredColor: Color3,
ResizeGripHoveredTransparency: number,
ResizeGripActiveColor: Color3,
ResizeGripActiveTransparency: number,
HoverColor: Color3,
HoverTransparency: number,
-- Sizes
ItemWidth: UDim,
ContentWidth: UDim,
ContentHeight: UDim,
WindowPadding: Vector2,
WindowResizePadding: Vector2,
FramePadding: Vector2,
ItemSpacing: Vector2,
ItemInnerSpacing: Vector2,
CellPadding: Vector2,
DisplaySafeAreaPadding: Vector2,
IndentSpacing: number,
SeparatorTextPadding: Vector2,
TextFont: Font,
TextSize: number,
FrameBorderSize: number,
FrameRounding: number,
GrabRounding: number,
WindowBorderSize: number,
WindowTitleAlign: Enum.LeftRight,
PopupBorderSize: number,
PopupRounding: number,
ScrollbarSize: number,
GrabMinSize: number,
SeparatorTextBorderSize: number,
ImageBorderSize: number,
UseScreenGUIs: boolean,
IgnoreGuiInset: boolean,
ScreenInsets: Enum.ScreenInsets,
Parent: BasePlayerGui,
RichText: boolean,
TextWrapped: boolean,
DisplayOrderOffset: number,
ZIndexOffset: number,
MouseDoubleClickTime: number,
MouseDoubleClickMaxDist: number,
MouseDragThreshold: number,
}
type WidgetCall<W, A, S, E...> = (arguments: A, states: S, E...) -> W
export type Iris = {
--[[
-----------
WIDGETS
-----------
]]
End: () -> (),
-- Window API
Window: WidgetCall<Window, WidgetArguments, WidgetStates?>,
Tooltip: WidgetCall<Tooltip, WidgetArguments, nil>,
-- Menu Widget API
MenuBar: () -> Widget,
Menu: WidgetCall<Menu, WidgetArguments, WidgetStates?>,
MenuItem: WidgetCall<MenuItem, WidgetArguments, nil>,
MenuToggle: WidgetCall<MenuToggle, WidgetArguments, WidgetStates?>,
-- Format Widget API
Separator: () -> Separator,
Indent: (arguments: WidgetArguments?) -> Indent,
SameLine: (arguments: WidgetArguments?) -> SameLine,
Group: () -> Group,
-- Text Widget API
Text: WidgetCall<Text, WidgetArguments, nil>,
TextWrapped: WidgetCall<Text, WidgetArguments, nil>,
TextColored: WidgetCall<Text, WidgetArguments, nil>,
SeparatorText: WidgetCall<SeparatorText, WidgetArguments, nil>,
InputText: WidgetCall<InputText, WidgetArguments, WidgetStates?>,
-- Basic Widget API
Button: WidgetCall<Button, WidgetArguments, nil>,
SmallButton: WidgetCall<Button, WidgetArguments, nil>,
Checkbox: WidgetCall<Checkbox, WidgetArguments, WidgetStates?>,
RadioButton: WidgetCall<RadioButton, WidgetArguments, WidgetStates?>,
-- Tree Widget API
Tree: WidgetCall<Tree, WidgetArguments, WidgetStates?>,
CollapsingHeader: WidgetCall<CollapsingHeader, WidgetArguments, WidgetStates?>,
-- Tab Widget API
TabBar: WidgetCall<TabBar, WidgetArguments?, WidgetStates?>,
Tab: WidgetCall<Tab, WidgetArguments, WidgetStates?>,
-- Input Widget API
InputNum: WidgetCall<Input<number>, WidgetArguments, WidgetStates?>,
InputVector2: WidgetCall<Input<Vector2>, WidgetArguments, WidgetStates?>,
InputVector3: WidgetCall<Input<Vector3>, WidgetArguments, WidgetStates?>,
InputUDim: WidgetCall<Input<UDim>, WidgetArguments, WidgetStates?>,
InputUDim2: WidgetCall<Input<UDim2>, WidgetArguments, WidgetStates?>,
InputRect: WidgetCall<Input<Rect>, WidgetArguments, WidgetStates?>,
InputColor3: WidgetCall<InputColor3, WidgetArguments, WidgetStates?>,
InputColor4: WidgetCall<InputColor4, WidgetArguments, WidgetStates?>,
-- Drag Widget API
DragNum: WidgetCall<Input<number>, WidgetArguments, WidgetStates?>,
DragVector2: WidgetCall<Input<Vector2>, WidgetArguments, WidgetStates?>,
DragVector3: WidgetCall<Input<Vector3>, WidgetArguments, WidgetStates?>,
DragUDim: WidgetCall<Input<UDim>, WidgetArguments, WidgetStates?>,
DragUDim2: WidgetCall<Input<UDim2>, WidgetArguments, WidgetStates?>,
DragRect: WidgetCall<Input<Rect>, WidgetArguments, WidgetStates?>,
-- Slider Widget API
SliderNum: WidgetCall<Input<number>, WidgetArguments, WidgetStates?>,
SliderVector2: WidgetCall<Input<Vector2>, WidgetArguments, WidgetStates?>,
SliderVector3: WidgetCall<Input<Vector3>, WidgetArguments, WidgetStates?>,
SliderUDim: WidgetCall<Input<UDim>, WidgetArguments, WidgetStates?>,
SliderUDim2: WidgetCall<Input<UDim2>, WidgetArguments, WidgetStates?>,
SliderRect: WidgetCall<Input<Rect>, WidgetArguments, WidgetStates?>,
-- Combo Widget Widget API
Selectable: WidgetCall<Selectable, WidgetArguments, WidgetStates?>,
Combo: WidgetCall<Combo, WidgetArguments, WidgetStates?>,
ComboArray: WidgetCall<Combo, WidgetArguments, WidgetStates?, { any }>,
ComboEnum: WidgetCall<Combo, WidgetArguments, WidgetStates?, Enum>,
InputEnum: WidgetCall<Combo, WidgetArguments, WidgetStates?, Enum>,
ProgressBar: WidgetCall<ProgressBar, WidgetArguments, WidgetStates?>,
PlotLines: WidgetCall<PlotLines, WidgetArguments, WidgetStates?>,
PlotHistogram: WidgetCall<PlotHistogram, WidgetArguments, WidgetStates?>,
Image: WidgetCall<Image, WidgetArguments, nil>,
ImageButton: WidgetCall<ImageButton, WidgetArguments, nil>,
-- Table Widget Api
Table: WidgetCall<Table, WidgetArguments, WidgetStates?>,
NextColumn: () -> number,
NextRow: () -> number,
SetColumnIndex: (index: number) -> (),
SetRowIndex: (index: number) -> (),
NextHeaderColumn: () -> number,
SetHeaderColumnIndex: (index: number) -> (),
SetColumnWidth: (index: number, width: number) -> (),
--[[
---------
STATE
---------
]]
State: <T>(initialValue: T) -> State<T>,
WeakState: <T>(initialValue: T) -> T,
VariableState: <T>(variable: T, callback: (T) -> ()) -> State<T>,
TableState: <K, V>(tab: { [K]: V }, key: K, callback: ((newValue: V) -> true?)?) -> State<V>,
ComputedState: <T, U>(firstState: State<T>, onChangeCallback: (firstValue: T) -> U) -> State<U>,
--[[
-------------
FUNCTIONS
-------------
]]
Init: (parentInstance: BasePlayerGui | GuiBase2d?, eventConnection: (RBXScriptSignal | (() -> number) | false)?, allowMultipleInits: boolean) -> Iris,
Shutdown: () -> (),
Connect: (self: Iris, callback: () -> ()) -> () -> (),
Append: (userInstance: GuiObject) -> (),
ForceRefresh: () -> (),
-- Widget
SetFocusedWindow: (thisWidget: Window?) -> (),
-- ID API
PushId: (ID: ID) -> (),
PopId: () -> (),
SetNextWidgetID: (ID: ID) -> (),
-- Config API
UpdateGlobalConfig: (deltaStyle: { [string]: any }) -> (),
PushConfig: (deltaStyle: { [string]: any }) -> (),
PopConfig: () -> (),
--[[
--------------
PROPERTIES
--------------
]]
Internal: Internal,
Disabled: boolean,
Args: { [string]: { [string]: number } },
Events: { [string]: () -> boolean },
TemplateConfig: { [string]: Config },
_config: Config,
ShowDemoWindow: () -> Window,
}
return {}
| 5,429 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/WidgetTypes.lua | --[=[
@within Iris
@type ID string
]=]
export type ID = string
--[=[
@within State
@type State<T> { ID: ID, value: T, get: (self) -> T, set: (self, newValue: T) -> T, onChange: (self, callback: (newValue: T) -> ()) -> (), ConnectedWidgets: { [ID]: Widget }, ConnectedFunctions: { (newValue: T) -> () } }
]=]
export type State<T> = {
ID: ID,
value: T,
lastChangeTick: number,
ConnectedWidgets: { [ID]: Widget },
ConnectedFunctions: { (newValue: T) -> () },
get: (self: State<T>) -> T,
set: (self: State<T>, newValue: T, force: true?) -> (),
onChange: (self: State<T>, funcToConnect: (newValue: T) -> ()) -> () -> (),
changed: (self: State<T>) -> boolean,
}
--[=[
@within Iris
@type Widget { ID: ID, type: string, lastCycleTick: number, parentWidget: Widget, Instance: GuiObject, ZIndex: number, arguments: { [string]: any }}
]=]
export type Widget = {
ID: ID,
type: string,
lastCycleTick: number,
trackedEvents: {},
parentWidget: ParentWidget,
arguments: {},
providedArguments: {},
Instance: GuiObject,
ZIndex: number,
}
export type ParentWidget = Widget & {
ChildContainer: GuiObject,
ZOffset: number,
ZUpdate: boolean,
}
export type StateWidget = Widget & {
state: {
[string]: State<any>,
},
}
-- Events
export type Hovered = {
isHoveredEvent: boolean,
hovered: () -> boolean,
}
export type Clicked = {
lastClickedTick: number,
clicked: () -> boolean,
}
export type RightClicked = {
lastRightClickedTick: number,
rightClicked: () -> boolean,
}
export type DoubleClicked = {
lastClickedTime: number,
lastClickedPosition: Vector2,
lastDoubleClickedTick: number,
doubleClicked: () -> boolean,
}
export type CtrlClicked = {
lastCtrlClickedTick: number,
ctrlClicked: () -> boolean,
}
export type Active = {
active: () -> boolean,
}
export type Checked = {
lastCheckedTick: number,
checked: () -> boolean,
}
export type Unchecked = {
lastUncheckedTick: number,
unchecked: () -> boolean,
}
export type Opened = {
lastOpenedTick: number,
opened: () -> boolean,
}
export type Closed = {
lastClosedTick: number,
closed: () -> boolean,
}
export type Collapsed = {
lastCollapsedTick: number,
collapsed: () -> boolean,
}
export type Uncollapsed = {
lastUncollapsedTick: number,
uncollapsed: () -> boolean,
}
export type Selected = {
lastSelectedTick: number,
selected: () -> boolean,
}
export type Unselected = {
lastUnselectedTick: number,
unselected: () -> boolean,
}
export type Changed = {
lastChangedTick: number,
changed: () -> boolean,
}
export type NumberChanged = {
lastNumberChangedTick: number,
numberChanged: () -> boolean,
}
export type TextChanged = {
lastTextChangedTick: number,
textChanged: () -> boolean,
}
-- Widgets
-- Window
export type Root = ParentWidget
export type Window = ParentWidget & {
usesScreenGuis: boolean,
arguments: {
Title: string?,
NoTitleBar: boolean?,
NoBackground: boolean?,
NoCollapse: boolean?,
NoClose: boolean?,
NoMove: boolean?,
NoScrollbar: boolean?,
NoResize: boolean?,
NoNav: boolean?,
NoMenu: boolean?,
},
state: {
size: State<Vector2>,
position: State<Vector2>,
isUncollapsed: State<boolean>,
isOpened: State<boolean>,
scrollDistance: State<number>,
},
} & Opened & Closed & Collapsed & Uncollapsed & Hovered
export type Tooltip = Widget & {
arguments: {
Text: string,
},
}
-- Menu
export type MenuBar = ParentWidget
export type Menu = ParentWidget & {
ButtonColors: { [string]: Color3 | number },
arguments: {
Text: string?,
},
state: {
isOpened: State<boolean>,
},
} & Clicked & Opened & Closed & Hovered
export type MenuItem = Widget & {
arguments: {
Text: string,
KeyCode: Enum.KeyCode?,
ModifierKey: Enum.ModifierKey?,
},
} & Clicked & Hovered
export type MenuToggle = Widget & {
arguments: {
Text: string,
KeyCode: Enum.KeyCode?,
ModifierKey: Enum.ModifierKey?,
},
state: {
isChecked: State<boolean>,
},
} & Checked & Unchecked & Hovered
-- Format
export type Separator = Widget
export type Indent = ParentWidget & {
arguments: {
Width: number?,
},
}
export type SameLine = ParentWidget & {
arguments: {
Width: number?,
VerticalAlignment: Enum.VerticalAlignment?,
HorizontalAlignment: Enum.HorizontalAlignment?,
},
}
export type Group = ParentWidget
-- Text
export type Text = Widget & {
arguments: {
Text: string,
Wrapped: boolean?,
Color: Color3?,
RichText: boolean?,
},
} & Hovered
export type SeparatorText = Widget & {
arguments: {
Text: string,
},
} & Hovered
-- Basic
export type Button = Widget & {
arguments: {
Text: string?,
Size: UDim2?,
},
} & Clicked & RightClicked & DoubleClicked & CtrlClicked & Hovered
export type Checkbox = Widget & {
arguments: {
Text: string?,
},
state: {
isChecked: State<boolean>,
},
} & Unchecked & Checked & Hovered
export type RadioButton = Widget & {
arguments: {
Text: string?,
Index: any,
},
state: {
index: State<any>,
},
active: () -> boolean,
} & Selected & Unselected & Active & Hovered
-- Image
export type Image = Widget & {
arguments: {
Image: string,
Size: UDim2,
Rect: Rect?,
ScaleType: Enum.ScaleType?,
TileSize: UDim2?,
SliceCenter: Rect?,
SliceScale: number?,
ResampleMode: Enum.ResamplerMode?,
},
} & Hovered
-- ooops, may have overriden a Roblox type, and then got a weird type message
-- let's just hope I don't have to use a Roblox ImageButton type anywhere by name in this file
export type ImageButton = Image & Clicked & RightClicked & DoubleClicked & CtrlClicked
-- Tree
export type Tree = CollapsingHeader & {
arguments: {
Text: string,
SpanAvailWidth: boolean?,
NoIndent: boolean?,
DefaultOpen: true?,
},
}
export type CollapsingHeader = ParentWidget & {
arguments: {
Text: string?,
DefaultOpen: true?,
},
state: {
isUncollapsed: State<boolean>,
},
} & Collapsed & Uncollapsed & Hovered
-- Tabs
export type TabBar = ParentWidget & {
Tabs: { Tab },
state: {
index: State<number>,
},
}
export type Tab = ParentWidget & {
parentWidget: TabBar,
Index: number,
ButtonColors: { [string]: Color3 | number },
arguments: {
Text: string,
Hideable: boolean,
},
state: {
index: State<number>,
isOpened: State<boolean>,
},
} & Clicked & Opened & Selected & Unselected & Active & Closed & Hovered
-- Input
export type Input<T> = Widget & {
lastClickedTime: number,
lastClickedPosition: Vector2,
arguments: {
Text: string?,
Increment: T,
Min: T,
Max: T,
Format: { string },
Prefix: { string },
NoButtons: boolean?,
},
state: {
number: State<T>,
editingText: State<number>,
},
} & NumberChanged & Hovered
export type InputColor3 = Input<{ number }> & {
arguments: {
UseFloats: boolean?,
UseHSV: boolean?,
},
state: {
color: State<Color3>,
editingText: State<boolean>,
},
} & NumberChanged & Hovered
export type InputColor4 = InputColor3 & {
state: {
transparency: State<number>,
},
}
export type InputEnum = Input<number> & {
state: {
enumItem: State<EnumItem>,
},
}
export type InputText = Widget & {
arguments: {
Text: string?,
TextHint: string?,
ReadOnly: boolean?,
MultiLine: boolean?,
},
state: {
text: State<string>,
},
} & TextChanged & Hovered
-- Combo
export type Selectable = Widget & {
ButtonColors: { [string]: Color3 | number },
arguments: {
Text: string?,
Index: any?,
NoClick: boolean?,
},
state: {
index: State<any>,
},
} & Selected & Unselected & Clicked & RightClicked & DoubleClicked & CtrlClicked & Hovered
export type Combo = ParentWidget & {
arguments: {
Text: string?,
NoButton: boolean?,
NoPreview: boolean?,
},
state: {
index: State<any>,
isOpened: State<boolean>,
},
UIListLayout: UIListLayout,
} & Opened & Closed & Changed & Clicked & Hovered
-- Plot
export type ProgressBar = Widget & {
arguments: {
Text: string?,
Format: string?,
},
state: {
progress: State<number>,
},
} & Changed & Hovered
export type PlotLines = Widget & {
Lines: { Frame },
HoveredLine: Frame | false,
Tooltip: TextLabel,
arguments: {
Text: string,
Height: number,
Min: number,
Max: number,
TextOverlay: string,
},
state: {
values: State<{ number }>,
hovered: State<{ number }?>,
},
} & Hovered
export type PlotHistogram = Widget & {
Blocks: { Frame },
HoveredBlock: Frame | false,
Tooltip: TextLabel,
arguments: {
Text: string,
Height: number,
Min: number,
Max: number,
TextOverlay: string,
BaseLine: number,
},
state: {
values: State<{ number }>,
hovered: State<number?>,
},
} & Hovered
export type Table = ParentWidget & {
_columnIndex: number,
_rowIndex: number,
_rowContainer: Frame,
_rowInstances: { Frame },
_cellInstances: { { Frame } },
_rowBorders: { Frame },
_columnBorders: { GuiButton },
_rowCycles: { number },
_widths: { UDim },
_minWidths: { number },
arguments: {
NumColumns: number,
Header: boolean,
RowBackground: boolean,
OuterBorders: boolean,
InnerBorders: boolean,
Resizable: boolean,
FixedWidth: boolean,
ProportionalWidth: boolean,
LimitTableWidth: boolean,
},
state: {
widths: State<{ number }>,
},
} & Hovered
return {}
| 2,630 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/config.lua | local TemplateConfig = {
colorDark = { -- Dear, ImGui default dark
TextColor = Color3.fromRGB(255, 255, 255),
TextTransparency = 0,
TextDisabledColor = Color3.fromRGB(128, 128, 128),
TextDisabledTransparency = 0,
-- Dear ImGui uses 110, 110, 125
-- The Roblox window selection highlight is 67, 191, 254
BorderColor = Color3.fromRGB(110, 110, 125),
BorderTransparency = 0.5,
BorderActiveColor = Color3.fromRGB(160, 160, 175), -- does not exist in Dear ImGui
BorderActiveTransparency = 0.3,
WindowBgColor = Color3.fromRGB(15, 15, 15),
WindowBgTransparency = 0.06,
PopupBgColor = Color3.fromRGB(20, 20, 20),
PopupBgTransparency = 0.06,
ScrollbarGrabColor = Color3.fromRGB(79, 79, 79),
ScrollbarGrabTransparency = 0,
TitleBgColor = Color3.fromRGB(10, 10, 10),
TitleBgTransparency = 0,
TitleBgActiveColor = Color3.fromRGB(41, 74, 122),
TitleBgActiveTransparency = 0,
TitleBgCollapsedColor = Color3.fromRGB(0, 0, 0),
TitleBgCollapsedTransparency = 0.5,
MenubarBgColor = Color3.fromRGB(36, 36, 36),
MenubarBgTransparency = 0,
FrameBgColor = Color3.fromRGB(41, 74, 122),
FrameBgTransparency = 0.46,
FrameBgHoveredColor = Color3.fromRGB(66, 150, 250),
FrameBgHoveredTransparency = 0.46,
FrameBgActiveColor = Color3.fromRGB(66, 150, 250),
FrameBgActiveTransparency = 0.33,
ButtonColor = Color3.fromRGB(66, 150, 250),
ButtonTransparency = 0.6,
ButtonHoveredColor = Color3.fromRGB(66, 150, 250),
ButtonHoveredTransparency = 0,
ButtonActiveColor = Color3.fromRGB(15, 135, 250),
ButtonActiveTransparency = 0,
ImageColor = Color3.fromRGB(255, 255, 255),
ImageTransparency = 0,
SliderGrabColor = Color3.fromRGB(66, 150, 250),
SliderGrabTransparency = 0,
SliderGrabActiveColor = Color3.fromRGB(66, 150, 250),
SliderGrabActiveTransparency = 0,
HeaderColor = Color3.fromRGB(66, 150, 250),
HeaderTransparency = 0.69,
HeaderHoveredColor = Color3.fromRGB(66, 150, 250),
HeaderHoveredTransparency = 0.2,
HeaderActiveColor = Color3.fromRGB(66, 150, 250),
HeaderActiveTransparency = 0,
TabColor = Color3.fromRGB(46, 89, 148),
TabTransparency = 0.14,
TabHoveredColor = Color3.fromRGB(66, 150, 250),
TabHoveredTransparency = 0.2,
TabActiveColor = Color3.fromRGB(51, 105, 173),
TabActiveTransparency = 0,
SelectionImageObjectColor = Color3.fromRGB(255, 255, 255),
SelectionImageObjectTransparency = 0.8,
SelectionImageObjectBorderColor = Color3.fromRGB(255, 255, 255),
SelectionImageObjectBorderTransparency = 0,
TableBorderStrongColor = Color3.fromRGB(79, 79, 89),
TableBorderStrongTransparency = 0,
TableBorderLightColor = Color3.fromRGB(59, 59, 64),
TableBorderLightTransparency = 0,
TableRowBgColor = Color3.fromRGB(0, 0, 0),
TableRowBgTransparency = 1,
TableRowBgAltColor = Color3.fromRGB(255, 255, 255),
TableRowBgAltTransparency = 0.94,
TableHeaderColor = Color3.fromRGB(48, 48, 51),
TableHeaderTransparency = 0,
NavWindowingHighlightColor = Color3.fromRGB(255, 255, 255),
NavWindowingHighlightTransparency = 0.3,
NavWindowingDimBgColor = Color3.fromRGB(204, 204, 204),
NavWindowingDimBgTransparency = 0.65,
SeparatorColor = Color3.fromRGB(110, 110, 128),
SeparatorTransparency = 0.5,
CheckMarkColor = Color3.fromRGB(66, 150, 250),
CheckMarkTransparency = 0,
PlotLinesColor = Color3.fromRGB(156, 156, 156),
PlotLinesTransparency = 0,
PlotLinesHoveredColor = Color3.fromRGB(255, 110, 89),
PlotLinesHoveredTransparency = 0,
PlotHistogramColor = Color3.fromRGB(230, 179, 0),
PlotHistogramTransparency = 0,
PlotHistogramHoveredColor = Color3.fromRGB(255, 153, 0),
PlotHistogramHoveredTransparency = 0,
ResizeGripColor = Color3.fromRGB(66, 150, 250),
ResizeGripTransparency = 0.8,
ResizeGripHoveredColor = Color3.fromRGB(66, 150, 250),
ResizeGripHoveredTransparency = 0.33,
ResizeGripActiveColor = Color3.fromRGB(66, 150, 250),
ResizeGripActiveTransparency = 0.05,
},
colorLight = { -- Dear, ImGui default light
TextColor = Color3.fromRGB(0, 0, 0),
TextTransparency = 0,
TextDisabledColor = Color3.fromRGB(153, 153, 153),
TextDisabledTransparency = 0,
-- Dear ImGui uses 0, 0, 0, 77
-- The Roblox window selection highlight is 67, 191, 254
BorderColor = Color3.fromRGB(64, 64, 64),
BorderActiveColor = Color3.fromRGB(64, 64, 64), -- does not exist in Dear ImGui
-- BorderTransparency will be problematic for non UIStroke border implimentations
-- will not be implimented because of this
BorderTransparency = 0.5,
BorderActiveTransparency = 0.2,
WindowBgColor = Color3.fromRGB(240, 240, 240),
WindowBgTransparency = 0,
PopupBgColor = Color3.fromRGB(255, 255, 255),
PopupBgTransparency = 0.02,
TitleBgColor = Color3.fromRGB(245, 245, 245),
TitleBgTransparency = 0,
TitleBgActiveColor = Color3.fromRGB(209, 209, 209),
TitleBgActiveTransparency = 0,
TitleBgCollapsedColor = Color3.fromRGB(255, 255, 255),
TitleBgCollapsedTransparency = 0.5,
MenubarBgColor = Color3.fromRGB(219, 219, 219),
MenubarBgTransparency = 0,
ScrollbarGrabColor = Color3.fromRGB(176, 176, 176),
ScrollbarGrabTransparency = 0.2,
FrameBgColor = Color3.fromRGB(255, 255, 255),
FrameBgTransparency = 0.6,
FrameBgHoveredColor = Color3.fromRGB(66, 150, 250),
FrameBgHoveredTransparency = 0.6,
FrameBgActiveColor = Color3.fromRGB(66, 150, 250),
FrameBgActiveTransparency = 0.33,
ButtonColor = Color3.fromRGB(66, 150, 250),
ButtonTransparency = 0.6,
ButtonHoveredColor = Color3.fromRGB(66, 150, 250),
ButtonHoveredTransparency = 0,
ButtonActiveColor = Color3.fromRGB(15, 135, 250),
ButtonActiveTransparency = 0,
ImageColor = Color3.fromRGB(255, 255, 255),
ImageTransparency = 0,
HeaderColor = Color3.fromRGB(66, 150, 250),
HeaderTransparency = 0.31,
HeaderHoveredColor = Color3.fromRGB(66, 150, 250),
HeaderHoveredTransparency = 0.2,
HeaderActiveColor = Color3.fromRGB(66, 150, 250),
HeaderActiveTransparency = 0,
TabColor = Color3.fromRGB(195, 203, 213),
TabTransparency = 0.07,
TabHoveredColor = Color3.fromRGB(66, 150, 250),
TabHoveredTransparency = 0.2,
TabActiveColor = Color3.fromRGB(152, 186, 255),
TabActiveTransparency = 0,
SliderGrabColor = Color3.fromRGB(61, 133, 224),
SliderGrabTransparency = 0,
SliderGrabActiveColor = Color3.fromRGB(117, 138, 204),
SliderGrabActiveTransparency = 0,
SelectionImageObjectColor = Color3.fromRGB(0, 0, 0),
SelectionImageObjectTransparency = 0.8,
SelectionImageObjectBorderColor = Color3.fromRGB(0, 0, 0),
SelectionImageObjectBorderTransparency = 0,
TableBorderStrongColor = Color3.fromRGB(145, 145, 163),
TableBorderStrongTransparency = 0,
TableBorderLightColor = Color3.fromRGB(173, 173, 189),
TableBorderLightTransparency = 0,
TableRowBgColor = Color3.fromRGB(0, 0, 0),
TableRowBgTransparency = 1,
TableRowBgAltColor = Color3.fromRGB(77, 77, 77),
TableRowBgAltTransparency = 0.91,
TableHeaderColor = Color3.fromRGB(199, 222, 250),
TableHeaderTransparency = 0,
NavWindowingHighlightColor = Color3.fromRGB(179, 179, 179),
NavWindowingHighlightTransparency = 0.3,
NavWindowingDimBgColor = Color3.fromRGB(51, 51, 51),
NavWindowingDimBgTransparency = 0.8,
SeparatorColor = Color3.fromRGB(99, 99, 99),
SeparatorTransparency = 0.38,
CheckMarkColor = Color3.fromRGB(66, 150, 250),
CheckMarkTransparency = 0,
PlotLinesColor = Color3.fromRGB(99, 99, 99),
PlotLinesTransparency = 0,
PlotLinesHoveredColor = Color3.fromRGB(255, 110, 89),
PlotLinesHoveredTransparency = 0,
PlotHistogramColor = Color3.fromRGB(230, 179, 0),
PlotHistogramTransparency = 0,
PlotHistogramHoveredColor = Color3.fromRGB(255, 153, 0),
PlotHistogramHoveredTransparency = 0,
ResizeGripColor = Color3.fromRGB(89, 89, 89),
ResizeGripTransparency = 0.83,
ResizeGripHoveredColor = Color3.fromRGB(66, 150, 250),
ResizeGripHoveredTransparency = 0.33,
ResizeGripActiveColor = Color3.fromRGB(66, 150, 250),
ResizeGripActiveTransparency = 0.05,
},
sizeDefault = { -- Dear, ImGui default
ItemWidth = UDim.new(1, 0),
ContentWidth = UDim.new(0.65, 0),
ContentHeight = UDim.new(0, 0),
WindowPadding = Vector2.new(8, 8),
WindowResizePadding = Vector2.new(6, 6),
FramePadding = Vector2.new(4, 3),
ItemSpacing = Vector2.new(8, 4),
ItemInnerSpacing = Vector2.new(4, 4),
CellPadding = Vector2.new(4, 2),
DisplaySafeAreaPadding = Vector2.new(0, 0),
SeparatorTextPadding = Vector2.new(20, 3),
IndentSpacing = 21,
TextFont = Font.fromEnum(Enum.Font.Code),
TextSize = 13,
FrameBorderSize = 0,
FrameRounding = 0,
GrabRounding = 0,
WindowRounding = 0, -- these don't actually work but it's nice to have them.
WindowBorderSize = 1,
WindowTitleAlign = Enum.LeftRight.Left,
PopupBorderSize = 1,
PopupRounding = 0,
ScrollbarSize = 7,
GrabMinSize = 10,
SeparatorTextBorderSize = 3,
ImageBorderSize = 2,
},
sizeClear = { -- easier to read and manuveure
ItemWidth = UDim.new(1, 0),
ContentWidth = UDim.new(0.65, 0),
ContentHeight = UDim.new(0, 0),
WindowPadding = Vector2.new(12, 8),
WindowResizePadding = Vector2.new(8, 8),
FramePadding = Vector2.new(6, 4),
ItemSpacing = Vector2.new(8, 8),
ItemInnerSpacing = Vector2.new(8, 8),
CellPadding = Vector2.new(4, 4),
DisplaySafeAreaPadding = Vector2.new(8, 8),
SeparatorTextPadding = Vector2.new(24, 6),
IndentSpacing = 25,
TextFont = Font.fromEnum(Enum.Font.Ubuntu),
TextSize = 15,
FrameBorderSize = 1,
FrameRounding = 4,
GrabRounding = 4,
WindowRounding = 4,
WindowBorderSize = 1,
WindowTitleAlign = Enum.LeftRight.Center,
PopupBorderSize = 1,
PopupRounding = 4,
ScrollbarSize = 9,
GrabMinSize = 14,
SeparatorTextBorderSize = 4,
ImageBorderSize = 4,
},
utilityDefault = {
UseScreenGUIs = true,
IgnoreGuiInset = false,
ScreenInsets = Enum.ScreenInsets.CoreUISafeInsets,
Parent = nil,
RichText = false,
TextWrapped = false,
DisplayOrderOffset = 127,
ZIndexOffset = 0,
MouseDoubleClickTime = 0.30, -- Time for a double-click, in seconds.
MouseDoubleClickMaxDist = 6.0, -- Distance threshold to stay in to validate a double-click, in pixels.
HoverColor = Color3.fromRGB(255, 255, 0),
HoverTransparency = 0.1,
},
}
return TemplateConfig
| 3,445 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Button.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local abstractButton = {
hasState = false,
hasChildren = false,
Args = {
["Text"] = 1,
["Size"] = 2,
},
Events = {
["clicked"] = widgets.EVENTS.click(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["rightClicked"] = widgets.EVENTS.rightClick(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["doubleClicked"] = widgets.EVENTS.doubleClick(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["ctrlClicked"] = widgets.EVENTS.ctrlClick(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(_thisWidget: Types.Button)
local Button = Instance.new("TextButton")
Button.AutomaticSize = Enum.AutomaticSize.XY
Button.Size = UDim2.fromOffset(0, 0)
Button.BackgroundColor3 = Iris._config.ButtonColor
Button.BackgroundTransparency = Iris._config.ButtonTransparency
Button.AutoButtonColor = false
widgets.applyTextStyle(Button)
Button.TextXAlignment = Enum.TextXAlignment.Center
widgets.applyFrameStyle(Button)
widgets.applyInteractionHighlights("Background", Button, Button, {
Color = Iris._config.ButtonColor,
Transparency = Iris._config.ButtonTransparency,
HoveredColor = Iris._config.ButtonHoveredColor,
HoveredTransparency = Iris._config.ButtonHoveredTransparency,
ActiveColor = Iris._config.ButtonActiveColor,
ActiveTransparency = Iris._config.ButtonActiveTransparency,
})
return Button
end,
Update = function(thisWidget: Types.Button)
local Button = thisWidget.Instance :: TextButton
Button.Text = thisWidget.arguments.Text or "Button"
Button.Size = thisWidget.arguments.Size or UDim2.fromOffset(0, 0)
end,
Discard = function(thisWidget: Types.Button)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass
widgets.abstractButton = abstractButton
--stylua: ignore
Iris.WidgetConstructor("Button", widgets.extend(abstractButton, {
Generate = function(thisWidget: Types.Button)
local Button = abstractButton.Generate(thisWidget)
Button.Name = "Iris_Button"
return Button
end,
} :: Types.WidgetClass)
)
--stylua: ignore
Iris.WidgetConstructor("SmallButton", widgets.extend(abstractButton, {
Generate = function(thisWidget: Types.Button)
local SmallButton = abstractButton.Generate(thisWidget)
SmallButton.Name = "Iris_SmallButton"
local uiPadding: UIPadding = SmallButton.UIPadding
uiPadding.PaddingLeft = UDim.new(0, 2)
uiPadding.PaddingRight = UDim.new(0, 2)
uiPadding.PaddingTop = UDim.new(0, 0)
uiPadding.PaddingBottom = UDim.new(0, 0)
return SmallButton
end,
} :: Types.WidgetClass)
)
end
| 707 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Checkbox.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
--stylua: ignore
Iris.WidgetConstructor("Checkbox", {
hasState = true,
hasChildren = false,
Args = {
["Text"] = 1,
},
Events = {
["checked"] = {
["Init"] = function(_thisWidget: Types.Checkbox) end,
["Get"] = function(thisWidget: Types.Checkbox)
return thisWidget.lastCheckedTick == Iris._cycleTick
end,
},
["unchecked"] = {
["Init"] = function(_thisWidget: Types.Checkbox) end,
["Get"] = function(thisWidget: Types.Checkbox)
return thisWidget.lastUncheckedTick == Iris._cycleTick
end,
},
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(thisWidget: Types.Checkbox)
local Checkbox = Instance.new("TextButton")
Checkbox.Name = "Iris_Checkbox"
Checkbox.AutomaticSize = Enum.AutomaticSize.XY
Checkbox.Size = UDim2.fromOffset(0, 0)
Checkbox.BackgroundTransparency = 1
Checkbox.BorderSizePixel = 0
Checkbox.Text = ""
Checkbox.AutoButtonColor = false
widgets.UIListLayout(Checkbox, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
local checkboxSize = Iris._config.TextSize + 2 * Iris._config.FramePadding.Y
local Box = Instance.new("Frame")
Box.Name = "Box"
Box.Size = UDim2.fromOffset(checkboxSize, checkboxSize)
Box.BackgroundColor3 = Iris._config.FrameBgColor
Box.BackgroundTransparency = Iris._config.FrameBgTransparency
widgets.applyFrameStyle(Box, true)
widgets.UIPadding(Box, Vector2.new(math.floor(checkboxSize / 10), math.floor(checkboxSize / 10)))
widgets.applyInteractionHighlights("Background", Checkbox, Box, {
Color = Iris._config.FrameBgColor,
Transparency = Iris._config.FrameBgTransparency,
HoveredColor = Iris._config.FrameBgHoveredColor,
HoveredTransparency = Iris._config.FrameBgHoveredTransparency,
ActiveColor = Iris._config.FrameBgActiveColor,
ActiveTransparency = Iris._config.FrameBgActiveTransparency,
})
Box.Parent = Checkbox
local Checkmark = Instance.new("ImageLabel")
Checkmark.Name = "Checkmark"
Checkmark.Size = UDim2.fromScale(1, 1)
Checkmark.BackgroundTransparency = 1
Checkmark.Image = widgets.ICONS.CHECKMARK
Checkmark.ImageColor3 = Iris._config.CheckMarkColor
Checkmark.ImageTransparency = 1
Checkmark.ScaleType = Enum.ScaleType.Fit
Checkmark.Parent = Box
widgets.applyButtonClick(Checkbox, function()
thisWidget.state.isChecked:set(not thisWidget.state.isChecked.value)
end)
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.LayoutOrder = 1
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = Checkbox
return Checkbox
end,
GenerateState = function(thisWidget: Types.Checkbox)
if thisWidget.state.isChecked == nil then
thisWidget.state.isChecked = Iris._widgetState(thisWidget, "checked", false)
end
end,
Update = function(thisWidget: Types.Checkbox)
local Checkbox = thisWidget.Instance :: TextButton
Checkbox.TextLabel.Text = thisWidget.arguments.Text or "Checkbox"
end,
UpdateState = function(thisWidget: Types.Checkbox)
local Checkbox = thisWidget.Instance :: TextButton
local Box = Checkbox.Box :: Frame
local Checkmark: ImageLabel = Box.Checkmark
if thisWidget.state.isChecked.value then
Checkmark.ImageTransparency = Iris._config.CheckMarkTransparency
thisWidget.lastCheckedTick = Iris._cycleTick + 1
else
Checkmark.ImageTransparency = 1
thisWidget.lastUncheckedTick = Iris._cycleTick + 1
end
end,
Discard = function(thisWidget: Types.Checkbox)
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
end
| 994 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Combo.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
--stylua: ignore
Iris.WidgetConstructor("Selectable", {
hasState = true,
hasChildren = false,
Args = {
["Text"] = 1,
["Index"] = 2,
["NoClick"] = 3,
},
Events = {
["selected"] = {
["Init"] = function(_thisWidget: Types.Selectable) end,
["Get"] = function(thisWidget: Types.Selectable)
return thisWidget.lastSelectedTick == Iris._cycleTick
end,
},
["unselected"] = {
["Init"] = function(_thisWidget: Types.Selectable) end,
["Get"] = function(thisWidget: Types.Selectable)
return thisWidget.lastUnselectedTick == Iris._cycleTick
end,
},
["active"] = {
["Init"] = function(_thisWidget: Types.Selectable) end,
["Get"] = function(thisWidget: Types.Selectable)
return thisWidget.state.index.value == thisWidget.arguments.Index
end,
},
["clicked"] = widgets.EVENTS.click(function(thisWidget: Types.Widget)
local Selectable = thisWidget.Instance :: Frame
return Selectable.SelectableButton
end),
["rightClicked"] = widgets.EVENTS.rightClick(function(thisWidget: Types.Widget)
local Selectable = thisWidget.Instance :: Frame
return Selectable.SelectableButton
end),
["doubleClicked"] = widgets.EVENTS.doubleClick(function(thisWidget: Types.Widget)
local Selectable = thisWidget.Instance :: Frame
return Selectable.SelectableButton
end),
["ctrlClicked"] = widgets.EVENTS.ctrlClick(function(thisWidget: Types.Widget)
local Selectable = thisWidget.Instance :: Frame
return Selectable.SelectableButton
end),
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
local Selectable = thisWidget.Instance :: Frame
return Selectable.SelectableButton
end),
},
Generate = function(thisWidget: Types.Selectable)
local Selectable = Instance.new("Frame")
Selectable.Name = "Iris_Selectable"
Selectable.Size = UDim2.new(Iris._config.ItemWidth, UDim.new(0, Iris._config.TextSize + 2 * Iris._config.FramePadding.Y - Iris._config.ItemSpacing.Y))
Selectable.BackgroundTransparency = 1
Selectable.BorderSizePixel = 0
local SelectableButton = Instance.new("TextButton")
SelectableButton.Name = "SelectableButton"
SelectableButton.Size = UDim2.new(1, 0, 0, Iris._config.TextSize + 2 * Iris._config.FramePadding.Y)
SelectableButton.Position = UDim2.fromOffset(0, -bit32.rshift(Iris._config.ItemSpacing.Y, 1)) -- divide by 2
SelectableButton.BackgroundColor3 = Iris._config.HeaderColor
SelectableButton.ClipsDescendants = true
widgets.applyFrameStyle(SelectableButton)
widgets.applyTextStyle(SelectableButton)
widgets.UISizeConstraint(SelectableButton, Vector2.xAxis)
thisWidget.ButtonColors = {
Color = Iris._config.HeaderColor,
Transparency = 1,
HoveredColor = Iris._config.HeaderHoveredColor,
HoveredTransparency = Iris._config.HeaderHoveredTransparency,
ActiveColor = Iris._config.HeaderActiveColor,
ActiveTransparency = Iris._config.HeaderActiveTransparency,
}
widgets.applyInteractionHighlights("Background", SelectableButton, SelectableButton, thisWidget.ButtonColors)
widgets.applyButtonClick(SelectableButton, function()
if thisWidget.arguments.NoClick ~= true then
if type(thisWidget.state.index.value) == "boolean" then
thisWidget.state.index:set(not thisWidget.state.index.value)
else
thisWidget.state.index:set(thisWidget.arguments.Index)
end
end
end)
SelectableButton.Parent = Selectable
return Selectable
end,
GenerateState = function(thisWidget: Types.Selectable)
if thisWidget.state.index == nil then
if thisWidget.arguments.Index ~= nil then
error("A shared state index is required for Iris.Selectables() with an Index argument.", 5)
end
thisWidget.state.index = Iris._widgetState(thisWidget, "index", false)
end
end,
Update = function(thisWidget: Types.Selectable)
local Selectable = thisWidget.Instance :: Frame
local SelectableButton: TextButton = Selectable.SelectableButton
SelectableButton.Text = thisWidget.arguments.Text or "Selectable"
end,
UpdateState = function(thisWidget: Types.Selectable)
local Selectable = thisWidget.Instance :: Frame
local SelectableButton: TextButton = Selectable.SelectableButton
if thisWidget.state.index.value == thisWidget.arguments.Index or thisWidget.state.index.value == true then
thisWidget.ButtonColors.Transparency = Iris._config.HeaderTransparency
SelectableButton.BackgroundTransparency = Iris._config.HeaderTransparency
thisWidget.lastSelectedTick = Iris._cycleTick + 1
else
thisWidget.ButtonColors.Transparency = 1
SelectableButton.BackgroundTransparency = 1
thisWidget.lastUnselectedTick = Iris._cycleTick + 1
end
end,
Discard = function(thisWidget: Types.Selectable)
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
local AnyOpenedCombo = false
local ComboOpenedTick = -1
local OpenedCombo: Types.Combo? = nil
local CachedContentSize = 0
local function UpdateChildContainerTransform(thisWidget: Types.Combo)
local Combo = thisWidget.Instance :: Frame
local PreviewContainer = Combo.PreviewContainer :: TextButton
local ChildContainer = thisWidget.ChildContainer :: ScrollingFrame
local previewPosition = PreviewContainer.AbsolutePosition - widgets.GuiOffset
local previewSize = PreviewContainer.AbsoluteSize
local borderSize = Iris._config.PopupBorderSize
local screenSize: Vector2 = ChildContainer.Parent.AbsoluteSize
local absoluteContentSize = thisWidget.UIListLayout.AbsoluteContentSize.Y
CachedContentSize = absoluteContentSize
local contentsSize = absoluteContentSize + 2 * Iris._config.WindowPadding.Y
local x = previewPosition.X
local y = previewPosition.Y + previewSize.Y + borderSize
local anchor = Vector2.zero
local distanceToScreen = screenSize.Y - y
-- Only extend upwards if we cannot fully extend downwards, and we are on the bottom half of the screen.
-- i.e. there is more space upwards than there is downwards.
if contentsSize > distanceToScreen and y > (screenSize.Y / 2) then
y = previewPosition.Y - borderSize
anchor = Vector2.yAxis
distanceToScreen = y -- from 0 to the current position
end
ChildContainer.AnchorPoint = anchor
ChildContainer.Position = UDim2.fromOffset(x, y)
local height = math.min(contentsSize, distanceToScreen)
ChildContainer.Size = UDim2.fromOffset(PreviewContainer.AbsoluteSize.X, height)
end
table.insert(Iris._postCycleCallbacks, function()
if AnyOpenedCombo and OpenedCombo then
local contentSize = OpenedCombo.UIListLayout.AbsoluteContentSize.Y
if contentSize ~= CachedContentSize then
UpdateChildContainerTransform(OpenedCombo)
end
end
end)
local function UpdateComboState(input: InputObject)
if not Iris._started then
return
end
if input.UserInputType ~= Enum.UserInputType.MouseButton1 and input.UserInputType ~= Enum.UserInputType.MouseButton2 and input.UserInputType ~= Enum.UserInputType.Touch and input.UserInputType ~= Enum.UserInputType.MouseWheel then
return
end
if AnyOpenedCombo == false or not OpenedCombo then
return
end
if ComboOpenedTick == Iris._cycleTick then
return
end
local MouseLocation = widgets.getMouseLocation()
local Combo = OpenedCombo.Instance :: Frame
local PreviewContainer: TextButton = Combo.PreviewContainer
local ChildContainer = OpenedCombo.ChildContainer
local rectMin = PreviewContainer.AbsolutePosition - widgets.GuiOffset
local rectMax = PreviewContainer.AbsolutePosition - widgets.GuiOffset + PreviewContainer.AbsoluteSize
if widgets.isPosInsideRect(MouseLocation, rectMin, rectMax) then
return
end
rectMin = ChildContainer.AbsolutePosition - widgets.GuiOffset
rectMax = ChildContainer.AbsolutePosition - widgets.GuiOffset + ChildContainer.AbsoluteSize
if widgets.isPosInsideRect(MouseLocation, rectMin, rectMax) then
return
end
OpenedCombo.state.isOpened:set(false)
end
widgets.registerEvent("InputBegan", UpdateComboState)
widgets.registerEvent("InputChanged", UpdateComboState)
--stylua: ignore
Iris.WidgetConstructor("Combo", {
hasState = true,
hasChildren = true,
Args = {
["Text"] = 1,
["NoButton"] = 2,
["NoPreview"] = 3,
},
Events = {
["opened"] = {
["Init"] = function(_thisWidget: Types.Combo) end,
["Get"] = function(thisWidget: Types.Combo)
return thisWidget.lastOpenedTick == Iris._cycleTick
end,
},
["closed"] = {
["Init"] = function(_thisWidget: Types.Combo) end,
["Get"] = function(thisWidget: Types.Combo)
return thisWidget.lastClosedTick == Iris._cycleTick
end,
},
["changed"] = {
["Init"] = function(_thisWidget: Types.Combo) end,
["Get"] = function(thisWidget: Types.Combo)
return thisWidget.lastChangedTick == Iris._cycleTick
end,
},
["clicked"] = widgets.EVENTS.click(function(thisWidget: Types.Widget)
local Combo = thisWidget.Instance :: Frame
return Combo.PreviewContainer
end),
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(thisWidget: Types.Combo)
local frameHeight = Iris._config.TextSize + 2 * Iris._config.FramePadding.Y
local Combo = Instance.new("Frame")
Combo.Name = "Iris_Combo"
Combo.AutomaticSize = Enum.AutomaticSize.Y
Combo.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
Combo.BackgroundTransparency = 1
Combo.BorderSizePixel = 0
widgets.UIListLayout(Combo, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
local PreviewContainer = Instance.new("TextButton")
PreviewContainer.Name = "PreviewContainer"
PreviewContainer.AutomaticSize = Enum.AutomaticSize.Y
PreviewContainer.Size = UDim2.new(Iris._config.ContentWidth, UDim.new(0, 0))
PreviewContainer.BackgroundTransparency = 1
PreviewContainer.Text = ""
PreviewContainer.AutoButtonColor = false
PreviewContainer.ZIndex = 2
widgets.applyFrameStyle(PreviewContainer, true)
widgets.UIListLayout(PreviewContainer, Enum.FillDirection.Horizontal, UDim.new(0, 0))
widgets.UISizeConstraint(PreviewContainer, Vector2.new(frameHeight))
PreviewContainer.Parent = Combo
local PreviewLabel = Instance.new("TextLabel")
PreviewLabel.Name = "PreviewLabel"
PreviewLabel.AutomaticSize = Enum.AutomaticSize.Y
PreviewLabel.Size = UDim2.new(UDim.new(1, 0), Iris._config.ContentHeight)
PreviewLabel.BackgroundColor3 = Iris._config.FrameBgColor
PreviewLabel.BackgroundTransparency = Iris._config.FrameBgTransparency
PreviewLabel.BorderSizePixel = 0
PreviewLabel.ClipsDescendants = true
widgets.applyTextStyle(PreviewLabel)
widgets.UIPadding(PreviewLabel, Iris._config.FramePadding)
PreviewLabel.Parent = PreviewContainer
local DropdownButton = Instance.new("TextLabel")
DropdownButton.Name = "DropdownButton"
DropdownButton.Size = UDim2.new(0, frameHeight, Iris._config.ContentHeight.Scale, math.max(Iris._config.ContentHeight.Offset, frameHeight))
DropdownButton.BackgroundColor3 = Iris._config.ButtonColor
DropdownButton.BackgroundTransparency = Iris._config.ButtonTransparency
DropdownButton.BorderSizePixel = 0
DropdownButton.Text = ""
local padding = math.round(frameHeight * 0.2)
local dropdownSize = frameHeight - 2 * padding
local Dropdown = Instance.new("ImageLabel")
Dropdown.Name = "Dropdown"
Dropdown.AnchorPoint = Vector2.new(0.5, 0.5)
Dropdown.Size = UDim2.fromOffset(dropdownSize, dropdownSize)
Dropdown.Position = UDim2.fromScale(0.5, 0.5)
Dropdown.BackgroundTransparency = 1
Dropdown.BorderSizePixel = 0
Dropdown.ImageColor3 = Iris._config.TextColor
Dropdown.ImageTransparency = Iris._config.TextTransparency
Dropdown.Parent = DropdownButton
DropdownButton.Parent = PreviewContainer
-- for some reason ImGui Combo has no highlights for Active, only hovered.
-- so this deviates from ImGui, but its a good UX change
widgets.applyInteractionHighlightsWithMultiHighlightee("Background", PreviewContainer, {
{
PreviewLabel,
{
Color = Iris._config.FrameBgColor,
Transparency = Iris._config.FrameBgTransparency,
HoveredColor = Iris._config.FrameBgHoveredColor,
HoveredTransparency = Iris._config.FrameBgHoveredTransparency,
ActiveColor = Iris._config.FrameBgActiveColor,
ActiveTransparency = Iris._config.FrameBgActiveTransparency,
},
},
{
DropdownButton,
{
Color = Iris._config.ButtonColor,
Transparency = Iris._config.ButtonTransparency,
HoveredColor = Iris._config.ButtonHoveredColor,
HoveredTransparency = Iris._config.ButtonHoveredTransparency,
-- Use hovered for active
ActiveColor = Iris._config.ButtonHoveredColor,
ActiveTransparency = Iris._config.ButtonHoveredTransparency,
},
},
})
widgets.applyButtonClick(PreviewContainer, function()
if AnyOpenedCombo and OpenedCombo ~= thisWidget then
return
end
thisWidget.state.isOpened:set(not thisWidget.state.isOpened.value)
end)
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.X
TextLabel.Size = UDim2.fromOffset(0, frameHeight)
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = Combo
local ChildContainer = Instance.new("ScrollingFrame")
ChildContainer.Name = "ComboContainer"
ChildContainer.BackgroundColor3 = Iris._config.PopupBgColor
ChildContainer.BackgroundTransparency = Iris._config.PopupBgTransparency
ChildContainer.BorderSizePixel = 0
ChildContainer.AutomaticCanvasSize = Enum.AutomaticSize.Y
ChildContainer.ScrollBarImageTransparency = Iris._config.ScrollbarGrabTransparency
ChildContainer.ScrollBarImageColor3 = Iris._config.ScrollbarGrabColor
ChildContainer.ScrollBarThickness = Iris._config.ScrollbarSize
ChildContainer.CanvasSize = UDim2.fromScale(0, 0)
ChildContainer.VerticalScrollBarInset = Enum.ScrollBarInset.ScrollBar
ChildContainer.TopImage = widgets.ICONS.BLANK_SQUARE
ChildContainer.MidImage = widgets.ICONS.BLANK_SQUARE
ChildContainer.BottomImage = widgets.ICONS.BLANK_SQUARE
-- appear over everything else
ChildContainer.ClipsDescendants = true
-- Unfortunatley, ScrollingFrame does not work with UICorner
-- if Iris._config.PopupRounding > 0 then
-- widgets.UICorner(ChildContainer, Iris._config.PopupRounding)
-- end
widgets.UIStroke(ChildContainer, Iris._config.WindowBorderSize, Iris._config.BorderColor, Iris._config.BorderTransparency)
widgets.UIPadding(ChildContainer, Vector2.new(2, Iris._config.WindowPadding.Y))
widgets.UISizeConstraint(ChildContainer, Vector2.new(100))
local ChildContainerUIListLayout = widgets.UIListLayout(ChildContainer, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.ItemSpacing.Y))
ChildContainerUIListLayout.VerticalAlignment = Enum.VerticalAlignment.Top
local RootPopupScreenGui = Iris._rootInstance and Iris._rootInstance:WaitForChild("PopupScreenGui") :: GuiObject
ChildContainer.Parent = RootPopupScreenGui
thisWidget.ChildContainer = ChildContainer
thisWidget.UIListLayout = ChildContainerUIListLayout
return Combo
end,
GenerateState = function(thisWidget: Types.Combo)
if thisWidget.state.index == nil then
thisWidget.state.index = Iris._widgetState(thisWidget, "index", "No Selection")
end
if thisWidget.state.isOpened == nil then
thisWidget.state.isOpened = Iris._widgetState(thisWidget, "isOpened", false)
end
thisWidget.state.index:onChange(function()
thisWidget.lastChangedTick = Iris._cycleTick + 1
if thisWidget.state.isOpened.value then
thisWidget.state.isOpened:set(false)
end
end)
end,
Update = function(thisWidget: Types.Combo)
local Iris_Combo = thisWidget.Instance :: Frame
local PreviewContainer = Iris_Combo.PreviewContainer :: TextButton
local PreviewLabel: TextLabel = PreviewContainer.PreviewLabel
local DropdownButton: TextLabel = PreviewContainer.DropdownButton
local TextLabel: TextLabel = Iris_Combo.TextLabel
TextLabel.Text = thisWidget.arguments.Text or "Combo"
if thisWidget.arguments.NoButton then
DropdownButton.Visible = false
PreviewLabel.Size = UDim2.new(UDim.new(1, 0), PreviewLabel.Size.Height)
else
DropdownButton.Visible = true
local DropdownButtonSize = Iris._config.TextSize + 2 * Iris._config.FramePadding.Y
PreviewLabel.Size = UDim2.new(UDim.new(1, -DropdownButtonSize), PreviewLabel.Size.Height)
end
if thisWidget.arguments.NoPreview then
PreviewLabel.Visible = false
PreviewContainer.Size = UDim2.new(0, 0, 0, 0)
PreviewContainer.AutomaticSize = Enum.AutomaticSize.XY
else
PreviewLabel.Visible = true
PreviewContainer.Size = UDim2.new(Iris._config.ContentWidth, Iris._config.ContentHeight)
PreviewContainer.AutomaticSize = Enum.AutomaticSize.Y
end
end,
UpdateState = function(thisWidget: Types.Combo)
local Combo = thisWidget.Instance :: Frame
local ChildContainer = thisWidget.ChildContainer :: ScrollingFrame
local PreviewContainer = Combo.PreviewContainer :: TextButton
local PreviewLabel: TextLabel = PreviewContainer.PreviewLabel
local DropdownButton = PreviewContainer.DropdownButton :: TextLabel
local Dropdown: ImageLabel = DropdownButton.Dropdown
if thisWidget.state.isOpened.value then
AnyOpenedCombo = true
OpenedCombo = thisWidget
ComboOpenedTick = Iris._cycleTick
thisWidget.lastOpenedTick = Iris._cycleTick + 1
-- ImGui also does not do this, and the Arrow is always facing down
Dropdown.Image = widgets.ICONS.RIGHT_POINTING_TRIANGLE
ChildContainer.Visible = true
UpdateChildContainerTransform(thisWidget)
else
if AnyOpenedCombo then
AnyOpenedCombo = false
OpenedCombo = nil
thisWidget.lastClosedTick = Iris._cycleTick + 1
end
Dropdown.Image = widgets.ICONS.DOWN_POINTING_TRIANGLE
ChildContainer.Visible = false
end
local stateIndex = thisWidget.state.index.value
PreviewLabel.Text = if typeof(stateIndex) == "EnumItem" then stateIndex.Name else tostring(stateIndex)
end,
ChildAdded = function(thisWidget: Types.Combo, _thisChild: Types.Widget)
UpdateChildContainerTransform(thisWidget)
return thisWidget.ChildContainer
end,
Discard = function(thisWidget: Types.Combo)
-- If we are discarding the current combo active, we need to hide it
if OpenedCombo and OpenedCombo == thisWidget then
OpenedCombo = nil
AnyOpenedCombo = false
end
thisWidget.Instance:Destroy()
thisWidget.ChildContainer:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
end
| 4,577 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Format.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
--stylua: ignore
Iris.WidgetConstructor("Separator", {
hasState = false,
hasChildren = false,
Args = {},
Events = {},
Generate = function(thisWidget: Types.Separator)
local Separator = Instance.new("Frame")
Separator.Name = "Iris_Separator"
if thisWidget.parentWidget.type == "SameLine" then
Separator.Size = UDim2.new(0, 1, Iris._config.ItemWidth.Scale, Iris._config.ItemWidth.Offset)
else
Separator.Size = UDim2.new(Iris._config.ItemWidth.Scale, Iris._config.ItemWidth.Offset, 0, 1)
end
Separator.BackgroundColor3 = Iris._config.SeparatorColor
Separator.BackgroundTransparency = Iris._config.SeparatorTransparency
Separator.BorderSizePixel = 0
widgets.UIListLayout(Separator, Enum.FillDirection.Vertical, UDim.new(0, 0))
-- this is to prevent a bug of AutomaticLayout edge case when its parent has automaticLayout enabled
return Separator
end,
Update = function(_thisWidget: Types.Separator) end,
Discard = function(thisWidget: Types.Separator)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
--stylua: ignore
Iris.WidgetConstructor("Indent", {
hasState = false,
hasChildren = true,
Args = {
["Width"] = 1,
},
Events = {},
Generate = function(_thisWidget: Types.Indent)
local Indent = Instance.new("Frame")
Indent.Name = "Iris_Indent"
Indent.AutomaticSize = Enum.AutomaticSize.Y
Indent.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
Indent.BackgroundTransparency = 1
Indent.BorderSizePixel = 0
widgets.UIListLayout(Indent, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.ItemSpacing.Y))
widgets.UIPadding(Indent, Vector2.zero)
return Indent
end,
Update = function(thisWidget: Types.Indent)
local Indent = thisWidget.Instance :: Frame
Indent.UIPadding.PaddingLeft = UDim.new(0, if thisWidget.arguments.Width then thisWidget.arguments.Width else Iris._config.IndentSpacing)
end,
ChildAdded = function(thisWidget: Types.Indent, _thisChild: Types.Widget)
return thisWidget.Instance
end,
Discard = function(thisWidget: Types.Indent)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
--stylua: ignore
Iris.WidgetConstructor("SameLine", {
hasState = false,
hasChildren = true,
Args = {
["Width"] = 1,
["VerticalAlignment"] = 2,
["HorizontalAlignment"] = 3,
},
Events = {},
Generate = function(_thisWidget: Types.SameLine)
local SameLine = Instance.new("Frame")
SameLine.Name = "Iris_SameLine"
SameLine.AutomaticSize = Enum.AutomaticSize.Y
SameLine.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
SameLine.BackgroundTransparency = 1
SameLine.BorderSizePixel = 0
widgets.UIListLayout(SameLine, Enum.FillDirection.Horizontal, UDim.new(0, 0))
return SameLine
end,
Update = function(thisWidget: Types.SameLine)
local Sameline = thisWidget.Instance :: Frame
local UIListLayout: UIListLayout = Sameline.UIListLayout
UIListLayout.Padding = UDim.new(0, if thisWidget.arguments.Width then thisWidget.arguments.Width else Iris._config.ItemSpacing.X)
if thisWidget.arguments.VerticalAlignment then
UIListLayout.VerticalAlignment = thisWidget.arguments.VerticalAlignment
else
UIListLayout.VerticalAlignment = Enum.VerticalAlignment.Top
end
if thisWidget.arguments.HorizontalAlignment then
UIListLayout.HorizontalAlignment = thisWidget.arguments.HorizontalAlignment
else
UIListLayout.HorizontalAlignment = Enum.HorizontalAlignment.Left
end
end,
ChildAdded = function(thisWidget: Types.SameLine, _thisChild: Types.Widget)
return thisWidget.Instance
end,
Discard = function(thisWidget: Types.SameLine)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
--stylua: ignore
Iris.WidgetConstructor("Group", {
hasState = false,
hasChildren = true,
Args = {},
Events = {},
Generate = function(_thisWidget: Types.Group)
local Group = Instance.new("Frame")
Group.Name = "Iris_Group"
Group.AutomaticSize = Enum.AutomaticSize.XY
Group.Size = UDim2.fromOffset(0, 0)
Group.BackgroundTransparency = 1
Group.BorderSizePixel = 0
Group.ClipsDescendants = false
widgets.UIListLayout(Group, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.ItemSpacing.Y))
return Group
end,
Update = function(_thisWidget: Types.Group) end,
ChildAdded = function(thisWidget: Types.Group, _thisChild: Types.Widget)
return thisWidget.Instance
end,
Discard = function(thisWidget: Types.Group)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
end
| 1,200 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Image.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local abstractImage = {
hasState = false,
hasChildren = false,
Args = {
["Image"] = 1,
["Size"] = 2,
["Rect"] = 3,
["ScaleType"] = 4,
["ResampleMode"] = 5,
["TileSize"] = 6,
["SliceCenter"] = 7,
["SliceScale"] = 8,
},
Discard = function(thisWidget: Types.Image)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass
--stylua: ignore
Iris.WidgetConstructor("Image", widgets.extend(abstractImage, {
Events = {
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(_thisWidget: Types.Image)
local Image = Instance.new("ImageLabel")
Image.Name = "Iris_Image"
Image.BackgroundTransparency = 1
Image.BorderSizePixel = 0
Image.ImageColor3 = Iris._config.ImageColor
Image.ImageTransparency = Iris._config.ImageTransparency
widgets.applyFrameStyle(Image, true)
return Image
end,
Update = function(thisWidget: Types.Image)
local Image = thisWidget.Instance :: ImageLabel
Image.Image = thisWidget.arguments.Image or widgets.ICONS.UNKNOWN_TEXTURE
Image.Size = thisWidget.arguments.Size
if thisWidget.arguments.ScaleType then
Image.ScaleType = thisWidget.arguments.ScaleType
if thisWidget.arguments.ScaleType == Enum.ScaleType.Tile and thisWidget.arguments.TileSize then
Image.TileSize = thisWidget.arguments.TileSize
elseif thisWidget.arguments.ScaleType == Enum.ScaleType.Slice then
if thisWidget.arguments.SliceCenter then
Image.SliceCenter = thisWidget.arguments.SliceCenter
end
if thisWidget.arguments.SliceScale then
Image.SliceScale = thisWidget.arguments.SliceScale
end
end
end
if thisWidget.arguments.Rect then
Image.ImageRectOffset = thisWidget.arguments.Rect.Min
Image.ImageRectSize = Vector2.new(thisWidget.arguments.Rect.Width, thisWidget.arguments.Rect.Height)
end
if thisWidget.arguments.ResampleMode then
Image.ResampleMode = thisWidget.arguments.ResampleMode
end
end,
} :: Types.WidgetClass)
)
--stylua: ignore
Iris.WidgetConstructor("ImageButton", widgets.extend(abstractImage, {
Events = {
["clicked"] = widgets.EVENTS.click(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["rightClicked"] = widgets.EVENTS.rightClick(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["doubleClicked"] = widgets.EVENTS.doubleClick(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["ctrlClicked"] = widgets.EVENTS.ctrlClick(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(_thisWidget: Types.ImageButton)
local Button = Instance.new("ImageButton")
Button.Name = "Iris_ImageButton"
Button.AutomaticSize = Enum.AutomaticSize.XY
Button.BackgroundColor3 = Iris._config.FrameBgColor
Button.BackgroundTransparency = Iris._config.FrameBgTransparency
Button.BorderSizePixel = 0
Button.Image = ""
Button.ImageTransparency = 1
Button.AutoButtonColor = false
widgets.applyFrameStyle(Button, true)
widgets.UIPadding(Button, Vector2.new(Iris._config.ImageBorderSize, Iris._config.ImageBorderSize))
local Image = Instance.new("ImageLabel")
Image.Name = "ImageLabel"
Image.BackgroundTransparency = 1
Image.BorderSizePixel = 0
Image.ImageColor3 = Iris._config.ImageColor
Image.ImageTransparency = Iris._config.ImageTransparency
Image.Parent = Button
widgets.applyInteractionHighlights("Background", Button, Button, {
Color = Iris._config.FrameBgColor,
Transparency = Iris._config.FrameBgTransparency,
HoveredColor = Iris._config.FrameBgHoveredColor,
HoveredTransparency = Iris._config.FrameBgHoveredTransparency,
ActiveColor = Iris._config.FrameBgActiveColor,
ActiveTransparency = Iris._config.FrameBgActiveTransparency,
})
return Button
end,
Update = function(thisWidget: Types.ImageButton)
local Button = thisWidget.Instance :: TextButton
local Image: ImageLabel = Button.ImageLabel
Image.Image = thisWidget.arguments.Image or widgets.ICONS.UNKNOWN_TEXTURE
Image.Size = thisWidget.arguments.Size
if thisWidget.arguments.ScaleType then
Image.ScaleType = thisWidget.arguments.ScaleType
if thisWidget.arguments.ScaleType == Enum.ScaleType.Tile and thisWidget.arguments.TileSize then
Image.TileSize = thisWidget.arguments.TileSize
elseif thisWidget.arguments.ScaleType == Enum.ScaleType.Slice then
if thisWidget.arguments.SliceCenter then
Image.SliceCenter = thisWidget.arguments.SliceCenter
end
if thisWidget.arguments.SliceScale then
Image.SliceScale = thisWidget.arguments.SliceScale
end
end
end
if thisWidget.arguments.Rect then
Image.ImageRectOffset = thisWidget.arguments.Rect.Min
Image.ImageRectSize = Vector2.new(thisWidget.arguments.Rect.Width, thisWidget.arguments.Rect.Height)
end
if thisWidget.arguments.ResampleMode then
Image.ResampleMode = thisWidget.arguments.ResampleMode
end
end,
} :: Types.WidgetClass)
)
end
| 1,249 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Input.lua | local Types = require(script.Parent.Parent.Types)
type InputDataTypes = "Num" | "Vector2" | "Vector3" | "UDim" | "UDim2" | "Color3" | "Color4" | "Rect" | "Enum" | "" | string
type InputType = "Input" | "Drag" | "Slider"
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local numberChanged = {
["Init"] = function(_thisWidget: Types.Widget) end,
["Get"] = function(thisWidget: Types.Input<any>)
return thisWidget.lastNumberChangedTick == Iris._cycleTick
end,
}
local function getValueByIndex<T>(value: T, index: number, arguments: Types.Arguments)
local val = value :: unknown
if typeof(val) == "number" then
return val
elseif typeof(val) == "Vector2" then
if index == 1 then
return val.X
elseif index == 2 then
return val.Y
end
elseif typeof(val) == "Vector3" then
if index == 1 then
return val.X
elseif index == 2 then
return val.Y
elseif index == 3 then
return val.Z
end
elseif typeof(val) == "UDim" then
if index == 1 then
return val.Scale
elseif index == 2 then
return val.Offset
end
elseif typeof(val) == "UDim2" then
if index == 1 then
return val.X.Scale
elseif index == 2 then
return val.X.Offset
elseif index == 3 then
return val.Y.Scale
elseif index == 4 then
return val.Y.Offset
end
elseif typeof(val) == "Color3" then
local color = if arguments.UseHSV then { val:ToHSV() } else { val.R, val.G, val.B }
if index == 1 then
return color[1]
elseif index == 2 then
return color[2]
elseif index == 3 then
return color[3]
end
elseif typeof(val) == "Rect" then
if index == 1 then
return val.Min.X
elseif index == 2 then
return val.Min.Y
elseif index == 3 then
return val.Max.X
elseif index == 4 then
return val.Max.Y
end
elseif typeof(val) == "table" then
return val[index]
end
error(`Incorrect datatype or value: {value} {typeof(value)} {index}.`)
end
local function updateValueByIndex<T>(value: T, index: number, newValue: number, arguments: Types.Arguments): T
local val = value :: unknown
if typeof(val) == "number" then
return newValue :: any
elseif typeof(val) == "Vector2" then
if index == 1 then
return Vector2.new(newValue, val.Y) :: any
elseif index == 2 then
return Vector2.new(val.X, newValue) :: any
end
elseif typeof(val) == "Vector3" then
if index == 1 then
return Vector3.new(newValue, val.Y, val.Z) :: any
elseif index == 2 then
return Vector3.new(val.X, newValue, val.Z) :: any
elseif index == 3 then
return Vector3.new(val.X, val.Y, newValue) :: any
end
elseif typeof(val) == "UDim" then
if index == 1 then
return UDim.new(newValue, val.Offset) :: any
elseif index == 2 then
return UDim.new(val.Scale, newValue) :: any
end
elseif typeof(val) == "UDim2" then
if index == 1 then
return UDim2.new(UDim.new(newValue, val.X.Offset), val.Y) :: any
elseif index == 2 then
return UDim2.new(UDim.new(val.X.Scale, newValue), val.Y) :: any
elseif index == 3 then
return UDim2.new(val.X, UDim.new(newValue, val.Y.Offset)) :: any
elseif index == 4 then
return UDim2.new(val.X, UDim.new(val.Y.Scale, newValue)) :: any
end
elseif typeof(val) == "Rect" then
if index == 1 then
return Rect.new(Vector2.new(newValue, val.Min.Y), val.Max) :: any
elseif index == 2 then
return Rect.new(Vector2.new(val.Min.X, newValue), val.Max) :: any
elseif index == 3 then
return Rect.new(val.Min, Vector2.new(newValue, val.Max.Y)) :: any
elseif index == 4 then
return Rect.new(val.Min, Vector2.new(val.Max.X, newValue)) :: any
end
elseif typeof(val) == "Color3" then
if arguments.UseHSV then
local h: number, s: number, v: number = val:ToHSV()
if index == 1 then
return Color3.fromHSV(newValue, s, v) :: any
elseif index == 2 then
return Color3.fromHSV(h, newValue, v) :: any
elseif index == 3 then
return Color3.fromHSV(h, s, newValue) :: any
end
end
if index == 1 then
return Color3.new(newValue, val.G, val.B) :: any
elseif index == 2 then
return Color3.new(val.R, newValue, val.B) :: any
elseif index == 3 then
return Color3.new(val.R, val.G, newValue) :: any
end
end
error(`Incorrect datatype or value {value} {typeof(value)} {index}.`)
end
local defaultIncrements: { [InputDataTypes]: { number } } = {
Num = { 1 },
Vector2 = { 1, 1 },
Vector3 = { 1, 1, 1 },
UDim = { 0.01, 1 },
UDim2 = { 0.01, 1, 0.01, 1 },
Color3 = { 1, 1, 1 },
Color4 = { 1, 1, 1, 1 },
Rect = { 1, 1, 1, 1 },
}
local defaultMin: { [InputDataTypes]: { number } } = {
Num = { 0 },
Vector2 = { 0, 0 },
Vector3 = { 0, 0, 0 },
UDim = { 0, 0 },
UDim2 = { 0, 0, 0, 0 },
Rect = { 0, 0, 0, 0 },
}
local defaultMax: { [InputDataTypes]: { number } } = {
Num = { 100 },
Vector2 = { 100, 100 },
Vector3 = { 100, 100, 100 },
UDim = { 1, 960 },
UDim2 = { 1, 960, 1, 960 },
Rect = { 960, 960, 960, 960 },
}
local defaultPrefx: { [InputDataTypes]: { string } } = {
Num = { "" },
Vector2 = { "X: ", "Y: " },
Vector3 = { "X: ", "Y: ", "Z: " },
UDim = { "", "" },
UDim2 = { "", "", "", "" },
Color3_RGB = { "R: ", "G: ", "B: " },
Color3_HSV = { "H: ", "S: ", "V: " },
Color4_RGB = { "R: ", "G: ", "B: ", "T: " },
Color4_HSV = { "H: ", "S: ", "V: ", "T: " },
Rect = { "X: ", "Y: ", "X: ", "Y: " },
}
local defaultSigFigs: { [InputDataTypes]: { number } } = {
Num = { 0 },
Vector2 = { 0, 0 },
Vector3 = { 0, 0, 0 },
UDim = { 3, 0 },
UDim2 = { 3, 0, 3, 0 },
Color3 = { 0, 0, 0 },
Color4 = { 0, 0, 0, 0 },
Rect = { 0, 0, 0, 0 },
}
local function generateAbstract<T>(inputType: InputType, dataType: InputDataTypes, components: number, defaultValue: T): Types.WidgetClass
return {
hasState = true,
hasChildren = false,
Args = {
["Text"] = 1,
["Increment"] = 2,
["Min"] = 3,
["Max"] = 4,
["Format"] = 5,
},
Events = {
["numberChanged"] = numberChanged,
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
GenerateState = function(thisWidget: Types.Input<T>)
if thisWidget.state.number == nil then
thisWidget.state.number = Iris._widgetState(thisWidget, "number", defaultValue)
end
if thisWidget.state.editingText == nil then
thisWidget.state.editingText = Iris._widgetState(thisWidget, "editingText", 0)
end
end,
Update = function(thisWidget: Types.Input<T>)
local Input = thisWidget.Instance :: GuiObject
local TextLabel: TextLabel = Input.TextLabel
TextLabel.Text = thisWidget.arguments.Text or `Input {dataType}`
if thisWidget.arguments.Format and typeof(thisWidget.arguments.Format) ~= "table" then
thisWidget.arguments.Format = { thisWidget.arguments.Format }
elseif not thisWidget.arguments.Format then
-- we calculate the format for the s.f. using the max, min and increment arguments.
local format = {}
for index = 1, components do
local sigfigs = defaultSigFigs[dataType][index]
if thisWidget.arguments.Increment then
local value = getValueByIndex(thisWidget.arguments.Increment, index, thisWidget.arguments :: any)
sigfigs = math.max(sigfigs, math.ceil(-math.log10(value == 0 and 1 or value)), sigfigs)
end
if thisWidget.arguments.Max then
local value = getValueByIndex(thisWidget.arguments.Max, index, thisWidget.arguments :: any)
sigfigs = math.max(sigfigs, math.ceil(-math.log10(value == 0 and 1 or value)), sigfigs)
end
if thisWidget.arguments.Min then
local value = getValueByIndex(thisWidget.arguments.Min, index, thisWidget.arguments :: any)
sigfigs = math.max(sigfigs, math.ceil(-math.log10(value == 0 and 1 or value)), sigfigs)
end
if sigfigs > 0 then
-- we know it's a float.
format[index] = `%.{sigfigs}f`
else
format[index] = "%d"
end
end
thisWidget.arguments.Format = format
thisWidget.arguments.Prefix = defaultPrefx[dataType]
end
if inputType == "Input" and dataType == "Num" then
Input.SubButton.Visible = not thisWidget.arguments.NoButtons
Input.AddButton.Visible = not thisWidget.arguments.NoButtons
local InputField: TextBox = Input.InputField1
local rightPadding = if thisWidget.arguments.NoButtons then 0 else (2 * Iris._config.ItemInnerSpacing.X) + (2 * (Iris._config.TextSize + 2 * Iris._config.FramePadding.Y))
InputField.Size = UDim2.new(UDim.new(Iris._config.ContentWidth.Scale, Iris._config.ContentWidth.Offset - rightPadding), Iris._config.ContentHeight)
end
if inputType == "Slider" then
for index = 1, components do
local SliderField = Input:FindFirstChild("SliderField" .. tostring(index)) :: TextButton
local GrabBar: Frame = SliderField.GrabBar
local increment = thisWidget.arguments.Increment and getValueByIndex(thisWidget.arguments.Increment, index, thisWidget.arguments :: any) or defaultIncrements[dataType][index]
local min = thisWidget.arguments.Min and getValueByIndex(thisWidget.arguments.Min, index, thisWidget.arguments :: any) or defaultMin[dataType][index]
local max = thisWidget.arguments.Max and getValueByIndex(thisWidget.arguments.Max, index, thisWidget.arguments :: any) or defaultMax[dataType][index]
local grabScaleSize = 1 / math.floor((1 + max - min) / increment)
GrabBar.Size = UDim2.fromScale(grabScaleSize, 1)
end
local callbackIndex = #Iris._postCycleCallbacks + 1
local desiredCycleTick = Iris._cycleTick + 1
Iris._postCycleCallbacks[callbackIndex] = function()
if Iris._cycleTick >= desiredCycleTick then
if thisWidget.lastCycleTick ~= -1 then
thisWidget.state.number.lastChangeTick = Iris._cycleTick
Iris._widgets[`Slider{dataType}`].UpdateState(thisWidget)
end
Iris._postCycleCallbacks[callbackIndex] = nil
end
end
end
end,
Discard = function(thisWidget: Types.Input<T>)
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass
end
local function focusLost<T>(thisWidget: Types.Input<T>, InputField: TextBox, index: number, dataType: InputDataTypes)
local newValue = tonumber(InputField.Text:match("-?%d*%.?%d*"))
local state = thisWidget.state.number
local widget = thisWidget
if dataType == "Color4" and index == 4 then
state = widget.state.transparency
elseif dataType == "Color3" or dataType == "Color4" then
state = widget.state.color
end
if newValue ~= nil then
if dataType == "Color3" or dataType == "Color4" and not widget.arguments.UseFloats then
newValue = newValue / 255
end
if thisWidget.arguments.Min ~= nil then
newValue = math.max(newValue, getValueByIndex(thisWidget.arguments.Min, index, thisWidget.arguments :: any))
end
if thisWidget.arguments.Max ~= nil then
newValue = math.min(newValue, getValueByIndex(thisWidget.arguments.Max, index, thisWidget.arguments :: any))
end
if thisWidget.arguments.Increment then
newValue = math.round(newValue / getValueByIndex(thisWidget.arguments.Increment, index, thisWidget.arguments :: any)) * getValueByIndex(thisWidget.arguments.Increment, index, thisWidget.arguments :: any)
end
state:set(updateValueByIndex(state.value, index, newValue, thisWidget.arguments :: any))
thisWidget.lastNumberChangedTick = Iris._cycleTick + 1
end
local value = getValueByIndex(state.value, index, thisWidget.arguments :: any)
if dataType == "Color3" or dataType == "Color4" and not widget.arguments.UseFloats then
value = math.round(value * 255)
end
local format = thisWidget.arguments.Format[index] or thisWidget.arguments.Format[1]
if thisWidget.arguments.Prefix then
format = thisWidget.arguments.Prefix[index] .. format
end
InputField.Text = string.format(format, value)
thisWidget.state.editingText:set(0)
InputField:ReleaseFocus(true)
end
--[[
Input
]]
local generateInputScalar: <T>(dataType: InputDataTypes, components: number, defaultValue: T) -> Types.WidgetClass
do
local function generateButtons(thisWidget: Types.Input<number>, parent: GuiObject, textHeight: number)
local SubButton = widgets.abstractButton.Generate(thisWidget) :: TextButton
SubButton.Name = "SubButton"
SubButton.Size = UDim2.fromOffset(Iris._config.TextSize + 2 * Iris._config.FramePadding.Y, Iris._config.TextSize)
SubButton.Text = "-"
SubButton.TextXAlignment = Enum.TextXAlignment.Center
SubButton.ZIndex = 5
SubButton.LayoutOrder = 5
SubButton.Parent = parent
widgets.applyButtonClick(SubButton, function()
local isCtrlHeld = widgets.UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or widgets.UserInputService:IsKeyDown(Enum.KeyCode.RightControl)
local changeValue = (thisWidget.arguments.Increment and getValueByIndex(thisWidget.arguments.Increment, 1, thisWidget.arguments :: Types.Argument) or 1) * (isCtrlHeld and 100 or 1)
local newValue = thisWidget.state.number.value - changeValue
if thisWidget.arguments.Min ~= nil then
newValue = math.max(newValue, getValueByIndex(thisWidget.arguments.Min, 1, thisWidget.arguments :: Types.Argument))
end
if thisWidget.arguments.Max ~= nil then
newValue = math.min(newValue, getValueByIndex(thisWidget.arguments.Max, 1, thisWidget.arguments :: Types.Argument))
end
thisWidget.state.number:set(newValue)
thisWidget.lastNumberChangedTick = Iris._cycleTick + 1
end)
local AddButton = widgets.abstractButton.Generate(thisWidget) :: TextButton
AddButton.Name = "AddButton"
AddButton.Size = UDim2.fromOffset(Iris._config.TextSize + 2 * Iris._config.FramePadding.Y, Iris._config.TextSize)
AddButton.Text = "+"
AddButton.TextXAlignment = Enum.TextXAlignment.Center
AddButton.ZIndex = 6
AddButton.LayoutOrder = 6
AddButton.Parent = parent
widgets.applyButtonClick(AddButton, function()
local isCtrlHeld = widgets.UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or widgets.UserInputService:IsKeyDown(Enum.KeyCode.RightControl)
local changeValue = (thisWidget.arguments.Increment and getValueByIndex(thisWidget.arguments.Increment, 1, thisWidget.arguments :: Types.Argument) or 1) * (isCtrlHeld and 100 or 1)
local newValue = thisWidget.state.number.value + changeValue
if thisWidget.arguments.Min ~= nil then
newValue = math.max(newValue, getValueByIndex(thisWidget.arguments.Min, 1, thisWidget.arguments :: Types.Argument))
end
if thisWidget.arguments.Max ~= nil then
newValue = math.min(newValue, getValueByIndex(thisWidget.arguments.Max, 1, thisWidget.arguments :: Types.Argument))
end
thisWidget.state.number:set(newValue)
thisWidget.lastNumberChangedTick = Iris._cycleTick + 1
end)
return 2 * Iris._config.ItemInnerSpacing.X + 2 * textHeight
end
local function generateField<T>(thisWidget: Types.Input<T>, index: number, componentWidth: UDim, dataType: InputDataTypes)
local InputField = Instance.new("TextBox")
InputField.Name = "InputField" .. tostring(index)
InputField.AutomaticSize = Enum.AutomaticSize.Y
InputField.Size = UDim2.new(componentWidth, Iris._config.ContentHeight)
InputField.BackgroundColor3 = Iris._config.FrameBgColor
InputField.BackgroundTransparency = Iris._config.FrameBgTransparency
InputField.TextTruncate = Enum.TextTruncate.AtEnd
InputField.ClearTextOnFocus = false
InputField.ZIndex = index
InputField.LayoutOrder = index
InputField.ClipsDescendants = true
widgets.applyFrameStyle(InputField)
widgets.applyTextStyle(InputField)
widgets.UISizeConstraint(InputField, Vector2.xAxis)
InputField.FocusLost:Connect(function()
focusLost(thisWidget, InputField, index, dataType)
end)
InputField.Focused:Connect(function()
-- this highlights the entire field
InputField.CursorPosition = #InputField.Text + 1
InputField.SelectionStart = 1
thisWidget.state.editingText:set(index)
end)
return InputField
end
function generateInputScalar<T>(dataType: InputDataTypes, components: number, defaultValue: T)
local input = generateAbstract("Input", dataType, components, defaultValue)
return widgets.extend(input, {
Generate = function(thisWidget: Types.Input<T>)
local Input = Instance.new("Frame")
Input.Name = "Iris_Input" .. dataType
Input.AutomaticSize = Enum.AutomaticSize.Y
Input.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
Input.BackgroundTransparency = 1
Input.BorderSizePixel = 0
widgets.UIListLayout(Input, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
-- we add plus and minus buttons if there is only one box. This can be disabled through the argument.
local rightPadding = 0
local textHeight = Iris._config.TextSize + 2 * Iris._config.FramePadding.Y
if components == 1 then
rightPadding = generateButtons(thisWidget :: any, Input, textHeight)
end
-- we divide the total area evenly between each field. This includes accounting for any additional boxes and the offset.
-- for the final field, we make sure it's flush by calculating the space avaiable for it. This only makes the Vector2 box
-- 4 pixels shorter, all for the sake of flush.
local componentWidth = UDim.new(Iris._config.ContentWidth.Scale / components, (Iris._config.ContentWidth.Offset - (Iris._config.ItemInnerSpacing.X * (components - 1)) - rightPadding) / components)
local totalWidth = UDim.new(componentWidth.Scale * (components - 1), (componentWidth.Offset * (components - 1)) + (Iris._config.ItemInnerSpacing.X * (components - 1)) + rightPadding)
local lastComponentWidth = Iris._config.ContentWidth - totalWidth
-- we handle each component individually since they don't need to interact with each other.
for index = 1, components do
generateField(thisWidget, index, if index == components then lastComponentWidth else componentWidth, dataType).Parent = Input
end
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.LayoutOrder = 7
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = Input
return Input
end,
UpdateState = function(thisWidget: Types.Input<T>)
local Input = thisWidget.Instance :: GuiObject
for index = 1, components do
local InputField: TextBox = Input:FindFirstChild("InputField" .. tostring(index))
local format = thisWidget.arguments.Format[index] or thisWidget.arguments.Format[1]
if thisWidget.arguments.Prefix then
format = thisWidget.arguments.Prefix[index] .. format
end
InputField.Text = string.format(format, getValueByIndex(thisWidget.state.number.value, index, thisWidget.arguments :: any))
end
end,
})
end
end
--[[
Drag
]]
local generateDragScalar: <T>(dataType: InputDataTypes, components: number, defaultValue: T) -> Types.WidgetClass
local generateColorDragScalar: (dataType: InputDataTypes, ...any) -> Types.WidgetClass
do
local PreviouseMouseXPosition = 0
local AnyActiveDrag = false
local ActiveDrag: Types.Input<Types.InputDataType>? = nil
local ActiveIndex = 0
local ActiveDataType: InputDataTypes | "" = ""
local function updateActiveDrag()
local currentMouseX = widgets.getMouseLocation().X
local mouseXDelta = currentMouseX - PreviouseMouseXPosition
PreviouseMouseXPosition = currentMouseX
if AnyActiveDrag == false then
return
end
if ActiveDrag == nil then
return
end
local state = ActiveDrag.state.number
if ActiveDataType == "Color3" or ActiveDataType == "Color4" then
local Drag = ActiveDrag
state = Drag.state.color
if ActiveIndex == 4 then
state = Drag.state.transparency
end
end
local increment = ActiveDrag.arguments.Increment and getValueByIndex(ActiveDrag.arguments.Increment, ActiveIndex, ActiveDrag.arguments :: any) or defaultIncrements[ActiveDataType][ActiveIndex]
increment *= (widgets.UserInputService:IsKeyDown(Enum.KeyCode.LeftShift) or widgets.UserInputService:IsKeyDown(Enum.KeyCode.RightShift)) and 10 or 1
increment *= (widgets.UserInputService:IsKeyDown(Enum.KeyCode.LeftAlt) or widgets.UserInputService:IsKeyDown(Enum.KeyCode.RightAlt)) and 0.1 or 1
-- we increase the speed for Color3 and Color4 since it's too slow because the increment argument needs to be low.
increment *= (ActiveDataType == "Color3" or ActiveDataType == "Color4") and 5 or 1
local value = getValueByIndex(state.value, ActiveIndex, ActiveDrag.arguments :: any)
local newValue = value + (mouseXDelta * increment)
if ActiveDrag.arguments.Min ~= nil then
newValue = math.max(newValue, getValueByIndex(ActiveDrag.arguments.Min, ActiveIndex, ActiveDrag.arguments :: any))
end
if ActiveDrag.arguments.Max ~= nil then
newValue = math.min(newValue, getValueByIndex(ActiveDrag.arguments.Max, ActiveIndex, ActiveDrag.arguments :: any))
end
state:set(updateValueByIndex(state.value, ActiveIndex, newValue, ActiveDrag.arguments :: any))
ActiveDrag.lastNumberChangedTick = Iris._cycleTick + 1
end
local function DragMouseDown(thisWidget: Types.Input<Types.InputDataType>, dataTypes: InputDataTypes, index: number, x: number, y: number)
local currentTime = widgets.getTime()
local isTimeValid = currentTime - thisWidget.lastClickedTime < Iris._config.MouseDoubleClickTime
local isCtrlHeld = widgets.UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or widgets.UserInputService:IsKeyDown(Enum.KeyCode.RightControl)
if (isTimeValid and (Vector2.new(x, y) - thisWidget.lastClickedPosition).Magnitude < Iris._config.MouseDoubleClickMaxDist) or isCtrlHeld then
thisWidget.state.editingText:set(index)
else
thisWidget.lastClickedTime = currentTime
thisWidget.lastClickedPosition = Vector2.new(x, y)
AnyActiveDrag = true
ActiveDrag = thisWidget
ActiveIndex = index
ActiveDataType = dataTypes
updateActiveDrag()
end
end
widgets.registerEvent("InputChanged", function()
if not Iris._started then
return
end
updateActiveDrag()
end)
widgets.registerEvent("InputEnded", function(inputObject: InputObject)
if not Iris._started then
return
end
if inputObject.UserInputType == Enum.UserInputType.MouseButton1 and AnyActiveDrag then
AnyActiveDrag = false
ActiveDrag = nil
ActiveIndex = 0
end
end)
local function generateField<T>(thisWidget: Types.Input<T>, index: number, componentSize: UDim2, dataType: InputDataTypes)
local DragField = Instance.new("TextButton")
DragField.Name = "DragField" .. tostring(index)
DragField.AutomaticSize = Enum.AutomaticSize.Y
DragField.Size = componentSize
DragField.BackgroundColor3 = Iris._config.FrameBgColor
DragField.BackgroundTransparency = Iris._config.FrameBgTransparency
DragField.Text = ""
DragField.AutoButtonColor = false
DragField.LayoutOrder = index
DragField.ClipsDescendants = true
widgets.applyFrameStyle(DragField)
widgets.applyTextStyle(DragField)
widgets.UISizeConstraint(DragField, Vector2.xAxis)
DragField.TextXAlignment = Enum.TextXAlignment.Center
widgets.applyInteractionHighlights("Background", DragField, DragField, {
Color = Iris._config.FrameBgColor,
Transparency = Iris._config.FrameBgTransparency,
HoveredColor = Iris._config.FrameBgHoveredColor,
HoveredTransparency = Iris._config.FrameBgHoveredTransparency,
ActiveColor = Iris._config.FrameBgActiveColor,
ActiveTransparency = Iris._config.FrameBgActiveTransparency,
})
local InputField = Instance.new("TextBox")
InputField.Name = "InputField"
InputField.Size = UDim2.fromScale(1, 1)
InputField.BackgroundTransparency = 1
InputField.ClearTextOnFocus = false
InputField.TextTruncate = Enum.TextTruncate.AtEnd
InputField.ClipsDescendants = true
InputField.Visible = false
widgets.applyFrameStyle(InputField, true)
widgets.applyTextStyle(InputField)
InputField.Parent = DragField
InputField.FocusLost:Connect(function()
focusLost(thisWidget, InputField, index, dataType)
end)
InputField.Focused:Connect(function()
-- this highlights the entire field
InputField.CursorPosition = #InputField.Text + 1
InputField.SelectionStart = 1
thisWidget.state.editingText:set(index)
end)
widgets.applyButtonDown(DragField, function(x: number, y: number)
DragMouseDown(thisWidget :: any, dataType, index, x, y)
end)
return DragField
end
function generateDragScalar<T>(dataType: InputDataTypes, components: number, defaultValue: T)
local input = generateAbstract("Drag", dataType, components, defaultValue)
return widgets.extend(input, {
Generate = function(thisWidget: Types.Input<T>)
thisWidget.lastClickedTime = -1
thisWidget.lastClickedPosition = Vector2.zero
local Drag = Instance.new("Frame")
Drag.Name = "Iris_Drag" .. dataType
Drag.AutomaticSize = Enum.AutomaticSize.Y
Drag.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
Drag.BackgroundTransparency = 1
Drag.BorderSizePixel = 0
widgets.UIListLayout(Drag, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
-- we add a color box if it is Color3 or Color4.
local rightPadding = 0
local textHeight = Iris._config.TextSize + 2 * Iris._config.FramePadding.Y
if dataType == "Color3" or dataType == "Color4" then
rightPadding += Iris._config.ItemInnerSpacing.X + textHeight
local ColorBox = Instance.new("ImageLabel")
ColorBox.Name = "ColorBox"
ColorBox.Size = UDim2.fromOffset(textHeight, textHeight)
ColorBox.BorderSizePixel = 0
ColorBox.Image = widgets.ICONS.ALPHA_BACKGROUND_TEXTURE
ColorBox.ImageTransparency = 1
ColorBox.LayoutOrder = 5
widgets.applyFrameStyle(ColorBox, true)
ColorBox.Parent = Drag
end
-- we divide the total area evenly between each field. This includes accounting for any additional boxes and the offset.
-- for the final field, we make sure it's flush by calculating the space avaiable for it. This only makes the Vector2 box
-- 4 pixels shorter, all for the sake of flush.
local componentWidth = UDim.new(Iris._config.ContentWidth.Scale / components, (Iris._config.ContentWidth.Offset - (Iris._config.ItemInnerSpacing.X * (components - 1)) - rightPadding) / components)
local totalWidth = UDim.new(componentWidth.Scale * (components - 1), (componentWidth.Offset * (components - 1)) + (Iris._config.ItemInnerSpacing.X * (components - 1)) + rightPadding)
local lastComponentWidth = Iris._config.ContentWidth - totalWidth
for index = 1, components do
generateField(thisWidget, index, if index == components then UDim2.new(lastComponentWidth, Iris._config.ContentHeight) else UDim2.new(componentWidth, Iris._config.ContentHeight), dataType).Parent = Drag
end
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.LayoutOrder = 6
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = Drag
return Drag
end,
UpdateState = function(thisWidget: Types.Input<T>)
local Drag = thisWidget.Instance :: Frame
local widget = thisWidget :: any
for index = 1, components do
local state = thisWidget.state.number
if dataType == "Color3" or dataType == "Color4" then
state = widget.state.color
if index == 4 then
state = widget.state.transparency
end
end
local DragField = Drag:FindFirstChild("DragField" .. tostring(index)) :: TextButton
local InputField: TextBox = DragField.InputField
local value = getValueByIndex(state.value, index, thisWidget.arguments :: any)
if (dataType == "Color3" or dataType == "Color4") and not widget.arguments.UseFloats then
value = math.round(value * 255)
end
local format = thisWidget.arguments.Format[index] or thisWidget.arguments.Format[1]
if thisWidget.arguments.Prefix then
format = thisWidget.arguments.Prefix[index] .. format
end
DragField.Text = string.format(format, value)
InputField.Text = tostring(value)
if thisWidget.state.editingText.value == index then
InputField.Visible = true
InputField:CaptureFocus()
DragField.TextTransparency = 1
else
InputField.Visible = false
DragField.TextTransparency = Iris._config.TextTransparency
end
end
if dataType == "Color3" or dataType == "Color4" then
local ColorBox: ImageLabel = Drag.ColorBox
ColorBox.BackgroundColor3 = widget.state.color.value
if dataType == "Color4" then
ColorBox.ImageTransparency = 1 - widget.state.transparency.value
end
end
end,
})
end
function generateColorDragScalar(dataType: InputDataTypes, ...: any)
local defaultValues = { ... }
local input = generateDragScalar(dataType, dataType == "Color4" and 4 or 3, defaultValues[1])
return widgets.extend(input, {
Args = {
["Text"] = 1,
["UseFloats"] = 2,
["UseHSV"] = 3,
["Format"] = 4,
},
Update = function(thisWidget: Types.InputColor4)
local Input = thisWidget.Instance :: GuiObject
local TextLabel: TextLabel = Input.TextLabel
TextLabel.Text = thisWidget.arguments.Text or `Drag {dataType}`
if thisWidget.arguments.Format and typeof(thisWidget.arguments.Format) ~= "table" then
thisWidget.arguments.Format = { thisWidget.arguments.Format }
elseif not thisWidget.arguments.Format then
if thisWidget.arguments.UseFloats then
thisWidget.arguments.Format = { "%.3f" }
else
thisWidget.arguments.Format = { "%d" }
end
thisWidget.arguments.Prefix = defaultPrefx[dataType .. if thisWidget.arguments.UseHSV then "_HSV" else "_RGB"]
end
thisWidget.arguments.Min = { 0, 0, 0, 0 }
thisWidget.arguments.Max = { 1, 1, 1, 1 }
thisWidget.arguments.Increment = { 0.001, 0.001, 0.001, 0.001 }
-- since the state values have changed display, we call an update. The check is because state is not
-- initialised on creation, so it would error otherwise.
if thisWidget.state then
thisWidget.state.color.lastChangeTick = Iris._cycleTick
if dataType == "Color4" then
thisWidget.state.transparency.lastChangeTick = Iris._cycleTick
end
Iris._widgets[thisWidget.type].UpdateState(thisWidget)
end
end,
GenerateState = function(thisWidget: Types.InputColor4)
if thisWidget.state.color == nil then
thisWidget.state.color = Iris._widgetState(thisWidget, "color", defaultValues[1])
end
if dataType == "Color4" then
if thisWidget.state.transparency == nil then
thisWidget.state.transparency = Iris._widgetState(thisWidget, "transparency", defaultValues[2])
end
end
if thisWidget.state.editingText == nil then
thisWidget.state.editingText = Iris._widgetState(thisWidget, "editingText", false)
end
end,
})
end
end
--[[
Slider
]]
local generateSliderScalar: <T>(dataType: InputDataTypes, components: number, defaultValue: T) -> Types.WidgetClass
local generateEnumSliderScalar: (enum: Enum, item: EnumItem) -> Types.WidgetClass
do
local AnyActiveSlider = false
local ActiveSlider: Types.Input<Types.InputDataType>? = nil
local ActiveIndex = 0
local ActiveDataType: InputDataTypes | "" = ""
local function updateActiveSlider()
if AnyActiveSlider == false then
return
end
if ActiveSlider == nil then
return
end
local Slider = ActiveSlider.Instance :: Frame
local SliderField = Slider:FindFirstChild("SliderField" .. tostring(ActiveIndex)) :: TextButton
local GrabBar: Frame = SliderField.GrabBar
local increment = ActiveSlider.arguments.Increment and getValueByIndex(ActiveSlider.arguments.Increment, ActiveIndex, ActiveSlider.arguments :: any) or defaultIncrements[ActiveDataType][ActiveIndex]
local min = ActiveSlider.arguments.Min and getValueByIndex(ActiveSlider.arguments.Min, ActiveIndex, ActiveSlider.arguments :: any) or defaultMin[ActiveDataType][ActiveIndex]
local max = ActiveSlider.arguments.Max and getValueByIndex(ActiveSlider.arguments.Max, ActiveIndex, ActiveSlider.arguments :: any) or defaultMax[ActiveDataType][ActiveIndex]
local GrabWidth = GrabBar.AbsoluteSize.X
local Offset = widgets.getMouseLocation().X - (SliderField.AbsolutePosition.X - widgets.GuiOffset.X + GrabWidth / 2)
local Ratio = Offset / (SliderField.AbsoluteSize.X - GrabWidth)
local Positions = math.floor((max - min) / increment)
local newValue = math.clamp(math.round(Ratio * Positions) * increment + min, min, max)
ActiveSlider.state.number:set(updateValueByIndex(ActiveSlider.state.number.value, ActiveIndex, newValue, ActiveSlider.arguments :: any))
ActiveSlider.lastNumberChangedTick = Iris._cycleTick + 1
end
local function SliderMouseDown(thisWidget: Types.Input<Types.InputDataType>, dataType: InputDataTypes, index: number)
local isCtrlHeld = widgets.UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or widgets.UserInputService:IsKeyDown(Enum.KeyCode.RightControl)
if isCtrlHeld then
thisWidget.state.editingText:set(index)
else
AnyActiveSlider = true
ActiveSlider = thisWidget
ActiveIndex = index
ActiveDataType = dataType
updateActiveSlider()
end
end
widgets.registerEvent("InputChanged", function()
if not Iris._started then
return
end
updateActiveSlider()
end)
widgets.registerEvent("InputEnded", function(inputObject: InputObject)
if not Iris._started then
return
end
if inputObject.UserInputType == Enum.UserInputType.MouseButton1 and AnyActiveSlider then
AnyActiveSlider = false
ActiveSlider = nil
ActiveIndex = 0
ActiveDataType = ""
end
end)
local function generateField<T>(thisWidget: Types.Input<T>, index: number, componentSize: UDim2, dataType: InputDataTypes)
local SliderField = Instance.new("TextButton")
SliderField.Name = "SliderField" .. tostring(index)
SliderField.AutomaticSize = Enum.AutomaticSize.Y
SliderField.Size = componentSize
SliderField.BackgroundColor3 = Iris._config.FrameBgColor
SliderField.BackgroundTransparency = Iris._config.FrameBgTransparency
SliderField.Text = ""
SliderField.AutoButtonColor = false
SliderField.LayoutOrder = index
SliderField.ClipsDescendants = true
widgets.applyFrameStyle(SliderField)
widgets.applyTextStyle(SliderField)
widgets.UISizeConstraint(SliderField, Vector2.xAxis)
local OverlayText = Instance.new("TextLabel")
OverlayText.Name = "OverlayText"
OverlayText.Size = UDim2.fromScale(1, 1)
OverlayText.BackgroundTransparency = 1
OverlayText.BorderSizePixel = 0
OverlayText.ZIndex = 10
OverlayText.ClipsDescendants = true
widgets.applyTextStyle(OverlayText)
OverlayText.TextXAlignment = Enum.TextXAlignment.Center
OverlayText.Parent = SliderField
widgets.applyInteractionHighlights("Background", SliderField, SliderField, {
Color = Iris._config.FrameBgColor,
Transparency = Iris._config.FrameBgTransparency,
HoveredColor = Iris._config.FrameBgHoveredColor,
HoveredTransparency = Iris._config.FrameBgHoveredTransparency,
ActiveColor = Iris._config.FrameBgActiveColor,
ActiveTransparency = Iris._config.FrameBgActiveTransparency,
})
local InputField = Instance.new("TextBox")
InputField.Name = "InputField"
InputField.Size = UDim2.fromScale(1, 1)
InputField.BackgroundTransparency = 1
InputField.ClearTextOnFocus = false
InputField.TextTruncate = Enum.TextTruncate.AtEnd
InputField.ClipsDescendants = true
InputField.Visible = false
widgets.applyFrameStyle(InputField, true)
widgets.applyTextStyle(InputField)
InputField.Parent = SliderField
InputField.FocusLost:Connect(function()
focusLost(thisWidget, InputField, index, dataType)
end)
InputField.Focused:Connect(function()
-- this highlights the entire field
InputField.CursorPosition = #InputField.Text + 1
InputField.SelectionStart = 1
thisWidget.state.editingText:set(index)
end)
widgets.applyButtonDown(SliderField, function()
SliderMouseDown(thisWidget :: any, dataType, index)
end)
local GrabBar = Instance.new("Frame")
GrabBar.Name = "GrabBar"
GrabBar.AnchorPoint = Vector2.new(0.5, 0.5)
GrabBar.Position = UDim2.fromScale(0, 0.5)
GrabBar.BackgroundColor3 = Iris._config.SliderGrabColor
GrabBar.Transparency = Iris._config.SliderGrabTransparency
GrabBar.BorderSizePixel = 0
GrabBar.ZIndex = 5
widgets.applyInteractionHighlights("Background", SliderField, GrabBar, {
Color = Iris._config.SliderGrabColor,
Transparency = Iris._config.SliderGrabTransparency,
HoveredColor = Iris._config.SliderGrabColor,
HoveredTransparency = Iris._config.SliderGrabTransparency,
ActiveColor = Iris._config.SliderGrabActiveColor,
ActiveTransparency = Iris._config.SliderGrabActiveTransparency,
})
if Iris._config.GrabRounding > 0 then
widgets.UICorner(GrabBar, Iris._config.GrabRounding)
end
widgets.UISizeConstraint(GrabBar, Vector2.new(Iris._config.GrabMinSize, 0))
GrabBar.Parent = SliderField
return SliderField
end
function generateSliderScalar<T>(dataType: InputDataTypes, components: number, defaultValue: T)
local input = generateAbstract("Slider", dataType, components, defaultValue)
return widgets.extend(input, {
Generate = function(thisWidget: Types.Input<T>)
local Slider = Instance.new("Frame")
Slider.Name = "Iris_Slider" .. dataType
Slider.AutomaticSize = Enum.AutomaticSize.Y
Slider.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
Slider.BackgroundTransparency = 1
Slider.BorderSizePixel = 0
widgets.UIListLayout(Slider, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
-- we divide the total area evenly between each field. This includes accounting for any additional boxes and the offset.
-- for the final field, we make sure it's flush by calculating the space avaiable for it. This only makes the Vector2 box
-- 4 pixels shorter, all for the sake of flush.
local componentWidth = UDim.new(Iris._config.ContentWidth.Scale / components, (Iris._config.ContentWidth.Offset - (Iris._config.ItemInnerSpacing.X * (components - 1))) / components)
local totalWidth = UDim.new(componentWidth.Scale * (components - 1), (componentWidth.Offset * (components - 1)) + (Iris._config.ItemInnerSpacing.X * (components - 1)))
local lastComponentWidth = Iris._config.ContentWidth - totalWidth
for index = 1, components do
generateField(thisWidget, index, if index == components then UDim2.new(lastComponentWidth, Iris._config.ContentHeight) else UDim2.new(componentWidth, Iris._config.ContentHeight), dataType).Parent = Slider
end
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.LayoutOrder = 5
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = Slider
return Slider
end,
UpdateState = function(thisWidget: Types.Input<T>)
local Slider = thisWidget.Instance :: Frame
for index = 1, components do
local SliderField = Slider:FindFirstChild("SliderField" .. tostring(index)) :: TextButton
local InputField: TextBox = SliderField.InputField
local OverlayText: TextLabel = SliderField.OverlayText
local GrabBar: Frame = SliderField.GrabBar
local value = getValueByIndex(thisWidget.state.number.value, index, thisWidget.arguments :: any)
local format = thisWidget.arguments.Format[index] or thisWidget.arguments.Format[1]
if thisWidget.arguments.Prefix then
format = thisWidget.arguments.Prefix[index] .. format
end
OverlayText.Text = string.format(format, value)
InputField.Text = tostring(value)
local increment = thisWidget.arguments.Increment and getValueByIndex(thisWidget.arguments.Increment, index, thisWidget.arguments :: any) or defaultIncrements[dataType][index]
local min = thisWidget.arguments.Min and getValueByIndex(thisWidget.arguments.Min, index, thisWidget.arguments :: any) or defaultMin[dataType][index]
local max = thisWidget.arguments.Max and getValueByIndex(thisWidget.arguments.Max, index, thisWidget.arguments :: any) or defaultMax[dataType][index]
local SliderWidth = SliderField.AbsoluteSize.X
local PaddedWidth = SliderWidth - GrabBar.AbsoluteSize.X
local Ratio = (value - min) / (max - min)
local Positions = math.floor((max - min) / increment)
local ClampedRatio = math.clamp(math.floor((Ratio * Positions)) / Positions, 0, 1)
local PaddedRatio = ((PaddedWidth / SliderWidth) * ClampedRatio) + ((1 - (PaddedWidth / SliderWidth)) / 2)
GrabBar.Position = UDim2.fromScale(PaddedRatio, 0.5)
if thisWidget.state.editingText.value == index then
InputField.Visible = true
OverlayText.Visible = false
GrabBar.Visible = false
InputField:CaptureFocus()
else
InputField.Visible = false
OverlayText.Visible = true
GrabBar.Visible = true
end
end
end,
})
end
function generateEnumSliderScalar(enum: Enum, item: EnumItem)
local input: Types.WidgetClass = generateSliderScalar("Enum", 1, item.Value)
local valueToName = { string }
for _, enumItem in enum:GetEnumItems() do
valueToName[enumItem.Value] = enumItem.Name
end
return widgets.extend(input, {
Args = {
["Text"] = 1,
},
Update = function(thisWidget: Types.InputEnum)
local Input = thisWidget.Instance :: GuiObject
local TextLabel: TextLabel = Input.TextLabel
TextLabel.Text = thisWidget.arguments.Text or "Input Enum"
thisWidget.arguments.Increment = 1
thisWidget.arguments.Min = 0
thisWidget.arguments.Max = #enum:GetEnumItems() - 1
local SliderField = Input:FindFirstChild("SliderField1") :: TextButton
local GrabBar: Frame = SliderField.GrabBar
local grabScaleSize = 1 / math.floor(#enum:GetEnumItems())
GrabBar.Size = UDim2.fromScale(grabScaleSize, 1)
end,
GenerateState = function(thisWidget: Types.InputEnum)
if thisWidget.state.number == nil then
thisWidget.state.number = Iris._widgetState(thisWidget, "number", item.Value)
end
if thisWidget.state.enumItem == nil then
thisWidget.state.enumItem = Iris._widgetState(thisWidget, "enumItem", item)
end
if thisWidget.state.editingText == nil then
thisWidget.state.editingText = Iris._widgetState(thisWidget, "editingText", false)
end
end,
})
end
end
do
local inputNum: Types.WidgetClass = generateInputScalar("Num", 1, 0)
inputNum.Args["NoButtons"] = 6
Iris.WidgetConstructor("InputNum", inputNum)
end
Iris.WidgetConstructor("InputVector2", generateInputScalar("Vector2", 2, Vector2.zero))
Iris.WidgetConstructor("InputVector3", generateInputScalar("Vector3", 3, Vector3.zero))
Iris.WidgetConstructor("InputUDim", generateInputScalar("UDim", 2, UDim.new()))
Iris.WidgetConstructor("InputUDim2", generateInputScalar("UDim2", 4, UDim2.new()))
Iris.WidgetConstructor("InputRect", generateInputScalar("Rect", 4, Rect.new(0, 0, 0, 0)))
Iris.WidgetConstructor("DragNum", generateDragScalar("Num", 1, 0))
Iris.WidgetConstructor("DragVector2", generateDragScalar("Vector2", 2, Vector2.zero))
Iris.WidgetConstructor("DragVector3", generateDragScalar("Vector3", 3, Vector3.zero))
Iris.WidgetConstructor("DragUDim", generateDragScalar("UDim", 2, UDim.new()))
Iris.WidgetConstructor("DragUDim2", generateDragScalar("UDim2", 4, UDim2.new()))
Iris.WidgetConstructor("DragRect", generateDragScalar("Rect", 4, Rect.new(0, 0, 0, 0)))
Iris.WidgetConstructor("InputColor3", generateColorDragScalar("Color3", Color3.fromRGB(0, 0, 0)))
Iris.WidgetConstructor("InputColor4", generateColorDragScalar("Color4", Color3.fromRGB(0, 0, 0), 0))
Iris.WidgetConstructor("SliderNum", generateSliderScalar("Num", 1, 0))
Iris.WidgetConstructor("SliderVector2", generateSliderScalar("Vector2", 2, Vector2.zero))
Iris.WidgetConstructor("SliderVector3", generateSliderScalar("Vector3", 3, Vector3.zero))
Iris.WidgetConstructor("SliderUDim", generateSliderScalar("UDim", 2, UDim.new()))
Iris.WidgetConstructor("SliderUDim2", generateSliderScalar("UDim2", 4, UDim2.new()))
Iris.WidgetConstructor("SliderRect", generateSliderScalar("Rect", 4, Rect.new(0, 0, 0, 0)))
-- Iris.WidgetConstructor("SliderEnum", generateSliderScalar("Enum", 4, 0))
-- stylua: ignore
Iris.WidgetConstructor("InputText", {
hasState = true,
hasChildren = false,
Args = {
["Text"] = 1,
["TextHint"] = 2,
["ReadOnly"] = 3,
["MultiLine"] = 4,
},
Events = {
["textChanged"] = {
["Init"] = function(thisWidget: Types.InputText)
thisWidget.lastTextChangedTick = 0
end,
["Get"] = function(thisWidget: Types.InputText)
return thisWidget.lastTextChangedTick == Iris._cycleTick
end,
},
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(thisWidget: Types.InputText)
local InputText: Frame = Instance.new("Frame")
InputText.Name = "Iris_InputText"
InputText.AutomaticSize = Enum.AutomaticSize.Y
InputText.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
InputText.BackgroundTransparency = 1
InputText.BorderSizePixel = 0
widgets.UIListLayout(InputText, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
local InputField: TextBox = Instance.new("TextBox")
InputField.Name = "InputField"
InputField.AutomaticSize = Enum.AutomaticSize.Y
InputField.Size = UDim2.new(Iris._config.ContentWidth, Iris._config.ContentHeight)
InputField.BackgroundColor3 = Iris._config.FrameBgColor
InputField.BackgroundTransparency = Iris._config.FrameBgTransparency
InputField.Text = ""
InputField.TextYAlignment = Enum.TextYAlignment.Top
InputField.PlaceholderColor3 = Iris._config.TextDisabledColor
InputField.ClearTextOnFocus = false
InputField.ClipsDescendants = true
widgets.applyFrameStyle(InputField)
widgets.applyTextStyle(InputField)
widgets.UISizeConstraint(InputField, Vector2.xAxis) -- prevents sizes beaking when getting too small.
-- InputField.UIPadding.PaddingLeft = UDim.new(0, Iris._config.ItemInnerSpacing.X)
-- InputField.UIPadding.PaddingRight = UDim.new(0, 0)
InputField.Parent = InputText
InputField.FocusLost:Connect(function()
thisWidget.state.text:set(InputField.Text)
thisWidget.lastTextChangedTick = Iris._cycleTick + 1
end)
local frameHeight: number = Iris._config.TextSize + 2 * Iris._config.FramePadding.Y
local TextLabel: TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.X
TextLabel.Size = UDim2.fromOffset(0, frameHeight)
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.LayoutOrder = 1
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = InputText
return InputText
end,
GenerateState = function(thisWidget: Types.InputText)
if thisWidget.state.text == nil then
thisWidget.state.text = Iris._widgetState(thisWidget, "text", "")
end
end,
Update = function(thisWidget: Types.InputText)
local InputText = thisWidget.Instance :: Frame
local TextLabel: TextLabel = InputText.TextLabel
local InputField: TextBox = InputText.InputField
TextLabel.Text = thisWidget.arguments.Text or "Input Text"
InputField.PlaceholderText = thisWidget.arguments.TextHint or ""
InputField.TextEditable = not thisWidget.arguments.ReadOnly
InputField.MultiLine = thisWidget.arguments.MultiLine or false
end,
UpdateState = function(thisWidget: Types.InputText)
local InputText = thisWidget.Instance :: Frame
local InputField: TextBox = InputText.InputField
InputField.Text = thisWidget.state.text.value
end,
Discard = function(thisWidget: Types.InputText)
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
end
| 12,590 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Menu.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local AnyMenuOpen = false
local ActiveMenu: Types.Menu? = nil
local MenuStack: { Types.Menu } = {}
local function EmptyMenuStack(menuIndex: number?)
for index = #MenuStack, menuIndex and menuIndex + 1 or 1, -1 do
local widget = MenuStack[index]
widget.state.isOpened:set(false)
widget.Instance.BackgroundColor3 = Iris._config.HeaderColor
widget.Instance.BackgroundTransparency = 1
table.remove(MenuStack, index)
end
if #MenuStack == 0 then
AnyMenuOpen = false
ActiveMenu = nil
end
end
local function UpdateChildContainerTransform(thisWidget: Types.Menu)
local submenu = thisWidget.parentWidget.type == "Menu"
local Menu = thisWidget.Instance :: Frame
local ChildContainer = thisWidget.ChildContainer :: ScrollingFrame
ChildContainer.Size = UDim2.fromOffset(Menu.AbsoluteSize.X, 0)
if ChildContainer.Parent == nil then
return
end
local menuPosition = Menu.AbsolutePosition - widgets.GuiOffset
local menuSize = Menu.AbsoluteSize
local containerSize = ChildContainer.AbsoluteSize
local borderSize = Iris._config.PopupBorderSize
local screenSize: Vector2 = ChildContainer.Parent.AbsoluteSize
local x = menuPosition.X
local y
local anchor = Vector2.zero
if submenu then
if menuPosition.X + containerSize.X > screenSize.X then
anchor = Vector2.xAxis
else
x = menuPosition.X + menuSize.X
end
end
if menuPosition.Y + containerSize.Y > screenSize.Y then
-- too low.
y = menuPosition.Y - borderSize + (submenu and menuSize.Y or 0)
anchor += Vector2.yAxis
else
y = menuPosition.Y + borderSize + (submenu and 0 or menuSize.Y)
end
ChildContainer.Position = UDim2.fromOffset(x, y)
ChildContainer.AnchorPoint = anchor
end
widgets.registerEvent("InputBegan", function(inputObject: InputObject)
if not Iris._started then
return
end
if inputObject.UserInputType ~= Enum.UserInputType.MouseButton1 and inputObject.UserInputType ~= Enum.UserInputType.MouseButton2 then
return
end
if AnyMenuOpen == false then
return
end
if ActiveMenu == nil then
return
end
-- this only checks if we clicked outside all the menus. If we clicked in any menu, then the hover function handles this.
local isInMenu = false
local MouseLocation = widgets.getMouseLocation()
for _, menu in MenuStack do
for _, container in { menu.ChildContainer, menu.Instance } do
local rectMin = container.AbsolutePosition - widgets.GuiOffset
local rectMax = rectMin + container.AbsoluteSize
if widgets.isPosInsideRect(MouseLocation, rectMin, rectMax) then
isInMenu = true
break
end
end
if isInMenu then
break
end
end
if not isInMenu then
EmptyMenuStack()
end
end)
--stylua: ignore
Iris.WidgetConstructor("MenuBar", {
hasState = false,
hasChildren = true,
Args = {},
Events = {},
Generate = function(_thisWidget: Types.MenuBar)
local MenuBar = Instance.new("Frame")
MenuBar.Name = "Iris_MenuBar"
MenuBar.AutomaticSize = Enum.AutomaticSize.Y
MenuBar.Size = UDim2.fromScale(1, 0)
MenuBar.BackgroundColor3 = Iris._config.MenubarBgColor
MenuBar.BackgroundTransparency = Iris._config.MenubarBgTransparency
MenuBar.BorderSizePixel = 0
MenuBar.ClipsDescendants = true
widgets.UIPadding(MenuBar, Vector2.new(Iris._config.WindowPadding.X, 1))
widgets.UIListLayout(MenuBar, Enum.FillDirection.Horizontal, UDim.new()).VerticalAlignment = Enum.VerticalAlignment.Center
widgets.applyFrameStyle(MenuBar, true, true)
return MenuBar
end,
Update = function(_thisWidget: Types.Widget)
end,
ChildAdded = function(thisWidget: Types.MenuBar, _thisChild: Types.Widget)
return thisWidget.Instance
end,
Discard = function(thisWidget: Types.MenuBar)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
--stylua: ignore
Iris.WidgetConstructor("Menu", {
hasState = true,
hasChildren = true,
Args = {
["Text"] = 1,
},
Events = {
["clicked"] = widgets.EVENTS.click(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["opened"] = {
["Init"] = function(_thisWidget: Types.Menu) end,
["Get"] = function(thisWidget: Types.Menu)
return thisWidget.lastOpenedTick == Iris._cycleTick
end,
},
["closed"] = {
["Init"] = function(_thisWidget: Types.Menu) end,
["Get"] = function(thisWidget: Types.Menu)
return thisWidget.lastClosedTick == Iris._cycleTick
end,
},
},
Generate = function(thisWidget: Types.Menu)
local Menu: TextButton
thisWidget.ButtonColors = {
Color = Iris._config.HeaderColor,
Transparency = 1,
HoveredColor = Iris._config.HeaderHoveredColor,
HoveredTransparency = Iris._config.HeaderHoveredTransparency,
ActiveColor = Iris._config.HeaderHoveredColor,
ActiveTransparency = Iris._config.HeaderHoveredTransparency,
}
if thisWidget.parentWidget.type == "Menu" then
-- this Menu is a sub-Menu
Menu = Instance.new("TextButton")
Menu.Name = "Menu"
Menu.AutomaticSize = Enum.AutomaticSize.Y
Menu.Size = UDim2.fromScale(1, 0)
Menu.BackgroundColor3 = Iris._config.HeaderColor
Menu.BackgroundTransparency = 1
Menu.BorderSizePixel = 0
Menu.Text = ""
Menu.AutoButtonColor = false
local UIPadding = widgets.UIPadding(Menu, Iris._config.FramePadding)
UIPadding.PaddingTop = UIPadding.PaddingTop - UDim.new(0, 1)
widgets.UIListLayout(Menu, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = Menu
local frameSize = Iris._config.TextSize + 2 * Iris._config.FramePadding.Y
local padding = math.round(0.2 * frameSize)
local iconSize = frameSize - 2 * padding
local Icon = Instance.new("ImageLabel")
Icon.Name = "Icon"
Icon.Size = UDim2.fromOffset(iconSize, iconSize)
Icon.BackgroundTransparency = 1
Icon.BorderSizePixel = 0
Icon.ImageColor3 = Iris._config.TextColor
Icon.ImageTransparency = Iris._config.TextTransparency
Icon.Image = widgets.ICONS.RIGHT_POINTING_TRIANGLE
Icon.LayoutOrder = 1
Icon.Parent = Menu
else
Menu = Instance.new("TextButton")
Menu.Name = "Menu"
Menu.AutomaticSize = Enum.AutomaticSize.XY
Menu.Size = UDim2.fromScale(0, 0)
Menu.BackgroundColor3 = Iris._config.HeaderColor
Menu.BackgroundTransparency = 1
Menu.BorderSizePixel = 0
Menu.Text = ""
Menu.AutoButtonColor = false
Menu.ClipsDescendants = true
widgets.applyTextStyle(Menu)
widgets.UIPadding(Menu, Vector2.new(Iris._config.ItemSpacing.X, Iris._config.FramePadding.Y))
end
widgets.applyInteractionHighlights("Background", Menu, Menu, thisWidget.ButtonColors)
widgets.applyButtonClick(Menu, function()
local openMenu = if #MenuStack <= 1 then not thisWidget.state.isOpened.value else true
thisWidget.state.isOpened:set(openMenu)
AnyMenuOpen = openMenu
ActiveMenu = openMenu and thisWidget or nil
-- the hovering should handle all of the menus after the first one.
if #MenuStack <= 1 then
if openMenu then
table.insert(MenuStack, thisWidget)
else
table.remove(MenuStack)
end
end
end)
widgets.applyMouseEnter(Menu, function()
if AnyMenuOpen and ActiveMenu and ActiveMenu ~= thisWidget then
local parentMenu = thisWidget.parentWidget :: Types.Menu
local parentIndex = table.find(MenuStack, parentMenu)
EmptyMenuStack(parentIndex)
thisWidget.state.isOpened:set(true)
ActiveMenu = thisWidget
AnyMenuOpen = true
table.insert(MenuStack, thisWidget)
end
end)
local ChildContainer = Instance.new("ScrollingFrame")
ChildContainer.Name = "MenuContainer"
ChildContainer.AutomaticSize = Enum.AutomaticSize.XY
ChildContainer.Size = UDim2.fromOffset(0, 0)
ChildContainer.BackgroundColor3 = Iris._config.PopupBgColor
ChildContainer.BackgroundTransparency = Iris._config.PopupBgTransparency
ChildContainer.BorderSizePixel = 0
ChildContainer.AutomaticCanvasSize = Enum.AutomaticSize.Y
ChildContainer.ScrollBarImageTransparency = Iris._config.ScrollbarGrabTransparency
ChildContainer.ScrollBarImageColor3 = Iris._config.ScrollbarGrabColor
ChildContainer.ScrollBarThickness = Iris._config.ScrollbarSize
ChildContainer.CanvasSize = UDim2.fromScale(0, 0)
ChildContainer.VerticalScrollBarInset = Enum.ScrollBarInset.ScrollBar
ChildContainer.TopImage = widgets.ICONS.BLANK_SQUARE
ChildContainer.MidImage = widgets.ICONS.BLANK_SQUARE
ChildContainer.BottomImage = widgets.ICONS.BLANK_SQUARE
ChildContainer.ZIndex = 6
ChildContainer.LayoutOrder = 6
ChildContainer.ClipsDescendants = true
-- Unfortunatley, ScrollingFrame does not work with UICorner
-- if Iris._config.PopupRounding > 0 then
-- widgets.UICorner(ChildContainer, Iris._config.PopupRounding)
-- end
widgets.UIStroke(ChildContainer, Iris._config.WindowBorderSize, Iris._config.BorderColor, Iris._config.BorderTransparency)
widgets.UIPadding(ChildContainer, Vector2.new(2, Iris._config.WindowPadding.Y - Iris._config.ItemSpacing.Y))
widgets.UIListLayout(ChildContainer, Enum.FillDirection.Vertical, UDim.new(0, 1)).VerticalAlignment = Enum.VerticalAlignment.Top
local RootPopupScreenGui = Iris._rootInstance and Iris._rootInstance:FindFirstChild("PopupScreenGui") :: GuiObject
ChildContainer.Parent = RootPopupScreenGui
thisWidget.ChildContainer = ChildContainer
return Menu
end,
Update = function(thisWidget: Types.Menu)
local Menu = thisWidget.Instance :: TextButton
local TextLabel: TextLabel
if thisWidget.parentWidget.type == "Menu" then
TextLabel = Menu.TextLabel
else
TextLabel = Menu
end
TextLabel.Text = thisWidget.arguments.Text or "Menu"
end,
ChildAdded = function(thisWidget: Types.Menu, _thisChild: Types.Widget)
UpdateChildContainerTransform(thisWidget)
return thisWidget.ChildContainer
end,
ChildDiscarded = function(thisWidget: Types.Menu, _thisChild: Types.Widget)
UpdateChildContainerTransform(thisWidget)
end,
GenerateState = function(thisWidget: Types.Menu)
if thisWidget.state.isOpened == nil then
thisWidget.state.isOpened = Iris._widgetState(thisWidget, "isOpened", false)
end
end,
UpdateState = function(thisWidget: Types.Menu)
local ChildContainer = thisWidget.ChildContainer :: ScrollingFrame
if thisWidget.state.isOpened.value then
thisWidget.lastOpenedTick = Iris._cycleTick + 1
thisWidget.ButtonColors.Transparency = Iris._config.HeaderTransparency
ChildContainer.Visible = true
UpdateChildContainerTransform(thisWidget)
else
thisWidget.lastClosedTick = Iris._cycleTick + 1
thisWidget.ButtonColors.Transparency = 1
ChildContainer.Visible = false
end
end,
Discard = function(thisWidget: Types.Menu)
-- properly handle removing a menu if open and deleted
if AnyMenuOpen then
local parentMenu = thisWidget.parentWidget :: Types.Menu
local parentIndex = table.find(MenuStack, parentMenu)
if parentIndex then
EmptyMenuStack(parentIndex)
if #MenuStack ~= 0 then
ActiveMenu = parentMenu
AnyMenuOpen = true
end
end
end
thisWidget.Instance:Destroy()
thisWidget.ChildContainer:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
--stylua: ignore
Iris.WidgetConstructor("MenuItem", {
hasState = false,
hasChildren = false,
Args = {
Text = 1,
KeyCode = 2,
ModifierKey = 3,
},
Events = {
["clicked"] = widgets.EVENTS.click(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(thisWidget: Types.MenuItem)
local MenuItem = Instance.new("TextButton")
MenuItem.Name = "Iris_MenuItem"
MenuItem.AutomaticSize = Enum.AutomaticSize.Y
MenuItem.Size = UDim2.fromScale(1, 0)
MenuItem.BackgroundTransparency = 1
MenuItem.BorderSizePixel = 0
MenuItem.Text = ""
MenuItem.AutoButtonColor = false
local UIPadding = widgets.UIPadding(MenuItem, Iris._config.FramePadding)
UIPadding.PaddingTop = UIPadding.PaddingTop - UDim.new(0, 1)
widgets.UIListLayout(MenuItem, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X))
widgets.applyInteractionHighlights("Background", MenuItem, MenuItem, {
Color = Iris._config.HeaderColor,
Transparency = 1,
HoveredColor = Iris._config.HeaderHoveredColor,
HoveredTransparency = Iris._config.HeaderHoveredTransparency,
ActiveColor = Iris._config.HeaderHoveredColor,
ActiveTransparency = Iris._config.HeaderHoveredTransparency,
})
widgets.applyButtonClick(MenuItem, function()
EmptyMenuStack()
end)
widgets.applyMouseEnter(MenuItem, function()
local parentMenu = thisWidget.parentWidget :: Types.Menu
if AnyMenuOpen and ActiveMenu and ActiveMenu ~= parentMenu then
local parentIndex = table.find(MenuStack, parentMenu)
EmptyMenuStack(parentIndex)
ActiveMenu = parentMenu
AnyMenuOpen = true
end
end)
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = MenuItem
local Shortcut = Instance.new("TextLabel")
Shortcut.Name = "Shortcut"
Shortcut.AutomaticSize = Enum.AutomaticSize.XY
Shortcut.BackgroundTransparency = 1
Shortcut.BorderSizePixel = 0
Shortcut.LayoutOrder = 1
widgets.applyTextStyle(Shortcut)
Shortcut.Text = ""
Shortcut.TextColor3 = Iris._config.TextDisabledColor
Shortcut.TextTransparency = Iris._config.TextDisabledTransparency
Shortcut.Parent = MenuItem
return MenuItem
end,
Update = function(thisWidget: Types.MenuItem)
local MenuItem = thisWidget.Instance :: TextButton
local TextLabel: TextLabel = MenuItem.TextLabel
local Shortcut: TextLabel = MenuItem.Shortcut
TextLabel.Text = thisWidget.arguments.Text
if thisWidget.arguments.KeyCode then
if thisWidget.arguments.ModifierKey then
Shortcut.Text = thisWidget.arguments.ModifierKey.Name .. " + " .. thisWidget.arguments.KeyCode.Name
else
Shortcut.Text = thisWidget.arguments.KeyCode.Name
end
end
end,
Discard = function(thisWidget: Types.MenuItem)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
--stylua: ignore
Iris.WidgetConstructor("MenuToggle", {
hasState = true,
hasChildren = false,
Args = {
Text = 1,
KeyCode = 2,
ModifierKey = 3,
},
Events = {
["checked"] = {
["Init"] = function(_thisWidget: Types.MenuToggle) end,
["Get"] = function(thisWidget: Types.MenuToggle): boolean
return thisWidget.lastCheckedTick == Iris._cycleTick
end,
},
["unchecked"] = {
["Init"] = function(_thisWidget: Types.MenuToggle) end,
["Get"] = function(thisWidget: Types.MenuToggle): boolean
return thisWidget.lastUncheckedTick == Iris._cycleTick
end,
},
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(thisWidget: Types.MenuToggle)
local MenuToggle = Instance.new("TextButton")
MenuToggle.Name = "Iris_MenuToggle"
MenuToggle.AutomaticSize = Enum.AutomaticSize.Y
MenuToggle.Size = UDim2.fromScale(1, 0)
MenuToggle.BackgroundTransparency = 1
MenuToggle.BorderSizePixel = 0
MenuToggle.Text = ""
MenuToggle.AutoButtonColor = false
local UIPadding = widgets.UIPadding(MenuToggle, Iris._config.FramePadding)
UIPadding.PaddingTop = UIPadding.PaddingTop - UDim.new(0, 1)
widgets.UIListLayout(MenuToggle, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
widgets.applyInteractionHighlights("Background", MenuToggle, MenuToggle, {
Color = Iris._config.HeaderColor,
Transparency = 1,
HoveredColor = Iris._config.HeaderHoveredColor,
HoveredTransparency = Iris._config.HeaderHoveredTransparency,
ActiveColor = Iris._config.HeaderHoveredColor,
ActiveTransparency = Iris._config.HeaderHoveredTransparency,
})
widgets.applyButtonClick(MenuToggle, function()
thisWidget.state.isChecked:set(not thisWidget.state.isChecked.value)
EmptyMenuStack()
end)
widgets.applyMouseEnter(MenuToggle, function()
local parentMenu = thisWidget.parentWidget :: Types.Menu
if AnyMenuOpen and ActiveMenu and ActiveMenu ~= parentMenu then
local parentIndex = table.find(MenuStack, parentMenu)
EmptyMenuStack(parentIndex)
ActiveMenu = parentMenu
AnyMenuOpen = true
end
end)
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = MenuToggle
local Shortcut = Instance.new("TextLabel")
Shortcut.Name = "Shortcut"
Shortcut.AutomaticSize = Enum.AutomaticSize.XY
Shortcut.BackgroundTransparency = 1
Shortcut.BorderSizePixel = 0
Shortcut.LayoutOrder = 1
widgets.applyTextStyle(Shortcut)
Shortcut.Text = ""
Shortcut.TextColor3 = Iris._config.TextDisabledColor
Shortcut.TextTransparency = Iris._config.TextDisabledTransparency
Shortcut.Parent = MenuToggle
local frameSize = Iris._config.TextSize + 2 * Iris._config.FramePadding.Y
local padding = math.round(0.2 * frameSize)
local iconSize = frameSize - 2 * padding
local Icon = Instance.new("ImageLabel")
Icon.Name = "Icon"
Icon.Size = UDim2.fromOffset(iconSize, iconSize)
Icon.BackgroundTransparency = 1
Icon.BorderSizePixel = 0
Icon.ImageColor3 = Iris._config.TextColor
Icon.ImageTransparency = Iris._config.TextTransparency
Icon.Image = widgets.ICONS.CHECKMARK
Icon.LayoutOrder = 2
Icon.Parent = MenuToggle
return MenuToggle
end,
GenerateState = function(thisWidget: Types.MenuToggle)
if thisWidget.state.isChecked == nil then
thisWidget.state.isChecked = Iris._widgetState(thisWidget, "isChecked", false)
end
end,
Update = function(thisWidget: Types.MenuToggle)
local MenuToggle = thisWidget.Instance :: TextButton
local TextLabel: TextLabel = MenuToggle.TextLabel
local Shortcut: TextLabel = MenuToggle.Shortcut
TextLabel.Text = thisWidget.arguments.Text
if thisWidget.arguments.KeyCode then
if thisWidget.arguments.ModifierKey then
Shortcut.Text = thisWidget.arguments.ModifierKey.Name .. " + " .. thisWidget.arguments.KeyCode.Name
else
Shortcut.Text = thisWidget.arguments.KeyCode.Name
end
end
end,
UpdateState = function(thisWidget: Types.MenuToggle)
local MenuItem = thisWidget.Instance :: TextButton
local Icon: ImageLabel = MenuItem.Icon
if thisWidget.state.isChecked.value then
Icon.ImageTransparency = Iris._config.TextTransparency
thisWidget.lastCheckedTick = Iris._cycleTick + 1
else
Icon.ImageTransparency = 1
thisWidget.lastUncheckedTick = Iris._cycleTick + 1
end
end,
Discard = function(thisWidget: Types.MenuToggle)
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
end
| 4,927 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Plot.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
-- stylua: ignore
Iris.WidgetConstructor("ProgressBar", {
hasState = true,
hasChildren = false,
Args = {
["Text"] = 1,
["Format"] = 2,
},
Events = {
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["changed"] = {
["Init"] = function(_thisWidget: Types.ProgressBar) end,
["Get"] = function(thisWidget: Types.ProgressBar)
return thisWidget.lastChangedTick == Iris._cycleTick
end,
},
},
Generate = function(_thisWidget: Types.ProgressBar)
local ProgressBar = Instance.new("Frame")
ProgressBar.Name = "Iris_ProgressBar"
ProgressBar.AutomaticSize = Enum.AutomaticSize.Y
ProgressBar.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
ProgressBar.BackgroundTransparency = 1
widgets.UIListLayout(ProgressBar, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
local Bar = Instance.new("Frame")
Bar.Name = "Bar"
Bar.AutomaticSize = Enum.AutomaticSize.Y
Bar.Size = UDim2.new(Iris._config.ContentWidth, Iris._config.ContentHeight)
Bar.BackgroundColor3 = Iris._config.FrameBgColor
Bar.BackgroundTransparency = Iris._config.FrameBgTransparency
Bar.BorderSizePixel = 0
Bar.ClipsDescendants = true
widgets.applyFrameStyle(Bar, true)
Bar.Parent = ProgressBar
local Progress = Instance.new("TextLabel")
Progress.Name = "Progress"
Progress.AutomaticSize = Enum.AutomaticSize.Y
Progress.Size = UDim2.new(UDim.new(0, 0), Iris._config.ContentHeight)
Progress.BackgroundColor3 = Iris._config.PlotHistogramColor
Progress.BackgroundTransparency = Iris._config.PlotHistogramTransparency
Progress.BorderSizePixel = 0
widgets.applyTextStyle(Progress)
widgets.UIPadding(Progress, Iris._config.FramePadding)
widgets.UICorner(Progress, Iris._config.FrameRounding)
Progress.Text = ""
Progress.Parent = Bar
local Value = Instance.new("TextLabel")
Value.Name = "Value"
Value.AutomaticSize = Enum.AutomaticSize.XY
Value.Size = UDim2.new(UDim.new(0, 0), Iris._config.ContentHeight)
Value.BackgroundTransparency = 1
Value.BorderSizePixel = 0
Value.ZIndex = 1
widgets.applyTextStyle(Value)
widgets.UIPadding(Value, Iris._config.FramePadding)
Value.Parent = Bar
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.AnchorPoint = Vector2.new(0, 0.5)
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.LayoutOrder = 1
widgets.applyTextStyle(TextLabel)
widgets.UIPadding(Value, Iris._config.FramePadding)
TextLabel.Parent = ProgressBar
return ProgressBar
end,
GenerateState = function(thisWidget: Types.ProgressBar)
if thisWidget.state.progress == nil then
thisWidget.state.progress = Iris._widgetState(thisWidget, "Progress", 0)
end
end,
Update = function(thisWidget: Types.ProgressBar)
local Progress = thisWidget.Instance :: Frame
local TextLabel: TextLabel = Progress.TextLabel
local Bar = Progress.Bar :: Frame
local Value: TextLabel = Bar.Value
if thisWidget.arguments.Format ~= nil and typeof(thisWidget.arguments.Format) == "string" then
Value.Text = thisWidget.arguments.Format
end
TextLabel.Text = thisWidget.arguments.Text or "Progress Bar"
end,
UpdateState = function(thisWidget: Types.ProgressBar)
local ProgressBar = thisWidget.Instance :: Frame
local Bar = ProgressBar.Bar :: Frame
local Progress: TextLabel = Bar.Progress
local Value: TextLabel = Bar.Value
local progress = math.clamp(thisWidget.state.progress.value, 0, 1)
local totalWidth = Bar.AbsoluteSize.X
local textWidth = Value.AbsoluteSize.X
if totalWidth * (1 - progress) < textWidth then
Value.AnchorPoint = Vector2.xAxis
Value.Position = UDim2.fromScale(1, 0)
else
Value.AnchorPoint = Vector2.zero
Value.Position = UDim2.fromScale(progress, 0)
end
Progress.Size = UDim2.new(UDim.new(progress, 0), Progress.Size.Height)
if thisWidget.arguments.Format ~= nil and typeof(thisWidget.arguments.Format) == "string" then
Value.Text = thisWidget.arguments.Format
else
Value.Text = string.format("%d%%", progress * 100)
end
thisWidget.lastChangedTick = Iris._cycleTick + 1
end,
Discard = function(thisWidget: Types.ProgressBar)
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
local function createLine(parent: Frame, index: number)
local Block = Instance.new("Frame")
Block.Name = tostring(index)
Block.AnchorPoint = Vector2.new(0.5, 0.5)
Block.BackgroundColor3 = Iris._config.PlotLinesColor
Block.BackgroundTransparency = Iris._config.PlotLinesTransparency
Block.BorderSizePixel = 0
Block.Parent = parent
return Block
end
local function clearLine(thisWidget: Types.PlotLines)
if thisWidget.HoveredLine then
thisWidget.HoveredLine.BackgroundColor3 = Iris._config.PlotLinesColor
thisWidget.HoveredLine.BackgroundTransparency = Iris._config.PlotLinesTransparency
thisWidget.HoveredLine = false
thisWidget.state.hovered:set(nil)
end
end
local function updateLine(thisWidget: Types.PlotLines, silent: true?)
local PlotLines = thisWidget.Instance :: Frame
local Background = PlotLines.Background :: Frame
local Plot = Background.Plot :: Frame
local mousePosition = widgets.getMouseLocation()
local position = Plot.AbsolutePosition - widgets.GuiOffset
local scale = (mousePosition.X - position.X) / Plot.AbsoluteSize.X
local index = math.ceil(scale * #thisWidget.Lines)
local line: Frame? = thisWidget.Lines[index]
if line then
if line ~= thisWidget.HoveredLine and not silent then
clearLine(thisWidget)
end
local start: number? = thisWidget.state.values.value[index]
local stop: number? = thisWidget.state.values.value[index + 1]
if start and stop then
if math.floor(start) == start and math.floor(stop) == stop then
thisWidget.Tooltip.Text = ("%d: %d\n%d: %d"):format(index, start, index + 1, stop)
else
thisWidget.Tooltip.Text = ("%d: %.3f\n%d: %.3f"):format(index, start, index + 1, stop)
end
end
thisWidget.HoveredLine = line
line.BackgroundColor3 = Iris._config.PlotLinesHoveredColor
line.BackgroundTransparency = Iris._config.PlotLinesHoveredTransparency
if silent then
thisWidget.state.hovered.value = { start, stop }
else
thisWidget.state.hovered:set({ start, stop })
end
end
end
-- stylua: ignore
Iris.WidgetConstructor("PlotLines", {
hasState = true,
hasChildren = false,
Args = {
["Text"] = 1,
["Height"] = 2,
["Min"] = 3,
["Max"] = 4,
["TextOverlay"] = 5,
},
Events = {
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(thisWidget: Types.PlotLines)
local PlotLines = Instance.new("Frame")
PlotLines.Name = "Iris_PlotLines"
PlotLines.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
PlotLines.BackgroundTransparency = 1
PlotLines.BorderSizePixel = 0
widgets.UIListLayout(PlotLines, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
local Background = Instance.new("Frame")
Background.Name = "Background"
Background.Size = UDim2.new(Iris._config.ContentWidth, UDim.new(1, 0))
Background.BackgroundColor3 = Iris._config.FrameBgColor
Background.BackgroundTransparency = Iris._config.FrameBgTransparency
widgets.applyFrameStyle(Background)
Background.Parent = PlotLines
local Plot = Instance.new("Frame")
Plot.Name = "Plot"
Plot.Size = UDim2.fromScale(1, 1)
Plot.BackgroundTransparency = 1
Plot.BorderSizePixel = 0
Plot.ClipsDescendants = true
Plot:GetPropertyChangedSignal("AbsoluteSize"):Connect(function()
thisWidget.state.values.lastChangeTick = Iris._cycleTick
Iris._widgets.PlotLines.UpdateState(thisWidget)
end)
local OverlayText = Instance.new("TextLabel")
OverlayText.Name = "OverlayText"
OverlayText.AutomaticSize = Enum.AutomaticSize.XY
OverlayText.AnchorPoint = Vector2.new(0.5, 0)
OverlayText.Size = UDim2.fromOffset(0, 0)
OverlayText.Position = UDim2.fromScale(0.5, 0)
OverlayText.BackgroundTransparency = 1
OverlayText.BorderSizePixel = 0
OverlayText.ZIndex = 2
widgets.applyTextStyle(OverlayText)
OverlayText.Parent = Plot
local Tooltip = Instance.new("TextLabel")
Tooltip.Name = "Iris_Tooltip"
Tooltip.AutomaticSize = Enum.AutomaticSize.XY
Tooltip.Size = UDim2.fromOffset(0, 0)
Tooltip.BackgroundColor3 = Iris._config.PopupBgColor
Tooltip.BackgroundTransparency = Iris._config.PopupBgTransparency
Tooltip.BorderSizePixel = 0
Tooltip.Visible = false
widgets.applyTextStyle(Tooltip)
widgets.UIStroke(Tooltip, Iris._config.PopupBorderSize, Iris._config.BorderActiveColor, Iris._config.BorderActiveTransparency)
widgets.UIPadding(Tooltip, Iris._config.WindowPadding)
if Iris._config.PopupRounding > 0 then
widgets.UICorner(Tooltip, Iris._config.PopupRounding)
end
local popup = Iris._rootInstance and Iris._rootInstance:FindFirstChild("PopupScreenGui")
Tooltip.Parent = popup and popup:FindFirstChild("TooltipContainer")
thisWidget.Tooltip = Tooltip
widgets.applyMouseMoved(Plot, function()
updateLine(thisWidget)
end)
widgets.applyMouseLeave(Plot, function()
clearLine(thisWidget)
end)
Plot.Parent = Background
thisWidget.Lines = {}
thisWidget.HoveredLine = false
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.Size = UDim2.fromOffset(0, 0)
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.ZIndex = 3
TextLabel.LayoutOrder = 3
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = PlotLines
return PlotLines
end,
GenerateState = function(thisWidget: Types.PlotLines)
if thisWidget.state.values == nil then
thisWidget.state.values = Iris._widgetState(thisWidget, "values", { 0, 1 })
end
if thisWidget.state.hovered == nil then
thisWidget.state.hovered = Iris._widgetState(thisWidget, "hovered", nil)
end
end,
Update = function(thisWidget: Types.PlotLines)
local PlotLines = thisWidget.Instance :: Frame
local TextLabel: TextLabel = PlotLines.TextLabel
local Background = PlotLines.Background :: Frame
local Plot = Background.Plot :: Frame
local OverlayText: TextLabel = Plot.OverlayText
TextLabel.Text = thisWidget.arguments.Text or "Plot Lines"
OverlayText.Text = thisWidget.arguments.TextOverlay or ""
PlotLines.Size = UDim2.new(1, 0, 0, thisWidget.arguments.Height or 0)
end,
UpdateState = function(thisWidget: Types.PlotLines)
if thisWidget.state.hovered.lastChangeTick == Iris._cycleTick then
if thisWidget.state.hovered.value then
thisWidget.Tooltip.Visible = true
else
thisWidget.Tooltip.Visible = false
end
end
if thisWidget.state.values.lastChangeTick == Iris._cycleTick then
local PlotLines = thisWidget.Instance :: Frame
local Background = PlotLines.Background :: Frame
local Plot = Background.Plot :: Frame
local values = thisWidget.state.values.value
local count = #values - 1
local numLines = #thisWidget.Lines
local min = thisWidget.arguments.Min or math.huge
local max = thisWidget.arguments.Max or -math.huge
if min == nil or max == nil then
for _, value in values do
min = math.min(min, value)
max = math.max(max, value)
end
end
-- add or remove blocks depending on how many are needed
if numLines < count then
for index = numLines + 1, count do
table.insert(thisWidget.Lines, createLine(Plot, index))
end
elseif numLines > count then
for _ = count + 1, numLines do
local line = table.remove(thisWidget.Lines)
if line then
line:Destroy()
end
end
end
local range = max - min
local size = Plot.AbsoluteSize
for index = 1, count do
local start = values[index]
local stop = values[index + 1]
local a = size * Vector2.new((index - 1) / count, (max - start) / range)
local b = size * Vector2.new(index / count, (max - stop) / range)
local position = (a + b) / 2
thisWidget.Lines[index].Size = UDim2.fromOffset((b - a).Magnitude + 1, 1)
thisWidget.Lines[index].Position = UDim2.fromOffset(position.X, position.Y)
thisWidget.Lines[index].Rotation = math.atan2(b.Y - a.Y, b.X - a.X) * (180 / math.pi)
end
-- only update the hovered block if it exists.
if thisWidget.HoveredLine then
updateLine(thisWidget, true)
end
end
end,
Discard = function(thisWidget: Types.PlotLines)
thisWidget.Instance:Destroy()
thisWidget.Tooltip:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
local function createBlock(parent: Frame, index: number)
local Block = Instance.new("Frame")
Block.Name = tostring(index)
Block.BackgroundColor3 = Iris._config.PlotHistogramColor
Block.BackgroundTransparency = Iris._config.PlotHistogramTransparency
Block.BorderSizePixel = 0
Block.Parent = parent
return Block
end
local function clearBlock(thisWidget: Types.PlotHistogram)
if thisWidget.HoveredBlock then
thisWidget.HoveredBlock.BackgroundColor3 = Iris._config.PlotHistogramColor
thisWidget.HoveredBlock.BackgroundTransparency = Iris._config.PlotHistogramTransparency
thisWidget.HoveredBlock = false
thisWidget.state.hovered:set(nil)
end
end
local function updateBlock(thisWidget: Types.PlotHistogram, silent: true?)
local PlotHistogram = thisWidget.Instance :: Frame
local Background = PlotHistogram.Background :: Frame
local Plot = Background.Plot :: Frame
local mousePosition = widgets.getMouseLocation()
local position = Plot.AbsolutePosition - widgets.GuiOffset
local scale = (mousePosition.X - position.X) / Plot.AbsoluteSize.X
local index = math.ceil(scale * #thisWidget.Blocks)
local block: Frame? = thisWidget.Blocks[index]
if block then
if block ~= thisWidget.HoveredBlock and not silent then
clearBlock(thisWidget)
end
local value: number? = thisWidget.state.values.value[index]
if value then
thisWidget.Tooltip.Text = if math.floor(value) == value then ("%d: %d"):format(index, value) else ("%d: %.3f"):format(index, value)
end
thisWidget.HoveredBlock = block
block.BackgroundColor3 = Iris._config.PlotHistogramHoveredColor
block.BackgroundTransparency = Iris._config.PlotHistogramHoveredTransparency
if silent then
thisWidget.state.hovered.value = value
else
thisWidget.state.hovered:set(value)
end
end
end
-- stylua: ignore
Iris.WidgetConstructor("PlotHistogram", {
hasState = true,
hasChildren = false,
Args = {
["Text"] = 1,
["Height"] = 2,
["Min"] = 3,
["Max"] = 4,
["TextOverlay"] = 5,
["BaseLine"] = 6,
},
Events = {
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(thisWidget: Types.PlotHistogram)
local PlotHistogram = Instance.new("Frame")
PlotHistogram.Name = "Iris_PlotHistogram"
PlotHistogram.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
PlotHistogram.BackgroundTransparency = 1
PlotHistogram.BorderSizePixel = 0
widgets.UIListLayout(PlotHistogram, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
local Background = Instance.new("Frame")
Background.Name = "Background"
Background.Size = UDim2.new(Iris._config.ContentWidth, UDim.new(1, 0))
Background.BackgroundColor3 = Iris._config.FrameBgColor
Background.BackgroundTransparency = Iris._config.FrameBgTransparency
widgets.applyFrameStyle(Background)
local UIPadding = (Background :: any).UIPadding
UIPadding.PaddingRight = UDim.new(0, Iris._config.FramePadding.X - 1)
Background.Parent = PlotHistogram
local Plot = Instance.new("Frame")
Plot.Name = "Plot"
Plot.Size = UDim2.fromScale(1, 1)
Plot.BackgroundTransparency = 1
Plot.BorderSizePixel = 0
Plot.ClipsDescendants = true
local OverlayText = Instance.new("TextLabel")
OverlayText.Name = "OverlayText"
OverlayText.AutomaticSize = Enum.AutomaticSize.XY
OverlayText.AnchorPoint = Vector2.new(0.5, 0)
OverlayText.Size = UDim2.fromOffset(0, 0)
OverlayText.Position = UDim2.fromScale(0.5, 0)
OverlayText.BackgroundTransparency = 1
OverlayText.BorderSizePixel = 0
OverlayText.ZIndex = 2
widgets.applyTextStyle(OverlayText)
OverlayText.Parent = Plot
local Tooltip = Instance.new("TextLabel")
Tooltip.Name = "Iris_Tooltip"
Tooltip.AutomaticSize = Enum.AutomaticSize.XY
Tooltip.Size = UDim2.fromOffset(0, 0)
Tooltip.BackgroundColor3 = Iris._config.PopupBgColor
Tooltip.BackgroundTransparency = Iris._config.PopupBgTransparency
Tooltip.BorderSizePixel = 0
Tooltip.Visible = false
widgets.applyTextStyle(Tooltip)
widgets.UIStroke(Tooltip, Iris._config.PopupBorderSize, Iris._config.BorderActiveColor, Iris._config.BorderActiveTransparency)
widgets.UIPadding(Tooltip, Iris._config.WindowPadding)
if Iris._config.PopupRounding > 0 then
widgets.UICorner(Tooltip, Iris._config.PopupRounding)
end
local popup = Iris._rootInstance and Iris._rootInstance:FindFirstChild("PopupScreenGui")
Tooltip.Parent = popup and popup:FindFirstChild("TooltipContainer")
thisWidget.Tooltip = Tooltip
widgets.applyMouseMoved(Plot, function()
updateBlock(thisWidget)
end)
widgets.applyMouseLeave(Plot, function()
clearBlock(thisWidget)
end)
Plot.Parent = Background
thisWidget.Blocks = {}
thisWidget.HoveredBlock = false
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.Size = UDim2.fromOffset(0, 0)
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.ZIndex = 3
TextLabel.LayoutOrder = 3
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = PlotHistogram
return PlotHistogram
end,
GenerateState = function(thisWidget: Types.PlotHistogram)
if thisWidget.state.values == nil then
thisWidget.state.values = Iris._widgetState(thisWidget, "values", { 1 })
end
if thisWidget.state.hovered == nil then
thisWidget.state.hovered = Iris._widgetState(thisWidget, "hovered", nil)
end
end,
Update = function(thisWidget: Types.PlotHistogram)
local PlotLines = thisWidget.Instance :: Frame
local TextLabel: TextLabel = PlotLines.TextLabel
local Background = PlotLines.Background :: Frame
local Plot = Background.Plot :: Frame
local OverlayText: TextLabel = Plot.OverlayText
TextLabel.Text = thisWidget.arguments.Text or "Plot Histogram"
OverlayText.Text = thisWidget.arguments.TextOverlay or ""
PlotLines.Size = UDim2.new(1, 0, 0, thisWidget.arguments.Height or 0)
end,
UpdateState = function(thisWidget: Types.PlotHistogram)
if thisWidget.state.hovered.lastChangeTick == Iris._cycleTick then
if thisWidget.state.hovered.value then
thisWidget.Tooltip.Visible = true
else
thisWidget.Tooltip.Visible = false
end
end
if thisWidget.state.values.lastChangeTick == Iris._cycleTick then
local PlotHistogram = thisWidget.Instance :: Frame
local Background = PlotHistogram.Background :: Frame
local Plot = Background.Plot :: Frame
local values = thisWidget.state.values.value
local count = #values
local numBlocks = #thisWidget.Blocks
local min = thisWidget.arguments.Min or math.huge
local max = thisWidget.arguments.Max or -math.huge
local baseline = thisWidget.arguments.BaseLine or 0
if min == nil or max == nil then
for _, value in values do
min = math.min(min or value, value)
max = math.max(max or value, value)
end
end
-- add or remove blocks depending on how many are needed
if numBlocks < count then
for index = numBlocks + 1, count do
table.insert(thisWidget.Blocks, createBlock(Plot, index))
end
elseif numBlocks > count then
for _ = count + 1, numBlocks do
local block= table.remove(thisWidget.Blocks)
if block then
block:Destroy()
end
end
end
local range = max - min
local width = UDim.new(1 / count, -1)
for index = 1, count do
local num = values[index]
if num >= 0 then
thisWidget.Blocks[index].Size = UDim2.new(width, UDim.new((num - baseline) / range))
thisWidget.Blocks[index].Position = UDim2.fromScale((index - 1) / count, (max - num) / range)
else
thisWidget.Blocks[index].Size = UDim2.new(width, UDim.new((baseline - num) / range))
thisWidget.Blocks[index].Position = UDim2.fromScale((index - 1) / count, (max - baseline) / range)
end
end
-- only update the hovered block if it exists.
if thisWidget.HoveredBlock then
updateBlock(thisWidget, true)
end
end
end,
Discard = function(thisWidget: Types.PlotHistogram)
thisWidget.Instance:Destroy()
thisWidget.Tooltip:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
end
| 5,541 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/RadioButton.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
--stylua: ignore
Iris.WidgetConstructor("RadioButton", {
hasState = true,
hasChildren = false,
Args = {
["Text"] = 1,
["Index"] = 2,
},
Events = {
["selected"] = {
["Init"] = function(_thisWidget: Types.RadioButton) end,
["Get"] = function(thisWidget: Types.RadioButton)
return thisWidget.lastSelectedTick == Iris._cycleTick
end,
},
["unselected"] = {
["Init"] = function(_thisWidget: Types.RadioButton) end,
["Get"] = function(thisWidget: Types.RadioButton)
return thisWidget.lastUnselectedTick == Iris._cycleTick
end,
},
["active"] = {
["Init"] = function(_thisWidget: Types.RadioButton) end,
["Get"] = function(thisWidget: Types.RadioButton)
return thisWidget.state.index.value == thisWidget.arguments.Index
end,
},
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(thisWidget: Types.RadioButton)
local RadioButton = Instance.new("TextButton")
RadioButton.Name = "Iris_RadioButton"
RadioButton.AutomaticSize = Enum.AutomaticSize.XY
RadioButton.Size = UDim2.fromOffset(0, 0)
RadioButton.BackgroundTransparency = 1
RadioButton.BorderSizePixel = 0
RadioButton.Text = ""
RadioButton.AutoButtonColor = false
widgets.UIListLayout(RadioButton, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
local buttonSize = Iris._config.TextSize + 2 * (Iris._config.FramePadding.Y - 1)
local Button = Instance.new("Frame")
Button.Name = "Button"
Button.Size = UDim2.fromOffset(buttonSize, buttonSize)
Button.BackgroundColor3 = Iris._config.FrameBgColor
Button.BackgroundTransparency = Iris._config.FrameBgTransparency
Button.Parent = RadioButton
widgets.UICorner(Button)
widgets.UIPadding(Button, Vector2.new(math.max(1, math.floor(buttonSize / 5)), math.max(1, math.floor(buttonSize / 5))))
local Circle = Instance.new("Frame")
Circle.Name = "Circle"
Circle.Size = UDim2.fromScale(1, 1)
Circle.BackgroundColor3 = Iris._config.CheckMarkColor
Circle.BackgroundTransparency = Iris._config.CheckMarkTransparency
widgets.UICorner(Circle)
Circle.Parent = Button
widgets.applyInteractionHighlights("Background", RadioButton, Button, {
Color = Iris._config.FrameBgColor,
Transparency = Iris._config.FrameBgTransparency,
HoveredColor = Iris._config.FrameBgHoveredColor,
HoveredTransparency = Iris._config.FrameBgHoveredTransparency,
ActiveColor = Iris._config.FrameBgActiveColor,
ActiveTransparency = Iris._config.FrameBgActiveTransparency,
})
widgets.applyButtonClick(RadioButton, function()
thisWidget.state.index:set(thisWidget.arguments.Index)
end)
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.LayoutOrder = 1
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = RadioButton
return RadioButton
end,
Update = function(thisWidget: Types.RadioButton)
local RadioButton = thisWidget.Instance :: TextButton
local TextLabel: TextLabel = RadioButton.TextLabel
TextLabel.Text = thisWidget.arguments.Text or "Radio Button"
if thisWidget.state then
thisWidget.state.index.lastChangeTick = Iris._cycleTick
Iris._widgets[thisWidget.type].UpdateState(thisWidget)
end
end,
Discard = function(thisWidget: Types.RadioButton)
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
GenerateState = function(thisWidget: Types.RadioButton)
if thisWidget.state.index == nil then
thisWidget.state.index = Iris._widgetState(thisWidget, "index", thisWidget.arguments.Index)
end
end,
UpdateState = function(thisWidget: Types.RadioButton)
local RadioButton = thisWidget.Instance :: TextButton
local Button = RadioButton.Button :: Frame
local Circle: Frame = Button.Circle
if thisWidget.state.index.value == thisWidget.arguments.Index then
-- only need to hide the circle
Circle.BackgroundTransparency = Iris._config.CheckMarkTransparency
thisWidget.lastSelectedTick = Iris._cycleTick + 1
else
Circle.BackgroundTransparency = 1
thisWidget.lastUnselectedTick = Iris._cycleTick + 1
end
end,
} :: Types.WidgetClass)
end
| 1,087 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Root.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local NumNonWindowChildren: number = 0
--stylua: ignore
Iris.WidgetConstructor("Root", {
hasState = false,
hasChildren = true,
Args = {},
Events = {},
Generate = function(_thisWidget: Types.Root)
local Root = Instance.new("Folder")
Root.Name = "Iris_Root"
local PseudoWindowScreenGui
if Iris._config.UseScreenGUIs then
PseudoWindowScreenGui = Instance.new("ScreenGui")
PseudoWindowScreenGui.ResetOnSpawn = false
PseudoWindowScreenGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
PseudoWindowScreenGui.ScreenInsets = Iris._config.ScreenInsets
PseudoWindowScreenGui.IgnoreGuiInset = Iris._config.IgnoreGuiInset
PseudoWindowScreenGui.DisplayOrder = Iris._config.DisplayOrderOffset
else
PseudoWindowScreenGui = Instance.new("Frame")
PseudoWindowScreenGui.AnchorPoint = Vector2.new(0.5, 0.5)
PseudoWindowScreenGui.Position = UDim2.fromScale(0.5, 0.5)
PseudoWindowScreenGui.Size = UDim2.fromScale(1, 1)
PseudoWindowScreenGui.BackgroundTransparency = 1
PseudoWindowScreenGui.ZIndex = Iris._config.DisplayOrderOffset
end
PseudoWindowScreenGui.Name = "PseudoWindowScreenGui"
PseudoWindowScreenGui.Parent = Root
local PopupScreenGui
if Iris._config.UseScreenGUIs then
PopupScreenGui = Instance.new("ScreenGui")
PopupScreenGui.ResetOnSpawn = false
PopupScreenGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
PopupScreenGui.DisplayOrder = Iris._config.DisplayOrderOffset + 1024 -- room for 1024 regular windows before overlap
PopupScreenGui.ScreenInsets = Iris._config.ScreenInsets
PopupScreenGui.IgnoreGuiInset = Iris._config.IgnoreGuiInset
else
PopupScreenGui = Instance.new("Frame")
PopupScreenGui.AnchorPoint = Vector2.new(0.5, 0.5)
PopupScreenGui.Position = UDim2.fromScale(0.5, 0.5)
PopupScreenGui.Size = UDim2.fromScale(1, 1)
PopupScreenGui.BackgroundTransparency = 1
PopupScreenGui.ZIndex = Iris._config.DisplayOrderOffset + 1024
end
PopupScreenGui.Name = "PopupScreenGui"
PopupScreenGui.Parent = Root
local TooltipContainer = Instance.new("Frame")
TooltipContainer.Name = "TooltipContainer"
TooltipContainer.AutomaticSize = Enum.AutomaticSize.XY
TooltipContainer.Size = UDim2.fromOffset(0, 0)
TooltipContainer.BackgroundTransparency = 1
TooltipContainer.BorderSizePixel = 0
widgets.UIListLayout(TooltipContainer, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.PopupBorderSize))
TooltipContainer.Parent = PopupScreenGui
local MenuBarContainer = Instance.new("Frame")
MenuBarContainer.Name = "MenuBarContainer"
MenuBarContainer.AutomaticSize = Enum.AutomaticSize.Y
MenuBarContainer.Size = UDim2.fromScale(1, 0)
MenuBarContainer.BackgroundTransparency = 1
MenuBarContainer.BorderSizePixel = 0
MenuBarContainer.Parent = PopupScreenGui
local PseudoWindow = Instance.new("Frame")
PseudoWindow.Name = "PseudoWindow"
PseudoWindow.AutomaticSize = Enum.AutomaticSize.XY
PseudoWindow.Size = UDim2.new(0, 0, 0, 0)
PseudoWindow.Position = UDim2.fromOffset(0, 22)
PseudoWindow.BackgroundTransparency = Iris._config.WindowBgTransparency
PseudoWindow.BackgroundColor3 = Iris._config.WindowBgColor
PseudoWindow.BorderSizePixel = Iris._config.WindowBorderSize
PseudoWindow.BorderColor3 = Iris._config.BorderColor
PseudoWindow.Selectable = false
PseudoWindow.SelectionGroup = true
PseudoWindow.SelectionBehaviorUp = Enum.SelectionBehavior.Stop
PseudoWindow.SelectionBehaviorDown = Enum.SelectionBehavior.Stop
PseudoWindow.SelectionBehaviorLeft = Enum.SelectionBehavior.Stop
PseudoWindow.SelectionBehaviorRight = Enum.SelectionBehavior.Stop
PseudoWindow.Visible = false
widgets.UIPadding(PseudoWindow, Iris._config.WindowPadding)
widgets.UIListLayout(PseudoWindow, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.ItemSpacing.Y))
PseudoWindow.Parent = PseudoWindowScreenGui
return Root
end,
Update = function(thisWidget: Types.Root)
if NumNonWindowChildren > 0 then
local Root = thisWidget.Instance :: any
local PseudoWindowScreenGui = Root.PseudoWindowScreenGui :: any
local PseudoWindow: Frame = PseudoWindowScreenGui.PseudoWindow
PseudoWindow.Visible = true
end
end,
Discard = function(thisWidget: Types.Root)
NumNonWindowChildren = 0
thisWidget.Instance:Destroy()
end,
ChildAdded = function(thisWidget: Types.Root, thisChild: Types.Widget)
local Root = thisWidget.Instance :: any
if thisChild.type == "Window" then
return thisWidget.Instance
elseif thisChild.type == "Tooltip" then
return Root.PopupScreenGui.TooltipContainer
elseif thisChild.type == "MenuBar" then
return Root.PopupScreenGui.MenuBarContainer
else
local PseudoWindowScreenGui = Root.PseudoWindowScreenGui :: any
local PseudoWindow: Frame = PseudoWindowScreenGui.PseudoWindow
NumNonWindowChildren += 1
PseudoWindow.Visible = true
return PseudoWindow
end
end,
ChildDiscarded = function(thisWidget: Types.Root, thisChild: Types.Widget)
if thisChild.type ~= "Window" and thisChild.type ~= "Tooltip" and thisChild.type ~= "MenuBar" then
NumNonWindowChildren -= 1
if NumNonWindowChildren == 0 then
local Root = thisWidget.Instance :: any
local PseudoWindowScreenGui = Root.PseudoWindowScreenGui :: any
local PseudoWindow: Frame = PseudoWindowScreenGui.PseudoWindow
PseudoWindow.Visible = false
end
end
end,
} :: Types.WidgetClass)
end
| 1,437 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Tab.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local function openTab(TabBar: Types.TabBar, Index: number)
if TabBar.state.index.value > 0 then
return
end
TabBar.state.index:set(Index)
end
local function closeTab(TabBar: Types.TabBar, Index: number)
if TabBar.state.index.value ~= Index then
return
end
-- search left for open tabs
for i = Index - 1, 1, -1 do
if TabBar.Tabs[i].state.isOpened.value == true then
TabBar.state.index:set(i)
return
end
end
-- search right for open tabs
for i = Index, #TabBar.Tabs do
if TabBar.Tabs[i].state.isOpened.value == true then
TabBar.state.index:set(i)
return
end
end
-- no open tabs, so wait for one
TabBar.state.index:set(0)
end
--stylua: ignore
Iris.WidgetConstructor("TabBar", {
hasState = true,
hasChildren = true,
Args = {},
Events = {},
Generate = function(thisWidget: Types.TabBar)
local TabBar = Instance.new("Frame")
TabBar.Name = "Iris_TabBar"
TabBar.AutomaticSize = Enum.AutomaticSize.Y
TabBar.Size = UDim2.fromScale(1, 0)
TabBar.BackgroundTransparency = 1
TabBar.BorderSizePixel = 0
widgets.UIListLayout(TabBar, Enum.FillDirection.Vertical, UDim.new()).VerticalAlignment = Enum.VerticalAlignment.Bottom
local Bar = Instance.new("Frame")
Bar.Name = "Bar"
Bar.AutomaticSize = Enum.AutomaticSize.Y
Bar.Size = UDim2.fromScale(1, 0)
Bar.BackgroundTransparency = 1
Bar.BorderSizePixel = 0
widgets.UIListLayout(Bar, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X))
Bar.Parent = TabBar
local Underline = Instance.new("Frame")
Underline.Name = "Underline"
Underline.Size = UDim2.new(1, 0, 0, 1)
Underline.BackgroundColor3 = Iris._config.TabActiveColor
Underline.BackgroundTransparency = Iris._config.TabActiveTransparency
Underline.BorderSizePixel = 0
Underline.LayoutOrder = 1
Underline.Parent = TabBar
local ChildContainer = Instance.new("Frame")
ChildContainer.Name = "TabContainer"
ChildContainer.AutomaticSize = Enum.AutomaticSize.Y
ChildContainer.Size = UDim2.fromScale(1, 0)
ChildContainer.BackgroundTransparency = 1
ChildContainer.BorderSizePixel = 0
ChildContainer.LayoutOrder = 2
ChildContainer.ClipsDescendants = true
ChildContainer.Parent = TabBar
thisWidget.ChildContainer = ChildContainer
thisWidget.Tabs = {}
return TabBar
end,
Update = function(_thisWidget: Types.TabBar) end,
ChildAdded = function(thisWidget: Types.TabBar, thisChild: Types.Tab)
assert(thisChild.type == "Tab", "Only Iris.Tab can be parented to Iris.TabBar.")
local TabBar = thisWidget.Instance :: Frame
thisChild.ChildContainer.Parent = thisWidget.ChildContainer
thisChild.Index = #thisWidget.Tabs + 1
thisWidget.state.index.ConnectedWidgets[thisChild.ID] = thisChild
table.insert(thisWidget.Tabs, thisChild)
return TabBar.Bar
end,
ChildDiscarded = function(thisWidget: Types.TabBar, thisChild: Types.Tab)
local Index = thisChild.Index
table.remove(thisWidget.Tabs, Index)
for i = Index, #thisWidget.Tabs do
thisWidget.Tabs[i].Index = i
end
closeTab(thisWidget, Index)
end,
GenerateState = function(thisWidget: Types.Tab)
if thisWidget.state.index == nil then
thisWidget.state.index = Iris._widgetState(thisWidget, "index", 1)
end
end,
UpdateState = function(_thisWidget: Types.Tab)
end,
Discard = function(thisWidget: Types.TabBar)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
--stylua: ignore
Iris.WidgetConstructor("Tab", {
hasState = true,
hasChildren = true,
Args = {
["Text"] = 1,
["Hideable"] = 2,
},
Events = {
["clicked"] = widgets.EVENTS.click(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
["selected"] = {
["Init"] = function(_thisWidget: Types.Tab) end,
["Get"] = function(thisWidget: Types.Tab)
return thisWidget.lastSelectedTick == Iris._cycleTick
end,
},
["unselected"] = {
["Init"] = function(_thisWidget: Types.Tab) end,
["Get"] = function(thisWidget: Types.Tab)
return thisWidget.lastUnselectedTick == Iris._cycleTick
end,
},
["active"] = {
["Init"] = function(_thisWidget: Types.Tab) end,
["Get"] = function(thisWidget: Types.Tab)
return thisWidget.state.index.value == thisWidget.Index
end,
},
["opened"] = {
["Init"] = function(_thisWidget: Types.Tab) end,
["Get"] = function(thisWidget: Types.Tab)
return thisWidget.lastOpenedTick == Iris._cycleTick
end,
},
["closed"] = {
["Init"] = function(_thisWidget: Types.Tab) end,
["Get"] = function(thisWidget: Types.Tab)
return thisWidget.lastClosedTick == Iris._cycleTick
end,
},
},
Generate = function(thisWidget: Types.Tab)
local Tab = Instance.new("TextButton")
Tab.Name = "Iris_Tab"
Tab.AutomaticSize = Enum.AutomaticSize.XY
Tab.BackgroundColor3 = Iris._config.TabColor
Tab.BackgroundTransparency = Iris._config.TabTransparency
Tab.BorderSizePixel = 0
Tab.Text = ""
Tab.AutoButtonColor = false
thisWidget.ButtonColors = {
Color = Iris._config.TabColor,
Transparency = Iris._config.TabTransparency,
HoveredColor = Iris._config.TabHoveredColor,
HoveredTransparency = Iris._config.TabHoveredTransparency,
ActiveColor = Iris._config.TabActiveColor,
ActiveTransparency = Iris._config.TabActiveTransparency,
}
widgets.UIPadding(Tab, Vector2.new(Iris._config.FramePadding.X, 0))
widgets.applyFrameStyle(Tab, true, true)
widgets.UIListLayout(Tab, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
widgets.applyInteractionHighlights("Background", Tab, Tab, thisWidget.ButtonColors)
widgets.applyButtonClick(Tab, function()
thisWidget.state.index:set(thisWidget.Index)
end)
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
widgets.applyTextStyle(TextLabel)
widgets.UIPadding(TextLabel, Vector2.new(0, Iris._config.FramePadding.Y))
TextLabel.Parent = Tab
local ButtonSize = Iris._config.TextSize + ((Iris._config.FramePadding.Y - 1) * 2)
local CloseButton = Instance.new("TextButton")
CloseButton.Name = "CloseButton"
CloseButton.Size = UDim2.fromOffset(ButtonSize, ButtonSize)
CloseButton.BackgroundTransparency = 1
CloseButton.BorderSizePixel = 0
CloseButton.Text = ""
CloseButton.AutoButtonColor = false
CloseButton.LayoutOrder = 1
widgets.UICorner(CloseButton)
widgets.applyButtonClick(CloseButton, function()
thisWidget.state.isOpened:set(false)
closeTab(thisWidget.parentWidget, thisWidget.Index)
end)
widgets.applyInteractionHighlights("Background", CloseButton, CloseButton, {
Color = Iris._config.TabColor,
Transparency = 1,
HoveredColor = Iris._config.ButtonHoveredColor,
HoveredTransparency = Iris._config.ButtonHoveredTransparency,
ActiveColor = Iris._config.ButtonActiveColor,
ActiveTransparency = Iris._config.ButtonActiveTransparency,
})
CloseButton.Parent = Tab
local Icon = Instance.new("ImageLabel")
Icon.Name = "Icon"
Icon.AnchorPoint = Vector2.new(0.5, 0.5)
Icon.Position = UDim2.fromScale(0.5, 0.5)
Icon.Size = UDim2.fromOffset(math.floor(0.7 * ButtonSize), math.floor(0.7 * ButtonSize))
Icon.BackgroundTransparency = 1
Icon.BorderSizePixel = 0
Icon.Image = widgets.ICONS.MULTIPLICATION_SIGN
Icon.ImageTransparency = 1
widgets.applyInteractionHighlights("Image", Tab, Icon, {
Color = Iris._config.TextColor,
Transparency = 1,
HoveredColor = Iris._config.TextColor,
HoveredTransparency = Iris._config.TextTransparency,
ActiveColor = Iris._config.TextColor,
ActiveTransparency = Iris._config.TextTransparency,
})
Icon.Parent = CloseButton
local ChildContainer = Instance.new("Frame")
ChildContainer.Name = "TabContainer"
ChildContainer.AutomaticSize = Enum.AutomaticSize.Y
ChildContainer.Size = UDim2.fromScale(1, 0)
ChildContainer.BackgroundTransparency = 1
ChildContainer.BorderSizePixel = 0
ChildContainer.ClipsDescendants = true
widgets.UIListLayout(ChildContainer, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.ItemSpacing.Y))
widgets.UIPadding(ChildContainer, Vector2.new(0, Iris._config.ItemSpacing.Y)).PaddingBottom = UDim.new()
thisWidget.ChildContainer = ChildContainer
return Tab
end,
Update = function(thisWidget: Types.Tab)
local Tab = thisWidget.Instance :: TextButton
local TextLabel: TextLabel = Tab.TextLabel
local CloseButton: TextButton = Tab.CloseButton
TextLabel.Text = thisWidget.arguments.Text
CloseButton.Visible = if thisWidget.arguments.Hideable == true then true else false
end,
ChildAdded = function(thisWidget: Types.Tab, _thisChild: Types.Widget)
return thisWidget.ChildContainer
end,
GenerateState = function(thisWidget: Types.Tab)
thisWidget.state.index = thisWidget.parentWidget.state.index
thisWidget.state.index.ConnectedWidgets[thisWidget.ID] = thisWidget
if thisWidget.state.isOpened == nil then
thisWidget.state.isOpened = Iris._widgetState(thisWidget, "isOpened", true)
end
end,
UpdateState = function(thisWidget: Types.Tab)
local Tab = thisWidget.Instance :: TextButton
local Container = thisWidget.ChildContainer :: Frame
if thisWidget.state.isOpened.lastChangeTick == Iris._cycleTick then
if thisWidget.state.isOpened.value == true then
thisWidget.lastOpenedTick = Iris._cycleTick + 1
openTab(thisWidget.parentWidget, thisWidget.Index)
Tab.Visible = true
else
thisWidget.lastClosedTick = Iris._cycleTick + 1
closeTab(thisWidget.parentWidget, thisWidget.Index)
Tab.Visible = false
end
end
if thisWidget.state.index.lastChangeTick == Iris._cycleTick then
if thisWidget.state.index.value == thisWidget.Index then
thisWidget.ButtonColors.Color = Iris._config.TabActiveColor
thisWidget.ButtonColors.Transparency = Iris._config.TabActiveTransparency
Tab.BackgroundColor3 = Iris._config.TabActiveColor
Tab.BackgroundTransparency = Iris._config.TabActiveTransparency
Container.Visible = true
thisWidget.lastSelectedTick = Iris._cycleTick + 1
else
thisWidget.ButtonColors.Color = Iris._config.TabColor
thisWidget.ButtonColors.Transparency = Iris._config.TabTransparency
Tab.BackgroundColor3 = Iris._config.TabColor
Tab.BackgroundTransparency = Iris._config.TabTransparency
Container.Visible = false
thisWidget.lastUnselectedTick = Iris._cycleTick + 1
end
end
end,
Discard = function(thisWidget: Types.Tab)
if thisWidget.state.isOpened.value == true then
closeTab(thisWidget.parentWidget, thisWidget.Index)
end
thisWidget.Instance:Destroy()
thisWidget.ChildContainer:Destroy()
widgets.discardState(thisWidget)
end
} :: Types.WidgetClass)
end
| 2,889 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Table.lua | local Types = require(script.Parent.Parent.Types)
-- Tables need an overhaul.
--[[
Iris.Table(
{
NumColumns,
Header,
RowBackground,
OuterBorders,
InnerBorders
}
)
Config = {
CellPadding: Vector2,
CellSize: UDim2,
}
Iris.NextColumn()
Iris.NextRow()
Iris.SetColumnIndex(index: number)
Iris.SetRowIndex(index: number)
Iris.NextHeaderColumn()
Iris.SetHeaderColumnIndex(index: number)
Iris.SetColumnWidth(index: number, width: number | UDim)
]]
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local Tables: { [Types.ID]: Types.Table } = {}
local TableMinWidths: { [Types.Table]: { boolean } } = {}
local AnyActiveTable = false
local ActiveTable: Types.Table? = nil
local ActiveColumn = 0
local ActiveLeftWidth = -1
local ActiveRightWidth = -1
local MousePositionX = 0
local function CalculateMinColumnWidth(thisWidget: Types.Table, index: number)
local width = 0
for _, row in thisWidget._cellInstances do
local cell = row[index]
for _, child in cell:GetChildren() do
if child:IsA("GuiObject") then
width = math.max(width, child.AbsoluteSize.X)
end
end
end
thisWidget._minWidths[index] = width + 2 * Iris._config.CellPadding.X
end
table.insert(Iris._postCycleCallbacks, function()
for _, thisWidget in Tables do
for rowIndex, cycleTick in thisWidget._rowCycles do
if cycleTick < Iris._cycleTick - 1 then
local Row = thisWidget._rowInstances[rowIndex]
local RowBorder = thisWidget._rowBorders[rowIndex - 1]
if Row ~= nil then
Row:Destroy()
end
if RowBorder ~= nil then
RowBorder:Destroy()
end
thisWidget._rowInstances[rowIndex] = nil
thisWidget._rowBorders[rowIndex - 1] = nil
thisWidget._cellInstances[rowIndex] = nil
thisWidget._rowCycles[rowIndex] = nil
end
end
thisWidget._rowIndex = 1
thisWidget._columnIndex = 1
-- update the border container size to be the same, albeit *every* frame!
local Table = thisWidget.Instance :: Frame
local BorderContainer: Frame = Table.BorderContainer
BorderContainer.Size = UDim2.new(1, 0, 0, thisWidget._rowContainer.AbsoluteSize.Y)
thisWidget._columnBorders[0].Size = UDim2.fromOffset(5, thisWidget._rowContainer.AbsoluteSize.Y)
end
for thisWidget, columns in TableMinWidths do
local refresh = false
for column, _ in columns do
CalculateMinColumnWidth(thisWidget, column)
refresh = true
end
if refresh then
table.clear(columns)
Iris._widgets["Table"].UpdateState(thisWidget)
end
end
end)
local function UpdateActiveColumn()
if AnyActiveTable == false or ActiveTable == nil then
return
end
local widths = ActiveTable.state.widths
local NumColumns = ActiveTable.arguments.NumColumns
local Table = ActiveTable.Instance :: Frame
local BorderContainer = Table.BorderContainer :: Frame
local Fixed = ActiveTable.arguments.FixedWidth
local Padding = 2 * Iris._config.CellPadding.X
if ActiveLeftWidth == -1 then
ActiveLeftWidth = widths.value[ActiveColumn]
if ActiveLeftWidth == 0 then
ActiveLeftWidth = Padding / Table.AbsoluteSize.X
end
ActiveRightWidth = widths.value[ActiveColumn + 1] or -1
if ActiveRightWidth == 0 then
ActiveRightWidth = Padding / Table.AbsoluteSize.X
end
end
local BorderX = Table.AbsolutePosition.X
local LeftX: number -- the start of the current column
-- local CurrentX: number = BorderContainer:FindFirstChild(`Border_{ActiveColumn}`).AbsolutePosition.X + 3 - BorderX -- the current column position
local RightX: number -- the end of the next column
if ActiveColumn == 1 then
LeftX = 0
else
LeftX = math.floor(BorderContainer:FindFirstChild(`Border_{ActiveColumn - 1}`).AbsolutePosition.X + 3 - BorderX)
end
if ActiveColumn >= NumColumns - 1 then
RightX = Table.AbsoluteSize.X
else
RightX = math.floor(BorderContainer:FindFirstChild(`Border_{ActiveColumn + 1}`).AbsolutePosition.X + 3 - BorderX)
end
local TableX: number = BorderX - widgets.GuiOffset.X
local DeltaX: number = math.clamp(widgets.getMouseLocation().X, LeftX + TableX + Padding, RightX + TableX - Padding) - MousePositionX
local LeftOffset = (MousePositionX - TableX) - LeftX
local LeftRatio = ActiveLeftWidth / LeftOffset
if Fixed then
widths.value[ActiveColumn] = math.clamp(math.round(ActiveLeftWidth + DeltaX), Padding, Table.AbsoluteSize.X - LeftX)
else
local Change = LeftRatio * DeltaX
widths.value[ActiveColumn] = math.clamp(ActiveLeftWidth + Change, 0, (RightX - LeftX - Padding) / Table.AbsoluteSize.X)
if ActiveColumn < NumColumns then
widths.value[ActiveColumn + 1] = math.clamp(ActiveRightWidth - Change, 0, 1)
end
end
widths:set(widths.value, true)
end
local function ColumnMouseDown(thisWidget: Types.Table, index: number)
AnyActiveTable = true
ActiveTable = thisWidget
ActiveColumn = index
ActiveLeftWidth = -1
ActiveRightWidth = -1
MousePositionX = widgets.getMouseLocation().X
end
widgets.registerEvent("InputChanged", function()
if not Iris._started then
return
end
UpdateActiveColumn()
end)
widgets.registerEvent("InputEnded", function(inputObject: InputObject)
if not Iris._started then
return
end
if inputObject.UserInputType == Enum.UserInputType.MouseButton1 and AnyActiveTable then
AnyActiveTable = false
ActiveTable = nil
ActiveColumn = 0
ActiveLeftWidth = -1
ActiveRightWidth = -1
MousePositionX = 0
end
end)
local function GenerateCell(_thisWidget: Types.Table, index: number, width: UDim, header: boolean)
local Cell: TextButton
if header then
Cell = Instance.new("TextButton")
Cell.Text = ""
Cell.AutoButtonColor = false
else
Cell = (Instance.new("Frame") :: GuiObject) :: TextButton
end
Cell.Name = `Cell_{index}`
Cell.AutomaticSize = Enum.AutomaticSize.Y
Cell.Size = UDim2.new(width, UDim.new())
Cell.BackgroundTransparency = 1
Cell.ZIndex = index
Cell.LayoutOrder = index
Cell.ClipsDescendants = true
if header then
widgets.applyInteractionHighlights("Background", Cell, Cell, {
Color = Iris._config.HeaderColor,
Transparency = 1,
HoveredColor = Iris._config.HeaderHoveredColor,
HoveredTransparency = Iris._config.HeaderHoveredTransparency,
ActiveColor = Iris._config.HeaderActiveColor,
ActiveTransparency = Iris._config.HeaderActiveTransparency,
})
end
widgets.UIPadding(Cell, Iris._config.CellPadding)
widgets.UIListLayout(Cell, Enum.FillDirection.Vertical, UDim.new())
widgets.UISizeConstraint(Cell, Vector2.new(2 * Iris._config.CellPadding.X, 0))
return Cell
end
local function GenerateColumnBorder(thisWidget: Types.Table, index: number, style: "Light" | "Strong")
local Border = Instance.new("ImageButton")
Border.Name = `Border_{index}`
Border.Size = UDim2.new(0, 5, 1, 0)
Border.BackgroundTransparency = 1
Border.Image = ""
Border.ImageTransparency = 1
Border.AutoButtonColor = false
Border.ZIndex = index
Border.LayoutOrder = 2 * index
local offset = if index == thisWidget.arguments.NumColumns then 3 else 2
local Line = Instance.new("Frame")
Line.Name = "Line"
Line.Size = UDim2.new(0, 1, 1, 0)
Line.Position = UDim2.fromOffset(offset, 0)
Line.BackgroundColor3 = Iris._config[`TableBorder{style}Color`]
Line.BackgroundTransparency = Iris._config[`TableBorder{style}Transparency`]
Line.BorderSizePixel = 0
Line.Parent = Border
local Hover = Instance.new("Frame")
Hover.Name = "Hover"
Hover.Position = UDim2.fromOffset(offset, 0)
Hover.Size = UDim2.new(0, 1, 1, 0)
Hover.BackgroundColor3 = Iris._config[`TableBorder{style}Color`]
Hover.BackgroundTransparency = Iris._config[`TableBorder{style}Transparency`]
Hover.BorderSizePixel = 0
Hover.Visible = thisWidget.arguments.Resizable
Hover.Parent = Border
widgets.applyInteractionHighlights("Background", Border, Hover, {
Color = Iris._config.ResizeGripColor,
Transparency = 1,
HoveredColor = Iris._config.ResizeGripHoveredColor,
HoveredTransparency = Iris._config.ResizeGripHoveredTransparency,
ActiveColor = Iris._config.ResizeGripActiveColor,
ActiveTransparency = Iris._config.ResizeGripActiveTransparency,
})
widgets.applyButtonDown(Border, function()
if thisWidget.arguments.Resizable then
ColumnMouseDown(thisWidget, index)
end
end)
return Border
end
-- creates a new row and all columns, and adds all to the table's row and cell instance tables, but does not parent
local function GenerateRow(thisWidget: Types.Table, index: number)
local Row: Frame = Instance.new("Frame")
Row.Name = `Row_{index}`
Row.AutomaticSize = Enum.AutomaticSize.Y
Row.Size = UDim2.fromScale(1, 0)
if index == 0 then
Row.BackgroundColor3 = Iris._config.TableHeaderColor
Row.BackgroundTransparency = Iris._config.TableHeaderTransparency
elseif thisWidget.arguments.RowBackground == true then
if (index % 2) == 0 then
Row.BackgroundColor3 = Iris._config.TableRowBgAltColor
Row.BackgroundTransparency = Iris._config.TableRowBgAltTransparency
else
Row.BackgroundColor3 = Iris._config.TableRowBgColor
Row.BackgroundTransparency = Iris._config.TableRowBgTransparency
end
else
Row.BackgroundTransparency = 1
end
Row.BorderSizePixel = 0
Row.ZIndex = 2 * index - 1
Row.LayoutOrder = 2 * index - 1
Row.ClipsDescendants = true
widgets.UIListLayout(Row, Enum.FillDirection.Horizontal, UDim.new())
thisWidget._cellInstances[index] = table.create(thisWidget.arguments.NumColumns)
for columnIndex = 1, thisWidget.arguments.NumColumns do
local Cell = GenerateCell(thisWidget, columnIndex, thisWidget._widths[columnIndex], index == 0)
Cell.Parent = Row
thisWidget._cellInstances[index][columnIndex] = Cell
end
thisWidget._rowInstances[index] = Row
return Row
end
local function GenerateRowBorder(_thisWidget: Types.Table, index: number, style: "Light" | "Strong")
local Border = Instance.new("Frame")
Border.Name = `Border_{index}`
Border.Size = UDim2.fromScale(1, 0)
Border.BackgroundTransparency = 1
Border.ZIndex = 2 * index
Border.LayoutOrder = 2 * index
local Line = Instance.new("Frame")
Line.Name = "Line"
Line.AnchorPoint = Vector2.new(0, 0.5)
Line.Size = UDim2.new(1, 0, 0, 1)
Line.BackgroundColor3 = Iris._config[`TableBorder{style}Color`]
Line.BackgroundTransparency = Iris._config[`TableBorder{style}Transparency`]
Line.BorderSizePixel = 0
Line.Parent = Border
return Border
end
--stylua: ignore
Iris.WidgetConstructor("Table", {
hasState = true,
hasChildren = true,
Args = {
NumColumns = 1,
Header = 2,
RowBackground = 3,
OuterBorders = 4,
InnerBorders = 5,
Resizable = 6,
FixedWidth = 7,
ProportionalWidth = 8,
LimitTableWidth = 9,
},
Events = {},
Generate = function(thisWidget: Types.Table)
Tables[thisWidget.ID] = thisWidget
TableMinWidths[thisWidget] = {}
local Table = Instance.new("Frame")
Table.Name = "Iris_Table"
Table.AutomaticSize = Enum.AutomaticSize.Y
Table.Size = UDim2.fromScale(1, 0)
Table.BackgroundTransparency = 1
local RowContainer = Instance.new("Frame")
RowContainer.Name = "RowContainer"
RowContainer.AutomaticSize = Enum.AutomaticSize.Y
RowContainer.Size = UDim2.fromScale(1, 0)
RowContainer.BackgroundTransparency = 1
RowContainer.ZIndex = 1
widgets.UISizeConstraint(RowContainer)
widgets.UIListLayout(RowContainer, Enum.FillDirection.Vertical, UDim.new())
RowContainer.Parent = Table
thisWidget._rowContainer = RowContainer
local BorderContainer = Instance.new("Frame")
BorderContainer.Name = "BorderContainer"
BorderContainer.Size = UDim2.fromScale(1, 1)
BorderContainer.BackgroundTransparency = 1
BorderContainer.ZIndex = 2
BorderContainer.ClipsDescendants = true
widgets.UISizeConstraint(BorderContainer)
widgets.UIListLayout(BorderContainer, Enum.FillDirection.Horizontal, UDim.new())
widgets.UIStroke(BorderContainer, 1, Iris._config.TableBorderStrongColor, Iris._config.TableBorderStrongTransparency)
BorderContainer.Parent = Table
thisWidget._columnIndex = 1
thisWidget._rowIndex = 1
thisWidget._rowInstances = {}
thisWidget._cellInstances = {}
thisWidget._rowBorders = {}
thisWidget._columnBorders = {}
thisWidget._rowCycles = {}
local callbackIndex = #Iris._postCycleCallbacks + 1
local desiredCycleTick = Iris._cycleTick + 1
Iris._postCycleCallbacks[callbackIndex] = function()
if Iris._cycleTick >= desiredCycleTick then
if thisWidget.lastCycleTick ~= -1 then
thisWidget.state.widths.lastChangeTick = Iris._cycleTick
Iris._widgets["Table"].UpdateState(thisWidget)
end
Iris._postCycleCallbacks[callbackIndex] = nil
end
end
return Table
end,
GenerateState = function(thisWidget: Types.Table)
local NumColumns = thisWidget.arguments.NumColumns
if thisWidget.state.widths == nil then
local Widths: { number } = table.create(NumColumns, 1 / NumColumns)
thisWidget.state.widths = Iris._widgetState(thisWidget, "widths", Widths)
end
thisWidget._widths = table.create(NumColumns, UDim.new())
thisWidget._minWidths = table.create(NumColumns, 0)
local Table = thisWidget.Instance :: Frame
local BorderContainer: Frame = Table.BorderContainer
thisWidget._cellInstances[-1] = table.create(NumColumns)
for index = 1, NumColumns do
local Border = GenerateColumnBorder(thisWidget, index, "Light")
Border.Visible = thisWidget.arguments.InnerBorders
thisWidget._columnBorders[index] = Border
Border.Parent = BorderContainer
local Cell = GenerateCell(thisWidget, index, thisWidget._widths[index], false)
local UISizeConstraint = Cell:FindFirstChild("UISizeConstraint") :: UISizeConstraint
UISizeConstraint.MinSize = Vector2.new(
2 * Iris._config.CellPadding.X + (if index > 1 then -2 else 0) + (if index < NumColumns then -3 else 0),
0
)
Cell.LayoutOrder = 2 * index - 1
thisWidget._cellInstances[-1][index] = Cell
Cell.Parent = BorderContainer
end
local TableColumnBorder = GenerateColumnBorder(thisWidget, NumColumns, "Strong")
thisWidget._columnBorders[0] = TableColumnBorder
TableColumnBorder.Parent = Table
end,
Update = function(thisWidget: Types.Table)
local NumColumns = thisWidget.arguments.NumColumns
assert(NumColumns >= 1, "Iris.Table must have at least one column.")
if thisWidget._widths ~= nil and #thisWidget._widths ~= NumColumns then
-- disallow changing the number of columns. It's too much effort
thisWidget.arguments.NumColumns = #thisWidget._widths
warn("NumColumns cannot change once set. See documentation.")
end
for rowIndex, row in thisWidget._rowInstances do
if rowIndex == 0 then
row.BackgroundColor3 = Iris._config.TableHeaderColor
row.BackgroundTransparency = Iris._config.TableHeaderTransparency
elseif thisWidget.arguments.RowBackground == true then
if (rowIndex % 2) == 0 then
row.BackgroundColor3 = Iris._config.TableRowBgAltColor
row.BackgroundTransparency = Iris._config.TableRowBgAltTransparency
else
row.BackgroundColor3 = Iris._config.TableRowBgColor
row.BackgroundTransparency = Iris._config.TableRowBgTransparency
end
else
row.BackgroundTransparency = 1
end
end
for _, Border: Frame in thisWidget._rowBorders do
Border.Visible = thisWidget.arguments.InnerBorders
end
for _, Border: GuiButton in thisWidget._columnBorders do
Border.Visible = thisWidget.arguments.InnerBorders or thisWidget.arguments.Resizable
end
for _, border in thisWidget._columnBorders do
local hover = border:FindFirstChild("Hover") :: Frame?
if hover then
hover.Visible = thisWidget.arguments.Resizable
end
end
if thisWidget._columnBorders[NumColumns] ~= nil then
thisWidget._columnBorders[NumColumns].Visible =
not thisWidget.arguments.LimitTableWidth and (thisWidget.arguments.Resizable or thisWidget.arguments.InnerBorders)
thisWidget._columnBorders[0].Visible =
thisWidget.arguments.LimitTableWidth and (thisWidget.arguments.Resizable or thisWidget.arguments.OuterBorders)
end
-- the header border visibility must be updated after settings all borders
-- visiblity or not
local HeaderRow: Frame? = thisWidget._rowInstances[0]
local HeaderBorder: Frame? = thisWidget._rowBorders[0]
if HeaderRow ~= nil then
HeaderRow.Visible = thisWidget.arguments.Header
end
if HeaderBorder ~= nil then
HeaderBorder.Visible = thisWidget.arguments.Header and thisWidget.arguments.InnerBorders
end
local Table = thisWidget.Instance :: Frame
local BorderContainer = Table.BorderContainer :: Frame
BorderContainer.UIStroke.Enabled = thisWidget.arguments.OuterBorders
for index = 1, thisWidget.arguments.NumColumns do
TableMinWidths[thisWidget][index] = true
end
if thisWidget._widths ~= nil then
Iris._widgets["Table"].UpdateState(thisWidget)
end
end,
UpdateState = function(thisWidget: Types.Table)
local Table = thisWidget.Instance :: Frame
local BorderContainer = Table.BorderContainer :: Frame
local RowContainer = Table.RowContainer :: Frame
local NumColumns = thisWidget.arguments.NumColumns
local ColumnWidths = thisWidget.state.widths.value
local MinWidths = thisWidget._minWidths
local Fixed = thisWidget.arguments.FixedWidth
local Proportional = thisWidget.arguments.ProportionalWidth
if not thisWidget.arguments.Resizable then
if Fixed then
if Proportional then
for index = 1, NumColumns do
ColumnWidths[index] = MinWidths[index]
end
else
local maxWidth = 0
for _, width in MinWidths do
maxWidth = math.max(maxWidth, width)
end
for index = 1, NumColumns do
ColumnWidths[index] = maxWidth
end
end
else
if Proportional then
local TotalWidth = 0
for _, width in MinWidths do
TotalWidth += width
end
local Ratio = 1 / TotalWidth
for index = 1, NumColumns do
ColumnWidths[index] = Ratio * MinWidths[index]
end
else
local width = 1 / NumColumns
for index = 1, NumColumns do
ColumnWidths[index] = width
end
end
end
end
local Position = UDim.new()
for index = 1, NumColumns do
local ColumnWidth = ColumnWidths[index]
local Width = UDim.new(
if Fixed then 0 else math.clamp(ColumnWidth, 0, 1),
if Fixed then math.max(ColumnWidth, 0) else 0
)
thisWidget._widths[index] = Width
Position += Width
for _, row in thisWidget._cellInstances do
row[index].Size = UDim2.new(Width, UDim.new())
end
thisWidget._cellInstances[-1][index].Size = UDim2.new(Width + UDim.new(0,
(if index > 1 then -2 else 0) - 3
), UDim.new())
end
-- if the table has a fixed width and we want to cap it, we calculate the table width necessary
local Width = Position.Offset
if not thisWidget.arguments.FixedWidth or not thisWidget.arguments.LimitTableWidth then
Width = math.huge
end
BorderContainer.UISizeConstraint.MaxSize = Vector2.new(Width, math.huge)
RowContainer.UISizeConstraint.MaxSize = Vector2.new(Width, math.huge)
thisWidget._columnBorders[0].Position = UDim2.fromOffset(Width - 3, 0)
end,
ChildAdded = function(thisWidget: Types.Table, _: Types.Widget)
local rowIndex = thisWidget._rowIndex
local columnIndex = thisWidget._columnIndex
-- determine if the row exists yet
local Row = thisWidget._rowInstances[rowIndex]
thisWidget._rowCycles[rowIndex] = Iris._cycleTick
TableMinWidths[thisWidget][columnIndex] = true
if Row ~= nil then
return thisWidget._cellInstances[rowIndex][columnIndex]
end
Row = GenerateRow(thisWidget, rowIndex)
if rowIndex == 0 then
Row.Visible = thisWidget.arguments.Header
end
Row.Parent = thisWidget._rowContainer
if rowIndex > 0 then
local Border = GenerateRowBorder(thisWidget, rowIndex - 1, if rowIndex == 1 then "Strong" else "Light")
Border.Visible = thisWidget.arguments.InnerBorders and (if rowIndex == 1 then (thisWidget.arguments.Header and thisWidget.arguments.InnerBorders) and (thisWidget._rowInstances[0] ~= nil) else true)
thisWidget._rowBorders[rowIndex - 1] = Border
Border.Parent = thisWidget._rowContainer
end
return thisWidget._cellInstances[rowIndex][columnIndex]
end,
ChildDiscarded = function(thisWidget: Types.Table, thisChild: Types.Widget)
local Cell = thisChild.Instance.Parent
if Cell ~= nil then
local columnIndex = tonumber(Cell.Name:sub(6))
if columnIndex then
TableMinWidths[thisWidget][columnIndex] = true
end
end
end,
Discard = function(thisWidget: Types.Table)
Tables[thisWidget.ID] = nil
TableMinWidths[thisWidget] = nil
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end
} :: Types.WidgetClass)
end
| 5,534 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Text.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
--stylua: ignore
Iris.WidgetConstructor("Text", {
hasState = false,
hasChildren = false,
Args = {
["Text"] = 1,
["Wrapped"] = 2,
["Color"] = 3,
["RichText"] = 4,
},
Events = {
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(_thisWidget: Types.Text)
local Text = Instance.new("TextLabel")
Text.Name = "Iris_Text"
Text.AutomaticSize = Enum.AutomaticSize.XY
Text.Size = UDim2.fromOffset(0, 0)
Text.BackgroundTransparency = 1
Text.BorderSizePixel = 0
widgets.applyTextStyle(Text)
widgets.UIPadding(Text, Vector2.new(0, 2))
return Text
end,
Update = function(thisWidget: Types.Text)
local Text = thisWidget.Instance :: TextLabel
if thisWidget.arguments.Text == nil then
error("Text argument is required for Iris.Text().", 5)
end
if thisWidget.arguments.Wrapped ~= nil then
Text.TextWrapped = thisWidget.arguments.Wrapped
else
Text.TextWrapped = Iris._config.TextWrapped
end
if thisWidget.arguments.Color then
Text.TextColor3 = thisWidget.arguments.Color
else
Text.TextColor3 = Iris._config.TextColor
end
if thisWidget.arguments.RichText ~= nil then
Text.RichText = thisWidget.arguments.RichText
else
Text.RichText = Iris._config.RichText
end
Text.Text = thisWidget.arguments.Text
end,
Discard = function(thisWidget: Types.Text)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
--stylua: ignore
Iris.WidgetConstructor("SeparatorText", {
hasState = false,
hasChildren = false,
Args = {
["Text"] = 1,
},
Events = {
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
return thisWidget.Instance
end),
},
Generate = function(_thisWidget: Types.SeparatorText)
local SeparatorText = Instance.new("Frame")
SeparatorText.Name = "Iris_SeparatorText"
SeparatorText.AutomaticSize = Enum.AutomaticSize.Y
SeparatorText.Size = UDim2.new(Iris._config.ItemWidth, UDim.new())
SeparatorText.BackgroundTransparency = 1
SeparatorText.BorderSizePixel = 0
SeparatorText.ClipsDescendants = true
widgets.UIPadding(SeparatorText, Vector2.new(0, Iris._config.SeparatorTextPadding.Y))
widgets.UIListLayout(SeparatorText, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemSpacing.X))
SeparatorText.UIListLayout.VerticalAlignment = Enum.VerticalAlignment.Center
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
TextLabel.LayoutOrder = 1
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = SeparatorText
local Left = Instance.new("Frame")
Left.Name = "Left"
Left.AnchorPoint = Vector2.new(1, 0.5)
Left.Size = UDim2.fromOffset(Iris._config.SeparatorTextPadding.X - Iris._config.ItemSpacing.X, Iris._config.SeparatorTextBorderSize)
Left.BackgroundColor3 = Iris._config.SeparatorColor
Left.BackgroundTransparency = Iris._config.SeparatorTransparency
Left.BorderSizePixel = 0
Left.Parent = SeparatorText
local Right = Instance.new("Frame")
Right.Name = "Right"
Right.AnchorPoint = Vector2.new(1, 0.5)
Right.Size = UDim2.new(1, 0, 0, Iris._config.SeparatorTextBorderSize)
Right.BackgroundColor3 = Iris._config.SeparatorColor
Right.BackgroundTransparency = Iris._config.SeparatorTransparency
Right.BorderSizePixel = 0
Right.LayoutOrder = 2
Right.Parent = SeparatorText
return SeparatorText
end,
Update = function(thisWidget: Types.SeparatorText)
local SeparatorText = thisWidget.Instance :: Frame
local TextLabel: TextLabel = SeparatorText.TextLabel
if thisWidget.arguments.Text == nil then
error("Text argument is required for Iris.SeparatorText().", 5)
end
TextLabel.Text = thisWidget.arguments.Text
end,
Discard = function(thisWidget: Types.SeparatorText)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
end
| 1,082 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Tree.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local abstractTree = {
hasState = true,
hasChildren = true,
Events = {
["collapsed"] = {
["Init"] = function(_thisWidget: Types.CollapsingHeader) end,
["Get"] = function(thisWidget: Types.CollapsingHeader)
return thisWidget.lastCollapsedTick == Iris._cycleTick
end,
},
["uncollapsed"] = {
["Init"] = function(_thisWidget: Types.CollapsingHeader) end,
["Get"] = function(thisWidget: Types.CollapsingHeader)
return thisWidget.lastUncollapsedTick == Iris._cycleTick
end,
},
["hovered"] = widgets.EVENTS.hover(function(thisWidget)
return thisWidget.Instance
end),
},
Discard = function(thisWidget: Types.CollapsingHeader)
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
ChildAdded = function(thisWidget: Types.CollapsingHeader, _thisChild: Types.Widget)
local ChildContainer = thisWidget.ChildContainer :: Frame
ChildContainer.Visible = thisWidget.state.isUncollapsed.value
return ChildContainer
end,
UpdateState = function(thisWidget: Types.CollapsingHeader)
local isUncollapsed = thisWidget.state.isUncollapsed.value
local Tree = thisWidget.Instance :: Frame
local ChildContainer = thisWidget.ChildContainer :: Frame
local Header = Tree.Header :: Frame
local Button = Header.Button :: TextButton
local Arrow: ImageLabel = Button.Arrow
Arrow.Image = (isUncollapsed and widgets.ICONS.DOWN_POINTING_TRIANGLE or widgets.ICONS.RIGHT_POINTING_TRIANGLE)
if isUncollapsed then
thisWidget.lastUncollapsedTick = Iris._cycleTick + 1
else
thisWidget.lastCollapsedTick = Iris._cycleTick + 1
end
ChildContainer.Visible = isUncollapsed
end,
GenerateState = function(thisWidget: Types.CollapsingHeader)
if thisWidget.state.isUncollapsed == nil then
thisWidget.state.isUncollapsed = Iris._widgetState(thisWidget, "isUncollapsed", thisWidget.arguments.DefaultOpen or false)
end
end,
} :: Types.WidgetClass
--stylua: ignore
Iris.WidgetConstructor(
"Tree",
widgets.extend(abstractTree, {
Args = {
["Text"] = 1,
["SpanAvailWidth"] = 2,
["NoIndent"] = 3,
["DefaultOpen"] = 4,
},
Generate = function(thisWidget: Types.Tree)
local Tree = Instance.new("Frame")
Tree.Name = "Iris_Tree"
Tree.AutomaticSize = Enum.AutomaticSize.Y
Tree.Size = UDim2.new(Iris._config.ItemWidth, UDim.new(0, 0))
Tree.BackgroundTransparency = 1
Tree.BorderSizePixel = 0
widgets.UIListLayout(Tree, Enum.FillDirection.Vertical, UDim.new(0, 0))
local ChildContainer = Instance.new("Frame")
ChildContainer.Name = "TreeContainer"
ChildContainer.AutomaticSize = Enum.AutomaticSize.Y
ChildContainer.Size = UDim2.fromScale(1, 0)
ChildContainer.BackgroundTransparency = 1
ChildContainer.BorderSizePixel = 0
ChildContainer.LayoutOrder = 1
ChildContainer.Visible = false
-- ChildContainer.ClipsDescendants = true
widgets.UIListLayout(ChildContainer, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.ItemSpacing.Y))
widgets.UIPadding(ChildContainer, Vector2.zero).PaddingTop = UDim.new(0, Iris._config.ItemSpacing.Y)
ChildContainer.Parent = Tree
local Header = Instance.new("Frame")
Header.Name = "Header"
Header.AutomaticSize = Enum.AutomaticSize.Y
Header.Size = UDim2.fromScale(1, 0)
Header.BackgroundTransparency = 1
Header.BorderSizePixel = 0
Header.Parent = Tree
local Button = Instance.new("TextButton")
Button.Name = "Button"
Button.BackgroundTransparency = 1
Button.BorderSizePixel = 0
Button.Text = ""
Button.AutoButtonColor = false
widgets.applyInteractionHighlights("Background", Button, Header, {
Color = Color3.fromRGB(0, 0, 0),
Transparency = 1,
HoveredColor = Iris._config.HeaderHoveredColor,
HoveredTransparency = Iris._config.HeaderHoveredTransparency,
ActiveColor = Iris._config.HeaderActiveColor,
ActiveTransparency = Iris._config.HeaderActiveTransparency,
})
widgets.UIPadding(Button, Vector2.zero).PaddingLeft = UDim.new(0, Iris._config.FramePadding.X)
widgets.UIListLayout(Button, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.FramePadding.X)).VerticalAlignment = Enum.VerticalAlignment.Center
Button.Parent = Header
local Arrow = Instance.new("ImageLabel")
Arrow.Name = "Arrow"
Arrow.Size = UDim2.fromOffset(Iris._config.TextSize, math.floor(Iris._config.TextSize * 0.7))
Arrow.BackgroundTransparency = 1
Arrow.BorderSizePixel = 0
Arrow.ImageColor3 = Iris._config.TextColor
Arrow.ImageTransparency = Iris._config.TextTransparency
Arrow.ScaleType = Enum.ScaleType.Fit
Arrow.Parent = Button
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.Size = UDim2.fromOffset(0, 0)
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
widgets.UIPadding(TextLabel, Vector2.zero).PaddingRight = UDim.new(0, 21)
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = Button
widgets.applyButtonClick(Button, function()
thisWidget.state.isUncollapsed:set(not thisWidget.state.isUncollapsed.value)
end)
thisWidget.ChildContainer = ChildContainer
return Tree
end,
Update = function(thisWidget: Types.Tree)
local Tree = thisWidget.Instance :: Frame
local ChildContainer = thisWidget.ChildContainer :: Frame
local Header = Tree.Header :: Frame
local Button = Header.Button :: TextButton
local TextLabel: TextLabel = Button.TextLabel
local Padding: UIPadding = ChildContainer.UIPadding
TextLabel.Text = thisWidget.arguments.Text or "Tree"
if thisWidget.arguments.SpanAvailWidth then
Button.AutomaticSize = Enum.AutomaticSize.Y
Button.Size = UDim2.fromScale(1, 0)
else
Button.AutomaticSize = Enum.AutomaticSize.XY
Button.Size = UDim2.fromScale(0, 0)
end
if thisWidget.arguments.NoIndent then
Padding.PaddingLeft = UDim.new(0, 0)
else
Padding.PaddingLeft = UDim.new(0, Iris._config.IndentSpacing)
end
end,
})
)
--stylua: ignore
Iris.WidgetConstructor(
"CollapsingHeader",
widgets.extend(abstractTree, {
Args = {
["Text"] = 1,
["DefaultOpen"] = 2
},
Generate = function(thisWidget: Types.CollapsingHeader)
local CollapsingHeader = Instance.new("Frame")
CollapsingHeader.Name = "Iris_CollapsingHeader"
CollapsingHeader.AutomaticSize = Enum.AutomaticSize.Y
CollapsingHeader.Size = UDim2.new(Iris._config.ItemWidth, UDim.new(0, 0))
CollapsingHeader.BackgroundTransparency = 1
CollapsingHeader.BorderSizePixel = 0
widgets.UIListLayout(CollapsingHeader, Enum.FillDirection.Vertical, UDim.new(0, 0))
local ChildContainer = Instance.new("Frame")
ChildContainer.Name = "CollapsingHeaderContainer"
ChildContainer.AutomaticSize = Enum.AutomaticSize.Y
ChildContainer.Size = UDim2.fromScale(1, 0)
ChildContainer.BackgroundTransparency = 1
ChildContainer.BorderSizePixel = 0
ChildContainer.LayoutOrder = 1
ChildContainer.Visible = false
-- ChildContainer.ClipsDescendants = true
widgets.UIListLayout(ChildContainer, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.ItemSpacing.Y))
widgets.UIPadding(ChildContainer, Vector2.zero).PaddingTop = UDim.new(0, Iris._config.ItemSpacing.Y)
ChildContainer.Parent = CollapsingHeader
local Header = Instance.new("Frame")
Header.Name = "Header"
Header.AutomaticSize = Enum.AutomaticSize.Y
Header.Size = UDim2.fromScale(1, 0)
Header.BackgroundTransparency = 1
Header.BorderSizePixel = 0
Header.Parent = CollapsingHeader
local Button = Instance.new("TextButton")
Button.Name = "Button"
Button.AutomaticSize = Enum.AutomaticSize.Y
Button.Size = UDim2.fromScale(1, 0)
Button.BackgroundColor3 = Iris._config.HeaderColor
Button.BackgroundTransparency = Iris._config.HeaderTransparency
Button.BorderSizePixel = 0
Button.Text = ""
Button.AutoButtonColor = false
Button.ClipsDescendants = true
widgets.UIPadding(Button, Iris._config.FramePadding) -- we add a custom padding because it extends on both sides
widgets.applyFrameStyle(Button, true)
widgets.UIListLayout(Button, Enum.FillDirection.Horizontal, UDim.new(0, 2 * Iris._config.FramePadding.X)).VerticalAlignment = Enum.VerticalAlignment.Center
widgets.applyInteractionHighlights("Background", Button, Button, {
Color = Iris._config.HeaderColor,
Transparency = Iris._config.HeaderTransparency,
HoveredColor = Iris._config.HeaderHoveredColor,
HoveredTransparency = Iris._config.HeaderHoveredTransparency,
ActiveColor = Iris._config.HeaderActiveColor,
ActiveTransparency = Iris._config.HeaderActiveTransparency,
})
Button.Parent = Header
local Arrow = Instance.new("ImageLabel")
Arrow.Name = "Arrow"
Arrow.AutomaticSize = Enum.AutomaticSize.Y
Arrow.Size = UDim2.fromOffset(Iris._config.TextSize, math.ceil(Iris._config.TextSize * 0.8))
Arrow.BackgroundTransparency = 1
Arrow.BorderSizePixel = 0
Arrow.ImageColor3 = Iris._config.TextColor
Arrow.ImageTransparency = Iris._config.TextTransparency
Arrow.ScaleType = Enum.ScaleType.Fit
Arrow.Parent = Button
local TextLabel = Instance.new("TextLabel")
TextLabel.Name = "TextLabel"
TextLabel.AutomaticSize = Enum.AutomaticSize.XY
TextLabel.Size = UDim2.fromOffset(0, 0)
TextLabel.BackgroundTransparency = 1
TextLabel.BorderSizePixel = 0
widgets.UIPadding(TextLabel, Vector2.zero).PaddingRight = UDim.new(0, 21)
widgets.applyTextStyle(TextLabel)
TextLabel.Parent = Button
widgets.applyButtonClick(Button, function()
thisWidget.state.isUncollapsed:set(not thisWidget.state.isUncollapsed.value)
end)
thisWidget.ChildContainer = ChildContainer
return CollapsingHeader
end,
Update = function(thisWidget: Types.CollapsingHeader)
local Tree = thisWidget.Instance :: Frame
local Header = Tree.Header :: Frame
local Button = Header.Button :: TextButton
local TextLabel: TextLabel = Button.TextLabel
TextLabel.Text = thisWidget.arguments.Text or "Collapsing Header"
end,
})
)
end
| 2,614 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/Window.lua | local Types = require(script.Parent.Parent.Types)
return function(Iris: Types.Internal, widgets: Types.WidgetUtility)
local function relocateTooltips()
if Iris._rootInstance == nil then
return
end
local PopupScreenGui = Iris._rootInstance:FindFirstChild("PopupScreenGui")
local TooltipContainer: Frame = PopupScreenGui.TooltipContainer
local mouseLocation = widgets.getMouseLocation()
local newPosition = widgets.findBestWindowPosForPopup(mouseLocation, TooltipContainer.AbsoluteSize, Iris._config.DisplaySafeAreaPadding, PopupScreenGui.AbsoluteSize)
TooltipContainer.Position = UDim2.fromOffset(newPosition.X, newPosition.Y)
end
widgets.registerEvent("InputChanged", function()
if not Iris._started then
return
end
relocateTooltips()
end)
--stylua: ignore
Iris.WidgetConstructor("Tooltip", {
hasState = false,
hasChildren = false,
Args = {
["Text"] = 1,
},
Events = {},
Generate = function(thisWidget: Types.Tooltip)
thisWidget.parentWidget = Iris._rootWidget -- only allow root as parent
local Tooltip = Instance.new("Frame")
Tooltip.Name = "Iris_Tooltip"
Tooltip.AutomaticSize = Enum.AutomaticSize.Y
Tooltip.Size = UDim2.new(Iris._config.ContentWidth, UDim.new(0, 0))
Tooltip.BorderSizePixel = 0
Tooltip.BackgroundTransparency = 1
local TooltipText = Instance.new("TextLabel")
TooltipText.Name = "TooltipText"
TooltipText.AutomaticSize = Enum.AutomaticSize.XY
TooltipText.Size = UDim2.fromOffset(0, 0)
TooltipText.BackgroundColor3 = Iris._config.PopupBgColor
TooltipText.BackgroundTransparency = Iris._config.PopupBgTransparency
widgets.applyTextStyle(TooltipText)
widgets.UIStroke(TooltipText, Iris._config.PopupBorderSize, Iris._config.BorderActiveColor, Iris._config.BorderActiveTransparency)
widgets.UIPadding(TooltipText, Iris._config.WindowPadding)
if Iris._config.PopupRounding > 0 then
widgets.UICorner(TooltipText, Iris._config.PopupRounding)
end
TooltipText.Parent = Tooltip
return Tooltip
end,
Update = function(thisWidget: Types.Tooltip)
local Tooltip = thisWidget.Instance :: Frame
local TooltipText: TextLabel = Tooltip.TooltipText
if thisWidget.arguments.Text == nil then
error("Text argument is required for Iris.Tooltip().", 5)
end
TooltipText.Text = thisWidget.arguments.Text
relocateTooltips()
end,
Discard = function(thisWidget: Types.Tooltip)
thisWidget.Instance:Destroy()
end,
} :: Types.WidgetClass)
local windowDisplayOrder = 0 -- incremental count which is used for determining focused windows ZIndex
local dragWindow: Types.Window? -- window being dragged, may be nil
local isDragging = false
local moveDeltaCursorPosition: Vector2 -- cursor offset from drag origin (top left of window)
local resizeWindow: Types.Window? -- window being resized, may be nil
local isResizing = false
local isInsideResize = false -- is cursor inside of the focused window resize outer padding
local isInsideWindow = false -- is cursor inside of the focused window
local resizeFromTopBottom = Enum.TopBottom.Top
local resizeFromLeftRight = Enum.LeftRight.Left
local lastCursorPosition: Vector2
local focusedWindow: Types.Window? -- window with focus, may be nil
local anyFocusedWindow = false -- is there any focused window?
local windowWidgets: { [Types.ID]: Types.Window } = {} -- array of widget objects of type window
local function quickSwapWindows()
-- ctrl + tab swapping functionality
if Iris._config.UseScreenGUIs == false then
return
end
local lowest = 0xFFFF
local lowestWidget: Types.Window
for _, widget in windowWidgets do
if widget.state.isOpened.value and not widget.arguments.NoNav then
if widget.Instance:IsA("ScreenGui") then
local value = widget.Instance.DisplayOrder
if value < lowest then
lowest = value
lowestWidget = widget
end
end
end
end
if not lowestWidget then
return
end
if lowestWidget.state.isUncollapsed.value == false then
lowestWidget.state.isUncollapsed:set(true)
end
Iris.SetFocusedWindow(lowestWidget)
end
local function fitSizeToWindowBounds(thisWidget: Types.Window, intentedSize: Vector2)
local windowSize = Vector2.new(thisWidget.state.position.value.X, thisWidget.state.position.value.Y)
local minWindowSize = (Iris._config.TextSize + 2 * Iris._config.FramePadding.Y) * 2
local usableSize = widgets.getScreenSizeForWindow(thisWidget)
local safeAreaPadding = Vector2.new(Iris._config.WindowBorderSize + Iris._config.DisplaySafeAreaPadding.X, Iris._config.WindowBorderSize + Iris._config.DisplaySafeAreaPadding.Y)
local maxWindowSize = (usableSize - windowSize - safeAreaPadding)
return Vector2.new(math.clamp(intentedSize.X, minWindowSize, math.max(maxWindowSize.X, minWindowSize)), math.clamp(intentedSize.Y, minWindowSize, math.max(maxWindowSize.Y, minWindowSize)))
end
local function fitPositionToWindowBounds(thisWidget: Types.Window, intendedPosition: Vector2)
local thisWidgetInstance = thisWidget.Instance
local usableSize = widgets.getScreenSizeForWindow(thisWidget)
local safeAreaPadding = Vector2.new(Iris._config.WindowBorderSize + Iris._config.DisplaySafeAreaPadding.X, Iris._config.WindowBorderSize + Iris._config.DisplaySafeAreaPadding.Y)
return Vector2.new(
math.clamp(intendedPosition.X, safeAreaPadding.X, math.max(safeAreaPadding.X, usableSize.X - thisWidgetInstance.WindowButton.AbsoluteSize.X - safeAreaPadding.X)),
math.clamp(intendedPosition.Y, safeAreaPadding.Y, math.max(safeAreaPadding.Y, usableSize.Y - thisWidgetInstance.WindowButton.AbsoluteSize.Y - safeAreaPadding.Y))
)
end
Iris.SetFocusedWindow = function(thisWidget: Types.Window?)
if focusedWindow == thisWidget then
return
end
if anyFocusedWindow and focusedWindow ~= nil then
if windowWidgets[focusedWindow.ID] then
local Window = focusedWindow.Instance :: Frame
local WindowButton = Window.WindowButton :: TextButton
local Content = WindowButton.Content :: Frame
local TitleBar: Frame = Content.TitleBar
-- update appearance to unfocus
if focusedWindow.state.isUncollapsed.value then
TitleBar.BackgroundColor3 = Iris._config.TitleBgColor
TitleBar.BackgroundTransparency = Iris._config.TitleBgTransparency
else
TitleBar.BackgroundColor3 = Iris._config.TitleBgCollapsedColor
TitleBar.BackgroundTransparency = Iris._config.TitleBgCollapsedTransparency
end
WindowButton.UIStroke.Color = Iris._config.BorderColor
end
anyFocusedWindow = false
focusedWindow = nil
end
if thisWidget ~= nil then
-- update appearance to focus
anyFocusedWindow = true
focusedWindow = thisWidget
local Window = thisWidget.Instance :: Frame
local WindowButton = Window.WindowButton :: TextButton
local Content = WindowButton.Content :: Frame
local TitleBar: Frame = Content.TitleBar
TitleBar.BackgroundColor3 = Iris._config.TitleBgActiveColor
TitleBar.BackgroundTransparency = Iris._config.TitleBgActiveTransparency
WindowButton.UIStroke.Color = Iris._config.BorderActiveColor
windowDisplayOrder += 1
if thisWidget.usesScreenGuis then
Window.DisplayOrder = windowDisplayOrder + Iris._config.DisplayOrderOffset
else
Window.ZIndex = windowDisplayOrder + Iris._config.DisplayOrderOffset
end
if thisWidget.state.isUncollapsed.value == false then
thisWidget.state.isUncollapsed:set(true)
end
local firstSelectedObject: GuiObject? = widgets.GuiService.SelectedObject
if firstSelectedObject then
if TitleBar.Visible then
widgets.GuiService:Select(TitleBar)
else
widgets.GuiService:Select(thisWidget.ChildContainer)
end
end
end
end
widgets.registerEvent("InputBegan", function(input: InputObject)
if not Iris._started then
return
end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
local inWindow = false
local position = widgets.getMouseLocation()
for _, window in windowWidgets do
local Window = window.Instance
if not Window then
continue
end
local WindowButton = Window.WindowButton :: TextButton
local ResizeBorder: TextButton = WindowButton.ResizeBorder
if ResizeBorder and widgets.isPosInsideRect(position, ResizeBorder.AbsolutePosition - widgets.GuiOffset, ResizeBorder.AbsolutePosition - widgets.GuiOffset + ResizeBorder.AbsoluteSize) then
inWindow = true
break
end
end
if not inWindow then
Iris.SetFocusedWindow(nil)
end
end
if input.KeyCode == Enum.KeyCode.Tab and (widgets.UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or widgets.UserInputService:IsKeyDown(Enum.KeyCode.RightControl)) then
quickSwapWindows()
end
if input.UserInputType == Enum.UserInputType.MouseButton1 and isInsideResize and not isInsideWindow and anyFocusedWindow and focusedWindow then
local midWindow = focusedWindow.state.position.value + (focusedWindow.state.size.value / 2)
local cursorPosition = widgets.getMouseLocation() - midWindow
-- check which axis its closest to, then check which side is closest with math.sign
if math.abs(cursorPosition.X) * focusedWindow.state.size.value.Y >= math.abs(cursorPosition.Y) * focusedWindow.state.size.value.X then
resizeFromTopBottom = Enum.TopBottom.Center
resizeFromLeftRight = if math.sign(cursorPosition.X) == -1 then Enum.LeftRight.Left else Enum.LeftRight.Right
else
resizeFromLeftRight = Enum.LeftRight.Center
resizeFromTopBottom = if math.sign(cursorPosition.Y) == -1 then Enum.TopBottom.Top else Enum.TopBottom.Bottom
end
isResizing = true
resizeWindow = focusedWindow
end
end)
widgets.registerEvent("TouchTapInWorld", function(_, gameProcessedEvent: boolean)
if not Iris._started then
return
end
if not gameProcessedEvent then
Iris.SetFocusedWindow(nil)
end
end)
widgets.registerEvent("InputChanged", function(input: InputObject)
if not Iris._started then
return
end
if isDragging and dragWindow then
local mouseLocation
if input.UserInputType == Enum.UserInputType.Touch then
local location = input.Position
mouseLocation = Vector2.new(location.X, location.Y)
else
mouseLocation = widgets.getMouseLocation()
end
local Window = dragWindow.Instance :: Frame
local dragInstance: TextButton = Window.WindowButton
local intendedPosition = mouseLocation - moveDeltaCursorPosition
local newPos = fitPositionToWindowBounds(dragWindow, intendedPosition)
-- state shouldnt be used like this, but calling :set would run the entire UpdateState function for the window, which is slow.
dragInstance.Position = UDim2.fromOffset(newPos.X, newPos.Y)
dragWindow.state.position.value = newPos
end
if isResizing and resizeWindow and resizeWindow.arguments.NoResize ~= true then
local Window = resizeWindow.Instance :: Frame
local resizeInstance: TextButton = Window.WindowButton
local windowPosition = Vector2.new(resizeInstance.Position.X.Offset, resizeInstance.Position.Y.Offset)
local windowSize = Vector2.new(resizeInstance.Size.X.Offset, resizeInstance.Size.Y.Offset)
local mouseDelta
if input.UserInputType == Enum.UserInputType.Touch then
mouseDelta = input.Delta
else
mouseDelta = widgets.getMouseLocation() - lastCursorPosition
end
local intendedPosition = windowPosition + Vector2.new(if resizeFromLeftRight == Enum.LeftRight.Left then mouseDelta.X else 0, if resizeFromTopBottom == Enum.TopBottom.Top then mouseDelta.Y else 0)
local intendedSize = windowSize
+ Vector2.new(
if resizeFromLeftRight == Enum.LeftRight.Left then -mouseDelta.X elseif resizeFromLeftRight == Enum.LeftRight.Right then mouseDelta.X else 0,
if resizeFromTopBottom == Enum.TopBottom.Top then -mouseDelta.Y elseif resizeFromTopBottom == Enum.TopBottom.Bottom then mouseDelta.Y else 0
)
local newSize = fitSizeToWindowBounds(resizeWindow, intendedSize)
local newPosition = fitPositionToWindowBounds(resizeWindow, intendedPosition)
resizeInstance.Size = UDim2.fromOffset(newSize.X, newSize.Y)
resizeWindow.state.size.value = newSize
resizeInstance.Position = UDim2.fromOffset(newPosition.X, newPosition.Y)
resizeWindow.state.position.value = newPosition
end
lastCursorPosition = widgets.getMouseLocation()
end)
widgets.registerEvent("InputEnded", function(input, _)
if not Iris._started then
return
end
if (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch) and isDragging and dragWindow then
local Window = dragWindow.Instance :: Frame
local dragInstance: TextButton = Window.WindowButton
isDragging = false
dragWindow.state.position:set(Vector2.new(dragInstance.Position.X.Offset, dragInstance.Position.Y.Offset))
end
if (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch) and isResizing and resizeWindow then
local Window = resizeWindow.Instance :: Instance
isResizing = false
resizeWindow.state.size:set(Window.WindowButton.AbsoluteSize)
end
if input.KeyCode == Enum.KeyCode.ButtonX then
quickSwapWindows()
end
end)
--stylua: ignore
Iris.WidgetConstructor("Window", {
hasState = true,
hasChildren = true,
Args = {
["Title"] = 1,
["NoTitleBar"] = 2,
["NoBackground"] = 3,
["NoCollapse"] = 4,
["NoClose"] = 5,
["NoMove"] = 6,
["NoScrollbar"] = 7,
["NoResize"] = 8,
["NoNav"] = 9,
["NoMenu"] = 10,
},
Events = {
["closed"] = {
["Init"] = function(_thisWidget: Types.Window) end,
["Get"] = function(thisWidget: Types.Window)
return thisWidget.lastClosedTick == Iris._cycleTick
end,
},
["opened"] = {
["Init"] = function(_thisWidget: Types.Window) end,
["Get"] = function(thisWidget: Types.Window)
return thisWidget.lastOpenedTick == Iris._cycleTick
end,
},
["collapsed"] = {
["Init"] = function(_thisWidget: Types.Window) end,
["Get"] = function(thisWidget: Types.Window)
return thisWidget.lastCollapsedTick == Iris._cycleTick
end,
},
["uncollapsed"] = {
["Init"] = function(_thisWidget: Types.Window) end,
["Get"] = function(thisWidget: Types.Window)
return thisWidget.lastUncollapsedTick == Iris._cycleTick
end,
},
["hovered"] = widgets.EVENTS.hover(function(thisWidget: Types.Widget)
local Window = thisWidget.Instance :: Frame
return Window.WindowButton
end),
},
Generate = function(thisWidget: Types.Window)
thisWidget.parentWidget = Iris._rootWidget -- only allow root as parent
thisWidget.usesScreenGuis = Iris._config.UseScreenGUIs
windowWidgets[thisWidget.ID] = thisWidget
local Window
if thisWidget.usesScreenGuis then
Window = Instance.new("ScreenGui")
Window.ResetOnSpawn = false
Window.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
Window.DisplayOrder = Iris._config.DisplayOrderOffset
Window.ScreenInsets = Iris._config.ScreenInsets
Window.IgnoreGuiInset = Iris._config.IgnoreGuiInset
else
Window = Instance.new("Frame")
Window.AnchorPoint = Vector2.new(0.5, 0.5)
Window.Position = UDim2.fromScale(0.5, 0.5)
Window.Size = UDim2.fromScale(1, 1)
Window.BackgroundTransparency = 1
Window.ZIndex = Iris._config.DisplayOrderOffset
end
Window.Name = "Iris_Window"
local WindowButton = Instance.new("TextButton")
WindowButton.Name = "WindowButton"
WindowButton.Size = UDim2.fromOffset(0, 0)
WindowButton.BackgroundTransparency = 1
WindowButton.BorderSizePixel = 0
WindowButton.Text = ""
WindowButton.AutoButtonColor = false
WindowButton.ClipsDescendants = false
WindowButton.Selectable = false
WindowButton.SelectionImageObject = Iris.SelectionImageObject
WindowButton.SelectionGroup = true
WindowButton.SelectionBehaviorUp = Enum.SelectionBehavior.Stop
WindowButton.SelectionBehaviorDown = Enum.SelectionBehavior.Stop
WindowButton.SelectionBehaviorLeft = Enum.SelectionBehavior.Stop
WindowButton.SelectionBehaviorRight = Enum.SelectionBehavior.Stop
widgets.UIStroke(WindowButton, Iris._config.WindowBorderSize, Iris._config.BorderColor, Iris._config.BorderTransparency)
WindowButton.Parent = Window
widgets.applyInputBegan(WindowButton, function(input)
if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Keyboard then
return
end
if thisWidget.state.isUncollapsed.value then
Iris.SetFocusedWindow(thisWidget)
end
if not thisWidget.arguments.NoMove and input.UserInputType == Enum.UserInputType.MouseButton1 then
dragWindow = thisWidget
isDragging = true
moveDeltaCursorPosition = widgets.getMouseLocation() - thisWidget.state.position.value
end
end)
local Content = Instance.new("Frame")
Content.Name = "Content"
Content.AnchorPoint = Vector2.new(0.5, 0.5)
Content.Position = UDim2.fromScale(0.5, 0.5)
Content.Size = UDim2.fromScale(1, 1)
Content.BackgroundTransparency = 1
Content.ClipsDescendants = true
Content.Parent = WindowButton
local UIListLayout = widgets.UIListLayout(Content, Enum.FillDirection.Vertical, UDim.new(0, 0))
UIListLayout.HorizontalAlignment = Enum.HorizontalAlignment.Center
UIListLayout.VerticalAlignment = Enum.VerticalAlignment.Top
local ChildContainer = Instance.new("ScrollingFrame")
ChildContainer.Name = "WindowContainer"
ChildContainer.Size = UDim2.fromScale(1, 1)
ChildContainer.BackgroundColor3 = Iris._config.WindowBgColor
ChildContainer.BackgroundTransparency = Iris._config.WindowBgTransparency
ChildContainer.BorderSizePixel = 0
ChildContainer.AutomaticCanvasSize = Enum.AutomaticSize.Y
ChildContainer.ScrollBarImageTransparency = Iris._config.ScrollbarGrabTransparency
ChildContainer.ScrollBarImageColor3 = Iris._config.ScrollbarGrabColor
ChildContainer.CanvasSize = UDim2.fromScale(0, 0)
ChildContainer.VerticalScrollBarInset = Enum.ScrollBarInset.ScrollBar
ChildContainer.TopImage = widgets.ICONS.BLANK_SQUARE
ChildContainer.MidImage = widgets.ICONS.BLANK_SQUARE
ChildContainer.BottomImage = widgets.ICONS.BLANK_SQUARE
ChildContainer.LayoutOrder = thisWidget.ZIndex + 0xFFFF
ChildContainer.ClipsDescendants = true
widgets.UIPadding(ChildContainer, Iris._config.WindowPadding)
ChildContainer.Parent = Content
local UIFlexItem = Instance.new("UIFlexItem")
UIFlexItem.FlexMode = Enum.UIFlexMode.Fill
UIFlexItem.ItemLineAlignment = Enum.ItemLineAlignment.End
UIFlexItem.Parent = ChildContainer
ChildContainer:GetPropertyChangedSignal("CanvasPosition"):Connect(function()
-- "wrong" use of state here, for optimization
thisWidget.state.scrollDistance.value = ChildContainer.CanvasPosition.Y
end)
widgets.applyInputBegan(ChildContainer, function(input)
if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Keyboard then
return
end
if thisWidget.state.isUncollapsed.value then
Iris.SetFocusedWindow(thisWidget)
end
end)
local TerminatingFrame = Instance.new("Frame")
TerminatingFrame.Name = "TerminatingFrame"
TerminatingFrame.Size = UDim2.fromOffset(0, Iris._config.WindowPadding.Y + Iris._config.FramePadding.Y)
TerminatingFrame.BackgroundTransparency = 1
TerminatingFrame.BorderSizePixel = 0
TerminatingFrame.LayoutOrder = 0x7FFFFFF0
widgets.UIListLayout(ChildContainer, Enum.FillDirection.Vertical, UDim.new(0, Iris._config.ItemSpacing.Y)).VerticalAlignment = Enum.VerticalAlignment.Top
TerminatingFrame.Parent = ChildContainer
local TitleBar = Instance.new("Frame")
TitleBar.Name = "TitleBar"
TitleBar.AutomaticSize = Enum.AutomaticSize.Y
TitleBar.Size = UDim2.fromScale(1, 0)
TitleBar.BorderSizePixel = 0
TitleBar.ClipsDescendants = true
TitleBar.Parent = Content
widgets.UIPadding(TitleBar, Vector2.new(Iris._config.FramePadding.X))
widgets.UIListLayout(TitleBar, Enum.FillDirection.Horizontal, UDim.new(0, Iris._config.ItemInnerSpacing.X)).VerticalAlignment = Enum.VerticalAlignment.Center
widgets.applyInputBegan(TitleBar, function(input)
if input.UserInputType == Enum.UserInputType.Touch then
if not thisWidget.arguments.NoMove then
dragWindow = thisWidget
isDragging = true
local location = input.Position
moveDeltaCursorPosition = Vector2.new(location.X, location.Y) - thisWidget.state.position.value
end
end
end)
local TitleButtonSize = Iris._config.TextSize + ((Iris._config.FramePadding.Y - 1) * 2)
local CollapseButton = Instance.new("TextButton")
CollapseButton.Name = "CollapseButton"
CollapseButton.AutomaticSize = Enum.AutomaticSize.None
CollapseButton.AnchorPoint = Vector2.new(0, 0.5)
CollapseButton.Size = UDim2.fromOffset(TitleButtonSize, TitleButtonSize)
CollapseButton.Position = UDim2.fromScale(0, 0.5)
CollapseButton.BackgroundTransparency = 1
CollapseButton.BorderSizePixel = 0
CollapseButton.AutoButtonColor = false
CollapseButton.Text = ""
widgets.UICorner(CollapseButton)
CollapseButton.Parent = TitleBar
widgets.applyButtonClick(CollapseButton, function()
thisWidget.state.isUncollapsed:set(not thisWidget.state.isUncollapsed.value)
end)
widgets.applyInteractionHighlights("Background", CollapseButton, CollapseButton, {
Color = Iris._config.ButtonColor,
Transparency = 1,
HoveredColor = Iris._config.ButtonHoveredColor,
HoveredTransparency = Iris._config.ButtonHoveredTransparency,
ActiveColor = Iris._config.ButtonActiveColor,
ActiveTransparency = Iris._config.ButtonActiveTransparency,
})
local CollapseArrow = Instance.new("ImageLabel")
CollapseArrow.Name = "Arrow"
CollapseArrow.AnchorPoint = Vector2.new(0.5, 0.5)
CollapseArrow.Size = UDim2.fromOffset(math.floor(0.7 * TitleButtonSize), math.floor(0.7 * TitleButtonSize))
CollapseArrow.Position = UDim2.fromScale(0.5, 0.5)
CollapseArrow.BackgroundTransparency = 1
CollapseArrow.BorderSizePixel = 0
CollapseArrow.Image = widgets.ICONS.MULTIPLICATION_SIGN
CollapseArrow.ImageColor3 = Iris._config.TextColor
CollapseArrow.ImageTransparency = Iris._config.TextTransparency
CollapseArrow.Parent = CollapseButton
local CloseButton = Instance.new("TextButton")
CloseButton.Name = "CloseButton"
CloseButton.AutomaticSize = Enum.AutomaticSize.None
CloseButton.AnchorPoint = Vector2.new(1, 0.5)
CloseButton.Size = UDim2.fromOffset(TitleButtonSize, TitleButtonSize)
CloseButton.Position = UDim2.fromScale(1, 0.5)
CloseButton.BackgroundTransparency = 1
CloseButton.BorderSizePixel = 0
CloseButton.Text = ""
CloseButton.AutoButtonColor = false
CloseButton.LayoutOrder = 2
widgets.UICorner(CloseButton)
widgets.applyButtonClick(CloseButton, function()
thisWidget.state.isOpened:set(false)
end)
widgets.applyInteractionHighlights("Background", CloseButton, CloseButton, {
Color = Iris._config.ButtonColor,
Transparency = 1,
HoveredColor = Iris._config.ButtonHoveredColor,
HoveredTransparency = Iris._config.ButtonHoveredTransparency,
ActiveColor = Iris._config.ButtonActiveColor,
ActiveTransparency = Iris._config.ButtonActiveTransparency,
})
CloseButton.Parent = TitleBar
local CloseIcon = Instance.new("ImageLabel")
CloseIcon.Name = "Icon"
CloseIcon.AnchorPoint = Vector2.new(0.5, 0.5)
CloseIcon.Size = UDim2.fromOffset(math.floor(0.7 * TitleButtonSize), math.floor(0.7 * TitleButtonSize))
CloseIcon.Position = UDim2.fromScale(0.5, 0.5)
CloseIcon.BackgroundTransparency = 1
CloseIcon.BorderSizePixel = 0
CloseIcon.Image = widgets.ICONS.MULTIPLICATION_SIGN
CloseIcon.ImageColor3 = Iris._config.TextColor
CloseIcon.ImageTransparency = Iris._config.TextTransparency
CloseIcon.Parent = CloseButton
-- allowing fractional titlebar title location dosent seem useful, as opposed to Enum.LeftRight.
local Title = Instance.new("TextLabel")
Title.Name = "Title"
Title.AutomaticSize = Enum.AutomaticSize.XY
Title.BorderSizePixel = 0
Title.BackgroundTransparency = 1
Title.LayoutOrder = 1
Title.ClipsDescendants = true
widgets.UIPadding(Title, Vector2.new(0, Iris._config.FramePadding.Y))
widgets.applyTextStyle(Title)
Title.TextXAlignment = Enum.TextXAlignment[Iris._config.WindowTitleAlign.Name] :: Enum.TextXAlignment
local TitleFlexItem = Instance.new("UIFlexItem")
TitleFlexItem.FlexMode = Enum.UIFlexMode.Fill
TitleFlexItem.ItemLineAlignment = Enum.ItemLineAlignment.Center
TitleFlexItem.Parent = Title
Title.Parent = TitleBar
local ResizeButtonSize = Iris._config.TextSize + Iris._config.FramePadding.X
local LeftResizeGrip = Instance.new("ImageButton")
LeftResizeGrip.Name = "LeftResizeGrip"
LeftResizeGrip.AnchorPoint = Vector2.yAxis
LeftResizeGrip.Rotation = 180
LeftResizeGrip.Position = UDim2.fromScale(0, 1)
LeftResizeGrip.Size = UDim2.fromOffset(ResizeButtonSize, ResizeButtonSize)
LeftResizeGrip.BackgroundTransparency = 1
LeftResizeGrip.BorderSizePixel = 0
LeftResizeGrip.Image = widgets.ICONS.BOTTOM_RIGHT_CORNER
LeftResizeGrip.ImageColor3 = Iris._config.ResizeGripColor
LeftResizeGrip.ImageTransparency = 1
LeftResizeGrip.AutoButtonColor = false
LeftResizeGrip.ZIndex = 3
LeftResizeGrip.Parent = WindowButton
widgets.applyInteractionHighlights("Image", LeftResizeGrip, LeftResizeGrip, {
Color = Iris._config.ResizeGripColor,
Transparency = 1,
HoveredColor = Iris._config.ResizeGripHoveredColor,
HoveredTransparency = Iris._config.ResizeGripHoveredTransparency,
ActiveColor = Iris._config.ResizeGripActiveColor,
ActiveTransparency = Iris._config.ResizeGripActiveTransparency,
})
widgets.applyButtonDown(LeftResizeGrip, function()
if not anyFocusedWindow or not (focusedWindow == thisWidget) then
Iris.SetFocusedWindow(thisWidget)
-- mitigating wrong focus when clicking on buttons inside of a window without clicking the window itself
end
isResizing = true
resizeFromTopBottom = Enum.TopBottom.Bottom
resizeFromLeftRight = Enum.LeftRight.Left
resizeWindow = thisWidget
end)
-- each border uses an image, allowing it to have a visible borde which is larger than the UI
local RightResizeGrip = Instance.new("ImageButton")
RightResizeGrip.Name = "RightResizeGrip"
RightResizeGrip.AnchorPoint = Vector2.one
RightResizeGrip.Rotation = 90
RightResizeGrip.Position = UDim2.fromScale(1, 1)
RightResizeGrip.Size = UDim2.fromOffset(ResizeButtonSize, ResizeButtonSize)
RightResizeGrip.BackgroundTransparency = 1
RightResizeGrip.BorderSizePixel = 0
RightResizeGrip.Image = widgets.ICONS.BOTTOM_RIGHT_CORNER
RightResizeGrip.ImageColor3 = Iris._config.ResizeGripColor
RightResizeGrip.ImageTransparency = Iris._config.ResizeGripTransparency
RightResizeGrip.AutoButtonColor = false
RightResizeGrip.ZIndex = 3
RightResizeGrip.Parent = WindowButton
widgets.applyInteractionHighlights("Image", RightResizeGrip, RightResizeGrip, {
Color = Iris._config.ResizeGripColor,
Transparency = Iris._config.ResizeGripTransparency,
HoveredColor = Iris._config.ResizeGripHoveredColor,
HoveredTransparency = Iris._config.ResizeGripHoveredTransparency,
ActiveColor = Iris._config.ResizeGripActiveColor,
ActiveTransparency = Iris._config.ResizeGripActiveTransparency,
})
widgets.applyButtonDown(RightResizeGrip, function()
if not anyFocusedWindow or not (focusedWindow == thisWidget) then
Iris.SetFocusedWindow(thisWidget)
-- mitigating wrong focus when clicking on buttons inside of a window without clicking the window itself
end
isResizing = true
resizeFromTopBottom = Enum.TopBottom.Bottom
resizeFromLeftRight = Enum.LeftRight.Right
resizeWindow = thisWidget
end)
local LeftResizeBorder = Instance.new("ImageButton")
LeftResizeBorder.Name = "LeftResizeBorder"
LeftResizeBorder.AnchorPoint = Vector2.new(1, .5)
LeftResizeBorder.Position = UDim2.fromScale(0, .5)
LeftResizeBorder.Size = UDim2.new(0, Iris._config.WindowResizePadding.X, 1, 2 * Iris._config.WindowBorderSize)
LeftResizeBorder.Transparency = 1
LeftResizeBorder.Image = widgets.ICONS.BORDER
LeftResizeBorder.ResampleMode = Enum.ResamplerMode.Pixelated
LeftResizeBorder.ScaleType = Enum.ScaleType.Slice
LeftResizeBorder.SliceCenter = Rect.new(0, 0, 1, 1)
LeftResizeBorder.ImageRectOffset = Vector2.new(2, 2)
LeftResizeBorder.ImageRectSize = Vector2.new(2, 1)
LeftResizeBorder.ImageTransparency = 1
LeftResizeBorder.AutoButtonColor = false
LeftResizeBorder.ZIndex = 4
LeftResizeBorder.Parent = WindowButton
local RightResizeBorder = Instance.new("ImageButton")
RightResizeBorder.Name = "RightResizeBorder"
RightResizeBorder.AnchorPoint = Vector2.new(0, .5)
RightResizeBorder.Position = UDim2.fromScale(1, .5)
RightResizeBorder.Size = UDim2.new(0, Iris._config.WindowResizePadding.X, 1, 2 * Iris._config.WindowBorderSize)
RightResizeBorder.Transparency = 1
RightResizeBorder.Image = widgets.ICONS.BORDER
RightResizeBorder.ResampleMode = Enum.ResamplerMode.Pixelated
RightResizeBorder.ScaleType = Enum.ScaleType.Slice
RightResizeBorder.SliceCenter = Rect.new(1, 0, 2, 1)
RightResizeBorder.ImageRectOffset = Vector2.new(1, 2)
RightResizeBorder.ImageRectSize = Vector2.new(2, 1)
RightResizeBorder.ImageTransparency = 1
RightResizeBorder.AutoButtonColor = false
RightResizeBorder.ZIndex = 4
RightResizeBorder.Parent = WindowButton
local TopResizeBorder = Instance.new("ImageButton")
TopResizeBorder.Name = "TopResizeBorder"
TopResizeBorder.AnchorPoint = Vector2.new(.5, 1)
TopResizeBorder.Position = UDim2.fromScale(.5, 0)
TopResizeBorder.Size = UDim2.new(1, 2 * Iris._config.WindowBorderSize, 0, Iris._config.WindowResizePadding.Y)
TopResizeBorder.Transparency = 1
TopResizeBorder.Image = widgets.ICONS.BORDER
TopResizeBorder.ResampleMode = Enum.ResamplerMode.Pixelated
TopResizeBorder.ScaleType = Enum.ScaleType.Slice
TopResizeBorder.SliceCenter = Rect.new(0, 0, 1, 1)
TopResizeBorder.ImageRectOffset = Vector2.new(2, 2)
TopResizeBorder.ImageRectSize = Vector2.new(1, 2)
TopResizeBorder.ImageTransparency = 1
TopResizeBorder.AutoButtonColor = false
TopResizeBorder.ZIndex = 4
TopResizeBorder.Parent = WindowButton
local BottomResizeBorder = Instance.new("ImageButton")
BottomResizeBorder.Name = "BottomResizeBorder"
BottomResizeBorder.AnchorPoint = Vector2.new(.5, 0)
BottomResizeBorder.Position = UDim2.fromScale(.5, 1)
BottomResizeBorder.Size = UDim2.new(1, 2 * Iris._config.WindowBorderSize, 0, Iris._config.WindowResizePadding.Y)
BottomResizeBorder.Transparency = 1
BottomResizeBorder.Image = widgets.ICONS.BORDER
BottomResizeBorder.ResampleMode = Enum.ResamplerMode.Pixelated
BottomResizeBorder.ScaleType = Enum.ScaleType.Slice
BottomResizeBorder.SliceCenter = Rect.new(0, 1, 1, 2)
BottomResizeBorder.ImageRectOffset = Vector2.new(2, 1)
BottomResizeBorder.ImageRectSize = Vector2.new(1, 2)
BottomResizeBorder.ImageTransparency = 1
BottomResizeBorder.AutoButtonColor = false
BottomResizeBorder.ZIndex = 4
BottomResizeBorder.Parent = WindowButton
widgets.applyInteractionHighlights("Image", LeftResizeBorder, LeftResizeBorder, {
Color = Iris._config.ResizeGripColor,
Transparency = 1,
HoveredColor = Iris._config.ResizeGripHoveredColor,
HoveredTransparency = Iris._config.ResizeGripHoveredTransparency,
ActiveColor = Iris._config.ResizeGripActiveColor,
ActiveTransparency = Iris._config.ResizeGripActiveTransparency,
})
widgets.applyInteractionHighlights("Image", RightResizeBorder, RightResizeBorder, {
Color = Iris._config.ResizeGripColor,
Transparency = 1,
HoveredColor = Iris._config.ResizeGripHoveredColor,
HoveredTransparency = Iris._config.ResizeGripHoveredTransparency,
ActiveColor = Iris._config.ResizeGripActiveColor,
ActiveTransparency = Iris._config.ResizeGripActiveTransparency,
})
widgets.applyInteractionHighlights("Image", TopResizeBorder, TopResizeBorder, {
Color = Iris._config.ResizeGripColor,
Transparency = 1,
HoveredColor = Iris._config.ResizeGripHoveredColor,
HoveredTransparency = Iris._config.ResizeGripHoveredTransparency,
ActiveColor = Iris._config.ResizeGripActiveColor,
ActiveTransparency = Iris._config.ResizeGripActiveTransparency,
})
widgets.applyInteractionHighlights("Image", BottomResizeBorder, BottomResizeBorder, {
Color = Iris._config.ResizeGripColor,
Transparency = 1,
HoveredColor = Iris._config.ResizeGripHoveredColor,
HoveredTransparency = Iris._config.ResizeGripHoveredTransparency,
ActiveColor = Iris._config.ResizeGripActiveColor,
ActiveTransparency = Iris._config.ResizeGripActiveTransparency,
})
local ResizeBorder = Instance.new("Frame")
ResizeBorder.Name = "ResizeBorder"
ResizeBorder.Position = UDim2.fromOffset(-Iris._config.WindowResizePadding.X, -Iris._config.WindowResizePadding.Y)
ResizeBorder.Size = UDim2.new(1, Iris._config.WindowResizePadding.X * 2, 1, Iris._config.WindowResizePadding.Y * 2)
ResizeBorder.BackgroundTransparency = 1
ResizeBorder.BorderSizePixel = 0
ResizeBorder.Active = false
ResizeBorder.Selectable = false
ResizeBorder.ClipsDescendants = false
ResizeBorder.Parent = WindowButton
widgets.applyMouseEnter(ResizeBorder, function()
if focusedWindow == thisWidget then
isInsideResize = true
end
end)
widgets.applyMouseLeave(ResizeBorder, function()
if focusedWindow == thisWidget then
isInsideResize = false
end
end)
widgets.applyInputBegan(ResizeBorder, function(input)
if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Keyboard then
return
end
if thisWidget.state.isUncollapsed.value then
Iris.SetFocusedWindow(thisWidget)
end
end)
widgets.applyMouseEnter(WindowButton, function()
if focusedWindow == thisWidget then
isInsideWindow = true
end
end)
widgets.applyMouseLeave(WindowButton, function()
if focusedWindow == thisWidget then
isInsideWindow = false
end
end)
thisWidget.ChildContainer = ChildContainer
return Window
end,
GenerateState = function(thisWidget: Types.Window)
if thisWidget.state.size == nil then
thisWidget.state.size = Iris._widgetState(thisWidget, "size", Vector2.new(400, 300))
end
if thisWidget.state.position == nil then
thisWidget.state.position = Iris._widgetState(thisWidget, "position", if anyFocusedWindow and focusedWindow then focusedWindow.state.position.value + Vector2.new(15, 45) else Vector2.new(150, 250))
end
thisWidget.state.position.value = fitPositionToWindowBounds(thisWidget, thisWidget.state.position.value)
thisWidget.state.size.value = fitSizeToWindowBounds(thisWidget, thisWidget.state.size.value)
if thisWidget.state.isUncollapsed == nil then
thisWidget.state.isUncollapsed = Iris._widgetState(thisWidget, "isUncollapsed", true)
end
if thisWidget.state.isOpened == nil then
thisWidget.state.isOpened = Iris._widgetState(thisWidget, "isOpened", true)
end
if thisWidget.state.scrollDistance == nil then
thisWidget.state.scrollDistance = Iris._widgetState(thisWidget, "scrollDistance", 0)
end
end,
Update = function(thisWidget: Types.Window)
local Window = thisWidget.Instance :: GuiObject
local ChildContainer = thisWidget.ChildContainer :: ScrollingFrame
local WindowButton = Window.WindowButton :: TextButton
local Content = WindowButton.Content :: Frame
local TitleBar = Content.TitleBar :: Frame
local Title: TextLabel = TitleBar.Title
local MenuBar: Frame? = Content:FindFirstChild("Iris_MenuBar")
local LeftResizeGrip: TextButton = WindowButton.LeftResizeGrip
local RightResizeGrip: TextButton = WindowButton.RightResizeGrip
local LeftResizeBorder: Frame = WindowButton.LeftResizeBorder
local RightResizeBorder: Frame = WindowButton.RightResizeBorder
local TopResizeBorder: Frame = WindowButton.TopResizeBorder
local BottomResizeBorder: Frame = WindowButton.BottomResizeBorder
if thisWidget.arguments.NoResize ~= true then
LeftResizeGrip.Visible = true
RightResizeGrip.Visible = true
LeftResizeBorder.Visible = true
RightResizeBorder.Visible = true
TopResizeBorder.Visible = true
BottomResizeBorder.Visible = true
else
LeftResizeGrip.Visible = false
RightResizeGrip.Visible = false
LeftResizeBorder.Visible = false
RightResizeBorder.Visible = false
TopResizeBorder.Visible = false
BottomResizeBorder.Visible = false
end
if thisWidget.arguments.NoScrollbar then
ChildContainer.ScrollBarThickness = 0
else
ChildContainer.ScrollBarThickness = Iris._config.ScrollbarSize
end
if thisWidget.arguments.NoTitleBar then
TitleBar.Visible = false
else
TitleBar.Visible = true
end
if MenuBar then
if thisWidget.arguments.NoMenu then
MenuBar.Visible = false
else
MenuBar.Visible = true
end
end
if thisWidget.arguments.NoBackground then
ChildContainer.BackgroundTransparency = 1
else
ChildContainer.BackgroundTransparency = Iris._config.WindowBgTransparency
end
-- TitleBar buttons
if thisWidget.arguments.NoCollapse then
TitleBar.CollapseButton.Visible = false
else
TitleBar.CollapseButton.Visible = true
end
if thisWidget.arguments.NoClose then
TitleBar.CloseButton.Visible = false
else
TitleBar.CloseButton.Visible = true
end
Title.Text = thisWidget.arguments.Title or ""
end,
UpdateState = function(thisWidget: Types.Window)
local stateSize = thisWidget.state.size.value
local statePosition = thisWidget.state.position.value
local stateIsUncollapsed = thisWidget.state.isUncollapsed.value
local stateIsOpened = thisWidget.state.isOpened.value
local stateScrollDistance = thisWidget.state.scrollDistance.value
local Window = thisWidget.Instance :: Frame
local ChildContainer = thisWidget.ChildContainer :: ScrollingFrame
local WindowButton = Window.WindowButton :: TextButton
local Content = WindowButton.Content :: Frame
local TitleBar = Content.TitleBar :: Frame
local MenuBar: Frame? = Content:FindFirstChild("Iris_MenuBar")
local LeftResizeGrip: TextButton = WindowButton.LeftResizeGrip
local RightResizeGrip: TextButton = WindowButton.RightResizeGrip
local LeftResizeBorder: Frame = WindowButton.LeftResizeBorder
local RightResizeBorder: Frame = WindowButton.RightResizeBorder
local TopResizeBorder: Frame = WindowButton.TopResizeBorder
local BottomResizeBorder: Frame = WindowButton.BottomResizeBorder
WindowButton.Size = UDim2.fromOffset(stateSize.X, stateSize.Y)
WindowButton.Position = UDim2.fromOffset(statePosition.X, statePosition.Y)
if stateIsOpened then
if thisWidget.usesScreenGuis then
Window.Enabled = true
WindowButton.Visible = true
else
Window.Visible = true
WindowButton.Visible = true
end
thisWidget.lastOpenedTick = Iris._cycleTick + 1
else
if thisWidget.usesScreenGuis then
Window.Enabled = false
WindowButton.Visible = false
else
Window.Visible = false
WindowButton.Visible = false
end
thisWidget.lastClosedTick = Iris._cycleTick + 1
end
if stateIsUncollapsed then
TitleBar.CollapseButton.Arrow.Image = widgets.ICONS.DOWN_POINTING_TRIANGLE
if MenuBar then
MenuBar.Visible = not thisWidget.arguments.NoMenu
end
ChildContainer.Visible = true
if thisWidget.arguments.NoResize ~= true then
LeftResizeGrip.Visible = true
RightResizeGrip.Visible = true
LeftResizeBorder.Visible = true
RightResizeBorder.Visible = true
TopResizeBorder.Visible = true
BottomResizeBorder.Visible = true
end
WindowButton.AutomaticSize = Enum.AutomaticSize.None
thisWidget.lastUncollapsedTick = Iris._cycleTick + 1
else
local collapsedHeight: number = TitleBar.AbsoluteSize.Y -- Iris._config.TextSize + Iris._config.FramePadding.Y * 2
TitleBar.CollapseButton.Arrow.Image = widgets.ICONS.RIGHT_POINTING_TRIANGLE
if MenuBar then
MenuBar.Visible = false
end
ChildContainer.Visible = false
LeftResizeGrip.Visible = false
RightResizeGrip.Visible = false
LeftResizeBorder.Visible = false
RightResizeBorder.Visible = false
TopResizeBorder.Visible = false
BottomResizeBorder.Visible = false
WindowButton.Size = UDim2.fromOffset(stateSize.X, collapsedHeight)
thisWidget.lastCollapsedTick = Iris._cycleTick + 1
end
if stateIsOpened and stateIsUncollapsed then
Iris.SetFocusedWindow(thisWidget)
else
TitleBar.BackgroundColor3 = Iris._config.TitleBgCollapsedColor
TitleBar.BackgroundTransparency = Iris._config.TitleBgCollapsedTransparency
WindowButton.UIStroke.Color = Iris._config.BorderColor
Iris.SetFocusedWindow(nil)
end
-- cant update canvasPosition in this cycle because scrollingframe isint ready to be changed
if stateScrollDistance and stateScrollDistance ~= 0 then
local callbackIndex = #Iris._postCycleCallbacks + 1
local desiredCycleTick = Iris._cycleTick + 1
Iris._postCycleCallbacks[callbackIndex] = function()
if Iris._cycleTick >= desiredCycleTick then
if thisWidget.lastCycleTick ~= -1 then
ChildContainer.CanvasPosition = Vector2.new(0, stateScrollDistance)
end
Iris._postCycleCallbacks[callbackIndex] = nil
end
end
end
end,
ChildAdded = function(thisWidget: Types.Window, thisChid: Types.Widget)
local Window = thisWidget.Instance :: Frame
local WindowButton = Window.WindowButton :: TextButton
local Content = WindowButton.Content :: Frame
if thisChid.type == "MenuBar" then
local ChildContainer = thisWidget.ChildContainer :: ScrollingFrame
thisChid.Instance.ZIndex = ChildContainer.ZIndex + 1
thisChid.Instance.LayoutOrder = ChildContainer.LayoutOrder - 1
return Content
end
return thisWidget.ChildContainer
end,
Discard = function(thisWidget: Types.Window)
if focusedWindow == thisWidget then
focusedWindow = nil
anyFocusedWindow = false
end
if dragWindow == thisWidget then
dragWindow = nil
isDragging = false
end
if resizeWindow == thisWidget then
resizeWindow = nil
isResizing = false
end
windowWidgets[thisWidget.ID] = nil
thisWidget.Instance:Destroy()
widgets.discardState(thisWidget)
end,
} :: Types.WidgetClass)
end
| 10,433 |
SirMallard/Iris | SirMallard-Iris-5b77f59/lib/widgets/init.lua | local Types = require(script.Parent.Types)
local widgets = {} :: Types.WidgetUtility
return function(Iris: Types.Internal)
widgets.GuiService = game:GetService("GuiService")
widgets.RunService = game:GetService("RunService")
widgets.UserInputService = game:GetService("UserInputService")
widgets.ContextActionService = game:GetService("ContextActionService")
widgets.TextService = game:GetService("TextService")
widgets.ICONS = {
BLANK_SQUARE = "rbxassetid://83265623867126",
RIGHT_POINTING_TRIANGLE = "rbxassetid://105541346271951",
DOWN_POINTING_TRIANGLE = "rbxassetid://95465797476827",
MULTIPLICATION_SIGN = "rbxassetid://133890060015237", -- best approximation for a close X which roblox supports, needs to be scaled about 2x
BOTTOM_RIGHT_CORNER = "rbxassetid://125737344915000", -- used in window resize icon in bottom right
CHECKMARK = "rbxassetid://109638815494221",
BORDER = "rbxassetid://133803690460269",
ALPHA_BACKGROUND_TEXTURE = "rbxassetid://114090016039876", -- used for color4 alpha
UNKNOWN_TEXTURE = "rbxassetid://95045813476061",
}
widgets.IS_STUDIO = widgets.RunService:IsStudio()
function widgets.getTime()
-- time() always returns 0 in the context of plugins
if widgets.IS_STUDIO then
return os.clock()
else
return time()
end
end
-- acts as an offset where the absolute position of the base frame is not zero, such as IgnoreGuiInset or for stories
widgets.GuiOffset = if Iris._config.IgnoreGuiInset then -widgets.GuiService:GetGuiInset() else Vector2.zero
-- the registered mouse position always ignores the topbar, so needs a separate variable offset
widgets.MouseOffset = if Iris._config.IgnoreGuiInset then Vector2.zero else widgets.GuiService:GetGuiInset()
-- the topbar inset changes updates a frame later.
local connection: RBXScriptConnection
connection = widgets.GuiService:GetPropertyChangedSignal("TopbarInset"):Once(function()
widgets.MouseOffset = if Iris._config.IgnoreGuiInset then Vector2.zero else widgets.GuiService:GetGuiInset()
widgets.GuiOffset = if Iris._config.IgnoreGuiInset then -widgets.GuiService:GetGuiInset() else Vector2.zero
connection:Disconnect()
end)
-- in case the topbar doesn't change, we cancel the event.
task.delay(5, function()
connection:Disconnect()
end)
function widgets.getMouseLocation()
return widgets.UserInputService:GetMouseLocation() - widgets.MouseOffset
end
function widgets.isPosInsideRect(pos: Vector2, rectMin: Vector2, rectMax: Vector2)
return pos.X >= rectMin.X and pos.X <= rectMax.X and pos.Y >= rectMin.Y and pos.Y <= rectMax.Y
end
function widgets.findBestWindowPosForPopup(refPos: Vector2, size: Vector2, outerMin: Vector2, outerMax: Vector2)
local CURSOR_OFFSET_DIST = 20
if refPos.X + size.X + CURSOR_OFFSET_DIST > outerMax.X then
if refPos.Y + size.Y + CURSOR_OFFSET_DIST > outerMax.Y then
-- placed to the top
refPos += Vector2.new(0, -(CURSOR_OFFSET_DIST + size.Y))
else
-- placed to the bottom
refPos += Vector2.new(0, CURSOR_OFFSET_DIST)
end
else
-- placed to the right
refPos += Vector2.new(CURSOR_OFFSET_DIST)
end
return Vector2.new(math.max(math.min(refPos.X + size.X, outerMax.X) - size.X, outerMin.X), math.max(math.min(refPos.Y + size.Y, outerMax.Y) - size.Y, outerMin.Y))
end
function widgets.getScreenSizeForWindow(thisWidget: Types.Widget) -- possible parents are GuiBase2d, CoreGui, PlayerGui
if thisWidget.Instance:IsA("GuiBase2d") then
return thisWidget.Instance.AbsoluteSize
else
local rootParent = thisWidget.Instance.Parent
if rootParent:IsA("GuiBase2d") then
return rootParent.AbsoluteSize
else
if rootParent.Parent:IsA("GuiBase2d") then
return rootParent.AbsoluteSize
else
return workspace.CurrentCamera.ViewportSize
end
end
end
end
function widgets.extend(superClass: Types.WidgetClass, subClass: Types.WidgetClass): Types.WidgetClass
local newClass = table.clone(superClass)
for index, value in subClass do
newClass[index] = value
end
return newClass
end
function widgets.UIPadding(Parent: GuiObject, PxPadding: Vector2)
local UIPaddingInstance = Instance.new("UIPadding")
UIPaddingInstance.PaddingLeft = UDim.new(0, PxPadding.X)
UIPaddingInstance.PaddingRight = UDim.new(0, PxPadding.X)
UIPaddingInstance.PaddingTop = UDim.new(0, PxPadding.Y)
UIPaddingInstance.PaddingBottom = UDim.new(0, PxPadding.Y)
UIPaddingInstance.Parent = Parent
return UIPaddingInstance
end
function widgets.UIListLayout(Parent: GuiObject, FillDirection: Enum.FillDirection, Padding: UDim)
local UIListLayoutInstance = Instance.new("UIListLayout")
UIListLayoutInstance.SortOrder = Enum.SortOrder.LayoutOrder
UIListLayoutInstance.Padding = Padding
UIListLayoutInstance.FillDirection = FillDirection
UIListLayoutInstance.Parent = Parent
return UIListLayoutInstance
end
function widgets.UIStroke(Parent: GuiObject, Thickness: number, Color: Color3, Transparency: number)
local UIStrokeInstance = Instance.new("UIStroke")
UIStrokeInstance.Thickness = Thickness
UIStrokeInstance.Color = Color
UIStrokeInstance.Transparency = Transparency
UIStrokeInstance.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
UIStrokeInstance.LineJoinMode = Enum.LineJoinMode.Round
UIStrokeInstance.Parent = Parent
return UIStrokeInstance
end
function widgets.UICorner(Parent: GuiObject, PxRounding: number?)
local UICornerInstance = Instance.new("UICorner")
UICornerInstance.CornerRadius = UDim.new(PxRounding and 0 or 1, PxRounding or 0)
UICornerInstance.Parent = Parent
return UICornerInstance
end
function widgets.UISizeConstraint(Parent: GuiObject, MinSize: Vector2?, MaxSize: Vector2?)
local UISizeConstraintInstance = Instance.new("UISizeConstraint")
UISizeConstraintInstance.MinSize = MinSize or UISizeConstraintInstance.MinSize -- made these optional
UISizeConstraintInstance.MaxSize = MaxSize or UISizeConstraintInstance.MaxSize
UISizeConstraintInstance.Parent = Parent
return UISizeConstraintInstance
end
-- below uses Iris
function widgets.applyTextStyle(thisInstance: TextLabel & TextButton & TextBox)
thisInstance.FontFace = Iris._config.TextFont
thisInstance.TextSize = Iris._config.TextSize
thisInstance.TextColor3 = Iris._config.TextColor
thisInstance.TextTransparency = Iris._config.TextTransparency
thisInstance.TextXAlignment = Enum.TextXAlignment.Left
thisInstance.TextYAlignment = Enum.TextYAlignment.Center
thisInstance.RichText = Iris._config.RichText
thisInstance.TextWrapped = Iris._config.TextWrapped
thisInstance.AutoLocalize = false
end
function widgets.applyInteractionHighlights(Property: string, Button: GuiButton, Highlightee: GuiObject, Colors: { [string]: any })
local exitedButton = false
widgets.applyMouseEnter(Button, function()
Highlightee[Property .. "Color3"] = Colors.HoveredColor
Highlightee[Property .. "Transparency"] = Colors.HoveredTransparency
exitedButton = false
end)
widgets.applyMouseLeave(Button, function()
Highlightee[Property .. "Color3"] = Colors.Color
Highlightee[Property .. "Transparency"] = Colors.Transparency
exitedButton = true
end)
widgets.applyInputBegan(Button, function(input: InputObject)
if not (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Gamepad1) then
return
end
Highlightee[Property .. "Color3"] = Colors.ActiveColor
Highlightee[Property .. "Transparency"] = Colors.ActiveTransparency
end)
widgets.applyInputEnded(Button, function(input: InputObject)
if not (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Gamepad1) or exitedButton then
return
end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
Highlightee[Property .. "Color3"] = Colors.HoveredColor
Highlightee[Property .. "Transparency"] = Colors.HoveredTransparency
end
if input.UserInputType == Enum.UserInputType.Gamepad1 then
Highlightee[Property .. "Color3"] = Colors.Color
Highlightee[Property .. "Transparency"] = Colors.Transparency
end
end)
Button.SelectionImageObject = Iris.SelectionImageObject
end
function widgets.applyInteractionHighlightsWithMultiHighlightee(Property: string, Button: GuiButton, Highlightees: { { GuiObject | { [string]: Color3 | number } } })
local exitedButton = false
widgets.applyMouseEnter(Button, function()
for _, Highlightee in Highlightees do
Highlightee[1][Property .. "Color3"] = Highlightee[2].HoveredColor
Highlightee[1][Property .. "Transparency"] = Highlightee[2].HoveredTransparency
exitedButton = false
end
end)
widgets.applyMouseLeave(Button, function()
for _, Highlightee in Highlightees do
Highlightee[1][Property .. "Color3"] = Highlightee[2].Color
Highlightee[1][Property .. "Transparency"] = Highlightee[2].Transparency
exitedButton = true
end
end)
widgets.applyInputBegan(Button, function(input: InputObject)
if not (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Gamepad1) then
return
end
for _, Highlightee in Highlightees do
Highlightee[1][Property .. "Color3"] = Highlightee[2].ActiveColor
Highlightee[1][Property .. "Transparency"] = Highlightee[2].ActiveTransparency
end
end)
widgets.applyInputEnded(Button, function(input: InputObject)
if not (input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Gamepad1) or exitedButton then
return
end
for _, Highlightee in Highlightees do
if input.UserInputType == Enum.UserInputType.MouseButton1 then
Highlightee[1][Property .. "Color3"] = Highlightee[2].HoveredColor
Highlightee[1][Property .. "Transparency"] = Highlightee[2].HoveredTransparency
end
if input.UserInputType == Enum.UserInputType.Gamepad1 then
Highlightee[1][Property .. "Color3"] = Highlightee[2].Color
Highlightee[1][Property .. "Transparency"] = Highlightee[2].Transparency
end
end
end)
Button.SelectionImageObject = Iris.SelectionImageObject
end
function widgets.applyFrameStyle(thisInstance: GuiObject, noPadding: boolean?, noCorner: boolean?)
-- padding, border, and rounding
-- optimized to only use what instances are needed, based on style
local FrameBorderSize = Iris._config.FrameBorderSize
local FrameRounding = Iris._config.FrameRounding
thisInstance.BorderSizePixel = 0
if FrameBorderSize > 0 then
widgets.UIStroke(thisInstance, FrameBorderSize, Iris._config.BorderColor, Iris._config.BorderTransparency)
end
if FrameRounding > 0 and not noCorner then
widgets.UICorner(thisInstance, FrameRounding)
end
if not noPadding then
widgets.UIPadding(thisInstance, Iris._config.FramePadding)
end
end
function widgets.applyButtonClick(thisInstance: GuiButton, callback: () -> ())
thisInstance.MouseButton1Click:Connect(function()
callback()
end)
end
function widgets.applyButtonDown(thisInstance: GuiButton, callback: (x: number, y: number) -> ())
thisInstance.MouseButton1Down:Connect(function(x: number, y: number)
local position = Vector2.new(x, y) - widgets.MouseOffset
callback(position.X, position.Y)
end)
end
function widgets.applyMouseEnter(thisInstance: GuiObject, callback: (x: number, y: number) -> ())
thisInstance.MouseEnter:Connect(function(x: number, y: number)
local position = Vector2.new(x, y) - widgets.MouseOffset
callback(position.X, position.Y)
end)
end
function widgets.applyMouseMoved(thisInstance: GuiObject, callback: (x: number, y: number) -> ())
thisInstance.MouseMoved:Connect(function(x: number, y: number)
local position = Vector2.new(x, y) - widgets.MouseOffset
callback(position.X, position.Y)
end)
end
function widgets.applyMouseLeave(thisInstance: GuiObject, callback: (x: number, y: number) -> ())
thisInstance.MouseLeave:Connect(function(x: number, y: number)
local position = Vector2.new(x, y) - widgets.MouseOffset
callback(position.X, position.Y)
end)
end
function widgets.applyInputBegan(thisInstance: GuiButton, callback: (input: InputObject) -> ())
thisInstance.InputBegan:Connect(function(...)
callback(...)
end)
end
function widgets.applyInputEnded(thisInstance: GuiButton, callback: (input: InputObject) -> ())
thisInstance.InputEnded:Connect(function(...)
callback(...)
end)
end
function widgets.discardState(thisWidget: Types.StateWidget)
for _, state in thisWidget.state do
state.ConnectedWidgets[thisWidget.ID] = nil
end
end
function widgets.registerEvent(event: string, callback: (...any) -> ())
table.insert(Iris._initFunctions, function()
table.insert(Iris._connections, widgets.UserInputService[event]:Connect(callback))
end)
end
widgets.EVENTS = {
hover = function(pathToHovered: (thisWidget: Types.Widget) -> GuiObject)
return {
["Init"] = function(thisWidget: Types.Widget & Types.Hovered)
local hoveredGuiObject = pathToHovered(thisWidget)
widgets.applyMouseEnter(hoveredGuiObject, function()
thisWidget.isHoveredEvent = true
end)
widgets.applyMouseLeave(hoveredGuiObject, function()
thisWidget.isHoveredEvent = false
end)
thisWidget.isHoveredEvent = false
end,
["Get"] = function(thisWidget: Types.Widget & Types.Hovered)
return thisWidget.isHoveredEvent
end,
}
end,
click = function(pathToClicked: (thisWidget: Types.Widget) -> GuiButton)
return {
["Init"] = function(thisWidget: Types.Widget & Types.Clicked)
local clickedGuiObject = pathToClicked(thisWidget)
thisWidget.lastClickedTick = -1
widgets.applyButtonClick(clickedGuiObject, function()
thisWidget.lastClickedTick = Iris._cycleTick + 1
end)
end,
["Get"] = function(thisWidget: Types.Widget & Types.Clicked)
return thisWidget.lastClickedTick == Iris._cycleTick
end,
}
end,
rightClick = function(pathToClicked: (thisWidget: Types.Widget) -> GuiButton)
return {
["Init"] = function(thisWidget: Types.Widget & Types.RightClicked)
local clickedGuiObject = pathToClicked(thisWidget)
thisWidget.lastRightClickedTick = -1
clickedGuiObject.MouseButton2Click:Connect(function()
thisWidget.lastRightClickedTick = Iris._cycleTick + 1
end)
end,
["Get"] = function(thisWidget: Types.Widget & Types.RightClicked)
return thisWidget.lastRightClickedTick == Iris._cycleTick
end,
}
end,
doubleClick = function(pathToClicked: (thisWidget: Types.Widget) -> GuiButton)
return {
["Init"] = function(thisWidget: Types.Widget & Types.DoubleClicked)
local clickedGuiObject = pathToClicked(thisWidget)
thisWidget.lastClickedTime = -1
thisWidget.lastClickedPosition = Vector2.zero
thisWidget.lastDoubleClickedTick = -1
widgets.applyButtonDown(clickedGuiObject, function(x: number, y: number)
local currentTime = widgets.getTime()
local isTimeValid = currentTime - thisWidget.lastClickedTime < Iris._config.MouseDoubleClickTime
if isTimeValid and (Vector2.new(x, y) - thisWidget.lastClickedPosition).Magnitude < Iris._config.MouseDoubleClickMaxDist then
thisWidget.lastDoubleClickedTick = Iris._cycleTick + 1
else
thisWidget.lastClickedTime = currentTime
thisWidget.lastClickedPosition = Vector2.new(x, y)
end
end)
end,
["Get"] = function(thisWidget: Types.Widget & Types.DoubleClicked)
return thisWidget.lastDoubleClickedTick == Iris._cycleTick
end,
}
end,
ctrlClick = function(pathToClicked: (thisWidget: Types.Widget) -> GuiButton)
return {
["Init"] = function(thisWidget: Types.Widget & Types.CtrlClicked)
local clickedGuiObject = pathToClicked(thisWidget)
thisWidget.lastCtrlClickedTick = -1
widgets.applyButtonClick(clickedGuiObject, function()
if widgets.UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or widgets.UserInputService:IsKeyDown(Enum.KeyCode.RightControl) then
thisWidget.lastCtrlClickedTick = Iris._cycleTick + 1
end
end)
end,
["Get"] = function(thisWidget: Types.Widget & Types.CtrlClicked)
return thisWidget.lastCtrlClickedTick == Iris._cycleTick
end,
}
end,
}
Iris._utility = widgets
require(script.Root)(Iris, widgets)
require(script.Window)(Iris, widgets)
require(script.Menu)(Iris, widgets)
require(script.Format)(Iris, widgets)
require(script.Text)(Iris, widgets)
require(script.Button)(Iris, widgets)
require(script.Checkbox)(Iris, widgets)
require(script.RadioButton)(Iris, widgets)
require(script.Image)(Iris, widgets)
require(script.Tree)(Iris, widgets)
require(script.Tab)(Iris, widgets)
require(script.Input)(Iris, widgets)
require(script.Combo)(Iris, widgets)
require(script.Plot)(Iris, widgets)
require(script.Table)(Iris, widgets)
end
| 4,284 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.