Repository navigation
Expand file tree
/
Copy pathexamples-basic.html
More file actions
197 lines (182 loc) · 11.1 KB
/
Copy pathexamples-basic.html
File metadata and controls
197 lines (182 loc) · 11.1 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
<meta name="kmwc:title" content="Basic Usage">
<meta name="kmwc:subtitle" content="The three-line setup, the ways to open the palette, the effect events (<code>select</code> / <code>action</code>), and translating the UI with <code>labels</code>.">
<meta name="kmwc:body-class" content="dark-output">
<!-- ============================================================= -->
<!-- BU01 · The three-line setup -->
<!-- ============================================================= -->
<div class="card">
<h2>BU01 · The Three-Line Setup</h2>
<p>
Mount one <code><web-command-palette></code> per page and give it
<code>commands</code>, <code>contexts</code> and a <code>searchCallback</code>. That's a
fully working palette. Press <kbd>Ctrl</kbd>/<kbd>⌘</kbd>+<kbd>K</kbd>, then type
<code>/</code> for commands, <code>:</code> for contexts, or anything else for global search.
</p>
<div class="code-block" data-language="js"><pre><code>palette.commands = [{ id: 'home', trigger: '/home', text: 'Go home', shortcut: 'g h' }, …];
palette.contexts = [{ id: 'people', trigger: ':people', aliases: [':p'], text: 'People' }];
palette.searchCallback = async ({ scope, term, signal }) => fetchResults(scope, term, signal);</code></pre></div>
<div class="demo-area">
<button type="button" data-open="">Open (Ctrl/⌘+K)</button>
<button type="button" class="secondary" data-open="/">/ commands</button>
<button type="button" class="secondary" data-open=":">: contexts</button>
<button type="button" class="secondary" data-open="ada">“ada” (global)</button>
</div>
</div>
<!-- ============================================================= -->
<!-- BU02 · Opening the palette -->
<!-- ============================================================= -->
<div class="card">
<h2>BU02 · Opening the Palette</h2>
<p>
<code>open-key</code> sets the key used with Ctrl/⌘ (clear it to disable the global hotkey).
A command's <code>shortcut: 'g h'</code> runs it from anywhere while the palette is closed.
These <kbd>g</kbd>-sequences are ignored while you type in a field. Hosts can also call
<code>el.controller.open()</code>, <code>toggle()</code> or <code>openWith(term)</code> to open it already filled in.
</p>
<div class="controls">
<span><code>open-key</code>:</span>
<label><input type="radio" name="bu02-key" value="k" checked> k</label>
<label><input type="radio" name="bu02-key" value="p"> p</label>
<label><input type="radio" name="bu02-key" value=""> <em>(disabled)</em></label>
</div>
<div class="demo-area">
<button type="button" data-open="/theme ">openWith('/theme ')</button>
<button type="button" class="secondary" data-open=":p ">openWith(':p ')</button>
<p class="muted mt-1">Click the page background, then press <kbd>g</kbd> <kbd>h</kbd>.</p>
</div>
</div>
<!-- ============================================================= -->
<!-- BU03 · Effect events -->
<!-- ============================================================= -->
<div class="card">
<h2>BU03 · Effect Events</h2>
<p>
The host performs the effect and the palette closes itself:
<code>select</code> for a search result, and <code>action</code> when a command runs (a command is
a core action item: <code>detail.id</code> is the command id, <code>detail.selections</code> the wizard's
answers, empty for an instant command). <code>open</code> and <code>close</code> bracket every session.
Each event has a camelCase twin (<code>el.onAction = (detail) => …</code>), and
<code>beforeActionCallback</code> / <code>beforeResultSelectCallback</code> can return <code>false</code> to cancel.
</p>
<div class="output">
<div class="output-label">Event log</div>
<pre id="bu03-log">Open the palette and pick something…</pre>
</div>
</div>
<!-- ============================================================= -->
<!-- BU04 · Labels (i18n) -->
<!-- ============================================================= -->
<div class="card">
<h2>BU04 · Labels (i18n)</h2>
<p>
Every visible string comes from <code>labels</code>. It's partial: unset keys fall back to English, and
<code>{name}</code>, <code>{page}</code>, <code>{total}</code> and <code>{count}</code> are filled in.
</p>
<div class="controls">
<span><code>labels</code>:</span>
<label><input type="radio" name="bu04-lang" value="en" checked> English</label>
<label><input type="radio" name="bu04-lang" value="cs"> Čeština</label>
</div>
<div class="demo-area">
<button type="button" data-open=":p ">Open a context</button>
</div>
</div>
<!-- ============================================================= -->
<!-- BU05 · Page-wide labels (window.components.locale) -->
<!-- ============================================================= -->
<div class="card">
<h2>BU05 · Page-wide labels — <code>window.components.locale</code></h2>
<p>
Every UI string goes through core <code>/locale</code>: the instance <code>labels</code> (BU04) win, then the
page-wide flat dictionary <code>window.components.locale.labels['web-command-palette.<key>']</code>, then
English. Keys are <code><elementType>.<name></code> (<code>placeholders.idle</code>,
<code>messages.noResults</code>, <code>labels.pageOf</code>, …). Assigning the
page object re-renders an open palette in place — try it with the palette open. The numbers in
<code>{count}</code>, <code>{page}</code> and <code>{total}</code> are formatted for the locale: the
<em>Numbers</em> context returns 12,345 rows, so the pagination reads <code>12 345</code> in Czech.
</p>
<div class="controls">
<span><code>window.components.locale</code>:</span>
<label><input type="radio" name="bu05-lang" value="en" checked> unset (English)</label>
<label><input type="radio" name="bu05-lang" value="cs"> Czech, page-wide</label>
</div>
<div class="demo-area">
<button type="button" data-open=":n 1">Open the Numbers context</button>
</div>
<div class="code-block" data-language="js"><pre><code>window.components.locale = {
locale: 'cs',
labels: {
'web-command-palette.labels.pageOf': 'Strana {page} z {total} · {count} výsledků',
'web-command-palette.messages.noResults': 'Nic nenalezeno',
…
},
};</code></pre></div>
</div>
<!-- One palette per page: it owns the global Ctrl/⌘+K listener. -->
<web-command-palette id="palette"></web-command-palette>
<!-- Page wiring -->
<script type="module">
import { attachControlsPersistence } from '@keenmate/web-components-devkit/examples';
const CS = {
'placeholders.idle': 'Napište / pro příkazy, : pro hledání, nebo cokoli…',
'messages.noResults': 'Nic nenalezeno',
'messages.searching': 'Hledám…',
'labels.scopeSearchingIn': 'Hledání v: {name}',
'messages.typeToSearch': 'Začněte psát pro hledání v: {name}',
'headers.commands': 'Příkazy', 'headers.search': 'Hledání',
'labels.scopeCommands': 'Příkazy', 'labels.scopeContexts': 'Oblasti hledání',
'labels.navigate': 'Pohyb', 'labels.select': 'Vybrat', 'labels.back': 'Zpět', 'labels.close': 'Zavřít', 'labels.pages': 'Stránky',
'labels.pageOf': 'Strana {page} z {total} · {count} výsledků',
};
/** The same Czech strings as full keys, for the page-wide flat dictionary. */
const toFullKeys = (map) => Object.fromEntries(Object.entries(map).map(([k, v]) => [`web-command-palette.${k}`, v]));
function wire() {
const palette = document.getElementById('palette');
palette.commands = [
{ id: 'home', trigger: '/home', text: 'Go home', description: 'Instant command', shortcut: 'g h', icon: '🏠' },
{ id: 'theme', trigger: '/theme', text: 'Switch theme', description: 'One-step wizard', icon: '🎨',
steps: [{ id: 'theme', options: [{ text: 'Light', value: 'light', icon: '☀️' }, { text: 'Dark', value: 'dark', icon: '🌑' }] }] },
];
palette.contexts = [
{ id: 'people', trigger: ':people', aliases: [':p'], text: 'People', description: 'Search people', icon: '👥' },
{ id: 'numbers', trigger: ':numbers', aliases: [':n'], text: 'Numbers', description: '12,345 rows — formatted counts', icon: '🔢',
searchCallback: () => Array.from({ length: 12345 }, (_, i) => ({ id: `n${i}`, title: `Row ${i + 1}` })) },
];
palette.searchCallback = async ({ scope, term }) =>
['Ada Lovelace', 'Alan Turing', 'Grace Hopper', 'Linus Torvalds', 'Margaret Hamilton']
.filter((n) => n.toLowerCase().includes(term.toLowerCase()))
.map((n) => ({ id: n, title: n, subtitle: scope === 'global' ? 'Person' : 'In People', icon: '👤' }));
document.querySelectorAll('[data-open]').forEach((b) =>
b.addEventListener('click', () => palette.controller.openWith(b.dataset.open)));
document.querySelectorAll('input[name="bu02-key"]').forEach((r) =>
r.addEventListener('change', (e) => { if (e.target.checked) palette.setAttribute('open-key', e.target.value); }));
const PAGE_CS = {
locale: 'cs',
labels: toFullKeys({
...CS,
'headers.favorites': 'Oblíbené', 'headers.recent': 'Nedávné',
'ariaLabels.resultsCount': '{count} výsledků', 'headers.done': 'Hotovo', 'ariaLabels.done': 'Hotovo',
}),
};
document.querySelectorAll('input[name="bu05-lang"]').forEach((r) =>
r.addEventListener('change', (e) => { if (e.target.checked) window.components.locale = e.target.value === 'cs' ? PAGE_CS : null; }));
window.addEventListener('pagehide', () => { window.components.locale = null; });
document.querySelectorAll('input[name="bu04-lang"]').forEach((r) =>
r.addEventListener('change', (e) => { if (e.target.checked) palette.labels = e.target.value === 'cs' ? CS : {}; }));
const log = document.getElementById('bu03-log');
let started = false;
// The data of each detail (controller / element are non-enumerable, so JSON skips them).
const brief = (name, d) => name === 'action' ? { id: d.id, selections: d.selections }
: name === 'result-select' ? { result: d.result, scope: d.scope } : {};
for (const name of ['open', 'close', 'result-select', 'action']) {
palette.addEventListener(name, (e) => {
const line = `${name} ${JSON.stringify(brief(name, e.detail))}`;
log.textContent = started ? `${line}\n${log.textContent}` : line;
started = true;
});
}
attachControlsPersistence('basic');
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', wire);
else wire();
</script>