@forgewp/compiler 0.4.3 → 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.
- package/README.md +59 -0
- package/bin/add.js +20 -14
- package/bin/cli.js +145 -70
- package/bin/doctor.js +21 -12
- package/bin/export.js +69 -20
- package/bin/fresh.js +5 -0
- package/bin/i18n-extract.js +3 -10
- package/bin/i18n-translate.js +15 -24
- package/bin/make-block.js +13 -0
- package/bin/make-editable.js +166 -0
- package/bin/make-form.js +131 -0
- package/bin/make-loop.js +40 -43
- package/bin/make-mail.js +27 -0
- package/bin/make-post-type.js +57 -29
- package/bin/make-sandbox.js +62 -11
- package/bin/make-section.js +221 -0
- package/bin/make-shell.js +375 -0
- package/bin/repair.js +14 -26
- package/bin/seed.js +119 -0
- package/bin/sync-routes.js +107 -85
- package/lib/adapters/html-adapter.js +5 -0
- package/lib/adapters/stub-adapter.js +4 -0
- package/lib/add-component.js +153 -92
- package/lib/asset-loader.js +313 -3
- package/lib/assets/asset-graph.js +432 -0
- package/lib/assets/asset-pipeline.js +125 -0
- package/lib/assets/diagnostics-report.js +345 -0
- package/lib/assets/external-fetcher.js +173 -0
- package/lib/assets/font-orchestrator.js +348 -0
- package/lib/assets/font-usage-scanner.js +242 -0
- package/lib/assets/image-optimizer.js +229 -0
- package/lib/assets/index.js +51 -0
- package/lib/assets/preload-generator.js +70 -0
- package/lib/assets/public-url.js +153 -0
- package/lib/block-authoring-help.js +11 -0
- package/lib/blocks/ast-parser.js +67 -0
- package/lib/blocks/discover-blocks.js +146 -0
- package/lib/blocks/editor-scope.js +733 -0
- package/lib/blocks/editor-transpiler.js +1229 -0
- package/lib/blocks/index.js +2838 -0
- package/lib/blocks/php-transpiler.js +4928 -0
- package/lib/blocks/scanner.js +1487 -0
- package/lib/blocks/shared-utils.js +290 -0
- package/lib/blocks/source-sanitize.js +1449 -0
- package/lib/blueprints.js +31 -91
- package/lib/build-assets.js +38 -33
- package/lib/collect-page-template-routes.js +102 -0
- package/lib/collect-static-routes.js +175 -0
- package/lib/diagnostics.js +58 -33
- package/lib/export-theme.js +84 -5
- package/lib/extract-template-content.js +90 -0
- package/lib/forms-preview.js +42 -0
- package/lib/functions/cpt-routing.js +69 -0
- package/lib/functions/forms.js +2461 -0
- package/lib/functions/hydration-enqueuer.js +400 -0
- package/lib/functions/index.js +1623 -0
- package/lib/functions/load-menus.js +112 -0
- package/lib/functions/load-translations.js +148 -0
- package/lib/functions/rest-endpoints.js +2923 -0
- package/lib/functions/routing.js +765 -0
- package/lib/functions/seed-mock-data.js +392 -0
- package/lib/functions/seed-products.js +481 -0
- package/lib/functions/settings-page.js +273 -0
- package/lib/functions/theme-setup.js +494 -0
- package/lib/generate-theme.js +1916 -339
- package/lib/hydration/editable-schemas.js +332 -0
- package/lib/hydration/enter-hidden-initial.js +65 -0
- package/lib/hydration/form-schemas.js +227 -0
- package/lib/hydration/index.js +12 -0
- package/lib/hydration/is-interactive.js +951 -0
- package/lib/hydration/island-split.js +1231 -0
- package/lib/hydration/islands-scanner.js +599 -0
- package/lib/hydration/resolve-island-chunk.js +103 -0
- package/lib/hydration/resolve-island-component.js +52 -0
- package/lib/hydration/rollup-inputs.js +81 -0
- package/lib/hydration/root-class-extractor.js +220 -0
- package/lib/hydration/scan-app-providers.js +154 -0
- package/lib/hydration/static-lint.js +382 -0
- package/lib/hydration/transform.js +257 -0
- package/lib/hydration/uses-block-area.js +49 -0
- package/lib/hydration/utils.js +119 -0
- package/lib/i18n/translation-cache.js +141 -0
- package/lib/icon-registry.js +72 -0
- package/lib/index.d.ts +287 -8
- package/lib/index.js +2 -1
- package/lib/load-config.js +338 -242
- package/lib/mail-templates.js +37 -0
- package/lib/markup-processor.js +388 -102
- package/lib/node-runtime.js +7 -0
- package/lib/page-config-plugin.js +64 -20
- package/lib/php-builders.js +383 -44
- package/lib/react-adapter.js +983 -235
- package/lib/registration-metadata.js +11 -0
- package/lib/render-theme.mts +1410 -616
- package/lib/route-layout.js +76 -0
- package/lib/template-discovery.js +58 -0
- package/lib/theme-compatibility.js +32 -0
- package/lib/validate-export.js +2 -2
- package/lib/validate.js +27 -5
- package/lib/virtual-plugin.js +319 -0
- package/lib/walkthrough.md +26 -0
- package/package.json +16 -5
- package/templates/auth/cms/email-logs.json +9 -0
- package/templates/auth/cms/menus.json +11 -0
- package/templates/auth/cms/mock-data.json +123 -0
- package/templates/auth/cms/roles.json +7 -0
- package/templates/auth/cms/sessions.json +1 -0
- package/templates/auth/cms/site-settings.json +28 -0
- package/templates/auth/cms/translations.json +4 -0
- package/templates/auth/cms/users.json +46 -0
- package/templates/auth/components/forgot-password-form-wrapper.tsx +10 -2
- package/templates/auth/components/login-form-wrapper.tsx +118 -21
- package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
- package/templates/auth/components/signup-form-wrapper.tsx +2 -2
- package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
- package/templates/auth/pages/DashboardPage.tsx +1 -4
- package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
- package/templates/auth/pages/LoginPage.tsx +1 -4
- package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
- package/templates/auth/pages/SignUpPage.tsx +1 -4
- package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
- package/templates/auth/ui/button.tsx +57 -0
- package/templates/auth/ui/card.tsx +76 -0
- package/templates/auth/ui/field.tsx +242 -0
- package/templates/auth/ui/input.tsx +22 -0
- package/templates/auth/ui/label.tsx +24 -0
- package/templates/auth/ui/separator.tsx +31 -0
- package/templates/menus.json +12 -10
- package/templates/users.json +8 -4
- package/templates/wordpress.tsx +690 -245
- package/lib/block-compiler.js +0 -552
- package/lib/functions-builder.js +0 -2970
- package/lib/hydration-scanner.js +0 -833
package/templates/wordpress.tsx
CHANGED
|
@@ -6,16 +6,29 @@
|
|
|
6
6
|
* with the equivalent WordPress PHP function call.
|
|
7
7
|
*/
|
|
8
8
|
import React from 'react';
|
|
9
|
-
import { Link as WouterLink, useLocation as useWouterLocation, useSearch as useWouterSearch } from 'wouter';
|
|
10
9
|
|
|
11
10
|
// @ts-ignore
|
|
12
|
-
import
|
|
11
|
+
import rawMockData from '../../cms/mock-data';
|
|
13
12
|
// @ts-ignore
|
|
14
|
-
import
|
|
13
|
+
import rawMenusData from '../../cms/menus';
|
|
15
14
|
// @ts-ignore
|
|
16
|
-
import
|
|
15
|
+
import wpConfig from '../../wp.config';
|
|
17
16
|
// @ts-ignore
|
|
18
|
-
import
|
|
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
|
+
{};
|
|
19
32
|
|
|
20
33
|
import {
|
|
21
34
|
WpQueryLoop as _WpQueryLoop,
|
|
@@ -44,16 +57,96 @@ import {
|
|
|
44
57
|
useWpMenu as _useWpMenu,
|
|
45
58
|
BlockArea as _BlockArea,
|
|
46
59
|
defineEditable,
|
|
60
|
+
getEditableDefaults,
|
|
61
|
+
buildPageEditable,
|
|
62
|
+
pickEditable,
|
|
63
|
+
mergeEditable,
|
|
47
64
|
text,
|
|
48
65
|
richText,
|
|
49
66
|
image,
|
|
50
67
|
boolean,
|
|
51
68
|
repeater,
|
|
69
|
+
color,
|
|
70
|
+
url,
|
|
71
|
+
select,
|
|
72
|
+
number,
|
|
73
|
+
icon,
|
|
74
|
+
isEditorPreview,
|
|
75
|
+
useIsEditorPreview,
|
|
52
76
|
WpRepeater,
|
|
53
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,
|
|
54
101
|
} from '@forgewp/react';
|
|
55
102
|
|
|
56
|
-
export {
|
|
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
|
+
};
|
|
57
150
|
|
|
58
151
|
import type {
|
|
59
152
|
WpQueryLoopProps,
|
|
@@ -69,16 +162,23 @@ import type {
|
|
|
69
162
|
BlockAreaProps,
|
|
70
163
|
WpRepeaterProps,
|
|
71
164
|
WpIconProps,
|
|
165
|
+
WpFormFieldsProps,
|
|
166
|
+
WpFormFieldDescriptor,
|
|
167
|
+
WpFormResult,
|
|
72
168
|
} from '@forgewp/react';
|
|
73
169
|
|
|
170
|
+
export type { WpFormFieldsProps, WpFormFieldDescriptor, WpFormResult };
|
|
171
|
+
|
|
74
172
|
const IS_DEV =
|
|
75
173
|
typeof import.meta !== 'undefined' &&
|
|
76
174
|
// @ts-ignore
|
|
77
175
|
import.meta.env?.DEV === true;
|
|
78
176
|
|
|
79
177
|
const IS_DECOUPLED =
|
|
80
|
-
|
|
81
|
-
|
|
178
|
+
typeof window !== 'undefined' && (window as any)._forgeWpCompileTime
|
|
179
|
+
? false
|
|
180
|
+
: IS_DEV ||
|
|
181
|
+
(typeof window !== 'undefined' && !(window as any).forgeWpHydration);
|
|
82
182
|
|
|
83
183
|
export function decodeHtmlEntities(str: string): string {
|
|
84
184
|
if (!str) return '';
|
|
@@ -105,9 +205,63 @@ function getDevMockPosts(): any {
|
|
|
105
205
|
|
|
106
206
|
if (IS_DEV) {
|
|
107
207
|
if (typeof window !== 'undefined') {
|
|
108
|
-
|
|
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
|
+
};
|
|
109
221
|
(window as any)._forgeWpMockPosts = mockData;
|
|
110
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
|
+
}
|
|
111
265
|
}
|
|
112
266
|
}
|
|
113
267
|
|
|
@@ -147,6 +301,26 @@ export function useWpFeaturedImage(): string {
|
|
|
147
301
|
if (IS_DECOUPLED) return _useWpFeaturedImage();
|
|
148
302
|
return '__FORGEWP_THE_POST_THUMBNAIL_URL__';
|
|
149
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
|
+
|
|
150
324
|
export function useWpCustomField(fieldName: string, defaultValue = ''): any {
|
|
151
325
|
if (IS_DECOUPLED) return _useWpCustomField(fieldName, defaultValue);
|
|
152
326
|
|
|
@@ -155,8 +329,14 @@ export function useWpCustomField(fieldName: string, defaultValue = ''): any {
|
|
|
155
329
|
if (!win._forgeWpCompileTime) {
|
|
156
330
|
const post = React.useContext(WpPostContext);
|
|
157
331
|
const currentPost = post || win.forgeWpHydration?.post;
|
|
158
|
-
if (
|
|
159
|
-
|
|
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
|
+
}
|
|
160
340
|
}
|
|
161
341
|
}
|
|
162
342
|
}
|
|
@@ -172,8 +352,14 @@ export function useWpField(fieldName: string, defaultValue = ''): any {
|
|
|
172
352
|
if (!win._forgeWpCompileTime) {
|
|
173
353
|
const post = React.useContext(WpPostContext);
|
|
174
354
|
const currentPost = post || win.forgeWpHydration?.post;
|
|
175
|
-
if (
|
|
176
|
-
|
|
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
|
+
}
|
|
177
363
|
}
|
|
178
364
|
}
|
|
179
365
|
}
|
|
@@ -181,28 +367,113 @@ export function useWpField(fieldName: string, defaultValue = ''): any {
|
|
|
181
367
|
return '__FORGEWP_CUSTOM_FIELD__' + fieldName + '__';
|
|
182
368
|
}
|
|
183
369
|
|
|
184
|
-
export
|
|
185
|
-
|
|
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);
|
|
186
382
|
|
|
187
383
|
// Browser-side hydration: check for forgeWpHydration data first
|
|
188
384
|
if (typeof window !== 'undefined') {
|
|
189
385
|
const win = window as any;
|
|
190
386
|
if (win._forgeWpCompileTime) {
|
|
191
|
-
if (
|
|
192
|
-
|
|
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;
|
|
193
406
|
}
|
|
194
|
-
|
|
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;
|
|
195
413
|
}
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
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;
|
|
200
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;
|
|
201
448
|
}
|
|
202
449
|
|
|
203
450
|
// Fallback to token for compiler replacement
|
|
204
|
-
|
|
205
|
-
|
|
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;
|
|
206
477
|
}
|
|
207
478
|
|
|
208
479
|
export function useWpOption(optionName: string, defaultValue = ''): string {
|
|
@@ -211,11 +482,9 @@ export function useWpOption(optionName: string, defaultValue = ''): string {
|
|
|
211
482
|
// Browser-side hydration: check for forgeWpHydration data first
|
|
212
483
|
if (typeof window !== 'undefined') {
|
|
213
484
|
const win = window as any;
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
const value = siteSettings.options[optionName];
|
|
218
|
-
// Handle false/null values from WordPress
|
|
485
|
+
const hydrationOptions = win.forgeWpHydration?.siteSettings?.options;
|
|
486
|
+
if (hydrationOptions?.[optionName] !== undefined) {
|
|
487
|
+
const value = hydrationOptions[optionName];
|
|
219
488
|
if (value === false || value === null) {
|
|
220
489
|
return defaultValue || `[option: ${optionName}]`;
|
|
221
490
|
}
|
|
@@ -224,9 +493,11 @@ export function useWpOption(optionName: string, defaultValue = ''): string {
|
|
|
224
493
|
}
|
|
225
494
|
|
|
226
495
|
// Fallback to token for compiler replacement
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
496
|
+
const defaultStr =
|
|
497
|
+
typeof defaultValue === 'string'
|
|
498
|
+
? defaultValue
|
|
499
|
+
: JSON.stringify(defaultValue);
|
|
500
|
+
return `__FORGEWP_OPTION_${optionName}_DEFAULT_${encodeURIComponent(defaultStr).replace(/_/g, '%5F')}__`;
|
|
230
501
|
}
|
|
231
502
|
|
|
232
503
|
export function useWpThemeMod(modName: string, defaultValue = ''): string {
|
|
@@ -235,11 +506,9 @@ export function useWpThemeMod(modName: string, defaultValue = ''): string {
|
|
|
235
506
|
// Browser-side hydration: check for forgeWpHydration data first
|
|
236
507
|
if (typeof window !== 'undefined') {
|
|
237
508
|
const win = window as any;
|
|
238
|
-
const
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
const value = siteSettings.theme_mods[modName];
|
|
242
|
-
// Handle false/null values from WordPress
|
|
509
|
+
const hydrationMods = win.forgeWpHydration?.siteSettings?.theme_mods;
|
|
510
|
+
if (hydrationMods?.[modName] !== undefined) {
|
|
511
|
+
const value = hydrationMods[modName];
|
|
243
512
|
if (value === false || value === null) {
|
|
244
513
|
return defaultValue || `[theme_mod: ${modName}]`;
|
|
245
514
|
}
|
|
@@ -248,9 +517,11 @@ export function useWpThemeMod(modName: string, defaultValue = ''): string {
|
|
|
248
517
|
}
|
|
249
518
|
|
|
250
519
|
// Fallback to token for compiler replacement
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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')}__`;
|
|
254
525
|
}
|
|
255
526
|
|
|
256
527
|
export function useWpThemeUri(): string {
|
|
@@ -265,26 +536,48 @@ export function useWpPageLink(name: string, fallback: string): string {
|
|
|
265
536
|
if (IS_DECOUPLED) return _useWpPageLink(name, fallback);
|
|
266
537
|
if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
|
|
267
538
|
const win = window as any;
|
|
268
|
-
if
|
|
269
|
-
|
|
539
|
+
// Use the resolved WP permalink if available and non-empty
|
|
540
|
+
const resolved = win.forgeWpHydration?.pageLinks?.[name];
|
|
541
|
+
if (resolved) {
|
|
542
|
+
return resolved;
|
|
270
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}__`;
|
|
271
557
|
}
|
|
272
|
-
return fallback
|
|
273
|
-
|
|
274
|
-
: `__FORGEWP_PAGELINK_${name}__`;
|
|
558
|
+
// SSR / unknown context: return fallback
|
|
559
|
+
return fallback || '';
|
|
275
560
|
}
|
|
276
561
|
|
|
277
562
|
export function useWpPagePath(name: string, fallback: string): string {
|
|
278
563
|
const href = useWpPageLink(name, fallback);
|
|
279
564
|
return React.useMemo(() => {
|
|
280
565
|
try {
|
|
281
|
-
return new URL(
|
|
566
|
+
return new URL(
|
|
567
|
+
href,
|
|
568
|
+
typeof window !== 'undefined'
|
|
569
|
+
? window.location.origin
|
|
570
|
+
: 'http://localhost',
|
|
571
|
+
).pathname;
|
|
282
572
|
} catch (e) {
|
|
283
573
|
return href;
|
|
284
574
|
}
|
|
285
575
|
}, [href]);
|
|
286
576
|
}
|
|
287
|
-
const queryCache = new Map<
|
|
577
|
+
const queryCache = new Map<
|
|
578
|
+
string,
|
|
579
|
+
{ posts: any[]; total: number; hasMore: boolean; totalPages?: number }
|
|
580
|
+
>();
|
|
288
581
|
|
|
289
582
|
const activeQueries = new Set<{
|
|
290
583
|
args: any;
|
|
@@ -296,48 +589,87 @@ let prefetchTimeout: any = null;
|
|
|
296
589
|
|
|
297
590
|
async function fetchWpApi(args: any, page: number) {
|
|
298
591
|
const {
|
|
592
|
+
queryId = '',
|
|
299
593
|
postType = 'post',
|
|
300
594
|
postsPerPage = 10,
|
|
301
595
|
categoryName = '',
|
|
302
596
|
s = '',
|
|
303
597
|
orderby = 'date',
|
|
304
598
|
order = 'DESC',
|
|
599
|
+
p,
|
|
600
|
+
taxQuery = [],
|
|
601
|
+
metaQuery = [],
|
|
305
602
|
} = args;
|
|
306
603
|
|
|
307
604
|
const endpoint =
|
|
308
|
-
postType === 'post'
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
params.append('order', order.toLowerCase());
|
|
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
|
+
);
|
|
325
621
|
}
|
|
326
|
-
|
|
327
|
-
|
|
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
|
+
}
|
|
328
653
|
}
|
|
329
654
|
|
|
330
655
|
// Polylang multi-language query support
|
|
331
|
-
const currentLang =
|
|
656
|
+
const currentLang =
|
|
657
|
+
(window as any).forgeWpLocale ||
|
|
658
|
+
(window as any).forgeWpTranslations?.currentLanguage;
|
|
332
659
|
if (currentLang) {
|
|
333
660
|
params.append('lang', currentLang);
|
|
334
661
|
}
|
|
335
662
|
|
|
336
|
-
const apiBase =
|
|
663
|
+
const apiBase =
|
|
664
|
+
(typeof window !== 'undefined' && (window as any).FORGEWP_API_URL) ||
|
|
337
665
|
(import.meta as any).env?.VITE_WP_API_URL ||
|
|
338
|
-
(typeof (globalThis as any).process !== 'undefined' &&
|
|
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)) ||
|
|
339
670
|
(() => {
|
|
340
|
-
const homeUrl =
|
|
671
|
+
const homeUrl =
|
|
672
|
+
(window as any).forgeWpHydration?.siteSettings?.options?.home || '';
|
|
341
673
|
if (homeUrl) {
|
|
342
674
|
try {
|
|
343
675
|
return new URL(homeUrl).pathname.replace(/\/$/, '');
|
|
@@ -345,7 +677,15 @@ async function fetchWpApi(args: any, page: number) {
|
|
|
345
677
|
}
|
|
346
678
|
return '';
|
|
347
679
|
})();
|
|
348
|
-
const
|
|
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()}`;
|
|
349
689
|
console.log(`[useWpQuery] Fetching CPT "${postType}" from URL:`, fetchUrl);
|
|
350
690
|
|
|
351
691
|
const headers: Record<string, string> = {};
|
|
@@ -357,17 +697,30 @@ async function fetchWpApi(args: any, page: number) {
|
|
|
357
697
|
}
|
|
358
698
|
|
|
359
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
|
+
}
|
|
360
706
|
if (!response.ok) {
|
|
361
707
|
throw new Error(
|
|
362
708
|
`WordPress API returned ${response.status}: ${response.statusText}`,
|
|
363
709
|
);
|
|
364
710
|
}
|
|
365
711
|
|
|
366
|
-
const
|
|
712
|
+
const rawData = await response.json();
|
|
713
|
+
const data = isSinglePostLookup
|
|
714
|
+
? [rawData]
|
|
715
|
+
: useGeneratedQuery
|
|
716
|
+
? rawData.posts
|
|
717
|
+
: rawData;
|
|
367
718
|
if (!Array.isArray(data)) {
|
|
368
719
|
throw new Error('Invalid response format from WordPress API');
|
|
369
720
|
}
|
|
370
|
-
console.log(
|
|
721
|
+
console.log(
|
|
722
|
+
`[useWpQuery] Successfully loaded ${data.length} items for CPT "${postType}"`,
|
|
723
|
+
);
|
|
371
724
|
|
|
372
725
|
const cleanHtml = (html: string) => {
|
|
373
726
|
if (!html) return '';
|
|
@@ -375,7 +728,11 @@ async function fetchWpApi(args: any, page: number) {
|
|
|
375
728
|
};
|
|
376
729
|
|
|
377
730
|
const mappedPosts: WpPost[] = data.map((wp: any) => {
|
|
378
|
-
let featuredImage =
|
|
731
|
+
let featuredImage =
|
|
732
|
+
typeof wp.featuredImage === 'string'
|
|
733
|
+
? wp.featuredImage
|
|
734
|
+
: wp.featuredImage?.url ||
|
|
735
|
+
'https://picsum.photos/seed/forgewp/1200/630';
|
|
379
736
|
if (
|
|
380
737
|
wp._embedded &&
|
|
381
738
|
wp._embedded['wp:featuredmedia'] &&
|
|
@@ -396,7 +753,8 @@ async function fetchWpApi(args: any, page: number) {
|
|
|
396
753
|
_terms[taxonomy] = termGroup.map((t: any) => ({
|
|
397
754
|
id: t.id,
|
|
398
755
|
slug: t.slug,
|
|
399
|
-
name:
|
|
756
|
+
name:
|
|
757
|
+
typeof t.name === 'string' ? decodeHtmlEntities(t.name) : '',
|
|
400
758
|
}));
|
|
401
759
|
}
|
|
402
760
|
}
|
|
@@ -404,54 +762,70 @@ async function fetchWpApi(args: any, page: number) {
|
|
|
404
762
|
}
|
|
405
763
|
|
|
406
764
|
return {
|
|
407
|
-
id: wp.id,
|
|
765
|
+
id: wp.id ?? wp.ID,
|
|
408
766
|
title:
|
|
409
|
-
typeof wp.title === 'object'
|
|
767
|
+
typeof wp.title === 'object'
|
|
768
|
+
? decodeHtmlEntities(wp.title.rendered)
|
|
769
|
+
: decodeHtmlEntities(wp.title || ''),
|
|
410
770
|
excerpt:
|
|
411
771
|
typeof wp.excerpt === 'object'
|
|
412
772
|
? cleanHtml(wp.excerpt.rendered)
|
|
413
773
|
: cleanHtml(wp.excerpt || ''),
|
|
414
774
|
content:
|
|
415
|
-
typeof wp.content === 'object'
|
|
416
|
-
? wp.content.rendered
|
|
417
|
-
: wp.content || '',
|
|
775
|
+
typeof wp.content === 'object' ? wp.content.rendered : wp.content || '',
|
|
418
776
|
date: wp.date
|
|
419
|
-
? new Date(wp.date).toLocaleDateString(
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
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
|
+
)
|
|
424
785
|
: '',
|
|
425
786
|
modified: wp.modified
|
|
426
|
-
? new Date(wp.modified).toLocaleDateString(
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
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
|
+
)
|
|
431
795
|
: '',
|
|
432
796
|
author:
|
|
433
|
-
wp._embedded &&
|
|
434
|
-
wp._embedded['author'] &&
|
|
435
|
-
wp._embedded['author'][0]
|
|
797
|
+
wp._embedded && wp._embedded['author'] && wp._embedded['author'][0]
|
|
436
798
|
? wp._embedded['author'][0].name
|
|
437
799
|
: 'Admin',
|
|
438
800
|
featuredImage,
|
|
439
|
-
permalink: wp.link,
|
|
440
|
-
|
|
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
|
+
},
|
|
441
811
|
_terms,
|
|
442
|
-
__postType: wp.type || postType,
|
|
812
|
+
__postType: wp.type || wp.post_type || postType,
|
|
443
813
|
};
|
|
444
814
|
});
|
|
445
815
|
|
|
446
816
|
const totalPagesHeader = response.headers.get('X-WP-TotalPages');
|
|
447
|
-
const totalPages =
|
|
448
|
-
?
|
|
449
|
-
:
|
|
817
|
+
const totalPages = useGeneratedQuery
|
|
818
|
+
? Number(rawData.totalPages) || 1
|
|
819
|
+
: totalPagesHeader
|
|
820
|
+
? parseInt(totalPagesHeader, 10)
|
|
821
|
+
: 1;
|
|
450
822
|
|
|
451
823
|
const totalHeader = response.headers.get('X-WP-Total');
|
|
452
|
-
const total =
|
|
453
|
-
?
|
|
454
|
-
:
|
|
824
|
+
const total = useGeneratedQuery
|
|
825
|
+
? Number(rawData.total) || mappedPosts.length
|
|
826
|
+
: totalHeader
|
|
827
|
+
? parseInt(totalHeader, 10)
|
|
828
|
+
: mappedPosts.length;
|
|
455
829
|
|
|
456
830
|
return {
|
|
457
831
|
posts: mappedPosts,
|
|
@@ -467,7 +841,10 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
467
841
|
}
|
|
468
842
|
|
|
469
843
|
// Node SSR (Compile-time)
|
|
470
|
-
if (
|
|
844
|
+
if (
|
|
845
|
+
typeof window === 'undefined' ||
|
|
846
|
+
(typeof window !== 'undefined' && (window as any)._forgeWpCompileTime)
|
|
847
|
+
) {
|
|
471
848
|
// In production WordPress themes, dynamic hydration islands should SSR in a loading state
|
|
472
849
|
// so that the initial page layout contains loading skeletons instead of developer's compile-time mock data.
|
|
473
850
|
return {
|
|
@@ -484,6 +861,9 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
484
861
|
}
|
|
485
862
|
|
|
486
863
|
// Browser (Hydration/Production Client)
|
|
864
|
+
const argsRef = React.useRef(args);
|
|
865
|
+
argsRef.current = args;
|
|
866
|
+
|
|
487
867
|
const {
|
|
488
868
|
postType = 'post',
|
|
489
869
|
postsPerPage = 10,
|
|
@@ -492,9 +872,11 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
492
872
|
paged = 1,
|
|
493
873
|
orderby = 'date',
|
|
494
874
|
order = 'DESC',
|
|
875
|
+
p,
|
|
495
876
|
} = args;
|
|
496
877
|
|
|
497
878
|
const queryKey = JSON.stringify({
|
|
879
|
+
queryId: args.queryId,
|
|
498
880
|
postType,
|
|
499
881
|
postsPerPage,
|
|
500
882
|
categoryName,
|
|
@@ -502,6 +884,10 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
502
884
|
paged,
|
|
503
885
|
orderby,
|
|
504
886
|
order,
|
|
887
|
+
p,
|
|
888
|
+
taxQuery: args.taxQuery,
|
|
889
|
+
metaQuery: args.metaQuery,
|
|
890
|
+
metaRelation: args.metaRelation,
|
|
505
891
|
});
|
|
506
892
|
|
|
507
893
|
let initialState = null;
|
|
@@ -513,12 +899,12 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
513
899
|
if (parsed.queries && parsed.queries[queryKey]) {
|
|
514
900
|
initialState = parsed.queries[queryKey];
|
|
515
901
|
// Pre-populate queryCache for page 1
|
|
516
|
-
const cacheKey = JSON.stringify({ ...
|
|
902
|
+
const cacheKey = JSON.stringify({ ...argsRef.current, paged: paged });
|
|
517
903
|
if (!queryCache.has(cacheKey)) {
|
|
518
904
|
queryCache.set(cacheKey, {
|
|
519
905
|
posts: initialState.posts,
|
|
520
906
|
hasMore: initialState.hasMore,
|
|
521
|
-
total: initialState.total || initialState.posts.length
|
|
907
|
+
total: initialState.total || initialState.posts.length,
|
|
522
908
|
});
|
|
523
909
|
}
|
|
524
910
|
}
|
|
@@ -528,11 +914,15 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
528
914
|
}
|
|
529
915
|
}
|
|
530
916
|
|
|
531
|
-
const [posts, setPosts] = React.useState<WpPost[]>(
|
|
917
|
+
const [posts, setPosts] = React.useState<WpPost[]>(
|
|
918
|
+
initialState ? initialState.posts : [],
|
|
919
|
+
);
|
|
532
920
|
const [loading, setLoading] = React.useState(initialState ? false : true);
|
|
533
921
|
const [error, setError] = React.useState<string | null>(null);
|
|
534
922
|
const [currentPage, setCurrentPage] = React.useState(paged);
|
|
535
|
-
const [hasMore, setHasMore] = React.useState(
|
|
923
|
+
const [hasMore, setHasMore] = React.useState(
|
|
924
|
+
initialState ? initialState.hasMore : true,
|
|
925
|
+
);
|
|
536
926
|
const [totalPages, setTotalPages] = React.useState<number>(1);
|
|
537
927
|
const hydratedFromSsrRef = React.useRef(initialState ? true : false);
|
|
538
928
|
// 'append' = loadMore behaviour; 'replace' = goToPage behaviour
|
|
@@ -554,32 +944,47 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
554
944
|
// Consume the mode; subsequent calls revert to append (for loadMore)
|
|
555
945
|
pageModeRef.current = 'append';
|
|
556
946
|
|
|
557
|
-
const cacheKey = JSON.stringify({ ...
|
|
947
|
+
const cacheKey = JSON.stringify({ ...argsRef.current, paged: page });
|
|
558
948
|
if (queryCache.has(cacheKey)) {
|
|
559
949
|
const cached = queryCache.get(cacheKey)!;
|
|
560
950
|
setPosts((prev: WpPost[]) => {
|
|
561
951
|
if (mode === 'append') {
|
|
562
952
|
const existingIds = new Set(prev.map((p: WpPost) => p.id));
|
|
563
|
-
const newPosts = cached.posts.filter(
|
|
953
|
+
const newPosts = cached.posts.filter(
|
|
954
|
+
(p: WpPost) => !existingIds.has(p.id),
|
|
955
|
+
);
|
|
564
956
|
return [...prev, ...newPosts];
|
|
565
957
|
}
|
|
566
958
|
return cached.posts;
|
|
567
959
|
});
|
|
568
960
|
setHasMore(cached.hasMore);
|
|
569
|
-
if ((cached as any).totalPages)
|
|
961
|
+
if ((cached as any).totalPages)
|
|
962
|
+
setTotalPages((cached as any).totalPages);
|
|
570
963
|
setError(null);
|
|
571
964
|
return;
|
|
572
965
|
}
|
|
573
966
|
|
|
574
967
|
setLoading(true);
|
|
575
968
|
try {
|
|
576
|
-
const {
|
|
577
|
-
|
|
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
|
+
});
|
|
578
981
|
|
|
579
982
|
setPosts((prev: WpPost[]) => {
|
|
580
983
|
if (mode === 'append') {
|
|
581
984
|
const existingIds = new Set(prev.map((p: WpPost) => p.id));
|
|
582
|
-
const newPosts = fetchedPosts.filter(
|
|
985
|
+
const newPosts = fetchedPosts.filter(
|
|
986
|
+
(p: WpPost) => !existingIds.has(p.id),
|
|
987
|
+
);
|
|
583
988
|
return [...prev, ...newPosts];
|
|
584
989
|
}
|
|
585
990
|
return fetchedPosts;
|
|
@@ -593,7 +998,7 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
593
998
|
setLoading(false);
|
|
594
999
|
}
|
|
595
1000
|
},
|
|
596
|
-
[queryKey
|
|
1001
|
+
[queryKey],
|
|
597
1002
|
);
|
|
598
1003
|
|
|
599
1004
|
React.useEffect(() => {
|
|
@@ -605,7 +1010,7 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
605
1010
|
}, [executeProdQuery, currentPage]);
|
|
606
1011
|
|
|
607
1012
|
const querySelector = React.useCallback((params: URLSearchParams) => {
|
|
608
|
-
const target = { ...
|
|
1013
|
+
const target = { ...argsRef.current };
|
|
609
1014
|
if (params.has('q') || params.has('s')) {
|
|
610
1015
|
target.s = params.get('q') || params.get('s') || '';
|
|
611
1016
|
}
|
|
@@ -613,12 +1018,14 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
613
1018
|
target.categoryName = params.get('category') || '';
|
|
614
1019
|
}
|
|
615
1020
|
return target;
|
|
616
|
-
}, [
|
|
1021
|
+
}, []);
|
|
617
1022
|
|
|
618
1023
|
React.useEffect(() => {
|
|
619
1024
|
if (typeof window === 'undefined') return;
|
|
620
1025
|
const item = {
|
|
621
|
-
args
|
|
1026
|
+
get args() {
|
|
1027
|
+
return argsRef.current;
|
|
1028
|
+
},
|
|
622
1029
|
querySelector,
|
|
623
1030
|
execute: async (targetArgs: any) => {
|
|
624
1031
|
const cacheKey = JSON.stringify({ ...targetArgs, paged: 1 });
|
|
@@ -627,13 +1034,13 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
627
1034
|
const res = await fetchWpApi(targetArgs, 1);
|
|
628
1035
|
queryCache.set(cacheKey, res);
|
|
629
1036
|
} catch (e) {}
|
|
630
|
-
}
|
|
1037
|
+
},
|
|
631
1038
|
};
|
|
632
1039
|
activeQueries.add(item);
|
|
633
1040
|
return () => {
|
|
634
1041
|
activeQueries.delete(item);
|
|
635
1042
|
};
|
|
636
|
-
}, [
|
|
1043
|
+
}, [querySelector]);
|
|
637
1044
|
|
|
638
1045
|
const loadMore = React.useCallback(async () => {
|
|
639
1046
|
if (loading || !hasMore) return;
|
|
@@ -642,13 +1049,16 @@ export function useWpQuery(args: WpQueryArgs = {}): WpQueryResults {
|
|
|
642
1049
|
setCurrentPage(nextPage);
|
|
643
1050
|
}, [currentPage, loading, hasMore]);
|
|
644
1051
|
|
|
645
|
-
const goToPage = React.useCallback(
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
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
|
+
);
|
|
652
1062
|
|
|
653
1063
|
const refetch = React.useCallback(async () => {
|
|
654
1064
|
pageModeRef.current = 'replace';
|
|
@@ -704,9 +1114,14 @@ export interface WpTerm {
|
|
|
704
1114
|
meta: Record<string, any>;
|
|
705
1115
|
}
|
|
706
1116
|
|
|
707
|
-
export function useWpTerms(taxonomy: string): {
|
|
1117
|
+
export function useWpTerms(taxonomy: string): {
|
|
1118
|
+
terms: WpTerm[];
|
|
1119
|
+
loading: boolean;
|
|
1120
|
+
error: string | null;
|
|
1121
|
+
} {
|
|
708
1122
|
if (IS_DEV) {
|
|
709
|
-
const raw: any[] =
|
|
1123
|
+
const raw: any[] =
|
|
1124
|
+
(getDevMockPosts() as any)?.[`_taxonomy_${taxonomy}`] || [];
|
|
710
1125
|
const terms: WpTerm[] = raw.map((t: any) => ({
|
|
711
1126
|
id: t.id ?? 0,
|
|
712
1127
|
name: t.name ?? '',
|
|
@@ -730,12 +1145,22 @@ export function useWpTerms(taxonomy: string): { terms: WpTerm[]; loading: boolea
|
|
|
730
1145
|
|
|
731
1146
|
React.useEffect(() => {
|
|
732
1147
|
let cancelled = false;
|
|
733
|
-
const endpoint =
|
|
734
|
-
|
|
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) ||
|
|
735
1156
|
(import.meta as any).env?.VITE_WP_API_URL ||
|
|
736
|
-
(typeof (globalThis as any).process !== 'undefined' &&
|
|
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)) ||
|
|
737
1161
|
(() => {
|
|
738
|
-
const homeUrl =
|
|
1162
|
+
const homeUrl =
|
|
1163
|
+
(window as any).forgeWpHydration?.siteSettings?.options?.home || '';
|
|
739
1164
|
if (homeUrl) {
|
|
740
1165
|
try {
|
|
741
1166
|
return new URL(homeUrl).pathname.replace(/\/$/, '');
|
|
@@ -743,10 +1168,15 @@ export function useWpTerms(taxonomy: string): { terms: WpTerm[]; loading: boolea
|
|
|
743
1168
|
}
|
|
744
1169
|
return '';
|
|
745
1170
|
})();
|
|
746
|
-
const currentLang =
|
|
1171
|
+
const currentLang =
|
|
1172
|
+
(window as any).forgeWpLocale ||
|
|
1173
|
+
(window as any).forgeWpTranslations?.currentLanguage;
|
|
747
1174
|
const langParam = currentLang ? `&lang=${currentLang}` : '';
|
|
748
1175
|
const fetchUrl = `${apiBase}/wp-json/wp/v2/${endpoint}?per_page=100&_fields=id,name,slug,description,count,acf,meta${langParam}`;
|
|
749
|
-
console.log(
|
|
1176
|
+
console.log(
|
|
1177
|
+
`[useWpTerms] Fetching taxonomy "${taxonomy}" from URL:`,
|
|
1178
|
+
fetchUrl,
|
|
1179
|
+
);
|
|
750
1180
|
|
|
751
1181
|
const headers: Record<string, string> = {};
|
|
752
1182
|
if (typeof window !== 'undefined') {
|
|
@@ -763,7 +1193,9 @@ export function useWpTerms(taxonomy: string): { terms: WpTerm[]; loading: boolea
|
|
|
763
1193
|
})
|
|
764
1194
|
.then((data: any[]) => {
|
|
765
1195
|
if (cancelled) return;
|
|
766
|
-
console.log(
|
|
1196
|
+
console.log(
|
|
1197
|
+
`[useWpTerms] Successfully loaded ${data.length} terms for taxonomy "${taxonomy}"`,
|
|
1198
|
+
);
|
|
767
1199
|
setTerms(
|
|
768
1200
|
data.map((t) => ({
|
|
769
1201
|
id: t.id,
|
|
@@ -772,27 +1204,30 @@ export function useWpTerms(taxonomy: string): { terms: WpTerm[]; loading: boolea
|
|
|
772
1204
|
description: t.description || '',
|
|
773
1205
|
count: t.count || 0,
|
|
774
1206
|
meta: { ...(t.acf || {}), ...(t.meta || {}) },
|
|
775
|
-
}))
|
|
1207
|
+
})),
|
|
776
1208
|
);
|
|
777
1209
|
setError(null);
|
|
778
1210
|
})
|
|
779
1211
|
.catch((err: any) => {
|
|
780
1212
|
if (!cancelled) {
|
|
781
|
-
console.error(
|
|
1213
|
+
console.error(
|
|
1214
|
+
`[useWpTerms] Error loading taxonomy "${taxonomy}":`,
|
|
1215
|
+
err,
|
|
1216
|
+
);
|
|
782
1217
|
setError(err.message || `Failed to load ${taxonomy} terms`);
|
|
783
1218
|
}
|
|
784
1219
|
})
|
|
785
1220
|
.finally(() => {
|
|
786
1221
|
if (!cancelled) setLoading(false);
|
|
787
1222
|
});
|
|
788
|
-
return () => {
|
|
1223
|
+
return () => {
|
|
1224
|
+
cancelled = true;
|
|
1225
|
+
};
|
|
789
1226
|
}, [taxonomy]);
|
|
790
1227
|
|
|
791
1228
|
return { terms, loading, error };
|
|
792
1229
|
}
|
|
793
1230
|
|
|
794
|
-
|
|
795
|
-
|
|
796
1231
|
// ── WpQueryLoop — data bridge wraps @forgewp/react with mock data ─────────────
|
|
797
1232
|
|
|
798
1233
|
export function WpQueryLoop({
|
|
@@ -811,7 +1246,9 @@ export function WpQueryLoop({
|
|
|
811
1246
|
posts = [...posts].sort((a, b) => {
|
|
812
1247
|
const titleA = a.title || '';
|
|
813
1248
|
const titleB = b.title || '';
|
|
814
|
-
return order === 'ASC'
|
|
1249
|
+
return order === 'ASC'
|
|
1250
|
+
? titleA.localeCompare(titleB)
|
|
1251
|
+
: titleB.localeCompare(titleA);
|
|
815
1252
|
});
|
|
816
1253
|
} else if (orderby === 'date') {
|
|
817
1254
|
posts = [...posts].sort((a, b) => {
|
|
@@ -870,19 +1307,37 @@ export function WpLoop({ children }: { children: React.ReactNode }) {
|
|
|
870
1307
|
|
|
871
1308
|
// ── useWpMenu ────────────────────────────────────────────────────────────────
|
|
872
1309
|
|
|
873
|
-
export function useWpMenu(location: string = 'primary'): {
|
|
1310
|
+
export function useWpMenu(location: string = 'primary'): {
|
|
1311
|
+
items: WpMenuItem[];
|
|
1312
|
+
loading: boolean;
|
|
1313
|
+
} {
|
|
874
1314
|
if (IS_DEV) {
|
|
875
1315
|
return _useWpMenu(location);
|
|
876
1316
|
}
|
|
877
1317
|
|
|
878
1318
|
// Node SSR (Compile-time)
|
|
879
|
-
if (typeof window ===
|
|
880
|
-
|
|
1319
|
+
if (typeof window === 'undefined' || (window as any)._forgeWpCompileTime) {
|
|
1320
|
+
const items = (menusData as any)?.[location] || [];
|
|
1321
|
+
return { items: normalizeRuntimeMenuItems(items), loading: false };
|
|
881
1322
|
}
|
|
882
1323
|
|
|
883
1324
|
// Browser production hydration client
|
|
884
|
-
const items =
|
|
885
|
-
|
|
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
|
+
}));
|
|
886
1341
|
}
|
|
887
1342
|
|
|
888
1343
|
// ── WpMenu — data bridge wraps @forgewp/react with menus.json ────────────────
|
|
@@ -906,23 +1361,30 @@ export function WpMenu({
|
|
|
906
1361
|
}
|
|
907
1362
|
|
|
908
1363
|
// Production browser hydration client: render menu items from localized PHP data
|
|
909
|
-
if (typeof window !==
|
|
1364
|
+
if (typeof window !== 'undefined' && !(window as any)._forgeWpCompileTime) {
|
|
910
1365
|
if (items.length > 0) {
|
|
911
1366
|
return (
|
|
912
1367
|
<nav className={className}>
|
|
913
1368
|
{items.map((item: any, idx: number) => (
|
|
914
|
-
<a
|
|
1369
|
+
<a
|
|
1370
|
+
key={idx}
|
|
1371
|
+
href={item.url}
|
|
1372
|
+
className={linkClassName}
|
|
1373
|
+
>
|
|
915
1374
|
{item.title}
|
|
916
1375
|
</a>
|
|
917
1376
|
))}
|
|
918
1377
|
</nav>
|
|
919
1378
|
);
|
|
920
1379
|
}
|
|
921
|
-
|
|
1380
|
+
|
|
922
1381
|
// Server-matching fallback nav to guarantee zero hydration mismatch
|
|
923
1382
|
return (
|
|
924
1383
|
<nav className={className}>
|
|
925
|
-
<a
|
|
1384
|
+
<a
|
|
1385
|
+
href='/'
|
|
1386
|
+
className={linkClassName}
|
|
1387
|
+
>
|
|
926
1388
|
Home
|
|
927
1389
|
</a>
|
|
928
1390
|
</nav>
|
|
@@ -982,7 +1444,13 @@ export function WpHead(props: WpHeadProps) {
|
|
|
982
1444
|
/>
|
|
983
1445
|
);
|
|
984
1446
|
}
|
|
985
|
-
export type {
|
|
1447
|
+
export type {
|
|
1448
|
+
WpHeadProps,
|
|
1449
|
+
WpImageProps,
|
|
1450
|
+
WpAttachment,
|
|
1451
|
+
WpRepeaterProps,
|
|
1452
|
+
WpIconProps,
|
|
1453
|
+
};
|
|
986
1454
|
|
|
987
1455
|
export function WpImage(props: WpImageProps) {
|
|
988
1456
|
if (IS_DECOUPLED) {
|
|
@@ -997,39 +1465,24 @@ export function WpImage(props: WpImageProps) {
|
|
|
997
1465
|
return <_WpImage {...props} />;
|
|
998
1466
|
}
|
|
999
1467
|
|
|
1000
|
-
// ── Routing Wrappers for Dev SPA vs Production Multi-Page WordPress ───────────
|
|
1001
|
-
|
|
1002
|
-
export function WpLink({ href, className, children, ...props }: any) {
|
|
1003
|
-
if (IS_DECOUPLED) {
|
|
1004
|
-
return (
|
|
1005
|
-
<WouterLink href={href} className={className} {...props}>
|
|
1006
|
-
{children}
|
|
1007
|
-
</WouterLink>
|
|
1008
|
-
);
|
|
1009
|
-
}
|
|
1010
|
-
return (
|
|
1011
|
-
<a href={href} className={className} {...props}>
|
|
1012
|
-
{children}
|
|
1013
|
-
</a>
|
|
1014
|
-
);
|
|
1015
|
-
}
|
|
1016
|
-
export { WpLink as Link };
|
|
1017
|
-
|
|
1018
1468
|
export function useWpI18n() {
|
|
1019
1469
|
const getTranslatedText = (text: string) => {
|
|
1020
|
-
if (typeof window ===
|
|
1470
|
+
if (typeof window === 'undefined') {
|
|
1021
1471
|
return text;
|
|
1022
1472
|
}
|
|
1023
|
-
const currentLang =
|
|
1473
|
+
const currentLang =
|
|
1474
|
+
(window as any).forgeWpLocale ||
|
|
1475
|
+
(window as any).forgeWpTranslations?.currentLanguage ||
|
|
1476
|
+
'de';
|
|
1024
1477
|
const dict = (window as any).forgeWpTranslations?.translations;
|
|
1025
|
-
|
|
1478
|
+
|
|
1026
1479
|
if (dict) {
|
|
1027
1480
|
// 1. Nested dictionary format: { de: { ... }, en: { ... } }
|
|
1028
|
-
if (dict[currentLang] && typeof dict[currentLang][text] !==
|
|
1481
|
+
if (dict[currentLang] && typeof dict[currentLang][text] !== 'undefined') {
|
|
1029
1482
|
return dict[currentLang][text];
|
|
1030
1483
|
}
|
|
1031
1484
|
// 2. Flat enqueued active locale format: { 'Kontakt': 'Kontakt' }
|
|
1032
|
-
if (typeof dict[text] !==
|
|
1485
|
+
if (typeof dict[text] !== 'undefined') {
|
|
1033
1486
|
return dict[text];
|
|
1034
1487
|
}
|
|
1035
1488
|
}
|
|
@@ -1039,30 +1492,33 @@ export function useWpI18n() {
|
|
|
1039
1492
|
if (IS_DECOUPLED) {
|
|
1040
1493
|
return {
|
|
1041
1494
|
__: (text: string) => {
|
|
1042
|
-
if (typeof window ===
|
|
1495
|
+
if (typeof window === 'undefined') {
|
|
1043
1496
|
return text;
|
|
1044
1497
|
}
|
|
1045
1498
|
const pathname = window.location.pathname;
|
|
1046
1499
|
const translations = translationsData || {};
|
|
1047
|
-
const languages =
|
|
1500
|
+
const languages =
|
|
1501
|
+
Object.keys(translations).length > 0
|
|
1502
|
+
? Object.keys(translations)
|
|
1503
|
+
: ['de', 'en'];
|
|
1048
1504
|
const defaultLanguage = languages[0] || 'de';
|
|
1049
1505
|
|
|
1050
|
-
const matchedLang = languages.find(lang => {
|
|
1506
|
+
const matchedLang = languages.find((lang) => {
|
|
1051
1507
|
if (lang === defaultLanguage) return false;
|
|
1052
1508
|
return pathname.startsWith(`/${lang}/`) || pathname === `/${lang}`;
|
|
1053
1509
|
});
|
|
1054
1510
|
const currentLang = matchedLang || defaultLanguage;
|
|
1055
1511
|
|
|
1056
1512
|
const dict = (translationsData as any)?.[currentLang];
|
|
1057
|
-
if (dict && typeof dict[text] !==
|
|
1513
|
+
if (dict && typeof dict[text] !== 'undefined') {
|
|
1058
1514
|
return dict[text];
|
|
1059
1515
|
}
|
|
1060
1516
|
return text;
|
|
1061
|
-
}
|
|
1517
|
+
},
|
|
1062
1518
|
};
|
|
1063
1519
|
}
|
|
1064
1520
|
// Node SSR (Compile-time): return the token so the compiler can perform string replacement
|
|
1065
|
-
if (typeof window ===
|
|
1521
|
+
if (typeof window === 'undefined' || (window as any)._forgeWpCompileTime) {
|
|
1066
1522
|
return {
|
|
1067
1523
|
__: (text: string) => `__FORGEWP_I18N_${text}__`,
|
|
1068
1524
|
};
|
|
@@ -1072,7 +1528,9 @@ export function useWpI18n() {
|
|
|
1072
1528
|
__: getTranslatedText,
|
|
1073
1529
|
};
|
|
1074
1530
|
}
|
|
1075
|
-
const locationListeners = new Set<
|
|
1531
|
+
const locationListeners = new Set<
|
|
1532
|
+
(payload: { pathname: string; search: string }) => void
|
|
1533
|
+
>();
|
|
1076
1534
|
let popstateBound = false;
|
|
1077
1535
|
|
|
1078
1536
|
function handleLocationUpdate() {
|
|
@@ -1083,7 +1541,9 @@ function handleLocationUpdate() {
|
|
|
1083
1541
|
locationListeners.forEach((listener) => listener(payload));
|
|
1084
1542
|
}
|
|
1085
1543
|
|
|
1086
|
-
function subscribeToLocation(
|
|
1544
|
+
export function subscribeToLocation(
|
|
1545
|
+
listener: (payload: { pathname: string; search: string }) => void,
|
|
1546
|
+
) {
|
|
1087
1547
|
locationListeners.add(listener);
|
|
1088
1548
|
if (typeof window !== 'undefined' && !popstateBound) {
|
|
1089
1549
|
window.addEventListener('popstate', handleLocationUpdate);
|
|
@@ -1091,14 +1551,18 @@ function subscribeToLocation(listener: (payload: { pathname: string; search: str
|
|
|
1091
1551
|
}
|
|
1092
1552
|
return () => {
|
|
1093
1553
|
locationListeners.delete(listener);
|
|
1094
|
-
if (
|
|
1554
|
+
if (
|
|
1555
|
+
locationListeners.size === 0 &&
|
|
1556
|
+
typeof window !== 'undefined' &&
|
|
1557
|
+
popstateBound
|
|
1558
|
+
) {
|
|
1095
1559
|
window.removeEventListener('popstate', handleLocationUpdate);
|
|
1096
1560
|
popstateBound = false;
|
|
1097
1561
|
}
|
|
1098
1562
|
};
|
|
1099
1563
|
}
|
|
1100
1564
|
|
|
1101
|
-
function navigateTo(to: string) {
|
|
1565
|
+
export function navigateTo(to: string) {
|
|
1102
1566
|
if (typeof window === 'undefined') return;
|
|
1103
1567
|
try {
|
|
1104
1568
|
const targetUrl = new URL(to, window.location.href);
|
|
@@ -1138,59 +1602,24 @@ export function useWpPrefetch() {
|
|
|
1138
1602
|
return prefetch;
|
|
1139
1603
|
}
|
|
1140
1604
|
|
|
1141
|
-
export function useWpLocation() {
|
|
1142
|
-
const prefetch = useWpPrefetch();
|
|
1143
|
-
if (IS_DECOUPLED) {
|
|
1144
|
-
const [wLoc, wNavigate] = useWouterLocation();
|
|
1145
|
-
return [wLoc, wNavigate, prefetch] as const;
|
|
1146
|
-
}
|
|
1147
|
-
const [loc, setLoc] = React.useState(typeof window !== "undefined" ? window.location.pathname : "/");
|
|
1148
|
-
|
|
1149
|
-
React.useEffect(() => {
|
|
1150
|
-
return subscribeToLocation((payload) => {
|
|
1151
|
-
setLoc(payload.pathname);
|
|
1152
|
-
});
|
|
1153
|
-
}, []);
|
|
1154
|
-
|
|
1155
|
-
const navigate = React.useCallback((to: string) => {
|
|
1156
|
-
navigateTo(to);
|
|
1157
|
-
}, []);
|
|
1158
|
-
|
|
1159
|
-
return [loc, navigate, prefetch] as const;
|
|
1160
|
-
}
|
|
1161
|
-
export { useWpLocation as useLocation };
|
|
1162
|
-
|
|
1163
|
-
export function useWpSearch() {
|
|
1164
|
-
if (IS_DECOUPLED) {
|
|
1165
|
-
return useWouterSearch();
|
|
1166
|
-
}
|
|
1167
|
-
const [search, setSearch] = React.useState(typeof window !== "undefined" ? window.location.search : "");
|
|
1168
|
-
|
|
1169
|
-
React.useEffect(() => {
|
|
1170
|
-
return subscribeToLocation((payload) => {
|
|
1171
|
-
setSearch(payload.search);
|
|
1172
|
-
});
|
|
1173
|
-
}, []);
|
|
1174
|
-
|
|
1175
|
-
return search;
|
|
1176
|
-
}
|
|
1177
|
-
export { useWpSearch as useSearch };
|
|
1178
|
-
|
|
1179
1605
|
export function useWpSearchParams(): URLSearchParams {
|
|
1180
|
-
const search =
|
|
1606
|
+
const search = useSearch();
|
|
1181
1607
|
return React.useMemo(() => new URLSearchParams(search), [search]);
|
|
1182
1608
|
}
|
|
1183
1609
|
|
|
1184
|
-
|
|
1185
1610
|
export function useWpLanguage() {
|
|
1186
1611
|
if (IS_DECOUPLED) {
|
|
1187
1612
|
const translations = translationsData || {};
|
|
1188
|
-
const languages =
|
|
1613
|
+
const languages =
|
|
1614
|
+
Object.keys(translations).length > 0
|
|
1615
|
+
? Object.keys(translations)
|
|
1616
|
+
: ['de', 'en'];
|
|
1189
1617
|
const defaultLanguage = languages[0] || 'de';
|
|
1190
1618
|
|
|
1191
|
-
const pathname =
|
|
1619
|
+
const pathname =
|
|
1620
|
+
typeof window !== 'undefined' ? window.location.pathname : '/';
|
|
1192
1621
|
// Find if the path starts with one of the non-default languages, e.g. "/en" or "/en/"
|
|
1193
|
-
const matchedLang = languages.find(lang => {
|
|
1622
|
+
const matchedLang = languages.find((lang) => {
|
|
1194
1623
|
if (lang === defaultLanguage) return false;
|
|
1195
1624
|
return pathname.startsWith(`/${lang}/`) || pathname === `/${lang}`;
|
|
1196
1625
|
});
|
|
@@ -1199,7 +1628,7 @@ export function useWpLanguage() {
|
|
|
1199
1628
|
// Generate URLs dynamically
|
|
1200
1629
|
const urls: Record<string, string> = {};
|
|
1201
1630
|
const homeUrls: Record<string, string> = {};
|
|
1202
|
-
languages.forEach(lang => {
|
|
1631
|
+
languages.forEach((lang) => {
|
|
1203
1632
|
const url = lang === defaultLanguage ? '/' : `/${lang}/`;
|
|
1204
1633
|
urls[lang] = url;
|
|
1205
1634
|
homeUrls[lang] = url;
|
|
@@ -1207,11 +1636,20 @@ export function useWpLanguage() {
|
|
|
1207
1636
|
|
|
1208
1637
|
const homeUrl = homeUrls[currentLanguage] || '/';
|
|
1209
1638
|
|
|
1210
|
-
const switchLanguage = React.useCallback(
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
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
|
+
);
|
|
1215
1653
|
|
|
1216
1654
|
return {
|
|
1217
1655
|
currentLanguage,
|
|
@@ -1223,8 +1661,9 @@ export function useWpLanguage() {
|
|
|
1223
1661
|
};
|
|
1224
1662
|
}
|
|
1225
1663
|
|
|
1226
|
-
const translations =
|
|
1227
|
-
|
|
1664
|
+
const translations =
|
|
1665
|
+
typeof window !== 'undefined' ? (window as any).forgeWpTranslations : null;
|
|
1666
|
+
|
|
1228
1667
|
// Dynamic current language slug enqueued by WordPress
|
|
1229
1668
|
const currentLanguage = translations?.currentLanguage || 'de';
|
|
1230
1669
|
|
|
@@ -1232,22 +1671,29 @@ export function useWpLanguage() {
|
|
|
1232
1671
|
const urls: Record<string, string> = translations?.urls || { de: '/' };
|
|
1233
1672
|
|
|
1234
1673
|
// Dynamic dictionary mapping active language slugs to home page URLs
|
|
1235
|
-
const homeUrls: Record<string, string> = translations?.homeUrls || {
|
|
1674
|
+
const homeUrls: Record<string, string> = translations?.homeUrls || {
|
|
1675
|
+
de: '/',
|
|
1676
|
+
};
|
|
1236
1677
|
const homeUrl = homeUrls[currentLanguage] || '/';
|
|
1237
1678
|
|
|
1238
1679
|
// Dynamic list of active language slugs enqueued on the site
|
|
1239
1680
|
const languages = React.useMemo(() => Object.keys(urls), [urls]);
|
|
1240
1681
|
|
|
1241
1682
|
// Redirection helper to switch safely between languages
|
|
1242
|
-
const switchLanguage = React.useCallback(
|
|
1243
|
-
|
|
1244
|
-
if (
|
|
1245
|
-
window.location.
|
|
1246
|
-
|
|
1247
|
-
|
|
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;
|
|
1248
1693
|
}
|
|
1249
|
-
}
|
|
1250
|
-
|
|
1694
|
+
},
|
|
1695
|
+
[urls],
|
|
1696
|
+
);
|
|
1251
1697
|
|
|
1252
1698
|
return {
|
|
1253
1699
|
currentLanguage,
|
|
@@ -1259,7 +1705,6 @@ export function useWpLanguage() {
|
|
|
1259
1705
|
};
|
|
1260
1706
|
}
|
|
1261
1707
|
|
|
1262
|
-
|
|
1263
1708
|
// ── Compiler custom element JSX declarations ──────────────────────────────────
|
|
1264
1709
|
|
|
1265
1710
|
declare global {
|