From 68aabef30ae118651bde9f8313ae54f152f97bda Mon Sep 17 00:00:00 2001 From: BeADre Date: Tue, 26 Jan 2021 09:59:44 +0800 Subject: [PATCH 1/6] feat(switch): add validation --- packages/varlet-ui/src/form/example/index.vue | 11 ++- packages/varlet-ui/src/styles/var.less | 2 +- packages/varlet-ui/src/switch/Switch.vue | 87 ++++++++++++++----- .../varlet-ui/src/switch/example/index.vue | 5 +- packages/varlet-ui/src/switch/props.ts | 9 ++ packages/varlet-ui/src/switch/provide.ts | 3 + packages/varlet-ui/src/switch/switch.less | 24 +++-- 7 files changed, 110 insertions(+), 31 deletions(-) create mode 100644 packages/varlet-ui/src/switch/provide.ts diff --git a/packages/varlet-ui/src/form/example/index.vue b/packages/varlet-ui/src/form/example/index.vue index 7f0191c61bc..c211dbffe36 100644 --- a/packages/varlet-ui/src/form/example/index.vue +++ b/packages/varlet-ui/src/form/example/index.vue @@ -3,14 +3,14 @@ @@ -51,6 +51,10 @@ 打游戏 同意 +

+ 透视锁头 + +

