diff --git a/.changeset/localize-keystar-ui-strings.md b/.changeset/localize-keystar-ui-strings.md new file mode 100644 index 000000000..74ba6cd27 --- /dev/null +++ b/.changeset/localize-keystar-ui-strings.md @@ -0,0 +1,5 @@ +--- +'@keystar/ui': patch +--- + +Localize the split view resize handle and the keyboard modifier labels in `Kbd`, and fall back to `en-US` for any key a locale doesn't have diff --git a/.changeset/localize-ui-strings.md b/.changeset/localize-ui-strings.md new file mode 100644 index 000000000..bbc027aa2 --- /dev/null +++ b/.changeset/localize-ui-strings.md @@ -0,0 +1,5 @@ +--- +'@keystatic/core': patch +--- + +Move the Admin UI's hard-coded English strings into the `en-US` locale so they can be translated, and fall back to English for any key a locale doesn't have 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/design-system/pkg/src/split-view/SplitView.tsx b/design-system/pkg/src/split-view/SplitView.tsx index e9846975e..a5cf9066e 100644 --- a/design-system/pkg/src/split-view/SplitView.tsx +++ b/design-system/pkg/src/split-view/SplitView.tsx @@ -7,6 +7,7 @@ import { } from '@keystar/ui/style'; import { useId, useIsMounted } from '@keystar/ui/utils'; import { useLocale } from 'react-aria/I18nProvider'; +import { useLocalizedStringFormatter } from 'react-aria/useLocalizedStringFormatter'; import { filterDOMProps } from 'react-aria/filterDOMProps'; import { useUpdateEffect } from 'react-aria/private/utils/useUpdateEffect'; import { clamp } from 'react-stately/private/utils/number'; @@ -23,6 +24,7 @@ import { import { SplitViewProvider, useSplitView } from './context'; import { resetGlobalCursorStyle, setGlobalCursorStyle } from './cursor'; +import localizedMessages from './l10n'; import { defaultStorage } from './storage'; import { CursorState, @@ -424,13 +426,14 @@ const SplitViewResizeHandle = forwardRef(function SplitViewResizeHandle( forwardedRef: ForwardedRef ) { let { activity, id, isCollapsed } = useSplitView(); + let stringFormatter = useLocalizedStringFormatter(localizedMessages); return ( { 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/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/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/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/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/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 }) + ); diff --git a/packages/keystatic/src/app/l10n/en-US.json b/packages/keystatic/src/app/l10n/en-US.json index 6a3c81874..01ca8099b 100644 --- a/packages/keystatic/src/app/l10n/en-US.json +++ b/packages/keystatic/src/app/l10n/en-US.json @@ -1,29 +1,285 @@ { + "account": "Account", "add": "Add", + "added": "Added", + "addGitHubAppToRepo": "Make sure to add the App to the {repo} repository.", + "addItem": "Add item", + "addLink": "Add link", + "addName": "Add {name}", + "addTheFirstItem": "Add the first item to see it here.", + "alignCenter": "Align Center", + "alignEnd": "Align End", + "alignStart": "Align Start", + "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", - "branchName": "Branch name", + "blockquote": "Blockquote", + "blocks": "Blocks", + "bold": "Bold", + "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.", + "bulletList": "Bullet list", + "bulletListTitleCase": "Bullet List", "cancel": "Cancel", + "cellOptions": "Cell options", + "changeCount": "{count, plural, =1 {{count} change} other {{count} changes}}", + "changed": "Changed", + "changesWithoutCount": "{count, plural, =1 {change} other {changes}}", + "checking": "Checking…", + "chooseFile": "Choose file", "clear": "Clear", + "clearFormatting": "Clear formatting", + "clickToConfigure": "(click to configure)", + "clipboardAccessDenied": "Failed to paste because clipboard access was denied", + "cloudImage": "Cloud image", + "code": "Code", + "codeBlock": "Code block", + "codeBlockLanguage": "Code block language", + "collapse": "Collapse", "collection": "Collection", "collections": "Collections", + "constrainProportions": "Constrain proportions", + "containsInvalidFields": "Contains invalid fields. Please edit.", + "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", + "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.", + "deleteColumn": "Delete column", + "deleteEntry": "Delete entry", + "deleteEntryConfirmation": "Are you sure? This action cannot be undone.", + "deleteEntryEllipsis": "Delete entry…", + "deleteRow": "Delete row", + "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.", + "divider": "Divider", + "documentEditorPlaceholder": "Start writing or press \"/\" for commands...", + "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", + "editImageOptions": "Edit Image Options", + "editItem": "Edit item", + "editLink": "Edit link", + "editName": "Edit {name}", + "emptyCollection": "Empty collection", + "emptyCollectionMessage": "There aren't any entries yet. {createLink} to see it here.", + "emptyList": "Empty list", + "entryCount": "{count, plural, =1 {{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.", + "expand": "Expand", + "failedToLoadShell": "Failed to load shell", + "failedToReadClipboard": "Failed to read clipboard", + "failedToUpdate": "Failed to update", + "failedToUploadImage": "Failed to upload image: {error}", + "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", + "fileName": "File name", + "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", + "formattingOptions": "Formatting options", + "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.", + "headerRow": "Header row", + "heading": "Heading", + "heading1Description": "Use this for a top level heading", + "heading2Description": "Use this for key sections", + "heading3Description": "Use this for sub-sections", + "heading4Description": "Use this for deep headings", + "heading5Description": "Use this for grouping list items", + "heading6Description": "Use this for low-level headings", + "headingLevel": "Heading {level}", + "height": "Height", + "helloName": "Hello, {name}!", + "image": "Image", + "imageDetails": "Image details", + "imageLibrary": "Image library", + "imageLibraryNoBreak": "Image Library", + "imageLibraryTitleCase": "Image Library", + "imageTooLarge": "Images must be smaller than 10MB", + "imageUploaded": "Image uploaded", + "imageUrl": "Image URL", + "imageUrlIsRequired": "Image URL is required.", + "insert": "Insert", + "insertBlock": "Insert block", + "insertBlockquoteDescription": "Insert a quote or citation", + "insertBulletListDescription": "Insert an unordered list", + "insertCodeBlockDescription": "Display code with syntax highlighting", + "insertColumnRight": "Insert column right", + "insertDividerDescription": "A horizontal line to separate content", + "insertImageDescription": "Insert an image", + "insertMenu": "Insert menu", + "insertOrderedListDescription": "Insert an ordered list", + "insertRowBelow": "Insert row below", + "insertTableDescription": "Insert a table", + "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", + "invalidImageType": "Invalid image type, only PNG, JPEG, GIF, and WebP are supported", + "invalidState": "Invalid state", + "italic": "Italic", + "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:", + "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.", + "language": "Language", + "layout": "Layout", + "layouts": "Layouts", + "link": "Link", + "lists": "Lists", "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", + "markdocEditorPlaceholder": "Start writing or press \"/\" for commands…", + "missingCodeOrState": "Missing code or state", + "missingKeystaticCloudConfig": "Missing Keystatic Cloud config", + "mustHaveAtLeastItems": "Must have at least {count, plural, =1 {{count} item} other {{count} items}}.", + "mustHaveAtMostItems": "Must have at most {count, plural, =1 {{count} item} other {{count} items}}.", + "name": "Name", + "nameDetails": "{name} details", "newBranch": "New branch…", + "noItemsMatching": "No items matching \"{searchTerm}\" were found.", + "noItemsSelected": "No items selected…", + "noMoreItems": "No more items…", + "noResults": "No results", + "noResultsEllipsis": "No results…", + "notFound": "Not found", + "numberedList": "Numbered list", + "numberedListTitleCase": "Numbered List", + "openAppNavigation": "Open app navigation", + "options": "Options", + "orderedList": "Ordered list", "otherBranches": "Other branches", + "pageNotFoundMessage": "This page could not be found.", + "paragraph": "Paragraph", + "pasteEntry": "Paste entry", + "pasteImageUrl": "Copy an image URL from the {imageLibraryLink} and paste it into this field.", + "pleaseProvideFileName": "Please provide a file name.", + "pleaseProvideValidUrl": "Please provide a valid URL.", + "preview": "Preview", + "pullRequestNumber": "Pull request #{number}", "pullRequests": "Pull requests", + "quote": "Quote", + "regenerate": "Regenerate", + "regenerateAriaLabel": "regenerate", + "remove": "Remove", + "removeImage": "Remove Image", + "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", + "restoredDraftFrom": "Restored draft from {time}.", + "revertToOriginalDimensions": "Revert to original ({width} × {height})", "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", + "selectColumn": "Select Column", + "selectRow": "Select Row", + "selectTable": "Select Table", + "showSearch": "show search", + "signIntoCloud": "Sign into Cloud", + "signInToUploadImages": "You must be signed in to upload images", "singleton": "Singleton", "singletons": "Singletons", + "slug": "Slug", + "status": "Status", + "strikethrough": "Strikethrough", + "subscript": "Subscript", + "superscript": "Superscript", + "table": "Table", + "text": "Text", + "textAlignment": "Text Alignment", + "textBlock": "Text block", + "textFormatting": "Text formatting", "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", + "unableToLoadCollection": "Unable to load collection", + "unchanged": "Unchanged", + "underline": "Underline", + "undo": "Undo", + "unexpectedResponseFromCloud": "Unexpected response from cloud", + "unlink": "Unlink", + "unsaved": "Unsaved", + "updatingName": "Updating {name}", + "upload": "Upload", + "uploading": "Uploading…", + "uploadingImage": "Uploading image…", + "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", + "viewPullRequestNumber": "Pull Request #{number}", + "viewPullRequests": "View pull requests", + "width": "Width", + "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..45314fc53 --- /dev/null +++ b/packages/keystatic/src/app/l10n/l10n.test.ts @@ -0,0 +1,63 @@ +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'; +import { pluralize } from '../pluralize'; + +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++; + // plural rules differ between locales, the English text must not + for (const count of [0, 1, 2, 5, 21, 101, 1000]) { + expect(formatter.format(key, { count })).toBe( + defaultStringFormatter.format(key, { count }) + ); + } + } + } + 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 + ); + } +}); + +test('counts read the same as before they were localized', () => { + for (const count of [0, 1, 2, 21, 1000]) { + expect(defaultStringFormatter.format('entryCount', { count })).toBe( + pluralize(count, { singular: 'entry', plural: 'entries' }) + ); + expect( + defaultStringFormatter.format('changesWithoutCount', { count }) + ).toBe(pluralize(count, { singular: 'change', inclusive: false })); + } +}); 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/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/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..dac215935 100644 --- a/packages/keystatic/src/app/shell/i18n.tsx +++ b/packages/keystatic/src/app/shell/i18n.tsx @@ -1,8 +1,42 @@ 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]]} + ); +} + +/** Renders a message, for elements that are created outside of a component. */ +export function LocalizedText(props: { + id: LocalizedMessageKey; + args?: Record; +}) { + return <>{useLocalizedString().format(props.id, props.args)}; +} 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 }) { ); 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')} ); 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) { diff --git a/packages/keystatic/src/component-blocks/cloud-image-preview.tsx b/packages/keystatic/src/component-blocks/cloud-image-preview.tsx index b749b1969..c139bb842 100644 --- a/packages/keystatic/src/component-blocks/cloud-image-preview.tsx +++ b/packages/keystatic/src/component-blocks/cloud-image-preview.tsx @@ -31,6 +31,13 @@ import { Heading, Text } from '@keystar/ui/typography'; import { useId } from '@keystar/ui/utils'; import { useConfig } from '../app/shell/context'; +import l10nMessages from '../app/l10n'; +import type { KeystaticStringFormatter } from '../app/l10n/default-formatter'; +import { formatWithElements, useLocalizedString } from '../app/shell/i18n'; +import { + LocalizedStringDictionary, + LocalizedStringFormatter, +} from '@internationalized/string'; import { focusWithPreviousSelection } from '../form/fields/document/DocumentEditor/ui-utils'; import { KEYSTATIC_CLOUD_API_URL, @@ -73,19 +80,21 @@ const imageUploadResponse = s.type({ height: s.number(), }); -function uploadImage(file: File, config: Config) { +function uploadImage( + file: File, + config: Config, + stringFormatter: KeystaticStringFormatter +) { if (file.size > 10_000_000) { - throw new Error('Images must be smaller than 10MB'); + throw new Error(stringFormatter.format('imageTooLarge')); } const auth = getCloudAuth(config); if (!auth) { - throw new Error('You must be signed in to upload images'); + throw new Error(stringFormatter.format('signInToUploadImages')); } const filenameMatch = /(.+)\.(png|jpe?g|gif|webp)$/.exec(file.name); if (!filenameMatch) { - throw new Error( - 'Invalid image type, only PNG, JPEG, GIF, and WebP are supported' - ); + throw new Error(stringFormatter.format('invalidImageType')); } const filename = slugify(filenameMatch[1]); const ext = filenameMatch[2]; @@ -107,7 +116,11 @@ function uploadImage(file: File, config: Config) { body: formData, }); if (!res.ok) { - throw new Error(`Failed to upload image: ${await res.text()}`); + throw new Error( + stringFormatter.format('failedToUploadImage', { + error: await res.text(), + }) + ); } const data = await res.json(); @@ -115,7 +128,7 @@ function uploadImage(file: File, config: Config) { try { parsedData = imageUploadResponse.create(data); } catch { - throw new Error('Unexpected response from cloud'); + throw new Error(stringFormatter.format('unexpectedResponseFromCloud')); } return parsedData; })(); @@ -234,7 +247,11 @@ export function ImageDimensionsInput(props: { const dimensions = useImageDimensions(props.src); const [constrainProportions, setConstrainProportions] = useState(true); - const revertLabel = `Revert to original (${dimensions.width} × ${dimensions.height})`; + const stringFormatter = useLocalizedString(); + const revertLabel = stringFormatter.format('revertToOriginalDimensions', { + width: String(dimensions.width), + height: String(dimensions.height), + }); const dimensionsMatchOriginal = dimensions.width === props.image.width && dimensions.height === props.image.height; @@ -242,7 +259,7 @@ export function ImageDimensionsInput(props: { return ( { setConstrainProportions(state => !state); @@ -268,10 +285,10 @@ export function ImageDimensionsInput(props: { > - Constrain proportions + {stringFormatter.format('constrainProportions')} - {isUploading ? 'Uploading…' : 'Upload'} + {stringFormatter.format(isUploading ? 'uploading' : 'upload')} ); @@ -359,6 +377,7 @@ function ImageDialog(props: { const [status, setStatus] = useState(image ? 'good' : ''); const formId = useId(); const imageLibraryURL = useImageLibraryURL(); + const stringFormatter = useLocalizedString(); const onPaste = (event: ClipboardEvent) => { event.preventDefault(); @@ -394,7 +413,7 @@ function ImageDialog(props: { return ( - Cloud image + {stringFormatter.format('cloudImage')} - Copy an image URL from the{' '} - - Image Library - {' '} - and paste it into this field. + {formatWithElements(stringFormatter, 'pasteImageUrl', { + imageLibraryLink: ( + + {stringFormatter.format('imageLibraryTitleCase')} + + ), + })} } endElement={ @@ -445,7 +466,7 @@ function ImageDialog(props: { > @@ -466,7 +487,7 @@ function ImageDialog(props: { {status === 'good' ? ( <>