tam_select 1.2.5 → 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,314 +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. When Importmap is absent, the installer detects an existing esbuild `build` script in `package.json` and appends the alias automatically:
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
- The update is idempotent, so rerunning the installer does not duplicate the alias. If `package.json` or an esbuild build script is not present, the installer prints the exact alias flag to add manually.
85
+ ### Dark mode
70
86
 
71
- 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:
87
+ Tam Select follows the `dark` class on the document:
72
88
 
73
- ```bash
74
- npm install github:tamiru/tam_select
89
+ ```js
90
+ document.documentElement.classList.toggle("dark")
75
91
  ```
76
92
 
93
+ ## Remote Search
94
+
77
95
  ```js
78
- 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
+ })
79
111
  ```
80
112
 
81
- Add the generated JavaScript to Tailwind's source detection in `app/assets/tailwind/application.css`:
113
+ ### Custom transport
82
114
 
83
- ```css
84
- @import "tailwindcss";
85
- @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
+ })
86
129
  ```
87
130
 
88
- ### Upgrading
131
+ ## Virtual Scroll
89
132
 
90
- 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:
91
134
 
92
- ```bash
93
- bundle update tam_select
94
- bin/rails generate tam_select:install
135
+ ```js
136
+ new TamSelect(select, {
137
+ virtualScroll: true,
138
+ virtualItemHeight: 32
139
+ })
95
140
  ```
96
141
 
97
- Rails prompts before replacing changed files. To replace every generated file without prompting, use:
142
+ Auto-enables when visible items exceed `virtualScrollThreshold` (default: 100).
98
143
 
99
- ```bash
100
- 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
+ })
101
153
  ```
102
154
 
103
- 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.
104
162
 
105
- 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.
106
168
 
107
- ## 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.
108
173
 
109
- - Single and multiple selection
110
- - Local search and user-created tags
111
- - Remote JSON search with debouncing and incremental pagination
112
- - Loading, empty, and error states
113
- - Select2-style closed selection and open search states with clear active, selected, disabled, loading, empty, and error feedback
114
- - Right-aligned select chevron that remains pinned to the control edge for short and default labels
115
- - Keyboard navigation: arrows, Enter, Escape, Tab, and Backspace
116
- - Combobox/listbox ARIA semantics
117
- - Light and dark Tailwind themes
118
- - Rails 8, Turbo, Turbo Frames, Stimulus, and Simple Form integration
119
- - Public API and bubbling custom events
120
- - 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.
121
179
 
122
- ## Tailwind CSS 4
180
+ ## Animations
123
181
 
124
- Add the package source to `app/assets/tailwind/application.css` so Tailwind generates every class used by the JavaScript templates:
182
+ Choose a preset:
125
183
 
126
- ```css
127
- @import "tailwindcss";
128
- @source "../../../node_modules/tam-select/src/**/*.js";
129
- @source "../../../node_modules/tam-select/rails/**/*.js";
130
- ```
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
131
236
 
132
- When the Rails generator is used, scan the generated component source:
237
+ ```js
238
+ const instance = new TamSelect(select, options)
133
239
 
134
- ```css
135
- @source "../../javascript/tam_select/**/*.js";
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
253
+
254
+ // Read current value
255
+ instance.value // "apple" or ["apple", "banana"]
256
+
257
+ // Get existing instance
258
+ TamSelect.getInstance(select)
136
259
  ```
137
260
 
138
- 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>`:
139
264
 
140
265
  ```js
141
- 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))
142
273
  ```
143
274
 
144
- 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`.
145
276
 
146
- ```css
147
- @custom-variant dark (&:where(.dark, .dark *));
148
- ```
277
+ ---
149
278
 
150
- ## Standard Rails forms and Stimulus
279
+ ## Rails Integration
151
280
 
152
- The install generator copies the Stimulus controller into your application, where Stimulus normally discovers it automatically. If controllers are registered manually:
281
+ ### Installation
153
282
 
154
- ```js
155
- import TamSelectController from "./tam_select_controller"
156
- application.register("tam-select", TamSelectController)
283
+ ```ruby
284
+ # Gemfile
285
+ gem "tam_select", github: "tamiru/tam_select"
157
286
  ```
