Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch qsa matches closest to accept :popover-open #84

Merged
merged 4 commits into from
Apr 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

- 🚀 NEW: Support for `:popover-open` pseudo selector, including a polyfill for
JavaScript API methods (`querySelector`, `querySelectorAll`, `matches`, and
`closest`) --
[#84](https://github.com/oddbird/popover-polyfill/pull/84)
- 🐛 BUGFIX: Return `null` for disconnected elements --
[#90](https://github.com/oddbird/popover-polyfill/pull/90)

Expand Down Expand Up @@ -47,7 +51,8 @@

## 0.0.8: 2023-01-26

- 🚀 NEW: Add support for new [`beforetoggle` event](https://whatpr.org/html/8221/popover.html#show-popover) --
- 🚀 NEW: Add support for new [`beforetoggle`
event](https://whatpr.org/html/8221/popover.html#show-popover) --
[#68](https://github.com/oddbird/popover-polyfill/pull/68)
- 🏠 INTERNAL: Upgrade dependencies

Expand All @@ -61,8 +66,9 @@

## 0.0.6: 2023-01-17

- 🚀 NEW: Update CSS to align closer to [Chrome's user-agent CSS](https://github.com/chromium/chromium/blob/main/third_party/blink/renderer/core/css/popover.css) --
[#60](https://github.com/oddbird/popover-polyfill/pull/60)
- 🚀 NEW: Update CSS to align closer to [Chrome's user-agent
CSS](https://github.com/chromium/chromium/blob/main/third_party/blink/renderer/core/css/popover.css)
-- [#60](https://github.com/oddbird/popover-polyfill/pull/60)
- 🏠 INTERNAL: Upgrade dependencies

## 0.0.5: 2023-01-14
Expand Down
30 changes: 18 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,24 @@ attributes to the HTMLElement class.
This polyfill is not a perfect replacement for the native behavior; there are
some caveats which will need accommodations:

- Native `popover` has an `:open` and `:closed` pseudo selector state. This is
not possible to polyfill, so instead this adds the `.\:open` CSS class to any
open popover.

- `:closed` is not implemented due to difficulty in finding popover elements
during page load. As such, you'll need to style them using `:not(.\:open)`.

- Using native `:open` in CSS that does not support native `popover` results
in an invalid selector, and so the entire declaration is thrown away. This
is important because if you intend to style a popover using `.\:open` it
will need to be a separate declaration. For example,
`[popover]:open, [popover].\:open` will not work.
- A native `popover` has a `:popover-open` pseudo selector when in the open
state. Pseudo selectors cannot be polyfilled within CSS, and so instead the
polyfill will add the `.\:popover-open` CSS class to any open popover. In
other words a popover in the open state will have `class=":popover-open"`. In
CSS the `:` character must be escaped with a backslash.

- The `:popover-open` selector within JavaScript methods has been polyfilled,
so both `.querySelector(':popover-open')` _and_
`.querySelector('.\:popover-open')` will work to select the same element.
`matches` and `closest` have also been patched, so
`.matches(':popover-open')` will work the same as
`.matches('.\:popover-open')`.

- Using native `:popover-open` in CSS that does not support native `popover`
results in an invalid selector, and so the entire declaration is thrown
away. This is important because if you intend to style a popover using
`.\:popover-open` it will need to be a separate declaration. For example,
`[popover]:popover-open, [popover].\:popover-open` will not work.

- Native `popover` elements use the `:top-layer` pseudo element which gets
placed above all other elements on the page, regardless of overflow or
Expand Down
4 changes: 2 additions & 2 deletions src/popover-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ export function showPopover(element: HTMLElement) {
}
previouslyFocusedElements.delete(element);
const originallyFocusedElement = document.activeElement as HTMLElement;
element.classList.add(':open');
element.classList.add(':popover-open');
visibilityState.set(element, 'showing');
if (!topLayerElements.has(document)) {
topLayerElements.set(document, new Set());
Expand Down Expand Up @@ -293,7 +293,7 @@ export function hidePopover(
}
topLayerElements.get(document)?.delete(element);
autoPopoverList.get(document)?.delete(element);
element.classList.remove(':open');
element.classList.remove(':popover-open');
visibilityState.set(element, 'hidden');
if (fireEvents) {
queuePopoverToggleEventTask(element, 'open', 'closed');
Expand Down
21 changes: 17 additions & 4 deletions src/popover.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,26 @@
}

/* stylelint-disable selector-class-pattern */

/* This older `:open` pseudo selector is deprecated and support will be removed
in a later release. */
@supports not selector([popover]:open) {
jgerigmeyer marked this conversation as resolved.
Show resolved Hide resolved
[popover]:not(.\:open) {
[popover]:not(.\:popover-open, dialog[open]) {
display: none;
}

[anchor].\:popover-open {
inset: auto;
}
}
/* stylelint-enable selector-class-pattern */

[popover][anchor] {
inset: auto;
@supports not selector([popover]:popover-open) {
[popover]:not(.\:popover-open, dialog[open]) {
display: none;
}

[anchor].\:popover-open {
inset: auto;
}
}
/* stylelint-enable selector-class-pattern */
42 changes: 42 additions & 0 deletions src/popover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,51 @@ export function isSupported() {
);
}

function patchSelectorFn<K extends string>(
object: Record<PropertyKey & K, unknown>,
name: K,
mapper: (selector: string) => string,
) {
const original = object[name] as (selectors: string) => NodeList;
Object.defineProperty(object, name, {
value(selector: string) {
return original.call(this, mapper(selector));
},
});
}

const nonEscapedPopoverSelector = /(^|[^\\]):popover-open\b/g;

export function apply() {
window.ToggleEvent = window.ToggleEvent || ToggleEvent;

function rewriteSelector(selector: string) {
if (selector.includes(':popover-open')) {
selector = selector.replace(
nonEscapedPopoverSelector,
'$1.\\:popover-open',
);
}
return selector;
}

patchSelectorFn(Document.prototype, 'querySelector', rewriteSelector);
patchSelectorFn(Document.prototype, 'querySelectorAll', rewriteSelector);
patchSelectorFn(Element.prototype, 'querySelector', rewriteSelector);
patchSelectorFn(Element.prototype, 'querySelectorAll', rewriteSelector);
patchSelectorFn(Element.prototype, 'matches', rewriteSelector);
patchSelectorFn(Element.prototype, 'closest', rewriteSelector);
Comment on lines +51 to +52
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HTMLDocument nor DocumentFragment have matches nor closest. I think I have all functions that take CSS selectors here. Let me know if I missed one!

patchSelectorFn(
DocumentFragment.prototype,
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ShadowRoot inherits DocumentFragment, and so patching DocumentFragment also patches ShadowRoot.

'querySelectorAll',
rewriteSelector,
);
patchSelectorFn(
DocumentFragment.prototype,
'querySelectorAll',
rewriteSelector,
);

Object.defineProperties(HTMLElement.prototype, {
popover: {
enumerable: true,
Expand Down
35 changes: 35 additions & 0 deletions tests/basic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,45 @@ expect.extend({
await popover.evaluate((node) => node.showPopover()),
).toBeUndefined();
await expect(popover).toBeVisible();
await expect(
await popover.evaluate((node) => node.matches(':popover-open')),
).toEqual(true);
await expect(
await popover.evaluate((node) => node.closest(':popover-open') === node),
).toEqual(true);
await expect(
await popover.evaluate((node) => node.matches(':not(:popover-open)')),
).toEqual(false);
await expect(
await popover.evaluate(
() => document.querySelectorAll(':popover-open').length,
),
).toEqual(1);
await expect(
await popover.evaluate((node) => node.hidePopover()),
).toBeUndefined();
await expect(popover).toBeHidden();
await expect(
await popover.evaluate((node) => node.matches(':popover-open')),
).toEqual(false);
await expect(
await popover.evaluate((node) => node.matches(':not(:popover-open)')),
).toEqual(true);
await expect(
await popover.evaluate(
(node) => node.closest(':not(:popover-open)') === node,
),
).toEqual(true);
await expect(
await popover.evaluate(
() => document.querySelectorAll(':popover-open').length,
),
).toEqual(0);
await expect(
await popover.evaluate(
() => document.querySelectorAll('[popover]:popover-open').length,
),
).toEqual(0);
return { pass: true };
},
});
Expand Down