From d1af496d6af548e17763bd4124d053cb93e4fc1f Mon Sep 17 00:00:00 2001 From: Albert Casanovas Date: Wed, 18 Nov 2026 14:44:35 +0000 Subject: [PATCH 01/12] Fall back to en-US for missing translations Generated locale modules now spread the en-US strings under each locale's own strings, so a locale that doesn't have a key shows the English text instead of throwing. The generated types also list the en-US keys, so unknown keys are type errors. --- .eslintignore | 2 + .gitignore | 2 + .prettierignore | 2 + design-system/pkg/build-l10n.mts | 24 +++++++-- packages/keystatic/scripts/l10n.ts | 54 +++++++++++++++---- .../src/app/l10n/default-formatter.ts | 19 +++++++ 6 files changed, 89 insertions(+), 14 deletions(-) create mode 100644 packages/keystatic/src/app/l10n/default-formatter.ts diff --git a/.eslintignore b/.eslintignore index b29cdedcb..c802e593f 100644 --- a/.eslintignore +++ b/.eslintignore @@ -61,3 +61,5 @@ l10n.js l10n.d.ts packages/keystatic/src/app/l10n/index.js packages/keystatic/src/app/l10n/index.d.ts +packages/keystatic/src/app/l10n/default-locale.js +packages/keystatic/src/app/l10n/default-locale.d.ts diff --git a/.gitignore b/.gitignore index e7414127b..9741f3cbc 100644 --- a/.gitignore +++ b/.gitignore @@ -66,3 +66,5 @@ l10n.js l10n.d.ts packages/keystatic/src/app/l10n/index.js packages/keystatic/src/app/l10n/index.d.ts +packages/keystatic/src/app/l10n/default-locale.js +packages/keystatic/src/app/l10n/default-locale.d.ts diff --git a/.prettierignore b/.prettierignore index 80706b57d..f521602d9 100644 --- a/.prettierignore +++ b/.prettierignore @@ -64,3 +64,5 @@ l10n.js l10n.d.ts packages/keystatic/src/app/l10n/index.js packages/keystatic/src/app/l10n/index.d.ts +packages/keystatic/src/app/l10n/default-locale.js +packages/keystatic/src/app/l10n/default-locale.d.ts diff --git a/design-system/pkg/build-l10n.mts b/design-system/pkg/build-l10n.mts index 9b252e695..824c24926 100644 --- a/design-system/pkg/build-l10n.mts +++ b/design-system/pkg/build-l10n.mts @@ -19,13 +19,23 @@ for (const file of await fs.readdir(src)) { const l10n: Record> = JSON.parse( l10nFileContents ); - let out = 'const localizedMessages = {\n'; - for (const [lang, translations] of Object.entries(l10n)) { - out += ` ${JSON.stringify(lang)}: {\n`; + const defaultStrings = l10n['en-US']; + const compile = (translations: Record) => { + let out = ''; for (const [key, value] of Object.entries(translations)) { out += ` ${JSON.stringify(key)}: ${compileString(value)},\n`; } - out += ' },\n'; + return out; + }; + // every locale falls back to en-US for keys it doesn't have + let out = `const defaultStrings = {\n${compile(defaultStrings)}};\n\n`; + out += 'const localizedMessages = {\n'; + for (const [lang, translations] of Object.entries(l10n)) { + out += ` ${JSON.stringify(lang)}: `; + out += + lang === 'en-US' + ? 'defaultStrings,\n' + : `{\n ...defaultStrings,\n${compile(translations)} },\n`; } out += '};\n'; out += 'export default localizedMessages;\n'; @@ -33,7 +43,11 @@ for (const file of await fs.readdir(src)) { await fs.writeFile(withoutExtension + '.js', out); await fs.writeFile( withoutExtension + '.d.ts', - `declare const localizedMessages: Record>; + `declare const localizedMessages: Record JSON.stringify(key)) + .join(' | ')}, import('@internationalized/string').LocalizedString>>; export default localizedMessages; ` ); diff --git a/packages/keystatic/scripts/l10n.ts b/packages/keystatic/scripts/l10n.ts index c86afbf03..2b1548b43 100644 --- a/packages/keystatic/scripts/l10n.ts +++ b/packages/keystatic/scripts/l10n.ts @@ -3,6 +3,18 @@ import path from 'path'; import { compileString } from '@internationalized/string-compiler'; const localesDir = 'src/app/l10n'; +const defaultLocale = 'en-US'; + +function compileTranslations(translations: Record) { + let out = ''; + for (const [key, value] of Object.entries(translations).sort(([a], [b]) => + a.localeCompare(b) + )) { + out += ` ${JSON.stringify(key)}: ${compileString(value)},\n`; + } + return out; +} + (async () => { const locales: Record> = {}; for (const entry of ( @@ -24,15 +36,39 @@ const localesDir = 'src/app/l10n'; } locales[locale] = translations; } - let out = 'const strings = {\n'; + const defaultTranslations = locales[defaultLocale]; + + // the default locale is in its own module so that code that also runs + // outside of the Admin UI (e.g. field validation in the reader) can use it + // without including every locale + await fs.writeFile( + path.join(localesDir, 'default-locale.js'), + `const defaultLocaleStrings = {\n${compileTranslations( + defaultTranslations + )}};\nexport default defaultLocaleStrings;\n` + ); + const keyType = Object.keys(defaultTranslations) + .sort((a, b) => a.localeCompare(b)) + .map(key => `\n | ${JSON.stringify(key)}`) + .join(''); + await fs.writeFile( + path.join(localesDir, 'default-locale.d.ts'), + `export type LocalizedMessageKey =${keyType}; +declare const defaultLocaleStrings: Record; +export default defaultLocaleStrings; +` + ); + + // every locale falls back to the default locale for keys it doesn't have + let out = `import defaultLocaleStrings from './default-locale.js';\n\nconst strings = {\n`; for (const [lang, translations] of Object.entries(locales)) { - out += ` ${JSON.stringify(lang)}: {\n`; - for (const [key, value] of Object.entries(translations).sort(([a], [b]) => - a.localeCompare(b) - )) { - out += ` ${JSON.stringify(key)}: ${compileString(value)},\n`; - } - out += ' },\n'; + out += ` ${JSON.stringify(lang)}: `; + out += + lang === defaultLocale + ? 'defaultLocaleStrings,\n' + : `{\n ...defaultLocaleStrings,\n${compileTranslations( + translations + )} },\n`; } out += '};\n'; out += 'export default strings;\n'; @@ -40,7 +76,7 @@ const localesDir = 'src/app/l10n'; await fs.writeFile(path.join(localesDir, 'index.js'), out); await fs.writeFile( path.join(localesDir, 'index.d.ts'), - `declare const l10nMessages: Record>; + `declare const l10nMessages: Record>; export default l10nMessages; ` ); diff --git a/packages/keystatic/src/app/l10n/default-formatter.ts b/packages/keystatic/src/app/l10n/default-formatter.ts new file mode 100644 index 000000000..42f5f366b --- /dev/null +++ b/packages/keystatic/src/app/l10n/default-formatter.ts @@ -0,0 +1,19 @@ +import { + LocalizedString, + LocalizedStringDictionary, + LocalizedStringFormatter, +} from '@internationalized/string'; +import defaultLocaleStrings, { LocalizedMessageKey } from './default-locale'; + +export type KeystaticStringFormatter = LocalizedStringFormatter< + LocalizedMessageKey, + LocalizedString +>; + +// for messages created outside of the Admin UI's locale (e.g. field validation +// in the reader), without including every locale +export const defaultStringFormatter: KeystaticStringFormatter = + new LocalizedStringFormatter( + 'en-US', + new LocalizedStringDictionary({ 'en-US': defaultLocaleStrings }) + ); From 864df91f873d56dcec1d24ea828b979bf1458eee Mon Sep 17 00:00:00 2001 From: Albert Casanovas Date: Wed, 18 Nov 2026 14:44:43 +0000 Subject: [PATCH 02/12] Localize app shell and dashboard strings --- .../src/app/dashboard/BranchSection.tsx | 6 +- .../src/app/dashboard/DashboardCards.tsx | 34 ++++++---- .../src/app/dashboard/DashboardPage.tsx | 5 +- packages/keystatic/src/app/l10n/en-US.json | 34 +++++++++- packages/keystatic/src/app/l10n/l10n.test.ts | 48 ++++++++++++++ .../keystatic/src/app/shell/empty-repo.tsx | 18 ++++-- packages/keystatic/src/app/shell/i18n.tsx | 26 ++++++++ packages/keystatic/src/app/shell/index.tsx | 11 +++- packages/keystatic/src/app/shell/page.tsx | 4 +- .../src/app/shell/sidebar/components.tsx | 64 +++++++++++-------- .../keystatic/src/app/shell/sidebar/index.tsx | 10 ++- 11 files changed, 200 insertions(+), 60 deletions(-) create mode 100644 packages/keystatic/src/app/l10n/l10n.test.ts diff --git a/packages/keystatic/src/app/dashboard/BranchSection.tsx b/packages/keystatic/src/app/dashboard/BranchSection.tsx index 92482e958..b477dee7a 100644 --- a/packages/keystatic/src/app/dashboard/BranchSection.tsx +++ b/packages/keystatic/src/app/dashboard/BranchSection.tsx @@ -75,7 +75,11 @@ export function BranchSection() { ) : ( - Pull request #{prNumber} + + {localizedString.format('pullRequestNumber', { + number: prNumber, + })} + ))} diff --git a/packages/keystatic/src/app/dashboard/DashboardCards.tsx b/packages/keystatic/src/app/dashboard/DashboardCards.tsx index 910464171..b5f6710ad 100644 --- a/packages/keystatic/src/app/dashboard/DashboardCards.tsx +++ b/packages/keystatic/src/app/dashboard/DashboardCards.tsx @@ -6,7 +6,8 @@ import { Divider, Flex } from '@keystar/ui/layout'; import { Text } from '@keystar/ui/typography'; import { ItemOrGroup, useNavItems } from '../useNavItems'; -import { pluralize } from '../pluralize'; +import type { KeystaticStringFormatter } from '../l10n/default-formatter'; +import { useLocalizedString } from '../shell/i18n'; import { DashboardCard, DashboardGrid, @@ -16,20 +17,24 @@ import { export function DashboardCards() { const navItems = useNavItems(); + const stringFormatter = useLocalizedString(); const hasSections = navItems.some(item => 'children' in item); - const items = navItems.map(item => renderItemOrGroup(item)); + const items = navItems.map(item => renderItemOrGroup(item, stringFormatter)); return hasSections ? ( <>{items} ) : ( - + {items} ); } let dividerCount = 0; -function renderItemOrGroup(itemOrGroup: ItemOrGroup) { +function renderItemOrGroup( + itemOrGroup: ItemOrGroup, + stringFormatter: KeystaticStringFormatter +) { if (itemOrGroup.isDivider) { return ( @@ -46,7 +51,9 @@ function renderItemOrGroup(itemOrGroup: ItemOrGroup) { return ( - {itemOrGroup.children.map(child => renderItemOrGroup(child))} + {itemOrGroup.children.map(child => + renderItemOrGroup(child, stringFormatter) + )} ); @@ -59,13 +66,12 @@ function renderItemOrGroup(itemOrGroup: ItemOrGroup) { return typeof itemOrGroup.changed === 'number' ? ( - {pluralize(itemOrGroup.changed, { - singular: 'change', - plural: 'changes', + {stringFormatter.format('changeCount', { + count: itemOrGroup.changed, })} ) : ( - Changed + {stringFormatter.format('changed')} ); })(); @@ -78,7 +84,10 @@ function renderItemOrGroup(itemOrGroup: ItemOrGroup) { return ( {changeElement} - + @@ -94,9 +103,8 @@ function renderItemOrGroup(itemOrGroup: ItemOrGroup) { > {typeof itemOrGroup.entryCount === 'number' ? ( - {pluralize(itemOrGroup.entryCount, { - singular: 'entry', - plural: 'entries', + {stringFormatter.format('entryCount', { + count: itemOrGroup.entryCount, })} ) : null} diff --git a/packages/keystatic/src/app/dashboard/DashboardPage.tsx b/packages/keystatic/src/app/dashboard/DashboardPage.tsx index 1bde80f25..478de6ab5 100644 --- a/packages/keystatic/src/app/dashboard/DashboardPage.tsx +++ b/packages/keystatic/src/app/dashboard/DashboardPage.tsx @@ -52,6 +52,7 @@ function UserInfo({ user: { avatarUrl?: string; name: string }; manageAccount: boolean; }) { + const stringFormatter = useLocalizedStringFormatter(l10nMessages); return ( @@ -63,11 +64,11 @@ function UserInfo({ fontWeight: tokenSchema.typography.fontWeight.bold, }} > - Hello, {user.name}! + {stringFormatter.format('helloName', { name: user.name })} {manageAccount && ( - Manage Account + {stringFormatter.format('manageAccount')} )} diff --git a/packages/keystatic/src/app/l10n/en-US.json b/packages/keystatic/src/app/l10n/en-US.json index 6a3c81874..93105e71f 100644 --- a/packages/keystatic/src/app/l10n/en-US.json +++ b/packages/keystatic/src/app/l10n/en-US.json @@ -1,12 +1,19 @@ { + "account": "Account", "add": "Add", "basedOn": "Based on", - "branchName": "Branch name", + "branchDoesNotExist": "The branch {branchName} does not exist in this repository.", "branches": "Branches", + "branchName": "Branch name", + "branchNotFound": "Branch not found", "cancel": "Cancel", + "changeCount": "{count, plural, one {{count} change} other {{count} changes}}", + "changed": "Changed", + "changesWithoutCount": "{count, plural, one {change} other {changes}}", "clear": "Clear", "collection": "Collection", "collections": "Collections", + "content": "Content", "create": "Create", "createPullRequest": "Create pull request", "currentBranch": "Current branch", @@ -14,16 +21,39 @@ "defaultBranch": "Default branch", "delete": "Delete", "deleteBranch": "Delete branch", + "deleteBranchConfirmation": "Are you sure you want to delete the \"{branchName}\" branch? This cannot be undone.", "edit": "Edit", + "entryCount": "{count, plural, one {{count} entry} other {{count} entries}}", + "failedToLoadShell": "Failed to load shell", + "gitActions": "git actions", + "githubRepo": "Github repo", + "gitRepoNotInitialised": "Git repo not initialised", + "gitRepoNotInitialisedMessage": "The Keystatic GitHub App is installed in the GitHub repository {repo} but the Git repo is not initialised. Please initialise the Git repo before using Keystatic.", + "helloName": "Hello, {name}!", + "imageLibrary": "Image library", "loading": "Loading", + "logOut": "Log out", + "manageAccount": "Manage Account", "newBranch": "New branch…", + "openAppNavigation": "Open app navigation", "otherBranches": "Other branches", + "pullRequestNumber": "Pull request #{number}", "pullRequests": "Pull requests", + "repository": "Repository", "save": "Save", "search": "Search", + "signIntoCloud": "Sign into Cloud", "singleton": "Singleton", "singletons": "Singletons", "theCurrentlyCheckedOutBranch": "The currently checked out branch. Choose this if you need to build on existing work from the current branch.", "theDefaultBranchInYourRepository": "The default branch in your repository. Choose this to start something new that's not dependent on your current branch.", - "viewPullRequests": "View pull requests" + "theme": "theme", + "themeDark": "Dark", + "themeLight": "Light", + "themeSystem": "System", + "userMenu": "User menu", + "viewFork": "View fork", + "viewPullRequestNumber": "Pull Request #{number}", + "viewPullRequests": "View pull requests", + "yesDelete": "Yes, delete" } diff --git a/packages/keystatic/src/app/l10n/l10n.test.ts b/packages/keystatic/src/app/l10n/l10n.test.ts new file mode 100644 index 000000000..a30d67ef8 --- /dev/null +++ b/packages/keystatic/src/app/l10n/l10n.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { + LocalizedStringDictionary, + LocalizedStringFormatter, +} from '@internationalized/string'; +import l10nMessages from '.'; +import defaultLocaleStrings from './default-locale'; +import { defaultStringFormatter } from './default-formatter'; +import enUS from './en-US.json'; + +const formatterFor = (locale: string) => + new LocalizedStringFormatter( + locale, + new LocalizedStringDictionary(l10nMessages) + ); + +test('locales fall back to en-US for keys they do not have', () => { + const dir = path.dirname(new URL(import.meta.url).pathname); + let fallbacks = 0; + for (const locale of Object.keys(l10nMessages)) { + const own: Record = JSON.parse( + fs.readFileSync(path.join(dir, `${locale}.json`), 'utf8') + ); + expect(Object.keys(l10nMessages[locale]).sort()).toEqual( + Object.keys(defaultLocaleStrings).sort() + ); + const formatter = formatterFor(locale); + for (const key of Object.keys(enUS) as (keyof typeof enUS)[]) { + if (key in own) continue; + fallbacks++; + expect(formatter.format(key, { count: 2 })).toBe( + defaultStringFormatter.format(key, { count: 2 }) + ); + } + } + expect(fallbacks).toBeGreaterThan(0); +}); + +test('en-US strings without arguments are unchanged by compilation', () => { + for (const [key, value] of Object.entries(enUS)) { + if (value.includes('{')) continue; + expect(defaultStringFormatter.format(key as keyof typeof enUS), key).toBe( + value + ); + } +}); diff --git a/packages/keystatic/src/app/shell/empty-repo.tsx b/packages/keystatic/src/app/shell/empty-repo.tsx index 4c49d9fe7..93edcc39e 100644 --- a/packages/keystatic/src/app/shell/empty-repo.tsx +++ b/packages/keystatic/src/app/shell/empty-repo.tsx @@ -2,7 +2,10 @@ import { Flex } from '@keystar/ui/layout'; import { TextLink } from '@keystar/ui/link'; import { Heading, Text } from '@keystar/ui/typography'; +import { formatWithElements, useLocalizedString } from './i18n'; + export function EmptyRepo(props: { repo: string }) { + const stringFormatter = useLocalizedString(); return ( - Git repo not initialised + {stringFormatter.format('gitRepoNotInitialised')} - The Keystatic GitHub App is installed in the GitHub repository{' '} - - {props.repo} - {' '} - but the Git repo is not initialised. Please initialise the Git repo - before using Keystatic. + {formatWithElements(stringFormatter, 'gitRepoNotInitialisedMessage', { + repo: ( + + {props.repo} + + ), + })} diff --git a/packages/keystatic/src/app/shell/i18n.tsx b/packages/keystatic/src/app/shell/i18n.tsx index f8058f3d8..867ad3b0c 100644 --- a/packages/keystatic/src/app/shell/i18n.tsx +++ b/packages/keystatic/src/app/shell/i18n.tsx @@ -1,8 +1,34 @@ import { useLocalizedStringFormatter } from 'react-aria/useLocalizedStringFormatter'; +import { Fragment, ReactNode } from 'react'; import l10nMessages from '../l10n'; +import type { KeystaticStringFormatter } from '../l10n/default-formatter'; +import type { LocalizedMessageKey } from '../l10n/default-locale'; export function useLocalizedString() { let stringFormatter = useLocalizedStringFormatter(l10nMessages); return stringFormatter; } + +const marker = '\u0000'; + +/** + * Formats a message where some variables are elements, e.g. a link in the + * middle of a sentence. + */ +export function formatWithElements( + stringFormatter: KeystaticStringFormatter, + key: LocalizedMessageKey, + elements: Record +): ReactNode { + const names = Object.keys(elements); + const message = stringFormatter.format( + key, + Object.fromEntries(names.map((name, i) => [name, marker + i + marker])) + ); + return message + .split(marker) + .map((part, i) => + i % 2 === 0 ? part : {elements[names[+part]]} + ); +} diff --git a/packages/keystatic/src/app/shell/index.tsx b/packages/keystatic/src/app/shell/index.tsx index dabfce36e..54567a47f 100644 --- a/packages/keystatic/src/app/shell/index.tsx +++ b/packages/keystatic/src/app/shell/index.tsx @@ -18,10 +18,12 @@ import { import { SidebarProvider } from './sidebar'; import { MainPanelLayout } from './panels'; import { EmptyState } from './empty-state'; +import { useLocalizedString } from './i18n'; function BranchNotFound(props: { children: ReactNode }) { const branches = useBranches(); const currentBranch = useCurrentBranch(); + const stringFormatter = useLocalizedString(); const appShellDataContext = useContext(GitHubAppShellDataContext); if ( appShellDataContext?.data?.repository?.refs?.pageInfo.hasNextPage === @@ -31,8 +33,10 @@ function BranchNotFound(props: { children: ReactNode }) { return ( ); } @@ -45,6 +49,7 @@ export const AppShell = (props: { currentBranch: string; basePath: string; }) => { + const stringFormatter = useLocalizedString(); const content = ( {error => @@ -54,7 +59,7 @@ export const AppShell = (props: { ) ? ( ) : ( diff --git a/packages/keystatic/src/app/shell/page.tsx b/packages/keystatic/src/app/shell/page.tsx index f336814c1..31739e6e5 100644 --- a/packages/keystatic/src/app/shell/page.tsx +++ b/packages/keystatic/src/app/shell/page.tsx @@ -13,6 +13,7 @@ import { css, tokenSchema, VoussoirTheme } from '@keystar/ui/style'; import { MAIN_PANEL_ID } from './constants'; import { ScrollView } from './primitives'; import { useSidebar } from './sidebar'; +import { useLocalizedString } from './i18n'; type PageContextValue = { containerWidth: keyof VoussoirTheme['size']['container'] | 'none'; @@ -47,6 +48,7 @@ export const PageHeader = ({ children }: PropsWithChildren) => { const sidebarState = useSidebar(); const menuButtonRef = useRef(null); const { direction } = useLocale(); + const stringFormatter = useLocalizedString(); let icon = sidebarState.isOpen ? panelLeftCloseIcon : panelLeftOpenIcon; if (direction === 'rtl') { @@ -63,7 +65,7 @@ export const PageHeader = ({ children }: PropsWithChildren) => { > ({ - id, - icon, - label, -})); export function ThemeMenu() { let { theme, setTheme } = useThemeContext(); let matchesDark = useMediaQuery('(prefers-color-scheme: dark)'); + let stringFormatter = useLocalizedStringFormatter(l10nMessages); + let themeItems = useMemo( + () => + Object.entries(THEME_MODE).map(([id, { icon, label }]) => ({ + id, + icon, + label: stringFormatter.format(label), + })), + [stringFormatter] + ); let icon = THEME_MODE[theme].icon; if (theme === 'auto') { icon = matchesDark ? moonIcon : sunIcon; @@ -95,7 +100,10 @@ export function ThemeMenu() { return ( - + - Sign into Cloud + {stringFormatter.format('signIntoCloud')} ); } @@ -161,12 +170,13 @@ export function UserMenu(user: { let config = useConfig(); const cloudInfo = useCloudInfo(); const imageLibraryUrl = useImageLibraryURL(); + const stringFormatter = useLocalizedStringFormatter(l10nMessages); const menuItems = useMemo(() => { let items: MenuItem[] = [ { key: 'logout', - label: 'Log out', + label: stringFormatter.format('logOut'), href: config.storage.kind === 'github' ? '/api/keystatic/github/logout' @@ -177,7 +187,7 @@ export function UserMenu(user: { if (config.cloud?.project) { items.unshift({ key: 'manage', - label: 'Account', + label: stringFormatter.format('account'), icon: userIcon, href: 'https://keystatic.cloud/account', target: '_blank', @@ -187,7 +197,7 @@ export function UserMenu(user: { if (cloudInfo?.team.images) { items.unshift({ key: 'image-library', - label: 'Image library', + label: stringFormatter.format('imageLibrary'), icon: imageIcon, href: imageLibraryUrl, target: '_blank', @@ -195,7 +205,7 @@ export function UserMenu(user: { }); } return items; - }, [cloudInfo, config, imageLibraryUrl]); + }, [cloudInfo, config, imageLibraryUrl, stringFormatter]); if (!user) { return null; @@ -257,11 +267,12 @@ const UserDetailsButton = forwardRef(function UserDetailsButton( ref: ForwardedRef ) { let { avatarUrl, login, name, ...otherProps } = props; + let stringFormatter = useLocalizedStringFormatter(l10nMessages); return ( { @@ -485,10 +498,10 @@ export function GitMenu() { {deleteBranchDialogVisible && ( { if (repoInfo) { @@ -504,8 +517,9 @@ export function GitMenu() { } }} > - Are you sure you want to delete the "{currentBranch}" branch? This - cannot be undone. + {stringFormatter.format('deleteBranchConfirmation', { + branchName: currentBranch, + })} )} diff --git a/packages/keystatic/src/app/shell/sidebar/index.tsx b/packages/keystatic/src/app/shell/sidebar/index.tsx index 20d2b3380..be110b131 100644 --- a/packages/keystatic/src/app/shell/sidebar/index.tsx +++ b/packages/keystatic/src/app/shell/sidebar/index.tsx @@ -34,7 +34,6 @@ import l10nMessages from '../../l10n'; import { useRouter } from '../../router'; import { ItemOrGroup, useNavItems } from '../../useNavItems'; import { isLocalConfig } from '../../utils'; -import { pluralize } from '../../pluralize'; import { useBrand } from '../common'; import { SIDE_PANEL_ID } from '../constants'; @@ -286,6 +285,7 @@ function useIsCurrent() { // ---------------------------------------------------------------------------- function NavItemOrGroup({ itemOrGroup }: { itemOrGroup: ItemOrGroup }) { const isCurrent = useIsCurrent(); + const stringFormatter = useLocalizedStringFormatter(l10nMessages); if (itemOrGroup.isDivider) { return ; } @@ -309,10 +309,8 @@ function NavItemOrGroup({ itemOrGroup }: { itemOrGroup: ItemOrGroup }) { {itemOrGroup.changed} - {pluralize(itemOrGroup.changed, { - singular: 'change', - plural: 'changes', - inclusive: false, + {stringFormatter.format('changesWithoutCount', { + count: itemOrGroup.changed, })} @@ -320,7 +318,7 @@ function NavItemOrGroup({ itemOrGroup }: { itemOrGroup: ItemOrGroup }) { ); From f16d2f69bf540505a37f81b6c2295ee68787242d Mon Sep 17 00:00:00 2001 From: Albert Casanovas Date: Wed, 18 Nov 2026 14:53:21 +0000 Subject: [PATCH 03/12] Localize collection and entry pages --- packages/keystatic/src/app/CollectionPage.tsx | 71 +++++++++++------ packages/keystatic/src/app/ItemPage.tsx | 77 +++++++++++-------- packages/keystatic/src/app/SingletonPage.tsx | 36 +++++---- .../keystatic/src/app/branch-selection.tsx | 33 ++++++-- packages/keystatic/src/app/create-item.tsx | 45 +++++++---- packages/keystatic/src/app/entry-clipboard.ts | 19 +++-- packages/keystatic/src/app/fork-repo.tsx | 48 ++++++------ packages/keystatic/src/app/l10n/en-US.json | 56 ++++++++++++++ packages/keystatic/src/app/persistence.tsx | 34 +++++--- packages/keystatic/src/app/updating.tsx | 19 +++-- 10 files changed, 301 insertions(+), 137 deletions(-) diff --git a/packages/keystatic/src/app/CollectionPage.tsx b/packages/keystatic/src/app/CollectionPage.tsx index 1604f34cc..fb26e4ecc 100644 --- a/packages/keystatic/src/app/CollectionPage.tsx +++ b/packages/keystatic/src/app/CollectionPage.tsx @@ -42,6 +42,7 @@ import { sortBy } from './collection-sort'; import l10nMessages from './l10n'; import { useRouter } from './router'; import { EmptyState } from './shell/empty-state'; +import { formatWithElements } from './shell/i18n'; import { useTree, TreeData, @@ -183,7 +184,7 @@ function CollectionPageHeader(props: { /> { setSearchVisible(true); @@ -218,6 +219,7 @@ function CollectionPageHeader(props: { type CollectionPageContentProps = CollectionPageProps & { searchTerm: string }; function CollectionPageContent(props: CollectionPageContentProps) { const trees = useTree(); + const stringFormatter = useLocalizedStringFormatter(l10nMessages); const tree = trees.merged.kind === 'loaded' @@ -230,11 +232,11 @@ function CollectionPageContent(props: CollectionPageContentProps) { return ( - Dashboard + {stringFormatter.format('dashboard')} } /> @@ -245,7 +247,7 @@ function CollectionPageContent(props: CollectionPageContentProps) { return ( @@ -257,20 +259,18 @@ function CollectionPageContent(props: CollectionPageContentProps) { return ( - There aren't any entries yet.{' '} + title={stringFormatter.format('emptyCollection')} + message={formatWithElements(stringFormatter, 'emptyCollectionMessage', { + createLink: ( - Create the first entry - {' '} - to see it here. - - } + {stringFormatter.format('createTheFirstEntry')} + + ), + })} /> ); } @@ -295,6 +295,7 @@ function CollectionTable( const currentBranch = useCurrentBranch(); let isLocalMode = isLocalConfig(props.config); let router = useRouter(); + let stringFormatter = useLocalizedStringFormatter(l10nMessages); let [sortDescriptor, setSortDescriptor] = useState({ column: SLUG, direction: 'ascending', @@ -465,9 +466,16 @@ function CollectionTable( return [ ...(hideStatusColumn ? [] - : [{ name: 'Status', key: STATUS, minWidth: 32, width: 32 }]), + : [ + { + name: stringFormatter.format('status'), + key: STATUS, + minWidth: 32, + width: 32, + }, + ]), { - name: 'Slug', + name: stringFormatter.format('slug'), key: SLUG, }, ...collection.columns.map(column => { @@ -480,12 +488,17 @@ function CollectionTable( ]; } return hideStatusColumn - ? [{ name: 'Name', key: SLUG }] + ? [{ name: stringFormatter.format('name'), key: SLUG }] : [ - { name: 'Status', key: STATUS, minWidth: 32, width: 32 }, - { name: 'Name', key: SLUG }, + { + name: stringFormatter.format('status'), + key: STATUS, + minWidth: 32, + width: 32, + }, + { name: stringFormatter.format('name'), key: SLUG }, ]; - }, [collection, hideStatusColumn]); + }, [collection, hideStatusColumn, stringFormatter]); return ( ( )} flex @@ -533,7 +546,10 @@ function CollectionTable( {({ name, key, ...options }) => key === STATUS ? ( - + ) : ( @@ -545,7 +561,16 @@ function CollectionTable( {item => { const statusCell = ( - + {item.status === 'Added' ? ( ) : item.status === 'Changed' ? ( diff --git a/packages/keystatic/src/app/ItemPage.tsx b/packages/keystatic/src/app/ItemPage.tsx index f19cc2de7..73ed2d785 100644 --- a/packages/keystatic/src/app/ItemPage.tsx +++ b/packages/keystatic/src/app/ItemPage.tsx @@ -1,3 +1,4 @@ +import { useLocale } from 'react-aria/I18nProvider'; import { useLocalizedStringFormatter } from 'react-aria/useLocalizedStringFormatter'; import { isHotkey } from 'is-hotkey'; import { @@ -133,6 +134,7 @@ function ItemPageInner( onUpdate: parentOnUpdate, } = props; const { collectionConfig, schema } = useCollection(collection); + const stringFormatter = useLocalizedStringFormatter(l10nMessages); const router = useRouter(); const baseCommit = useBaseCommit(); @@ -198,15 +200,20 @@ function ItemPageInner( }); const onPaste = useEventCallback(async () => { - const entry = await getPastedEntry(formatInfo, collectionConfig.schema, { - field: collectionConfig.slugField, - slug: getSlugFromState(collectionConfig, props.state), - }); + const entry = await getPastedEntry( + formatInfo, + collectionConfig.schema, + { + field: collectionConfig.slugField, + slug: getSlugFromState(collectionConfig, props.state), + }, + stringFormatter + ); if (entry) { setValueToPreviewProps(entry, props.previewProps); - toastQueue.positive('Entry pasted', { + toastQueue.positive(stringFormatter.format('entryPasted'), { shouldCloseOnAction: true, - actionLabel: 'Undo', + actionLabel: stringFormatter.format('undo'), onAction: () => { setValueToPreviewProps(props.state, props.previewProps); }, @@ -582,34 +589,34 @@ function HeaderActions(props: { let items: ActionType[] = [ { key: 'reset', - label: 'Reset changes', // TODO: l10n + label: stringFormatter.format('resetChanges'), icon: historyIcon, }, { key: 'delete', - label: 'Delete entry…', // TODO: l10n + label: stringFormatter.format('deleteEntryEllipsis'), icon: trash2Icon, }, { key: 'copy', - label: 'Copy entry', // TODO: l10n + label: stringFormatter.format('copyEntry'), icon: clipboardCopyIcon, }, { key: 'paste', - label: 'Paste entry', // TODO: l10n + label: stringFormatter.format('pasteEntry'), icon: clipboardPasteIcon, }, { key: 'duplicate', - label: 'Duplicate entry…', // TODO: l10n + label: stringFormatter.format('duplicateEntryEllipsis'), icon: copyPlusIcon, }, ]; if (previewHref) { items.push({ key: 'preview', - label: 'Preview', + label: stringFormatter.format('preview'), icon: externalLinkIcon, href: previewHref, target: '_blank', @@ -619,7 +626,7 @@ function HeaderActions(props: { if (viewHref) { items.push({ key: 'view', - label: 'View on GitHub', + label: stringFormatter.format('viewOnGitHub'), icon: githubIcon, href: viewHref, target: '_blank', @@ -628,13 +635,13 @@ function HeaderActions(props: { } return items; - }, [previewHref, viewHref]); + }, [previewHref, viewHref, stringFormatter]); const indicatorElement = (() => { if (isLoading) { return ( - Unsaved + {stringFormatter.format('unsaved')} ) : ( - Unsaved + {stringFormatter.format('unsaved')} ); } @@ -720,28 +727,28 @@ function HeaderActions(props: { setDeleteAlertOpen(false)}> {deleteAlertIsOpen && ( - Are you sure? This action cannot be undone. + {stringFormatter.format('deleteEntryConfirmation')} )} setDuplicateAlertOpen(false)}> {duplicateAlertIsOpen && ( - You have unsaved changes. Save this entry to duplicate it. + {stringFormatter.format('saveAndDuplicateMessage')} )} @@ -756,6 +763,7 @@ export function CreateBranchDuringUpdateDialog(props: { reason: string; }) { const stringFormatter = useLocalizedStringFormatter(l10nMessages); + const { locale } = useLocale(); const repoInfo = useRepoInfo(); const [branchName, setBranchName] = useState(''); const [{ error, fetching, data }, createBranch] = useCreateBranchMutation(); @@ -806,10 +814,14 @@ export function CreateBranchDuringUpdateDialog(props: { @@ -819,14 +831,14 @@ export function CreateBranchDuringUpdateDialog(props: { )} @@ -848,6 +860,7 @@ function ItemPageOuterWrapper(props: ItemPageWrapperProps) { () => getCollectionFormat(props.config, props.collection), [props.config, props.collection] ); + const stringFormatter = useLocalizedStringFormatter(l10nMessages); const slugInfo = useMemo(() => { return { slug: props.itemSlug, field: collectionConfig.slugField }; @@ -934,7 +947,9 @@ function ItemPageOuterWrapper(props: ItemPageWrapperProps) { fallback={ - Entry not found. + + {stringFormatter.format('entryNotFound')} + } @@ -957,7 +972,7 @@ function ItemPageOuterWrapper(props: ItemPageWrapperProps) { minHeight="scale.3000" > diff --git a/packages/keystatic/src/app/SingletonPage.tsx b/packages/keystatic/src/app/SingletonPage.tsx index e64eef51e..0927209b0 100644 --- a/packages/keystatic/src/app/SingletonPage.tsx +++ b/packages/keystatic/src/app/SingletonPage.tsx @@ -1,4 +1,5 @@ import { useRouter } from './router'; +import { useLocalizedString } from './shell/i18n'; import { FormEvent, ReactElement, @@ -93,6 +94,7 @@ function SingletonPageInner( const { schema, singletonConfig } = useSingleton(props.singleton); const router = useRouter(); + const stringFormatter = useLocalizedString(); const previewHref = useMemo(() => { if (!singletonConfig.previewUrl) return undefined; @@ -129,24 +131,24 @@ function SingletonPageInner( }[] = [ { key: 'reset', - label: 'Reset', + label: stringFormatter.format('reset'), icon: historyIcon, }, { key: 'copy', - label: 'Copy entry', + label: stringFormatter.format('copyEntry'), icon: clipboardCopyIcon, }, { key: 'paste', - label: 'Paste entry', + label: stringFormatter.format('pasteEntry'), icon: clipboardPasteIcon, }, ]; if (previewHref) { actions.push({ key: 'preview', - label: 'Preview', + label: stringFormatter.format('preview'), icon: externalLinkIcon, href: previewHref, target: '_blank', @@ -156,7 +158,7 @@ function SingletonPageInner( if (viewHref) { actions.push({ key: 'view', - label: 'View on GitHub', + label: stringFormatter.format('viewOnGitHub'), icon: githubIcon, href: viewHref, target: '_blank', @@ -164,7 +166,7 @@ function SingletonPageInner( }); } return actions; - }, [previewHref, viewHref]); + }, [previewHref, viewHref, stringFormatter]); const formID = 'singleton-form'; @@ -194,13 +196,14 @@ function SingletonPageInner( const entry = await getPastedEntry( formatInfo, singletonConfig.schema, - undefined + undefined, + stringFormatter ); if (entry) { setValueToPreviewProps(entry, props.previewProps); - toastQueue.positive('Entry pasted', { + toastQueue.positive(stringFormatter.format('entryPasted'), { shouldCloseOnAction: true, - actionLabel: 'Undo', + actionLabel: stringFormatter.format('undo'), onAction: () => { setValueToPreviewProps(props.state, props.previewProps); }, @@ -217,13 +220,17 @@ function SingletonPageInner( {props.updateResult.kind === 'loading' ? ( ) : ( - props.hasChanged && Unsaved + props.hasChanged && ( + {stringFormatter.format('unsaved')} + ) )} @@ -268,7 +275,7 @@ function SingletonPageInner( prominence="high" type="submit" > - {isCreating ? 'Create' : 'Save'} + {stringFormatter.format(isCreating ? 'create' : 'save')} getSingletonFormat(props.config, props.singleton), [props.config, props.singleton] ); + const stringFormatter = useLocalizedString(); const dirpath = getSingletonPath(props.config, props.singleton); @@ -661,7 +669,9 @@ function SingletonPageWrapper(props: { singleton: string; config: Config }) { minHeight="scale.3000" > diff --git a/packages/keystatic/src/app/branch-selection.tsx b/packages/keystatic/src/app/branch-selection.tsx index 97d7802a8..576bba1bf 100644 --- a/packages/keystatic/src/app/branch-selection.tsx +++ b/packages/keystatic/src/app/branch-selection.tsx @@ -1,3 +1,4 @@ +import { useLocale } from 'react-aria/I18nProvider'; import { useLocalizedStringFormatter } from 'react-aria/useLocalizedStringFormatter'; import { gql } from '@ts-gql/tag/no-transform'; import { useMemo, useState } from 'react'; @@ -17,6 +18,7 @@ import { TextField } from '@keystar/ui/text-field'; import { Heading, Text } from '@keystar/ui/typography'; import l10nMessages from './l10n'; +import type { KeystaticStringFormatter } from './l10n/default-formatter'; import { useRouter } from './router'; import { Ref_base, @@ -106,6 +108,7 @@ export function CreateBranchDialog(props: { const currentBranch = useCurrentBranch(); const isDefaultBranch = repoInfo?.defaultBranch === currentBranch; const stringFormatter = useLocalizedStringFormatter(l10nMessages); + const { locale } = useLocale(); const [{ error, fetching }, createBranch] = useCreateBranchMutation(); const createBranchSubmitButtonId = 'create-branch-submit-button'; @@ -165,7 +168,11 @@ export function CreateBranchDialog(props: { label={stringFormatter.format('branchName')} // description="Your new branch will be based on the currently checked out branch, which is the default branch for this repository." autoFocus - errorMessage={prettyErrorForCreateBranchMutation(error)} + errorMessage={prettyErrorForCreateBranchMutation( + error, + stringFormatter, + locale + )} {...propsForBranchPrefix} /> ) : ( @@ -175,7 +182,11 @@ export function CreateBranchDialog(props: { value={branchName} onChange={setBranchName} autoFocus - errorMessage={prettyErrorForCreateBranchMutation(error)} + errorMessage={prettyErrorForCreateBranchMutation( + error, + stringFormatter, + locale + )} {...propsForBranchPrefix} /> branchname.includes(c)); if (invalidMatches.length > 0) { let options = { style: 'long', type: 'conjunction' } as const; - let formatter = new Intl.ListFormat('en-US', options); + let formatter = new Intl.ListFormat(locale, options); let list = invalidMatches.map(char => `"${char}"`); - return `Some characters are not allowed: ${formatter.format(list)}`; + return stringFormatter.format('branchNameCharactersNotAllowed', { + characters: formatter.format(list), + }); } // unknown - return 'Invalid branch name'; + return stringFormatter.format('invalidBranchName'); } return error.message; diff --git a/packages/keystatic/src/app/create-item.tsx b/packages/keystatic/src/app/create-item.tsx index 6f8d2417e..7a7262cb9 100644 --- a/packages/keystatic/src/app/create-item.tsx +++ b/packages/keystatic/src/app/create-item.tsx @@ -65,6 +65,7 @@ function CreateItemWrapper(props: { basePath: string; }) { const router = useRouter(); + const stringFormatter = useLocalizedStringFormatter(l10nMessages); const duplicateSlug = useMemo(() => { const url = new URL(router.href, 'http://localhost'); return url.searchParams.get('duplicate'); @@ -207,7 +208,7 @@ function CreateItemWrapper(props: { return ( @@ -221,7 +222,9 @@ function CreateItemWrapper(props: { ) { return ( - Entry not found. + + {stringFormatter.format('entryNotFound')} + ); } @@ -457,7 +460,9 @@ function CreateItemInner(props: { if (await props.createItem()) { const slug = getSlugFromState(collectionConfig, props.state); router.push(`${collectionPath}/item/${encodeURIComponent(slug)}`); - toastQueue.positive('Entry created', { timeout: 5000 }); // TODO: l10n + toastQueue.positive(stringFormatter.format('entryCreated'), { + timeout: 5000, + }); } }; @@ -469,15 +474,20 @@ function CreateItemInner(props: { }; const onPaste = async () => { - const entry = await getPastedEntry(formatInfo, collectionConfig.schema, { - field: collectionConfig.slugField, - slug: getSlugFromState(collectionConfig, props.state), - }); + const entry = await getPastedEntry( + formatInfo, + collectionConfig.schema, + { + field: collectionConfig.slugField, + slug: getSlugFromState(collectionConfig, props.state), + }, + stringFormatter + ); if (entry) { setValueToPreviewProps(entry, props.previewProps); - toastQueue.positive('Entry pasted', { + toastQueue.positive(stringFormatter.format('entryPasted'), { shouldCloseOnAction: true, - actionLabel: 'Undo', + actionLabel: stringFormatter.format('undo'), onAction: () => { setValueToPreviewProps(props.state, props.previewProps); }, @@ -513,7 +523,7 @@ function CreateItemInner(props: { {isLoading && ( @@ -541,9 +551,12 @@ function CreateItemInner(props: { }} > {item => ( - + - {item.label} + {stringFormatter.format(item.label)} )} @@ -648,19 +661,19 @@ function CreateItemInner(props: { const menuActions = [ { key: 'reset', - label: 'Reset', + label: 'reset', icon: historyIcon, }, { key: 'copy', - label: 'Copy entry', + label: 'copyEntry', icon: clipboardCopyIcon, }, { key: 'paste', - label: 'Paste entry', + label: 'pasteEntry', icon: clipboardPasteIcon, }, -]; +] as const; export { CreateItemWrapper as CreateItem }; diff --git a/packages/keystatic/src/app/entry-clipboard.ts b/packages/keystatic/src/app/entry-clipboard.ts index 533b99657..979742fe0 100644 --- a/packages/keystatic/src/app/entry-clipboard.ts +++ b/packages/keystatic/src/app/entry-clipboard.ts @@ -4,6 +4,7 @@ import { ComponentSchema } from '../form/api'; import { serializeEntryToFiles } from './updating'; import { parseEntry } from './useItemData'; import { FormatInfo, getEntryDataFilepath } from './utils'; +import type { KeystaticStringFormatter } from './l10n/default-formatter'; import * as s from 'superstruct'; const keystaticEntryAttributeSchema = s.type({ @@ -66,7 +67,8 @@ function parseEntryFromPlaintext( export async function getPastedEntry( format: FormatInfo, schema: Record, - slugInfo: { field: string; slug: string } | undefined + slugInfo: { field: string; slug: string } | undefined, + stringFormatter: KeystaticStringFormatter ) { let clipboardItems: ClipboardItem[]; try { @@ -75,13 +77,14 @@ export async function getPastedEntry( clipboardItems = await navigator.clipboard.read(); } catch (err) { if (err instanceof DOMException && err.name === 'NotAllowedError') { - toastQueue.critical( - 'Failed to paste because clipboard access was denied', - { timeout: 5000 } - ); + toastQueue.critical(stringFormatter.format('clipboardAccessDenied'), { + timeout: 5000, + }); return; } - toastQueue.critical('Failed to read clipboard', { timeout: 5000 }); + toastQueue.critical(stringFormatter.format('failedToReadClipboard'), { + timeout: 5000, + }); return; } for (const item of clipboardItems) { @@ -107,7 +110,9 @@ export async function getPastedEntry( } } } - toastQueue.critical('Entry not found in clipboard', { timeout: 5000 }); + toastQueue.critical(stringFormatter.format('entryNotFoundInClipboard'), { + timeout: 5000, + }); } function serializeEntryForClipboard( diff --git a/packages/keystatic/src/app/fork-repo.tsx b/packages/keystatic/src/app/fork-repo.tsx index bc513f873..6c59bb540 100644 --- a/packages/keystatic/src/app/fork-repo.tsx +++ b/packages/keystatic/src/app/fork-repo.tsx @@ -14,6 +14,7 @@ import { AppSlugContext } from './onboarding/install-app'; import { Flex } from '@keystar/ui/layout'; import { TextLink } from '@keystar/ui/link'; import { parseRepoConfig, serializeRepoConfig } from './repo-config'; +import { formatWithElements } from './shell/i18n'; export function ForkRepoDialog(props: { onDismiss: () => void; @@ -73,7 +74,7 @@ export function ForkRepoDialog(props: { props.onDismiss(); }} > - Fork Repo + {stringFormatter.format('forkRepo')} {state.kind === 'error' ? ( <> @@ -89,29 +90,30 @@ export function ForkRepoDialog(props: { <> + {stringFormatter.format('forkRepoNoPermission')} - You don't have permission to write to this repo so to save your - changes, you need to fork the repo. - - - To start,{' '} - - fork the repo on GitHub - - . Then, come back to this page and{' '} - - install the Keystatic GitHub App on your fork. - + {formatWithElements(stringFormatter, 'forkRepoInstructions', { + forkLink: ( + + {stringFormatter.format('forkTheRepoOnGitHub')} + + ), + installLink: ( + + {stringFormatter.format('installGitHubAppOnFork')} + + ), + })} diff --git a/packages/keystatic/src/app/l10n/en-US.json b/packages/keystatic/src/app/l10n/en-US.json index 93105e71f..0d22aceb8 100644 --- a/packages/keystatic/src/app/l10n/en-US.json +++ b/packages/keystatic/src/app/l10n/en-US.json @@ -1,58 +1,114 @@ { "account": "Account", "add": "Add", + "added": "Added", "basedOn": "Based on", "branchDoesNotExist": "The branch {branchName} does not exist in this repository.", "branches": "Branches", "branchName": "Branch name", + "branchNameCannotEndWith": "Cannot end with \"{char}\"", + "branchNameCannotStartWith": "Cannot start with \"{char}\"", + "branchNameCharactersNotAllowed": "Some characters are not allowed: {characters}", "branchNotFound": "Branch not found", + "branchRequiresPullRequest": "Changes must be made via pull request to this branch. Create a new branch to save changes.", "cancel": "Cancel", "changeCount": "{count, plural, one {{count} change} other {{count} changes}}", "changed": "Changed", "changesWithoutCount": "{count, plural, one {change} other {changes}}", "clear": "Clear", + "clipboardAccessDenied": "Failed to paste because clipboard access was denied", "collection": "Collection", "collections": "Collections", "content": "Content", + "copyEntry": "Copy entry", "create": "Create", + "createBranchAndSave": "Create branch and save", "createPullRequest": "Create pull request", + "createTheFirstEntry": "Create the first entry", + "creatingBranch": "Creating Branch", + "creatingEntry": "Creating entry", "currentBranch": "Current branch", "dashboard": "Dashboard", "defaultBranch": "Default branch", "delete": "Delete", "deleteBranch": "Delete branch", "deleteBranchConfirmation": "Are you sure you want to delete the \"{branchName}\" branch? This cannot be undone.", + "deleteEntry": "Delete entry", + "deleteEntryConfirmation": "Are you sure? This action cannot be undone.", + "deleteEntryEllipsis": "Delete entry…", + "draftHasChangedSince": "Other changes have been made to this entry since the draft. You may want to discard the draft changes.", + "duplicateEntryEllipsis": "Duplicate entry…", "edit": "Edit", + "emptyCollection": "Empty collection", + "emptyCollectionMessage": "There aren't any entries yet. {createLink} to see it here.", "entryCount": "{count, plural, one {{count} entry} other {{count} entries}}", + "entryCreated": "Entry created", + "entryNotFound": "Entry not found.", + "entryNotFoundInClipboard": "Entry not found in clipboard", + "entryPasted": "Entry pasted", + "entryUpdatedSinceOpened": "This entry has been updated since it was opened. Create a new branch to save changes.", "failedToLoadShell": "Failed to load shell", + "failedToReadClipboard": "Failed to read clipboard", + "failedToUpdate": "Failed to update", + "forkRepo": "Fork Repo", + "forkRepoInstructions": "To start, {forkLink}. Then, come back to this page and {installLink}", + "forkRepoNoPermission": "You don't have permission to write to this repo so to save your changes, you need to fork the repo.", + "forkTheRepoOnGitHub": "fork the repo on GitHub", "gitActions": "git actions", + "githubAppUnableToCommit": "The GitHub App is unable to commit to the repository. Please ensure that the Keystatic GitHub App is installed in the GitHub repository {repo}", "githubRepo": "Github repo", "gitRepoNotInitialised": "Git repo not initialised", "gitRepoNotInitialisedMessage": "The Keystatic GitHub App is installed in the GitHub repository {repo} but the Git repo is not initialised. Please initialise the Git repo before using Keystatic.", "helloName": "Hello, {name}!", "imageLibrary": "Image library", + "installGitHubAppOnFork": "install the Keystatic GitHub App on your fork.", + "invalidBranchName": "Invalid branch name", "loading": "Loading", + "loadingEntries": "Loading Entries", + "loadingItem": "Loading Item", + "loadingName": "Loading {name}", "logOut": "Log out", "manageAccount": "Manage Account", + "name": "Name", "newBranch": "New branch…", + "noItemsMatching": "No items matching \"{searchTerm}\" were found.", + "noResults": "No results", "openAppNavigation": "Open app navigation", "otherBranches": "Other branches", + "pasteEntry": "Paste entry", + "preview": "Preview", "pullRequestNumber": "Pull request #{number}", "pullRequests": "Pull requests", "repository": "Repository", + "reset": "Reset", + "resetChanges": "Reset changes", + "restoredDraftFrom": "Restored draft from {time}.", "save": "Save", + "saveAndDuplicate": "Save and duplicate", + "saveAndDuplicateEntry": "Save and duplicate entry", + "saveAndDuplicateMessage": "You have unsaved changes. Save this entry to duplicate it.", + "savingChanges": "Saving changes", "search": "Search", + "showSearch": "show search", "signIntoCloud": "Sign into Cloud", "singleton": "Singleton", "singletons": "Singletons", + "slug": "Slug", + "status": "Status", "theCurrentlyCheckedOutBranch": "The currently checked out branch. Choose this if you need to build on existing work from the current branch.", "theDefaultBranchInYourRepository": "The default branch in your repository. Choose this to start something new that's not dependent on your current branch.", "theme": "theme", "themeDark": "Dark", "themeLight": "Light", "themeSystem": "System", + "unableToLoadCollection": "Unable to load collection", + "unchanged": "Unchanged", + "undo": "Undo", + "unsaved": "Unsaved", + "updatingName": "Updating {name}", "userMenu": "User menu", "viewFork": "View fork", + "viewOnGitHub": "View on GitHub", "viewPullRequestNumber": "Pull Request #{number}", "viewPullRequests": "View pull requests", "yesDelete": "Yes, delete" diff --git a/packages/keystatic/src/app/persistence.tsx b/packages/keystatic/src/app/persistence.tsx index 4ff335ed9..3126849f7 100644 --- a/packages/keystatic/src/app/persistence.tsx +++ b/packages/keystatic/src/app/persistence.tsx @@ -4,6 +4,8 @@ import { useLocale } from 'react-aria/I18nProvider'; import { UseStore, clear, createStore, del, get, set } from 'idb-keyval'; import { useState, useMemo } from 'react'; +import { formatWithElements, useLocalizedString } from './shell/i18n'; + const units = { seconds: 60, minutes: 60, @@ -44,20 +46,34 @@ function RelativeTime(props: { date: Date }) { return ; } +function DraftRestoredMessage(props: { + savedAt: Date; + hasChangedSince: boolean; +}) { + const stringFormatter = useLocalizedString(); + return ( + + {formatWithElements(stringFormatter, 'restoredDraftFrom', { + time: , + })}{' '} + {props.hasChangedSince && ( + + {stringFormatter.format('draftHasChangedSince')} + + )} + + ); +} + export function showDraftRestoredToast( savedAt: Date, hasChangedSince: boolean ) { toastQueue.info( - - Restored draft from .{' '} - {hasChangedSince && ( - - Other changes have been made to this entry since the draft. You may - want to discard the draft changes. - - )} - , + , { timeout: 8000 } ); } diff --git a/packages/keystatic/src/app/updating.tsx b/packages/keystatic/src/app/updating.tsx index d9e87d11b..43981b297 100644 --- a/packages/keystatic/src/app/updating.tsx +++ b/packages/keystatic/src/app/updating.tsx @@ -28,6 +28,7 @@ import { AppSlugContext } from './onboarding/install-app'; import { createUrqlClient } from './provider'; import { serializeProps } from '../form/serialize-props'; import { scopeEntriesWithPathPrefix } from './shell/path-prefix'; +import { useLocalizedString } from './shell/i18n'; import { base64Encode } from '#base64'; const textEncoder = new TextEncoder(); @@ -133,6 +134,7 @@ export function useUpsertItem(args: { const repoInfo = useRepoInfo(); const appSlug = useContext(AppSlugContext); const unscopedTreeData = useCurrentUnscopedTree(); + const stringFormatter = useLocalizedString(); return [ state, @@ -235,8 +237,7 @@ export function useUpsertItem(args: { ) { setState({ kind: 'needs-new-branch', - reason: - 'Changes must be made via pull request to this branch. Create a new branch to save changes.', + reason: stringFormatter.format('branchRequiresPullRequest'), }); return false; } @@ -283,8 +284,7 @@ export function useUpsertItem(args: { } else { setState({ kind: 'needs-new-branch', - reason: - 'This entry has been updated since it was opened. Create a new branch to save changes.', + reason: stringFormatter.format('entryUpdatedSinceOpened'), }); return false; } @@ -300,7 +300,9 @@ export function useUpsertItem(args: { ) ) { throw new Error( - `The GitHub App is unable to commit to the repository. Please ensure that the Keystatic GitHub App is installed in the GitHub repository ${repoInfo.owner}/${repoInfo.name}` + stringFormatter.format('githubAppUnableToCommit', { + repo: `${repoInfo.owner}/${repoInfo.name}`, + }) ); } @@ -312,7 +314,7 @@ export function useUpsertItem(args: { setState({ kind: 'updated' }); return true; } - throw new Error('Failed to update'); + throw new Error(stringFormatter.format('failedToUpdate')); } else { const res = await fetch('/api/keystatic/update', { method: 'POST', @@ -390,6 +392,7 @@ export function useDeleteItem(args: { const repoInfo = useRepoInfo(); const appSlug = useContext(AppSlugContext); const unscopedTreeData = useCurrentUnscopedTree(); + const stringFormatter = useLocalizedString(); return [ state, @@ -444,7 +447,9 @@ export function useDeleteItem(args: { ) ) { throw new Error( - `The GitHub App is unable to commit to the repository. Please ensure that the Keystatic GitHub App is installed in the GitHub repository ${repoInfo.owner}/${repoInfo.name}` + stringFormatter.format('githubAppUnableToCommit', { + repo: `${repoInfo.owner}/${repoInfo.name}`, + }) ); } if (error) { From 640e33dd77e290d4f080b26ef7161207022a49e0 Mon Sep 17 00:00:00 2001 From: Albert Casanovas Date: Wed, 18 Nov 2026 14:53:21 +0000 Subject: [PATCH 04/12] Localize sign-in and GitHub setup screens --- .../keystatic/src/app/cloud-auth-callback.tsx | 10 ++++--- packages/keystatic/src/app/l10n/en-US.json | 28 +++++++++++++++++ .../src/app/onboarding/created-github-app.tsx | 15 +++++----- .../src/app/onboarding/install-app.tsx | 18 ++++++----- .../src/app/onboarding/repo-not-found.tsx | 12 ++++---- .../keystatic/src/app/onboarding/setup.tsx | 30 +++++++++---------- packages/keystatic/src/app/ui.tsx | 13 ++++---- 7 files changed, 80 insertions(+), 46 deletions(-) diff --git a/packages/keystatic/src/app/cloud-auth-callback.tsx b/packages/keystatic/src/app/cloud-auth-callback.tsx index cec4eae10..787b15095 100644 --- a/packages/keystatic/src/app/cloud-auth-callback.tsx +++ b/packages/keystatic/src/app/cloud-auth-callback.tsx @@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from 'react'; import * as s from 'superstruct'; import { Config } from '../config'; import { useRouter } from './router'; +import { useLocalizedString } from './shell/i18n'; import { KEYSTATIC_CLOUD_API_URL, KEYSTATIC_CLOUD_HEADERS } from './utils'; import { Flex } from '@keystar/ui/layout'; @@ -20,6 +21,7 @@ const tokenResponseSchema = s.type({ export function KeystaticCloudAuthCallback({ config }: { config: Config }) { const router = useRouter(); + const stringFormatter = useLocalizedString(); const url = new URL(window.location.href); const code = url.searchParams.get('code'); const state = url.searchParams.get('state'); @@ -77,13 +79,13 @@ export function KeystaticCloudAuthCallback({ config }: { config: Config }) { } }, [code, state, router, storedState, config]); if (!config.cloud?.project) { - return Missing Keystatic Cloud config; + return {stringFormatter.format('missingKeystaticCloudConfig')}; } if (!code || !state) { - return Missing code or state; + return {stringFormatter.format('missingCodeOrState')}; } if (!storedState || state !== storedState.state) { - return Invalid state; + return {stringFormatter.format('invalidState')}; } if (error) { @@ -94,7 +96,7 @@ export function KeystaticCloudAuthCallback({ config }: { config: Config }) { ); diff --git a/packages/keystatic/src/app/l10n/en-US.json b/packages/keystatic/src/app/l10n/en-US.json index 0d22aceb8..beb25b773 100644 --- a/packages/keystatic/src/app/l10n/en-US.json +++ b/packages/keystatic/src/app/l10n/en-US.json @@ -2,6 +2,9 @@ "account": "Account", "add": "Add", "added": "Added", + "addGitHubAppToRepo": "Make sure to add the App to the {repo} repository.", + "appSlugEnvironmentVariableMissing": "The {envName} environment variable wasn't provided so we can't link to the GitHub app installation page. You should find the App on GitHub and add the repo yourself.", + "authenticating": "Authenticating", "basedOn": "Based on", "branchDoesNotExist": "The branch {branchName} does not exist in this repository.", "branches": "Branches", @@ -21,8 +24,10 @@ "collections": "Collections", "content": "Content", "copyEntry": "Copy entry", + "copyRepoName": "Copy Repo Name", "create": "Create", "createBranchAndSave": "Create branch and save", + "createGitHubApp": "Create GitHub App", "createPullRequest": "Create pull request", "createTheFirstEntry": "Create the first entry", "creatingBranch": "Creating Branch", @@ -36,6 +41,8 @@ "deleteEntry": "Delete entry", "deleteEntryConfirmation": "Are you sure? This action cannot be undone.", "deleteEntryEllipsis": "Delete entry…", + "deployedAppUrl": "Deployed App URL", + "deployedAppUrlDescription": "This should the root of your domain. If you're not sure where Keystatic will be deployed, leave this blank and you can update the GitHub app later.", "draftHasChangedSince": "Other changes have been made to this entry since the draft. You may want to discard the draft changes.", "duplicateEntryEllipsis": "Duplicate entry…", "edit": "Edit", @@ -50,35 +57,56 @@ "failedToLoadShell": "Failed to load shell", "failedToReadClipboard": "Failed to read clipboard", "failedToUpdate": "Failed to update", + "findGitHubAppAndAddRepo": "Find the App on GitHub and add the repo.", "forkRepo": "Fork Repo", "forkRepoInstructions": "To start, {forkLink}. Then, come back to this page and {installLink}", "forkRepoNoPermission": "You don't have permission to write to this repo so to save your changes, you need to fork the repo.", "forkTheRepoOnGitHub": "fork the repo on GitHub", "gitActions": "git actions", "githubAppUnableToCommit": "The GitHub App is unable to commit to the repository. Please ensure that the Keystatic GitHub App is installed in the GitHub repository {repo}", + "githubOrganization": "GitHub organization (if any)", + "githubOrganizationDescription": "You must be an owner or GitHub App manager in the organization to create the GitHub App. Leave this blank to create the app in your personal account.", "githubRepo": "Github repo", "gitRepoNotInitialised": "Git repo not initialised", "gitRepoNotInitialisedMessage": "The Keystatic GitHub App is installed in the GitHub repository {repo} but the Git repo is not initialised. Please initialise the Git repo before using Keystatic.", "helloName": "Hello, {name}!", "imageLibrary": "Image library", + "installedKeystatic": "You've installed Keystatic! 🎉", + "installGitHubApp": "Install GitHub App", "installGitHubAppOnFork": "install the Keystatic GitHub App on your fork.", + "installGitHubAppToStart": "To start using Keystatic, you need to install the GitHub app you've created.", "invalidBranchName": "Invalid branch name", + "invalidState": "Invalid state", + "keystaticSetup": "Keystatic Setup", + "keystaticSetupCreateApp": "If you haven't created your GitHub app for Keystatic, you can create one below.", + "keystaticSetupEnvironmentVariables": "If you've already created your GitHub app, make sure to add the following environment variables:", + "keystaticSetupMissingConfig": "Keystatic doesn't have the required config.", + "keystaticSetupRedirect": "After visiting GitHub to create the GitHub app, you'll be redirected back here and secrets generated from GitHub will be written to your {envFile} file.", "loading": "Loading", "loadingEntries": "Loading Entries", "loadingItem": "Loading Item", "loadingName": "Loading {name}", + "logInWithGitHub": "Log in with GitHub", + "logInWithKeystaticCloud": "Log in with Keystatic Cloud", "logOut": "Log out", "manageAccount": "Manage Account", + "missingCodeOrState": "Missing code or state", + "missingKeystaticCloudConfig": "Missing Keystatic Cloud config", "name": "Name", "newBranch": "New branch…", "noItemsMatching": "No items matching \"{searchTerm}\" were found.", "noResults": "No results", + "notFound": "Not found", "openAppNavigation": "Open app navigation", "otherBranches": "Other branches", + "pageNotFoundMessage": "This page could not be found.", "pasteEntry": "Paste entry", "preview": "Preview", "pullRequestNumber": "Pull request #{number}", "pullRequests": "Pull requests", + "repoName": "Repo Name", + "repoNotFound": "Repo not found", + "repoNotFoundMessage": "Keystatic is configured for the {repo} GitHub repo but Keystatic isn't able to access this repo. This is either because you don't have access to this repo or you haven't added the GitHub app to it.", "repository": "Repository", "reset": "Reset", "resetChanges": "Reset changes", diff --git a/packages/keystatic/src/app/onboarding/created-github-app.tsx b/packages/keystatic/src/app/onboarding/created-github-app.tsx index 57b3ee823..64c1094d9 100644 --- a/packages/keystatic/src/app/onboarding/created-github-app.tsx +++ b/packages/keystatic/src/app/onboarding/created-github-app.tsx @@ -3,8 +3,10 @@ import { Heading, Text } from '@keystar/ui/typography'; import { GitHubConfig } from '../..'; import { InstallGitHubApp } from './install-app'; import { serializeRepoConfig } from '../repo-config'; +import { formatWithElements, useLocalizedString } from '../shell/i18n'; export function CreatedGitHubApp(props: { config: GitHubConfig }) { + const stringFormatter = useLocalizedString(); return ( - You've installed Keystatic! 🎉 + {stringFormatter.format('installedKeystatic')} + {stringFormatter.format('installGitHubAppToStart')} - To start using Keystatic, you need to install the GitHub app you've - created. - - - Make sure to add the App to the{' '} - {serializeRepoConfig(props.config.storage.repo)}{' '} - repository. + {formatWithElements(stringFormatter, 'addGitHubAppToRepo', { + repo: {serializeRepoConfig(props.config.storage.repo)}, + })} diff --git a/packages/keystatic/src/app/onboarding/install-app.tsx b/packages/keystatic/src/app/onboarding/install-app.tsx index a51a80a07..21fd7bc3d 100644 --- a/packages/keystatic/src/app/onboarding/install-app.tsx +++ b/packages/keystatic/src/app/onboarding/install-app.tsx @@ -7,6 +7,7 @@ import { useRouter } from '../router'; import { GitHubConfig } from '../../config'; import { createContext, useContext } from 'react'; import { parseRepoConfig } from '../repo-config'; +import { formatWithElements, useLocalizedString } from '../shell/i18n'; export const AppSlugContext = createContext< { envName: string; value: string | undefined } | undefined @@ -21,11 +22,12 @@ export function InstallGitHubApp(props: { config: GitHubConfig }) { new URL(router.href, 'https://example.com').searchParams.get('slug') ?? appSlugFromContext?.value; const parsedRepo = parseRepoConfig(props.config.storage.repo); + const stringFormatter = useLocalizedString(); return ( - Copy Repo Name + {stringFormatter.format('copyRepoName')} {appSlug ? ( @@ -43,18 +45,20 @@ export function InstallGitHubApp(props: { config: GitHubConfig }) { prominence="high" href={`https://github.com/apps/${appSlug}/installations/new`} > - Install GitHub App + {stringFormatter.format('installGitHubApp')} ) : ( {appSlugFromContext ? ( - The {appSlugFromContext.envName} environment variable - wasn't provided so we can't link to the GitHub app installation - page. You should find the App on GitHub and add the repo yourself. + {formatWithElements( + stringFormatter, + 'appSlugEnvironmentVariableMissing', + { envName: {appSlugFromContext.envName} } + )} ) : ( - Find the App on GitHub and add the repo. + {stringFormatter.format('findGitHubAppAndAddRepo')} )} )} diff --git a/packages/keystatic/src/app/onboarding/repo-not-found.tsx b/packages/keystatic/src/app/onboarding/repo-not-found.tsx index cc851d06d..1c89588da 100644 --- a/packages/keystatic/src/app/onboarding/repo-not-found.tsx +++ b/packages/keystatic/src/app/onboarding/repo-not-found.tsx @@ -4,9 +4,11 @@ import { Heading, Text } from '@keystar/ui/typography'; import { GitHubConfig } from '../..'; import { InstallGitHubApp } from './install-app'; import { serializeRepoConfig } from '../repo-config'; +import { formatWithElements, useLocalizedString } from '../shell/i18n'; export function RepoNotFound(props: { config: GitHubConfig }) { const repo = serializeRepoConfig(props.config.storage.repo); + const stringFormatter = useLocalizedString(); return ( - Repo not found + {stringFormatter.format('repoNotFound')} - Keystatic is configured for the{' '} - {repo} GitHub repo but - Keystatic isn't able to access this repo. This is either because you - don't have access to this repo or you haven't added the GitHub app to - it. + {formatWithElements(stringFormatter, 'repoNotFoundMessage', { + repo: {repo}, + })} diff --git a/packages/keystatic/src/app/onboarding/setup.tsx b/packages/keystatic/src/app/onboarding/setup.tsx index 5d1dc58b5..425ea0346 100644 --- a/packages/keystatic/src/app/onboarding/setup.tsx +++ b/packages/keystatic/src/app/onboarding/setup.tsx @@ -7,10 +7,12 @@ import { TextField } from '@keystar/ui/text-field'; import { Heading, Text } from '@keystar/ui/typography'; import { GitHubConfig } from '../..'; import { parseRepoConfig } from '../repo-config'; +import { formatWithElements, useLocalizedString } from '../shell/i18n'; export function KeystaticSetup(props: { config: GitHubConfig }) { const [deployedURL, setDeployedURL] = useState(''); const [organization, setOrganization] = useState(''); + const stringFormatter = useLocalizedString(); return ( - Keystatic Setup + {stringFormatter.format('keystaticSetup')} - Keystatic doesn't have the required config. + {stringFormatter.format('keystaticSetupMissingConfig')} - If you've already created your GitHub app, make sure to add the - following environment variables: + {stringFormatter.format('keystaticSetupEnvironmentVariables')}
  • @@ -47,26 +48,23 @@ export function KeystaticSetup(props: { config: GitHubConfig }) { KEYSTATIC_SECRET
  • - - If you haven't created your GitHub app for Keystatic, you can create - one below. - + {stringFormatter.format('keystaticSetupCreateApp')} - After visiting GitHub to create the GitHub app, you'll be redirected - back here and secrets generated from GitHub will be written to your{' '} - .env file. + {formatWithElements(stringFormatter, 'keystaticSetupRedirect', { + envFile: .env, + })}
    diff --git a/packages/keystatic/src/app/ui.tsx b/packages/keystatic/src/app/ui.tsx index 541ef7d96..fec570502 100644 --- a/packages/keystatic/src/app/ui.tsx +++ b/packages/keystatic/src/app/ui.tsx @@ -23,6 +23,7 @@ import Provider from './provider'; import { AppShell } from './shell'; import { PageBody, PageRoot } from './shell/page'; import { EmptyState } from './shell/empty-state'; +import { useLocalizedString } from './shell/i18n'; import { SingletonPage } from './SingletonPage'; import { CreatedGitHubApp } from './onboarding/created-github-app'; import { KeystaticSetup } from './onboarding/setup'; @@ -100,6 +101,7 @@ function RedirectToBranch(props: { config: Config }) { function PageInner({ config }: { config: Config }) { const { params } = useRouter(); + const stringFormatter = useLocalizedString(); let branch = null, parsedParams, basePath: string; @@ -137,7 +139,7 @@ function PageInner({ config }: { config: Config }) { } } if (params[0] !== 'branch' || params.length < 2) { - return Not found; + return {stringFormatter.format('notFound')}; } branch = params[1]; basePath = `/keystatic/branch/${encodeURIComponent(branch)}`; @@ -154,8 +156,8 @@ function PageInner({ config }: { config: Config }) { @@ -216,6 +218,7 @@ function AuthWrapper(props: { 'unknown' ); const router = useRouter(); + const stringFormatter = useLocalizedString(); useEffect(() => { getAuth(props.config).then(auth => { if (auth) { @@ -245,7 +248,7 @@ function AuthWrapper(props: { target="_top" > - Log in with GitHub + {stringFormatter.format('logInWithGitHub')}
    ); @@ -261,7 +264,7 @@ function AuthWrapper(props: { ); }} > - Log in with Keystatic Cloud + {stringFormatter.format('logInWithKeystaticCloud')} ); From fdeb7fd135c73b1a30d4bb2a22d362e140f6bc2e Mon Sep 17 00:00:00 2001 From: Albert Casanovas Date: Wed, 18 Nov 2026 14:57:57 +0000 Subject: [PATCH 05/12] Localize field inputs and validation messages --- packages/keystatic/src/app/l10n/en-US.json | 46 ++++++++++++++ .../keystatic/src/form/fields/array/ui.tsx | 36 +++++------ .../keystatic/src/form/fields/blocks/ui.tsx | 30 ++++----- .../src/form/fields/cloudImage/ui.tsx | 37 ++++++----- .../keystatic/src/form/fields/date/ui.tsx | 9 ++- .../src/form/fields/date/validateDate.tsx | 22 +++++-- .../keystatic/src/form/fields/datetime/ui.tsx | 9 ++- .../form/fields/datetime/validateDatetime.tsx | 22 +++++-- .../keystatic/src/form/fields/file/ui.tsx | 14 +++-- .../keystatic/src/form/fields/image/ui.tsx | 13 ++-- .../keystatic/src/form/fields/integer/ui.tsx | 9 ++- .../form/fields/integer/validateInteger.tsx | 22 +++++-- .../src/form/fields/multiRelationship/ui.tsx | 29 ++++++--- .../form/fields/multiRelationship/validate.ts | 16 ++--- .../keystatic/src/form/fields/number/ui.tsx | 5 +- .../src/form/fields/number/validateNumber.tsx | 24 ++++++-- .../src/form/fields/pathReference/ui.tsx | 4 +- .../src/form/fields/relationship/ui.tsx | 4 +- .../keystatic/src/form/fields/slug/ui.tsx | 15 +++-- .../keystatic/src/form/fields/text/ui.tsx | 5 +- .../src/form/fields/text/validateText.tsx | 61 +++++++++++++++---- packages/keystatic/src/form/fields/url/ui.tsx | 9 ++- .../src/form/fields/url/validateUrl.tsx | 11 +++- 23 files changed, 329 insertions(+), 123 deletions(-) diff --git a/packages/keystatic/src/app/l10n/en-US.json b/packages/keystatic/src/app/l10n/en-US.json index beb25b773..816e23e59 100644 --- a/packages/keystatic/src/app/l10n/en-US.json +++ b/packages/keystatic/src/app/l10n/en-US.json @@ -3,8 +3,14 @@ "add": "Add", "added": "Added", "addGitHubAppToRepo": "Make sure to add the App to the {repo} repository.", + "addItem": "Add item", + "addName": "Add {name}", + "addTheFirstItem": "Add the first item to see it here.", + "allSelected": "All selected", + "altText": "Alt text", "appSlugEnvironmentVariableMissing": "The {envName} environment variable wasn't provided so we can't link to the GitHub app installation page. You should find the App on GitHub and add the repo yourself.", "authenticating": "Authenticating", + "awaitingImageUrl": "Awaiting URL to display image preview and information…", "basedOn": "Based on", "branchDoesNotExist": "The branch {branchName} does not exist in this repository.", "branches": "Branches", @@ -18,6 +24,8 @@ "changeCount": "{count, plural, one {{count} change} other {{count} changes}}", "changed": "Changed", "changesWithoutCount": "{count, plural, one {change} other {changes}}", + "checking": "Checking…", + "chooseFile": "Choose file", "clear": "Clear", "clipboardAccessDenied": "Failed to paste because clipboard access was denied", "collection": "Collection", @@ -43,11 +51,16 @@ "deleteEntryEllipsis": "Delete entry…", "deployedAppUrl": "Deployed App URL", "deployedAppUrlDescription": "This should the root of your domain. If you're not sure where Keystatic will be deployed, leave this blank and you can update the GitHub app later.", + "done": "Done", + "download": "Download", "draftHasChangedSince": "Other changes have been made to this entry since the draft. You may want to discard the draft changes.", "duplicateEntryEllipsis": "Duplicate entry…", "edit": "Edit", + "editItem": "Edit item", + "editName": "Edit {name}", "emptyCollection": "Empty collection", "emptyCollectionMessage": "There aren't any entries yet. {createLink} to see it here.", + "emptyList": "Empty list", "entryCount": "{count, plural, one {{count} entry} other {{count} entries}}", "entryCreated": "Entry created", "entryNotFound": "Entry not found.", @@ -57,6 +70,27 @@ "failedToLoadShell": "Failed to load shell", "failedToReadClipboard": "Failed to read clipboard", "failedToUpdate": "Failed to update", + "fieldIsNotValidDate": "{label} is not a valid date", + "fieldIsNotValidDatetime": "{label} is not a valid datetime", + "fieldIsNotValidUrl": "{label} is not a valid URL", + "fieldIsRequired": "{label} is required", + "fieldMustBeAfter": "{label} must be after {min}", + "fieldMustBeAtLeast": "{label} must be at least {min}", + "fieldMustBeAtLeastCharacters": "{label} must be at least {min} characters long", + "fieldMustBeAtMost": "{label} must be at most {max}", + "fieldMustBeMultipleOf": "{label} must be a multiple of {step}", + "fieldMustBeNoLaterThan": "{label} must be no later than {max}", + "fieldMustBeNoLongerThanCharacters": "{label} must be no longer than {max} characters", + "fieldMustBeNumber": "{label} must be a number", + "fieldMustBeUnique": "{label} must be unique", + "fieldMustBeWholeNumber": "{label} must be a whole number", + "fieldMustMatchPattern": "{label} must match the pattern {pattern}", + "fieldMustNotBe": "{label} must not be {value}", + "fieldMustNotBeEmpty": "{label} must not be empty", + "fieldMustNotContain": "{label} must not contain {value}", + "fieldMustNotContainSlashes": "{label} must not contain slashes", + "fieldMustNotStartOrEndWithSpaces": "{label} must not start or end with spaces", + "filename": "Filename", "findGitHubAppAndAddRepo": "Find the App on GitHub and add the repo.", "forkRepo": "Fork Repo", "forkRepoInstructions": "To start, {forkLink}. Then, come back to this page and {installLink}", @@ -71,12 +105,16 @@ "gitRepoNotInitialisedMessage": "The Keystatic GitHub App is installed in the GitHub repository {repo} but the Git repo is not initialised. Please initialise the Git repo before using Keystatic.", "helloName": "Hello, {name}!", "imageLibrary": "Image library", + "imageLibraryNoBreak": "Image Library", + "imageUrl": "Image URL", + "imageUrlIsRequired": "Image URL is required.", "installedKeystatic": "You've installed Keystatic! 🎉", "installGitHubApp": "Install GitHub App", "installGitHubAppOnFork": "install the Keystatic GitHub App on your fork.", "installGitHubAppToStart": "To start using Keystatic, you need to install the GitHub app you've created.", "invalidBranchName": "Invalid branch name", "invalidState": "Invalid state", + "itemNumber": "Item {number}", "keystaticSetup": "Keystatic Setup", "keystaticSetupCreateApp": "If you haven't created your GitHub app for Keystatic, you can create one below.", "keystaticSetupEnvironmentVariables": "If you've already created your GitHub app, make sure to add the following environment variables:", @@ -92,9 +130,13 @@ "manageAccount": "Manage Account", "missingCodeOrState": "Missing code or state", "missingKeystaticCloudConfig": "Missing Keystatic Cloud config", + "mustHaveAtLeastItems": "Must have at least {count, plural, one {{count} item} other {{count} items}}.", + "mustHaveAtMostItems": "Must have at most {count, plural, one {{count} item} other {{count} items}}.", "name": "Name", "newBranch": "New branch…", "noItemsMatching": "No items matching \"{searchTerm}\" were found.", + "noItemsSelected": "No items selected…", + "noMoreItems": "No more items…", "noResults": "No results", "notFound": "Not found", "openAppNavigation": "Open app navigation", @@ -104,6 +146,9 @@ "preview": "Preview", "pullRequestNumber": "Pull request #{number}", "pullRequests": "Pull requests", + "regenerate": "Regenerate", + "regenerateAriaLabel": "regenerate", + "remove": "Remove", "repoName": "Repo Name", "repoNotFound": "Repo not found", "repoNotFoundMessage": "Keystatic is configured for the {repo} GitHub repo but Keystatic isn't able to access this repo. This is either because you don't have access to this repo or you haven't added the GitHub app to it.", @@ -134,6 +179,7 @@ "undo": "Undo", "unsaved": "Unsaved", "updatingName": "Updating {name}", + "uploadOrPasteImageUrl": "Upload an image, or copy a URL from the {imageLibraryLink} and paste it into this field.", "userMenu": "User menu", "viewFork": "View fork", "viewOnGitHub": "View on GitHub", diff --git a/packages/keystatic/src/form/fields/array/ui.tsx b/packages/keystatic/src/form/fields/array/ui.tsx index a9209d1bd..d63df3947 100644 --- a/packages/keystatic/src/form/fields/array/ui.tsx +++ b/packages/keystatic/src/form/fields/array/ui.tsx @@ -19,7 +19,6 @@ import { useId, Key, useMemo, useState } from 'react'; import l10nMessages from '../../../app/l10n'; import { getSlugFromState } from '../../../app/utils'; -import { pluralize } from '../../../app/pluralize'; import { ArrayField, ComponentSchema, GenericPreviewProps } from '../../api'; import { clientSideValidateProp } from '../../errors'; @@ -114,7 +113,7 @@ export function ArrayFieldInput( if (modalState.state !== 'edit') return; return ( - Edit item + {stringFormatter.format('editItem')} ( /> @@ -176,7 +175,7 @@ function ArrayFieldAddItemModalContent(props: { )(value); return ( - Add item + {stringFormatter.format('addItem')} ( props: GenericPreviewProps, unknown> & ExtraFieldInputProps @@ -290,20 +288,21 @@ export function useArrayFieldValidationMessage( const { elements, forceValidation, schema } = props; const minLength = schema.validation?.length?.min; const maxLength = schema.validation?.length?.max; + const stringFormatter = useLocalizedStringFormatter(l10nMessages); return useMemo(() => { if (forceValidation) { if (minLength && elements.length < minLength) { - return `Must have at least ${pluralize(minLength, { - singular: 'item', - })}.`; + return stringFormatter.format('mustHaveAtLeastItems', { + count: minLength, + }); } else if (maxLength && elements.length > maxLength) { - return `Must have at most ${pluralize(maxLength, { - singular: 'item', - })}.`; + return stringFormatter.format('mustHaveAtMostItems', { + count: maxLength, + }); } } - }, [elements.length, forceValidation, maxLength, minLength]); + }, [elements.length, forceValidation, maxLength, minLength, stringFormatter]); } export function ArrayFieldListView( @@ -383,7 +382,7 @@ export function ArrayFieldListView( dragAndDropHooks={dragAndDropHooks} height={props.elements.length ? undefined : 'scale.2000'} selectionMode="none" - renderEmptyState={arrayFieldEmptyState} + renderEmptyState={() => } onAction={key => { const idx = props.elements.findIndex(x => x.key === key); if (idx === -1) return; @@ -393,7 +392,9 @@ export function ArrayFieldListView( {item => { const label = props.schema.itemLabel?.(item) || - `Item ${props.elements.indexOf(item) + 1}`; + stringFormatter.format('itemNumber', { + number: props.elements.indexOf(item) + 1, + }); return ( {label} @@ -414,7 +415,8 @@ export function ArrayFieldListView( ); } -function arrayFieldEmptyState() { +function ArrayFieldEmptyState() { + const stringFormatter = useLocalizedStringFormatter(l10nMessages); return ( - Empty list + {stringFormatter.format('emptyList')} - Add the first item to see it here. + {stringFormatter.format('addTheFirstItem')} ); diff --git a/packages/keystatic/src/form/fields/blocks/ui.tsx b/packages/keystatic/src/form/fields/blocks/ui.tsx index 32ec7838f..a15ff05c4 100644 --- a/packages/keystatic/src/form/fields/blocks/ui.tsx +++ b/packages/keystatic/src/form/fields/blocks/ui.tsx @@ -93,7 +93,9 @@ export function BlocksFieldInput( )} - Add + + {stringFormatter.format('add')} + { @@ -136,12 +138,12 @@ export function BlocksFieldInput( return ( - Edit{' '} - { - props.schema.element.discriminant.options.find( - x => x.value === discriminant - )?.label - } + {stringFormatter.format('editName', { + name: + props.schema.element.discriminant.options.find( + x => x.value === discriminant + )?.label ?? '', + })} @@ -161,12 +163,12 @@ export function BlocksFieldInput( return ( - Add{' '} - { - props.schema.element.discriminant.options.find( - x => x.value === discriminant - )?.label - } + {stringFormatter.format('addName', { + name: + props.schema.element.discriminant.options.find( + x => x.value === discriminant + )?.label ?? '', + })} (image.src ? 'good' : ''); const imageLibraryURL = useImageLibraryURL(); + const stringFormatter = useLocalizedString(); const onPaste = (event: ClipboardEvent) => { event.preventDefault(); @@ -81,14 +86,14 @@ function ImageField(props: { const errorMessage = (blurred || props.forceValidation) && props.isRequired && !image.src - ? 'Image URL is required.' + ? stringFormatter.format('imageUrlIsRequired') : undefined; return ( - Upload an image, or copy a URL from the{' '} - - Image Library - {' '} - and paste it into this field. + {formatWithElements(stringFormatter, 'uploadOrPasteImageUrl', { + imageLibraryLink: ( + + {stringFormatter.format('imageLibraryNoBreak')} + + ), + })} } endElement={ @@ -124,7 +131,7 @@ function ImageField(props: { > @@ -166,7 +173,7 @@ function ImageField(props: { />