Skip to content

Commit d385bcf

Browse files
committed
fix(tree): handle expanded/collapsed nodes in scroll
fix(tree): id generation for non-root nodes
1 parent ef3229e commit d385bcf

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

lua/nui-components/tree.lua

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,36 @@ local fn = require("nui-components.utils.fn")
88

99
local function focus_item(instance, direction, current_linenr)
1010
local actions = instance:get_actions()
11+
---@type NuiTree
1112
local tree = instance:get_tree()
1213

1314
local curr_linenr = current_linenr or vim.api.nvim_win_get_cursor(instance.winid)[1]
1415
local next_linenr = nil
1516

17+
local function tree_height(node_id)
18+
local height = 1
19+
local node = tree:get_node(node_id)
20+
if node and node:has_children() and node:is_expanded() then
21+
for _, child in ipairs(node:get_child_ids()) do
22+
height = height + tree_height(child)
23+
end
24+
end
25+
return height
26+
end
27+
28+
local height = fn.ireduce(tree:get_nodes(), function(acc, node)
29+
return acc + tree_height(node._id)
30+
end, 0)
31+
1632
if direction == "next" then
17-
if curr_linenr == instance:get_max_lines() then
33+
if curr_linenr == height then
1834
next_linenr = 1
1935
else
2036
next_linenr = curr_linenr + 1
2137
end
2238
elseif direction == "prev" then
2339
if curr_linenr == 1 then
24-
next_linenr = instance:get_max_lines()
40+
next_linenr = height
2541
else
2642
next_linenr = curr_linenr - 1
2743
end
@@ -257,16 +273,15 @@ function Tree:on_mount()
257273
self._private.tree = NuiTree({
258274
bufnr = self.bufnr,
259275
ns_id = self.ns_id,
260-
nodes = fn.imap(props.data, function(node)
261-
if node.id then
262-
node._id = node.id
263-
return node
264-
end
265-
266-
node._id = tostring(math.random())
267-
return node
268-
end),
276+
nodes = props.data,
269277
get_node_id = function(node)
278+
if node._id == nil then
279+
if node.id then
280+
node._id = node.id
281+
else
282+
node._id = tostring(math.random())
283+
end
284+
end
270285
return node._id
271286
end,
272287
prepare_node = actions.prepare_node,

0 commit comments

Comments
 (0)