@atlaskit/top-layer 0.2.0 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @atlaskit/top-layer
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [`60e2bb08cd411`](https://bitbucket.org/atlassian/atlassian-frontend-monorepo/commits/60e2bb08cd411) -
8
+ Expose Popover API and HTMLDialogElement jsdom polyfill (and toBeVisible patch) via new
9
+ testing/polyfill and testing/to-be-visible subpath exports. Adopters can now opt in to the
10
+ polyfill in their jest setup with a single import.
11
+
3
12
  ## 0.2.0
4
13
 
5
14
  ### Minor Changes
@@ -0,0 +1,347 @@
1
+ "use strict";
2
+
3
+ /* eslint-disable compat/compat */
4
+ /**
5
+ * Popover API & HTMLDialogElement polyfills for jsdom.
6
+ *
7
+ * jsdom does not implement the Popover API or the HTMLDialogElement methods
8
+ * (showModal, show, close). This polyfill provides faithful implementations,
9
+ * including timing semantics validated against Chromium via Playwright.
10
+ *
11
+ * Behaviour:
12
+ * - beforetoggle: sync, cancelable on show only. toggle: async task, not cancelable.
13
+ * - Rapid show/hide coalesces into one toggle event (originalOldState to finalNewState).
14
+ * - Dialog: showModal/show fire beforetoggle+toggle. close fires toggle then close event.
15
+ * - Popover open state tracked via `data-popover-open` (no `:popover-open` in jsdom).
16
+ *
17
+ * Companion `toBeVisible` patch lives at `./to-be-visible`.
18
+ *
19
+ * Importing this module has the side-effect of patching the relevant
20
+ * prototypes. It is safe to import multiple times; each branch is guarded
21
+ * to avoid overwriting native implementations or re-patching.
22
+ */
23
+
24
+ /**
25
+ * e.g. `<div#my-id.class-a.class-b>`
26
+ */
27
+ function describeElement(_ref) {
28
+ var element = _ref.element;
29
+ var tag = element.tagName ? element.tagName.toLowerCase() : 'unknown';
30
+ var id = element.id ? "#".concat(element.id) : '';
31
+ var classes = element.classList && element.classList.length > 0 ? ".".concat(Array.from(element.classList).join('.')) : '';
32
+ return "<".concat(tag).concat(id).concat(classes, ">");
33
+ }
34
+ function createToggleEvent(_ref2) {
35
+ var type = _ref2.type,
36
+ oldState = _ref2.oldState,
37
+ newState = _ref2.newState,
38
+ cancelable = _ref2.cancelable;
39
+ if (typeof globalThis.ToggleEvent === 'function') {
40
+ // ToggleEvent is not in lib.dom.d.ts at the time of writing; cast to any for construction.
41
+ var ToggleEventCtor = globalThis.ToggleEvent;
42
+ return new ToggleEventCtor(type, {
43
+ oldState: oldState,
44
+ newState: newState,
45
+ cancelable: cancelable,
46
+ bubbles: false
47
+ });
48
+ }
49
+ var event = new Event(type, {
50
+ cancelable: cancelable,
51
+ bubbles: false
52
+ });
53
+ event.oldState = oldState;
54
+ event.newState = newState;
55
+ return event;
56
+ }
57
+ function fireToggleEvent(_ref3) {
58
+ var element = _ref3.element,
59
+ type = _ref3.type,
60
+ oldState = _ref3.oldState,
61
+ newState = _ref3.newState,
62
+ cancelable = _ref3.cancelable;
63
+ return element.dispatchEvent(createToggleEvent({
64
+ type: type,
65
+ oldState: oldState,
66
+ newState: newState,
67
+ cancelable: cancelable
68
+ }));
69
+ }
70
+ function oppositeState(_ref4) {
71
+ var state = _ref4.state;
72
+ if (state === 'open') {
73
+ return 'closed';
74
+ }
75
+ return 'open';
76
+ }
77
+
78
+ // Coalesces rapid show/hide into one toggle event per element.
79
+ // Uses setTimeout (task) not Promise.resolve (microtask) to match browser timing.
80
+ function createToggleScheduler() {
81
+ var pending = new Map();
82
+ return function schedule(_ref5) {
83
+ var element = _ref5.element,
84
+ newState = _ref5.newState;
85
+ var existing = pending.get(element);
86
+ if (existing) {
87
+ // Coalesce: keep the original oldState, update newState
88
+ pending.set(element, {
89
+ oldState: existing.oldState,
90
+ newState: newState
91
+ });
92
+ return;
93
+ }
94
+ pending.set(element, {
95
+ oldState: oppositeState({
96
+ state: newState
97
+ }),
98
+ newState: newState
99
+ });
100
+
101
+ // Task queue (setTimeout) — browser fires toggle after microtasks drain, not during
102
+ setTimeout(function () {
103
+ var entry = pending.get(element);
104
+ if (!entry) {
105
+ return;
106
+ }
107
+ pending.delete(element);
108
+ fireToggleEvent({
109
+ element: element,
110
+ type: 'toggle',
111
+ oldState: entry.oldState,
112
+ newState: entry.newState,
113
+ cancelable: false
114
+ });
115
+ }, 0);
116
+ };
117
+ }
118
+
119
+ // Like createToggleScheduler but also fires a close event as a separate task after toggle.
120
+ function createDialogToggleScheduler() {
121
+ var pending = new Map();
122
+ return function schedule(_ref6) {
123
+ var dialog = _ref6.dialog,
124
+ newState = _ref6.newState,
125
+ shouldFireCloseEvent = _ref6.shouldFireCloseEvent;
126
+ var existing = pending.get(dialog);
127
+ if (existing) {
128
+ // Coalesce: keep the original oldState, merge shouldFireCloseEvent
129
+ pending.set(dialog, {
130
+ oldState: existing.oldState,
131
+ newState: newState,
132
+ shouldFireCloseEvent: existing.shouldFireCloseEvent || shouldFireCloseEvent
133
+ });
134
+ return;
135
+ }
136
+ pending.set(dialog, {
137
+ oldState: oppositeState({
138
+ state: newState
139
+ }),
140
+ newState: newState,
141
+ shouldFireCloseEvent: shouldFireCloseEvent
142
+ });
143
+
144
+ // Browser fires toggle as a task, not synchronously or as a microtask
145
+ setTimeout(function () {
146
+ var entry = pending.get(dialog);
147
+ if (!entry) {
148
+ return;
149
+ }
150
+ pending.delete(dialog);
151
+ fireToggleEvent({
152
+ element: dialog,
153
+ type: 'toggle',
154
+ oldState: entry.oldState,
155
+ newState: entry.newState,
156
+ cancelable: false
157
+ });
158
+ if (entry.shouldFireCloseEvent) {
159
+ // Browser fires close as a separate task after toggle
160
+ setTimeout(function () {
161
+ dialog.dispatchEvent(new Event('close', {
162
+ bubbles: false,
163
+ cancelable: false
164
+ }));
165
+ }, 0);
166
+ }
167
+ }, 0);
168
+ };
169
+ }
170
+
171
+ // ─── Popover API ────────────────────────────────────────────────────────────
172
+
173
+ if (typeof HTMLElement !== 'undefined' && !HTMLElement.prototype.showPopover) {
174
+ var schedulePopoverToggle = createToggleScheduler();
175
+ HTMLElement.prototype.showPopover = function showPopover() {
176
+ if (!this.hasAttribute('popover')) {
177
+ throw new DOMException("Failed to execute 'showPopover' on 'HTMLElement': ".concat(describeElement({
178
+ element: this
179
+ }), " is not a popover element. Ensure the element has a 'popover' attribute (e.g. <div popover>)."), 'NotSupportedError');
180
+ }
181
+ if (!this.isConnected) {
182
+ throw new DOMException("Failed to execute 'showPopover' on 'HTMLElement': ".concat(describeElement({
183
+ element: this
184
+ }), " is not connected to the document. Ensure the element has been added to the DOM (e.g. via render() or document.body.appendChild()) before calling showPopover()."), 'InvalidStateError');
185
+ }
186
+ if (this.hasAttribute('data-popover-open')) {
187
+ return; // already showing — no-op
188
+ }
189
+
190
+ // sync, cancelable on show only
191
+ var allowed = fireToggleEvent({
192
+ element: this,
193
+ type: 'beforetoggle',
194
+ oldState: 'closed',
195
+ newState: 'open',
196
+ cancelable: true
197
+ });
198
+ if (!allowed) {
199
+ return;
200
+ }
201
+ this.setAttribute('data-popover-open', '');
202
+ schedulePopoverToggle({
203
+ element: this,
204
+ newState: 'open'
205
+ });
206
+ };
207
+ HTMLElement.prototype.hidePopover = function hidePopover() {
208
+ if (!this.hasAttribute('popover')) {
209
+ throw new DOMException("Failed to execute 'hidePopover' on 'HTMLElement': ".concat(describeElement({
210
+ element: this
211
+ }), " is not a popover element. Ensure the element has a 'popover' attribute (e.g. <div popover>)."), 'NotSupportedError');
212
+ }
213
+ // Browser does not throw for disconnected elements on hide — just no-op
214
+ if (!this.isConnected || !this.hasAttribute('data-popover-open')) {
215
+ return;
216
+ }
217
+
218
+ // not cancelable on hide
219
+ fireToggleEvent({
220
+ element: this,
221
+ type: 'beforetoggle',
222
+ oldState: 'open',
223
+ newState: 'closed',
224
+ cancelable: false
225
+ });
226
+ this.removeAttribute('data-popover-open');
227
+ schedulePopoverToggle({
228
+ element: this,
229
+ newState: 'closed'
230
+ });
231
+ };
232
+ HTMLElement.prototype.togglePopover = function togglePopover(force) {
233
+ var isOpen = this.hasAttribute('data-popover-open');
234
+ if (typeof force === 'boolean') {
235
+ if (force && !isOpen) {
236
+ this.showPopover();
237
+ } else if (!force && isOpen) {
238
+ this.hidePopover();
239
+ }
240
+ return force;
241
+ }
242
+ if (isOpen) {
243
+ this.hidePopover();
244
+ return false;
245
+ }
246
+ this.showPopover();
247
+ return true;
248
+ };
249
+ }
250
+
251
+ // ─── HTMLDialogElement ──────────────────────────────────────────────────────
252
+
253
+ if (typeof HTMLDialogElement !== 'undefined') {
254
+ var proto = HTMLDialogElement.prototype;
255
+ var scheduleDialogToggle = createDialogToggleScheduler();
256
+ if (typeof proto.showModal !== 'function') {
257
+ proto.showModal = function showModal() {
258
+ if (!this.isConnected) {
259
+ throw new DOMException("Failed to execute 'showModal' on 'HTMLDialogElement': ".concat(describeElement({
260
+ element: this
261
+ }), " is not connected to the document. Ensure the element has been added to the DOM (e.g. via render() or document.body.appendChild()) before calling showModal()."), 'InvalidStateError');
262
+ }
263
+ if (this.hasAttribute('open')) {
264
+ if (this._isModal) {
265
+ return; // already modal — no-op
266
+ }
267
+ throw new DOMException("Failed to execute 'showModal' on 'HTMLDialogElement': ".concat(describeElement({
268
+ element: this
269
+ }), " already has an 'open' attribute, and therefore cannot be opened modally. The dialog was likely opened non-modally with .show(). Call .close() first, then .showModal()."), 'InvalidStateError');
270
+ }
271
+ fireToggleEvent({
272
+ element: this,
273
+ type: 'beforetoggle',
274
+ oldState: 'closed',
275
+ newState: 'open',
276
+ cancelable: false
277
+ });
278
+ this.setAttribute('open', '');
279
+ this._isModal = true;
280
+ scheduleDialogToggle({
281
+ dialog: this,
282
+ newState: 'open',
283
+ shouldFireCloseEvent: false
284
+ });
285
+ };
286
+ }
287
+ if (typeof proto.show !== 'function') {
288
+ proto.show = function show() {
289
+ // Browser does not throw for disconnected elements on show — just no-op
290
+ if (!this.isConnected || this.hasAttribute('open')) {
291
+ return;
292
+ }
293
+ fireToggleEvent({
294
+ element: this,
295
+ type: 'beforetoggle',
296
+ oldState: 'closed',
297
+ newState: 'open',
298
+ cancelable: false
299
+ });
300
+ this.setAttribute('open', '');
301
+ this._isModal = false;
302
+ scheduleDialogToggle({
303
+ dialog: this,
304
+ newState: 'open',
305
+ shouldFireCloseEvent: false
306
+ });
307
+ };
308
+ }
309
+ if (typeof proto.close !== 'function') {
310
+ proto.close = function close(returnValue) {
311
+ if (!this.hasAttribute('open')) {
312
+ return; // already closed — no-op
313
+ }
314
+
315
+ // Sync beforetoggle (not cancelable) — matches browser behavior
316
+ fireToggleEvent({
317
+ element: this,
318
+ type: 'beforetoggle',
319
+ oldState: 'open',
320
+ newState: 'closed',
321
+ cancelable: false
322
+ });
323
+ this.removeAttribute('open');
324
+ this._isModal = false;
325
+ if (returnValue !== undefined) {
326
+ this.returnValue = returnValue;
327
+ }
328
+ scheduleDialogToggle({
329
+ dialog: this,
330
+ newState: 'closed',
331
+ shouldFireCloseEvent: true
332
+ });
333
+ };
334
+ }
335
+ if (!('returnValue' in proto)) {
336
+ Object.defineProperty(proto, 'returnValue', {
337
+ get: function get() {
338
+ return this._returnValue === undefined ? '' : this._returnValue;
339
+ },
340
+ set: function set(value) {
341
+ this._returnValue = String(value);
342
+ },
343
+ configurable: true,
344
+ enumerable: true
345
+ });
346
+ }
347
+ }
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+
3
+ var _matchers = require("@testing-library/jest-dom/matchers");
4
+ /* eslint-disable compat/compat */
5
+ /* global expect */
6
+ /**
7
+ * Patches `toBeVisible()` to understand popover and dialog visibility.
8
+ *
9
+ * jest-dom's `toBeVisible()` does not know about the Popover API. In real
10
+ * browsers the UA stylesheet hides `[popover]` with `display: none`, but
11
+ * jsdom has no such stylesheet — so closed popovers incorrectly appear visible.
12
+ *
13
+ * Raw jest-dom results in jsdom:
14
+ *
15
+ * closed popover / child → true (WRONG — should be false)
16
+ * open popover / child → true (correct)
17
+ * closed dialog / child → false (correct — jsdom natively hides <dialog>)
18
+ * open dialog / child → true (correct)
19
+ *
20
+ * We correct both false positives and false negatives:
21
+ * 1. Delegate to the original first.
22
+ * 2. If it says "visible" → check for closed top-layer hosts (false positive).
23
+ * 3. If it says "not visible" → check for open top-layer hosts (false negative).
24
+ *
25
+ * Must load via `setupFilesAfterEnv` (after jest-dom registers its matchers).
26
+ * Polyfills live in `./polyfill` (loaded via `setupFiles`).
27
+ */
28
+
29
+ // Delegating to jest-dom's matcher; types come from @testing-library/jest-dom.
30
+ // eslint-disable-next-line import/no-extraneous-dependencies
31
+
32
+ /**
33
+ * Finds the nearest popover or dialog ancestor (including the element itself)
34
+ * and returns its state: 'open', 'closed', or null if no top-layer ancestor exists.
35
+ *
36
+ * Checking the *nearest* ancestor handles nesting correctly:
37
+ * a closed popover inside an open popover → nearest is closed → not visible.
38
+ */
39
+ function nearestTopLayerState(element) {
40
+ if (!element) {
41
+ return null;
42
+ }
43
+ if (element.hasAttribute('popover')) {
44
+ return element.hasAttribute('data-popover-open') ? 'open' : 'closed';
45
+ }
46
+ if (element.nodeName === 'DIALOG') {
47
+ return element.hasAttribute('open') ? 'open' : 'closed';
48
+ }
49
+ return nearestTopLayerState(element.parentElement);
50
+ }
51
+ function getNearestTopLayerType(element) {
52
+ if (!element.closest) {
53
+ return 'top-layer element';
54
+ }
55
+ if (element.closest('[popover]')) {
56
+ return 'popover';
57
+ }
58
+ return 'dialog';
59
+ }
60
+
61
+ // `expect` is registered globally by jest before this file runs.
62
+
63
+ expect.extend({
64
+ toBeVisible: function toBeVisible(element) {
65
+ var originalResult = _matchers.toBeVisible.call(this, element);
66
+ var topLayerState = nearestTopLayerState(element);
67
+ if (originalResult.pass) {
68
+ // Original says visible — override if nearest top-layer host is closed.
69
+ if (topLayerState === 'closed') {
70
+ return {
71
+ pass: false,
72
+ message: function message() {
73
+ return "expected element to be visible, but it is inside a closed ".concat(getNearestTopLayerType(element));
74
+ }
75
+ };
76
+ }
77
+ return originalResult;
78
+ }
79
+
80
+ // Original says not visible — override if nearest top-layer host is open.
81
+ // jsdom may hide [popover] elements even when they are logically open.
82
+ if (topLayerState === 'open') {
83
+ return {
84
+ pass: true,
85
+ message: function message() {
86
+ return "expected element not to be visible, but it is inside an open ".concat(getNearestTopLayerType(element));
87
+ }
88
+ };
89
+ }
90
+ return originalResult;
91
+ }
92
+ });