/
index.ts
225 lines (195 loc) · 5.63 KB
/
index.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { URL } from "frontity";
import {
HeadTags,
HeadTag,
State,
PostTypeWithHeadTags,
TaxonomyWithHeadTags
} from "../../types";
// Return a string inviting to ask questions in the community.
const msg = (text: string) => `${text}
If you have any questions, join our community at https://community.frontity.org/.
`;
// Attributes that could contain links.
const possibleLink = ["href", "content"];
const deepTransform = (obj: object, func: Function, ...args: object[]) => {
for (const key in obj) {
if (typeof obj[key] === "string") {
obj[key] = func(obj[key], ...args);
} else if (typeof obj[key] === "object") {
deepTransform(obj[key], func, ...args);
}
}
};
const getWpUrl = (api: string, isWpCom: boolean): URL => {
const apiUrl = new URL(api);
if (isWpCom) {
const { pathname } = apiUrl;
return new URL(pathname.replace(/^\/wp\/v2\/sites\//, "https://"));
}
// Get API subdirectory.
const apiSubdir = apiUrl.pathname.replace(/\/wp-json\/?$/, "/");
return new URL(apiSubdir, apiUrl);
};
const shouldTransform = (value: string, prefix: string, ignore: string) => {
return (
value.startsWith(prefix) &&
!new RegExp(ignore).test(value.replace(prefix, ""))
);
};
const getNewLink = (value: string, base: string, newBase: string) => {
const { pathname, search, hash } = new URL(value);
const finalPathname = pathname.replace(
new RegExp(`^${new URL(base).pathname}`),
"/"
);
return `${newBase.replace(/\/?$/, "")}${finalPathname}${search}${hash}`;
};
const getPrefixFromSource = ({ state }: { state: State }): string => {
const { api, isWpCom } = state.source;
return getWpUrl(api, isWpCom).href;
};
const transformLink = ({
value,
ignore,
base,
newBase
}: {
value: string;
ignore: string;
base: string;
newBase: string;
}) => {
if (shouldTransform(value, base, ignore))
return getNewLink(value, base, newBase);
return value;
};
export const useFrontityLinks = ({
state,
headTags
}: {
state: State;
headTags: HeadTags;
}) => {
/**
* At this point we assume that `state.headTags.transformLinks` and
* `state.frontity.url` are defined.
*/
if (!state.headTags.transformLinks || !state.frontity.url) return headTags;
// prefix of links to change.
const base =
state.headTags.transformLinks.base || getPrefixFromSource({ state });
const ignore = state.headTags.transformLinks.ignore;
// The site URL.
const newBase = state.frontity.url;
// For each head tag...
return headTags.map(({ tag, attributes, content }) => {
// Init processed head tag.
const processed: HeadTag = { tag };
if (content) {
// Set initial content value.
processed.content = content;
// Transform URLs inside JSON content.
if (
attributes &&
attributes.type &&
attributes.type.endsWith("ld+json")
) {
// Try to parse the tag content.
let json: object;
try {
json = JSON.parse(content);
} catch (e) {
console.warn(
msg(
`The following content of a <script type="ld+json"> tag is not a valid JSON. Links in that tag will not be changed.
${content}`
)
);
}
// Iterate over json props.
if (json) {
deepTransform(json, (value: string) => {
return transformLink({ value, ignore, base, newBase });
});
// Stringify json again.
processed.content = JSON.stringify(json);
}
}
}
// Process Attributes.
if (attributes) {
processed.attributes = Object.entries(attributes)
.map(([key, value]) => {
// Change value if it's a WP blog link.
if (possibleLink.includes(key)) {
value = transformLink({ value, ignore, base, newBase });
}
// Return the entry.
return [key, value];
})
.reduce((result, [key, value]) => {
result[key] = value;
return result;
}, {});
}
// Return processed head tag.
return processed;
});
};
// Get the entity related to the current link.
export const getCurrentEntity = ({
state,
link
}: {
state: State;
link: string;
}) => {
const data = state.source.get(link);
if (data.isPostType) {
const { type, id } = data;
return state.source[type][id] as PostTypeWithHeadTags;
}
if (data.isTaxonomy) {
const { taxonomy, id } = data;
return state.source[taxonomy][id] as TaxonomyWithHeadTags;
}
if (data.isAuthor) {
const { id } = data;
return state.source.author[id];
}
if (data.isPostTypeArchive) {
const { type } = data;
return state.source.type[type];
}
return null;
};
/**
* Get the head tags stored in the current entity,
* or an empty array if there is no entity or head tags.
*/
export const getCurrentHeadTags = ({
state,
link
}: {
state: State;
link: string;
}) => {
const entity = getCurrentEntity({ state, link });
const headTags = entity && entity.head_tags;
// Return an empty array if there is no entity or head tags.
if (!headTags) return [];
// Leave head tags unchanged if `transform` is set to false.
if (!state.headTags.transformLinks) return headTags;
// Do not change links if `state.frontity.url` is not defined.
if (!state.frontity || !state.frontity.url) {
console.warn(
msg(
"Property `state.headTags.links.transform` is defined but `state.frontity.url` is not. All links in <head> tags pointing to other site (e.g. WordPress) instead to the Frontity site won't be changed."
)
);
return headTags;
}
// Transform links.
return useFrontityLinks({ state, headTags });
};