tam_select 1.2.4 → 1.4.1

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.
data/README.md CHANGED
@@ -1,311 +1,398 @@
1
- # Tam Select
1
+ # tam-select
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/tam-select.svg)](https://www.npmjs.com/package/tam-select)
3
4
  [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
4
- [![Gem Version](https://img.shields.io/badge/version-1.2.3-blue.svg)](https://github.com/tamiru/tam_select)
5
+ [![CI](https://github.com/tamiru/tam_select/actions/workflows/ci.yml/badge.svg)](https://github.com/tamiru/tam_select/actions)
5
6
 
6
- **Tam Select** is an accessible, searchable select component for Ruby on Rails, built for Simple Form, Stimulus, Turbo, and Tailwind CSS. It keeps the native `<select>` as the source of truth, so Rails form submission, validation, selected values, and browser autofill continue to work.
7
+ Accessible, searchable select component. Keeps the native `<select>` as the source of truth — form submission, validation, and autofill continue to work. Zero dependencies.
7
8
 
8
- ## Requirements
9
+ **[Live Playground](examples/playground.html)** · **[Rails Guide](#rails-integration)** · **[API Reference](#options)**
9
10
 
10
- - Ruby 3.2 or newer
11
- - Rails 8
12
- - Stimulus 3.2 or newer
13
- - Tailwind CSS 4
14
- - Simple Form when using the `TamSelectInput` integration
11
+ ---
15
12
 
16
- ## Rails installation
17
-
18
- Add the gem directly from GitHub:
19
-
20
- ```ruby
21
- # Gemfile
22
- gem "tam_select", github: "tamiru/tam_select"
23
- ```
24
-
25
- Install the dependency and generate the Rails integration files:
13
+ ## Install
26
14
 
27
15
  ```bash
28
- bundle install
29
- bin/rails generate tam_select:install
16
+ npm install tam-select
17
+ # or
18
+ bun add tam-select
30
19
  ```
31
20
 
32
- The generator installs the core module, Stimulus controller, Rails helpers, and remote-search concerns:
21
+ ## Quick Start
33
22
 
34
- ```text
35
- app/javascript/tam_select/tam_select.js
36
- app/javascript/controllers/tam_select_controller.js
37
- app/controllers/concerns/tam_select_paginatable.rb
38
- app/controllers/concerns/tam_select_remote.rb
39
- app/controllers/tam_select_remote_controller.rb
40
- app/helpers/tam_select_helper.rb
41
- ```
23
+ ```html
24
+ <select id="my-select">
25
+ <option value="">Choose a fruit…</option>
26
+ <option value="apple">Apple</option>
27
+ <option value="banana">Banana</option>
28
+ <option value="cherry">Cherry</option>
29
+ </select>
42
30
 
43
- When Simple Form is present, it also installs `app/inputs/tam_select_input.rb`. Simple Form is optional; applications without it receive a short skip message and continue with standard Rails form helpers.
31
+ <script type="module">
32
+ import TamSelect from "tam-select"
44
33
 
45
- Commit these generated files with the Rails application. This makes customization straightforward and allows Tailwind CSS 4 to scan the component without resolving a Ruby gem directory at build time.
34
+ new TamSelect(document.getElementById("my-select"), {
35
+ searchable: true,
36
+ clearable: true,
37
+ placeholder: "Choose a fruit…"
38
+ })
39
+ </script>
40
+ ```
46
41
 
47
- ### Rails 8 importmap
42
+ ## Features
48
43
 
49
- The default Rails 8 importmap setup needs no manual JavaScript package installation. The generator adds this pin to `config/importmap.rb`:
44
+ - Single and multi-select with inline tags
45
+ - Filter-aware bulk selection, live selection counts, and optional hidden selections
46
+ - Ranked fuzzy search with highlighted matches
47
+ - Remote API search with debouncing and pagination
48
+ - Option groups with section headers
49
+ - Smooth dropdown animations (11 built-in presets)
50
+ - Virtual scrolling for 1000+ items
51
+ - RTL support (Arabic, Hebrew, mixed direction)
52
+ - Custom transports for GraphQL and authenticated APIs
53
+ - Keyboard navigation: arrows, Enter, Escape, Tab, Home, End, Ctrl+A
54
+ - Combobox ARIA semantics
55
+ - Light and dark themes
56
+ - Customizable via Tailwind classes
57
+ - No jQuery, Tom Select, Select2, or Floating UI dependency
58
+
59
+ ## Theming
60
+
61
+ Tam Select ships with two built-in themes:
62
+
63
+ | Theme | Style |
64
+ |---|---|
65
+ | `"default"` | Zinc palette, blue focus, subtle hover |
66
+ | `"select2"` | Gray palette, blue hover fill, bordered tags |
50
67
 
51
- ```ruby
52
- pin "tam_select", to: "tam_select/tam_select.js"
68
+ ```js
69
+ new TamSelect(select, { theme: "select2" })
53
70
  ```
54
71
 
55
- The generated Stimulus controller imports `TamSelect` from `"tam_select"`. Running the generator again updates an old pin when necessary and never adds a duplicate. Rails' normal `pin_all_from "app/javascript/controllers", under: "controllers"` line discovers the generated controller.
72
+ ### Custom themes
56
73
 
57
- ### jsbundling-rails and esbuild
74
+ Override any class group via the `classes` option:
58
75
 
59
- The same generated controller works with esbuild when the bare `tam_select` import is aliased to the generated core file. Add the alias flag to the existing `build` script in `package.json`:
60
-
61
- ```json
62
- {
63
- "scripts": {
64
- "build": "esbuild app/javascript/*.* --bundle --sourcemap --format=esm --outdir=app/assets/builds --public-path=/assets --alias:tam_select=./app/javascript/tam_select/tam_select.js"
76
+ ```js
77
+ new TamSelect(select, {
78
+ classes: {
79
+ control: "h-10 rounded-lg border-2 border-indigo-500 bg-white",
80
+ option: "px-4 py-3 hover:bg-indigo-50"
65
81
  }
66
- }
82
+ })
67
83
  ```
68
84
 
69
- This uses the local file installed by the generator. For non-Rails bundler use, install the npm package from GitHub and import its published package name instead:
85
+ ### Dark mode
70
86
 
71
- ```bash
72
- npm install github:tamiru/tam_select
87
+ Tam Select follows the `dark` class on the document:
88
+
89
+ ```js
90
+ document.documentElement.classList.toggle("dark")
73
91
  ```
74
92
 
93
+ ## Remote Search
94
+
75
95
  ```js
76
- import TamSelect from "tam-select"
96
+ new TamSelect(select, {
97
+ remoteUrl: "/api/users",
98
+ queryParam: "q",
99
+ minQueryLength: 2,
100
+ debounce: 300,
101
+ processResults: (data) => ({
102
+ items: data.users.map(u => ({
103
+ value: u.id,
104
+ label: u.name,
105
+ detail: u.email,
106
+ meta: u.role
107
+ })),
108
+ pagination: { has_more: data.total > data.page * 20 }
109
+ })
110
+ })
77
111
  ```
78
112
 
79
- Add the generated JavaScript to Tailwind's source detection in `app/assets/tailwind/application.css`:
113
+ ### Custom transport
80
114
 
81
- ```css
82
- @import "tailwindcss";
83
- @source "../../javascript/tam_select/**/*.js";
115
+ ```js
116
+ new TamSelect(select, {
117
+ transport: async ({ url, query, signal }) => {
118
+ const res = await fetch(url, {
119
+ headers: { Authorization: `Bearer ${token}` },
120
+ signal
121
+ })
122
+ return res.json()
123
+ },
124
+ processResults: (data) => ({
125
+ items: data.nodes.map(n => ({ value: n.id, label: n.name })),
126
+ pagination: { has_more: data.pageInfo.hasNextPage }
127
+ })
128
+ })
84
129
  ```
85
130
 
86
- ### Upgrading
131
+ ## Virtual Scroll
87
132
 
88
- The Rails integration files are copied into your application, so updating the gem does not update them automatically. Commit local customizations first, then run:
133
+ For large datasets, enable virtual scrolling to render only visible options:
89
134
 
90
- ```bash
91
- bundle update tam_select
92
- bin/rails generate tam_select:install
135
+ ```js
136
+ new TamSelect(select, {
137
+ virtualScroll: true,
138
+ virtualItemHeight: 32
139
+ })
93
140
  ```
94
141
 
95
- Rails prompts before replacing changed files. To replace every generated file without prompting, use:
142
+ Auto-enables when visible items exceed `virtualScrollThreshold` (default: 100).
96
143
 
97
- ```bash
98
- bin/rails generate tam_select:install --force
144
+ ## Advanced Multi-select
145
+
146
+ ```js
147
+ new TamSelect(select, {
148
+ bulkActions: true,
149
+ showSelectionCount: true,
150
+ hideSelected: true,
151
+ maximumSelectionLength: 10
152
+ })
99
153
  ```
100
154
 
101
- Review `git diff` afterward because `--force` overwrites application-specific customizations.
155
+ The dropdown displays count-aware **Select all** and **Clear** actions with
156
+ icons, a Ctrl/⌘-A shortcut hint, and a live selected-count badge (for example,
157
+ `3 / 10 selected`). Actions apply to the current search,
158
+ preserve its text, skip disabled options and groups, and respect cancelable
159
+ `selecting` / `unselecting` events. Selections outside the search stay unchanged.
160
+ With `hideSelected`, Clear still includes matching selected items that
161
+ are hidden from the results. Empty group headings disappear automatically.
102
162
 
103
- Versions before this release generated a relative controller import. After upgrading, confirm the controller uses `import TamSelect from "tam_select"` and that the importmap pin or esbuild alias above is present.
163
+ Remote actions affect only loaded results; they never fetch or select unseen
164
+ pages. Virtual scrolling selects all loaded matches, including rows outside the
165
+ rendered viewport. Each bulk action emits one native `change`, one
166
+ `tam-select:change`, per-item completion events, and a `tam-select:bulk-change`
167
+ event with `{ action, items, value }`. No-op actions emit nothing.
104
168
 
105
- ## Features
169
+ Tab moves from the search field to the action buttons; Shift+Tab returns to
170
+ search and Escape closes the dropdown. Search remains available when the
171
+ selection limit is reached. Composition-based keyboards can finish entering
172
+ text before filtering or creating tags.
106
173
 
107
- - Single and multiple selection
108
- - Local search and user-created tags
109
- - Remote JSON search with debouncing and incremental pagination
110
- - Loading, empty, and error states
111
- - Select2-style closed selection and open search states with clear active, selected, disabled, loading, empty, and error feedback
112
- - Keyboard navigation: arrows, Enter, Escape, Tab, and Backspace
113
- - Combobox/listbox ARIA semantics
114
- - Light and dark Tailwind themes
115
- - Rails 8, Turbo, Turbo Frames, Stimulus, and Simple Form integration
116
- - Public API and bubbling custom events
117
- - No jQuery, Tom Select, Select2, Preline, or Floating UI dependency
174
+ Localize the toolbar through `language.selectAll`, `language.deselectAll`, and
175
+ `language.selectionCount` (a string or `(count, limit) => string`). Override its
176
+ appearance with `classes.selectionToolbar`, `classes.selectionAction`, and
177
+ `classes.selectionCount`. These multi-select UI features are opt-in and do not
178
+ change single-select controls.
118
179
 
119
- ## Tailwind CSS 4
180
+ ## Animations
120
181
 
121
- Add the package source to `app/assets/tailwind/application.css` so Tailwind generates every class used by the JavaScript templates:
182
+ Choose a preset:
122
183
 
123
- ```css
124
- @import "tailwindcss";
125
- @source "../../../node_modules/tam-select/src/**/*.js";
126
- @source "../../../node_modules/tam-select/rails/**/*.js";
127
- ```
184
+ ```js
185
+ new TamSelect(select, { animationPreset: "spring" })
186
+ ```
187
+
188
+ | Preset | Duration | Feel |
189
+ |---|---|---|
190
+ | `"default"` | 150ms | Standard |
191
+ | `"material"` | 250ms | Material Design |
192
+ | `"spring"` | 400ms | Bouncy overshoot |
193
+ | `"bounce"` | 500ms | Overshoot bounce |
194
+ | `"elastic"` | 600ms | Wide spring |
195
+ | `"snappy"` | 100ms | Fast, responsive |
196
+ | `"smooth"` | 300ms | Gentle ease |
197
+ | `"fade"` | 200ms | Simple opacity |
198
+ | `"pop"` | 200ms | Quick pop-in |
199
+ | `"slide"` | 250ms | Smooth deceleration |
200
+ | `"none"` | 0ms | Instant |
201
+
202
+ ## Options
203
+
204
+ | Option | Default | Description |
205
+ |---|---:|---|
206
+ | `searchable` | `true` | Enable text filtering |
207
+ | `creatable` | `false` | Allow typed values to become options |
208
+ | `clearable` | `true` | Show clear button (single selects need an empty `value=""` option) |
209
+ | `closeAfterSelect` | `true` (single) | Close dropdown after selection |
210
+ | `placeholder` | `"Select…"` | Placeholder text |
211
+ | `remoteUrl` | `null` | Remote search endpoint |
212
+ | `minQueryLength` | `0` | Characters before remote search |
213
+ | `debounce` | `250` | Remote request delay (ms) |
214
+ | `maximumSelectionLength` | `0` | Max selectable items (0 = unlimited) |
215
+ | `bulkActions` | `false` | Show count-aware Select all / Clear actions on multi-selects |
216
+ | `showSelectionCount` | `false` | Show live selected count and configured limit |
217
+ | `hideSelected` | `false` | Hide selected results from the option list (single or multiple) |
218
+ | `theme` | `"auto"` | `"default"`, `"select2"`, or `"auto"` |
219
+ | `classes` | `{}` | Override any Tailwind class group |
220
+ | `animationPreset` | `null` | Built-in animation preset |
221
+ | `virtualScroll` | `false` | Enable virtual scrolling |
222
+ | `virtualItemHeight` | `32` | Row height for virtual scroll |
223
+ | `wrapOptionText` | automatic | Wrap ordinary result labels/details; set `true` to wrap even large lists (disables fixed-height virtualization), or `false` to truncate |
224
+ | `optionTooltip` | `true` | Show full option text in native hover tooltips |
225
+ | `fuzzySearch` | `true` | Tolerate typing mistakes |
226
+ | `highlightMatches` | `true` | Highlight search matches |
227
+ | `sortByRelevance` | `true` | Rank strong matches first |
228
+ | `dropdownParent` | `null` | Portal target used to escape clipped containers |
229
+ | `width` | `"resolve"` | `"resolve"` fills the container (or uses the native select's inline `style="width: …"`); `"auto"` sizes the control to its widest option like a native select; or any CSS width |
230
+ | `dropdownWidth` | `"auto"` | `"auto"` is at least the control's width and grows to fit the widest option, like a native select; `"trigger"` always matches the control (`"content"` aliases `"auto"`) |
231
+ | `maxDropdownWidth` | `480` | Widest an `"auto"` menu grows (px) before long options wrap; never narrower than the control, and always kept inside the viewport |
232
+ | `maxDropdownHeight` | `360` | Maximum menu height before results scroll |
233
+ | `viewportPadding` | `8` | Space kept between a portaled menu and viewport edges |
234
+
235
+ ## API
236
+
237
+ ```js
238
+ const instance = new TamSelect(select, options)
128
239
 
129
- When the Rails generator is used, scan the generated component source:
240
+ instance.open() // Open dropdown
241
+ instance.close() // Close dropdown
242
+ instance.focus() // Focus search input
243
+ instance.blur() // Remove focus
244
+ instance.setValue("apple") // Set selected value
245
+ instance.clear() // Clear all selections
246
+ instance.selectAll() // Select loaded matches within the selection limit
247
+ instance.deselectAll() // Deselect loaded matches, preserving other selections
248
+ instance.refresh() // Re-read native options
249
+ instance.addData({ value: "new", label: "New" }) // Add option
250
+ instance.removeData("old") // Remove option
251
+ instance.clearRemoteCache() // Clear cached responses
252
+ instance.destroy() // Remove all generated markup
130
253
 
131
- ```css
132
- @source "../../javascript/tam_select/**/*.js";
254
+ // Read current value
255
+ instance.value // "apple" or ["apple", "banana"]
256
+
257
+ // Get existing instance
258
+ TamSelect.getInstance(select)
133
259
  ```
134
260
 
135
- Tam Select includes adaptive light and dark styles for every state. It follows a `dark` class on the document or any ancestor and also sets the appropriate native `color-scheme`:
261
+ ## Events
262
+
263
+ All events bubble on the original `<select>`:
136
264
 
137
265
  ```js
138
- document.documentElement.classList.toggle("dark")
266
+ select.addEventListener("tam-select:change", (e) => console.log(e.detail.value))
267
+ select.addEventListener("tam-select:open", () => console.log("opened"))
268
+ select.addEventListener("tam-select:close", () => console.log("closed"))
269
+ select.addEventListener("tam-select:select", (e) => console.log(e.detail.item))
270
+ select.addEventListener("tam-select:create", (e) => console.log(e.detail.item))
271
+ select.addEventListener("tam-select:error", (e) => console.error(e.detail.error))
272
+ select.addEventListener("tam-select:bulk-change", (e) => console.log(e.detail.action, e.detail.items))
139
273
  ```
140
274
 
141
- For Tailwind CSS 4 class-based theming, define the variant in the application stylesheet if it is not already present:
275
+ Cancelable: `opening`, `closing`, `selecting`, `unselecting`, `clearing`, `creating`.
142
276
 
143
- ```css
144
- @custom-variant dark (&:where(.dark, .dark *));
145
- ```
277
+ ---
146
278
 
147
- ## Standard Rails forms and Stimulus
279
+ ## Rails Integration
148
280
 
149
- The install generator copies the Stimulus controller into your application, where Stimulus normally discovers it automatically. If controllers are registered manually:
281
+ ### Installation
150
282
 
151
- ```js
152
- import TamSelectController from "./tam_select_controller"
153
- application.register("tam-select", TamSelectController)
283
+ ```ruby
284
+ # Gemfile
285
+ gem "tam_select", github: "tamiru/tam_select"
154
286
  ```
155
287
 
156
- Use a normal Rails select:
288
+ ```bash
289
+ bundle install
290
+ bin/rails generate tam_select:install
291
+ ```
157
292
 
158
- ```erb
159
- <%= form.select :region_id,
160
- options_from_collection_for_select(Region.order(:name), :id, :name, form.object.region_id),
161
- { prompt: "Select region" },
162
- data: {
163
- controller: "tam-select",
164
- tam_select_options_value: {
165
- searchable: true,
166
- placeholder: "Select region…"
167
- }.to_json
168
- } %>
293
+ With importmap, the gem serves everything itself: the JavaScript, the
294
+ `tam-select` Stimulus controller, `TamSelectHelper`, the Simple Form input
295
+ (when Simple Form is installed), and the `TamSelectPaginatable` and
296
+ `TamSelectRemote` concerns. The generator adds one line to
297
+ `app/assets/tailwind/application.css` so Tailwind (tailwindcss-rails 4.4+)
298
+ finds the classes Tam Select renders:
299
+
300
+ ```css
301
+ @import "tailwindcss";
302
+ @import "../builds/tailwind/tam_select";
169
303
  ```
170
304
 
171
- Stimulus destroys generated markup when Turbo removes the select and recreates it on reconnection.
305
+ With jsbundling (esbuild and similar), the generator adds the `tam-select`
306
+ npm package to `package.json` and a one-line controller that re-exports it.
307
+ Run your package manager's install, then `bin/rails stimulus:manifest:update`
308
+ if you use a controllers manifest. For Tailwind, add an `@source` for
309
+ `node_modules/tam-select/src` to your CSS entry point.
172
310
 
173
- For multiple selection, Rails must receive an array field and the native select must include `multiple: true`:
311
+ ### Every select as a Tam Select
174
312
 
175
- ```erb
176
- <%= form.select :skill_ids,
177
- options_from_collection_for_select(Skill.order(:name), :id, :name, form.object.skill_ids),
178
- {},
179
- multiple: true,
180
- data: {
181
- controller: "tam-select",
182
- tam_select_options_value: {
183
- searchable: true,
184
- closeAfterSelect: false,
185
- placeholder: "Add skills…"
186
- }.to_json
187
- } %>
313
+ The generated `config/initializers/tam_select.rb` enables:
314
+
315
+ ```ruby
316
+ config.tam_select.default_select = true
188
317
  ```
189
318
 
190
- The original `<select>` remains the source of truth. This preserves form names in nested forms, submitted values, prompts, `required`, validation metadata, and native `change` events.
319
+ With it, every select is a Tam Select without changing views: Simple Form's
320
+ `f.input :region, collection: ...` and `as: :select`, and Rails'
321
+ `select_tag`, `f.select`, `collection_select` and `grouped_collection_select`.
322
+ Single selects get a blank option (so they can be cleared and show their
323
+ placeholder) unless you pass `include_blank` or `prompt`, or the choices
324
+ already contain one. Keep a field native with `data: { tam_select: false }`
325
+ (for Simple Form: `input_html: { data: { tam_select: false } }`).
191
326
 
192
- ## Simple Form
327
+ ### Updating
193
328
 
194
- When the `simple_form` gem is installed, the generator creates `app/inputs/tam_select_input.rb`. Use `as: :tam_select` with any Simple Form collection input. The input forwards Simple Form's prompt, selected values, multiple flag, error classes, ARIA attributes, and nested builder context to the native collection select.
329
+ ```bash
330
+ bundle update tam_select # importmap
331
+ bundle update tam_select && npm update tam-select # jsbundling
332
+ ```
195
333
 
196
- ### Local collection
334
+ Nothing is copied into your app, so there is nothing else to update. To
335
+ customize a piece, add a file with the same path to your app (for example
336
+ `app/helpers/tam_select_helper.rb` or
337
+ `app/javascript/controllers/tam_select_controller.js`); the app's file wins
338
+ over the gem's.
197
339
 
198
- ```erb
199
- <%= form.input :region_id,
200
- as: :tam_select,
201
- collection: Region.order(:name),
202
- label_method: :name,
203
- value_method: :id,
204
- prompt: "Select region" %>
340
+ #### Upgrading from 1.3 or earlier
341
+
342
+ Earlier versions copied every file into the app. Run this once:
343
+
344
+ ```bash
345
+ bundle update tam_select
346
+ bin/rails generate tam_select:update
205
347
  ```
206
348
 
207
- ### Remote collection
349
+ It removes each copied file you never changed, and the old `tam_select` pin
350
+ or esbuild alias, so the gem's versions load instead. Files you changed are
351
+ kept and listed; they keep overriding the gem's version until you delete them.
208
352
 
209
- Keep the currently selected record in the initial collection so edit forms can display its label before the AJAX request completes:
353
+ ### Usage
210
354
 
211
355
  ```erb
212
- <%= form.input :region_id,
213
- as: :tam_select,
214
- collection: [form.object.region].compact,
215
- label_method: :name,
216
- value_method: :id,
217
- prompt: "Select region",
218
- input_html: {
219
- tam_options: {
220
- remoteUrl: tam_select_options_regions_path(format: :json),
221
- minQueryLength: 1,
222
- debounce: 250
223
- }
356
+ <%= form.select :region_id,
357
+ options_from_collection_for_select(Region.order(:name), :id, :name),
358
+ { prompt: "Select region" },
359
+ data: {
360
+ controller: "tam-select",
361
+ tam_select_options_value: { placeholder: "Search…" }.to_json
224
362
  } %>
225
363
  ```
226
364
 
227
- The concern and route required by this example are described in [Add remote search to an existing controller](#add-remote-search-to-an-existing-controller).
228
-
229
- ### Multiple selection
365
+ ### Simple Form
230
366
 
231
367
  ```erb
232
- <%= form.input :skill_ids,
368
+ <%= form.input :region_id,
233
369
  as: :tam_select,
234
- collection: Skill.order(:name),
370
+ collection: Region.order(:name),
235
371
  label_method: :name,
236
372
  value_method: :id,
237
- input_html: {
238
- multiple: true,
239
- tam_options: {
240
- searchable: true,
241
- closeAfterSelect: false
242
- }
243
- } %>
244
- ```
245
-
246
- Options are passed under `input_html[:tam_options]`. Common options include `searchable`, `creatable`, `clearable`, `placeholder`, `searchPlaceholder`, `remoteUrl`, `minQueryLength`, and `debounce`. See [Main options](#main-options) for defaults.
247
-
248
- ## Remote API contract
249
-
250
- `tam-select` sends `q` and `page` query parameters and expects:
251
-
252
- ```json
253
- {
254
- "items": [
255
- { "value": "1", "label": "Hana Bekele", "detail": "Admission no. UG/1024/26", "meta": "Active", "image": "/avatars/hana.jpg" },
256
- { "value": "2", "label": "Afar", "detail": "Semera", "meta": "AF" }
257
- ],
258
- "pagination": {
259
- "page": 1,
260
- "next_page": 2,
261
- "has_more": true
262
- }
263
- }
373
+ prompt: "Select region" %>
264
374
  ```
265
375
 
266
- The generator installs `TamSelectPaginatable` as a Rails response helper. A complete Region controller is available in [`examples/regions_controller.rb`](examples/regions_controller.rb).
267
-
268
- Secure remote endpoints exactly like other Rails JSON endpoints. Scope records by the current user's permissions and never trust a submitted value merely because it appeared in the dropdown.
269
-
270
- ### Add remote search to an existing controller
271
-
272
- Include `TamSelectRemote` and declare the allowed model and searchable fields. This adds the public `tam_select_options` action to the controller:
376
+ ### Remote search
273
377
 
274
378
  ```ruby
275
- # app/controllers/regions_controller.rb
276
379
  class RegionsController < ApplicationController
277
380
  include TamSelectRemote
278
381
 
279
382
  tam_select_remote(
280
383
  model: Region,
281
384
  label: :name,
282
- value: :id,
283
385
  detail: :description,
284
- meta: :code,
285
386
  search_by: %i[name code],
286
- scope: -> { Region.order(:name) },
287
- per_page: 20
387
+ scope: -> { Region.order(:name) }
288
388
  )
289
389
  end
290
390
  ```
291
391
 
292
- The optional `scope` lambda runs in the controller context, so it can use `current_user`, `current_account`, or an authorization policy.
293
-
294
- ```ruby
295
- # config/routes.rb
296
- resources :regions do
297
- get :tam_select_options, on: :collection, defaults: { format: :json }
298
- end
299
- ```
300
-
301
- Point Simple Form to that collection action:
302
-
303
392
  ```erb
304
393
  <%= form.input :region_id,
305
394
  as: :tam_select,
306
395
  collection: [form.object.region].compact,
307
- label_method: :name,
308
- value_method: :id,
309
396
  input_html: {
310
397
  tam_options: {
311
398
  remoteUrl: tam_select_options_regions_path(format: :json),
@@ -314,160 +401,58 @@ Point Simple Form to that collection action:
314
401
  } %>
315
402
  ```
316
403
 
317
- Typing sends `GET /regions/tam_select_options.json?q=addis&page=1` and receives the standard Tam Select JSON payload.
404
+ ---
318
405
 
319
- When `pagination.has_more` is true, scrolling near the bottom requests `next_page`. Earlier pages keep their order, duplicate values are collapsed, and a later response can update an existing item's label, metadata, image, or disabled state. A new query aborts the old request and never displays cached results from the previous query.
406
+ ## CI/CD
320
407
 
321
- Remote items may include optional `detail`, `meta`, and `image` fields. Tam Select renders the primary label with the detail on a second line and an optional circular image on the left. The selected value keeps the same image, label, and detail, including an initial value rendered before remote search completes. `meta` remains a badge on the right.
408
+ ### GitHub Actions
322
409
 
323
- This works well for program and student searches. For example, return the program name as `label` and admission as `detail`:
410
+ The CI workflow validates Ruby, JavaScript, TypeScript declarations, and npm package contents on every push.
324
411
 
325
- ```ruby
326
- tam_select_remote(
327
- model: Estudent::Program,
328
- label: :name,
329
- detail: ->(program) { program.admission.to_s },
330
- search_by: %i[name],
331
- scope: -> { Estudent::Program.includes(admission: %i[admission_type enrollment_type enrollment_mode]).order(:name) }
332
- )
333
- ```
412
+ ### Publishing
334
413
 
335
- For student search, add the admission number and photo URL:
414
+ A matching `v*.*.*` tag publishes both the gem and npm package using trusted
415
+ publishing (OIDC), so the repository needs no registry secrets.
336
416
 
337
- ```ruby
338
- tam_select_remote(
339
- model: Estudent::Student,
340
- label: ->(student) { student.full_name },
341
- detail: ->(student) { "Admission no. #{student.applicant.registration_number}" },
342
- image: ->(student) { url_for(student.applicant.person.avatar) if student.applicant.person.avatar.attached? },
343
- search_by: %i[id_number],
344
- scope: -> { Estudent::Student.includes(applicant: { person: { avatar_attachment: :blob } }) }
345
- )
346
- ```
347
-
348
- For a local native select, provide the same values as option data attributes:
349
-
350
- ```erb
351
- <option value="1" data-detail="Admission no. UG/1024/26" data-meta="Active" data-image="/avatars/hana.jpg">Hana Bekele</option>
352
- ```
417
+ **Register a trusted publisher** on [RubyGems](https://rubygems.org/gems/tam_select)
418
+ and [npm](https://www.npmjs.com/package/tam-select) with these values:
353
419
 
354
- The browser sends requests such as:
355
-
356
- ```text
357
- GET /regions/tam_select_options.json?q=addis&page=1
358
- Accept: application/json
359
- ```
360
-
361
- Test an endpoint independently with:
420
+ | Field | Value |
421
+ |---|---|
422
+ | Repository | `tamiru/tam_select` |
423
+ | Workflow | `release.yml` |
424
+ | Environment | `release` |
362
425
 
363
426
  ```bash
364
- curl -H "Accept: application/json" \
365
- "http://localhost:3000/regions/tam_select_options.json?q=addis&page=1"
427
+ # Release: bump the version in lib/tam_select/version.rb, package.json and the
428
+ # lockfiles, then
429
+ git tag v1.4.1
430
+ git push origin v1.4.1
366
431
  ```
367
432
 
368
- A `406 Not Acceptable` response means the route or controller rejected JSON. Keep `defaults: { format: :json }` on the route, use a `.json` URL, and ensure the controller does not restrict responses to HTML only.
369
-
370
- ## Creatable values
371
-
372
- Set `creatable: true` for tag-style input. The Create action is part of the same keyboard list as normal results, so ArrowUp and ArrowDown can highlight it and Enter creates it.
373
-
374
- ```erb
375
- <%= form.select :category_ids,
376
- options_from_collection_for_select(Category.order(:name), :id, :name),
377
- {},
378
- multiple: true,
379
- data: {
380
- controller: "tam-select",
381
- tam_select_options_value: {
382
- creatable: true,
383
- closeAfterSelect: false,
384
- placeholder: "Add categories…"
385
- }.to_json
386
- } %>
387
- ```
388
-
389
- Values and labels are compared with normalized, case-insensitive, accent-insensitive text before creation, preventing duplicate entries such as `Café` and `cafe`. A successful creation dispatches `tam-select:create`.
390
-
391
- ## Keyboard and accessibility behavior
392
-
393
- - ArrowDown and ArrowUp open the list, move through the rendered entries, and skip disabled options.
394
- - Enter selects the highlighted option or activates the highlighted Create action.
395
- - Escape closes the list and returns focus to the combobox; Tab closes without trapping focus.
396
- - Backspace removes the last tag from a multiple select when the search input is empty.
397
- - Searchable controls use an input combobox; non-searchable controls use a focusable button combobox.
398
- - Rails labels, descriptions, required state, disabled state, and invalid state are mirrored from the native select.
399
-
400
- ## Core JavaScript
433
+ If a publish fails, re-run the failed jobs. A version that already reached a
434
+ registry is skipped, so a partial release can be finished safely.
401
435
 
402
- For a generated Rails/importmap installation, use the pinned module name:
436
+ ### Local development
403
437
 
404
- ```js
405
- import TamSelect from "tam_select"
406
-
407
- const instance = new TamSelect(document.querySelector("#student_region_id"), {
408
- searchable: true,
409
- creatable: false,
410
- remoteUrl: "/regions",
411
- minQueryLength: 1
412
- })
413
-
414
- instance.setValue("2")
415
- instance.open()
416
- instance.close()
417
- instance.clear()
418
- instance.refresh()
419
- instance.destroy()
438
+ ```bash
439
+ bundle install
440
+ bundle exec rake test # Ruby tests
441
+ npm test # JavaScript tests
442
+ npm run check # Syntax check
443
+ npm run typecheck # TypeScript declarations
420
444
  ```
421
445
 
422
- When consuming the npm package directly, import from `"tam-select"` instead.
446
+ ## License
423
447
 
424
- ## Main options
448
+ [MIT](LICENSE)
425
449
 
426
- | Option | Default | Purpose |
427
- |---|---:|---|
428
- | `searchable` | `true` | Enables text filtering |
429
- | `creatable` | `false` | Allows typed values to become options |
430
- | `clearable` | `true` | Displays the clear control |
431
- | `closeAfterSelect` | Single only | Keeps multiple dropdowns open |
432
- | `placeholder` | Native prompt or `Select…` | Closed-control placeholder |
433
- | `searchPlaceholder` | `Search…` | Search-input placeholder |
434
- | `remoteUrl` | `null` | JSON search endpoint |
435
- | `queryParam` | `q` | Remote search parameter |
436
- | `pageParam` | `page` | Remote page parameter |
437
- | `debounce` | `250` | Remote request delay in milliseconds |
438
- | `minQueryLength` | `0` | Characters required before requesting |
439
- | `valueField` | `value` | Remote item value key |
440
- | `labelField` | `label` | Remote item label key |
441
- | `imageField` | `image` | Remote item image URL key |
442
- | `matcher` | `null` | Optional `(item, query) => boolean` local matcher |
443
- | `classes` | `{}` | Overrides any Tailwind class group |
450
+ ### Compact sizing and long option text
444
451
 
445
- ## Events
446
-
447
- Listen on the original select. Every event bubbles:
452
+ Controls use a 36px minimum height; simple dropdown options use 32px rows with 14px regular text and 6px vertical padding. Descriptions use 12px text. Long labels and descriptions wrap by default, and rich options grow to fit their content. For large virtualized lists, set `wrapOptionText: true` to show every line:
448
453
 
449
454
  ```js
450
- select.addEventListener("tam-select:change", ({ detail }) => console.log(detail.value))
451
- select.addEventListener("tam-select:open", () => console.log("opened"))
452
- select.addEventListener("tam-select:close", () => console.log("closed"))
453
- select.addEventListener("tam-select:load", ({ detail }) => console.log(detail.items))
454
- select.addEventListener("tam-select:create", ({ detail }) => console.log(detail.item))
455
- select.addEventListener("tam-select:error", ({ detail }) => console.error(detail.error))
456
- ```
457
-
458
- Standard native `change` events are also dispatched for Rails and other controllers.
459
-
460
- The supported public methods are `open()`, `close()`, `setValue(value)`, `clear()`, `refresh()`, and `destroy()`. Read the current native-compatible selection through `instance.value`, and recover an existing instance with `TamSelect.getInstance(select)`.
461
-
462
- ## Development
463
-
464
- ```bash
465
- bundle install
466
- bundle exec rake test
467
- npm test
468
- npm run check
455
+ new TamSelect(select, { wrapOptionText: true })
469
456
  ```
470
457
 
471
- ## License
472
-
473
- Tam Select is available under the [MIT License](LICENSE).
458
+ Wrapping applies to dropdown labels and details in both themes, including long words. Selected values stay on one line. Fixed-height virtual scrolling is disabled when wrapping is enabled. Set `wrapOptionText: false` to keep every result on one line.