openproject-primer_view_components 0.85.0 → 0.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +10 -0
  3. data/app/assets/javascripts/primer_view_components.js +1 -1
  4. data/app/assets/javascripts/primer_view_components.js.map +1 -1
  5. data/app/assets/styles/primer_view_components.css +1 -1
  6. data/app/assets/styles/primer_view_components.css.map +1 -1
  7. data/app/components/primer/alpha/tree_view/leaf_node.html.erb +5 -0
  8. data/app/components/primer/alpha/tree_view/leaf_node.rb +18 -0
  9. data/app/components/primer/alpha/tree_view/node.html.erb +3 -0
  10. data/app/components/primer/alpha/tree_view/node.rb +10 -0
  11. data/app/components/primer/alpha/tree_view/sub_tree_node.html.erb +5 -0
  12. data/app/components/primer/alpha/tree_view/sub_tree_node.rb +18 -0
  13. data/app/components/primer/alpha/tree_view/trailing_action.html.erb +3 -0
  14. data/app/components/primer/alpha/tree_view/trailing_action.rb +18 -0
  15. data/app/components/primer/alpha/tree_view.css +1 -1
  16. data/app/components/primer/alpha/tree_view.css.json +4 -1
  17. data/app/components/primer/alpha/tree_view.css.map +1 -1
  18. data/app/components/primer/alpha/tree_view.pcss +22 -6
  19. data/app/components/primer/open_project/filterable_tree_view/sub_tree.rb +6 -6
  20. data/app/components/primer/open_project/filterable_tree_view.css +1 -0
  21. data/app/components/primer/open_project/filterable_tree_view.css.json +14 -0
  22. data/app/components/primer/open_project/filterable_tree_view.css.map +1 -0
  23. data/app/components/primer/open_project/filterable_tree_view.html.erb +26 -14
  24. data/app/components/primer/open_project/filterable_tree_view.js +294 -5
  25. data/app/components/primer/open_project/filterable_tree_view.pcss +57 -0
  26. data/app/components/primer/open_project/filterable_tree_view.rb +58 -10
  27. data/app/components/primer/open_project/filterable_tree_view.ts +316 -4
  28. data/app/components/primer/primer.pcss +1 -0
  29. data/app/controllers/primer/view_components/filterable_tree_view_items_controller.rb +192 -0
  30. data/app/views/primer/view_components/filterable_tree_view_items/_node.html.erb +38 -0
  31. data/app/views/primer/view_components/filterable_tree_view_items/async_form_tree.html.erb +9 -0
  32. data/app/views/primer/view_components/filterable_tree_view_items/index.html.erb +6 -0
  33. data/config/routes.rb +4 -0
  34. data/lib/primer/view_components/version.rb +1 -1
  35. data/previews/primer/alpha/tree_view_preview/leaf_node_playground.html.erb +4 -0
  36. data/previews/primer/alpha/tree_view_preview.rb +3 -0
  37. data/previews/primer/open_project/filterable_tree_view_preview/async.html.erb +3 -0
  38. data/previews/primer/open_project/filterable_tree_view_preview/async_form_input.html.erb +9 -0
  39. data/previews/primer/open_project/filterable_tree_view_preview/link_nodes.html.erb +18 -0
  40. data/previews/primer/open_project/filterable_tree_view_preview.rb +23 -2
  41. data/static/arguments.json +22 -0
  42. data/static/audited_at.json +1 -0
  43. data/static/classes.json +9 -0
  44. data/static/constants.json +9 -0
  45. data/static/info_arch.json +123 -1
  46. data/static/previews.json +39 -0
  47. data/static/statuses.json +1 -0
  48. metadata +17 -10
@@ -2,7 +2,8 @@ import {controller, target} from '@github/catalyst'
2
2
  import {SegmentedControlElement} from '../alpha/segmented_control'
3
3
  import {TreeViewElement} from '../alpha/tree_view/tree_view'
4
4
  import {TreeViewSubTreeNodeElement} from '../alpha/tree_view/tree_view_sub_tree_node_element'
5
- import {TreeViewNodeInfo} from '../shared_events'
5
+ // eslint-disable-next-line import/named
6
+ import {TreeViewCheckedValue, TreeViewNodeInfo} from '../shared_events'
6
7
 
7
8
  // This function is expected to return the following values:
8
9
  // 1. No match - return null
