All my dotfiles
1local comlink = require("comlink")
2
3---The Watcher module sends a notification for every message in a "watched" channel
4---@class Watcher
5---
6---@field channels string[] List of channels that are being watched
7local M = {
8 channels = {},
9}
10
11---Adds a channel to the list of watchers
12---@param channel string The channel to add
13function M.add(channel)
14 if channel == nil or channel == "" then
15 local maybe_channel = comlink.selected_channel()
16 if maybe_channel then
17 channel = maybe_channel:name()
18 end
19 end
20 table.insert(M.channels, channel)
21 comlink.notify("comlink", "watching " .. channel)
22end
23
24---Removes a channel from the list of watchers
25---@param channel string The channel to remove
26function M.remove(channel)
27 if channel == "" then
28 local maybe_channel = comlink.selected_channel()
29 if maybe_channel then
30 channel = maybe_channel:name()
31 end
32 end
33 for i, chan in ipairs(M.channels) do
34 if chan == channel then
35 table.remove(M.channels, i)
36 comlink.notify("comlink", "removed watcher for " .. channel)
37 return
38 end
39 end
40end
41
42---Callback when a message is received
43---@param channel string The channel the message was sent in
44---@param sender string The sender of the message
45---@param msg string The sender of the message
46function M.on_message(channel, sender, msg)
47 for _, watched in ipairs(M.channels) do
48 if watched == channel then
49 if channel:sub(1, 2) == "#" then
50 comlink.notify(sender .. " in " .. channel, msg)
51 return
52 end
53 comlink.notify(sender, msg)
54 return
55 end
56 end
57end
58
59comlink.add_command("watch", M.add)
60comlink.add_command("unwatch", M.remove)
61
62return M