refactor: rewrite setup and conf module

This commit is contained in:
JuanZoran
2023-07-24 22:28:09 +08:00
parent 073e8667b2
commit eb68b8bb95
13 changed files with 267 additions and 316 deletions

View File

@ -0,0 +1,8 @@
local Trans = require'Trans'
---@class Trans
local M = {}
return M

View File

@ -10,9 +10,11 @@ local Trans = require 'Trans'
---@class TransBackendOnline: TransBackend
---@field uri string @request uri
---@field method 'get' | 'post' @request method
---@field formatter fun(body: table, data: TransData): TransResult|false|nil @formatter
---@field formatter fun(body: table, data: TransData): TransResult|false|nil transform response body to TransResult
---@field get_query fun(data: TransData): table<string, any> @get query table
---@field error_message? fun(errorCode) @get error message
-- -@field header table<string, string>|fun(data: TransData): table<string, string> @request header
---@class TransBackendOffline: TransBackend
@ -22,56 +24,41 @@ local Trans = require 'Trans'
---@class TransBackendCore
local M = {
---@type table<string, TransBackend>
---@type table<string, TransBackend> backendname -> backend source
sources = {},
}
local m_util = {}
-- INFO :Template method for online query
-- ---@param data TransData @data
-- ---@param backend TransOnlineBackend @backend
-- function M.do_query(data, backend)
-- 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
-- data.result[name] = formatter(body, data)
-- end
-- Trans.curl[method](uri, {
-- query = query,
-- callback = handle,
-- header = header,
-- })
-- -- Hook ?
-- end
---@param data TransData @data
---@param backend TransBackendOnline @backend
function M.do_query(data, backend)
local name = backend.name
local formatter = backend.formatter
-- 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
data.result[name] = false
return
end
data.result[name] = formatter(body, data)
end
Trans.curl[backend.method](backend.uri, {
query = backend.get_query(data),
callback = handle,
--- FIXME :
header = header,
})
end
-- TODO :Implement all of utility functions
M.util = m_util
M.random_num = math.random(bit.lshift(1, 15))
-- INFO :Parse configuration file
local path = Trans.conf.dir .. '/Trans.json'
@ -82,6 +69,7 @@ if file then
user_conf = vim.json.decode(content) or user_conf
file:close()
end
-- WARNING : [Breaking change] 'Trans.json' should use json object instead of array
---@class Trans

View File

