From ebf18e59ff403424fe03cfc855a19865773b29d1 Mon Sep 17 00:00:00 2001 From: Sky Mulley Date: Mon, 23 Nov 2026 16:25:46 +0000 Subject: [PATCH] bug run through --- .../Commands/Translations/CoverageCommand.php | 1 + .../Api/Client/AccountController.php | 2 +- .../Api/Client/Servers/StartupController.php | 2 +- .../Admin/RequireSessionAuthentication.php | 2 +- .../Servers/StoreServerRequest.php | 2 +- .../Servers/Schedules/ViewScheduleRequest.php | 2 +- app/Http/Requests/Base/LocaleRequest.php | 3 +- .../Concerns/ValidatesNodeAcceptsEgg.php | 13 ++-- .../Api/Concerns/FormatsActivityLogs.php | 12 ++++ app/Services/Extensions/ExtensionManifest.php | 4 +- .../Scaffolding/stubs/language-readme.stub | 10 ++-- app/Services/Themes/ThemeSetting.php | 2 +- .../Translations/LanguageRegistry.php | 10 +++- .../Translations/TranslationCoverage.php | 10 +++- ...23_000000_make_users_language_nullable.php | 3 +- .../hello-world/src/client/examples.spec.tsx | 2 +- packages/sdk/manifest.schema.json | 4 +- .../types/components/elements/Translate.d.ts | 5 +- packages/sdk/types/lib/formatters.d.ts | 3 +- packages/sdk/types/sdk/index.d.ts | 2 +- resources/lang/en.json | 46 +++++++++------ resources/lang/en/activity.php | 3 + resources/lang/en/exceptions.php | 2 + resources/lang/en/validation.php | 2 + resources/scripts/api/server/files/queries.ts | 2 +- .../components/admin/api/ApiKeyTable.tsx | 2 +- .../admin/extensions/ExtensionsContainer.tsx | 5 +- .../locations/LocationDetailContainer.tsx | 6 +- .../admin/nodes/NodeAllocationTab.tsx | 8 ++- .../admin/servers/ServerDatabaseTab.tsx | 4 +- .../components/elements/Translate.spec.tsx | 59 +++++++++++++++++++ .../scripts/components/elements/Translate.tsx | 43 +++++++++++++- .../elements/table/DataTablePagination.tsx | 18 +++--- .../elements/table/PaginationFooter.tsx | 4 +- resources/scripts/components/ui/Select.tsx | 2 +- resources/scripts/i18n.spec.ts | 48 +++++++++++++++ resources/scripts/i18n.ts | 35 +++++++++-- resources/scripts/lib/dayjs.spec.ts | 17 ++++++ resources/scripts/lib/dayjs.ts | 33 +++++++---- resources/scripts/lib/formatters.spec.ts | 11 +++- resources/scripts/lib/formatters.ts | 11 +++- resources/scripts/sdk/index.ts | 2 +- .../views/activity/ActivityLogEntry.tsx | 24 ++++---- .../views/dashboard/ServerCardMetrics.tsx | 4 +- .../views/server/backups/BackupList.tsx | 15 ++++- .../classic/views/server/console/Graphs.tsx | 13 +++- .../classic/views/server/console/Stats.tsx | 4 +- .../views/server/databases/Databases.tsx | 6 +- .../server/files/FileManagerSelection.tsx | 6 +- .../classic/views/server/files/Uploads.tsx | 2 +- .../views/server/network/Allocations.tsx | 4 +- .../Api/Admin/Servers/ServerTagCheckTest.php | 13 ++++ .../Api/Client/AccountControllerTest.php | 9 +++ .../Translations/LanguagePackTest.php | 15 +++++ .../Controllers/Base/LocaleControllerTest.php | 8 ++- 55 files changed, 462 insertions(+), 118 deletions(-) diff --git a/app/Console/Commands/Translations/CoverageCommand.php b/app/Console/Commands/Translations/CoverageCommand.php index f0b2e2ee0..5de8ecd26 100644 --- a/app/Console/Commands/Translations/CoverageCommand.php +++ b/app/Console/Commands/Translations/CoverageCommand.php @@ -56,6 +56,7 @@ class CoverageCommand extends Command $this->components->info(sprintf('%s%s: %d of %d keys translated (%s%%).', $locale, $pack instanceof ExtensionManifest ? " ({$pack->id})" : '', $report['translated'], $report['total'], $percentage)); $this->section('Missing', $report['missing']); + $this->section('Same as English', $report['unchanged']); $this->section('Not strings', $report['invalid']); $this->section('Placeholders English does not have', $this->describe($report['unknown_placeholders'])); $this->section('Placeholders left out', $this->describe($report['dropped_placeholders'])); diff --git a/app/Http/Controllers/Api/Client/AccountController.php b/app/Http/Controllers/Api/Client/AccountController.php index c39e4267a..38f72dbf1 100644 --- a/app/Http/Controllers/Api/Client/AccountController.php +++ b/app/Http/Controllers/Api/Client/AccountController.php @@ -101,7 +101,7 @@ class AccountController extends ClientApiController if ($original !== $user->language) { Activity::event('user:account.language-changed') ->subject($user) - ->property(['old' => $original ?? 'default', 'new' => $user->language ?? 'default']) + ->property(['old' => $original, 'new' => $user->language]) ->log(); } diff --git a/app/Http/Controllers/Api/Client/Servers/StartupController.php b/app/Http/Controllers/Api/Client/Servers/StartupController.php index 7c6e3d4d8..4cb41e6e8 100644 --- a/app/Http/Controllers/Api/Client/Servers/StartupController.php +++ b/app/Http/Controllers/Api/Client/Servers/StartupController.php @@ -60,7 +60,7 @@ class StartupController extends ClientApiController public function update(UpdateStartupVariableRequest $request, UpdatesServerVariable $variables, Server $server): EggVariableResource { $variable = $request->variable(); - throw_if(! $variable instanceof EggVariable || ! $variable->user_viewable, BadRequestHttpException::class, 'The environment variable you are trying to edit does not exist.'); + throw_if(! $variable instanceof EggVariable || ! $variable->user_viewable, BadRequestHttpException::class, __('exceptions.server.variable_not_found')); throw_unless($variable->user_editable, BadRequestHttpException::class, __('exceptions.server.variable_read_only')); diff --git a/app/Http/Middleware/Api/Admin/RequireSessionAuthentication.php b/app/Http/Middleware/Api/Admin/RequireSessionAuthentication.php index 14dd78494..189ffd319 100644 --- a/app/Http/Middleware/Api/Admin/RequireSessionAuthentication.php +++ b/app/Http/Middleware/Api/Admin/RequireSessionAuthentication.php @@ -22,7 +22,7 @@ class RequireSessionAuthentication { $token = $request->user()?->currentAccessToken(); - throw_unless($token instanceof TransientToken, AccessDeniedHttpException::class, 'This action can only be performed from an authenticated panel session, not with an API key.'); + throw_unless($token instanceof TransientToken, AccessDeniedHttpException::class, __('exceptions.api.session_required')); return $next($request); } diff --git a/app/Http/Requests/Api/Application/Servers/StoreServerRequest.php b/app/Http/Requests/Api/Application/Servers/StoreServerRequest.php index 57bfef6cb..218c7e342 100644 --- a/app/Http/Requests/Api/Application/Servers/StoreServerRequest.php +++ b/app/Http/Requests/Api/Application/Servers/StoreServerRequest.php @@ -153,7 +153,7 @@ class StoreServerRequest extends ApplicationApiRequest private function validateDeployTagReference(string $attribute, mixed $value, Closure $fail): void { if (! is_int($value) && ! is_string($value)) { - $fail("The {$attribute} field must be a tag ID or slug."); + $fail(__('validation.internal.tag_reference')); } } } diff --git a/app/Http/Requests/Api/Client/Servers/Schedules/ViewScheduleRequest.php b/app/Http/Requests/Api/Client/Servers/Schedules/ViewScheduleRequest.php index 1f9a76be5..5c7a757ad 100644 --- a/app/Http/Requests/Api/Client/Servers/Schedules/ViewScheduleRequest.php +++ b/app/Http/Requests/Api/Client/Servers/Schedules/ViewScheduleRequest.php @@ -34,7 +34,7 @@ class ViewScheduleRequest extends ClientApiRequest implements ClientPermissionsR // error if the task being requested does not belong to the associated schedule. if ($schedule instanceof Schedule) { $task = $route->parameter('task'); - throw_if($schedule->server_id !== $server->id || ($task instanceof Task && $task->schedule_id !== $schedule->id), NotFoundHttpException::class, 'The requested resource does not exist on the system.'); + throw_if($schedule->server_id !== $server->id || ($task instanceof Task && $task->schedule_id !== $schedule->id), NotFoundHttpException::class, __('exceptions.api.resource_not_on_system')); } return true; diff --git a/app/Http/Requests/Base/LocaleRequest.php b/app/Http/Requests/Base/LocaleRequest.php index 67d1591ce..e287af63b 100644 --- a/app/Http/Requests/Base/LocaleRequest.php +++ b/app/Http/Requests/Base/LocaleRequest.php @@ -5,10 +5,11 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Base; use Illuminate\Foundation\Http\FormRequest; +use Pterodactyl\Services\Extensions\ExtensionManifest; class LocaleRequest extends FormRequest { - private const string LOCALE = '[a-z]{2}(?:_[A-Z]{2})?'; + private const string LOCALE = ExtensionManifest::LOCALE_PATTERN; private const string NAMESPACE = '(?:[a-z]{1,191}|ext-[a-z][a-z0-9-]{0,47}::[a-z][a-z0-9_-]{0,63})'; diff --git a/app/Http/Requests/Concerns/ValidatesNodeAcceptsEgg.php b/app/Http/Requests/Concerns/ValidatesNodeAcceptsEgg.php index 36e0fa04c..75e7e585b 100644 --- a/app/Http/Requests/Concerns/ValidatesNodeAcceptsEgg.php +++ b/app/Http/Requests/Concerns/ValidatesNodeAcceptsEgg.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pterodactyl\Http\Requests\Concerns; +use Illuminate\Support\Str; use Illuminate\Validation\Validator; use Pterodactyl\Models\Egg; use Pterodactyl\Models\Node; @@ -22,12 +23,14 @@ trait ValidatesNodeAcceptsEgg return; } - $tags = $node->eggTags->map(fn (Tag $tag): string => $tag->effectiveName())->implode(', '); + $replacements = []; + foreach (['node' => $node->name, 'tags' => $node->eggTags->map(fn (Tag $tag): string => $tag->effectiveName())->implode(', ')] as $key => $value) { + $replacements[':'.$key] = $value; + $replacements[':'.Str::ucfirst($key)] = Str::ucfirst($value); + $replacements[':'.Str::upper($key)] = Str::upper($value); + } - $validator->addReplacer( - 'node_accepts_egg', - fn (string $message): string => str_replace([':node', ':tags'], [$node->name, $tags], $message), - ); + $validator->addReplacer('node_accepts_egg', fn (string $message): string => strtr($message, $replacements)); $validator->addFailure($field, 'NodeAcceptsEgg'); } diff --git a/app/Http/Resources/Api/Concerns/FormatsActivityLogs.php b/app/Http/Resources/Api/Concerns/FormatsActivityLogs.php index 671b3720f..263fc64ed 100644 --- a/app/Http/Resources/Api/Concerns/FormatsActivityLogs.php +++ b/app/Http/Resources/Api/Concerns/FormatsActivityLogs.php @@ -6,6 +6,7 @@ namespace Pterodactyl\Http\Resources\Api\Concerns; use Illuminate\Support\Str; use Pterodactyl\Models\ActivityLog; +use Pterodactyl\Services\Translations\LanguageRegistry; use stdClass; trait FormatsActivityLogs @@ -59,6 +60,10 @@ trait FormatsActivityLogs return [$key => $value]; }); + if ($model->event === 'user:account.language-changed') { + $properties = $properties->merge(array_map($this->languageLabel(...), $properties->only(['old', 'new'])->all())); + } + $keys = $properties->keys()->filter(fn (int|string $key): bool => Str::endsWith((string) $key, '_count'))->values(); if ($keys->containsOneItem()) { $countKey = $keys->first(); @@ -98,4 +103,11 @@ trait FormatsActivityLogs return false; } + + private function languageLabel(mixed $locale): string + { + return is_string($locale) && $locale !== '' && $locale !== 'default' + ? LanguageRegistry::displayName($locale, app()->getLocale()) + : __('activity.values.panel-default'); + } } diff --git a/app/Services/Extensions/ExtensionManifest.php b/app/Services/Extensions/ExtensionManifest.php index 14cef4b79..bb7e3be94 100644 --- a/app/Services/Extensions/ExtensionManifest.php +++ b/app/Services/Extensions/ExtensionManifest.php @@ -19,7 +19,9 @@ class ExtensionManifest public const string LANGUAGES_DIRECTORY = 'resources/languages'; - public const string LOCALE_REGEX = '/^[a-z]{2}(?:_[A-Z]{2})?$/D'; + public const string LOCALE_PATTERN = '[a-z]{2,3}(?:_[A-Z][a-z]{3})?(?:_(?:[A-Z]{2}|[0-9]{3}))?'; + + public const string LOCALE_REGEX = '/^'.self::LOCALE_PATTERN.'$/D'; public const array TYPES = ['extension', 'theme']; diff --git a/app/Services/Extensions/Scaffolding/stubs/language-readme.stub b/app/Services/Extensions/Scaffolding/stubs/language-readme.stub index 5ee5678ee..41c931a22 100644 --- a/app/Services/Extensions/Scaffolding/stubs/language-readme.stub +++ b/app/Services/Extensions/Scaffolding/stubs/language-readme.stub @@ -21,8 +21,8 @@ file only needs the keys it translates. Extensions add their interface text to t `resources/languages/vendor/ext-/{{language}}/.php` with that extension's keys. When two enabled packs provide the same key for a locale, the one loaded later wins: a pack listed under -`requires.extensions` loads first, and unrelated packs load in alphabetical order. The extension page in -the admin area and `p:lang:coverage` list such conflicts. +`requires.extensions` loads first, and unrelated packs load in alphabetical order. +`p:lang:coverage` and the Admin API's extension listing (`language_conflicts`) report such conflicts. ## Develop @@ -32,5 +32,7 @@ php {{artisan}} p:lang:coverage {{language}} --extension={{id}} php {{artisan}} p:extension:pack . ``` -`p:lang:coverage` lists missing and stale keys and placeholder mistakes, and exits non-zero when keys are -missing or a translation uses a placeholder English does not. +`p:lang:coverage` lists missing and stale keys, values still the same as the English, and placeholder +mistakes. It exits non-zero when keys are missing or a translation uses a placeholder English does not. The +scaffolded files start as copies of the English, so every key is listed as the same as English until it is +translated. diff --git a/app/Services/Themes/ThemeSetting.php b/app/Services/Themes/ThemeSetting.php index bc0b753e5..9ea71fc71 100644 --- a/app/Services/Themes/ThemeSetting.php +++ b/app/Services/Themes/ThemeSetting.php @@ -190,7 +190,7 @@ final readonly class ThemeSetting return function (string $attribute, mixed $value, Closure $fail) use ($step, $base): void { $steps = is_numeric($value) ? ((float) $value - $base) / $step : 0.5; if (abs($steps - round($steps)) > 1e-9) { - $fail("The :attribute must be in steps of {$this->step}."); + $fail(__('validation.internal.setting_step', ['step' => $this->step])); } }; } diff --git a/app/Services/Translations/LanguageRegistry.php b/app/Services/Translations/LanguageRegistry.php index 5514487a8..024da587f 100644 --- a/app/Services/Translations/LanguageRegistry.php +++ b/app/Services/Translations/LanguageRegistry.php @@ -100,6 +100,13 @@ class LanguageRegistry return $entries; } + public static function displayName(string $locale, string $in): string + { + $name = Locale::getDisplayName($locale, $in); + + return Str::title($name === false ? $locale : $name); + } + /** * @return Collection */ @@ -147,8 +154,7 @@ class LanguageRegistry { $languages = []; foreach (array_keys($this->sources()) as $locale) { - $name = Locale::getDisplayName($locale, $localize ? $locale : self::FALLBACK); - $languages[$locale] = Str::title($name === false ? $locale : $name); + $languages[$locale] = self::displayName($locale, $localize ? $locale : self::FALLBACK); } return $languages; diff --git a/app/Services/Translations/TranslationCoverage.php b/app/Services/Translations/TranslationCoverage.php index 9dc0485bf..cd71af34f 100644 --- a/app/Services/Translations/TranslationCoverage.php +++ b/app/Services/Translations/TranslationCoverage.php @@ -25,7 +25,7 @@ class TranslationCoverage ) {} /** - * @return array{locale: string, extension: string|null, total: int, translated: int, missing: list, stale: list, invalid: list, unknown_placeholders: array>, dropped_placeholders: array>, conflicts: list, winner: string}>} + * @return array{locale: string, extension: string|null, total: int, translated: int, missing: list, unchanged: list, stale: list, invalid: list, unknown_placeholders: array>, dropped_placeholders: array>, conflicts: list, winner: string}>} */ public function report(string $locale, ?ExtensionManifest $pack = null): array { @@ -41,6 +41,7 @@ class TranslationCoverage } $missing = []; + $unchanged = []; $unknown = []; $dropped = []; foreach ($base as $key => $english) { @@ -52,6 +53,10 @@ class TranslationCoverage continue; } + if ($value === $english) { + $unchanged[] = $key; + } + $expected = $this->placeholders($key, $english); $found = $this->placeholders($key, $value); if (($extra = array_values(array_diff($found, $expected))) !== []) { @@ -98,8 +103,9 @@ class TranslationCoverage 'locale' => $locale, 'extension' => $pack?->id, 'total' => count($base), - 'translated' => count($base) - count($missing), + 'translated' => count($base) - count($missing) - count($unchanged), 'missing' => $missing, + 'unchanged' => $unchanged, 'stale' => $stale, 'invalid' => $invalid, 'unknown_placeholders' => $unknown, diff --git a/database/migrations/2026_10_23_000000_make_users_language_nullable.php b/database/migrations/2026_10_23_000000_make_users_language_nullable.php index 83d3bf4e9..c4030fda8 100644 --- a/database/migrations/2026_10_23_000000_make_users_language_nullable.php +++ b/database/migrations/2026_10_23_000000_make_users_language_nullable.php @@ -12,7 +12,7 @@ return new class extends Migration public function up(): void { Schema::table('users', function (Blueprint $table): void { - $table->char('language', 5)->nullable()->default(null)->change(); + $table->string('language', 16)->nullable()->default(null)->change(); }); DB::table('users')->where('language', 'en')->update(['language' => null]); @@ -20,6 +20,7 @@ return new class extends Migration public function down(): void { + DB::table('users')->whereRaw('LENGTH(language) > 5')->update(['language' => null]); DB::table('users')->whereNull('language')->update(['language' => 'en']); Schema::table('users', function (Blueprint $table): void { diff --git a/packages/hello-world/src/client/examples.spec.tsx b/packages/hello-world/src/client/examples.spec.tsx index 860f76a56..1b109bd39 100644 --- a/packages/hello-world/src/client/examples.spec.tsx +++ b/packages/hello-world/src/client/examples.spec.tsx @@ -202,7 +202,7 @@ it('composes the native server card using the real SDK fixture', () => { }); expect(screen.getByText('Survival')).toBeTruthy(); - expect(screen.getByText('12.00 %')).toBeTruthy(); + expect(screen.getByText('12.00%')).toBeTruthy(); // The prefixed utility replaces the native card's own gap instead of sitting beside it. const card = screen.getByText('Survival').closest('.grid'); diff --git a/packages/sdk/manifest.schema.json b/packages/sdk/manifest.schema.json index 1a9416c21..f074d5fef 100644 --- a/packages/sdk/manifest.schema.json +++ b/packages/sdk/manifest.schema.json @@ -130,9 +130,9 @@ "uniqueItems": true, "items": { "type": "string", - "pattern": "^[a-z]{2}(?:_[A-Z]{2})?$" + "pattern": "^[a-z]{2,3}(?:_[A-Z][a-z]{3})?(?:_(?:[A-Z]{2}|[0-9]{3}))?$" }, - "description": "Locales this package translates the panel into, such as de or pt_BR. Each one is a directory under resources/languages holding PHP files for core translation groups, which merge over the panel's own; resources/languages/vendor/ext-/ translates another extension. Packages that declare the same locale merge key by key, a package listed in requires.extensions loading first." + "description": "Locales this package translates the panel into, such as de, pt_BR or zh_Hant. Each one is a directory under resources/languages holding PHP files for core translation groups, which merge over the panel's own; resources/languages/vendor/ext-/ translates another extension. Packages that declare the same locale merge key by key, a package listed in requires.extensions loading first." }, "routes": { "type": "object", diff --git a/packages/sdk/types/components/elements/Translate.d.ts b/packages/sdk/types/components/elements/Translate.d.ts index 5d52c47b3..c6ced2ee7 100644 --- a/packages/sdk/types/components/elements/Translate.d.ts +++ b/packages/sdk/types/components/elements/Translate.d.ts @@ -9,7 +9,10 @@ interface Props { i18nKey: string; values?: TranslationValues; components?: Readonly>; + valueComponent?: React.ReactElement<{ + children?: React.ReactNode; + }>; children?: React.ReactNode; } -export default function Translate({ ns, children, ...props }: Props): React.JSX.Element; +export default function Translate({ ns, children, values, components, valueComponent, ...props }: Props): React.JSX.Element; export {}; diff --git a/packages/sdk/types/lib/formatters.d.ts b/packages/sdk/types/lib/formatters.d.ts index 343777fe8..5f44dc724 100644 --- a/packages/sdk/types/lib/formatters.d.ts +++ b/packages/sdk/types/lib/formatters.d.ts @@ -2,6 +2,7 @@ declare function mbToBytes(megabytes: number): number; declare function bytesToString(bytes: number, decimals?: number): string; declare function bytesRatioToString(used: number, total: number, decimals?: number): string; +declare function percentageToString(value: number, decimals?: number): string; /** Wraps IPv6 addresses in brackets. */ declare function ip(value: string): string; -export { ip, mbToBytes, bytesToString, bytesRatioToString }; +export { ip, mbToBytes, bytesToString, bytesRatioToString, percentageToString }; diff --git a/packages/sdk/types/sdk/index.d.ts b/packages/sdk/types/sdk/index.d.ts index 9c0210283..61a1bb102 100644 --- a/packages/sdk/types/sdk/index.d.ts +++ b/packages/sdk/types/sdk/index.d.ts @@ -56,7 +56,7 @@ export * from "./navigation.js"; export * from "./localization.js"; export * from "./progress.js"; export { onThemeChange, notifyThemeChange, readThemeToken } from "./theme.js"; -export { bytesToString, ip, mbToBytes } from "../lib/formatters.js"; +export { bytesToString, ip, mbToBytes, percentageToString } from "../lib/formatters.js"; export { formatDate, fromNow } from "../lib/dates.js"; export { useDebouncedCallback, type DebouncedCallback } from "../plugins/useDebouncedCallback.js"; export { useShortcut, type Shortcut } from "../plugins/useShortcut.js"; diff --git a/resources/lang/en.json b/resources/lang/en.json index 39195504e..5383c6053 100644 --- a/resources/lang/en.json +++ b/resources/lang/en.json @@ -217,7 +217,8 @@ "Application Feature Limits": "Application Feature Limits", "Archive": "Archive", "Archive started": "Archive started", - "Are you sure you want to delete {{number}} files? This is a permanent action and the files cannot be recovered.": "Are you sure you want to delete {{number}} files? This is a permanent action and the files cannot be recovered.", + "Are you sure you want to delete {{count}} files? This is a permanent action and the files cannot be recovered._one": "Are you sure you want to delete {{count}} file? This is a permanent action and the file cannot be recovered.", + "Are you sure you want to delete {{count}} files? This is a permanent action and the files cannot be recovered._other": "Are you sure you want to delete {{count}} files? This is a permanent action and the files cannot be recovered.", "Are you sure you want to delete this task? This action cannot be undone.": "Are you sure you want to delete this task? This action cannot be undone.", "Are you sure you wish to remove this subuser? They will have all access to this server revoked immediately.": "Are you sure you wish to remove this subuser? They will have all access to this server revoked immediately.", "Assign Additional Ports": "Assign Additional Ports", @@ -635,13 +636,13 @@ "File Name": "File Name", "File Uploads": "File Uploads", "File copied": "File copied", - "File deleted": "File deleted", "File editor": "File editor", "File removed": "File removed", "File saved": "File saved", "File uploaded": "File uploaded", "Files": "Files", - "Files deleted": "Files deleted", + "Files deleted_one": "File deleted", + "Files deleted_other": "Files deleted", "Files updated": "Files updated", "Find": "Find", "Find and import server templates from eggs.pterodactyl.io.": "Find and import server templates from eggs.pterodactyl.io.", @@ -1227,23 +1228,28 @@ "Showing {{start}} to {{end}} of {{count}} API keys_other": "Showing {{start}} to {{end}} of {{count}} API keys", "Showing {{start}} to {{end}} of {{count}} allocations_one": "Showing {{start}} to {{end}} of {{count}} allocation", "Showing {{start}} to {{end}} of {{count}} allocations_other": "Showing {{start}} to {{end}} of {{count}} allocations", + "Showing {{start}} to {{end}} of {{count}} backups_one": "Showing {{start}} to {{end}} of {{count}} backup", + "Showing {{start}} to {{end}} of {{count}} backups_other": "Showing {{start}} to {{end}} of {{count}} backups", "Showing {{start}} to {{end}} of {{count}} database hosts_one": "Showing {{start}} to {{end}} of {{count}} database host", "Showing {{start}} to {{end}} of {{count}} database hosts_other": "Showing {{start}} to {{end}} of {{count}} database hosts", "Showing {{start}} to {{end}} of {{count}} databases_one": "Showing {{start}} to {{end}} of {{count}} database", "Showing {{start}} to {{end}} of {{count}} databases_other": "Showing {{start}} to {{end}} of {{count}} databases", + "Showing {{start}} to {{end}} of {{count}} items_one": "Showing {{start}} to {{end}} of {{count}} item", + "Showing {{start}} to {{end}} of {{count}} items_other": "Showing {{start}} to {{end}} of {{count}} items", "Showing {{start}} to {{end}} of {{count}} locations_one": "Showing {{start}} to {{end}} of {{count}} location", "Showing {{start}} to {{end}} of {{count}} locations_other": "Showing {{start}} to {{end}} of {{count}} locations", "Showing {{start}} to {{end}} of {{count}} mounts_one": "Showing {{start}} to {{end}} of {{count}} mount", "Showing {{start}} to {{end}} of {{count}} mounts_other": "Showing {{start}} to {{end}} of {{count}} mounts", "Showing {{start}} to {{end}} of {{count}} nodes_one": "Showing {{start}} to {{end}} of {{count}} node", "Showing {{start}} to {{end}} of {{count}} nodes_other": "Showing {{start}} to {{end}} of {{count}} nodes", + "Showing {{start}} to {{end}} of {{count}} results._one": "Showing {{start}} to {{end}} of {{count}} result.", + "Showing {{start}} to {{end}} of {{count}} results._other": "Showing {{start}} to {{end}} of {{count}} results.", "Showing {{start}} to {{end}} of {{count}} servers_one": "Showing {{start}} to {{end}} of {{count}} server", "Showing {{start}} to {{end}} of {{count}} servers_other": "Showing {{start}} to {{end}} of {{count}} servers", "Showing {{start}} to {{end}} of {{count}} tags_one": "Showing {{start}} to {{end}} of {{count}} tag", "Showing {{start}} to {{end}} of {{count}} tags_other": "Showing {{start}} to {{end}} of {{count}} tags", "Showing {{start}} to {{end}} of {{count}} users_one": "Showing {{start}} to {{end}} of {{count}} user", "Showing {{start}} to {{end}} of {{count}} users_other": "Showing {{start}} to {{end}} of {{count}} users", - "Showing {{start}} to {{end}} of {{total}} results.": "Showing {{start}} to {{end}} of {{total}} results.", "Showing {{start}} to {{end}} of {{total}} {{items}}": "Showing {{start}} to {{end}} of {{total}} {{items}}", "Showing others' servers": "Showing others' servers", "Showing your servers": "Showing your servers", @@ -1464,7 +1470,8 @@ "This will flip the install status between installed and installing for this server.": "This will flip the install status between installed and installing for this server.", "This will permanently delete every unassigned allocation for {{ip}}. This action cannot be undone.": "This will permanently delete every unassigned allocation for {{ip}}. This action cannot be undone.", "This will permanently delete the {{address}} allocation. This action cannot be undone.": "This will permanently delete the {{address}} allocation. This action cannot be undone.", - "This will permanently delete the {{selected}} selected allocation(s). This action cannot be undone.": "This will permanently delete the {{selected}} selected allocation(s). This action cannot be undone.", + "This will permanently delete the {{count}} selected allocations. This action cannot be undone._one": "This will permanently delete the {{count}} selected allocation. This action cannot be undone.", + "This will permanently delete the {{count}} selected allocations. This action cannot be undone._other": "This will permanently delete the {{count}} selected allocations. This action cannot be undone.", "This will permanently remove the {{name}} variable from this egg.": "This will permanently remove the {{name}} variable from this egg.", "This will reinstall the server with its assigned service scripts. This could overwrite server data.": "This will reinstall the server with its assigned service scripts. This could overwrite server data.", "This will reinstall the server with the assigned service scripts.": "This will reinstall the server with the assigned service scripts.", @@ -1700,7 +1707,8 @@ "Wings {{version}}": "Wings {{version}}", "Yes, reinstall server": "Yes, reinstall server", "Yes, remove subuser": "Yes, remove subuser", - "You are currently using {{used}} of {{limit}} allowed allocations for this server.": "You are currently using {{used}} of {{limit}} allowed allocations for this server.", + "You are currently using {{used}} of {{count}} allowed allocations for this server._one": "You are currently using {{used}} of {{count}} allowed allocation for this server.", + "You are currently using {{used}} of {{count}} allowed allocations for this server._other": "You are currently using {{used}} of {{count}} allowed allocations for this server.", "You are running version {{current}}.": "You are running version {{current}}.", "You are running version {{current}}; the latest available is {{latest}}.": "You are running version {{current}}; the latest available is {{latest}}.", "You are using reCAPTCHA keys that shipped with this Panel. Generate new invisible reCAPTCHA keys for this website to improve security.": "You are using reCAPTCHA keys that shipped with this Panel. Generate new invisible reCAPTCHA keys for this website to improve security.", @@ -1735,9 +1743,9 @@ "Your server will be stopped and some files may be deleted or modified during this process, are you sure you wish to continue?": "Your server will be stopped and some files may be deleted or modified during this process, are you sure you wish to continue?", "Your server will be stopped. You will not be able to control the power state, access the file manager, or create additional backups until completed.": "Your server will be stopped. You will not be able to control the power state, access the file manager, or create additional backups until completed.", "active": "active", - "and {{number}} others": "and {{number}} others", + "and {{count}} others_one": "and {{count}} other", + "and {{count}} others_other": "and {{count}} others", "any value": "any value", - "backups": "backups", "by {{author}}": "by {{author}}", "every 5 minutes": "every 5 minutes", "every Monday": "every Monday", @@ -1745,7 +1753,6 @@ "every hour": "every hour", "hour range": "hour range", "inactive": "inactive", - "items": "items", "n/a": "n/a", "new": "new", "of {{limit}}": "of {{limit}}", @@ -1762,7 +1769,6 @@ "up to {{size}} KB": "up to {{size}} KB", "value list separator": "value list separator", "{{address}} is available.": "{{address}} is available.", - "{{allocated}} of {{limit}} databases have been allocated to this server.": "{{allocated}} of {{limit}} databases have been allocated to this server.", "{{count}} allocations_one": "{{count}} allocation", "{{count}} allocations_other": "{{count}} allocations", "{{count}} databases_one": "{{count}} database", @@ -1771,9 +1777,18 @@ "{{count}} eggs_other": "{{count}} eggs", "{{count}} extensions need attention_one": "{{count}} extension needs attention", "{{count}} extensions need attention_other": "{{count}} extensions need attention", + "{{count}} files are uploading, click to view_one": "{{count}} file is uploading, click to view", + "{{count}} files are uploading, click to view_other": "{{count}} files are uploading, click to view", + "{{count}} granted_one": "{{count}} granted", + "{{count}} granted_other": "{{count}} granted", "{{count}} nodes_one": "{{count}} node", "{{count}} nodes_other": "{{count}} nodes", - "{{created}} of {{limit}} backups have been created for this server.": "{{created}} of {{limit}} backups have been created for this server.", + "{{count}} selected_one": "{{count}} selected", + "{{count}} selected_other": "{{count}} selected", + "{{count}} servers_one": "{{count}} server", + "{{count}} servers_other": "{{count}} servers", + "{{created}} of {{count}} backups have been created for this server._one": "{{created}} of {{count}} backup has been created for this server.", + "{{created}} of {{count}} backups have been created for this server._other": "{{created}} of {{count}} backups have been created for this server.", "{{days}}d {{hours}}h {{minutes}}m": "{{days}}d {{hours}}h {{minutes}}m", "{{email}} avatar": "{{email}} avatar", "{{email}} has been invited.": "{{email}} has been invited.", @@ -1810,14 +1825,11 @@ "{{name}} is now active. Reload the page to see it.": "{{name}} is now active. Reload the page to see it.", "{{name}} is ready to use.": "{{name}} is ready to use.", "{{name}} settings": "{{name}} settings", - "{{nodes}} nodes · {{servers}} servers": "{{nodes}} nodes · {{servers}} servers", + "{{nodes}} · {{servers}}": "{{nodes}} · {{servers}}", "{{node}} only accepts eggs tagged {{tags}}.": "{{node}} only accepts eggs tagged {{tags}}.", - "{{number}} files are uploading, click to view": "{{number}} files are uploading, click to view", "{{seconds}}s later": "{{seconds}}s later", - "{{selected}} selected": "{{selected}} selected", "{{title}} usage": "{{title}} usage", - "{{total}} granted": "{{total}} granted", - "{{total}} selected": "{{total}} selected", "{{unassigned}} unassigned": "{{unassigned}} unassigned", - "{{used}} of {{limit}} databases have been allocated to this server.": "{{used}} of {{limit}} databases have been allocated to this server." + "{{used}} of {{count}} databases have been allocated to this server._one": "{{used}} of {{count}} database has been allocated to this server.", + "{{used}} of {{count}} databases have been allocated to this server._other": "{{used}} of {{count}} databases have been allocated to this server." } diff --git a/resources/lang/en/activity.php b/resources/lang/en/activity.php index cb23658f1..f4f0c798a 100644 --- a/resources/lang/en/activity.php +++ b/resources/lang/en/activity.php @@ -241,4 +241,7 @@ return [ 'disable-2fa' => 'Disabled two-factor authentication for :email', ], ], + 'values' => [ + 'panel-default' => 'the panel default', + ], ]; diff --git a/resources/lang/en/exceptions.php b/resources/lang/en/exceptions.php index 362913098..7e53507ba 100644 --- a/resources/lang/en/exceptions.php +++ b/resources/lang/en/exceptions.php @@ -111,6 +111,7 @@ return [ 'default_allocation_not_assigned' => 'The requested default allocation is not currently assigned to this server.', 'offline_command' => 'Server must be online in order to send commands.', 'docker_image_locked' => "This server's Docker image has been manually set by an administrator and cannot be updated.", + 'variable_not_found' => 'The environment variable you are trying to edit does not exist.', 'variable_read_only' => 'The environment variable you are trying to edit is read-only.', 'websocket_forbidden' => "You do not have permission to connect to this server's websocket.", 'transfer_logs_forbidden' => 'You do not have permission to view server transfer logs.', @@ -150,6 +151,7 @@ return [ 'malformed_json' => 'The JSON data passed in the request appears to be malformed: :error', 'unauthenticated' => 'This endpoint requires an authenticated user.', 'unauthorized' => 'This action is unauthorized.', + 'session_required' => 'This action can only be performed from an authenticated panel session, not with an API key.', 'recaptcha_failed' => 'Failed to validate reCAPTCHA data.', 'application_key_rejected' => 'You are attempting to use an application API key on an endpoint that does not accept them.', 'client_key_required' => 'You are attempting to use an application API key on an endpoint that requires a client API key.', diff --git a/resources/lang/en/validation.php b/resources/lang/en/validation.php index a3238bcd5..a6a4919ae 100644 --- a/resources/lang/en/validation.php +++ b/resources/lang/en/validation.php @@ -109,6 +109,8 @@ return [ 'fqdn_ip_with_https' => 'The :attribute must not be an IP address when HTTPS is enabled.', 'path_within' => 'The :field path cannot be or reside within [:path].', 'path_reserved' => 'The :field path cannot be [:path].', + 'tag_reference' => 'The :attribute field must be a tag ID or slug.', + 'setting_step' => 'The :attribute must be in steps of :step.', 'tag_slug_numeric' => 'A tag slug cannot be purely numeric (reserved for tag and legacy nest IDs).', 'docker_images_empty' => 'The :attribute field must list at least one image.', 'docker_image_invalid' => 'The :attribute entry ":image" is not a valid Docker image.', diff --git a/resources/scripts/api/server/files/queries.ts b/resources/scripts/api/server/files/queries.ts index ae85a8057..ac949536e 100644 --- a/resources/scripts/api/server/files/queries.ts +++ b/resources/scripts/api/server/files/queries.ts @@ -356,7 +356,7 @@ export const useDeleteFiles = () => { ); } - toast.success(body?.files?.length === 1 ? i18next.t('File deleted') : i18next.t('Files deleted')); + toast.success(i18next.t('Files deleted', { count: body?.files?.length ?? 0 })); }, onError: (error) => notifyHttpError(error, i18next.t('Unable to delete files')), }); diff --git a/resources/scripts/components/admin/api/ApiKeyTable.tsx b/resources/scripts/components/admin/api/ApiKeyTable.tsx index a675a1ec5..77907baab 100644 --- a/resources/scripts/components/admin/api/ApiKeyTable.tsx +++ b/resources/scripts/components/admin/api/ApiKeyTable.tsx @@ -76,7 +76,7 @@ export const apiKeyColumns = (t: Translation['t']) => header: t('Permissions'), cell: ({ row }) => ( - {t('{{total}} granted', { total: grantedCount(row.original) })} + {t('{{count}} granted', { count: grantedCount(row.original) })} ), enableSorting: false, diff --git a/resources/scripts/components/admin/extensions/ExtensionsContainer.tsx b/resources/scripts/components/admin/extensions/ExtensionsContainer.tsx index e4fb95c28..3dea19914 100644 --- a/resources/scripts/components/admin/extensions/ExtensionsContainer.tsx +++ b/resources/scripts/components/admin/extensions/ExtensionsContainer.tsx @@ -2,6 +2,7 @@ import React, { useState } from 'react'; import { AlertCircle, FileArchive, RefreshCw, Settings2, Trash2, UploadCloud } from 'lucide-react'; import { getExtensionStates, useExtensionRegistry } from '@/extensions/registry'; import { cn } from '@/lib/cn'; +import { formatDate } from '@/lib/dates'; import { httpErrorToHuman } from '@/api/http'; import { disableAdminExtensionInput, @@ -630,9 +631,9 @@ function ExtensionCardDetails({ extension }: { extension: AdminExtension }) { {extension.error_phase ? t('In {{phase}}, {{date}}', { phase: extension.error_phase, - date: new Date(extension.errored_at).toLocaleString(), + date: formatDate(extension.errored_at, 'll LTS'), }) - : new Date(extension.errored_at).toLocaleString()} + : formatDate(extension.errored_at, 'll LTS')}

)} diff --git a/resources/scripts/components/admin/locations/LocationDetailContainer.tsx b/resources/scripts/components/admin/locations/LocationDetailContainer.tsx index 44bed916c..c3e5472b9 100644 --- a/resources/scripts/components/admin/locations/LocationDetailContainer.tsx +++ b/resources/scripts/components/admin/locations/LocationDetailContainer.tsx @@ -206,9 +206,9 @@ function LocationDetailForm({ location }: { location: AdminLocation }) {

{t('Nodes')}

- {t('{{nodes}} nodes · {{servers}} servers', { - nodes: attributes.nodes_count, - servers: attributes.servers_count, + {t('{{nodes}} · {{servers}}', { + nodes: t('{{count}} nodes', { count: attributes.nodes_count }), + servers: t('{{count}} servers', { count: attributes.servers_count }), })}
diff --git a/resources/scripts/components/admin/nodes/NodeAllocationTab.tsx b/resources/scripts/components/admin/nodes/NodeAllocationTab.tsx index c680e787a..45b68bc4a 100644 --- a/resources/scripts/components/admin/nodes/NodeAllocationTab.tsx +++ b/resources/scripts/components/admin/nodes/NodeAllocationTab.tsx @@ -336,7 +336,7 @@ const ExistingAllocationsSummary = ({ selectedCount, total, onBulkDelete }: Exis return (
- {t('{{selected}} selected', { selected: selectedCount })} + {t('{{count}} selected', { count: selectedCount })} {t( - 'This will permanently delete the {{selected}} selected allocation(s). This action cannot be undone.', - { selected: selectedCount } + 'This will permanently delete the {{count}} selected allocations. This action cannot be undone.', + { + count: selectedCount, + } )}
diff --git a/resources/scripts/components/admin/servers/ServerDatabaseTab.tsx b/resources/scripts/components/admin/servers/ServerDatabaseTab.tsx index 314103c13..41bbea7e4 100644 --- a/resources/scripts/components/admin/servers/ServerDatabaseTab.tsx +++ b/resources/scripts/components/admin/servers/ServerDatabaseTab.tsx @@ -90,9 +90,9 @@ function ServerDatabaseContent({ server }: { server: AdminServer }) { const canCreate = databaseLimit > 0 && data.length < databaseLimit; const usage = databaseLimit > 0 && data.length > 0 - ? t('{{used}} of {{limit}} databases have been allocated to this server.', { + ? t('{{used}} of {{count}} databases have been allocated to this server.', { used: data.length, - limit: databaseLimit, + count: databaseLimit, }) : null; diff --git a/resources/scripts/components/elements/Translate.spec.tsx b/resources/scripts/components/elements/Translate.spec.tsx index ba4cc1701..fcface6db 100644 --- a/resources/scripts/components/elements/Translate.spec.tsx +++ b/resources/scripts/components/elements/Translate.spec.tsx @@ -36,3 +36,62 @@ it('translates a catalogue sentence with markup around its values', async () => expect(screen.getByText('Lobby').tagName).toBe('STRONG'); expect(document.body.textContent).toBe('Lobby endgültig löschen?'); }); + +it.each(['ay', 'z', 'a & b'])( + 'keeps the value %s as literal text', + async (name) => { + const i18n = createInstance(); + + await i18n.init({ lng: 'en', nsSeparator: false, interpolation: { escapeValue: false }, resources: {} }); + + const { container } = render( + + }} + /> + + ); + + expect(container.querySelectorAll('strong')).toHaveLength(1); + expect(container.querySelector('strong')?.textContent).toBe(name); + expect(container.textContent).toBe(`Delete ${name} (2)?`); + } +); + +it('wraps every text value, nested and listed ones included, and keeps counts for plurals', async () => { + const i18n = createInstance(); + + await i18n.init({ + lng: 'en', + nsSeparator: false, + interpolation: { escapeValue: false }, + resources: { + en: { + translation: { + 'Deleted {{files}} from {{server.name}}_one': 'Deleted {{files}} from {{server.name}}', + 'Deleted {{files}} from {{server.name}}_other': + 'Deleted {{count}} files ({{files}}) from {{server.name}}', + }, + }, + }, + }); + + const { container } = render( + + x' } }} + valueComponent={} + /> + + ); + + expect([...container.querySelectorAll('strong')].map((node) => node.textContent)).toEqual([ + 'ax', + ]); + expect(container.textContent).toBe('Deleted 2 files (ax'); +}); diff --git a/resources/scripts/components/elements/Translate.tsx b/resources/scripts/components/elements/Translate.tsx index 62a5fcff3..c54c0bff5 100644 --- a/resources/scripts/components/elements/Translate.tsx +++ b/resources/scripts/components/elements/Translate.tsx @@ -16,14 +16,53 @@ interface Props { i18nKey: string; values?: TranslationValues; components?: Readonly>; + valueComponent?: React.ReactElement<{ children?: React.ReactNode }>; children?: React.ReactNode; } -export default function Translate({ ns = 'translation', children, ...props }: Props) { +// Trans parses interpolated values as markup, so text is passed as an element to keep it literal. +function literalValues(values: TranslationValues, wrapper: Props['valueComponent']) { + const elements: Record = {}; + + const visit = (value: TranslationValue): TranslationValue => { + if (value === null || value === true || value === false || Number.isFinite(value)) { + return value; + } + + if (Array.isArray(value)) { + return value.map(visit); + } + + if (value instanceof Object) { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)])); + } + + const name = `value-${Object.keys(elements).length}`; + const text = String(value); + + elements[name] = wrapper + ? React.cloneElement(wrapper, undefined, text) + : React.createElement(React.Fragment, undefined, text); + + return `<${name}/>`; + }; + + return { values: Object.fromEntries(Object.entries(values).map(([key, value]) => [key, visit(value)])), elements }; +} + +export default function Translate({ + ns = 'translation', + children, + values, + components, + valueComponent, + ...props +}: Props) { const { t } = useTranslation(ns); + const literal = literalValues(values ?? {}, valueComponent); return ( - + {children} ); diff --git a/resources/scripts/components/elements/table/DataTablePagination.tsx b/resources/scripts/components/elements/table/DataTablePagination.tsx index b5fc62ed9..fb5f430c9 100644 --- a/resources/scripts/components/elements/table/DataTablePagination.tsx +++ b/resources/scripts/components/elements/table/DataTablePagination.tsx @@ -71,14 +71,16 @@ export default function DataTablePagination({ page: pageIndex + 1, pages: Math.max(pageCount, 1), }); - const text = summary - ? summary(range) - : t('Showing {{start}} to {{end}} of {{total}} {{items}}', { - start, - end, - total, - items: itemLabel ?? t('items'), - }); + const defaultSummary = (shown: PaginationRange): string => + itemLabel + ? t('Showing {{start}} to {{end}} of {{total}} {{items}}', { + start: shown.start, + end: shown.end, + total: shown.count, + items: itemLabel, + }) + : t('Showing {{start}} to {{end}} of {{count}} items', shown); + const text = (summary ?? defaultSummary)(range); return (
diff --git a/resources/scripts/components/elements/table/PaginationFooter.tsx b/resources/scripts/components/elements/table/PaginationFooter.tsx index ed87ba254..b6299f597 100644 --- a/resources/scripts/components/elements/table/PaginationFooter.tsx +++ b/resources/scripts/components/elements/table/PaginationFooter.tsx @@ -73,8 +73,8 @@ const PaginationFooter = ({ pagination, className, onPageSelect }: Props) => {

}} />

diff --git a/resources/scripts/components/ui/Select.tsx b/resources/scripts/components/ui/Select.tsx index 154017808..b83b8959c 100644 --- a/resources/scripts/components/ui/Select.tsx +++ b/resources/scripts/components/ui/Select.tsx @@ -347,7 +347,7 @@ function MultiSelectCombobox({ {(value: SelectOption[]) => ( <> {value.length > 0 && ( - {t('{{total}} selected', { total: value.length })} + {t('{{count}} selected', { count: value.length })} )} { expect(toPanelLocale('pt-BR')).toBe('pt_BR'); expect(toPanelLocale('pt-br')).toBe('pt_BR'); expect(toPanelLocale('de')).toBe('de'); + expect(toI18nLanguage('zh_Hant_TW')).toBe('zh-Hant-TW'); + expect(toPanelLocale('zh-hant-tw')).toBe('zh_Hant_TW'); + expect(toPanelLocale('sr-Latn')).toBe('sr_Latn'); + expect(toPanelLocale('es-419')).toBe('es_419'); + expect(toPanelLocale('fil')).toBe('fil'); }); it('follows language changes of the cached current user', async () => { @@ -95,6 +100,49 @@ it('follows language changes of the cached current user', async () => { client.clear(); }); +it('refetches cached server text when the language changes', async () => { + (window as BootstrapWindow).PterodactylUser = user('en'); + const { followCurrentUserLanguage } = await import('@/i18n'); + const { currentUserQueryKey, currentUserQueryOptions, setCurrentUserQueryData } = + await import('@/api/account/queries'); + const instance = createInstance(); + + await instance.init({ lng: 'en', resources: {} }); + const client = new QueryClient(); + const stop = followCurrentUserLanguage(client, instance); + + await client.ensureQueryData(currentUserQueryOptions()); + client.setQueryData(['permissions'], { description: 'Start the server' }); + expect(client.getQueryState(['permissions'])?.isInvalidated).toBe(false); + + setCurrentUserQueryData(client, { language: 'de' }); + await vi.waitFor(() => expect(client.getQueryState(['permissions'])?.isInvalidated).toBe(true)); + expect(client.getQueryState(currentUserQueryKey)?.isInvalidated).toBe(false); + + stop(); + client.clear(); +}); + +it('re-renders once the date locale of a new language has loaded', async () => { + const { DATE_LOCALE_LOADED, followDateLocale } = await import('@/i18n'); + const { default: dayjs } = await import('@/lib/dayjs'); + const instance = createInstance(); + + await instance.init({ lng: 'en', resources: {} }); + const stop = followDateLocale(instance); + const loaded = vi.fn(); + + instance.on(DATE_LOCALE_LOADED, loaded); + + await instance.changeLanguage('de'); + await vi.waitFor(() => expect(loaded).toHaveBeenCalledWith('de')); + expect(dayjs.locale()).toBe('de'); + + stop(); + await instance.changeLanguage('fr'); + expect(loaded).toHaveBeenCalledTimes(1); +}); + it('adds the revision of an extension to the URL of its translations only', async () => { (window as BootstrapWindow).SiteConfiguration = { extensions: [ diff --git a/resources/scripts/i18n.ts b/resources/scripts/i18n.ts index 573ef6895..8a71c5139 100644 --- a/resources/scripts/i18n.ts +++ b/resources/scripts/i18n.ts @@ -18,12 +18,15 @@ interface MultiloadHttpBackendOptions extends HttpBackendOptions { // Busts the locale cache on every reload under HMR, otherwise once per build. const hash = import.meta.hot ? Date.now().toString(16) : import.meta.env.WEBPACK_BUILD_HASH; -export const toI18nLanguage = (locale: string): string => locale.replace('_', '-'); +export const toI18nLanguage = (locale: string): string => locale.replaceAll('_', '-'); + +const panelSubtag = (subtag: string): string => + subtag.length === 4 ? `${subtag[0]!.toUpperCase()}${subtag.slice(1).toLowerCase()}` : subtag.toUpperCase(); export const toPanelLocale = (language: string): string => { - const [code, region] = language.split('-'); + const [code, ...subtags] = language.split('-'); - return region ? `${code}_${region.toUpperCase()}` : code!; + return [code!.toLowerCase(), ...subtags.map(panelSubtag)].join('_'); }; /** @@ -89,12 +92,32 @@ export function followCurrentUserLanguage(queryClient: QueryClient, instance: I1 const language = resolveLanguage(user.language); if (language !== instance.language) { - void instance.changeLanguage(language); + // Cached responses can hold text the server translated, such as permissions and activity. + void instance + .changeLanguage(language) + .then(() => + queryClient.invalidateQueries({ predicate: (query) => query.queryHash !== currentUserHash }) + ); } }); } -i18n.on('languageChanged', (language) => void setDateLocale(language)); +export const DATE_LOCALE_LOADED = 'dateLocaleLoaded'; + +export function followDateLocale(instance: I18n = i18n): () => void { + const load = (language: string) => + void setDateLocale(language).then(() => { + if (instance.language === language) { + instance.emit(DATE_LOCALE_LOADED, language); + } + }); + + instance.on('languageChanged', load); + + return () => instance.off('languageChanged', load); +} + +followDateLocale(); void i18n .use(I18NextMultiloadBackendAdapter) @@ -103,7 +126,7 @@ void i18n ...translationOptions, debug: import.meta.env.DEV, lng: initialLanguage(), - react: { bindI18n: 'languageChanged loaded' }, + react: { bindI18n: `languageChanged loaded ${DATE_LOCALE_LOADED}` }, backend: { backend: I18NextHttpBackend, backendOption: { diff --git a/resources/scripts/lib/dayjs.spec.ts b/resources/scripts/lib/dayjs.spec.ts index 47aeb1a9d..ce5f014fe 100644 --- a/resources/scripts/lib/dayjs.spec.ts +++ b/resources/scripts/lib/dayjs.spec.ts @@ -19,8 +19,25 @@ it('uses the regional variant of a language when dayjs has one', async () => { expect(dayjs(date).format('L')).toBe('03/10/2026'); }); +it('shows english times on a 24-hour clock', async () => { + expect(await setDateLocale('en')).toBe('en'); + expect(dayjs(date).format('lll')).toBe('Oct 3, 2026 20:02'); + expect(dayjs(date).format('LTS')).toBe('20:02:05'); +}); + +it('keeps the locale of the latest change when loads finish out of order', async () => { + const first = setDateLocale('de'); + const second = setDateLocale('fr'); + + await Promise.all([first, second]); + + expect(dayjs.locale()).toBe('fr'); +}); + it('falls back to the language, then english', async () => { expect(await setDateLocale('de-XX')).toBe('de'); + expect(await setDateLocale('zh_Hant_TW')).toBe('zh-tw'); + expect(await setDateLocale('sr_Latn')).toBe('sr'); expect(await setDateLocale('xx')).toBe('en'); expect(dayjs(date).format('ll')).toBe('Oct 3, 2026'); }); diff --git a/resources/scripts/lib/dayjs.ts b/resources/scripts/lib/dayjs.ts index 2e88959f3..d29078236 100644 --- a/resources/scripts/lib/dayjs.ts +++ b/resources/scripts/lib/dayjs.ts @@ -8,29 +8,42 @@ dayjs.extend(advancedFormat); dayjs.extend(localizedFormat); dayjs.extend(relativeTime); +// The panel has always shown English times on a 24-hour clock. +dayjs.Ls.en!.formats = { + LT: 'HH:mm', + LTS: 'HH:mm:ss', + L: 'MM/DD/YYYY', + LL: 'MMMM D, YYYY', + LLL: 'MMMM D, YYYY HH:mm', + LLLL: 'dddd, MMMM D, YYYY HH:mm', +}; + const locales = import.meta.glob<{ default: ILocale }>('../../../node_modules/dayjs/esm/locale/*.js'); const localeLoader = (code: string) => locales[`../../../node_modules/dayjs/esm/locale/${code}.js`]; -export async function setDateLocale(language: string): Promise { - const code = language.toLowerCase().replace('_', '-'); +let latest = 0; - const load = [code, code.split('-')[0]!] +export async function setDateLocale(language: string): Promise { + const request = ++latest; + const code = language.toLowerCase().replaceAll('_', '-'); + const [base, ...subtags] = code.split('-'); + const region = subtags.find((subtag) => subtag.length !== 4); + + const load = [code, region ? `${base}-${region}` : code, base!] .filter((candidate) => candidate !== 'en') .map(localeLoader) .find((loader) => loader !== undefined); - if (!load) { - dayjs.locale('en'); + const locale = load ? (await load()).default : null; - return 'en'; + if (request !== latest) { + return dayjs.locale(); } - const { default: locale } = await load(); + dayjs.locale(locale ?? 'en'); - dayjs.locale(locale); - - return locale.name; + return locale?.name ?? 'en'; } export default dayjs; diff --git a/resources/scripts/lib/formatters.spec.ts b/resources/scripts/lib/formatters.spec.ts index e31744e5d..4b117b0fc 100644 --- a/resources/scripts/lib/formatters.spec.ts +++ b/resources/scripts/lib/formatters.spec.ts @@ -1,6 +1,6 @@ import i18next from 'i18next'; import { afterEach, describe, expect, it } from 'vitest'; -import { bytesRatioToString, bytesToString, ip, mbToBytes } from '@/lib/formatters'; +import { bytesRatioToString, bytesToString, ip, mbToBytes, percentageToString } from '@/lib/formatters'; describe('@/lib/formatters.ts', () => { describe('mbToBytes()', () => { @@ -85,5 +85,14 @@ describe('@/lib/formatters.ts', () => { expect(bytesToString(100)).toBe('100 Byte'); expect(bytesRatioToString(1_356_000, 2_097_152)).toBe('1,29 / 2 MiB'); }); + + it('formats percentages the way the language writes them', async () => { + expect(percentageToString(12.3456)).toBe('12.35%'); + + await i18next.changeLanguage('de'); + + expect(percentageToString(12.3456)).toBe('12,35 %'); + expect(percentageToString(1234.5, 0)).toBe('1235 %'); + }); }); }); diff --git a/resources/scripts/lib/formatters.ts b/resources/scripts/lib/formatters.ts index d7ba0102e..93419c0b1 100644 --- a/resources/scripts/lib/formatters.ts +++ b/resources/scripts/lib/formatters.ts @@ -43,10 +43,19 @@ function bytesRatioToString(used: number, total: number, decimals = 2): string { return `${formatNumber(scaleBytes(Math.max(0, used), i, decimals))} / ${formatNumber(scaleBytes(total, i, decimals))} ${unitLabel(i)}`; } +function percentageToString(value: number, decimals = 2): string { + return new Intl.NumberFormat(i18next.language || 'en', { + style: 'percent', + minimumFractionDigits: decimals, + maximumFractionDigits: decimals, + useGrouping: false, + }).format(value / 100); +} + /** Wraps IPv6 addresses in brackets. */ function ip(value: string): string { // noinspection RegExpSimplifiable return /([a-f0-9:]+:+)+[a-f0-9]+/.test(value) ? `[${value}]` : value; } -export { ip, mbToBytes, bytesToString, bytesRatioToString }; +export { ip, mbToBytes, bytesToString, bytesRatioToString, percentageToString }; diff --git a/resources/scripts/sdk/index.ts b/resources/scripts/sdk/index.ts index aed64001b..74e0863a1 100644 --- a/resources/scripts/sdk/index.ts +++ b/resources/scripts/sdk/index.ts @@ -103,7 +103,7 @@ export * from './navigation'; export * from './localization'; export * from './progress'; export { onThemeChange, notifyThemeChange, readThemeToken } from './theme'; -export { bytesToString, ip, mbToBytes } from '@/lib/formatters'; +export { bytesToString, ip, mbToBytes, percentageToString } from '@/lib/formatters'; export { formatDate, fromNow } from '@/lib/dates'; export { useDebouncedCallback, type DebouncedCallback } from '@/plugins/useDebouncedCallback'; export { useShortcut, type Shortcut } from '@/plugins/useShortcut'; diff --git a/resources/scripts/themes/classic/views/activity/ActivityLogEntry.tsx b/resources/scripts/themes/classic/views/activity/ActivityLogEntry.tsx index d62821b73..f0b3666da 100644 --- a/resources/scripts/themes/classic/views/activity/ActivityLogEntry.tsx +++ b/resources/scripts/themes/classic/views/activity/ActivityLogEntry.tsx @@ -21,10 +21,12 @@ const activityIconClass = const activityDescriptionClass = 'mt-1 text-sm break-words line-clamp-2 pr-4 [&_strong]:break-all [&_strong]:font-semibold [&_strong]:text-foreground'; -/** Emphasises every value the description interpolates, apart from the counts its plurals read. */ -function wrapProperty(value: TranslationValue): TranslationValue { +const isCount = (key: string): boolean => key === 'count' || key.endsWith('_count'); + +// Every value is emphasised as text, apart from the counts the plurals read. +function textProperty(value: TranslationValue): TranslationValue { if (Array.isArray(value)) { - return value.map(wrapProperty); + return value.map(textProperty); } if (value === true || value === false) { @@ -33,18 +35,17 @@ function wrapProperty(value: TranslationValue): TranslationValue { if (value instanceof Object) { return Object.fromEntries( - Object.entries(value).map(([key, item]) => [ - key, - key === 'count' || key.endsWith('_count') ? item : wrapProperty(item), - ]) + Object.entries(value).map(([key, item]) => [key, isCount(key) ? item : textProperty(item)]) ); } - return `${String(value)}`; + return String(value); } -const wrapProperties = (properties: ActivityProperties): TranslationValues => - Object.fromEntries(Object.entries(properties).map(([key, value]) => [key, wrapProperty(value)])); +const textProperties = (properties: ActivityProperties): TranslationValues => + Object.fromEntries( + Object.entries(properties).map(([key, value]) => [key, isCount(key) ? value : textProperty(value)]) + ); export default function ActivityLogEntry({ entry }: { entry: ActivityEntry }) { const { actor } = entry; @@ -94,7 +95,8 @@ export default function ActivityLogEntry({ entry }: { entry: ActivityEntry }) {

} i18nKey={entry.event.replace(':', '.')} />

diff --git a/resources/scripts/themes/classic/views/dashboard/ServerCardMetrics.tsx b/resources/scripts/themes/classic/views/dashboard/ServerCardMetrics.tsx index ae6503612..57ef6ea54 100644 --- a/resources/scripts/themes/classic/views/dashboard/ServerCardMetrics.tsx +++ b/resources/scripts/themes/classic/views/dashboard/ServerCardMetrics.tsx @@ -1,5 +1,5 @@ import { Cpu, HardDrive, MemoryStick } from 'lucide-react'; -import { Badge, bytesToString, cn, Spinner, Stat, useTranslation, type Translation } from '@/sdk'; +import { Badge, bytesToString, cn, percentageToString, Spinner, Stat, useTranslation, type Translation } from '@/sdk'; import type { ServerCardState, ServerStatMetric, ServerUnavailableReason, UiTone, ViewProps } from '@/sdk/theme'; const unavailableLabels = (t: Translation['t']) => @@ -54,7 +54,7 @@ function MetricsContent({ state }: { state: ServerCardState }) { label: t('CPU'), icon: Cpu, metric: state.cpu, - value: `${state.cpu.value.toFixed(2)} %`, + value: percentageToString(state.cpu.value), limit: state.cpu.limit === 0 ? t('Unlimited') : `${state.cpu.limit} %`, }, { diff --git a/resources/scripts/themes/classic/views/server/backups/BackupList.tsx b/resources/scripts/themes/classic/views/server/backups/BackupList.tsx index bec21f796..b840156c9 100644 --- a/resources/scripts/themes/classic/views/server/backups/BackupList.tsx +++ b/resources/scripts/themes/classic/views/server/backups/BackupList.tsx @@ -36,7 +36,10 @@ const backupUsage = (model: BackupListModel, t: Translation['t']): string | null } if (model.permissions.create && limit > 0 && count > 0) { - return t('{{created}} of {{limit}} backups have been created for this server.', { created: count, limit }); + return t('{{created}} of {{count}} backups have been created for this server.', { + created: count, + count: limit, + }); } return null; @@ -174,7 +177,15 @@ export default function BackupList({ model, className }: ViewProps<'server.backu emptyState={} pagination={{ ...model.pagination, - itemLabel: t('backups'), + summary: ({ start, end, count }) => + t( + 'Showing {{start}} to {{end}} of {{count}} backups', + { + start, + end, + count, + } + ), onPageSelect: model.actions.setPage, }} /> diff --git a/resources/scripts/themes/classic/views/server/console/Graphs.tsx b/resources/scripts/themes/classic/views/server/console/Graphs.tsx index 8712ad3e5..d35fb0c9d 100644 --- a/resources/scripts/themes/classic/views/server/console/Graphs.tsx +++ b/resources/scripts/themes/classic/views/server/console/Graphs.tsx @@ -1,5 +1,14 @@ import { CloudDownload, CloudUpload } from 'lucide-react'; -import { AreaChart, bytesToString, ChartCard, cn, Tooltip, useTranslation, type ChartSeries } from '@/sdk'; +import { + AreaChart, + bytesToString, + ChartCard, + cn, + percentageToString, + Tooltip, + useTranslation, + type ChartSeries, +} from '@/sdk'; import type { ViewProps } from '@/sdk/theme'; const CYAN = 'var(--chart-1)'; @@ -24,7 +33,7 @@ export default function Graphs({ model, className }: ViewProps<'server.graphs'>) live={live} windowMs={windowMs} suggestedMax={model.cpu.limit} - tickFormatter={(value) => `${value.toFixed(2)}%`} + tickFormatter={(value) => percentageToString(value)} /> diff --git a/resources/scripts/themes/classic/views/server/console/Stats.tsx b/resources/scripts/themes/classic/views/server/console/Stats.tsx index 75b45bfa3..35c81cc8d 100644 --- a/resources/scripts/themes/classic/views/server/console/Stats.tsx +++ b/resources/scripts/themes/classic/views/server/console/Stats.tsx @@ -1,5 +1,5 @@ import { Clock, CloudDownload, CloudUpload, Cpu, HardDrive, MemoryStick, Wifi } from 'lucide-react'; -import { bytesToString, cn, CopyOnClick, Stat, useTranslation, type Translation } from '@/sdk'; +import { bytesToString, cn, CopyOnClick, percentageToString, Stat, useTranslation, type Translation } from '@/sdk'; import type { ServerRunState, ServerStatMetric, UiTone, ViewProps } from '@/sdk/theme'; const tile = 'col-span-3 md:col-span-2 lg:col-span-6'; @@ -76,7 +76,7 @@ export default function Stats({ model, className }: ViewProps<'server.stats'>) { 0 && count > 0 - ? t('{{allocated}} of {{limit}} databases have been allocated to this server.', { - allocated: count, - limit: model.limit, + ? t('{{used}} of {{count}} databases have been allocated to this server.', { + used: count, + count: model.limit, }) : null; diff --git a/resources/scripts/themes/classic/views/server/files/FileManagerSelection.tsx b/resources/scripts/themes/classic/views/server/files/FileManagerSelection.tsx index 7dd07189d..fb6543678 100644 --- a/resources/scripts/themes/classic/views/server/files/FileManagerSelection.tsx +++ b/resources/scripts/themes/classic/views/server/files/FileManagerSelection.tsx @@ -45,8 +45,8 @@ function MassActions({ model, className }: { model: FileManagerModel; className? >

}} />

@@ -55,7 +55,7 @@ function MassActions({ model, className }: { model: FileManagerModel; className?
  • {file}
  • ))} {selection.length > 15 && ( -
  • {t('and {{number}} others', { number: selection.length - 15 })}
  • +
  • {t('and {{count}} others', { count: selection.length - 15 })}
  • )} diff --git a/resources/scripts/themes/classic/views/server/files/Uploads.tsx b/resources/scripts/themes/classic/views/server/files/Uploads.tsx index 538b55329..1ad8e8f18 100644 --- a/resources/scripts/themes/classic/views/server/files/Uploads.tsx +++ b/resources/scripts/themes/classic/views/server/files/Uploads.tsx @@ -154,7 +154,7 @@ export function UploadStatus({ model }: { model: FileManagerModel }) { return ( ( - +