@@ -78,7 +78,9 @@ local function create_floating_preview_window(state)
7878 win :mount ()
7979 return win
8080end
81- Preview = {}
81+
82+ local Preview = {}
83+ local instance = nil
8284
8385--- Creates a new preview.
8486--- @param state table The state of the source.
107109--- @param start_pos table ? The (0-indexed ) starting position of the previewed text. May be absent.
108110--- @param end_pos table ? The (0-indexed ) ending position of the previewed text. May be absent
109111function Preview :preview (bufnr , start_pos , end_pos )
112+ log .warn (" Creating preview window" )
110113 if self .is_neo_tree_window then
111114 log .error (" Could not find appropriate window for preview" )
112115 return
@@ -136,15 +139,6 @@ function Preview:preview(bufnr, start_pos, end_pos)
136139 self :highlight ()
137140end
138141
139- function Preview .dispose (state )
140- if state .preview and state .preview .active then
141- if state .preview .active then
142- state .preview :revert ()
143- end
144- end
145- state .preview = nil
146- end
147-
148142--- Reverts the preview and inactivates it, restoring the preview window to its previous state.
149143function Preview :revert ()
150144 self .active = false
@@ -343,4 +337,63 @@ function Preview:clearHighlight()
343337 end
344338end
345339
340+ Preview .hide = function ()
341+ if instance then
342+ instance :revert ()
343+ end
344+ instance = nil
345+ end
346+
347+ Preview .show = function (state )
348+ local node = state .tree :get_node ()
349+ if node .type == " directory" then
350+ return
351+ end
352+
353+ if instance then
354+ instance :findWindow (state )
355+ if not renderer .is_window_valid (instance .winid ) then
356+ log .warn (" Preview window is not valid" )
357+ Preview .hide ()
358+ instance = Preview :new (state )
359+ end
360+ else
361+ instance = Preview :new (state )
362+ end
363+
364+ local extra = node .extra or {}
365+ local position = extra .position
366+ local end_position = extra .end_position
367+ local path = node .path or node :get_id ()
368+ local bufnr = extra .bufnr or vim .fn .bufadd (path )
369+
370+ if bufnr and bufnr > 0 and instance then
371+ instance :preview (bufnr , position , end_position )
372+ end
373+ end
374+
375+ Preview .toggle = function (state )
376+ if instance then
377+ Preview .hide ()
378+ else
379+ Preview .show (state )
380+ local preview_event = {
381+ event = events .VIM_CURSOR_MOVED ,
382+ handler = function ()
383+ if not instance .active then
384+ return
385+ end
386+ if vim .api .nvim_get_current_win () == state .winid then
387+ Preview .show (state )
388+ else
389+ log .debug (" Neo-tree window lost focus, disposing preview" )
390+ Preview .hide ()
391+ end
392+ end ,
393+ id = " preview-event" ,
394+ }
395+ instance :subscribe (state .name , preview_event )
396+ end
397+ end
398+
346399return Preview
0 commit comments