@forgewp/compiler 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +4 -0
- package/bin/sync-hooks.js +221 -0
- package/lib/blueprints.js +12 -1456
- package/lib/functions-builder.js +244 -1
- package/lib/generate-theme.js +121 -0
- package/lib/hydration-scanner.js +147 -0
- package/lib/markup-processor.js +5 -0
- package/lib/render-theme.mts +19 -2
- package/package.json +3 -2
- package/templates/PresetsStyle.tsx +74 -0
- package/templates/SEO.tsx +109 -0
- package/templates/forgewp-config.ts +43 -0
- package/templates/menus.json +11 -0
- package/templates/mock-data.json +434 -0
- package/templates/wordpress.tsx +1297 -0
|
@@ -0,0 +1,1297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ForgeWP WordPress Data Hooks
|
|
3
|
+
*
|
|
4
|
+
* These hooks provide mock data during local development (Vite dev server).
|
|
5
|
+
* When the theme is exported, the ForgeWP compiler replaces every token
|
|
6
|
+
* with the equivalent WordPress PHP function call.
|
|
7
|
+
*/
|
|
8
|
+
import React from 'react';
|
|
9
|
+
import { Link as WouterLink, useLocation as useWouterLocation, useSearch as useWouterSearch } from 'wouter';
|
|
10
|
+
|
|
11
|
+
// @ts-ignore
|
|
12
|
+
import mockData from '../../cms/mock-data.json';
|
|
13
|
+
// @ts-ignore
|
|
14
|
+
import menusData from '../../cms/menus.json';
|
|
15
|
+
// @ts-ignore
|
|
16
|
+
import siteSettings from '../../cms/site-settings.json';
|
|
17
|
+
// @ts-ignore
|
|
18
|
+
import translationsData from '../../cms/translations.json';
|
|
19
|
+
|
|
20
|
+
import {
|
|
21
|
+
WpQueryLoop as _WpQueryLoop,
|
|
22
|
+
WpMenu as _WpMenu,
|
|
23
|
+
WpShortcode as _WpShortcode,
|
|
24
|
+
useWpTitle as _useWpTitle,
|
|
25
|
+
useWpContent as _useWpContent,
|
|
26
|
+
useWpExcerpt as _useWpExcerpt,
|
|
27
|
+
useWpPermalink as _useWpPermalink,
|
|
28
|
+
useWpDate as _useWpDate,
|
|
29
|
+
useWpModifiedDate as _useWpModifiedDate,
|
|
30
|
+
useWpAuthor as _useWpAuthor,
|
|
31
|
+
useWpFeaturedImage as _useWpFeaturedImage,
|
|
32
|
+
useWpCustomField as _useWpCustomField,
|
|
33
|
+
useWpField as _useWpField,
|
|
34
|
+
useWpOption as _useWpOption,
|
|
35
|
+
useWpThemeMod as _useWpThemeMod,
|
|
36
|
+
useWpThemeUri as _useWpThemeUri,
|
|
37
|
+
useWpQuery as _useWpQuery,
|
|
38
|
+
useWpPrefetch as _useWpPrefetch,
|
|
39
|
+
WpHead as _WpHead,
|
|
40
|
+
WpImage as _WpImage,
|
|
41
|
+
WpPostContext,
|
|
42
|
+
useWpMeta as _useWpMeta,
|
|
43
|
+
useWpPageLink as _useWpPageLink,
|
|
44
|
+
useWpMenu as _useWpMenu,
|
|
45
|
+
BlockArea as _BlockArea,
|
|
46
|
+
defineEditable,
|
|
47
|
+
text,
|
|
48
|
+
richText,
|
|
49
|
+
image,
|
|
50
|
+
boolean,
|
|
51
|
+
repeater,
|
|
52
|
+
WpRepeater,
|
|
53
|
+
WpIcon,
|
|
54
|
+
} from '@forgewp/react';
|
|
55
|
+
|
|
56
|
+
export { WpPostContext, defineEditable, text, richText, image, boolean, repeater, WpRepeater, WpIcon };
|
|
57
|
+
|
|
58
|
+
import type {
|
|
59
|
+
WpQueryLoopProps,
|
|
60
|
+
WpMenuProps,
|
|
61
|
+
WpMenuItem,
|
|
62
|
+
WpHeadProps,
|
|
63
|
+
WpImageProps,
|
|
64
|
+
WpAttachment,
|
|
65
|
+
WpQueryArgs,
|
|
66
|
+
WpQueryResults,
|
|
67
|
+
WpPost,
|
|
68
|
+
WpShortcodeProps,
|
|
69
|
+
BlockAreaProps,
|
|
70
|
+
WpRepeaterProps,
|
|
71
|
+
WpIconProps,
|
|
72
|
+
} from '@forgewp/react';
|
|
73
|
+
|
|
74
|
+
const IS_DEV =
|
|
75
|
+
typeof import.meta !== 'undefined' &&
|
|
76
|
+
// @ts-ignore
|
|
77
|
+
import.meta.env?.DEV === true;
|
|
78
|
+
|
|
79
|
+
export function decodeHtmlEntities(str: string): string {
|
|
80
|
+
if (!str) return '';
|
|
81
|
+
if (typeof window === 'undefined') {
|
|
82
|
+
return str
|
|
83
|
+
.replace(/&/g, '&')
|
|
84
|
+
.replace(/</g, '<')
|
|
85
|
+
.replace(/>/g, '>')
|
|
86
|
+
.replace(/"/g, '"')
|
|
87
|
+
.replace(/'/g, "'")
|
|
88
|
+
.replace(/'/g, "'");
|
|
89
|
+
}
|
|
90
|
+
const txt = document.createElement('textarea');
|
|
91
|
+
txt.innerHTML = str;
|
|
92
|
+
return txt.value;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (IS_DEV) {
|
|
96
|
+
if (typeof window !== 'undefined') {
|
|
97
|
+
(window as any)._forgeWpMockSiteSettings = siteSettings;
|
|
98
|
+
(window as any)._forgeWpMockPosts = mockData;
|
|
99
|
+
(window as any)._forgeWpMockMenus = menusData;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ── Re-export pure hooks with compiler token fallbacks ────────────────────────
|
|
104
|
+
// In dev: @forgewp/react hook returns the mock value from WpPostContext.
|
|
105
|
+
// In prod: compiler replaces the call with the PHP equivalent below.
|
|
106
|
+
|
|
107
|
+
export function useWpTitle(): string {
|
|
108
|
+
if (IS_DEV) return _useWpTitle();
|
|
109
|
+
return '__FORGEWP_THE_TITLE__';
|
|
110
|
+
}
|
|
111
|
+
export function useWpContent(): string {
|
|
112
|
+
if (IS_DEV) return _useWpContent();
|
|
113
|
+
return '__FORGEWP_THE_CONTENT__';
|
|
114
|
+
}
|
|
115
|
+
export function useWpExcerpt(): string {
|
|
116
|
+
if (IS_DEV) return _useWpExcerpt();
|
|
117
|
+
return '__FORGEWP_THE_EXCERPT__';
|
|
118
|
+
}
|
|
119
|
+
export function useWpPermalink(): string {
|
|
120
|
+
if (IS_DEV) return _useWpPermalink();
|
|
121
|
+
return '__FORGEWP_THE_PERMALINK__';
|
|
122
|
+
}
|
|
123
|
+
export function useWpDate(): string {
|
|
124
|
+
if (IS_DEV) return _useWpDate();
|
|
125
|
+
return '__FORGEWP_THE_DATE__';
|
|
126
|
+
}
|
|
127
|
+
export function useWpModifiedDate(): string {
|
|
128
|
+
if (IS_DEV) return _useWpModifiedDate();
|
|
129
|
+
return '__FORGEWP_THE_MODIFIED_DATE__';
|
|
130
|
+
}
|
|
131
|
+
export function useWpAuthor(): string {
|
|
132
|
+
if (IS_DEV) return _useWpAuthor();
|
|
133
|
+
return '__FORGEWP_THE_AUTHOR__';
|
|
134
|
+
}
|
|
135
|
+
export function useWpFeaturedImage(): string {
|
|
136
|
+
if (IS_DEV) return _useWpFeaturedImage();
|
|
137
|
+
return '__FORGEWP_THE_POST_THUMBNAIL_URL__';
|
|
138
|
+
}
|
|
139
|
+
export function useWpCustomField(fieldName: string, defaultValue = ''): any {
|
|
140
|
+
if (IS_DEV) return _useWpCustomField(fieldName, defaultValue);
|
|
141
|
+
|
|
142
|
+
if (typeof window !== 'undefined') {
|
|
143
|
+
const win = window as any;
|
|
144
|
+
if (!win._forgeWpCompileTime) {
|
|
145
|
+
const post = React.useContext(WpPostContext);
|
|
146
|
+
const currentPost = post || win.forgeWpHydration?.post;
|
|
147
|
+
if (currentPost?.customFields && typeof currentPost.customFields[fieldName] !== 'undefined') {
|
|
148
|
+
return currentPost.customFields[fieldName];
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return '__FORGEWP_CUSTOM_FIELD__' + fieldName + '__';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function useWpField(fieldName: string, defaultValue = ''): any {
|
|
157
|
+
if (IS_DEV) return _useWpField(fieldName, defaultValue);
|
|
158
|
+
|
|
159
|
+
if (typeof window !== 'undefined') {
|
|
160
|
+
const win = window as any;
|
|
161
|
+
if (!win._forgeWpCompileTime) {
|
|
162
|
+
const post = React.useContext(WpPostContext);
|
|
163
|
+
const currentPost = post || win.forgeWpHydration?.post;
|
|
164
|
+
if (currentPost?.customFields && typeof currentPost.customFields[fieldName] !== 'undefined') {
|
|
165
|
+
return currentPost.customFields[fieldName];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return '__FORGEWP_CUSTOM_FIELD__' + fieldName + '__';
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function useWpMeta<T>(key: string, defaultValue: T): T {
|
|
174
|
+
if (IS_DEV) return _useWpMeta(key, defaultValue);
|
|
175
|
+
|
|
176
|
+
// Browser-side hydration: check for forgeWpHydration data first
|
|
177
|
+
if (typeof window !== 'undefined') {
|
|
178
|
+
const win = window as any;
|
|
179
|
+
if (win._forgeWpCompileTime) {
|
|
180
|
+
if (typeof defaultValue === 'string') {
|
|
181
|
+
return `__FORGEWP_META_${key}_DEFAULT_${encodeURIComponent(defaultValue).replace(/_/g, '%5F')}__` as any as T;
|
|
182
|
+
}
|
|
183
|
+
return defaultValue;
|
|
184
|
+
}
|
|
185
|
+
const post = React.useContext(WpPostContext);
|
|
186
|
+
const currentPost = post || win.forgeWpHydration?.post;
|
|
187
|
+
if (currentPost?.customFields && typeof currentPost.customFields[key] !== 'undefined') {
|
|
188
|
+
return currentPost.customFields[key] as T;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Fallback to token for compiler replacement
|
|
193
|
+
const defaultStr = typeof defaultValue === 'string' ? defaultValue : JSON.stringify(defaultValue);
|
|
194
|
+
return `__FORGEWP_META_${key}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__` as any as T;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function useWpOption(optionName: string, defaultValue = ''): string {
|
|
198
|
+
if (IS_DEV) return _useWpOption(optionName, defaultValue);
|
|
199
|
+
|
|
200
|
+
// Browser-side hydration: check for forgeWpHydration data first
|
|
201
|
+
if (typeof window !== 'undefined') {
|
|
202
|
+
const win = window as any;
|
|
203
|
+
const siteSettings =
|
|
204
|
+
win._forgeWpMockSiteSettings || win.forgeWpHydration?.siteSettings;
|
|
205
|
+
if (siteSettings?.options?.[optionName] !== undefined) {
|
|
206
|
+
const value = siteSettings.options[optionName];
|
|
207
|
+
// Handle false/null values from WordPress
|
|
208
|
+
if (value === false || value === null) {
|
|
209
|
+
return defaultValue || `[option: ${optionName}]`;
|
|
210
|
+
}
|
|
211
|
+
return String(value);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Fallback to token for compiler replacement
|
|
216
|
+
return defaultValue
|
|
217
|
+
? `__FORGEWP_OPTION_${optionName}_DEFAULT_${encodeURIComponent(defaultValue)}__`
|
|
218
|
+
: `__FORGEWP_OPTION_${optionName}__`;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function useWpThemeMod(modName: string, defaultValue = ''): string {
|
|
222
|
+
if (IS_DEV) return _useWpThemeMod(modName, defaultValue);
|
|
223
|
+
|
|
224
|
+
// Browser-side hydration: check for forgeWpHydration data first
|
|
225
|
+
if (typeof window !== 'undefined') {
|
|
226
|
+
const win = window as any;
|
|
227
|
+
const siteSettings =
|
|
228
|
+
win._forgeWpMockSiteSettings || win.forgeWpHydration?.siteSettings;
|
|
229
|
+
if (siteSettings?.theme_mods?.[modName] !== undefined) {
|
|
230
|
+
const value = siteSettings.theme_mods[modName];
|
|
231
|
+
// Handle false/null values from WordPress
|
|
232
|
+
if (value === false || value === null) {
|
|
233
|
+
return defaultValue || `[theme_mod: ${modName}]`;
|
|
234
|
+
}
|
|
235
|
+
return String(value);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Fallback to token for compiler replacement
|
|
240
|
+
return defaultValue
|
|
241
|
+
? `__FORGEWP_THEME_MOD_${modName}_DEFAULT_${encodeURIComponent(defaultValue)}__`
|
|
242
|
+
: `__FORGEWP_THEME_MOD_${modName}__`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function useWpThemeUri(): string {
|
|
246
|
+
if (IS_DEV) return _useWpThemeUri();
|
|
247
|
+
if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
|
|
248
|
+
return (window as any).forgeWpHydration?.themeUri || '';
|
|
249
|
+
}
|
|
250
|
+
return '__FORGEWP_THEME_URI__';
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function useWpPageLink(name: string, fallback: string): string {
|
|
254
|
+
if (IS_DEV) return _useWpPageLink(name, fallback);
|
|
255
|
+
if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
|
|
256
|
+
const win = window as any;
|
|
257
|
+
if (win.forgeWpHydration?.pageLinks?.[name]) {
|
|
258
|
+
return win.forgeWpHydration.pageLinks[name];
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return fallback
|
|
262
|
+
? `__FORGEWP_PAGELINK_${name}_DEFAULT_${encodeURIComponent(fallback)}__`
|
|
263
|
+
: `__FORGEWP_PAGELINK_${name}__`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function useWpPagePath(name: string, fallback: string): string {
|
|
267
|
+
const href = useWpPageLink(name, fallback);
|
|
268
|
+
return React.useMemo(() => {
|
|
269
|
+
try {
|
|
270
|
+
return new URL(href, typeof window !== 'undefined' ? window.location.origin : 'http://localhost').pathname;
|
|
271
|
+
} catch (e) {
|
|
272
|
+
return href;
|
|
273
|
+
}
|
|
274
|
+
}, [href]);
|
|
275
|
+
}
|
|
276
|
+
const queryCache = new Map<string, { posts: any[]; total: number; hasMore: boolean; totalPages?: number }>();
|
|
277
|
+
|
|
278
|
+
const activeQueries = new Set<{
|
|
279
|
+
args: any;
|
|
280
|
+
querySelector: (params: URLSearchParams) => any;
|
|
281
|
+
execute: (targetArgs: any) => Promise<any>;
|
|
282
|
+
}>();
|
|
283
|
+
|
|
284
|
+
let prefetchTimeout: any = null;
|
|
285
|
+
|
|
286
|
+
async function fetchWpApi(args: any, page: number) {
|
|
287
|
+
const {
|
|
288
|
+
postType = 'post',
|
|
289
|
+
postsPerPage = 10,
|
|
290
|
+
categoryName = '',
|
|
291
|
+
s = '',
|
|
292
|
+
orderby = 'date',
|
|
293
|
+
order = 'DESC',
|
|
294
|
+
} = args;
|
|
295
|
+
|
|
296
|
+
const endpoint =
|
|
297
|
+
postType === 'post'
|
|
298
|
+
? 'posts'
|
|
299
|
+
: postType === 'page'
|
|
300
|
+
? 'pages'
|
|
301
|
+
: postType;
|
|
302
|
+
const params = new URLSearchParams();
|
|
303
|
+
params.append('per_page', String(postsPerPage));
|
|
304
|
+
params.append('page', String(page));
|
|
305
|
+
params.append('_embed', '1');
|
|
306
|
+
if (s) {
|
|
307
|
+
params.append('search', s);
|
|
308
|
+
}
|
|
309
|
+
if (orderby) {
|
|
310
|
+
params.append('orderby', orderby === 'date' ? 'date' : orderby);
|
|
311
|
+
}
|
|
312
|
+
if (order) {
|
|
313
|
+
params.append('order', order.toLowerCase());
|
|
314
|
+
}
|
|
315
|
+
if (categoryName) {
|
|
316
|
+
params.append('category_name', categoryName);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// Polylang multi-language query support
|
|
320
|
+
const currentLang = (window as any).forgeWpLocale || (window as any).forgeWpTranslations?.currentLanguage;
|
|
321
|
+
if (currentLang) {
|
|
322
|
+
params.append('lang', currentLang);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const homeUrl = (window as any).forgeWpHydration?.siteSettings?.options?.home || '';
|
|
326
|
+
let apiBase = '';
|
|
327
|
+
if (homeUrl) {
|
|
328
|
+
try {
|
|
329
|
+
apiBase = new URL(homeUrl).pathname.replace(new RegExp('/$'), '');
|
|
330
|
+
} catch (e) {}
|
|
331
|
+
}
|
|
332
|
+
const fetchUrl = `${apiBase}/wp-json/wp/v2/${endpoint}?${params.toString()}`;
|
|
333
|
+
console.log(`[useWpQuery] Fetching CPT "${postType}" from URL:`, fetchUrl);
|
|
334
|
+
const response = await fetch(fetchUrl);
|
|
335
|
+
if (!response.ok) {
|
|
336
|
+
throw new Error(
|
|
337
|
+
`WordPress API returned ${response.status}: ${response.statusText}`,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const data = await response.json();
|
|
342
|
+
if (!Array.isArray(data)) {
|
|
343
|
+
throw new Error('Invalid response format from WordPress API');
|
|
344
|
+
}
|
|
345
|
+
console.log(`[useWpQuery] Successfully loaded ${data.length} items for CPT "${postType}"`);
|
|
346
|
+
|
|
347
|
+
const cleanHtml = (html: string) => {
|
|
348
|
+
if (!html) return '';
|
|
349
|
+
return decodeHtmlEntities(html.replace(/<\/?[^>]+(>|$)/g, '')).trim();
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
const mappedPosts: WpPost[] = data.map((wp: any) => {
|
|
353
|
+
let featuredImage = 'https://picsum.photos/seed/forgewp/1200/630';
|
|
354
|
+
if (
|
|
355
|
+
wp._embedded &&
|
|
356
|
+
wp._embedded['wp:featuredmedia'] &&
|
|
357
|
+
wp._embedded['wp:featuredmedia'][0]
|
|
358
|
+
) {
|
|
359
|
+
const media = wp._embedded['wp:featuredmedia'][0];
|
|
360
|
+
featuredImage = media.source_url || featuredImage;
|
|
361
|
+
} else if (wp.featured_media_src_url) {
|
|
362
|
+
featuredImage = wp.featured_media_src_url;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const _terms: Record<string, any[]> = {};
|
|
366
|
+
if (wp._embedded && wp._embedded['wp:term']) {
|
|
367
|
+
for (const termGroup of wp._embedded['wp:term']) {
|
|
368
|
+
if (Array.isArray(termGroup) && termGroup.length > 0) {
|
|
369
|
+
const taxonomy = termGroup[0].taxonomy;
|
|
370
|
+
if (taxonomy) {
|
|
371
|
+
_terms[taxonomy] = termGroup.map((t: any) => ({
|
|
372
|
+
id: t.id,
|
|
373
|
+
slug: t.slug,
|
|
374
|
+
name: typeof t.name === 'string' ? decodeHtmlEntities(t.name) : '',
|
|
375
|
+
}));
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return {
|
|
382
|
+
id: wp.id,
|
|
383
|
+
title:
|
|
384
|
+
typeof wp.title === 'object' ? decodeHtmlEntities(wp.title.rendered) : decodeHtmlEntities(wp.title || ''),
|
|
385
|
+
excerpt:
|
|
386
|
+
typeof wp.excerpt === 'object'
|
|
387
|
+
? cleanHtml(wp.excerpt.rendered)
|
|
388
|
+
: cleanHtml(wp.excerpt || ''),
|
|
389
|
+
content:
|
|
390
|
+
typeof wp.content === 'object'
|
|
391
|
+
? wp.content.rendered
|
|
392
|
+
: wp.content || '',
|
|
393
|
+
date: wp.date
|
|
394
|
+
? new Date(wp.date).toLocaleDateString(currentLang === 'de' ? 'de-DE' : 'en-US', {
|
|
395
|
+
year: 'numeric',
|
|
396
|
+
month: 'long',
|
|
397
|
+
day: 'numeric',
|
|
398
|
+
})
|
|
399
|
+
: '',
|
|
400
|
+
modified: wp.modified
|
|
401
|
+
? new Date(wp.modified).toLocaleDateString(currentLang === 'de' ? 'de-DE' : 'en-US', {
|
|
402
|
+
year: 'numeric',
|
|
403
|
+
month: 'long',
|
|
404
|
+
day: 'numeric',
|
|
405
|
+
})
|
|
406
|
+
: '',
|
|
407
|
+
author:
|
|
408
|
+
wp._embedded &&
|
|
409
|
+
wp._embedded['author'] &&
|
|
410
|
+
wp._embedded['author'][0]
|
|
411
|
+
? wp._embedded['author'][0].name
|
|
412
|
+
: 'Admin',
|
|
413
|
+
featuredImage,
|
|
414
|
+
permalink: wp.link,
|
|
415
|
+
customFields: { ...(wp.acf || {}), ...(wp.meta || {}) },
|
|
416
|
+
_terms,
|
|
417
|
+
__postType: wp.type || postType,
|
|
418
|
+
};
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
const totalPagesHeader = response.headers.get('X-WP-TotalPages');
|
|
422
|
+
const totalPages = totalPagesHeader
|
|
423
|
+
? parseInt(totalPagesHeader, 10)
|
|
424
|
+
: 1;
|
|
425
|
+
|
|
426
|
+
const totalHeader = response.headers.get('X-WP-Total');
|
|
427
|
+
const total = totalHeader
|
|
428
|
+
? parseInt(totalHeader, 10)
|
|
429
|
+
: mappedPosts.length;
|
|
430
|
+
|
|
431
|
+
return {
|
|
432
|
+
posts: mappedPosts,
|
|
433
|
+
hasMore: page < totalPages && mappedPosts.length > 0,
|
|
434
|
+
total,
|
|
435
|
+
totalPages,
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
440
|
+
if (IS_DEV) {
|
|
441
|
+
return _useWpQuery(args);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Node SSR (Compile-time)
|
|
445
|
+
if (typeof window === 'undefined' || (typeof window !== 'undefined' && (window as any)._forgeWpCompileTime)) {
|
|
446
|
+
// In production WordPress themes, dynamic hydration islands should SSR in a loading state
|
|
447
|
+
// so that the initial page layout contains loading skeletons instead of developer's compile-time mock data.
|
|
448
|
+
return {
|
|
449
|
+
posts: [],
|
|
450
|
+
loading: true,
|
|
451
|
+
error: null,
|
|
452
|
+
hasMore: true,
|
|
453
|
+
totalPages: 1,
|
|
454
|
+
currentPage: 1,
|
|
455
|
+
loadMore: async () => {},
|
|
456
|
+
goToPage: (_n: number) => {},
|
|
457
|
+
refetch: async () => {},
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Browser (Hydration/Production Client)
|
|
462
|
+
const {
|
|
463
|
+
postType = 'post',
|
|
464
|
+
postsPerPage = 10,
|
|
465
|
+
categoryName = '',
|
|
466
|
+
s = '',
|
|
467
|
+
paged = 1,
|
|
468
|
+
orderby = 'date',
|
|
469
|
+
order = 'DESC',
|
|
470
|
+
} = args;
|
|
471
|
+
|
|
472
|
+
const queryKey = JSON.stringify({
|
|
473
|
+
postType,
|
|
474
|
+
postsPerPage,
|
|
475
|
+
categoryName,
|
|
476
|
+
s,
|
|
477
|
+
paged,
|
|
478
|
+
orderby,
|
|
479
|
+
order,
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
let initialState = null;
|
|
483
|
+
if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
|
|
484
|
+
const stateEl = document.getElementById('forgewp-initial-state');
|
|
485
|
+
if (stateEl) {
|
|
486
|
+
try {
|
|
487
|
+
const parsed = JSON.parse(stateEl.textContent || '{}');
|
|
488
|
+
if (parsed.queries && parsed.queries[queryKey]) {
|
|
489
|
+
initialState = parsed.queries[queryKey];
|
|
490
|
+
// Pre-populate queryCache for page 1
|
|
491
|
+
const cacheKey = JSON.stringify({ ...args, paged: paged });
|
|
492
|
+
if (!queryCache.has(cacheKey)) {
|
|
493
|
+
queryCache.set(cacheKey, {
|
|
494
|
+
posts: initialState.posts,
|
|
495
|
+
hasMore: initialState.hasMore,
|
|
496
|
+
total: initialState.total || initialState.posts.length
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
} catch (e) {
|
|
501
|
+
console.warn('Failed to parse forgewp-initial-state:', e);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
const [posts, setPosts] = React.useState<WpPost[]>(initialState ? initialState.posts : []);
|
|
507
|
+
const [loading, setLoading] = React.useState(initialState ? false : true);
|
|
508
|
+
const [error, setError] = React.useState<string | null>(null);
|
|
509
|
+
const [currentPage, setCurrentPage] = React.useState(paged);
|
|
510
|
+
const [hasMore, setHasMore] = React.useState(initialState ? initialState.hasMore : true);
|
|
511
|
+
const [totalPages, setTotalPages] = React.useState<number>(1);
|
|
512
|
+
const hydratedFromSsrRef = React.useRef(initialState ? true : false);
|
|
513
|
+
// 'append' = loadMore behaviour; 'replace' = goToPage behaviour
|
|
514
|
+
const pageModeRef = React.useRef<'append' | 'replace'>('replace');
|
|
515
|
+
|
|
516
|
+
const [prevQueryKey, setPrevQueryKey] = React.useState(queryKey);
|
|
517
|
+
if (prevQueryKey !== queryKey) {
|
|
518
|
+
setPrevQueryKey(queryKey);
|
|
519
|
+
setCurrentPage(1);
|
|
520
|
+
setPosts([]);
|
|
521
|
+
setHasMore(true);
|
|
522
|
+
pageModeRef.current = 'replace';
|
|
523
|
+
hydratedFromSsrRef.current = false;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const executeProdQuery = React.useCallback(
|
|
527
|
+
async (page: number) => {
|
|
528
|
+
const mode = pageModeRef.current;
|
|
529
|
+
// Consume the mode; subsequent calls revert to append (for loadMore)
|
|
530
|
+
pageModeRef.current = 'append';
|
|
531
|
+
|
|
532
|
+
const cacheKey = JSON.stringify({ ...args, paged: page });
|
|
533
|
+
if (queryCache.has(cacheKey)) {
|
|
534
|
+
const cached = queryCache.get(cacheKey)!;
|
|
535
|
+
setPosts((prev: WpPost[]) => {
|
|
536
|
+
if (mode === 'append') {
|
|
537
|
+
const existingIds = new Set(prev.map((p: WpPost) => p.id));
|
|
538
|
+
const newPosts = cached.posts.filter((p: WpPost) => !existingIds.has(p.id));
|
|
539
|
+
return [...prev, ...newPosts];
|
|
540
|
+
}
|
|
541
|
+
return cached.posts;
|
|
542
|
+
});
|
|
543
|
+
setHasMore(cached.hasMore);
|
|
544
|
+
if ((cached as any).totalPages) setTotalPages((cached as any).totalPages);
|
|
545
|
+
setError(null);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
setLoading(true);
|
|
550
|
+
try {
|
|
551
|
+
const { posts: fetchedPosts, hasMore: nextPageHasMore, total: totalCount, totalPages: tp } = await fetchWpApi(args, page);
|
|
552
|
+
queryCache.set(cacheKey, { posts: fetchedPosts, hasMore: nextPageHasMore, total: totalCount, totalPages: tp });
|
|
553
|
+
|
|
554
|
+
setPosts((prev: WpPost[]) => {
|
|
555
|
+
if (mode === 'append') {
|
|
556
|
+
const existingIds = new Set(prev.map((p: WpPost) => p.id));
|
|
557
|
+
const newPosts = fetchedPosts.filter((p: WpPost) => !existingIds.has(p.id));
|
|
558
|
+
return [...prev, ...newPosts];
|
|
559
|
+
}
|
|
560
|
+
return fetchedPosts;
|
|
561
|
+
});
|
|
562
|
+
setHasMore(nextPageHasMore);
|
|
563
|
+
setTotalPages(tp);
|
|
564
|
+
setError(null);
|
|
565
|
+
} catch (err: any) {
|
|
566
|
+
setError(err.message || 'Failed to fetch from WordPress API');
|
|
567
|
+
} finally {
|
|
568
|
+
setLoading(false);
|
|
569
|
+
}
|
|
570
|
+
},
|
|
571
|
+
[queryKey, args],
|
|
572
|
+
);
|
|
573
|
+
|
|
574
|
+
React.useEffect(() => {
|
|
575
|
+
if (hydratedFromSsrRef.current) {
|
|
576
|
+
hydratedFromSsrRef.current = false;
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
executeProdQuery(currentPage);
|
|
580
|
+
}, [executeProdQuery, currentPage]);
|
|
581
|
+
|
|
582
|
+
const querySelector = React.useCallback((params: URLSearchParams) => {
|
|
583
|
+
const target = { ...args };
|
|
584
|
+
if (params.has('q') || params.has('s')) {
|
|
585
|
+
target.s = params.get('q') || params.get('s') || '';
|
|
586
|
+
}
|
|
587
|
+
if (params.has('category')) {
|
|
588
|
+
target.categoryName = params.get('category') || '';
|
|
589
|
+
}
|
|
590
|
+
return target;
|
|
591
|
+
}, [args]);
|
|
592
|
+
|
|
593
|
+
React.useEffect(() => {
|
|
594
|
+
if (typeof window === 'undefined') return;
|
|
595
|
+
const item = {
|
|
596
|
+
args,
|
|
597
|
+
querySelector,
|
|
598
|
+
execute: async (targetArgs: any) => {
|
|
599
|
+
const cacheKey = JSON.stringify({ ...targetArgs, paged: 1 });
|
|
600
|
+
if (queryCache.has(cacheKey)) return;
|
|
601
|
+
try {
|
|
602
|
+
const res = await fetchWpApi(targetArgs, 1);
|
|
603
|
+
queryCache.set(cacheKey, res);
|
|
604
|
+
} catch (e) {}
|
|
605
|
+
}
|
|
606
|
+
};
|
|
607
|
+
activeQueries.add(item);
|
|
608
|
+
return () => {
|
|
609
|
+
activeQueries.delete(item);
|
|
610
|
+
};
|
|
611
|
+
}, [args, querySelector]);
|
|
612
|
+
|
|
613
|
+
const loadMore = React.useCallback(async () => {
|
|
614
|
+
if (loading || !hasMore) return;
|
|
615
|
+
pageModeRef.current = 'append';
|
|
616
|
+
const nextPage = currentPage + 1;
|
|
617
|
+
setCurrentPage(nextPage);
|
|
618
|
+
}, [currentPage, loading, hasMore]);
|
|
619
|
+
|
|
620
|
+
const goToPage = React.useCallback((targetPage: number) => {
|
|
621
|
+
if (loading) return;
|
|
622
|
+
if (targetPage < 1 || targetPage > totalPages) return;
|
|
623
|
+
pageModeRef.current = 'replace';
|
|
624
|
+
setPosts([]);
|
|
625
|
+
setCurrentPage(targetPage);
|
|
626
|
+
}, [loading, totalPages]);
|
|
627
|
+
|
|
628
|
+
const refetch = React.useCallback(async () => {
|
|
629
|
+
pageModeRef.current = 'replace';
|
|
630
|
+
setCurrentPage(1);
|
|
631
|
+
executeProdQuery(1);
|
|
632
|
+
}, [executeProdQuery]);
|
|
633
|
+
|
|
634
|
+
return {
|
|
635
|
+
posts,
|
|
636
|
+
loading,
|
|
637
|
+
error,
|
|
638
|
+
hasMore,
|
|
639
|
+
totalPages,
|
|
640
|
+
currentPage,
|
|
641
|
+
loadMore,
|
|
642
|
+
goToPage,
|
|
643
|
+
refetch,
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
export function useWpCategories(): string {
|
|
648
|
+
if (IS_DEV) return '<a href="#">Technology</a>, <a href="#">Design</a>';
|
|
649
|
+
return '__FORGEWP_THE_CATEGORY_LIST__';
|
|
650
|
+
}
|
|
651
|
+
export function useWpArchiveTitle(): string {
|
|
652
|
+
if (IS_DEV) return 'Category: Technology';
|
|
653
|
+
return '__FORGEWP_THE_ARCHIVE_TITLE__';
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
export function useWpTaxonomyList(taxonomy: string, defaultValue = ''): string {
|
|
657
|
+
if (IS_DEV) {
|
|
658
|
+
const post = React.useContext(WpPostContext);
|
|
659
|
+
const terms = (post as any)?._terms?.[taxonomy];
|
|
660
|
+
if (Array.isArray(terms) && terms.length > 0) {
|
|
661
|
+
return terms.map((t: any) => t.name).join(', ');
|
|
662
|
+
}
|
|
663
|
+
return defaultValue || `[taxonomy: ${taxonomy}]`;
|
|
664
|
+
}
|
|
665
|
+
return `__FORGEWP_TAXONOMY_LIST_${taxonomy}__`;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// ── useWpTerms — fetch all terms for a given taxonomy ─────────────────────────
|
|
669
|
+
// Dev: reads `_taxonomy_<name>` key from mock-data.json
|
|
670
|
+
// SSR: returns [] synchronously (Hydrate island loads in browser)
|
|
671
|
+
// Prod: fetches /wp-json/wp/v2/<taxonomy>?per_page=100
|
|
672
|
+
|
|
673
|
+
export interface WpTerm {
|
|
674
|
+
id: number;
|
|
675
|
+
name: string;
|
|
676
|
+
slug: string;
|
|
677
|
+
description: string;
|
|
678
|
+
count: number;
|
|
679
|
+
meta: Record<string, any>;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
export function useWpTerms(taxonomy: string): { terms: WpTerm[]; loading: boolean; error: string | null } {
|
|
683
|
+
if (IS_DEV) {
|
|
684
|
+
const raw: any[] = (mockData as any)?.[`_taxonomy_${taxonomy}`] || [];
|
|
685
|
+
const terms: WpTerm[] = raw.map((t: any) => ({
|
|
686
|
+
id: t.id ?? 0,
|
|
687
|
+
name: t.name ?? '',
|
|
688
|
+
slug: t.slug ?? '',
|
|
689
|
+
description: t.description ?? '',
|
|
690
|
+
count: t.count ?? 0,
|
|
691
|
+
meta: t.meta ?? {},
|
|
692
|
+
}));
|
|
693
|
+
return { terms, loading: false, error: null };
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// Node SSR — return empty; Hydrate wrapper will load in browser
|
|
697
|
+
if (typeof window === 'undefined') {
|
|
698
|
+
return { terms: [], loading: true, error: null };
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// Browser production — live WP REST API fetch
|
|
702
|
+
const [terms, setTerms] = React.useState<WpTerm[]>([]);
|
|
703
|
+
const [loading, setLoading] = React.useState(true);
|
|
704
|
+
const [error, setError] = React.useState<string | null>(null);
|
|
705
|
+
|
|
706
|
+
React.useEffect(() => {
|
|
707
|
+
let cancelled = false;
|
|
708
|
+
const endpoint = taxonomy === 'category' ? 'categories' : taxonomy === 'post_tag' ? 'tags' : taxonomy;
|
|
709
|
+
const homeUrl = (window as any).forgeWpHydration?.siteSettings?.options?.home || '';
|
|
710
|
+
let apiBase = '';
|
|
711
|
+
if (homeUrl) {
|
|
712
|
+
try {
|
|
713
|
+
apiBase = new URL(homeUrl).pathname.replace(new RegExp('/$'), '');
|
|
714
|
+
} catch (e) {}
|
|
715
|
+
}
|
|
716
|
+
const currentLang = (window as any).forgeWpLocale || (window as any).forgeWpTranslations?.currentLanguage;
|
|
717
|
+
const langParam = currentLang ? `&lang=${currentLang}` : '';
|
|
718
|
+
const fetchUrl = `${apiBase}/wp-json/wp/v2/${endpoint}?per_page=100&_fields=id,name,slug,description,count,acf,meta${langParam}`;
|
|
719
|
+
console.log(`[useWpTerms] Fetching taxonomy "${taxonomy}" from URL:`, fetchUrl);
|
|
720
|
+
fetch(fetchUrl)
|
|
721
|
+
.then((res) => {
|
|
722
|
+
if (!res.ok) throw new Error(`WP Terms API ${taxonomy}: ${res.status}`);
|
|
723
|
+
return res.json();
|
|
724
|
+
})
|
|
725
|
+
.then((data: any[]) => {
|
|
726
|
+
if (cancelled) return;
|
|
727
|
+
console.log(`[useWpTerms] Successfully loaded ${data.length} terms for taxonomy "${taxonomy}"`);
|
|
728
|
+
setTerms(
|
|
729
|
+
data.map((t) => ({
|
|
730
|
+
id: t.id,
|
|
731
|
+
name: typeof t.name === 'string' ? decodeHtmlEntities(t.name) : '',
|
|
732
|
+
slug: t.slug || '',
|
|
733
|
+
description: t.description || '',
|
|
734
|
+
count: t.count || 0,
|
|
735
|
+
meta: { ...(t.acf || {}), ...(t.meta || {}) },
|
|
736
|
+
}))
|
|
737
|
+
);
|
|
738
|
+
setError(null);
|
|
739
|
+
})
|
|
740
|
+
.catch((err: any) => {
|
|
741
|
+
if (!cancelled) {
|
|
742
|
+
console.error(`[useWpTerms] Error loading taxonomy "${taxonomy}":`, err);
|
|
743
|
+
setError(err.message || `Failed to load ${taxonomy} terms`);
|
|
744
|
+
}
|
|
745
|
+
})
|
|
746
|
+
.finally(() => {
|
|
747
|
+
if (!cancelled) setLoading(false);
|
|
748
|
+
});
|
|
749
|
+
return () => { cancelled = true; };
|
|
750
|
+
}, [taxonomy]);
|
|
751
|
+
|
|
752
|
+
return { terms, loading, error };
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
// ── WpQueryLoop — data bridge wraps @forgewp/react with mock data ─────────────
|
|
758
|
+
|
|
759
|
+
export function WpQueryLoop({
|
|
760
|
+
postType = 'post',
|
|
761
|
+
postsPerPage = 3,
|
|
762
|
+
categoryName = '',
|
|
763
|
+
children,
|
|
764
|
+
}: WpQueryLoopProps) {
|
|
765
|
+
if (IS_DEV) {
|
|
766
|
+
const posts = (mockData as any)?.[postType] || [];
|
|
767
|
+
return (
|
|
768
|
+
<_WpQueryLoop
|
|
769
|
+
posts={posts}
|
|
770
|
+
postType={postType}
|
|
771
|
+
postsPerPage={postsPerPage}
|
|
772
|
+
categoryName={categoryName}
|
|
773
|
+
>
|
|
774
|
+
{children}
|
|
775
|
+
</_WpQueryLoop>
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// Production: compiler transforms these custom elements into WordPress loop PHP
|
|
780
|
+
return (
|
|
781
|
+
<>
|
|
782
|
+
{/* @ts-ignore */}
|
|
783
|
+
<forgewp-query-loop-start
|
|
784
|
+
postType={postType}
|
|
785
|
+
postsPerPage={postsPerPage}
|
|
786
|
+
categoryName={categoryName}
|
|
787
|
+
/>
|
|
788
|
+
{children}
|
|
789
|
+
{/* @ts-ignore */}
|
|
790
|
+
<forgewp-query-loop-end />
|
|
791
|
+
</>
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// ── WpLoop — simple all-posts loop (no postType arg) ─────────────────────────
|
|
796
|
+
|
|
797
|
+
export function WpLoop({ children }: { children: React.ReactNode }) {
|
|
798
|
+
if (IS_DEV) {
|
|
799
|
+
const posts = (mockData as any)?.post || [];
|
|
800
|
+
return <_WpQueryLoop posts={posts}>{children}</_WpQueryLoop>;
|
|
801
|
+
}
|
|
802
|
+
return (
|
|
803
|
+
<>
|
|
804
|
+
{/* @ts-ignore */}
|
|
805
|
+
<forgewp-loop-start />
|
|
806
|
+
{children}
|
|
807
|
+
{/* @ts-ignore */}
|
|
808
|
+
<forgewp-loop-end />
|
|
809
|
+
</>
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// ── useWpMenu ────────────────────────────────────────────────────────────────
|
|
814
|
+
|
|
815
|
+
export function useWpMenu(location: string = 'primary'): { items: WpMenuItem[]; loading: boolean } {
|
|
816
|
+
if (IS_DEV) {
|
|
817
|
+
return _useWpMenu(location);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// Node SSR (Compile-time)
|
|
821
|
+
if (typeof window === "undefined" || (window as any)._forgeWpCompileTime) {
|
|
822
|
+
return { items: [], loading: true };
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// Browser production hydration client
|
|
826
|
+
const items = (window as any).forgeWpHydration?.menus?.[location] || [];
|
|
827
|
+
return { items, loading: false };
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// ── WpMenu — data bridge wraps @forgewp/react with menus.json ────────────────
|
|
831
|
+
|
|
832
|
+
export function WpMenu({
|
|
833
|
+
location = 'primary',
|
|
834
|
+
className = '',
|
|
835
|
+
linkClassName = '',
|
|
836
|
+
}: WpMenuProps) {
|
|
837
|
+
const { items } = useWpMenu(location);
|
|
838
|
+
|
|
839
|
+
if (IS_DEV) {
|
|
840
|
+
return (
|
|
841
|
+
<_WpMenu
|
|
842
|
+
items={items}
|
|
843
|
+
location={location}
|
|
844
|
+
className={className}
|
|
845
|
+
linkClassName={linkClassName}
|
|
846
|
+
/>
|
|
847
|
+
);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
// Production browser hydration client: render menu items from localized PHP data
|
|
851
|
+
if (typeof window !== "undefined" && !(window as any)._forgeWpCompileTime) {
|
|
852
|
+
if (items.length > 0) {
|
|
853
|
+
return (
|
|
854
|
+
<nav className={className}>
|
|
855
|
+
{items.map((item: any, idx: number) => (
|
|
856
|
+
<a key={idx} href={item.url} className={linkClassName}>
|
|
857
|
+
{item.title}
|
|
858
|
+
</a>
|
|
859
|
+
))}
|
|
860
|
+
</nav>
|
|
861
|
+
);
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// Server-matching fallback nav to guarantee zero hydration mismatch
|
|
865
|
+
return (
|
|
866
|
+
<nav className={className}>
|
|
867
|
+
<a href="/" className={linkClassName}>
|
|
868
|
+
Home
|
|
869
|
+
</a>
|
|
870
|
+
</nav>
|
|
871
|
+
);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
// Production: compiler transforms this into wp_nav_menu()
|
|
875
|
+
return (
|
|
876
|
+
// @ts-ignore
|
|
877
|
+
<forgewp-menu
|
|
878
|
+
location={location}
|
|
879
|
+
className={className}
|
|
880
|
+
linkClassName={linkClassName}
|
|
881
|
+
/>
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// ── BlockArea ────────────────────────────────────────────────────────────────
|
|
886
|
+
export function BlockArea(props: BlockAreaProps) {
|
|
887
|
+
if (IS_DEV) {
|
|
888
|
+
return <_BlockArea {...props} />;
|
|
889
|
+
}
|
|
890
|
+
return (
|
|
891
|
+
// @ts-ignore
|
|
892
|
+
<forgewp-block-area name={props.name} />
|
|
893
|
+
);
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// ── WpShortcode ──────────────────────────────────────────────────────────────
|
|
897
|
+
export function WpShortcode({ code }: WpShortcodeProps) {
|
|
898
|
+
if (IS_DEV) {
|
|
899
|
+
return <_WpShortcode code={code} />;
|
|
900
|
+
}
|
|
901
|
+
return (
|
|
902
|
+
// @ts-ignore
|
|
903
|
+
<forgewp-shortcode code={code} />
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
export function WpHead(props: WpHeadProps) {
|
|
908
|
+
if (IS_DEV) {
|
|
909
|
+
return <_WpHead {...props} />;
|
|
910
|
+
}
|
|
911
|
+
return (
|
|
912
|
+
// @ts-ignore
|
|
913
|
+
<forgewp-head
|
|
914
|
+
data-title={props.title}
|
|
915
|
+
data-description={props.description}
|
|
916
|
+
data-keywords={props.keywords}
|
|
917
|
+
data-og-title={props.ogTitle}
|
|
918
|
+
data-og-description={props.ogDescription}
|
|
919
|
+
data-og-image={props.ogImage}
|
|
920
|
+
data-og-type={props.ogType}
|
|
921
|
+
data-twitter-card={props.twitterCard}
|
|
922
|
+
data-twitter-creator={props.twitterCreator}
|
|
923
|
+
data-canonical={props.canonical}
|
|
924
|
+
/>
|
|
925
|
+
);
|
|
926
|
+
}
|
|
927
|
+
export type { WpHeadProps, WpImageProps, WpAttachment, WpRepeaterProps, WpIconProps };
|
|
928
|
+
|
|
929
|
+
export function WpImage(props: WpImageProps) {
|
|
930
|
+
if (IS_DEV) {
|
|
931
|
+
const attachments = (mockData as any)?.attachment || [];
|
|
932
|
+
return (
|
|
933
|
+
<_WpImage
|
|
934
|
+
{...props}
|
|
935
|
+
attachments={attachments}
|
|
936
|
+
/>
|
|
937
|
+
);
|
|
938
|
+
}
|
|
939
|
+
return <_WpImage {...props} />;
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// ── Routing Wrappers for Dev SPA vs Production Multi-Page WordPress ───────────
|
|
943
|
+
|
|
944
|
+
export function WpLink({ href, className, children, ...props }: any) {
|
|
945
|
+
if (IS_DEV) {
|
|
946
|
+
return (
|
|
947
|
+
<WouterLink href={href} className={className} {...props}>
|
|
948
|
+
{children}
|
|
949
|
+
</WouterLink>
|
|
950
|
+
);
|
|
951
|
+
}
|
|
952
|
+
return (
|
|
953
|
+
<a href={href} className={className} {...props}>
|
|
954
|
+
{children}
|
|
955
|
+
</a>
|
|
956
|
+
);
|
|
957
|
+
}
|
|
958
|
+
export { WpLink as Link };
|
|
959
|
+
|
|
960
|
+
export function useWpI18n() {
|
|
961
|
+
const getTranslatedText = (text: string) => {
|
|
962
|
+
if (typeof window === "undefined") {
|
|
963
|
+
return text;
|
|
964
|
+
}
|
|
965
|
+
const currentLang = (window as any).forgeWpLocale || (window as any).forgeWpTranslations?.currentLanguage || 'de';
|
|
966
|
+
const dict = (window as any).forgeWpTranslations?.translations;
|
|
967
|
+
|
|
968
|
+
if (dict) {
|
|
969
|
+
// 1. Nested dictionary format: { de: { ... }, en: { ... } }
|
|
970
|
+
if (dict[currentLang] && typeof dict[currentLang][text] !== "undefined") {
|
|
971
|
+
return dict[currentLang][text];
|
|
972
|
+
}
|
|
973
|
+
// 2. Flat enqueued active locale format: { 'Kontakt': 'Kontakt' }
|
|
974
|
+
if (typeof dict[text] !== "undefined") {
|
|
975
|
+
return dict[text];
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return text;
|
|
979
|
+
};
|
|
980
|
+
|
|
981
|
+
if (IS_DEV) {
|
|
982
|
+
return {
|
|
983
|
+
__: (text: string) => {
|
|
984
|
+
if (typeof window === "undefined") {
|
|
985
|
+
return text;
|
|
986
|
+
}
|
|
987
|
+
const pathname = window.location.pathname;
|
|
988
|
+
const translations = translationsData || {};
|
|
989
|
+
const languages = Object.keys(translations).length > 0 ? Object.keys(translations) : ['de', 'en'];
|
|
990
|
+
const defaultLanguage = languages[0] || 'de';
|
|
991
|
+
|
|
992
|
+
const matchedLang = languages.find(lang => {
|
|
993
|
+
if (lang === defaultLanguage) return false;
|
|
994
|
+
return pathname.startsWith(`/${lang}/`) || pathname === `/${lang}`;
|
|
995
|
+
});
|
|
996
|
+
const currentLang = matchedLang || defaultLanguage;
|
|
997
|
+
|
|
998
|
+
const dict = (translationsData as any)?.[currentLang];
|
|
999
|
+
if (dict && typeof dict[text] !== "undefined") {
|
|
1000
|
+
return dict[text];
|
|
1001
|
+
}
|
|
1002
|
+
return text;
|
|
1003
|
+
}
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
// Node SSR (Compile-time): return the token so the compiler can perform string replacement
|
|
1007
|
+
if (typeof window === "undefined" || (window as any)._forgeWpCompileTime) {
|
|
1008
|
+
return {
|
|
1009
|
+
__: (text: string) => `__FORGEWP_I18N_${text}__`,
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
// Production Browser (Hydration & Client-side rendering):
|
|
1013
|
+
return {
|
|
1014
|
+
__: getTranslatedText,
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
const locationListeners = new Set<(payload: { pathname: string; search: string }) => void>();
|
|
1018
|
+
let popstateBound = false;
|
|
1019
|
+
|
|
1020
|
+
function handleLocationUpdate() {
|
|
1021
|
+
const payload = {
|
|
1022
|
+
pathname: typeof window !== 'undefined' ? window.location.pathname : '/',
|
|
1023
|
+
search: typeof window !== 'undefined' ? window.location.search : '',
|
|
1024
|
+
};
|
|
1025
|
+
locationListeners.forEach((listener) => listener(payload));
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function subscribeToLocation(listener: (payload: { pathname: string; search: string }) => void) {
|
|
1029
|
+
locationListeners.add(listener);
|
|
1030
|
+
if (typeof window !== 'undefined' && !popstateBound) {
|
|
1031
|
+
window.addEventListener('popstate', handleLocationUpdate);
|
|
1032
|
+
popstateBound = true;
|
|
1033
|
+
}
|
|
1034
|
+
return () => {
|
|
1035
|
+
locationListeners.delete(listener);
|
|
1036
|
+
if (locationListeners.size === 0 && typeof window !== 'undefined' && popstateBound) {
|
|
1037
|
+
window.removeEventListener('popstate', handleLocationUpdate);
|
|
1038
|
+
popstateBound = false;
|
|
1039
|
+
}
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
function navigateTo(to: string) {
|
|
1044
|
+
if (typeof window === 'undefined') return;
|
|
1045
|
+
try {
|
|
1046
|
+
const targetUrl = new URL(to, window.location.href);
|
|
1047
|
+
if (targetUrl.pathname === window.location.pathname) {
|
|
1048
|
+
window.history.pushState(null, '', to);
|
|
1049
|
+
handleLocationUpdate();
|
|
1050
|
+
} else {
|
|
1051
|
+
window.location.href = to;
|
|
1052
|
+
}
|
|
1053
|
+
} catch (e) {
|
|
1054
|
+
window.location.href = to;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
export function useWpPrefetch() {
|
|
1059
|
+
if (IS_DEV) {
|
|
1060
|
+
return _useWpPrefetch();
|
|
1061
|
+
}
|
|
1062
|
+
const prefetch = React.useCallback((to: string) => {
|
|
1063
|
+
if (typeof window === 'undefined') return;
|
|
1064
|
+
if (prefetchTimeout) {
|
|
1065
|
+
clearTimeout(prefetchTimeout);
|
|
1066
|
+
}
|
|
1067
|
+
prefetchTimeout = setTimeout(() => {
|
|
1068
|
+
try {
|
|
1069
|
+
const url = new URL(to, window.location.href);
|
|
1070
|
+
const params = url.searchParams;
|
|
1071
|
+
activeQueries.forEach((item) => {
|
|
1072
|
+
const targetArgs = item.querySelector(params);
|
|
1073
|
+
item.execute(targetArgs);
|
|
1074
|
+
});
|
|
1075
|
+
} catch (e) {
|
|
1076
|
+
console.warn('[prefetch] Failed to parse target URL:', to, e);
|
|
1077
|
+
}
|
|
1078
|
+
}, 80);
|
|
1079
|
+
}, []);
|
|
1080
|
+
return prefetch;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
export function useWpLocation() {
|
|
1084
|
+
const prefetch = useWpPrefetch();
|
|
1085
|
+
if (IS_DEV) {
|
|
1086
|
+
const [wLoc, wNavigate] = useWouterLocation();
|
|
1087
|
+
return [wLoc, wNavigate, prefetch] as const;
|
|
1088
|
+
}
|
|
1089
|
+
const [loc, setLoc] = React.useState(typeof window !== "undefined" ? window.location.pathname : "/");
|
|
1090
|
+
|
|
1091
|
+
React.useEffect(() => {
|
|
1092
|
+
return subscribeToLocation((payload) => {
|
|
1093
|
+
setLoc(payload.pathname);
|
|
1094
|
+
});
|
|
1095
|
+
}, []);
|
|
1096
|
+
|
|
1097
|
+
const navigate = React.useCallback((to: string) => {
|
|
1098
|
+
navigateTo(to);
|
|
1099
|
+
}, []);
|
|
1100
|
+
|
|
1101
|
+
return [loc, navigate, prefetch] as const;
|
|
1102
|
+
}
|
|
1103
|
+
export { useWpLocation as useLocation };
|
|
1104
|
+
|
|
1105
|
+
export function useWpSearch() {
|
|
1106
|
+
if (IS_DEV) {
|
|
1107
|
+
return useWouterSearch();
|
|
1108
|
+
}
|
|
1109
|
+
const [search, setSearch] = React.useState(typeof window !== "undefined" ? window.location.search : "");
|
|
1110
|
+
|
|
1111
|
+
React.useEffect(() => {
|
|
1112
|
+
return subscribeToLocation((payload) => {
|
|
1113
|
+
setSearch(payload.search);
|
|
1114
|
+
});
|
|
1115
|
+
}, []);
|
|
1116
|
+
|
|
1117
|
+
return search;
|
|
1118
|
+
}
|
|
1119
|
+
export { useWpSearch as useSearch };
|
|
1120
|
+
|
|
1121
|
+
export function useWpSearchParams(): URLSearchParams {
|
|
1122
|
+
const search = useWpSearch();
|
|
1123
|
+
return React.useMemo(() => new URLSearchParams(search), [search]);
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
export function useWpLanguage() {
|
|
1128
|
+
if (IS_DEV) {
|
|
1129
|
+
const translations = translationsData || {};
|
|
1130
|
+
const languages = Object.keys(translations).length > 0 ? Object.keys(translations) : ['de', 'en'];
|
|
1131
|
+
const defaultLanguage = languages[0] || 'de';
|
|
1132
|
+
|
|
1133
|
+
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
|
|
1134
|
+
// Find if the path starts with one of the non-default languages, e.g. "/en" or "/en/"
|
|
1135
|
+
const matchedLang = languages.find(lang => {
|
|
1136
|
+
if (lang === defaultLanguage) return false;
|
|
1137
|
+
return pathname.startsWith(`/${lang}/`) || pathname === `/${lang}`;
|
|
1138
|
+
});
|
|
1139
|
+
const currentLanguage = matchedLang || defaultLanguage;
|
|
1140
|
+
|
|
1141
|
+
// Generate URLs dynamically
|
|
1142
|
+
const urls: Record<string, string> = {};
|
|
1143
|
+
const homeUrls: Record<string, string> = {};
|
|
1144
|
+
languages.forEach(lang => {
|
|
1145
|
+
const url = lang === defaultLanguage ? '/' : `/${lang}/`;
|
|
1146
|
+
urls[lang] = url;
|
|
1147
|
+
homeUrls[lang] = url;
|
|
1148
|
+
});
|
|
1149
|
+
|
|
1150
|
+
const homeUrl = homeUrls[currentLanguage] || '/';
|
|
1151
|
+
|
|
1152
|
+
const switchLanguage = React.useCallback((lang: string) => {
|
|
1153
|
+
if (typeof window !== 'undefined') {
|
|
1154
|
+
window.location.href = urls[lang] || (lang === defaultLanguage ? '/' : `/${lang}/`);
|
|
1155
|
+
}
|
|
1156
|
+
}, [urls, defaultLanguage]);
|
|
1157
|
+
|
|
1158
|
+
return {
|
|
1159
|
+
currentLanguage,
|
|
1160
|
+
languages,
|
|
1161
|
+
urls,
|
|
1162
|
+
homeUrls,
|
|
1163
|
+
homeUrl,
|
|
1164
|
+
switchLanguage,
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
const translations = typeof window !== 'undefined' ? (window as any).forgeWpTranslations : null;
|
|
1169
|
+
|
|
1170
|
+
// Dynamic current language slug enqueued by WordPress
|
|
1171
|
+
const currentLanguage = translations?.currentLanguage || 'de';
|
|
1172
|
+
|
|
1173
|
+
// Dynamic dictionary mapping active language slugs to translation counterpart URLs
|
|
1174
|
+
const urls: Record<string, string> = translations?.urls || { de: '/' };
|
|
1175
|
+
|
|
1176
|
+
// Dynamic dictionary mapping active language slugs to home page URLs
|
|
1177
|
+
const homeUrls: Record<string, string> = translations?.homeUrls || { de: '/' };
|
|
1178
|
+
const homeUrl = homeUrls[currentLanguage] || '/';
|
|
1179
|
+
|
|
1180
|
+
// Dynamic list of active language slugs enqueued on the site
|
|
1181
|
+
const languages = React.useMemo(() => Object.keys(urls), [urls]);
|
|
1182
|
+
|
|
1183
|
+
// Redirection helper to switch safely between languages
|
|
1184
|
+
const switchLanguage = React.useCallback((lang: string) => {
|
|
1185
|
+
if (typeof window !== 'undefined') {
|
|
1186
|
+
if (urls && urls[lang]) {
|
|
1187
|
+
window.location.href = urls[lang];
|
|
1188
|
+
} else {
|
|
1189
|
+
window.location.href = lang === 'de' ? '/' : `/${lang}/`;
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
}, [urls]);
|
|
1193
|
+
|
|
1194
|
+
return {
|
|
1195
|
+
currentLanguage,
|
|
1196
|
+
languages,
|
|
1197
|
+
urls,
|
|
1198
|
+
homeUrls,
|
|
1199
|
+
homeUrl,
|
|
1200
|
+
switchLanguage,
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
// ── Compiler custom element JSX declarations ──────────────────────────────────
|
|
1206
|
+
|
|
1207
|
+
declare global {
|
|
1208
|
+
namespace React {
|
|
1209
|
+
namespace JSX {
|
|
1210
|
+
interface IntrinsicElements {
|
|
1211
|
+
'forgewp-menu': React.DetailedHTMLProps<
|
|
1212
|
+
React.HTMLAttributes<HTMLElement> & {
|
|
1213
|
+
location?: 'primary' | 'footer' | 'sidebar' | string;
|
|
1214
|
+
linkClassName?: string;
|
|
1215
|
+
},
|
|
1216
|
+
HTMLElement
|
|
1217
|
+
>;
|
|
1218
|
+
'forgewp-query-loop-start': React.DetailedHTMLProps<
|
|
1219
|
+
React.HTMLAttributes<HTMLElement> & {
|
|
1220
|
+
postType?: string;
|
|
1221
|
+
postsPerPage?: number;
|
|
1222
|
+
categoryName?: string;
|
|
1223
|
+
},
|
|
1224
|
+
HTMLElement
|
|
1225
|
+
>;
|
|
1226
|
+
'forgewp-query-loop-end': React.DetailedHTMLProps<
|
|
1227
|
+
React.HTMLAttributes<HTMLElement>,
|
|
1228
|
+
HTMLElement
|
|
1229
|
+
>;
|
|
1230
|
+
'forgewp-loop-start': React.DetailedHTMLProps<
|
|
1231
|
+
React.HTMLAttributes<HTMLElement>,
|
|
1232
|
+
HTMLElement
|
|
1233
|
+
>;
|
|
1234
|
+
'forgewp-loop-end': React.DetailedHTMLProps<
|
|
1235
|
+
React.HTMLAttributes<HTMLElement>,
|
|
1236
|
+
HTMLElement
|
|
1237
|
+
>;
|
|
1238
|
+
'forgewp-shortcode': React.DetailedHTMLProps<
|
|
1239
|
+
React.HTMLAttributes<HTMLElement> & {
|
|
1240
|
+
code?: string;
|
|
1241
|
+
},
|
|
1242
|
+
HTMLElement
|
|
1243
|
+
>;
|
|
1244
|
+
'forgewp-head': React.DetailedHTMLProps<
|
|
1245
|
+
React.HTMLAttributes<HTMLElement> & {
|
|
1246
|
+
'data-title'?: string;
|
|
1247
|
+
'data-description'?: string;
|
|
1248
|
+
'data-keywords'?: string;
|
|
1249
|
+
'data-og-title'?: string;
|
|
1250
|
+
'data-og-description'?: string;
|
|
1251
|
+
'data-og-image'?: string;
|
|
1252
|
+
'data-og-type'?: string;
|
|
1253
|
+
'data-twitter-card'?: string;
|
|
1254
|
+
'data-twitter-creator'?: string;
|
|
1255
|
+
'data-canonical'?: string;
|
|
1256
|
+
},
|
|
1257
|
+
HTMLElement
|
|
1258
|
+
>;
|
|
1259
|
+
'forgewp-image': React.DetailedHTMLProps<
|
|
1260
|
+
React.HTMLAttributes<HTMLElement> & {
|
|
1261
|
+
'data-id'?: string;
|
|
1262
|
+
'data-field'?: string;
|
|
1263
|
+
'data-size'?: string;
|
|
1264
|
+
'data-class-name'?: string;
|
|
1265
|
+
'data-alt'?: string;
|
|
1266
|
+
},
|
|
1267
|
+
HTMLElement
|
|
1268
|
+
>;
|
|
1269
|
+
'forgewp-block-area': React.DetailedHTMLProps<
|
|
1270
|
+
React.HTMLAttributes<HTMLElement> & {
|
|
1271
|
+
name?: string;
|
|
1272
|
+
},
|
|
1273
|
+
HTMLElement
|
|
1274
|
+
>;
|
|
1275
|
+
'forgewp-repeater-start': React.DetailedHTMLProps<
|
|
1276
|
+
React.HTMLAttributes<HTMLElement> & {
|
|
1277
|
+
name?: string;
|
|
1278
|
+
subfields?: string;
|
|
1279
|
+
},
|
|
1280
|
+
HTMLElement
|
|
1281
|
+
>;
|
|
1282
|
+
'forgewp-repeater-end': React.DetailedHTMLProps<
|
|
1283
|
+
React.HTMLAttributes<HTMLElement>,
|
|
1284
|
+
HTMLElement
|
|
1285
|
+
>;
|
|
1286
|
+
'forgewp-icon-placeholder': React.DetailedHTMLProps<
|
|
1287
|
+
React.HTMLAttributes<HTMLElement> & {
|
|
1288
|
+
name?: string;
|
|
1289
|
+
provider?: string;
|
|
1290
|
+
class?: string;
|
|
1291
|
+
},
|
|
1292
|
+
HTMLElement
|
|
1293
|
+
>;
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
}
|