Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions src/composer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,30 +218,37 @@ function getLocaleMessages(
return ret
}

function addPreCompileMessages(
export function addPreCompileMessages(
messages: LocaleMessages,
functions: MessageFunctions
): void {
const keys = Object.keys(functions)
keys.forEach(key => {
const compiled = functions[key]
const { l, k } = JSON.parse(key)
const targetLocaleMessage = (messages[l] = messages[l] || {})
if (!messages[l]) {
messages[l] = {}
}
const targetLocaleMessage = messages[l]
const paths = parsePath(k)
if (paths != null) {
const len = paths.length
let last = targetLocaleMessage as any // eslint-disable-line @typescript-eslint/no-explicit-any
let i = 0
while (i < len) {
const path = paths[i]
const val = last[path]
if (val != null) {
last[path] = {}
if (i === len - 1) {
last[path] = compiled
break
} else {
let val = last[path]
if (!val) {
last[path] = val = {}
}
last = val
i++
}
last = val
i++
}
last = compiled
}
})
}
Expand Down
29 changes: 28 additions & 1 deletion test/composer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ jest.mock('../src/utils', () => ({
}))
import { warn } from '../src/utils'

import { createComposer, MissingHandler } from '../src/composer'
import {
createComposer,
MissingHandler,
addPreCompileMessages
} from '../src/composer'
import { generateFormatCacheKey } from '../src/utils'
import { watch } from 'vue'

describe('locale', () => {
Expand Down Expand Up @@ -716,4 +721,26 @@ describe('__i18n', () => {
})
})

test('addPreCompileMessages', () => {
const messages = {}
const functions = Object.create(null)
const msg1 = () => {}
const msg2 = () => {}
functions[generateFormatCacheKey('en', 'hello', 'hello,world')] = msg1
functions[
generateFormatCacheKey('ja', 'foo.bar.hello', 'こんにちは、世界')
] = msg2
addPreCompileMessages(messages, functions)
expect(messages['en']).toMatchObject({
hello: msg1
})
expect(messages['ja']).toMatchObject({
foo: {
bar: {
hello: msg2
}
}
})
})

/* eslint-enable @typescript-eslint/no-empty-function */