158
287
 
159
- Use a normal Rails select:
288
+ ```bash
289
+ bundle install
290
+ bin/rails generate tam_select:install
291
+ ```
160
292
 
161
- ```erb
162
- <%= form.select :region_id,
163
- options_from_collection_for_select(Region.order(:name), :id, :name, form.object.region_id),
164
- { prompt: "Select region" },
165
- data: {
166
- controller: "tam-select",
167
- tam_select_options_value: {
168
- searchable: true,
169
- placeholder: "Select region…"
170
- }.to_json
171
- } %>
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";
172
303
  ```
173
304
 
174
- 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.
175
310
 
176
- For multiple selection, Rails must receive an array field and the native select must include `multiple: true`:
311
+ ### Every select as a Tam Select
177
312
 
178
- ```erb
179
- <%= form.select :skill_ids,
180
- options_from_collection_for_select(Skill.order(:name), :id, :name, form.object.skill_ids),
181
- {},
182
- multiple: true,
183
- data: {
184
- controller: "tam-select",
185
- tam_select_options_value: {
186
- searchable: true,
187
- closeAfterSelect: false,
188
- placeholder: "Add skills…"
189
- }.to_json
190
- } %>
313
+ The generated `config/initializers/tam_select.rb` enables:
314
+
315
+ ```ruby
316
+ config.tam_select.default_select = true
191
317
  ```
192
318
 
193
- 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 } }`).
194
326
 
195
- ## Simple Form
327
+ ### Updating
196
328
 
197
- 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
+ ```
198
333
 
199
- ### 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.
200
339
 
201
- ```erb
202
- <%= form.input :region_id,
203
- as: :tam_select,
204
- collection: Region.order(:name),
205
- label_method: :name,
206
- value_method: :id,
207
- 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
208
347
  ```
209
348
 
210
- ### 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.
211
352
 
212
- Keep the currently selected record in the initial collection so edit forms can display its label before the AJAX request completes:
353
+ ### Usage
213
354
 
214
355
  ```erb
215
- <%= form.input :region_id,
216
- as: :tam_select,
217
- collection: [form.object.region].compact,
218
- label_method: :name,
219
- value_method: :id,
220
- prompt: "Select region",
221
- input_html: {
222
- tam_options: {
223
- remoteUrl: tam_select_options_regions_path(format: :json),
224
- minQueryLength: 1,
225
- debounce: 250
226
- }
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
227
362
  } %>
228
363
  ```
229
364
 
230
- 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).
231
-
232
- ### Multiple selection
365
+ ### Simple Form
233
366
 
234
367
  ```erb
235
- <%= form.input :skill_ids,
368
+ <%= form.input :region_id,
236
369
  as: :tam_select,
237
- collection: Skill.order(:name),
370
+ collection: Region.order(:name),
238
371
  label_method: :name,
239
372
  value_method: :id,
240
- input_html: {
241
- multiple: true,
242
- tam_options: {
243
- searchable: true,
244
- closeAfterSelect: false
245
- }
246
- } %>
247
- ```
248
-
249
- 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.
250
-
251
- ## Remote API contract
252
-
253
- `tam-select` sends `q` and `page` query parameters and expects:
254
-
255
- ```json
256
- {
257
- "items": [
258
- { "value": "1", "label": "Hana Bekele", "detail": "Admission no. UG/1024/26", "meta": "Active", "image": "/avatars/hana.jpg" },
259
- { "value": "2", "label": "Afar", "detail": "Semera", "meta": "AF" }
260
- ],
261
- "pagination": {
262
- "page": 1,
263
- "next_page": 2,
264
- "has_more": true
265
- }
266
- }
373
+ prompt: "Select region" %>
267
374
  ```
268
375
 
269
- The generator installs `TamSelectPaginatable` as a Rails response helper. A complete Region controller is available in [`examples/regions_controller.rb`](examples/regions_controller.rb).
270
-
271
- 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.
272
-
273
- ### Add remote search to an existing controller
274
-
275
- Include `TamSelectRemote` and declare the allowed model and searchable fields. This adds the public `tam_select_options` action to the controller:
376
+ ### Remote search
276
377
 
277
378
  ```ruby