@@ -15,6 +16,8 @@ type NodeState = {
15
16
  disabled: boolean
16
17
  }
17
18
 
19
+ const ASYNC_DEBOUNCE_MS = 300
20
+
18
21
  @controller
19
22
  export class FilterableTreeViewElement extends HTMLElement {
20
23
  @target filterInput: HTMLInputElement
@@ -27,15 +30,43 @@ export class FilterableTreeViewElement extends HTMLElement {
27
30
  #abortController: AbortController
28
31
  #stateMap: Map<TreeViewSubTreeNodeElement, Map<HTMLElement, NodeState>> = new Map()
29
32
 
33
+ // Async mode state
34
+ #debounceTimer: ReturnType<typeof setTimeout> | null = null
35
+ #fetchAbortController: AbortController | null = null
36
+ // nodeId → wasExpanded: taken once before the first filter query is entered, cleared when filter is removed
37
+ #expansionSnapshot: Map<string, boolean> | null = null
38
+ // nodeId → wasExpanded: taken before entering "selected" mode, cleared when leaving it
39
+ #selectedModeSnapshot: Map<string, boolean> | null = null
40
+ // nodeId → checkedValue: persists across tree replacements, updated on every treeViewNodeChecked event
41
+ #checkedNodeIds: Map<string, TreeViewCheckedValue> = new Map()
42
+ // nodeId → form payload: mirrors #checkedNodeIds but stores the data needed to synthesise a hidden
43
+ // form input for nodes that are checked but not currently in the DOM (e.g. filtered out).
44
+ #checkedNodeFormPayloads: Map<string, {path: string[]; value?: string}> = new Map()
45
+ #isFiltered = false
46
+
30
47
  connectedCallback() {
31
48
  const {signal} = (this.#abortController = new AbortController())
32
49
  this.addEventListener('treeViewNodeChecked', this, {signal})
33
50
  this.addEventListener('itemActivated', this, {signal})
34
51
  this.addEventListener('input', this, {signal})
52
+
53
+ if (this.#isAsyncMode) {
54
+ void this.#fetchAndReplaceTree()
55
+ }
35
56
  }
36
57
 
37
58
  disconnectedCallback() {
38
59
  this.#abortController.abort()
60
+ this.#fetchAbortController?.abort()
61
+ if (this.#debounceTimer !== null) clearTimeout(this.#debounceTimer)
62
+ }
63
+
64
+ get #src(): string | null {
65
+ return this.getAttribute('src')
66
+ }
67
+
68
+ get #isAsyncMode(): boolean {
69
+ return !!this.#src
39
70
  }
40
71
 
41
72
  handleEvent(event: Event) {
@@ -57,11 +88,48 @@ export class FilterableTreeViewElement extends HTMLElement {
57
88
  // when calling this.treeView.setNodeCheckedValue.
58
89
  switch (origEvent.type) {
59
90
  case 'treeViewNodeChecked':
91
+ // Always track checked node IDs before delegating, so async replacements can restore selection.
92
+ this.#updateCheckedNodeIds(event)
60
93
  this.#handleTreeViewNodeChecked(event)
61
94
  break
62
95
  }
63
96
  }
64
97
 
98
+ // Keeps #checkedNodeIds and #checkedNodeFormPayloads in sync with every user-triggered check event
99
+ // so we can restore selection and synthesise form inputs after async tree replacements, even for
100
+ // nodes that are no longer visible (e.g. filtered out by the server).
101
+ #updateCheckedNodeIds(event: CustomEvent<TreeViewNodeInfo[]>) {
102
+ if (!this.#isAsyncMode) return
103
+
104
+ for (const nodeInfo of event.detail) {
105
+ const node = nodeInfo.node as HTMLElement
106
+ const nodeId = node.getAttribute('data-node-id')
107
+ if (nodeId) {
108
+ if (nodeInfo.checkedValue === 'false') {
109
+ this.#checkedNodeIds.delete(nodeId)
110
+ this.#checkedNodeFormPayloads.delete(nodeId)
111
+ } else {
112
+ // In single-select mode, TreeView clears the previous selection internally
113
+ // (via checkOnlyAtPath) but the treeViewNodeChecked event only contains the
114
+ // newly selected node. Clear our tracked state so #restoreSelectionState does
115
+ // not re-check previously selected nodes after a tree replacement.
116
+ if (node.getAttribute('data-select-variant') === 'single') {
117
+ this.#checkedNodeIds.clear()
118
+ this.#checkedNodeFormPayloads.clear()
119
+ }
120
+
121
+ this.#checkedNodeIds.set(nodeId, nodeInfo.checkedValue)
122
+ const payload: {path: string[]; value?: string} = {path: nodeInfo.path}
123
+ const dataValue = node.getAttribute('data-value')
124
+ if (dataValue) payload.value = dataValue
125
+ this.#checkedNodeFormPayloads.set(nodeId, payload)
126
+ }
127
+ }
128
+ }
129
+
130
+ this.#updateRetainedSelections()
131
+ }
132
+
65
133
  #handleTreeViewNodeChecked(event: CustomEvent<TreeViewNodeInfo[]>) {
66
134
  if (!this.treeView) return
67
135
  if (!this.includeSubItemsCheckBox.checked) return
@@ -118,20 +186,56 @@ export class FilterableTreeViewElement extends HTMLElement {
118
186
  #handleFilterModeEvent(event: Event) {
119
187
  if (event.type !== 'itemActivated') return
120
188
 
121
- this.#applyFilterOptions()
189
+ if (this.#isAsyncMode) {
190
+ if (this.filterMode === 'selected') {
191
+ // "selected" mode is client-side: snapshot expansion state before the filter collapses nodes,
192
+ // then apply client-side filter without a server round-trip.
193
+ this.#selectedModeSnapshot = this.#captureExpansionState()
194
+ this.#applyFilterOptions()
195
+ } else if (this.#selectedModeSnapshot !== null && this.queryString.length === 0) {
196
+ // Leaving "selected" mode with no active query: undo client-side filter and restore expansion
197
+ // state without a server round-trip (the full tree is already in the DOM).
198
+ this.#undoClientSideFilter()
199
+ this.#applyExpansionSnapshot(this.#selectedModeSnapshot)
200
+ this.#selectedModeSnapshot = null
201
+ } else {
202
+ // "all" mode with an active query, or switching away from a custom mode: use async fetch.
203
+ this.#selectedModeSnapshot = null
204
+ this.#scheduleAsyncFetch()
205
+ }
206
+ } else {
207
+ this.#applyFilterOptions()
208
+ }
209
+ }
210
+
211
+ // Removes `hidden` attributes added by the client-side filter from leaf list items and sub-tree nodes.
212
+ #undoClientSideFilter() {
213
+ for (const el of this.querySelectorAll<HTMLElement>('tree-view li[hidden], tree-view-sub-tree-node[hidden]')) {
214
+ el.removeAttribute('hidden')
215
+ }
122
216
  }
123
217
 
124
218
  #handleFilterInputEvent(event: Event) {
125
219
  if (event.type !== 'input') return
126
220
 
127
- this.#applyFilterOptions()
221
+ // "selected" mode is always client-side – the server doesn't know the selection state.
222
+ if (this.#isAsyncMode && this.filterMode !== 'selected') {
223
+ this.#scheduleAsyncFetch()
224
+ } else {
225
+ this.#applyFilterOptions()
226
+ }
128
227
  }
129
228
 
130
229
  #handleIncludeSubItemsCheckBoxEvent(event: Event) {
131
230
  if (!this.treeView) return
132
231
  if (event.type !== 'input') return
133
232
 
134
- this.#applyFilterOptions()
233
+ // In async mode, toggling include-sub-items does not require a server round-trip: the client
234
+ // handles the visual state entirely (checking/disabling visible descendants). The flag will be
235
+ // included automatically in the next filter request triggered by a query or filter-mode change.
236
+ if (!this.#isAsyncMode) {
237
+ this.#applyFilterOptions()
238
+ }
135
239
 
136
240
  if (this.includeSubItemsCheckBox.checked) {
137
241
  this.#includeSubItems()
@@ -185,6 +289,214 @@ export class FilterableTreeViewElement extends HTMLElement {
185
289
  }
186
290
  }
187
291
 
292
+ // ─── Async mode ────────────────────────────────────────────────────────────
293
+
294
+ #scheduleAsyncFetch() {
295
+ if (this.#debounceTimer !== null) clearTimeout(this.#debounceTimer)
296
+
297
+ this.#debounceTimer = setTimeout(() => {
298
+ this.#debounceTimer = null
299
+ void this.#fetchAndReplaceTree()
300
+ }, ASYNC_DEBOUNCE_MS)
301
+ }
302
+
303
+ async #fetchAndReplaceTree() {
304
+ const src = this.#src
305
+ if (!src) return
306
+
307
+ const query = this.queryString
308
+ const filterMode = this.filterMode || 'all'
309
+ const includeSubItems = this.includeSubItemsCheckBox?.checked ?? false
310
+
311
+ // Snapshot expansion state the first time the user enters a filter query
312
+ if (!this.#isFiltered && query.length > 0) {
313
+ this.#snapshotExpansionState()
314
+ this.#isFiltered = true
315
+ } else if (this.#isFiltered && query.length === 0) {
316
+ this.#isFiltered = false
317
+ }
318
+
319
+ // Remember which filter state this particular request was for so we apply
320
+ // the correct post-processing even if the user types quickly.
321
+ const requestWasFiltered = query.length > 0
322
+
323
+ // Abort any in-flight request
324
+ this.#fetchAbortController?.abort()
325
+ const {signal} = (this.#fetchAbortController = new AbortController())
326
+
327
+ const url = new URL(src, window.location.href)
328
+ url.searchParams.set('query', query)
329
+ url.searchParams.set('filter_mode', filterMode)
330
+ url.searchParams.set('include_sub_items', String(includeSubItems))
331
+
332
+ // Send currently-checked node IDs so the server can apply include-sub-items
333
+ // logic even for nodes that are no longer visible due to filtering / pagination.
334
+ for (const nodeId of this.#checkedNodeIds.keys()) {
335
+ url.searchParams.append('checked_ids[]', nodeId)
336
+ }
337
+
338
+ this.setAttribute('data-loading', '')
339
+ this.setAttribute('aria-busy', 'true')
340
+
341
+ try {
342
+ const response = await fetch(url.toString(), {
343
+ signal,
344
+ headers: {Accept: 'text/html'},
345
+ credentials: 'same-origin',
346
+ method: 'GET',
347
+ })
348
+ if (!response.ok) return
349
+
350
+ const html = await response.text()
351
+ const doc = new DOMParser().parseFromString(html, 'text/html')
352
+ const newTreeView = doc.querySelector('tree-view')
353
+ if (!newTreeView) return
354
+
355
+ const oldTreeView = this.treeViewList?.closest('tree-view')
356
+ if (!oldTreeView) return
357
+
358
+ // Invalidate old stateMap entries – the referenced DOM nodes no longer exist after replacement.
359
+ this.#stateMap.clear()
360
+
361
+ oldTreeView.replaceWith(newTreeView)
362
+ // Catalyst re-resolves @target treeViewList dynamically on next access.
363
+
364
+ // Restore checked state for all nodes that now appear in the new tree.
365
+ this.#restoreSelectionState()
366
+
367
+ // Re-apply include-sub-items visually if the checkbox is still checked.
368
+ if (includeSubItems) {
369
+ this.#includeSubItems()
370
+ }
371
+
372
+ if (requestWasFiltered) {
373
+ this.#expandAllSubTrees()
374
+ this.#applyAsyncHighlights(query)
375
+ const hasResults = !!this.treeViewList?.querySelector('[role=treeitem]')
376
+ this.noResultsMessage.toggleAttribute('hidden', hasResults)
377
+ this.treeViewList?.toggleAttribute('hidden', !hasResults)
378
+ } else {
379
+ this.#removeHighlights()
380
+ this.#restoreExpansionState()
381
+ this.noResultsMessage.setAttribute('hidden', 'hidden')
382
+ this.treeViewList?.removeAttribute('hidden')
383
+ }
384
+
385
+ // Synthesise form inputs for nodes that are checked but absent from the current DOM
386
+ // (e.g. filtered out). Must run after restoreSelectionState so we know what is in the DOM.
387
+ this.#updateRetainedSelections()
388
+ } catch (e) {
389
+ if ((e as Error).name === 'AbortError') return
390
+ throw e
391
+ } finally {
392
+ this.removeAttribute('data-loading')
393
+ this.setAttribute('aria-busy', 'false')
394
+ }
395
+ }
396
+
397
+ // Captures the current expanded/collapsed state of every sub-tree node as a nodeId → boolean map.
398
+ #captureExpansionState(): Map<string, boolean> {
399
+ const snapshot = new Map<string, boolean>()
400
+ for (const treeitem of this.querySelectorAll<HTMLElement>(
401
+ '[role=treeitem][data-node-id][data-node-type=sub-tree]',
402
+ )) {
403
+ snapshot.set(treeitem.getAttribute('data-node-id')!, treeitem.getAttribute('aria-expanded') === 'true')
404
+ }
405
+ return snapshot
406
+ }
407
+
408
+ // Applies a previously captured expansion snapshot to the current tree.
409
+ #applyExpansionSnapshot(snapshot: Map<string, boolean>) {
410
+ for (const [nodeId, wasExpanded] of snapshot) {
411
+ const treeitem = this.querySelector<HTMLElement>(`[role=treeitem][data-node-id="${CSS.escape(nodeId)}"]`)
412
+ const subTreeNode = treeitem?.closest('tree-view-sub-tree-node') as TreeViewSubTreeNodeElement | null
413
+ if (subTreeNode) {
414
+ if (wasExpanded) {
415
+ subTreeNode.expand()
416
+ } else {
417
+ subTreeNode.collapse()
418
+ }
419
+ }
420
+ }
421
+ }
422
+
423
+ // Saves the expanded/collapsed state of every sub-tree node before the first filter query is applied.
424
+ #snapshotExpansionState() {
425
+ this.#expansionSnapshot = this.#captureExpansionState()
426
+ }
427
+
428
+ // Restores the expansion state that was saved before filtering began, then discards the snapshot.
429
+ #restoreExpansionState() {
430
+ if (!this.#expansionSnapshot) return
431
+ this.#applyExpansionSnapshot(this.#expansionSnapshot)
432
+ this.#expansionSnapshot = null
433
+ }
434
+
435
+ // Re-applies checked values from #checkedNodeIds to every node that exists in the current tree.
436
+ #restoreSelectionState() {
437
+ if (!this.treeView) return
438
+
439
+ for (const treeitem of this.querySelectorAll<HTMLElement>('[role=treeitem][data-node-id]')) {
440
+ const nodeId = treeitem.getAttribute('data-node-id')!
441
+ const savedValue = this.#checkedNodeIds.get(nodeId)
442
+ if (savedValue !== undefined) {
443
+ this.treeView.setNodeCheckedValue(treeitem, savedValue)
444
+ }
445
+ }
446
+ }
447
+
448
+ // Expands every sub-tree node in the current tree – used after a filtered result is rendered so all
449
+ // matches and their ancestors are visible.
450
+ #expandAllSubTrees() {
451
+ for (const subTreeNode of this.querySelectorAll<TreeViewSubTreeNodeElement>('tree-view-sub-tree-node')) {
452
+ subTreeNode.expand()
453
+ }
454
+ }
455
+
456
+ // Applies highlights based on the current query string to whatever tree is in the DOM. Unlike the
457
+ // client-side path, filtering is already done by the server, so we only need to produce highlights.
458
+ #applyAsyncHighlights(query: string) {
459
+ this.#removeHighlights()
460
+ const ranges: Range[] = []
461
+
462
+ for (const treeitem of this.querySelectorAll<HTMLElement>('[role=treeitem]')) {
463
+ const result = this.defaultFilterFn(treeitem, query, 'all')
464
+ if (result) ranges.push(...result)
465
+ }
466
+
467
+ if (ranges.length > 0) this.#applyHighlights(ranges)
468
+ }
469
+
470
+ // Maintains hidden form inputs (with the same name as the TreeView's own inputs) for nodes that are
471
+ // checked but currently absent from the DOM (e.g. filtered out by the server). These inputs live
472
+ // directly inside <filterable-tree-view> – outside <tree-view> – so they survive tree replacements.
473
+ // The server therefore receives a complete set of checked paths regardless of what is currently visible.
474
+ #updateRetainedSelections() {
475
+ // Only relevant when a form is wired up.
476
+ const prototype = this.treeView?.formInputPrototype
477
+ if (!prototype) return
478
+
479
+ // Remove previously injected retained inputs.
480
+ for (const el of this.querySelectorAll('[data-filterable-tree-view-retained]')) {
481
+ el.remove()
482
+ }
483
+
484
+ for (const [nodeId, payload] of this.#checkedNodeFormPayloads) {
485
+ // Nodes currently in the DOM are already covered by TreeView's updateHiddenFormInputs.
486
+ const inDom = !!this.querySelector(`[role=treeitem][data-node-id="${CSS.escape(nodeId)}"]`)
487
+ if (inDom) continue
488
+
489
+ const input = document.createElement('input')
490
+ input.type = 'hidden'
491
+ input.name = prototype.name
492
+ input.value = JSON.stringify(payload)
493
+ input.setAttribute('data-filterable-tree-view-retained', '')
494
+ this.appendChild(input)
495
+ }
496
+ }
497
+
498
+ // ─── End async mode ─────────────────────────────────────────────────────────
499
+
188
500
  set filterFn(newFn: FilterFn) {
189
501
  this.#filterFn = newFn
190
502
  }
