Repository navigation
Expand file tree
/
Copy pathtry.rb
More file actions
executable file
·1731 lines (1511 loc) · 53.4 KB
/
Copy pathtry.rb
File metadata and controls
executable file
·1731 lines (1511 loc) · 53.4 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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
require 'io/console'
require 'time'
require 'set'
require_relative 'lib/tui'
require_relative 'lib/fuzzy'
# Spinel AOT has no FileUtils, IO#raw/#cooked/#iflush, IO.console, or Gem.
# These helpers are MRI-compatible stand-ins so the same source runs both ways.
module TryCompat
def self.mkdir_p(path)
path = File.expand_path(path.to_s)
return path if Dir.exist?(path)
stack = []
dir = path
while dir && dir != "/" && dir != "." && !Dir.exist?(dir)
stack.unshift(dir)
parent = File.dirname(dir)
break if parent == dir
dir = parent
end
stack.each do |d|
begin
Dir.mkdir(d.to_s)
rescue Errno::EEXIST
end
end
path
end
def self.stty_save
`stty -g 2>/dev/null`.to_s.chomp
rescue
""
end
def self.stty_set(state)
return if state.nil? || state.empty?
system("stty #{state} 2>/dev/null")
end
def self.with_raw_tty
saved = nil
if STDIN.tty?
saved = stty_save
system("stty raw -echo 2>/dev/null")
end
yield
ensure
stty_set(saved) if saved && !saved.empty?
end
def self.with_cooked_tty
saved = nil
if STDIN.tty?
saved = stty_save
system("stty cooked echo 2>/dev/null")
end
yield
ensure
stty_set(saved) if saved && !saved.empty?
end
def self.stdin_iflush
begin
loop { STDIN.read_nonblock(4096) }
rescue IO::WaitReadable, EOFError, Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::EINVAL
end
end
def self.win_platform?
!!(RUBY_PLATFORM.to_s =~ /mswin|mingw|cygwin/i)
end
# true when this process is a Spinel-compiled native binary (or any
# non-.rb executable), so init snippets should invoke $0 directly.
def self.compiled_binary?
name = File.basename($0.to_s)
!name.end_with?(".rb")
end
def self.self_exec_prefix(script_path)
quoted = "'" + script_path.to_s.gsub("'", %q('"'"')) + "'"
if compiled_binary?
quoted
else
"/usr/bin/env ruby #{quoted}"
end
end
end
# Emergency restore if the process exits while the TUI alt-screen is active.
$try_tui_active = false
at_exit do
next unless $try_tui_active
begin
STDERR.print("#{Tui::ANSI::RESET}#{Tui::ANSI::CURSOR_DEFAULT}#{Tui::ANSI::SHOW}#{Tui::ANSI::ALT_SCREEN_OFF}")
rescue
end
end
class TrySelector
include Tui::Helpers
TRY_PATH = ENV['TRY_PATH'] || File.expand_path("~/src/tries")
TRY_PROJECTS = ENV['TRY_PROJECTS']
# Precompiled regex constants
INPUT_CHAR_RE = /[a-zA-Z0-9\-\_\. ]/
WORD_CHAR_RE = /[a-zA-Z0-9]/
def initialize(search_term = "", base_path: TRY_PATH, initial_input: nil, test_render_once: false, test_no_cls: false, test_keys: nil, test_confirm: nil)
@search_term = search_term.gsub(/\s+/, '-')
@cursor_pos = 0 # Navigation cursor (list position)
@scroll_offset = 0
@search = Tui::InputField.new(
placeholder: "",
text: initial_input ? initial_input.gsub(/\s+/, '-') : @search_term
)
@selected = nil
@all_trials = nil # Memoized trials
@base_path = base_path.to_s
@delete_status = nil # Status message for deletions
@delete_mode = false # Whether we're in deletion mode
@marked_for_deletion = [] # Paths marked for deletion
@test_render_once = test_render_once
@test_no_cls = test_no_cls
@test_keys = test_keys
@test_had_keys = test_keys && !test_keys.empty?
@test_confirm = test_confirm
@old_winch_handler = nil # Store original SIGWINCH handler
@needs_redraw = false
TryCompat.mkdir_p(@base_path) unless Dir.exist?(@base_path.to_s)
end
def run
# Always use STDERR for rendering (it stays connected to TTY)
# This allows stdout to be captured for the shell commands
setup_terminal
# In test mode with no keys, render once and exit without TTY requirements
# If test_keys are provided, run the full loop
if @test_render_once && (@test_keys.nil? || @test_keys.empty?)
tries = get_tries
render(tries)
return nil
end
# Check if we have a TTY; allow tests with injected keys
if !STDIN.tty? || !STDERR.tty?
if @test_keys.nil? || @test_keys.empty?
STDERR.puts "Error: try requires an interactive terminal"
return nil
end
main_loop
else
TryCompat.with_raw_tty do
main_loop
end
end
ensure
restore_terminal
end
private
def setup_terminal
@terminal_restored = false
unless @test_no_cls
# Switch to alternate screen buffer (like vim, less, etc.)
STDERR.print("#{Tui::ANSI::ALT_SCREEN_ON}#{Tui::ANSI.set_title("try")}#{Tui::ANSI::CURSOR_BLINK}")
$try_tui_active = true
end
# Spinel can SIGSEGV restoring a previous WINCH handler on process exit.
unless TryCompat.compiled_binary?
@old_winch_handler = Signal.trap('WINCH') { @needs_redraw = true } if Signal.list.key?('WINCH')
end
end
def restore_terminal
return if @terminal_restored
@terminal_restored = true
unless @test_no_cls
STDERR.print(Tui::ANSI::RESET)
STDERR.print(Tui::ANSI::CURSOR_DEFAULT)
# Return to main screen buffer
STDERR.print(Tui::ANSI::ALT_SCREEN_OFF)
$try_tui_active = false
end
Signal.trap('WINCH', @old_winch_handler) if @old_winch_handler
begin
TryCompat.stdin_iflush
rescue
end
end
def load_all_tries
# Load trials only once - single pass through directory
@all_tries ||= begin
tries = []
now = Time.now
Dir.foreach(@base_path.to_s) do |entry|
# exclude . and .. but also .git, and any other hidden dirs.
next if entry.start_with?('.')
path = File.join(@base_path, entry)
begin
stat = File.stat(path)
rescue Errno::ENOENT, Errno::EACCES
next
end
# Only include directories
next unless stat.directory?
# Compute base_score from recency + date prefix bonus
mtime = stat.mtime
hours_since_access = (now - mtime) / 3600.0
base_score = 3.0 / Math.sqrt(hours_since_access + 1)
# Bonus for date-prefixed directories
base_score += 2.0 if entry.match?(/^\d{4}-\d{2}-\d{2}-/)
is_symlink = File.symlink?(path)
tries << {
text: entry,
basename: entry,
path: is_symlink ? File.realpath(path) : path,
is_new: false,
is_symlink: is_symlink,
ctime: stat.ctime,
mtime: mtime,
base_score: base_score
}
end
tries
end
end
# Result wrapper to avoid Hash#merge allocation per entry
TryEntry = Data.define(:data, :score, :highlight_positions) do
def [](key)
case key
when :score then score
when :highlight_positions then highlight_positions
else data[key]
end
end
def text; data[:text]; end
def basename; data[:basename]; end
def path; data[:path]; end
def is_new; data[:is_new]; end
def is_symlink; data[:is_symlink]; end
def ctime; data[:ctime]; end
def mtime; data[:mtime]; end
def base_score; data[:base_score]; end
end
def get_tries
load_all_tries
@fuzzy ||= Fuzzy.new(@all_tries)
# Cache results - only re-match when query changes
if @last_query == @search.text && @cached_results
return @cached_results
end
@last_query = @search.text
height = Tui::Terminal.size(STDERR)[0] || 24
max_results = [height - 6, 3].max
results = []
@fuzzy.match(@search.text).limit(max_results).each do |entry, positions, score|
results << TryEntry.new(entry, score, positions)
end
@cached_results = results
end
def main_loop
loop do
tries = get_tries
show_create_new = !@search.text.empty?
total_items = tries.length + (show_create_new ? 1 : 0)
# Ensure cursor is within bounds
@cursor_pos = [[@cursor_pos, 0].max, [total_items - 1, 0].max].min
render(tries)
key = read_key
# nil means terminal resize - just re-render with new dimensions
next unless key
before = @search.text
if @search.handle_key(key)
@cursor_pos = 0 if @search.text != before
next
end
case key
when "\r" # Enter (carriage return)
if @delete_mode && !@marked_for_deletion.empty?
# Confirm deletion of marked items
confirm_batch_delete(tries)
break if @selected
elsif @cursor_pos < tries.length
handle_selection(tries[@cursor_pos])
break if @selected
elsif show_create_new
# Selected "Create new"
handle_create_new
break if @selected
end
when "\e[A", "\x10" # Up arrow or Ctrl-P
@cursor_pos = [@cursor_pos - 1, 0].max
when "\e[B", "\x0E" # Down arrow or Ctrl-N
@cursor_pos = [@cursor_pos + 1, total_items - 1].min
when "\x04" # Ctrl-D - toggle mark for deletion
if @cursor_pos < tries.length
path = tries[@cursor_pos].path
if @marked_for_deletion.include?(path)
@marked_for_deletion.delete(path)
else
@marked_for_deletion << path
@delete_mode = true
end
# Exit delete mode if no more marks
@delete_mode = false if @marked_for_deletion.empty?
end
when "\x14" # Ctrl-T - create new try (immediate)
handle_create_new
break if @selected
when "\x12" # Ctrl-R - rename selected entry
if @cursor_pos < tries.length
run_rename_dialog(tries[@cursor_pos])
break if @selected
end
when "\x07" # Ctrl-G - graduate/ascend selected entry
if @cursor_pos < tries.length
run_ascend_dialog(tries[@cursor_pos])
break if @selected
end
when "\x03", "\x1b" # Ctrl-C or ESC
if @delete_mode
# Exit delete mode, clear marks
@marked_for_deletion.clear
@delete_mode = false
else
# Return a Hash (not nil): Spinel can SIGSEGV if this method's
# inferred return type is Hash and we break with nil.
@selected = { type: :cancel }
break
end
end
end
@selected
end
def read_key
if @test_keys && !@test_keys.empty?
return @test_keys.shift
end
# In test mode with no more keys, auto-exit by returning ESC
return "\e" if @test_had_keys && @test_keys && @test_keys.empty?
# Use IO.select with timeout to allow checking for resize
loop do
if @needs_redraw
@needs_redraw = false
clear_screen unless @test_no_cls
return nil
end
ready = IO.select([STDIN], nil, nil, 0.1)
return read_keypress if ready
end
end
def read_keypress
input = STDIN.getc
return nil if input.nil?
if input == "\e"
begin
nxt = STDIN.read_nonblock(1)
input << nxt
if nxt == "["
# CSI: consume until a final byte in 0x40-0x7E so mouse/unknown
# sequences never leak into the filter. Bare ESC still returns "\e"
# when no following byte is available (WaitReadable).
loop do
ch = STDIN.read_nonblock(1)
input << ch
code = ch.ord
break if code >= 0x40 && code <= 0x7E
end
# X10 mouse: ESC [ M + 3 payload bytes
if input == "\e[M"
begin
input << STDIN.read_nonblock(3)
rescue IO::WaitReadable, EOFError, Errno::EAGAIN, Errno::EWOULDBLOCK
end
end
elsif nxt == "O"
input << STDIN.read_nonblock(1)
end
rescue IO::WaitReadable, EOFError, Errno::EAGAIN, Errno::EWOULDBLOCK
# Standalone ESC (or incomplete sequence) — keep what we have
end
end
input
end
def clear_screen
STDERR.print("\e[2J\e[H")
end
def hide_cursor
STDERR.print(Tui::ANSI::HIDE)
end
def show_cursor
STDERR.print(Tui::ANSI::SHOW)
end
def render(tries)
screen = Tui::Screen.new(io: STDERR)
width = screen.width
height = screen.height
line = screen.header.add_line
line.write.write(emoji("🏠")).write(Tui::Text.accent(" Try Directory Selection") )
line = screen.header.add_line
line.write.write_dim(fill("─"))
line = screen.header.add_line
prefix = "Search: "
line.write.write_dim(prefix)
line.write.write(screen.input("", value: @search.text, cursor: @search.cursor).to_s)
line.mark_has_input(Tui::Metrics.visible_width(prefix))
line = screen.header.add_line
line.write.write_dim(fill("─"))
# Add footer first to get accurate line count
line = screen.footer.add_line
line.write.write_dim(fill("─"))
if @delete_status
line = screen.footer.add_line
line.write.write_bold(@delete_status)
@delete_status = nil
elsif @delete_mode
line = screen.footer.add_line(Tui::Palette::DANGER_BG)
line.write.write_bold(" DELETE MODE ")
line.write.write(" #{@marked_for_deletion.length} marked | Ctrl-D: Toggle Enter: Confirm Esc: Cancel")
else
line = screen.footer.add_line
line.center.write_dim("↑/↓: Navigate Enter: Select ^R: Rename ^G: Graduate ^D: Delete Esc: Cancel")
end
# Calculate max visible from actual header/footer counts
header_lines = screen.header.lines.length
footer_lines = screen.footer.lines.length
max_visible = [height - header_lines - footer_lines, 3].max
show_create_new = !@search.text.empty?
total_items = tries.length + (show_create_new ? 1 : 0)
if @cursor_pos < @scroll_offset
@scroll_offset = @cursor_pos
elsif @cursor_pos >= @scroll_offset + max_visible
@scroll_offset = @cursor_pos - max_visible + 1
end
visible_end = [@scroll_offset + max_visible, total_items].min
(@scroll_offset...visible_end).each do |idx|
if idx == tries.length && !tries.empty? && idx >= @scroll_offset
screen.body.add_line
end
if idx < tries.length
render_entry_line(screen, tries[idx], idx == @cursor_pos, width)
else
render_create_line(screen, idx == @cursor_pos, width)
end
end
screen.flush
end
def render_entry_line(screen, entry, is_selected, width)
is_marked = @marked_for_deletion.include?(entry.path)
# Marked items keep the danger background; selected rows add a readable foreground.
background = if is_marked
Tui::Palette::DANGER_BG + (is_selected ? Tui::Palette::SELECTED_FG : "")
elsif is_selected
Tui::Palette::SELECTED_BG + Tui::Palette::SELECTED_FG
end
line = screen.body.add_line(background)
line.write.write((is_selected ? Tui::Text.highlight("→ ") + selected_foreground : " "))
icon = if is_marked
emoji("🗑️")
elsif entry.is_symlink
emoji("🔗")
else
emoji("📁")
end
line.write.write(icon).write(" ")
plain_name, rendered_name = formatted_entry_name(entry, selected: is_selected)
prefix_width = 5
meta_text = "#{format_relative_time(entry.mtime)}, #{format('%.1f', entry.score)}"
# Only truncate name if it exceeds total line width (not to make room for metadata)
max_name_width = width - prefix_width - 1
if plain_name.length > max_name_width && max_name_width > 2
display_rendered = truncate_with_ansi(rendered_name, max_name_width - 1) + "…"
else
display_rendered = rendered_name
end
line.write.write(display_rendered)
# Right content is lower layer - will be overwritten by left if they overlap
line.right.write(is_selected ? meta_text : Tui::Text.dim(meta_text))
end
def render_create_line(screen, is_selected, width)
background = if is_selected
Tui::Palette::SELECTED_BG + Tui::Palette::SELECTED_FG
end
line = screen.body.add_line(background)
line.write.write((is_selected ? Tui::Text.highlight("→ ") + selected_foreground : " "))
date_prefix = Time.now.strftime("%Y-%m-%d")
label = if @search.text.empty?
"📂 Create new: #{date_prefix}-"
else
"📂 Create new: #{date_prefix}-#{@search.text}"
end
line.write.write(label)
end
def formatted_entry_name(entry, selected: false)
basename = entry.basename
positions = entry.highlight_positions || []
if basename =~ /^(\d{4}-\d{2}-\d{2})-(.+)$/
date_part = $1
name_part = $2
date_len = date_part.length + 1 # +1 for the hyphen
rendered = selected ? date_part : Tui::Text.dim(date_part)
# Highlight hyphen if it's in positions
hyphen = if positions.include?(10)
Tui::Text.highlight('-')
elsif selected
'-'
else
Tui::Text.dim('-')
end
rendered += hyphen
rendered += selected_foreground if selected && positions.include?(10)
rendered += highlight_with_positions(name_part, positions, date_len, selected: selected)
["#{date_part}-#{name_part}", rendered]
else
[basename, highlight_with_positions(basename, positions, 0, selected: selected)]
end
end
def highlight_with_positions(text, positions, offset, selected: false)
pos_set = positions.is_a?(Set) ? positions : positions.to_set
result = String.new
chars = text.chars
i = 0
while i < chars.length
if pos_set.include?(i + offset)
# Batch consecutive highlighted characters
batch_start = i
i += 1
i += 1 while i < chars.length && pos_set.include?(i + offset)
result << Tui::Text.highlight(chars[batch_start...i].join)
result << selected_foreground if selected
else
result << chars[i]
i += 1
end
end
result
end
def selected_foreground
Tui.colors_enabled? ? Tui::Palette::SELECTED_FG : ""
end
# Find the position of the previous word boundary for Ctrl-W deletion.
# Skips non-alphanumeric chars, then skips alphanumeric chars.
def word_boundary_backward(buffer, cursor)
Tui::InputField.new(placeholder: "", text: buffer.to_s, cursor: cursor).word_boundary_backward(buffer.to_s, cursor)
end
def format_relative_time(time)
return "?" unless time
seconds = Time.now - time
minutes = seconds / 60
hours = minutes / 60
days = hours / 24
if seconds < 60
"just now"
elsif minutes < 60
"#{minutes.to_i}m ago"
elsif hours < 24
"#{hours.to_i}h ago"
elsif days < 7
"#{days.to_i}d ago"
else
"#{(days/7).to_i}w ago"
end
end
def truncate_with_ansi(text, max_length)
# Simple truncation that preserves ANSI codes
visible_count = 0
result = ""
in_ansi = false
text.chars.each do |char|
if char == "\e"
in_ansi = true
result += char
elsif in_ansi
result += char
in_ansi = false if char == "m"
else
break if visible_count >= max_length
result += char
visible_count += 1
end
end
result
end
# Rename dialog - dedicated screen similar to delete
def run_rename_dialog(entry)
@delete_mode = false
@marked_for_deletion.clear
current_name = entry.basename
input = Tui::InputField.new(placeholder: "", text: current_name.dup)
rename_error = nil
loop do
render_rename_dialog(current_name, input.text, input.cursor, rename_error)
ch = read_key
next unless ch
before = input.text
if input.handle_key(ch)
rename_error = nil if input.text != before
next
end
case ch
when "\r" # Enter - confirm
result = finalize_rename(entry, input.text)
if result == true
break
else
rename_error = result # Error message string
end
when "\x1b", "\x03" # ESC or Ctrl-C - cancel
break
end
end
@needs_redraw = true
end
def render_rename_dialog(current_name, rename_buffer, rename_cursor, rename_error)
screen = Tui::Screen.new(io: STDERR)
line = screen.header.add_line
line.center.write(emoji("✏️")).write(Tui::Text.accent(" Rename directory"))
line = screen.header.add_line
line.write.write_dim(fill("─"))
line = screen.body.add_line
line.write.write(emoji("📁")).write(" #{current_name}")
# Add empty lines, then centered input prompt
screen.body.add_line
screen.body.add_line
line = screen.body.add_line
prefix = "New name: "
line.center.write_dim(prefix)
line.center.write(screen.input("", value: rename_buffer, cursor: rename_cursor).to_s)
# Input displays buffer + trailing space when cursor at end
# Use (width - 1) to match Line.render's max_content calculation
input_width = [rename_buffer.length, rename_cursor + 1].max
prefix_width = Tui::Metrics.visible_width(prefix)
max_content = screen.width - 1
center_start = (max_content - prefix_width - input_width) / 2
line.mark_has_input(center_start + prefix_width)
if rename_error
screen.body.add_line
line = screen.body.add_line
line.center.write_bold(rename_error)
end
line = screen.footer.add_line
line.write.write_dim(fill("─"))
line = screen.footer.add_line
line.center.write_dim("Enter: Confirm Esc: Cancel")
screen.flush
end
def finalize_rename(entry, rename_buffer)
new_name = rename_buffer.strip.gsub(/\s+/, '-')
old_name = entry.basename
return "Name cannot be empty" if new_name.empty?
return "Name cannot contain /" if new_name.include?('/')
return true if new_name == old_name # No change, just exit
return "Directory exists: #{new_name}" if Dir.exist?(File.join(@base_path, new_name))
@selected = { type: :rename, old: old_name, new: new_name, base_path: @base_path }
true
end
# Ascend dialog - promote a try to a permanent project directory
def run_ascend_dialog(entry)
@delete_mode = false
@marked_for_deletion.clear
current_name = entry.basename
# Strip date prefix for the default project name
project_name = current_name.sub(/^\d{4}-\d{2}-\d{2}-/, '')
# Compute default destination directory
projects_dir = if TRY_PROJECTS
File.expand_path(TRY_PROJECTS)
else
File.dirname(@base_path)
end
input = Tui::InputField.new(placeholder: "", text: File.join(projects_dir, project_name))
ascend_error = nil
loop do
render_ascend_dialog(current_name, input.text, input.cursor, ascend_error, projects_dir)
ch = read_key
next unless ch
before = input.text
if input.handle_key(ch)
ascend_error = nil if input.text != before
next
end
case ch
when "\r" # Enter - confirm
result = finalize_ascend(entry, input.text)
if result == true
break
else
ascend_error = result
end
when "\x1b", "\x03" # ESC or Ctrl-C - cancel
break
end
end
@needs_redraw = true
end
def render_ascend_dialog(current_name, ascend_buffer, ascend_cursor, ascend_error, projects_dir)
screen = Tui::Screen.new(io: STDERR)
line = screen.header.add_line
line.center.write(emoji("🚀")).write(Tui::Text.accent(" Graduate try to project"))
line = screen.header.add_line
line.write.write_dim(fill("─"))
line = screen.body.add_line
line.write.write(emoji("📁")).write(" #{current_name}")
screen.body.add_line
env_hint = TRY_PROJECTS ? "$TRY_PROJECTS" : "parent of $TRY_PATH"
line = screen.body.add_line
line.center.write_dim("Destination (#{env_hint}: #{projects_dir})")
line = screen.body.add_line
prefix = "Move to: "
line.center.write_dim(prefix)
line.center.write(screen.input("", value: ascend_buffer, cursor: ascend_cursor).to_s)
input_width = [ascend_buffer.length, ascend_cursor + 1].max
prefix_width = Tui::Metrics.visible_width(prefix)
max_content = screen.width - 1
center_start = (max_content - prefix_width - input_width) / 2
line.mark_has_input(center_start + prefix_width)
screen.body.add_line
line = screen.body.add_line
line.center.write_dim("A symlink will be left in the tries directory")
if ascend_error
screen.body.add_line
line = screen.body.add_line
line.center.write_bold(ascend_error)
end
line = screen.footer.add_line
line.write.write_dim(fill("─"))
line = screen.footer.add_line
line.center.write_dim("Enter: Confirm Esc: Cancel")
screen.flush
end
def finalize_ascend(entry, ascend_buffer)
dest = ascend_buffer.strip
dest = File.expand_path(dest)
return "Destination cannot be empty" if dest.empty?
return "Destination already exists: #{dest}" if File.exist?(dest)
parent = File.dirname(dest)
return "Parent directory does not exist: #{parent}" unless Dir.exist?(parent)
@selected = {
type: :ascend,
source: entry.path,
dest: dest,
basename: entry.basename,
base_path: @base_path
}
true
end
def handle_selection(try_dir)
# Select existing try directory
@selected = { type: :cd, path: try_dir.path }
end
def handle_create_new
# Create new try directory
date_prefix = Time.now.strftime("%Y-%m-%d")
# If user already typed a name, use it directly
if !@search.text.empty?
final_name = "#{date_prefix}-#{@search.text}".gsub(/\s+/, '-')
full_path = File.join(@base_path, final_name)
@selected = { type: :mkdir, path: full_path }
else
# No name typed, prompt for one
entry = ""
begin
clear_screen unless @test_no_cls
show_cursor
STDERR.puts "Enter new try name"
STDERR.puts
STDERR.print("> #{date_prefix}-")
STDERR.flush
TryCompat.with_cooked_tty do
TryCompat.stdin_iflush
entry = STDIN.gets&.chomp.to_s
end
ensure
hide_cursor unless @test_no_cls
end
return if entry.nil? || entry.empty?
final_name = "#{date_prefix}-#{entry}".gsub(/\s+/, '-')
full_path = File.join(@base_path, final_name)
@selected = { type: :mkdir, path: full_path }
end
end
def confirm_batch_delete(tries)
# Find marked items with their info
marked_items = tries.select { |t| @marked_for_deletion.include?(t.path) }
return if marked_items.empty?
input = Tui::InputField.new(placeholder: "", text: "")
# Handle test mode
if @test_keys && !@test_keys.empty?
while @test_keys && !@test_keys.empty?
ch = @test_keys.shift
break if ch == "\r" || ch == "\n"
input.handle_key(ch)
end
process_delete_confirmation(marked_items, input.text)
return
elsif @test_confirm || !STDERR.tty?
confirmation_buffer = (@test_confirm || STDIN.gets)&.chomp.to_s
process_delete_confirmation(marked_items, confirmation_buffer)
return
end
# Interactive delete confirmation dialog
# Clear screen once before dialog to ensure clean slate
clear_screen unless @test_no_cls
loop do
render_delete_dialog(marked_items, input.text, input.cursor)
ch = read_key
next unless ch
if input.handle_key(ch)
next
end
case ch
when "\r" # Enter - confirm
process_delete_confirmation(marked_items, input.text)
break
when "\e", "\x03" # Escape or Ctrl-C - cancel
@delete_status = "Delete cancelled"
@marked_for_deletion.clear
@delete_mode = false
break
end
end
@needs_redraw = true
end
def render_delete_dialog(marked_items, confirmation_buffer, confirmation_cursor)
screen = Tui::Screen.new(io: STDERR)
count = marked_items.length
line = screen.header.add_line
line.center.write(emoji("🗑️")).write(Tui::Text.accent(" Delete #{count} #{count == 1 ? 'directory' : 'directories'}?"))
line = screen.header.add_line
line.write.write_dim(fill("─"))
marked_items.each do |item|
line = screen.body.add_line(Tui::Palette::DANGER_BG)
line.write.write(emoji("🗑️")).write(" #{item.basename}")
end
# Add empty lines, then centered confirmation prompt
screen.body.add_line
screen.body.add_line
line = screen.body.add_line
prefix = "Type YES to confirm: "
line.center.write_dim(prefix)
line.center.write(screen.input("", value: confirmation_buffer, cursor: confirmation_cursor).to_s)
# Input displays buffer + trailing space when cursor at end
# Use (width - 1) to match Line.render's max_content calculation
input_width = [confirmation_buffer.length, confirmation_cursor + 1].max
prefix_width = Tui::Metrics.visible_width(prefix)
max_content = screen.width - 1
center_start = (max_content - prefix_width - input_width) / 2
line.mark_has_input(center_start + prefix_width)
line = screen.footer.add_line
line.write.write_dim(fill("─"))
line = screen.footer.add_line
line.center.write_dim("Enter: Confirm Esc: Cancel")
screen.flush
end
def process_delete_confirmation(marked_items, confirmation)
if confirmation == "YES"
begin
base_real = File.realpath(@base_path)
# Validate all paths first
validated_paths = []
marked_items.each do |item|
target_real = File.realpath(item.path)
unless target_real.start_with?(base_real + "/")
raise "Safety check failed: #{target_real} is not inside #{base_real}"
end
validated_paths << { path: target_real, basename: item.basename }
end
# Return delete action with all paths
@selected = { type: :delete, paths: validated_paths, base_path: base_real }
names = validated_paths.map { |p| p[:basename] }.join(", ")
@delete_status = "Deleted: #{names}"
@all_tries = nil # Clear cache
@fuzzy = nil
@cached_results = nil
@last_query = nil
@marked_for_deletion.clear
@delete_mode = false
rescue => e