Options
All
  • Public
  • Public/Protected
  • All
Menu

interminimal

Index

Components

T: TComponent = ...

A wrapper for content that should be translated. It attempts to translate the content you give it according to the active LangContext. It can translate content looked up in the translation dictionary and fat strings (or TStrings).

It can optionally perform template substitution on the translated text, allowing child components to render portions of the translated text with arbitrary wrappers.

By default translated text is wrapped in a span. Render a different element using the as property.

If the wrapped content can't be translated into the context's preferred language it will have a lang= property specifying its actual language.

The simplest usage is to render translatable content without template substition:

// Render multilingual content
const hi = { en: "Hello", de: "Hallo", fr: "Bonjour" };
return <T content={hi} />;
// fr: <span>Bonjour</span>

Template substitution allows you to build whole component trees from a translated string:

const info = {
en: "Here's a %1[useful link] and here's some %2[italic text]",
fr: "Voici %2[du texte en italique] et un %1[lien utile]",
de: "Hier ist ein %1[nützlicher Link] und hier ein %2[kursiver Text]"
};
return (
<T as="div" text={info}>
<T as="a" tag="%1" href="/" />
<T as="i" tag="%2" />
</T>
);
// fr:
// <div>
// Voici <i>du texte en italique</i> et un <a href="/">lien utile</a>
// </div>

You can also look up and translate dictionary tags:

// Same as the previous example if `info` is in the dictionary
return (
<T as="div" tag="info">
<T as="a" tag="%1" href="/" />
<T as="i" tag="%2" />
</T>
);

See Using T for more examples.

Translate: TranslateComponent = ...

Wrap components in a nested LangContext that establishes a new language stack. By default any children will be wrapped in a div with a lang= property that indicates the language of the wrapped content.

Within this context any content which can't be translated into the requested languages will have it's own lang= property to reflect the fact that it is in a different language than expected.

// Renders as <div lang="cy">....</div>
const Welsh: ComponentType<{ children: ReactNode }> = ({ children }) => (
<Translate lang="cy">{children}</Translate>
);

// Renders as <section lang="cy">....</section>
const WelshSection: ComponentType<{ children: ReactNode }> = ({ children }) => (
<Translate as="section" lang="cy">
{children}
</Translate>
);

Unlike TranslateLocal Translate always wraps the translated content in an element with a lang= property.

TranslateLocal: ComponentType<TranslateLocalProps> = ...

Wrap components in a nested LangContext. Used to override settings in the context. For example we can add an additional dictionary.

const Miscount = ({ children }: { children: ReactNode }) => {
// pretend one is three
const dict = { $$dict: { one: { en: "three" } } };
return <TranslateLocal dictionary={dict}>{children}</TranslateLocal>;
};

Dictionary

TDictionaryMeta: {}

Type declaration

  • [key: string]: string
TDictionaryRoot: { $$dict: TDictionaryType; $$meta?: TDictionaryMeta }

The root of a translation dictionary

Type declaration

  • $$dict: TDictionaryType

    the translations

  • Optional $$meta?: TDictionaryMeta

    optional metadata - ignored by Interminimal

nextDict: NextCache<TDictionaryRoot, TDictionaryRoot> = ...
rootDict: TDictionaryRoot = ...
  • checkDictionary(dictionary: object): void

Hooks

  • Hook that gets the currently active translation context. Here's an example of a component that wraps the Intl.DateTimeFormat API using the translation context.

    const TDateFormat: ComponentType<{ date: Date }> = ({ date }) => {
    // Get the context
    const ctx = useTranslation();
    // Use context's languages stack to find a format for our locale
    const dtf = new Intl.DateTimeFormat(ctx.languages);
    // Find out which language was matched...
    const { locale } = dtf.resolvedOptions();
    const ts = TString.literal(dtf.format(date), locale);
    return <T text={ts} />;
    };

    Returns LangContext

    the active translation context

LangContext

StringPropType: TFatString | TString | string
TextPropType: TFatString | TString | string | string[]

Locale

localeRoot: LocaleStack = ...

