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

feat: introduce new render params body and bodyAttributes #23

Closed
wants to merge 2 commits into from
Closed
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: 11 additions & 1 deletion src/render.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,23 @@ function dirPlugin(): Plugin<void> {
}

test('should allow `<html>` attributes override', () => {
expect(createRenderFunction()({title: 'Foobar'})).toMatch('<html >');
expect(createRenderFunction()({title: 'Foobar'})).toMatch('<html>');
expect(createRenderFunction([dirPlugin()])({title: 'Foobar'})).toMatch('<html dir="ltr">');
});

test('should allow `<body>` attributes override', () => {
expect(createRenderFunction()({title: 'Foobar'})).toMatch('<body>');
expect(createRenderFunction()({title: 'Foobar', bodyAttributes: {dir: 'ltr'}})).toMatch(
'<body dir="ltr">',
);
});

test('should render root content', () => {
expect(createRenderFunction()({title: 'Foobar'})).toMatch(/<div id="root">\s*<\/div>/);
expect(createRenderFunction()({title: 'Foobar', bodyContent: {root: 'content'}})).toMatch(
/<div id="root">\s*content\s*<\/div>/,
);
expect(createRenderFunction()({title: 'Foobar', body: '<div id="root">content</div>'})).toMatch(
/<div id="root">content<\/div>/,
);
});
36 changes: 26 additions & 10 deletions src/render.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import htmlescape from 'htmlescape';
import {attrs, getRenderHelpers, hasProperty} from './utils.js';
import type {Icon, Meta, RenderParams, Plugin, RenderContent} from './types.js';
import type {Icon, Meta, RenderParams, Plugin, RenderContent, Attributes} from './types.js';

