Skip to content

Commit

Permalink
feat: 🎸 add onClickRefresh & onClickDismiss & dismissUpdate
Browse files Browse the repository at this point in the history
export functions: onClickRefresh & onClickDismiss & dismissUpdate &
closeNotification
  • Loading branch information
GreatAuk committed Feb 2, 2023
1 parent e68ab00 commit 0b285b9
Show file tree
Hide file tree
Showing 10 changed files with 91 additions and 50 deletions.
1 change: 1 addition & 0 deletions example/vue-vite/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/// <reference types="vite/client" />
/// <reference types="@plugin-web-update-notification/core" />
16 changes: 9 additions & 7 deletions example/vue-vite/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

const app = createApp(App)
const app = createApp(App);
window.pluginWebUpdateNotice_.onClickDismiss = (version) => {
alert(version);
};
app.use(router);

app.use(router)

app.mount('#app')
app.mount("#app");
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { dirname } from 'path'
import { fileURLToPath } from 'url'
import { execSync } from 'child_process'
import './shim.d.ts'

import { name as pkgName_ } from '../package.json'
import type { VersionType } from './type'
Expand Down
53 changes: 42 additions & 11 deletions packages/core/src/injectScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { CUSTOM_UPDATE_EVENT_NAME, DIRECTORY_NAME, JSON_FILE_NAME, LOCAL_STORAGE
import presetLocaleData from './locale'

let hasShowSystemUpdateNotice = false
/** latest version from server */
let latestVersion = ''
let currentLocale = ''

Expand Down Expand Up @@ -45,13 +46,16 @@ function checkUpdate(options: Options) {
if (window.pluginWebUpdateNotice_version !== versionFromServer) {
// dispatch custom event
document.body.dispatchEvent(new CustomEvent(CUSTOM_UPDATE_EVENT_NAME, {
detail: options,
detail: {
options,
version: versionFromServer,
},
bubbles: true,
}))

const dismiss = localStorage.getItem(`${LOCAL_STORAGE_PREFIX}${versionFromServer}`) === 'true'
if (!hasShowSystemUpdateNotice && !hiddenDefaultNotification && !dismiss)
handleShowNotification(options)
showNotification(options)
}
})
.catch((err) => {
Expand All @@ -60,7 +64,7 @@ function checkUpdate(options: Options) {
}

// check system update after page loaded
checkSystemUpdate()
setTimeout(checkSystemUpdate)

// polling check system update
setInterval(checkSystemUpdate, checkInterval || 10 * 60 * 1000)
Expand Down Expand Up @@ -89,14 +93,38 @@ function checkUpdate(options: Options) {
true,
)
}

window.pluginWebUpdateNotice_ = {
checkUpdate,
dismissUpdate,
closeNotification,
setLocale: (locale: string) => {
window.pluginWebUpdateNotice_.locale = locale
currentLocale = locale
},
}

/**
* close notification, remove the notification from the DOM
*/
function closeNotification() {
hasShowSystemUpdateNotice = false
document.querySelector(`.${NOTIFICATION_ANCHOR_CLASS_NAME} .plugin-web-update-notice`)?.remove()
}

/**
* dismiss current update and hide notification
*/
function dismissUpdate() {
try {
closeNotification()
localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${latestVersion}`, 'true')
}
catch (err) {
console.error(err)
}
}

/**
* Bind the refresh button click event to refresh the page, and bind the dismiss button click event to
* hide the notification and dismiss the system update.
Expand All @@ -105,20 +133,23 @@ function bindBtnEvent() {
// bind refresh button click event, click to refresh page
const refreshBtn = document.querySelector(`.${NOTIFICATION_REFRESH_BTN_CLASS_NAME}`)
refreshBtn?.addEventListener('click', () => {
const { onClickRefresh } = window.pluginWebUpdateNotice_
if (onClickRefresh) {
onClickRefresh(latestVersion)
return
}
window.location.reload()
})

// bind dismiss button click event, click to hide notification
const dismissBtn = document.querySelector(`.${NOTIFICATION_DISMISS_BTN_CLASS_NAME}`)
dismissBtn?.addEventListener('click', () => {
try {
hasShowSystemUpdateNotice = false
document.querySelector(`.${NOTIFICATION_ANCHOR_CLASS_NAME} .plugin-web-update-notice`)?.remove()
localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${latestVersion}`, 'true')
}
catch (err) {
console.error(err)
const { onClickDismiss } = window.pluginWebUpdateNotice_
if (onClickDismiss) {
onClickDismiss(latestVersion)
return
}
dismissUpdate()
})
}