A global empty locale stack which equals [].

  • Given a set of BCP 47 language tags and a list of locales in descending preference order find the tag that best satisfies the locale preference.

    import { bestLocale } from "interminimal";
    const tags = ["en", "en-GB", "fr", "fr-BE"];
    console.log(bestLocale(tags, ["en-GB"])); // en-GB
    console.log(bestLocale(tags, ["en-AU", "fr-BE"])); // en
    console.log(bestLocale(tags, ["de", "fr-BE", "en"])); // fr-BE
    console.log(bestLocale(tags, ["cy", "fr-BE-x-foo", "en"])); // fr-BE
    console.log(bestLocale(tags, ["de", "de-AT"])); // undefined

    Parameters

    • tags: LocaleStack

      an array of available language tags - order unimportant

    • langs: LocaleStack

      an array of locales to match

    Returns undefined | string

    a language tag or undefined if no match found

  • canonicaliseLanguage(tag: string): undefined | string
  • Canonicalise a language tag. Canonicalisation is cached so don't call this function on untrusted input. Use safeCanonicaliseLanguage for user input.

    Parameters

    • tag: string

      the language to canonicalise

    Returns undefined | string

    the canonical version or undefined if tag is invalid

  • Canonicalise a list of languages.

    console.log(
    canonicaliseLocales(["en", "fr", "en", "de", "de", "fr", "cy", "de"])
    );
    // ["en", "fr", "de", "cy"]

    Equivalent language lists canonicalise to the same array object and can therefore be used as the key for a Map or Set.

    Parameters

    • stack: LocaleStack

      the list of languages to canonicalise

    Returns LocaleStack

    the canonical language stack

  • Parse an HTTP Accept-Language header. Badly formed languages are dropped, languages are canonicalised.

    const stack = parseAcceptLanguage("fr;b=9,en-GB;q=0.9,en-AU;q=0.8");
    console.log(stack); // [ "en-GB", "en-AU" ]

    Parameters

    • accept: string

      the contents of the header

    Returns LocaleStack

    a priority ordered language stack

  • Return the stack that is the result of prepending a (possibly empty) list of locales to a locale stack

    const ls1 = resolveLocales(localeRoot, ["en", "fr"]);
    const ls2 = resolveLocales(ls1, ["fr"]); // now ["fr", "en"]
    const ls3 = resolveLocales(localeRoot, ["fr", "en"]); // also ["fr", "en"]
    if (ls2 === ls3) console.log("Same thing!");

    Parameters

    Returns LocaleStack

    a stack node with the prepended langs

  • safeCanonicaliseLanguage(tag: string): undefined | string
  • Canonicalise a language tag. No caching - safe to use on user input.

    Parameters

    • tag: string

      the language to canonicalise

    Returns undefined | string

    the canonical version or undefined if tag is invalid

Other

LocaleStack: readonly string[]
TProps<C>: PolyPropRef<C, { children?: ReactNode; content?: TextPropType; count?: number; tag?: string; text?: TextPropType }> & TPrefix<ComponentPropsWithoutRef<C>>

Properties for the <T> component.

Type parameters

  • C: ElementType

TranslateLocalProps: LangContextProps & { children: ReactNode }
As: AsComponent = ...
TText: TTextComponent = ...
maxAcceptLanguageLength: 200 = 200
  • Dictionary type guard: checks that an object looks like a dictionary. Specifically does it have a $$dict key?

    Parameters

    • d: object

      maybe a dictionary

    Returns d is TDictionaryRoot

    true if d looks like a dictionary

TString

TFatString: {} & { $$dict?: never } & { $$meta?: object }
TPluralType: { readonly [ key in Intl.LDMLPluralRule]?: string }

Utilities

  • tBind<C>(as: C): ComponentType<TProps<C>>
  • Create a new component that behaves like <T> but with a different default as element.

    const Toption = tBind("option");
    // later
    return <Toption value="1" tag="one" />

    It's also possible to wrap React components.

    const TImage = tBind(Image as FunctionComponent);
    

    The need for the cast is ugly. Not sure how to fix that. PRs welcome...

    The generated components are cached - so whenever you call tBind("p") you will get the same component.

    Type parameters

    • C: ElementType<any>

    Parameters

    • as: C

    Returns ComponentType<TProps<C>>

Generated using TypeDoc