Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

experimental: Hooking for @intlify/devtools #433

Merged
merged 1 commit into from
Apr 7, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,12 @@
"*.json": "jsonc",
".fixpackrc": "json"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"typescript.tsdk": "node_modules/typescript/lib"
}
1 change: 1 addition & 0 deletions packages/core-base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"jsdelivr": "dist/core-base.global.js",
"types": "dist/core-base.d.ts",
"dependencies": {
"@intlify/devtools-if": "9.0.0",
"@intlify/message-compiler": "9.0.0",
"@intlify/message-resolver": "9.0.0",
"@intlify/runtime": "9.0.0",
Expand Down
27 changes: 26 additions & 1 deletion packages/core-base/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
isObject
} from '@intlify/shared'
import { VueDevToolsTimelineEvents } from '@intlify/vue-devtools'
import { initI18nDevTools } from './devtools'
import { CoreWarnCodes, getWarnMessage } from './warnings'

import type { Path } from '@intlify/message-resolver'
Expand All @@ -25,6 +26,7 @@ import type {
} from '@intlify/runtime'
import type { VueDevToolsEmitter } from '@intlify/vue-devtools'
import type {
MetaInfo,
NumberFormat,
DateTimeFormat,
DateTimeFormats as DateTimeFormatsType,
Expand Down Expand Up @@ -94,9 +96,11 @@ export interface CoreInternalOptions {
__datetimeFormatters?: Map<string, Intl.DateTimeFormat>
__numberFormatters?: Map<string, Intl.NumberFormat>
__v_emitter?: VueDevToolsEmitter // eslint-disable-line camelcase
__meta?: MetaInfo
}

export interface CoreCommonContext<Message = string> {
cid: number
locale: Locale
fallbackLocale: FallbackLocale
missing: CoreMissingHandler<Message> | null
Expand Down Expand Up @@ -143,8 +147,15 @@ export interface CoreInternalContext {
__numberFormatters: Map<string, Intl.NumberFormat>
__localeChainCache?: Map<Locale, Locale[]>
__v_emitter?: VueDevToolsEmitter // eslint-disable-line camelcase
__meta?: MetaInfo
}

/**
* Intlify core-base version
* @internal
*/
export const VERSION = __VERSION__

export const NOT_REOSLVED = -1

export const MISSING_RESOLVE_VALUE = ''
Expand Down Expand Up @@ -173,6 +184,9 @@ export function registerMessageCompiler<Message>(
_compiler = compiler
}

// ID for CoreContext
let _cid = 0

export function createCoreContext<
Message = string,
Options extends CoreOptions<Message> = object,
Expand Down Expand Up @@ -252,8 +266,12 @@ export function createCoreContext<
const __numberFormatters = isObject(internalOptions.__numberFormatters)
? internalOptions.__numberFormatters
: new Map<string, Intl.NumberFormat>()
const { __meta } = internalOptions

_cid++

const context = {
cid: _cid,
locale,
fallbackLocale,
messages,
Expand All @@ -273,7 +291,8 @@ export function createCoreContext<
messageCompiler,
onWarn,
__datetimeFormatters,
__numberFormatters
__numberFormatters,
__meta
} as CoreContext<
Options['messages'],
Options['datetimeFormats'],
Expand All @@ -289,6 +308,12 @@ export function createCoreContext<
: undefined
}

// NOTE: experimental !!
// TODO: should be checked with feature flags
if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
initI18nDevTools(context, VERSION, __meta)
}

return context
}

Expand Down
40 changes: 40 additions & 0 deletions packages/core-base/src/devtools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { IntlifyDevToolsHooks } from '@intlify/devtools-if'

import type {
IntlifyDevToolsEmitter,
IntlifyDevToolsHookPayloads
} from '@intlify/devtools-if'

let devtools: IntlifyDevToolsEmitter | null = null

export function setDevToolsHook(hook: IntlifyDevToolsEmitter | null): void {
devtools = hook
}

export function getDevToolsHook(): IntlifyDevToolsEmitter | null {
return devtools
}

export function initI18nDevTools(
i18n: unknown,
version: string,
meta?: Record<string, unknown>
): void {
// TODO: queue if devtools is undefined
devtools &&
devtools.emit(IntlifyDevToolsHooks.I18N_INIT, {
timestamp: Date.now(),
i18n,
version,
meta
})
}

export const translateDevTools = /* #__PURE__*/ createDevToolsHook(
IntlifyDevToolsHooks.FUNCTION_TRANSLATE
)

function createDevToolsHook(hook: IntlifyDevToolsHooks) {
return (payloads: IntlifyDevToolsHookPayloads[IntlifyDevToolsHooks]) =>
devtools && devtools.emit(hook, payloads)
}
1 change: 1 addition & 0 deletions packages/core-base/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from './number'
export { getWarnMessage, CoreWarnCodes } from './warnings'
export { CoreError, CoreErrorCodes, createCoreError } from './errors'
export * from './types'
export * from './devtools'
30 changes: 28 additions & 2 deletions packages/core-base/src/translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
} from './context'
import { CoreWarnCodes, getWarnMessage } from './warnings'
import { CoreErrorCodes, createCoreError } from './errors'
import { translateDevTools } from './devtools'
import { VueDevToolsTimelineEvents } from '@intlify/vue-devtools'