@@ -56,3 +56,4 @@
56
56
  @import "./open_project/border_box/collapsible_header.pcss";
57
57
  @import "./open_project/collapsible_section.pcss";
58
58
  @import "./open_project/pagination.pcss";
59
+ @import "./open_project/filterable_tree_view.pcss";
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Primer
4
+ module ViewComponents
5
+ # :nodoc:
6
+ # :nocov:
7
+ class FilterableTreeViewItemsController < ApplicationController
8
+ # A node in the demo tree. Leaf nodes have no children.
9
+ TreeNode = Data.define(:id, :label, :children, :all_descendant_ids) do
10
+ def leaf?
11
+ children.nil? || children.empty?
12
+ end
13
+
14
+ # Returns a filtered copy of this node. Leaf nodes are included if they match the query.
15
+ # Sub-tree nodes are included if they match OR any descendant matches. The all_descendant_ids
16
+ # field always reflects the ORIGINAL (unfiltered) descendant set, so clients can use it to
17
+ # determine which nodes to select when "include sub-items" is active on a filtered tree.
18
+ def filter(query)
19
+ return self if query.empty?
20
+
21
+ if leaf?
22
+ matches?(query) ? self : nil
23
+ else
24
+ filtered_children = children.filter_map { |child| child.filter(query) }
25
+ if matches?(query) || !filtered_children.empty?
26
+ self.class.new(
27
+ id: id,
28
+ label: label,
29
+ children: filtered_children,
30
+ all_descendant_ids: all_descendant_ids
31
+ )
32
+ end
33
+ end
34
+ end
35
+
36
+ private
37
+
38
+ def matches?(query)
39
+ label.downcase.include?(query.downcase)
40
+ end
41
+ end
42
+
43
+ # Build a leaf node
44
+ def self.leaf(id:, label:)
45
+ TreeNode.new(id: id, label: label, children: [], all_descendant_ids: [])
46
+ end
47
+
48
+ # Build a branch node, computing all_descendant_ids automatically
49
+ def self.branch(id:, label:, children:)
50
+ all_ids = children.flat_map { |c| [c.id] + c.all_descendant_ids }
51
+ TreeNode.new(id: id, label: label, children: children, all_descendant_ids: all_ids)
52
+ end
53
+
54
+ TREE = [
55
+ branch(
56
+ id: "hogwarts",
57
+ label: "Hogwarts School of Witchcraft and Wizardry",
58
+ children: [
59
+ branch(
60
+ id: "hogwarts-students",
61
+ label: "Students",
62
+ children: [
63
+ branch(
64
+ id: "gryffindor",
65
+ label: "Gryffindor",
66
+ children: [
67
+ leaf(id: "harry-potter", label: "Harry Potter"),
68
+ leaf(id: "ron-weasley", label: "Ron Weasley"),
69
+ leaf(id: "hermione-granger", label: "Hermione Granger"),
70
+ leaf(id: "neville-longbottom", label: "Neville Longbottom"),
71
+ leaf(id: "ginny-weasley", label: "Ginny Weasley")
72
+ ]
73
+ ),
74
+ branch(
75
+ id: "slytherin",
76
+ label: "Slytherin",
77
+ children: [
78
+ leaf(id: "draco-malfoy", label: "Draco Malfoy"),
79
+ leaf(id: "pansy-parkinson", label: "Pansy Parkinson"),
80
+ leaf(id: "blaise-zabini", label: "Blaise Zabini")
81
+ ]
82
+ ),
83
+ branch(
84
+ id: "ravenclaw",
85
+ label: "Ravenclaw",
86
+ children: [
87
+ leaf(id: "luna-lovegood", label: "Luna Lovegood"),
88
+ leaf(id: "cho-chang", label: "Cho Chang"),
89
+ leaf(id: "terry-boot", label: "Terry Boot")
90
+ ]
91
+ ),
92
+ branch(
93
+ id: "hufflepuff",
94
+ label: "Hufflepuff",
95
+ children: [
96
+ leaf(id: "cedric-diggory", label: "Cedric Diggory"),
97
+ leaf(id: "susan-bones", label: "Susan Bones"),
98
+ leaf(id: "hannah-abbott", label: "Hannah Abbott")
99
+ ]
100
+ )
101
+ ]
102
+ ),
103
+ branch(
104
+ id: "hogwarts-teachers",
105
+ label: "Teachers",
106
+ children: [
107
+ leaf(id: "albus-dumbledore", label: "Albus Dumbledore"),
108
+ leaf(id: "minerva-mcgonagall", label: "Minerva McGonagall"),
109
+ leaf(id: "severus-snape", label: "Severus Snape"),
110
+ leaf(id: "rubeus-hagrid", label: "Rubeus Hagrid"),
111
+ leaf(id: "remus-lupin", label: "Remus Lupin"),
112
+ leaf(id: "sybill-trelawney", label: "Sybill Trelawney")
113
+ ]
114
+ )
115
+ ]
116
+ ),
117
+ branch(
118
+ id: "beauxbatons",
119
+ label: "Beauxbatons Academy of Magic",
120
+ children: [
121
+ branch(
122
+ id: "beauxbatons-students",
123
+ label: "Students",
124
+ children: [
125
+ leaf(id: "fleur-delacour", label: "Fleur Delacour"),
126
+ leaf(id: "gabrielle-delacour", label: "Gabrielle Delacour"),
127
+ leaf(id: "cecile-fontaine", label: "Cécile Fontaine")
128
+ ]
129
+ ),
130
+ branch(
131
+ id: "beauxbatons-teachers",
132
+ label: "Teachers",
133
+ children: [
134
+ leaf(id: "olympe-maxime", label: "Olympe Maxime"),
135
+ leaf(id: "sylvie-beaumont", label: "Sylvie Beaumont")
136
+ ]
137
+ )
138
+ ]
139
+ ),
140
+ branch(
141
+ id: "durmstrang",
142
+ label: "Durmstrang Institute",
143
+ children: [
144
+ branch(
145
+ id: "durmstrang-students",
146
+ label: "Students",
147
+ children: [
148
+ leaf(id: "viktor-krum", label: "Viktor Krum"),
149
+ leaf(id: "dmitri-poliakoff", label: "Dmitri Poliakoff"),
150
+ leaf(id: "gregor-tarasov", label: "Gregor Tarasov")
151
+ ]
152
+ ),
153
+ branch(
154
+ id: "durmstrang-teachers",
155
+ label: "Teachers",
156
+ children: [
157
+ leaf(id: "igor-karkaroff", label: "Igor Karkaroff"),
158
+ leaf(id: "fyodor-dolohov", label: "Fyodor Dolohov")
159
+ ]
160
+ )
161
+ ]
162
+ )
163
+ ].freeze
164
+
165
+ def index
166
+ query = params[:query].to_s.strip
167
+ select_variant = (params[:select_variant].presence || "multiple").to_sym
168
+ nodes = TREE.filter_map { |node| node.filter(query) }
169
+
170
+ render locals: {
171
+ nodes: nodes,
172
+ query: query,
173
+ select_variant: select_variant
174
+ }
175
+ end
176
+
177
+ def async_form_tree
178
+ query = params[:query].to_s.strip
179
+ name = params[:name].to_s.presence || "characters"
180
+ nodes = TREE.filter_map { |node| node.filter(query) }
181
+ builder = ActionView::Helpers::FormBuilder.new("", nil, view_context, {})
182
+
183
+ render locals: {
184
+ nodes: nodes,
185
+ query: query,
186
+ name: name,
187
+ builder: builder
188
+ }
189
+ end
190
+ end
191
+ end
192
+ end
@@ -0,0 +1,38 @@
1
+ <% if node.leaf? %>
2
+ <% component.with_leaf(
3
+ label: node.label,
4
+ select_variant: select_variant,
5
+ data: { node_id: node.id }
6
+ ) %>
7
+ <% else %>
8
+ <%
9
+ # At the top-level TreeView we must explicitly provide sub_tree_component_klass and
10
+ # select_strategy. At nested levels, FilterableTreeView::SubTree#with_sub_tree already
11
+ # passes both via super and would raise "keyword argument duplicated" if we passed them again.
12
+ sub_tree_opts = {}
13
+ if component.is_a?(Primer::Alpha::TreeView)
14
+ sub_tree_opts[:sub_tree_component_klass] = Primer::OpenProject::FilterableTreeView::SubTree
15
+ sub_tree_opts[:select_strategy] = :self
16
+ end
17
+
18
+ # When a filter query is active, every sub-tree in the result is either a match or an ancestor
19
+ # of a match – either way it should be expanded so the user sees the results immediately.
20
+ sub_tree_opts[:expanded] = true if query.present?
21
+
22
+ hierarchy_only = query.present? && !node.label.downcase.include?(query.downcase)
23
+ %>
24
+ <% component.with_sub_tree(
25
+ label: node.label,
26
+ select_variant: select_variant,
27
+ **sub_tree_opts,
28
+ data: {
29
+ node_id: node.id,
30
+ hierarchy_only: (hierarchy_only ? true : nil)
31
+ }
32
+ ) do |sub| %>
33
+ <% node.children.each do |child| %>
34
+ <%= render partial: "primer/view_components/filterable_tree_view_items/node",
35
+ locals: { component: sub, node: child, query: query, select_variant: select_variant } %>
36
+ <% end %>
37
+ <% end %>
38
+ <% end %>
@@ -0,0 +1,9 @@
1
+ <%= render(Primer::Alpha::TreeView.new(
2
+ data: { target: "filterable-tree-view.treeViewList" },
3
+ form_arguments: { builder: builder, name: name }
4
+ )) do |tree| %>
5
+ <% nodes.each do |node| %>
6
+ <%= render partial: "primer/view_components/filterable_tree_view_items/node",
7
+ locals: { component: tree, node: node, query: query, select_variant: :multiple } %>
8
+ <% end %>
9
+ <% end %>
@@ -0,0 +1,6 @@
1
+ <%= render(Primer::Alpha::TreeView.new(data: { target: "filterable-tree-view.treeViewList" })) do |tree| %>
2
+ <% nodes.each do |node| %>
3
+ <%= render partial: "primer/view_components/filterable_tree_view_items/node",
4
+ locals: { component: tree, node: node, query: query, select_variant: select_variant } %>
5
+ <% end %>
6
+ <% end %>
data/config/routes.rb CHANGED
@@ -12,6 +12,10 @@ Primer::ViewComponents::Engine.routes.draw do
12
12
  resources :tree_view_items, only: [:index]
