MCPcopy
hub / github.com/formatjs/formatjs / IntlMessageFormat

Class IntlMessageFormat

packages/intl-messageformat/core.ts:104–299  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

102}
103
104export class IntlMessageFormat {
105 private readonly ast: MessageFormatElement[]
106 private readonly locales: string | string[]
107 private readonly resolvedLocale?: Intl.Locale
108 private readonly formatters: Formatters
109 private readonly formats: Formats
110 private readonly message: string | undefined
111 private readonly formatterCache: FormatterCache = {
112 number: {},
113 dateTime: {},
114 pluralRules: {},
115 }
116 constructor(
117 message: string | MessageFormatElement[],
118 locales: string | string[] = IntlMessageFormat.defaultLocale,
119 overrideFormats?: Partial<Formats>,
120 opts?: Options
121 ) {
122 // Defined first because it's used to build the format pattern.
123 this.locales = locales
124 this.resolvedLocale = IntlMessageFormat.resolveLocale(locales)
125
126 if (typeof message === 'string') {
127 this.message = message
128 if (!IntlMessageFormat.__parse) {
129 throw new TypeError(
130 'IntlMessageFormat.__parse must be set to process `message` of type `string`'
131 )
132 }
133 const {...parseOpts} = opts || {}
134 // Parse string messages into an AST.
135 this.ast = IntlMessageFormat.__parse(message, {
136 ...parseOpts,
137 locale: this.resolvedLocale,
138 })
139 } else {
140 this.ast = message
141 }
142
143 if (!Array.isArray(this.ast)) {
144 throw new TypeError('A message must be provided as a String or AST.')
145 }
146
147 // Creates a new object with the specified `formats` merged with the default
148 // formats.
149 this.formats = mergeConfigs(IntlMessageFormat.formats, overrideFormats)
150
151 this.formatters =
152 (opts && opts.formatters) || createDefaultFormatters(this.formatterCache)
153 }
154
155 format = <T = void>(
156 values?: Record<string, PrimitiveType | T | FormatXMLElementFn<T>>
157 ): string | T | (string | T)[] => {
158 const parts = this.formatToParts(values)
159 // Hot path for straight simple msg translations
160 if (parts.length === 1) {
161 return parts[0].value

Callers

nothing calls this directly

Calls 4

formatToPartsFunction · 0.70
formatToPartsMethod · 0.65
supportedLocalesOfMethod · 0.65
toStringMethod · 0.45

Tested by

no test coverage detected