Skip to content

Commit

Permalink
Place filetree cursor at selected file on init
Browse files Browse the repository at this point in the history
  • Loading branch information
julienvincent committed Aug 1, 2024
1 parent 99886cf commit 8fd2ec4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
8 changes: 0 additions & 8 deletions lua/hunk/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,6 @@ end

function M.start(left, right, output)
local changeset = api.changeset.load_changeset(left, right)
local files = utils.get_keys(changeset)

local layout = ui.layout.create_layout()

CONTEXT = {
Expand All @@ -147,19 +145,16 @@ function M.start(left, right, output)
output = output,
}

local current_change = changeset[files[1]]
local left_file, right_file, tree

tree = ui.tree.create({
winid = layout.tree,
changeset = changeset,
on_open = function(change)
current_change = change
left_file, right_file = open_file(layout, tree, change)
vim.api.nvim_set_current_win(layout.right)
end,
on_preview = function(change)
current_change = change
left_file, right_file = open_file(layout, tree, change)
vim.api.nvim_set_current_win(layout.tree)
end,
Expand All @@ -174,9 +169,6 @@ function M.start(left, right, output)

tree.render()

left_file, right_file = open_file(layout, tree, current_change)
vim.api.nvim_set_current_win(layout.tree)

set_global_bindings(layout, tree.buf)
end

Expand Down
32 changes: 32 additions & 0 deletions lua/hunk/ui/tree.lua
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,27 @@ local function apply_signs(tree, buf, nodes)
end
end

local function find_node_by_filepath(tree, path, nodes)
nodes = nodes or tree:get_nodes()
for _, node in pairs(nodes) do
local children = vim.tbl_map(function(id)
return tree:get_node(id)
end, node:get_child_ids())

local match, match_linenr = find_node_by_filepath(tree, path, children)
if match then
return match, match_linenr
end

if node.type == "file" then
local _, linenr = tree:get_node(node:get_id())
if linenr and node.change.filepath == path then
return node, linenr
end
end
end
end

local M = {}

function M.create(opts)
Expand Down Expand Up @@ -198,6 +219,17 @@ function M.create(opts)
end

tree:set_nodes(file_tree_to_nodes(file_tree))
Component.render()

local selected_file = file_tree_api.find_first_file_in_tree(file_tree)
if selected_file then
local _, selected_linenr = find_node_by_filepath(tree, selected_file.change.filepath)
if selected_linenr then
vim.api.nvim_win_set_cursor(opts.winid, { selected_linenr, 0 })
end

opts.on_preview(selected_file.change)
end

return Component
end
Expand Down

0 comments on commit 8fd2ec4

Please sign in to comment.