forked from staylor/react-helmet-async
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
208 lines (184 loc) · 6.8 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import React from 'react';
import {
HELMET_ATTRIBUTE,
TAG_NAMES,
REACT_TAG_MAP,
TAG_PROPERTIES,
ATTRIBUTE_NAMES,
SEO_PRIORITY_TAGS,
} from './constants';
import { flattenArray, prioritizer } from './utils';
import type { MappedServerState } from './types';
const SELF_CLOSING_TAGS: string[] = [TAG_NAMES.NOSCRIPT, TAG_NAMES.SCRIPT, TAG_NAMES.STYLE];
const encodeSpecialCharacters = (str: string, encode = true) => {
if (encode === false) {
return String(str);
}
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
type Attributes = { [key: string]: string | number | boolean };
const generateElementAttributesAsString = (attributes: Attributes) =>
Object.keys(attributes).reduce((str, key) => {
const attr = typeof attributes[key] !== 'undefined' ? `${key}="${attributes[key]}"` : `${key}`;
return str ? `${str} ${attr}` : attr;
}, '');
const generateTitleAsString = (
type: string,
title: string,
attributes: Attributes,
encode: boolean
) => {
const attributeString = generateElementAttributesAsString(attributes);
const flattenedTitle = flattenArray(title);
return attributeString
? `<${type} ${HELMET_ATTRIBUTE}="true" ${attributeString}>${encodeSpecialCharacters(
flattenedTitle,
encode
)}</${type}>`
: `<${type} ${HELMET_ATTRIBUTE}="true">${encodeSpecialCharacters(
flattenedTitle,
encode
)}</${type}>`;
};
const generateTagsAsString = (type: string, tags: HTMLElement[], encode = true) =>
tags.reduce((str, t) => {
const tag = t as unknown as Attributes;
const attributeHtml = Object.keys(tag)
.filter(
attribute =>
!(attribute === TAG_PROPERTIES.INNER_HTML || attribute === TAG_PROPERTIES.CSS_TEXT)
)
.reduce((string, attribute) => {
const attr =
typeof tag[attribute] === 'undefined'
? attribute
: `${attribute}="${encodeSpecialCharacters(tag[attribute] as string, encode)}"`;
return string ? `${string} ${attr}` : attr;
}, '');
const tagContent = tag.innerHTML || tag.cssText || '';
const isSelfClosing = SELF_CLOSING_TAGS.indexOf(type) === -1;
return `${str}<${type} ${HELMET_ATTRIBUTE}="true" ${attributeHtml}${
isSelfClosing ? `/>` : `>${tagContent}</${type}>`
}`;
}, '');
const convertElementAttributesToReactProps = (attributes: Attributes, initProps = {}) =>
Object.keys(attributes).reduce((obj: Attributes, key: string) => {
const mapped = (REACT_TAG_MAP as Attributes)[key] as string;
obj[mapped || key] = attributes[key];
return obj;
}, initProps);
const generateTitleAsReactComponent = (_type: string, title: string, attributes: Attributes) => {
// assigning into an array to define toString function on it
const initProps = {
key: title,
[HELMET_ATTRIBUTE]: true,
};
const props = convertElementAttributesToReactProps(attributes, initProps);
return [React.createElement(TAG_NAMES.TITLE, props, title)];
};
const generateTagsAsReactComponent = (type: string, tags: any[]) =>
tags.map((tag, i) => {
const mappedTag: { [key: string]: any } = {
key: i,
[HELMET_ATTRIBUTE]: true,
};
Object.keys(tag).forEach(attribute => {
const mapped = (REACT_TAG_MAP as Attributes)[attribute] as string;
const mappedAttribute = mapped || attribute;
if (
mappedAttribute === TAG_PROPERTIES.INNER_HTML ||
mappedAttribute === TAG_PROPERTIES.CSS_TEXT
) {
const content = tag.innerHTML || tag.cssText;
mappedTag.dangerouslySetInnerHTML = { __html: content };
} else {
mappedTag[mappedAttribute] = tag[attribute];
}
});
return React.createElement(type, mappedTag);
});
const getMethodsForTag = (type: string, tags: any, encode = true) => {
switch (type) {
case TAG_NAMES.TITLE:
return {
toComponent: () => generateTitleAsReactComponent(type, tags.title, tags.titleAttributes),
toString: () => generateTitleAsString(type, tags.title, tags.titleAttributes, encode),
};
case ATTRIBUTE_NAMES.BODY:
case ATTRIBUTE_NAMES.HTML:
return {
toComponent: () => convertElementAttributesToReactProps(tags),
toString: () => generateElementAttributesAsString(tags),
};
default:
return {
toComponent: () => generateTagsAsReactComponent(type, tags),
toString: () => generateTagsAsString(type, tags, encode),
};
}
};
const getPriorityMethods = ({ metaTags, linkTags, scriptTags, encode }: MappedServerState) => {
const meta = prioritizer(metaTags, SEO_PRIORITY_TAGS.meta);
const link = prioritizer(linkTags, SEO_PRIORITY_TAGS.link);
const script = prioritizer(scriptTags, SEO_PRIORITY_TAGS.script);
// need to have toComponent() and toString()
const priorityMethods = {
toComponent: () => [
...generateTagsAsReactComponent(TAG_NAMES.META, meta.priority),
...generateTagsAsReactComponent(TAG_NAMES.LINK, link.priority),
...generateTagsAsReactComponent(TAG_NAMES.SCRIPT, script.priority),
],
toString: () =>
// generate all the tags as strings and concatenate them
`${getMethodsForTag(TAG_NAMES.META, meta.priority, encode)} ${getMethodsForTag(
TAG_NAMES.LINK,
link.priority,
encode
)} ${getMethodsForTag(TAG_NAMES.SCRIPT, script.priority, encode)}`,
};
return {
priorityMethods,
metaTags: meta.default as HTMLMetaElement[],
linkTags: link.default as HTMLLinkElement[],
scriptTags: script.default as HTMLScriptElement[],
};
};
const mapStateOnServer = (props: MappedServerState) => {
const {
baseTag,
bodyAttributes,
encode = true,
htmlAttributes,
noscriptTags,
styleTags,
title = '',
titleAttributes,
prioritizeSeoTags,
} = props;
let { linkTags, metaTags, scriptTags } = props;
let priorityMethods = {
toComponent: () => {},
toString: () => '',
};
if (prioritizeSeoTags) {
({ priorityMethods, linkTags, metaTags, scriptTags } = getPriorityMethods(props));
}
return {
priority: priorityMethods,
base: getMethodsForTag(TAG_NAMES.BASE, baseTag, encode),
bodyAttributes: getMethodsForTag(ATTRIBUTE_NAMES.BODY, bodyAttributes as Attributes, encode),
htmlAttributes: getMethodsForTag(ATTRIBUTE_NAMES.HTML, htmlAttributes as Attributes, encode),
link: getMethodsForTag(TAG_NAMES.LINK, linkTags, encode),
meta: getMethodsForTag(TAG_NAMES.META, metaTags, encode),
noscript: getMethodsForTag(TAG_NAMES.NOSCRIPT, noscriptTags, encode),
script: getMethodsForTag(TAG_NAMES.SCRIPT, scriptTags, encode),
style: getMethodsForTag(TAG_NAMES.STYLE, styleTags, encode),
title: getMethodsForTag(TAG_NAMES.TITLE, { title, titleAttributes }, encode),
};
};
export default mapStateOnServer;