@forgewp/compiler 0.4.2 → 0.4.4

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 (144) hide show
  1. package/README.md +70 -3
  2. package/bin/add.js +30 -15
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +149 -70
  5. package/bin/doctor.js +21 -12
  6. package/bin/export.js +69 -20
  7. package/bin/fresh.js +6 -1
  8. package/bin/i18n-extract.js +3 -10
  9. package/bin/i18n-translate.js +15 -24
  10. package/bin/make-block.js +24 -0
  11. package/bin/make-editable.js +166 -0
  12. package/bin/make-form.js +131 -0
  13. package/bin/make-island.js +11 -0
  14. package/bin/make-loop.js +147 -0
  15. package/bin/make-mail.js +27 -0
  16. package/bin/make-page.js +83 -0
  17. package/bin/make-post-type.js +68 -29
  18. package/bin/make-sandbox.js +609 -0
  19. package/bin/make-section.js +221 -0
  20. package/bin/make-shell.js +375 -0
  21. package/bin/repair.js +14 -26
  22. package/bin/seed.js +119 -0
  23. package/bin/sync-routes.js +107 -85
  24. package/lib/adapters/html-adapter.js +13 -3
  25. package/lib/adapters/stub-adapter.js +10 -2
  26. package/lib/add-component.js +153 -92
  27. package/lib/asset-loader.js +333 -1
  28. package/lib/assets/asset-graph.js +432 -0
  29. package/lib/assets/asset-pipeline.js +125 -0
  30. package/lib/assets/diagnostics-report.js +345 -0
  31. package/lib/assets/external-fetcher.js +173 -0
  32. package/lib/assets/font-orchestrator.js +348 -0
  33. package/lib/assets/font-usage-scanner.js +242 -0
  34. package/lib/assets/image-optimizer.js +229 -0
  35. package/lib/assets/index.js +51 -0
  36. package/lib/assets/preload-generator.js +70 -0
  37. package/lib/assets/public-url.js +153 -0
  38. package/lib/block-authoring-help.js +11 -0
  39. package/lib/blocks/ast-parser.js +67 -0
  40. package/lib/blocks/discover-blocks.js +146 -0
  41. package/lib/blocks/editor-scope.js +733 -0
  42. package/lib/blocks/editor-transpiler.js +1229 -0
  43. package/lib/blocks/index.js +2838 -0
  44. package/lib/blocks/php-transpiler.js +4928 -0
  45. package/lib/blocks/scanner.js +1487 -0
  46. package/lib/blocks/shared-utils.js +290 -0
  47. package/lib/blocks/source-sanitize.js +1449 -0
  48. package/lib/blueprints.js +77 -5
  49. package/lib/build-assets.js +38 -33
  50. package/lib/collect-page-template-routes.js +102 -0
  51. package/lib/collect-static-routes.js +175 -0
  52. package/lib/diagnostics.js +58 -33
  53. package/lib/export-theme.js +84 -5
  54. package/lib/extract-template-content.js +90 -0
  55. package/lib/forms-preview.js +42 -0
  56. package/lib/functions/cpt-routing.js +69 -0
  57. package/lib/functions/forms.js +2461 -0
  58. package/lib/functions/hydration-enqueuer.js +400 -0
  59. package/lib/functions/index.js +1623 -0
  60. package/lib/functions/load-menus.js +112 -0
  61. package/lib/functions/load-translations.js +148 -0
  62. package/lib/functions/rest-endpoints.js +2923 -0
  63. package/lib/functions/routing.js +765 -0
  64. package/lib/functions/seed-mock-data.js +392 -0
  65. package/lib/functions/seed-products.js +481 -0
  66. package/lib/functions/settings-page.js +273 -0
  67. package/lib/functions/theme-setup.js +494 -0
  68. package/lib/generate-theme.js +2076 -303
  69. package/lib/hydration/editable-schemas.js +332 -0
  70. package/lib/hydration/enter-hidden-initial.js +65 -0
  71. package/lib/hydration/form-schemas.js +227 -0
  72. package/lib/hydration/index.js +12 -0
  73. package/lib/hydration/is-interactive.js +951 -0
  74. package/lib/hydration/island-split.js +1231 -0
  75. package/lib/hydration/islands-scanner.js +599 -0
  76. package/lib/hydration/resolve-island-chunk.js +103 -0
  77. package/lib/hydration/resolve-island-component.js +52 -0
  78. package/lib/hydration/rollup-inputs.js +81 -0
  79. package/lib/hydration/root-class-extractor.js +220 -0
  80. package/lib/hydration/scan-app-providers.js +154 -0
  81. package/lib/hydration/static-lint.js +382 -0
  82. package/lib/hydration/transform.js +257 -0
  83. package/lib/hydration/uses-block-area.js +49 -0
  84. package/lib/hydration/utils.js +119 -0
  85. package/lib/i18n/translation-cache.js +141 -0
  86. package/lib/icon-registry.js +72 -0
  87. package/lib/index.d.ts +324 -8
  88. package/lib/index.js +3 -2
  89. package/lib/load-config.js +338 -144
  90. package/lib/mail-templates.js +37 -0
  91. package/lib/markup-processor.js +483 -92
  92. package/lib/node-runtime.js +7 -0
  93. package/lib/page-config-plugin.js +84 -0
  94. package/lib/php-builders.js +383 -42
  95. package/lib/react-adapter.js +1053 -246
  96. package/lib/registration-metadata.js +11 -0
  97. package/lib/render-theme.mts +1410 -543
  98. package/lib/route-layout.js +76 -0
  99. package/lib/template-discovery.js +58 -0
  100. package/lib/theme-compatibility.js +32 -0
  101. package/lib/validate-export.js +51 -2
  102. package/lib/validate.js +27 -5
  103. package/lib/virtual-plugin.js +319 -0
  104. package/lib/walkthrough.md +26 -0
  105. package/package.json +17 -5
  106. package/templates/PresetsStyle.tsx +1 -1
  107. package/templates/auth/cms/email-logs.json +9 -0
  108. package/templates/auth/cms/menus.json +11 -0
  109. package/templates/auth/cms/mock-data.json +123 -0
  110. package/templates/auth/cms/roles.json +7 -0
  111. package/templates/auth/cms/sessions.json +1 -0
  112. package/templates/auth/cms/site-settings.json +28 -0
  113. package/templates/auth/cms/translations.json +4 -0
  114. package/templates/auth/cms/users.json +46 -0
  115. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  116. package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
  117. package/templates/auth/components/login-form-wrapper.tsx +300 -0
  118. package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
  119. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  120. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  121. package/templates/auth/pages/DashboardPage.tsx +12 -0
  122. package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
  123. package/templates/auth/pages/LoginPage.tsx +11 -0
  124. package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
  125. package/templates/auth/pages/SignUpPage.tsx +11 -0
  126. package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
  127. package/templates/auth/ui/button.tsx +57 -0
  128. package/templates/auth/ui/card.tsx +76 -0
  129. package/templates/auth/ui/field.tsx +242 -0
  130. package/templates/auth/ui/input.tsx +22 -0
  131. package/templates/auth/ui/label.tsx +24 -0
  132. package/templates/auth/ui/separator.tsx +31 -0
  133. package/templates/forgewp-config.ts +70 -3
  134. package/templates/menus.json +12 -10
  135. package/templates/mock-data.json +122 -433
  136. package/templates/products.json +5 -0
  137. package/templates/roles.json +7 -0
  138. package/templates/sessions.json +1 -0
  139. package/templates/users.json +38 -0
  140. package/templates/wordpress.tsx +1835 -1297
  141. package/bin/make-template.js +0 -145
  142. package/lib/block-compiler.js +0 -552
  143. package/lib/functions-builder.js +0 -2044
  144. package/lib/hydration-scanner.js +0 -821
