Trans.nvim/lua/Trans/core/translate.lua

105 lines
2.6 KiB
Lua
Raw Normal View History

local Trans = require('Trans')
local util = Trans.util
2023-03-09 19:42:41 +08:00
2023-03-12 21:33:00 +08:00
local function init_opts(opts)
2023-03-09 19:42:41 +08:00
opts = opts or {}
opts.mode = opts.mode or vim.fn.mode()
2023-03-12 21:33:00 +08:00
opts.str = util.get_str(opts.mode)
return opts
end
---To Do Online Query
---@param data TransData @data
---@param backend TransOnlineBackend @backend
local function do_query(data, backend)
-- TODO : template method for online query
local name = backend.name
local uri = backend.uri
local method = backend.method
local formatter = backend.formatter
local query = backend.get_query(data)
local header = type(backend.header) == "function" and backend.header(data) or backend.header
local function handle(output)
local status, body = pcall(vim.json.decode, output.body)
if not status or not body then
if not Trans.conf.debug then
backend.debug(body)
data.trace[name] = output
end
data.result[name] = false
return
end
-- vim.print(data.result[name])
data.result[name] = formatter(body, data)
end
Trans.curl[method](uri, {
query = query,
callback = handle,
header = header,
})
-- Hook ?
end
2023-03-18 21:56:12 +08:00
---@type table<string, fun(data: TransData):boolean>
2023-03-15 20:57:28 +08:00
local strategy = {
fallback = function(data)
2023-03-15 20:57:28 +08:00
local result = data.result
Trans.backend.offline.query(data)
2023-03-18 21:56:12 +08:00
if result.offline then return true end
local update = data.frontend:wait()
2023-03-15 20:57:28 +08:00
for _, backend in ipairs(data.backends) do
do_query(data, backend)
2023-03-18 21:56:12 +08:00
local name = backend.name
2023-03-15 20:57:28 +08:00
---@cast backend TransBackend
2023-03-18 21:56:12 +08:00
while result[name] == nil do
if not update() then break end
2023-03-15 20:57:28 +08:00
end
2023-03-18 21:56:12 +08:00
if result[name] then return true end
end
2023-03-18 21:56:12 +08:00
return false
2023-03-16 00:03:13 +08:00
end,
--- TODO :More Strategys
2023-03-15 20:57:28 +08:00
}
2023-03-11 11:32:13 +08:00
2023-03-12 21:33:00 +08:00
2023-03-11 11:32:13 +08:00
-- HACK : Core process logic
local function process(opts)
2023-03-12 21:33:00 +08:00
opts = init_opts(opts)
local str = opts.str
if not str or str == '' then return end
2023-03-12 21:33:00 +08:00
-- Find in cache
if Trans.cache[str] then
local data = Trans.cache[str]
data.frontend:process(data)
return
2023-03-12 21:33:00 +08:00
end
2023-03-13 19:50:28 +08:00
local data = Trans.data.new(opts)
if strategy[data.frontend.opts.query](data) then
Trans.cache[data.str] = data
data.frontend:process(data)
else
data.frontend:fallback()
end
2023-03-09 19:42:41 +08:00
end
2023-03-14 18:17:07 +08:00
---@class Trans
2023-03-15 11:34:50 +08:00
---@field translate fun(opts: { frontend: string?, mode: string?}?) Translate string core function
2023-03-14 18:17:07 +08:00
return function(opts)
coroutine.wrap(process)(opts)
end