-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgropdown-js_templ.go
564 lines (494 loc) · 16.9 KB
/
gropdown-js_templ.go
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.2.680
package gropdown
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
func GropdownJS(configMap *ConfigMap) templ.ComponentScript {
return templ.ComponentScript{
Name: `__templ_GropdownJS_8d5a`,
Function: `function __templ_GropdownJS_8d5a(configMap){// Utility function to check if a value is null or undefined
function isNullish(value) {
return value === null || value === undefined;
}
// Utility function to checks if a given value is of boolean type and has a value of ` + "`" + `true` + "`" + ` or ` + "`" + `false` + "`" + `.
function isBool(value) {
return typeof value === 'boolean' && (value === true || value === false);
}
// Utility function to check if a given string is a single character.
function isChar(txt) {
const charsRegex = /\S/;
return txt.length === 1 && charsRegex.test(txt);
}
/**
* The ` + "`" + `ComponentFocusManager` + "`" + ` class provides focus management for components with multiple
* interactive items. It enables navigation between items, setting focus to specific items, and
* handling keyboard interactions.
*
* Use it to ensure keyboard accessibility as per [WAI ARIA Patterns](https://www.w3.org/WAI/ARIA/apg/patterns/)
* and improve user experience in menus, dropdowns, and other interactive components.
*/
class ComponentFocusManager {
/**
* Constructs an instance of ComponentFocusManager.
* @param {string} componentId - The ID of the component.
*/
constructor(componentId) {
this._id = componentId
this._items = {}
this._firstChars = {}
this._firstItem = {}
this._lastItem = {}
this._applyDOMChangesFn = async () => {
// Default implementation: no pending state changes, resolves immediately
return Promise.resolve()
}
this._items[componentId] = []
this._firstChars[componentId] = []
this._firstItem[componentId] = null
this._lastItem[componentId] = null
}
/**
* Gets or sets the collection of items.
* @type {Object<string, HTMLElement[]>}
*/
get items() {
const { _items } = this
return _items
}
set items(value) {
this._items = value
}
/**
* Gets or sets the collection of first characters.
* @type {Object<string, string[]>}
*/
get firstChars() {
const { _firstChars } = this
return _firstChars
}
set firstChars(value) {
this._firstChars = value
}
/**
* Gets or sets the first item in each collection.
* @type {Object<string, HTMLElement | null>}
*/
get firstItem() {
const { _firstItem } = this
return _firstItem
}
set firstItem(value) {
this._firstItem = value
}
/**
* Gets or sets the last item in each collection.
* @type {Object<string, HTMLElement | null>}
*/
get lastItem() {
const { _lastItem } = this
return _lastItem
}
set lastItem(value) {
this._lastItem = value
}
/**
* Gets or sets the applyDOMChanges promise.
* @type {() => Promise<void>}
*/
get applyDOMChangesFn() {
return this._applyDOMChangesFn
}
set applyDOMChangesFn(value) {
this._applyDOMChangesFn = value
}
/** methods */
/**
* Runs the focus manager to initialize the collections.
*/
run() {
this._items[this._id].forEach((item) => {
const menuItemContent = item.textContent?.trim().toLowerCase()[0]
if (menuItemContent) this._firstChars[this._id].push(menuItemContent)
if (!this._firstItem[this._id]) {
this._firstItem[this._id] = item
}
this._lastItem[this._id] = item
})
}
/**
* Sets the focus to the first item.
* @param {string} [cId] - Optional ID of the component.
*/
setFocusToFirstItem(cId) {
const id = this._resolveId(cId)
this._setFocusToItem(this._firstItem[id])
}
/**
* Sets the focus to the last item.
* @param {string} [cId] - Optional ID of the component.
*/
setFocusToLastItem(cId) {
const id = this._resolveId(cId)
this._setFocusToItem(this._lastItem[id])
}
/**
* Sets the focus to the previous item relative to the current item.
* @param {HTMLElement} currentItem - The current item.
* @param {string} [cId] - Optional ID of the component.
* @returns {HTMLElement} The new focused item.
*/
setFocusToPreviousItem(currentItem, cId) {
const id = this._resolveId(cId)
let newMenuItem, index
if (currentItem === this._firstItem[id]) {
newMenuItem = this._lastItem[id]
} else {
index = this._items[id].indexOf(currentItem)
newMenuItem = this._items[id][index - 1]
}
this._setFocusToItem(newMenuItem)
return newMenuItem
}
/**
* Sets the focus to the next item relative to the current item.
* @param {HTMLElement} currentItem - The current item.
* @param {string} [cId] - Optional ID of the component.
* @returns {HTMLElement} The new focused item.
*/
setFocusToNextItem(currentItem, cId) {
const id = this._resolveId(cId)
let newMenuItem, index
if (currentItem === this._lastItem[id]) {
newMenuItem = this._firstItem[id]
} else {
index = this._items[id].indexOf(currentItem)
newMenuItem = this._items[id][index + 1]
}
this._setFocusToItem(newMenuItem)
return newMenuItem
}
/**
* Sets the focus to the item whose content starts with the specified character.
* @param {HTMLElement} currentItem - The current item.
* @param {string} c - The character to match.
*/
setFocusByFirstChar(currentItem, c) {
let start, index
if (c.length > 1) return
c = c.toLowerCase()
start = this._items[this._id].indexOf(currentItem) + 1
if (start >= this._items[this._id].length) {
start = 0
}
index = this._firstChars[this._id].indexOf(c, start)
if (index === -1) {
index = this._firstChars[this._id].indexOf(c, 0)
}
if (index > -1) {
this._setFocusToItem(this._items[this._id][index])
}
}
/**
* Checks if the given node is a submenu.
* @param {HTMLElement} node - The node to check.
* @returns {boolean} A boolean indicating whether the node is a submenu.
*/
isSubMenu(node) {
return node.getAttribute('aria-haspopup') === 'true'
}
/**
* Resolves the ID to use based on the provided ID or the default ID of the component.
* @param {string} [id] - The optional ID to resolve.
* @returns {string} The resolved ID.
* @private
*/
_resolveId(id) {
return !isNullish(id) ? id : this._id
}
/**
* Sets the focus to the given item.
* @param {HTMLElement | null} item - The item to set focus to.
* @private
*/
async _setFocusToItem(item) {
if (this._items[this._id] && item) {
await Promise.all(
this._items[this._id].map(async (itemNode) => {
if (itemNode === item) {
itemNode.tabIndex = 0
await this.applyDOMChangesFn()
itemNode.focus()
} else {
itemNode.tabIndex = -1
}
})
)
}
}
}
/**
* Initializes accessibility actions for a dropdown component.
* @param {HTMLElement} node - The root element of the dropdown component.
* @param {object} options - Options for configuring the accessibility actions.
* @param {boolean} options.enabled - Flag indicating if the accessibility actions on the dropdown should be enabled.
* @param {boolean} options.open - Flag indicating if the dropdown is initially open.
* @param {boolean} options.animated - Flag indicating if the dropdown menu button should use icon animations.
*/
function a11yActions(node, options) {
let open = options?.open
const animated = options?.animated
const componentId = node.getAttribute("id");
const focusManager = new ComponentFocusManager(componentId)
const listGroups = {}
const firstChars = {}
const firstItem = {}
const lastItem = {}
// Initializes the dropdown component.
const initialize = () => {
listGroups[componentId] = []
firstChars[componentId] = []
firstItem[componentId] = null
lastItem[componentId] = null
}
/**
* Checks if the given target element is a link (anchor tag).
*
* @param {HTMLElement} target - The target element to check.
* @returns {boolean} Returns true if the target element is a link, otherwise false.
*/
const isLinkElement = (target) => {
return target.tagName === 'A';
};
/**
* Handles click events on dropdown items, performing appropriate actions based on the type of item.
*
* @param {Event} e - The click event.
*/
const handleClickOnItem = (e) => {
e.stopPropagation();
e.preventDefault();
if (isLinkElement(e.target)) {
handleLinkClick(e.target);
} else {
handleButtonClick();
}
};
/**
* Handles click events on link elements, navigating to the specified URL and closing the dropdown if necessary.
*
* @param {HTMLElement} linkElement - The link element that was clicked.
*/
const handleLinkClick = (linkElement) => {
const href = linkElement.getAttribute('href');
const isExternal = linkElement.getAttribute('data-external') === 'true';
if (href) {
if (isExternal) {
window.open(href, '_blank');
} else {
window.location.href = href;
}
}
closeMenu();
};
// Handles click events on button items, closing the dropdown if necessary.
const handleButtonClick = () => {
closeMenu();
};
// Toggles the dropdown open/close state.
const toggleDropdown = () => {
open = !open
const ariaExpanded = open ? 'true' : 'false'
node
.querySelector('.gdd_button')
.setAttribute('aria-expanded', ariaExpanded)
const ulElement = node.querySelector('ul[role="menu"]')
if (!ulElement) return
const currentState = ulElement.getAttribute('data-state')
ulElement.setAttribute(
'data-state',
currentState === 'open' ? 'close' : 'open'
)
if (animated) {
const svgElement = node.querySelector('svg');
svgElement.classList.toggle('iconToOpen', currentState === 'close');
svgElement.classList.toggle('iconToClose', currentState === 'open');
}
}
const closeMenu = () => {
toggleDropdown()
node.focus()
}
/** ***************** START - Event Handlers ******************************************** */
// Button click event handler.
const onButtonClick = (e) => {
e.stopPropagation()
e.preventDefault()
toggleDropdown()
if (open) focusManager.setFocusToFirstItem()
}
// Button keydown event handler.
const onButtonKeydown = (e) => {
e.stopPropagation()
e.preventDefault()
switch (e.code) {
case 'Space':
case 'Enter':
case 'Down':
case 'ArrowDown':
if (!open) { // handle not open by default
toggleDropdown()
}
focusManager.setFocusToFirstItem()
break
case 'Up':
case 'ArrowUp':
if (!open) { // handle not open by default
toggleDropdown()
}
focusManager.setFocusToLastItem()
break
case 'Tab':
node.blur()
break
default:
break
}
}
// Item click event handler.
const onItemClick = handleClickOnItem;
// Item keydown event handler.
const onItemKeydown = (e) => {
e.stopPropagation()
e.preventDefault()
const target = e.currentTarget
if (e.shiftKey) {
if (isChar(e.key)) {
focusManager.setFocusByFirstChar(target, e.key)
}
} else {
switch (e.code) {
case 'Space':
case 'Enter':
handleClickOnItem(e)
break
case 'Esc':
case 'Escape':
closeMenu()
dropdownBtn.focus()
break
case 'Up':
case 'ArrowUp':
focusManager.setFocusToPreviousItem(target)
break
case 'Down':
case 'ArrowDown':
focusManager.setFocusToNextItem(target)
break
case 'Home':
case 'PageUp':
focusManager.setFocusToFirstItem()
break
case 'End':
case 'PageDown':
focusManager.setFocusToLastItem()
break
default:
if (isChar(e.key)) {
focusManager.setFocusByFirstChar(target, e.key)
}
}
}
}
// Item mouseover event handler.
const onItemMouseOver = (e) => {
const target = e.currentTarget
target.focus()
}
/** ***************** END - Event Handlers ******************************************** */
const dropdownBtn = node.querySelector(".gdd_button")
if (dropdownBtn != null && options?.enabled) {
const dropdownBtnLabel = dropdownBtn.getAttribute("aria-label").toLowerCase()
const menuNode = node.querySelector('[role="menu"]')
menuNode.setAttribute("id", ` + "`" + `dropdown-menu-${dropdownBtnLabel}` + "`" + `)
menuNode.setAttribute("aria-labelledby", ` + "`" + `dropdown-button-${dropdownBtnLabel}` + "`" + `)
initialize()
node.addEventListener('click', onButtonClick)
node.addEventListener('keydown', onButtonKeydown)
const menuItemNodes = Array.from(node.querySelectorAll('[role="menuitem"]'))
menuItemNodes.forEach((item) => {
item.addEventListener('keydown', onItemKeydown)
item.addEventListener('mouseover', onItemMouseOver)
item.addEventListener('click', onItemClick)
listGroups[componentId].push(item)
const extractFirstChar = (item) => {
const textContent = item.textContent?.split('\n').pop().trim();
const firstChar = textContent ? textContent.trim().toLowerCase()[0] : null;
return firstChar;
};
const contentFirstChar = extractFirstChar(item)
if (contentFirstChar) firstChars[componentId].push(contentFirstChar)
if (!firstItem[componentId]) {
firstItem[componentId] = item
}
lastItem[componentId] = item
})
focusManager.items = listGroups
focusManager.firstChars = firstChars
focusManager.firstItem = firstItem
focusManager.lastItem = lastItem
// set the focus on the button when open by default.
if (open) {
dropdownBtn.focus()
}
}
}
/**
* Handles the action to close the dropdown when clicked outside of it.
* @param {MouseEvent} e - The event object generated by the click action.
* @param {object} options - Options for configuring the accessibility actions.
* @param {boolean} options.animated - Flag indicating if the dropdown menu button should use icon animations.
*/
function clickOutsideAction(e, options) {
const animated = options?.animated || true;
const idSelector = ` + "`" + `gropdown-container-${options?.id}` + "`" + `;
const dropdownContainer = document.getElementById(idSelector);
if (!dropdownContainer) return;
const isClickedInsideDropdown = dropdownContainer.contains(e.target);
if (!isClickedInsideDropdown) {
dropdownBtn = dropdownContainer.querySelector('.gdd_button');
dropdownBtn.setAttribute('aria-expanded', false);
if (animated) {
const svgElement = dropdownBtn.querySelector('svg');
svgElement.classList.remove('iconToOpen');
svgElement.classList.remove('iconToClose');
}
const ulElement = dropdownContainer.querySelector('ul[role="menu"]');
if (!ulElement) return;
ulElement.setAttribute('data-state', 'close');
}
}
document.addEventListener('DOMContentLoaded', function() {
// Loop over all tabber components in the page and initialise them.
for (const key in configMap.Data) {
const gropdownConfig = configMap.Data[key];
const containerNode = document.getElementById(` + "`" + `gropdown-container-${key}` + "`" + `);
if (containerNode !== null) {
a11yActions(containerNode, {
enabled: true,
open: gropdownConfig.Open,
animated: gropdownConfig.Animation,
});
if(configMap.Data[key].CloseOnOutsideClick) {
// Add event listener to each container
document.body.addEventListener('click', function(e) {
clickOutsideAction(e,{id: key} );
});
}
}
}
});
}`,
Call: templ.SafeScript(`__templ_GropdownJS_8d5a`, configMap),
CallInline: templ.SafeScriptInline(`__templ_GropdownJS_8d5a`, configMap),
}
}