import type { Path, PathValue } from '@intlify/message-resolver'
Expand All @@ -39,6 +40,7 @@ import type {
MessageType,
MessageContext
} from '@intlify/runtime'
import type { AdditionalPayloads } from '@intlify/devtools-if'
import type {
LocaleMessages,
LocaleMessageValue,
Expand All @@ -47,7 +49,7 @@ import type {
} from './context'

const NOOP_MESSAGE_FUNCTION = () => ''
const isMessageFunction = <T>(val: unknown): val is MessageFunction<T> =>
export const isMessageFunction = <T>(val: unknown): val is MessageFunction<T> =>
isFunction(val)

/**
Expand Down Expand Up @@ -379,7 +381,31 @@ export function translate<Messages, Message = string>(
)

// if use post translation option, proceed it with handler
return postTranslation ? postTranslation(messaged) : messaged
const ret = postTranslation ? postTranslation(messaged) : messaged

// NOTE: experimental !!
// TODO: should be checked with feature flags
if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
const payloads = {
timestamp: Date.now(),
key:
!isMessageFunction(format) && isString(key)
? key
: (format as MessageFunctionInternal).key!,
locale: targetLocale!,
format:
!isMessageFunction(format) && isString(format)
? format
: (format as MessageFunctionInternal).source!,
message: ret as string
}
if (((context as unknown) as CoreInternalContext).__meta) {
;(payloads as AdditionalPayloads).meta = ((context as unknown) as CoreInternalContext).__meta
}
translateDevTools(payloads)
}

return ret
}

function escapeParams(options: TranslateOptions) {
Expand Down
3 changes: 3 additions & 0 deletions packages/core-base/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,6 @@ export type FormattedNumberPart = {
value: string
}
export type NumberFormatToPartsResult = { [index: number]: FormattedNumberPart }
export interface MetaInfo {
[field: string]: unknown
}
104 changes: 104 additions & 0 deletions packages/core-base/test/devtools.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { createCoreContext, translate } from '../src/index'
import { createEmitter } from '@intlify/shared'
import { compileToFunction } from '../src/compile'
import { IntlifyDevToolsHooks } from '@intlify/devtools-if'
import { setDevToolsHook, getDevToolsHook } from '../src/devtools'

import type {
IntlifyDevToolsEmitterHooks,
IntlifyDevToolsEmitter
} from '@intlify/devtools-if'

let devtools: IntlifyDevToolsEmitter | null = null
beforeEach(() => {
const emitter = createEmitter<IntlifyDevToolsEmitterHooks>()
setDevToolsHook(emitter)
devtools = getDevToolsHook()
})

afterEach(() => {
setDevToolsHook(null)
devtools = null
})

test('initI18nDevTools', () => {
const fn = jest.fn()
devtools!.on(IntlifyDevToolsHooks.I18N_INIT, fn)

const meta = { framework: 'Vue' }
const ctx = createCoreContext({
locale: 'en',
messages: {
en: {
hello: 'Hello!'
}
},
__meta: meta
})

expect(fn).toBeCalled()
expect(fn.mock.calls[0][0]).toMatchObject({
i18n: ctx,
version: '9.0.0',
meta
})
})

describe('translateDevTools', () => {
test('basic', () => {
const fn = jest.fn()
devtools!.on(IntlifyDevToolsHooks.FUNCTION_TRANSLATE, fn)

const meta = { __INTLIFY_META__: 'xxx', framework: 'Vue' }
const HELLO = 'Hello {name}!'
const ctx = createCoreContext({
locale: 'en',
messageCompiler: compileToFunction,
messages: {
en: {
hello: HELLO
}
},
__meta: meta
})

const translated = translate(ctx, 'hello', { name: 'DIO' })
expect(fn.mock.calls[0][0]).toMatchObject({
key: 'hello',
message: translated,
format: HELLO,
locale: 'en',
meta
})
})

test('fallback', () => {
const fn = jest.fn()
devtools!.on(IntlifyDevToolsHooks.FUNCTION_TRANSLATE, fn)

const HELLO = 'やあ {name}!'
const ctx = createCoreContext({
locale: 'en',
fallbackLocale: ['ja'],
messageCompiler: compileToFunction,
messages: {
ja: {
hello: HELLO
}
}
})

const translated = translate(
ctx,
'hello',
{ name: 'ディオ' },
{ locale: 'ja' }
)
expect(fn.mock.calls[0][0]).toMatchObject({
key: 'hello',
message: translated,
format: HELLO,
locale: 'ja'
})
})
})
20 changes: 20 additions & 0 deletions packages/devtools-if/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2021 kazuya kawaguchi

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13 changes: 13 additions & 0 deletions packages/devtools-if/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# @intlify/devtools-if

The [`@intlify/devtools`](https://github.com/intlify/devtools) interface(I/F:if) for intlify projects

## :warning: NOTE:

This is experimental.

Don’t use in production yet.

## :copyright: License

[MIT](http://opensource.org/licenses/MIT)
7 changes: 7 additions & 0 deletions packages/devtools-if/api-extractor.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../api-extractor.json",
"mainEntryPointFilePath": "./dist/packages/<unscopedPackageName>/src/index.d.ts",
"dtsRollup": {
"publicTrimmedFilePath": "./dist/<unscopedPackageName>.d.ts"
}
}
7 changes: 7 additions & 0 deletions packages/devtools-if/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict'

if (process.env.NODE_ENV === 'production') {
module.exports = require('./dist/devtools-if.cjs.prod.js')
} else {
module.exports = require('./dist/devtools-if.cjs.js')
}