@k8ordo/i18n

API

@k8ordo/i18nがexportする関数と型の一覧です。入口は1つで、Server ComponentとClient Componentのどちらからもimportできます。

このページの内容

defineLocales

import元 @k8ordo/i18n

アプリのロケールの集合を定義します。ロケールの一覧を使うものは、すべてこの戻り値から読みます。

ts
defineLocales(
  definitions: Record<string, LocaleDefinition>,
  options?: LocalesOptions<D>,
): Locales<L, D>

引数

definitionsRecord<string, LocaleDefinition>
ロケールのタグをキーに、そのロケールのtimeZoneとdirを値にしたオブジェクト。タグはBCP 47で書きます。書いた順がallの順になります。
optionsLocalesOptions<D>
既定のロケールを選ぶオプション。LocalesOptionsを見てください。

戻り値

Locales<L, D> — ロケールの一覧と、一覧から作った関数やスキーマをまとめた集合。

注意

  • ロケールが1つも無い定義は、呼んだ時点でdefineLocales: no locale is definedのTypeErrorになります。一覧に無いdefaultと、BCP 47ではないタグもTypeErrorになります。欠けたtimeZoneや実行環境が知らないtimeZone、ltrでもrtlでもないdirもTypeErrorです。エラー文は種類ごとに違います。
  • 定義した集合はglobalThisに登録されます。messageはそこから既定のロケールを読みます。後から定義した集合が優先されるので、アプリで1回だけ呼びます。
  • キーはリテラル型のまま推論されます。as constは要りません。
src/i18n.ts
export const locales = defineLocales(
  {
    ja: { timeZone: 'Asia/Tokyo', dir: 'ltr' },
    en: { timeZone: 'America/New_York', dir: 'ltr' },
  },
  { default: 'en' },
);

Locales

import元 @k8ordo/i18n

defineLocalesが返す集合の型です。Lはタグの和集合、Dは既定のロケールのタグです。

ts
type Locales<L extends string, D extends L> =
  IntlFormats & {
    all: readonly L[];
    definitions: Readonly<Record<L, LocaleDefinition>>;
    default: D;
    is: (value: unknown) => value is L;
    negotiate: (requested: Iterable<string>) => L;
    negotiateRequest: (
      request: Request,
      options?: NegotiateRequestOptions,
    ) => L;
    localize: (pathname: string, locale: L) => string;
    delocalize: (pathname: string) => Delocalized<L>;
    paramsSchema: LocaleParamsSchema<L>;
    getLocale: () => L;
    run: <T>(locale: L, fn: () => T) => T;
  };

フィールド

allreadonly L[]
書いた順に並んだタグ。
definitionsReadonly<Record<L, LocaleDefinition>>
ロケールごとの{ timeZone, dir }。defineLocalesに渡したオブジェクトです。
defaultD
既定のロケール。どこにもロケールが指定されていないときと、言語の選択でどれも一致しなかったときに使います。
is(value: unknown) => value is L
一覧に含まれるかを確かめる型ガード。大文字と小文字を区別するので、is('EN')はfalseです。
negotiate(requested) => L
希望のタグの並びから、集合のロケールを1つ選びます。タグごとに同じタグ、次に同じ言語のロケールを探します。最後まで無ければ既定のロケールを返します。
negotiateRequest(request, options?) => L
Requestからロケールを選びます。options.cookieで名前を渡したCookieを先に読み、次にAccept-Languageを読みます。
localize(pathname, locale) => string
pathnameの先頭にロケールの区間を付けます。'/ui'は'/en/ui'に、'/'は'/en'になります。
delocalize(pathname) => Delocalized<L>
先頭のロケールの区間を外し、Delocalizedを返します。
paramsSchemaLocaleParamsSchema<L>
{ locale }を検証するStandard Schema。サーバーでは、受け付けたロケールを、検証を呼んだ非同期コンテキストの残りに設定します。
getLocale() => L
今のロケール。ブラウザではURLの先頭の区間、サーバーではparamsSchemaが受け付けたかrunに渡したロケールです。どちらも無ければ既定のロケールです。
run(locale, fn) => T
fnをロケールがlocaleの状態で実行し、fnの戻り値を返します。fnから始まる非同期の処理にも及びます。サーバーでだけ使えます。
dateTimeFormat …IntlFormats
今のロケールのIntlのオブジェクトを返すメンバー。下のIntlFormatsを見てください。

