Skip to content

Commit

Permalink
Updates Template component to allow all the common HTML attributes.
Browse files Browse the repository at this point in the history
For some reason, `createElement()` falls apart here. I think it's inferring possible tag names from the input properties and not finding any matches. I could define a new intrinsic, but I don't want to leak that into user code, since that's inherently a global modification.
  • Loading branch information
dgp1130 committed Mar 13, 2023
1 parent 2a612d2 commit 46f5930
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
15 changes: 9 additions & 6 deletions packages/preact/index.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { VNode, createElement, ComponentChildren } from 'preact';
import { JSX, VNode, createElement } from 'preact';
import { render } from 'preact-render-to-string';
import * as rulesPrerender from 'rules_prerender';

Expand Down Expand Up @@ -49,10 +49,13 @@ export function inlineStyle(importPath: string, meta: ImportMeta): VNode {
return createElement('rules_prerender:annotation', {}, [ annotation ]);
}

interface TemplateProps extends JSX.HTMLAttributes<HTMLTemplateElement> {
shadowroot?: ShadowRootMode;
}

/** A component representing the native HTML `<template />` tag. */
export function Template({ children, ...attrs }: {
children?: ComponentChildren,
[attr: string]: unknown,
} = {}): VNode {
return createElement('template', { children, ...attrs });
export function Template({ children, ...attrs }: TemplateProps = {}): VNode {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore JSX types are weird AF.
return createElement('template', attrs, children);
}
26 changes: 24 additions & 2 deletions packages/preact/index_test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -69,16 +69,38 @@ describe('preact', () => {
describe('Template', () => {
it('renders a `<template />` element', () => {
const html = render(Template({
shadowroot: 'open',
children: [
createElement('div', {}, [
'Hello, World!',
]),
],
}));

expect(html).toContain('<template shadowroot="open">');
expect(html).toContain('<template>');
expect(html).toContain('<div>Hello, World!</div>');
});

it('accepts `shadowroot`', () => {
const html = render(Template({ shadowroot: 'open' }));

expect(html).toContain('<template shadowroot="open">');
});

it('allows other HTML attributes', () => {
const html = render(Template({ id: 'my-template' }));

expect(html).toContain('<template id="my-template">');
});

it('restricts `shadowroot` type', () => {
// @ts-expect-error Wrong shadow root module.
expect(() => Template({ shadowroot: 'not-a-shadowroot-mode' }))
.not.toThrow();
});

it('disallows unknown attributes', () => {
// @ts-expect-error Unknown attribute.
expect(() => Template({ notAnAttribute: 'test' })).not.toThrow();
});
});
});

0 comments on commit 46f5930

Please sign in to comment.