/** * Fallback-safe i18n for self-bundled React entries (improvement-plan P2-4). * * Delegates to `window.wp.i18n` (loaded via the `wp-i18n` script dependency + * `wp_set_script_translations`) when present, and falls back to identity * functions otherwise so the UI never crashes if wp-i18n is missing or loads * late. Resolution happens at call time, not module load, so translations * registered before our module scripts execute are always picked up. * * Signature-compatible with @wordpress/i18n: `__( text, domain )`. * Text domain for all plugin strings: `llmagnet-llm-txt-generator`. * * NOTE: the editor bundle aliases `@wordpress/i18n` to src/wp-externals/i18n.ts * (hard dependency on wp-i18n). Shared/self-bundled components import from * this module instead. */ function wpI18n() { return typeof window !== 'undefined' ? window.wp?.i18n : undefined; } /** * Minimal printf fallback: supports %s, %d, %f and positional %1$s forms, * which covers every placeholder used in this plugin's strings. */ function fallbackSprintf(format: string, ...args: Array): string { let cursor = 0; return format.replace(/%(\d+\$)?[sdf]/g, (match, position?: string) => { const index = position ? parseInt(position, 10) - 1 : cursor++; const value = args[index]; return value === undefined ? match : String(value); }); } /** Translate a string. */ export function __(text: string, domain?: string): string { const impl = wpI18n(); return impl?.__ ? impl.__(text, domain) : text; } /** Translate a string with gettext context. */ export function _x(text: string, context: string, domain?: string): string { const impl = wpI18n(); return impl?._x ? impl._x(text, context, domain) : text; } /** Translate and retrieve the singular or plural form based on the supplied number. */ export function _n(single: string, plural: string, number: number, domain?: string): string { const impl = wpI18n(); if (impl?._n) { return impl._n(single, plural, number, domain); } return number === 1 ? single : plural; } /** Plural form with gettext context. */ export function _nx( single: string, plural: string, number: number, context: string, domain?: string, ): string { const impl = wpI18n(); if (impl?._nx) { return impl._nx(single, plural, number, context, domain); } return number === 1 ? single : plural; } /** printf-style string substitution (wp.i18n sprintf when available). */ export function sprintf(format: string, ...args: Array): string { const impl = wpI18n(); if (impl?.sprintf) { try { return impl.sprintf(format, ...args); } catch { return fallbackSprintf(format, ...args); } } return fallbackSprintf(format, ...args); } /** Whether the current locale is right-to-left. */ export function isRTL(): boolean { const impl = wpI18n(); if (impl?.isRTL) { return impl.isRTL(); } return typeof document !== 'undefined' && document.documentElement.dir === 'rtl'; }