@@ -1,1297 +1,1835 @@
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(/&lt;/g, '<')
85
- .replace(/&gt;/g, '>')
86
- .replace(/&quot;/g, '"')
87
- .replace(/&#39;/g, "'")
88
- .replace(/&#x27;/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
- }
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
+
10
+ // @ts-ignore
11
+ import rawMockData from '../../cms/mock-data';
12
+ // @ts-ignore
13
+ import rawMenusData from '../../cms/menus';
14
+ // @ts-ignore
15
+ import wpConfig from '../../wp.config';
16
+ // @ts-ignore
17
+ import rawTranslationsData from '../../cms/translations';
18
+
19
+ const mockData =
20
+ (rawMockData && (rawMockData.default || rawMockData.mockData)) ||
21
+ rawMockData ||
22
+ {};
23
+ const menusData =
24
+ (rawMenusData && (rawMenusData.default || rawMenusData.menus)) ||
25
+ rawMenusData ||
26
+ {};
27
+ const translationsData =
28
+ (rawTranslationsData &&
29
+ (rawTranslationsData.default || rawTranslationsData.translations)) ||
30
+ rawTranslationsData ||
31
+ {};
32
+
33
+ import {
34
+ WpQueryLoop as _WpQueryLoop,
35
+ WpMenu as _WpMenu,
36
+ WpShortcode as _WpShortcode,
37
+ useWpTitle as _useWpTitle,
38
+ useWpContent as _useWpContent,
39
+ useWpExcerpt as _useWpExcerpt,
40
+ useWpPermalink as _useWpPermalink,
41
+ useWpDate as _useWpDate,
42
+ useWpModifiedDate as _useWpModifiedDate,
43
+ useWpAuthor as _useWpAuthor,
44
+ useWpFeaturedImage as _useWpFeaturedImage,
45
+ useWpCustomField as _useWpCustomField,
46
+ useWpField as _useWpField,
47
+ useWpOption as _useWpOption,
48
+ useWpThemeMod as _useWpThemeMod,
49
+ useWpThemeUri as _useWpThemeUri,
50
+ useWpQuery as _useWpQuery,
51
+ useWpPrefetch as _useWpPrefetch,
52
+ WpHead as _WpHead,
53
+ WpImage as _WpImage,
54
+ WpPostContext,
55
+ useWpMeta as _useWpMeta,
56
+ useWpPageLink as _useWpPageLink,
57
+ useWpMenu as _useWpMenu,
58
+ BlockArea as _BlockArea,
59
+ defineEditable,
60
+ getEditableDefaults,
61
+ buildPageEditable,
62
+ pickEditable,
63
+ mergeEditable,
64
+ text,
65
+ richText,
66
+ image,
67
+ boolean,
68
+ repeater,
69
+ color,
70
+ url,
71
+ select,
72
+ number,
73
+ icon,
74
+ isEditorPreview,
75
+ useIsEditorPreview,
76
+ WpRepeater,
77
+ WpIcon,
78
+ defineWpOptions,
79
+ optionText,
80
+ optionUrl,
81
+ optionEmail,
82
+ optionTextarea,
83
+ optionToggle,
84
+ optionNumber,
85
+ optionPostPicker,
86
+ WpFormFields,
87
+ submitWpForm,
88
+ isDecoupled,
89
+ useIsDecoupled,
90
+ isWordPress,
91
+ useIsWordPress,
92
+ WpLink,
93
+ Link,
94
+ Router,
95
+ Route,
96
+ Switch,
97
+ useLocation,
98
+ useSearch,
99
+ useParams,
100
+ useRoute,
101
+ } from '@forgewp/react';
102
+
103
+ export {
104
+ WpPostContext,
105
+ defineEditable,
106
+ getEditableDefaults,
107
+ buildPageEditable,
108
+ pickEditable,
109
+ mergeEditable,
110
+ text,
111
+ richText,
112
+ image,
113
+ boolean,
114
+ repeater,
115
+ color,
116
+ url,
117
+ select,
118
+ number,
119
+ icon,
120
+ isEditorPreview,
121
+ useIsEditorPreview,
122
+ isDecoupled,
123
+ useIsDecoupled,
124
+ isWordPress,
125
+ useIsWordPress,
126
+ WpRepeater,
127
+ WpIcon,
128
+ defineWpOptions,
129
+ optionText,
130
+ optionUrl,
131
+ optionEmail,
132
+ optionTextarea,
133
+ optionToggle,
134
+ optionNumber,
135
+ optionPostPicker,
136
+ WpFormFields,
137
+ submitWpForm,
138
+ WpLink,
139
+ Link,
140
+ Router,
141
+ Route,
142
+ Switch,
143
+ useLocation,
144
+ useSearch,
145
+ useParams,
146
+ useRoute,
147
+ useLocation as useWpLocation,
148
+ useSearch as useWpSearch,
149
+ };
150
+
151
+ import type {
152
+ WpQueryLoopProps,
153
+ WpMenuProps,
154
+ WpMenuItem,
155
+ WpHeadProps,
156
+ WpImageProps,
157
+ WpAttachment,
158
+ WpQueryArgs,
159
+ WpQueryResults,
160
+ WpPost,
161
+ WpShortcodeProps,
162
+ BlockAreaProps,
163
+ WpRepeaterProps,
164
+ WpIconProps,
165
+ WpFormFieldsProps,
166
+ WpFormFieldDescriptor,
167
+ WpFormResult,
168
+ } from '@forgewp/react';
169
+
170
+ export type { WpFormFieldsProps, WpFormFieldDescriptor, WpFormResult };
171
+
172
+ const IS_DEV =
173
+ typeof import.meta !== 'undefined' &&
174
+ // @ts-ignore
175
+ import.meta.env?.DEV === true;
176
+
177
+ const IS_DECOUPLED =
178
+ typeof window !== 'undefined' && (window as any)._forgeWpCompileTime
179
+ ? false
180
+ : IS_DEV ||
181
+ (typeof window !== 'undefined' && !(window as any).forgeWpHydration);
182
+
183
+ export function decodeHtmlEntities(str: string): string {
184
+ if (!str) return '';
185
+ if (typeof window === 'undefined') {
186
+ return str
187
+ .replace(/&amp;/g, '&')
188
+ .replace(/&lt;/g, '<')
189
+ .replace(/&gt;/g, '>')
190
+ .replace(/&quot;/g, '"')
191
+ .replace(/&#39;/g, "'")
192
+ .replace(/&#x27;/g, "'");
193
+ }
194
+ const txt = document.createElement('textarea');
195
+ txt.innerHTML = str;
196
+ return txt.value;
197
+ }
198
+
199
+ function getDevMockPosts(): any {
200
+ if (typeof window !== 'undefined' && (window as any)._forgeWpMockPosts) {
201
+ return (window as any)._forgeWpMockPosts;
202
+ }
203
+ return mockData;
204
+ }
205
+
206
+ if (IS_DEV) {
207
+ if (typeof window !== 'undefined') {
208
+ const mockOptions = {} as any;
209
+ if (wpConfig && wpConfig.options) {
210
+ for (const [key, field] of Object.entries(wpConfig.options)) {
211
+ if (field && typeof field === 'object' && 'default' in field) {
212
+ mockOptions[key] = field.default;
213
+ }
214
+ }
215
+ }
216
+ const mockThemeMods = wpConfig?.themeMods || {};
217
+ (window as any)._forgeWpMockSiteSettings = {
218
+ options: mockOptions,
219
+ theme_mods: mockThemeMods,
220
+ };
221
+ (window as any)._forgeWpMockPosts = mockData;
222
+ (window as any)._forgeWpMockMenus = menusData;
223
+
224
+ const mockForms: Record<string, { fields: any[] }> = {};
225
+ if (wpConfig && wpConfig.forms) {
226
+ // clientFields.seed is either a flat array (single-locale theme, or
227
+ // "same content for every locale") or a per-locale map — pick the
228
+ // URL-prefix-detected language (matching useWpI18n's own dev-mode
229
+ // detection below), falling back to the configured default locale.
230
+ const configuredLocales: string[] = wpConfig.i18n?.locales || [];
231
+ let devLang: string | undefined =
232
+ wpConfig.i18n?.defaultLocale || configuredLocales[0];
233
+ if (configuredLocales.length > 1) {
234
+ const match = window.location.pathname.match(
235
+ /^\/([a-zA-Z]{2})(?:\/|$)/,
236
+ );
237
+ if (match && configuredLocales.includes(match[1])) {
238
+ devLang = match[1];
239
+ }
240
+ }
241
+ for (const [formName, formConfig] of Object.entries(
242
+ wpConfig.forms as Record<string, any>,
243
+ )) {
244
+ const seed = formConfig?.clientFields?.enabled
245
+ ? formConfig.clientFields.seed
246
+ : undefined;
247
+ let seedFields: any[] = [];
248
+ if (Array.isArray(seed)) {
249
+ seedFields = seed;
250
+ } else if (seed && typeof seed === 'object') {
251
+ seedFields =
252
+ seed[devLang as string] ||
253
+ (configuredLocales[0] && seed[configuredLocales[0]]) ||
254
+ Object.values(seed)[0] ||
255
+ [];
256
+ }
257
+ mockForms[formName] = { fields: seedFields };
258
+ }
259
+ }
260
+ // The virtual runtime includes discovered forms and owns its locale-aware data.
261
+ // Retain this bootstrap only when no virtual runtime has initialized it.
262
+ if (!(window as any)._forgeWpMockForms) {
263
+ (window as any)._forgeWpMockForms = mockForms;
264
+ }
265
+ }
266
+ }
267
+
268
+ // ── Re-export pure hooks with compiler token fallbacks ────────────────────────
269
+ // In dev: @forgewp/react hook returns the mock value from WpPostContext.
270
+ // In prod: compiler replaces the call with the PHP equivalent below.
271
+
272
+ export function useWpTitle(): string {
273
+ if (IS_DECOUPLED) return _useWpTitle();
274
+ return '__FORGEWP_THE_TITLE__';
275
+ }
276
+ export function useWpContent(): string {
277
+ if (IS_DECOUPLED) return _useWpContent();
278
+ return '__FORGEWP_THE_CONTENT__';
279
+ }
280
+ export function useWpExcerpt(): string {
281
+ if (IS_DECOUPLED) return _useWpExcerpt();
282
+ return '__FORGEWP_THE_EXCERPT__';
283
+ }
284
+ export function useWpPermalink(): string {
285
+ if (IS_DECOUPLED) return _useWpPermalink();
286
+ return '__FORGEWP_THE_PERMALINK__';
287
+ }
288
+ export function useWpDate(): string {
289
+ if (IS_DECOUPLED) return _useWpDate();
290
+ return '__FORGEWP_THE_DATE__';
291
+ }
292
+ export function useWpModifiedDate(): string {
293
+ if (IS_DECOUPLED) return _useWpModifiedDate();
294
+ return '__FORGEWP_THE_MODIFIED_DATE__';
295
+ }
296
+ export function useWpAuthor(): string {
297
+ if (IS_DECOUPLED) return _useWpAuthor();
298
+ return '__FORGEWP_THE_AUTHOR__';
299
+ }
300
+ export function useWpFeaturedImage(): string {
301
+ if (IS_DECOUPLED) return _useWpFeaturedImage();
302
+ return '__FORGEWP_THE_POST_THUMBNAIL_URL__';
303
+ }
304
+ /**
305
+ * Match PHP `forgewp_get_meta_value`: empty ACF/meta must fall through to schema
306
+ * defaults. Hydration previously injected `""` / `[]` for every registered key,
307
+ * which made island remounts wipe SSR text (front page, About, etc.).
308
+ */
309
+ function isEmptyMetaValue(value: unknown): boolean {
310
+ if (
311
+ value === null ||
312
+ value === undefined ||
313
+ value === false ||
314
+ value === ''
315
+ ) {
316
+ return true;
317
+ }
318
+ if (Array.isArray(value) && value.length === 0) {
319
+ return true;
320
+ }
321
+ return false;
322
+ }
323
+
324
+ export function useWpCustomField(fieldName: string, defaultValue = ''): any {
325
+ if (IS_DECOUPLED) return _useWpCustomField(fieldName, defaultValue);
326
+
327
+ if (typeof window !== 'undefined') {
328
+ const win = window as any;
329
+ if (!win._forgeWpCompileTime) {
330
+ const post = React.useContext(WpPostContext);
331
+ const currentPost = post || win.forgeWpHydration?.post;
332
+ if (
333
+ currentPost?.customFields &&
334
+ typeof currentPost.customFields[fieldName] !== 'undefined'
335
+ ) {
336
+ const val = currentPost.customFields[fieldName];
337
+ if (!isEmptyMetaValue(val)) {
338
+ return val;
339
+ }
340
+ }
341
+ }
342
+ }
343
+
344
+ return '__FORGEWP_CUSTOM_FIELD__' + fieldName + '__';
345
+ }
346
+
347
+ export function useWpField(fieldName: string, defaultValue = ''): any {
348
+ if (IS_DECOUPLED) return _useWpField(fieldName, defaultValue);
349
+
350
+ if (typeof window !== 'undefined') {
351
+ const win = window as any;
352
+ if (!win._forgeWpCompileTime) {
353
+ const post = React.useContext(WpPostContext);
354
+ const currentPost = post || win.forgeWpHydration?.post;
355
+ if (
356
+ currentPost?.customFields &&
357
+ typeof currentPost.customFields[fieldName] !== 'undefined'
358
+ ) {
359
+ const val = currentPost.customFields[fieldName];
360
+ if (!isEmptyMetaValue(val)) {
361
+ return val;
362
+ }
363
+ }
364
+ }
365
+ }
366
+
367
+ return '__FORGEWP_CUSTOM_FIELD__' + fieldName + '__';
368
+ }
369
+
370
+ export const WpBlockContext =
371
+ typeof window !== 'undefined'
372
+ ? (window as any)._forgeWpBlockContext ||
373
+ ((window as any)._forgeWpBlockContext = React.createContext<any>(null))
374
+ : React.createContext<any>(null);
375
+
376
+ export function useWpMeta<T>(
377
+ key: string,
378
+ defaultValue: T,
379
+ postId?: number | string,
380
+ ): T {
381
+ if (IS_DECOUPLED) return (_useWpMeta as any)(key, defaultValue);
382
+
383
+ // Browser-side hydration: check for forgeWpHydration data first
384
+ if (typeof window !== 'undefined') {
385
+ const win = window as any;
386
+ if (win._forgeWpCompileTime) {
387
+ if (Array.isArray(defaultValue)) {
388
+ const postSuffix = postId ? `_POST_${postId}` : '';
389
+ return defaultValue.map((item, index) => {
390
+ if (item && typeof item === 'object') {
391
+ const tokenItem: any = {};
392
+ for (const prop in item) {
393
+ const defaultStr =
394
+ typeof item[prop] === 'string'
395
+ ? item[prop]
396
+ : JSON.stringify(item[prop]);
397
+ tokenItem[prop] =
398
+ `__FORGEWP_META_${key}_${index}_${prop}${postSuffix}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__`;
399
+ }
400
+ return tokenItem;
401
+ }
402
+ const defaultStr =
403
+ typeof item === 'string' ? item : JSON.stringify(item);
404
+ return `__FORGEWP_META_${key}_${index}${postSuffix}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__`;
405
+ }) as any as T;
406
+ }
407
+ const defaultStr =
408
+ typeof defaultValue === 'string'
409
+ ? defaultValue
410
+ : JSON.stringify(defaultValue);
411
+ const postSuffix = postId ? `_POST_${postId}` : '';
412
+ return `__FORGEWP_META_${key}${postSuffix}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__` as any as T;
413
+ }
414
+ const blockAttrs = React.useContext(WpBlockContext) as any;
415
+ if (
416
+ !postId &&
417
+ blockAttrs &&
418
+ typeof blockAttrs[key] !== 'undefined' &&
419
+ !isEmptyMetaValue(blockAttrs[key])
420
+ ) {
421
+ return blockAttrs[key] as T;
422
+ }
423
+ let targetPost = null;
424
+ if (postId) {
425
+ let resolvedPostId = postId;
426
+ if (postId === 'front') {
427
+ resolvedPostId =
428
+ win.forgeWpHydration?.siteSettings?.options?.page_on_front || 0;
429
+ }
430
+ if (win.forgeWpHydration?.posts?.[resolvedPostId]) {
431
+ targetPost = win.forgeWpHydration.posts[resolvedPostId];
432
+ }
433
+ } else {
434
+ const post = React.useContext(WpPostContext);
435
+ targetPost = post || win.forgeWpHydration?.post;
436
+ }
437
+ if (
438
+ targetPost?.customFields &&
439
+ typeof targetPost.customFields[key] !== 'undefined'
440
+ ) {
441
+ const val = targetPost.customFields[key];
442
+ if (!isEmptyMetaValue(val)) {
443
+ return val as T;
444
+ }
445
+ }
446
+ // Empty ACF/meta → component schema defaults (same as PHP forgewp_get_meta_value)
447
+ return defaultValue;
448
+ }
449
+
450
+ // Fallback to token for compiler replacement
451
+ if (Array.isArray(defaultValue)) {
452
+ const postSuffix = postId ? `_POST_${postId}` : '';
453
+ return defaultValue.map((item, index) => {
454
+ if (item && typeof item === 'object') {
455
+ const tokenItem: any = {};
456
+ for (const prop in item) {
457
+ const defaultStr =
458
+ typeof item[prop] === 'string'
459
+ ? item[prop]
460
+ : JSON.stringify(item[prop]);
461
+ tokenItem[prop] =
462
+ `__FORGEWP_META_${key}_${index}_${prop}${postSuffix}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__`;
463
+ }
464
+ return tokenItem;
465
+ }
466
+ const defaultStr = typeof item === 'string' ? item : JSON.stringify(item);
467
+ return `__FORGEWP_META_${key}_${index}${postSuffix}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__`;
468
+ }) as any as T;
469
+ }
470
+
471
+ const defaultStr =
472
+ typeof defaultValue === 'string'
473
+ ? defaultValue
474
+ : JSON.stringify(defaultValue);
475
+ const postSuffix = postId ? `_POST_${postId}` : '';
476
+ return `__FORGEWP_META_${key}${postSuffix}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__` as any as T;
477
+ }
478
+
479
+ export function useWpOption(optionName: string, defaultValue = ''): string {
480
+ if (IS_DECOUPLED) return _useWpOption(optionName, defaultValue);
481
+
482
+ // Browser-side hydration: check for forgeWpHydration data first
483
+ if (typeof window !== 'undefined') {
484
+ const win = window as any;
485
+ const hydrationOptions = win.forgeWpHydration?.siteSettings?.options;
486
+ if (hydrationOptions?.[optionName] !== undefined) {
487
+ const value = hydrationOptions[optionName];
488
+ if (value === false || value === null) {
489
+ return defaultValue || `[option: ${optionName}]`;
490
+ }
491
+ return String(value);
492
+ }
493
+ }
494
+
495
+ // Fallback to token for compiler replacement
496
+ const defaultStr =
497
+ typeof defaultValue === 'string'
498
+ ? defaultValue
499
+ : JSON.stringify(defaultValue);
500
+ return `__FORGEWP_OPTION_${optionName}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__`;
501
+ }
502
+
503
+ export function useWpThemeMod(modName: string, defaultValue = ''): string {
504
+ if (IS_DECOUPLED) return _useWpThemeMod(modName, defaultValue);
505
+
506
+ // Browser-side hydration: check for forgeWpHydration data first
507
+ if (typeof window !== 'undefined') {
508
+ const win = window as any;
509
+ const hydrationMods = win.forgeWpHydration?.siteSettings?.theme_mods;
510
+ if (hydrationMods?.[modName] !== undefined) {
511
+ const value = hydrationMods[modName];
512
+ if (value === false || value === null) {
513
+ return defaultValue || `[theme_mod: ${modName}]`;
514
+ }
515
+ return String(value);
516
+ }
517
+ }
518
+
519
+ // Fallback to token for compiler replacement
520
+ const defaultStr =
521
+ typeof defaultValue === 'string'
522
+ ? defaultValue
523
+ : JSON.stringify(defaultValue);
524
+ return `__FORGEWP_THEME_MOD_${modName}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__`;
525
+ }
526
+
527
+ export function useWpThemeUri(): string {
528
+ if (IS_DECOUPLED) return _useWpThemeUri();
529
+ if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
530
+ return (window as any).forgeWpHydration?.themeUri || '';
531
+ }
532
+ return '__FORGEWP_THEME_URI__';
533
+ }
534
+
535
+ export function useWpPageLink(name: string, fallback: string): string {
536
+ if (IS_DECOUPLED) return _useWpPageLink(name, fallback);
537
+ if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
538
+ const win = window as any;
539
+ // Use the resolved WP permalink if available and non-empty
540
+ const resolved = win.forgeWpHydration?.pageLinks?.[name];
541
+ if (resolved) {
542
+ return resolved;
543
+ }
544
+ // pageLinks key exists but is empty string (page not assigned template yet) → use fallback
545
+ if (
546
+ win.forgeWpHydration?.pageLinks &&
547
+ name in win.forgeWpHydration.pageLinks
548
+ ) {
549
+ return fallback || '';
550
+ }
551
+ }
552
+ // Compile-time: emit the token so the PHP compiler can replace it
553
+ if (typeof window !== 'undefined' && (window as any)._forgeWpCompileTime) {
554
+ return fallback
555
+ ? `__FORGEWP_PAGELINK_${name}_DEFAULT_${encodeURIComponent(fallback)}__`
556
+ : `__FORGEWP_PAGELINK_${name}__`;
557
+ }
558
+ // SSR / unknown context: return fallback
559
+ return fallback || '';
560
+ }
561
+
562
+ export function useWpPagePath(name: string, fallback: string): string {
563
+ const href = useWpPageLink(name, fallback);
564
+ return React.useMemo(() => {
565
+ try {
566
+ return new URL(
567
+ href,
568
+ typeof window !== 'undefined'
569
+ ? window.location.origin
570
+ : 'http://localhost',
571
+ ).pathname;
572
+ } catch (e) {
573
+ return href;
574
+ }
575
+ }, [href]);
576
+ }
577
+ const queryCache = new Map<
578
+ string,
579
+ { posts: any[]; total: number; hasMore: boolean; totalPages?: number }
580
+ >();
581
+
582
+ const activeQueries = new Set<{
583
+ args: any;
584
+ querySelector: (params: URLSearchParams) => any;
585
+ execute: (targetArgs: any) => Promise<any>;
586
+ }>();
587
+
588
+ let prefetchTimeout: any = null;
589
+
590
+ async function fetchWpApi(args: any, page: number) {
591
+ const {
592
+ queryId = '',
593
+ postType = 'post',
594
+ postsPerPage = 10,
595
+ categoryName = '',
596
+ s = '',
597
+ orderby = 'date',
598
+ order = 'DESC',
599
+ p,
600
+ taxQuery = [],
601
+ metaQuery = [],
602
+ } = args;
603
+
604
+ const endpoint =
605
+ postType === 'post' ? 'posts' : postType === 'page' ? 'pages' : postType;
606
+
607
+ // Single-post lookup by ID (mirrors WP_Query's `p` argument) — hits the REST
608
+ // single-resource route directly instead of the list route, bypassing every
609
+ // other filter/sort/pagination option, matching WP_Query's own precedence.
610
+ const isSinglePostLookup = p !== undefined && p !== null && p !== '';
611
+ const useGeneratedQuery = Boolean(queryId) && !isSinglePostLookup;
612
+
613
+ if (
614
+ !isSinglePostLookup &&
615
+ !queryId &&
616
+ (taxQuery.length > 0 || metaQuery.length > 0)
617
+ ) {
618
+ throw new Error(
619
+ 'useWpQuery with taxQuery or metaQuery requires a stable queryId in production.',
620
+ );
621
+ }
622
+
623
+ const params = new URLSearchParams();
624
+ if (isSinglePostLookup) {
625
+ params.append('_embed', '1');
626
+ } else if (useGeneratedQuery) {
627
+ params.append('page', String(page));
628
+ if (s) params.append('search', s);
629
+ taxQuery.forEach((query: any, index: number) => {
630
+ params.append(`tax_${index}`, JSON.stringify(query.terms));
631
+ });
632
+ metaQuery.forEach((query: any, index: number) => {
633
+ if (query.value !== undefined) {
634
+ params.append(`meta_${index}`, JSON.stringify(query.value));
635
+ }
636
+ });
637
+ } else {
638
+ params.append('per_page', String(postsPerPage));
639
+ params.append('page', String(page));
640
+ params.append('_embed', '1');
641
+ if (s) {
642
+ params.append('search', s);
643
+ }
644
+ if (orderby) {
645
+ params.append('orderby', orderby === 'date' ? 'date' : orderby);
646
+ }
647
+ if (order) {
648
+ params.append('order', order.toLowerCase());
649
+ }
650
+ if (categoryName) {
651
+ params.append('category_name', categoryName);
652
+ }
653
+ }
654
+
655
+ // Polylang multi-language query support
656
+ const currentLang =
657
+ (window as any).forgeWpLocale ||
658
+ (window as any).forgeWpTranslations?.currentLanguage;
659
+ if (currentLang) {
660
+ params.append('lang', currentLang);
661
+ }
662
+
663
+ const apiBase =
664
+ (typeof window !== 'undefined' && (window as any).FORGEWP_API_URL) ||
665
+ (import.meta as any).env?.VITE_WP_API_URL ||
666
+ (typeof (globalThis as any).process !== 'undefined' &&
667
+ (globalThis as any).process.env &&
668
+ ((globalThis as any).process.env.NEXT_PUBLIC_WP_API_URL ||
669
+ (globalThis as any).process.env.WP_API_URL)) ||
670
+ (() => {
671
+ const homeUrl =
672
+ (window as any).forgeWpHydration?.siteSettings?.options?.home || '';
673
+ if (homeUrl) {
674
+ try {
675
+ return new URL(homeUrl).pathname.replace(/\/$/, '');
676
+ } catch (e) {}
677
+ }
678
+ return '';
679
+ })();
680
+ const cleanQueryId = String(queryId)
681
+ .toLowerCase()
682
+ .replace(/[^a-z0-9]+/g, '-')
683
+ .replace(/(^-|-$)/g, '');
684
+ const fetchUrl = useGeneratedQuery
685
+ ? `${apiBase}/wp-json/forgewp/v1/query-${cleanQueryId}?${params.toString()}`
686
+ : isSinglePostLookup
687
+ ? `${apiBase}/wp-json/wp/v2/${endpoint}/${p}?${params.toString()}`
688
+ : `${apiBase}/wp-json/wp/v2/${endpoint}?${params.toString()}`;
689
+ console.log(`[useWpQuery] Fetching CPT "${postType}" from URL:`, fetchUrl);
690
+
691
+ const headers: Record<string, string> = {};
692
+ if (typeof window !== 'undefined') {
693
+ const token = window.localStorage.getItem('forgewp_jwt_token');
694
+ if (token) {
695
+ headers['Authorization'] = `Bearer ${token}`;
696
+ }
697
+ }
698
+
699
+ const response = await fetch(fetchUrl, { headers });
700
+ if (isSinglePostLookup && !response.ok) {
701
+ // Selected post no longer exists / isn't publicly visible (deleted, unpublished,
702
+ // permissions) — resolve to an empty result instead of throwing, so callers
703
+ // (e.g. a "spotlight post" section) can fall back gracefully.
704
+ return { posts: [], hasMore: false, total: 0, totalPages: 1 };
705
+ }
706
+ if (!response.ok) {
707
+ throw new Error(
708
+ `WordPress API returned ${response.status}: ${response.statusText}`,
709
+ );
710
+ }
711
+
712
+ const rawData = await response.json();
713
+ const data = isSinglePostLookup
714
+ ? [rawData]
715
+ : useGeneratedQuery
716
+ ? rawData.posts
717
+ : rawData;
718
+ if (!Array.isArray(data)) {
719
+ throw new Error('Invalid response format from WordPress API');
720
+ }
721
+ console.log(
722
+ `[useWpQuery] Successfully loaded ${data.length} items for CPT "${postType}"`,
723
+ );
724
+
725
+ const cleanHtml = (html: string) => {
726
+ if (!html) return '';
727
+ return decodeHtmlEntities(html.replace(/<\/?[^>]+(>|$)/g, '')).trim();
728
+ };
729
+
730
+ const mappedPosts: WpPost[] = data.map((wp: any) => {
731
+ let featuredImage =
732
+ typeof wp.featuredImage === 'string'
733
+ ? wp.featuredImage
734
+ : wp.featuredImage?.url ||
735
+ 'https://picsum.photos/seed/forgewp/1200/630';
736
+ if (
737
+ wp._embedded &&
738
+ wp._embedded['wp:featuredmedia'] &&
739
+ wp._embedded['wp:featuredmedia'][0]
740
+ ) {
741
+ const media = wp._embedded['wp:featuredmedia'][0];
742
+ featuredImage = media.source_url || featuredImage;
743
+ } else if (wp.featured_media_src_url) {
744
+ featuredImage = wp.featured_media_src_url;
745
+ }
746
+
747
+ const _terms: Record<string, any[]> = {};
748
+ if (wp._embedded && wp._embedded['wp:term']) {
749
+ for (const termGroup of wp._embedded['wp:term']) {
750
+ if (Array.isArray(termGroup) && termGroup.length > 0) {
751
+ const taxonomy = termGroup[0].taxonomy;
752
+ if (taxonomy) {
753
+ _terms[taxonomy] = termGroup.map((t: any) => ({
754
+ id: t.id,
755
+ slug: t.slug,
756
+ name:
757
+ typeof t.name === 'string' ? decodeHtmlEntities(t.name) : '',
758
+ }));
759
+ }
760
+ }
761
+ }
762
+ }
763
+
764
+ return {
765
+ id: wp.id ?? wp.ID,
766
+ title:
767
+ typeof wp.title === 'object'
768
+ ? decodeHtmlEntities(wp.title.rendered)
769
+ : decodeHtmlEntities(wp.title || ''),
770
+ excerpt:
771
+ typeof wp.excerpt === 'object'
772
+ ? cleanHtml(wp.excerpt.rendered)
773
+ : cleanHtml(wp.excerpt || ''),
774
+ content:
775
+ typeof wp.content === 'object' ? wp.content.rendered : wp.content || '',
776
+ date: wp.date
777
+ ? new Date(wp.date).toLocaleDateString(
778
+ currentLang === 'de' ? 'de-DE' : 'en-US',
779
+ {
780
+ year: 'numeric',
781
+ month: 'long',
782
+ day: 'numeric',
783
+ },
784
+ )
785
+ : '',
786
+ modified: wp.modified
787
+ ? new Date(wp.modified).toLocaleDateString(
788
+ currentLang === 'de' ? 'de-DE' : 'en-US',
789
+ {
790
+ year: 'numeric',
791
+ month: 'long',
792
+ day: 'numeric',
793
+ },
794
+ )
795
+ : '',
796
+ author:
797
+ wp._embedded && wp._embedded['author'] && wp._embedded['author'][0]
798
+ ? wp._embedded['author'][0].name
799
+ : 'Admin',
800
+ featuredImage,
801
+ permalink: wp.link || wp.permalink,
802
+ // ACF REST may return `[]` when no field group matches — never spread arrays into customFields.
803
+ customFields: {
804
+ ...(wp.acf && !Array.isArray(wp.acf) && typeof wp.acf === 'object'
805
+ ? wp.acf
806
+ : {}),
807
+ ...(wp.meta && !Array.isArray(wp.meta) && typeof wp.meta === 'object'
808
+ ? wp.meta
809
+ : {}),
810
+ },
811
+ _terms,
812
+ __postType: wp.type || wp.post_type || postType,
813
+ };
814
+ });
815
+
816
+ const totalPagesHeader = response.headers.get('X-WP-TotalPages');
817
+ const totalPages = useGeneratedQuery
818
+ ? Number(rawData.totalPages) || 1
819
+ : totalPagesHeader
820
+ ? parseInt(totalPagesHeader, 10)
821
+ : 1;
822
+
823
+ const totalHeader = response.headers.get('X-WP-Total');
824
+ const total = useGeneratedQuery
825
+ ? Number(rawData.total) || mappedPosts.length
826
+ : totalHeader
827
+ ? parseInt(totalHeader, 10)
828
+ : mappedPosts.length;
829
+
830
+ return {
831
+ posts: mappedPosts,
832
+ hasMore: page < totalPages && mappedPosts.length > 0,
833
+ total,
834
+ totalPages,
835
+ };
836
+ }
837
+
838
+ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
839
+ if (IS_DEV) {
840
+ return _useWpQuery(args);
841
+ }
842
+
843
+ // Node SSR (Compile-time)
844
+ if (
845
+ typeof window === 'undefined' ||
846
+ (typeof window !== 'undefined' && (window as any)._forgeWpCompileTime)
847
+ ) {
848
+ // In production WordPress themes, dynamic hydration islands should SSR in a loading state
849
+ // so that the initial page layout contains loading skeletons instead of developer's compile-time mock data.
850
+ return {
851
+ posts: [],
852
+ loading: true,
853
+ error: null,
854
+ hasMore: true,
855
+ totalPages: 1,
856
+ currentPage: 1,
857
+ loadMore: async () => {},
858
+ goToPage: (_n: number) => {},
859
+ refetch: async () => {},
860
+ };
861
+ }
862
+
863
+ // Browser (Hydration/Production Client)
864
+ const argsRef = React.useRef(args);
865
+ argsRef.current = args;
866
+
867
+ const {
868
+ postType = 'post',
869
+ postsPerPage = 10,
870
+ categoryName = '',
871
+ s = '',
872
+ paged = 1,
873
+ orderby = 'date',
874
+ order = 'DESC',
875
+ p,
876
+ } = args;
877
+
878
+ const queryKey = JSON.stringify({
879
+ queryId: args.queryId,
880
+ postType,
881
+ postsPerPage,
882
+ categoryName,
883
+ s,
884
+ paged,
885
+ orderby,
886
+ order,
887
+ p,
888
+ taxQuery: args.taxQuery,
889
+ metaQuery: args.metaQuery,
890
+ metaRelation: args.metaRelation,
891
+ });
892
+
893
+ let initialState = null;
894
+ if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
895
+ const stateEl = document.getElementById('forgewp-initial-state');
896
+ if (stateEl) {
897
+ try {
898
+ const parsed = JSON.parse(stateEl.textContent || '{}');
899
+ if (parsed.queries && parsed.queries[queryKey]) {
900
+ initialState = parsed.queries[queryKey];
901
+ // Pre-populate queryCache for page 1
902
+ const cacheKey = JSON.stringify({ ...argsRef.current, paged: paged });
903
+ if (!queryCache.has(cacheKey)) {
904
+ queryCache.set(cacheKey, {
905
+ posts: initialState.posts,
906
+ hasMore: initialState.hasMore,
907
+ total: initialState.total || initialState.posts.length,
908
+ });
909
+ }
910
+ }
911
+ } catch (e) {
912
+ console.warn('Failed to parse forgewp-initial-state:', e);
913
+ }
914
+ }
915
+ }
916
+
917
+ const [posts, setPosts] = React.useState<WpPost[]>(
918
+ initialState ? initialState.posts : [],
919
+ );
920
+ const [loading, setLoading] = React.useState(initialState ? false : true);
921
+ const [error, setError] = React.useState<string | null>(null);
922
+ const [currentPage, setCurrentPage] = React.useState(paged);
923
+ const [hasMore, setHasMore] = React.useState(
924
+ initialState ? initialState.hasMore : true,
925
+ );
926
+ const [totalPages, setTotalPages] = React.useState<number>(1);
927
+ const hydratedFromSsrRef = React.useRef(initialState ? true : false);
928
+ // 'append' = loadMore behaviour; 'replace' = goToPage behaviour
929
+ const pageModeRef = React.useRef<'append' | 'replace'>('replace');
930
+
931
+ const [prevQueryKey, setPrevQueryKey] = React.useState(queryKey);
932
+ if (prevQueryKey !== queryKey) {
933
+ setPrevQueryKey(queryKey);
934
+ setCurrentPage(1);
935
+ setPosts([]);
936
+ setHasMore(true);
937
+ pageModeRef.current = 'replace';
938
+ hydratedFromSsrRef.current = false;
939
+ }
940
+
941
+ const executeProdQuery = React.useCallback(
942
+ async (page: number) => {
943
+ const mode = pageModeRef.current;
944
+ // Consume the mode; subsequent calls revert to append (for loadMore)
945
+ pageModeRef.current = 'append';
946
+
947
+ const cacheKey = JSON.stringify({ ...argsRef.current, paged: page });
948
+ if (queryCache.has(cacheKey)) {
949
+ const cached = queryCache.get(cacheKey)!;
950
+ setPosts((prev: WpPost[]) => {
951
+ if (mode === 'append') {
952
+ const existingIds = new Set(prev.map((p: WpPost) => p.id));
953
+ const newPosts = cached.posts.filter(
954
+ (p: WpPost) => !existingIds.has(p.id),
955
+ );
956
+ return [...prev, ...newPosts];
957
+ }
958
+ return cached.posts;
959
+ });
960
+ setHasMore(cached.hasMore);
961
+ if ((cached as any).totalPages)
962
+ setTotalPages((cached as any).totalPages);
963
+ setError(null);
964
+ return;
965
+ }
966
+
967
+ setLoading(true);
968
+ try {
969
+ const {
970
+ posts: fetchedPosts,
971
+ hasMore: nextPageHasMore,
972
+ total: totalCount,
973
+ totalPages: tp,
974
+ } = await fetchWpApi(argsRef.current, page);
975
+ queryCache.set(cacheKey, {
976
+ posts: fetchedPosts,
977
+ hasMore: nextPageHasMore,
978
+ total: totalCount,
979
+ totalPages: tp,
980
+ });
981
+
982
+ setPosts((prev: WpPost[]) => {
983
+ if (mode === 'append') {
984
+ const existingIds = new Set(prev.map((p: WpPost) => p.id));
985
+ const newPosts = fetchedPosts.filter(
986
+ (p: WpPost) => !existingIds.has(p.id),
987
+ );
988
+ return [...prev, ...newPosts];
989
+ }
990
+ return fetchedPosts;
991
+ });
992
+ setHasMore(nextPageHasMore);
993
+ setTotalPages(tp);
994
+ setError(null);
995
+ } catch (err: any) {
996
+ setError(err.message || 'Failed to fetch from WordPress API');
997
+ } finally {
998
+ setLoading(false);
999
+ }
1000
+ },
1001
+ [queryKey],
1002
+ );
1003
+
1004
+ React.useEffect(() => {
1005
+ if (hydratedFromSsrRef.current) {
1006
+ hydratedFromSsrRef.current = false;
1007
+ return;
1008
+ }
1009
+ executeProdQuery(currentPage);
1010
+ }, [executeProdQuery, currentPage]);
1011
+
1012
+ const querySelector = React.useCallback((params: URLSearchParams) => {
1013
+ const target = { ...argsRef.current };
1014
+ if (params.has('q') || params.has('s')) {
1015
+ target.s = params.get('q') || params.get('s') || '';
1016
+ }
1017
+ if (params.has('category')) {
1018
+ target.categoryName = params.get('category') || '';
1019
+ }
1020
+ return target;
1021
+ }, []);
1022
+
1023
+ React.useEffect(() => {
1024
+ if (typeof window === 'undefined') return;
1025
+ const item = {
1026
+ get args() {
1027
+ return argsRef.current;
1028
+ },
1029
+ querySelector,
1030
+ execute: async (targetArgs: any) => {
1031
+ const cacheKey = JSON.stringify({ ...targetArgs, paged: 1 });
1032
+ if (queryCache.has(cacheKey)) return;
1033
+ try {
1034
+ const res = await fetchWpApi(targetArgs, 1);
1035
+ queryCache.set(cacheKey, res);
1036
+ } catch (e) {}
1037
+ },
1038
+ };
1039
+ activeQueries.add(item);
1040
+ return () => {
1041
+ activeQueries.delete(item);
1042
+ };
1043
+ }, [querySelector]);
1044
+
1045
+ const loadMore = React.useCallback(async () => {
1046
+ if (loading || !hasMore) return;
1047
+ pageModeRef.current = 'append';
1048
+ const nextPage = currentPage + 1;
1049
+ setCurrentPage(nextPage);
1050
+ }, [currentPage, loading, hasMore]);
1051
+
1052
+ const goToPage = React.useCallback(
1053
+ (targetPage: number) => {
1054
+ if (loading) return;
1055
+ if (targetPage < 1 || targetPage > totalPages) return;
1056
+ pageModeRef.current = 'replace';
1057
+ setPosts([]);
1058
+ setCurrentPage(targetPage);
1059
+ },
1060
+ [loading, totalPages],
1061
+ );
1062
+
1063
+ const refetch = React.useCallback(async () => {
1064
+ pageModeRef.current = 'replace';
1065
+ setCurrentPage(1);
1066
+ executeProdQuery(1);
1067
+ }, [executeProdQuery]);
1068
+
1069
+ return {
1070
+ posts,
1071
+ loading,
1072
+ error,
1073
+ hasMore,
1074
+ totalPages,
1075
+ currentPage,
1076
+ loadMore,
1077
+ goToPage,
1078
+ refetch,
1079
+ };
1080
+ }
1081
+
1082
+ export function useWpCategories(): string {
1083
+ if (IS_DEV) return '<a href="#">Technology</a>, <a href="#">Design</a>';
1084
+ return '__FORGEWP_THE_CATEGORY_LIST__';
1085
+ }
1086
+ export function useWpArchiveTitle(): string {
1087
+ if (IS_DEV) return 'Category: Technology';
1088
+ return '__FORGEWP_THE_ARCHIVE_TITLE__';
1089
+ }
1090
+
1091
+ export function useWpTaxonomyList(taxonomy: string, defaultValue = ''): string {
1092
+ if (IS_DEV) {
1093
+ const post = React.useContext(WpPostContext);
1094
+ const terms = (post as any)?._terms?.[taxonomy];
1095
+ if (Array.isArray(terms) && terms.length > 0) {
1096
+ return terms.map((t: any) => t.name).join(', ');
1097
+ }
1098
+ return defaultValue || `[taxonomy: ${taxonomy}]`;
1099
+ }
1100
+ return `__FORGEWP_TAXONOMY_LIST_${taxonomy}__`;
1101
+ }
1102
+
1103
+ // ── useWpTerms — fetch all terms for a given taxonomy ─────────────────────────
1104
+ // Dev: reads `_taxonomy_<name>` key from mock-data.json
1105
+ // SSR: returns [] synchronously (Hydrate island loads in browser)
1106
+ // Prod: fetches /wp-json/wp/v2/<taxonomy>?per_page=100
1107
+
1108
+ export interface WpTerm {
1109
+ id: number;
1110
+ name: string;
1111
+ slug: string;
1112
+ description: string;
1113
+ count: number;
1114
+ meta: Record<string, any>;
1115
+ }
1116
+
1117
+ export function useWpTerms(taxonomy: string): {
1118
+ terms: WpTerm[];
1119
+ loading: boolean;
1120
+ error: string | null;
1121
+ } {
1122
+ if (IS_DEV) {
1123
+ const raw: any[] =
1124
+ (getDevMockPosts() as any)?.[`_taxonomy_${taxonomy}`] || [];
1125
+ const terms: WpTerm[] = raw.map((t: any) => ({
1126
+ id: t.id ?? 0,
1127
+ name: t.name ?? '',
1128
+ slug: t.slug ?? '',
1129
+ description: t.description ?? '',
1130
+ count: t.count ?? 0,
1131
+ meta: t.meta ?? {},
1132
+ }));
1133
+ return { terms, loading: false, error: null };
1134
+ }
1135
+
1136
+ // Node SSR — return empty; Hydrate wrapper will load in browser
1137
+ if (typeof window === 'undefined') {
1138
+ return { terms: [], loading: true, error: null };
1139
+ }
1140
+
1141
+ // Browser production — live WP REST API fetch
1142
+ const [terms, setTerms] = React.useState<WpTerm[]>([]);
1143
+ const [loading, setLoading] = React.useState(true);
1144
+ const [error, setError] = React.useState<string | null>(null);
1145
+
1146
+ React.useEffect(() => {
1147
+ let cancelled = false;
1148
+ const endpoint =
1149
+ taxonomy === 'category'
1150
+ ? 'categories'
1151
+ : taxonomy === 'post_tag'
1152
+ ? 'tags'
1153
+ : taxonomy;
1154
+ const apiBase =
1155
+ (typeof window !== 'undefined' && (window as any).FORGEWP_API_URL) ||
1156
+ (import.meta as any).env?.VITE_WP_API_URL ||
1157
+ (typeof (globalThis as any).process !== 'undefined' &&
1158
+ (globalThis as any).process.env &&
1159
+ ((globalThis as any).process.env.NEXT_PUBLIC_WP_API_URL ||
1160
+ (globalThis as any).process.env.WP_API_URL)) ||
1161
+ (() => {
1162
+ const homeUrl =
1163
+ (window as any).forgeWpHydration?.siteSettings?.options?.home || '';
1164
+ if (homeUrl) {
1165
+ try {
1166
+ return new URL(homeUrl).pathname.replace(/\/$/, '');
1167
+ } catch (e) {}
1168
+ }
1169
+ return '';
1170
+ })();
1171
+ const currentLang =
1172
+ (window as any).forgeWpLocale ||
1173
+ (window as any).forgeWpTranslations?.currentLanguage;
1174
+ const langParam = currentLang ? `&lang=${currentLang}` : '';
1175
+ const fetchUrl = `${apiBase}/wp-json/wp/v2/${endpoint}?per_page=100&_fields=id,name,slug,description,count,acf,meta${langParam}`;
1176
+ console.log(
1177
+ `[useWpTerms] Fetching taxonomy "${taxonomy}" from URL:`,
1178
+ fetchUrl,
1179
+ );
1180
+
1181
+ const headers: Record<string, string> = {};
1182
+ if (typeof window !== 'undefined') {
1183
+ const token = window.localStorage.getItem('forgewp_jwt_token');
1184
+ if (token) {
1185
+ headers['Authorization'] = `Bearer ${token}`;
1186
+ }
1187
+ }
1188
+
1189
+ fetch(fetchUrl, { headers })
1190
+ .then((res) => {
1191
+ if (!res.ok) throw new Error(`WP Terms API ${taxonomy}: ${res.status}`);
1192
+ return res.json();
1193
+ })
1194
+ .then((data: any[]) => {
1195
+ if (cancelled) return;
1196
+ console.log(
1197
+ `[useWpTerms] Successfully loaded ${data.length} terms for taxonomy "${taxonomy}"`,
1198
+ );
1199
+ setTerms(
1200
+ data.map((t) => ({
1201
+ id: t.id,
1202
+ name: typeof t.name === 'string' ? decodeHtmlEntities(t.name) : '',
1203
+ slug: t.slug || '',
1204
+ description: t.description || '',
1205
+ count: t.count || 0,
1206
+ meta: { ...(t.acf || {}), ...(t.meta || {}) },
1207
+ })),
1208
+ );
1209
+ setError(null);
1210
+ })
1211
+ .catch((err: any) => {
1212
+ if (!cancelled) {
1213
+ console.error(
1214
+ `[useWpTerms] Error loading taxonomy "${taxonomy}":`,
1215
+ err,
1216
+ );
1217
+ setError(err.message || `Failed to load ${taxonomy} terms`);
1218
+ }
1219
+ })
1220
+ .finally(() => {
1221
+ if (!cancelled) setLoading(false);
1222
+ });
1223
+ return () => {
1224
+ cancelled = true;
1225
+ };
1226
+ }, [taxonomy]);
1227
+
1228
+ return { terms, loading, error };
1229
+ }
1230
+
1231
+ // ── WpQueryLoop — data bridge wraps @forgewp/react with mock data ─────────────
1232
+
1233
+ export function WpQueryLoop({
1234
+ postType = 'post',
1235
+ postsPerPage = 3,
1236
+ categoryName = '',
1237
+ orderby = '',
1238
+ order = '',
1239
+ children,
1240
+ }: WpQueryLoopProps & { orderby?: string; order?: string }) {
1241
+ if (IS_DEV) {
1242
+ let posts = (getDevMockPosts() as any)?.[postType] || [];
1243
+ if (orderby === 'rand') {
1244
+ posts = [...posts].sort(() => Math.random() - 0.5);
1245
+ } else if (orderby === 'title') {
1246
+ posts = [...posts].sort((a, b) => {
1247
+ const titleA = a.title || '';
1248
+ const titleB = b.title || '';
1249
+ return order === 'ASC'
1250
+ ? titleA.localeCompare(titleB)
1251
+ : titleB.localeCompare(titleA);
1252
+ });
1253
+ } else if (orderby === 'date') {
1254
+ posts = [...posts].sort((a, b) => {
1255
+ const dateA = new Date(a.date || 0).getTime();
1256
+ const dateB = new Date(b.date || 0).getTime();
1257
+ return order === 'ASC' ? dateA - dateB : dateB - dateA;
1258
+ });
1259
+ }
1260
+ return (
1261
+ <_WpQueryLoop
1262
+ posts={posts}
1263
+ postType={postType}
1264
+ postsPerPage={postsPerPage}
1265
+ categoryName={categoryName}
1266
+ >
1267
+ {children}
1268
+ </_WpQueryLoop>
1269
+ );
1270
+ }
1271
+
1272
+ // Production: compiler transforms these custom elements into WordPress loop PHP
1273
+ return (
1274
+ <>
1275
+ {/* @ts-ignore */}
1276
+ <forgewp-query-loop-start
1277
+ postType={postType}
1278
+ postsPerPage={postsPerPage}
1279
+ categoryName={categoryName}
1280
+ orderby={orderby}
1281
+ order={order}
1282
+ />
1283
+ {children}
1284
+ {/* @ts-ignore */}
1285
+ <forgewp-query-loop-end />
1286
+ </>
1287
+ );
1288
+ }
1289
+
1290
+ // ── WpLoop — simple all-posts loop (no postType arg) ─────────────────────────
1291
+
1292
+ export function WpLoop({ children }: { children: React.ReactNode }) {
1293
+ if (IS_DEV) {
1294
+ const posts = (getDevMockPosts() as any)?.post || [];
1295
+ return <_WpQueryLoop posts={posts}>{children}</_WpQueryLoop>;
1296
+ }
1297
+ return (
1298
+ <>
1299
+ {/* @ts-ignore */}
1300
+ <forgewp-loop-start />
1301
+ {children}
1302
+ {/* @ts-ignore */}
1303
+ <forgewp-loop-end />
1304
+ </>
1305
+ );
1306
+ }
1307
+
1308
+ // ── useWpMenu ────────────────────────────────────────────────────────────────
1309
+
1310
+ export function useWpMenu(location: string = 'primary'): {
1311
+ items: WpMenuItem[];
1312
+ loading: boolean;
1313
+ } {
1314
+ if (IS_DEV) {
1315
+ return _useWpMenu(location);
1316
+ }
1317
+
1318
+ // Node SSR (Compile-time)
1319
+ if (typeof window === 'undefined' || (window as any)._forgeWpCompileTime) {
1320
+ const items = (menusData as any)?.[location] || [];
1321
+ return { items: normalizeRuntimeMenuItems(items), loading: false };
1322
+ }
1323
+
1324
+ // Browser production hydration client
1325
+ const items =
1326
+ (window as any).forgeWpHydration?.menus?.[location] ||
1327
+ (menusData as any)?.[location] ||
1328
+ [];
1329
+ return { items: normalizeRuntimeMenuItems(items), loading: false };
1330
+ }
1331
+
1332
+ function normalizeRuntimeMenuItems(items: any[]): any[] {
1333
+ if (!Array.isArray(items)) return [];
1334
+ return items.map((item) => ({
1335
+ ...item,
1336
+ id: item?.id == null || item.id === '' ? item?.id : String(item.id),
1337
+ children: item?.children
1338
+ ? normalizeRuntimeMenuItems(item.children)
1339
+ : item?.children,
1340
+ }));
1341
+ }
1342
+
1343
+ // ── WpMenu — data bridge wraps @forgewp/react with menus.json ────────────────
1344
+
1345
+ export function WpMenu({
1346
+ location = 'primary',
1347
+ className = '',
1348
+ linkClassName = '',
1349
+ }: WpMenuProps) {
1350
+ const { items } = useWpMenu(location);
1351
+
1352
+ if (IS_DEV) {
1353
+ return (
1354
+ <_WpMenu
1355
+ items={items}
1356
+ location={location}
1357
+ className={className}
1358
+ linkClassName={linkClassName}
1359
+ />
1360
+ );
1361
+ }
1362
+
1363
+ // Production browser hydration client: render menu items from localized PHP data
1364
+ if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
1365
+ if (items.length > 0) {
1366
+ return (
1367
+ <nav className={className}>
1368
+ {items.map((item: any, idx: number) => (
1369
+ <a
1370
+ key={idx}
1371
+ href={item.url}
1372
+ className={linkClassName}
1373
+ >
1374
+ {item.title}
1375
+ </a>
1376
+ ))}
1377
+ </nav>
1378
+ );
1379
+ }
1380
+
1381
+ // Server-matching fallback nav to guarantee zero hydration mismatch
1382
+ return (
1383
+ <nav className={className}>
1384
+ <a
1385
+ href='/'
1386
+ className={linkClassName}
1387
+ >
1388
+ Home
1389
+ </a>
1390
+ </nav>
1391
+ );
1392
+ }
1393
+
1394
+ // Production: compiler transforms this into wp_nav_menu()
1395
+ return (
1396
+ // @ts-ignore
1397
+ <forgewp-menu
1398
+ location={location}
1399
+ className={className}
1400
+ linkClassName={linkClassName}
1401
+ />
1402
+ );
1403
+ }
1404
+
1405
+ // ── BlockArea ────────────────────────────────────────────────────────────────
1406
+ export function BlockArea(props: BlockAreaProps) {
1407
+ if (IS_DECOUPLED) {
1408
+ return <_BlockArea {...props} />;
1409
+ }
1410
+ return (
1411
+ // @ts-ignore
1412
+ <forgewp-block-area name={props.name} />
1413
+ );
1414
+ }
1415
+
1416
+ // ── WpShortcode ──────────────────────────────────────────────────────────────
1417
+ export function WpShortcode({ code }: WpShortcodeProps) {
1418
+ if (IS_DECOUPLED) {
1419
+ return <_WpShortcode code={code} />;
1420
+ }
1421
+ return (
1422
+ // @ts-ignore
1423
+ <forgewp-shortcode code={code} />
1424
+ );
1425
+ }
1426
+
1427
+ export function WpHead(props: WpHeadProps) {
1428
+ if (IS_DECOUPLED) {
1429
+ return <_WpHead {...props} />;
1430
+ }
1431
+ return (
1432
+ // @ts-ignore
1433
+ <forgewp-head
1434
+ data-title={props.title}
1435
+ data-description={props.description}
1436
+ data-keywords={props.keywords}
1437
+ data-og-title={props.ogTitle}
1438
+ data-og-description={props.ogDescription}
1439
+ data-og-image={props.ogImage}
1440
+ data-og-type={props.ogType}
1441
+ data-twitter-card={props.twitterCard}
1442
+ data-twitter-creator={props.twitterCreator}
1443
+ data-canonical={props.canonical}
1444
+ />
1445
+ );
1446
+ }
1447
+ export type {
1448
+ WpHeadProps,
1449
+ WpImageProps,
1450
+ WpAttachment,
1451
+ WpRepeaterProps,
1452
+ WpIconProps,
1453
+ };
1454
+
1455
+ export function WpImage(props: WpImageProps) {
1456
+ if (IS_DECOUPLED) {
1457
+ const attachments = (getDevMockPosts() as any)?.attachment || [];
1458
+ return (
1459
+ <_WpImage
1460
+ {...props}
1461
+ attachments={attachments}
1462
+ />
1463
+ );
1464
+ }
1465
+ return <_WpImage {...props} />;
1466
+ }
1467
+
1468
+ export function useWpI18n() {
1469
+ const getTranslatedText = (text: string) => {
1470
+ if (typeof window === 'undefined') {
1471
+ return text;
1472
+ }
1473
+ const currentLang =
1474
+ (window as any).forgeWpLocale ||
1475
+ (window as any).forgeWpTranslations?.currentLanguage ||
1476
+ 'de';
1477
+ const dict = (window as any).forgeWpTranslations?.translations;
1478
+
1479
+ if (dict) {
1480
+ // 1. Nested dictionary format: { de: { ... }, en: { ... } }
1481
+ if (dict[currentLang] && typeof dict[currentLang][text] !== 'undefined') {
1482
+ return dict[currentLang][text];
1483
+ }
1484
+ // 2. Flat enqueued active locale format: { 'Kontakt': 'Kontakt' }
1485
+ if (typeof dict[text] !== 'undefined') {
1486
+ return dict[text];
1487
+ }
1488
+ }
1489
+ return text;
1490
+ };
1491
+
1492
+ if (IS_DECOUPLED) {
1493
+ return {
1494
+ __: (text: string) => {
1495
+ if (typeof window === 'undefined') {
1496
+ return text;
1497
+ }
1498
+ const pathname = window.location.pathname;
1499
+ const translations = translationsData || {};
1500
+ const languages =
1501
+ Object.keys(translations).length > 0
1502
+ ? Object.keys(translations)
1503
+ : ['de', 'en'];
1504
+ const defaultLanguage = languages[0] || 'de';
1505
+
1506
+ const matchedLang = languages.find((lang) => {
1507
+ if (lang === defaultLanguage) return false;
1508
+ return pathname.startsWith(`/${lang}/`) || pathname === `/${lang}`;
1509
+ });
1510
+ const currentLang = matchedLang || defaultLanguage;
1511
+
1512
+ const dict = (translationsData as any)?.[currentLang];
1513
+ if (dict && typeof dict[text] !== 'undefined') {
1514
+ return dict[text];
1515
+ }
1516
+ return text;
1517
+ },
1518
+ };
1519
+ }
1520
+ // Node SSR (Compile-time): return the token so the compiler can perform string replacement
1521
+ if (typeof window === 'undefined' || (window as any)._forgeWpCompileTime) {
1522
+ return {
1523
+ __: (text: string) => `__FORGEWP_I18N_${text}__`,
1524
+ };
1525
+ }
1526
+ // Production Browser (Hydration & Client-side rendering):
1527
+ return {
1528
+ __: getTranslatedText,
1529
+ };
1530
+ }
1531
+ const locationListeners = new Set<
1532
+ (payload: { pathname: string; search: string }) => void
1533
+ >();
1534
+ let popstateBound = false;
1535
+
1536
+ function handleLocationUpdate() {
1537
+ const payload = {
1538
+ pathname: typeof window !== 'undefined' ? window.location.pathname : '/',
1539
+ search: typeof window !== 'undefined' ? window.location.search : '',
1540
+ };
1541
+ locationListeners.forEach((listener) => listener(payload));
1542
+ }
1543
+
1544
+ export function subscribeToLocation(
1545
+ listener: (payload: { pathname: string; search: string }) => void,
1546
+ ) {
1547
+ locationListeners.add(listener);
1548
+ if (typeof window !== 'undefined' && !popstateBound) {
1549
+ window.addEventListener('popstate', handleLocationUpdate);
1550
+ popstateBound = true;
1551
+ }
1552
+ return () => {
1553
+ locationListeners.delete(listener);
1554
+ if (
1555
+ locationListeners.size === 0 &&
1556
+ typeof window !== 'undefined' &&
1557
+ popstateBound
1558
+ ) {
1559
+ window.removeEventListener('popstate', handleLocationUpdate);
1560
+ popstateBound = false;
1561
+ }
1562
+ };
1563
+ }
1564
+
1565
+ export function navigateTo(to: string) {
1566
+ if (typeof window === 'undefined') return;
1567
+ try {
1568
+ const targetUrl = new URL(to, window.location.href);
1569
+ if (targetUrl.pathname === window.location.pathname) {
1570
+ window.history.pushState(null, '', to);
1571
+ handleLocationUpdate();
1572
+ } else {
1573
+ window.location.href = to;
1574
+ }
1575
+ } catch (e) {
1576
+ window.location.href = to;
1577
+ }
1578
+ }
1579
+
1580
+ export function useWpPrefetch() {
1581
+ if (IS_DECOUPLED) {
1582
+ return _useWpPrefetch();
1583
+ }
1584
+ const prefetch = React.useCallback((to: string) => {
1585
+ if (typeof window === 'undefined') return;
1586
+ if (prefetchTimeout) {
1587
+ clearTimeout(prefetchTimeout);
1588
+ }
1589
+ prefetchTimeout = setTimeout(() => {
1590
+ try {
1591
+ const url = new URL(to, window.location.href);
1592
+ const params = url.searchParams;
1593
+ activeQueries.forEach((item) => {
1594
+ const targetArgs = item.querySelector(params);
1595
+ item.execute(targetArgs);
1596
+ });
1597
+ } catch (e) {
1598
+ console.warn('[prefetch] Failed to parse target URL:', to, e);
1599
+ }
1600
+ }, 80);
1601
+ }, []);
1602
+ return prefetch;
1603
+ }
1604
+
1605
+ export function useWpSearchParams(): URLSearchParams {
1606
+ const search = useSearch();
1607
+ return React.useMemo(() => new URLSearchParams(search), [search]);
1608
+ }
1609
+
1610
+ export function useWpLanguage() {
1611
+ if (IS_DECOUPLED) {
1612
+ const translations = translationsData || {};
1613
+ const languages =
1614
+ Object.keys(translations).length > 0
1615
+ ? Object.keys(translations)
1616
+ : ['de', 'en'];
1617
+ const defaultLanguage = languages[0] || 'de';
1618
+
1619
+ const pathname =
1620
+ typeof window !== 'undefined' ? window.location.pathname : '/';
1621
+ // Find if the path starts with one of the non-default languages, e.g. "/en" or "/en/"
1622
+ const matchedLang = languages.find((lang) => {
1623
+ if (lang === defaultLanguage) return false;
1624
+ return pathname.startsWith(`/${lang}/`) || pathname === `/${lang}`;
1625
+ });
1626
+ const currentLanguage = matchedLang || defaultLanguage;
1627
+
1628
+ // Generate URLs dynamically
1629
+ const urls: Record<string, string> = {};
1630
+ const homeUrls: Record<string, string> = {};
1631
+ languages.forEach((lang) => {
1632
+ const url = lang === defaultLanguage ? '/' : `/${lang}/`;
1633
+ urls[lang] = url;
1634
+ homeUrls[lang] = url;
1635
+ });
1636
+
1637
+ const homeUrl = homeUrls[currentLanguage] || '/';
1638
+
1639
+ const switchLanguage = React.useCallback(
1640
+ (lang: string) => {
1641
+ if (typeof window !== 'undefined') {
1642
+ const search = window.location.search;
1643
+ const base =
1644
+ urls[lang] || (lang === defaultLanguage ? '/' : `/${lang}/`);
1645
+ const separator = base.includes('?') ? '&' : '?';
1646
+ window.location.href = search
1647
+ ? base + separator + search.substring(1)
1648
+ : base;
1649
+ }
1650
+ },
1651
+ [urls, defaultLanguage],
1652
+ );
1653
+
1654
+ return {
1655
+ currentLanguage,
1656
+ languages,
1657
+ urls,
1658
+ homeUrls,
1659
+ homeUrl,
1660
+ switchLanguage,
1661
+ };
1662
+ }
1663
+
1664
+ const translations =
1665
+ typeof window !== 'undefined' ? (window as any).forgeWpTranslations : null;
1666
+
1667
+ // Dynamic current language slug enqueued by WordPress
1668
+ const currentLanguage = translations?.currentLanguage || 'de';
1669
+
1670
+ // Dynamic dictionary mapping active language slugs to translation counterpart URLs
1671
+ const urls: Record<string, string> = translations?.urls || { de: '/' };
1672
+
1673
+ // Dynamic dictionary mapping active language slugs to home page URLs
1674
+ const homeUrls: Record<string, string> = translations?.homeUrls || {
1675
+ de: '/',
1676
+ };
1677
+ const homeUrl = homeUrls[currentLanguage] || '/';
1678
+
1679
+ // Dynamic list of active language slugs enqueued on the site
1680
+ const languages = React.useMemo(() => Object.keys(urls), [urls]);
1681
+
1682
+ // Redirection helper to switch safely between languages
1683
+ const switchLanguage = React.useCallback(
1684
+ (lang: string) => {
1685
+ if (typeof window !== 'undefined') {
1686
+ const search = window.location.search;
1687
+ const base =
1688
+ urls && urls[lang] ? urls[lang] : lang === 'de' ? '/' : `/${lang}/`;
1689
+ const separator = base.includes('?') ? '&' : '?';
1690
+ window.location.href = search
1691
+ ? base + separator + search.substring(1)
1692
+ : base;
1693
+ }
1694
+ },
1695
+ [urls],
1696
+ );
1697
+
1698
+ return {
1699
+ currentLanguage,
1700
+ languages,
1701
+ urls,
1702
+ homeUrls,
1703
+ homeUrl,
1704
+ switchLanguage,
1705
+ };
1706
+ }
1707
+
1708
+ // ── Compiler custom element JSX declarations ──────────────────────────────────
1709
+
1710
+ declare global {
1711
+ namespace React {
1712
+ namespace JSX {
1713
+ interface IntrinsicElements {
1714
+ 'forgewp-menu': React.DetailedHTMLProps<
1715
+ React.HTMLAttributes<HTMLElement> & {
1716
+ location?: 'primary' | 'footer' | 'sidebar' | string;
1717
+ linkClassName?: string;
1718
+ },
1719
+ HTMLElement
1720
+ >;
1721
+ 'forgewp-query-loop-start': React.DetailedHTMLProps<
1722
+ React.HTMLAttributes<HTMLElement> & {
1723
+ postType?: string;
1724
+ postsPerPage?: number;
1725
+ categoryName?: string;
1726
+ orderby?: string;
1727
+ order?: string;
1728
+ },
1729
+ HTMLElement
1730
+ >;
1731
+ 'forgewp-query-loop-end': React.DetailedHTMLProps<
1732
+ React.HTMLAttributes<HTMLElement>,
1733
+ HTMLElement
1734
+ >;
1735
+ 'forgewp-loop-start': React.DetailedHTMLProps<
1736
+ React.HTMLAttributes<HTMLElement>,
1737
+ HTMLElement
1738
+ >;
1739
+ 'forgewp-loop-end': React.DetailedHTMLProps<
1740
+ React.HTMLAttributes<HTMLElement>,
1741
+ HTMLElement
1742
+ >;
1743
+ 'forgewp-shortcode': React.DetailedHTMLProps<
1744
+ React.HTMLAttributes<HTMLElement> & {
1745
+ code?: string;
1746
+ },
1747
+ HTMLElement
1748
+ >;
1749
+ 'forgewp-head': React.DetailedHTMLProps<
1750
+ React.HTMLAttributes<HTMLElement> & {
1751
+ 'data-title'?: string;
1752
+ 'data-description'?: string;
1753
+ 'data-keywords'?: string;
1754
+ 'data-og-title'?: string;
1755
+ 'data-og-description'?: string;
1756
+ 'data-og-image'?: string;
1757
+ 'data-og-type'?: string;
1758
+ 'data-twitter-card'?: string;
1759
+ 'data-twitter-creator'?: string;
1760
+ 'data-canonical'?: string;
1761
+ },
1762
+ HTMLElement
1763
+ >;
1764
+ 'forgewp-image': React.DetailedHTMLProps<
1765
+ React.HTMLAttributes<HTMLElement> & {
1766
+ 'data-id'?: string;
1767
+ 'data-field'?: string;
1768
+ 'data-size'?: string;
1769
+ 'data-class-name'?: string;
1770
+ 'data-alt'?: string;
1771
+ },
1772
+ HTMLElement
1773
+ >;
1774
+ 'forgewp-block-area': React.DetailedHTMLProps<
1775
+ React.HTMLAttributes<HTMLElement> & {
1776
+ name?: string;
1777
+ },
1778
+ HTMLElement
1779
+ >;
1780
+ 'forgewp-repeater-start': React.DetailedHTMLProps<
1781
+ React.HTMLAttributes<HTMLElement> & {
1782
+ name?: string;
1783
+ subfields?: string;
1784
+ },
1785
+ HTMLElement
1786
+ >;
1787
+ 'forgewp-repeater-end': React.DetailedHTMLProps<
1788
+ React.HTMLAttributes<HTMLElement>,
1789
+ HTMLElement
1790
+ >;
1791
+ 'forgewp-icon-placeholder': React.DetailedHTMLProps<
1792
+ React.HTMLAttributes<HTMLElement> & {
1793
+ name?: string;
1794
+ provider?: string;
1795
+ class?: string;
1796
+ },
1797
+ HTMLElement
1798
+ >;
1799
+ 'forgewp-auth-gate-start': React.DetailedHTMLProps<
1800
+ React.HTMLAttributes<HTMLElement>,
1801
+ HTMLElement
1802
+ >;
1803
+ 'forgewp-auth-gate-fallback': React.DetailedHTMLProps<
1804
+ React.HTMLAttributes<HTMLElement>,
1805
+ HTMLElement
1806
+ >;
1807
+ 'forgewp-auth-gate-end': React.DetailedHTMLProps<
1808
+ React.HTMLAttributes<HTMLElement>,
1809
+ HTMLElement
1810
+ >;
1811
+ 'forgewp-capability-gate-start': React.DetailedHTMLProps<
1812
+ React.HTMLAttributes<HTMLElement> & {
1813
+ allowed?: string;
1814
+ },
1815
+ HTMLElement
1816
+ >;
1817
+ 'forgewp-capability-gate-fallback': React.DetailedHTMLProps<
1818
+ React.HTMLAttributes<HTMLElement>,
1819
+ HTMLElement
1820
+ >;
1821
+ 'forgewp-capability-gate-end': React.DetailedHTMLProps<
1822
+ React.HTMLAttributes<HTMLElement>,
1823
+ HTMLElement
1824
+ >;
1825
+ 'forgewp-require-auth': React.DetailedHTMLProps<
1826
+ React.HTMLAttributes<HTMLElement> & {
1827
+ allowed?: string;
1828
+ redirect?: string;
1829
+ },
1830
+ HTMLElement
1831
+ >;
1832
+ }
1833
+ }
1834
+ }
1835
+ }