feat: add options for autoresize

* add `throttle: number` to specify throttle delay (#419 #562)
* add `onResize: () => void` to specify a resize callback (#714)
This commit is contained in:
Justineo
2023-06-13 20:35:45 +08:00
parent 47f7885f19
commit e8697382a1
8 changed files with 99 additions and 56 deletions

View File

@ -1,26 +1,42 @@
import { Ref, watch } from "vue-demi";
import { watch, type Ref, type PropType } from "vue-demi";
import { throttle } from "echarts/core";
import { addListener, removeListener, ResizeCallback } from "resize-detector";
import { EChartsType } from "../types";
import {
addListener,
removeListener,
type ResizeCallback
} from "resize-detector";
import { type EChartsType } from "../types";
type AutoresizeProp =
| boolean
| {
throttle?: number;
onResize?: () => void;
};
export function useAutoresize(
chart: Ref<EChartsType | undefined>,
autoresize: Ref<boolean>,
autoresize: Ref<AutoresizeProp | undefined>,
root: Ref<HTMLElement | undefined>
): void {
let resizeListener: ResizeCallback | null = null;
watch([root, chart, autoresize], ([root, chart, autoresize], _, cleanup) => {
if (root && chart && autoresize) {
resizeListener = throttle(() => {
chart.resize();
}, 100);
const autoresizeOptions = autoresize === true ? {} : autoresize;
const { throttle: wait = 100, onResize } = autoresizeOptions;
const callback = () => {
chart.resize();
onResize?.();
};
resizeListener = wait ? throttle(callback, wait) : callback;
addListener(root, resizeListener);
}
cleanup(() => {
if (resizeListener && root) {
if (root && resizeListener) {
removeListener(root, resizeListener);
}
});
@ -28,5 +44,5 @@ export function useAutoresize(
}
export const autoresizeProps = {
autoresize: Boolean
autoresize: [Boolean, Object] as PropType<AutoresizeProp>
};

View File

@ -4,21 +4,20 @@ import {
computed,
watchEffect,
type Ref,
type InjectionKey
type InjectionKey,
type PropType
} from "vue-demi";
import { EChartsType } from "../types";
import type { EChartsType, LoadingOptions } from "../types";
export const LOADING_OPTIONS_KEY =
"ecLoadingOptions" as unknown as InjectionKey<
UnknownRecord | Ref<UnknownRecord>
LoadingOptions | Ref<LoadingOptions>
>;
type UnknownRecord = Record<string, unknown>;
export function useLoading(
chart: Ref<EChartsType | undefined>,
loading: Ref<boolean>,
loadingOptions: Ref<UnknownRecord | undefined>
loadingOptions: Ref<LoadingOptions | undefined>
): void {
const defaultLoadingOptions = inject(LOADING_OPTIONS_KEY, {});
const realLoadingOptions = computed(() => ({
@ -42,5 +41,5 @@ export function useLoading(
export const loadingProps = {
loading: Boolean,
loadingOptions: Object
loadingOptions: Object as PropType<LoadingOptions>
};