UNPKG

@antdv/pro-utils

Version:

@antdv/pro-utils

130 lines (129 loc) 3.15 kB
import { isRef, nextTick, watch } from "vue"; import { promiseTimeout, toValue } from "../../vueuse/utils.mjs"; function createUntil(r, isNot = false) { function toMatch(condition, { flush = "sync", deep = false, timeout, throwOnTimeout } = {}) { let stop = null; const watcher = new Promise((resolve) => { stop = watch( r, (v) => { if (condition(v) !== isNot) { if (stop) stop(); else nextTick(() => stop == null ? void 0 : stop()); resolve(v); } }, { flush, deep, immediate: true } ); }); const promises = [watcher]; if (timeout != null) { promises.push( promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => stop == null ? void 0 : stop()) ); } return Promise.race(promises); } function toBe(value, options) { if (!isRef(value)) return toMatch((v) => v === value, options); const { flush = "sync", deep = false, timeout, throwOnTimeout } = options != null ? options : {}; let stop = null; const watcher = new Promise((resolve) => { stop = watch( [r, value], ([v1, v2]) => { if (isNot !== (v1 === v2)) { if (stop) stop(); else nextTick(() => stop == null ? void 0 : stop()); resolve(v1); } }, { flush, deep, immediate: true } ); }); const promises = [watcher]; if (timeout != null) { promises.push( promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => { stop == null ? void 0 : stop(); return toValue(r); }) ); } return Promise.race(promises); } function toBeTruthy(options) { return toMatch((v) => Boolean(v), options); } function toBeNull(options) { return toBe(null, options); } function toBeUndefined(options) { return toBe(void 0, options); } function toBeNaN(options) { return toMatch(Number.isNaN, options); } function toContains(value, options) { return toMatch((v) => { const array = Array.from(v); return array.includes(value) || array.includes(toValue(value)); }, options); } function changed(options) { return changedTimes(1, options); } function changedTimes(n = 1, options) { let count = -1; return toMatch(() => { count += 1; return count >= n; }, options); } if (Array.isArray(toValue(r))) { const instance = { toMatch, toContains, changed, changedTimes, get not() { return createUntil(r, !isNot); } }; return instance; } else { const instance = { toMatch, toBe, toBeTruthy, toBeNull, toBeNaN, toBeUndefined, changed, changedTimes, get not() { return createUntil(r, !isNot); } }; return instance; } } function until(r) { return createUntil(r); } export { until };