i18n: supported and community language tiers
Automatic language choices resolve only to supported languages; community translations are listed apart in Settings and offered as a one-click switch. waybetter i18n check reads `supported` and generates `tier` into languages.json.
This commit is contained in:
parent
17c86907bc
commit
a41ea542a7
64 changed files with 426 additions and 26 deletions
|
|
@ -21,6 +21,8 @@ export type AppLanguage = {
|
|||
englishName: string;
|
||||
dir: 'ltr' | 'rtl';
|
||||
status: 'source' | 'machine' | 'reviewed';
|
||||
/** `supported`: automatic language choices may resolve to it. `community`: only when picked explicitly. */
|
||||
tier: 'supported' | 'community';
|
||||
reviewers: string[];
|
||||
fallback?: string;
|
||||
/** Share of English messages this catalog translates (its fallback's included), 0..1. */
|
||||
|
|
|
|||
|
|
@ -32,6 +32,12 @@ export type LanguageOptions = {
|
|||
native: { invoke: Invoke; listen: Listen };
|
||||
/** Where the choice is kept for the app's other local windows (default `wb.language`). */
|
||||
storageKey?: string;
|
||||
/**
|
||||
* The supported tier: automatic choices ("Follow the site", "Follow system") resolve only to
|
||||
* these (English is always one). Any other catalog is a community language: it applies only
|
||||
* when picked explicitly. Default: every catalog is supported.
|
||||
*/
|
||||
supported?: readonly string[];
|
||||
};
|
||||
|
||||
type NativeLanguage = { preference?: string; locale?: string; system?: string[] };
|
||||
|
|
@ -40,11 +46,32 @@ type Stored = { preference: LanguagePreference; locale: string; siteLang?: strin
|
|||
/** Where the shell keeps its choice for the app's other local windows (localStorage). */
|
||||
export const DEFAULT_STORAGE_KEY = `wb.language`;
|
||||
|
||||
/** The catalog to use for a preference, the site's reported language and the OS preferences. */
|
||||
export function resolveLocale(preference: LanguagePreference, siteLang: string | null, system: readonly string[], available: readonly string[]): string {
|
||||
if (preference === 'site') return matchLocale(siteLang ? [siteLang] : system, available, siteLang ? matchLocale(system, available) : 'en');
|
||||
if (preference === 'system') return matchLocale(system, available);
|
||||
return matchLocale([preference], available, matchLocale(system, available));
|
||||
/**
|
||||
* The catalog to use for a preference, the site's reported language and the OS preferences.
|
||||
* Automatic choices ("site", "system") only resolve to `supported` languages (default: all of
|
||||
* `available`), through the normal fallback chain (pt-BR -> pt, zh-TW -> zh-Hant); a language
|
||||
* picked explicitly applies whatever its tier.
|
||||
*/
|
||||
export function resolveLocale(preference: LanguagePreference, siteLang: string | null, system: readonly string[], available: readonly string[], supported: readonly string[] = available): string {
|
||||
if (preference === 'site') {
|
||||
if (!siteLang) return matchLocale(system, supported, 'en');
|
||||
const site = matchLocale([siteLang], supported, '');
|
||||
if (site) return site;
|
||||
// The site's language is a community translation: English (it is offered as a switch), not the system language.
|
||||
return matchLocale([siteLang], available, '') ? 'en' : matchLocale(system, supported);
|
||||
}
|
||||
if (preference === 'system') return matchLocale(system, supported);
|
||||
return matchLocale([preference], available, matchLocale(system, supported));
|
||||
}
|
||||
|
||||
/**
|
||||
* The community language an automatic choice would have used had it been supported (the site's or
|
||||
* the system's), or null: the panel offers it as a one-click switch.
|
||||
*/
|
||||
export function communitySuggestion(preference: LanguagePreference, siteLang: string | null, system: readonly string[], available: readonly string[], supported: readonly string[] = available): string | null {
|
||||
if (preference !== 'site' && preference !== 'system') return null;
|
||||
const wanted = resolveLocale(preference, siteLang, system, available, available);
|
||||
return supported.includes(wanted) ? null : wanted;
|
||||
}
|
||||
|
||||
export type Language = ReturnType<typeof createLanguage>;
|
||||
|
|
@ -53,6 +80,7 @@ export function createLanguage(options: LanguageOptions) {
|
|||
const { i18n, nativePrefixes, native } = options;
|
||||
const storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY;
|
||||
const available = i18n.available;
|
||||
const supported = options.supported ? ['en', ...options.supported.filter(code => available.includes(code))] : available;
|
||||
const current = {
|
||||
preference: 'site' as LanguagePreference,
|
||||
siteLang: null as string | null,
|
||||
|
|
@ -88,7 +116,7 @@ export function createLanguage(options: LanguageOptions) {
|
|||
let syncing: Promise<unknown> = Promise.resolve();
|
||||
|
||||
async function apply() {
|
||||
const locale = resolveLocale(current.preference, current.siteLang, current.system, available);
|
||||
const locale = resolveLocale(current.preference, current.siteLang, current.system, available, supported);
|
||||
await i18n.setLocale(locale);
|
||||
paint(i18n.locale);
|
||||
writeStored({ preference: current.preference, locale: i18n.locale, siteLang: current.siteLang });
|
||||
|
|
@ -130,7 +158,7 @@ export function createLanguage(options: LanguageOptions) {
|
|||
/** Another local window (a popover) and previews: the shell's last choice, kept current through storage events. */
|
||||
async function initFollower(forced?: string | null): Promise<void> {
|
||||
const pick = async () => {
|
||||
const locale = forced ? matchLocale([forced], available) : readStored()?.locale ?? matchLocale(browserLanguages(), available);
|
||||
const locale = forced ? matchLocale([forced], available) : readStored()?.locale ?? matchLocale(browserLanguages(), supported);
|
||||
await i18n.setLocale(locale);
|
||||
paint(i18n.locale);
|
||||
};
|
||||
|
|
@ -141,7 +169,10 @@ export function createLanguage(options: LanguageOptions) {
|
|||
}
|
||||
|
||||
function state() {
|
||||
return { preference: current.preference, siteLang: current.siteLang, system: current.system, locale: i18n.locale };
|
||||
return {
|
||||
preference: current.preference, siteLang: current.siteLang, system: current.system, locale: i18n.locale,
|
||||
community: communitySuggestion(current.preference, current.siteLang, current.system, available, supported),
|
||||
};
|
||||
}
|
||||
|
||||
async function set(preference: LanguagePreference): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,15 @@
|
|||
// Settings → Language: follow the site, follow the system, or pick one of the languages the app has
|
||||
// a catalog for (`PanelSite.languages`, the app's frame/language.ts state). Machine-drafted
|
||||
// translations say so and link to the app's contributor guide.
|
||||
// a catalog for (`PanelSite.languages`, the app's frame/language.ts state). Supported languages come
|
||||
// first, community translations (machine drafts nobody has reviewed) in a group below; the two
|
||||
// automatic choices only pick supported ones, so a community language the site or system uses is
|
||||
// offered as a one-click switch. Machine-drafted translations link to the app's contributor guide.
|
||||
import { useMemo, useSyncExternalStore } from 'react';
|
||||
import { invoke } from '../frame/bridge.ts';
|
||||
import { useT } from '../frame/hooks.ts';
|
||||
import { formatNumber } from '../frame/i18n.ts';
|
||||
import type { LanguagePreference } from '../frame/language.ts';
|
||||
import { Badge, Row, Section, Select, type Option } from './controls.tsx';
|
||||
import { groupLanguages } from './languageModel.ts';
|
||||
import { panelSite, type PanelLanguages } from './site.ts';
|
||||
|
||||
/** The language state as a store for React (the snapshot only changes when the state does). */
|
||||
|
|
@ -14,7 +17,7 @@ function languageStore(languages: PanelLanguages) {
|
|||
let cached = languages.state();
|
||||
const snapshot = () => {
|
||||
const next = languages.state();
|
||||
if (next.preference !== cached.preference || next.siteLang !== cached.siteLang || next.locale !== cached.locale || next.system !== cached.system) cached = next;
|
||||
if (next.preference !== cached.preference || next.siteLang !== cached.siteLang || next.locale !== cached.locale || next.system !== cached.system || next.community !== cached.community) cached = next;
|
||||
return cached;
|
||||
};
|
||||
return { subscribe: (listener: () => void) => languages.subscribe(listener), snapshot };
|
||||
|
|
@ -27,17 +30,20 @@ export function LanguageSettings() {
|
|||
const store = useMemo(() => languageStore(languages), [languages]);
|
||||
const current = useSyncExternalStore(store.subscribe, store.snapshot, store.snapshot);
|
||||
const active = LANGUAGES.find(language => language.code === current.locale);
|
||||
const { supported, community } = groupLanguages(LANGUAGES);
|
||||
const siteLanguage = current.siteLang ? LANGUAGES.find(language => language.code === current.siteLang) : null;
|
||||
const options: Array<Option<LanguagePreference>> = [
|
||||
{ value: 'site', label: t('wb.settings.language.followSite'), hint: siteLanguage ? t('wb.settings.language.followSiteNow', { language: siteLanguage.name }) : t('wb.settings.language.followSiteHint') },
|
||||
{ value: 'system', label: t('wb.settings.language.followSystem'), hint: t('wb.settings.language.followSystemHint') },
|
||||
...LANGUAGES.map(language => ({
|
||||
...[...supported, ...community].map(language => ({
|
||||
value: language.code,
|
||||
label: language.name,
|
||||
hint: language.name === language.englishName ? undefined : language.englishName,
|
||||
style: { direction: language.dir },
|
||||
group: community.length ? (language.tier === 'community' ? t('wb.settings.language.groupCommunity') : t('wb.settings.language.groupSupported')) : undefined,
|
||||
})),
|
||||
];
|
||||
const suggested = current.community ? LANGUAGES.find(language => language.code === current.community) : null;
|
||||
const guide = languages.translateUrl;
|
||||
const open = () => { if (guide) invoke('open_external_url', { url: guide }).catch(() => window.open(guide, '_blank', 'noopener')); };
|
||||
const machine = active && active.status === 'machine';
|
||||
|
|
@ -48,6 +54,9 @@ export function LanguageSettings() {
|
|||
<Select label={t('wb.settings.language.label')} value={current.preference} options={options} width={240}
|
||||
onChange={value => { void languages.set(value); }}/>
|
||||
</Row>
|
||||
{suggested && <Row label={t('wb.settings.language.communityAvailable', { language: suggested.name })} keywords="community translation machine">
|
||||
<button type="button" className="bt-btn is-plain is-sm" onClick={() => { void languages.set(suggested.code); }}>{t('wb.settings.language.communitySwitch')}</button>
|
||||
</Row>}
|
||||
{guide && active && active.code !== 'en' && <Row label={t('wb.settings.language.helpTitle')} keywords="translate translation crowdin contribute"
|
||||
hint={machine
|
||||
? t('wb.settings.language.helpMachine', { language: active.name })
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
// and one aligned control on the right (stacked under the label in a narrow split pane). Controls
|
||||
// are small, keyboard-first and announce state with the matching ARIA role.
|
||||
import {
|
||||
createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState,
|
||||
createContext, Fragment, useContext, useEffect, useId, useLayoutEffect, useRef, useState,
|
||||
type CSSProperties, type KeyboardEvent, type ReactNode,
|
||||
} from 'react';
|
||||
import { useT } from '../frame/hooks.ts';
|
||||
|
|
@ -89,7 +89,8 @@ export function Toggle({ checked, onChange, label, disabled }: { checked: boolea
|
|||
// ---------------------------------------------------------------------------------------------
|
||||
// Segmented control (2-4 options)
|
||||
|
||||
export type Option<T extends string | number> = { value: T; label: string; hint?: string; icon?: ReactNode; style?: CSSProperties };
|
||||
/** `group`: a Select shows a heading above the first option of each group (options of a group are consecutive). */
|
||||
export type Option<T extends string | number> = { value: T; label: string; hint?: string; icon?: ReactNode; style?: CSSProperties; group?: string };
|
||||
|
||||
export function Segmented<T extends string | number>({ value, options, onChange, label, size = 'md' }: { value: T | null; options: Array<Option<T>>; onChange(next: T): void; label: string; size?: 'sm' | 'md' }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
|
@ -149,7 +150,7 @@ export function Select<T extends string>({ value, options, onChange, label, plac
|
|||
document.addEventListener('pointerdown', close);
|
||||
return () => document.removeEventListener('pointerdown', close);
|
||||
}, [open]);
|
||||
useEffect(() => { if (open) list.current?.querySelectorAll('li')[active]?.scrollIntoView({ block: 'nearest' }); }, [active, open]);
|
||||
useEffect(() => { if (open) list.current?.querySelectorAll('li[role="option"]')[active]?.scrollIntoView({ block: 'nearest' }); }, [active, open]);
|
||||
const choose = (option: Option<T>) => { onChange(option.value); setOpen(false); root.current?.querySelector<HTMLElement>('button')?.focus(); };
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (!open && ['ArrowDown', 'ArrowUp', 'Enter', ' '].includes(event.key)) { event.preventDefault(); setOpen(true); return; }
|
||||
|
|
@ -168,12 +169,15 @@ export function Select<T extends string>({ value, options, onChange, label, plac
|
|||
<svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true"><path d="M3 4.5 6 7.5 9 4.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
|
||||
</button>
|
||||
{open && <ul ref={list} id={id} role="listbox" aria-label={label} className="bt-select-list" aria-activedescendant={`${id}-${active}`}>
|
||||
{options.map((option, i) => <li key={String(option.value)} id={`${id}-${i}`} role="option" aria-selected={option.value === value}
|
||||
className={`${i === active ? 'is-active' : ''} ${option.value === value ? 'is-on' : ''}`} onPointerEnter={() => setActive(i)} onClick={() => choose(option)}>
|
||||
<span className="bt-select-opt" style={option.style}>{option.icon}{option.label}</span>
|
||||
{option.hint && <small>{option.hint}</small>}
|
||||
{option.value === value && <svg className="bt-select-check" width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="m3 7.5 2.5 2.5L11 4.5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
|
||||
</li>)}
|
||||
{options.map((option, i) => <Fragment key={String(option.value)}>
|
||||
{option.group && option.group !== options[i - 1]?.group && <li role="presentation" className="bt-select-group">{option.group}</li>}
|
||||
<li id={`${id}-${i}`} role="option" aria-selected={option.value === value}
|
||||
className={`${i === active ? 'is-active' : ''} ${option.value === value ? 'is-on' : ''}`} onPointerEnter={() => setActive(i)} onClick={() => choose(option)}>
|
||||
<span className="bt-select-opt" style={option.style}>{option.icon}{option.label}</span>
|
||||
{option.hint && <small>{option.hint}</small>}
|
||||
{option.value === value && <svg className="bt-select-check" width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="m3 7.5 2.5 2.5L11 4.5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
|
||||
</li>
|
||||
</Fragment>)}
|
||||
</ul>}
|
||||
</div>;
|
||||
}
|
||||
|
|
|
|||
10
packages/shell/src/panel/languageModel.ts
Normal file
10
packages/shell/src/panel/languageModel.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
// Settings → Language: how the app's languages are grouped. Supported ones come first; community
|
||||
// translations (machine drafts nobody has reviewed) are listed apart below them.
|
||||
import type { PanelLanguage } from './site.ts';
|
||||
|
||||
export function groupLanguages(list: readonly PanelLanguage[]): { supported: PanelLanguage[]; community: PanelLanguage[] } {
|
||||
return {
|
||||
supported: list.filter(language => language.tier !== 'community'),
|
||||
community: list.filter(language => language.tier === 'community'),
|
||||
};
|
||||
}
|
||||
|
|
@ -128,6 +128,8 @@
|
|||
.bt-select-value { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.bt-select-list { position: absolute; z-index: 30; top: calc(100% + 6px); inset-inline-end: 0; min-width: 100%; width: max-content; max-width: 300px; max-height: 300px; margin: 0; padding: 5px; overflow-y: auto; list-style: none; border: 1px solid var(--c-line-strong); border-radius: 11px; background: var(--c-popover); box-shadow: 0 18px 50px rgba(0, 0, 0, .6), 0 0 0 1px rgba(0, 0, 0, .4); animation: bt-pop .14s var(--ease); scrollbar-width: thin; }
|
||||
.bt-select-list li { position: relative; display: flex; flex-direction: column; justify-content: center; min-height: 32px; padding-block: 5px; padding-inline: 9px 28px; border-radius: 7px; cursor: pointer; }
|
||||
.bt-select-list li.bt-select-group { min-height: 0; margin-top: 4px; padding-block: 7px 3px; color: var(--c-muted); font-size: 11px; font-weight: 600; cursor: default; pointer-events: none; }
|
||||
.bt-select-list li.bt-select-group:first-child { margin-top: 0; }
|
||||
.bt-select-list li.is-active { background: var(--c-raise); }
|
||||
.bt-select-list li.is-on .bt-select-opt { color: var(--c-text); font-weight: 560; }
|
||||
.bt-select-list li small { color: var(--c-muted); font-size: 11px; }
|
||||
|
|
|
|||
|
|
@ -566,11 +566,15 @@ export const PANEL_MESSAGES = {
|
|||
'wb.settings.home.saved': 'Home page saved.',
|
||||
'wb.settings.home.url': 'Home page URL',
|
||||
'wb.settings.language.active': 'Showing {language}',
|
||||
'wb.settings.language.communityAvailable': '{language} is available as a community translation',
|
||||
'wb.settings.language.communitySwitch': 'Switch',
|
||||
'wb.settings.language.followSite': 'Follow {site}',
|
||||
'wb.settings.language.followSiteHint': 'The language your {site} account is set to',
|
||||
'wb.settings.language.followSiteNow': 'Now: {language}',
|
||||
'wb.settings.language.followSystem': 'Follow system',
|
||||
'wb.settings.language.followSystemHint': 'Your computer\'s language',
|
||||
'wb.settings.language.groupCommunity': 'Community translations — machine-drafted, not reviewed yet',
|
||||
'wb.settings.language.groupSupported': 'Supported languages',
|
||||
'wb.settings.language.help': 'Help translate',
|
||||
'wb.settings.language.helpMachine': 'This {language} translation was drafted by a machine and has not been checked by people yet. Fixes are welcome.',
|
||||
'wb.settings.language.helpReviewed': '{language}: {percent} translated and reviewed by volunteers.',
|
||||
|
|
|
|||
|
|
@ -113,13 +113,15 @@ export type PanelLanguage = {
|
|||
englishName: string;
|
||||
dir: 'ltr' | 'rtl';
|
||||
status: 'source' | 'machine' | 'reviewed';
|
||||
/** `community` languages are listed apart and never chosen automatically. */
|
||||
tier: 'supported' | 'community';
|
||||
coverage: number;
|
||||
};
|
||||
|
||||
/** The app's language state (frame/language.ts `createLanguage`). */
|
||||
export type PanelLanguages = {
|
||||
list: readonly PanelLanguage[];
|
||||
state(): { preference: string; siteLang: string | null; system: readonly string[]; locale: string };
|
||||
state(): { preference: string; siteLang: string | null; system: readonly string[]; locale: string; community: string | null };
|
||||
subscribe(listener: () => void): () => void;
|
||||
set(preference: string): Promise<void>;
|
||||
/** The contributor guide ("Help translate"), opened in the system browser. */
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue