102 lines
2.5 KiB
Lua
Raw Normal View History

2023-03-24 00:56:36 +08:00
local util = require 'Trans'.util
---@class TransNode
---@field [1] string text to be rendered
---@field render fun(self: TransNode, buffer: TransBuffer, line: number, col: number) render the node
2023-04-24 20:58:46 +08:00
local item = (function()
---@class TransItem : TransNode
local mt = {
---@param self TransItem
---@param buffer TransBuffer
---@param line integer
---@param col integer
render = function(self, buffer, line, col)
if self[2] then
buffer:add_highlight(line, self[2], col, col + #self[1])
end
end,
}
mt.__index = mt
---Basic item node
---@param tuple {[1]: string, [2]: string?}
---@return TransItem
return function(tuple)
return setmetatable(tuple, mt)
end
end)()
local text = (function()
---@class TransText : TransNode
---@field step string
---@field nodes TransNode[]
local mt = {
---@param self TransText
---@param buffer TransBuffer
---@param line integer
---@param col integer
render = function(self, buffer, line, col)
local nodes = self.nodes
local step = self.step
local len = step and #step or 0
for _, node in ipairs(nodes) do
node:render(buffer, line, col)
col = col + #node[1] + len
end
end,
}
mt.__index = mt
---@param nodes {[number]: TransNode, step: string?}
---@return TransText
return function(nodes)
return setmetatable({
[1] = table.concat(util.list_fields(nodes, 1), nodes.step),
step = nodes.step,
nodes = nodes,
}, mt)
end
end)()
---@param args {[number]: TransNode, width: integer, spin: string?}
---@return TransText
local function format(args)
local width = args.width
2023-03-24 00:56:36 +08:00
local spin = args.spin or ' '
local size = #args
local wid = 0
for i = 1, size do
wid = wid + args[i][1]:width()
end
local space = math.max(math.floor((width - wid) / (size - 1)), 0)
args.step = spin:rep(space)
args.width = nil
args.spin = nil
---@diagnostic disable-next-line: param-type-mismatch
return text(args)
end
---@class TransUtil
---@field node TransNodes
---@class TransNodes
return {
item = item,
text = text,
format = format,
2023-03-26 20:07:04 +08:00
prompt = function(str)
return {
2023-03-24 00:56:36 +08:00
item { '', 'TransTitleRound' },
item { str, 'TransTitle' },
item { '', 'TransTitleRound' },
}
2023-03-18 13:53:09 +08:00
end,
2023-01-26 20:28:19 +08:00
}