278
- # app/controllers/regions_controller.rb
279
379
  class RegionsController < ApplicationController
280
380
  include TamSelectRemote
281
381
 
282
382
  tam_select_remote(
283
383
  model: Region,
284
384
  label: :name,
285
- value: :id,
286
385
  detail: :description,
287
- meta: :code,
288
386
  search_by: %i[name code],
289
- scope: -> { Region.order(:name) },
290
- per_page: 20
387
+ scope: -> { Region.order(:name) }
291
388
  )
292
389
  end
293
390
  ```
294
391
 
295
- The optional `scope` lambda runs in the controller context, so it can use `current_user`, `current_account`, or an authorization policy.
296
-
297
- ```ruby
298
- # config/routes.rb
299
- resources :regions do
300
- get :tam_select_options, on: :collection, defaults: { format: :json }
301
- end
302
- ```
303
-
304
- Point Simple Form to that collection action:
305
-
306
392
  ```erb
307
393
  <%= form.input :region_id,
308
394
  as: :tam_select,
309
395
  collection: [form.object.region].compact,
310
- label_method: :name,
311
- value_method: :id,
312
396
  input_html: {
313
397
  tam_options: {
314
398
  remoteUrl: tam_select_options_regions_path(format: :json),
@@ -317,160 +401,58 @@ Point Simple Form to that collection action:
317
401
  } %>
318
402
  ```
319
403
 
320
- Typing sends `GET /regions/tam_select_options.json?q=addis&page=1` and receives the standard Tam Select JSON payload.
404
+ ---
321
405
 
322
- 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
323
407
 
324
- 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
325
409
 
326
- 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.
327
411
 
328
- ```ruby
329
- tam_select_remote(
330
- model: Estudent::Program,
331
- label: :name,
332
- detail: ->(program) { program.admission.to_s },
333
- search_by: %i[name],
334
- scope: -> { Estudent::Program.includes(admission: %i[admission_type enrollment_type enrollment_mode]).order(:name) }
335
- )
336
- ```
412
+ ### Publishing
337
413
 
338
- 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.
339
416
 
340
- ```ruby
341
- tam_select_remote(
342
- model: Estudent::Student,
343
- label: ->(student) { student.full_name },
344
- detail: ->(student) { "Admission no. #{student.applicant.registration_number}" },
345
- image: ->(student) { url_for(student.applicant.person.avatar) if student.applicant.person.avatar.attached? },
346
- search_by: %i[id_number],
347
- scope: -> { Estudent::Student.includes(applicant: { person: { avatar_attachment: :blob } }) }
348
- )
349
- ```
350
-
351
- For a local native select, provide the same values as option data attributes:
352
-
353
- ```erb
354
- <option value="1" data-detail="Admission no. UG/1024/26" data-meta="Active" data-image="/avatars/hana.jpg">Hana Bekele</option>
355
- ```
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:
356
419
 
357
- The browser sends requests such as:
358
-
359
- ```text
360
- GET /regions/tam_select_options.json?q=addis&page=1
361
- Accept: application/json
362
- ```
363
-
364
- Test an endpoint independently with:
420
+ | Field | Value |
421
+ |---|---|
422
+ | Repository | `tamiru/tam_select` |
423
+ | Workflow | `release.yml` |
424
+ | Environment | `release` |
365
425
 
366
426
  ```bash
367
- curl -H "Accept: application/json" \
368
- "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
369
431
  ```
370
432
 
371
- 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.
372
-
373
- ## Creatable values
374
-
375
- 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.
376
-
377
- ```erb
378
- <%= form.select :category_ids,
379
- options_from_collection_for_select(Category.order(:name), :id, :name),
380
- {},
381
- multiple: true,
382
- data: {
383
- controller: "tam-select",
384
- tam_select_options_value: {
385
- creatable: true,
386
- closeAfterSelect: false,
387
- placeholder: "Add categories…"
388
- }.to_json
389
- } %>
390
- ```
391
-
392
- 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`.
393
-
394
- ## Keyboard and accessibility behavior
395
-
396
- - ArrowDown and ArrowUp open the list, move through the rendered entries, and skip disabled options.
397
- - Enter selects the highlighted option or activates the highlighted Create action.
398
- - Escape closes the list and returns focus to the combobox; Tab closes without trapping focus.
399
- - Backspace removes the last tag from a multiple select when the search input is empty.
400
- - Searchable controls use an input combobox; non-searchable controls use a focusable button combobox.
401
- - Rails labels, descriptions, required state, disabled state, and invalid state are mirrored from the native select.
402
-
403
- ## 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.
404
435
 
405
- For a generated Rails/importmap installation, use the pinned module name:
436
+ ### Local development
406
437
 
407
- ```js
408
- import TamSelect from "tam_select"
409
-
410
- const instance = new TamSelect(document.querySelector("#student_region_id"), {
411
- searchable: true,
412
- creatable: false,
413
- remoteUrl: "/regions",
414
- minQueryLength: 1
415
- })
416
-
417
- instance.setValue("2")
418
- instance.open()
419
- instance.close()
420
- instance.clear()
421
- instance.refresh()
422
- 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
423
444
  ```
424
445
 
425
- When consuming the npm package directly, import from `"tam-select"` instead.
446
+ ## License
426
447
 
427
- ## Main options
448
+ [MIT](LICENSE)
428
449
 
429
- | Option | Default | Purpose |
430
- |---|---:|---|
431
- | `searchable` | `true` | Enables text filtering |
432
- | `creatable` | `false` | Allows typed values to become options |
433
- | `clearable` | `true` | Displays the clear control |
434
- | `closeAfterSelect` | Single only | Keeps multiple dropdowns open |
435
- | `placeholder` | Native prompt or `Select…` | Closed-control placeholder |
436
- | `searchPlaceholder` | `Search…` | Search-input placeholder |
437
- | `remoteUrl` | `null` | JSON search endpoint |
438
- | `queryParam` | `q` | Remote search parameter |
439
- | `pageParam` | `page` | Remote page parameter |
440
- | `debounce` | `250` | Remote request delay in milliseconds |
441
- | `minQueryLength` | `0` | Characters required before requesting |
442
- | `valueField` | `value` | Remote item value key |
443
- | `labelField` | `label` | Remote item label key |
444
- | `imageField` | `image` | Remote item image URL key |
445
- | `matcher` | `null` | Optional `(item, query) => boolean` local matcher |
446
- | `classes` | `{}` | Overrides any Tailwind class group |
450
+ ### Compact sizing and long option text
447
451
 
448
- ## Events
449
-
450
- 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:
451
453
 
452
454
  ```js
453
- select.addEventListener("tam-select:change", ({ detail }) => console.log(detail.value))
454
- select.addEventListener("tam-select:open", () => console.log("opened"))
455
- select.addEventListener("tam-select:close", () => console.log("closed"))
456
- select.addEventListener("tam-select:load", ({ detail }) => console.log(detail.items))
457
- select.addEventListener("tam-select:create", ({ detail }) => console.log(detail.item))
458
- select.addEventListener("tam-select:error", ({ detail }) => console.error(detail.error))
459
- ```
460
-
461
- Standard native `change` events are also dispatched for Rails and other controllers.
462
-
463
- 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)`.
464
-
465
- ## Development
466
-
467
- ```bash
468
- bundle install
469
- bundle exec rake test
470
- npm test
471
- npm run check
455
+ new TamSelect(select, { wrapOptionText: true })
472
456
  ```
473
457
 
474
- ## License
475
-
476
- 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.