const defaultIcon: Icon = {
type: 'image/png',
Expand All @@ -26,7 +26,7 @@ export function generateRenderContent<Plugins extends Plugin[], Data>(
params: RenderParams<Data, Plugins>,
): RenderContent {
const helpers = getRenderHelpers(params);
const htmlAttributes: Record<string, string> = {};
const htmlAttributes: Attributes = {...params.htmlAttributes};
const meta = [...defaultMeta, ...(params.meta ?? [])];
const styleSheets = params.styleSheets || [];
const scripts = params.scripts || [];
Expand All @@ -43,6 +43,12 @@ export function generateRenderContent<Plugins extends Plugin[], Data>(
beforeRoot: content.beforeRoot ? [content.beforeRoot] : [],
afterRoot: content.afterRoot ? [content.afterRoot] : [],
};
const body = params.body;
const bodyClassName = bodyContent.className.filter(Boolean).join(' ');
const bodyAttributes = {
class: bodyClassName ? bodyClassName : undefined,
...params.bodyAttributes,
};

const {lang, isMobile, title, pluginsOptions = {}} = params;
for (const plugin of plugins ?? []) {
Expand All @@ -59,6 +65,8 @@ export function generateRenderContent<Plugins extends Plugin[], Data>(
inlineStyleSheets,
inlineScripts,
bodyContent,
body,
bodyAttributes,
},
commonOptions: {title, lang, isMobile},
utils: helpers,
Expand All @@ -78,6 +86,8 @@ export function generateRenderContent<Plugins extends Plugin[], Data>(
inlineStyleSheets,
inlineScripts,
bodyContent,
body,
bodyAttributes,
};
}

Expand All @@ -92,6 +102,8 @@ export function createRenderFunction<Plugins extends Plugin[]>(plugins?: Plugins
inlineScripts,
links,
bodyContent,
body,
bodyAttributes,
} = generateRenderContent(plugins, params);

const helpers = getRenderHelpers(params);
Expand All @@ -101,13 +113,21 @@ export function createRenderFunction<Plugins extends Plugin[]>(plugins?: Plugins
...params.icon,
};

const bodyHtml = body
? body
: [
bodyContent.beforeRoot.join('\n'),
`<div id="root">${bodyContent.root ?? ''}</div>`,
bodyContent.afterRoot.join('\n'),
].join('\n');

return `
<!DOCTYPE html>
<html ${attrs({...htmlAttributes})}>
<html${attrs({...htmlAttributes})}>
<head>
<meta charset="utf-8">
<title>${params.title}</title>
<link ${attrs({rel: 'icon', type: icon.type, sizes: icon.sizes, href: icon.href})}>
<link${attrs({rel: 'icon', type: icon.type, sizes: icon.sizes, href: icon.href})}>
${[
...scripts.map(({src, crossOrigin}) =>
helpers.renderLink({href: src, crossOrigin, rel: 'preload', as: 'script'}),
Expand All @@ -122,12 +142,8 @@ export function createRenderFunction<Plugins extends Plugin[]>(plugins?: Plugins
.filter(Boolean)
.join('\n')}
</head>
<body ${attrs({class: bodyContent.className.filter(Boolean).join(' ')})}>
${bodyContent.beforeRoot.join('\n')}
<div id="root">
${bodyContent.root ?? ''}
</div>
${bodyContent.afterRoot.join('\n')}
<body${attrs({...bodyAttributes})}>
${bodyHtml}
</body>
</html>
`.trim();
Expand Down
13 changes: 12 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,24 @@
}

export interface RenderContent {
htmlAttributes: Record<string, string>;
htmlAttributes: Attributes;
meta: Meta[];
links: Link[];
scripts: Script[];
styleSheets: Stylesheet[];
inlineScripts: string[];
inlineStyleSheets: string[];
/**
* @deprecated
*/
bodyContent: {
className: string[];
beforeRoot: string[];
root?: string;
afterRoot: string[];
};
body?: string;
bodyAttributes: Attributes;
}

export interface RenderHelpers {
Expand All @@ -59,7 +64,7 @@
renderMeta(meta: Meta): string;
renderLink(link: Link): string;
}
export interface Plugin<Options = any, Name extends string = string> {

Check warning on line 67 in src/types.ts

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected any. Specify a different type
name: Name;
apply: (params: {
options: Options | undefined;
Expand All @@ -73,18 +78,24 @@
icon?: Icon;
nonce?: string;
// content
htmlAttributes?: Attributes;
meta?: Meta[];
links?: Link[];
scripts?: Script[];
styleSheets?: Stylesheet[];
inlineScripts?: string[];
inlineStyleSheets?: string[];
/**
* @deprecated
*/
bodyContent?: {
className?: string;
beforeRoot?: string;
root?: string;
afterRoot?: string;
};
body?: string;
bodyAttributes?: Attributes;
// plugins options
pluginsOptions?: Partial<PluginsOptions<Plugins>>;
}
Expand All @@ -96,7 +107,7 @@
? {[K in Name & string]: Options}
: {};

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void

Check warning on line 110 in src/types.ts

View workflow job for this annotation

GitHub Actions / Verify Files

Unexpected any. Specify a different type
? I
: never;

Expand Down
16 changes: 8 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import type {Attributes, Link, Meta, Script, Stylesheet, RenderHelpers} from './
export function attrs(obj: Attributes): string {
return Object.entries(obj)
.filter(([, value]) => value !== undefined)
.map(([name, value]) => `${name}="${value}"`)
.join(' ');
.map(([name, value]) => ` ${name}="${value}"`)
.join('');
}

const OG_META_PREFIX = 'og:';

export function getRenderHelpers(params: {nonce?: string}): RenderHelpers {
function renderScript({src, defer, async, crossOrigin}: Script) {
return src
? `<script ${attrs({
? `<script${attrs({
src,
defer,
async,
Expand All @@ -22,23 +22,23 @@ export function getRenderHelpers(params: {nonce?: string}): RenderHelpers {
: '';
}
function renderInlineScript(content: string) {
return `<script ${attrs({nonce: params.nonce})}>${content}</script>`;
return `<script${attrs({nonce: params.nonce})}>${content}</script>`;
}
function renderStyle({href}: Stylesheet) {
return href ? `<link ${attrs({rel: 'stylesheet', href})}>` : '';
return href ? `<link${attrs({rel: 'stylesheet', href})}>` : '';
}
function renderInlineStyle(content: string) {
return `<style ${attrs({nonce: params.nonce})}>${content}</style>`;
return `<style${attrs({nonce: params.nonce})}>${content}</style>`;
}
function renderMeta({name, content}: Meta) {
return `<meta ${attrs({
return `<meta${attrs({
[name.startsWith(OG_META_PREFIX) ? 'property' : 'name']: name,
content,
})}>`;
}
function renderLink({href, crossOrigin, as, ...rest}: Link) {
return href
? `<link ${attrs({
? `<link${attrs({
href,
crossorigin: crossOrigin,
as,
Expand Down
Loading