Skip to content

Commit

Permalink
feat: Internationalization
Browse files Browse the repository at this point in the history
  • Loading branch information
GreatAuk committed Dec 10, 2022
1 parent b0ecee0 commit d9dbf7e
Show file tree
Hide file tree
Showing 27 changed files with 201 additions and 95 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export default defineConfig({
})

// other file to listener custom update event
document.body.addEventListener('system_update_plugin_web_update_notification', (options) => {
document.body.addEventListener('plugin_web_update_notice', (options) => {
console.log(options)
alert('System update!')
})
Expand Down
2 changes: 1 addition & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export default defineConfig({
})

// 在其他文件中监听自定义更新事件
document.body.addEventListener('system_update_plugin_web_update_notification', (options) => {
document.body.addEventListener('plugin_web_update_notice', (options) => {
console.log(options)
alert('System update!')
})
Expand Down
4 changes: 3 additions & 1 deletion example/svelte-vite/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ import { svelte } from '@sveltejs/vite-plugin-svelte'
import { webUpdateNotice } from '@plugin-web-update-notification/vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [svelte(), webUpdateNotice()],
plugins: [svelte(), webUpdateNotice({
locale: 'zh_TW',
})],
})
1 change: 1 addition & 0 deletions example/vue-cli/vue.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module.exports = defineConfig({
new WebUpdateNotificationPlugin({
logVersion: true,
injectFileBase: './',
locale: 'en_US',
}),
],
},
Expand Down
6 changes: 3 additions & 3 deletions example/vue-vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
"vue-router": "^4.0.15"
},
"devDependencies": {
"@playwright/test": "^1.24.0-alpha-1655882451000",
"@playwright/test": "^1.28.1",
"@plugin-web-update-notification/core": "workspace:*",
"@plugin-web-update-notification/vite": "workspace:*",
"@rushstack/eslint-patch": "^1.1.0",
"@types/jsdom": "^16.2.14",
"@types/node": "^16.11.36",
Expand All @@ -32,8 +34,6 @@
"prettier": "^2.5.1",
"start-server-and-test": "^1.14.0",
"typescript": "~4.7.2",
"@plugin-web-update-notification/vite": "workspace:*",
"@plugin-web-update-notification/core": "workspace:*",
"vitest": "^0.13.0",
"vue-tsc": "^0.35.2"
}
Expand Down
12 changes: 9 additions & 3 deletions example/vue-vite/tests/e2e/plugin.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { test, expect } from "@playwright/test";
import {
DIRECTORY_NAME,
NOTIFICATION_ANCHOR_CLASS_NAME,
INJECT_STYLE_FILE_NAME,
INJECT_SCRIPT_FILE_NAME,
Expand All @@ -16,11 +17,13 @@ test.describe("test @plugin-web-update-notification/vite", () => {
});
test("script and css file inject success", async ({ page }) => {
const scriptTag = page.locator(
`script[src="${INJECT_SCRIPT_FILE_NAME}.js"]`
`script[src="${DIRECTORY_NAME}/${INJECT_SCRIPT_FILE_NAME}.js"]`
);
expect(await scriptTag.count()).toEqual(1);

const cssTag = page.locator(`link[href="${INJECT_STYLE_FILE_NAME}.css"]`);
const cssTag = page.locator(
`link[href="${DIRECTORY_NAME}/${INJECT_STYLE_FILE_NAME}.css"]`
);
expect(await cssTag.count()).toEqual(1);
});

Expand All @@ -30,7 +33,9 @@ test.describe("test @plugin-web-update-notification/vite", () => {
});

test(`should has a ${JSON_FILE_NAME}.json file`, async ({ request }) => {
const jsonFileRes = await request.get(`${JSON_FILE_NAME}.json`);
const jsonFileRes = await request.get(
`${DIRECTORY_NAME}/${JSON_FILE_NAME}.json`
);
expect(jsonFileRes.ok()).toBeTruthy();

const res = await jsonFileRes.json();
Expand Down Expand Up @@ -63,6 +68,7 @@ test.describe("test @plugin-web-update-notification/vite", () => {
const notificationContent = page.locator(
`[data-cy="notification-content"]`
);
expect(await notificationContent.count()).toEqual(1);
expect(await notificationContent.innerHTML()).toContain("system update");
expect(await notificationContent.innerHTML()).toContain("refresh");
});
Expand Down
2 changes: 1 addition & 1 deletion example/vue-vite/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default defineConfig({
plugins: [
vue(),
webUpdateNotice({
versionType: "pkg_version",
versionType: "git_commit_hash",
logVersion: true,
checkInterval: 0.5 * 60 * 1000,
notificationProps: {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export default defineConfig({
})

// other file to listener custom update event
document.body.addEventListener('system_update_plugin_web_update_notification', (options) => {
document.body.addEventListener('plugin_web_update_notice', (options) => {
console.log(options)
alert('System update!')
})
Expand Down
2 changes: 1 addition & 1 deletion packages/core/README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export default defineConfig({
})

// other file to listener custom update event
document.body.addEventListener('system_update_plugin_web_update_notification', (options) => {
document.body.addEventListener('plugin_web_update_notice', (options) => {
console.log(options)
alert('System update!')
})
Expand Down
2 changes: 1 addition & 1 deletion packages/core/public/webUpdateNoticeInjectStyle.css
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
.plugin-web-update-notice-content-title {
font-weight: 500;
margin-bottom: 4px;
font-size: 15px;
font-size: 14px;
line-height: 24px;
}

Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/constant.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
export const DIRECTORY_NAME = 'pluginWebUpdateNotice'
export const JSON_FILE_NAME = 'web_version_by_plugin'
export const INJECT_STYLE_FILE_NAME = 'webUpdateNoticeInjectStyle'
/** .global is iife suffix */
export const INJECT_SCRIPT_FILE_NAME = 'webUpdateNoticeInjectScript.global'
export const CUSTOM_UPDATE_EVENT_NAME = 'system_update_plugin_web_update_notification'
export const CUSTOM_UPDATE_EVENT_NAME = 'plugin_web_update_notice'
export const NOTIFICATION_ANCHOR_CLASS_NAME = 'plugin-web-update-notice-anchor'

/** refresh button class name */
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export function getVersion(versionType: VersionType = 'git_commit_hash') {
[plugin-web-update-notice] get version throw a error, we will use the packaging timestamp instead.
======================================================`)
console.error(err)
return `${Date.now()}`
return getTimestamp()
}
}

Expand Down
92 changes: 60 additions & 32 deletions packages/core/src/injectScript.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { Options } from './type'
import { CUSTOM_UPDATE_EVENT_NAME, JSON_FILE_NAME, LOCAL_STORAGE_PREFIX, NOTIFICATION_ANCHOR_CLASS_NAME, NOTIFICATION_DISMISS_BTN_CLASS_NAME, NOTIFICATION_REFRESH_BTN_CLASS_NAME } from './constant'
import type { LocaleData, Options } from './type'
import { CUSTOM_UPDATE_EVENT_NAME, DIRECTORY_NAME, JSON_FILE_NAME, LOCAL_STORAGE_PREFIX, NOTIFICATION_ANCHOR_CLASS_NAME, NOTIFICATION_DISMISS_BTN_CLASS_NAME, NOTIFICATION_REFRESH_BTN_CLASS_NAME } from './constant'
import presetLocaleData from './locale'

let hasShowSystemUpdateNotice = false
let latestVersion = ''
let currentLocale = ''

/**
* limit function
Expand All @@ -27,11 +29,11 @@ function limit(fn: Function, delay: number) {
* It checks whether the system has been updated and if so, it shows a notification.
* @param {Options} options - Options
*/
function webUpdateCheck_checkAndNotice(options: Options) {
function checkUpdate(options: Options) {
const { injectFileBase = '', checkInterval, hiddenDefaultNotification } = options
const checkSystemUpdate = () => {
window
.fetch(`${injectFileBase}${JSON_FILE_NAME}.json?t=${performance.now()}`)
.fetch(`${injectFileBase}${DIRECTORY_NAME}/${JSON_FILE_NAME}.json?t=${performance.now()}`)
.then((response) => {
if (!response.ok)
throw new Error(`Failed to fetch ${JSON_FILE_NAME}.json`)
Expand All @@ -40,7 +42,7 @@ function webUpdateCheck_checkAndNotice(options: Options) {
})
.then(({ version: versionFromServer }: { version: string }) => {
latestVersion = versionFromServer
if (window.web_version_by_plugin !== versionFromServer) {
if (window.pluginWebUpdateNotice_version !== versionFromServer) {
// dispatch custom event
document.body.dispatchEvent(new CustomEvent(CUSTOM_UPDATE_EVENT_NAME, {
detail: options,
Expand All @@ -53,9 +55,7 @@ function webUpdateCheck_checkAndNotice(options: Options) {
}
})
.catch((err) => {
console.error(err)
// eslint-disable-next-line no-console
console.log('Failed to check system update')
console.error('[pluginWebUpdateNotice] Failed to check system update', err)
})
}

Expand Down Expand Up @@ -89,7 +89,13 @@ function webUpdateCheck_checkAndNotice(options: Options) {
true,
)
}
window.webUpdateCheck_checkAndNotice = webUpdateCheck_checkAndNotice
window.pluginWebUpdateNotice_ = {
checkUpdate,
setLocale: (locale: string) => {
window.pluginWebUpdateNotice_.locale = locale
currentLocale = locale
},
}

/**
* Bind the refresh button click event to refresh the page, and bind the dismiss button click event to
Expand All @@ -116,28 +122,46 @@ function bindBtnEvent() {
})
}

/**
* It returns the value of the key in the localeData object, or the value of the key in the
* presetLocaleData object, or the value of the key in the presetLocaleData.zh_CN object
* @param {string} locale - The locale to be used, such as zh_CN, en_US, etc.
* @param key - The key of the text to be obtained in the locale data.
* @param {LocaleData} localeData - The locale data object that you passed in.
* @returns The value of the key in the localeData object.
*/
function getLocaleText(locale: string, key: keyof LocaleData[string], localeData: LocaleData) {
return localeData[locale]?.[key] ?? presetLocaleData[locale]?.[key] ?? presetLocaleData.zh_CN[key]
}

/**
* show update notification
*/
function handleShowNotification(options: Options) {
hasShowSystemUpdateNotice = true

const { notificationProps, customNotificationHTML, hiddenDismissButton } = options
try {
hasShowSystemUpdateNotice = true

const { notificationProps, customNotificationHTML, hiddenDismissButton, locale = 'zh_CN', localeData: localeData_ } = options
const localeData = Object.assign({}, presetLocaleData, localeData_)
if (!currentLocale) {
currentLocale = locale
window.pluginWebUpdateNotice_.locale = locale
}

const notification = document.createElement('div')
let notificationInnerHTML = ''
const notification = document.createElement('div')
let notificationInnerHTML = ''

if (customNotificationHTML) {
notificationInnerHTML = customNotificationHTML
}
else {
const title = notificationProps?.title ?? '📢  系统升级通知'
const description = notificationProps?.description ?? '检测到当前系统版本已更新,请刷新页面后使用。'
const buttonText = notificationProps?.buttonText ?? '刷新'
const dismissButtonText = notificationProps?.dismissButtonText ?? '忽略'
const dismissButtonHtml = hiddenDismissButton ? '' : `<a class="plugin-web-update-notice-btn plugin-web-update-notice-dismiss-btn">${dismissButtonText}</a>`
notification.classList.add('plugin-web-update-notice')
notificationInnerHTML = `
if (customNotificationHTML) {
notificationInnerHTML = customNotificationHTML
}
else {
const title = notificationProps?.title ?? getLocaleText(currentLocale, 'title', localeData)
const description = notificationProps?.description ?? getLocaleText(currentLocale, 'description', localeData)
const buttonText = notificationProps?.buttonText ?? getLocaleText(currentLocale, 'buttonText', localeData)
const dismissButtonText = notificationProps?.dismissButtonText ?? getLocaleText(currentLocale, 'dismissButtonText', localeData)
const dismissButtonHtml = hiddenDismissButton ? '' : `<a class="plugin-web-update-notice-btn plugin-web-update-notice-dismiss-btn">${dismissButtonText}</a>`
notification.classList.add('plugin-web-update-notice')
notificationInnerHTML = `
<div class="plugin-web-update-notice-content" data-cy="notification-content">
<div class="plugin-web-update-notice-content-title">
${title}
Expand All @@ -152,17 +176,21 @@ function handleShowNotification(options: Options) {
</a>
</div>
</div>`
}
}

notification.innerHTML = notificationInnerHTML
document
.querySelector(`.${NOTIFICATION_ANCHOR_CLASS_NAME}`)!
.appendChild(notification)
notification.innerHTML = notificationInnerHTML
document
.querySelector(`.${NOTIFICATION_ANCHOR_CLASS_NAME}`)!
.appendChild(notification)

bindBtnEvent()
bindBtnEvent()
}
catch (err) {
console.error('[pluginWebUpdateNotice] Failed to show notification', err)
}
}

// meaningless export, in order to let tsup bundle these functions
export {
webUpdateCheck_checkAndNotice,
checkUpdate,
}
24 changes: 24 additions & 0 deletions packages/core/src/locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { LocaleData } from './type'

const localeData: LocaleData = {
zh_CN: {
title: '发现新版本',
description: '网页更新啦!请刷新页面后使用。',
buttonText: '刷新',
dismissButtonText: '忽略',
},
zh_TW: {
title: '發現新版本',
description: '網頁更新啦!請刷新頁面後使用。',
buttonText: '刷新',
dismissButtonText: '忽略',
},
en_US: {
title: 'Discover new version',
description: 'A new version is available! Please refresh the page.',
buttonText: 'Refresh',
dismissButtonText: 'Dismiss',
},
}

export default localeData
22 changes: 15 additions & 7 deletions packages/core/src/shim.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
interface Window {
/** git commit hash or packaging time */
web_version_by_plugin: string
/** 是否已经显示了系统升级 notification */
hasShowSystemUpdateNotice_plugin?: boolean
webUpdateCheck_checkAndNotice: (any) => void
}
import type { Options } from './type'

declare global {
interface Window {
/** version number */
pluginWebUpdateNotice_version: string
pluginWebUpdateNotice_: {
locale?: string;
/** set language */
setLocale: (locale: string) => void
/** check update */
checkUpdate: (options: Options) => void
}
}
}
15 changes: 12 additions & 3 deletions packages/core/src/type.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
export interface Options {
/**
* ```text
* support 'git_commit_hash' | 'pkg_version' | 'build_timestamp'
*
* default is 'git_commit_hash'
* ```
* */
versionType?: VersionType
/** polling interval(ms), default 10*60*1000 */
/** polling interval(ms), default 10 * 60 * 1000 */
checkInterval?: number
/** whether to output version in console */
logVersion?: boolean
customNotificationHTML?: string
/** notificationProps have higher priority than locale */
notificationProps?: NotificationProps
/** locale default is zh_CN
*
* preset: zh_CN | zh_TW | en_US
* */
locale?: string
localeData?: LocaleData
hiddenDefaultNotification?: boolean
hiddenDismissButton?: boolean
/**
* Base public path for inject file, Valid values include:
* * Absolute URL pathname, e.g. /foo/
* * Full URL, e.g. https://foo.com/
* * Empty string(default) or ./
* !!! Don't forget last /
*/
injectFileBase?: string
}
Expand All @@ -33,3 +40,5 @@ export interface NotificationProps {
/** dismiss button text */
dismissButtonText?: string
}

export type LocaleData = Record<string, NotificationProps>
Loading

0 comments on commit d9dbf7e

Please sign in to comment.