注意

  • どのメンバーもthisを使いません。export const { getLocale } = localesのように取り出して使えます。
  • runをブラウザで呼ぶと、locales.run: in the browser the URL is the locale — navigate insteadのエラーになります。
  • AsyncLocalStorageを取り出せない(process.getBuiltinModuleが無い)サーバーのランタイムでは、runとロケールを受け付けるときのparamsSchemaがエラーになります。エラー文はthis runtime has no AsyncLocalStorage to scope a locale toを含みます。

IntlFormats

import元 @k8ordo/i18n

集合のうち、今のロケールのIntlのオブジェクトを返すメンバーの型です。戻り値のformatやselectなど、Intlのメソッドをそのまま呼べます。

ts
type IntlFormats = {
  dateTimeFormat: (
    options?: LocaleDateTimeFormatOptions,
  ) => Intl.DateTimeFormat;
  numberFormat: (
    options?: Intl.NumberFormatOptions,
  ) => Intl.NumberFormat;
  relativeTimeFormat: (
    options?: Intl.RelativeTimeFormatOptions,
  ) => Intl.RelativeTimeFormat;
  pluralRules: (
    options?: Intl.PluralRulesOptions,
  ) => Intl.PluralRules;
  listFormat: (options?: Intl.ListFormatOptions) => Intl.ListFormat;
};

フィールド

dateTimeFormat(options?) => Intl.DateTimeFormat
今のロケールと、そのロケールのtimeZoneで日時を表示するIntl.DateTimeFormat。
numberFormat(options?) => Intl.NumberFormat
今のロケールのIntl.NumberFormat。
relativeTimeFormat(options?) => Intl.RelativeTimeFormat
今のロケールのIntl.RelativeTimeFormat。
pluralRules(options?) => Intl.PluralRules
今のロケールのIntl.PluralRules。
listFormat(options?) => Intl.ListFormat
今のロケールのIntl.ListFormat。

注意

  • ロケールとオプションの組ごとに1つだけ作り、2回目からは同じものを返します。オプションはJSONにして比べます。
  • どれもフックではありません。Server ComponentでもClient Componentでも、文言の関数の中でも呼べます。

message

import元 @k8ordo/i18n

1つの文言を、すべてのロケールの文とともに宣言します。返す関数は、呼ばれた場所のロケールの文を返します。

ts
function message(variants: Variants<string>): Message;
function message<A extends readonly unknown[]>(
  variants: Variants<(...args: A) => string>,
): Message<A>;

引数

variantsVariants<string> | Variants<(...args: A) => string>
ロケールごとの文。すべてのロケールを文字列で書くか、すべてを同じ引数の関数で書きます。

戻り値

Message<A> — 引数を受け取り、今のロケールの文を返す関数。

注意

  • ロケールの型がRegisterに登録されていれば、ロケールが欠けた宣言は型エラーになります。型で検出できなかった欠けは、読んだ時点でmessage: no text for "en" in ["ja"]のようなTypeErrorになります。
  • どこにもロケールが指定されていないときは、既定のロケールの文を返します。集合がまだ定義されていない環境では、既定のロケールの代わりに最初に書いた文を返します。
  • 引数の型は、型注釈を書いたロケールの関数から推論されます。どこにも書かないとunknownになります。少なくとも1つに書くか、message<[name: string]>({ … })のように型引数で渡します。
  • 宣言に副作用は無いので、どこからも呼ばれない文言はバンドラが取り除きます。
src/messages/nav.ts
export const home = message({ ja: 'ホーム', en: 'Home' });

export const greeting = message({
  ja: (name: string) => `こんにちは、${name}さん`,
  en: (name) => `Hello, ${name}`,
});

Message

import元 @k8ordo/i18n

messageが返す関数の型です。文言をpropsで受け取るコンポーネントは、この型で受け取ります。

ts
type Message<A extends readonly unknown[] = []> = (
  ...args: A
) => string;

注意

  • 関数なので、Server ComponentからClient Componentへpropsで渡せません。Server Componentで呼び、結果の文字列を渡します。

parseAcceptLanguage

import元 @k8ordo/i18n

Accept-Languageヘッダーを、negotiateに渡せるタグの並びにします。

ts
parseAcceptLanguage(header: string | null): string[]

引数

headerstring | null
ヘッダーの値。request.headers.get('accept-language')をそのまま渡せます。

戻り値

string[] — 重みの大きい順に並べたタグ。ヘッダーが無いか空白だけなら空の配列。

注意

  • 重みが同じタグは、ヘッダーの順を保ちます。重みが0以下のタグと*は除きます。
  • タグそのものは確かめません。BCP 47ではないタグはnegotiateが読み飛ばします。
ts
parseAcceptLanguage('en-US;q=0.8, ja, en;q=0.9');
// ['ja', 'en', 'en-US']

