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: export html parts renderers #38

Merged
merged 5 commits into from
Mar 19, 2024
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
89 changes: 78 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ interface Link {
href: string;
rel?: string;
type?: string;
sizes?: string;
title?: HTMLLinkElement['title'];
crossOrigin?: '' | 'anonymous' | 'use-credentials';
}
Expand Down Expand Up @@ -236,6 +237,7 @@ interface Plugin<Options = any, Name = string> {
options: Options | undefined; // passed through `renderLayout` function in `pluginsOptions` parameter.
commonOptions: CommonOptions;
renderContent: RenderContent;
/** @deprecated use `renderContent.helpers` instead */
utils: RenderHelpers;
}) => void;
}
Expand All @@ -247,20 +249,29 @@ interface CommonOptions {
isMobile?: boolean;
}

interface RenderContent {
meta: Meta[];
links: Link[];
export interface HeadContent {
scripts: Script[];
helpers: RenderHelpers;
links: Link[];
meta: Meta[];
styleSheets: Stylesheet[];
inlineScripts: string[];
inlineStyleSheets: string[];
bodyContent: {
theme?: string;
className: string[];
beforeRoot: string[];
root?: string;
afterRoot: string[];
};
inlineScripts: string[];
title: string;
}

export interface BodyContent {
attributes: Attributes;
/** @deprecated use attributes.class instead */
className: string[];
beforeRoot: string[];
root?: string;
afterRoot: string[];
}

export interface RenderContent extends HeadContent {
htmlAttributes: Attributes;
bodyContent: BodyContent;
}

export interface RenderHelpers {
Expand All @@ -270,6 +281,7 @@ export interface RenderHelpers {
renderInlineStyle(content: string): string;
renderMeta(meta: Meta): string;
renderLink(link: Link): string;
attrs(obj: Attributes): string;
}
```

Expand Down Expand Up @@ -438,3 +450,58 @@ app.get((req, res) => {
}));
})
```

## Alternative usage

With parts renderers `generateRenderContent`, `renderHeadContent`, `renderBodyContent` via html streaming:

```js
import express from 'express';
import htmlescape from 'htmlescape';
import {
generateRenderContent,
renderHeadContent,
renderBodyContent,
createDefaultPlugins,
} from '@gravity-ui/app-layout';

const app = express();

app.get('/', async function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Transfer-Encoding': 'chunked',
});

const plugins = createDefaultPlugins({layout: {manifest: 'path/to/assets-manifest.json'}});

const content = generateRenderContent(plugins, {
ValeraS marked this conversation as resolved.
Show resolved Hide resolved
title: 'Home page',
});

const {htmlAttributes, helpers, bodyContent} = content;

res.write(`
<!DOCTYPE html>
<html ${helpers.attrs({...htmlAttributes})}>
<head>
${renderHeadContent(content)}
</head>
<body ${helpers.attrs(bodyContent.attributes)}>
${renderBodyContent(content)}
`);

const data = await getUserData();

res.write(`
${content.renderHelpers.renderInlineScript(`
window.__DATA__ = ${htmlescape(data)};
ValeraS marked this conversation as resolved.
Show resolved Hide resolved
`)}
</body>
</html>
`);
res.end();
});

app.listen(3000);
```
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
export {createRenderFunction, generateRenderContent} from './render.js';
export {generateRenderContent} from './utils/generateRenderContent.js';
export {renderHeadContent} from './utils/renderHeadContent.js';
export {renderBodyContent} from './utils/renderBodyContent.js';
export {createRenderFunction} from './render.js';
export {
createGoogleAnalyticsPlugin,
createYandexMetrikaPlugin,
Expand Down
153 changes: 10 additions & 143 deletions src/render.ts
Original file line number Diff line number Diff line change
@@ -1,155 +1,22 @@
import htmlescape from 'htmlescape';

import type {Icon, Meta, Plugin, RenderContent, RenderParams} from './types.js';
import {attrs, getRenderHelpers, hasProperty} from './utils.js';

function getRootClassName(theme?: string) {
if (!theme) {
return [];
}
const classes = ['g-root'];
if (theme) {
classes.push(`g-root_theme_${theme}`);
}
return classes;
}

const defaultIcon: Icon = {
type: 'image/png',
sizes: '16x16',
href: '/favicon.png',
};

const defaultMeta: Meta[] = [
{
name: 'viewport',
content: 'width=device-width, initial-scale=1.0',
},
];

/**
* Generates the content to be rendered in an HTML page.
* @param plugins - An array of plugins.
* @param params - An object containing various parameters for rendering the content.
* @returns An object containing the generated content for an HTML page.
*/
export function generateRenderContent<Plugins extends Plugin[], Data>(
plugins: Plugins | undefined,
params: RenderParams<Data, Plugins>,
): RenderContent {
const helpers = getRenderHelpers(params);
const htmlAttributes: Record<string, string> = {};
const meta = params.meta ?? [];
// in terms of sets: meta = params.meta ∪ (defaultMeta ∖ params.meta)
defaultMeta.forEach((defaultMetaItem) => {
if (!meta.find(({name}) => name === defaultMetaItem.name)) {
meta.push(defaultMetaItem);
}
});
const styleSheets = params.styleSheets || [];
const scripts = params.scripts || [];
const inlineStyleSheets = params.inlineStyleSheets || [];
const inlineScripts = params.inlineScripts || [];
const links = params.links || [];

inlineScripts.unshift(`window.__DATA__ = ${htmlescape(params.data || {})};`);

const content = params.bodyContent ?? {};
const {theme, className} = content;
const bodyClasses = Array.from(
new Set([...getRootClassName(theme), ...(className ? className.split(' ') : [])]),
);
const bodyContent = {
className: bodyClasses,
root: content.root,
beforeRoot: content.beforeRoot ? [content.beforeRoot] : [],
afterRoot: content.afterRoot ? [content.afterRoot] : [],
};

const {lang, isMobile, title, pluginsOptions = {}} = params;
for (const plugin of plugins ?? []) {
plugin.apply({
options: hasProperty(pluginsOptions, plugin.name)
? pluginsOptions[plugin.name]
: undefined,
renderContent: {
htmlAttributes,
meta,
links,
styleSheets,
scripts,
inlineStyleSheets,
inlineScripts,
bodyContent,
},
commonOptions: {title, lang, isMobile},
utils: helpers,
});
}

if (lang) {
htmlAttributes.lang = lang;
}

return {
htmlAttributes,
meta,
links,
styleSheets,
scripts,
inlineStyleSheets,
inlineScripts,
bodyContent,
};
}
import type {Plugin, RenderParams} from './types.js';
import {generateRenderContent} from './utils/generateRenderContent.js';
import {renderBodyContent} from './utils/renderBodyContent.js';
import {renderHeadContent} from './utils/renderHeadContent.js';

export function createRenderFunction<Plugins extends Plugin[]>(plugins?: Plugins) {
return function render<Data>(params: RenderParams<Data, Plugins>) {
const {
htmlAttributes,
meta,
styleSheets,
scripts,
inlineStyleSheets,
inlineScripts,
links,
bodyContent,
} = generateRenderContent(plugins, params);

const helpers = getRenderHelpers(params);
const content = generateRenderContent(plugins, params);

const icon: Icon = {
...defaultIcon,
...params.icon,
};
const {htmlAttributes, helpers, bodyContent} = content;

return `
<!DOCTYPE html>
<html ${attrs({...htmlAttributes})}>
<html ${helpers.attrs({...htmlAttributes})}>
<head>
<meta charset="utf-8">
<title>${params.title}</title>
<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'}),
),
...links.map((link) => helpers.renderLink(link)),
...meta.map((metaData) => helpers.renderMeta(metaData)),
...styleSheets.map((style) => helpers.renderStyle(style)),
...inlineStyleSheets.map((text) => helpers.renderInlineStyle(text)),
...scripts.map((script) => helpers.renderScript(script)),
...inlineScripts.map((text) => helpers.renderInlineScript(text)),
]
.filter(Boolean)
.join('\n')}
${renderHeadContent(content)}
</head>
<body ${attrs({class: bodyContent.className.filter(Boolean).join(' ')})}>
${bodyContent.beforeRoot.join('\n')}
<div id="root">
${bodyContent.root ?? ''}
</div>
${bodyContent.afterRoot.join('\n')}
<body ${helpers.attrs(bodyContent.attributes)}>
${renderBodyContent(bodyContent)}
</body>
</html>
`.trim();
Expand Down
38 changes: 26 additions & 12 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
href: string;
rel?: string;
type?: string;
sizes?: string;
title?: HTMLLinkElement['title'];
crossOrigin?: '' | 'anonymous' | 'use-credentials';
hreflang?: HTMLLinkElement['hreflang'];
Expand All @@ -36,20 +37,31 @@
isMobile?: boolean;
}

export interface RenderContent {
htmlAttributes: Record<string, string>;
meta: Meta[];
links: Link[];
export interface HeadContent {
scripts: Script[];
helpers: RenderHelpers;
links: Link[];
meta: Meta[];
styleSheets: Stylesheet[];
inlineScripts: string[];
inlineStyleSheets: string[];
bodyContent: {
className: string[];
beforeRoot: string[];
root?: string;
afterRoot: string[];
};
inlineScripts: string[];
title: string;
}

export interface BodyContent {
attributes: Attributes;
/** @deprecated use attributes.class instead */
className: string[];
ValeraS marked this conversation as resolved.
Show resolved Hide resolved
beforeRoot: string[];
root?: string;
afterRoot: string[];
}

export type OldBodyContent = Omit<BodyContent, 'attributes'>;

export interface RenderContent extends HeadContent {
htmlAttributes: Attributes;
bodyContent: BodyContent;
ValeraS marked this conversation as resolved.
Show resolved Hide resolved
}

export interface RenderHelpers {
Expand All @@ -59,13 +71,15 @@
renderInlineStyle(content: string): string;
renderMeta(meta: Meta): string;
renderLink(link: Link): string;
attrs(obj: Attributes): string;
}
export interface Plugin<Options = any, Name extends string = string> {

Check warning on line 76 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;
renderContent: RenderContent;
renderContent: Omit<RenderContent, 'bodyContent'> & {bodyContent: OldBodyContent};
commonOptions: CommonOptions;
/** @deprecated use `renderContent.helpers` instead */
utils: RenderHelpers;
}) => void;
}
Expand Down Expand Up @@ -98,7 +112,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 115 in src/types.ts

View workflow job for this annotation

GitHub Actions / Verify Files

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

Expand Down
1 change: 1 addition & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export function getRenderHelpers(params: {nonce?: string}): RenderHelpers {
renderInlineStyle,
renderMeta,
renderLink,
attrs,
};
}

Expand Down
Loading
Loading