search_ui 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f7f6fca3d9ba87b61984b165b1a2d61fff1e11c2d6ad46e2c9af944f917a973c
4
- data.tar.gz: fcf83ece6431de1f2d733f9af803883fb715f55188041ecbebc0fca83f687a72
3
+ metadata.gz: 7524eb818f3757c57c95a7bced05db2b43da433e3c0f2939e12b06308eae5578
4
+ data.tar.gz: da19f31f4e0cf1cbc5f1381f94a65b9399abb1257c818a5e11c0126a1d2746c5
5
5
  SHA512:
6
- metadata.gz: 476baebb8eb065b104201bfb85fe62288c8dc3923ef11db2aeff0140f7c082974f49dff9ace589ed0186b2c5da182d50a89c4c64645d50dc5867ee6778293428
7
- data.tar.gz: 8872b95adff98b2028f1305aeea5e8377e52ba00a4f674c18b73ea7ee1891d5ed75a5c20a8de755f0e562562bff5e80aa54f6a6cad2954d07a11735c9f76454a
6
+ metadata.gz: 36282396842b4bb83ae843d1b76e80e785fc9b0cb96c4b0556eb0503af028372cb83d599963ae8c69c342ea3c00cc18c083466b51f18ef9ecd9921aedad3c5dc
7
+ data.tar.gz: a635a7ee1cc6a3fc2b9deb76c8ee086ad8d46dad67d2b80c8b80b1d1cad6242568b708e51a79c86d9689961eddb1c6146a650ccf2bad5076b37480d2832145fa
data/README.md CHANGED
@@ -10,8 +10,9 @@ Complete API documentation is available at: [GitHub.io](https://flori.github.io/
10
10
 
11
11
  ## Features
12
12
 
13
- - **Interactive Navigation** 🎮: Arrow key navigation through search results
13
+ - **Interactive Navigation** 🎮: Arrow keys, Home, End, PgUp, PgDn with scrollable viewport
14
14
  - **Real-time Filtering** ⚡: Instant search updates as you type
15
+ - **Multi-Select** 📋: Tab toggles items, Enter returns all picked
15
16
  - **Flexible Configuration** 🔧: Customizable matching, display, and selection logic
16
17
  - **Terminal-aware** 🖥️: Properly handles terminal input and display management
17
18
  - **Minimal Dependencies** 📦: Lightweight implementation using standard Ruby libraries
@@ -64,6 +65,66 @@ result = SearchUI::Search.new(
64
65
  puts "Selected: #{result}"
65
66
  ```
66
67
 
68
+ #### Multi-Select
69
+
70
+ Pass `multi: true` to collect multiple items before returning. The `query`
71
+ proc additionally receives a fourth argument — a `picked` Hash — so you can
72
+ render a visual marker (e.g. `✔`) on already-selected entries.
73
+
74
+ **Keys:**
75
+
76
+ | Key | Action |
77
+ |-------------|-------------------------------------------------|
78
+ | Arrow Up/Dn | Navigate the list |
79
+ | Home / End | Jump to first / last entry |
80
+ | PgUp / PgDn | Scroll by one viewport height |
81
+ | Tab | Toggle selection of the current entry |
82
+ | Enter | Confirm and return all picked items as an Array |
83
+ | Ctrl-C | Abort and return `nil` |
84
+
85
+ ```ruby
86
+ require 'search_ui'
87
+
88
+ result = SearchUI::Search.new(
89
+ match: ->(pattern) {
90
+ %w[apples bananas cherries dates figs grapes].select do |f|
91
+ pattern.empty? || f.include?(pattern)
92
+ end
93
+ },
94
+ query: ->(answer, matches, selector, picked) {
95
+ matches.each_with_index.map do |m, i|
96
+ cursor = i == selector ? '→' : ' '
97
+ mark = picked[m] ? '✔' : ' '
98
+ "#{cursor} #{mark} #{m}"
99
+ end.join("\n")
100
+ },
101
+ found: ->(answer, matches, selector) { matches[selector] },
102
+ multi: true,
103
+ picked: ['bananas'],
104
+ prompt: 'Pick fruit? %s [Tab=toggle, Enter=done, ^C=abort]'
105
+ ).start
106
+
107
+ puts "Picked: #{result.inspect}"
108
+ ```
109
+
110
+ **Bulk selection sentinels:**
111
+
112
+ Pass `all:` and `none:` to add sentinel entries that bulk-select or
113
+ clear all items in one Tab press. Include the sentinel strings in your
114
+ entry list; they are excluded from the returned result:
115
+
116
+ ```ruby
117
+ entries = %w[ [ALL] [NONE] ] + fruit_list
118
+
119
+ result = SearchUI::Search.new(
120
+ # ... match:, query:, found: as above ...
121
+ multi: true,
122
+ all: '[ALL]',
123
+ none: '[NONE]',
124
+ prompt: 'Pick? %s [Tab=toggle, Enter=done, ^C=abort]'
125
+ ).start
126
+ ```
127
+
67
128
  ### Command Line Tool
68
129
 
69
130
  The `search_it` binary provides a ready-to-use search interface:
@@ -74,6 +135,9 @@ The `search_it` binary provides a ready-to-use search interface:
74
135
 
75
136
  # Search through a file 📄
76
137
  ./bin/search_it -f items.txt
138
+
139
+ # Multi-select mode (Tab to toggle, Enter to confirm) 📋
140
+ ./bin/search_it -m apple banana cherry
77
141
  ```
78
142
 
79
143
  ## Author
data/VERSION CHANGED
@@ -1 +1 @@
1
- 0.3.0
1
+ 0.4.0
data/bin/search_it CHANGED
@@ -1,4 +1,18 @@
1
1
  #!/usr/bin/env ruby
2
+ #
3
+ # Interactive console search for picking items from a list.
4
+ #
5
+ # Usage:
6
+ # search_it [ITEM …] Search through command-line arguments
7
+ # search_it -f FILE Search through lines of a file
8
+ # search_it -m … Multi-select mode (Tab to toggle, Enter to confirm)
9
+ #
10
+ # Keys:
11
+ # ↑/↓ Navigate results
12
+ # Enter Confirm selection
13
+ # Ctrl-C Abort (returns nothing)
14
+ # Ctrl-K Clear search input
15
+ # Tab Toggle item (multi mode only)
2
16
 
3
17
  require 'search_ui'
4
18
  require 'tins/terminal'
@@ -7,7 +21,7 @@ include Tins::GO
7
21
  require 'amatch'
8
22
  include SearchUI
9
23
 
10
- opts = go('f:')
24
+ opts = go('mf:')
11
25
 
12
26
  choices =
13
27
  if filename = opts[?f]
@@ -18,19 +32,32 @@ choices =
18
32
  ARGV
19
33
  end
20
34
 
35
+ if multi = !!opts[?m]
36
+ query = -> _answer, matches, selector, picked {
37
+ matches.each_with_index.map { |m, i|
38
+ mark = picked[m] ? '✓' : '☐'
39
+ cursor = i == selector ? "→ " : " "
40
+ "#{cursor}#{mark} #{m}"
41
+ } * ?\n
42
+ }
43
+ else
44
+ query = -> _answer, matches, selector {
45
+ matches.each_with_index.
46
+ map { |m, i| i == selector ? "→ " + Search.on_blue(m) : " " + m } * ?\n
47
+ }
48
+ end
49
+
21
50
  found = Search.new(
22
- match: -> answer {
51
+ match: -> answer {
23
52
  matcher = Amatch::PairDistance.new(answer.downcase)
24
53
  matches = choices.map { |n| [ n, -matcher.similar(n.downcase) ] }.
25
54
  select { |_, s| s < 0 }.sort_by(&:last).map(&:first)
26
55
  matches.empty? and matches = choices
27
- matches.first(Tins::Terminal.lines - 1)
28
- },
29
- query: -> _answer, matches, selector {
30
- matches.each_with_index.
31
- map { |m, i| i == selector ? "→ " + Search.on_blue(m) : " " + m } * ?\n
56
+ matches
32
57
  },
33
- found: -> _answer, matches, selector {
58
+ query:,
59
+ multi:,
60
+ found: -> _answer, matches, selector {
34
61
  matches[selector]
35
62
  },
36
63
  output: STDOUT
@@ -1,4 +1,6 @@
1
1
  require 'term/ansicolor'
2
+ require 'io/console'
3
+ require 'tins'
2
4
 
3
5
  # SearchUI::Search manages interactive console-based searching through an array
4
6
  # of objects
@@ -31,11 +33,18 @@ class SearchUI::Search
31
33
  #
32
34
  # @param match [ Proc ] a procedure that accepts a search pattern string and returns
33
35
  # an array of matching objects.
34
- # @param query [ Proc ] a procedure that accepts the current answer, the list of
35
- # matches, and the current selector index to generate the string representation
36
- # of the results list.
37
- # @param found [ Proc ] a procedure that accepts the current answer, the list of
38
- # matches, and the current selector index to determine the final selected object.
36
+ # @param query [ Proc ] a procedure that accepts the current answer, the
37
+ # visible slice of matches, the cursor index relative to that slice, and
38
+ # (in multi mode) a fourth argument — a Hash of picked items. Used to
39
+ # generate the string representation of the visible results.
40
+ # @param found [ Proc ] a procedure that accepts the current answer, the
41
+ # full list of matches, and the absolute selector index to determine the
42
+ # final selected object.
43
+ # @param height [ Integer ] the number of rows to display. Defaults to
44
+ # `Tins::Terminal.lines - 1` (clamped to >= 0).
45
+ # @param multi [ Boolean ] enable multi-select mode where Tab
46
+ # toggles items in a picked set and Enter returns all picked items as
47
+ # an Array. Defaults to false.
39
48
  # @param output [ IO ] the output stream where the interface will be rendered.
40
49
  # Defaults to STDOUT.
41
50
  # @param prompt [ String ] a format string used as the user prompt.
@@ -43,20 +52,47 @@ class SearchUI::Search
43
52
  # @param state [ SearchUI::Search::State, nil ] an initial state object containing
44
53
  # the starting answer and selector position. Defaults to a new State with an
45
54
  # empty answer and selector set to 0.
55
+ # @param picked [ Hash, Array, Set, nil ] initial multi-select picks. A Hash
56
+ # is merged directly; an Array or Set is converted to `{ item => true }`.
57
+ # Only meaningful when `multi: true`. Defaults to nil (no pre-picks).
58
+ # @raise [ ArgumentError ] if `picked` is not `nil` and does not respond
59
+ # to `#to_hash`, `#to_ary`, or `#to_set`.
46
60
  def initialize(
47
61
  match:,
48
62
  query:,
49
63
  found:,
64
+ height: (Tins::Terminal.lines - 1).clamp(0..),
65
+ multi: false,
50
66
  output: STDOUT,
51
67
  prompt: 'Search? %s',
52
- state: nil
68
+ state: nil,
69
+ all: nil,
70
+ none: nil,
71
+ picked: nil
53
72
  )
54
73
  @match = match
55
74
  @query = query
56
75
  @found = found
76
+ @height = height
77
+ @offset = 0
57
78
  @output = output
58
79
  @prompt = prompt
80
+ @multi = multi
59
81
  @state = state || State.new('', 0)
82
+ @all = all
83
+ @none = none
84
+ @picked = Hash.new(false)
85
+ case
86
+ when picked.nil?
87
+ when picked.respond_to?(:to_hash)
88
+ @picked.update(picked.to_hash)
89
+ when picked.respond_to?(:to_ary)
90
+ @picked.update(picked.to_ary.each_with_object({}) { |k, h| h[k] = true })
91
+ when picked.respond_to?(:to_set)
92
+ @picked.update(picked.to_set.each_with_object({}) { |k, h| h[k] = true })
93
+ else
94
+ raise ArgumentError, 'picked needs to support #to_hash | #to_ary | #to_set'
95
+ end
60
96
  end
61
97
 
62
98
  # Reads the current internal state of the search interface, containing the
@@ -69,89 +105,180 @@ class SearchUI::Search
69
105
  # Starts the interactive search interface and handles user input until a
70
106
  # selection is made or the process is cancelled.
71
107
  #
72
- # @return [ Object, nil ] returns the selected result object when a selection
73
- # is made, or nil if the process is cancelled
108
+ # @return [ Object, Array, nil ] In single mode, returns the selected result
109
+ # object or nil if cancelled. In multi mode, returns an Array of picked
110
+ # items or nil if cancelled.
74
111
  def start
75
112
  @output.print reset
76
- @matches = @match.(@state.answer)
77
- @state.selector = @state.selector.clamp(0, [ @matches.size - 1, 0 ].max)
78
- result = @query.(@state.answer, @matches, @state.selector)
113
+ @matchables = @match.('').dup
114
+ @matchables.delete(@all) unless @all.nil?
115
+ @matchables.delete(@none) unless @none.nil?
116
+ result = refresh
79
117
  loop do
80
118
  @output.print clear_screen
81
119
  @output.print move_home { @prompt % @state.answer + ?\n + result }
82
120
  case getc
83
121
  when true
84
122
  @output.print clear_screen, move_home, reset
85
- if result = @found.(@state.answer, @matches, @state.selector)
86
- return result
123
+ if @multi
124
+ return @picked.select { _2 }.keys
87
125
  else
88
- return nil
126
+ if result = @found.(@state.answer, @matches, @state.selector)
127
+ return result
128
+ else
129
+ return nil
130
+ end
89
131
  end
90
132
  when false
91
133
  return nil
92
134
  end
93
- @matches = @match.(@state.answer)
94
- @state.selector = @state.selector.clamp(0, [ @matches.size - 1, 0 ].max)
95
- result = @query.(@state.answer, @matches, @state.selector)
135
+ result = refresh
96
136
  end
97
137
  end
98
138
 
99
139
  private
100
140
 
141
+ # Re-runs the match proc, keeps the selector and scroll offset in sync
142
+ # with the new result set, and renders the visible window.
143
+ #
144
+ # @return [ String ] the rendered results list for the current viewport
145
+ def refresh
146
+ @matches = @match.(@state.answer)
147
+ @state.selector = @state.selector.clamp(0, [ @matches.size - 1, 0 ].max)
148
+ adjust_offset
149
+ slice, relative = viewport
150
+ if @multi
151
+ @query.(@state.answer, slice, relative, @picked)
152
+ else
153
+ @query.(@state.answer, slice, relative)
154
+ end
155
+ end
156
+
157
+ # Slides the scroll offset so the selected item is always inside the
158
+ # visible window, using sticky hysteresis: the window only moves when the
159
+ # cursor crosses an edge, never on mere up/down wobble.
160
+ def adjust_offset
161
+ @offset = [ @offset, [ @matches.size - @height, 0 ].max ].min
162
+ @offset = @state.selector if @state.selector < @offset
163
+ @offset = @state.selector - @height + 1 if @state.selector >= @offset + @height
164
+ end
165
+
166
+ # Returns the slice of matches for the visible window along with the
167
+ # selector's position relative to that slice.
168
+ #
169
+ # @return [ Array, Integer ] the visible rows and the relative cursor index
170
+ def viewport
171
+ [ @matches[@offset, @height], @state.selector - @offset ]
172
+ end
173
+
101
174
  # Reads and processes a single character input from STDIN, handling special
102
175
  # key sequences and updating the search state accordingly.
103
176
  #
104
- # This method manages raw terminal input to capture user keystrokes,
105
- # interpreting control characters and ANSI escape sequences:
106
- # - Up/Down arrows: Navigate the result selector.
177
+ # This method uses `STDIN.raw` (io/console) to capture user keystrokes in
178
+ # raw mode with interrupt handling, interpreting control characters and
179
+ # ANSI escape sequences:
180
+ # - Up/Down arrows: Navigate the result selector by one row.
181
+ # - Home (\e[H, \e[1~, \eOH) / End (\e[F, \e[4~, \eOF): Jump to first / last.
182
+ # - PgUp (\e[5~) / PgDn (\e[6~): Jump by one viewport height.
107
183
  # - Enter (`\r`): Confirms the current selection.
108
- # - Ctrl-C (`\x03`): Cancels the search operation.
184
+ # - Tab (`\t`): In multi mode, toggles selection of the current
185
+ # match. In single mode, ignored.
186
+ # - Ctrl-C: Raises Interrupt, caught to cancel the search operation.
109
187
  # - Ctrl-K (`\v`): Clears the current search answer.
110
188
  # - Backspace (`\x7f`): Deletes the last character of the answer.
111
189
  # - Note: Any modification to the search answer resets the selector to 0.
112
190
  #
113
- # It temporarily disables terminal echo and sets raw mode to ensure proper
114
- # input handling.
115
- #
116
191
  # @return [ Boolean, nil ]
117
192
  # - `true`: The Enter key was pressed to confirm selection.
118
193
  # - `false`: Ctrl-C was pressed to cancel the operation.
119
194
  # - `nil`: Input updated the search state or was ignored.
120
195
  def getc
196
+ interrupted = [ Interrupt, Errno::ENOTTY ]
197
+ interrupted << IRB::Abort if defined? IRB::Abort
121
198
  print hide_cursor
122
- system 'stty raw -echo'
123
- c = STDIN.getc
124
- system 'stty cooked echo'
125
- case c
126
- when "\x03"
127
- false
128
- when "\e"
129
- STDIN.getc == ?[ or return nil
130
- STDIN.getc =~ /\A([AB])\z/ or return nil
131
- if $1 == ?A
132
- @state.selector -= 1
199
+ STDIN.raw(min: 1, intr: true) do |io|
200
+ c = io.getc
201
+ case c
202
+ when "\e"
203
+ prefix = io.getc
204
+ case prefix
205
+ when ?[
206
+ key = io.getc
207
+ case key
208
+ when ?A
209
+ @state.selector -= 1
210
+ when ?B
211
+ @state.selector += 1
212
+ when ?H
213
+ @state.selector = 0
214
+ when ?F
215
+ @state.selector = [ @matches.size - 1, 0 ].max
216
+ when ?1, ?4, ?5, ?6
217
+ io.getc == ?~ or return nil
218
+ case key
219
+ when ?1
220
+ @state.selector = 0
221
+ when ?4
222
+ @state.selector = [ @matches.size - 1, 0 ].max
223
+ when ?5
224
+ @state.selector -= @height
225
+ when ?6
226
+ @state.selector += @height
227
+ end
228
+ else
229
+ return nil
230
+ end
231
+ when ?O
232
+ key = io.getc
233
+ case key
234
+ when ?H
235
+ @state.selector = 0
236
+ when ?F
237
+ @state.selector = [ @matches.size - 1, 0 ].max
238
+ else
239
+ return nil
240
+ end
241
+ else
242
+ return nil
243
+ end
244
+ @state.selector = [ @state.selector, 0 ].max
245
+ nil
246
+ when ?\r
247
+ true
248
+ when "\x7f"
249
+ @state.selector = 0
250
+ @state.answer.chop!
251
+ nil
252
+ when ?\v
253
+ @state.selector = 0
254
+ @state.answer.clear
255
+ nil
256
+ when ?\t
257
+ if @multi
258
+ if m = @matches[@state.selector]
259
+ case
260
+ when !@all.nil? && @all == m
261
+ @matchables.each { @picked[_1] = true }
262
+ when !@none.nil? && @none == m
263
+ @picked.clear
264
+ when @picked[m]
265
+ @picked[m] = false
266
+ else
267
+ @picked[m] = true
268
+ end
269
+ end
270
+ end
271
+ nil
272
+ when /\A[\x00-\x1f]\z/
273
+ nil
133
274
  else
134
- @state.selector += 1
275
+ @state.selector = 0
276
+ @state.answer << c
277
+ nil
135
278
  end
136
- @state.selector = [ @state.selector, 0 ].max
137
- nil
138
- when ?\r
139
- true
140
- when "\x7f"
141
- @state.selector = 0
142
- @state.answer.chop!
143
- nil
144
- when ?\v
145
- @state.selector = 0
146
- @state.answer.clear
147
- nil
148
- when /\A[\x00-\x1f]\z/
149
- nil
150
- else
151
- @state.selector = 0
152
- @state.answer << c
153
- nil
154
279
  end
280
+ rescue *interrupted
281
+ false
155
282
  ensure
156
283
  print show_cursor
157
284
  end
@@ -5,7 +5,7 @@
5
5
  # by hand; it is rewritten on every `rake version` invocation.
6
6
  module SearchUI
7
7
  # The current version of the SearchUI gem as a String.
8
- VERSION = '0.3.0'
8
+ VERSION = '0.4.0'
9
9
  VERSION_ARRAY = VERSION.split('.').map(&:to_i) # :nodoc:
10
10
  VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
11
11
  VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
@@ -51,7 +51,7 @@ class SearchUI::Wrapper < BasicObject
51
51
  # @return [String]
52
52
  def to_s
53
53
  if @display.respond_to?(:call)
54
- case @display.method(:call).arity
54
+ case @display.arity
55
55
  when 0
56
56
  @display.()
57
57
  else
data/search_ui.gemspec CHANGED
@@ -1,9 +1,9 @@
1
1
  # -*- encoding: utf-8 -*-
2
- # stub: search_ui 0.3.0 ruby lib
2
+ # stub: search_ui 0.4.0 ruby lib
3
3
 
4
4
  Gem::Specification.new do |s|
5
5
  s.name = "search_ui".freeze
6
- s.version = "0.3.0".freeze
6
+ s.version = "0.4.0".freeze
7
7
 
8
8
  s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
9
9
  s.require_paths = ["lib".freeze]
@@ -13,14 +13,14 @@ Gem::Specification.new do |s|
13
13
  s.email = "flori@ping.de".freeze
14
14
  s.executables = ["search_it".freeze]
15
15
  s.extra_rdoc_files = ["README.md".freeze, "lib/search_ui.rb".freeze, "lib/search_ui/search.rb".freeze, "lib/search_ui/version.rb".freeze, "lib/search_ui/wrapper.rb".freeze]
16
- s.files = [".rspec".freeze, "Gemfile".freeze, "LICENSE".freeze, "README.md".freeze, "Rakefile".freeze, "VERSION".freeze, "bin/search_it".freeze, "lib/search_ui.rb".freeze, "lib/search_ui/search.rb".freeze, "lib/search_ui/version.rb".freeze, "lib/search_ui/wrapper.rb".freeze, "search_ui.gemspec".freeze, "spec/search_ui/wrapper_spec.rb".freeze, "spec/spec_helper.rb".freeze]
16
+ s.files = [".rspec".freeze, "Gemfile".freeze, "LICENSE".freeze, "README.md".freeze, "Rakefile".freeze, "VERSION".freeze, "bin/search_it".freeze, "lib/search_ui.rb".freeze, "lib/search_ui/search.rb".freeze, "lib/search_ui/version.rb".freeze, "lib/search_ui/wrapper.rb".freeze, "search_ui.gemspec".freeze, "spec/search_ui/search_spec.rb".freeze, "spec/search_ui/wrapper_spec.rb".freeze, "spec/spec_helper.rb".freeze]
17
17
  s.homepage = "https://github.com/flori/search_ui".freeze
18
18
  s.licenses = ["MIT".freeze]
19
19
  s.rdoc_options = ["--title".freeze, "SearchUI -- Search User Interface".freeze, "--main".freeze, "README.md".freeze]
20
20
  s.required_ruby_version = Gem::Requirement.new(">= 2.0".freeze)
21
21
  s.rubygems_version = "4.0.24".freeze
22
22
  s.summary = "Library to provide a user interface for searching in a console".freeze
23
- s.test_files = ["spec/search_ui/wrapper_spec.rb".freeze, "spec/spec_helper.rb".freeze]
23
+ s.test_files = ["spec/search_ui/search_spec.rb".freeze, "spec/search_ui/wrapper_spec.rb".freeze, "spec/spec_helper.rb".freeze]
24
24
 
25
25
  s.specification_version = 4
26
26
 
@@ -0,0 +1,84 @@
1
+ require 'spec_helper'
2
+
3
+ describe SearchUI::Search do
4
+ let(:height) { 5 }
5
+ let(:items) { (1..20).map(&:to_s) }
6
+
7
+ let(:search) do
8
+ described_class.new(
9
+ height: height,
10
+ match: -> _answer { items },
11
+ query: -> _a, _m, _s { '' },
12
+ found: -> _a, _m, _s { nil }
13
+ )
14
+ end
15
+
16
+ def set_state(search, matches, selector)
17
+ search.instance_variable_set(:@matches, matches)
18
+ search.state.selector = selector
19
+ end
20
+
21
+ describe '#adjust_offset' do
22
+ it 'keeps offset at 0 when list fits in the viewport' do
23
+ set_state(search, (1..3).map(&:to_s), 2)
24
+ search.send(:adjust_offset)
25
+ expect(search.instance_variable_get(:@offset)).to eq 0
26
+ end
27
+
28
+ it 'slides the window down when the selector crosses the bottom edge' do
29
+ set_state(search, items, 4) # last visible row (0-indexed)
30
+ search.send(:adjust_offset) # offset still 0
31
+ expect(search.instance_variable_get(:@offset)).to eq 0
32
+
33
+ search.state.selector = 5 # crossed the edge
34
+ search.send(:adjust_offset)
35
+ expect(search.instance_variable_get(:@offset)).to eq 1
36
+ end
37
+
38
+ it 'slides the window up when the selector crosses the top edge' do
39
+ search.instance_variable_set(:@matches, items)
40
+ search.instance_variable_set(:@offset, 10)
41
+ search.state.selector = 9 # one above the window
42
+ search.send(:adjust_offset)
43
+ expect(search.instance_variable_get(:@offset)).to eq 9
44
+ end
45
+
46
+ it 'does not move the window on wobble within the visible range' do
47
+ search.instance_variable_set(:@matches, items)
48
+ search.instance_variable_set(:@offset, 5)
49
+ search.state.selector = 9 # bottom of window (5+5-1=9)
50
+ search.send(:adjust_offset)
51
+ expect(search.instance_variable_get(:@offset)).to eq 5
52
+
53
+ search.state.selector = 6 # still inside window
54
+ search.send(:adjust_offset)
55
+ expect(search.instance_variable_get(:@offset)).to eq 5
56
+ end
57
+
58
+ it 'clamps offset when the match list shrinks' do
59
+ search.instance_variable_set(:@offset, 15)
60
+ set_state(search, (1..8).map(&:to_s), 0)
61
+ search.send(:adjust_offset)
62
+ expect(search.instance_variable_get(:@offset)).to eq 0
63
+ end
64
+ end
65
+
66
+ describe '#viewport' do
67
+ it 'returns the full list and absolute index when list fits' do
68
+ set_state(search, (1..3).map(&:to_s), 1)
69
+ search.send(:adjust_offset)
70
+ slice, relative = search.send(:viewport)
71
+ expect(slice).to eq %w[1 2 3]
72
+ expect(relative).to eq 1
73
+ end
74
+
75
+ it 'returns a windowed slice with relative cursor' do
76
+ search.instance_variable_set(:@matches, items)
77
+ search.instance_variable_set(:@offset, 7)
78
+ search.state.selector = 10
79
+ slice, relative = search.send(:viewport)
80
+ expect(slice).to eq %w[8 9 10 11 12]
81
+ expect(relative).to eq 3
82
+ end
83
+ end
84
+ end
@@ -19,6 +19,28 @@ describe SearchUI::Wrapper do
19
19
  wrapper = described_class.new(value)
20
20
  expect(wrapper.to_s).to eq 'foo'
21
21
  end
22
+ context 'with a Proc display' do
23
+ it 'calls with no args when arity is 0' do
24
+ wrapper = described_class.new(value, display: -> { '🟢 custom' })
25
+ expect(wrapper.to_s).to eq '🟢 custom'
26
+ end
27
+
28
+ it 'calls with the value when arity is positive' do
29
+ wrapper = described_class.new(
30
+ value,
31
+ display: ->(v) { "🔵 #{v.upcase}" }
32
+ )
33
+ expect(wrapper.to_s).to eq '🔵 FOO'
34
+ end
35
+
36
+ it 'calls with the value when arity is negative (splat)' do
37
+ wrapper = described_class.new(
38
+ value,
39
+ display: ->(*args) { "🟡 #{args.first}" }
40
+ )
41
+ expect(wrapper.to_s).to eq '🟡 foo'
42
+ end
43
+ end
22
44
 
23
45
  it 'delegates methods to the wrapped value (e.g., length)' do
24
46
  expect(sw1.length).to eq 3
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: search_ui
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Florian Frank
@@ -134,6 +134,7 @@ files:
134
134
  - lib/search_ui/version.rb
135
135
  - lib/search_ui/wrapper.rb
136
136
  - search_ui.gemspec
137
+ - spec/search_ui/search_spec.rb
137
138
  - spec/search_ui/wrapper_spec.rb
138
139
  - spec/spec_helper.rb
139
140
  homepage: https://github.com/flori/search_ui
@@ -162,5 +163,6 @@ rubygems_version: 4.0.24
162
163
  specification_version: 4
163
164
  summary: Library to provide a user interface for searching in a console
164
165
  test_files:
166
+ - spec/search_ui/search_spec.rb
165
167
  - spec/search_ui/wrapper_spec.rb
166
168
  - spec/spec_helper.rb