@jungherz-de/notionkit-elements 1.8.0 → 1.10.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 (32) hide show
  1. package/README.md +13 -13
  2. package/dist/components/nk-app.js +8 -1
  3. package/dist/components/nk-btn.js +17 -3
  4. package/dist/components/nk-calendar-view.js +138 -0
  5. package/dist/components/nk-calendar.js +356 -0
  6. package/dist/components/nk-dialog.js +150 -0
  7. package/dist/components/nk-menu.js +2 -14
  8. package/dist/components/nk-peek.js +80 -5
  9. package/dist/components/nk-sidebar.js +68 -6
  10. package/dist/components/nk-table-view.js +9 -3
  11. package/dist/components/nk-tooltip.js +138 -0
  12. package/dist/components/nk-workspace-switcher.js +1 -1
  13. package/dist/components/shared/dates-a32DcW1l.js +67 -0
  14. package/dist/components/shared/floating-CxHxy-Cb.js +37 -0
  15. package/dist/notionkit-elements.esm.js +1102 -91
  16. package/dist/notionkit-elements.js +1105 -90
  17. package/dist/notionkit-elements.min.js +1 -1
  18. package/package.json +3 -3
  19. package/src/components/data/nk-calendar-view.js +136 -0
  20. package/src/components/data/nk-table-view.js +9 -3
  21. package/src/components/forms/nk-btn.js +17 -3
  22. package/src/components/forms/nk-calendar.js +354 -0
  23. package/src/components/overlays/nk-dialog.js +148 -0
  24. package/src/components/overlays/nk-menu.js +2 -14
  25. package/src/components/overlays/nk-peek.js +80 -5
  26. package/src/components/overlays/nk-tooltip.js +136 -0
  27. package/src/components/shell/nk-app.js +8 -1
  28. package/src/components/shell/nk-sidebar.js +68 -6
  29. package/src/components/shell/nk-workspace-switcher.js +1 -1
  30. package/src/index.js +4 -0
  31. package/src/util/dates.js +65 -0
  32. package/src/util/floating.js +35 -0
