Options
All
  • Public
  • Public/Protected
  • All
Menu

Class LangContext

A language context. All translation takes place inside a context and contexts nest to allow their configuration to be modified. Normally you'll get a context using the useTranslation hook.

Hierarchy

  • LangContext

Index

Constructors

Properties

defaultLang: string = "en"

The default language for this context. Used for any non-translated content.

retainAmbience: boolean = false

Whether to pass ambient language down the context stack.

Accessors

  • get ambience(): string
  • The ambient language. This is defined in contexts which can't match the desired language so that a lang= attribute can be added to nested elements

    Returns string

  • get language(): string
  • The current language. This is the same as the first element of the languages array.

    Returns string

  • get languages(): string[]
  • Get the language preference stack for this context. The languages array is always normalised - duplicates are removed.

    const ctx = new LangContext({ lang: "cy", defaultLang: "en" });
    expect(ctx.languages).toEqual(["cy", "en"]);

    const ctx2 = ctx.derive({ lang: "de", defaultLang: "fr" });
    expect(ctx2.languages).toEqual(["de", "fr", "cy", "en"]);

    // "en" de-duplicated from languages
    const ctx3 = ctx2.derive({ lang: "en" });
    expect(ctx3.languages).toEqual(["en", "de", "fr", "cy"]);

    // Start from scratch with an explicit lang stack
    const ctx4 = new LangContext({ lang: ["en", "de", "fr", "cy"] });

    // All equivalent stacks are the same object
    expect(ctx4.languages).toBe(ctx3.languages);

    Equivalent language arrays are always the same object. This makes it possible to use languages in e.g. React.useMemo() to perform expensive operations only when the language stack changes.

    Returns string[]

  • get search(): string[]
  • The context's language expanded for searching. The expansion of a particular language stack is canonicalised and cached - different contexts with the same languages will have the same search property too.

    const ctx = new LangContext({
    lang: ["en-GB-x-foo", "en-US", "fr-CA", "de-AT"]
    });
    // Search path expands and groups tags
    console.log(ctx.search);
    // [
    // "en-GB-x-foo",
    // "en-GB",
    // "en-US",
    // "en",
    // "fr-CA",
    // "fr",
    // "de-AT",
    // "de"
    // ]

    The rules for tag expansion are slightly subtle. Notice in the example above that "en" is only injected after both "en-GB" and "en-US".

    Returns string[]

Methods

  • Turn something stringy into a TString. A plain string turns into a TString with its language set to defaultLang.

    Parameters

    Returns TString

    a TString that represents text

  • Create a new context nested below this one overriding any properties as desired.

    const root = new LangContext({ lang: ["en-GB"], defaultLang: "en" });
    const welsh = root.derive({ lang: "cy" });
    console.log(welsh.languages); // ['cy', 'en-GB', 'en']

    Parameters

    Returns LangContext

    a nested context

  • hasTag(tag: string): boolean
  • Check whether this context can resolve a particular tag. Use it to guard translation tags which might be missing.

    Parameters

    • tag: string

      the dictionary tag to check

    Returns boolean

    true if tag can be resolved

  • render(ts: TString, count?: number): string
  • Convert a TString to a string expanding any %{tag} expansions. Expansions are recursively looked up in the dictionary chain. Any % that isn't part of a tag expansion should be escaped as %%

    Parameters

    • ts: TString

      the string to render

    • Optional count: number

      the number of things in case of pluralisation

    Returns string

    a string with any %{tag} references resolved.

  • Resolve a text property which can be

    • a single element array containing the name of a tag
    • an existing TString or TFatString
    • a plain string

    Tags are resolved against the dictionary chain. Plain strings are converted into a TString with the context's defaultLang.

    Parameters

    Returns TString

    a TString containing the translation

  • Get a new language stack that prepends languages to the context's stack.

    const ctx = new LangContext({lang:"en"});
    console.log(ctx.resolveLocales(["cy"])); // ["cy", "en"]

    Parameters

    • langs: string[]

      languages to prepend to context's stack

    Returns LocaleStack

    a language array that prepends langs to the context's stack

  • resolveMagicProps<T>(props: T, lang?: string): T
  • Translate a React style props object by replacing any t-foo properties with foo containing translated text. The value of any t-* properties should be capable of being resolved by resolve.

    Type parameters

    • T

    Parameters

    • props: T

      a properties object to translate

    • Optional lang: string

      an additional language to add to the context's stack

    Returns T

    a new props object with t-* entries translated

  • Resolve a [tag], string, TString, fat string and translate it according to this context's languages.

    Parameters

    Returns TString

    a TString with the best language match selected

  • translateTextAndProps(text: TextPropType, props?: { lang?: string }, count?: number): { props: {}; str: string }
  • This is a convenience method which may be useful when wrapping components that don't work well with Interminimal. For example here's how we can set the page title using NextJS's Head component.

    // Inject page title into a NextJS <Head> component. We have to do the
    // translation explicitly because we can't nest a T inside a Head
    // Use this component *outside* of any other <Head></Head>
    const TTitle: ComponentType<TTitleProps> = ({ text, ...rest }) => {
    // Translate text and props
    const { str, props } = useTranslation().translateTextAndProps(text, rest);
    return (
    <Head>
    <title {...props}>{str}</title>
    </Head>
    );
    };

    Parameters

    • text: TextPropType

      the text to translate

    • props: { lang?: string } = {}

      a React style props object

      • [key: string]: any
      • Optional lang?: string
    • Optional count: number

      how many of a thing we have for pluralisation

    Returns { props: {}; str: string }

    an object { str, props } containing the translated text and properties.

    • props: {}
      • str: string

    Generated using TypeDoc