currentLocale

import元 @k8ordo/i18n

defineLocalesで定義した集合から、今のロケールを返します。アプリの集合をimportできないライブラリが使います。

ts
currentLocale(): RegisteredLocale | null

戻り値

RegisteredLocale | null — 指定されたロケール。無ければ集合の既定のロケール。集合が定義されていない環境ではnull。

注意

  • @k8ordo/uiのコンポーネントは、自分が表示する文言のロケールをこれで決めます。
  • アプリのコードでは、集合の型が付くlocales.getLocale()を使います。

Register

import元 @k8ordo/i18n

アプリのロケールの型をパッケージに伝える宣言です。アプリで1回だけ手で書きます。@k8ordo/frameworkのアプリでは、src/i18n.tsがexportするlocalesから生成されます。

ts
declare module '@k8ordo/i18n' {
  interface Register {
    locale: LocaleOf<typeof locales>;
  }
}

注意

  • マージするための型なので、typeでなくinterfaceで書きます。
  • ロケールの型がRegisterに登録されるまでは、RegisteredLocaleがstringなので、ロケールの欠けは型エラーになりません。

RegisteredLocale

import元 @k8ordo/i18n

Registerに登録されたロケールの和集合です。

ts
type RegisteredLocale = Register extends {
  locale: infer L extends string;
}
  ? L
  : string;

Variants

import元 @k8ordo/i18n

Registerに登録されたロケールごとに1つずつ値を持つオブジェクトの型です。messageが受け取るのもこの型です。

ts
type Variants<V> = Readonly<Record<RegisteredLocale, V>>;

注意

  • 文言以外にも使えます。言語の切り替えに並べる言語名のように、ロケールごとに漏れなく持たせたい値に向きます。

LocaleOf

import元 @k8ordo/i18n

集合のタグの和集合を取り出します。Registerのlocaleもこの型です。

ts
type LocaleOf<Ls> =
  Ls extends Locales<infer L, infer _D> ? L : never;

LocaleDefinition

import元 @k8ordo/i18n

ロケールごとに書く情報の型です。どちらも実行環境からは導かず、アプリが書きます。

ts
type LocaleDefinition = {
  timeZone: string;
  dir: 'ltr' | 'rtl';
};

フィールド

timeZonestring
そのロケールの日付を表示するIANAのタイムゾーン。サーバーでもブラウザでも同じタイムゾーンで表示するので、日付がずれません。
dir'ltr' | 'rtl'
そのロケールの文字の向き。<html dir>に使います。

LocalesOptions

import元 @k8ordo/i18n

defineLocalesの2つ目の引数の型です。

ts
type LocalesOptions<D extends string> = { default?: D };

フィールド

defaultD
既定のロケール。一覧のタグから選びます。省くと先頭に書いたロケールです。

NegotiateRequestOptions

import元 @k8ordo/i18n

negotiateRequestの2つ目の引数の型です。

ts
type NegotiateRequestOptions = { cookie?: string };

フィールド

cookiestring
訪問者が選んだ言語を持つCookieの名前。省くとAccept-Languageだけを読みます。

Delocalized

import元 @k8ordo/i18n

delocalizeが返す値の型です。

ts
type Delocalized<L extends string> = {
  locale: L | null;
  pathname: string;
};

フィールド

localeL | null
先頭の区間が示すロケール。先頭の区間がロケールでなければnull。
pathnamestring
区間を外した残りのpathname。ロケールの区間しか無いときは/です。

LocaleParamsSchema

import元 @k8ordo/i18n

paramsSchemaの型です。Standard Schemaの形をこのパッケージ自身が宣言しているので、スキーマのライブラリは要りません。

ts
type LocaleParamsSchema<L extends string> = {
  '~standard': {
    version: 1;
    vendor: '@k8ordo/i18n';
    validate: (value: unknown) =>
      | { value: { locale: L } }
      | { issues: { message: string; path: ['locale'] }[] };
  };
};

注意

  • 検証は同期的です。一覧に無いロケールには、path: ['locale']のissueを返します。
  • 受け付けた値は{ locale }だけで、ほかのキーは含みません。

LocaleDateTimeFormatOptions

import元 @k8ordo/i18n

dateTimeFormatのオプションの型です。Intl.DateTimeFormatOptionsからtimeZoneだけを除いた型です。

ts
type LocaleDateTimeFormatOptions = Intl.DateTimeFormatOptions & {
  timeZone?: never;
};

注意

  • asでtimeZoneを通しても、ロケールのtimeZoneで上書きします。
k8ordo

Baselineに入った機能を、制限なく使うReactのライブラリ群。