|
| 1 | +local log = require("leetcode.logger") |
| 2 | +local config = require("leetcode.config") |
| 3 | + |
| 4 | +---@return "fzf" | "telescope" |
| 5 | +local function resolve_provider() |
| 6 | + ---@type string |
| 7 | + local provider = config.user.picker.provider |
| 8 | + |
| 9 | + if provider == nil then |
| 10 | + local fzf_ok = pcall(require, "fzf-lua") |
| 11 | + if fzf_ok then |
| 12 | + return "fzf" |
| 13 | + end |
| 14 | + local telescope_ok = pcall(require, "telescope") |
| 15 | + if telescope_ok then |
| 16 | + return "telescope" |
| 17 | + end |
| 18 | + error("no supported picker provider found") |
| 19 | + else |
| 20 | + local provider_ok = pcall(require, provider) |
| 21 | + assert(provider_ok, ("specified picker provider not found: `%s`"):format(provider)) |
| 22 | + return provider == "fzf-lua" and "fzf" or provider |
| 23 | + end |
| 24 | +end |
| 25 | + |
| 26 | +---@class leet.Picker |
| 27 | +local P = {} |
| 28 | +P.provider = resolve_provider() |
| 29 | + |
| 30 | +function P.hl_to_ansi(hl_group) |
| 31 | + local color = vim.api.nvim_get_hl(0, { name = hl_group }) |
| 32 | + if color and color.fg then |
| 33 | + return string.format( |
| 34 | + "\x1b[38;2;%d;%d;%dm", |
| 35 | + bit.rshift(color.fg, 16), |
| 36 | + bit.band(bit.rshift(color.fg, 8), 0xFF), |
| 37 | + bit.band(color.fg, 0xFF) |
| 38 | + ) |
| 39 | + end |
| 40 | + return "" |
| 41 | +end |
| 42 | + |
| 43 | +function P.apply_hl(text, hl_group) |
| 44 | + if not hl_group then |
| 45 | + return text |
| 46 | + end |
| 47 | + return P.hl_to_ansi(hl_group) .. text .. "\x1b[0m" |
| 48 | +end |
| 49 | + |
| 50 | +function P.normalize(items) |
| 51 | + return vim.tbl_map(function(item) |
| 52 | + return table.concat( |
| 53 | + vim.tbl_map(function(col) |
| 54 | + if type(col) == "table" then |
| 55 | + return P.apply_hl(col[1], col[2]) |
| 56 | + else |
| 57 | + return col |
| 58 | + end |
| 59 | + end, item.entry), |
| 60 | + " " |
| 61 | + ) |
| 62 | + end, items) |
| 63 | +end |
| 64 | + |
| 65 | +function P.pick(path, ...) |
| 66 | + local rpath = table.concat({ "leetcode.picker", path, P.provider }, ".") |
| 67 | + return require(rpath)(...) |
| 68 | +end |
| 69 | + |
| 70 | +function P.language(...) |
| 71 | + P.pick("language", ...) |
| 72 | +end |
| 73 | + |
| 74 | +function P.question(...) |
| 75 | + P.pick("question", ...) |
| 76 | +end |
| 77 | + |
| 78 | +function P.tabs() |
| 79 | + local utils = require("leetcode.utils") |
| 80 | + local tabs = utils.question_tabs() |
| 81 | + |
| 82 | + if vim.tbl_isempty(tabs) then |
| 83 | + return log.warn("No questions opened") |
| 84 | + end |
| 85 | + |
| 86 | + P.pick("tabs", tabs) |
| 87 | +end |
| 88 | + |
| 89 | +function P.hidden_field(text, deli) |
| 90 | + return text:match(("([^%s]+)$"):format(deli)) |
| 91 | +end |
| 92 | + |
| 93 | +return P |
0 commit comments