local astal = require("astal") local Variable = require("astal").Variable local Astal = require("astal.gtk3").Astal local GLib = astal.require("GLib") local lib lib = { --- get path to file in astal source src = function(path) local str = debug.getinfo(2, "S").source:sub(2) local src = str:match("(.*/)") or str:match("(.*\\)") or "./" return src .. path end, --- map an array with a function map = function(array, func) local new_arr = {} for i, v in ipairs(array) do new_arr[i] = func(v, i) end return new_arr end, --- filter an array with a function filter = function(array, func) local new_arr = {} for i, v in ipairs(array) do if func(v, i) then new_arr[i] = v end end return new_arr end, --- sort an array of object on a key sort = function(array, func) -- default func to sort on attr 'id' if not func then func = 'id' end -- make function if just provided with attribute if type(func) ~= 'function' then local key = func func = function(a, b) return a[key] < b[key] end end -- copy to new array local new_arr = {} for i, v in ipairs(array) do new_arr[i] = v end -- sort and return table.sort(new_arr, func) return new_arr end, --- returns if value is an array is_array = function(val) return type(val) == 'table' end, --- returns if value is an string is_string = function(val) return type(val) == 'string' end, --- returns if value is nil is_nil = function(val) return val == nil end, --- returns length of table or string count = function(val) if lib.is_array(val) then return #val elseif lib.is_string(val) then return val:len() elseif lib.is_nil(val) then return 0 else return nil end end, --- returns if a table is empty empty = function(array) return lib.count(array) == 0 end, --- negates value neg = function(val) return not val end, --- better truthy function is_true = function(val) -- zero is false if val == 0 then return false end -- empty array or string is false if lib.empty(val) then return false end -- default truthyness return val and true or false end, --- better fasly function is_false = function(val) return not lib.is_true(val) end, --- checks if a file exists file_exists = function(path) return GLib.file_test(path, "EXISTS") end, --- checks if a string is an icon is_icon = function(icon) return Astal.Icon.lookup_icon(icon) ~= nil end, --- applies one object onto another apply = function(l, r) for k,v in pairs(r) do l[k] = v end return l end, --- returns current unix epoch unix = function() return os.time(os.date("!*t")) end, --- formats a time time = function(t) -- default args t = lib.apply({ time = lib.unix(), format = "%H:%M" }, t or {}) return GLib.DateTime.new_from_unix_local(t.time):format(t.format) end, } return lib