Expand All @@ -137,7 +168,7 @@ function getLocaleText(locale: string, key: keyof LocaleData[string], localeData
/**
* show update notification
*/
function handleShowNotification(options: Options) {
function showNotification(options: Options) {
try {
hasShowSystemUpdateNotice = true

Expand Down
13 changes: 12 additions & 1 deletion packages/core/src/shim.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,19 @@ declare global {
locale?: string;
/** set language */
setLocale: (locale: string) => void
/** check update */
checkUpdate: (options: Options) => void
/** dismiss current update and close notification, same behavior as dismiss the button */
dismissUpdate: () => void
/** close notification */
closeNotification: () => void
/**
* refresh button click event, if you set it, it will cover the default event (location.reload())
*/
onClickRefresh?: (version: string) => void
/**
* dismiss button click event, if you set it, it will cover the default event (dismissUpdate())
*/
onClickDismiss?: (version: string) => void
}
}
}
10 changes: 9 additions & 1 deletion packages/core/src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export interface Options {
checkInterval?: number
/** whether to output version in console */
logVersion?: boolean
/**
* @deprecated
*/
customNotificationHTML?: string
/** notificationProps have higher priority than locale */
notificationProps?: NotificationProps
Expand All @@ -18,14 +21,19 @@ export interface Options {
* */
locale?: string
localeData?: LocaleData
/**
* Whether to hide the default notification, default is false
*
* If you set it to true, you need to custom behavior by yourself
*/
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 /
* !!! Don't forget / at the end of the path
*/
injectFileBase?: string
}
Expand Down
13 changes: 8 additions & 5 deletions packages/umi-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { resolve } from 'path'
import { copyFileSync, readFileSync, writeFileSync } from 'fs'
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import type { IApi } from 'umi'
import type { Options } from '@plugin-web-update-notification/core'
import { DIRECTORY_NAME, INJECT_SCRIPT_FILE_NAME, INJECT_STYLE_FILE_NAME, JSON_FILE_NAME, NOTIFICATION_ANCHOR_CLASS_NAME, generateJSONFileContent, getVersion } from '@plugin-web-update-notification/core'
Expand Down Expand Up @@ -72,7 +72,7 @@ export default (api: IApi) => {
]
})

api.addHTMLScripts(() => {
api.addHTMLHeadScripts(() => {
const scriptList = []
if (logVersion) {
scriptList.push({
Expand All @@ -82,10 +82,15 @@ export default (api: IApi) => {
scriptList.push({
content: injectVersionTpl(version),
})
scriptList.push({
src: `${injectFileBase}${INJECT_SCRIPT_FILE_NAME}.js`,
})
return scriptList
})

api.onBuildComplete(() => {
mkdirSync(`dist/${DIRECTORY_NAME}`)

// copy file from @plugin-web-update-notification/core/dist/??.css */ to dist/
const cssFilePath = resolve('node_modules', pkgName, 'dist', `${INJECT_STYLE_FILE_NAME}.css`)
copyFileSync(cssFilePath, `dist/${DIRECTORY_NAME}/${INJECT_STYLE_FILE_NAME}.css`)
Expand All @@ -99,9 +104,7 @@ export default (api: IApi) => {

api.modifyHTML(($) => {
if (!hiddenDefaultNotification)
$('body').append(`<div class="${NOTIFICATION_ANCHOR_CLASS_NAME}"></div></body>`)

$('body').append(`<script defer src="${injectFileBase}${INJECT_SCRIPT_FILE_NAME}.js"></script>`)
$('body').append(`<div class="${NOTIFICATION_ANCHOR_CLASS_NAME}"></div>`)
return $
})
}
9 changes: 4 additions & 5 deletions packages/vite-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,12 @@ function injectPluginHtml(html: string, version: string, options: Options) {
let res = html

res = res.replace(
'</head>',
`${cssLinkHtml}
'<head>',
`<head>
${cssLinkHtml}
<script defer src="${injectFileBase}${DIRECTORY_NAME}/${INJECT_SCRIPT_FILE_NAME}.js"></script>
${logHtml}
${versionScript}
</head>
`,
${versionScript}`,
)

if (!hiddenDefaultNotification) {
Expand Down
9 changes: 4 additions & 5 deletions packages/webpack-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,12 @@ function injectPluginHtml(html: string, version: string, options: Options) {
let res = html

res = res.replace(
'</head>',
`${cssLinkHtml}
'<head>',
`<head>
${cssLinkHtml}
<script defer src="${injectFileBase}${DIRECTORY_NAME}/${INJECT_SCRIPT_FILE_NAME}.js"></script>
${logHtml}
${versionScript}
</head>
`,
${versionScript}`,
)

if (!hiddenDefaultNotification) {
Expand Down
16 changes: 1 addition & 15 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 0b285b9

Please sign in to comment.