chore: clean code (#9870)

This commit is contained in:
neverland 2021-11-15 20:09:56 +08:00 committed by GitHub
parent d2d1604276
commit 6244161d6b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 117 additions and 124 deletions

View File

@ -9,6 +9,7 @@ import {
import {
extend,
numericProp,
preventDefault,
makeStringProp,
createNamespace,
BORDER_SURROUND,
@ -135,7 +136,7 @@ export default defineComponent({
const onClick = (event: MouseEvent) => {
if (props.loading) {
event.preventDefault();
preventDefault(event);
} else if (!props.disabled) {
emit('click', event);
route();

View File

@ -12,6 +12,7 @@ import {
isDef,
truthProp,
numericProp,
windowHeight,
makeStringProp,
makeNumericProp,
createNamespace,
@ -86,7 +87,7 @@ export default defineComponent({
if (props.direction === 'down') {
offset.value = rect.bottom;
} else {
offset.value = window.innerHeight - rect.top;
offset.value = windowHeight.value - rect.top;
}
}
};

View File

@ -5,6 +5,7 @@ import {
FORM_KEY,
truthProp,
numericProp,
preventDefault,
makeStringProp,
createNamespace,
} from '../utils';
@ -170,7 +171,7 @@ export default defineComponent({
};
const onSubmit = (event: Event) => {
event.preventDefault();
preventDefault(event);
submit();
};

View File

@ -16,6 +16,8 @@ import {
truthProp,
unknownProp,
Interceptor,
windowWidth,
windowHeight,
makeArrayProp,
makeStringProp,
makeNumericProp,
@ -25,7 +27,7 @@ import {
} from '../utils';
// Composables
import { useRect, useWindowSize } from '@vant/use';
import { useRect } from '@vant/use';
import { useExpose } from '../composables/use-expose';
// Components
@ -78,7 +80,6 @@ export default defineComponent({
setup(props, { emit, slots }) {
const swipeRef = ref<SwipeInstance>();
const windowSize = useWindowSize();
const state = reactive({
active: 0,
@ -185,7 +186,7 @@ export default defineComponent({
onMounted(resize);
watch([windowSize.width, windowSize.height], resize);
watch([windowWidth, windowHeight], resize);
watch(
() => props.startPosition,

View File

@ -14,7 +14,7 @@ class LazyContainer {
this.options = {};
this.lazy = lazy;
this._queue = [];
this.queue = [];
this.update({ el, binding });
}
@ -61,7 +61,7 @@ class LazyContainer {
export default class LazyContainerManager {
constructor({ lazy }) {
this.lazy = lazy;
this._queue = [];
this.queue = [];
}
bind(el, binding, vnode) {
@ -71,19 +71,19 @@ export default class LazyContainerManager {
vnode,
lazy: this.lazy,
});
this._queue.push(container);
this.queue.push(container);
}
update(el, binding, vnode) {
const container = this._queue.find((item) => item.el === el);
const container = this.queue.find((item) => item.el === el);
if (!container) return;
container.update({ el, binding, vnode });
}
unbind(el) {
const container = this._queue.find((item) => item.el === el);
const container = this.queue.find((item) => item.el === el);
if (!container) return;
container.clear();
remove(this._queue, container);
remove(this.queue, container);
}
}

View File

@ -59,7 +59,7 @@ export default (lazyManager) => ({
},
methods: {
init() {
const { src, loading, error } = lazyManager._valueFormatter(this.src);
const { src, loading, error } = lazyManager.valueFormatter(this.src);
this.state.loaded = false;
this.options.src = src;
this.options.error = error;

View File

@ -50,9 +50,9 @@ export default function () {
observerOptions,
}) {
this.mode = modeType.event;
this.ListenerQueue = [];
this.TargetIndex = 0;
this.TargetQueue = [];
this.listeners = [];
this.targetIndex = 0;
this.targets = [];
this.options = {
silent,
dispatchEvent: !!dispatchEvent,
@ -70,10 +70,10 @@ export default function () {
observer: !!observer,
observerOptions: observerOptions || DEFAULT_OBSERVER_OPTIONS,
};
this._initEvent();
this._imageCache = new ImageCache({ max: 200 });
this.initEvent();
this.imageCache = new ImageCache({ max: 200 });
this.lazyLoadHandler = throttle(
this._lazyLoadHandler.bind(this),
this.lazyLoadHandler.bind(this),
this.options.throttleWait
);
@ -94,7 +94,7 @@ export default function () {
* @return {Array}
*/
performance() {
return this.ListenerQueue.map((item) => item.performance());
return this.listeners.map((item) => item.performance());
}
/*
@ -103,12 +103,12 @@ export default function () {
* @return
*/
addLazyBox(vm) {
this.ListenerQueue.push(vm);
this.listeners.push(vm);
if (inBrowser) {
this._addListenerTarget(window);
this._observer && this._observer.observe(vm.el);
this.addListenerTarget(window);
this.observer && this.observer.observe(vm.el);
if (vm.$el && vm.$el.parentNode) {
this._addListenerTarget(vm.$el.parentNode);
this.addListenerTarget(vm.$el.parentNode);
}
}
}
@ -121,17 +121,17 @@ export default function () {
* @return
*/
add(el, binding, vnode) {
if (this.ListenerQueue.some((item) => item.el === el)) {
if (this.listeners.some((item) => item.el === el)) {
this.update(el, binding);
return nextTick(this.lazyLoadHandler);
}
const value = this._valueFormatter(binding.value);
const value = this.valueFormatter(binding.value);
let { src } = value;
nextTick(() => {
src = getBestSelectionFromSrcset(el, this.options.scale) || src;
this._observer && this._observer.observe(el);
this.observer && this.observer.observe(el);
const container = Object.keys(binding.modifiers)[0];
let $parent;
@ -156,16 +156,16 @@ export default function () {
loading: value.loading,
error: value.error,
cors: value.cors,
elRenderer: this._elRenderer.bind(this),
elRenderer: this.elRenderer.bind(this),
options: this.options,
imageCache: this._imageCache,
imageCache: this.imageCache,
});
this.ListenerQueue.push(newListener);
this.listeners.push(newListener);
if (inBrowser) {
this._addListenerTarget(window);
this._addListenerTarget($parent);
this.addListenerTarget(window);
this.addListenerTarget($parent);
}
this.lazyLoadHandler();
@ -180,11 +180,11 @@ export default function () {
* @return
*/
update(el, binding, vnode) {
const value = this._valueFormatter(binding.value);
const value = this.valueFormatter(binding.value);
let { src } = value;
src = getBestSelectionFromSrcset(el, this.options.scale) || src;
const exist = this.ListenerQueue.find((item) => item.el === el);
const exist = this.listeners.find((item) => item.el === el);
if (!exist) {
this.add(el, binding, vnode);
} else {
@ -194,9 +194,9 @@ export default function () {
loading: value.loading,
});
}
if (this._observer) {
this._observer.unobserve(el);
this._observer.observe(el);
if (this.observer) {
this.observer.unobserve(el);
this.observer.observe(el);
}
this.lazyLoadHandler();
nextTick(() => this.lazyLoadHandler());
@ -209,12 +209,12 @@ export default function () {
*/
remove(el) {
if (!el) return;
this._observer && this._observer.unobserve(el);
const existItem = this.ListenerQueue.find((item) => item.el === el);
this.observer && this.observer.unobserve(el);
const existItem = this.listeners.find((item) => item.el === el);
if (existItem) {
this._removeListenerTarget(existItem.$parent);
this._removeListenerTarget(window);
remove(this.ListenerQueue, existItem);
this.removeListenerTarget(existItem.$parent);
this.removeListenerTarget(window);
remove(this.listeners, existItem);
existItem.$destroy();
}
}
@ -226,12 +226,12 @@ export default function () {
*/
removeComponent(vm) {
if (!vm) return;
remove(this.ListenerQueue, vm);
this._observer && this._observer.unobserve(vm.el);
remove(this.listeners, vm);
this.observer && this.observer.unobserve(vm.el);
if (vm.$parent && vm.$el.parentNode) {
this._removeListenerTarget(vm.$el.parentNode);
this.removeListenerTarget(vm.$el.parentNode);
}
this._removeListenerTarget(window);
this.removeListenerTarget(window);
}
setMode(mode) {
@ -242,21 +242,21 @@ export default function () {
this.mode = mode; // event or observer
if (mode === modeType.event) {
if (this._observer) {
this.ListenerQueue.forEach((listener) => {
this._observer.unobserve(listener.el);
if (this.observer) {
this.listeners.forEach((listener) => {
this.observer.unobserve(listener.el);
});
this._observer = null;
this.observer = null;
}
this.TargetQueue.forEach((target) => {
this._initListen(target.el, true);
this.targets.forEach((target) => {
this.initListen(target.el, true);
});
} else {
this.TargetQueue.forEach((target) => {
this._initListen(target.el, false);
this.targets.forEach((target) => {
this.initListen(target.el, false);
});
this._initIntersectionObserver();
this.initIntersectionObserver();
}
}
@ -269,22 +269,22 @@ export default function () {
* @param {DOM} el listener target
* @return
*/
_addListenerTarget(el) {
addListenerTarget(el) {
if (!el) return;
let target = this.TargetQueue.find((target) => target.el === el);
let target = this.targets.find((target) => target.el === el);
if (!target) {
target = {
el,
id: ++this.TargetIndex,
id: ++this.targetIndex,
childrenCount: 1,
listened: true,
};
this.mode === modeType.event && this._initListen(target.el, true);
this.TargetQueue.push(target);
this.mode === modeType.event && this.initListen(target.el, true);
this.targets.push(target);
} else {
target.childrenCount++;
}
return this.TargetIndex;
return this.targetIndex;
}
/*
@ -292,13 +292,13 @@ export default function () {
* @param {DOM} el or window
* @return
*/
_removeListenerTarget(el) {
this.TargetQueue.forEach((target, index) => {
removeListenerTarget(el) {
this.targets.forEach((target, index) => {
if (target.el === el) {
target.childrenCount--;
if (!target.childrenCount) {
this._initListen(target.el, false);
this.TargetQueue.splice(index, 1);
this.initListen(target.el, false);
this.targets.splice(index, 1);
target = null;
}
}
@ -311,13 +311,13 @@ export default function () {
* @param {boolean} start flag
* @return
*/
_initListen(el, start) {
initListen(el, start) {
this.options.ListenEvents.forEach((evt) =>
(start ? on : off)(el, evt, this.lazyLoadHandler)
);
}
_initEvent() {
initEvent() {
this.Event = {
listeners: {
loading: [],
@ -358,9 +358,9 @@ export default function () {
* find nodes which in viewport and trigger load
* @return
*/
_lazyLoadHandler() {
lazyLoadHandler() {
const freeList = [];
this.ListenerQueue.forEach((listener) => {
this.listeners.forEach((listener) => {
if (!listener.el || !listener.el.parentNode) {
freeList.push(listener);
}
@ -369,7 +369,7 @@ export default function () {
listener.load();
});
freeList.forEach((item) => {
remove(this.ListenerQueue, item);
remove(this.listeners, item);
item.$destroy();
});
}
@ -379,19 +379,19 @@ export default function () {
* set mode to observer
* @return
*/
_initIntersectionObserver() {
initIntersectionObserver() {
if (!hasIntersectionObserver) {
return;
}
this._observer = new IntersectionObserver(
this._observerHandler.bind(this),
this.observer = new IntersectionObserver(
this.observerHandler.bind(this),
this.options.observerOptions
);
if (this.ListenerQueue.length) {
this.ListenerQueue.forEach((listener) => {
this._observer.observe(listener.el);
if (this.listeners.length) {
this.listeners.forEach((listener) => {
this.observer.observe(listener.el);
});
}
}
@ -400,13 +400,13 @@ export default function () {
* init IntersectionObserver
* @return
*/
_observerHandler(entries) {
observerHandler(entries) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
this.ListenerQueue.forEach((listener) => {
this.listeners.forEach((listener) => {
if (listener.el === entry.target) {
if (listener.state.loaded)
return this._observer.unobserve(listener.el);
return this.observer.unobserve(listener.el);
listener.load();
}
});
@ -421,7 +421,7 @@ export default function () {
* @param {bool} inCache is rendered from cache
* @return
*/
_elRenderer(listener, state, cache) {
elRenderer(listener, state, cache) {
if (!listener.el) return;
const { el, bindType } = listener;
@ -463,7 +463,7 @@ export default function () {
* @param {string} image's src
* @return {object} image's loading, loaded, error url
*/
_valueFormatter(value) {
valueFormatter(value) {
let src = value;
let { loading, error } = this.options;

View File

@ -30,7 +30,7 @@ export default class ReactiveListener {
this.$parent = $parent;
this.elRenderer = elRenderer;
this._imageCache = imageCache;
this.imageCache = imageCache;
this.performanceData = {
loadStart: 0,
loadEnd: 0,
@ -156,7 +156,7 @@ export default class ReactiveListener {
return;
}
if (this.state.rendered && this.state.loaded) return;
if (this._imageCache.has(this.src)) {
if (this.imageCache.has(this.src)) {
this.state.loaded = true;
this.render('loaded', true);
this.state.rendered = true;
@ -182,7 +182,7 @@ export default class ReactiveListener {
this.record('loadEnd');
this.render('loaded', false);
this.state.rendered = true;
this._imageCache.add(this.src);
this.imageCache.add(this.src);
onFinish();
},
(err) => {

View File

@ -139,8 +139,7 @@ export const loadImageAsync = (item, resolve, reject) => {
const image = new Image();
if (!item || !item.src) {
const err = new Error('image src is required');
return reject(err);
return reject(new Error('image src is required'));
}
image.src = item.src;
@ -163,22 +162,22 @@ export class ImageCache {
this.options = {
max: max || 100,
};
this._caches = [];
this.caches = [];
}
has(key) {
return this._caches.indexOf(key) > -1;
return this.caches.indexOf(key) > -1;
}
add(key) {
if (this.has(key)) return;
this._caches.push(key);
if (this._caches.length > this.options.max) {
this.caches.push(key);
if (this.caches.length > this.options.max) {
this.free();
}
}
free() {
this._caches.shift();
this.caches.shift();
}
}

View File

@ -139,10 +139,7 @@ export default defineComponent({
}
};
watch(
[() => props.loading, () => props.finished, () => props.error],
check
);
watch(() => [props.loading, props.finished, props.error], check);
if (tabStatus) {
watch(tabStatus, (tabActive) => {

View File

@ -1,5 +1,5 @@
import { ref, PropType, defineComponent } from 'vue';
import { numericProp, createNamespace } from '../utils';
import { numericProp, createNamespace, preventDefault } from '../utils';
import { useTouch } from '../composables/use-touch';
import { Loading } from '../loading';
@ -61,7 +61,7 @@ export default defineComponent({
// eliminate tap delay on safari
// see: https://github.com/youzan/vant/issues/6836
if (!slots.default) {
event.preventDefault();
preventDefault(event);
}
active.value = false;
emit('press', props.text, props.type);

View File

@ -247,14 +247,14 @@ export default defineComponent({
// fix mobile safari page scroll down issue
// see: https://github.com/youzan/vant/issues/7690
if (props.disableInput) {
event.preventDefault();
preventDefault(event);
}
};
const createListeners = (type: 'plus' | 'minus') => ({
const createListeners = (type: typeof actionType) => ({
onClick: (event: MouseEvent) => {
// disable double tap scrolling on mobile safari
event.preventDefault();
preventDefault(event);
actionType = type;
onChange();
},
@ -267,12 +267,7 @@ export default defineComponent({
});
watch(
[
() => props.max,
() => props.min,
() => props.integer,
() => props.decimalLength,
],
() => [props.max, props.min, props.integer, props.decimalLength],
check
);

View File

@ -1,6 +1,6 @@
import { nextTick, ref } from 'vue';
import { VueWrapper } from '@vue/test-utils';
import { mockScrollTop, mount } from '../../../test';
import { mockScrollTop, trigger, mount } from '../../../test';
import { Sticky } from '..';
import { ComponentInstance } from '../../utils';
@ -130,6 +130,7 @@ test('should allow to using offset-top prop with rem unit', async () => {
test('should allow to using offset-top prop with vw unit', async () => {
Object.defineProperty(window, 'innerWidth', { value: 300 });
trigger(window, 'resize');
const wrapper = mount({
render() {

View File

@ -19,18 +19,15 @@ import {
isHidden,
truthProp,
numericProp,
windowWidth,
windowHeight,
preventDefault,
createNamespace,
makeNumericProp,
} from '../utils';
// Composables
import {
doubleRaf,
useChildren,
useWindowSize,
usePageVisibility,
} from '@vant/use';
import { doubleRaf, useChildren, usePageVisibility } from '@vant/use';
import { useTouch } from '../composables/use-touch';
import { useExpose } from '../composables/use-expose';
import { onPopupReopen } from '../composables/on-popup-reopen';
@ -78,7 +75,6 @@ export default defineComponent({
});
const touch = useTouch();
const windowSize = useWindowSize();
const { children, linkChildren } = useChildren(SWIPE_KEY);
const count = computed(() => children.length);
@ -413,7 +409,7 @@ export default defineComponent({
watch(count, () => initialize(state.active));
watch(() => props.autoplay, autoplay);
watch([windowSize.width, windowSize.height], resize);
watch([windowWidth, windowHeight], resize);
watch(usePageVisibility(), (visible) => {
if (visible === 'visible') {
autoplay();

View File

@ -24,6 +24,7 @@ import {
truthProp,
numericProp,
Interceptor,
windowWidth,
getElementTop,
makeStringProp,
callInterceptor,
@ -39,7 +40,6 @@ import { scrollLeftTo, scrollTopTo } from './utils';
import {
useRect,
useChildren,
useWindowSize,
useScrollParent,
useEventListener,
onMountedOrActivated,
@ -123,7 +123,6 @@ export default defineComponent({
const navRef = ref<HTMLElement>();
const wrapRef = ref<HTMLElement>();
const windowSize = useWindowSize();
const scroller = useScrollParent(root);
const [titleRefs, setTitleRefs] = useRefs<ComponentInstance>();
const { children, linkChildren } = useChildren(TABS_KEY);
@ -408,7 +407,7 @@ export default defineComponent({
);
};
watch([() => props.color, windowSize.width], setLine);
watch([() => props.color, windowWidth], setLine);
watch(
() => props.active,

View File

@ -1,4 +1,4 @@
import { useRect } from '@vant/use';
import { useRect, useWindowSize } from '@vant/use';
import { unref, Ref } from 'vue';
import { isIOS as checkIsIOS } from './validate';
@ -84,3 +84,5 @@ export function isHidden(
return hidden || parentHidden;
}
export const { width: windowWidth, height: windowHeight } = useWindowSize();

View File

@ -1,6 +1,6 @@
import { CSSProperties } from 'vue';
import { useWindowSize } from '@vant/use';
import { inBrowser } from './basic';
import { windowWidth, windowHeight } from './dom';
import { isDef, isNumeric } from './validate';
export function addUnit(value?: string | number): string | undefined {
@ -51,15 +51,13 @@ function convertRem(value: string) {
}
function convertVw(value: string) {
const { width } = useWindowSize();
value = value.replace(/vw/g, '');
return (+value * width.value) / 100;
return (+value * windowWidth.value) / 100;
}
function convertVh(value: string) {
const { height } = useWindowSize();
value = value.replace(/vh/g, '');
return (+value * height.value) / 100;
return (+value * windowHeight.value) / 100;
}
export function unitToPx(value: string | number): number {

View File

@ -3,6 +3,7 @@ import { deepClone } from '../deep-clone';
import { deepAssign } from '../deep-assign';
import { isDef, isMobile, isNumeric } from '../validate';
import { addUnit, unitToPx, camelize, formatNumber } from '../format';
import { trigger } from '../../../test';
test('deepClone', () => {
const a = { foo: 0 };
@ -110,6 +111,7 @@ test('unitToPx', () => {
Object.defineProperty(window, 'innerWidth', { value: 100 });
Object.defineProperty(window, 'innerHeight', { value: 200 });
trigger(window, 'resize');
expect(unitToPx(0)).toEqual(0);
expect(unitToPx(10)).toEqual(10);