forked from primer/view_components
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathselect_panel.rb
More file actions
550 lines (501 loc) · 23.9 KB
/
Copy pathselect_panel.rb
File metadata and controls
550 lines (501 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# frozen_string_literal: true
module Primer
module Alpha
# Select panels allow for selecting from a large number of options and can be thought of as a more capable
# version of the traditional HTML `<select>` element.
#
# Select panels:
#
# 1. feature an input field at the top that allows an end user to filter the list of results.
# 1. can render their items statically or dynamically by fetching results from the server.
# 1. allow selecting a single item or multiple items.
# 1. permit leading visuals like Octicons, avatars, and custom SVGs.
# 1. can be used as form inputs in Rails forms.
#
# ## Static list items
#
# The Rails `SelectPanel` component allows items to be provided statically or loaded dynamically from the
# server. Providing items statically is done using a fetch strategy of `:local` in combination with the
# `item` slot:
#
# ```erb
# <%= render(Primer::Alpha::SelectPanel.new(fetch_strategy: :local))) do |panel| %>
# <% panel.with_show_button { "Select item" } %>
# <% panel.with_item(label: "Item 1") %>
# <% panel.with_item(label: "Item 2") %>
# <% end %>
# ```
#
# ## Dynamic list items
#
# List items can also be fetched dynamically from the server and will require creating a Rails controller action
# to respond with the list of items in addition to rendering the `SelectPanel` instance. Render the instance as
# normal, providing your desired [fetch strategy](#fetch-strategies):
#
# ```erb
# <%= render(
# Primer::Alpha::SelectPanel.new(
# fetch_strategy: :remote,
# src: search_items_path # perhaps a Rails URL helper
# )
# ) %>
# ```
#
# Define a controller action to serve the list of items. The `SelectPanel` component passes any filter text in
# the `q=` URL parameter.
#
# ```ruby
# class SearchItemsController < ApplicationController
# def show
# # NOTE: params[:q] may be nil since there is no filter string available
# # when the panel is first opened
# @results = SomeModel.search(params[:q] || "")
# end
# end
# ```
#
# Responses must be HTML fragments, eg. have a content type of `text/html+fragment`. This content type isn't
# available by default in Rails, so you may have to register it eg. in an initializer:
#
# ```ruby
# Mime::Type.register("text/fragment+html", :html_fragment)
# ```
#
# Render a `Primer::Alpha::SelectPanel::ItemList` in the action's template, search_items/show.html_fragment.erb:
#
# ```erb
# <%= render(Primer::Alpha::SelectPanel::ItemList.new) do |list| %>
# <% @results.each do |result| %>
# <% list.with_item(label: result.title) do |item| %>
# <% item.with_description(result.description) %>
# <% end %>
# <% end %>
# <% end %>
# ```
#
# ### Selection consistency
#
# The `SelectPanel` component automatically "remembers" which items have been selected across item fetch requests,
# meaning the controller that renders dynamic list items does not (and should not) remember these selections or
# persist them until the user has confirmed them, either by submitting the form or otherwise indicating completion.
# The `SelectPanel` component does not include unconfirmed selection data in requests.
#
# ## Fetch strategies
#
# The list of items can be fetched from a remote URL, or provided as a static list, configured using the
# `fetch_strategy` attribute. Fetch strategies are summarized below.
#
# 1. `:remote`: a query is made to the URL in the `src` attribute every time the input field changes.
#
# 2. `:eventually_local`: a query is made to the URL in the `src` attribute when the panel is first opened. The
# results are "remembered" and filtered in-memory for all subsequent filter operations, i.e. when the input
# field changes.
#
# 3. `:local`: the list of items is provided statically ahead of time and filtered in-memory. No requests are made
# to the server.
#
# ## Customizing filter behavior
#
# If the fetch strategy is `:remote`, then filtering is handled server-side. The server should render a
# `Primer::Alpha::SelectPanel::ItemList` (an alias of <%= link_to_component(Primer::Alpha::ActionList) %>)
# in the response containing the filtered list of items. The component achieves remote fetching via the
# [remote-input-element](https://github.com/github/remote-input-element), which sends a request to the
# server with the filter string in the `q=` parameter. Responses must be HTML fragments, eg. have a content
# type of `text/html+fragment`.
#
# ### Local filtering
#
# If the fetch strategy is `:local` or `:eventually_local`, filtering is performed client-side. Filter behavior can
# be customized in JavaScript by setting the `filterFn` attribute on the instance of `SelectPanelElement`, eg:
#
# ```javascript
# document.querySelector("select-panel").filterFn = (item: HTMLElement, query: string): boolean => {
# // return true if the item should be displayed, false otherwise
# }
# ```
#
# The element's default filter function uses the value of the `data-filter-string` attribute, falling back to the
# element's `innerText` property. It performs a case-insensitive substring match against the filter string.
#
# ### `SelectPanel`s as form inputs
#
# `SelectPanel`s can be used as form inputs. They behave very similarly to how HTML `<select>` boxes behave, and
# play nicely with Rails' built-in form mechanisms. Pass arguments via the `form_arguments:` argument, including
# the Rails form builder object and the name of the field. Each list item must also have a value specified in
# `content_arguments: { data: { value: } }`.
#
# ```erb
# <% form_with(model: Address.new) do |f| %>
# <%= render(Primer::Alpha::SelectPanel.new(form_arguments: { builder: f, name: "country" })) do |menu| %>
# <% countries.each do |country|
# <% menu.with_item(label: country.name, content_arguments: { data: { value: country.code } }) %>
# <% end %>
# <% end %>
# <% end %>
# ```
#
# The value of the `data: { value: ... }` argument is sent to the server on submit, keyed using the name provided above
# (eg. `"country"`). If no value is provided for an item, the value of that item is the item's label. Here's the
# corresponding `AddressesController` that might be written to handle the form above:
#
# ```ruby
# class AddressesController < ApplicationController
# def create
# puts "You chose #{address_params[:country]} as your country"
# end
#
# private
#
# def address_params
# params.require(:address).permit(:country)
# end
# end
# ```
# ### JavaScript API
#
# `SelectPanel`s render a `<select-panel>` custom element that exposes behavior to the client.
#
# #### Utility methods
#
# * `show()`: Manually open the panel. Under normal circumstances, a show button is used to show the panel, but this method exists to support unusual use-cases.
# * `hide()`: Manually hides (closes) the panel.
#
# #### Query methods
#
# * `getItemById(itemId: string): Element`: Returns the item's HTML `<li>` element. The return value can be passed as the `item` argument to the other methods listed below.
# * `isItemChecked(item: Element): boolean`: Returns `true` if the item is checked, `false` otherwise.
# * `isItemHidden(item: Element): boolean`: Returns `true` if the item is hidden, `false` otherwise.
# * `isItemDisabled(item: Element): boolean`: Returns `true` if the item is disabled, `false` otherwise.
#
# NOTE: Item IDs are special values provided by the user that are attached to `SelectPanel` list items as the `data-item-id`
# HTML attribute. Item IDs can be provided by passing an `item_id:` attribute when adding items to the panel, eg:
#
# ```erb
# <%= render(Primer::Alpha::SelectPanel.new) do |panel| %>
# <% panel.with_item(item_id: "my-id") %>
# <% end %>
# ```
#
# The same is true when rendering `ItemList`s:
#
# ```erb
# <%= render(Primer::Alpha::SelectPanel::ItemList.new) do |list| %>
# <% list.with_item(item_id: "my-id") %>
# <% end %>
# ```
#
# #### State methods
#
# * `enableItem(item: Element)`: Enables the item, i.e. makes it clickable by the mouse and keyboard.
# * `disableItem(item: Element)`: Disables the item, i.e. makes it unclickable by the mouse and keyboard.
# * `checkItem(item: Element)`: Checks the item. Only has an effect in single- and multi-select modes.
# * `uncheckItem(item: Element)`: Unchecks the item. Only has an effect in multi-select mode, since items cannot be unchecked in single-select mode.
#
# #### Events
#
# |Name |Type |Bubbles |Cancelable |
# |:--------------------|:------------------------------------------|:-------|:----------|
# |`itemActivated` |`CustomEvent<ItemActivatedEvent>` |Yes |No |
# |`beforeItemActivated`|`CustomEvent<ItemActivatedEvent>` |Yes |Yes |
# |`dialog:open` |`CustomEvent<{dialog: HTMLDialogElement}>` |No |No |
# |`panelClosed` |`CustomEvent<{panel: SelectPanelElement}>` |Yes |No |
#
# _Item activation_
#
# The `<select-panel>` element fires an `itemActivated` event whenever an item is activated (eg. clicked) via the mouse or keyboard.
#
# ```typescript
# document.querySelector("select-panel").addEventListener(
# "itemActivated",
# (event: CustomEvent<ItemActivatedEvent>) => {
# event.detail.item // Element: the <li> item that was activated
# event.detail.checked // boolean: whether or not the result of the activation checked the item
# }
# )
# ```
#
# The `beforeItemActivated` event fires before an item is activated. Canceling this event will prevent the item
# from being activated.
#
# ```typescript
# document.querySelector("select-panel").addEventListener(
# "beforeItemActivated",
# (event: CustomEvent<ItemActivatedEvent>) => {
# event.detail.item // Element: the <li> item that was activated
# event.detail.checked // boolean: whether or not the result of the activation checked the item
# event.preventDefault() // Cancel the event to prevent activation (eg. checking/unchecking)
# }
# )
# ```
class SelectPanel < Primer::Component
# @private
module Utils
def raise_if_role_given!(**system_arguments)
return if shouldnt_raise_error?
return unless system_arguments.include?(:role)
raise(
"Please avoid passing the `role:` argument to `SelectPanel` and its subcomponents. "\
"The component will automatically apply the correct roles where necessary."
)
end
end
include Utils
# The component that should be used to render the list of items in the body of a SelectPanel.
class ItemList < Primer::Alpha::ActionList
include Utils
# @param system_arguments [Hash] The arguments accepted by <%= link_to_component(Primer::Alpha::ActionList) %>.
def initialize(**system_arguments)
raise_if_role_given!(**system_arguments)
select_variant = system_arguments.delete(:select_variant) || Primer::Alpha::ActionList::DEFAULT_SELECT_VARIANT
super(
p: 2,
role: "listbox",
aria_selection_variant: select_variant == :single ? :selected : :checked,
select_variant: select_variant == :multiple ? :multiple_checkbox : :single,
**system_arguments
)
end
def with_item(**system_arguments)
raise_if_role_given!(**system_arguments)
super
end
def with_avatar_item(**system_arguments)
raise_if_role_given!(**system_arguments)
super
end
end
status :alpha
DEFAULT_PRELOAD = false
DEFAULT_FETCH_STRATEGY = :remote
FETCH_STRATEGIES = [
DEFAULT_FETCH_STRATEGY,
:eventually_local,
:local
]
DEFAULT_SELECT_VARIANT = :single
SELECT_VARIANT_OPTIONS = [
DEFAULT_SELECT_VARIANT,
:multiple,
:none,
].freeze
DEFAULT_BANNER_SCHEME = :danger
BANNER_SCHEME_OPTIONS = [
DEFAULT_BANNER_SCHEME,
:warning
].freeze
# The URL to fetch search results from.
#
# @return [String]
attr_reader :src
# The unique ID of the panel.
#
# @return [String]
attr_reader :panel_id
# The unique ID of the panel body.
#
# @return [String]
attr_reader :body_id
# <%= one_of(Primer::Alpha::ActionMenu::Menu::SELECT_VARIANT_OPTIONS) %>
#
# @return [Symbol]
attr_reader :select_variant
# <%= one_of(Primer::Alpha::SelectPanel::BANNER_SCHEME_OPTIONS) %>
#
# @return [Symbol]
attr_reader :banner_scheme
# <%= one_of(Primer::Alpha::SelectPanel::FETCH_STRATEGIES) %>
#
# @return [Symbol]
attr_reader :fetch_strategy
# Whether to preload search results when the page loads. If this option is false, results are loaded when the panel is opened.
#
# @return [Boolean]
attr_reader :preload
alias preload? preload
# Whether or not to show the filter input.
#
# @return [Boolean]
attr_reader :show_filter
alias show_filter? show_filter
# @param src [String] The URL to fetch search results from.
# @param title [String] The title that appears at the top of the panel.
# @param id [String] The unique ID of the panel.
# @param size [Symbol] The size of the panel. <%= one_of(Primer::Alpha::Overlay::SIZE_OPTIONS) %>
# @param select_variant [Symbol] <%= one_of(Primer::Alpha::SelectPanel::SELECT_VARIANT_OPTIONS) %>
# @param fetch_strategy [Symbol] <%= one_of(Primer::Alpha::SelectPanel::FETCH_STRATEGIES) %>
# @param no_results_label [String] The label to display when no results are found.
# @param preload [Boolean] Whether to preload search results when the page loads. If this option is false, results are loaded when the panel is opened.
# @param dynamic_label [Boolean] Whether or not to display the text of the currently selected item in the show button.
# @param dynamic_label_prefix [String] If provided, the prefix is prepended to the dynamic label and displayed in the show button.
# @param dynamic_aria_label_prefix [String] If provided, the prefix is prepended to the dynamic label and set as the value of the `aria-label` attribute on the show button.
# @param body_id [String] The unique ID of the panel body. If not provided, the body ID will be set to the panel ID with a "-body" suffix.
# @param list_arguments [Hash] Arguments to pass to the underlying <%= link_to_component(Primer::Alpha::ActionList) %> component. Only has an effect for the local fetch strategy.
# @param form_arguments [Hash] Form arguments. Supported for all fetch strategies.
# @param show_filter [Boolean] Whether or not to show the filter input.
# @param open_on_load [Boolean] Open the panel when the page loads.
# @param anchor_align [Symbol] The anchor alignment of the Overlay. <%= one_of(Primer::Alpha::Overlay::ANCHOR_ALIGN_OPTIONS) %>
# @param anchor_side [Symbol] The side to anchor the Overlay to. <%= one_of(Primer::Alpha::Overlay::ANCHOR_SIDE_OPTIONS) %>
# @param loading_label [String] The aria-label to use when the panel is loading, defaults to 'Loading content...'.
# @param loading_description [String] The description to use when the panel is loading. If not provided, no description will be used.
# @param banner_scheme [Symbol] The scheme for the error banner <%= one_of(Primer::Alpha::SelectPanel::BANNER_SCHEME_OPTIONS) %>
# @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
def initialize(
src: nil,
title: "Menu",
id: self.class.generate_id,
size: :small,
select_variant: DEFAULT_SELECT_VARIANT,
fetch_strategy: DEFAULT_FETCH_STRATEGY,
no_results_label: "No results found",
preload: DEFAULT_PRELOAD,
dynamic_label: false,
dynamic_label_prefix: nil,
dynamic_aria_label_prefix: nil,
body_id: nil,
list_arguments: {},
form_arguments: {},
show_filter: true,
open_on_load: false,
anchor_align: Primer::Alpha::Overlay::DEFAULT_ANCHOR_ALIGN,
anchor_side: Primer::Alpha::Overlay::DEFAULT_ANCHOR_SIDE,
loading_label: "Loading content...",
loading_description: nil,
banner_scheme: DEFAULT_BANNER_SCHEME,
**system_arguments
)
raise_if_role_given!(**system_arguments)
if src.present?
url = URI(src)
query = url.query || ""
url.query = query.split("&").push("experimental=1").join("&")
@src = url
end
@panel_id = id
@body_id = body_id || "#{@panel_id}-body"
@preload = fetch_or_fallback_boolean(preload, DEFAULT_PRELOAD)
@select_variant = fetch_or_fallback(SELECT_VARIANT_OPTIONS, select_variant, DEFAULT_SELECT_VARIANT)
@fetch_strategy = fetch_or_fallback(FETCH_STRATEGIES, fetch_strategy, DEFAULT_FETCH_STRATEGY)
@no_results_label = no_results_label
@show_filter = show_filter
@dynamic_label = dynamic_label
@dynamic_label_prefix = dynamic_label_prefix
@dynamic_aria_label_prefix = dynamic_aria_label_prefix
@loading_label = loading_label
@loading_description_id = nil
@form_builder = form_arguments[:builder]
@value = form_arguments[:value]
@input_name = form_arguments[:name]
@list_form_arguments = {}
if loading_description.present?
@loading_description_id = "#{@panel_id}-loading-description"
end
@loading_description = loading_description
@banner_scheme = fetch_or_fallback(BANNER_SCHEME_OPTIONS, banner_scheme, DEFAULT_BANNER_SCHEME)
@system_arguments = deny_tag_argument(**system_arguments)
@system_arguments[:id] = @panel_id
@system_arguments[:"anchor-align"] = fetch_or_fallback(Primer::Alpha::Overlay::ANCHOR_ALIGN_OPTIONS, anchor_align, Primer::Alpha::Overlay::DEFAULT_ANCHOR_ALIGN)
@system_arguments[:"anchor-side"] = Primer::Alpha::Overlay::ANCHOR_SIDE_MAPPINGS[fetch_or_fallback(Primer::Alpha::Overlay::ANCHOR_SIDE_OPTIONS, anchor_side, Primer::Alpha::Overlay::DEFAULT_ANCHOR_SIDE)]
@title = title
@system_arguments[:tag] = :"select-panel"
@system_arguments[:preload] = true if @src.present? && preload?
@system_arguments[:data] = merge_data(
system_arguments, {
data: { select_variant: @select_variant, fetch_strategy: @fetch_strategy, open_on_load: open_on_load }.tap do |data|
data[:dynamic_label] = dynamic_label if dynamic_label
data[:dynamic_label_prefix] = dynamic_label_prefix if dynamic_label_prefix.present?
data[:dynamic_aria_label_prefix] = dynamic_aria_label_prefix if dynamic_aria_label_prefix.present?
end
}
)
@dialog = Primer::BaseComponent.new(
id: "#{@panel_id}-dialog",
"aria-labelledby": "#{@panel_id}-dialog-title",
tag: :dialog,
data: { target: "select-panel.dialog" },
classes: class_names(
"Overlay",
"Overlay-whenNarrow",
Primer::Alpha::Dialog::SIZE_MAPPINGS[
fetch_or_fallback(Primer::Alpha::Dialog::SIZE_OPTIONS, size, Primer::Alpha::Dialog::DEFAULT_SIZE)
],
),
style: "position: absolute;",
)
@list = Primer::Alpha::SelectPanel::ItemList.new(
**list_arguments,
form_arguments: @list_form_arguments,
id: "#{@panel_id}-list",
select_variant: @select_variant,
aria: {
label: "#{title} options"
}
)
return if @show_filter || @fetch_strategy != :remote
return if shouldnt_raise_error?
raise(
"Hiding the filter input with a remote fetch strategy is not permitted, "\
"since such a combinaton of options will cause the component to only "\
"fetch items from the server once when the panel opens for the first time; "\
"this is what the `:eventually_local` fetch strategy is designed to do. "\
"Consider passing `show_filter: true` or use the `:eventually_local` fetch "\
"strategy instead."
)
end
# @!parse
# # Adds an item to the list. Note that this method only has an effect for the local fetch strategy.
# #
# # @param system_arguments [Hash] The arguments accepted by <%= link_to_component(Primer::Alpha::ActionList) %>'s `item` slot.
# def with_item(**system_arguments)
# end
#
# # Adds an avatar item to the list. Note that this method only has an effect for the local fetch strategy.
#
# # @param system_arguments [Hash] The arguments accepted by <%= link_to_component(Primer::Alpha::ActionList) %>'s `item` slot.
# def with_avatar_item
# end
delegate :with_item, :with_avatar_item, to: :@list
# Renders content in a footer region below the list of items.
#
# @param system_arguments [Hash] The arguments accepted by <%= link_to_component(Primer::Alpha::Dialog::Footer) %>.
renders_one :footer, Primer::Alpha::Dialog::Footer
# Renders content underneath the title at the top of the panel.
#
# @param system_arguments [Hash] The arguments accepted by <%= link_to_component(Primer::Alpha::Dialog::Header) %>'s `subtitle` slot.
renders_one :subtitle
# Adds a show button (i.e. a button) that will open the panel when clicked.
#
# @param icon [String] Name of <%= link_to_octicons %> to use instead of text. If an [icon](https://primer.style/octicons/usage-guidelines/) is provided, a <%= link_to_component(Primer::Beta::IconButton) %> will be rendered. Otherwise a <%= link_to_component(Primer::Beta::Button) %> will be rendered.
# @param system_arguments [Hash] The arguments accepted by <%= link_to_component(Primer::Beta::Button) %>.
renders_one :show_button, lambda { |icon: nil, **system_arguments|
system_arguments[:id] = "#{@panel_id}-button"
system_arguments[:aria] = merge_aria(
system_arguments,
{ aria: { controls: "#{@panel_id}-dialog", "haspopup": "dialog", "expanded": "false" } }
)
if icon.present?
Primer::Beta::IconButton.new(icon: icon, **system_arguments)
else
Primer::Beta::Button.new(**system_arguments)
end
}
# Customizable content for the error message that appears when items are fetched for the first time. This message
# appears in place of the list of items.
# For more information, see the [documentation regarding SelectPanel error messaging](/components/selectpanel#errorwarning).
renders_one :preload_error_content
# Customizable content for the error message that appears when items are fetched as the result of a filter
# operation. This message appears as a banner above the previously fetched list of items.
# For more information, see the [documentation regarding SelectPanel error messaging](/components/selectpanel#errorwarning).
renders_one :error_content
private
def before_render
content
end
def required_form_arguments_given?
@input_name && @form_builder
end
def multi_select?
select_variant == :multiple
end
end
end
end