forked from sudo-tee/opencode.nvim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_picker.lua
More file actions
688 lines (605 loc) · 20.8 KB
/
base_picker.lua
File metadata and controls
688 lines (605 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
local config = require('opencode.config')
local util = require('opencode.util')
local Promise = require('opencode.promise')
---@class PickerAction
---@field key? OpencodeKeymapEntry|string The key binding for this action
---@field label string The display label for this action
---@field fn fun(selected: any|any[], opts: PickerOptions): any[]|Promise<any[]>? The action function
---@field reload? boolean Whether to reload the picker after action
---@field multi_selection? boolean Whether this action supports multi-selection
---@class PickerOptions
---@field items any[] The list of items to pick from
---@field format_fn fun(item: any, width?: number): PickerItem Function to format items for display
---@field actions table<string, PickerAction> Available actions for the picker
---@field callback fun(selected: any?) Callback when item is selected
---@field title string|fun(): string The picker title
---@field width? number Optional width for the picker (defaults to config or current window width)
---@field multi_selection? table<string, boolean> Actions that support multi-selection
---@field preview? "file"|"none"|false Preview mode: "file" for file preview, "none" or false to disable
---@field layout_opts? OpencodeUIPickerConfig
---@class TelescopeEntry
---@field value any
---@field display fun(entry: TelescopeEntry): string[]
---@field ordinal string
---@class FzfLuaOptions
---@field fn_fzf_index fun(line: string): integer?
---@class FzfAction
---@field fn fun(selected: string[], fzf_opts: FzfLuaOptions): nil|Promise<nil>
---@field header string
---@field reload boolean
---@class FzfLuaActions
---@field [string] FzfAction|fun(selected: string[], fzf_opts: FzfLuaOptions): nil
---@class MiniPickItem
---@field text string
---@field item any
---@class MiniPickSelected
---@field current MiniPickItem?
---@class PickerItemPart
---@field text string The text content
---@field highlight? string Optional highlight group
---@class PickerItem
---@field parts PickerItemPart[] Array of text parts with optional highlights
---@field to_string fun(self: PickerItem): string
---@field to_formatted_text fun(self: PickerItem): table
---@class BasePicker
local M = {}
local picker = require('opencode.ui.picker')
---Build title with action legend
---@param base_title string The base title
---@param actions table<string, PickerAction> The available actions
---@param support_multi? boolean Whether multi-selection is supported
---@return string title The formatted title with action legend
local function build_title(base_title, actions, support_multi)
local legend = {}
for _, action in pairs(actions) do
if action.key and action.key[1] then
local label = action.label .. (action.multi_selection and support_multi ~= false and ' (multi)' or '')
table.insert(legend, action.key[1] .. ' ' .. label)
end
end
return base_title .. (#legend > 0 and ' | ' .. table.concat(legend, ' | ') or '')
end
---Telescope UI implementation
---@param opts PickerOptions The picker options
local function telescope_ui(opts)
local pickers = require('telescope.pickers')
local finders = require('telescope.finders')
local conf = require('telescope.config').values
local actions = require('telescope.actions')
local action_state = require('telescope.actions.state')
local action_utils = require('telescope.actions.utils')
local entry_display = require('telescope.pickers.entry_display')
-- Create displayer dynamically based on number of parts
local function create_displayer(picker_item)
local items = {}
for _ in ipairs(picker_item.parts) do
table.insert(items, {})
end
return entry_display.create({
separator = ' ',
items = items,
})
end
local current_picker
---Creates entry maker function for telescope
---@param item any
---@return TelescopeEntry
local function make_entry(item)
local picker_item = opts.format_fn(item)
local displayer = create_displayer(picker_item)
local entry = {
value = item,
display = function(entry)
local formatted = opts.format_fn(entry.value):to_formatted_text()
return displayer(formatted)
end,
ordinal = picker_item:to_string(),
}
if type(item) == 'table' then
entry.path = item.file or item.file_path or item.path or item.filename
entry.lnum = item.line or item.lnum
entry.col = item.column or item.col
-- Support line ranges for preview highlighting
if item.end_pos and type(item.end_pos) == 'table' and item.end_pos[1] then
entry.lnend = item.end_pos[1]
end
elseif type(item) == 'string' then
entry.path = item
end
return entry
end
local function refresh_picker()
return current_picker
and current_picker:refresh(
finders.new_table({ results = opts.items, entry_maker = make_entry }),
{ reset_prompt = false }
)
end
local selection_made = false
current_picker = pickers.new({}, {
prompt_title = opts.title,
finder = finders.new_table({ results = opts.items, entry_maker = make_entry }),
sorter = conf.generic_sorter({}),
previewer = opts.preview == 'file' and require('telescope.previewers').vim_buffer_vimgrep.new({}) or nil,
layout_config = opts.width and {
width = opts.width + 7, -- extra space for telescope UI
} or nil,
attach_mappings = function(prompt_bufnr, map)
actions.select_default:replace(function()
selection_made = true
local selection = action_state.get_selected_entry()
actions.close(prompt_bufnr)
if selection and opts.callback then
opts.callback(selection.value)
end
end)
actions.close:enhance({
post = function()
if not selection_made and opts.callback then
vim.schedule(function()
opts.callback(nil)
end)
end
end,
})
for _, action in pairs(opts.actions) do
if action.key and action.key[1] then
local modes = action.key.mode or { 'i', 'n' }
if type(modes) == 'string' then
modes = { modes }
end
local action_fn = function()
local items_to_process
if action.multi_selection then
local multi_selection = {}
action_utils.map_selections(prompt_bufnr, function(entry, index)
table.insert(multi_selection, entry.value)
end)
if #multi_selection > 0 then
items_to_process = multi_selection
else
local selection = action_state.get_selected_entry()
items_to_process = selection and selection.value or nil
end
else
local selection = action_state.get_selected_entry()
items_to_process = selection and selection.value or nil
end
if items_to_process then
local new_items = action.fn(items_to_process, opts)
Promise.wrap(new_items):and_then(function(resolved_items)
if action.reload and resolved_items then
opts.items = resolved_items
refresh_picker()
end
end)
end
end
for _, mode in ipairs(modes) do
map(mode, action.key[1], action_fn)
end
end
end
return true
end,
})
current_picker:find()
end
---FZF-Lua UI implementation
---@param opts PickerOptions The picker options
local function fzf_ui(opts)
local fzf_lua = require('fzf-lua')
local function create_fzf_config()
local has_multi_action = util.some(opts.actions, function(action)
return action.multi_selection
end)
return {
winopts = opts.width and {
width = opts.width + 8, -- extra space for fzf UI
} or nil,
fzf_opts = {
['--prompt'] = opts.title .. ' > ',
['--multi'] = has_multi_action and true or nil,
['--with-nth'] = '2..', -- hide the index prefix from display
['--delimiter'] = '\x01', -- use SOH as delimiter (invisible char)
},
_headers = { 'actions' },
-- Enable builtin previewer for file preview support
previewer = opts.preview == 'file' and 'builtin' or nil,
fn_fzf_index = function(line)
-- Extract the numeric index prefix before the SOH delimiter
local idx_str = line:match('^(%d+)\x01')
if idx_str then
return tonumber(idx_str)
end
return nil
end,
}
end
local function create_finder()
return function(fzf_cb)
for idx, item in ipairs(opts.items) do
local line_str = opts.format_fn(item):to_string()
-- Prepend index with SOH delimiter for reliable matching
local indexed_line = tostring(idx) .. '\x01' .. line_str
-- For file preview support, append file:line:col format
-- fzf-lua's builtin previewer automatically parses this format
if opts.preview == 'file' and type(item) == 'table' then
local file_path = item.file_path or item.path or item.filename or item.file
local line = item.line or item.lnum
local col = item.column or item.col
if file_path then
-- fzf-lua parses "path:line:col:" format for preview positioning
local pos_info = file_path
if line then
pos_info = pos_info .. ':' .. tostring(line)
if col then
pos_info = pos_info .. ':' .. tostring(col)
end
pos_info = pos_info .. ':'
end
-- Append position info after nbsp separator (fzf-lua standard)
-- nbsp is U+2002 EN SPACE, not regular tab
local nbsp = '\xe2\x80\x82'
indexed_line = indexed_line .. nbsp .. pos_info
end
end
fzf_cb(indexed_line)
end
fzf_cb()
end
end
local function refresh_fzf()
vim.schedule(function()
fzf_ui(opts)
end)
end
---@type FzfLuaActions
local actions_config = {
['default'] = function(selected, fzf_opts)
if not selected or #selected == 0 then
if opts.callback then
opts.callback(nil)
end
return
end
local idx = fzf_opts.fn_fzf_index(selected[1] --[[@as string]])
if idx and opts.items[idx] and opts.callback then
opts.callback(opts.items[idx])
end
end,
['esc'] = function()
if opts.callback then
opts.callback(nil)
end
end,
}
for _, action in pairs(opts.actions) do
if action.key and action.key[1] then
local key = require('fzf-lua.utils').neovim_bind_to_fzf(action.key[1])
actions_config[key] = {
fn = function(selected, fzf_opts)
if not selected or #selected == 0 then
return
end
local items_to_process
if action.multi_selection and #selected > 1 then
items_to_process = {}
for _, sel in ipairs(selected) do
local idx = fzf_opts.fn_fzf_index(sel --[[@as string]])
if idx and opts.items[idx] then
table.insert(items_to_process, opts.items[idx])
end
end
else
local idx = fzf_opts.fn_fzf_index(selected[1] --[[@as string]])
if idx and opts.items[idx] then
items_to_process = opts.items[idx]
end
end
if items_to_process then
local new_items = action.fn(items_to_process, opts)
Promise.wrap(new_items):and_then(function(resolved_items)
if action.reload and resolved_items then
---@cast resolved_items any[]
opts.items = resolved_items
refresh_fzf()
end
end)
end
end,
header = action.label,
reload = action.reload or false,
}
end
end
local fzf_config = create_fzf_config()
fzf_config.actions = actions_config
fzf_lua.fzf_exec(create_finder(), fzf_config)
end
---Mini.pick UI implementation
---@param opts PickerOptions The picker options
local function mini_pick_ui(opts)
local mini_pick = require('mini.pick')
---@type MiniPickItem[]
local items = vim.tbl_map(function(item)
return { text = opts.format_fn(item):to_string(), item = item }
end, opts.items)
local mappings = {}
for action_name, action in pairs(opts.actions) do
if action.key and action.key[1] then
mappings[action_name] = {
char = action.key[1],
func = function()
local current = mini_pick.get_picker_matches().current
if current and current.item then
-- Mini.pick doesn't have native multi-selection, we fallback single selection
local new_items = action.fn(current.item, opts)
Promise.wrap(new_items):and_then(function(resolved_items)
if action.reload and resolved_items then
opts.items = resolved_items
mini_pick_ui(opts)
end
end)
end
return true
end,
}
end
end
local selection_made = false
mini_pick.start({
window = opts.width
and {
config = {
width = opts.width + 2, -- extra space for mini.pick UI
},
}
or nil,
source = {
items = items,
name = opts.title,
choose = function(selected)
if selected and selected.item and opts.callback then
selection_made = true
opts.callback(selected.item)
end
return false
end,
on_done = function()
if not selection_made and opts.callback then
vim.schedule(function()
opts.callback(nil)
end)
end
end,
},
mappings = mappings,
})
end
---Snacks picker UI implementation
---@param opts PickerOptions The picker options
local function snacks_picker_ui(opts)
local Snacks = require('snacks')
local has_preview = opts.preview == 'file'
local title = type(opts.title) == 'function' and opts.title() or opts.title
---@cast title string
local layout_opts = opts.layout_opts and opts.layout_opts.snacks_layout or nil
local selection_made = false
---@type snacks.picker.Config
local snack_opts = {
title = title,
layout = layout_opts or {
preview = has_preview and 'main' or false,
preset = 'select',
config = function(layout)
local width = opts.width and (opts.width + 3) or nil -- extra space for snacks UI
if not has_preview then
layout.layout.width = width
layout.layout.max_width = width
layout.layout.min_width = width
end
end,
},
finder = function()
return opts.items
end,
matcher = {
sort_empty = false,
},
sort = {
fields = { 'score:desc', 'idx' },
},
transform = function(item, ctx)
if type(item) == 'table' then
if item.idx == nil then
item.idx = ctx.idx
end
if item.favorite_index and item.favorite_index < 999 then
item.score_add = (item.score_add or 0) + (1000 - item.favorite_index) * 1000
end
if not item.text then
local picker_item = opts.format_fn(item)
item.text = picker_item:to_string()
end
end
end,
format = function(item)
return opts.format_fn(item):to_formatted_text()
end,
on_close = function()
if not selection_made and opts.callback then
vim.schedule(function()
opts.callback(nil)
end)
end
end,
actions = {
confirm = function(_picker, item)
selection_made = true
_picker:close()
if item and opts.callback then
vim.schedule(function()
opts.callback(item)
end)
end
end,
},
}
-- Add file preview if enabled
if has_preview then
snack_opts.preview = 'file'
else
snack_opts.preview = function()
return false
end
end
snack_opts.win = snack_opts.win or {}
snack_opts.win.input = snack_opts.win.input or { keys = {} }
for action_name, action in pairs(opts.actions) do
if action.key and action.key[1] then
snack_opts.win.input.keys[action.key[1]] = { action_name, mode = action.key.mode or 'i' }
snack_opts.actions[action_name] = function(_picker, item)
if item then
local items_to_process
if action.multi_selection then
local selected_items = _picker:selected({ fallback = true })
items_to_process = #selected_items > 1 and selected_items or item
else
items_to_process = item
end
if not action.reload then
selection_made = true
_picker:close()
end
vim.schedule(function()
local new_items = action.fn(items_to_process, opts)
Promise.wrap(new_items):and_then(function(resolved_items)
if action.reload and resolved_items then
opts.items = resolved_items
_picker:refresh()
_picker:find()
end
end)
end)
end
end
end
end
---@generic T
Snacks.picker.pick(snack_opts)
end
---@param text? string
---@param width integer
---@param opts? {align?: "left" | "right" | "center", truncate?: boolean}
function M.align(text, width, opts)
text = text or ''
opts = opts or {}
opts.align = opts.align or 'left'
local tw = vim.api.nvim_strwidth(text)
if tw > width then
return opts.truncate and (vim.fn.strcharpart(text, 0, width - 1) .. '…') or text
end
local left = math.floor((width - tw) / 2)
local right = width - tw - left
if opts.align == 'left' then
left, right = 0, width - tw
elseif opts.align == 'right' then
left, right = width - tw, 0
end
return (' '):rep(left) .. text .. (' '):rep(right)
end
---Creates a generic picker item that can format itself for different pickers
---@param parts PickerItemPart[] Array of text parts with optional highlights
---@return PickerItem
function M.create_picker_item(parts)
local item = {
parts = parts,
}
function item:to_string()
local texts = {}
for _, part in ipairs(self.parts) do
table.insert(texts, part.text)
end
return table.concat(texts, ' ')
end
function item:to_formatted_text()
local formatted = {}
for _, part in ipairs(self.parts) do
if part.highlight then
table.insert(formatted, { ' ' .. part.text, part.highlight })
else
table.insert(formatted, { part.text })
end
end
return formatted
end
return item
end
---Helper function to create a simple picker item with content, time, and debug text
---This is a convenience wrapper around create_picker_item for common use cases
---@param text string Main content text
---@param time? number Optional time to format
---@param debug_text? string Optional debug text to append
---@param width? number Optional width override
---@return PickerItem
function M.create_time_picker_item(text, time, debug_text, width)
local time_width = time and #util.format_time(time) + 1 or 0
local debug_width = config.debug.show_ids and debug_text and #debug_text + 1 or 0
local item_width = width or vim.api.nvim_win_get_width(0)
local text_width = item_width - (debug_width + time_width)
local parts = {
{
text = M.align(text, text_width --[[@as integer]], { truncate = true }),
},
}
if time then
table.insert(parts, {
text = M.align(util.format_time(time), time_width, { align = 'right' }),
highlight = 'OpencodePickerTime',
})
end
if config.debug.show_ids and debug_text then
table.insert(parts, {
text = debug_text,
highlight = 'OpencodeDebugText',
})
end
return M.create_picker_item(parts)
end
---Generic picker that abstracts common logic for different picker UIs
---@param opts PickerOptions The picker options
---@return boolean success Whether the picker was successfully launched
function M.pick(opts)
local picker_type = picker.get_best_picker()
if not picker_type then
return false
end
if not opts.width then
opts.width = config.ui.picker_width
end
local original_format_fn = opts.format_fn
opts.format_fn = function(item)
return original_format_fn(item, opts.width)
end
local title_str = type(opts.title) == 'function' and opts.title() or opts.title --[[@as string]]
vim.schedule(function()
if picker_type == 'telescope' then
opts.title = build_title(title_str, opts.actions)
telescope_ui(opts)
elseif picker_type == 'fzf' then
opts.title = title_str
fzf_ui(opts)
elseif picker_type == 'mini.pick' then
opts.title = build_title(title_str, opts.actions, false)
mini_pick_ui(opts)
elseif picker_type == 'snacks' then
opts.title = build_title(title_str, opts.actions)
snacks_picker_ui(opts)
else
opts.callback(nil)
end
end)
return true
end
return M