@ -1,168 +0,0 @@
---@class Trans
---@field conf TransConf
---@alias TransMode 'visual' 'input'
---@class TransConf
return {
---@type string the directory for database file and password file
dir = require 'Trans'.plugin_dir,
---@type 'default' | 'dracula' | 'tokyonight' global Trans theme [@see lua/Trans/style/theme.lua]
theme = 'default', -- default | tokyonight | dracula
---@type table<TransMode, { frontend:string, backend:string | string[] }> fallback strategy for mode
strategy = {
default = {
frontend = 'hover',
backend = {
'offline',
-- 'youdao',
-- 'baidu',
}
},
-- input = {
-- visual = {
-- ...
},
---@type table frontend options
frontend = {
---@class TransFrontendOpts
---@field keymaps table<string, string>
default = {
auto_play = true,
query = 'fallback',
border = 'rounded',
title = vim.fn.has 'nvim-0.9' == 1 and {
{ '', 'TransTitleRound' },
{ ' Trans', 'TransTitle' },
{ '', 'TransTitleRound' },
} or nil, -- need nvim-0.9+
---@type {open: string | boolean, close: string | boolean, interval: integer} Hover Window Animation
animation = {
open = 'slid', -- 'fold', 'slid'
close = 'slid',
interval = 12,
},
timeout = 2000,
},
---@class TransHoverOpts : TransFrontendOpts
hover = {
---@type integer Max Width of Hover Window
width = 37,
---@type integer Max Height of Hover Window
height = 27,
---@type string -- see: /lua/Trans/style/spinner
spinner = 'dots',
---@type string
fallback_message = '{{notfound}} {{error_message}}',
auto_resize = true,
split_width = 60,
padding = 10, -- padding for hover window width
keymaps = {
-- pageup = '<C-u>',
-- pagedown = '<C-d>',
-- pin = '<leader>[',
-- close = '<leader>]',
-- toggle_entry = '<leader>;',
},
---@type string[] auto close events
auto_close_events = {
'InsertEnter',
'CursorMoved',
'BufLeave',
},
---@type table<string, string[]> order to display translate result
order = {
default = {
'str',
'translation',
'definition',
},
offline = {
'title',
'tag',
'pos',
'exchange',
'translation',
'definition',
},
youdao = {
'title',
'translation',
'definition',
'web',
},
},
icon = {
-- or use emoji
list = '', -- ● | ○ | ◉ | ◯ | ◇ | ◆ | ▪ | ▫ | ⬤ | 🟢 | 🟡 | 🟣 | 🟤 | 🟠| 🟦 | 🟨 | 🟧 | 🟥 | 🟪 | 🟫 | 🟩 | 🟦
star = '', -- ⭐ | ✴ | ✳ | ✲ | ✱ | ✰ | ★ | ☆ | 🌟 | 🌠 | 🌙 | 🌛 | 🌜 | 🌟 | 🌠 | 🌌 | 🌙 |
notfound = '', --❔ | ❓ | ❗ | ❕|
yes = '', -- ✅ | ✔️ | ☑
no = '', -- ❌ | ❎ | ✖ | ✘ | ✗ |
cell = '', -- ■ | □ | ▇ | ▏ ▎ ▍ ▌ ▋ ▊ ▉
web = '󰖟', --🌍 | 🌎 | 🌏 | 🌐 |
tag = '',
pos = '',
exchange = '',
definition = '󰗊',
translation = '󰊿',
},
},
},
-- debug = true,
}
-- TODO :
-- float = {
-- width = 0.8,
-- height = 0.8,
-- border = 'rounded',
-- keymap = {
-- quit = 'q',
-- },
-- animation = {
-- open = 'fold',
-- close = 'fold',
-- interval = 10,
-- },
-- tag = {
-- wait = '#519aba',
-- fail = '#e46876',
-- success = '#10b981',
-- },
-- },
-- local title = {
-- "████████╗██████╗ █████╗ ███╗ ██╗███████╗",
-- "╚══██╔══╝██╔══██╗██╔══██╗████╗ ██║██╔════╝",
-- " ██║ ██████╔╝███████║██╔██╗ ██║███████╗",
-- " ██║ ██╔══██╗██╔══██║██║╚██╗██║╚════██║",
-- " ██║ ██║ ██║██║ ██║██║ ╚████║███████║",
-- " ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚══════╝",
--}

View File

@ -1,10 +1,33 @@
local Trans = require 'Trans'
local frontend_opts = Trans.conf.frontend
local Trans = require 'Trans'
---@class TransFrontendOpts
local default_frontend = {
auto_play = true,
query = 'fallback',
border = 'rounded',
title = vim.fn.has 'nvim-0.9' == 1 and {
{ '', 'TransTitleRound' },
{ ' Trans', 'TransTitle' },
{ '', 'TransTitleRound' },
} or nil, -- need nvim-0.9+
---@type {open: string | boolean, close: string | boolean, interval: integer} Window Animation
animation = {
open = 'slid', -- 'fold', 'slid'
close = 'slid',
interval = 12,
},
timeout = 2000, -- only for online backend query
}
if Trans.conf.frontend.default then
default_frontend = vim.tbl_extend('force', default_frontend, Trans.conf.frontend.default)
end
---@class TransFrontend
---@field opts TransFrontendOpts
---@field opts? TransFrontendOpts options which user can set
---@field get_active_instance fun():TransFrontend?
---@field process fun(self: TransFrontend, data: TransData)
---@field process fun(self: TransFrontend, data: TransData) @render backend result
---@field wait fun(self: TransFrontend): fun(backend: TransBackend): boolean Update wait status
---@field execute fun(action: string) @Execute action for frontend instance
---@field fallback fun() @Fallback method when no result
@ -14,17 +37,17 @@ local frontend_opts = Trans.conf.frontend
---@field frontend TransFrontend
return setmetatable({}, {
__index = function(self, name)
local opts = vim.tbl_extend('keep', frontend_opts[name] or {}, frontend_opts.default)
---@type TransFrontend
local frontend = require('Trans.frontend.' .. name)
frontend.opts = opts
self[name] = frontend
frontend.opts =
vim.tbl_extend('force', frontend.opts or {}, default_frontend, Trans.conf.frontend[name])
if frontend.setup then
frontend.setup()
end
rawset(self, name, frontend)
return frontend
end,
})

19
lua/Trans/core/helper.lua Normal file
View File

@ -0,0 +1,19 @@
local fn, api = vim.fn, vim.api
local Trans = require 'Trans'
---@class TransHelper for Trans module dev
local M = {}
---Get abs_path of file
---@param path string[]
---@param is_dir boolean? [default]: false
---@return string @Generated path
function M.relative_path(path, is_dir)
return Trans.plugin_dir .. table.concat(path, Trans.separator) .. (is_dir and Trans.separator or '')
end
return M

View File

@ -1,6 +0,0 @@
local M = {}
-- TODO :
return M

View File

@ -1,44 +1,31 @@
---@class Trans
local Trans = require 'Trans'
-- local function set_strategy_opts(conf)
-- local all_backends = conf.frontend.default.enabled_backend
-- local g_strategy = conf.strategy
---@alias TransMode 'visual' 'input'
local default_strategy = {
frontend = 'hover',
backend = {
'offline',
-- 'youdao',
-- 'baidu',
},
}
-- local function parse_backend(backend)
-- if type(backend) == 'string' then
-- return backend == '*' and all_backends or { backend }
-- end
Trans.conf = {
---@type string the directory for database file and password file
dir = require 'Trans'.plugin_dir,
---@type 'default' | 'dracula' | 'tokyonight' global Trans theme [@see lua/Trans/style/theme.lua]
theme = 'default',
---@type table<TransMode, { frontend:string, backend:string | string[] }> fallback strategy for mode
-- input = {
-- visual = {
-- ...
strategy = vim.defaulttable(function()
return setmetatable({}, default_strategy)
end),
frontend = {},
}
-- return backend
-- end
-- local default_strategy = g_strategy.default
-- default_strategy.backend = parse_backend(default_strategy.backend)
-- default_strategy.__index = default_strategy
-- g_strategy.default = nil
-- setmetatable(g_strategy, {
-- __index = function()
-- return default_strategy
-- end,
-- })
-- for _, strategy in pairs(g_strategy) do
-- strategy.backend = parse_backend(strategy.backend)
-- setmetatable(strategy, default_strategy)
-- end
-- end
local function define_highlights(conf)
local set_hl = vim.api.nvim_set_hl
local highlights = Trans.style.theme[conf.theme]
for hl, opt in pairs(highlights) do
set_hl(0, hl, opt)
end
end
---@class Trans
@ -48,8 +35,12 @@ return function(opts)
Trans.conf = vim.tbl_deep_extend('force', Trans.conf, opts)
end
local conf = Trans.conf
conf.dir = vim.fn.expand(conf.dir)
conf.dir = vim.fn.expand(conf.dir)
-- set_strategy_opts(conf)
define_highlights(conf)
-- INFO : set highlight
local set_hl = vim.api.nvim_set_hl
local highlights = Trans.style.theme[conf.theme]
for hl, opt in pairs(highlights) do
set_hl(0, hl, opt)
end
end

View File

@ -3,7 +3,6 @@ local fn, api = vim.fn, vim.api
---@class TransUtil
local M = require 'Trans'.metatable 'util'
---Get selected text
---@return string
function M.get_select()