From 4835eb66c7e0ce8bc239f6e04b121acd502ccca5 Mon Sep 17 00:00:00 2001 From: bootx Date: Tue, 2 Jul 2024 21:27:05 +0800 Subject: [PATCH] =?UTF-8?q?remove=20=E5=9B=BD=E9=99=85=E5=8C=96=E5=88=A0?= =?UTF-8?q?=E9=99=A4,=20=E4=BE=9D=E8=B5=96=E7=B2=BE=E7=AE=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/extensions.json | 1 - .vscode/settings.json | 9 -- apps/test-server/controller/FileController.ts | 16 +-- apps/test-server/controller/UserController.ts | 14 +- apps/test-server/index.ts | 56 ++++---- apps/test-server/routes.ts | 6 +- apps/test-server/service/FileService.ts | 48 +++---- apps/test-server/service/UserService.ts | 8 +- apps/test-server/utils.ts | 2 +- .../vite-config/src/config/application.ts | 4 - package.json | 3 +- packages/hooks/build.config.ts | 4 +- packages/hooks/src/index.ts | 14 +- packages/hooks/src/onMountedOrActivated.ts | 20 +-- packages/hooks/src/useAttrs.ts | 42 +++--- packages/hooks/src/useRefs.ts | 22 ++-- packages/hooks/src/useRequest/Fetch.ts | 90 ++++++------- packages/hooks/src/useRequest/index.ts | 24 ++-- .../useRequest/plugins/useAutoRunPlugin.ts | 32 ++--- .../src/useRequest/plugins/useCachePlugin.ts | 90 ++++++------- .../useRequest/plugins/useDebouncePlugin.ts | 54 ++++---- .../plugins/useLoadingDelayPlugin.ts | 30 ++--- .../useRequest/plugins/usePollingPlugin.ts | 50 +++---- .../plugins/useRefreshOnWindowFocusPlugin.ts | 36 +++--- .../src/useRequest/plugins/useRetryPlugin.ts | 42 +++--- .../useRequest/plugins/useThrottlePlugin.ts | 48 +++---- packages/hooks/src/useRequest/types.ts | 122 +++++++++--------- .../src/useRequest/useRequestImplement.ts | 30 ++--- packages/hooks/src/useRequest/utils/cache.ts | 40 +++--- .../src/useRequest/utils/cachePromise.ts | 20 +-- .../src/useRequest/utils/cacheSubscribe.ts | 20 +-- .../hooks/src/useRequest/utils/isBrowser.ts | 2 +- .../src/useRequest/utils/isDocumentVisible.ts | 6 +- .../hooks/src/useRequest/utils/isFunction.ts | 2 +- .../hooks/src/useRequest/utils/isOnline.ts | 6 +- packages/hooks/src/useRequest/utils/limit.ts | 14 +- .../src/useRequest/utils/subscribeFocus.ts | 30 ++--- .../useRequest/utils/subscribeReVisible.ts | 26 ++-- packages/hooks/src/useScrollTo.ts | 62 ++++----- packages/hooks/src/useWindowSizeFn.ts | 44 +++---- packages/types/build.config.ts | 4 +- packages/types/src/index.ts | 2 +- packages/types/src/utils.ts | 20 +-- pnpm-lock.yaml | 49 +------ src/api/common/FileUpload.ts | 5 +- src/api/sys/menu.ts | 5 +- src/api/sys/upload.ts | 5 +- src/components/Application/src/AppLogo.vue | 6 +- .../Application/src/AppProvider.vue | 7 +- .../Application/src/search/AppSearchModal.vue | 17 ++- .../Application/src/search/useMenuSearch.ts | 27 +++- src/components/Basic/src/BasicHelp.vue | 4 +- .../CodeEditor/src/codemirror/CodeMirror.vue | 16 ++- .../Container/src/ScrollContainer.vue | 7 +- .../Container/src/collapse/CollapseHeader.vue | 4 +- .../ContextMenu/src/ContextMenu.vue | 14 +- src/components/Cropper/src/Cropper.vue | 9 +- src/components/Cropper/src/CropperAvatar.vue | 26 +++- src/components/Cropper/src/CropperModal.vue | 51 +++++++- .../Description/src/Description.vue | 10 +- src/components/Description/src/typing.ts | 5 +- src/components/Drawer/src/BasicDrawer.vue | 13 +- .../Drawer/src/components/DrawerFooter.vue | 9 +- src/components/Drawer/src/useDrawer.ts | 19 ++- src/components/Dropdown/src/Dropdown.vue | 18 ++- src/components/EllipsisText/src/_utils.ts | 6 +- src/components/Icon/Icon.vue | 15 ++- src/components/Icon/src/SvgIcon.vue | 6 +- src/components/Loading/src/useLoading.ts | 4 +- src/components/Menu/src/BasicMenu.vue | 15 ++- src/components/Menu/src/useOpenKeys.ts | 7 +- src/components/Modal/src/BasicModal.vue | 28 +++- .../Modal/src/components/ModalFooter.vue | 8 +- .../Modal/src/components/ModalWrapper.vue | 16 ++- src/components/Modal/src/hooks/useModal.ts | 20 ++- src/components/Page/src/PageWrapper.vue | 25 +++- src/components/Preview/src/Functional.vue | 28 +++- src/components/Qrcode/src/drawCanvas.ts | 7 +- src/components/Qrcode/src/drawLogo.ts | 9 +- src/components/Scrollbar/src/Scrollbar.vue | 11 +- src/components/Scrollbar/src/bar.ts | 34 +++-- src/components/SimpleMenu/src/SimpleMenu.vue | 15 ++- .../SimpleMenu/src/components/Menu.vue | 11 +- .../SimpleMenu/src/components/SubMenuItem.vue | 62 ++++++--- .../StrengthMeter/src/StrengthMeter.vue | 9 +- src/components/Time/src/Time.vue | 3 +- src/components/Transition/index.ts | 10 +- .../Transition/src/CreateTransition.tsx | 6 +- src/components/Tree/src/BasicTree.vue | 58 +++++++-- src/components/Tree/src/types/tree.ts | 23 +++- .../VirtualScroll/src/VirtualScroll.vue | 13 +- src/components/VxeTable/src/VxeBasicTable.tsx | 7 +- .../VxeTable/src/components/AAutoComplete.tsx | 8 +- .../VxeTable/src/components/AButton.tsx | 21 ++- .../VxeTable/src/components/AButtonGroup.tsx | 28 +++- .../VxeTable/src/components/ACascader.tsx | 16 ++- .../VxeTable/src/components/ADatePicker.tsx | 7 +- .../VxeTable/src/components/AInput.tsx | 8 +- .../VxeTable/src/components/AInputNumber.tsx | 8 +- .../VxeTable/src/components/AMonthPicker.tsx | 7 +- .../VxeTable/src/components/ARangePicker.tsx | 11 +- .../VxeTable/src/components/ARate.tsx | 8 +- .../VxeTable/src/components/ASelect.tsx | 46 +++++-- .../VxeTable/src/components/ATimePicker.tsx | 7 +- .../VxeTable/src/components/ATreeSelect.tsx | 8 +- .../VxeTable/src/components/AWeekPicker.tsx | 7 +- .../VxeTable/src/components/AYearPicker.tsx | 7 +- .../VxeTable/src/components/common.tsx | 47 +++++-- .../VxeTable/src/components/index.tsx | 7 +- src/components/VxeTable/src/methods.ts | 8 +- src/directives/clickOutside.ts | 12 +- src/directives/ripple/index.ts | 17 ++- src/hooks/component/useFormItem.ts | 18 ++- src/hooks/core/useContext.ts | 11 +- src/hooks/setting/useHeaderSetting.ts | 27 +++- src/hooks/setting/useMenuSetting.ts | 15 ++- src/hooks/setting/useRootSetting.ts | 9 +- src/hooks/web/useContentHeight.ts | 12 +- src/hooks/web/useECharts.ts | 5 +- src/hooks/web/useI18n.ts | 59 --------- src/hooks/web/usePage.ts | 5 +- src/hooks/web/usePagination.ts | 5 +- src/hooks/web/usePermission.ts | 4 +- src/hooks/web/useWatermark.ts | 6 +- src/layouts/default/content/index.vue | 6 +- src/layouts/default/feature/index.vue | 5 +- src/layouts/default/header/MultipleHeader.vue | 21 ++- .../header/components/notify/NoticeList.vue | 10 +- .../default/header/components/notify/data.ts | 3 +- src/layouts/default/header/index.vue | 27 +++- src/layouts/default/menu/index.vue | 22 +++- src/layouts/default/menu/useLayoutMenu.ts | 8 +- .../setting/components/InputNumberItem.vue | 7 +- .../setting/components/SettingFooter.vue | 2 +- src/layouts/default/setting/handler.ts | 3 +- src/layouts/default/sider/LayoutSider.vue | 19 ++- src/layouts/default/sider/MixSider.vue | 34 +++-- src/layouts/default/sider/useLayoutSider.ts | 10 +- .../default/tabs/components/FoldButton.vue | 4 +- .../default/tabs/components/TabContent.vue | 13 +- src/layouts/default/tabs/useMultipleTabs.ts | 9 +- src/layouts/default/tabs/useTabDropdown.ts | 17 ++- src/layouts/default/trigger/HeaderTrigger.vue | 4 +- src/layouts/iframe/index.vue | 6 +- src/locales/lang/zh_CN.ts | 5 +- src/locales/setupI18n.ts | 44 ------- src/logics/mitt/routeChange.ts | 5 +- src/logics/websocket/UserGlobalWebSocker.ts | 7 +- src/router/helper/routeHelper.ts | 19 ++- src/router/routes/basic.ts | 1 - src/router/routes/index.ts | 3 +- src/router/routes/modules/about.ts | 5 +- src/router/routes/modules/dashboard.ts | 1 - src/router/types.ts | 5 +- src/settings/designSetting.ts | 1 - src/store/action/userAction.ts | 2 +- src/store/modules/app.ts | 8 +- src/store/modules/multipleTab.ts | 4 +- src/store/modules/tableSetting.ts | 4 +- src/utils/color.ts | 5 +- src/utils/domUtils.ts | 12 +- src/utils/env.ts | 7 +- src/utils/file/download.ts | 10 +- src/utils/helper/treeHelper.ts | 29 ++++- src/utils/helper/tsxHelper.ts | 2 +- src/utils/http/axios/Axios.ts | 18 ++- src/utils/http/axios/axiosTransform.ts | 12 +- src/utils/http/axios/checkStatus.ts | 6 +- src/utils/http/axios/helper.ts | 5 +- src/utils/http/axios/index.ts | 15 ++- src/utils/index.ts | 5 +- src/utils/lib/echarts.ts | 10 +- src/utils/mitt.ts | 9 +- src/utils/props.ts | 52 ++++++-- src/utils/types.ts | 8 +- .../analysis/components/SiteAnalysis.vue | 7 +- .../analysis/components/VisitAnalysis.vue | 8 +- src/views/sys/exception/Exception.vue | 40 +++--- src/views/sys/iframe/index.vue | 7 +- src/views/sys/login/ForgetPasswordForm.vue | 14 +- src/views/sys/login/Login.vue | 4 +- src/views/sys/login/LoginForm.vue | 29 ++++- src/views/sys/login/MobileForm.vue | 22 ++-- src/views/sys/login/QrCodeForm.vue | 14 +- src/views/sys/login/RegisterForm.vue | 47 ++++--- src/views/sys/login/useLogin.ts | 30 ++--- types/global.d.ts | 13 +- uno.config.ts | 2 +- 188 files changed, 2086 insertions(+), 1161 deletions(-) delete mode 100644 src/hooks/web/useI18n.ts delete mode 100644 src/locales/setupI18n.ts diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 12dc9f2f7..9d1677d76 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -5,7 +5,6 @@ "stylelint.vscode-stylelint", "esbenp.prettier-vscode", "mrmlnc.vscode-less", - "lokalise.i18n-ally", "antfu.iconify", "antfu.unocss", "mikestead.dotenv", diff --git a/.vscode/settings.json b/.vscode/settings.json index 82b16ee1a..1ef0a20c5 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -93,15 +93,6 @@ }, "editor.defaultFormatter": "esbenp.prettier-vscode" }, - "i18n-ally.localesPaths": ["src/locales/lang"], - "i18n-ally.keystyle": "nested", - "i18n-ally.sortKeys": true, - "i18n-ally.namespace": true, - "i18n-ally.pathMatcher": "{locale}/{namespaces}.{ext}", - "i18n-ally.enabledParsers": ["json", "ts", "js"], - "i18n-ally.sourceLanguage": "en", - "i18n-ally.displayLanguage": "zh-CN", - "i18n-ally.enabledFrameworks": ["vue", "react"], "cSpell.words": [ "antd", "antv", diff --git a/apps/test-server/controller/FileController.ts b/apps/test-server/controller/FileController.ts index cf6d90d5b..35e19acb1 100644 --- a/apps/test-server/controller/FileController.ts +++ b/apps/test-server/controller/FileController.ts @@ -1,18 +1,18 @@ -import FileService from '../service/FileService'; +import FileService from '../service/FileService' class FileController { - private service: FileService = new FileService(); + private service: FileService = new FileService() upload = async (ctx) => { - const files = ctx.request.files.file; - console.log(files); + const files = ctx.request.files.file + console.log(files) if (files.length === undefined) { - this.service.upload(ctx, files, false); + this.service.upload(ctx, files, false) } else { - this.service.upload(ctx, files, true); + this.service.upload(ctx, files, true) } - }; + } } -export default new FileController(); +export default new FileController() diff --git a/apps/test-server/controller/UserController.ts b/apps/test-server/controller/UserController.ts index db815c2f2..b42af32a8 100644 --- a/apps/test-server/controller/UserController.ts +++ b/apps/test-server/controller/UserController.ts @@ -1,15 +1,15 @@ -import UserService from '../service/UserService'; +import UserService from '../service/UserService' class UserController { - private service: UserService = new UserService(); + private service: UserService = new UserService() login = async (ctx) => { - ctx.body = await this.service.login(); - }; + ctx.body = await this.service.login() + } getUserInfoById = async (ctx) => { - ctx.body = await this.service.getUserInfoById(); - }; + ctx.body = await this.service.getUserInfoById() + } } -export default new UserController(); +export default new UserController() diff --git a/apps/test-server/index.ts b/apps/test-server/index.ts index 6c92d7666..ab99faa1f 100644 --- a/apps/test-server/index.ts +++ b/apps/test-server/index.ts @@ -1,22 +1,22 @@ -import Koa from 'koa'; -import path from 'path'; -import Router from 'koa-router'; -import body from 'koa-body'; -import cors from 'koa2-cors'; -import koaStatic from 'koa-static'; -import websockify from 'koa-websocket'; -import route from 'koa-route'; +import Koa from 'koa' +import path from 'path' +import Router from 'koa-router' +import body from 'koa-body' +import cors from 'koa2-cors' +import koaStatic from 'koa-static' +import websockify from 'koa-websocket' +import route from 'koa-route' -import AppRoutes from './routes'; +import AppRoutes from './routes' -const PORT = 3300; +const PORT = 3300 -const app = websockify(new Koa()); +const app = websockify(new Koa()) app.ws.use(function (ctx, next) { - ctx.websocket.send('connection succeeded!'); - return next(ctx); -}); + ctx.websocket.send('connection succeeded!') + return next(ctx) +}) app.ws.use( route.all('/test', function (ctx) { @@ -29,20 +29,20 @@ app.ws.use( id: Math.ceil(Math.random() * 1000), time: new Date().getTime(), res: `${message}`, - }); - ctx.websocket.send(data); + }) + ctx.websocket.send(data) } - console.log(message); - }); + console.log(message) + }) }), -); +) -const router = new Router(); +const router = new Router() // router -AppRoutes.forEach((route) => router[route.method](route.path, route.action)); +AppRoutes.forEach((route) => router[route.method](route.path, route.action)) -app.use(cors()); +app.use(cors()) app.use( body({ encoding: 'gzip', @@ -53,11 +53,11 @@ app.use( maxFieldsSize: 20 * 1024 * 1024, }, }), -); -app.use(router.routes()); -app.use(router.allowedMethods()); -app.use(koaStatic(path.join(__dirname))); +) +app.use(router.routes()) +app.use(router.allowedMethods()) +app.use(koaStatic(path.join(__dirname))) app.listen(PORT, () => { - console.log(`Application started successfully: http://localhost:${PORT}`); -}); + console.log(`Application started successfully: http://localhost:${PORT}`) +}) diff --git a/apps/test-server/routes.ts b/apps/test-server/routes.ts index 7fe647598..a1f01d0b8 100644 --- a/apps/test-server/routes.ts +++ b/apps/test-server/routes.ts @@ -1,5 +1,5 @@ -import UserController from './controller/UserController'; -import FileController from './controller/FileController'; +import UserController from './controller/UserController' +import FileController from './controller/FileController' export default [ // user @@ -20,4 +20,4 @@ export default [ method: 'post', action: FileController.upload, }, -]; +] diff --git a/apps/test-server/service/FileService.ts b/apps/test-server/service/FileService.ts index 6ad491856..24d1479da 100644 --- a/apps/test-server/service/FileService.ts +++ b/apps/test-server/service/FileService.ts @@ -1,54 +1,54 @@ -import path from 'path'; -import fs from 'fs-extra'; +import path from 'path' +import fs from 'fs-extra' -const uploadUrl = 'http://localhost:3300/static/upload'; -const filePath = path.join(__dirname, '../static/upload/'); +const uploadUrl = 'http://localhost:3300/static/upload' +const filePath = path.join(__dirname, '../static/upload/') -fs.ensureDir(filePath); +fs.ensureDir(filePath) export default class FileService { async upload(ctx, files, isMultiple) { - let fileReader, fileResource, writeStream; + let fileReader, fileResource, writeStream const fileFunc = function (file) { - fileReader = fs.createReadStream(file.filepath); - fileResource = filePath + `/${file.originalFilename}`; - console.log(fileResource); + fileReader = fs.createReadStream(file.filepath) + fileResource = filePath + `/${file.originalFilename}` + console.log(fileResource) - writeStream = fs.createWriteStream(fileResource); - fileReader.pipe(writeStream); - }; + writeStream = fs.createWriteStream(fileResource) + fileReader.pipe(writeStream) + } const returnFunc = function (flag) { if (flag) { - let url = ''; + let url = '' for (let i = 0; i < files.length; i++) { - url += uploadUrl + `/${files[i].originalFilename},`; + url += uploadUrl + `/${files[i].originalFilename},` } - url = url.replace(/,$/gi, ''); + url = url.replace(/,$/gi, '') ctx.body = { url: url, code: 0, message: 'upload Success!', - }; + } } else { ctx.body = { url: uploadUrl + `/${files.originalFilename}`, code: 0, message: 'upload Success!', - }; + } } - }; - console.log(isMultiple, files.length); + } + console.log(isMultiple, files.length) if (isMultiple) { for (let i = 0; i < files.length; i++) { - const f1 = files[i]; - fileFunc(f1); + const f1 = files[i] + fileFunc(f1) } } else { - fileFunc(files); + fileFunc(files) } - fs.ensureDir(filePath); - returnFunc(isMultiple); + fs.ensureDir(filePath) + returnFunc(isMultiple) } } diff --git a/apps/test-server/service/UserService.ts b/apps/test-server/service/UserService.ts index 0c395e52e..bdb5d3802 100644 --- a/apps/test-server/service/UserService.ts +++ b/apps/test-server/service/UserService.ts @@ -1,4 +1,4 @@ -import { Result } from '../utils'; +import { Result } from '../utils' const fakeUserInfo = { userId: '1', @@ -13,13 +13,13 @@ const fakeUserInfo = { value: 'super', }, ], -}; +} export default class UserService { async login() { - return Result.success(fakeUserInfo); + return Result.success(fakeUserInfo) } async getUserInfoById() { - return Result.success(fakeUserInfo); + return Result.success(fakeUserInfo) } } diff --git a/apps/test-server/utils.ts b/apps/test-server/utils.ts index 7fd0b3fad..ba0c758b5 100644 --- a/apps/test-server/utils.ts +++ b/apps/test-server/utils.ts @@ -4,6 +4,6 @@ export class Result { code: 0, success: true, result: data, - }; + } } } diff --git a/internal/vite-config/src/config/application.ts b/internal/vite-config/src/config/application.ts index fe92a94b4..2ea6611e3 100644 --- a/internal/vite-config/src/config/application.ts +++ b/internal/vite-config/src/config/application.ts @@ -37,10 +37,6 @@ function defineApplicationConfig(defineOptions: DefineOptions = {}) { base: VITE_PUBLIC_PATH, resolve: { alias: [ - { - find: 'vue-i18n', - replacement: 'vue-i18n/dist/vue-i18n.cjs.js', - }, // @/xxxx => src/xxxx { find: /@\//, diff --git a/package.json b/package.json index 93f395f6e..500fe2966 100644 --- a/package.json +++ b/package.json @@ -93,13 +93,12 @@ "sortablejs": "^1.15.2", "unocss": "^0.59.4", "vue": "^3.4.25", - "vue-i18n": "^9.13.1", "vue-json-pretty": "^2.4.0", "vue-router": "^4.3.2", "vue-types": "^5.1.1", "vuedraggable": "^4.1.0", "vxe-table": "^4.7.31", - "xe-utils": "^3.5.25" + "xe-utils": "^3.5.28" }, "devDependencies": { "@commitlint/cli": "^19.3.0", diff --git a/packages/hooks/build.config.ts b/packages/hooks/build.config.ts index 20c8b54a1..aef3e10bd 100644 --- a/packages/hooks/build.config.ts +++ b/packages/hooks/build.config.ts @@ -1,4 +1,4 @@ -import { defineBuildConfig } from 'unbuild'; +import { defineBuildConfig } from 'unbuild' export default defineBuildConfig({ clean: true, @@ -7,4 +7,4 @@ export default defineBuildConfig({ rollup: { emitCJS: true, }, -}); +}) diff --git a/packages/hooks/src/index.ts b/packages/hooks/src/index.ts index 557a974d8..1e860cb9b 100644 --- a/packages/hooks/src/index.ts +++ b/packages/hooks/src/index.ts @@ -1,7 +1,7 @@ -export * from './onMountedOrActivated'; -export * from './useAttrs'; -export * from './useRefs'; -export * from './useRequest'; -export * from './useScrollTo'; -export * from './useWindowSizeFn'; -export { useTimeoutFn } from '@vueuse/core'; +export * from './onMountedOrActivated' +export * from './useAttrs' +export * from './useRefs' +export * from './useRequest' +export * from './useScrollTo' +export * from './useWindowSizeFn' +export { useTimeoutFn } from '@vueuse/core' diff --git a/packages/hooks/src/onMountedOrActivated.ts b/packages/hooks/src/onMountedOrActivated.ts index 53a3c5e57..8944c946d 100644 --- a/packages/hooks/src/onMountedOrActivated.ts +++ b/packages/hooks/src/onMountedOrActivated.ts @@ -1,25 +1,25 @@ -import { type AnyFunction } from '@vben/types'; -import { nextTick, onActivated, onMounted } from 'vue'; +import { type AnyFunction } from '@vben/types' +import { nextTick, onActivated, onMounted } from 'vue' /** * 在 OnMounted 或者 OnActivated 时触发 * @param hook 任何函数(包括异步函数) */ function onMountedOrActivated(hook: AnyFunction) { - let mounted: boolean; + let mounted: boolean onMounted(() => { - hook(); + hook() nextTick(() => { - mounted = true; - }); - }); + mounted = true + }) + }) onActivated(() => { if (mounted) { - hook(); + hook() } - }); + }) } -export { onMountedOrActivated }; +export { onMountedOrActivated } diff --git a/packages/hooks/src/useAttrs.ts b/packages/hooks/src/useAttrs.ts index df2118d88..b2e47dfe9 100644 --- a/packages/hooks/src/useAttrs.ts +++ b/packages/hooks/src/useAttrs.ts @@ -1,43 +1,43 @@ -import { type Recordable } from '@vben/types'; -import { getCurrentInstance, reactive, shallowRef, watchEffect } from 'vue'; +import { type Recordable } from '@vben/types' +import { getCurrentInstance, reactive, shallowRef, watchEffect } from 'vue' interface UseAttrsOptions { - excludeListeners?: boolean; - excludeKeys?: string[]; - excludeDefaultKeys?: boolean; + excludeListeners?: boolean + excludeKeys?: string[] + excludeDefaultKeys?: boolean } -const DEFAULT_EXCLUDE_KEYS = ['class', 'style']; -const LISTENER_PREFIX = /^on[A-Z]/; +const DEFAULT_EXCLUDE_KEYS = ['class', 'style'] +const LISTENER_PREFIX = /^on[A-Z]/ function entries(obj: Recordable): [string, T][] { - return Object.keys(obj).map((key: string) => [key, obj[key]]); + return Object.keys(obj).map((key: string) => [key, obj[key]]) } function useAttrs(options: UseAttrsOptions = {}): Recordable { - const instance = getCurrentInstance(); - if (!instance) return {}; + const instance = getCurrentInstance() + if (!instance) return {} - const { excludeListeners = false, excludeKeys = [], excludeDefaultKeys = true } = options; - const attrs = shallowRef({}); - const allExcludeKeys = excludeKeys.concat(excludeDefaultKeys ? DEFAULT_EXCLUDE_KEYS : []); + const { excludeListeners = false, excludeKeys = [], excludeDefaultKeys = true } = options + const attrs = shallowRef({}) + const allExcludeKeys = excludeKeys.concat(excludeDefaultKeys ? DEFAULT_EXCLUDE_KEYS : []) // Since attrs are not reactive, make it reactive instead of doing in `onUpdated` hook for better performance - instance.attrs = reactive(instance.attrs); + instance.attrs = reactive(instance.attrs) watchEffect(() => { const res = entries(instance.attrs).reduce((acm, [key, val]) => { if (!allExcludeKeys.includes(key) && !(excludeListeners && LISTENER_PREFIX.test(key))) { - acm[key] = val; + acm[key] = val } - return acm; - }, {} as Recordable); + return acm + }, {} as Recordable) - attrs.value = res; - }); + attrs.value = res + }) - return attrs; + return attrs } -export { useAttrs, type UseAttrsOptions }; +export { useAttrs, type UseAttrsOptions } diff --git a/packages/hooks/src/useRefs.ts b/packages/hooks/src/useRefs.ts index efbaabd27..a9442b4ae 100644 --- a/packages/hooks/src/useRefs.ts +++ b/packages/hooks/src/useRefs.ts @@ -1,24 +1,24 @@ -import type { ComponentPublicInstance, Ref } from 'vue'; -import { onBeforeUpdate, shallowRef } from 'vue'; +import type { ComponentPublicInstance, Ref } from 'vue' +import { onBeforeUpdate, shallowRef } from 'vue' function useRefs(): { - refs: Ref; - setRefs: (index: number) => (el: Element | ComponentPublicInstance | null) => void; + refs: Ref + setRefs: (index: number) => (el: Element | ComponentPublicInstance | null) => void } { - const refs = shallowRef([]) as Ref; + const refs = shallowRef([]) as Ref onBeforeUpdate(() => { - refs.value = []; - }); + refs.value = [] + }) const setRefs = (index: number) => (el: Element | ComponentPublicInstance | null) => { - refs.value[index] = el as T; - }; + refs.value[index] = el as T + } return { refs, setRefs, - }; + } } -export { useRefs }; +export { useRefs } diff --git a/packages/hooks/src/useRequest/Fetch.ts b/packages/hooks/src/useRequest/Fetch.ts index 5e5b40adc..884b7fdc6 100644 --- a/packages/hooks/src/useRequest/Fetch.ts +++ b/packages/hooks/src/useRequest/Fetch.ts @@ -1,20 +1,20 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ -import { reactive } from 'vue'; +import { reactive } from 'vue' -import type { FetchState, PluginReturn, Service, Subscribe, UseRequestOptions } from './types'; -import { isFunction } from './utils/isFunction'; +import type { FetchState, PluginReturn, Service, Subscribe, UseRequestOptions } from './types' +import { isFunction } from './utils/isFunction' export default class Fetch { - pluginImpls: PluginReturn[] = []; + pluginImpls: PluginReturn[] = [] - count: number = 0; + count: number = 0 state: FetchState = reactive({ loading: false, params: undefined, data: undefined, error: undefined, - }); + }) constructor( public serviceRef: Service, @@ -22,126 +22,126 @@ export default class Fetch { public subscribe: Subscribe, public initState: Partial> = {}, ) { - this.setState({ loading: !options.manual, ...initState }); + this.setState({ loading: !options.manual, ...initState }) } setState(s: Partial> = {}) { - Object.assign(this.state, s); - this.subscribe(); + Object.assign(this.state, s) + this.subscribe() } runPluginHandler(event: keyof PluginReturn, ...rest: any[]) { // @ts-ignore - const r = this.pluginImpls.map((i) => i[event]?.(...rest)).filter(Boolean); - return Object.assign({}, ...r); + const r = this.pluginImpls.map((i) => i[event]?.(...rest)).filter(Boolean) + return Object.assign({}, ...r) } async runAsync(...params: TParams): Promise { - this.count += 1; - const currentCount = this.count; + this.count += 1 + const currentCount = this.count const { stopNow = false, returnNow = false, ...state - } = this.runPluginHandler('onBefore', params); + } = this.runPluginHandler('onBefore', params) // stop request if (stopNow) { - return new Promise(() => {}); + return new Promise(() => {}) } this.setState({ loading: true, params, ...state, - }); + }) // return now if (returnNow) { - return Promise.resolve(state.data); + return Promise.resolve(state.data) } - this.options.onBefore?.(params); + this.options.onBefore?.(params) try { // replace service - let { servicePromise } = this.runPluginHandler('onRequest', this.serviceRef, params); + let { servicePromise } = this.runPluginHandler('onRequest', this.serviceRef, params) if (!servicePromise) { - servicePromise = this.serviceRef(...params); + servicePromise = this.serviceRef(...params) } - const res = await servicePromise; + const res = await servicePromise if (currentCount !== this.count) { // prevent run.then when request is canceled - return new Promise(() => {}); + return new Promise(() => {}) } // const formattedResult = this.options.formatResultRef.current ? this.options.formatResultRef.current(res) : res; - this.setState({ data: res, error: undefined, loading: false }); + this.setState({ data: res, error: undefined, loading: false }) - this.options.onSuccess?.(res, params); - this.runPluginHandler('onSuccess', res, params); + this.options.onSuccess?.(res, params) + this.runPluginHandler('onSuccess', res, params) - this.options.onFinally?.(params, res, undefined); + this.options.onFinally?.(params, res, undefined) if (currentCount === this.count) { - this.runPluginHandler('onFinally', params, res, undefined); + this.runPluginHandler('onFinally', params, res, undefined) } - return res; + return res } catch (error) { if (currentCount !== this.count) { // prevent run.then when request is canceled - return new Promise(() => {}); + return new Promise(() => {}) } - this.setState({ error, loading: false }); + this.setState({ error, loading: false }) - this.options.onError?.(error, params); - this.runPluginHandler('onError', error, params); + this.options.onError?.(error, params) + this.runPluginHandler('onError', error, params) - this.options.onFinally?.(params, undefined, error); + this.options.onFinally?.(params, undefined, error) if (currentCount === this.count) { - this.runPluginHandler('onFinally', params, undefined, error); + this.runPluginHandler('onFinally', params, undefined, error) } - throw error; + throw error } } run(...params: TParams) { this.runAsync(...params).catch((error) => { if (!this.options.onError) { - console.error(error); + console.error(error) } - }); + }) } cancel() { - this.count += 1; - this.setState({ loading: false }); + this.count += 1 + this.setState({ loading: false }) - this.runPluginHandler('onCancel'); + this.runPluginHandler('onCancel') } refresh() { // @ts-ignore - this.run(...(this.state.params || [])); + this.run(...(this.state.params || [])) } refreshAsync() { // @ts-ignore - return this.runAsync(...(this.state.params || [])); + return this.runAsync(...(this.state.params || [])) } mutate(data?: TData | ((oldData?: TData) => TData | undefined)) { - const targetData = isFunction(data) ? data(this.state.data) : data; - this.runPluginHandler('onMutate', targetData); - this.setState({ data: targetData }); + const targetData = isFunction(data) ? data(this.state.data) : data + this.runPluginHandler('onMutate', targetData) + this.setState({ data: targetData }) } } diff --git a/packages/hooks/src/useRequest/index.ts b/packages/hooks/src/useRequest/index.ts index 8b8c887d3..8813a2ab2 100644 --- a/packages/hooks/src/useRequest/index.ts +++ b/packages/hooks/src/useRequest/index.ts @@ -1,15 +1,15 @@ -import useAutoRunPlugin from './plugins/useAutoRunPlugin'; -import useCachePlugin from './plugins/useCachePlugin'; -import useDebouncePlugin from './plugins/useDebouncePlugin'; -import useLoadingDelayPlugin from './plugins/useLoadingDelayPlugin'; -import usePollingPlugin from './plugins/usePollingPlugin'; -import useRefreshOnWindowFocusPlugin from './plugins/useRefreshOnWindowFocusPlugin'; -import useRetryPlugin from './plugins/useRetryPlugin'; -import useThrottlePlugin from './plugins/useThrottlePlugin'; -import type { Service, UseRequestOptions, UseRequestPlugin } from './types'; -import { useRequestImplement } from './useRequestImplement'; +import useAutoRunPlugin from './plugins/useAutoRunPlugin' +import useCachePlugin from './plugins/useCachePlugin' +import useDebouncePlugin from './plugins/useDebouncePlugin' +import useLoadingDelayPlugin from './plugins/useLoadingDelayPlugin' +import usePollingPlugin from './plugins/usePollingPlugin' +import useRefreshOnWindowFocusPlugin from './plugins/useRefreshOnWindowFocusPlugin' +import useRetryPlugin from './plugins/useRetryPlugin' +import useThrottlePlugin from './plugins/useThrottlePlugin' +import type { Service, UseRequestOptions, UseRequestPlugin } from './types' +import { useRequestImplement } from './useRequestImplement' -export { clearCache } from './utils/cache'; +export { clearCache } from './utils/cache' export function useRequest( service: Service, @@ -26,5 +26,5 @@ export function useRequest( useAutoRunPlugin, useCachePlugin, useRetryPlugin, - ] as UseRequestPlugin[]); + ] as UseRequestPlugin[]) } diff --git a/packages/hooks/src/useRequest/plugins/useAutoRunPlugin.ts b/packages/hooks/src/useRequest/plugins/useAutoRunPlugin.ts index 0023b9be9..ced047bdc 100644 --- a/packages/hooks/src/useRequest/plugins/useAutoRunPlugin.ts +++ b/packages/hooks/src/useRequest/plugins/useAutoRunPlugin.ts @@ -1,52 +1,52 @@ -import { ref, unref, watch } from 'vue'; +import { ref, unref, watch } from 'vue' -import type { UseRequestPlugin } from '../types'; +import type { UseRequestPlugin } from '../types' // support refreshDeps & ready const useAutoRunPlugin: UseRequestPlugin = ( fetchInstance, { manual, ready = true, defaultParams = [], refreshDeps = [], refreshDepsAction }, ) => { - const hasAutoRun = ref(false); + const hasAutoRun = ref(false) watch( () => unref(ready), (readyVal) => { if (!unref(manual) && readyVal) { - hasAutoRun.value = true; - fetchInstance.run(...defaultParams); + hasAutoRun.value = true + fetchInstance.run(...defaultParams) } }, - ); + ) if (refreshDeps.length) { watch(refreshDeps, () => { if (hasAutoRun.value) { - return; + return } if (!manual) { if (refreshDepsAction) { - refreshDepsAction(); + refreshDepsAction() } else { - fetchInstance.refresh(); + fetchInstance.refresh() } } - }); + }) } return { onBefore: () => { if (!unref(ready)) { - return { stopNow: true }; + return { stopNow: true } } }, - }; -}; + } +} useAutoRunPlugin.onInit = ({ ready = true, manual }) => { return { loading: !unref(manual) && unref(ready), - }; -}; + } +} -export default useAutoRunPlugin; +export default useAutoRunPlugin diff --git a/packages/hooks/src/useRequest/plugins/useCachePlugin.ts b/packages/hooks/src/useRequest/plugins/useCachePlugin.ts index b449b6640..9c3819b50 100644 --- a/packages/hooks/src/useRequest/plugins/useCachePlugin.ts +++ b/packages/hooks/src/useRequest/plugins/useCachePlugin.ts @@ -1,10 +1,10 @@ -import { onUnmounted, ref, watchEffect } from 'vue'; +import { onUnmounted, ref, watchEffect } from 'vue' -import type { UseRequestPlugin } from '../types'; -import type { CachedData } from '../utils/cache'; -import { getCache, setCache } from '../utils/cache'; -import { getCachePromise, setCachePromise } from '../utils/cachePromise'; -import { subscribe, trigger } from '../utils/cacheSubscribe'; +import type { UseRequestPlugin } from '../types' +import type { CachedData } from '../utils/cache' +import { getCache, setCache } from '../utils/cache' +import { getCachePromise, setCachePromise } from '../utils/cachePromise' +import { subscribe, trigger } from '../utils/cacheSubscribe' const useCachePlugin: UseRequestPlugin = ( fetchInstance, @@ -16,52 +16,52 @@ const useCachePlugin: UseRequestPlugin = ( getCache: customGetCache, }, ) => { - const unSubscribeRef = ref<() => void>(); - const currentPromiseRef = ref>(); + const unSubscribeRef = ref<() => void>() + const currentPromiseRef = ref>() const _setCache = (key: string, cachedData: CachedData) => { - customSetCache ? customSetCache(cachedData) : setCache(key, cacheTime, cachedData); - trigger(key, cachedData.data); - }; + customSetCache ? customSetCache(cachedData) : setCache(key, cacheTime, cachedData) + trigger(key, cachedData.data) + } const _getCache = (key: string, params: any[] = []) => { - return customGetCache ? customGetCache(params) : getCache(key); - }; + return customGetCache ? customGetCache(params) : getCache(key) + } watchEffect(() => { - if (!cacheKey) return; + if (!cacheKey) return // get data from cache when init - const cacheData = _getCache(cacheKey); + const cacheData = _getCache(cacheKey) if (cacheData && Object.hasOwnProperty.call(cacheData, 'data')) { - fetchInstance.state.data = cacheData.data; - fetchInstance.state.params = cacheData.params; + fetchInstance.state.data = cacheData.data + fetchInstance.state.params = cacheData.params if (staleTime === -1 || new Date().getTime() - cacheData.time <= staleTime) { - fetchInstance.state.loading = false; + fetchInstance.state.loading = false } } // subscribe same cachekey update, trigger update unSubscribeRef.value = subscribe(cacheKey, (data) => { - fetchInstance.setState({ data }); - }); - }); + fetchInstance.setState({ data }) + }) + }) onUnmounted(() => { - unSubscribeRef.value?.(); - }); + unSubscribeRef.value?.() + }) if (!cacheKey) { - return {}; + return {} } return { onBefore: (params) => { - const cacheData = _getCache(cacheKey, params); + const cacheData = _getCache(cacheKey, params) if (!cacheData || !Object.hasOwnProperty.call(cacheData, 'data')) { - return {}; + return {} } // If the data is fresh, stop request @@ -71,57 +71,57 @@ const useCachePlugin: UseRequestPlugin = ( data: cacheData?.data, error: undefined, returnNow: true, - }; + } } else { // If the data is stale, return data, and request continue - return { data: cacheData?.data, error: undefined }; + return { data: cacheData?.data, error: undefined } } }, onRequest: (service, args) => { - let servicePromise = getCachePromise(cacheKey); + let servicePromise = getCachePromise(cacheKey) // If has servicePromise, and is not trigger by self, then use it if (servicePromise && servicePromise !== currentPromiseRef.value) { - return { servicePromise }; + return { servicePromise } } - servicePromise = service(...args); - currentPromiseRef.value = servicePromise; - setCachePromise(cacheKey, servicePromise); + servicePromise = service(...args) + currentPromiseRef.value = servicePromise + setCachePromise(cacheKey, servicePromise) - return { servicePromise }; + return { servicePromise } }, onSuccess: (data, params) => { if (cacheKey) { // cancel subscribe, avoid trgger self - unSubscribeRef.value?.(); + unSubscribeRef.value?.() - _setCache(cacheKey, { data, params, time: new Date().getTime() }); + _setCache(cacheKey, { data, params, time: new Date().getTime() }) // resubscribe unSubscribeRef.value = subscribe(cacheKey, (d) => { - fetchInstance.setState({ data: d }); - }); + fetchInstance.setState({ data: d }) + }) } }, onMutate: (data) => { if (cacheKey) { // cancel subscribe, avoid trigger self - unSubscribeRef.value?.(); + unSubscribeRef.value?.() _setCache(cacheKey, { data, params: fetchInstance.state.params, time: new Date().getTime(), - }); + }) // resubscribe unSubscribeRef.value = subscribe(cacheKey, (d) => { - fetchInstance.setState({ data: d }); - }); + fetchInstance.setState({ data: d }) + }) } }, - }; -}; + } +} -export default useCachePlugin; +export default useCachePlugin diff --git a/packages/hooks/src/useRequest/plugins/useDebouncePlugin.ts b/packages/hooks/src/useRequest/plugins/useDebouncePlugin.ts index 6a91ad1e7..bb33db741 100644 --- a/packages/hooks/src/useRequest/plugins/useDebouncePlugin.ts +++ b/packages/hooks/src/useRequest/plugins/useDebouncePlugin.ts @@ -1,42 +1,42 @@ -import type { DebouncedFunc, DebounceSettings } from 'lodash-es'; -import { debounce } from 'lodash-es'; -import { computed, ref, watchEffect } from 'vue'; +import type { DebouncedFunc, DebounceSettings } from 'lodash-es' +import { debounce } from 'lodash-es' +import { computed, ref, watchEffect } from 'vue' -import type { UseRequestPlugin } from '../types'; +import type { UseRequestPlugin } from '../types' const useDebouncePlugin: UseRequestPlugin = ( fetchInstance, { debounceWait, debounceLeading, debounceTrailing, debounceMaxWait }, ) => { - const debouncedRef = ref>(); + const debouncedRef = ref>() const options = computed(() => { - const ret: DebounceSettings = {}; + const ret: DebounceSettings = {} if (debounceLeading !== undefined) { - ret.leading = debounceLeading; + ret.leading = debounceLeading } if (debounceTrailing !== undefined) { - ret.trailing = debounceTrailing; + ret.trailing = debounceTrailing } if (debounceMaxWait !== undefined) { - ret.maxWait = debounceMaxWait; + ret.maxWait = debounceMaxWait } - return ret; - }); + return ret + }) watchEffect(() => { if (debounceWait) { - const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance); + const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance) debouncedRef.value = debounce( (callback) => { - callback(); + callback() }, debounceWait, options.value, - ); + ) // debounce runAsync should be promise // https://github.com/lodash/lodash/issues/4400#issuecomment-834800398 @@ -45,27 +45,27 @@ const useDebouncePlugin: UseRequestPlugin = ( debouncedRef.value?.(() => { _originRunAsync(...args) .then(resolve) - .catch(reject); - }); - }); - }; + .catch(reject) + }) + }) + } return () => { - debouncedRef.value?.cancel(); - fetchInstance.runAsync = _originRunAsync; - }; + debouncedRef.value?.cancel() + fetchInstance.runAsync = _originRunAsync + } } - }); + }) if (!debounceWait) { - return {}; + return {} } return { onCancel: () => { - debouncedRef.value?.cancel(); + debouncedRef.value?.cancel() }, - }; -}; + } +} -export default useDebouncePlugin; +export default useDebouncePlugin diff --git a/packages/hooks/src/useRequest/plugins/useLoadingDelayPlugin.ts b/packages/hooks/src/useRequest/plugins/useLoadingDelayPlugin.ts index 89c77f8a0..d11632b25 100644 --- a/packages/hooks/src/useRequest/plugins/useLoadingDelayPlugin.ts +++ b/packages/hooks/src/useRequest/plugins/useLoadingDelayPlugin.ts @@ -1,45 +1,45 @@ -import { ref, unref } from 'vue'; +import { ref, unref } from 'vue' -import type { UseRequestPlugin, UseRequestTimeout } from '../types'; +import type { UseRequestPlugin, UseRequestTimeout } from '../types' const useLoadingDelayPlugin: UseRequestPlugin = ( fetchInstance, { loadingDelay, ready }, ) => { - const timerRef = ref(); + const timerRef = ref() if (!loadingDelay) { - return {}; + return {} } const cancelTimeout = () => { if (timerRef.value) { - clearTimeout(timerRef.value); + clearTimeout(timerRef.value) } - }; + } return { onBefore: () => { - cancelTimeout(); + cancelTimeout() // Two cases: // 1. ready === undefined // 2. ready === true if (unref(ready) !== false) { timerRef.value = setTimeout(() => { - fetchInstance.setState({ loading: true }); - }, loadingDelay); + fetchInstance.setState({ loading: true }) + }, loadingDelay) } - return { loading: false }; + return { loading: false } }, onFinally: () => { - cancelTimeout(); + cancelTimeout() }, onCancel: () => { - cancelTimeout(); + cancelTimeout() }, - }; -}; + } +} -export default useLoadingDelayPlugin; +export default useLoadingDelayPlugin diff --git a/packages/hooks/src/useRequest/plugins/usePollingPlugin.ts b/packages/hooks/src/useRequest/plugins/usePollingPlugin.ts index 7d076b370..df0d86871 100644 --- a/packages/hooks/src/useRequest/plugins/usePollingPlugin.ts +++ b/packages/hooks/src/useRequest/plugins/usePollingPlugin.ts @@ -1,46 +1,46 @@ -import { ref, watch } from 'vue'; +import { ref, watch } from 'vue' -import type { UseRequestPlugin, UseRequestTimeout } from '../types'; -import { isDocumentVisible } from '../utils/isDocumentVisible'; -import subscribeReVisible from '../utils/subscribeReVisible'; +import type { UseRequestPlugin, UseRequestTimeout } from '../types' +import { isDocumentVisible } from '../utils/isDocumentVisible' +import subscribeReVisible from '../utils/subscribeReVisible' const usePollingPlugin: UseRequestPlugin = ( fetchInstance, { pollingInterval, pollingWhenHidden = true, pollingErrorRetryCount = -1 }, ) => { - const timerRef = ref(); - const unsubscribeRef = ref<() => void>(); - const countRef = ref(0); + const timerRef = ref() + const unsubscribeRef = ref<() => void>() + const countRef = ref(0) const stopPolling = () => { if (timerRef.value) { - clearTimeout(timerRef.value); + clearTimeout(timerRef.value) } - unsubscribeRef.value?.(); - }; + unsubscribeRef.value?.() + } watch( () => pollingInterval, () => { if (!pollingInterval) { - stopPolling(); + stopPolling() } }, - ); + ) if (!pollingInterval) { - return {}; + return {} } return { onBefore: () => { - stopPolling(); + stopPolling() }, onError: () => { - countRef.value += 1; + countRef.value += 1 }, onSuccess: () => { - countRef.value = 0; + countRef.value = 0 }, onFinally: () => { if ( @@ -52,20 +52,20 @@ const usePollingPlugin: UseRequestPlugin = ( // if pollingWhenHidden = false && document is hidden, then stop polling and subscribe revisible if (!pollingWhenHidden && !isDocumentVisible()) { unsubscribeRef.value = subscribeReVisible(() => { - fetchInstance.refresh(); - }); + fetchInstance.refresh() + }) } else { - fetchInstance.refresh(); + fetchInstance.refresh() } - }, pollingInterval); + }, pollingInterval) } else { - countRef.value = 0; + countRef.value = 0 } }, onCancel: () => { - stopPolling(); + stopPolling() }, - }; -}; + } +} -export default usePollingPlugin; +export default usePollingPlugin diff --git a/packages/hooks/src/useRequest/plugins/useRefreshOnWindowFocusPlugin.ts b/packages/hooks/src/useRequest/plugins/useRefreshOnWindowFocusPlugin.ts index e1f7b3bbb..845feb56f 100644 --- a/packages/hooks/src/useRequest/plugins/useRefreshOnWindowFocusPlugin.ts +++ b/packages/hooks/src/useRequest/plugins/useRefreshOnWindowFocusPlugin.ts @@ -1,37 +1,37 @@ -import { onUnmounted, ref, watchEffect } from 'vue'; +import { onUnmounted, ref, watchEffect } from 'vue' -import type { UseRequestPlugin } from '../types'; -import { limit } from '../utils/limit'; -import subscribeFocus from '../utils/subscribeFocus'; +import type { UseRequestPlugin } from '../types' +import { limit } from '../utils/limit' +import subscribeFocus from '../utils/subscribeFocus' const useRefreshOnWindowFocusPlugin: UseRequestPlugin = ( fetchInstance, { refreshOnWindowFocus, focusTimespan = 5000 }, ) => { - const unsubscribeRef = ref<() => void>(); + const unsubscribeRef = ref<() => void>() const stopSubscribe = () => { - unsubscribeRef.value?.(); - }; + unsubscribeRef.value?.() + } watchEffect(() => { if (refreshOnWindowFocus) { - const limitRefresh = limit(fetchInstance.refresh.bind(fetchInstance), focusTimespan); + const limitRefresh = limit(fetchInstance.refresh.bind(fetchInstance), focusTimespan) unsubscribeRef.value = subscribeFocus(() => { - limitRefresh(); - }); + limitRefresh() + }) } return () => { - stopSubscribe(); - }; - }); + stopSubscribe() + } + }) onUnmounted(() => { - stopSubscribe(); - }); + stopSubscribe() + }) - return {}; -}; + return {} +} -export default useRefreshOnWindowFocusPlugin; +export default useRefreshOnWindowFocusPlugin diff --git a/packages/hooks/src/useRequest/plugins/useRetryPlugin.ts b/packages/hooks/src/useRequest/plugins/useRetryPlugin.ts index b400db35e..bd0eba6d8 100644 --- a/packages/hooks/src/useRequest/plugins/useRetryPlugin.ts +++ b/packages/hooks/src/useRequest/plugins/useRetryPlugin.ts @@ -1,54 +1,54 @@ -import { ref } from 'vue'; +import { ref } from 'vue' -import type { UseRequestPlugin, UseRequestTimeout } from '../types'; +import type { UseRequestPlugin, UseRequestTimeout } from '../types' const useRetryPlugin: UseRequestPlugin = ( fetchInstance, { retryInterval, retryCount }, ) => { - const timerRef = ref(); - const countRef = ref(0); + const timerRef = ref() + const countRef = ref(0) - const triggerByRetry = ref(false); + const triggerByRetry = ref(false) if (!retryCount) { - return {}; + return {} } return { onBefore: () => { if (!triggerByRetry.value) { - countRef.value = 0; + countRef.value = 0 } - triggerByRetry.value = false; + triggerByRetry.value = false if (timerRef.value) { - clearTimeout(timerRef.value); + clearTimeout(timerRef.value) } }, onSuccess: () => { - countRef.value = 0; + countRef.value = 0 }, onError: () => { - countRef.value += 1; + countRef.value += 1 if (retryCount === -1 || countRef.value <= retryCount) { // Exponential backoff - const timeout = retryInterval ?? Math.min(1000 * 2 ** countRef.value, 30000); + const timeout = retryInterval ?? Math.min(1000 * 2 ** countRef.value, 30000) timerRef.value = setTimeout(() => { - triggerByRetry.value = true; - fetchInstance.refresh(); - }, timeout); + triggerByRetry.value = true + fetchInstance.refresh() + }, timeout) } else { - countRef.value = 0; + countRef.value = 0 } }, onCancel: () => { - countRef.value = 0; + countRef.value = 0 if (timerRef.value) { - clearTimeout(timerRef.value); + clearTimeout(timerRef.value) } }, - }; -}; + } +} -export default useRetryPlugin; +export default useRetryPlugin diff --git a/packages/hooks/src/useRequest/plugins/useThrottlePlugin.ts b/packages/hooks/src/useRequest/plugins/useThrottlePlugin.ts index adeed0518..41bdbe526 100644 --- a/packages/hooks/src/useRequest/plugins/useThrottlePlugin.ts +++ b/packages/hooks/src/useRequest/plugins/useThrottlePlugin.ts @@ -1,34 +1,34 @@ -import type { DebouncedFunc, ThrottleSettings } from 'lodash-es'; -import { throttle } from 'lodash-es'; -import { ref, watchEffect } from 'vue'; +import type { DebouncedFunc, ThrottleSettings } from 'lodash-es' +import { throttle } from 'lodash-es' +import { ref, watchEffect } from 'vue' -import type { UseRequestPlugin } from '../types'; +import type { UseRequestPlugin } from '../types' const useThrottlePlugin: UseRequestPlugin = ( fetchInstance, { throttleWait, throttleLeading, throttleTrailing }, ) => { - const throttledRef = ref>(); + const throttledRef = ref>() - const options: ThrottleSettings = {}; + const options: ThrottleSettings = {} if (throttleLeading !== undefined) { - options.leading = throttleLeading; + options.leading = throttleLeading } if (throttleTrailing !== undefined) { - options.trailing = throttleTrailing; + options.trailing = throttleTrailing } watchEffect(() => { if (throttleWait) { - const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance); + const _originRunAsync = fetchInstance.runAsync.bind(fetchInstance) throttledRef.value = throttle( (callback) => { - callback(); + callback() }, throttleWait, options, - ); + ) // throttle runAsync should be promise // https://github.com/lodash/lodash/issues/4400#issuecomment-834800398 @@ -37,27 +37,27 @@ const useThrottlePlugin: UseRequestPlugin = ( throttledRef.value?.(() => { _originRunAsync(...args) .then(resolve) - .catch(reject); - }); - }); - }; + .catch(reject) + }) + }) + } return () => { - fetchInstance.runAsync = _originRunAsync; - throttledRef.value?.cancel(); - }; + fetchInstance.runAsync = _originRunAsync + throttledRef.value?.cancel() + } } - }); + }) if (!throttleWait) { - return {}; + return {} } return { onCancel: () => { - throttledRef.value?.cancel(); + throttledRef.value?.cancel() }, - }; -}; + } +} -export default useThrottlePlugin; +export default useThrottlePlugin diff --git a/packages/hooks/src/useRequest/types.ts b/packages/hooks/src/useRequest/types.ts index 60cc8e95b..93021cb4c 100644 --- a/packages/hooks/src/useRequest/types.ts +++ b/packages/hooks/src/useRequest/types.ts @@ -1,93 +1,93 @@ -import type { MaybeRef, Ref, WatchSource } from 'vue'; +import type { MaybeRef, Ref, WatchSource } from 'vue' -import type Fetch from './Fetch'; -import type { CachedData } from './utils/cache'; +import type Fetch from './Fetch' +import type { CachedData } from './utils/cache' -export type Service = (...args: TParams) => Promise; -export type Subscribe = () => void; +export type Service = (...args: TParams) => Promise +export type Subscribe = () => void // for Fetch export interface FetchState { - loading: boolean; - params?: TParams; - data?: TData; - error?: Error; + loading: boolean + params?: TParams + data?: TData + error?: Error } export interface PluginReturn { onBefore?: (params: TParams) => | ({ - stopNow?: boolean; - returnNow?: boolean; + stopNow?: boolean + returnNow?: boolean } & Partial>) - | void; + | void onRequest?: ( service: Service, params: TParams, ) => { - servicePromise?: Promise; - }; + servicePromise?: Promise + } - onSuccess?: (data: TData, params: TParams) => void; - onError?: (e: Error, params: TParams) => void; - onFinally?: (params: TParams, data?: TData, e?: Error) => void; - onCancel?: () => void; - onMutate?: (data: TData) => void; + onSuccess?: (data: TData, params: TParams) => void + onError?: (e: Error, params: TParams) => void + onFinally?: (params: TParams, data?: TData, e?: Error) => void + onCancel?: () => void + onMutate?: (data: TData) => void } // for useRequestImplement export interface UseRequestOptions { - manual?: MaybeRef; + manual?: MaybeRef - onBefore?: (params: TParams) => void; - onSuccess?: (data: TData, params: TParams) => void; - onError?: (e: Error, params: TParams) => void; + onBefore?: (params: TParams) => void + onSuccess?: (data: TData, params: TParams) => void + onError?: (e: Error, params: TParams) => void // formatResult?: (res: any) => TData; - onFinally?: (params: TParams, data?: TData, e?: Error) => void; + onFinally?: (params: TParams, data?: TData, e?: Error) => void - defaultParams?: TParams; + defaultParams?: TParams // refreshDeps - refreshDeps?: WatchSource[]; - refreshDepsAction?: () => void; + refreshDeps?: WatchSource[] + refreshDepsAction?: () => void // loading delay - loadingDelay?: number; + loadingDelay?: number // polling - pollingInterval?: number; - pollingWhenHidden?: boolean; - pollingErrorRetryCount?: number; + pollingInterval?: number + pollingWhenHidden?: boolean + pollingErrorRetryCount?: number // refresh on window focus - refreshOnWindowFocus?: boolean; - focusTimespan?: number; + refreshOnWindowFocus?: boolean + focusTimespan?: number // debounce - debounceWait?: number; - debounceLeading?: boolean; - debounceTrailing?: boolean; - debounceMaxWait?: number; + debounceWait?: number + debounceLeading?: boolean + debounceTrailing?: boolean + debounceMaxWait?: number // throttle - throttleWait?: number; - throttleLeading?: boolean; - throttleTrailing?: boolean; + throttleWait?: number + throttleLeading?: boolean + throttleTrailing?: boolean // cache - cacheKey?: string; - cacheTime?: number; - staleTime?: number; - setCache?: (data: CachedData) => void; - getCache?: (params: TParams) => CachedData | undefined; + cacheKey?: string + cacheTime?: number + staleTime?: number + setCache?: (data: CachedData) => void + getCache?: (params: TParams) => CachedData | undefined // retry - retryCount?: number; - retryInterval?: number; + retryCount?: number + retryInterval?: number // ready - ready?: MaybeRef; + ready?: MaybeRef // [key: string]: any; } @@ -97,8 +97,8 @@ export interface UseRequestPlugin { ( fetchInstance: Fetch, options: UseRequestOptions, - ): PluginReturn; - onInit?: (options: UseRequestOptions) => Partial>; + ): PluginReturn + onInit?: (options: UseRequestOptions) => Partial> } // for index @@ -109,16 +109,16 @@ export interface UseRequestPlugin { // }; export interface UseRequestResult { - loading: Ref; - data: Ref; - error: Ref; - params: Ref; - cancel: Fetch['cancel']; - refresh: Fetch['refresh']; - refreshAsync: Fetch['refreshAsync']; - run: Fetch['run']; - runAsync: Fetch['runAsync']; - mutate: Fetch['mutate']; + loading: Ref + data: Ref + error: Ref + params: Ref + cancel: Fetch['cancel'] + refresh: Fetch['refresh'] + refreshAsync: Fetch['refreshAsync'] + run: Fetch['run'] + runAsync: Fetch['runAsync'] + mutate: Fetch['mutate'] } -export type UseRequestTimeout = ReturnType; +export type UseRequestTimeout = ReturnType diff --git a/packages/hooks/src/useRequest/useRequestImplement.ts b/packages/hooks/src/useRequest/useRequestImplement.ts index 54cf1530d..d450d56dd 100644 --- a/packages/hooks/src/useRequest/useRequestImplement.ts +++ b/packages/hooks/src/useRequest/useRequestImplement.ts @@ -1,41 +1,41 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ -import { onMounted, onUnmounted, toRefs } from 'vue'; +import { onMounted, onUnmounted, toRefs } from 'vue' -import Fetch from './Fetch'; -import type { Service, UseRequestOptions, UseRequestPlugin, UseRequestResult } from './types'; +import Fetch from './Fetch' +import type { Service, UseRequestOptions, UseRequestPlugin, UseRequestResult } from './types' export function useRequestImplement( service: Service, options: UseRequestOptions = {}, plugins: UseRequestPlugin[] = [], ) { - const { manual = false, ...rest } = options; - const fetchOptions = { manual, ...rest }; + const { manual = false, ...rest } = options + const fetchOptions = { manual, ...rest } - const initState = plugins.map((p) => p?.onInit?.(fetchOptions)).filter(Boolean); + const initState = plugins.map((p) => p?.onInit?.(fetchOptions)).filter(Boolean) const fetchInstance = new Fetch( service, fetchOptions, () => {}, Object.assign({}, ...initState), - ); + ) - fetchInstance.options = fetchOptions; + fetchInstance.options = fetchOptions // run all plugins hooks - fetchInstance.pluginImpls = plugins.map((p) => p(fetchInstance, fetchOptions)); + fetchInstance.pluginImpls = plugins.map((p) => p(fetchInstance, fetchOptions)) onMounted(() => { if (!manual) { - const params = fetchInstance.state.params || options.defaultParams || []; + const params = fetchInstance.state.params || options.defaultParams || [] // @ts-ignore - fetchInstance.run(...params); + fetchInstance.run(...params) } - }); + }) onUnmounted(() => { - fetchInstance.cancel(); - }); + fetchInstance.cancel() + }) return { ...toRefs(fetchInstance.state), @@ -45,5 +45,5 @@ export function useRequestImplement( refreshAsync: fetchInstance.refreshAsync.bind(fetchInstance), run: fetchInstance.run.bind(fetchInstance), runAsync: fetchInstance.runAsync.bind(fetchInstance), - } as UseRequestResult; + } as UseRequestResult } diff --git a/packages/hooks/src/useRequest/utils/cache.ts b/packages/hooks/src/useRequest/utils/cache.ts index f89e0a137..992bac364 100644 --- a/packages/hooks/src/useRequest/utils/cache.ts +++ b/packages/hooks/src/useRequest/utils/cache.ts @@ -1,48 +1,48 @@ -type Timer = ReturnType; -type CachedKey = string | number; +type Timer = ReturnType +type CachedKey = string | number export interface CachedData { - data: TData; - params: TParams; - time: number; + data: TData + params: TParams + time: number } interface RecordData extends CachedData { - timer: Timer | undefined; + timer: Timer | undefined } -const cache = new Map(); +const cache = new Map() export const setCache = (key: CachedKey, cacheTime: number, cachedData: CachedData) => { - const currentCache = cache.get(key); + const currentCache = cache.get(key) if (currentCache?.timer) { - clearTimeout(currentCache.timer); + clearTimeout(currentCache.timer) } - let timer: Timer | undefined = undefined; + let timer: Timer | undefined = undefined if (cacheTime > -1) { // if cache out, clear it timer = setTimeout(() => { - cache.delete(key); - }, cacheTime); + cache.delete(key) + }, cacheTime) } cache.set(key, { ...cachedData, timer, - }); -}; + }) +} export const getCache = (key: CachedKey) => { - return cache.get(key); -}; + return cache.get(key) +} export const clearCache = (key?: string | string[]) => { if (key) { - const cacheKeys = Array.isArray(key) ? key : [key]; - cacheKeys.forEach((cacheKey) => cache.delete(cacheKey)); + const cacheKeys = Array.isArray(key) ? key : [key] + cacheKeys.forEach((cacheKey) => cache.delete(cacheKey)) } else { - cache.clear(); + cache.clear() } -}; +} diff --git a/packages/hooks/src/useRequest/utils/cachePromise.ts b/packages/hooks/src/useRequest/utils/cachePromise.ts index 602a5c21f..2f0536db0 100644 --- a/packages/hooks/src/useRequest/utils/cachePromise.ts +++ b/packages/hooks/src/useRequest/utils/cachePromise.ts @@ -1,23 +1,23 @@ -type CachedKey = string | number; +type CachedKey = string | number -const cachePromise = new Map>(); +const cachePromise = new Map>() export const getCachePromise = (cacheKey: CachedKey) => { - return cachePromise.get(cacheKey); -}; + return cachePromise.get(cacheKey) +} export const setCachePromise = (cacheKey: CachedKey, promise: Promise) => { // Should cache the same promise, cannot be promise.finally // Because the promise.finally will change the reference of the promise - cachePromise.set(cacheKey, promise); + cachePromise.set(cacheKey, promise) // no use promise.finally for compatibility promise .then((res) => { - cachePromise.delete(cacheKey); - return res; + cachePromise.delete(cacheKey) + return res }) .catch(() => { - cachePromise.delete(cacheKey); - }); -}; + cachePromise.delete(cacheKey) + }) +} diff --git a/packages/hooks/src/useRequest/utils/cacheSubscribe.ts b/packages/hooks/src/useRequest/utils/cacheSubscribe.ts index c66dc0c91..4fdcb842e 100644 --- a/packages/hooks/src/useRequest/utils/cacheSubscribe.ts +++ b/packages/hooks/src/useRequest/utils/cacheSubscribe.ts @@ -1,22 +1,22 @@ -type Listener = (data: any) => void; +type Listener = (data: any) => void -const listeners: Record = {}; +const listeners: Record = {} export const trigger = (key: string, data: any) => { if (listeners[key]) { - listeners[key].forEach((item) => item(data)); + listeners[key].forEach((item) => item(data)) } -}; +} export const subscribe = (key: string, listener: Listener) => { if (!listeners[key]) { - listeners[key] = []; + listeners[key] = [] } - listeners[key].push(listener); + listeners[key].push(listener) return function unsubscribe() { - const index = listeners[key].indexOf(listener); - listeners[key].splice(index, 1); - }; -}; + const index = listeners[key].indexOf(listener) + listeners[key].splice(index, 1) + } +} diff --git a/packages/hooks/src/useRequest/utils/isBrowser.ts b/packages/hooks/src/useRequest/utils/isBrowser.ts index 4a1b91e97..adf8ea075 100644 --- a/packages/hooks/src/useRequest/utils/isBrowser.ts +++ b/packages/hooks/src/useRequest/utils/isBrowser.ts @@ -2,4 +2,4 @@ export const isBrowser = !!( typeof window !== 'undefined' && window.document && window.document.createElement -); +) diff --git a/packages/hooks/src/useRequest/utils/isDocumentVisible.ts b/packages/hooks/src/useRequest/utils/isDocumentVisible.ts index e9d1275d4..faee84460 100644 --- a/packages/hooks/src/useRequest/utils/isDocumentVisible.ts +++ b/packages/hooks/src/useRequest/utils/isDocumentVisible.ts @@ -1,8 +1,8 @@ -import { isBrowser } from './isBrowser'; +import { isBrowser } from './isBrowser' export function isDocumentVisible(): boolean { if (isBrowser) { - return document.visibilityState !== 'hidden'; + return document.visibilityState !== 'hidden' } - return true; + return true } diff --git a/packages/hooks/src/useRequest/utils/isFunction.ts b/packages/hooks/src/useRequest/utils/isFunction.ts index 782f37c82..b03e128fc 100644 --- a/packages/hooks/src/useRequest/utils/isFunction.ts +++ b/packages/hooks/src/useRequest/utils/isFunction.ts @@ -1,2 +1,2 @@ export const isFunction = (value: unknown): value is (...args: any) => any => - typeof value === 'function'; + typeof value === 'function' diff --git a/packages/hooks/src/useRequest/utils/isOnline.ts b/packages/hooks/src/useRequest/utils/isOnline.ts index 900f9a34c..b23d9d7bb 100644 --- a/packages/hooks/src/useRequest/utils/isOnline.ts +++ b/packages/hooks/src/useRequest/utils/isOnline.ts @@ -1,8 +1,8 @@ -import { isBrowser } from './isBrowser'; +import { isBrowser } from './isBrowser' export function isOnline(): boolean { if (isBrowser && typeof navigator.onLine !== 'undefined') { - return navigator.onLine; + return navigator.onLine } - return true; + return true } diff --git a/packages/hooks/src/useRequest/utils/limit.ts b/packages/hooks/src/useRequest/utils/limit.ts index c540e87d0..92e06d9bb 100644 --- a/packages/hooks/src/useRequest/utils/limit.ts +++ b/packages/hooks/src/useRequest/utils/limit.ts @@ -1,12 +1,12 @@ export function limit(fn: any, timespan: number) { - let pending = false; + let pending = false return (...args: any[]) => { - if (pending) return; - pending = true; - fn(...args); + if (pending) return + pending = true + fn(...args) setTimeout(() => { - pending = false; - }, timespan); - }; + pending = false + }, timespan) + } } diff --git a/packages/hooks/src/useRequest/utils/subscribeFocus.ts b/packages/hooks/src/useRequest/utils/subscribeFocus.ts index 751650fd4..f47081885 100644 --- a/packages/hooks/src/useRequest/utils/subscribeFocus.ts +++ b/packages/hooks/src/useRequest/utils/subscribeFocus.ts @@ -1,30 +1,30 @@ -import { isBrowser } from './isBrowser'; -import { isDocumentVisible } from './isDocumentVisible'; -import { isOnline } from './isOnline'; +import { isBrowser } from './isBrowser' +import { isDocumentVisible } from './isDocumentVisible' +import { isOnline } from './isOnline' -type Listener = () => void; +type Listener = () => void -const listeners: Listener[] = []; +const listeners: Listener[] = [] if (isBrowser) { const revalidate = () => { - if (!isDocumentVisible() || !isOnline()) return; + if (!isDocumentVisible() || !isOnline()) return for (let i = 0; i < listeners.length; i++) { - const listener = listeners[i]; - listener(); + const listener = listeners[i] + listener() } - }; - window.addEventListener('visibilitychange', revalidate, false); - window.addEventListener('focus', revalidate, false); + } + window.addEventListener('visibilitychange', revalidate, false) + window.addEventListener('focus', revalidate, false) } export default function subscribe(listener: Listener) { - listeners.push(listener); + listeners.push(listener) return function unsubscribe() { - const index = listeners.indexOf(listener); + const index = listeners.indexOf(listener) if (index > -1) { - listeners.splice(index, 1); + listeners.splice(index, 1) } - }; + } } diff --git a/packages/hooks/src/useRequest/utils/subscribeReVisible.ts b/packages/hooks/src/useRequest/utils/subscribeReVisible.ts index cf961e9ee..fa07ecde0 100644 --- a/packages/hooks/src/useRequest/utils/subscribeReVisible.ts +++ b/packages/hooks/src/useRequest/utils/subscribeReVisible.ts @@ -1,25 +1,25 @@ -import { isBrowser } from './isBrowser'; -import { isDocumentVisible } from './isDocumentVisible'; +import { isBrowser } from './isBrowser' +import { isDocumentVisible } from './isDocumentVisible' -type Listener = () => void; +type Listener = () => void -const listeners: Listener[] = []; +const listeners: Listener[] = [] if (isBrowser) { const revalidate = () => { - if (!isDocumentVisible()) return; + if (!isDocumentVisible()) return for (let i = 0; i < listeners.length; i++) { - const listener = listeners[i]; - listener(); + const listener = listeners[i] + listener() } - }; - window.addEventListener('visibilitychange', revalidate, false); + } + window.addEventListener('visibilitychange', revalidate, false) } export default function subscribe(listener: Listener) { - listeners.push(listener); + listeners.push(listener) return function unsubscribe() { - const index = listeners.indexOf(listener); - listeners.splice(index, 1); - }; + const index = listeners.indexOf(listener) + listeners.splice(index, 1) + } } diff --git a/packages/hooks/src/useScrollTo.ts b/packages/hooks/src/useScrollTo.ts index f6a95f483..fd20a117c 100644 --- a/packages/hooks/src/useScrollTo.ts +++ b/packages/hooks/src/useScrollTo.ts @@ -1,60 +1,60 @@ -import { shallowRef, unref } from 'vue'; +import { shallowRef, unref } from 'vue' interface UseScrollToOptions { - el: any; - to: number; - duration?: number; - callback?: () => any; + el: any + to: number + duration?: number + callback?: () => any } function easeInOutQuad(t: number, b: number, c: number, d: number) { - t /= d / 2; + t /= d / 2 if (t < 1) { - return (c / 2) * t * t + b; + return (c / 2) * t * t + b } - t--; - return (-c / 2) * (t * (t - 2) - 1) + b; + t-- + return (-c / 2) * (t * (t - 2) - 1) + b } function move(el: HTMLElement, amount: number) { - el.scrollTop = amount; + el.scrollTop = amount } const position = (el: HTMLElement) => { - return el.scrollTop; -}; + return el.scrollTop +} function useScrollTo({ el, to, duration = 500, callback }: UseScrollToOptions) { - const isActiveRef = shallowRef(false); - const start = position(el); - const change = to - start; - const increment = 20; - let currentTime = 0; + const isActiveRef = shallowRef(false) + const start = position(el) + const change = to - start + const increment = 20 + let currentTime = 0 const animateScroll = function () { if (!unref(isActiveRef)) { - return; + return } - currentTime += increment; - const val = easeInOutQuad(currentTime, start, change, duration); - move(el, val); + currentTime += increment + const val = easeInOutQuad(currentTime, start, change, duration) + move(el, val) if (currentTime < duration && unref(isActiveRef)) { - requestAnimationFrame(animateScroll); + requestAnimationFrame(animateScroll) } else { if (callback && typeof callback === 'function') { - callback(); + callback() } } - }; + } const run = () => { - isActiveRef.value = true; - animateScroll(); - }; + isActiveRef.value = true + animateScroll() + } const stop = () => { - isActiveRef.value = false; - }; + isActiveRef.value = false + } - return { start: run, stop }; + return { start: run, stop } } -export { useScrollTo, type UseScrollToOptions }; +export { useScrollTo, type UseScrollToOptions } diff --git a/packages/hooks/src/useWindowSizeFn.ts b/packages/hooks/src/useWindowSizeFn.ts index d8e77105d..591a0f4c0 100644 --- a/packages/hooks/src/useWindowSizeFn.ts +++ b/packages/hooks/src/useWindowSizeFn.ts @@ -1,40 +1,40 @@ -import { type AnyFunction } from '@vben/types'; -import { tryOnMounted, tryOnUnmounted, useDebounceFn } from '@vueuse/core'; +import { type AnyFunction } from '@vben/types' +import { tryOnMounted, tryOnUnmounted, useDebounceFn } from '@vueuse/core' interface UseWindowSizeOptions { - wait?: number; - once?: boolean; - immediate?: boolean; - listenerOptions?: AddEventListenerOptions | boolean; + wait?: number + once?: boolean + immediate?: boolean + listenerOptions?: AddEventListenerOptions | boolean } function useWindowSizeFn(fn: AnyFunction, options: UseWindowSizeOptions = {}) { - const { wait = 150, immediate } = options; + const { wait = 150, immediate } = options let handler = () => { - fn(); - }; - const handleSize = useDebounceFn(handler, wait); - handler = handleSize; + fn() + } + const handleSize = useDebounceFn(handler, wait) + handler = handleSize const start = () => { if (immediate) { - handler(); + handler() } - window.addEventListener('resize', handler); - }; + window.addEventListener('resize', handler) + } const stop = () => { - window.removeEventListener('resize', handler); - }; + window.removeEventListener('resize', handler) + } tryOnMounted(() => { - start(); - }); + start() + }) tryOnUnmounted(() => { - stop(); - }); - return { start, stop }; + stop() + }) + return { start, stop } } -export { useWindowSizeFn, type UseWindowSizeOptions }; +export { useWindowSizeFn, type UseWindowSizeOptions } diff --git a/packages/types/build.config.ts b/packages/types/build.config.ts index 20c8b54a1..aef3e10bd 100644 --- a/packages/types/build.config.ts +++ b/packages/types/build.config.ts @@ -1,4 +1,4 @@ -import { defineBuildConfig } from 'unbuild'; +import { defineBuildConfig } from 'unbuild' export default defineBuildConfig({ clean: true, @@ -7,4 +7,4 @@ export default defineBuildConfig({ rollup: { emitCJS: true, }, -}); +}) diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 04bca77e0..9c56149ef 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -1 +1 @@ -export * from './utils'; +export * from './utils' diff --git a/packages/types/src/utils.ts b/packages/types/src/utils.ts index b8ed226a0..1ea4fe686 100644 --- a/packages/types/src/utils.ts +++ b/packages/types/src/utils.ts @@ -1,49 +1,49 @@ /** * 任意类型的异步函数 */ -type AnyPromiseFunction = (...arg: any[]) => PromiseLike; +type AnyPromiseFunction = (...arg: any[]) => PromiseLike /** * 任意类型的普通函数 */ -type AnyNormalFunction = (...arg: any[]) => any; +type AnyNormalFunction = (...arg: any[]) => any /** * 任意类型的函数 */ -type AnyFunction = AnyNormalFunction | AnyPromiseFunction; +type AnyFunction = AnyNormalFunction | AnyPromiseFunction /** * T | null 包装 */ -type Nullable = T | null; +type Nullable = T | null /** * T | Not null 包装 */ -type NonNullable = T extends null | undefined ? never : T; +type NonNullable = T extends null | undefined ? never : T /** * 字符串类型对象 */ -type Recordable = Record; +type Recordable = Record /** * 字符串类型对象(只读) */ interface ReadonlyRecordable { - readonly [key: string]: T; + readonly [key: string]: T } /** * setTimeout 返回值类型 */ -type TimeoutHandle = ReturnType; +type TimeoutHandle = ReturnType /** * setInterval 返回值类型 */ -type IntervalHandle = ReturnType; +type IntervalHandle = ReturnType export { type AnyFunction, @@ -55,4 +55,4 @@ export { type ReadonlyRecordable, type Recordable, type TimeoutHandle, -}; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1bad5d683..837e7d308 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -83,9 +83,6 @@ importers: vue: specifier: ^3.4.25 version: 3.4.25(typescript@5.4.5) - vue-i18n: - specifier: ^9.13.1 - version: 9.13.1(vue@3.4.25(typescript@5.4.5)) vue-json-pretty: specifier: ^2.4.0 version: 2.4.0(vue@3.4.25(typescript@5.4.5)) @@ -102,8 +99,8 @@ importers: specifier: ^4.7.31 version: 4.7.40 xe-utils: - specifier: ^3.5.25 - version: 3.5.25 + specifier: ^3.5.28 + version: 3.5.28 devDependencies: '@commitlint/cli': specifier: ^19.3.0 @@ -1081,18 +1078,6 @@ packages: '@iconify/utils@2.1.23': resolution: {integrity: sha512-YGNbHKM5tyDvdWZ92y2mIkrfvm5Fvhe6WJSkWu7vvOFhMtYDP0casZpoRz0XEHZCrYsR4stdGT3cZ52yp5qZdQ==} - '@intlify/core-base@9.13.1': - resolution: {integrity: sha512-+bcQRkJO9pcX8d0gel9ZNfrzU22sZFSA0WVhfXrf5jdJOS24a+Bp8pozuS9sBI9Hk/tGz83pgKfmqcn/Ci7/8w==} - engines: {node: '>= 16'} - - '@intlify/message-compiler@9.13.1': - resolution: {integrity: sha512-SKsVa4ajYGBVm7sHMXd5qX70O2XXjm55zdZB3VeMFCvQyvLew/dLvq3MqnaIsTMF1VkkOb9Ttr6tHcMlyPDL9w==} - engines: {node: '>= 16'} - - '@intlify/shared@9.13.1': - resolution: {integrity: sha512-u3b6BKGhE6j/JeRU6C/RL2FgyJfy6LakbtfeVF8fJXURpZZTzfh3e05J0bu0XPw447Q6/WUp3C4ajv4TMS4YsQ==} - engines: {node: '>= 16'} - '@isaacs/cliui@8.0.2': resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} engines: {node: '>=12'} @@ -5914,12 +5899,6 @@ packages: peerDependencies: eslint: '>=6.0.0' - vue-i18n@9.13.1: - resolution: {integrity: sha512-mh0GIxx0wPtPlcB1q4k277y0iKgo25xmDPWioVVYanjPufDBpvu5ySTjP5wOrSvlYQ2m1xI+CFhGdauv/61uQg==} - engines: {node: '>= 16'} - peerDependencies: - vue: ^3.0.0 - vue-json-pretty@2.4.0: resolution: {integrity: sha512-e9bP41DYYIc2tWaB6KuwqFJq5odZ8/GkE6vHQuGcbPn37kGk4a3n1RNw3ZYeDrl66NWXgTlOfS+M6NKkowmkWw==} engines: {node: '>= 10.0.0', npm: '>= 5.0.0'} @@ -6076,9 +6055,6 @@ packages: utf-8-validate: optional: true - xe-utils@3.5.25: - resolution: {integrity: sha512-d/ty5eo4hXtho/3195XAvqereIoSYJ+XfC52f3ZEPxTaCeyLFivDZTyX6gTdsR65ISH1Irvn85H0bSL60dUhSQ==} - xe-utils@3.5.28: resolution: {integrity: sha512-oeLLJ0b54QdOSSgYQ9TiKW/xAGrc9r0weCA/5UfyGdm3n3js4cNOuuf9Tml7UwgBQpl4uWMbMwUZKLh2yqPF3A==} @@ -6759,18 +6735,6 @@ snapshots: transitivePeerDependencies: - supports-color - '@intlify/core-base@9.13.1': - dependencies: - '@intlify/message-compiler': 9.13.1 - '@intlify/shared': 9.13.1 - - '@intlify/message-compiler@9.13.1': - dependencies: - '@intlify/shared': 9.13.1 - source-map-js: 1.2.0 - - '@intlify/shared@9.13.1': {} - '@isaacs/cliui@8.0.2': dependencies: string-width: 5.1.2 @@ -12351,13 +12315,6 @@ snapshots: transitivePeerDependencies: - supports-color - vue-i18n@9.13.1(vue@3.4.25(typescript@5.4.5)): - dependencies: - '@intlify/core-base': 9.13.1 - '@intlify/shared': 9.13.1 - '@vue/devtools-api': 6.6.1 - vue: 3.4.25(typescript@5.4.5) - vue-json-pretty@2.4.0(vue@3.4.25(typescript@5.4.5)): dependencies: vue: 3.4.25(typescript@5.4.5) @@ -12504,8 +12461,6 @@ snapshots: ws@8.16.0: {} - xe-utils@3.5.25: {} - xe-utils@3.5.28: {} xml-name-validator@4.0.0: {} diff --git a/src/api/common/FileUpload.ts b/src/api/common/FileUpload.ts index dce99877e..3a7cc2c4b 100644 --- a/src/api/common/FileUpload.ts +++ b/src/api/common/FileUpload.ts @@ -40,7 +40,10 @@ export const getFileDownloadUrl = (id) => { * @param params * @param onUploadProgress */ -export function uploadFile(params: UploadFileParams, onUploadProgress: (progressEvent: AxiosProgressEvent) => void) { +export function uploadFile( + params: UploadFileParams, + onUploadProgress: (progressEvent: AxiosProgressEvent) => void, +) { return defHttp.uploadFile( { url: VITE_GLOB_API_URL + VITE_GLOB_API_URL_PREFIX + '/file/upload', diff --git a/src/api/sys/menu.ts b/src/api/sys/menu.ts index a85852d59..da7d7d54a 100644 --- a/src/api/sys/menu.ts +++ b/src/api/sys/menu.ts @@ -18,5 +18,8 @@ export const getMenuList = () => { * 获取菜单和权限码 */ export const getPermissions = (clientCode: string) => { - return defHttp.get>({ url: '/role/menu/getPermissions', params: { clientCode } }) + return defHttp.get>({ + url: '/role/menu/getPermissions', + params: { clientCode }, + }) } diff --git a/src/api/sys/upload.ts b/src/api/sys/upload.ts index 0d88e9994..c45bde9f9 100644 --- a/src/api/sys/upload.ts +++ b/src/api/sys/upload.ts @@ -9,7 +9,10 @@ const { uploadUrl = '' } = useGlobSetting() /** * @description: Upload interface */ -export function uploadApi(params: UploadFileParams, onUploadProgress: (progressEvent: AxiosProgressEvent) => void) { +export function uploadApi( + params: UploadFileParams, + onUploadProgress: (progressEvent: AxiosProgressEvent) => void, +) { return defHttp.uploadFile( { url: uploadUrl, diff --git a/src/components/Application/src/AppLogo.vue b/src/components/Application/src/AppLogo.vue index 8077ae8e4..6916276a9 100644 --- a/src/components/Application/src/AppLogo.vue +++ b/src/components/Application/src/AppLogo.vue @@ -40,7 +40,11 @@ const { title } = useGlobSetting() const go = useGo() - const getAppLogoClass = computed(() => [prefixCls, props.theme, { 'collapsed-show-title': unref(getCollapsedShowTitle) }]) + const getAppLogoClass = computed(() => [ + prefixCls, + props.theme, + { 'collapsed-show-title': unref(getCollapsedShowTitle) }, + ]) const getTitleClass = computed(() => [ `${prefixCls}__title`, diff --git a/src/components/Application/src/AppProvider.vue b/src/components/Application/src/AppProvider.vue index 03103f007..a2c64e86f 100644 --- a/src/components/Application/src/AppProvider.vue +++ b/src/components/Application/src/AppProvider.vue @@ -45,7 +45,12 @@ if (!unref(isSetState)) { isSetState.value = true const { - menuSetting: { type: menuType, mode: menuMode, collapsed: menuCollapsed, split: menuSplit }, + menuSetting: { + type: menuType, + mode: menuMode, + collapsed: menuCollapsed, + split: menuSplit, + }, } = appStore.getProjectConfig appStore.setProjectConfig({ menuSetting: { diff --git a/src/components/Application/src/search/AppSearchModal.vue b/src/components/Application/src/search/AppSearchModal.vue index a572405da..9b89d28fc 100644 --- a/src/components/Application/src/search/AppSearchModal.vue +++ b/src/components/Application/src/search/AppSearchModal.vue @@ -4,7 +4,13 @@
- + @@ -34,7 +40,11 @@
- + {{ each.char }}
@@ -74,7 +84,8 @@ const { refs, setRefs } = useRefs() const { getIsMobile } = useAppInject() - const { handleSearch, searchResult, keyword, activeIndex, handleEnter, handleMouseenter } = useMenuSearch(refs, scrollWrap, emit) + const { handleSearch, searchResult, keyword, activeIndex, handleEnter, handleMouseenter } = + useMenuSearch(refs, scrollWrap, emit) const getIsNotData = computed(() => !keyword || unref(searchResult).length === 0) diff --git a/src/components/Application/src/search/useMenuSearch.ts b/src/components/Application/src/search/useMenuSearch.ts index d730f8c78..b4f109a4f 100644 --- a/src/components/Application/src/search/useMenuSearch.ts +++ b/src/components/Application/src/search/useMenuSearch.ts @@ -66,7 +66,11 @@ export function useMenuSearch(refs: Ref, scrollWrap: Ref, emit: A const ret: SearchResult[] = [] filterMenu.forEach((item) => { const { name, path, icon, children, hideMenu, meta } = item - if (!hideMenu && reg.test(name?.toLowerCase() ?? '') && (!children?.length || meta?.hideChildrenInMenu)) { + if ( + !hideMenu && + reg.test(name?.toLowerCase() ?? '') && + (!children?.length || meta?.hideChildrenInMenu) + ) { const chars: { char: string; highlight: boolean }[] = [] // 显示字符串 @@ -84,7 +88,10 @@ export function useMenuSearch(refs: Ref, scrollWrap: Ref, emit: A // 优先查找完整关键词的匹配 if (label.toLowerCase().includes(keyword.value.toLowerCase())) { while (includePointer < labelChars.length) { - if (label.toLowerCase().slice(includePointer, includePointer + keywordLength) === keyword.value.toLowerCase()) { + if ( + label.toLowerCase().slice(includePointer, includePointer + keywordLength) === + keyword.value.toLowerCase() + ) { chars.push( ...label .substring(labelPointer, includePointer) @@ -116,7 +123,10 @@ export function useMenuSearch(refs: Ref, scrollWrap: Ref, emit: A keywordPointer = 0 while (keywordPointer < keywordChars.length) { if (keywordChars[keywordPointer] !== void 0 && labelChars[labelPointer] !== void 0) { - if (keywordChars[keywordPointer].toLowerCase() === labelChars[labelPointer].toLowerCase()) { + if ( + keywordChars[keywordPointer].toLowerCase() === + labelChars[labelPointer].toLowerCase() + ) { chars.push({ char: labelChars[labelPointer], highlight: true, @@ -148,12 +158,17 @@ export function useMenuSearch(refs: Ref, scrollWrap: Ref, emit: A // 排序 return ret.sort((a, b) => { - if (a.name.toLowerCase().includes(keyword.value.toLowerCase()) && b.name.toLowerCase().includes(keyword.value.toLowerCase())) { + if ( + a.name.toLowerCase().includes(keyword.value.toLowerCase()) && + b.name.toLowerCase().includes(keyword.value.toLowerCase()) + ) { // 两者都存在完整关键词的匹配 // 匹配数量 - const ca = a.name.toLowerCase().match(new RegExp(keyword.value.toLowerCase(), 'g'))?.length ?? 0 - const cb = b.name.toLowerCase().match(new RegExp(keyword.value.toLowerCase(), 'g'))?.length ?? 0 + const ca = + a.name.toLowerCase().match(new RegExp(keyword.value.toLowerCase(), 'g'))?.length ?? 0 + const cb = + b.name.toLowerCase().match(new RegExp(keyword.value.toLowerCase(), 'g'))?.length ?? 0 // 匹配数量越多的优先显示,数量相同的按字符串排序 return ca === cb ? a.name.toLowerCase().localeCompare(b.name.toLowerCase()) : cb - ca diff --git a/src/components/Basic/src/BasicHelp.vue b/src/components/Basic/src/BasicHelp.vue index 9b74d9c82..4020e572e 100644 --- a/src/components/Basic/src/BasicHelp.vue +++ b/src/components/Basic/src/BasicHelp.vue @@ -48,7 +48,9 @@ setup(props, { slots }) { const { prefixCls } = useDesign('basic-help') - const getTooltipStyle = computed((): CSSProperties => ({ color: props.color, fontSize: props.fontSize })) + const getTooltipStyle = computed( + (): CSSProperties => ({ color: props.color, fontSize: props.fontSize }), + ) const getOverlayStyle = computed((): CSSProperties => ({ maxWidth: props.maxWidth })) diff --git a/src/components/CodeEditor/src/codemirror/CodeMirror.vue b/src/components/CodeEditor/src/codemirror/CodeMirror.vue index 2b539eb92..b4c0ac956 100644 --- a/src/components/CodeEditor/src/codemirror/CodeMirror.vue +++ b/src/components/CodeEditor/src/codemirror/CodeMirror.vue @@ -7,7 +7,16 @@