@forgewp/compiler 0.4.1 → 0.4.3

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