vue#VNodeArrayChildren TypeScript Examples
The following examples show how to use
vue#VNodeArrayChildren.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: formatRenderer.ts From vue-i18n-next with MIT License | 5 votes |
export function renderFormatter<
Props extends FormattableProps<Value, Format>,
Value,
Format extends FormatOverrideOptions,
Arg extends FormatOptions,
Return extends FormatPartReturn
>(
props: Props,
context: SetupContext,
slotKeys: string[],
partFormatter: (...args: unknown[]) => string | Return[]
): RenderFunction {
const { slots, attrs } = context
return (): VNodeChild => {
const options = { part: true } as Arg
let overrides = {} as FormatOverrideOptions
if (props.locale) {
options.locale = props.locale
}
if (isString(props.format)) {
options.key = props.format
} else if (isObject(props.format)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isString((props.format as any).key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.key = (props.format as any).key
}
// Filter out number format options only
overrides = Object.keys(props.format).reduce((options, prop) => {
return slotKeys.includes(prop)
? assign({}, options, { [prop]: (props.format as any)[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
: options
}, {})
}
const parts = partFormatter(...[props.value, options, overrides])
let children = [options.key] as VNodeArrayChildren
if (isArray(parts)) {
children = parts.map((part, index) => {
const slot = slots[part.type]
const node = slot
? slot({ [part.type]: part.value, index, parts })
: [part.value]
if (isVNode(node)) {
node[0].key = `${part.type}-${index}`
}
return node
})
} else if (isString(parts)) {
children = [parts]
}
const assignedAttrs = assign({}, attrs)
const tag =
isString(props.tag) || isObject(props.tag)
? props.tag
: getFragmentableTag('span')
return h(tag, assignedAttrs, children)
}
}
Example #2
Source File: composer.ts From vue-i18n-next with MIT License | 4 votes |
/**
* Create composer interface factory
*
* @internal
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function createComposer(options: any = {}, VueI18nLegacy?: any): any {
type Message = VueMessageType
const { __root } = options as ComposerInternalOptions<
LocaleMessages<LocaleMessage<Message>>,
DateTimeFormatsType,
NumberFormatsType
>
const _isGlobal = __root === undefined
let _inheritLocale = isBoolean(options.inheritLocale)
? options.inheritLocale
: true
const _locale = ref<Locale>(
// prettier-ignore
__root && _inheritLocale
? __root.locale.value
: isString(options.locale)
? options.locale
: DEFAULT_LOCALE
)
const _fallbackLocale = ref<FallbackLocale>(
// prettier-ignore
__root && _inheritLocale
? __root.fallbackLocale.value
: isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: _locale.value
)
const _messages = ref<LocaleMessages<LocaleMessage<Message>>>(
getLocaleMessages<LocaleMessages<LocaleMessage<Message>>>(
_locale.value as Locale,
options
)
)
// prettier-ignore
const _datetimeFormats = !__LITE__
? ref<DateTimeFormatsType>(
isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [_locale.value]: {} }
)
: /* #__PURE__*/ ref<DateTimeFormatsType>({})
// prettier-ignore
const _numberFormats = !__LITE__
? ref<NumberFormatsType>(
isPlainObject(options.numberFormats)
? options.numberFormats
: { [_locale.value]: {} }
)
: /* #__PURE__*/ ref<NumberFormatsType>({})
// warning suppress options
// prettier-ignore
let _missingWarn = __root
? __root.missingWarn
: isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true
// prettier-ignore
let _fallbackWarn = __root
? __root.fallbackWarn
: isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true
// prettier-ignore
let _fallbackRoot = __root
? __root.fallbackRoot
: isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true
// configure fall back to root
let _fallbackFormat = !!options.fallbackFormat
// runtime missing
let _missing = isFunction(options.missing) ? options.missing : null
let _runtimeMissing = isFunction(options.missing)
? defineCoreMissingHandler(options.missing)
: null
// postTranslation handler
let _postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null
// prettier-ignore
let _warnHtmlMessage = __root
? __root.warnHtmlMessage
: isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true
let _escapeParameter = !!options.escapeParameter
// custom linked modifiers
// prettier-ignore
const _modifiers = __root
? __root.modifiers
: isPlainObject(options.modifiers)
? options.modifiers
: {} as LinkedModifiers<Message>
// pluralRules
let _pluralRules = options.pluralRules || (__root && __root.pluralRules)
// for bridge
let __legacy: any
if (__BRIDGE__) {
if (!isLegacyVueI18n(VueI18nLegacy)) {
createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N)
}
const legacyOptions = {
locale: _locale.value,
fallbackLocale: _fallbackLocale.value,
messages: _messages.value,
dateTimeFormats: _datetimeFormats.value,
numberFormats: _numberFormats.value,
modifiers: _modifiers,
missing: _missing,
fallbackRoot: _fallbackRoot,
postTranslation: _postTranslation,
pluralizationRules: _pluralRules,
escapeParameterHtml: _escapeParameter,
sync: _inheritLocale,
silentFallbackWarn: isBoolean(_fallbackWarn)
? !_fallbackWarn
: _fallbackWarn,
silentTranslationWarn: isBoolean(_missingWarn)
? !_missingWarn
: _missingWarn,
formatFallbackMessages: isBoolean(_fallbackFormat)
? !_fallbackFormat
: _fallbackFormat,
warnHtmlInMessage: isBoolean(_warnHtmlMessage)
? _warnHtmlMessage
? 'warn'
: 'off'
: 'off',
__VUE_I18N_BRIDGE__
}
__legacy = new VueI18nLegacy(legacyOptions)
}
// runtime context
// eslint-disable-next-line prefer-const
let _context: CoreContext
function getCoreContext(): CoreContext {
_isGlobal && setFallbackContext(null)
const ctxOptions = {
version: VERSION,
locale: _locale.value,
fallbackLocale: _fallbackLocale.value,
messages: _messages.value,
modifiers: _modifiers,
pluralRules: _pluralRules,
missing: _runtimeMissing === null ? undefined : _runtimeMissing,
missingWarn: _missingWarn,
fallbackWarn: _fallbackWarn,
fallbackFormat: _fallbackFormat,
unresolving: true,
postTranslation: _postTranslation === null ? undefined : _postTranslation,
warnHtmlMessage: _warnHtmlMessage,
escapeParameter: _escapeParameter,
messageResolver: options.messageResolver,
__meta: { framework: 'vue' }
}
if (!__LITE__) {
;(ctxOptions as any).datetimeFormats = _datetimeFormats.value
;(ctxOptions as any).numberFormats = _numberFormats.value
;(ctxOptions as any).__datetimeFormatters = isPlainObject(_context)
? (_context as unknown as CoreInternalContext).__datetimeFormatters
: undefined
;(ctxOptions as any).__numberFormatters = isPlainObject(_context)
? (_context as unknown as CoreInternalContext).__numberFormatters
: undefined
}
if (!__BRIDGE__ && __DEV__) {
;(ctxOptions as any).__v_emitter = isPlainObject(_context)
? (_context as unknown as CoreInternalContext).__v_emitter
: undefined
}
const ctx = createCoreContext(ctxOptions as any)
_isGlobal && setFallbackContext(ctx)
return ctx
}
_context = getCoreContext()
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value)
// track reactivity
function trackReactivityValues() {
return !__LITE__
? [
_locale.value,
_fallbackLocale.value,
_messages.value,
_datetimeFormats.value,
_numberFormats.value
]
: [_locale.value, _fallbackLocale.value, _messages.value]
}
// locale
const locale = computed({
get: () => _locale.value,
set: val => {
_locale.value = val
if (__BRIDGE__) {
if (__legacy && !_isGlobal) {
__legacy.locale = val
}
}
_context.locale = _locale.value
}
})
// fallbackLocale
const fallbackLocale = computed({
get: () => _fallbackLocale.value,
set: val => {
_fallbackLocale.value = val
if (__BRIDGE__) {
if (__legacy && !_isGlobal) {
__legacy.fallbackLocale = val
}
}
_context.fallbackLocale = _fallbackLocale.value
updateFallbackLocale(_context, _locale.value, val)
}
})
// messages
const messages = computed<LocaleMessages<LocaleMessage<Message>, Message>>(
() => _messages.value as any
)
// datetimeFormats
const datetimeFormats = /* #__PURE__*/ computed<DateTimeFormatsType>(
() => _datetimeFormats.value
)
// numberFormats
const numberFormats = /* #__PURE__*/ computed<NumberFormatsType>(
() => _numberFormats.value
)
// getPostTranslationHandler
function getPostTranslationHandler(): PostTranslationHandler<Message> | null {
return isFunction(_postTranslation) ? _postTranslation : null
}
// setPostTranslationHandler
function setPostTranslationHandler(
handler: PostTranslationHandler | null
): void {
_postTranslation = handler
_context.postTranslation = handler
}
// getMissingHandler
function getMissingHandler(): MissingHandler | null {
return _missing
}
// setMissingHandler
function setMissingHandler(handler: MissingHandler | null): void {
if (handler !== null) {
_runtimeMissing = defineCoreMissingHandler(handler)
}
_missing = handler
_context.missing = _runtimeMissing
}
function isResolvedTranslateMessage(
type: ComposerWarnType,
arg: any // eslint-disable-line @typescript-eslint/no-explicit-any
): boolean {
return type !== 'translate' || !arg.resolvedMessage
}
function wrapWithDeps<T, U = T>(
fn: (context: unknown) => unknown,
argumentParser: () => unknown[],
warnType: ComposerWarnType,
fallbackSuccess: (root: Composer<T> & ComposerInternal) => U,
fallbackFail: (key: unknown) => U,
successCondition: (val: unknown) => boolean
): U {
trackReactivityValues() // track reactive dependency
// NOTE: experimental !!
let ret: unknown
if (__DEV__ || __FEATURE_PROD_INTLIFY_DEVTOOLS__) {
try {
setAdditionalMeta(getMetaInfo())
if (!_isGlobal) {
_context.fallbackContext = __root
? (getFallbackContext() as any)
: undefined
}
ret = fn(_context)
} finally {
setAdditionalMeta(null)
if (!_isGlobal) {
_context.fallbackContext = undefined
}
}
} else {
ret = fn(_context)
}
if (isNumber(ret) && ret === NOT_REOSLVED) {
const [key, arg2] = argumentParser()
if (
__DEV__ &&
__root &&
isString(key) &&
isResolvedTranslateMessage(warnType, arg2)
) {
if (
_fallbackRoot &&
(isTranslateFallbackWarn(_fallbackWarn, key) ||
isTranslateMissingWarn(_missingWarn, key))
) {
warn(
getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
key,
type: warnType
})
)
}
// for vue-devtools timeline event
if (!__BRIDGE__ && __DEV__) {
const { __v_emitter: emitter } =
_context as unknown as CoreInternalContext
if (emitter && _fallbackRoot) {
emitter.emit(VueDevToolsTimelineEvents.FALBACK, {
type: warnType,
key,
to: 'global',
groupId: `${warnType}:${key}`
})
}
}
}
return __root && _fallbackRoot
? fallbackSuccess(__root as unknown as Composer<T> & ComposerInternal)
: fallbackFail(key)
} else if (successCondition(ret)) {
return ret as U
} else {
/* istanbul ignore next */
throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE)
}
}
// t
function t(...args: unknown[]): string {
return wrapWithDeps<string>(
context => Reflect.apply(translate, null, [context, ...args]) as string,
() => parseTranslateArgs(...args),
'translate',
root => Reflect.apply(root.t, root, [...args]),
key => key as string,
val => isString(val)
)
}
// rt
function rt(...args: unknown[]): string {
const [arg1, arg2, arg3] = args
if (arg3 && !isObject(arg3)) {
throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT)
}
return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})])
}
// d
function d(...args: unknown[]): string {
return wrapWithDeps<string>(
context => Reflect.apply(datetime, null, [context, ...args]) as string,
() => parseDateTimeArgs(...args),
'datetime format',
root => Reflect.apply(root.d, root, [...args]),
() => MISSING_RESOLVE_VALUE,
val => isString(val)
)
}
// n
function n(...args: unknown[]): string {
return wrapWithDeps<string>(
context => Reflect.apply(number, null, [context, ...args]) as string,
() => parseNumberArgs(...args),
'number format',
root => Reflect.apply(root.n, root, [...args]),
() => MISSING_RESOLVE_VALUE,
val => isString(val)
)
}
// for custom processor
function normalize(
values: MessageType<string | VNode>[]
): MessageType<VNode>[] {
return values.map(val => (isString(val) ? createTextNode(val) : val))
}
const interpolate = (val: unknown): MessageType<VNode> => val as VNode
const processor = {
normalize,
interpolate,
type: 'vnode'
} as MessageProcessor<VNode>
// transrateVNode, using for `i18n-t` component
function transrateVNode(...args: unknown[]): VNodeArrayChildren {
return wrapWithDeps<VNode, VNodeArrayChildren>(
context => {
let ret: unknown
const _context = context as CoreContext<
VNode,
LocaleMessages<LocaleMessage<Message>>
>
try {
_context.processor = processor
ret = Reflect.apply(translate, null, [_context, ...args])
} finally {
_context.processor = null
}
return ret
},
() => parseTranslateArgs(...args),
'translate',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => (root as any)[TransrateVNodeSymbol](...args),
key => [createTextNode(key as string)],
val => isArray(val)
)
}
// numberParts, using for `i18n-n` component
function numberParts(...args: unknown[]): string | Intl.NumberFormatPart[] {
return wrapWithDeps<string | Intl.NumberFormatPart[]>(
context => Reflect.apply(number, null, [context, ...args]),
() => parseNumberArgs(...args),
'number format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => (root as any)[NumberPartsSymbol](...args),
() => [],
val => isString(val) || isArray(val)
)
}
// datetimeParts, using for `i18n-d` component
function datetimeParts(
...args: unknown[]
): string | Intl.DateTimeFormatPart[] {
return wrapWithDeps<string | Intl.DateTimeFormatPart[]>(
context => Reflect.apply(datetime, null, [context, ...args]),
() => parseDateTimeArgs(...args),
'datetime format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => (root as any)[DatetimePartsSymbol](...args),
() => [],
val => isString(val) || isArray(val)
)
}
function setPluralRules(rules: PluralizationRules): void {
_pluralRules = rules
_context.pluralRules = _pluralRules
}
// te
function te(key: Path, locale?: Locale): boolean {
const targetLocale = isString(locale) ? locale : _locale.value
const message = getLocaleMessage(targetLocale)
return _context.messageResolver(message, key) !== null
}
function resolveMessages(key: Path): LocaleMessageValue<Message> | null {
let messages: LocaleMessageValue<Message> | null = null
const locales = fallbackWithLocaleChain(
_context,
_fallbackLocale.value,
_locale.value
)
for (let i = 0; i < locales.length; i++) {
const targetLocaleMessages = _messages.value[locales[i]] || {}
const messageValue = _context.messageResolver(targetLocaleMessages, key)
if (messageValue != null) {
messages = messageValue as LocaleMessageValue<Message>
break
}
}
return messages
}
// tm
function tm(key: Path): LocaleMessageValue<Message> | {} {
const messages = resolveMessages(key)
// prettier-ignore
return messages != null
? messages
: __root
? __root.tm(key) as LocaleMessageValue<Message> || {}
: {}
}
// getLocaleMessage
function getLocaleMessage(locale: Locale): LocaleMessage<Message> {
return (_messages.value[locale] || {}) as LocaleMessage<Message>
}
// setLocaleMessage
function setLocaleMessage(locale: Locale, message: LocaleMessage<Message>) {
_messages.value[locale] = message
if (__BRIDGE__) {
__legacy && __legacy.setLocaleMessage(locale, message)
}
_context.messages = _messages.value as typeof _context.messages
}
// mergeLocaleMessage
function mergeLocaleMessage(
locale: Locale,
message: LocaleMessageDictionary<Message>
): void {
_messages.value[locale] = _messages.value[locale] || {}
if (__BRIDGE__) {
__legacy && __legacy.mergeLocaleMessage(locale, message)
}
deepCopy(message, _messages.value[locale])
_context.messages = _messages.value as typeof _context.messages
}
// getDateTimeFormat
function getDateTimeFormat(locale: Locale): DateTimeFormat {
return _datetimeFormats.value[locale] || {}
}
// setDateTimeFormat
function setDateTimeFormat(locale: Locale, format: DateTimeFormat): void {
_datetimeFormats.value[locale] = format
if (__BRIDGE__) {
__legacy && __legacy.setDateTimeFormat(locale, format)
}
_context.datetimeFormats = _datetimeFormats.value
clearDateTimeFormat(_context, locale, format)
}
// mergeDateTimeFormat
function mergeDateTimeFormat(locale: Locale, format: DateTimeFormat): void {
_datetimeFormats.value[locale] = assign(
_datetimeFormats.value[locale] || {},
format
)
if (__BRIDGE__) {
__legacy && __legacy.mergeDateTimeFormat(locale, format)
}
_context.datetimeFormats = _datetimeFormats.value
clearDateTimeFormat(_context, locale, format)
}
// getNumberFormat
function getNumberFormat(locale: Locale): NumberFormat {
return _numberFormats.value[locale] || {}
}
// setNumberFormat
function setNumberFormat(locale: Locale, format: NumberFormat): void {
_numberFormats.value[locale] = format
if (__BRIDGE__) {
__legacy && __legacy.setNumberFormat(locale, format)
}
_context.numberFormats = _numberFormats.value
clearNumberFormat(_context, locale, format)
}
// mergeNumberFormat
function mergeNumberFormat(locale: Locale, format: NumberFormat): void {
_numberFormats.value[locale] = assign(
_numberFormats.value[locale] || {},
format
)
if (__BRIDGE__) {
__legacy && __legacy.mergeNumberFormat(locale, format)
}
_context.numberFormats = _numberFormats.value
clearNumberFormat(_context, locale, format)
}
// for debug
composerID++
// watch root locale & fallbackLocale
if (__root && inBrowser) {
watch(__root.locale, (val: Locale) => {
if (_inheritLocale) {
_locale.value = val
if (__BRIDGE__) {
if (__legacy && !_isGlobal) {
__legacy.locale = val
}
}
_context.locale = val
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value)
}
})
watch(__root.fallbackLocale, (val: FallbackLocale) => {
if (_inheritLocale) {
_fallbackLocale.value = val
if (__BRIDGE__) {
if (__legacy && !_isGlobal) {
__legacy.fallbackLocale = val
}
}
_context.fallbackLocale = val
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value)
}
})
}
// define basic composition API!
const composer = {
id: composerID,
locale,
fallbackLocale,
get inheritLocale(): boolean {
return _inheritLocale
},
set inheritLocale(val: boolean) {
_inheritLocale = val
if (__BRIDGE__) {
if (__legacy) {
__legacy._sync = val
}
}
if (val && __root) {
_locale.value = __root.locale.value as Locale
_fallbackLocale.value = __root.fallbackLocale.value
if (__BRIDGE__) {
if (__legacy) {
__legacy.locale = __root.locale.value as Locale
__legacy.fallbackLocale = __root.fallbackLocale.value
}
}
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value)
}
},
get availableLocales(): Locale[] {
return Object.keys(_messages.value).sort()
},
messages,
get modifiers(): LinkedModifiers<Message> {
return _modifiers
},
get pluralRules(): PluralizationRules {
return _pluralRules || {}
},
get isGlobal(): boolean {
return _isGlobal
},
get missingWarn(): boolean | RegExp {
return _missingWarn
},
set missingWarn(val: boolean | RegExp) {
_missingWarn = val
_context.missingWarn = _missingWarn
},
get fallbackWarn(): boolean | RegExp {
return _fallbackWarn
},
set fallbackWarn(val: boolean | RegExp) {
_fallbackWarn = val
_context.fallbackWarn = _fallbackWarn
},
get fallbackRoot(): boolean {
return _fallbackRoot
},
set fallbackRoot(val: boolean) {
_fallbackRoot = val
},
get fallbackFormat(): boolean {
return _fallbackFormat
},
set fallbackFormat(val: boolean) {
_fallbackFormat = val
_context.fallbackFormat = _fallbackFormat
},
get warnHtmlMessage(): boolean {
return _warnHtmlMessage
},
set warnHtmlMessage(val: boolean) {
_warnHtmlMessage = val
_context.warnHtmlMessage = val
},
get escapeParameter(): boolean {
return _escapeParameter
},
set escapeParameter(val: boolean) {
_escapeParameter = val
_context.escapeParameter = val
},
t,
getLocaleMessage,
setLocaleMessage,
mergeLocaleMessage,
getPostTranslationHandler,
setPostTranslationHandler,
getMissingHandler,
setMissingHandler,
[SetPluralRulesSymbol]: setPluralRules
}
if (!__LITE__) {
;(composer as any).datetimeFormats = datetimeFormats
;(composer as any).numberFormats = numberFormats
;(composer as any).rt = rt
;(composer as any).te = te
;(composer as any).tm = tm
;(composer as any).d = d
;(composer as any).n = n
;(composer as any).getDateTimeFormat = getDateTimeFormat
;(composer as any).setDateTimeFormat = setDateTimeFormat
;(composer as any).mergeDateTimeFormat = mergeDateTimeFormat
;(composer as any).getNumberFormat = getNumberFormat
;(composer as any).setNumberFormat = setNumberFormat
;(composer as any).mergeNumberFormat = mergeNumberFormat
;(composer as any)[InejctWithOption] = options.__injectWithOption
;(composer as any)[TransrateVNodeSymbol] = transrateVNode
;(composer as any)[DatetimePartsSymbol] = datetimeParts
;(composer as any)[NumberPartsSymbol] = numberParts
}
if (__BRIDGE__) {
;(composer as any)[LegacyInstanceSymbol] = __legacy
}
// for vue-devtools timeline event
if (!__BRIDGE__ && __DEV__) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(composer as any)[EnableEmitter] = (emitter: VueDevToolsEmitter): void => {
;(_context as unknown as CoreInternalContext).__v_emitter = emitter
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(composer as any)[DisableEmitter] = (): void => {
;(_context as unknown as CoreInternalContext).__v_emitter = undefined
}
}
return composer
}