项目作者: fileglass

项目描述 :
Fast string formatter for templating, translating and modifying strings
高级语言: TypeScript
项目地址: git://github.com/fileglass/wooboo.git
创建时间: 2021-08-30T15:18:45Z
项目社区:https://github.com/fileglass/wooboo

开源协议:

下载


wooboo

Fast string formatter on steroids

Usage

  1. import Wooboo from "@fileglass/wooboo"
  2. //Create an instance
  3. const formatter = new Wooboo("CATS");
  4. const output = await formatter.fmt("Hello, my name is {name} and I like {insert_cats}", {
  5. "name": {value: "wooboo", modifiers: [new Wooboo.Modifiers.CapitalizeFirst()]},
  6. "insert_cats": {value: "cats"}
  7. })
  8. console.log(output) //Hello, my name is Wooboo and I like cats

Modifying by array

  1. const formatter = new Wooboo("CATS");
  2. const formatted = formatter.fmtArr("I love $0, because $1", ["cats", "they are cute"])
  3. console.log(formatted) // I love cats, because they are cute

Using the built-in modifiers

There are a few built in modifiers, they are stored in the Wooboo.Modifiers static property. (NOTE: Whole string means the value property of the current token)



UpperCase: Uppercases the whole string

LowerCase: Lowercases the whole string

CapitalizeFirst: Capitalizes the first letter of the string

Localizer: Utility to resolve locales (explained below)

Applying modifiers:

Every token accepts a modifiers array (example above)

Creating custom modifiers:

Every modifier has to implement the WooboModifier interface, exported from the root of the module.

The execute method can return a string, or a Promise with a string.

Example:

  1. export default class Localizer implements WooboModifier {
  2. constructor(private readonly locales: { [key: string]: Map<string, string> }) {}
  3. execute(val: string, rawValue: string | number | boolean, token: string, rawString: string, originalValue: string | number | boolean, self: Wooboo): string {
  4. const locale = self.getMeta("LOCALE") as string
  5. return this.locales[locale].get(token) || token
  6. }
  7. }

Params:

val: The stringified value passed to the value property

rawValue: The raw value passed to the value property

token: The token without the {}

rawString: The whole string inputted into the formatter

originalValue: The original value of value before any modifiers were applied

self: The class that the current modifier is executed in

Using the Localizer modifier

localizer.ts

  1. import Wooboo from "@fileglass/woobo"
  2. // Create locales
  3. const englishLocales = new Map<string, string>()
  4. const hungarianLocales = new Map<string, string>()
  5. englishLocales.set("number_disp", "The number is")
  6. hungarianLocales.set("number_disp", "A szám")
  7. const locales = {["en"]: englishLocales, ["hu"]: hungarianLocales}
  8. // Initiate the formatter
  9. const localeFormatter = new Wooboo("LOCALIZER")
  10. localeFormatter.setMeta("LOCALE", "en") // Set metadata for the formatter (the modifier will get the current locale from this)
  11. async function format() {
  12. return await localeFormatter.fmt("{number_disp}: {number}", {
  13. "number": {value: Math.random()},
  14. "number_disp": {value: "can be ignored, the localizer will take care of it", modifiers: [new Wooboo.Modifiers.Localizer(locales)]}
  15. })
  16. }
  17. format().then(result => console.log(result)) // The number is: [random number between 0 and 1]
  18. localeFormatter.setMeta("LOCALE", "hu") // Update the locale to Hungarian
  19. format().then(result => console.log(result)) // A szám: [random number between 0 and 1]

Reusing formatters

If you want to nest formatters, or use them across different files, Wooboo exposes a few utility functions to achieve this in an elegant way.

Using the resolveRef utility

other.ts

  1. import {resolveRef} from "@fileglass/woobo"
  2. const localizer = resolveRef("LOCALIZER")! // Resolve the reference to the `LOCALIZER` formatter, and mark it as defined
  3. localizer.setMeta("LOCALE", "en") // Change back the locale to English
  4. async function format() {
  5. return await localeFormatter.fmt("{number_disp}: {number}", {
  6. "number": {value: Math.random()},
  7. "number_disp": {value: "can be ignored, the localizer will take care of it", modifiers: [new Wooboo.Modifiers.Localizer(locales)]}
  8. })
  9. }
  10. format().then(result => console.log(result)) // The number is: [random number between 0 and 1]

Using the resolveFormatter method in an existing instance

other.ts

  1. import Wooboo from "@fileglass/woobo"
  2. const myFormatter = new Wooboo("MY_FORMATTER")
  3. const localizer = myFormatter.resolveFormatter("LOCALIZER")

Use cases:

Nesting formatters in custom modifiers (self argument)

Avoiding useless imports where possible

Example

mymodifier.ts

  1. import {WooboModifier} from "@fileglass/wooboo"
  2. export class MyModifier implements WooboModifier {
  3. execute(val: string, rawValue: string | number | boolean, token: string, rawString: string, originalValue: string | number | boolean, self: Wooboo): string {
  4. const localizer = self.resolveFormatter("LOCALIZER")
  5. const locale = localizer.getMeta("LOCALE")
  6. // Do actions based on the current locale
  7. }
  8. }

Using the Localizer efficiently (global modifiers)

While the examples above work, always passing modifiers: [new Localizer(locales)] can get tedious. To avoid this, Wooboo has a feature called global modifiers.

Global modifiers will be called on every token in the current class.

Applying global modifiers
  1. const localizer = new Wooboo.Modifiers.Localizer(locales, "LOC_")
  2. const localeFormatter = new Wooboo("LOCALE", [{modifier: localizer, match: "LOC_*"}])

The code above:

  1. Creates a new Localizer instance, assigns the LOC_ prefix to every locale passed to it
  2. Creates a new formatter instance, and sets the previously created Localizer instance as a global modifier
    What does match mean?
    The match property defines a pattern, that if matched (on the token, not on the input string) will trigger the modifier. (How to match patterns)

    In the example above, everything that starts with LOC_ will be matched. (Thats why we prefixed all the locales with LOC_)

    Notes:

  3. The Localizer class exposes a hook called usePrefixer that will prefix/format the string based on the prefix/formatter passed to the constructor
  4. There are use cases where you might want to use more advanced prefixes, in these cases the constructor accepts a function as the prefix, that will be called on every locale.

    Usage:

    Params:

    locale: The locale key (the inputted string if used from the hook)

    value: The locale value in the current language (false if used from the hook )

    lang: The current locale language that the function is being executed on (undefined if used from the hook)
    1. const localizer = new Wooboo.Modifiers.Localizer(locales, (locale, value, lang) => {
    2. return `LOC_${locale}`
    3. })