清空表单 清空验证 @@ -71,6 +75,7 @@ import Checkbox from '../../checkbox' import RadioGroup from '../../radio-group' import Radio from '../../radio' import Button from '../../button' +import Switch from '../../switch' export default defineComponent({ name: 'FormExample', @@ -83,6 +88,7 @@ export default defineComponent({ [RadioGroup.name]: RadioGroup, [Radio.name]: Radio, [Option.name]: Option, + [Switch.name]: Switch, [Button.name]: Button, }, setup() { @@ -92,6 +98,7 @@ export default defineComponent({ department: undefined, gender: undefined, confirm: false, + open: false, group: [], skill: [], like: [], diff --git a/packages/varlet-ui/src/styles/var.less b/packages/varlet-ui/src/styles/var.less index 23209df30a0..dd210196f92 100644 --- a/packages/varlet-ui/src/styles/var.less +++ b/packages/varlet-ui/src/styles/var.less @@ -15,6 +15,6 @@ @color-info: #0097a7; @color-success: #43a047; @color-warning: #ff6f00; -@color-danger: #e53935; +@color-danger: #ed5f59; @color-background-base: #f5f5f5; @color-font-md: #888; diff --git a/packages/varlet-ui/src/switch/Switch.vue b/packages/varlet-ui/src/switch/Switch.vue index edb6a255f2e..bc0cdbbf950 100644 --- a/packages/varlet-ui/src/switch/Switch.vue +++ b/packages/varlet-ui/src/switch/Switch.vue @@ -1,34 +1,43 @@ diff --git a/packages/varlet-ui/src/expansion-panel/provide.ts b/packages/varlet-ui/src/expansion-panel/provide.ts index 9c1efe3b766..86d828e4a4d 100644 --- a/packages/varlet-ui/src/expansion-panel/provide.ts +++ b/packages/varlet-ui/src/expansion-panel/provide.ts @@ -1,8 +1,7 @@ import { ComputedRef } from 'vue' export interface ExpansionPanelProvider { - index: ComputedRef - name: ComputedRef - init(accordion: boolean): void - toggle(isShow?: boolean, initOrAccordion?: boolean): void + index: ComputedRef + name: ComputedRef + init(accordion: boolean, show: boolean): void } diff --git a/packages/varlet-ui/src/expansion-panels/ExpansionPanels.vue b/packages/varlet-ui/src/expansion-panels/ExpansionPanels.vue index 43097aa89be..816b9468b0b 100644 --- a/packages/varlet-ui/src/expansion-panels/ExpansionPanels.vue +++ b/packages/varlet-ui/src/expansion-panels/ExpansionPanels.vue @@ -1,77 +1,122 @@ diff --git a/packages/varlet-ui/src/expansion-panels/example/index.vue b/packages/varlet-ui/src/expansion-panels/example/index.vue index 131406e617a..14c581493cc 100644 --- a/packages/varlet-ui/src/expansion-panels/example/index.vue +++ b/packages/varlet-ui/src/expansion-panels/example/index.vue @@ -1,53 +1,53 @@ diff --git a/packages/varlet-ui/src/expansion-panels/props.ts b/packages/varlet-ui/src/expansion-panels/props.ts index ee2d24e8b71..e77466e8923 100644 --- a/packages/varlet-ui/src/expansion-panels/props.ts +++ b/packages/varlet-ui/src/expansion-panels/props.ts @@ -1,21 +1,21 @@ import { PropType } from 'vue' export const props = { - modelValue: { - type: [Array, String, Number] as PropType>, - }, - accordion: { - type: Boolean, - default: false, - }, - onChange: { - type: Function, - }, - offset: { - type: Boolean, - default: true, - }, - 'onUpdate:modelValue': { - type: Function, - }, + modelValue: { + type: [Array, String, Number] as PropType>, + }, + accordion: { + type: Boolean, + default: false, + }, + onChange: { + type: Function, + }, + offset: { + type: Boolean, + default: true, + }, + 'onUpdate:modelValue': { + type: Function, + }, } diff --git a/packages/varlet-ui/src/expansion-panels/provide.ts b/packages/varlet-ui/src/expansion-panels/provide.ts index 8cd5ea2b220..8d090420961 100644 --- a/packages/varlet-ui/src/expansion-panels/provide.ts +++ b/packages/varlet-ui/src/expansion-panels/provide.ts @@ -1,9 +1,9 @@ import { ComputedRef } from 'vue' export interface ExpansionPanelsProvider { - active: ComputedRef | undefined> - offset: ComputedRef - updateItem: (value: number | string | undefined, isExpand: boolean) => void + active: ComputedRef | undefined | null> + offset: ComputedRef + updateItem: (value: number | string | undefined, isExpand: boolean) => void } export const EXPANSION_PANELS_BIND_EXPANSION_PANEL_KEY = Symbol('EXPANSION_PANELS_BIND_EXPANSION_PANEL_KEY') From 01de29cba46d96b579d8d60c882cd4b89618e657 Mon Sep 17 00:00:00 2001 From: BeADre Date: Thu, 28 Jan 2021 01:19:06 +0800 Subject: [PATCH 5/6] style: modify tab to space --- package.json | 4 +- packages/varlet-cli/site/mobile/App.vue | 74 +- .../site/mobile/components/AppType.vue | 14 +- packages/varlet-cli/site/mobile/main.ts | 4 +- packages/varlet-cli/site/pc/App.vue | 802 +++++++++--------- packages/varlet-cli/site/pc/main.ts | 8 +- packages/varlet-cli/src/commands/build.ts | 16 +- packages/varlet-cli/src/commands/compile.ts | 78 +- packages/varlet-cli/src/commands/create.ts | 48 +- packages/varlet-cli/src/commands/dev.ts | 64 +- .../varlet-cli/src/compiler/compileModule.ts | 90 +- .../varlet-cli/src/compiler/compileRoutes.ts | 84 +- .../varlet-cli/src/compiler/compileScript.ts | 120 +-- .../varlet-cli/src/compiler/compileStyle.ts | 54 +- .../varlet-cli/src/config/varlet.config.ts | 10 +- .../src/config/webpack.base.config.ts | 265 +++--- .../src/config/webpack.dev.config.ts | 70 +- .../src/config/webpack.umd.config.ts | 54 +- packages/varlet-cli/src/less.d.ts | 6 +- packages/varlet-cli/src/shared/constant.ts | 5 +- packages/varlet-cli/src/shared/fsUtils.ts | 56 +- packages/varlet-cli/varlet.default.config.js | 40 +- packages/varlet-eslint-config/index.js | 126 +-- packages/varlet-icons/lib/index.js | 66 +- packages/varlet-icons/varlet-icons.config.js | 8 +- packages/varlet-markdown-loader/index.js | 34 +- packages/varlet-touch-emulator/index.js | 84 +- .../varlet-ui/src/badge/example/index.vue | 56 +- packages/varlet-ui/src/badge/props.ts | 14 +- packages/varlet-ui/src/button/Button.vue | 48 +- .../varlet-ui/src/button/example/index.vue | 32 +- packages/varlet-ui/src/button/index.ts | 2 +- packages/varlet-ui/src/button/props.ts | 128 +-- .../src/checkbox-group/CheckboxGroup.vue | 166 ++-- .../checkbox-group/__tests__/index.spec.js | 4 +- .../src/checkbox-group/example/index.vue | 8 +- .../varlet-ui/src/checkbox-group/index.ts | 2 +- .../varlet-ui/src/checkbox-group/props.ts | 50 +- packages/varlet-ui/src/checkbox/Checkbox.vue | 226 ++--- .../varlet-ui/src/checkbox/example/index.vue | 40 +- packages/varlet-ui/src/checkbox/index.ts | 2 +- packages/varlet-ui/src/checkbox/props.ts | 92 +- packages/varlet-ui/src/chip/Chip.vue | 48 +- .../src/chip/__tests__/index.spec.js | 4 +- .../src/chip/chip/__tests__/index.spec.js | 4 +- packages/varlet-ui/src/chip/chip/index.ts | 2 +- packages/varlet-ui/src/chip/chip/props.ts | 40 +- packages/varlet-ui/src/chip/example/index.vue | 46 +- packages/varlet-ui/src/chip/index.ts | 2 +- packages/varlet-ui/src/chip/props.ts | 40 +- packages/varlet-ui/src/dialog/Dialog.vue | 134 +-- packages/varlet-ui/src/dialog/index.ts | 50 +- packages/varlet-ui/src/dialog/props.ts | 168 ++-- .../varlet-ui/src/expansion-panel/index.ts | 2 +- .../varlet-ui/src/expansion-panel/props.ts | 28 +- .../src/expansion-panels/ExpansionPanels.vue | 1 - .../varlet-ui/src/expansion-panels/index.ts | 2 +- .../src/form-details/FormDetails.vue | 4 +- .../src/form-details/example/index.vue | 8 +- packages/varlet-ui/src/form-details/index.ts | 2 +- packages/varlet-ui/src/form-details/props.ts | 16 +- packages/varlet-ui/src/form/Form.vue | 50 +- packages/varlet-ui/src/form/example/index.vue | 74 +- packages/varlet-ui/src/form/index.ts | 2 +- packages/varlet-ui/src/form/props.ts | 16 +- packages/varlet-ui/src/icon/Icon.vue | 70 +- packages/varlet-ui/src/icon/example/index.vue | 106 +-- packages/varlet-ui/src/icon/index.ts | 2 +- packages/varlet-ui/src/icon/props.ts | 22 +- packages/varlet-ui/src/image/Image.vue | 44 +- .../varlet-ui/src/image/example/index.vue | 32 +- packages/varlet-ui/src/image/props.ts | 84 +- .../src/index-anchor/IndexAnchor.vue | 88 +- packages/varlet-ui/src/index-anchor/index.ts | 2 +- packages/varlet-ui/src/index-anchor/props.ts | 6 +- packages/varlet-ui/src/index-bar/IndexBar.vue | 132 +-- .../varlet-ui/src/index-bar/example/index.vue | 44 +- packages/varlet-ui/src/index-bar/index.ts | 2 +- packages/varlet-ui/src/index-bar/props.ts | 50 +- packages/varlet-ui/src/input/Input.vue | 288 +++---- .../varlet-ui/src/input/example/index.vue | 44 +- packages/varlet-ui/src/input/props.ts | 204 ++--- packages/varlet-ui/src/lazy/index.ts | 282 +++--- packages/varlet-ui/src/loading/Loading.vue | 4 +- .../varlet-ui/src/loading/example/index.vue | 8 +- packages/varlet-ui/src/loading/index.ts | 2 +- packages/varlet-ui/src/loading/props.ts | 46 +- packages/varlet-ui/src/menu/Menu.vue | 118 +-- packages/varlet-ui/src/menu/index.ts | 2 +- packages/varlet-ui/src/menu/props.ts | 48 +- packages/varlet-ui/src/option/Option.vue | 92 +- .../varlet-ui/src/option/example/index.vue | 8 +- packages/varlet-ui/src/option/index.ts | 2 +- packages/varlet-ui/src/option/props.ts | 16 +- packages/varlet-ui/src/popup/index.ts | 2 +- packages/varlet-ui/src/progress/Progress.vue | 64 +- .../varlet-ui/src/progress/example/index.vue | 46 +- packages/varlet-ui/src/progress/index.ts | 2 +- packages/varlet-ui/src/progress/props.ts | 102 +-- .../src/pull-refresh/PullRefresh.vue | 202 ++--- .../src/pull-refresh/example/index.vue | 44 +- packages/varlet-ui/src/pull-refresh/index.ts | 2 +- packages/varlet-ui/src/pull-refresh/props.ts | 74 +- .../varlet-ui/src/radio-group/RadioGroup.vue | 118 +-- .../src/radio-group/example/index.vue | 8 +- packages/varlet-ui/src/radio-group/index.ts | 2 +- packages/varlet-ui/src/radio-group/props.ts | 42 +- packages/varlet-ui/src/radio/Radio.vue | 202 ++--- .../varlet-ui/src/radio/example/index.vue | 26 +- packages/varlet-ui/src/radio/index.ts | 2 +- packages/varlet-ui/src/radio/props.ts | 92 +- packages/varlet-ui/src/rate/Rate.vue | 148 ++-- packages/varlet-ui/src/rate/props.ts | 154 ++-- .../varlet-ui/src/ripple/example/index.vue | 16 +- packages/varlet-ui/src/ripple/index.ts | 196 ++--- packages/varlet-ui/src/select/Select.vue | 450 +++++----- .../varlet-ui/src/select/example/index.vue | 32 +- packages/varlet-ui/src/select/index.ts | 2 +- packages/varlet-ui/src/select/props.ts | 186 ++-- packages/varlet-ui/src/skeleton/Skeleton.vue | 4 +- .../varlet-ui/src/skeleton/example/index.vue | 16 +- packages/varlet-ui/src/skeleton/index.ts | 2 +- packages/varlet-ui/src/skeleton/props.ts | 92 +- packages/varlet-ui/src/slider/Slider.vue | 494 +++++------ .../varlet-ui/src/slider/example/index.vue | 72 +- packages/varlet-ui/src/slider/index.ts | 2 +- packages/varlet-ui/src/slider/props.ts | 178 ++-- packages/varlet-ui/src/snackbar/Snackbar.vue | 22 +- packages/varlet-ui/src/snackbar/core.vue | 150 ++-- .../varlet-ui/src/snackbar/example/index.vue | 380 ++++----- packages/varlet-ui/src/snackbar/index.ts | 282 +++--- packages/varlet-ui/src/snackbar/props.ts | 160 ++-- packages/varlet-ui/src/sticky/Sticky.vue | 168 ++-- .../varlet-ui/src/sticky/example/index.vue | 26 +- packages/varlet-ui/src/sticky/index.ts | 2 +- packages/varlet-ui/src/sticky/props.ts | 26 +- packages/varlet-ui/src/switch/Switch.vue | 142 ++-- .../varlet-ui/src/switch/example/index.vue | 32 +- packages/varlet-ui/src/switch/index.ts | 2 +- packages/varlet-ui/src/switch/props.ts | 88 +- packages/varlet-ui/src/tab-item/TabItem.vue | 72 +- .../varlet-ui/src/tab-item/example/index.vue | 8 +- packages/varlet-ui/src/tab-item/index.ts | 2 +- packages/varlet-ui/src/tab-item/props.ts | 6 +- packages/varlet-ui/src/tab/Tab.vue | 110 +-- packages/varlet-ui/src/tab/example/index.vue | 8 +- packages/varlet-ui/src/tab/index.ts | 2 +- packages/varlet-ui/src/tab/props.ts | 20 +- .../varlet-ui/src/tabs-items/TabsItems.vue | 156 ++-- .../src/tabs-items/example/index.vue | 8 +- packages/varlet-ui/src/tabs-items/index.ts | 2 +- packages/varlet-ui/src/tabs-items/props.ts | 14 +- packages/varlet-ui/src/tabs/Tabs.vue | 198 ++--- packages/varlet-ui/src/tabs/example/index.vue | 210 ++--- packages/varlet-ui/src/tabs/index.ts | 2 +- packages/varlet-ui/src/tabs/props.ts | 124 +-- packages/varlet-ui/src/utils/components.ts | 370 ++++---- packages/varlet-ui/src/utils/elements.ts | 90 +- packages/varlet-ui/src/utils/shared.ts | 120 +-- packages/varlet-ui/varlet.config.js | 404 ++++----- 160 files changed, 6101 insertions(+), 6124 deletions(-) diff --git a/package.json b/package.json index 3bbe1d15006..ce647611616 100644 --- a/package.json +++ b/package.json @@ -27,9 +27,9 @@ } }, "lint-staged": { - "*.{ts,tsx,js,vue,scss,less}": "prettier --write", + "*.{ts,tsx,js,vue,less}": "prettier --write", "*.{ts,tsx,js,vue}": "eslint --fix", - "*.{vue,css,scss}": "stylelint --fix" + "*.{vue,css}": "stylelint --fix" }, "eslintConfig": { "root": true, diff --git a/packages/varlet-cli/site/mobile/App.vue b/packages/varlet-cli/site/mobile/App.vue index 755c476b730..16767d77414 100644 --- a/packages/varlet-cli/site/mobile/App.vue +++ b/packages/varlet-cli/site/mobile/App.vue @@ -1,61 +1,61 @@ diff --git a/packages/varlet-cli/site/mobile/components/AppType.vue b/packages/varlet-cli/site/mobile/components/AppType.vue index f7977d07c33..c45bd0dcc92 100644 --- a/packages/varlet-cli/site/mobile/components/AppType.vue +++ b/packages/varlet-cli/site/mobile/components/AppType.vue @@ -1,21 +1,21 @@ diff --git a/packages/varlet-cli/site/mobile/main.ts b/packages/varlet-cli/site/mobile/main.ts index d47fd4d538e..207aa3d2c87 100644 --- a/packages/varlet-cli/site/mobile/main.ts +++ b/packages/varlet-cli/site/mobile/main.ts @@ -7,8 +7,8 @@ import AppType from './components/AppType.vue' import routes from './routes' const router = createRouter({ - history: createWebHashHistory(), - routes, + history: createWebHashHistory(), + routes, }) const app = createApp(App as any) diff --git a/packages/varlet-cli/site/pc/App.vue b/packages/varlet-cli/site/pc/App.vue index a98a3a955ea..0db8420b23a 100644 --- a/packages/varlet-cli/site/pc/App.vue +++ b/packages/varlet-cli/site/pc/App.vue @@ -1,426 +1,416 @@ diff --git a/packages/varlet-cli/site/pc/main.ts b/packages/varlet-cli/site/pc/main.ts index f08f6590f5a..f9d903191e4 100644 --- a/packages/varlet-cli/site/pc/main.ts +++ b/packages/varlet-cli/site/pc/main.ts @@ -8,12 +8,12 @@ import config from '@config' const defaultConfig = require('../../varlet.default.config.js') const mergeConfig = { - ...defaultConfig, - ...config, + ...defaultConfig, + ...config, } const router = createRouter({ - history: createWebHashHistory(), - routes, + history: createWebHashHistory(), + routes, }) const app = createApp(App as any) diff --git a/packages/varlet-cli/src/commands/build.ts b/packages/varlet-cli/src/commands/build.ts index 29099e7fc74..396df53e325 100644 --- a/packages/varlet-cli/src/commands/build.ts +++ b/packages/varlet-cli/src/commands/build.ts @@ -7,16 +7,16 @@ import { VARLET_CONFIG } from '../shared/constant' import { ensureConfigFile } from '../shared/fsUtils' export async function build() { - setProd() + setProd() - ensureConfigFile(VARLET_CONFIG) + ensureConfigFile(VARLET_CONFIG) - await Promise.all([buildMobileSiteRoutes(), buildPcSiteRoutes()]) + await Promise.all([buildMobileSiteRoutes(), buildPcSiteRoutes()]) - const config = getBuildConfig() + const config = getBuildConfig() - webpack(config, (err, stats: Stats) => { - err && logger.error(err.toString()) - stats?.hasErrors() && logger.error(stats) - }) + webpack(config, (err, stats: Stats) => { + err && logger.error(err.toString()) + stats?.hasErrors() && logger.error(stats) + }) } diff --git a/packages/varlet-cli/src/commands/compile.ts b/packages/varlet-cli/src/commands/compile.ts index 2b614ae36c8..782156e6c9b 100644 --- a/packages/varlet-cli/src/commands/compile.ts +++ b/packages/varlet-cli/src/commands/compile.ts @@ -9,58 +9,58 @@ import { parse } from 'path' import { compileLibraryEntry } from '../compiler/compileScript' export function removeDir() { - return Promise.all([remove(ES_DIR), remove(CJS_DIR), remove(UMD_DIR)]) + return Promise.all([remove(ES_DIR), remove(CJS_DIR), remove(UMD_DIR)]) } export async function recompile(changedRawPath: string) { - const changedESPath = changedRawPath.replace('src', 'es') - const changedCjsPath = changedRawPath.replace('src', 'cjs') + const changedESPath = changedRawPath.replace('src', 'es') + const changedCjsPath = changedRawPath.replace('src', 'cjs') - const { ext, dir: changedRawDir } = parse(changedRawPath) - const { dir: changedEsDir } = parse(changedESPath) - const { dir: changedCjsDir } = parse(changedCjsPath) + const { ext, dir: changedRawDir } = parse(changedRawPath) + const { dir: changedEsDir } = parse(changedESPath) + const { dir: changedCjsDir } = parse(changedCjsPath) - if (ext === '.vue') { - // style deps collection - await Promise.all([remove(changedEsDir), remove(changedCjsDir)]) - await Promise.all([copy(changedRawDir, changedEsDir), copy(changedRawDir, changedCjsDir)]) - await Promise.all([compileDir(changedEsDir), compileDir(changedCjsDir, 'cjs')]) - } else { - await Promise.all([copy(changedRawDir, changedESPath), copy(changedRawDir, changedCjsPath)]) - await Promise.all([compileFile(changedESPath), compileFile(changedCjsPath, 'cjs')]) - } + if (ext === '.vue') { + // style deps collection + await Promise.all([remove(changedEsDir), remove(changedCjsDir)]) + await Promise.all([copy(changedRawDir, changedEsDir), copy(changedRawDir, changedCjsDir)]) + await Promise.all([compileDir(changedEsDir), compileDir(changedCjsDir, 'cjs')]) + } else { + await Promise.all([copy(changedRawDir, changedESPath), copy(changedRawDir, changedCjsPath)]) + await Promise.all([compileFile(changedESPath), compileFile(changedCjsPath, 'cjs')]) + } - const [componentNames, exportDirNames]: Array> = await Promise.all([ - getComponentNames(), - getExportDirNames(), - ]) - await Promise.all([ - compileLibraryEntry(ES_DIR, componentNames, exportDirNames), - compileLibraryEntry(CJS_DIR, componentNames, exportDirNames, 'cjs'), - ]) + const [componentNames, exportDirNames]: Array> = await Promise.all([ + getComponentNames(), + getExportDirNames(), + ]) + await Promise.all([ + compileLibraryEntry(ES_DIR, componentNames, exportDirNames), + compileLibraryEntry(CJS_DIR, componentNames, exportDirNames, 'cjs'), + ]) } export function handleFilesChange() { - watch(SRC_DIR).on('change', async (path: string) => { - if (isExampleDir(path) || isTestsDir(path)) { - return - } - logger.info(`${path} has changed`) - await recompile(path) - }) + watch(SRC_DIR).on('change', async (path: string) => { + if (isExampleDir(path) || isTestsDir(path)) { + return + } + logger.info(`${path} has changed`) + await recompile(path) + }) } export async function compile(cmd: { watch: boolean }) { - const s = ora('Compile start for ES & CJS & UMD').start() + const s = ora('Compile start for ES & CJS & UMD').start() - await removeDir() - await Promise.all([compileModule(), compileModule('cjs')]) - await compileModule('umd') + await removeDir() + await Promise.all([compileModule(), compileModule('cjs')]) + await compileModule('umd') - s.succeed('Compile success!') + s.succeed('Compile success!') - if (cmd.watch) { - handleFilesChange() - logger.info('i will watching your files change') - } + if (cmd.watch) { + handleFilesChange() + logger.info('i will watching your files change') + } } diff --git a/packages/varlet-cli/src/commands/create.ts b/packages/varlet-cli/src/commands/create.ts index 61eda593cb0..9e44a88190a 100644 --- a/packages/varlet-cli/src/commands/create.ts +++ b/packages/varlet-cli/src/commands/create.ts @@ -6,9 +6,9 @@ import { DOCS_DIR_NAME, EXAMPLE_DIR_NAME, SRC_DIR, TESTS_DIR_NAME } from '../sha import { getVarletConfig } from '../config/varlet.config' export async function create(name: string) { - const varletConfig = getVarletConfig() - const namespace = accessProperty(varletConfig, 'namespace') - const vueTemplate = `\ + const varletConfig = getVarletConfig() + const namespace = accessProperty(varletConfig, 'namespace') + const vueTemplate = `\ @@ -27,7 +27,7 @@ export default defineComponent({ } ` - const indexTemplate = `\ + const indexTemplate = `\ import { App } from 'vue' import ${bigCamelize(name)} from './${bigCamelize(name)}.vue' @@ -37,7 +37,7 @@ ${bigCamelize(name)}.install = function(app: App) { export default ${bigCamelize(name)} ` - const testsTemplate = `\ + const testsTemplate = `\ const ${bigCamelize(name)} = require('../../../cjs/${name}').default const { render } = require('@testing-library/vue') @@ -46,7 +46,7 @@ test('test ${camelize(name)}', async () => { console.log(wrapper) }) ` - const exampleTemplate = `\ + const exampleTemplate = `\ @@ -69,24 +69,24 @@ export default defineComponent({ } ` - const componentDir = resolve(SRC_DIR, name) - const testsDir = resolve(SRC_DIR, name, TESTS_DIR_NAME) - const exampleDir = resolve(SRC_DIR, name, EXAMPLE_DIR_NAME) - const docsDir = resolve(SRC_DIR, name, DOCS_DIR_NAME) + const componentDir = resolve(SRC_DIR, name) + const testsDir = resolve(SRC_DIR, name, TESTS_DIR_NAME) + const exampleDir = resolve(SRC_DIR, name, EXAMPLE_DIR_NAME) + const docsDir = resolve(SRC_DIR, name, DOCS_DIR_NAME) - if (pathExistsSync(componentDir)) { - logger.error('component directory is existed') - return - } - await Promise.all([mkdirs(componentDir), mkdirs(testsDir), mkdirs(exampleDir), mkdirs(docsDir)]) - await Promise.all([ - writeFile(resolve(componentDir, `${bigCamelize(name)}.vue`), vueTemplate), - writeFile(resolve(componentDir, 'index.ts'), indexTemplate), - writeFile(resolve(testsDir, 'index.spec.js'), testsTemplate), - writeFile(resolve(exampleDir, 'index.vue'), exampleTemplate), - writeFile(resolve(docsDir, 'zh_CN.md'), ''), - writeFile(resolve(docsDir, 'en_US.md'), ''), - ]) + if (pathExistsSync(componentDir)) { + logger.error('component directory is existed') + return + } + await Promise.all([mkdirs(componentDir), mkdirs(testsDir), mkdirs(exampleDir), mkdirs(docsDir)]) + await Promise.all([ + writeFile(resolve(componentDir, `${bigCamelize(name)}.vue`), vueTemplate), + writeFile(resolve(componentDir, 'index.ts'), indexTemplate), + writeFile(resolve(testsDir, 'index.spec.js'), testsTemplate), + writeFile(resolve(exampleDir, 'index.vue'), exampleTemplate), + writeFile(resolve(docsDir, 'zh_CN.md'), ''), + writeFile(resolve(docsDir, 'en_US.md'), ''), + ]) - logger.success('create success!') + logger.success('create success!') } diff --git a/packages/varlet-cli/src/commands/dev.ts b/packages/varlet-cli/src/commands/dev.ts index e7411bbe5de..49292ce60bd 100644 --- a/packages/varlet-cli/src/commands/dev.ts +++ b/packages/varlet-cli/src/commands/dev.ts @@ -10,42 +10,42 @@ import { SRC_DIR, VARLET_CONFIG } from '../shared/constant' import { ensureConfigFile } from '../shared/fsUtils' export function runDevServer(port: number, config: any) { - const { host } = config.devServer - config.devServer.port = port - const server = new WebpackDevServer(webpack(config), config.devServer) + const { host } = config.devServer + config.devServer.port = port + const server = new WebpackDevServer(webpack(config), config.devServer) - ;(server as any).showStatus = function () {} + ;(server as any).showStatus = function () {} - server.listen(port, host, (err?: Error) => { - if (err) { - logger.error(err.toString()) - return - } + server.listen(port, host, (err?: Error) => { + if (err) { + logger.error(err.toString()) + return + } - logger.success(`Server running at http://${host}:${port}`) - }) + logger.success(`Server running at http://${host}:${port}`) + }) } export async function dev() { - setDev() - - ensureConfigFile(VARLET_CONFIG) - ensureDirSync(SRC_DIR) - - await Promise.all([buildMobileSiteRoutes(), buildPcSiteRoutes()]) - - const config = getDevConfig() - const { port } = config.devServer - getPort( - { - port, - }, - (err: Error, port: number) => { - if (err) { - logger.error(err.toString()) - return - } - runDevServer(port, config) - } - ) + setDev() + + ensureConfigFile(VARLET_CONFIG) + ensureDirSync(SRC_DIR) + + await Promise.all([buildMobileSiteRoutes(), buildPcSiteRoutes()]) + + const config = getDevConfig() + const { port } = config.devServer + getPort( + { + port, + }, + (err: Error, port: number) => { + if (err) { + logger.error(err.toString()) + return + } + runDevServer(port, config) + } + ) } diff --git a/packages/varlet-cli/src/compiler/compileModule.ts b/packages/varlet-cli/src/compiler/compileModule.ts index 54b95d4a52a..27e97dc759e 100644 --- a/packages/varlet-cli/src/compiler/compileModule.ts +++ b/packages/varlet-cli/src/compiler/compileModule.ts @@ -11,67 +11,67 @@ import webpack, { Stats } from 'webpack' import logger from '../shared/logger' export function compileUMD() { - return new Promise((resolve, reject) => { - setProd() - const config = getUmdConfig() + return new Promise((resolve, reject) => { + setProd() + const config = getUmdConfig() - webpack(config, (err, stats: Stats) => { - if (err) { - logger.error(err.toString()) - reject() - } - if (stats?.hasErrors()) { - logger.error(stats) - reject() - } - if (!err && !stats?.hasErrors()) { - resolve() - } - }) - }) + webpack(config, (err, stats: Stats) => { + if (err) { + logger.error(err.toString()) + reject() + } + if (stats?.hasErrors()) { + logger.error(stats) + reject() + } + if (!err && !stats?.hasErrors()) { + resolve() + } + }) + }) } export async function compileDir(dir: string, modules: string | boolean = false) { - const dirs = await readdir(dir) + const dirs = await readdir(dir) - await Promise.all( - dirs.map((filename) => { - const filePath = resolve(dir, filename) + await Promise.all( + dirs.map((filename) => { + const filePath = resolve(dir, filename) - ;[TESTS_DIR_NAME, EXAMPLE_DIR_NAME, DOCS_DIR_NAME].includes(filename) && removeSync(filePath) + ;[TESTS_DIR_NAME, EXAMPLE_DIR_NAME, DOCS_DIR_NAME].includes(filename) && removeSync(filePath) - return compileFile(filePath, modules) - }) - ) + return compileFile(filePath, modules) + }) + ) } export async function compileFile(path: string, modules: string | boolean = false) { - isSFC(path) && (await compileSFC(path, modules)) - isScript(path) && (await compileScriptFile(path, modules)) - isLess(path) && (await compileLess(path)) - isDir(path) && (await compileDir(path)) + isSFC(path) && (await compileSFC(path, modules)) + isScript(path) && (await compileScriptFile(path, modules)) + isLess(path) && (await compileLess(path)) + isDir(path) && (await compileDir(path)) } export async function compileModule(modules: string | boolean = false) { - if (modules === 'umd') { - await compileUMD() - return - } + if (modules === 'umd') { + await compileUMD() + return + } - const MODULE_DIR: string = modules === 'cjs' ? CJS_DIR : ES_DIR - await copy(SRC_DIR, MODULE_DIR) - const moduleDir: string[] = await readdir(MODULE_DIR) + const MODULE_DIR: string = modules === 'cjs' ? CJS_DIR : ES_DIR + await copy(SRC_DIR, MODULE_DIR) + const moduleDir: string[] = await readdir(MODULE_DIR) - await Promise.all( - moduleDir.map((filename: string) => { - const path: string = resolve(MODULE_DIR, filename) + await Promise.all( + moduleDir.map((filename: string) => { + const path: string = resolve(MODULE_DIR, filename) - // cover babel-import-plugin - isDir(path) && ensureFileSync(resolve(path, './style/index.js')) + // cover babel-import-plugin + isDir(path) && ensureFileSync(resolve(path, './style/index.js')) - return isDir(path) ? compileDir(path, modules) : null - }) - ) + return isDir(path) ? compileDir(path, modules) : null + }) + ) - await compileLibraryEntry(MODULE_DIR, await getComponentNames(), await getExportDirNames(), modules) + await compileLibraryEntry(MODULE_DIR, await getComponentNames(), await getExportDirNames(), modules) } diff --git a/packages/varlet-cli/src/compiler/compileRoutes.ts b/packages/varlet-cli/src/compiler/compileRoutes.ts index 7bf1b0ee5e1..e72c9008a39 100644 --- a/packages/varlet-cli/src/compiler/compileRoutes.ts +++ b/packages/varlet-cli/src/compiler/compileRoutes.ts @@ -1,87 +1,87 @@ import slash from 'slash' import { - DOCS_DIR_NAME, - EXAMPLE_DIR_INDEX, - EXAMPLE_DIR_NAME, - SITE_MOBILE_ROUTES, - SITE_PC_ROUTES, - SRC_DIR, + DOCS_DIR_NAME, + EXAMPLE_DIR_INDEX, + EXAMPLE_DIR_NAME, + SITE_MOBILE_ROUTES, + SITE_PC_ROUTES, + SRC_DIR, } from '../shared/constant' import { pathExistsSync, readdir, readdirSync, writeFile } from 'fs-extra' import { resolve } from 'path' import { isDir } from '../shared/fsUtils' interface I18MDPath { - [key: string]: string[] + [key: string]: string[] } export function resolveMobileSiteRoutePath(exampleComponentPath: string): string { - const componentName: string = exampleComponentPath.replace(`/${EXAMPLE_DIR_NAME}/index.vue`, '').replace(/.*\//g, '') + const componentName: string = exampleComponentPath.replace(`/${EXAMPLE_DIR_NAME}/index.vue`, '').replace(/.*\//g, '') - return `/${componentName}` + return `/${componentName}` } export function resolvePcSiteRoutePath(mdPath: string, componentName: string): string { - const language = mdPath.split('/').slice(-1)[0].split('.')[0] - return `/${language}/${componentName}` + const language = mdPath.split('/').slice(-1)[0].split('.')[0] + return `/${language}/${componentName}` } export async function findExampleComponentPaths(): Promise { - const srcDir: string[] = await readdir(SRC_DIR) - return srcDir - .filter((filename: string) => pathExistsSync(resolve(SRC_DIR, filename, EXAMPLE_DIR_NAME, EXAMPLE_DIR_INDEX))) - .map((validFilename: string) => slash(resolve(SRC_DIR, validFilename, EXAMPLE_DIR_NAME, EXAMPLE_DIR_INDEX))) + const srcDir: string[] = await readdir(SRC_DIR) + return srcDir + .filter((filename: string) => pathExistsSync(resolve(SRC_DIR, filename, EXAMPLE_DIR_NAME, EXAMPLE_DIR_INDEX))) + .map((validFilename: string) => slash(resolve(SRC_DIR, validFilename, EXAMPLE_DIR_NAME, EXAMPLE_DIR_INDEX))) } export async function findDocsMDPaths(): Promise { - const srcDir: string[] = await readdir(SRC_DIR) - return srcDir - .filter((filename: string) => isDir(resolve(SRC_DIR, filename))) - .reduce((i18MdPath: I18MDPath, componentName: string) => { - const docsPath = resolve(SRC_DIR, componentName, DOCS_DIR_NAME) - isDir(docsPath) && - (i18MdPath[componentName] = readdirSync(docsPath).map((filename: string) => slash(resolve(docsPath, filename)))) - return i18MdPath - }, {}) + const srcDir: string[] = await readdir(SRC_DIR) + return srcDir + .filter((filename: string) => isDir(resolve(SRC_DIR, filename))) + .reduce((i18MdPath: I18MDPath, componentName: string) => { + const docsPath = resolve(SRC_DIR, componentName, DOCS_DIR_NAME) + isDir(docsPath) && + (i18MdPath[componentName] = readdirSync(docsPath).map((filename: string) => slash(resolve(docsPath, filename)))) + return i18MdPath + }, {}) } export async function buildMobileSiteRoutes() { - const exampleComponentPaths: string[] = await findExampleComponentPaths() - const routes = exampleComponentPaths.map( - (exampleComponentPath: string) => ` + const exampleComponentPaths: string[] = await findExampleComponentPaths() + const routes = exampleComponentPaths.map( + (exampleComponentPath: string) => ` { path: '${resolveMobileSiteRoutePath(exampleComponentPath)}', component: () => import('${exampleComponentPath}') }\ ` - ) + ) - await writeFile( - SITE_MOBILE_ROUTES, - `export default [\ + await writeFile( + SITE_MOBILE_ROUTES, + `export default [\ ${routes.join(',')} ]` - ) + ) } export async function buildPcSiteRoutes() { - const i18MdPath: I18MDPath = await findDocsMDPaths() + const i18MdPath: I18MDPath = await findDocsMDPaths() - const routes = Object.entries(i18MdPath).map(([componentName, mdPaths]) => { - return mdPaths.map((mdPath) => { - return ` + const routes = Object.entries(i18MdPath).map(([componentName, mdPaths]) => { + return mdPaths.map((mdPath) => { + return ` { path: '${resolvePcSiteRoutePath(mdPath, componentName)}', component: () => import('${mdPath}') }\ ` - }) - }) + }) + }) - await writeFile( - SITE_PC_ROUTES, - `export default [\ + await writeFile( + SITE_PC_ROUTES, + `export default [\ ${routes.join(',')} ]` - ) + ) } diff --git a/packages/varlet-cli/src/compiler/compileScript.ts b/packages/varlet-cli/src/compiler/compileScript.ts index 22ccf96d781..c609c252d25 100644 --- a/packages/varlet-cli/src/compiler/compileScript.ts +++ b/packages/varlet-cli/src/compiler/compileScript.ts @@ -10,66 +10,66 @@ export const IMPORT_TS_PATH_RE = /((? { - return `${p1}.js${p2}` - } - return script.replace(IMPORT_VUE_PATH_RE, replacer).replace(REQUIRE_VUE_PATH_RE, replacer) + const replacer = (_: any, p1: string, p2: string): string => { + return `${p1}.js${p2}` + } + return script.replace(IMPORT_VUE_PATH_RE, replacer).replace(REQUIRE_VUE_PATH_RE, replacer) } export function replaceTSExt(script: string) { - const replacer = (_: any, p1: string, p2: string): string => { - return `${p1}js${p2}` - } - return script.replace(IMPORT_TS_PATH_RE, replacer).replace(REQUIRE_TS_PATH_RE, replacer) + const replacer = (_: any, p1: string, p2: string): string => { + return `${p1}js${p2}` + } + return script.replace(IMPORT_TS_PATH_RE, replacer).replace(REQUIRE_TS_PATH_RE, replacer) } export async function compileScript(script: string, path: string, modules: string | boolean = false) { - let { code } = (await transformAsync(script, { - filename: replaceExt(path, '.ts'), - presets: [ - [ - require('@babel/preset-env'), - { - loose: true, - modules, - }, - ], - require('@babel/preset-typescript'), - ], - plugins: [require('@babel/plugin-transform-runtime')], - })) as BabelFileResult - code = replaceStyleExt(code as string) - code = replaceVueExt(code as string) - code = replaceTSExt(code as string) - removeSync(path) - writeFileSync(replaceExt(path, '.js'), code, 'utf8') + let { code } = (await transformAsync(script, { + filename: replaceExt(path, '.ts'), + presets: [ + [ + require('@babel/preset-env'), + { + loose: true, + modules, + }, + ], + require('@babel/preset-typescript'), + ], + plugins: [require('@babel/plugin-transform-runtime')], + })) as BabelFileResult + code = replaceStyleExt(code as string) + code = replaceVueExt(code as string) + code = replaceTSExt(code as string) + removeSync(path) + writeFileSync(replaceExt(path, '.js'), code, 'utf8') } export async function compileScriptFile(path: string, modules: string | boolean = false) { - const sources = readFileSync(path, 'utf-8') - await compileScript(sources, path, modules) + const sources = readFileSync(path, 'utf-8') + await compileScript(sources, path, modules) } export async function compileLibraryEntry( - dir: string, - componentNames: string[], - exportDirNames: string[], - modules: string | boolean = false + dir: string, + componentNames: string[], + exportDirNames: string[], + modules: string | boolean = false ) { - const imports = exportDirNames - .map((exportDirNames: string) => `import ${bigCamelize(exportDirNames)} from './${exportDirNames}'`) - .join('\n') - const requires = exportDirNames - .map((exportDirNames: string) => `var ${bigCamelize(exportDirNames)} = require('./${exportDirNames}')`) - .join('\n') - const install = `\ + const imports = exportDirNames + .map((exportDirNames: string) => `import ${bigCamelize(exportDirNames)} from './${exportDirNames}'`) + .join('\n') + const requires = exportDirNames + .map((exportDirNames: string) => `var ${bigCamelize(exportDirNames)} = require('./${exportDirNames}')`) + .join('\n') + const install = `\ function install(app) { ${exportDirNames - .map((exportDirName: string) => `${bigCamelize(exportDirName)}.install && app.use(${bigCamelize(exportDirName)})`) - .join('\n ')} + .map((exportDirName: string) => `${bigCamelize(exportDirName)}.install && app.use(${bigCamelize(exportDirName)})`) + .join('\n ')} } ` - const esExports = `\ + const esExports = `\ export { ${exportDirNames.map((exportDirName: string) => `${bigCamelize(exportDirName)}`).join(',\n ')} } @@ -79,42 +79,42 @@ export default { ${exportDirNames.map((exportDirName: string) => `${bigCamelize(exportDirName)}`).join(',\n ')}, }\ ` - const cjsExports = `\ + const cjsExports = `\ module.exports = { install, ${exportDirNames.map((exportDirName: string) => `${bigCamelize(exportDirName)}`).join(',\n ')} }\ ` - const template = `\ + const template = `\ ${modules === 'cjs' ? requires : imports}\n ${install} ${modules === 'cjs' ? cjsExports : esExports} ` - const cssImports = componentNames.map((componentName: string) => `import './${componentName}/style'`).join('\n') - const cssRequires = componentNames.map((componentName: string) => `require('./${componentName}/style')`).join('\n') - const styleTemplate = `\ + const cssImports = componentNames.map((componentName: string) => `import './${componentName}/style'`).join('\n') + const cssRequires = componentNames.map((componentName: string) => `require('./${componentName}/style')`).join('\n') + const styleTemplate = `\ ${modules === 'cjs' ? cssRequires : cssImports} ` - const umdTemplate = `\ + const umdTemplate = `\ ${modules === 'cjs' ? requires : imports}\n ${install} ${modules === 'cjs' ? cssRequires : cssImports}\n ${modules === 'cjs' ? cjsExports : esExports} ` - const lessImports = componentNames.map((componentName: string) => `import './${componentName}/style/less'`).join('\n') - const lessRequires = componentNames - .map((componentName: string) => `require('./${componentName}/style/less')`) - .join('\n') - const lessTemplate = `\ + const lessImports = componentNames.map((componentName: string) => `import './${componentName}/style/less'`).join('\n') + const lessRequires = componentNames + .map((componentName: string) => `require('./${componentName}/style/less')`) + .join('\n') + const lessTemplate = `\ ${modules === 'cjs' ? lessRequires : lessImports} ` - await Promise.all([ - writeFile(resolve(dir, 'index.js'), template, 'utf-8'), - writeFile(resolve(dir, 'umdIndex.js'), umdTemplate, 'utf-8'), - writeFile(resolve(dir, 'style.js'), styleTemplate, 'utf-8'), - writeFile(resolve(dir, 'less.js'), lessTemplate, 'utf-8'), - ]) + await Promise.all([ + writeFile(resolve(dir, 'index.js'), template, 'utf-8'), + writeFile(resolve(dir, 'umdIndex.js'), umdTemplate, 'utf-8'), + writeFile(resolve(dir, 'style.js'), styleTemplate, 'utf-8'), + writeFile(resolve(dir, 'less.js'), lessTemplate, 'utf-8'), + ]) } diff --git a/packages/varlet-cli/src/compiler/compileStyle.ts b/packages/varlet-cli/src/compiler/compileStyle.ts index 7ce971c713f..2175ca442ce 100644 --- a/packages/varlet-cli/src/compiler/compileStyle.ts +++ b/packages/varlet-cli/src/compiler/compileStyle.ts @@ -9,49 +9,49 @@ export const EMPTY_SPACE_RE = /[\s]+/g export const EMPTY_LINE_RE = /[\n\r]*/g class TildeResolver extends FileManager { - loadFile(filename: string, ...args: any[]) { - filename = filename.replace('~', '') - return super.loadFile.apply(this, [filename, ...args]) - } + loadFile(filename: string, ...args: any[]) { + filename = filename.replace('~', '') + return super.loadFile.apply(this, [filename, ...args]) + } } const TildeResolverPlugin = { - install(lessInstance: unknown, pluginManager: any) { - pluginManager.addFileManager(new TildeResolver()) - }, + install(lessInstance: unknown, pluginManager: any) { + pluginManager.addFileManager(new TildeResolver()) + }, } export function replaceStyleExt(script: string) { - const replacer = (_: any, p1: string, p2: string): string => { - return `${p1}css${p2}` - } - return script.replace(IMPORT_LESS_PATH_RE, replacer).replace(REQUIRE_LESS_PATH_RE, replacer) + const replacer = (_: any, p1: string, p2: string): string => { + return `${p1}css${p2}` + } + return script.replace(IMPORT_LESS_PATH_RE, replacer).replace(REQUIRE_LESS_PATH_RE, replacer) } export function clearEmptyLine(style: string) { - return style.replace(EMPTY_LINE_RE, '').replace(EMPTY_SPACE_RE, ' ') + return style.replace(EMPTY_LINE_RE, '').replace(EMPTY_SPACE_RE, ' ') } export async function compileLess(path: string) { - const source = readFileSync(path, 'utf-8') - const { css } = await render(source, { - filename: path, - plugins: [TildeResolverPlugin], - }) + const source = readFileSync(path, 'utf-8') + const { css } = await render(source, { + filename: path, + plugins: [TildeResolverPlugin], + }) - writeFileSync(replaceExt(path, '.css'), clearEmptyLine(css), 'utf-8') + writeFileSync(replaceExt(path, '.css'), clearEmptyLine(css), 'utf-8') } export function emitStyleEntry(path: string, modules: string | boolean = false) { - const { ext, dir, base } = parse(path) - const styleIndex: string = resolve(dir, './style/index.js') - const styleLess: string = resolve(dir, './style/less.js') - ensureFileSync(styleIndex) - ensureFileSync(styleLess) + const { ext, dir, base } = parse(path) + const styleIndex: string = resolve(dir, './style/index.js') + const styleLess: string = resolve(dir, './style/less.js') + ensureFileSync(styleIndex) + ensureFileSync(styleLess) - const emitPath = ext === '.css' ? styleIndex : styleLess - const emitScript = modules === 'cjs' ? `require('../${base}')\n` : `import '../${base}'\n` - const currentScript = readFileSync(emitPath, 'utf-8') + const emitPath = ext === '.css' ? styleIndex : styleLess + const emitScript = modules === 'cjs' ? `require('../${base}')\n` : `import '../${base}'\n` + const currentScript = readFileSync(emitPath, 'utf-8') - writeFileSync(emitPath, `${currentScript}${emitScript}`) + writeFileSync(emitPath, `${currentScript}${emitScript}`) } diff --git a/packages/varlet-cli/src/config/varlet.config.ts b/packages/varlet-cli/src/config/varlet.config.ts index dcfdb522b05..e66ecb0da03 100644 --- a/packages/varlet-cli/src/config/varlet.config.ts +++ b/packages/varlet-cli/src/config/varlet.config.ts @@ -4,9 +4,9 @@ import { VARLET_CONFIG } from '../shared/constant' const defaultConfig = require('../../varlet.default.config.js') export function getVarletConfig() { - const config = (pathExistsSync(VARLET_CONFIG) && require(VARLET_CONFIG)) || {} - return { - ...defaultConfig, - ...config, - } + const config = (pathExistsSync(VARLET_CONFIG) && require(VARLET_CONFIG)) || {} + return { + ...defaultConfig, + ...config, + } } diff --git a/packages/varlet-cli/src/config/webpack.base.config.ts b/packages/varlet-cli/src/config/webpack.base.config.ts index 7f0cc8051eb..e3efb21f1ef 100644 --- a/packages/varlet-cli/src/config/webpack.base.config.ts +++ b/packages/varlet-cli/src/config/webpack.base.config.ts @@ -1,12 +1,7 @@ import HtmlWebpackPlugin from 'html-webpack-plugin' import MiniCssExtractPlugin from 'mini-css-extract-plugin' import { resolve } from 'path' -import { - EXTENSIONS, - POSTCSS_CONFIG, - TS_CONFIG, - VARLET_CONFIG -} from '../shared/constant' +import { EXTENSIONS, POSTCSS_CONFIG, TS_CONFIG, VARLET_CONFIG } from '../shared/constant' import { createPostcssOptions } from './postcss.config' import { ForkTsCheckerWebpackPlugin } from 'fork-ts-checker-webpack-plugin/lib/ForkTsCheckerWebpackPlugin' import { VueLoaderPlugin } from 'vue-loader' @@ -19,154 +14,154 @@ import { getVarletConfig } from './varlet.config' export type URLLoaderType = 'image' | 'video' | 'audio' | 'font' export const commonTemplateOption = { - minify: { - removeAttributeQuotes: true, - collapseWhitespace: true, - }, - hash: true, + minify: { + removeAttributeQuotes: true, + collapseWhitespace: true, + }, + hash: true, } export function createURLLoaderOptions(type: URLLoaderType) { - return { - name: '[name].[hash:7].[ext]', - limit: 8 * 1024, - outputPath: `${type}s/`, - esModule: false, - } + return { + name: '[name].[hash:7].[ext]', + limit: 8 * 1024, + outputPath: `${type}s/`, + esModule: false, + } } export function createCSSLoaders() { - return [ - isDev() ? 'style-loader' : MiniCssExtractPlugin.loader, - 'css-loader', - { - loader: 'postcss-loader', - options: createPostcssOptions(POSTCSS_CONFIG), - }, - ] + return [ + isDev() ? 'style-loader' : MiniCssExtractPlugin.loader, + 'css-loader', + { + loader: 'postcss-loader', + options: createPostcssOptions(POSTCSS_CONFIG), + }, + ] } export function createBabelConfig() { - return { - loader: 'babel-loader', - options: { - presets: ['@babel/preset-env'], - plugins: ['@babel/plugin-transform-runtime'], - }, - } + return { + loader: 'babel-loader', + options: { + presets: ['@babel/preset-env'], + plugins: ['@babel/plugin-transform-runtime'], + }, + } } export function createBasePlugins(): WebpackPluginInstance[] { - const varletConfig = getVarletConfig() + const varletConfig = getVarletConfig() - const plugins: WebpackPluginInstance[] = [ - new VueLoaderPlugin(), - new HtmlWebpackPlugin({ - template: resolve(__dirname, '../../site/pc/index.html'), - filename: 'index.html', - chunks: ['pc'], - title: accessProperty(varletConfig, 'pc.title'), - logo: accessProperty(varletConfig, 'pc.logo'), - description: accessProperty(varletConfig, 'pc.description'), - ...commonTemplateOption, - }), - new HtmlWebpackPlugin({ - template: resolve(__dirname, '../../site/mobile/mobile.html'), - filename: 'mobile.html', - chunks: ['mobile'], - title: accessProperty(varletConfig, 'mobile.title'), - logo: accessProperty(varletConfig, 'mobile.logo'), - description: accessProperty(varletConfig, 'mobile.description'), - ...commonTemplateOption, - }), - ] + const plugins: WebpackPluginInstance[] = [ + new VueLoaderPlugin(), + new HtmlWebpackPlugin({ + template: resolve(__dirname, '../../site/pc/index.html'), + filename: 'index.html', + chunks: ['pc'], + title: accessProperty(varletConfig, 'pc.title'), + logo: accessProperty(varletConfig, 'pc.logo'), + description: accessProperty(varletConfig, 'pc.description'), + ...commonTemplateOption, + }), + new HtmlWebpackPlugin({ + template: resolve(__dirname, '../../site/mobile/mobile.html'), + filename: 'mobile.html', + chunks: ['mobile'], + title: accessProperty(varletConfig, 'mobile.title'), + logo: accessProperty(varletConfig, 'mobile.logo'), + description: accessProperty(varletConfig, 'mobile.description'), + ...commonTemplateOption, + }), + ] - pathExistsSync(TS_CONFIG) && plugins.push(new ForkTsCheckerWebpackPlugin()) + pathExistsSync(TS_CONFIG) && plugins.push(new ForkTsCheckerWebpackPlugin()) - return plugins + return plugins } export function createBaseConfig() { - return { - entry: { - pc: resolve(__dirname, '../../site/pc/main.ts'), - mobile: resolve(__dirname, '../../site/mobile/main.ts'), - }, - resolve: { - extensions: EXTENSIONS, - alias: { - '@config': VARLET_CONFIG, - }, - }, - module: { - rules: [ - { - test: /\.vue$/, - use: ['cache-loader', 'vue-loader'], - }, - { - test: /\.js$/, - use: ['cache-loader', createBabelConfig()], - exclude: /node_modules/, - }, - { - test: /\.ts$/, - use: [ - 'cache-loader', - createBabelConfig(), - { - loader: 'ts-loader', - options: { - appendTsSuffixTo: [/\.vue$/], + return { + entry: { + pc: resolve(__dirname, '../../site/pc/main.ts'), + mobile: resolve(__dirname, '../../site/mobile/main.ts'), + }, + resolve: { + extensions: EXTENSIONS, + alias: { + '@config': VARLET_CONFIG, + }, + }, + module: { + rules: [ + { + test: /\.vue$/, + use: ['cache-loader', 'vue-loader'], + }, + { + test: /\.js$/, + use: ['cache-loader', createBabelConfig()], + exclude: /node_modules/, + }, + { + test: /\.ts$/, + use: [ + 'cache-loader', + createBabelConfig(), + { + loader: 'ts-loader', + options: { + appendTsSuffixTo: [/\.vue$/], allowTsInNodeModules: true, compilerOptions: { - declaration: false - } + declaration: false, + }, }, - }, - ], - }, - { - test: /\.md$/, - use: ['vue-loader', '@varlet/markdown-loader'], - }, - { - test: /\.(png|jpg|gif|jpeg|svg)$/, - use: { - loader: 'url-loader', - options: createURLLoaderOptions('image'), - }, - }, - { - test: /\.(eot|ttf|woff|woff2)$/, - use: { - loader: 'url-loader', - options: createURLLoaderOptions('font'), - }, - }, - { - test: /\.(mp3|wav|ogg)$/, - use: { - loader: 'url-loader', - options: createURLLoaderOptions('audio'), - }, - }, - { - test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)$/, - use: { - loader: 'url-loader', - options: createURLLoaderOptions('video'), - }, - }, - { - test: /\.css$/, - use: createCSSLoaders(), - }, - { - test: /\.less$/, - use: [...createCSSLoaders(), 'less-loader'], - } - ], - }, - } + }, + ], + }, + { + test: /\.md$/, + use: ['vue-loader', '@varlet/markdown-loader'], + }, + { + test: /\.(png|jpg|gif|jpeg|svg)$/, + use: { + loader: 'url-loader', + options: createURLLoaderOptions('image'), + }, + }, + { + test: /\.(eot|ttf|woff|woff2)$/, + use: { + loader: 'url-loader', + options: createURLLoaderOptions('font'), + }, + }, + { + test: /\.(mp3|wav|ogg)$/, + use: { + loader: 'url-loader', + options: createURLLoaderOptions('audio'), + }, + }, + { + test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)$/, + use: { + loader: 'url-loader', + options: createURLLoaderOptions('video'), + }, + }, + { + test: /\.css$/, + use: createCSSLoaders(), + }, + { + test: /\.less$/, + use: [...createCSSLoaders(), 'less-loader'], + }, + ], + }, + } } diff --git a/packages/varlet-cli/src/config/webpack.dev.config.ts b/packages/varlet-cli/src/config/webpack.dev.config.ts index 64f606d436c..81d8fbcec15 100644 --- a/packages/varlet-cli/src/config/webpack.dev.config.ts +++ b/packages/varlet-cli/src/config/webpack.dev.config.ts @@ -5,39 +5,39 @@ import { getVarletConfig } from './varlet.config' import { accessProperty } from '../shared/fsUtils' export function getDevConfig() { - const varletConfig = getVarletConfig() - return merge(createBaseConfig() as any, { - mode: 'development', - devtool: 'source-map', - output: { - chunkFilename: 'js/[name].[chunkhash:8].js', - }, - devServer: { - port: accessProperty(varletConfig, 'port'), - host: accessProperty(varletConfig, 'host'), - publicPath: '/', - stats: 'errors-only', - disableHostCheck: true, - hot: true, - }, - optimization: { - splitChunks: { - cacheGroups: { - chunks: { - chunks: 'all', - minChunks: 2, - minSize: 0, - name: 'chunks', - }, - }, - }, - }, - plugins: [ - new WebpackBarPlugin({ - name: 'Site development building', - color: '#15DD6A', - }), - ...createBasePlugins(), - ], - }) + const varletConfig = getVarletConfig() + return merge(createBaseConfig() as any, { + mode: 'development', + devtool: 'source-map', + output: { + chunkFilename: 'js/[name].[chunkhash:8].js', + }, + devServer: { + port: accessProperty(varletConfig, 'port'), + host: accessProperty(varletConfig, 'host'), + publicPath: '/', + stats: 'errors-only', + disableHostCheck: true, + hot: true, + }, + optimization: { + splitChunks: { + cacheGroups: { + chunks: { + chunks: 'all', + minChunks: 2, + minSize: 0, + name: 'chunks', + }, + }, + }, + }, + plugins: [ + new WebpackBarPlugin({ + name: 'Site development building', + color: '#15DD6A', + }), + ...createBasePlugins(), + ], + }) } diff --git a/packages/varlet-cli/src/config/webpack.umd.config.ts b/packages/varlet-cli/src/config/webpack.umd.config.ts index 7987d7a4149..e880812149e 100644 --- a/packages/varlet-cli/src/config/webpack.umd.config.ts +++ b/packages/varlet-cli/src/config/webpack.umd.config.ts @@ -8,32 +8,32 @@ import { VueLoaderPlugin } from 'vue-loader' import MiniCssExtractPlugin from 'mini-css-extract-plugin' export function getUmdConfig() { - const varletConfig = getVarletConfig() - const namespace = accessProperty(varletConfig, 'namespace') + const varletConfig = getVarletConfig() + const namespace = accessProperty(varletConfig, 'namespace') - return merge(createBaseConfig() as any, { - mode: 'production', - entry: resolve(ES_DIR, 'umdIndex.js'), - output: { - path: UMD_DIR, - filename: `${namespace}.js`, - library: `${bigCamelize(namespace)}`, - libraryTarget: 'umd', - umdNamedDefine: true, - }, - externals: { - vue: { - root: 'Vue', - commonjs: 'vue', - commonjs2: 'vue', - amd: 'vue', - }, - }, - plugins: [ - new VueLoaderPlugin(), - new MiniCssExtractPlugin({ - filename: `${namespace}.css`, - }), - ], - }) + return merge(createBaseConfig() as any, { + mode: 'production', + entry: resolve(ES_DIR, 'umdIndex.js'), + output: { + path: UMD_DIR, + filename: `${namespace}.js`, + library: `${bigCamelize(namespace)}`, + libraryTarget: 'umd', + umdNamedDefine: true, + }, + externals: { + vue: { + root: 'Vue', + commonjs: 'vue', + commonjs2: 'vue', + amd: 'vue', + }, + }, + plugins: [ + new VueLoaderPlugin(), + new MiniCssExtractPlugin({ + filename: `${namespace}.css`, + }), + ], + }) } diff --git a/packages/varlet-cli/src/less.d.ts b/packages/varlet-cli/src/less.d.ts index 23dc5e09403..959fd710b4c 100644 --- a/packages/varlet-cli/src/less.d.ts +++ b/packages/varlet-cli/src/less.d.ts @@ -1,6 +1,6 @@ declare module 'less' { - declare const render: any - declare const FileManager: any + declare const render: any + declare const FileManager: any - export { render, FileManager } + export { render, FileManager } } diff --git a/packages/varlet-cli/src/shared/constant.ts b/packages/varlet-cli/src/shared/constant.ts index 6458f98050d..70a249f5338 100644 --- a/packages/varlet-cli/src/shared/constant.ts +++ b/packages/varlet-cli/src/shared/constant.ts @@ -9,10 +9,7 @@ export const SRC_DIR = resolve(CWD, 'src') export const ES_DIR = resolve(CWD, 'es') export const CJS_DIR = resolve(CWD, 'cjs') export const UMD_DIR = resolve(CWD, 'umd') -export const SITE_MOBILE_ROUTES = resolve( - __dirname, - '../../site/mobile/routes.ts' -) +export const SITE_MOBILE_ROUTES = resolve(__dirname, '../../site/mobile/routes.ts') export const SITE_PC_ROUTES = resolve(__dirname, '../../site/PC/routes.ts') export const EXAMPLE_DIR_NAME = 'example' export const DOCS_DIR_NAME = 'docs' diff --git a/packages/varlet-cli/src/shared/fsUtils.ts b/packages/varlet-cli/src/shared/fsUtils.ts index c0450b9d96a..18fe2f5dc04 100644 --- a/packages/varlet-cli/src/shared/fsUtils.ts +++ b/packages/varlet-cli/src/shared/fsUtils.ts @@ -3,77 +3,77 @@ import { ensureFileSync, lstatSync, pathExistsSync, readdir, readdirSync, writeF import { EXAMPLE_DIR_NAME, SRC_DIR, TESTS_DIR_NAME } from './constant' export function ensureConfigFile(path: string) { - if (!pathExistsSync(path)) { - ensureFileSync(path) - writeFileSync(path, 'module.exports = {}') - } + if (!pathExistsSync(path)) { + ensureFileSync(path) + writeFileSync(path, 'module.exports = {}') + } } export function accessProperty(target: any, operator: string) { - const keys: string[] = operator.split('.') - return keys.reduce((value: any, key: string) => { - if (value === null || value === undefined) { - return null - } - return value[key] || [] - }, target) + const keys: string[] = operator.split('.') + return keys.reduce((value: any, key: string) => { + if (value === null || value === undefined) { + return null + } + return value[key] || [] + }, target) } export async function getComponentNames(): Promise { - const srcDir: string[] = await readdir(SRC_DIR) - return srcDir.filter((filename: string) => isComponentDir(resolve(SRC_DIR, filename))) + const srcDir: string[] = await readdir(SRC_DIR) + return srcDir.filter((filename: string) => isComponentDir(resolve(SRC_DIR, filename))) } export async function getExportDirNames(): Promise { - const srcDir: string[] = await readdir(SRC_DIR) - return srcDir.filter((filename: string) => isExportDir(resolve(SRC_DIR, filename))) + const srcDir: string[] = await readdir(SRC_DIR) + return srcDir.filter((filename: string) => isExportDir(resolve(SRC_DIR, filename))) } export function isDir(path: string): boolean { - return pathExistsSync(path) && lstatSync(path).isDirectory() + return pathExistsSync(path) && lstatSync(path).isDirectory() } export function isSFC(path: string): boolean { - return pathExistsSync(path) && extname(path) === '.vue' + return pathExistsSync(path) && extname(path) === '.vue' } export function hasSFC(path: string): boolean { - const dir = readdirSync(path) - return dir.some((filename) => isSFC(resolve(path, filename))) + const dir = readdirSync(path) + return dir.some((filename) => isSFC(resolve(path, filename))) } export function isScript(path: string): boolean { - return (pathExistsSync(path) && extname(path) === '.js') || extname(path) === '.ts' + return (pathExistsSync(path) && extname(path) === '.js') || extname(path) === '.ts' } export function isLess(path: string): boolean { - return pathExistsSync(path) && extname(path) === '.less' + return pathExistsSync(path) && extname(path) === '.less' } export function isExampleDir(path: string): boolean { - return pathExistsSync(path) && parse(path).dir.endsWith(EXAMPLE_DIR_NAME) + return pathExistsSync(path) && parse(path).dir.endsWith(EXAMPLE_DIR_NAME) } export function isTestsDir(path: string): boolean { - return pathExistsSync(path) && parse(path).dir.endsWith(TESTS_DIR_NAME) + return pathExistsSync(path) && parse(path).dir.endsWith(TESTS_DIR_NAME) } export function isExportDir(path: string): boolean { - return pathExistsSync(resolve(path, 'index.js')) || pathExistsSync(resolve(path, 'index.ts')) + return pathExistsSync(resolve(path, 'index.js')) || pathExistsSync(resolve(path, 'index.ts')) } export function isComponentDir(path: string): boolean { - return hasSFC(path) && isExportDir(path) + return hasSFC(path) && isExportDir(path) } export function replaceExt(path: string, ext: string): string { - return path.replace(extname(path), ext) + return path.replace(extname(path), ext) } export function bigCamelize(str: string): string { - return camelize(str).replace(str.charAt(0), str.charAt(0).toUpperCase()) + return camelize(str).replace(str.charAt(0), str.charAt(0).toUpperCase()) } export function camelize(str: string): string { - return str.replace(/-(\w)/g, (_: any, p: string) => p.toUpperCase()) + return str.replace(/-(\w)/g, (_: any, p: string) => p.toUpperCase()) } diff --git a/packages/varlet-cli/varlet.default.config.js b/packages/varlet-cli/varlet.default.config.js index 426cb43ae5e..e2d4d195e8c 100644 --- a/packages/varlet-cli/varlet.default.config.js +++ b/packages/varlet-cli/varlet.default.config.js @@ -1,22 +1,22 @@ module.exports = { - namespace: 'var', - host: 'localhost', - title: 'varlet', - port: 8080, - pc: { - title: 'Varlet 组件库文档', - description: 'Varlet 组件库文档', - logo: 'https://cn.vuejs.org/images/logo.png', - header: { - i18nButton: { - zh_CN: 'En', - en_US: '中文', - }, - }, - }, - mobile: { - title: 'Varlet 组件库示例', - description: 'Varlet 组件库示例', - logo: 'https://cn.vuejs.org/images/logo.png', - }, + namespace: 'var', + host: 'localhost', + title: 'varlet', + port: 8080, + pc: { + title: 'Varlet 组件库文档', + description: 'Varlet 组件库文档', + logo: 'https://cn.vuejs.org/images/logo.png', + header: { + i18nButton: { + zh_CN: 'En', + en_US: '中文', + }, + }, + }, + mobile: { + title: 'Varlet 组件库示例', + description: 'Varlet 组件库示例', + logo: 'https://cn.vuejs.org/images/logo.png', + }, } diff --git a/packages/varlet-eslint-config/index.js b/packages/varlet-eslint-config/index.js index 9e82f8d00a7..5211f6e3dc6 100644 --- a/packages/varlet-eslint-config/index.js +++ b/packages/varlet-eslint-config/index.js @@ -1,65 +1,65 @@ module.exports = { - extends: [ - 'airbnb-base', - 'plugin:@typescript-eslint/recommended', - 'plugin:vue/vue3-recommended', - 'prettier', - 'prettier/vue', - ], - parserOptions: { - parser: '@typescript-eslint/parser', - ecmaVersion: 2020, - sourceType: 'module', - extraFileExtensions: ['.vue'], - }, - plugins: ['@typescript-eslint'], - env: { - es6: true, - node: true, - browser: true, - }, - rules: { - 'no-new': 'off', - 'no-shadow': 'off', - 'no-bitwise': 'off', - 'func-names': 'off', - 'no-console': 'off', - 'no-plusplus': 'off', - 'default-case': 'off', - 'prefer-template': 'off', - 'consistent-return': 'off', - 'no-param-reassign': 'off', - 'no-nested-ternary': 'off', - 'no-underscore-dangle': 'off', - 'no-unused-expressions': 'off', - 'no-restricted-globals': 'off', - 'no-use-before-define': 'off', - 'class-methods-use-this': 'off', - 'global-require': 'off', - 'prefer-destructuring': ['error', { object: true, array: false }], - // eslint-plugin-import - 'import/order': 'off', - 'import/extensions': 'off', - 'import/no-unresolved': 'off', - 'import/prefer-default-export': 'off', - 'import/no-extraneous-dependencies': 'off', - 'import/no-dynamic-require': 'off', - // eslint-plugin-vue - 'vue/comment-directive': 'off', - 'vue/no-v-html': 'off', - 'vue/attributes-order': 'off', - 'vue/require-default-prop': 'off', - 'vue/no-unused-components': 'off', - 'vue/require-explicit-emits': 'off', - // typescript-eslint - '@typescript-eslint/camelcase': 'off', - '@typescript-eslint/ban-ts-ignore': 'off', - '@typescript-eslint/no-var-requires': 'off', - '@typescript-eslint/no-extra-semi': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-empty-function': 'off', - '@typescript-eslint/no-non-null-assertion': 'off', - '@typescript-eslint/explicit-function-return-type': 'off', - '@typescript-eslint/explicit-module-boundary-types': 'off', - }, + extends: [ + 'airbnb-base', + 'plugin:@typescript-eslint/recommended', + 'plugin:vue/vue3-recommended', + 'prettier', + 'prettier/vue', + ], + parserOptions: { + parser: '@typescript-eslint/parser', + ecmaVersion: 2020, + sourceType: 'module', + extraFileExtensions: ['.vue'], + }, + plugins: ['@typescript-eslint'], + env: { + es6: true, + node: true, + browser: true, + }, + rules: { + 'no-new': 'off', + 'no-shadow': 'off', + 'no-bitwise': 'off', + 'func-names': 'off', + 'no-console': 'off', + 'no-plusplus': 'off', + 'default-case': 'off', + 'prefer-template': 'off', + 'consistent-return': 'off', + 'no-param-reassign': 'off', + 'no-nested-ternary': 'off', + 'no-underscore-dangle': 'off', + 'no-unused-expressions': 'off', + 'no-restricted-globals': 'off', + 'no-use-before-define': 'off', + 'class-methods-use-this': 'off', + 'global-require': 'off', + 'prefer-destructuring': ['error', { object: true, array: false }], + // eslint-plugin-import + 'import/order': 'off', + 'import/extensions': 'off', + 'import/no-unresolved': 'off', + 'import/prefer-default-export': 'off', + 'import/no-extraneous-dependencies': 'off', + 'import/no-dynamic-require': 'off', + // eslint-plugin-vue + 'vue/comment-directive': 'off', + 'vue/no-v-html': 'off', + 'vue/attributes-order': 'off', + 'vue/require-default-prop': 'off', + 'vue/no-unused-components': 'off', + 'vue/require-explicit-emits': 'off', + // typescript-eslint + '@typescript-eslint/camelcase': 'off', + '@typescript-eslint/ban-ts-ignore': 'off', + '@typescript-eslint/no-var-requires': 'off', + '@typescript-eslint/no-extra-semi': 'off', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-empty-function': 'off', + '@typescript-eslint/no-non-null-assertion': 'off', + '@typescript-eslint/explicit-function-return-type': 'off', + '@typescript-eslint/explicit-module-boundary-types': 'off', + }, } diff --git a/packages/varlet-icons/lib/index.js b/packages/varlet-icons/lib/index.js index b1cf58dbb32..33728b541ed 100755 --- a/packages/varlet-icons/lib/index.js +++ b/packages/varlet-icons/lib/index.js @@ -15,31 +15,31 @@ const formats = ['ttf', 'eot', 'woff', 'woff2'] const config = require(resolve(CWD, 'varlet-icons.config.js')) async function build() { - const { publicPath, namespace, fontName, fileName, fontWeight = 'normal', fontStyle = 'normal' } = config + const { publicPath, namespace, fontName, fileName, fontWeight = 'normal', fontStyle = 'normal' } = config - const { ttf, eot, woff, woff2 } = await webfont({ - files: `${SVG_DIR}/*.svg`, - fontName, - formats, - fontHeight: 512, - descent: 64, - }) + const { ttf, eot, woff, woff2 } = await webfont({ + files: `${SVG_DIR}/*.svg`, + fontName, + formats, + fontHeight: 512, + descent: 64, + }) - removeSync(DIST_DIR) + removeSync(DIST_DIR) - await Promise.all([ensureDir(FONTS_DIR), ensureDir(CSS_DIR)]) + await Promise.all([ensureDir(FONTS_DIR), ensureDir(CSS_DIR)]) - const icons = readdirSync(SVG_DIR).map((svgName) => { - const i = svgName.indexOf('-') - const extIndex = svgName.lastIndexOf('.') + const icons = readdirSync(SVG_DIR).map((svgName) => { + const i = svgName.indexOf('-') + const extIndex = svgName.lastIndexOf('.') - return { - name: svgName.slice(i + 1, extIndex), - pointCode: svgName.slice(1, i), - } - }) + return { + name: svgName.slice(i + 1, extIndex), + pointCode: svgName.slice(1, i), + } + }) - const cssTemplate = `\ + const cssTemplate = `\ @font-face { font-family: "${fontName}"; src: url("${publicPath}${fileName}-webfont.eot"); @@ -59,12 +59,12 @@ async function build() { } ${icons - .map((icon) => { - return `.${namespace}-${icon.name}::before { + .map((icon) => { + return `.${namespace}-${icon.name}::before { content: "\\${icon.pointCode}"; }` - }) - .join('\n\n')} + }) + .join('\n\n')} ` const iconNames = icons.map((iconName) => ` "${iconName.name}"`) @@ -76,16 +76,16 @@ ${iconNames.join(',\n')} ` await Promise.all([ - writeFile(resolve(FONTS_DIR, `${fileName}-webfont.ttf`), ttf), - writeFile(resolve(FONTS_DIR, `${fileName}-webfont.eot`), eot), - writeFile(resolve(FONTS_DIR, `${fileName}-webfont.woff`), woff), - writeFile(resolve(FONTS_DIR, `${fileName}-webfont.woff2`), woff2), - writeFile(resolve(CSS_DIR, `${fileName}.css`), cssTemplate), - writeFile(resolve(CSS_DIR, `${fileName}.less`), cssTemplate), - writeFile(resolve(DIST_DIR, 'index.js'), indexTemplate) - ]) - - console.log('build success!') + writeFile(resolve(FONTS_DIR, `${fileName}-webfont.ttf`), ttf), + writeFile(resolve(FONTS_DIR, `${fileName}-webfont.eot`), eot), + writeFile(resolve(FONTS_DIR, `${fileName}-webfont.woff`), woff), + writeFile(resolve(FONTS_DIR, `${fileName}-webfont.woff2`), woff2), + writeFile(resolve(CSS_DIR, `${fileName}.css`), cssTemplate), + writeFile(resolve(CSS_DIR, `${fileName}.less`), cssTemplate), + writeFile(resolve(DIST_DIR, 'index.js'), indexTemplate), + ]) + + console.log('build success!') } commander.command('build').description('Build varlet icons from svg').action(build) diff --git a/packages/varlet-icons/varlet-icons.config.js b/packages/varlet-icons/varlet-icons.config.js index 9aacd79dfe6..ac64addd2de 100644 --- a/packages/varlet-icons/varlet-icons.config.js +++ b/packages/varlet-icons/varlet-icons.config.js @@ -1,6 +1,6 @@ module.exports = { - namespace: 'var-icon', - publicPath: '~@varlet/icons/dist/fonts/', - fileName: 'varlet-icons', - fontName: 'varlet-icons', + namespace: 'var-icon', + publicPath: '~@varlet/icons/dist/fonts/', + fileName: 'varlet-icons', + fontName: 'varlet-icons', } diff --git a/packages/varlet-markdown-loader/index.js b/packages/varlet-markdown-loader/index.js index c017cba7481..b522dcbedf0 100644 --- a/packages/varlet-markdown-loader/index.js +++ b/packages/varlet-markdown-loader/index.js @@ -3,30 +3,26 @@ const hljs = require('highlight.js') const cardWrapper = require('./src/cardWrapper.js') function highlight(str, lang) { - if (lang && hljs.getLanguage(lang)) { - return ( - '
' +
-			hljs.highlight(lang, str, true).value +
-			'
' - ) - } + if (lang && hljs.getLanguage(lang)) { + return ( + '
' +
+      hljs.highlight(lang, str, true).value +
+      '
' + ) + } - return '' + return '' } function markLoader(source) { - const md = markdown({ - html: true, - typographer: true, - highlight, - }) - const html = cardWrapper(md.render(source)) + const md = markdown({ + html: true, + typographer: true, + highlight, + }) + const html = cardWrapper(md.render(source)) - return ( - '\n' - ) + return `\n` } module.exports = markLoader diff --git a/packages/varlet-touch-emulator/index.js b/packages/varlet-touch-emulator/index.js index 9d03809f773..dcff85e1e2e 100644 --- a/packages/varlet-touch-emulator/index.js +++ b/packages/varlet-touch-emulator/index.js @@ -9,79 +9,79 @@ const isMousemove = (eventType) => eventType === 'mousemove' const isMouseup = (eventType) => eventType === 'mouseup' const isUpdateTarget = (eventType) => - isMousedown(eventType) || !eventTarget || (eventTarget && !eventTarget.dispatchEvent) + isMousedown(eventType) || !eventTarget || (eventTarget && !eventTarget.dispatchEvent) function Touch(target, identifier, mouseEvent) { - const { clientX, clientY, screenX, screenY, pageX, pageY } = mouseEvent - - this.identifier = identifier - this.target = target - this.clientX = clientX - this.clientY = clientY - this.screenX = screenX - this.screenY = screenY - this.pageX = pageX - this.pageY = pageY + const { clientX, clientY, screenX, screenY, pageX, pageY } = mouseEvent + + this.identifier = identifier + this.target = target + this.clientX = clientX + this.clientY = clientY + this.screenX = screenX + this.screenY = screenY + this.pageX = pageX + this.pageY = pageY } function updateTouchList(mouseEvent) { - const touchList = createTouchList() + const touchList = createTouchList() - touchList.push(new Touch(eventTarget, 1, mouseEvent)) - return touchList + touchList.push(new Touch(eventTarget, 1, mouseEvent)) + return touchList } function createTouchList() { - const touchList = [] + const touchList = [] - touchList.item = function (index) { - return this[index] || null - } + touchList.item = function (index) { + return this[index] || null + } - return touchList + return touchList } function getActiveTouches(mouseEvent) { - const { type } = mouseEvent - if (isMouseup(type)) return createTouchList() - return updateTouchList(mouseEvent) + const { type } = mouseEvent + if (isMouseup(type)) return createTouchList() + return updateTouchList(mouseEvent) } function triggerTouch(touchType, mouseEvent) { - const { altKey, ctrlKey, metaKey, shiftKey } = mouseEvent - const touchEvent = document.createEvent('Event') - touchEvent.initEvent(touchType, true, true) + const { altKey, ctrlKey, metaKey, shiftKey } = mouseEvent + const touchEvent = document.createEvent('Event') + touchEvent.initEvent(touchType, true, true) - touchEvent.altKey = altKey - touchEvent.ctrlKey = ctrlKey - touchEvent.metaKey = metaKey - touchEvent.shiftKey = shiftKey + touchEvent.altKey = altKey + touchEvent.ctrlKey = ctrlKey + touchEvent.metaKey = metaKey + touchEvent.shiftKey = shiftKey - touchEvent.touches = getActiveTouches(mouseEvent) - touchEvent.targetTouches = getActiveTouches(mouseEvent) - touchEvent.changedTouches = createTouchList(mouseEvent) + touchEvent.touches = getActiveTouches(mouseEvent) + touchEvent.targetTouches = getActiveTouches(mouseEvent) + touchEvent.changedTouches = createTouchList(mouseEvent) - eventTarget.dispatchEvent(touchEvent) + eventTarget.dispatchEvent(touchEvent) } function onMouse(mouseEvent, touchType) { - const { type, target } = mouseEvent + const { type, target } = mouseEvent - initiated = isMousedown(type) ? true : isMouseup(type) ? false : initiated + initiated = isMousedown(type) ? true : isMouseup(type) ? false : initiated - if (isMousemove(type) && !initiated) return + if (isMousemove(type) && !initiated) return - if (isUpdateTarget(type)) eventTarget = target + if (isUpdateTarget(type)) eventTarget = target - triggerTouch(touchType, mouseEvent) + triggerTouch(touchType, mouseEvent) - if (isMouseup(type)) eventTarget = null + if (isMouseup(type)) eventTarget = null } function createTouchEmulator() { - window.addEventListener('mousedown', (event) => onMouse(event, 'touchstart'), true) - window.addEventListener('mousemove', (event) => onMouse(event, 'touchmove'), true) - window.addEventListener('mouseup', (event) => onMouse(event, 'touchend'), true) + window.addEventListener('mousedown', (event) => onMouse(event, 'touchstart'), true) + window.addEventListener('mousemove', (event) => onMouse(event, 'touchmove'), true) + window.addEventListener('mouseup', (event) => onMouse(event, 'touchend'), true) } if (!supportTouch) createTouchEmulator() diff --git a/packages/varlet-ui/src/badge/example/index.vue b/packages/varlet-ui/src/badge/example/index.vue index da924067e66..e1bbeb4c5e2 100644 --- a/packages/varlet-ui/src/badge/example/index.vue +++ b/packages/varlet-ui/src/badge/example/index.vue @@ -56,35 +56,35 @@ diff --git a/packages/varlet-ui/src/icon/index.ts b/packages/varlet-ui/src/icon/index.ts index 7592d884c49..179076aeb07 100644 --- a/packages/varlet-ui/src/icon/index.ts +++ b/packages/varlet-ui/src/icon/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import Icon from './Icon.vue' Icon.install = function (app: App) { - app.component(Icon.name, Icon) + app.component(Icon.name, Icon) } export default Icon diff --git a/packages/varlet-ui/src/icon/props.ts b/packages/varlet-ui/src/icon/props.ts index 57fc2957b4f..73a942bd49e 100644 --- a/packages/varlet-ui/src/icon/props.ts +++ b/packages/varlet-ui/src/icon/props.ts @@ -1,21 +1,21 @@ export const props = { - name: { - type: String, - }, + name: { + type: String, + }, color: { type: String, }, size: { type: String, }, - namespace: { - type: String, - default: 'var-icon', - }, - transition: { - type: Number, - default: 0, - }, + namespace: { + type: String, + default: 'var-icon', + }, + transition: { + type: Number, + default: 0, + }, onClick: { type: Function } diff --git a/packages/varlet-ui/src/image/Image.vue b/packages/varlet-ui/src/image/Image.vue index 93fb23d966d..8234abf8fc0 100644 --- a/packages/varlet-ui/src/image/Image.vue +++ b/packages/varlet-ui/src/image/Image.vue @@ -32,32 +32,32 @@ import Ripple from '../ripple' import Lazy, { LazyHTMLElement } from '../lazy' export default defineComponent({ - name: 'VarImage', - directives: { - Lazy, - Ripple, - }, - inheritAttrs: false, - props, - setup(props) { - const handleLoad = (e: Event) => { - const el: LazyHTMLElement = e.currentTarget as LazyHTMLElement + name: 'VarImage', + directives: { + Lazy, + Ripple, + }, + inheritAttrs: false, + props, + setup(props) { + const handleLoad = (e: Event) => { + const el: LazyHTMLElement = e.currentTarget as LazyHTMLElement - el._lazy.state === 'success' && props.onLoad?.(e, 'success') - el._lazy.state === 'error' && props.onError?.(e, 'error') - } + el._lazy.state === 'success' && props.onLoad?.(e, 'success') + el._lazy.state === 'error' && props.onError?.(e, 'error') + } - const handleError = (e: Event) => { - const el: LazyHTMLElement = e.currentTarget as LazyHTMLElement + const handleError = (e: Event) => { + const el: LazyHTMLElement = e.currentTarget as LazyHTMLElement - el._lazy.state !== 'pending' && props.onError?.(e, 'native-error') - } + el._lazy.state !== 'pending' && props.onError?.(e, 'native-error') + } - return { - handleLoad, - handleError, - } - }, + return { + handleLoad, + handleError, + } + }, }) diff --git a/packages/varlet-ui/src/image/example/index.vue b/packages/varlet-ui/src/image/example/index.vue index c6416d109b4..c08b0ceb50a 100644 --- a/packages/varlet-ui/src/image/example/index.vue +++ b/packages/varlet-ui/src/image/example/index.vue @@ -48,22 +48,22 @@ import { defineComponent } from 'vue' import Image from '..' export default defineComponent({ - name: 'ImageExample', - components: { - [Image.name]: Image, - }, - setup() { - return { - handleLoad(e: Event, state: string) { - console.log(e) - console.log(state) - }, - handleError(e: Event, state: string) { - console.log(e) - console.log(state) - }, - } - }, + name: 'ImageExample', + components: { + [Image.name]: Image, + }, + setup() { + return { + handleLoad(e: Event, state: string) { + console.log(e) + console.log(state) + }, + handleError(e: Event, state: string) { + console.log(e) + console.log(state) + }, + } + }, }) diff --git a/packages/varlet-ui/src/image/props.ts b/packages/varlet-ui/src/image/props.ts index d835e829791..58472f4c832 100644 --- a/packages/varlet-ui/src/image/props.ts +++ b/packages/varlet-ui/src/image/props.ts @@ -1,47 +1,47 @@ function fitValidator(fit: string) { - return ['fill', 'contain', 'cover', 'none', 'scale-down'].includes(fit) + return ['fill', 'contain', 'cover', 'none', 'scale-down'].includes(fit) } export const props = { - src: { - type: String, - }, - fit: { - type: String, - validator: fitValidator, - default: 'fill', - }, - alt: { - type: String, - }, - width: { - type: String, - }, - height: { - type: String, - }, - radius: { - type: String, - default: '0', - }, - error: { - type: String, - }, - loading: { - type: String, - }, - ripple: { - type: Boolean, - default: false, - }, - block: { - type: Boolean, - default: true, - }, - onLoad: { - type: Function, - }, - onError: { - type: Function, - }, + src: { + type: String, + }, + fit: { + type: String, + validator: fitValidator, + default: 'fill', + }, + alt: { + type: String, + }, + width: { + type: String, + }, + height: { + type: String, + }, + radius: { + type: String, + default: '0', + }, + error: { + type: String, + }, + loading: { + type: String, + }, + ripple: { + type: Boolean, + default: false, + }, + block: { + type: Boolean, + default: true, + }, + onLoad: { + type: Function, + }, + onError: { + type: Function, + }, } diff --git a/packages/varlet-ui/src/index-anchor/IndexAnchor.vue b/packages/varlet-ui/src/index-anchor/IndexAnchor.vue index ed01e48c481..f13db621aa3 100644 --- a/packages/varlet-ui/src/index-anchor/IndexAnchor.vue +++ b/packages/varlet-ui/src/index-anchor/IndexAnchor.vue @@ -17,60 +17,60 @@ import Sticky from '../sticky' import { useParent, useAtParentIndex } from '../utils/components' import { IndexAnchorProvider } from './provide' import { - INDEX_BAR_BIND_INDEX_ANCHOR_KEY, - INDEX_BAR_COUNT_INDEX_ANCHOR_KEY, - IndexBarProvider, + INDEX_BAR_BIND_INDEX_ANCHOR_KEY, + INDEX_BAR_COUNT_INDEX_ANCHOR_KEY, + IndexBarProvider, } from '../index-bar/provide' import { props } from './props' export default defineComponent({ - name: 'VarIndexAnchor', - components: { - [Sticky.name]: Sticky, - }, - inheritAttrs: false, - props, - setup(props) { - const ownTop: Ref = ref(0) - const name: ComputedRef = computed(() => props.index) - const anchorEl: Ref = ref(null) - const { parentProvider: IndexBarProvider, bindParent } = useParent( - INDEX_BAR_BIND_INDEX_ANCHOR_KEY - ) + name: 'VarIndexAnchor', + components: { + [Sticky.name]: Sticky, + }, + inheritAttrs: false, + props, + setup(props) { + const ownTop: Ref = ref(0) + const name: ComputedRef = computed(() => props.index) + const anchorEl: Ref = ref(null) + const { parentProvider: IndexBarProvider, bindParent } = useParent( + INDEX_BAR_BIND_INDEX_ANCHOR_KEY + ) - if (!IndexBarProvider || !bindParent) { - console.error('[Varlet] IndexAnchor: You should use this component in "IndexBar"') - return - } + if (!IndexBarProvider || !bindParent) { + console.error('[Varlet] IndexAnchor: You should use this component in "IndexBar"') + return + } - const { active, sticky, stickyOffsetTop, zIndex } = IndexBarProvider - const { index } = useAtParentIndex(INDEX_BAR_COUNT_INDEX_ANCHOR_KEY) + const { active, sticky, stickyOffsetTop, zIndex } = IndexBarProvider + const { index } = useAtParentIndex(INDEX_BAR_COUNT_INDEX_ANCHOR_KEY) - const setOwnTop = () => { - ownTop.value = (anchorEl.value as RendererNode).$el - ? (anchorEl.value as RendererNode).$el.offsetTop - : (anchorEl.value as HTMLDivElement).offsetTop - } + const setOwnTop = () => { + ownTop.value = (anchorEl.value as RendererNode).$el + ? (anchorEl.value as RendererNode).$el.offsetTop + : (anchorEl.value as HTMLDivElement).offsetTop + } - const indexAnchorProvider: IndexAnchorProvider = { - index, - name, - ownTop, - setOwnTop, - } + const indexAnchorProvider: IndexAnchorProvider = { + index, + name, + ownTop, + setOwnTop, + } - bindParent(indexAnchorProvider) + bindParent(indexAnchorProvider) - return { - name, - anchorEl, - active, - sticky, - zIndex, - stickyOffsetTop, - Transition, - } - }, + return { + name, + anchorEl, + active, + sticky, + zIndex, + stickyOffsetTop, + Transition, + } + }, }) diff --git a/packages/varlet-ui/src/index-anchor/index.ts b/packages/varlet-ui/src/index-anchor/index.ts index 14cf84f7b0a..657284925b1 100644 --- a/packages/varlet-ui/src/index-anchor/index.ts +++ b/packages/varlet-ui/src/index-anchor/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import IndexAnchor from './IndexAnchor.vue' IndexAnchor.install = function (app: App) { - app.component(IndexAnchor.name, IndexAnchor) + app.component(IndexAnchor.name, IndexAnchor) } export default IndexAnchor diff --git a/packages/varlet-ui/src/index-anchor/props.ts b/packages/varlet-ui/src/index-anchor/props.ts index 5bf18a81ed2..e65c87eed7e 100644 --- a/packages/varlet-ui/src/index-anchor/props.ts +++ b/packages/varlet-ui/src/index-anchor/props.ts @@ -1,5 +1,5 @@ export const props = { - index: { - type: [Number, String], - }, + index: { + type: [Number, String], + }, } diff --git a/packages/varlet-ui/src/index-bar/IndexBar.vue b/packages/varlet-ui/src/index-bar/IndexBar.vue index eab2b0a7cc6..a4e3b76a303 100644 --- a/packages/varlet-ui/src/index-bar/IndexBar.vue +++ b/packages/varlet-ui/src/index-bar/IndexBar.vue @@ -23,85 +23,85 @@ import { IndexAnchorProvider } from '../index-anchor/provide' import { props } from './props' export default defineComponent({ - name: 'VarIndexBar', - props, - setup(props) { - const barEl: Ref = ref(null) + name: 'VarIndexBar', + props, + setup(props) { + const barEl: Ref = ref(null) - const active: ComputedRef = computed(() => props.active) - const sticky: ComputedRef = computed(() => props.sticky) - const stickyOffsetTop: ComputedRef = computed(() => props.stickyOffsetTop) - const zIndex: ComputedRef = computed(() => props.zIndex) + const active: ComputedRef = computed(() => props.active) + const sticky: ComputedRef = computed(() => props.sticky) + const stickyOffsetTop: ComputedRef = computed(() => props.stickyOffsetTop) + const zIndex: ComputedRef = computed(() => props.zIndex) - const anchorNameList: Ref> = ref([]) + const anchorNameList: Ref> = ref([]) - const { bindChildren, childProviders: IndexAnchorProviders } = useChildren( - INDEX_BAR_BIND_INDEX_ANCHOR_KEY - ) - const { length } = useAtChildrenCounter(INDEX_BAR_COUNT_INDEX_ANCHOR_KEY) + const { bindChildren, childProviders: IndexAnchorProviders } = useChildren( + INDEX_BAR_BIND_INDEX_ANCHOR_KEY + ) + const { length } = useAtChildrenCounter(INDEX_BAR_COUNT_INDEX_ANCHOR_KEY) - const indexBarProvider: IndexBarProvider = { - active, - sticky, - stickyOffsetTop, - zIndex, - } + const indexBarProvider: IndexBarProvider = { + active, + sticky, + stickyOffsetTop, + zIndex, + } - bindChildren(indexBarProvider) + bindChildren(indexBarProvider) - const emitEvent = (anchor: IndexAnchorProvider | number | string) => { - const anchorName = isBaseObject(anchor) ? anchor.name.value : anchor - if (anchorName === props.active) return - props['onUpdate:active']?.(anchorName) - props.onChange?.(anchorName) - } + const emitEvent = (anchor: IndexAnchorProvider | number | string) => { + const anchorName = isBaseObject(anchor) ? anchor.name.value : anchor + if (anchorName === props.active) return + props['onUpdate:active']?.(anchorName) + props.onChange?.(anchorName) + } - const handleScroll = () => { - const { scrollTop } = barEl.value as HTMLDivElement - IndexAnchorProviders.forEach((anchor: IndexAnchorProvider, index: number) => { - const anchorTop = anchor.ownTop.value - const top = scrollTop - anchorTop + stickyOffsetTop.value + const handleScroll = () => { + const { scrollTop } = barEl.value as HTMLDivElement + IndexAnchorProviders.forEach((anchor: IndexAnchorProvider, index: number) => { + const anchorTop = anchor.ownTop.value + const top = scrollTop - anchorTop + stickyOffsetTop.value - if (top >= 0 && top <= 10) { - emitEvent(anchor) - } else if (top < 0 && top >= -10) { - const preAnchor = IndexAnchorProviders[index - 1] - emitEvent(preAnchor) - } - }) - } + if (top >= 0 && top <= 10) { + emitEvent(anchor) + } else if (top < 0 && top >= -10) { + const preAnchor = IndexAnchorProviders[index - 1] + emitEvent(preAnchor) + } + }) + } - const anchorClick = (anchorName: string | number) => { - if (anchorName === active.value) return - const indexAnchor = IndexAnchorProviders.find(({ name }: IndexAnchorProvider) => anchorName === name.value) - if (!indexAnchor) return - const top = indexAnchor.ownTop.value - const { scrollLeft } = barEl.value as HTMLDivElement + const anchorClick = (anchorName: string | number) => { + if (anchorName === active.value) return + const indexAnchor = IndexAnchorProviders.find(({ name }: IndexAnchorProvider) => anchorName === name.value) + if (!indexAnchor) return + const top = indexAnchor.ownTop.value + const { scrollLeft } = barEl.value as HTMLDivElement ;(barEl.value as HTMLDivElement).scrollTo(scrollLeft, top) - emitEvent(anchorName) - } + emitEvent(anchorName) + } - watch( - () => length.value, - () => - nextTick(() => { - IndexAnchorProviders.forEach(({ name }) => { - if (name.value) anchorNameList.value.push(name.value) - }) - }) - ) + watch( + () => length.value, + () => + nextTick(() => { + IndexAnchorProviders.forEach(({ name }) => { + if (name.value) anchorNameList.value.push(name.value) + }) + }) + ) - onMounted(() => { - IndexAnchorProviders.forEach(({ setOwnTop }) => setOwnTop()) - }) + onMounted(() => { + IndexAnchorProviders.forEach(({ setOwnTop }) => setOwnTop()) + }) - return { - barEl, - anchorNameList, - anchorClick, - handleScroll, - } - }, + return { + barEl, + anchorNameList, + anchorClick, + handleScroll, + } + }, }) diff --git a/packages/varlet-ui/src/index-bar/example/index.vue b/packages/varlet-ui/src/index-bar/example/index.vue index c22bdf1ad56..e11aafd6cc8 100644 --- a/packages/varlet-ui/src/index-bar/example/index.vue +++ b/packages/varlet-ui/src/index-bar/example/index.vue @@ -15,31 +15,31 @@ import IndexAnchor from '../../index-anchor/IndexAnchor.vue' import IndexBar from '..' export default defineComponent({ - name: 'IndexBarExample', - components: { - [IndexBar.name]: IndexBar, - [IndexAnchor.name]: IndexAnchor, - }, - setup() { - const active = ref('A') - const list = ref([]) + name: 'IndexBarExample', + components: { + [IndexBar.name]: IndexBar, + [IndexAnchor.name]: IndexAnchor, + }, + setup() { + const active = ref('A') + const list = ref([]) - onBeforeMount(() => { - for (let i = 0; i < 26; i++) { - list.value.push(String.fromCharCode(65 + i)) - } - }) + onBeforeMount(() => { + for (let i = 0; i < 26; i++) { + list.value.push(String.fromCharCode(65 + i)) + } + }) - const change = (value) => { - console.log(value) - } + const change = (value) => { + console.log(value) + } - return { - active, - list, - change, - } - }, + return { + active, + list, + change, + } + }, }) diff --git a/packages/varlet-ui/src/index-bar/index.ts b/packages/varlet-ui/src/index-bar/index.ts index 30321909aef..3b3f93e11be 100644 --- a/packages/varlet-ui/src/index-bar/index.ts +++ b/packages/varlet-ui/src/index-bar/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import IndexBar from './IndexBar.vue' IndexBar.install = function (app: App) { - app.component(IndexBar.name, IndexBar) + app.component(IndexBar.name, IndexBar) } export default IndexBar diff --git a/packages/varlet-ui/src/index-bar/props.ts b/packages/varlet-ui/src/index-bar/props.ts index 501afdb5a9c..b53858bc1af 100644 --- a/packages/varlet-ui/src/index-bar/props.ts +++ b/packages/varlet-ui/src/index-bar/props.ts @@ -1,27 +1,27 @@ export const props = { - active: { - type: [Number, String], - }, - sticky: { - type: Boolean, - default: true, - }, - stickyOffsetTop: { - type: Number, - default: 0, - }, - zIndex: { - type: [Number, String], - default: 1, - }, - highlightColor: { - type: String, - default: '#ee0a24', - }, - 'onUpdate:active': { - type: Function, - }, - onChange: { - type: Function, - }, + active: { + type: [Number, String], + }, + sticky: { + type: Boolean, + default: true, + }, + stickyOffsetTop: { + type: Number, + default: 0, + }, + zIndex: { + type: [Number, String], + default: 1, + }, + highlightColor: { + type: String, + default: '#ee0a24', + }, + 'onUpdate:active': { + type: Function, + }, + onChange: { + type: Function, + }, } diff --git a/packages/varlet-ui/src/input/Input.vue b/packages/varlet-ui/src/input/Input.vue index 06305673150..21532149501 100644 --- a/packages/varlet-ui/src/input/Input.vue +++ b/packages/varlet-ui/src/input/Input.vue @@ -118,174 +118,174 @@ import FormDetails from '../form-details' import Icon from '../icon' export default defineComponent({ - name: 'VarInput', - components: { - [Icon.name]: Icon, - [FormDetails.name]: FormDetails, - }, - inheritAttrs: false, - props, - setup(props) { - const { bindParent: bindForm, parentProvider: formProvider } = useParent( - FORM_BIND_FORM_ITEM_KEY - ) + name: 'VarInput', + components: { + [Icon.name]: Icon, + [FormDetails.name]: FormDetails, + }, + inheritAttrs: false, + props, + setup(props) { + const { bindParent: bindForm, parentProvider: formProvider } = useParent( + FORM_BIND_FORM_ITEM_KEY + ) - const inputId: Ref = ref(`var-input-${getCurrentInstance()!.uid}`) - const isFocus: Ref = ref(false) - const inputEl: Ref = ref(null) + const inputId: Ref = ref(`var-input-${getCurrentInstance()!.uid}`) + const isFocus: Ref = ref(false) + const inputEl: Ref = ref(null) - const isNumberValue: ComputedRef = computed(() => isNumber(props.modelValue)) - const maxlengthText: ComputedRef = computed(() => { - const { maxlength, modelValue } = props + const isNumberValue: ComputedRef = computed(() => isNumber(props.modelValue)) + const maxlengthText: ComputedRef = computed(() => { + const { maxlength, modelValue } = props - if (!maxlength) { - return '' - } + if (!maxlength) { + return '' + } - if (isEmpty(modelValue)) { - return `0 / ${maxlength}` - } + if (isEmpty(modelValue)) { + return `0 / ${maxlength}` + } - return `${String(modelValue).length}/${maxlength}` - }) + return `${String(modelValue).length}/${maxlength}` + }) - const { errorMessage, validateWithTrigger: vt, validate: v, resetValidation } = useValidation() + const { errorMessage, validateWithTrigger: vt, validate: v, resetValidation } = useValidation() - const validate = () => v(props.rules, props.modelValue) + const validate = () => v(props.rules, props.modelValue) - const validateWithTrigger = (trigger: ValidateTriggers) => - nextTick(() => vt(props.validateTrigger, trigger, props.rules, props.modelValue)) + const validateWithTrigger = (trigger: ValidateTriggers) => + nextTick(() => vt(props.validateTrigger, trigger, props.rules, props.modelValue)) - const computePlaceholderState = () => { - if (!props.hint && !isEmpty(props.modelValue)) { - return 'var-input--placeholder-hidden' - } - if (props.hint && (!isEmpty(props.modelValue) || isFocus.value)) { - return 'var-input--placeholder-hint' - } - } + const computePlaceholderState = () => { + if (!props.hint && !isEmpty(props.modelValue)) { + return 'var-input--placeholder-hidden' + } + if (props.hint && (!isEmpty(props.modelValue) || isFocus.value)) { + return 'var-input--placeholder-hint' + } + } - const normalizeValue = (value: string) => { - return isNumberValue.value ? parseFloat(value) : value - } + const normalizeValue = (value: string) => { + return isNumberValue.value ? parseFloat(value) : value + } - const handleFocus = (e: Event) => { - isFocus.value = true - props.onFocus?.(e) + const handleFocus = (e: Event) => { + isFocus.value = true + props.onFocus?.(e) - validateWithTrigger('onFocus') - } + validateWithTrigger('onFocus') + } - const handleBlur = (e: Event) => { - isFocus.value = false - props.onBlur?.(e) + const handleBlur = (e: Event) => { + isFocus.value = false + props.onBlur?.(e) - validateWithTrigger('onBlur') - } + validateWithTrigger('onBlur') + } - const handleInput = (e: Event) => { - const { value } = e.target as HTMLInputElement + const handleInput = (e: Event) => { + const { value } = e.target as HTMLInputElement - props['onUpdate:modelValue']?.(normalizeValue(value)) - props.onInput?.(e) + props['onUpdate:modelValue']?.(normalizeValue(value)) + props.onInput?.(e) - validateWithTrigger('onInput') - } + validateWithTrigger('onInput') + } - const handleChange = (e: Event) => { - props.onChange?.(e) + const handleChange = (e: Event) => { + props.onChange?.(e) - validateWithTrigger('onChange') - } + validateWithTrigger('onChange') + } - const handleClear = () => { - if ( - formProvider?.disabled.value || + const handleClear = () => { + if ( + formProvider?.disabled.value || formProvider?.readonly.value || props.disabled || props.readonly || !props.clearable - ) { - return - } - - props['onUpdate:modelValue']?.(undefined) - props.onClear?.() - - validateWithTrigger('onClear') - } - - const handleClick = (e: Event) => { - if (formProvider?.disabled.value || props.disabled) { - return - } - - props.onClick?.(e) - - validateWithTrigger('onClick') - } - - const handleClickAppendIcon = (e: Event) => { - if (formProvider?.disabled.value || props.disabled) { - return - } - - props.onClickAppendIcon?.(e) - } - - const handleClickPrependIcon = (e: Event) => { - if (formProvider?.disabled.value || props.disabled) { - return - } - - props.onClickPrependIcon?.(e) - } - - const focus = () => { - ;(inputEl.value as HTMLInputElement).focus() - } - - const blur = () => { - ;(inputEl.value as HTMLInputElement).blur() - } - - const reset = () => { - props['onUpdate:modelValue']?.(undefined) - resetValidation() - } - - const inputProvider: InputProvider = { - reset, - validate, - resetValidation, - } - - bindForm?.(inputProvider) - - return { - inputEl, - inputId, - isFocus, - errorMessage, - maxlengthText, - formDisabled: formProvider?.disabled, - formReadonly: formProvider?.readonly, - computePlaceholderState, - handleFocus, - handleBlur, - handleInput, - handleChange, - handleClear, - handleClick, - handleClickAppendIcon, - handleClickPrependIcon, - validate, - resetValidation, - reset, - focus, - blur, - } - }, + ) { + return + } + + props['onUpdate:modelValue']?.(undefined) + props.onClear?.() + + validateWithTrigger('onClear') + } + + const handleClick = (e: Event) => { + if (formProvider?.disabled.value || props.disabled) { + return + } + + props.onClick?.(e) + + validateWithTrigger('onClick') + } + + const handleClickAppendIcon = (e: Event) => { + if (formProvider?.disabled.value || props.disabled) { + return + } + + props.onClickAppendIcon?.(e) + } + + const handleClickPrependIcon = (e: Event) => { + if (formProvider?.disabled.value || props.disabled) { + return + } + + props.onClickPrependIcon?.(e) + } + + const focus = () => { + ;(inputEl.value as HTMLInputElement).focus() + } + + const blur = () => { + ;(inputEl.value as HTMLInputElement).blur() + } + + const reset = () => { + props['onUpdate:modelValue']?.(undefined) + resetValidation() + } + + const inputProvider: InputProvider = { + reset, + validate, + resetValidation, + } + + bindForm?.(inputProvider) + + return { + inputEl, + inputId, + isFocus, + errorMessage, + maxlengthText, + formDisabled: formProvider?.disabled, + formReadonly: formProvider?.readonly, + computePlaceholderState, + handleFocus, + handleBlur, + handleInput, + handleChange, + handleClear, + handleClick, + handleClickAppendIcon, + handleClickPrependIcon, + validate, + resetValidation, + reset, + focus, + blur, + } + }, }) diff --git a/packages/varlet-ui/src/input/example/index.vue b/packages/varlet-ui/src/input/example/index.vue index d7be16da288..c2d27323192 100644 --- a/packages/varlet-ui/src/input/example/index.vue +++ b/packages/varlet-ui/src/input/example/index.vue @@ -54,29 +54,29 @@ import Button from '../../button' import Icon from '../../icon' export default defineComponent({ - name: 'InputExample', - components: { - [Input.name]: Input, - [Button.name]: Button, - [Icon.name]: Icon, - }, - setup() { - const value4: any = ref('') + name: 'InputExample', + components: { + [Input.name]: Input, + [Button.name]: Button, + [Icon.name]: Icon, + }, + setup() { + const value4: any = ref('') - return { - value: ref(''), - value2: ref(''), - value3: ref(''), - value4, - asyncValidator() { - return new Promise((resolve) => { - setTimeout(() => { - resolve('反正就是失败了') - }, 1000) - }) - }, - } - }, + return { + value: ref(''), + value2: ref(''), + value3: ref(''), + value4, + asyncValidator() { + return new Promise((resolve) => { + setTimeout(() => { + resolve('反正就是失败了') + }, 1000) + }) + }, + } + }, }) diff --git a/packages/varlet-ui/src/input/props.ts b/packages/varlet-ui/src/input/props.ts index e326a9f1a63..304ef2a8e18 100644 --- a/packages/varlet-ui/src/input/props.ts +++ b/packages/varlet-ui/src/input/props.ts @@ -1,114 +1,114 @@ import { PropType } from 'vue' export function textAlignValidator(textAlign: string) { - return ['left', 'right', 'center'].includes(textAlign) + return ['left', 'right', 'center'].includes(textAlign) } export function typeValidator(type: string) { - return ['text', 'password'].includes(type) + return ['text', 'password'].includes(type) } export type ValidateTriggers = 'onFocus' | 'onBlur' | 'onChange' | 'onClick' | 'onClear' | 'onInput' export const props = { - modelValue: { - type: [String, Number], - }, - textColor: { - type: String, - }, - inactiveColor: { - type: String, - }, - activeColor: { - type: String, - }, - type: { - type: String, - default: 'text', - validator: typeValidator, - }, - maxlength: { - type: [String, Number], - }, - disabled: { - type: Boolean, - default: false, - }, - readonly: { - type: Boolean, - default: false, - }, - clearable: { - type: Boolean, - default: false, - }, - textarea: { - type: Boolean, - default: false, - }, - resize: { - type: Boolean, - default: false, - }, - rows: { - type: [String, Number], - default: 8, - }, - textAlign: { - type: String, - default: 'left', - validator: textAlignValidator, - }, - placeholder: { - type: String, - }, - prependIcon: { - type: String, - }, - appendIcon: { - type: String, - }, - line: { - type: Boolean, - default: true, - }, - hint: { - type: Boolean, - default: true, - }, - validateTrigger: { - type: Array as PropType>, - default: ['onInput', 'onClear'], - }, - rules: { - type: Array as PropType any>>, - }, - onFocus: { - type: Function, - }, - onBlur: { - type: Function, - }, - onInput: { - type: Function, - }, - onChange: { - type: Function, - }, - onClick: { - type: Function, - }, - onClear: { - type: Function, - }, - onClickAppendIcon: { - type: Function, - }, - onClickPrependIcon: { - type: Function, - }, - 'onUpdate:modelValue': { - type: Function, - }, + modelValue: { + type: [String, Number], + }, + textColor: { + type: String, + }, + inactiveColor: { + type: String, + }, + activeColor: { + type: String, + }, + type: { + type: String, + default: 'text', + validator: typeValidator, + }, + maxlength: { + type: [String, Number], + }, + disabled: { + type: Boolean, + default: false, + }, + readonly: { + type: Boolean, + default: false, + }, + clearable: { + type: Boolean, + default: false, + }, + textarea: { + type: Boolean, + default: false, + }, + resize: { + type: Boolean, + default: false, + }, + rows: { + type: [String, Number], + default: 8, + }, + textAlign: { + type: String, + default: 'left', + validator: textAlignValidator, + }, + placeholder: { + type: String, + }, + prependIcon: { + type: String, + }, + appendIcon: { + type: String, + }, + line: { + type: Boolean, + default: true, + }, + hint: { + type: Boolean, + default: true, + }, + validateTrigger: { + type: Array as PropType>, + default: ['onInput', 'onClear'], + }, + rules: { + type: Array as PropType any>>, + }, + onFocus: { + type: Function, + }, + onBlur: { + type: Function, + }, + onInput: { + type: Function, + }, + onChange: { + type: Function, + }, + onClick: { + type: Function, + }, + onClear: { + type: Function, + }, + onClickAppendIcon: { + type: Function, + }, + onClickPrependIcon: { + type: Function, + }, + 'onUpdate:modelValue': { + type: Function, + }, } diff --git a/packages/varlet-ui/src/lazy/index.ts b/packages/varlet-ui/src/lazy/index.ts index 2d684b13485..98aaa85fa62 100644 --- a/packages/varlet-ui/src/lazy/index.ts +++ b/packages/varlet-ui/src/lazy/index.ts @@ -2,12 +2,12 @@ import { App, Directive, Plugin } from 'vue' import { DirectiveBinding } from '@vue/runtime-core' import { getParentScroller, inViewport } from '../utils/elements' import { - CacheInstance, - checkIntersectionObserverAPI, - createCache, - createInViewportObserver, - removeItem, - throttle, + CacheInstance, + checkIntersectionObserverAPI, + createCache, + createInViewportObserver, + removeItem, + throttle, } from '../utils/shared' interface LazyOptions { @@ -45,11 +45,11 @@ let listenTargets: ListenTarget[] = [] const imageCache: CacheInstance = createCache(100) export const defaultLazyOptions: LazyOptions = { - loading: PIXEL, - error: PIXEL, - attempt: 3, - throttleWait: 300, - events: EVENTS, + loading: PIXEL, + error: PIXEL, + attempt: 3, + throttleWait: 300, + events: EVENTS, } let checkAllWithThrottle = throttle(checkAll, defaultLazyOptions.throttleWait) @@ -59,200 +59,200 @@ let observer: IntersectionObserver | null = null const useIntersectionObserverAPI: boolean = checkIntersectionObserverAPI() function setLoading(el: LazyHTMLElement) { - el._lazy.loading - ? el._lazy.arg === BACKGROUND_IMAGE_ARG_NAME - ? (el.style.backgroundImage = `url(${el._lazy.loading})`) - : el.setAttribute('src', el._lazy.loading) - : null + el._lazy.loading + ? el._lazy.arg === BACKGROUND_IMAGE_ARG_NAME + ? (el.style.backgroundImage = `url(${el._lazy.loading})`) + : el.setAttribute('src', el._lazy.loading) + : null - !useIntersectionObserverAPI && checkAll() + !useIntersectionObserverAPI && checkAll() } function setError(el: LazyHTMLElement) { - if (el._lazy.error) { - if (el._lazy.arg === BACKGROUND_IMAGE_ARG_NAME) { - el.style.backgroundImage = `url(${el._lazy.error})` - } else { - el.setAttribute('src', el._lazy.error) - } - } - - el._lazy.state = 'error' - - clear(el) - !useIntersectionObserverAPI && checkAll() + if (el._lazy.error) { + if (el._lazy.arg === BACKGROUND_IMAGE_ARG_NAME) { + el.style.backgroundImage = `url(${el._lazy.error})` + } else { + el.setAttribute('src', el._lazy.error) + } + } + + el._lazy.state = 'error' + + clear(el) + !useIntersectionObserverAPI && checkAll() } function setSuccess(el: LazyHTMLElement, attemptSRC: string) { - el._lazy.arg === BACKGROUND_IMAGE_ARG_NAME - ? (el.style.backgroundImage = `url(${attemptSRC})`) - : el.setAttribute('src', attemptSRC) + el._lazy.arg === BACKGROUND_IMAGE_ARG_NAME + ? (el.style.backgroundImage = `url(${attemptSRC})`) + : el.setAttribute('src', attemptSRC) - el._lazy.state = 'success' + el._lazy.state = 'success' - clear(el) - !useIntersectionObserverAPI && checkAll() + clear(el) + !useIntersectionObserverAPI && checkAll() } function bindEvents(listenTarget: ListenTarget) { - if (listenTargets.includes(listenTarget)) { - return - } - listenTargets.push(listenTarget) - - defaultLazyOptions.events?.forEach((event: string) => { - listenTarget.addEventListener(event, checkAllWithThrottle, { passive: true }) - }) + if (listenTargets.includes(listenTarget)) { + return + } + listenTargets.push(listenTarget) + + defaultLazyOptions.events?.forEach((event: string) => { + listenTarget.addEventListener(event, checkAllWithThrottle, { passive: true }) + }) } function unbindEvents() { - listenTargets.forEach((listenTarget: ListenTarget) => { - defaultLazyOptions.events?.forEach((event: string) => { - listenTarget.removeEventListener(event, checkAllWithThrottle) - }) - }) + listenTargets.forEach((listenTarget: ListenTarget) => { + defaultLazyOptions.events?.forEach((event: string) => { + listenTarget.removeEventListener(event, checkAllWithThrottle) + }) + }) - listenTargets = [] + listenTargets = [] } function updateLazyOptions(el: LazyHTMLElement, binding: DirectiveBinding) { - const lazyInnerOptions: LazyOptions = { - loading: el.getAttribute(LAZY_LOADING) ?? defaultLazyOptions.loading, - error: el.getAttribute(LAZY_ERROR) ?? defaultLazyOptions.error, - attempt: el.getAttribute(LAZY_ATTEMPT) ? Number(el.getAttribute(LAZY_ATTEMPT)) : defaultLazyOptions.attempt, - } - - el._lazy = { - src: binding.value, - arg: binding.arg, - currentAttempt: 0, - state: 'pending', - attemptLock: false, - ...lazyInnerOptions, - } - - defaultLazyOptions.filter?.(el._lazy) + const lazyInnerOptions: LazyOptions = { + loading: el.getAttribute(LAZY_LOADING) ?? defaultLazyOptions.loading, + error: el.getAttribute(LAZY_ERROR) ?? defaultLazyOptions.error, + attempt: el.getAttribute(LAZY_ATTEMPT) ? Number(el.getAttribute(LAZY_ATTEMPT)) : defaultLazyOptions.attempt, + } + + el._lazy = { + src: binding.value, + arg: binding.arg, + currentAttempt: 0, + state: 'pending', + attemptLock: false, + ...lazyInnerOptions, + } + + defaultLazyOptions.filter?.(el._lazy) } function createImage(el: LazyHTMLElement, attemptSRC: string) { - const image: HTMLImageElement = new Image() - image.src = attemptSRC - image.addEventListener('load', () => { - el._lazy.attemptLock = false - - imageCache.add(attemptSRC) - setSuccess(el, attemptSRC) - }) - image.addEventListener('error', () => { - el._lazy.attemptLock = false - ;(el._lazy.currentAttempt as number) >= (el._lazy.attempt as number) ? setError(el) : attemptLoad(el) - }) + const image: HTMLImageElement = new Image() + image.src = attemptSRC + image.addEventListener('load', () => { + el._lazy.attemptLock = false + + imageCache.add(attemptSRC) + setSuccess(el, attemptSRC) + }) + image.addEventListener('error', () => { + el._lazy.attemptLock = false + ;(el._lazy.currentAttempt as number) >= (el._lazy.attempt as number) ? setError(el) : attemptLoad(el) + }) } function attemptLoad(el: LazyHTMLElement) { - if (el._lazy.attemptLock === true) { - return - } - el._lazy.attemptLock = true - el._lazy.currentAttempt++ - - const { src: attemptSRC }: Lazy = el._lazy - - if (imageCache.has(attemptSRC)) { - setSuccess(el, attemptSRC) - el._lazy.attemptLock = false - return - } - - setLoading(el) - createImage(el, attemptSRC) + if (el._lazy.attemptLock === true) { + return + } + el._lazy.attemptLock = true + el._lazy.currentAttempt++ + + const { src: attemptSRC }: Lazy = el._lazy + + if (imageCache.has(attemptSRC)) { + setSuccess(el, attemptSRC) + el._lazy.attemptLock = false + return + } + + setLoading(el) + createImage(el, attemptSRC) } function check(el: LazyHTMLElement) { - inViewport(el) && attemptLoad(el) + inViewport(el) && attemptLoad(el) } function checkAll() { - lazyElements.forEach((el: LazyHTMLElement) => check(el)) + lazyElements.forEach((el: LazyHTMLElement) => check(el)) } function clear(el: LazyHTMLElement) { - if (useIntersectionObserverAPI) { - observer?.unobserve(el) - } else { - removeItem(lazyElements, el) - lazyElements.length === 0 && unbindEvents() - } + if (useIntersectionObserverAPI) { + observer?.unobserve(el) + } else { + removeItem(lazyElements, el) + lazyElements.length === 0 && unbindEvents() + } } function observe(el: LazyHTMLElement) { - if (!observer) { - observer = createInViewportObserver((el: LazyHTMLElement) => attemptLoad(el)) - } + if (!observer) { + observer = createInViewportObserver((el: LazyHTMLElement) => attemptLoad(el)) + } - observer.unobserve(el) - observer.observe(el) + observer.unobserve(el) + observer.observe(el) } function diff(el: LazyHTMLElement, binding: DirectiveBinding): boolean { - const { src, arg, attempt, loading, error } = el._lazy - return ( - src !== binding.value || + const { src, arg, attempt, loading, error } = el._lazy + return ( + src !== binding.value || arg !== binding.arg || attempt !== Number(el.getAttribute(LAZY_ATTEMPT)) || loading !== el.getAttribute(LAZY_LOADING) || error !== el.getAttribute(LAZY_ERROR) - ) + ) } function mounted(el: LazyHTMLElement, binding: DirectiveBinding) { - !el.getAttribute('src') && el.setAttribute('src', PIXEL) + !el.getAttribute('src') && el.setAttribute('src', PIXEL) - updateLazyOptions(el, binding) + updateLazyOptions(el, binding) - if (useIntersectionObserverAPI) { - observe(el) - } else { - bindEvents(window) - bindEvents(getParentScroller(el)) - check(el) - } + if (useIntersectionObserverAPI) { + observe(el) + } else { + bindEvents(window) + bindEvents(getParentScroller(el)) + check(el) + } } function unmounted(el: LazyHTMLElement) { - clear(el) + clear(el) } function updated(el: LazyHTMLElement, binding: DirectiveBinding) { - diff(el, binding) - ? mounted(el, binding) - : !useIntersectionObserverAPI - ? lazyElements.includes(el) - ? check(el) - : null - : null + diff(el, binding) + ? mounted(el, binding) + : !useIntersectionObserverAPI + ? lazyElements.includes(el) + ? check(el) + : null + : null } function mergeLazyOptions(lazyOptions: LazyOptions) { - defaultLazyOptions.events = lazyOptions.events ?? defaultLazyOptions.events - defaultLazyOptions.loading = lazyOptions.loading ?? defaultLazyOptions.loading - defaultLazyOptions.error = lazyOptions.error ?? defaultLazyOptions.error - defaultLazyOptions.attempt = lazyOptions.attempt ?? defaultLazyOptions.attempt - defaultLazyOptions.throttleWait = lazyOptions.throttleWait ?? defaultLazyOptions.throttleWait - defaultLazyOptions.filter = lazyOptions.filter + defaultLazyOptions.events = lazyOptions.events ?? defaultLazyOptions.events + defaultLazyOptions.loading = lazyOptions.loading ?? defaultLazyOptions.loading + defaultLazyOptions.error = lazyOptions.error ?? defaultLazyOptions.error + defaultLazyOptions.attempt = lazyOptions.attempt ?? defaultLazyOptions.attempt + defaultLazyOptions.throttleWait = lazyOptions.throttleWait ?? defaultLazyOptions.throttleWait + defaultLazyOptions.filter = lazyOptions.filter } const Lazy: Directive & Plugin = { - mounted, - unmounted, - updated, - install(app: App, lazyOptions: LazyOptions) { - mergeLazyOptions(lazyOptions) + mounted, + unmounted, + updated, + install(app: App, lazyOptions: LazyOptions) { + mergeLazyOptions(lazyOptions) - checkAllWithThrottle = throttle(checkAll, defaultLazyOptions.throttleWait) + checkAllWithThrottle = throttle(checkAll, defaultLazyOptions.throttleWait) - app.directive('lazy', this) - }, + app.directive('lazy', this) + }, } export default Lazy diff --git a/packages/varlet-ui/src/loading/Loading.vue b/packages/varlet-ui/src/loading/Loading.vue index c25aceae994..536b2350468 100644 --- a/packages/varlet-ui/src/loading/Loading.vue +++ b/packages/varlet-ui/src/loading/Loading.vue @@ -62,8 +62,8 @@ import { defineComponent } from 'vue' import { props } from './props' export default defineComponent({ - name: 'VarLoading', - props, + name: 'VarLoading', + props, }) diff --git a/packages/varlet-ui/src/loading/example/index.vue b/packages/varlet-ui/src/loading/example/index.vue index 622ce80583d..f970181ceba 100644 --- a/packages/varlet-ui/src/loading/example/index.vue +++ b/packages/varlet-ui/src/loading/example/index.vue @@ -28,10 +28,10 @@ import { defineComponent } from 'vue' import Loading from '..' export default defineComponent({ - name: 'LoadingExample', - components: { - [Loading.name]: Loading, - }, + name: 'LoadingExample', + components: { + [Loading.name]: Loading, + }, }) diff --git a/packages/varlet-ui/src/loading/index.ts b/packages/varlet-ui/src/loading/index.ts index 1ad92cb3adf..200554506f7 100644 --- a/packages/varlet-ui/src/loading/index.ts +++ b/packages/varlet-ui/src/loading/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import Loading from './Loading.vue' Loading.install = function (app: App) { - app.component(Loading.name, Loading) + app.component(Loading.name, Loading) } export default Loading diff --git a/packages/varlet-ui/src/loading/props.ts b/packages/varlet-ui/src/loading/props.ts index 77c6fc743ee..889e0730bff 100644 --- a/packages/varlet-ui/src/loading/props.ts +++ b/packages/varlet-ui/src/loading/props.ts @@ -1,31 +1,31 @@ export function typeValidator(type: string): boolean { - return ['circle', 'wave', 'cube', 'rect', 'disappear'].includes(type) + return ['circle', 'wave', 'cube', 'rect', 'disappear'].includes(type) } export function sizeValidator(size: string): boolean { - return ['normal', 'mini', 'small', 'large'].includes(size) + return ['normal', 'mini', 'small', 'large'].includes(size) } export const props = { - // loading类型 - type: { - type: String, - default: 'circle', - validator: typeValidator, - }, - radius: { - type: [String, Number], - default: 15, - }, - // loading尺寸 - size: { - type: String, - default: 'normal', - validator: sizeValidator, - }, - // loading颜色 - color: { - type: String, - default: 'currentColor', - }, + // loading类型 + type: { + type: String, + default: 'circle', + validator: typeValidator, + }, + radius: { + type: [String, Number], + default: 15, + }, + // loading尺寸 + size: { + type: String, + default: 'normal', + validator: sizeValidator, + }, + // loading颜色 + color: { + type: String, + default: 'currentColor', + }, } diff --git a/packages/varlet-ui/src/menu/Menu.vue b/packages/varlet-ui/src/menu/Menu.vue index 5c015c76815..a8692311401 100644 --- a/packages/varlet-ui/src/menu/Menu.vue +++ b/packages/varlet-ui/src/menu/Menu.vue @@ -30,76 +30,76 @@ import { getLeft, getTop } from '../utils/elements' import { useZIndex } from '../context/zIndex' export default defineComponent({ - name: 'VarMenu', - inheritAttrs: false, - props, - setup(props) { - const { zIndex } = useZIndex(props, 'show', 1) + name: 'VarMenu', + inheritAttrs: false, + props, + setup(props) { + const { zIndex } = useZIndex(props, 'show', 1) - const host: Ref = ref(null) - const menu: Ref = ref(null) + const host: Ref = ref(null) + const menu: Ref = ref(null) - const top: Ref = ref(0) - const left: Ref = ref(0) - const computeTop = (alignment: string): number => { - return alignment === 'top' - ? getTop(host.value as HTMLElement) - : getTop(host.value as HTMLElement) - (menu.value as HTMLElement).offsetHeight - } + const top: Ref = ref(0) + const left: Ref = ref(0) + const computeTop = (alignment: string): number => { + return alignment === 'top' + ? getTop(host.value as HTMLElement) + : getTop(host.value as HTMLElement) - (menu.value as HTMLElement).offsetHeight + } - const clickSelf: Ref = ref(false) + const clickSelf: Ref = ref(false) - const handleClick = () => { - clickSelf.value = true - } + const handleClick = () => { + clickSelf.value = true + } - // positions effect - watch( - () => props.alignment, - (newValue: string) => { - props.show === true && (top.value = computeTop(newValue)) - } - ) - watch( - () => props.show, - async (newValue: boolean) => { - await nextTick() + // positions effect + watch( + () => props.alignment, + (newValue: string) => { + props.show === true && (top.value = computeTop(newValue)) + } + ) + watch( + () => props.show, + async (newValue: boolean) => { + await nextTick() - top.value = newValue === true ? computeTop(props.alignment) : top.value - }, - { immediate: true } - ) + top.value = newValue === true ? computeTop(props.alignment) : top.value + }, + { immediate: true } + ) - // menu hidden - const handleMenuBlur = () => { - if (clickSelf.value) { - clickSelf.value = false - return - } + // menu hidden + const handleMenuBlur = () => { + if (clickSelf.value) { + clickSelf.value = false + return + } - props['onUpdate:show']?.(false) - props.onBlur?.() - } + props['onUpdate:show']?.(false) + props.onBlur?.() + } - onMounted(() => { - top.value = computeTop(props.alignment) - left.value = getLeft(host.value as HTMLElement) + onMounted(() => { + top.value = computeTop(props.alignment) + left.value = getLeft(host.value as HTMLElement) - document.addEventListener('click', handleMenuBlur) - }) - onUnmounted(() => { - document.removeEventListener('click', handleMenuBlur) - }) + document.addEventListener('click', handleMenuBlur) + }) + onUnmounted(() => { + document.removeEventListener('click', handleMenuBlur) + }) - return { - zIndex, - host, - menu, - top, - left, - handleClick, - } - }, + return { + zIndex, + host, + menu, + top, + left, + handleClick, + } + }, }) diff --git a/packages/varlet-ui/src/menu/index.ts b/packages/varlet-ui/src/menu/index.ts index 6c5aebfd58c..f2f6b353b87 100644 --- a/packages/varlet-ui/src/menu/index.ts +++ b/packages/varlet-ui/src/menu/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import Menu from './Menu.vue' Menu.install = function (app: App) { - app.component(Menu.name, Menu) + app.component(Menu.name, Menu) } export default Menu diff --git a/packages/varlet-ui/src/menu/props.ts b/packages/varlet-ui/src/menu/props.ts index ee5245d7470..77bd5c387ac 100644 --- a/packages/varlet-ui/src/menu/props.ts +++ b/packages/varlet-ui/src/menu/props.ts @@ -1,29 +1,29 @@ function alignmentValidator(alignment: string) { - return ['top', 'bottom'].includes(alignment) + return ['top', 'bottom'].includes(alignment) } export const props = { - show: { - type: Boolean, - default: false, - }, - 'onUpdate:show': { - type: Function, - }, - alignment: { - type: String, - default: 'top', - validator: alignmentValidator, - }, - offsetX: { - type: String, - default: '0px', - }, - offsetY: { - type: String, - default: '0px', - }, - onBlur: { - type: Function, - }, + show: { + type: Boolean, + default: false, + }, + 'onUpdate:show': { + type: Function, + }, + alignment: { + type: String, + default: 'top', + validator: alignmentValidator, + }, + offsetX: { + type: String, + default: '0px', + }, + offsetY: { + type: String, + default: '0px', + }, + onBlur: { + type: Function, + }, } diff --git a/packages/varlet-ui/src/option/Option.vue b/packages/varlet-ui/src/option/Option.vue index 6a13add3472..bd2b9d8631a 100644 --- a/packages/varlet-ui/src/option/Option.vue +++ b/packages/varlet-ui/src/option/Option.vue @@ -37,62 +37,62 @@ import Checkbox from '../checkbox' import Ripple from '../ripple' export default defineComponent({ - name: 'VarOption', - directives: { Ripple }, - components: { - [Checkbox.name]: Checkbox, - }, - inheritAttrs: false, - props, - setup(props) { - const { bindParent, parentProvider: selectProvider } = useParent( - SELECT_BIND_OPTION_KEY - ) - useAtParentIndex(SELECT_COUNT_OPTION_KEY) + name: 'VarOption', + directives: { Ripple }, + components: { + [Checkbox.name]: Checkbox, + }, + inheritAttrs: false, + props, + setup(props) { + const { bindParent, parentProvider: selectProvider } = useParent( + SELECT_BIND_OPTION_KEY + ) + useAtParentIndex(SELECT_COUNT_OPTION_KEY) - if (!bindParent || !selectProvider) { - throw Error(' must in ') - } + if (!bindParent || !selectProvider) { + throw Error(' must in ') + } - const optionSelected: Ref = ref(false) + const optionSelected: Ref = ref(false) - const selected: ComputedRef = computed(() => optionSelected.value) - const label: ComputedRef = computed(() => props.label) - const value: ComputedRef = computed(() => props.value) + const selected: ComputedRef = computed(() => optionSelected.value) + const label: ComputedRef = computed(() => props.label) + const value: ComputedRef = computed(() => props.value) - const { wrapWidth, multiple, activeColor, onSelect } = selectProvider + const { wrapWidth, multiple, activeColor, onSelect } = selectProvider - const handleClick = () => { - optionSelected.value = !optionSelected.value - onSelect(optionProvider) - } + const handleClick = () => { + optionSelected.value = !optionSelected.value + onSelect(optionProvider) + } - const handleSelect = () => { - onSelect(optionProvider) - } + const handleSelect = () => { + onSelect(optionProvider) + } - const sync = (checked: boolean) => { - optionSelected.value = checked - } + const sync = (checked: boolean) => { + optionSelected.value = checked + } - const optionProvider: OptionProvider = { - label, - value, - selected, - sync, - } + const optionProvider: OptionProvider = { + label, + value, + selected, + sync, + } - bindParent(optionProvider) + bindParent(optionProvider) - return { - optionSelected, - wrapWidth, - multiple, - activeColor, - handleClick, - handleSelect, - } - }, + return { + optionSelected, + wrapWidth, + multiple, + activeColor, + handleClick, + handleSelect, + } + }, }) diff --git a/packages/varlet-ui/src/option/example/index.vue b/packages/varlet-ui/src/option/example/index.vue index b8df4b19f39..1ad7916e64f 100644 --- a/packages/varlet-ui/src/option/example/index.vue +++ b/packages/varlet-ui/src/option/example/index.vue @@ -7,10 +7,10 @@ import { defineComponent } from 'vue' import Option from '..' export default defineComponent({ - name: 'OptionExample', - components: { - [Option.name]: Option, - }, + name: 'OptionExample', + components: { + [Option.name]: Option, + }, }) diff --git a/packages/varlet-ui/src/option/index.ts b/packages/varlet-ui/src/option/index.ts index bd77ea352da..87eb0ce997e 100644 --- a/packages/varlet-ui/src/option/index.ts +++ b/packages/varlet-ui/src/option/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import Option from './Option.vue' Option.install = function (app: App) { - app.component(Option.name, Option) + app.component(Option.name, Option) } export default Option diff --git a/packages/varlet-ui/src/option/props.ts b/packages/varlet-ui/src/option/props.ts index adf901ecc81..2097d282a86 100644 --- a/packages/varlet-ui/src/option/props.ts +++ b/packages/varlet-ui/src/option/props.ts @@ -1,10 +1,10 @@ export const props = { - value: { - type: [String, Number, Boolean], - default: undefined, - }, - label: { - type: [String], - required: true, - }, + value: { + type: [String, Number, Boolean], + default: undefined, + }, + label: { + type: [String], + required: true, + }, } diff --git a/packages/varlet-ui/src/popup/index.ts b/packages/varlet-ui/src/popup/index.ts index e89ef11f33b..91749350135 100644 --- a/packages/varlet-ui/src/popup/index.ts +++ b/packages/varlet-ui/src/popup/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import Popup from './Popup.vue' Popup.install = function (app: App) { - app.component(Popup.name, Popup) + app.component(Popup.name, Popup) } export default Popup diff --git a/packages/varlet-ui/src/progress/Progress.vue b/packages/varlet-ui/src/progress/Progress.vue index 4b3a77ae544..c1abb0944e5 100644 --- a/packages/varlet-ui/src/progress/Progress.vue +++ b/packages/varlet-ui/src/progress/Progress.vue @@ -62,41 +62,41 @@ import { defineComponent, computed } from 'vue' import { props } from './props' export default defineComponent({ - name: 'VarProgress', - inheritAttrs: false, - props, - setup(props) { - const linearProps = computed(() => { - const width = isNaN(+props.value) ? 0 : props.value > 100 ? 100 : props.value - const roundValue = isNaN(+props.value) ? 0 : props.value > 100 ? 100 : Math.round(props.value) + name: 'VarProgress', + inheritAttrs: false, + props, + setup(props) { + const linearProps = computed(() => { + const width = isNaN(+props.value) ? 0 : props.value > 100 ? 100 : props.value + const roundValue = isNaN(+props.value) ? 0 : props.value > 100 ? 100 : Math.round(props.value) - return { - width: `${width}%`, - roundValue: `${roundValue}%`, - } - }) + return { + width: `${width}%`, + roundValue: `${roundValue}%`, + } + }) - const circleProps = computed(() => { - const { size, lineWidth, value } = props - const viewBox = `0 0 ${size} ${size}` - const roundValue = isNaN(+value) ? 0 : value > 100 ? 100 : Math.round(value) - const radius = (size - +lineWidth) / 2 - const perimeter = 2 * Math.PI * radius - const strokeDasharray = `${(roundValue / 100) * perimeter}, ${perimeter}` + const circleProps = computed(() => { + const { size, lineWidth, value } = props + const viewBox = `0 0 ${size} ${size}` + const roundValue = isNaN(+value) ? 0 : value > 100 ? 100 : Math.round(value) + const radius = (size - +lineWidth) / 2 + const perimeter = 2 * Math.PI * radius + const strokeDasharray = `${(roundValue / 100) * perimeter}, ${perimeter}` - return { - viewBox, - radius, - strokeDasharray, - perimeter, - roundValue: `${roundValue}%`, - } - }) - return { - linearProps, - circleProps, - } - }, + return { + viewBox, + radius, + strokeDasharray, + perimeter, + roundValue: `${roundValue}%`, + } + }) + return { + linearProps, + circleProps, + } + }, }) diff --git a/packages/varlet-ui/src/progress/example/index.vue b/packages/varlet-ui/src/progress/example/index.vue index 66fc7d6f31e..2f921099511 100644 --- a/packages/varlet-ui/src/progress/example/index.vue +++ b/packages/varlet-ui/src/progress/example/index.vue @@ -87,29 +87,29 @@ import { defineComponent, ref, onMounted, onUnmounted } from 'vue' import Progress from '..' export default defineComponent({ - name: 'ProgressExample', - components: { - [Progress.name]: Progress, - }, - setup() { - const value = ref(0) - const interval = ref(0) - - onMounted(() => { - interval.value = window.setInterval(() => { - if (value.value >= 100) value.value = 0 - else value.value += 20 - }, 1000) - }) - - onUnmounted(() => { - window.clearInterval(interval.value) - }) - - return { - value, - } - }, + name: 'ProgressExample', + components: { + [Progress.name]: Progress, + }, + setup() { + const value = ref(0) + const interval = ref(0) + + onMounted(() => { + interval.value = window.setInterval(() => { + if (value.value >= 100) value.value = 0 + else value.value += 20 + }, 1000) + }) + + onUnmounted(() => { + window.clearInterval(interval.value) + }) + + return { + value, + } + }, }) diff --git a/packages/varlet-ui/src/progress/index.ts b/packages/varlet-ui/src/progress/index.ts index 6d885f4976c..98bab27e156 100644 --- a/packages/varlet-ui/src/progress/index.ts +++ b/packages/varlet-ui/src/progress/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import Progress from './Progress.vue' Progress.install = function (app: App) { - app.component(Progress.name, Progress) + app.component(Progress.name, Progress) } export default Progress diff --git a/packages/varlet-ui/src/progress/props.ts b/packages/varlet-ui/src/progress/props.ts index 45057a079e5..e1b9c9460ba 100644 --- a/packages/varlet-ui/src/progress/props.ts +++ b/packages/varlet-ui/src/progress/props.ts @@ -1,56 +1,56 @@ function modeValidator(mode: string): boolean { - return ['linear', 'circle'].includes(mode) + return ['linear', 'circle'].includes(mode) } export const props = { - // progress 模式 - mode: { - type: String, - default: 'linear', - validator: modeValidator, - }, - // progress 线宽 - lineWidth: { - type: [Number, String], - default: 4, - }, - // progress 颜色 - color: { - type: String, - }, - // progress 轨道颜色 - trackColor: { - type: String, - default: '#d8d8d8', - }, - // 是否添加水波纹效果 - ripple: { - type: Boolean, - default: false, - }, - // progress 值 - value: { - type: Number, - default: 0, - }, - // 是否显示action - showAction: { - type: Boolean, - default: false, - }, - // circle 的尺寸 - size: { - type: Number, - default: 40, - }, - // circle的原点 - rotate: { - type: Number, - default: 0, - }, - // 是否显示 circle 轨道 - showTrack: { - type: Boolean, - default: true, - }, + // progress 模式 + mode: { + type: String, + default: 'linear', + validator: modeValidator, + }, + // progress 线宽 + lineWidth: { + type: [Number, String], + default: 4, + }, + // progress 颜色 + color: { + type: String, + }, + // progress 轨道颜色 + trackColor: { + type: String, + default: '#d8d8d8', + }, + // 是否添加水波纹效果 + ripple: { + type: Boolean, + default: false, + }, + // progress 值 + value: { + type: Number, + default: 0, + }, + // 是否显示action + showAction: { + type: Boolean, + default: false, + }, + // circle 的尺寸 + size: { + type: Number, + default: 40, + }, + // circle的原点 + rotate: { + type: Number, + default: 0, + }, + // 是否显示 circle 轨道 + showTrack: { + type: Boolean, + default: true, + }, } diff --git a/packages/varlet-ui/src/pull-refresh/PullRefresh.vue b/packages/varlet-ui/src/pull-refresh/PullRefresh.vue index c71a25a5bf7..e7c199de05b 100644 --- a/packages/varlet-ui/src/pull-refresh/PullRefresh.vue +++ b/packages/varlet-ui/src/pull-refresh/PullRefresh.vue @@ -32,107 +32,107 @@ const CONTROL_POSITION = -50 let scroller: HTMLElement | Window = window export default defineComponent({ - name: 'VarPullRefresh', - components: { - [Icon.name]: Icon, - }, - props, - setup(props) { - const freshNode: Ref = ref(null) - - const startPosition: Ref = ref(0) - - const distance: Ref = ref(CONTROL_POSITION) - - const iconName: Ref = ref('arrow-down') - - const refreshStatus: Ref = ref('default') - - const isEnd: Ref = ref(false) - - const isTouchable = computed( - () => refreshStatus.value !== 'loading' && refreshStatus.value !== 'success' && !props.disable - ) - - const iconClass = computed(() => ({ - 'var-pull-refresh__animation': refreshStatus.value === 'loading', - })) - - const controlStyle = computed(() => ({ - transform: `translate3d(0px, ${distance.value}px, 0px) translate(-50%, 0)`, - transition: isEnd.value ? `transform ${props.animationDuration}ms` : null, - background: props.successBgColor || props.bgColor, - color: props.successColor || props.color, - })) - - const isSuccess = computed(() => refreshStatus.value === 'success') - - const touchStart = (event: TouchEvent) => { - if (!isTouchable.value) return - refreshStatus.value = 'pulling' - startPosition.value = event.touches[0].clientY - } - const touchMove = (event: TouchEvent) => { - const scrollTop = getScrollTop(scroller) - if (scrollTop > 0 || !isTouchable.value) return - if (scrollTop === 0 && distance.value !== CONTROL_POSITION) event.cancelable && event.preventDefault() - - const moveDistance = (event.touches[0].clientY - startPosition.value) / 2 + CONTROL_POSITION - - distance.value = moveDistance >= MAX_DISTANCE ? MAX_DISTANCE : moveDistance - iconName.value = distance.value >= MAX_DISTANCE * 0.2 ? 'refresh' : 'arrow-down' - } - const touchEnd = () => { - if (!isTouchable.value) return - isEnd.value = true - if (distance.value >= MAX_DISTANCE * 0.2) { - refreshStatus.value = 'loading' - distance.value = MAX_DISTANCE * 0.3 - props.onRefresh?.() - } else { - refreshStatus.value = 'loosing' - iconName.value = 'arrow-down' - distance.value = CONTROL_POSITION - setTimeout(() => { - isEnd.value = false - }, +props.animationDuration) - } - } - - watch( - () => props.modelValue, - (newValue) => { - if (newValue === false) { - isEnd.value = true - refreshStatus.value = 'success' - iconName.value = 'checkbox-marked-circle' - setTimeout(() => { - distance.value = CONTROL_POSITION - setTimeout(() => { - refreshStatus.value = 'default' - iconName.value = 'arrow-down' - isEnd.value = false - }, +props.animationDuration) - }, +props.successDuration) - } - } - ) - - onMounted(() => { - scroller = getParentScroller(freshNode.value as HTMLElement, 'y') - }) - - return { - freshNode, - touchStart, - touchMove, - touchEnd, - iconName, - iconClass, - controlStyle, - isSuccess, - } - }, + name: 'VarPullRefresh', + components: { + [Icon.name]: Icon, + }, + props, + setup(props) { + const freshNode: Ref = ref(null) + + const startPosition: Ref = ref(0) + + const distance: Ref = ref(CONTROL_POSITION) + + const iconName: Ref = ref('arrow-down') + + const refreshStatus: Ref = ref('default') + + const isEnd: Ref = ref(false) + + const isTouchable = computed( + () => refreshStatus.value !== 'loading' && refreshStatus.value !== 'success' && !props.disable + ) + + const iconClass = computed(() => ({ + 'var-pull-refresh__animation': refreshStatus.value === 'loading', + })) + + const controlStyle = computed(() => ({ + transform: `translate3d(0px, ${distance.value}px, 0px) translate(-50%, 0)`, + transition: isEnd.value ? `transform ${props.animationDuration}ms` : null, + background: props.successBgColor || props.bgColor, + color: props.successColor || props.color, + })) + + const isSuccess = computed(() => refreshStatus.value === 'success') + + const touchStart = (event: TouchEvent) => { + if (!isTouchable.value) return + refreshStatus.value = 'pulling' + startPosition.value = event.touches[0].clientY + } + const touchMove = (event: TouchEvent) => { + const scrollTop = getScrollTop(scroller) + if (scrollTop > 0 || !isTouchable.value) return + if (scrollTop === 0 && distance.value !== CONTROL_POSITION) event.cancelable && event.preventDefault() + + const moveDistance = (event.touches[0].clientY - startPosition.value) / 2 + CONTROL_POSITION + + distance.value = moveDistance >= MAX_DISTANCE ? MAX_DISTANCE : moveDistance + iconName.value = distance.value >= MAX_DISTANCE * 0.2 ? 'refresh' : 'arrow-down' + } + const touchEnd = () => { + if (!isTouchable.value) return + isEnd.value = true + if (distance.value >= MAX_DISTANCE * 0.2) { + refreshStatus.value = 'loading' + distance.value = MAX_DISTANCE * 0.3 + props.onRefresh?.() + } else { + refreshStatus.value = 'loosing' + iconName.value = 'arrow-down' + distance.value = CONTROL_POSITION + setTimeout(() => { + isEnd.value = false + }, +props.animationDuration) + } + } + + watch( + () => props.modelValue, + (newValue) => { + if (newValue === false) { + isEnd.value = true + refreshStatus.value = 'success' + iconName.value = 'checkbox-marked-circle' + setTimeout(() => { + distance.value = CONTROL_POSITION + setTimeout(() => { + refreshStatus.value = 'default' + iconName.value = 'arrow-down' + isEnd.value = false + }, +props.animationDuration) + }, +props.successDuration) + } + } + ) + + onMounted(() => { + scroller = getParentScroller(freshNode.value as HTMLElement, 'y') + }) + + return { + freshNode, + touchStart, + touchMove, + touchEnd, + iconName, + iconClass, + controlStyle, + isSuccess, + } + }, }) diff --git a/packages/varlet-ui/src/pull-refresh/example/index.vue b/packages/varlet-ui/src/pull-refresh/example/index.vue index 62e399ccc44..3939e719de6 100644 --- a/packages/varlet-ui/src/pull-refresh/example/index.vue +++ b/packages/varlet-ui/src/pull-refresh/example/index.vue @@ -14,28 +14,28 @@ const data1 = Array(10).fill('List Item') const data2 = Array(10).fill('This is new List Item') export default defineComponent({ - name: 'PullRefreshExample', - components: { - [PullRefresh.name]: PullRefresh, - }, - setup() { - const isRefresh = ref(true) - const data = ref(data1) - - const refresh = () => { - isRefresh.value = true - setTimeout(() => { - data.value = data.value[0] === 'List Item' ? data2 : data1 - isRefresh.value = false - }, 2000) - } - - return { - refresh, - isRefresh, - data, - } - }, + name: 'PullRefreshExample', + components: { + [PullRefresh.name]: PullRefresh, + }, + setup() { + const isRefresh = ref(true) + const data = ref(data1) + + const refresh = () => { + isRefresh.value = true + setTimeout(() => { + data.value = data.value[0] === 'List Item' ? data2 : data1 + isRefresh.value = false + }, 2000) + } + + return { + refresh, + isRefresh, + data, + } + }, }) diff --git a/packages/varlet-ui/src/pull-refresh/index.ts b/packages/varlet-ui/src/pull-refresh/index.ts index b1f9b2c3efe..c0db119090c 100644 --- a/packages/varlet-ui/src/pull-refresh/index.ts +++ b/packages/varlet-ui/src/pull-refresh/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import PullRefresh from './PullRefresh.vue' PullRefresh.install = function (app: App) { - app.component(PullRefresh.name, PullRefresh) + app.component(PullRefresh.name, PullRefresh) } export default PullRefresh diff --git a/packages/varlet-ui/src/pull-refresh/props.ts b/packages/varlet-ui/src/pull-refresh/props.ts index dccecebe29c..3408c32f11e 100644 --- a/packages/varlet-ui/src/pull-refresh/props.ts +++ b/packages/varlet-ui/src/pull-refresh/props.ts @@ -1,39 +1,39 @@ export const props = { - modelValue: { - type: Boolean, - }, - // 是否禁用下拉刷新 - disable: { - type: Boolean, - default: false, - }, - // 动画时长 - animationDuration: { - type: [Number, String], - default: 300, - }, - // 刷新成功提示展示时长 - successDuration: { - type: [Number, String], - default: 2000, - }, - // control 的背景颜色 - bgColor: { - type: String, - }, - // 成功状态下 control 的背景颜色 - successBgColor: { - type: String, - }, - // control 的颜色 - color: { - type: String, - }, - // 成功状态下 control 的颜色 - successColor: { - type: String, - }, - onRefresh: { - type: Function, - }, + modelValue: { + type: Boolean, + }, + // 是否禁用下拉刷新 + disable: { + type: Boolean, + default: false, + }, + // 动画时长 + animationDuration: { + type: [Number, String], + default: 300, + }, + // 刷新成功提示展示时长 + successDuration: { + type: [Number, String], + default: 2000, + }, + // control 的背景颜色 + bgColor: { + type: String, + }, + // 成功状态下 control 的背景颜色 + successBgColor: { + type: String, + }, + // control 的颜色 + color: { + type: String, + }, + // 成功状态下 control 的颜色 + successColor: { + type: String, + }, + onRefresh: { + type: Function, + }, } diff --git a/packages/varlet-ui/src/radio-group/RadioGroup.vue b/packages/varlet-ui/src/radio-group/RadioGroup.vue index 55688be53e8..b47a75117fd 100644 --- a/packages/varlet-ui/src/radio-group/RadioGroup.vue +++ b/packages/varlet-ui/src/radio-group/RadioGroup.vue @@ -18,65 +18,65 @@ import FormDetails from '../form-details' import { FORM_BIND_FORM_ITEM_KEY, FormProvider } from '../form/provide' export default defineComponent({ - name: 'VarRadioGroup', - components: { - [FormDetails.name]: FormDetails, - }, - inheritAttrs: false, - props, - setup(props) { - const { bindChildren: bindRadio, childProviders: radioProviders } = useChildren( - RADIO_GROUP_BIND_RADIO_KEY - ) - const { bindParent: bindForm } = useParent(FORM_BIND_FORM_ITEM_KEY) - const { length } = useAtChildrenCounter(RADIO_GROUP_COUNT_RADIO_KEY) - - const { errorMessage, validateWithTrigger: vt, validate: v, resetValidation } = useValidation() - const errorMessageComputed: ComputedRef = computed(() => errorMessage.value) - - const validate = () => v(props.rules, props.modelValue) - - const validateWithTrigger = (trigger: ValidateTriggers) => - nextTick(() => vt(props.validateTrigger, trigger, props.rules, props.modelValue)) - - const syncAllRadio = () => { - radioProviders.forEach(({ sync }) => sync(props.modelValue)) - } - - const onToggle = (changedValue: any) => { - props['onUpdate:modelValue']?.(changedValue) - props.onChange?.(changedValue) - - validateWithTrigger('onChange') - } - - const reset = () => { - props['onUpdate:modelValue']?.(undefined) - resetValidation() - } - - watch(() => props.modelValue, syncAllRadio) - - watch(() => length.value, syncAllRadio) - - const radioGroupProvider: RadioGroupProvider = { - onToggle, - validate, - reset, - resetValidation, - errorMessage: errorMessageComputed, - } - - bindRadio(radioGroupProvider) - bindForm?.(radioGroupProvider) - - return { - errorMessage, - reset, - validate, - resetValidation, - } - }, + name: 'VarRadioGroup', + components: { + [FormDetails.name]: FormDetails, + }, + inheritAttrs: false, + props, + setup(props) { + const { bindChildren: bindRadio, childProviders: radioProviders } = useChildren( + RADIO_GROUP_BIND_RADIO_KEY + ) + const { bindParent: bindForm } = useParent(FORM_BIND_FORM_ITEM_KEY) + const { length } = useAtChildrenCounter(RADIO_GROUP_COUNT_RADIO_KEY) + + const { errorMessage, validateWithTrigger: vt, validate: v, resetValidation } = useValidation() + const errorMessageComputed: ComputedRef = computed(() => errorMessage.value) + + const validate = () => v(props.rules, props.modelValue) + + const validateWithTrigger = (trigger: ValidateTriggers) => + nextTick(() => vt(props.validateTrigger, trigger, props.rules, props.modelValue)) + + const syncAllRadio = () => { + radioProviders.forEach(({ sync }) => sync(props.modelValue)) + } + + const onToggle = (changedValue: any) => { + props['onUpdate:modelValue']?.(changedValue) + props.onChange?.(changedValue) + + validateWithTrigger('onChange') + } + + const reset = () => { + props['onUpdate:modelValue']?.(undefined) + resetValidation() + } + + watch(() => props.modelValue, syncAllRadio) + + watch(() => length.value, syncAllRadio) + + const radioGroupProvider: RadioGroupProvider = { + onToggle, + validate, + reset, + resetValidation, + errorMessage: errorMessageComputed, + } + + bindRadio(radioGroupProvider) + bindForm?.(radioGroupProvider) + + return { + errorMessage, + reset, + validate, + resetValidation, + } + }, }) diff --git a/packages/varlet-ui/src/radio-group/example/index.vue b/packages/varlet-ui/src/radio-group/example/index.vue index 7bd49a76c69..043f1c38895 100644 --- a/packages/varlet-ui/src/radio-group/example/index.vue +++ b/packages/varlet-ui/src/radio-group/example/index.vue @@ -7,10 +7,10 @@ import { defineComponent } from 'vue' import RadioGroup from '..' export default defineComponent({ - name: 'RadioGroupExample', - components: { - [RadioGroup.name]: RadioGroup, - }, + name: 'RadioGroupExample', + components: { + [RadioGroup.name]: RadioGroup, + }, }) diff --git a/packages/varlet-ui/src/radio-group/index.ts b/packages/varlet-ui/src/radio-group/index.ts index c4ad5b17755..1d931211e06 100644 --- a/packages/varlet-ui/src/radio-group/index.ts +++ b/packages/varlet-ui/src/radio-group/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import RadioGroup from './RadioGroup.vue' RadioGroup.install = function (app: App) { - app.component(RadioGroup.name, RadioGroup) + app.component(RadioGroup.name, RadioGroup) } export default RadioGroup diff --git a/packages/varlet-ui/src/radio-group/props.ts b/packages/varlet-ui/src/radio-group/props.ts index 20ce84e87b9..52a4b24e893 100644 --- a/packages/varlet-ui/src/radio-group/props.ts +++ b/packages/varlet-ui/src/radio-group/props.ts @@ -3,28 +3,28 @@ import { PropType } from 'vue' export type ValidateTriggers = 'onChange' export function directionValidator(direction: string) { - return ['horizontal', 'vertical'].includes(direction) + return ['horizontal', 'vertical'].includes(direction) } export const props = { - modelValue: { - default: false, - }, - direction: { - type: String, - default: 'horizontal', - }, - validateTrigger: { - type: Array as PropType>, - default: ['onChange'], - }, - rules: { - type: Array as PropType any>>, - }, - onChange: { - type: Function, - }, - 'onUpdate:modelValue': { - type: Function, - }, + modelValue: { + default: false, + }, + direction: { + type: String, + default: 'horizontal', + }, + validateTrigger: { + type: Array as PropType>, + default: ['onChange'], + }, + rules: { + type: Array as PropType any>>, + }, + onChange: { + type: Function, + }, + 'onUpdate:modelValue': { + type: Function, + }, } diff --git a/packages/varlet-ui/src/radio/Radio.vue b/packages/varlet-ui/src/radio/Radio.vue index 7dfb05a2d7a..7edacad53cb 100644 --- a/packages/varlet-ui/src/radio/Radio.vue +++ b/packages/varlet-ui/src/radio/Radio.vue @@ -45,110 +45,110 @@ import Icon from '../icon' import FormDetails from '../form-details' export default defineComponent({ - name: 'VarRadio', - directives: { Ripple }, - components: { - [Icon.name]: Icon, - [FormDetails.name]: FormDetails, - }, - inheritAttrs: false, - props, - setup(props) { - const { bindParent: bindRadioGroup, parentProvider: radioGroupProvider } = useParent< + name: 'VarRadio', + directives: { Ripple }, + components: { + [Icon.name]: Icon, + [FormDetails.name]: FormDetails, + }, + inheritAttrs: false, + props, + setup(props) { + const { bindParent: bindRadioGroup, parentProvider: radioGroupProvider } = useParent< RadioGroupProvider, RadioProvider >(RADIO_GROUP_BIND_RADIO_KEY) - const { bindParent: bindForm, parentProvider: formProvider } = useParent( - FORM_BIND_FORM_ITEM_KEY - ) - useAtParentIndex(RADIO_GROUP_COUNT_RADIO_KEY) - - const value: Ref = ref(false) - const checked: ComputedRef = computed(() => value.value === props.checkedValue) - - const { errorMessage, validateWithTrigger: vt, validate: v, resetValidation } = useValidation() - - const validate = () => v(props.rules, props.modelValue) - - const validateWithTrigger = (trigger: ValidateTriggers) => - nextTick(() => vt(props.validateTrigger, trigger, props.rules, props.modelValue)) - - const change = (changedValue: any) => { - if (radioGroupProvider && value.value === props.checkedValue) { - return - } - - value.value = changedValue - props['onUpdate:modelValue']?.(value.value) - props.onChange?.(value.value) - - validateWithTrigger('onChange') - - radioGroupProvider?.onToggle(props.checkedValue) - } - - const toggle = (changedValue?: any) => { - const isInvalidValue = changedValue !== props.uncheckedValue && changedValue !== props.checkedValue - if (changedValue != null && (isInvalidValue || changedValue === value.value)) { - return - } - - if (changedValue == null) { - changedValue = checked.value ? props.uncheckedValue : props.checkedValue - } - - change(changedValue) - } - - const handleClick = (e: Event) => { - if (formProvider?.disabled.value || formProvider?.readonly.value || props.disabled || props.readonly) { - return - } - - props.onClick?.(e) - - change(checked.value ? props.uncheckedValue : props.checkedValue) - } - - const sync = (v: any) => { - value.value = v === props.checkedValue ? props.checkedValue : props.uncheckedValue - } - - const reset = () => { - props['onUpdate:modelValue']?.(props.uncheckedValue) - resetValidation() - } - - watch( - () => props.modelValue, - (newValue) => { - value.value = newValue - }, - { immediate: true } - ) - - const radioProvider: RadioProvider = { - sync, - validate, - resetValidation, - reset, - } - - bindRadioGroup?.(radioProvider) - bindForm?.(radioProvider) - - return { - checked, - errorMessage, - radioGroupErrorMessage: radioGroupProvider?.errorMessage, - formDisabled: formProvider?.disabled, - handleClick, - toggle, - reset, - validate, - resetValidation, - } - }, + const { bindParent: bindForm, parentProvider: formProvider } = useParent( + FORM_BIND_FORM_ITEM_KEY + ) + useAtParentIndex(RADIO_GROUP_COUNT_RADIO_KEY) + + const value: Ref = ref(false) + const checked: ComputedRef = computed(() => value.value === props.checkedValue) + + const { errorMessage, validateWithTrigger: vt, validate: v, resetValidation } = useValidation() + + const validate = () => v(props.rules, props.modelValue) + + const validateWithTrigger = (trigger: ValidateTriggers) => + nextTick(() => vt(props.validateTrigger, trigger, props.rules, props.modelValue)) + + const change = (changedValue: any) => { + if (radioGroupProvider && value.value === props.checkedValue) { + return + } + + value.value = changedValue + props['onUpdate:modelValue']?.(value.value) + props.onChange?.(value.value) + + validateWithTrigger('onChange') + + radioGroupProvider?.onToggle(props.checkedValue) + } + + const toggle = (changedValue?: any) => { + const isInvalidValue = changedValue !== props.uncheckedValue && changedValue !== props.checkedValue + if (changedValue != null && (isInvalidValue || changedValue === value.value)) { + return + } + + if (changedValue == null) { + changedValue = checked.value ? props.uncheckedValue : props.checkedValue + } + + change(changedValue) + } + + const handleClick = (e: Event) => { + if (formProvider?.disabled.value || formProvider?.readonly.value || props.disabled || props.readonly) { + return + } + + props.onClick?.(e) + + change(checked.value ? props.uncheckedValue : props.checkedValue) + } + + const sync = (v: any) => { + value.value = v === props.checkedValue ? props.checkedValue : props.uncheckedValue + } + + const reset = () => { + props['onUpdate:modelValue']?.(props.uncheckedValue) + resetValidation() + } + + watch( + () => props.modelValue, + (newValue) => { + value.value = newValue + }, + { immediate: true } + ) + + const radioProvider: RadioProvider = { + sync, + validate, + resetValidation, + reset, + } + + bindRadioGroup?.(radioProvider) + bindForm?.(radioProvider) + + return { + checked, + errorMessage, + radioGroupErrorMessage: radioGroupProvider?.errorMessage, + formDisabled: formProvider?.disabled, + handleClick, + toggle, + reset, + validate, + resetValidation, + } + }, }) diff --git a/packages/varlet-ui/src/radio/example/index.vue b/packages/varlet-ui/src/radio/example/index.vue index 77d452e4db2..b1459030d0f 100644 --- a/packages/varlet-ui/src/radio/example/index.vue +++ b/packages/varlet-ui/src/radio/example/index.vue @@ -18,19 +18,19 @@ import RadioGroup from '../../radio-group' import Button from '../../button' export default defineComponent({ - name: 'RadioExample', - components: { - [Radio.name]: Radio, - [RadioGroup.name]: RadioGroup, - [Icon.name]: Icon, - [Button.name]: Button, - }, - setup() { - return { - v: ref(false), - i: ref(), - } - }, + name: 'RadioExample', + components: { + [Radio.name]: Radio, + [RadioGroup.name]: RadioGroup, + [Icon.name]: Icon, + [Button.name]: Button, + }, + setup() { + return { + v: ref(false), + i: ref(), + } + }, }) diff --git a/packages/varlet-ui/src/radio/index.ts b/packages/varlet-ui/src/radio/index.ts index 051f9d5ae2c..227b436e308 100644 --- a/packages/varlet-ui/src/radio/index.ts +++ b/packages/varlet-ui/src/radio/index.ts @@ -2,7 +2,7 @@ import { App } from 'vue' import Radio from './Radio.vue' Radio.install = function (app: App) { - app.component(Radio.name, Radio) + app.component(Radio.name, Radio) } export default Radio diff --git a/packages/varlet-ui/src/radio/props.ts b/packages/varlet-ui/src/radio/props.ts index 7ef25bf4e75..bfff78d5893 100644 --- a/packages/varlet-ui/src/radio/props.ts +++ b/packages/varlet-ui/src/radio/props.ts @@ -3,50 +3,50 @@ import { PropType } from 'vue' export type ValidateTriggers = 'onChange' export const props = { - modelValue: { - default: false, - }, - disabled: { - type: Boolean, - default: false, - }, - readonly: { - type: Boolean, - default: false, - }, - checkedValue: { - default: true, - }, - uncheckedValue: { - default: false, - }, - checkedColor: { - type: String, - }, - uncheckedColor: { - type: String, - }, - iconSize: { - type: String, - }, - ripple: { - type: Boolean, - default: true, - }, - validateTrigger: { - type: Array as PropType>, - default: ['onChange'], - }, - rules: { - type: Array as PropType any>>, - }, - 'onUpdate:modelValue': { - type: Function, - }, - onChange: { - type: Function, - }, - onClick: { - type: Function, - }, + modelValue: { + default: false, + }, + disabled: { + type: Boolean, + default: false, + }, + readonly: { + type: Boolean, + default: false, + }, + checkedValue: { + default: true, + }, + uncheckedValue: { + default: false, + }, + checkedColor: { + type: String, + }, + uncheckedColor: { + type: String, + }, + iconSize: { + type: String, + }, + ripple: { + type: Boolean, + default: true, + }, + validateTrigger: { + type: Array as PropType>, + default: ['onChange'], + }, + rules: { + type: Array as PropType any>>, + }, + 'onUpdate:modelValue': { + type: Function, + }, + onChange: { + type: Function, + }, + onClick: { + type: Function, + }, } diff --git a/packages/varlet-ui/src/rate/Rate.vue b/packages/varlet-ui/src/rate/Rate.vue index b949f8b05dc..c3d36ac7a45 100644 --- a/packages/varlet-ui/src/rate/Rate.vue +++ b/packages/varlet-ui/src/rate/Rate.vue @@ -1,86 +1,86 @@ diff --git a/packages/varlet-ui/src/rate/props.ts b/packages/varlet-ui/src/rate/props.ts index 57e03cd25eb..ee07c82849a 100644 --- a/packages/varlet-ui/src/rate/props.ts +++ b/packages/varlet-ui/src/rate/props.ts @@ -1,80 +1,80 @@ export const props = { - // 当前分数 - modelValue: { - type: Number, - default: 3, - }, - 'onUpdate:modelValue': { - type: Function, - }, - // 图标总数 - count: { - type: Number, - default: 5, - }, - // 选中时的颜色 - color: { - type: String, - default: '#ff9800', - }, - // 选中时图标样式 - icon: { - type: String, - default: 'star', - }, - // 未选中的图标的颜色 - emptyColor: { - type: String, - default: '#bdbdbd', - }, - // 未选中时图标样式 - emptyIcon: { - type: String, - default: 'star-outline', - }, - // 图标大小 - size: { - type: [String, Number], - default: '20', - }, - // 图标间隔 - marginRight: { - type: [String, Number], - default: '4', - }, + // 当前分数 + modelValue: { + type: Number, + default: 3, + }, + 'onUpdate:modelValue': { + type: Function, + }, + // 图标总数 + count: { + type: Number, + default: 5, + }, + // 选中时的颜色 + color: { + type: String, + default: '#ff9800', + }, + // 选中时图标样式 + icon: { + type: String, + default: 'star', + }, + // 未选中的图标的颜色 + emptyColor: { + type: String, + default: '#bdbdbd', + }, + // 未选中时图标样式 + emptyIcon: { + type: String, + default: 'star-outline', + }, + // 图标大小 + size: { + type: [String, Number], + default: '20', + }, + // 图标间隔 + marginRight: { + type: [String, Number], + default: '4', + }, - // 是否使用半评分 - half: { - type: Boolean, - default: false, - }, - // 选择一半时使用的图标 - halfIcon: { - type: String, - default: 'star-half-full', - }, - // 是否禁用 - disabled: { - type: Boolean, - default: false, - }, - // 禁用后的图标颜色 - disabledColor: { - type: String, - default: '#bdbdbd', - }, - // 是否只读 - readonly: { - type: Boolean, - default: false, - }, - // 点击时是否有水波纹样式 - ripple: { - type: Boolean, - default: false, - }, - // 点击回调 - onChange: { - type: Function, - }, + // 是否使用半评分 + half: { + type: Boolean, + default: false, + }, + // 选择一半时使用的图标 + halfIcon: { + type: String, + default: 'star-half-full', + }, + // 是否禁用 + disabled: { + type: Boolean, + default: false, + }, + // 禁用后的图标颜色 + disabledColor: { + type: String, + default: '#bdbdbd', + }, + // 是否只读 + readonly: { + type: Boolean, + default: false, + }, + // 点击时是否有水波纹样式 + ripple: { + type: Boolean, + default: false, + }, + // 点击回调 + onChange: { + type: Function, + }, } diff --git a/packages/varlet-ui/src/ripple/example/index.vue b/packages/varlet-ui/src/ripple/example/index.vue index d49b67a9060..044ff05fc79 100644 --- a/packages/varlet-ui/src/ripple/example/index.vue +++ b/packages/varlet-ui/src/ripple/example/index.vue @@ -9,15 +9,15 @@ diff --git a/packages/varlet-ui/src/snackbar/index.ts b/packages/varlet-ui/src/snackbar/index.ts index b016130f7f3..9648da06e9c 100644 --- a/packages/varlet-ui/src/snackbar/index.ts +++ b/packages/varlet-ui/src/snackbar/index.ts @@ -7,174 +7,174 @@ import { isBaseObject } from '../utils/shared' export type SnackbarType = 'success' | 'warning' | 'info' | 'error' | 'loading' type SnackbarHandel = { - clear: () => void + clear: () => void } interface SnackbarOptions { - type?: SnackbarType - content?: string - position?: 'top' | 'center' | 'bottom' - loadingType?: string - loadingSize?: string - teleport?: string - lockScroll?: boolean - contentClass?: string - duration?: number - vertical?: boolean - show?: boolean - forbidClick?: boolean - onOpen?: () => void - onClose?: () => void - onOpened?: () => void - onClosed?: () => void + type?: SnackbarType + content?: string + position?: 'top' | 'center' | 'bottom' + loadingType?: string + loadingSize?: string + teleport?: string + lockScroll?: boolean + contentClass?: string + duration?: number + vertical?: boolean + show?: boolean + forbidClick?: boolean + onOpen?: () => void + onClose?: () => void + onOpened?: () => void + onClosed?: () => void } interface UniqSnackbarOptions { - id: number - reactiveSnackOptions: SnackbarOptions - _update?: string + id: number + reactiveSnackOptions: SnackbarOptions + _update?: string } interface Snackbar { - (options: SnackbarOptions): SnackbarHandel + (options: SnackbarOptions): SnackbarHandel - install(app: App): void + install(app: App): void - allowMultiple(bool: boolean): void + allowMultiple(bool: boolean): void - success(options: SnackbarOptions | string): SnackbarHandel + success(options: SnackbarOptions | string): SnackbarHandel - warning(options: SnackbarOptions | string): SnackbarHandel + warning(options: SnackbarOptions | string): SnackbarHandel - info(options: SnackbarOptions | string): SnackbarHandel + info(options: SnackbarOptions | string): SnackbarHandel - error(options: SnackbarOptions | string): SnackbarHandel + error(options: SnackbarOptions | string): SnackbarHandel - loading(options: SnackbarOptions | string): SnackbarHandel + loading(options: SnackbarOptions | string): SnackbarHandel - clear(): void + clear(): void - isAllowMultiple: boolean - isMount: boolean | undefined - uniqSnackbarOptions: UniqSnackbarOptions[] - Component: RendererElement + isAllowMultiple: boolean + isMount: boolean | undefined + uniqSnackbarOptions: UniqSnackbarOptions[] + Component: RendererElement } export const SNACKBAR_TYPE: Array = ['loading', 'success', 'warning', 'info', 'error'] const transitionGroupProps: any = { - name: 'var-snackbar-fade', - tag: 'div', - class: 'var-transition-group', - afterEnter: 'onOpened', - afterLeave: 'onClosed', + name: 'var-snackbar-fade', + tag: 'div', + class: 'var-transition-group', + afterEnter: 'onOpened', + afterLeave: 'onClosed', } const TransitionGroupHost = { - setup() { - return () => { - const snackbarList = Snackbar.uniqSnackbarOptions.map( - ({ id, reactiveSnackOptions, _update }: UniqSnackbarOptions) => { - if (reactiveSnackOptions.forbidClick) { - const transitionGroupEl = document.querySelector('.var-transition-group') - ;(transitionGroupEl as HTMLElement).classList.add('var-pointer-auto') - } - if (Snackbar.isAllowMultiple) reactiveSnackOptions.position = 'top' - return h(VarSnackbarCore, { - ...reactiveSnackOptions, - ...{ - key: id, - 'data-id': id, - style: { - position: 'relative', - top: getTop(reactiveSnackOptions.position), - }, - _update, - 'onUpdate:show': (value: boolean) => { - reactiveSnackOptions.show = value - }, - }, - }) - } - ) - - return h( - TransitionGroup, - { - ...transitionGroupProps, - onAfterLeave: removeUniqOption, - }, - // remove [Vue warn]: Non-function value encountered for default slot. Prefer function slots for better performance - () => snackbarList - ) - } - }, + setup() { + return () => { + const snackbarList = Snackbar.uniqSnackbarOptions.map( + ({ id, reactiveSnackOptions, _update }: UniqSnackbarOptions) => { + if (reactiveSnackOptions.forbidClick) { + const transitionGroupEl = document.querySelector('.var-transition-group') + ;(transitionGroupEl as HTMLElement).classList.add('var-pointer-auto') + } + if (Snackbar.isAllowMultiple) reactiveSnackOptions.position = 'top' + return h(VarSnackbarCore, { + ...reactiveSnackOptions, + ...{ + key: id, + 'data-id': id, + style: { + position: 'relative', + top: getTop(reactiveSnackOptions.position), + }, + _update, + 'onUpdate:show': (value: boolean) => { + reactiveSnackOptions.show = value + }, + }, + }) + } + ) + + return h( + TransitionGroup, + { + ...transitionGroupProps, + onAfterLeave: removeUniqOption, + }, + // remove [Vue warn]: Non-function value encountered for default slot. Prefer function slots for better performance + () => snackbarList + ) + } + }, } const Snackbar: Snackbar = function (options: SnackbarOptions = {}): SnackbarHandel { - const snackOptions: SnackbarOptions = isBaseObject(options) ? options : {} - const reactiveSnackOptions: SnackbarOptions = reactive(snackOptions) - reactiveSnackOptions.show = true - - if (!Snackbar.isMount) { - Snackbar.isMount = true - mountInstance(TransitionGroupHost) - } - - const id = Date.now() - const { length } = Snackbar.uniqSnackbarOptions - const uniqSnackbarOptionItem: UniqSnackbarOptions = { - id, - reactiveSnackOptions, - } - - if (length === 0 || Snackbar.isAllowMultiple) { - addUniqOption(uniqSnackbarOptionItem) - } else { - const _update = `update-${id}` - updateUniqOption(reactiveSnackOptions, _update) - } - - return { - clear() { - if (!Snackbar.isAllowMultiple && Snackbar.uniqSnackbarOptions.length) - Snackbar.uniqSnackbarOptions[0].reactiveSnackOptions.show = false - else reactiveSnackOptions.show = false - }, - } + const snackOptions: SnackbarOptions = isBaseObject(options) ? options : {} + const reactiveSnackOptions: SnackbarOptions = reactive(snackOptions) + reactiveSnackOptions.show = true + + if (!Snackbar.isMount) { + Snackbar.isMount = true + mountInstance(TransitionGroupHost) + } + + const id = Date.now() + const { length } = Snackbar.uniqSnackbarOptions + const uniqSnackbarOptionItem: UniqSnackbarOptions = { + id, + reactiveSnackOptions, + } + + if (length === 0 || Snackbar.isAllowMultiple) { + addUniqOption(uniqSnackbarOptionItem) + } else { + const _update = `update-${id}` + updateUniqOption(reactiveSnackOptions, _update) + } + + return { + clear() { + if (!Snackbar.isAllowMultiple && Snackbar.uniqSnackbarOptions.length) + Snackbar.uniqSnackbarOptions[0].reactiveSnackOptions.show = false + else reactiveSnackOptions.show = false + }, + } } SNACKBAR_TYPE.forEach((type) => { - Snackbar[type] = (options: SnackbarOptions | string): SnackbarHandel => { - if (typeof options === 'string') { - options = { - content: options, - type, - } - } else { - options.type = type - } - return Snackbar(options) - } + Snackbar[type] = (options: SnackbarOptions | string): SnackbarHandel => { + if (typeof options === 'string') { + options = { + content: options, + type, + } + } else { + options.type = type + } + return Snackbar(options) + } }) Snackbar.install = function (app: App) { - app.component(VarSnackbar.name, VarSnackbar) + app.component(VarSnackbar.name, VarSnackbar) } Snackbar.allowMultiple = function (bool = false) { - if (bool !== Snackbar.isAllowMultiple) { - for (let i = 0; i < Snackbar.uniqSnackbarOptions.length; i++) { - Snackbar.uniqSnackbarOptions[i].reactiveSnackOptions.show = false - } - this.isAllowMultiple = !!bool - } + if (bool !== Snackbar.isAllowMultiple) { + for (let i = 0; i < Snackbar.uniqSnackbarOptions.length; i++) { + Snackbar.uniqSnackbarOptions[i].reactiveSnackOptions.show = false + } + this.isAllowMultiple = !!bool + } } Snackbar.clear = function () { - Snackbar.uniqSnackbarOptions.forEach((snackbar: UniqSnackbarOptions) => { - snackbar.reactiveSnackOptions.show = false - }) + Snackbar.uniqSnackbarOptions.forEach((snackbar: UniqSnackbarOptions) => { + snackbar.reactiveSnackOptions.show = false + }) } Snackbar.isAllowMultiple = false @@ -186,29 +186,29 @@ Snackbar.uniqSnackbarOptions = reactive([]) Snackbar.Component = VarSnackbar function removeUniqOption(element: HTMLElement): void { - element.parentElement && element.parentElement.classList.remove('var-pointer-auto') - const id = element.getAttribute('data-id') - for (let i = 0; i < Snackbar.uniqSnackbarOptions.length; i++) { - if (Snackbar.uniqSnackbarOptions[i].id === +(id as string)) Snackbar.uniqSnackbarOptions.splice(i, 1) - } + element.parentElement && element.parentElement.classList.remove('var-pointer-auto') + const id = element.getAttribute('data-id') + for (let i = 0; i < Snackbar.uniqSnackbarOptions.length; i++) { + if (Snackbar.uniqSnackbarOptions[i].id === +(id as string)) Snackbar.uniqSnackbarOptions.splice(i, 1) + } } function addUniqOption(uniqSnackbarOptionItem: UniqSnackbarOptions) { - Snackbar.uniqSnackbarOptions.push(uniqSnackbarOptionItem) + Snackbar.uniqSnackbarOptions.push(uniqSnackbarOptionItem) } function updateUniqOption(reactiveSnackOptions: SnackbarOptions, _update: string) { - Snackbar.uniqSnackbarOptions[0].reactiveSnackOptions = { - ...Snackbar.uniqSnackbarOptions[0].reactiveSnackOptions, - ...reactiveSnackOptions, - } - Snackbar.uniqSnackbarOptions[0]._update = _update + Snackbar.uniqSnackbarOptions[0].reactiveSnackOptions = { + ...Snackbar.uniqSnackbarOptions[0].reactiveSnackOptions, + ...reactiveSnackOptions, + } + Snackbar.uniqSnackbarOptions[0]._update = _update } function getTop(position = 'top'): string { - if (position === 'center') return '45%' - if (position === 'bottom') return '85%' - return '5%' + if (position === 'center') return '45%' + if (position === 'bottom') return '85%' + return '5%' } export default Snackbar diff --git a/packages/varlet-ui/src/snackbar/props.ts b/packages/varlet-ui/src/snackbar/props.ts index 07879232c10..2551b4c143b 100644 --- a/packages/varlet-ui/src/snackbar/props.ts +++ b/packages/varlet-ui/src/snackbar/props.ts @@ -4,92 +4,92 @@ import { props as loadingProps } from '../loading/props' import { SNACKBAR_TYPE, SnackbarType } from './index' export function positionValidator(type: string): boolean { - const validPositions = ['top', 'center', 'bottom'] - return validPositions.includes(type) + const validPositions = ['top', 'center', 'bottom'] + return validPositions.includes(type) } export function typeValidator(type: SnackbarType): boolean { - return SNACKBAR_TYPE.includes(type) + return SNACKBAR_TYPE.includes(type) } export const getPositionDefault = () => 'top' export const props = { - type: { - type: String as PropType, - validator: typeValidator, - }, - // snackbar显示的位置 - position: { - type: String, - default: getPositionDefault, - validator: positionValidator, - }, - // content内容 - content: { - type: String, - }, - // 为snackbar content添加自定义类名 - contentClass: { - type: String, - }, - // snackbar 持续时间 - duration: { - type: Number, - default: 3000, - }, - // 是否将消息条内容堆叠在操作(按钮)之上 - vertical: { - type: Boolean, - default: false, - }, - // 加载动画类型 - loadingType: pickProps(loadingProps, 'type'), - // 加载动画尺寸 - loadingSize: pickProps(loadingProps, 'size'), - // 是否禁止滚动穿透 - lockScroll: { - type: Boolean, - default: false, - }, - // 控制组件可见还是隐藏 - show: { - type: Boolean, - default: false, - }, - // teleport - teleport: { - default: 'body', - }, - // 是否禁止点击背景 - forbidClick: { - type: Boolean, - default: false, - }, - // 打开时的回调函数 - onOpen: { - type: Function, - default: () => {}, - }, - // 打开动画结束时的回调 - onOpened: { - type: Function, - default: () => {}, - }, - // 关闭时的回调函数 - onClose: { - type: Function, - default: () => {}, - }, - // 关闭动画结束时的回调 - onClosed: { - type: Function, - default: () => {}, - }, - 'onUpdate:show': { - type: Function, - }, - _update: { - type: String, - }, + type: { + type: String as PropType, + validator: typeValidator, + }, + // snackbar显示的位置 + position: { + type: String, + default: getPositionDefault, + validator: positionValidator, + }, + // content内容 + content: { + type: String, + }, + // 为snackbar content添加自定义类名 + contentClass: { + type: String, + }, + // snackbar 持续时间 + duration: { + type: Number, + default: 3000, + }, + // 是否将消息条内容堆叠在操作(按钮)之上 + vertical: { + type: Boolean, + default: false, + }, + // 加载动画类型 + loadingType: pickProps(loadingProps, 'type'), + // 加载动画尺寸 + loadingSize: pickProps(loadingProps, 'size'), + // 是否禁止滚动穿透 + lockScroll: { + type: Boolean, + default: false, + }, + // 控制组件可见还是隐藏 + show: { + type: Boolean, + default: false, + }, + // teleport + teleport: { + default: 'body', + }, + // 是否禁止点击背景 + forbidClick: { + type: Boolean, + default: false, + }, + // 打开时的回调函数 + onOpen: { + type: Function, + default: () => {}, + }, + // 打开动画结束时的回调 + onOpened: { + type: Function, + default: () => {}, + }, + // 关闭时的回调函数 + onClose: { + type: Function, + default: () => {}, + }, + // 关闭动画结束时的回调 + onClosed: { + type: Function, + default: () => {}, + }, + 'onUpdate:show': { + type: Function, + }, + _update: { + type: String, + }, } diff --git a/packages/varlet-ui/src/sticky/Sticky.vue b/packages/varlet-ui/src/sticky/Sticky.vue index 0970a82cd4a..a8ec6fb294a 100644 --- a/packages/varlet-ui/src/sticky/Sticky.vue +++ b/packages/varlet-ui/src/sticky/Sticky.vue @@ -32,90 +32,90 @@ import { props } from './props' import { getParentScroller, isPx, remToPx, formatPx } from '../utils/elements' export default defineComponent({ - name: 'VarSticky', - props, - setup(props) { - const stickyEl: Ref = ref(null) - const wrapperEl: Ref = ref(null) - - let isSupportCSSSticky = false - - const isFixed: Ref = ref(false) - const fixedTop: Ref = ref('0px') - const fixedLeft: Ref = ref('0px') - const fixedWidth: Ref = ref('auto') - const fixedHeight: Ref = ref('auto') - const fixedWrapperWidth: Ref = ref('auto') - const fixedWrapperHeight: Ref = ref('auto') - - const offsetTop = computed(() => { - return isPx(props.offsetTop) ? formatPx(props.offsetTop) : remToPx(props.offsetTop) - }) - - let scroller: HTMLElement | Window = window - - const handleScroll = () => { - let scrollerTop = 0 - - if (scroller !== window) { - const { top } = (scroller as HTMLElement).getBoundingClientRect() - scrollerTop = top - } - - const sticky = stickyEl.value as HTMLElement - const wrapper = wrapperEl.value as HTMLElement - - const { top: stickyTop, left: stickyLeft } = sticky.getBoundingClientRect() - const currentOffsetTop = stickyTop - scrollerTop - - if (currentOffsetTop <= offsetTop.value) { - if (!isSupportCSSSticky) { - fixedWidth.value = `${sticky.offsetWidth}px` - fixedHeight.value = `${sticky.offsetHeight}px` - fixedTop.value = `${scrollerTop + offsetTop.value}px` - fixedLeft.value = `${stickyLeft}px` - fixedWrapperWidth.value = `${wrapper.offsetWidth}px` - fixedWrapperHeight.value = `${wrapper.offsetHeight}px` - isFixed.value = true - } - - props.onScroll?.(offsetTop.value, true) - } else { - isFixed.value = false - - props.onScroll?.(currentOffsetTop, false) - } - } - - onMounted(() => { - const sticky = stickyEl.value as HTMLInputElement - - isSupportCSSSticky = ['sticky', '-webkit-sticky'].includes(window.getComputedStyle(sticky).position) - - window.addEventListener('scroll', handleScroll) - scroller = getParentScroller(sticky) - scroller !== window && scroller.addEventListener('scroll', handleScroll) - - handleScroll() - }) - onUnmounted(() => { - window.removeEventListener('scroll', handleScroll) - scroller !== window && scroller.removeEventListener('scroll', handleScroll) - }) - - return { - stickyEl, - wrapperEl, - isFixed, - offsetTop, - fixedTop, - fixedLeft, - fixedWidth, - fixedHeight, - fixedWrapperWidth, - fixedWrapperHeight, - } - }, + name: 'VarSticky', + props, + setup(props) { + const stickyEl: Ref = ref(null) + const wrapperEl: Ref = ref(null) + + let isSupportCSSSticky = false + + const isFixed: Ref = ref(false) + const fixedTop: Ref = ref('0px') + const fixedLeft: Ref = ref('0px') + const fixedWidth: Ref = ref('auto') + const fixedHeight: Ref = ref('auto') + const fixedWrapperWidth: Ref = ref('auto') + const fixedWrapperHeight: Ref = ref('auto') + + const offsetTop = computed(() => { + return isPx(props.offsetTop) ? formatPx(props.offsetTop) : remToPx(props.offsetTop) + }) + + let scroller: HTMLElement | Window = window + + const handleScroll = () => { + let scrollerTop = 0 + + if (scroller !== window) { + const { top } = (scroller as HTMLElement).getBoundingClientRect() + scrollerTop = top + } + + const sticky = stickyEl.value as HTMLElement + const wrapper = wrapperEl.value as HTMLElement + + const { top: stickyTop, left: stickyLeft } = sticky.getBoundingClientRect() + const currentOffsetTop = stickyTop - scrollerTop + + if (currentOffsetTop <= offsetTop.value) { + if (!isSupportCSSSticky) { + fixedWidth.value = `${sticky.offsetWidth}px` + fixedHeight.value = `${sticky.offsetHeight}px` + fixedTop.value = `${scrollerTop + offsetTop.value}px` + fixedLeft.value = `${stickyLeft}px` + fixedWrapperWidth.value = `${wrapper.offsetWidth}px` + fixedWrapperHeight.value = `${wrapper.offsetHeight}px` + isFixed.value = true + } + + props.onScroll?.(offsetTop.value, true) + } else { + isFixed.value = false + + props.onScroll?.(currentOffsetTop, false) + } + } + + onMounted(() => { + const sticky = stickyEl.value as HTMLInputElement + + isSupportCSSSticky = ['sticky', '-webkit-sticky'].includes(window.getComputedStyle(sticky).position) + + window.addEventListener('scroll', handleScroll) + scroller = getParentScroller(sticky) + scroller !== window && scroller.addEventListener('scroll', handleScroll) + + handleScroll() + }) + onUnmounted(() => { + window.removeEventListener('scroll', handleScroll) + scroller !== window && scroller.removeEventListener('scroll', handleScroll) + }) + + return { + stickyEl, + wrapperEl, + isFixed, + offsetTop, + fixedTop, + fixedLeft, + fixedWidth, + fixedHeight, + fixedWrapperWidth, + fixedWrapperHeight, + } + }, })