Skip to content

Commit

Permalink
Updates QueriedElement to support ShadowRoot roots.
Browse files Browse the repository at this point in the history
`el.shadowRoot.querySelector` uses a `ShadowRoot` as the root of the query, not an `Element` so we should support that. The behavior of `:scope` seems to be a little weird, but Chrome also returns `null` when used in a shadow root. This [csswg issue](w3c/csswg-drafts#7261) has some ambiguity, but it seems that because browsers don't see shadow roots as elements, `querySelector` can't return the `ShadowRoot`. I think the best behavior we can do is just type `null`.
  • Loading branch information
dgp1130 committed Aug 10, 2024
1 parent a4766f0 commit e4b210a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
8 changes: 8 additions & 0 deletions src/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ describe('query', () => {
const _el: QueriedElement<':scope'> = {} as Element;
});

typeTest('resolve `:scope` to `null` for `ShadowRoot`', () => {
const _el: QueriedElement<':scope', ShadowRoot> = null;
});

typeTest('resolves a tag name with class', () => {
const _el: HTMLInputElement = {} as QueriedElement<'input.clazz'>;
});
Expand Down Expand Up @@ -117,6 +121,10 @@ describe('query', () => {
typeTest('resolves queries without a tag name to `Element`', () => {
const _el: QueriedElement<'.foo'> = {} as Element;
});

typeTest('resolves queries from a `ShadowRoot`', () => {
const _el: QueriedElement<'input', ShadowRoot> = {} as HTMLInputElement;
});
});
});

Expand Down
8 changes: 5 additions & 3 deletions src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@
* return.
*
* @param Query The selector query to resolve.
* @param Host The host element making the query.
* @param Root The root element or shadow root making the query.
* @returns A union of all possible {@link Element} objects which may be
* returned by the query.
*/
export type QueriedElement<
Query extends string,
Host extends Element = Element,
Root extends Element | ShadowRoot = Element,
> = Query extends ':scope'
? Host
? Root extends Element
? Root
: null
: Union<ElementsOf<TagNames<Selectors<Query>>>>
;

Expand Down

0 comments on commit e4b210a

Please sign in to comment.