13
13
  get "/tree_view_items/async_alpha", to: "tree_view_items#async_alpha", as: :tree_view_items_async_alpha
14
14
 
15
+ resources :filterable_tree_view_items, only: [:index]
16
+ get "/filterable_tree_view_items/tree", to: "filterable_tree_view_items#index", as: :filterable_tree_view_items_tree
17
+ get "/filterable_tree_view_items/async_form_tree", to: "filterable_tree_view_items#async_form_tree", as: :filterable_tree_view_items_async_form_tree
18
+
15
19
  # generic form submission path
16
20
  post "/form_handler", to: "form_handler#form_action", as: :generic_form_submission
17
21
 
@@ -5,7 +5,7 @@ module Primer
5
5
  module ViewComponents
6
6
  module VERSION
7
7
  MAJOR = 0
8
- MINOR = 85
8
+ MINOR = 86
9
9
  PATCH = 0
10
10
 
11
11
  STRING = [MAJOR, MINOR, PATCH].join(".")
@@ -11,5 +11,9 @@
11
11
  <% if leading_action_icon && leading_action_icon != :none %>
12
12
  <% node.with_leading_action_button(icon: leading_action_icon, aria: { label: "Leading action icon" }) %>
13
13
  <% end %>
14
+
15
+ <% if trailing_action_icon && trailing_action_icon != :none %>
16
+ <% node.with_trailing_action_button(icon: trailing_action_icon, aria: { label: "Trailing action icon" }) %>
17
+ <% end %>
14
18
  <% end %>
15
19
  <% end %>