@@ -0,0 +1,356 @@
1
+ import { NkFormElement } from './base.js';
2
+ import { p as parseDay, i as isoOf, C as CHEVRONS, r as resolveLocale, f as firstWeekday, m as monthGrid, w as weekLabel, a as weekdayNames, b as isoWeek, s as stepMonth, c as addDays } from './shared/dates-a32DcW1l.js';
3
+ import { p as placeUnder } from './shared/floating-CxHxy-Cb.js';
4
+ import { d as deepActiveElement } from './shared/focus-BNAChOXO.js';
5
+ import '@jungherz-de/notionkit/notionkit-styles.js';
6
+
7
+ // <nk-calendar name="due" value="2026-06-02" weeks weekend="6,0"></nk-calendar>
8
+ // <nk-calendar range value="2026-06-08/2026-06-12"></nk-calendar>
9
+ // <nk-calendar floating sheet id="picker"></nk-calendar> picker.show(button)
10
+ // → [<div class="nk-pop floating sheet open">]<div class="nk-calendar weeks">
11
+ // <div class="cal-head"><div class="cal-title">June 2026</div><button class="cal-nav">Today</button>‹ ›</div>
12
+ // <div class="cal-grid"><span class="cal-wd">W</span>…<span class="cal-week">23</span><button class="cal-day selected">2</button>…</div>
13
+ // [<div class="cal-foot"><input class="nk-input" type="time"></div>]</div>
14
+ //
15
+ // Notion's date picker (NotionKit 1.9.0), after GlassKit Elements'
16
+ // glk-calendar, with what a planning tool needs on top: a range, ISO
17
+ // calendar weeks, days not worked, marks and a time.
18
+ // value: YYYY-MM-DD; with `range` the ISO interval "start/end"; with `time`
19
+ // YYYY-MM-DDTHH:MM. Also as the properties value, start, end.
20
+ // month (YYYY-MM shown; default the value's, else today's), min, max, today,
21
+ // locale (default the page's lang), week-start (0 = Sunday … 6 = Saturday;
22
+ // default from the locale, Monday where the browser cannot say), weeks,
23
+ // weekend (weekdays not worked, "6,0" for Saturday and Sunday), range, time,
24
+ // clearable, label and the texts today-label, prev-label, next-label,
25
+ // week-label, time-label, clear-label. `time` belongs to single days; a
26
+ // range has none.
27
+ // days (property, or JSON attribute): { 'YYYY-MM-DD': { off, label, marks } }
28
+ // – `off` greys a holiday, `label` names the day (tooltip and screen
29
+ // reader), `marks` puts up to three dots in the nine colours on it.
30
+ // Keys: arrows by a day or a week, Home/End to the ends of the week,
31
+ // PageUp/PageDown by a month (Shift: a year); Enter or Space picks. Arrows
32
+ // only move, so the picker stays quiet while someone looks around. Days
33
+ // outside min/max are aria-disabled – in the arrow path and announced, never
34
+ // picked. A range takes two picks, in either order. Form-associated: the
35
+ // value goes with the form, reset restores it.
36
+ // Events: nk-change { value, start, end, time } when a pick – for a range the
37
+ // second one –, a new time or Clear changes the value; nk-month { month } when the month
38
+ // changes; nk-toggle { open } with `floating`. `required` makes an empty
39
+ // value invalid.
40
+ // `floating` makes it a popover over the page – show(anchor) puts it under
41
+ // the anchor, right edges aligned (align="start": left edges) – and `sheet`
42
+ // a bottom sheet with 44px cells on a phone, as <nk-menu floating sheet>.
43
+ // A pick closes it – the second of a range; with `time` Escape or a tap
44
+ // outside does. Put a floating calendar directly under <body>.
45
+ const STEPS = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };
46
+ const floatSheet = new CSSStyleSheet();
47
+ floatSheet.replaceSync(`:host([floating]) { display: block; position: fixed; z-index: 60; pointer-events: none; }`);
48
+
49
+ class NkCalendar extends NkFormElement {
50
+ static get hostStyles() { return floatSheet; }
51
+ static get observedAttributes() {
52
+ return ['value', 'month', 'min', 'max', 'today', 'locale', 'week-start', 'weeks', 'weekend', 'range', 'time', 'clearable', 'days',
53
+ 'label', 'today-label', 'prev-label', 'next-label', 'week-label', 'time-label', 'clear-label', 'floating', 'sheet', 'open', 'align', 'required'];
54
+ }
55
+
56
+ render() {
57
+ // A value or month set as a property before the first connect wins over the attributes.
58
+ this._readValue(this._pendingValue ?? this.getAttribute('value'));
59
+ const month = this._pendingMonth || this._attrMonth();
60
+ if (month) this._month = month;
61
+ this._initialValue = this.getAttribute('value') ?? '';
62
+ this._build();
63
+ }
64
+
65
+ // ── value ──
66
+ _readValue(v) {
67
+ const s = String(v ?? '');
68
+ this._start = this._end = this._day = null;
69
+ this._time = '';
70
+ if (this.getBoolAttr('range')) {
71
+ const [a, b] = s.split('/');
72
+ this._start = parseDay(a) ? isoOf(parseDay(a)) : null;
73
+ this._end = parseDay(b) ? isoOf(parseDay(b)) : null;
74
+ } else if (parseDay(s)) {
75
+ this._day = isoOf(parseDay(s));
76
+ this._time = s.match(/T(\d{2}:\d{2})/)?.[1] ?? '';
77
+ }
78
+ // A new value brings its month; without one the month stays.
79
+ const shown = this._day || this._start;
80
+ this._month = shown ? shown.slice(0, 7) : (this._month || this._attrMonth() || this._todayIso().slice(0, 7));
81
+ this._focus = null;
82
+ }
83
+
84
+ _attrMonth() { const m = this.getAttribute('month'); return /^\d{4}-\d{2}$/.test(m || '') ? m : null; }
85
+ _todayIso() { return this.getAttribute('today') || isoOf(new Date()); }
86
+
87
+ get value() {
88
+ if (this.getBoolAttr('range')) return this._start ? `${this._start}${this._end ? `/${this._end}` : ''}` : '';
89
+ return this._day ? `${this._day}${this.getBoolAttr('time') && this._time ? `T${this._time}` : ''}` : '';
90
+ }
91
+ set value(v) {
92
+ this._readValue(v);
93
+ if (this._grid) this._draw(); else this._pendingValue = String(v ?? '');
94
+ }
95
+ get start() { return this.getBoolAttr('range') ? this._start : this._day; }
96
+ get end() { return this.getBoolAttr('range') ? this._end : this._day; }
97
+ get month() { return this._month; }
98
+ set month(v) {
99
+ if (!/^\d{4}-\d{2}$/.test(v)) return;
100
+ this._month = v; this._focus = null;
101
+ if (this._grid) this._draw(); else this._pendingMonth = v;
102
+ }
103
+ get days() { return this._days ?? {}; }
104
+ set days(v) { this._days = v && typeof v === 'object' ? v : {}; if (this._grid) this._draw(); }
105
+
106
+ // ── markup ──
107
+ _build() {
108
+ const floating = this.getBoolAttr('floating');
109
+ this._cal = this.createElement('div', ['nk-calendar'], { role: 'group' });
110
+ const head = this.createElement('div', ['cal-head']);
111
+ this._title = this.createElement('div', ['cal-title'], { 'aria-live': 'polite' });
112
+ this._todayBtn = this.createElement('button', ['cal-nav'], { type: 'button' });
113
+ this._prev = this.createElement('button', ['cal-nav'], { type: 'button' });
114
+ this._prev.innerHTML = CHEVRONS.prev;
115
+ this._next = this.createElement('button', ['cal-nav'], { type: 'button' });
116
+ this._next.innerHTML = CHEVRONS.next;
117
+ head.append(this._title, this._todayBtn, this._prev, this._next);
118
+ this._grid = this.createElement('div', ['cal-grid']);
119
+ this._foot = this.createElement('div', ['cal-foot']);
120
+ this._timeInput = this.createElement('input', ['nk-input'], { type: 'time' });
121
+ this._clear = this.createElement('button', ['cal-nav'], { type: 'button' });
122
+ this._cal.append(head, this._grid);
123
+ this._pop = floating ? this.createElement('div', ['nk-pop', 'floating']) : null;
124
+ if (this._pop) this._pop.appendChild(this._cal);
125
+ this._wrapper.replaceChildren(this._pop ?? this._cal);
126
+ this._draw();
127
+ }
128
+
129
+ get _hasTime() { return this.getBoolAttr('time') && !this.getBoolAttr('range'); }
130
+ get _locale() { return resolveLocale(this.getAttribute('locale')); }
131
+ get _weekStart() {
132
+ const n = Number(this.getAttribute('week-start'));
133
+ return this.hasAttribute('week-start') && Number.isInteger(n) && n >= 0 && n <= 6 ? n : firstWeekday(this._locale);
134
+ }
135
+
136
+ _syncPop() {
137
+ this._pop?.classList.toggle('sheet', this.getBoolAttr('sheet'));
138
+ this._pop?.classList.toggle('open', this.getBoolAttr('open'));
139
+ }
140
+
141
+ _draw() {
142
+ const locale = this._locale, ws = this._weekStart, weeks = this.getBoolAttr('weeks'), range = this.getBoolAttr('range');
143
+ const g = monthGrid(this._month, ws), today = this._todayIso();
144
+ const min = this.getAttribute('min') || '', max = this.getAttribute('max') || '';
145
+ const weekend = new Set((this.getAttribute('weekend') || '').split(',').map(s => s.trim()).filter(Boolean).map(Number));
146
+ let days = this._days;
147
+ if (!days && this.hasAttribute('days')) { try { days = JSON.parse(this.getAttribute('days')); } catch { days = {}; } }
148
+ days ??= {};
149
+ const long = new Intl.DateTimeFormat(locale, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
150
+ this._cal.classList.toggle('weeks', weeks);
151
+ this._syncPop();
152
+ const label = this.getAttribute('label');
153
+ if (label) this._cal.setAttribute('aria-label', label); else this._cal.removeAttribute('aria-label');
154
+ this._title.textContent = new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric' }).format(g.first);
155
+ this._todayBtn.textContent = this.getAttribute('today-label') || 'Today';
156
+ this._prev.setAttribute('aria-label', this.getAttribute('prev-label') || 'Previous month');
157
+ this._next.setAttribute('aria-label', this.getAttribute('next-label') || 'Next month');
158
+
159
+ // The one tab stop: the focused day, else the chosen one, else the 1st.
160
+ const cells = Array.from({ length: 42 }, (_, i) => isoOf(g.day(i)));
161
+ const chosen = range ? this._start : this._day;
162
+ if (!this._focus || !cells.includes(this._focus)) this._focus = cells.includes(chosen) ? chosen : `${this._month}-01`;
163
+
164
+ const nodes = [];
165
+ if (weeks) nodes.push(this._head(this.getAttribute('week-label') || weekLabel(locale)));
166
+ for (const w of weekdayNames(locale, ws, 2)) nodes.push(this._head(w));
167
+ for (let i = 0; i < 42; i++) {
168
+ const d = g.day(i), iso = cells[i], info = days[iso] || {};
169
+ if (weeks && i % 7 === 0) { const wk = this.createElement('span', ['cal-week'], { 'aria-hidden': 'true' }); wk.textContent = isoWeek(d); nodes.push(wk); }
170
+ const inRange = range && this._start && this._end && iso > this._start && iso < this._end;
171
+ const cls = ['cal-day', d.getMonth() !== g.m - 1 && 'out', (weekend.has(d.getDay()) || info.off) && 'off', iso === today && 'today',
172
+ !range && iso === this._day && 'selected', range && iso === this._start && 'start', range && iso === (this._end || this._start) && this._start && 'end', inRange && 'in-range'].filter(Boolean);
173
+ const day = this.createElement('button', cls, { type: 'button', 'data-date': iso, tabindex: iso === this._focus ? '0' : '-1',
174
+ 'aria-pressed': String(cls.includes('selected') || cls.includes('start') || cls.includes('end')),
175
+ 'aria-label': `${long.format(d)}${info.label ? `, ${info.label}` : ''}` });
176
+ if (info.label) day.title = info.label;
177
+ if ((min && iso < min) || (max && iso > max)) day.setAttribute('aria-disabled', 'true');
178
+ day.textContent = d.getDate();
179
+ const marks = (info.marks || []).slice(0, 3);
180
+ if (marks.length) {
181
+ const m = this.createElement('span', ['cal-marks']);
182
+ for (const tone of marks) m.appendChild(this.createElement('i', [tone]));
183
+ day.appendChild(m);
184
+ }
185
+ nodes.push(day);
186
+ }
187
+ // The days are drawn anew; focus inside the grid moves to the new tab stop.
188
+ const focused = this._grid.contains(this._shadow.activeElement);
189
+ this._grid.replaceChildren(...nodes);
190
+ if (focused) this.focusDay();
191
+
192
+ const time = this._hasTime, clearable = this.getBoolAttr('clearable');
193
+ this._timeInput.value = this._time;
194
+ this._timeInput.setAttribute('aria-label', this.getAttribute('time-label') || 'Time');
195
+ this._clear.textContent = this.getAttribute('clear-label') || 'Clear';
196
+ this._foot.replaceChildren(...[time && this._timeInput, clearable && this._clear].filter(Boolean));
197
+ if (time || clearable) this._cal.appendChild(this._foot); else this._foot.remove();
198
+ this._syncForm();
199
+ }
200
+
201
+ _syncForm() {
202
+ this.setFormValue(this.value);
203
+ if (this.getBoolAttr('required') && !this.value) this.setValidity({ valueMissing: true }, 'Please choose a date.', this._grid?.querySelector('[tabindex="0"]') ?? undefined);
204
+ else this.setValidity({});
205
+ }
206
+
207
+ _head(text) {
208
+ const s = this.createElement('span', ['cal-wd'], { 'aria-hidden': 'true' });
209
+ s.textContent = text;
210
+ return s;
211
+ }
212
+
213
+ // ── interaction ──
214
+ _goMonth(month, focus) {
215
+ if (month !== this._month) { this._month = month; this.emit('nk-month', { month }); }
216
+ this._focus = focus ?? null;
217
+ this._draw();
218
+ }
219
+
220
+ _pick(iso) {
221
+ const day = this._grid.querySelector(`[data-date="${iso}"]`);
222
+ if (day?.getAttribute('aria-disabled') === 'true') return;
223
+ const before = this.value;
224
+ let done = true;
225
+ if (this.getBoolAttr('range')) {
226
+ if (!this._start || this._end) { this._start = iso; this._end = null; done = false; }
227
+ else if (iso < this._start) { this._end = this._start; this._start = iso; }
228
+ else this._end = iso;
229
+ } else this._day = iso;
230
+ this._focus = iso;
231
+ if (iso.slice(0, 7) !== this._month) this._goMonth(iso.slice(0, 7), iso); else this._draw();
232
+ if (!done) return;
233
+ // Only a new value is a change; the same day again just closes a popover.
234
+ if (this.value !== before) this.emit('nk-change', { value: this.value, start: this.start, end: this.end, time: this._time || null });
235
+ if (this.getBoolAttr('floating') && !this._hasTime) this.close();
236
+ }
237
+
238
+ setupEvents() {
239
+ this._onGrid = (e) => { const day = e.target.closest('.cal-day'); if (day) this._pick(day.dataset.date); };
240
+ this._onToday = () => { const t = this._todayIso(); this._goMonth(t.slice(0, 7), t); };
241
+ this._onPrev = () => this._goMonth(stepMonth(this._month, -1));
242
+ this._onNext = () => this._goMonth(stepMonth(this._month, 1));
243
+ this._onKey = (e) => {
244
+ // Enter and Space are the day button's own click.
245
+ const day = e.target.closest?.('.cal-day');
246
+ if (!day) return;
247
+ const date = parseDay(day.dataset.date), ws = this._weekStart, wd = (date.getDay() - ws + 7) % 7;
248
+ let target = null;
249
+ if (STEPS[e.key]) target = addDays(date, STEPS[e.key]);
250
+ else if (e.key === 'Home') target = addDays(date, -wd);
251
+ else if (e.key === 'End') target = addDays(date, 6 - wd);
252
+ else if (e.key === 'PageUp' || e.key === 'PageDown') {
253
+ const months = (e.key === 'PageUp' ? -1 : 1) * (e.shiftKey ? 12 : 1);
254
+ const last = new Date(date.getFullYear(), date.getMonth() + months + 1, 0).getDate();
255
+ target = new Date(date.getFullYear(), date.getMonth() + months, Math.min(date.getDate(), last));
256
+ }
257
+ if (!target) return;
258
+ e.preventDefault();
259
+ const iso = isoOf(target);
260
+ if (iso.slice(0, 7) !== this._month) this._goMonth(iso.slice(0, 7), iso);
261
+ else { this._focus = iso; this._draw(); }
262
+ };
263
+ this._onTime = () => {
264
+ this._time = this._timeInput.value;
265
+ this._syncForm();
266
+ if (this._day) this.emit('nk-change', { value: this.value, start: this.start, end: this.end, time: this._time || null });
267
+ };
268
+ this._onClear = () => {
269
+ if (!this.value) return;
270
+ this._day = this._start = this._end = null; this._time = '';
271
+ this._draw();
272
+ this.emit('nk-change', { value: '', start: null, end: null, time: null });
273
+ };
274
+ // Floating: a tap outside closes it and reaches nothing else; Escape closes (captured, before a modal around it).
275
+ this._onOutside = (e) => {
276
+ const path = e.composedPath();
277
+ if (path.includes(this) || (this._anchor && path.includes(this._anchor))) return;
278
+ e.preventDefault(); e.stopPropagation();
279
+ this.close();
280
+ };
281
+ this._onEscape = (e) => { if (e.key === 'Escape' && this.getBoolAttr('floating') && this.getBoolAttr('open')) { e.stopPropagation(); this.close(); } };
282
+ this._grid.addEventListener('click', this._onGrid);
283
+ this._grid.addEventListener('keydown', this._onKey);
284
+ this._todayBtn.addEventListener('click', this._onToday);
285
+ this._prev.addEventListener('click', this._onPrev);
286
+ this._next.addEventListener('click', this._onNext);
287
+ this._timeInput.addEventListener('change', this._onTime);
288
+ this._clear.addEventListener('click', this._onClear);
289
+ document.addEventListener('keydown', this._onEscape, true);
290
+ if (this.getBoolAttr('open')) document.addEventListener('click', this._onOutside, true);
291
+ }
292
+
293
+ teardownEvents() {
294
+ this._grid?.removeEventListener('click', this._onGrid);
295
+ this._grid?.removeEventListener('keydown', this._onKey);
296
+ this._todayBtn?.removeEventListener('click', this._onToday);
297
+ this._prev?.removeEventListener('click', this._onPrev);
298
+ this._next?.removeEventListener('click', this._onNext);
299
+ this._timeInput?.removeEventListener('change', this._onTime);
300
+ this._clear?.removeEventListener('click', this._onClear);
301
+ document.removeEventListener('keydown', this._onEscape, true);
302
+ document.removeEventListener('click', this._onOutside, true);
303
+ }
304
+
305
+ onAttributeChanged(name, _old, value) {
306
+ if (name === 'value') { this._readValue(value); this._draw(); return; }
307
+ if (name === 'month') { this.month = value; return; }
308
+ if (name === 'open' || name === 'sheet') { this._syncPop(); if (name === 'open') this._syncOpen(); return; }
309
+ if (name === 'align') return;
310
+ if (name === 'floating') { this.teardownEvents(); this._build(); if (this.isConnected) this.setupEvents(); return; }
311
+ if (name === 'range') this._readValue(this.getAttribute('value'));
312
+ if (name === 'days') this._days = null;
313
+ this._draw();
314
+ }
315
+
316
+ _syncOpen() {
317
+ const open = this.getBoolAttr('open');
318
+ if (this._anchor) (this._anchor.shadowRoot?.querySelector('button, a[href]') ?? this._anchor).setAttribute('aria-expanded', String(open));
319
+ if (open) {
320
+ this._returnFocus = deepActiveElement();
321
+ if (this._returnFocus?.matches(':focus-visible')) requestAnimationFrame(() => this.focusDay());
322
+ document.addEventListener('click', this._onOutside, true);
323
+ } else {
324
+ document.removeEventListener('click', this._onOutside, true);
325
+ const back = this._returnFocus;
326
+ this._returnFocus = null;
327
+ const active = deepActiveElement();
328
+ if (back?.isConnected && active && this._shadow.contains(active)) back.focus({ preventScroll: true });
329
+ }
330
+ this.emit('nk-toggle', { open });
331
+ }
332
+
333
+ // ── form ──
334
+ resetValue() { this._readValue(this._initialValue); this._draw(); }
335
+ restoreValue(state) { this._readValue(state); this._draw(); }
336
+ onFormDisabled(disabled) { this._cal?.toggleAttribute('inert', disabled); }
337
+
338
+ // ── API ──
339
+ /** Opens under `anchor` (with `floating`), on the month of the value. */
340
+ show(anchor) {
341
+ if (anchor) { this._anchor = anchor; placeUnder(this, anchor, this.getAttribute('align')); }
342
+ const shown = this.start;
343
+ if (shown && shown.slice(0, 7) !== this._month) { this._month = shown.slice(0, 7); this._focus = null; this._draw(); }
344
+ this.setBoolAttr('open', true);
345
+ }
346
+ close() { this.setBoolAttr('open', false); }
347
+ toggle(anchor) { this.getBoolAttr('open') ? this.close() : this.show(anchor); }
348
+ get open() { return this.getBoolAttr('open'); }
349
+ set open(v) { this.setBoolAttr('open', v); }
350
+ /** Moves focus to the day with the tab stop. */
351
+ focusDay() { this._grid?.querySelector('[tabindex="0"]')?.focus(); }
352
+ }
353
+
354
+ customElements.define('nk-calendar', NkCalendar);
355
+
356
+ export { NkCalendar };
@@ -0,0 +1,150 @@
1
+ import { NkElement } from './base.js';
2
+ import { d as deepActiveElement, l as lockScroll, i as inertOutside, f as firstFocusable, u as unlockScroll } from './shared/focus-BNAChOXO.js';
3
+ import '@jungherz-de/notionkit/notionkit-styles.js';
4
+
5
+ // <nk-dialog id="trash" title="Move “Roadmap” to trash?" alert>
6
+ // The page and its sub-pages can be restored from Trash for 30 days.
7
+ // <nk-btn slot="actions" variant="secondary" value="">Cancel</nk-btn>
8
+ // <nk-btn slot="actions" variant="danger-solid" value="trash">Move to trash</nk-btn>
9
+ // </nk-dialog>
10
+ // → <div class="nk-dialog-backdrop open"><div class="nk-dialog" role="alertdialog">
11
+ // <div class="dl-title">…</div><div class="dl-body">…</div><div class="dl-actions">…</div></div></div>
12
+ //
13
+ // A question or a short form (NotionKit 1.10.0) with the contract of
14
+ // <nk-modal> and <nk-sheet>: show(), close(), toggle(), nk-toggle; Escape –
15
+ // captured, so it closes before a peek, a menu or a modal behind it – and
16
+ // the backdrop close it; focus moves in, to an [autofocus] element or the
17
+ // first field or button, and back out; the page behind is inert and
18
+ // scroll-locked. It lies above the modal and the sheet, so a question can
19
+ // come from either. 440px, `wide` 560px; below 860px a bottom sheet with the
20
+ // buttons stacked, the confirming one on top.
21
+ // A button in slot="actions" with a `value` closes it with that value; so
22
+ // does the submit of a <form method="dialog"> inside, with its submitter's
23
+ // value. Before it closes, nk-close { value } fires and can be cancelled –
24
+ // the place to check an input dialog; Escape and the backdrop close with ''.
25
+ // `returnValue` keeps the last value. `alert` makes it an alertdialog, named
26
+ // and described by its title and text. `title` is the heading, never a
27
+ // tooltip – see NkElement.takeTitle(). Put it directly under <body>.
28
+ class NkDialog extends NkElement {
29
+ static get observedAttributes() { return ['open', 'title', 'wide', 'alert']; }
30
+
31
+ render() {
32
+ this.takeTitle();
33
+ this.returnValue = '';
34
+ this._backdrop = this.createElement('div', ['nk-dialog-backdrop']);
35
+ this._backdrop.inert = true;
36
+ this._box = this.createElement('div', ['nk-dialog'], { 'aria-modal': 'true', tabindex: '-1' });
37
+ this._heading = this.createElement('div', ['dl-title'], { id: 'title' });
38
+ const body = this.createElement('div', ['dl-body'], { id: 'body' });
39
+ body.appendChild(document.createElement('slot'));
40
+ this._actions = this.createElement('div', ['dl-actions']);
41
+ this._actionsSlot = this.createElement('slot', [], { name: 'actions' });
42
+ this._actions.appendChild(this._actionsSlot);
43
+ this._box.append(this._heading, body, this._actions);
44
+ this._backdrop.appendChild(this._box);
45
+ this._wrapper.appendChild(this._backdrop);
46
+ this._syncTitle();
47
+ this._syncMode();
48
+ this._syncOpen();
49
+ }
50
+
51
+ _syncTitle() {
52
+ const text = this._titleText || '';
53
+ this._heading.textContent = text;
54
+ this._heading.hidden = !text;
55
+ if (text) this._box.setAttribute('aria-labelledby', 'title');
56
+ else this._box.removeAttribute('aria-labelledby');
57
+ }
58
+
59
+ _syncMode() {
60
+ const alert = this.getBoolAttr('alert');
61
+ this._box.setAttribute('role', alert ? 'alertdialog' : 'dialog');
62
+ if (alert) this._box.setAttribute('aria-describedby', 'body'); else this._box.removeAttribute('aria-describedby');
63
+ this._box.classList.toggle('wide', this.getBoolAttr('wide'));
64
+ }
65
+
66
+ _syncOpen() {
67
+ const open = this.getBoolAttr('open');
68
+ this._backdrop.classList.toggle('open', open);
69
+ this._backdrop.inert = !open;
70
+ if (open === this._wasOpen) return;
71
+ this._wasOpen = open;
72
+ if (open) {
73
+ this._returnFocus = this._from ?? deepActiveElement();
74
+ this._from = null;
75
+ // An overlay behind – a modal – made this host inert; the dialog lifts that while it is open.
76
+ this._wasInert = this.inert;
77
+ this.inert = false;
78
+ lockScroll();
79
+ this._undoInert = inertOutside(this);
80
+ requestAnimationFrame(() => (this.querySelector('[autofocus]') || firstFocusable(this) || this._box).focus({ preventScroll: true }));
81
+ } else {
82
+ unlockScroll();
83
+ this._undoInert?.(); this._undoInert = null;
84
+ this.inert = this._wasInert;
85
+ const back = this._returnFocus;
86
+ this._returnFocus = null;
87
+ if (back?.isConnected && typeof back.focus === 'function') back.focus({ preventScroll: true });
88
+ }
89
+ }
90
+
91
+ setupEvents() {
92
+ this._onBackdrop = (e) => { if (e.target === this._backdrop) this.close(''); };
93
+ this._onKey = (e) => { if (e.key === 'Escape' && this.getBoolAttr('open')) { e.stopPropagation(); this.close(''); } };
94
+ // A button with a value closes it; a submit button is the form's.
95
+ this._onClick = (e) => {
96
+ const button = e.composedPath().find(n => n instanceof Element && n !== this && this.contains(n) && n.hasAttribute('value') && (n.localName === 'nk-btn' || n.localName === 'button'));
97
+ if (!button || button.getAttribute('type') === 'submit') return;
98
+ this.close(button.getAttribute('value'));
99
+ };
100
+ this._onSubmit = (e) => {
101
+ if ((e.target.getAttribute('method') || '').toLowerCase() !== 'dialog') return;
102
+ e.preventDefault();
103
+ this.close(e.submitter?.value || e.submitter?.getAttribute?.('value') || 'submit');
104
+ };
105
+ this._onSlot = () => { this._actions.hidden = !this._actionsSlot.assignedElements().length; };
106
+ this._backdrop.addEventListener('click', this._onBackdrop);
107
+ this.addEventListener('click', this._onClick);
108
+ this.addEventListener('submit', this._onSubmit);
109
+ this._actionsSlot.addEventListener('slotchange', this._onSlot);
110
+ document.addEventListener('keydown', this._onKey, true);
111
+ this._onSlot();
112
+ }
113
+
114
+ teardownEvents() {
115
+ this._backdrop?.removeEventListener('click', this._onBackdrop);
116
+ this.removeEventListener('click', this._onClick);
117
+ this.removeEventListener('submit', this._onSubmit);
118
+ this._actionsSlot?.removeEventListener('slotchange', this._onSlot);
119
+ document.removeEventListener('keydown', this._onKey, true);
120
+ if (this._wasOpen) { unlockScroll(); this._undoInert?.(); this._undoInert = null; this._wasOpen = false; }
121
+ }
122
+
123
+ onAttributeChanged(name, oldValue, value) {
124
+ if (name === 'title') { if (this.takeTitle(value)) this._syncTitle(); return; }
125
+ if (name !== 'open') { this._syncMode(); return; }
126
+ this._syncOpen();
127
+ this.emit('nk-toggle', { open: this.getBoolAttr('open') });
128
+ }
129
+
130
+ /** Opens it; focus goes back to `from` when it closes (default: what had focus – pass the ⋯ of a menu that closes). */
131
+ show(from) { this.returnValue = ''; this._from = from ?? null; this.setBoolAttr('open', true); }
132
+ /** Closes with `value`, unless an nk-close listener cancels it. Returns whether it closed. */
133
+ close(value = '') {
134
+ if (!this.getBoolAttr('open')) return false;
135
+ if (!this.emit('nk-close', { value })) return false;
136
+ this.returnValue = value;
137
+ this.setBoolAttr('open', false);
138
+ return true;
139
+ }
140
+ toggle() { this.getBoolAttr('open') ? this.close('') : this.show(); }
141
+
142
+ get open() { return this.getBoolAttr('open'); }
143
+ set open(v) { v ? this.show() : this.close(''); }
144
+ get title() { return this._titleText ?? ''; }
145
+ set title(v) { this._titleText = v == null ? '' : String(v); if (this._initialized) this._syncTitle(); }
146
+ }
147
+
148
+ customElements.define('nk-dialog', NkDialog);
149
+
150
+ export { NkDialog };
@@ -1,5 +1,6 @@
1
1
  import { NkElement } from './base.js';
2
2
  import { d as deepActiveElement } from './shared/focus-BNAChOXO.js';
3
+ import { p as placeUnder } from './shared/floating-CxHxy-Cb.js';
3
4
  import '@jungherz-de/notionkit/notionkit-styles.js';
4
5
 
5
6
  // <nk-menu>
@@ -21,16 +22,6 @@ import '@jungherz-de/notionkit/notionkit-styles.js';
21
22
  const floatSheet = new CSSStyleSheet();
22
23
  floatSheet.replaceSync(`:host([floating]) { display: block; position: fixed; z-index: 60; pointer-events: none; }`);
23
24
 
24
- /** The border box of an element, or of the first descendant with one (display: contents hosts). */
25
- function boxOf(el) {
26
- if (el.getClientRects().length) return el.getBoundingClientRect();
27
- for (const child of [...(el.shadowRoot?.children ?? []), ...el.children]) {
28
- const r = boxOf(child);
29
- if (r.width || r.height) return r;
30
- }
31
- return el.getBoundingClientRect();
32
- }
33
-
34
25
  class NkMenu extends NkElement {
35
26
  static get hostStyles() { return floatSheet; }
36
27
  static get observedAttributes() { return ['floating', 'sheet', 'open', 'align']; }
@@ -71,10 +62,7 @@ class NkMenu extends NkElement {
71
62
  show(anchor) {
72
63
  if (anchor) {
73
64
  this._anchor = anchor;
74
- const r = boxOf(anchor);
75
- this.style.top = `${r.bottom + 6}px`;
76
- if (this.getAttribute('align') === 'start') { this.style.left = `${r.left}px`; this.style.right = ''; }
77
- else { this.style.right = `${Math.max(8, innerWidth - r.right)}px`; this.style.left = ''; }
65
+ placeUnder(this, anchor, this.getAttribute('align'));
78
66
  }
79
67
  this.setBoolAttr('open', true);
80
68
  }