summaryrefslogtreecommitdiff
path: root/examples/gtk3/lua/notifications/lib.lua
blob: 289fc7e9e3b357d8908de142b7c211cc919e282c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
local astal = require("astal")
local Variable = require("astal").Variable
local Gtk = require("astal.gtk3").Gtk
local GLib = astal.require("GLib")

local M = {}

function M.src(path)
	local str = debug.getinfo(2, "S").source:sub(2)
	local src = str:match("(.*/)") or str:match("(.*\\)") or "./"
	return src .. path
end

---@generic T, R
---@param array T[]
---@param func fun(T, i: integer): R
---@return R[]
function M.map(array, func)
	local new_arr = {}
	for i, v in ipairs(array) do
		new_arr[i] = func(v, i)
	end
	return new_arr
end

---@param path string
---@return boolean
function M.file_exists(path) return GLib.file_test(path, "EXISTS") end

function M.varmap(initial)
	local map = initial
	local var = Variable()

	local function notify()
		local arr = {}
		for _, value in pairs(map) do
			table.insert(arr, value)
		end
		var:set(arr)
	end

	local function delete(key)
		if Gtk.Widget:is_type_of(map[key]) then map[key]:destroy() end

		map[key] = nil
	end

	notify()

	return setmetatable({
		set = function(key, value)
			delete(key)
			map[key] = value
			notify()
		end,
		delete = function(key)
			delete(key)
			notify()
		end,
		get = function() return var:get() end,
		subscribe = function(callback) return var:subscribe(callback) end,
	}, {
		__call = function() return var() end,
	})
end

---@param time number
---@param format? string
function M.time(time, format)
	format = format or "%H:%M"
	return GLib.DateTime.new_from_unix_local(time):format(format)
end

return M