Repository navigation
Expand file tree
/
Copy pathexamples-action-buttons.html
More file actions
566 lines (521 loc) · 41.5 KB
/
Copy pathexamples-action-buttons.html
File metadata and controls
566 lines (521 loc) · 41.5 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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
<meta name="kmwc:title" content="Action Buttons Examples">
<meta name="kmwc:subtitle" content="Everything the action bar can do, each as ONE live picker you configure with control switches — built-in & static props, the dynamic callbacks (and their priority over statics), custom actions, icon buttons, layout, and a device-adaptive toolbar.">
<meta name="kmwc:body-class" content="dark-output">
<!-- Light-DOM pre-upgrade rule (= dist/style.css): reserves the input height before the JS defines the element -->
<link rel="stylesheet" href="/src/css/main.css">
<!-- Font Awesome for the icon-buttons chapter (font must be registered at document level) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<!-- ============================================================= -->
<!-- AB01 · Built-in & static properties -->
<!-- ============================================================= -->
<div class="card">
<h2>AB01 · Built-in & Static Properties</h2>
<p>
The two built-in actions — <code>select-all</code> and <code>clear-selection</code> — plus the static
per-button properties: <code>tooltip</code>, <code>cssClass</code>, <code>isVisible</code>, and
<code>isDisabled</code>. Toggle the switches to rebuild the <code>actionButtons</code> array live.
</p>
<div class="note">
<div class="note-title">Built-in smart defaults:</div>
With no static <code>isDisabled</code> (and no <code>getIsDisabledCallback</code>),
<strong>Select All</strong> auto-disables once every option is selected and
<strong>Clear All</strong> auto-disables while nothing is selected. Select all colors and watch
Select All disable.
</div>
<div class="controls">
<label title="Include the built-in select-all button. It selects every option and auto-disables once all are selected."><input type="checkbox" id="st-selall" checked> include <code>select-all</code></label>
<label title="Include the built-in clear-selection button. It clears the selection and auto-disables while nothing is selected."><input type="checkbox" id="st-clrall" checked> include <code>clear-selection</code></label>
<label title="Add a static tooltip string to each button (shown on hover)."><input type="checkbox" id="st-tooltips"> static <code>tooltip</code>s</label>
<label title="Apply cssClass:'custom-select-btn' to Select All. The class is injected into the Shadow DOM via getCustomStylesCallback (page CSS can't reach inside)."><input type="checkbox" id="st-style"> <code>cssClass</code> on Select All</label>
</div>
<div class="controls">
<label title="Add a custom button with isVisible:false — it stays in the config but is not rendered. Proof that isVisible hides a button."><input type="checkbox" id="st-hidden"> add a hidden button (<code>isVisible:false</code>)</label>
<label title="Add a custom button with isDisabled:true — rendered but greyed out and non-clickable."><input type="checkbox" id="st-disabled"> add a disabled button (<code>isDisabled:true</code>)</label>
</div>
<kmwc-demo>
<label class="demo-label">Select Colors:</label>
<web-multiselect id="ab-static" multiple="true"></web-multiselect>
<div class="output">
<div class="output-label">Selected:</div>
<pre id="out-static" data-kmwc-value-readout="ab-static" data-kmwc-property="selectedValue"></pre>
</div>
<script type="module" data-kmwc-show>
const colors = document.getElementById('ab-static');
colors.options = [
['red', 'Red'], ['blue', 'Blue'], ['green', 'Green'], ['yellow', 'Yellow'], ['purple', 'Purple']
];
// cssClass lands inside the Shadow DOM — page CSS can't reach it, so inject the rule:
colors.getCustomStylesCallback = () =>
`.custom-select-btn { background:#667eea !important; color:#fff !important; font-weight:600; }`;
// Rebuild the actionButtons array from the switches above.
const isOn = (id) => document.getElementById(id).checked;
const buildButtons = () => {
colors.actionButtons = [
isOn('st-selall') && { action: 'select-all', text: 'Select All',
...(isOn('st-tooltips') && { tooltip: 'Select all available colors' }), // static tooltip
...(isOn('st-style') && { cssClass: 'custom-select-btn' }) }, // needs getCustomStylesCallback
isOn('st-clrall') && { action: 'clear-selection', text: 'Clear All',
...(isOn('st-tooltips') && { tooltip: 'Remove all selections' }) },
isOn('st-hidden') && { id: 'hidden', text: 'Hidden Button', isVisible: false, onClick: () => {} },
isOn('st-disabled') && { id: 'disabled', text: 'Disabled Button', tooltip: 'This button is always disabled',
isDisabled: true, onClick: () => {} },
].filter(Boolean);
};
['st-selall', 'st-clrall', 'st-tooltips', 'st-style', 'st-hidden', 'st-disabled'].forEach((id) =>
document.getElementById(id).addEventListener('change', buildButtons));
buildButtons();
// Built-ins only? The string shorthand takes the default text from labels['buttons.selectAll'] / labels['buttons.clearSelection']:
// colors.actionButtons = ['select-all', 'clear-selection'];
</script>
</kmwc-demo>
</div>
<!-- ============================================================= -->
<!-- AB02 · Dynamic callbacks -->
<!-- ============================================================= -->
<div class="card">
<h2>AB02 · Dynamic Callbacks (& Priority)</h2>
<p>
Each button property has a dynamic twin that recomputes from the selection snapshot
<code>ctx</code> (<code>selectedCount</code>, <code>optionCount</code>, <code>selectedValues</code>,
<code>selectedOptions</code>, <code>options</code>, <code>isOpen</code>, <code>searchTerm</code>,
<code>controller</code>):
<code>getIsVisibleCallback</code>, <code>getIsDisabledCallback</code>,
<code>getTextCallback</code>, <code>getClassCallback</code>, and
<code>getTooltipCallback</code>. Pick which one drives the buttons — or choose
<strong>all (priority)</strong> to see every callback active at once, overriding the static
<code>text</code> / <code>isVisible</code> / <code>isDisabled</code> that are also set.
</p>
<div class="controls">
<span>callback:</span>
<label title="No dynamic callbacks — the buttons use only their static text/tooltip. Baseline to compare against."><input type="radio" name="dyn-cb" value="none" checked> none (static)</label>
<label title="getIsVisibleCallback — show/hide buttons by selection state: Clear All appears once something is selected; Select All hides when everything is selected."><input type="radio" name="dyn-cb" value="visibility"> visibility</label>
<label title="getIsDisabledCallback — enable/disable by state: Select All disables when all are selected, Clear All while nothing is; plus a 'Select First 3' button disabled when fewer than 3 options exist."><input type="radio" name="dyn-cb" value="disabled"> disabled</label>
<label title="getTextCallback — the button label recomputes live, e.g. 'Select All (8)', 'Clear 3 Selected', and a Select/Deselect toggle."><input type="radio" name="dyn-cb" value="text"> text</label>
<label title="getClassCallback — swap CSS classes by state (green→amber Select All; red active Clear). The classes are injected into the Shadow DOM via getCustomStylesCallback."><input type="radio" name="dyn-cb" value="class"> class</label>
<label title="getTooltipCallback — the hover text recomputes live (remaining count, how many will be cleared); plus a 'Random Select' button. Hover the buttons to see it."><input type="radio" name="dyn-cb" value="tooltip"> tooltip</label>
<label title="Every callback active at once on buttons that ALSO set static isVisible:false / isDisabled:true — the callbacks win over the statics. Selection caps at 5."><input type="radio" name="dyn-cb" value="all"> all (priority)</label>
</div>
<div class="demo-area">
<label class="demo-label">Select Items (the <code>all</code> mode caps at 5):</label>
<web-multiselect id="ab-dynamic" multiple="true"></web-multiselect>
<div class="output">
<div class="output-label">Selected:</div>
<pre id="out-dynamic" data-kmwc-value-readout="ab-dynamic" data-kmwc-property="selectedValue"></pre>
</div>
</div>
<div class="note">
<div class="note-title">Priority:</div>
When both a static property and its callback are set, the callback wins:
<code>get*Callback</code> > static > default. Try <strong>all (priority)</strong> — the
buttons carry <code>isVisible:false</code> / <code>isDisabled:true</code> yet the callbacks keep
them visible and enabled.
</div>
</div>
<!-- ============================================================= -->
<!-- AB03 · Custom actions -->
<!-- ============================================================= -->
<div class="card">
<h2>AB03 · Custom Actions with <code>onClick</code></h2>
<p>
Build your own buttons with an <code>id</code> (no <code>action</code> — that's only for the
built-ins) and an <code>onClick(detail)</code> handler. <code>detail</code> is the
<code>action</code> event detail: the selection snapshot (<code>selectedValues</code>,
<code>options</code>, …) plus <code>id</code>, <code>source</code> and <code>controller</code>,
which drives the component (<code>setSelected</code>, <code>selectAll</code>, <code>selectedValue</code>, …).
Here: pick popular languages, invert the selection, or pick two at random — plus the built-in Clear All.
Every activation also fires the <code>action</code> event (<code>el.onAction</code>), and
<code>beforeActionCallback(detail)</code> can cancel it by returning <code>false</code>.
</p>
<kmwc-demo>
<label class="demo-label">Select Programming Languages:</label>
<web-multiselect id="ab-custom" multiple="true"></web-multiselect>
<div class="output">
<div class="output-label">Selected:</div>
<pre id="out-custom" data-kmwc-value-readout="ab-custom" data-kmwc-property="selectedValue"></pre>
</div>
<script type="module" data-kmwc-show>
const languages = document.getElementById('ab-custom');
languages.options = [
['js', 'JavaScript'], ['ts', 'TypeScript'], ['py', 'Python'], ['java', 'Java'],
['go', 'Go'], ['rust', 'Rust'], ['cpp', 'C++'], ['ruby', 'Ruby']
];
const values = (options) => options.map(([value]) => value);
languages.actionButtons = [
{ id: 'popular', text: 'Select Popular', tooltip: 'Select JS, Python, and TypeScript',
onClick: ({ controller }) => controller.setSelected(['js', 'py', 'ts'], { notify: true }) },
{ id: 'invert', text: 'Invert Selection', tooltip: 'Invert current selection',
onClick: ({ controller, options, selectedValues }) =>
controller.setSelected(values(options).filter((v) => !selectedValues.includes(v)), { notify: true }) },
{ id: 'random', text: 'Select Random', tooltip: 'Select 2 random languages',
onClick: ({ controller, options }) =>
controller.setSelected(values([...options].sort(() => Math.random() - 0.5).slice(0, 2)), { notify: true }) },
{ action: 'clear-selection', text: 'Clear All' }
];
// Every activation (built-in or custom) also fires the `action` event:
// languages.onAction = ({ action, id, source }) => console.log(action, id, source);
</script>
</kmwc-demo>
</div>
<!-- ============================================================= -->
<!-- AB04 · Icon buttons -->
<!-- ============================================================= -->
<div class="card">
<h2>AB04 · Icon Buttons — Unicode Glyphs vs Font Awesome (font)</h2>
<p>
Each button has an <code>icon</code> field (and a dynamic <code>getIconCallback(ctx)</code>), rendered in
a <code>.ms__action-btn-icon</code> span before the <code>.ms__action-btn-label</code>. Both
<code>icon</code> and <code>text</code> are inserted as <strong>text, never HTML</strong> — so the icon is
a glyph: a <strong>Unicode symbol / emoji</strong> works with zero setup, and a
<strong>Font Awesome</strong> icon works as its code-point character, provided the
<code>@font-face</code> lives at document level (a <code><link></code> in the page
<code><head></code>, or an <code>@import</code> in the custom CSS, which core links there for
you) <em>and</em> the icon span gets the font via
<code>getCustomStylesCallback</code>. Inline SVG / <code><i class="fa-…"></code> markup is no
longer possible. Flip the switch to compare.
</p>
<div class="controls">
<span>icon library:</span>
<label title="Unicode glyphs / emoji in the icon field. No font, no <head> link, no CSS injection. The recommended path."><input type="radio" name="ico-lib" value="glyph" checked> Unicode glyphs (zero setup)</label>
<label title="Font Awesome code points in the icon field. Needs BOTH the @font-face at document level (the <link> in <head>) AND font-family on .ms__action-btn-icon injected via getCustomStylesCallback, or glyphs render as empty boxes."><input type="radio" name="ico-lib" value="fa"> Font Awesome (font)</label>
</div>
<div class="demo-area">
<label class="demo-label">Select Technologies:</label>
<web-multiselect id="ab-icons" multiple="true"></web-multiselect>
<div class="output">
<div class="output-label">Selected:</div>
<pre id="out-icons" data-kmwc-value-readout="ab-icons" data-kmwc-property="selectedValue"></pre>
</div>
</div>
<div class="note">
<div class="note-title">Prefer plain glyphs in Shadow DOM:</div>
A Unicode glyph needs no <code>@font-face</code>, no <code><head></code> link, and no CSS
injection. Font icons work, but require both halves (font at document level +
<code>font-family</code> on <code>.ms__action-btn-icon</code> in the shadow) or the glyphs render as
empty <code>□</code> boxes. Icon-only buttons (no <code>text</code>) should always carry a
descriptive <code>tooltip</code>.
</div>
</div>
<!-- ============================================================= -->
<!-- AB05 · Positioning, rows & alignment -->
<!-- ============================================================= -->
<div class="card">
<h2>AB05 · Positioning, Rows & Alignment</h2>
<p>
Place the actions block at the <code>top</code> (default) or <code>bottom</code> of the dropdown,
flow buttons across multiple rows with the per-button <code>row</code> property, and set horizontal
alignment with <code>actions-align</code>. Open the dropdown to see the bar move.
</p>
<div class="controls">
<span><code>actions-position</code>:</span>
<label title="Render the action bar above the options list (the default)."><input type="radio" name="lay-pos" value="top" checked> top</label>
<label title="Render the action bar below the options list."><input type="radio" name="lay-pos" value="bottom"> bottom</label>
<label style="margin-inline-start:1rem" title="Split the buttons across two rows using each button's per-button row property (row:1 / row:2). Off = a single row."><input type="checkbox" id="lay-rows" checked> two rows (per-button <code>row</code>)</label>
</div>
<div class="controls">
<span><code>actions-align</code>:</span>
<label title="actions-align:'stretch' (default) — buttons stretch to fill the bar width."><input type="radio" name="lay-align" value="stretch" checked> stretch</label>
<label title="actions-align:'left' — buttons packed to the start of the bar."><input type="radio" name="lay-align" value="left"> left</label>
<label title="actions-align:'center' — buttons centered in the bar."><input type="radio" name="lay-align" value="center"> center</label>
<label title="actions-align:'right' — buttons packed to the end of the bar."><input type="radio" name="lay-align" value="right"> right</label>
<label title="actions-align:'space-between' — buttons pushed to the edges with the gap distributed between them."><input type="radio" name="lay-align" value="space-between"> space-between</label>
</div>
<div class="demo-area">
<label class="demo-label">Open the dropdown to see the action bar:</label>
<web-multiselect id="ab-layout" multiple="true"></web-multiselect>
</div>
<div class="note">
<div class="note-title">Row ordering:</div>
Row 1 always sits at the panel's outer edge; higher rows stack inward toward the options list.
So <code>top</code> renders row 1 first (top), and <code>bottom</code> renders row 1 last (bottom).
</div>
</div>
<!-- ============================================================= -->
<!-- AB06 · Device-adaptive actions -->
<!-- ============================================================= -->
<div class="card">
<h2>AB06 · Device-Adaptive Actions</h2>
<p>
Twelve action buttons fit one row on a wide desktop, but there's no room on a phone, a
tablet, or a narrowed window. The fix isn't a CSS trick: define your action sets and let a
<strong>responsive rule</strong> pick the right one. A per-tag
<code>responsiveCallback</code> on <code>window.components['web-multiselect']</code> returns a
partial config for the current device class / viewport width; the component re-runs it on
every device-class flip and (callbacks only) every viewport-width change, and applies only
what changed — no app-side viewport observer, no
"did it change" bookkeeping. The rule is page-wide, so it opts in by a marker attribute
(<code>data-adaptive-actions</code>); anything set explicitly on a picker still wins over it.
</p>
<ul>
<li><strong>Desktop, wide (> 600px):</strong> all twelve buttons, one row (<code>nowrap</code>).</li>
<li><strong>Desktop, narrowed (≤ 600px):</strong> all twelve, flowed onto two rows (<code>wrap</code>).
A mouse device stays <code>desktop</code> at any width, so this is a width check
(<code>ctx.env.viewportWidth</code>), not a device class.</li>
<li><strong>Tablet:</strong> all twelve wrapped — a single row would run beyond the edge.</li>
<li><strong>Phone:</strong> the three essentials only, wrapped.</li>
</ul>
<kmwc-demo>
<label class="demo-label">
<code id="adaptive-device">…</code>
<span class="form-text" style="display:inline;">— resize the window (cross 600px) or toggle the device toolbar (DevTools) to see the toolbar re-shape.</span>
</label>
<web-multiselect id="ab-adaptive" multiple="true" data-adaptive-actions></web-multiselect>
<div class="output">
<div class="output-label">Selected:</div>
<pre id="out-adaptive" data-kmwc-value-readout="ab-adaptive" data-kmwc-property="selectedValue"></pre>
</div>
<script type="module" data-kmwc-show>
const items = [
['item1', 'Item 1'], ['item2', 'Item 2'], ['item3', 'Item 3'], ['item4', 'Item 4'],
['item5', 'Item 5'], ['item6', 'Item 6'], ['item7', 'Item 7'], ['item8', 'Item 8']
];
document.getElementById('ab-adaptive').options = items;
const values = (options) => options.map(([value]) => value);
const pick = (options) => ({ controller }) => controller.setSelected(values(options), { notify: true });
const pickRandom = (n) => ({ controller }) =>
controller.setSelected(values([...items].sort(() => Math.random() - 0.5).slice(0, n)), { notify: true });
const invert = ({ controller, options, selectedValues }) =>
controller.setSelected(values(options).filter((v) => !selectedValues.includes(v)), { notify: true });
const half = Math.ceil(items.length / 2);
const desktopActions = [
{ action: 'select-all', text: 'Select All Items' },
{ action: 'clear-selection', text: 'Clear Selection' },
{ id: 'first-3', text: 'First 3 Items', onClick: pick(items.slice(0, 3)) },
{ id: 'last-3', text: 'Last 3 Items', onClick: pick(items.slice(-3)) },
{ id: 'even', text: 'Even Positions', onClick: pick(items.filter((o, i) => i % 2 === 0)) },
{ id: 'odd', text: 'Odd Positions', onClick: pick(items.filter((o, i) => i % 2 === 1)) },
{ id: 'random', text: 'Random Selection', onClick: pickRandom(3) },
{ id: 'first-half', text: 'First Half', onClick: pick(items.slice(0, half)) },
{ id: 'second-half', text: 'Second Half', onClick: pick(items.slice(half)) },
{ id: 'invert', text: 'Invert', onClick: invert },
{ id: 'every-third', text: 'Every Third', onClick: pick(items.filter((o, i) => i % 3 === 0)) },
{ id: 'shuffle', text: 'Shuffle All', onClick: pickRandom(5) }
];
const mobileActions = [
{ action: 'select-all', text: 'All' },
{ action: 'clear-selection', text: 'Clear' },
{ id: 'invert', text: 'Invert', onClick: invert }
];
// A per-tag responsive rule (core SPEC §6.7), re-run by the component on every device-class
// flip and (callbacks only) every viewport-width change; only changed keys apply. It may be set
// before the component script loads: window.components = { 'web-multiselect': { responsiveCallback } }.
// Typed: import type { MultiSelectResponsiveCallback } from '@keenmate/web-multiselect';
const readout = document.getElementById('adaptive-device');
window.components['web-multiselect'].responsiveCallback = (ctx) => {
if (!ctx.element.hasAttribute('data-adaptive-actions')) return undefined; // opt-in marker
let partial;
if (ctx.deviceClass === 'mobile') { // phone: essentials, wrapped
partial = { actionButtons: mobileActions, actionsLayout: 'wrap' };
} else if (ctx.deviceClass === 'tablet') { // tablet: full set, wrapped
partial = { actionButtons: desktopActions, actionsLayout: 'wrap' };
} else { // desktop (mouse, any width): two rows at <= 600px
partial = { actionButtons: desktopActions, actionsLayout: ctx.env.viewportWidth <= 600 ? 'wrap' : 'nowrap' };
}
const rows = partial.actionsLayout === 'wrap' ? 'wrapped' : 'one row';
readout.textContent = `${ctx.deviceClass} · ${ctx.env.viewportWidth}px · ${partial.actionButtons.length} buttons · ${rows}`;
return partial;
};
</script>
</kmwc-demo>
</div>
<!-- ============================================================= -->
<!-- AB07 · Summary -->
<!-- ============================================================= -->
<div class="card">
<h2>AB07 · Summary</h2>
<h3>Static Properties</h3>
<div class="code-block" data-language="ts"><pre><code>action?: 'select-all' | 'clear-selection' // Built-ins only (or the string shorthand 'select-all')
id?: string // Identifies a custom item (reported in the action event)
text?: string // Plain text (default for built-ins: labels['buttons.selectAll'] / clearSelection)
icon?: string // Plain-text glyph, rendered before the text
row?: number // Optional (default: 1) — which button row
tooltip?: string // Optional
cssClass?: string // Optional
isVisible?: boolean // Optional (default: true)
isDisabled?: boolean // Optional (default: false)
isDanger?: boolean // Destructive styling (default: false)
isToggled?: boolean // Toggle state (ON) → aria-pressed (default: false)</code></pre></div>
<h3>Dynamic Callbacks</h3>
<div class="code-block" data-language="ts"><pre><code>onClick?: (detail) => void | Promise<void> // Runs for built-ins too, before the built-in
getIsVisibleCallback?: (ctx) => boolean // Dynamic visibility
getIsDisabledCallback?: (ctx) => boolean // Dynamic disabled state
getIsToggledCallback?: (ctx) => boolean // Dynamic toggle state
getTextCallback?: (ctx) => string // Dynamic text
getIconCallback?: (ctx) => string // Dynamic icon
getClassCallback?: (ctx) => string | string[] // Dynamic CSS classes
getTooltipCallback?: (ctx) => string // Dynamic tooltip
// ctx = { selectedValues, selectedOptions, options, selectedCount, optionCount, isOpen, searchTerm, controller, element }
// detail = ctx + { action, id, item, source, sourceEvent, triggerElement, dataset }
beforeActionCallback?: (detail) => false | void // element-level: false cancels onClick, the action event and the built-in
onAction / 'action' event // every activation — order: beforeActionCallback → onClick → action → built-in</code></pre></div>
<h3>Layout attributes</h3>
<div class="code-block" data-language="ts"><pre><code>actions-position // 'top' (default) | 'bottom'
actions-layout // 'nowrap' (default) | 'wrap'
actions-align // 'stretch' (default) | 'left' | 'center' | 'right' | 'space-between'</code></pre></div>
<h3>Priority Rules</h3>
<div class="note">
<div class="note-title">When both static and callback are defined:</div>
<ul style="margin-top: 0.5rem; margin-left: 1.5rem;">
<li><code>getIsVisibleCallback</code> > <code>isVisible</code> > default <code>true</code></li>
<li><code>getIsDisabledCallback</code> > <code>isDisabled</code> > default <code>false</code></li>
<li><code>getTextCallback</code> > <code>text</code></li>
<li><code>getClassCallback</code> > <code>cssClass</code></li>
<li><code>getTooltipCallback</code> > <code>tooltip</code></li>
</ul>
</div>
</div>
<script type="module">
import { attachControlsPersistence } from '@keenmate/web-components-devkit/examples';
// Loads (and registers) the component — window.components['web-multiselect'] exists
// afterwards. The build rewrites /src/index.ts → the dist bundle.
import '/src/index.ts';
// ── Datasets (tuple [value, label]) ──────────────────────────────
const itemOptions = [
['item1', 'Item 1'], ['item2', 'Item 2'], ['item3', 'Item 3'], ['item4', 'Item 4'],
['item5', 'Item 5'], ['item6', 'Item 6'], ['item7', 'Item 7'], ['item8', 'Item 8']
];
const techOptions = [
['js', 'JavaScript'], ['ts', 'TypeScript'], ['py', 'Python'], ['java', 'Java'],
['cpp', 'C++'], ['go', 'Go'], ['rust', 'Rust'], ['php', 'PHP'], ['ruby', 'Ruby'], ['swift', 'Swift']
];
// Custom-button CSS lives in Shadow DOM — page CSS can't cross the boundary.
const BTN_STYLES = `
.success-btn { background:#48bb78 !important; color:#fff !important; }
.warning-btn { background:#ed8936 !important; color:#fff !important; }
.danger-btn { background:#f56565 !important; color:#fff !important; }
.active-state { border:2px solid #667eea !important; }
.inactive-state { opacity:0.6; }
`;
document.addEventListener('DOMContentLoaded', () => {
// AB01 / AB03 / AB06 configure their pickers in their own (shown) demo scripts; the
// "Selected:" read-outs are the devkit's (data-kmwc-value-readout).
// Shared helpers — `ctx` is the action-item selection snapshot.
const values = (opts) => opts.map((o) => o[0]);
const invert = ({ controller, options, selectedValues }) =>
controller.setSelected(values(options).filter((v) => !selectedValues.includes(v)), { notify: true });
const pickRandom = (controller, opts, n) =>
controller.setSelected(values([...opts].sort(() => Math.random() - 0.5).slice(0, n)), { notify: true });
// ── AB02 · Dynamic callbacks ─────────────────────────────────
const abDyn = document.getElementById('ab-dynamic');
abDyn.options = itemOptions;
abDyn.getCustomStylesCallback = () => BTN_STYLES;
const dynSets = {
none: () => [
{ action: 'select-all', text: 'Select All', tooltip: 'Select all items' },
{ action: 'clear-selection', text: 'Clear All', tooltip: 'Clear selection' }
],
visibility: () => [
{ action: 'select-all', text: 'Select All', tooltip: 'Select all items',
getIsVisibleCallback: ({ selectedCount, optionCount }) => selectedCount < optionCount },
{ action: 'clear-selection', text: 'Clear All', tooltip: 'Clear selection',
getIsVisibleCallback: ({ selectedCount }) => selectedCount > 0 }
],
disabled: () => [
{ action: 'select-all', text: 'Select All',
getIsDisabledCallback: ({ selectedCount, optionCount }) => selectedCount >= optionCount },
{ action: 'clear-selection', text: 'Clear All',
getIsDisabledCallback: ({ selectedCount }) => selectedCount === 0 },
{ id: 'first-3', text: 'Select First 3',
getIsDisabledCallback: ({ optionCount }) => optionCount < 3,
onClick: ({ controller, options }) => controller.setSelected(values(options.slice(0, 3)), { notify: true }) }
],
text: () => [
{ action: 'select-all', text: 'Select All',
getTextCallback: ({ optionCount }) => `Select All (${optionCount})` },
{ action: 'clear-selection', text: 'Clear All',
getTextCallback: ({ selectedCount: c }) => c > 0 ? `Clear ${c} Selected` : 'Clear All' },
{ id: 'toggle', text: 'Toggle',
getTextCallback: ({ selectedCount, optionCount }) => selectedCount === optionCount ? 'Deselect All' : 'Select All',
onClick: ({ controller, selectedCount, optionCount }) => selectedCount === optionCount ? controller.setSelected([], { notify: true }) : controller.selectAll() }
],
class: () => [
{ action: 'select-all', text: 'Select All', cssClass: 'default-class',
getClassCallback: ({ selectedCount }) => selectedCount === 0 ? 'success-btn' : 'warning-btn' },
{ action: 'clear-selection', text: 'Clear All',
getClassCallback: ({ selectedCount }) => selectedCount > 0 ? ['danger-btn', 'active-state'] : 'inactive-state' }
],
tooltip: () => [
{ action: 'select-all', text: 'Select All', tooltip: 'Default tooltip',
getTooltipCallback: ({ selectedCount: s, optionCount: t }) => `Select all ${t} items (${t - s} remaining)` },
{ action: 'clear-selection', text: 'Clear All',
getTooltipCallback: ({ selectedCount: c }) => c > 0 ? `Remove ${c} selected item${c !== 1 ? 's' : ''}` : 'Nothing to clear' },
{ id: 'random', text: 'Random Select',
getTooltipCallback: ({ optionCount }) => `Randomly select 3 items from ${optionCount} available`,
onClick: ({ controller, options }) => pickRandom(controller, options, 3) }
],
all: () => [
{ action: 'select-all',
text: 'Static Text', tooltip: 'Static Tooltip', cssClass: 'static-class', isVisible: false, isDisabled: true,
getTextCallback: ({ selectedCount, optionCount }) => `Select All (${selectedCount}/${optionCount})`,
getTooltipCallback: ({ selectedCount }) => selectedCount >= 5 ? 'Maximum 5 items allowed' : 'Click to select all items',
getClassCallback: ({ selectedCount }) => selectedCount >= 5 ? 'danger-btn' : 'success-btn',
getIsVisibleCallback: ({ selectedCount, optionCount }) => selectedCount < optionCount,
getIsDisabledCallback: ({ selectedCount }) => selectedCount >= 5 },
{ action: 'clear-selection', text: 'Clear',
getTextCallback: ({ selectedCount }) => `Clear (${selectedCount})`,
getClassCallback: ({ selectedCount }) => selectedCount > 0 ? ['danger-btn', 'active-state'] : 'inactive-state',
getIsVisibleCallback: ({ selectedCount }) => selectedCount > 0,
getIsDisabledCallback: ({ selectedCount }) => selectedCount === 0 }
]
};
document.querySelectorAll('input[name="dyn-cb"]').forEach((r) =>
r.addEventListener('change', (e) => { if (e.target.checked) abDyn.actionButtons = dynSets[e.target.value](); }));
abDyn.actionButtons = dynSets.none();
// ── AB04 · Icon buttons (Unicode glyphs vs Font Awesome) ─────
const abIcons = document.getElementById('ab-icons');
abIcons.options = techOptions;
// `icon` / `text` are plain text, so each icon is a single character.
const iconButtons = (ic) => [
{ action: 'select-all', icon: ic.check, text: 'Select All', tooltip: 'Select all available technologies' },
{ action: 'clear-selection', icon: ic.x, text: 'Clear', tooltip: 'Clear all selections' },
{ id: 'random', icon: ic.shuffle, text: 'Random', tooltip: 'Select 3 random technologies',
onClick: ({ controller }) => pickRandom(controller, techOptions, 3) },
{ id: 'invert', icon: ic.refresh, tooltip: 'Invert Selection', onClick: invert },
{ id: 'toggle',
getIconCallback: ({ selectedCount, optionCount }) => selectedCount === optionCount ? ic.toggleOn : ic.toggleOff,
getTextCallback: ({ selectedCount, optionCount }) => `${selectedCount}/${optionCount}`,
getIsToggledCallback: ({ selectedCount, optionCount }) => selectedCount === optionCount,
getTooltipCallback: ({ selectedCount, optionCount }) => selectedCount === optionCount ? 'Deselect all' : 'Select all',
onClick: ({ controller, selectedCount, optionCount }) => selectedCount === optionCount ? controller.setSelected([], { notify: true }) : controller.selectAll() }
];
const glyphIcons = { check: '✔', x: '✕', shuffle: '🔀', refresh: '⇄', toggleOn: '◉', toggleOff: '○' };
// Font Awesome 6 Free (solid) code points: check-double, xmark, shuffle, rotate, toggle-on, toggle-off.
const faIcons = { check: '\uf560', x: '\uf00d', shuffle: '\uf074', refresh: '\uf2f1', toggleOn: '\uf205', toggleOff: '\uf204' };
const applyIcons = (lib) => {
if (lib === 'fa') {
// The <link> in <head> registers the font; the icon span needs the font-family in the Shadow DOM.
abIcons.getCustomStylesCallback = () => `.ms__action-btn-icon { font-family: 'Font Awesome 6 Free'; font-weight: 900; }`;
abIcons.actionButtons = iconButtons(faIcons);
} else {
// Plain glyphs need no shadow-DOM style injection — clear it.
abIcons.getCustomStylesCallback = () => '';
abIcons.actionButtons = iconButtons(glyphIcons);
}
};
document.querySelectorAll('input[name="ico-lib"]').forEach((r) =>
r.addEventListener('change', (e) => { if (e.target.checked) applyIcons(e.target.value); }));
applyIcons('glyph');
// ── AB05 · Positioning, rows & alignment ─────────────────────
const abLayout = document.getElementById('ab-layout');
abLayout.options = itemOptions;
const twoRowButtons = [
{ action: 'select-all', text: 'Select All', row: 1 },
{ action: 'clear-selection', text: 'Clear All', row: 1 },
{ id: 'first-3', text: 'First 3', row: 2, onClick: ({ controller }) => controller.setSelected(values(itemOptions.slice(0, 3)), { notify: true }) },
{ id: 'invert', text: 'Invert', row: 2, onClick: invert }
];
const oneRowButtons = ['select-all', 'clear-selection']; // string shorthand (text from labels)
const layRows = document.getElementById('lay-rows');
const applyLayout = () => {
abLayout.actionButtons = layRows.checked ? twoRowButtons : oneRowButtons;
};
document.querySelectorAll('input[name="lay-pos"]').forEach((r) =>
r.addEventListener('change', (e) => { if (e.target.checked) abLayout.setAttribute('actions-position', e.target.value); }));
document.querySelectorAll('input[name="lay-align"]').forEach((r) =>
r.addEventListener('change', (e) => { if (e.target.checked) abLayout.setAttribute('actions-align', e.target.value); }));
layRows.addEventListener('change', applyLayout);
applyLayout();
// Persist all control switches to localStorage and restore them on reload —
// re-applies to every picker via the listeners wired above.
attachControlsPersistence('action-buttons');
});
</script>