Repository navigation
Expand file tree
/
Copy pathexamples-logging.html
More file actions
335 lines (299 loc) · 18.1 KB
/
Copy pathexamples-logging.html
File metadata and controls
335 lines (299 loc) · 18.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
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
<meta name="kmwc:title" content="Logging & Diagnostics">
<meta name="kmwc:subtitle" content="The global component registry from <code>@keenmate/web-components-core</code> — introspection, logging controls, and the live-instance list">
<!-- 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">
<style>
.controls button { margin: 0.25rem; }
/* Live registry inspector — box from the kit's `.log-panel--dark` (a console, dark in
both themes); this is the two-column dt/dd grid and its chips on top of it. */
.registry {
display: grid;
grid-template-columns: max-content 1fr;
gap: 0.4rem 1rem;
}
.registry dt { color: var(--kmwc-console-info-color); white-space: nowrap; }
.registry dd { margin: 0; color: var(--kmwc-console-text-color); word-break: break-word; }
.registry .muted { color: var(--kmwc-console-muted-color); }
.registry .chip {
display: inline-block;
background: color-mix(in srgb, var(--kmwc-console-text-color) 8%, transparent);
color: var(--kmwc-console-info-color);
border: 1px solid color-mix(in srgb, var(--kmwc-console-text-color) 22%, transparent);
border-radius: 999px;
padding: 0.05rem 0.5rem;
margin: 0 0.2rem 0.2rem 0;
font-size: 0.78rem;
}
.registry .chip.on {
color: var(--kmwc-console-ok-color);
border-color: color-mix(in srgb, var(--kmwc-console-ok-color) 45%, transparent);
background: color-mix(in srgb, var(--kmwc-console-ok-color) 12%, transparent);
}
.count-badge {
display: inline-block;
min-width: 1.4rem;
text-align: center;
background: var(--kmwc-accent-color);
color: var(--kmwc-text-color-on-accent);
border-radius: 999px;
padding: 0.05rem 0.5rem;
font-weight: 700;
}
#dynamic-hosts { display: flex; flex-direction: column; gap: 0.75rem; margin-top: 0.75rem; }
#dynamic-hosts:empty::after {
content: "No dynamic instances yet — click \"Add a picker\".";
color: var(--kmwc-text-color-3); font-style: italic;
}
</style>
<div class="note warning">
<strong>Open the DevTools Console (F12).</strong> On load the component
registers itself on <code>window.components['web-multiselect']</code>. Try
<code>window.components['web-multiselect']</code> in the console, then use the
buttons below — everything here goes through that global, nothing else.
</div>
<!-- ── 1. The registry ─────────────────────────────────────────────── -->
<div class="card">
<h2>LG01 · The registry entry</h2>
<p>
Every Keenmate component publishes one entry via core's
<code>registerComponent()</code>. Below is a live view of
<code>window.components['web-multiselect']</code>, refreshed automatically
as instances connect and disconnect.
</p>
<div class="output">
<div class="output-label">window.components['web-multiselect']</div>
<dl class="log-panel log-panel--dark registry" id="registry-view"></dl>
</div>
<div class="controls">
<button onclick="refreshRegistry()">Refresh</button>
<button class="btn-outline" onclick="dumpToConsole()">console.log the entry</button>
</div>
</div>
<!-- ── 2. Logging through the registry ─────────────────────────────── -->
<div class="card">
<h2>LG02 · Logging controls — via <code>.logging</code></h2>
<p>
The <code>.logging</code> object is the flattened logger bundle. These
buttons call it directly (e.g.
<code>window.components['web-multiselect'].logging.setCategoryLevel('DATA','debug')</code>).
The active category level is reflected in the registry panel above. Interact
with the pickers to produce logs.
</p>
<div class="controls">
<button onclick="reg().logging.enableLogging()">Enable all (debug)</button>
<button class="secondary" onclick="reg().logging.disableLogging()">Disable all</button>
<button class="secondary" onclick="reg().logging.resetLogging()">Reset (follow the page, else warn)</button>
<button class="btn-outline" onclick="reg().logging.setLogLevel('info')">All → info</button>
</div>
<div class="controls">
<button onclick="onlyCategory('INIT')">Only INIT</button>
<button onclick="onlyCategory('DATA')">Only DATA</button>
<button onclick="onlyCategory('UI')">Only UI</button>
<button onclick="onlyCategory('INTERACTION')">Only INTERACTION</button>
</div>
<div class="grid grid-2 mt-1">
<div class="form-group">
<label>Fruits (basic)</label>
<web-multiselect id="fruits" is-multiple-enabled="true" labels='{"placeholders.search": "Search fruits..."}'></web-multiselect>
</div>
<div class="form-group">
<label>Colors (async search → DATA logs)</label>
<web-multiselect id="colors" is-multiple-enabled="true" is-close-on-select="false" labels='{"placeholders.search": "Search colors..."}'></web-multiselect>
</div>
</div>
</div>
<!-- ── 3. Live instances ───────────────────────────────────────────── -->
<div class="card">
<h2>LG03 · Live instances — <code>.getInstances()</code></h2>
<p>
<code>getInstances()</code> returns the connected elements of this tag —
maintained automatically (added on connect, removed on disconnect). Add and
remove pickers below and watch the count in the registry panel change; then
fan a call out across every live instance.
</p>
<div class="controls">
<button onclick="addPicker()">Add a picker</button>
<button class="secondary" onclick="removePicker()">Remove last</button>
<button class="btn-outline" onclick="logAllSelections()">Log every instance's selection</button>
</div>
<div id="dynamic-hosts"></div>
</div>
<!-- ── Reference ───────────────────────────────────────────────────── -->
<div class="card">
<h2>LG04 · Log categories</h2>
<ul>
<li><strong>INIT</strong> — initialization, config parsing, RTL detection, destruction</li>
<li><strong>DATA</strong> — async loading, option parsing, adding options, errors</li>
<li><strong>UI</strong> — dropdown/popover/tooltip rendering, positioning, badges</li>
<li><strong>INTERACTION</strong> — clicks, selections, keyboard, close-on-select</li>
</ul>
</div>
<div class="card">
<h2>LG05 · Usage</h2>
<div class="code-block" data-language="js"><pre><code>// No import needed at call sites — the registry is a global, populated the
// moment the component module is loaded anywhere on the page.
const ms = window.components['web-multiselect'];
ms.version(); // "2.0.0-rc01"
ms.config; // { name, version, author, license, … }
ms.getInstances(); // live <web-multiselect> elements
// Logging (a flattened view of the core logger bundle)
ms.logging.getCategories(); // ["INIT", "DATA", "UI", "INTERACTION"]
ms.logging.enableLogging(); // all categories → debug
ms.logging.setLogLevel('info'); // all → info
ms.logging.setCategoryLevel('DATA', 'debug');
ms.logging.setCategoryLevel('DATA', null); // clear one category again
ms.logging.disableLogging(); // this type → silent (beats the page level)
ms.logging.resetLogging(); // no type level: follow the page level
// Fan out across instances
for (const el of ms.getInstances()) console.log(el.id, el.selectedOptions);
// Levels coalesce, closest first — nothing is set by default:
// element el.enableLogging(level?) ONE element (debug by default; 'error' = quieter)
// el.disableLogging() silences this element
// el.resetLogging() it follows its type / the page again
// type ms.logging.* per category (above)
// page window.components.logging every component on the page
// default 'warn' errors and warnings only
// A page call never overwrites a type level, so call order doesn't matter.
// Instance debug / trace lines print through console.log (Chrome hides console.debug).
window.components.logging.enableLogging('info'); // page level
el.enableLogging('debug'); // one verbose element</code></pre></div>
</div>
<script type="module">
import { mapToEscapedHtml } from '@keenmate/web-components-devkit/examples';
// The component entry (loaded in <head> by the devkit layout) runs registerComponent(),
// so window.components is populated before this script runs.
const TAG = 'web-multiselect';
const reg = () => window.components?.[TAG];
window.reg = reg;
// ── sample data ──────────────────────────────────────────────────────
const fruits = [
{ id: 1, name: 'Apple', emoji: '🍎' }, { id: 2, name: 'Banana', emoji: '🍌' },
{ id: 3, name: 'Cherry', emoji: '🍒' }, { id: 4, name: 'Grape', emoji: '🍇' },
{ id: 5, name: 'Orange', emoji: '🍊' }, { id: 6, name: 'Strawberry', emoji: '🍓' },
{ id: 7, name: 'Watermelon', emoji: '🍉' }
];
const colors = [
{ id: 1, name: 'Red', hex: '#ef4444' }, { id: 2, name: 'Blue', hex: '#3b82f6' },
{ id: 3, name: 'Green', hex: '#10b981' }, { id: 4, name: 'Yellow', hex: '#f59e0b' },
{ id: 5, name: 'Purple', hex: '#8b5cf6' }, { id: 6, name: 'Pink', hex: '#ec4899' }
];
const fruitCfg = (el) => {
el.options = fruits;
el.getValueCallback = ({ option }) => option.id;
el.getDisplayValueCallback = ({ option }) => `${option.emoji} ${option.name}`;
};
// ── 1. registry inspector ────────────────────────────────────────────
window.refreshRegistry = () => {
const view = document.getElementById('registry-view');
const r = reg();
if (!r) { view.innerHTML = '<dt>status</dt><dd class="muted">not registered</dd>'; return; }
const cfg = r.config || {};
const cats = r.logging?.getCategories() ?? [];
const instances = r.getInstances();
const catPills = cats.map((c) => {
// Reflect each category's effective level from the underlying loggers.
const lvl = window.__catLevel?.[c];
const on = lvl && lvl !== 'silent';
return `<span class="chip ${on ? 'on' : ''}">${mapToEscapedHtml(c.split(':')[1] || c)}${on ? ` · ${lvl}` : ''}</span>`;
}).join('');
const instPills = instances.length
? instances.map((el, i) => `<span class="chip">${mapToEscapedHtml(el.id || `#${i}`)}</span>`).join('')
: '<span class="muted">none connected</span>';
view.innerHTML = `
<dt>version()</dt><dd>${mapToEscapedHtml(r.version())}</dd>
<dt>config.name</dt><dd>${mapToEscapedHtml(cfg.name ?? '—')}</dd>
<dt>config.author</dt><dd>${mapToEscapedHtml(cfg.author ?? '—')}</dd>
<dt>config.license</dt><dd>${mapToEscapedHtml(cfg.license ?? '—')}</dd>
<dt>logging</dt><dd>${cats.length ? catPills : '<span class="muted">no bundle</span>'}</dd>
<dt>getInstances()</dt><dd><span class="count-badge">${instances.length}</span> ${instPills}</dd>
`;
};
window.dumpToConsole = () => {
const r = reg();
console.log('%cwindow.components[\'web-multiselect\']', 'color:#3b82f6;font-weight:bold;font-size:1.1rem;', r);
console.log('config:', r?.config);
console.log('getInstances():', r?.getInstances());
};
// Track category levels we set so the panel can reflect them (the bundle
// has no getter for effective level, so we mirror what we set here).
window.__catLevel = {};
window.onlyCategory = (cat) => {
const r = reg();
r.logging.disableLogging();
r.logging.setCategoryLevel(cat, 'debug');
const cats = r.logging.getCategories();
window.__catLevel = {};
for (const c of cats) window.__catLevel[c] = 'silent';
const full = cats.find((c) => c.endsWith(':' + cat)) ?? cat;
window.__catLevel[full] = 'debug';
console.log(`%c▶ only ${cat} → debug`, 'color:#8b5cf6;font-weight:bold;');
refreshRegistry();
};
// Mirror the bulk controls too.
const origReg = reg;
const wrapLevels = () => {
const r = origReg(); if (!r?.logging) return;
const l = r.logging;
const cats = l.getCategories();
const _enable = l.enableLogging.bind(l), _disable = l.disableLogging.bind(l), _set = l.setLogLevel.bind(l), _reset = l.resetLogging.bind(l);
l.enableLogging = (lvl = 'debug') => { _enable(lvl); cats.forEach((c) => (window.__catLevel[c] = lvl)); refreshRegistry(); };
l.disableLogging = () => { _disable(); cats.forEach((c) => (window.__catLevel[c] = 'silent')); refreshRegistry(); };
l.setLogLevel = (lvl) => { _set(lvl); cats.forEach((c) => (window.__catLevel[c] = lvl)); refreshRegistry(); };
l.resetLogging = () => { _reset(); window.__catLevel = {}; refreshRegistry(); };
};
// ── 3. live instances ────────────────────────────────────────────────
let dynN = 0;
window.addPicker = () => {
const host = document.getElementById('dynamic-hosts');
const wrap = document.createElement('div');
wrap.className = 'form-group';
const label = document.createElement('label');
label.textContent = `Dynamic picker #${++dynN}`;
const el = document.createElement('web-multiselect');
el.id = `dyn-${dynN}`;
el.setAttribute('multiple', 'true');
el.labels = { 'placeholders.search': 'Search fruits...' };
wrap.append(label, el);
host.appendChild(wrap);
fruitCfg(el); // connectedCallback already fired on append
console.log(`%c+ connected ${el.id} — getInstances(): ${reg().getInstances().length}`, 'color:#10b981;font-weight:bold;');
refreshRegistry();
};
window.removePicker = () => {
const host = document.getElementById('dynamic-hosts');
const last = host.lastElementChild;
if (!last) return;
const id = last.querySelector('web-multiselect')?.id;
host.removeChild(last);
console.log(`%c- disconnected ${id} — getInstances(): ${reg().getInstances().length}`, 'color:#ef4444;font-weight:bold;');
refreshRegistry();
};
window.logAllSelections = () => {
const rows = reg().getInstances().map((el) => ({ id: el.id, selected: el.selectedOptions.map((o) => o.name ?? o.value ?? o) }));
console.log('%c🗂 selections across all live instances', 'color:#3b82f6;font-weight:bold;');
console.table(rows);
};
// ── boot ─────────────────────────────────────────────────────────────
customElements.whenDefined(TAG).then(() => {
wrapLevels();
fruitCfg(document.getElementById('fruits'));
const colorsEl = document.getElementById('colors');
colorsEl.options = colors;
colorsEl.getValueCallback = ({ option }) => option.id;
colorsEl.getDisplayValueCallback = ({ option }) => option.name;
colorsEl.getSubtitleCallback = ({ option }) => option.hex;
colorsEl.searchCallback = async ({ term }) => {
await new Promise((r) => setTimeout(r, 300));
if (!term) return colors;
const q = term.toLowerCase();
return colors.filter((c) => c.name.toLowerCase().includes(q) || c.hex.includes(q));
};
// Start at the default (no type level → the page level, else warn), then paint the panel.
reg().logging.resetLogging();
refreshRegistry();
console.log('%c🌐 window.components demo ready', 'color:#3b82f6;font-size:1.3rem;font-weight:bold;');
console.log('Try: %cwindow.components[\'web-multiselect\']', 'font-family:monospace;background:#eef;padding:2px 4px;');
});
// Keep the instance list honest even if instances change outside our buttons.
setInterval(() => refreshRegistry(), 2000);
</script>