robin/maivi

a tiny cute lua web framework

git clone https://git.robinwobin.dev/robin/maivi

robinrouter: `read_data` hook and ctx pattern matchae085a5

main
6.0 KiB247 linesraw
1-- selene: allow(unscoped_variables, global_usage)
2_G.maivi = _G.maivi or {} --[[@as table]]
3
4maivi.data = {}
5
6-- util =======================================================================
7
8-- https://github.com/neovim/neovim/blob/04f802a2f6387028e3389334e6e04abc28d92587/runtime/lua/vim/F.lua#L58-L66
9
10--- like {...} except preserve the length explicitly
11function maivi.pack_len(...)
12  return { n = select("#", ...), ... }
13end
14
15--- like unpack() but use the length set by F.pack_len if present
16function maivi.unpack_len(t)
17  return unpack(t, 1, t.n)
18end
19
20function maivi.print(...)
21  local t = maivi.pack_len(...)
22  for i = 1, t.n do
23    print(maivi.inspect(t[i]))
24  end
25end
26
27---@generic T
28---@param t table<string, T>
29---@param f fun(k: string): T
30---@param mt metatable
31function maivi.defaulttable(t, f, mt)
32  local mt_ = {
33    __index = function(self, k)
34      local v = f(k)
35      rawset(self, k, v)
36      return rawget(self, k)
37    end,
38  }
39  if mt then
40    for k, v in pairs(mt) do
41      mt_[k] = v
42    end
43  end
44  return setmetatable(t, mt_)
45end
46
47-- elem =======================================================================
48
49---@alias Displayable string | number | boolean | fun(): Displayable
50---@alias Props table<string, Displayable>
51---@alias Child Displayable | VNode
52---@alias Children Child[]
53---@alias PropsOrChildren { [string]: Displayable, [integer]: Child }|Child
54
55---@alias VNode { type: ElementType?, props: Props, children: Children }
56---@alias ElementType string | Component
57---@alias Element fun(args: PropsOrChildren): VNode
58---@alias Component fun(props: Props, children: Children): VNode
59
60---@class ElementConfig
61---@field close? boolean
62---@field empty? boolean
63
64---@class ParsedArgs
65---@field props Props
66---@field children Children
67---@field boolean_props string[]
68
69---@param etype ElementType?
70---@param props Props
71---@param children Children
72---@return VNode
73function maivi.h(etype, props, children)
74  if type(etype) == "function" then
75    return etype(props, children)
76  end
77  return { type = etype, props = props, children = children }
78end
79
80---@param etype? ElementType
81---@param config? ElementConfig
82---@return Element
83function maivi.elem(etype, config)
84  return function(args)
85    local parsed = maivi.parse(args)
86    return setmetatable(maivi.h(etype, parsed.props, parsed.children), {
87      config = config,
88    })
89  end
90end
91
92-- components =================================================================
93
94--- minimized version of `maivi.elem` since components dont use `.config`
95--- @param f Component
96--- @return Element
97function maivi.component(f)
98  return function(args)
99    local parsed = maivi.parse(args)
100    return maivi.h(f, parsed.props, parsed.children)
101  end
102end
103
104---@alias Slots table<string, VNode>
105---@param f fun(slots: Slots): Element
106---@return fun(page: Component): VNode
107function maivi.layout(f)
108  return function(page)
109    return function(args)
110      local parsed = maivi.parse(args)
111      local slots = page(parsed.props, parsed.children)
112      return f(slots)(parsed.props, parsed.children)
113    end
114  end
115end
116
117-- props & children ============================================================
118
119---@param args PropsOrChildren?
120---@return ParsedArgs
121function maivi.parse(args)
122  ---@type Props
123  local props = {}
124  ---@type Children
125  local children = {}
126  ---@type string[]
127  local boolean_props = {}
128
129  if type(args) == "table" and getmetatable(args) == nil then
130    for k, v in pairs(args) do
131      if type(k) == "number" then
132        table.insert(children, v)
133      elseif k == "_" and type(v) == "table" then
134        for _, prop in ipairs(v) do
135          table.insert(boolean_props, prop)
136        end
137      elseif k == "data" and type(v) == "table" then
138        for kdata, prop in pairs(v) do
139          props["data-" .. kdata] = maivi.display.attr(prop)
140        end
141      else
142        props[k] = maivi.display.attr(v)
143      end
144    end
145  elseif args ~= nil then
146    table.insert(children, args)
147  end
148
149  return {
150    props = props,
151    children = children,
152    boolean_props = boolean_props,
153  }
154end
155
156-- modules ====================================================================
157
158maivi.mod = setmetatable({
159  graph = {},
160}, {
161  ---@param t table
162  ---@param modname string
163  __call = function(t, modname)
164    local info = debug.getinfo(2, "Sln")
165    local source = info.source
166    t.graph[source] = t.graph[source] or {}
167    table.insert(t.graph[source], modname)
168
169    return function(...)
170      if this.dev then
171        package.loaded[modname] = nil
172      end
173
174      local ok, result = pcall(require, modname)
175      if not ok then
176        error(
177          ([[%s:%s error while loading module '%s':\t\n%s]]):format(
178            info.short_src,
179            info.currentline,
180            modname,
181            result
182          )
183        )
184      end
185      if type(result) ~= "function" then
186        error(
187          ([[%s:%s return value from module '%s' is not a function]]):format(
188            info.short_src,
189            info.currentline,
190            modname
191          )
192        )
193      end
194      return result(...)
195    end
196  end,
197})
198
199-- hooks =======================================================================
200
201---@alias ctx table<string, any?>
202---@alias props table<string, any?>
203---@alias hook fun(ctx: ctx)
204
205maivi._hooks = {}
206
207---@param event string
208---@param props props
209---@param fn hook
210function maivi.hook(event, props, fn)
211  maivi._hooks[event] = maivi._hooks[event] or {}
212  table.insert(maivi._hooks[event], { props = props, fn = fn })
213end
214
215---@param ref props
216---@param props props
217---@return boolean
218local function matchhook(ref, props)
219  for k, v in pairs(props) do
220    if k == "pattern" and ref.pattern then
221      return string.match(ref.pattern, v) ~= nil
222    elseif ref[k] ~= v then
223      return false
224    end
225  end
226
227  return true
228end
229
230---@param ctx ctx
231---@param event string
232---@param props props
233function maivi.trigger(ctx, event, props)
234  local hooks = maivi._hooks[event]
235  if not hooks then
236    return
237  end
238
239  for _, hook in ipairs(hooks) do
240    -- fallen can be nil
241    if ctx.fallen ~= true and matchhook(props, hook.props) then
242      hook.fn(ctx)
243    end
244  end
245end
246
247return maivi