UNPKG

@naturefw/ui-core

Version:

二次封装 UI库 共用的 JavaScript 函数库。TS 版

1,693 lines (1,635 loc) 43.4 kB
import { inject, provide, onBeforeMount, onMounted, nextTick, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onErrorCaptured, onRenderTracked, onRenderTriggered, onActivated, onDeactivated, reactive, watch, defineAsyncComponent, computed, customRef } from 'vue'; var config = { baseUrl: "/", axios }; function webAPI(url, query = "", body = null) { return new Promise((resolve, reject) => { const _url = `${config.baseUrl === "/" ? "/" : config.baseUrl}${url}${query ? "?" + query : ""}`; if (body === null) { config.axios.get(_url).then((res) => { resolve(res.data); }).catch((err) => { reject(err); }); } else { config.axios.post(_url, body).then((res) => { resolve(res.data); }).catch((err) => { reject(err); }); } }); } function log() { if (window.__showlog) { console.log(...arguments); } } const logTime = (msg, auto = true) => { const start = () => { if (window.__showlog) console.time(msg); }; const end = (msg2 = null) => { if (window.__showlog) { console.timeEnd(msg); if (!msg2) console.log(msg2); } }; if (auto) start(); return { start, end }; }; const f = Symbol("___nf-liefcycle___"); const flagCallback = Symbol("___nf-liefcycle-callback___"); function lifecycle(_flag, isTime = false, _events = {}) { const events = inject(flagCallback) ?? {}; provide(flagCallback, _events); if (typeof events.start === "function") events.start(); const _parentflag = inject(f); const flag = _parentflag ? _parentflag + "----" + _flag : _flag; provide(f, flag); const t = isTime ? logTime(`${flag}\u2014\u2014\u3010\u52A0\u8F7D\u3011\u7528\u65F6`) : { end: () => { } }; let t2 = null; onBeforeMount(() => { }); onMounted(() => { t.end(); if (typeof events.end === "function") { nextTick(() => { events.end(); }); } }); onBeforeUpdate(() => { if (isTime) { t2 = logTime(`${flag}\u2014\u2014\u3010\u66F4\u65B0\u3011 \u7528\u65F6`); } else { t2 = null; } }); onUpdated(() => { if (isTime) t2.end(); }); onBeforeUnmount(() => { if (isTime) { t2 = logTime(`${flag}\u2014\u2014\u3010\u5378\u8F7D\u3011\u7528\u65F6`); } else { t2 = null; } }); onUnmounted(() => { if (isTime) t2.end(); }); onErrorCaptured((res) => { log(`${flag} == onErrorCaptured`, res); }); onRenderTracked((res) => { }); onRenderTriggered((res) => { }); onActivated((res) => { log(`${flag} == onActivated`, res); }); onDeactivated((res) => { log(`${flag} == onDeactivated`, res); }); } const flag = Symbol("nf-router-menu___"); const treeToKey = (menus, list, paths = "") => { menus.forEach((_menu) => { let _comp = _menu.component ?? ""; if (typeof _comp === "function") { _comp = defineAsyncComponent(_comp); } list[_menu.menuId] = { menuId: _menu.menuId, title: _menu.title, path: _menu.path, paths: paths + "/" + _menu.path, component: _comp }; if (Array.isArray(_menu.childrens)) { treeToKey(_menu.childrens, list, list[_menu.menuId].paths); } }); return list; }; class Router { baseUrl; baseTitle; isRefresh; home; menus; menuList; tabs; currentRoute; constructor(info) { this.currentRoute = reactive({ key: "home", paths: [] }); this.baseUrl = info.baseUrl; this.home = info.home; this.menus = reactive(info.menus); this.baseTitle = document.title; this.isRefresh = false; this.menuList = {}; this.tabs = reactive(/* @__PURE__ */ new Set([])); this.setup(); } setup = () => { watch(() => this.currentRoute.key, (key) => { if (key !== "home") this.tabs.add(key); if (this.isRefresh) { this.isRefresh = false; return; } let _title = this.baseTitle; let _url = this.baseUrl; this.currentRoute.paths.forEach((key2) => { const _menu = this.menuList[key2]; _title = _menu.title + "-" + _title; _url += "/" + _menu.path; }); document.title = _title; window.history.pushState(null, null, _url); }); this.menuList = treeToKey(this.menus, {}); }; addRoute(newMenus, props) { let _parent = this.menus; const path = props.path ?? []; const index = props.index ?? null; if (path.length > 0) { path.forEach((id) => { const tmp2 = _parent.find((m) => m.menuId === id); if (!tmp2) { console.error("\u6CA1\u6709\u627E\u5230 \u7236\u7EA7\u83DC\u5355\uFF1A", id, this.menus); return; } if (!tmp2.childrens) { tmp2.childrens = []; } _parent = tmp2.childrens; }); } newMenus.forEach((_menu) => { if (_parent.findIndex((item) => item.menuId === _menu.menuId) === -1) { if (index === null) { _parent.push(_menu); } else { _parent.splice(index, 0, _menu); } } }); const tmp = treeToKey(newMenus, {}); Object.assign(this.menuList, tmp); } removeRoute(path = [], id = "") { let _parent = this.menus; let hasParent = true; if (path.length > 0) { path.forEach((id2, i) => { const tmp = _parent.find((m) => m.menuId === id2); if (!tmp) { console.error(`\u6CA1\u6709\u627E\u5230 \u7236\u7EA7\u83DC\u5355\uFF0C\u4F4D\u7F6E\uFF1A${i}\uFF0CID\uFF1A${id2}\uFF0C\u83DC\u5355\uFF1A`, this.menus); hasParent = false; } _parent = tmp.childrens; if (!_parent) { console.error(`\u6CA1\u6709\u5B50\u83DC\u5355\uFF0Cpath\uFF1A`, path, this.menus); hasParent = false; } }); } if (hasParent) { const index = _parent.findIndex((m) => m.menuId === id); if (index > -1) { _parent.splice(index, 1); } } } refresh = () => { const path = window.location.pathname; if (path === "/" || path === this.baseUrl) ; else { this.isRefresh = true; const tmp = path.replace(this.baseUrl, ""); Object.keys(this.menuList).forEach((key) => { const _menu = this.menuList[key]; if (_menu.paths === tmp) { this.currentRoute.key = key; document.title = _menu.title + "-" + this.baseTitle; } }); } }; getComponent = () => { if (this.currentRoute.key === "" || this.currentRoute.key === "home") { return this.home; } else { return this.menuList[this.currentRoute.key].component; } }; removeTab = (key) => { const arr = Array.from(this.tabs); if (arr.length === 1) { this.tabs.delete(key); this.currentRoute.key = "home"; return; } if (this.currentRoute.key === key) { const index = arr.indexOf(key); if (index === 0) { this.currentRoute.key = arr[1]; } else { this.currentRoute.key = arr[index - 1]; } } this.tabs.delete(key); }; install = (app) => { app.config.globalProperties.$router = this; app.provide(flag, this); }; } const createRouter = (info) => { const router = new Router(info); setTimeout(() => { router.refresh(); }, 300); return router; }; function useRouter() { return inject(flag); } const itemProps = { formItemMeta: { type: Object, default: () => { return {}; } }, optionList: { type: Object, default: () => { return []; } }, model: { type: Object }, clearable: { type: Boolean, default: true }, title: { type: String, default: "" }, size: { type: String, default: "" } }; const formProps = { model: { type: Object, required: true }, partModel: { type: Object, default: () => { return {}; } }, formMeta: { type: Object, default: () => { return {}; } }, itemMeta: { type: Object, default: () => { return {}; } }, labelSuffix: { type: String, default: "\uFF1A" }, labelWidth: { type: String, default: "130px" }, size: { type: String, default: "small" } }; const findProps = { findMeta: { moduleId: [Number, String], quickFind: { type: Array, default: () => { return []; } }, allFind: { type: Array, default: () => { return []; } }, customer: { type: Array, default: () => { return []; } }, customerDefault: { type: [Number, String], default: 1 }, reload: { type: Boolean, default: false } }, queryMini: { type: Object, default: () => { return []; } }, querys: { type: Array, default: () => { return {}; } }, itemMeta: { type: Object, default: () => { return {}; } } }; const gridProps = { gridMeta: { type: Object }, height: { type: [Number, String], default: 500 }, stripe: { type: Boolean, default: true }, border: { type: Boolean, default: true }, fit: { type: Boolean, default: true }, highlightCurrentRow: { type: Boolean, default: true }, itemMeta: { type: Object }, selection: { type: Object, default: () => { return { dataId: "", row: {}, dataIds: [], rows: [] }; } }, dataList: { type: Array, default: () => [] } }; const getChildrenOne = (data, parentId, level) => { const arr = []; const opts = data.filter((item) => item.parentId == parentId); for (let i = 0; i < opts.length; i++) { arr.push({ value: opts[i].value, label: opts[i].label, leaf: false, children: [...getChildrenOne(data, opts[i].value)] }); if (arr[arr.length - 1].children.length === 0) { delete arr[arr.length - 1].children; arr[arr.length - 1].leaf = true; } } return arr; }; const getChildren = (data, parentId, level) => { const arr = []; const maxLevel = data.levelName.length; if (maxLevel === level) { return arr; } else { const levelName = data.levelName[level]; const opts = data[levelName].filter((item) => item.parentId === parentId); for (let i = 0; i < opts.length; i++) { arr.push({ value: opts[i].value, label: opts[i].label, leaf: false, children: [...getChildren(data, opts[i].value, level + 1)] }); if (arr[arr.length - 1].children.length === 0) { delete arr[arr.length - 1].children; arr[arr.length - 1].leaf = true; } } return arr; } }; const shallowToDeep = (data) => { const arr = []; const levelName = data.levelName; const opts = data[levelName[0]]; for (let i = 0; i < opts.length; i++) { arr.push({ value: opts[i].value, label: opts[i].label, leaf: false, children: [...getChildren(data, opts[i].value, 1)] }); if (arr[arr.length - 1].children.length === 0) { delete arr[arr.length - 1].children; arr[arr.length - 1].leaf = true; } } return arr; }; const cascaderManage = (data) => { const levelName = data.levelName; const propsCascader = { lazy: false, lazyLoad(node, resolve) { const { level } = node; if (levelName.length >= level) { const key = levelName[level]; const newNode = data[key].filter((item) => item.parentId === node.value); resolve(newNode); } else { resolve([{ value: "22", label: "\u9009\u987911", leaf: true }]); } } }; return { propsCascader }; }; function modelRef(model, colName) { return computed({ get() { return model[colName]; }, set(val) { model[colName] = val; } }); } function debounceRef$1(props, emit, key, events, delay = 500) { let timeout; let _value = props[key]; events.run = () => { clearTimeout(timeout); emit(`update:${key.toString()}`, _value); }; events.clear = () => { clearTimeout(timeout); }; return customRef((track, trigger) => { watch(() => props[key], (v1) => { _value = v1; trigger(); }); return { get() { track(); return _value; }, set(val) { _value = val; trigger(); clearTimeout(timeout); timeout = setTimeout(() => { emit(`update:${key.toString()}`, val); }, delay); } }; }); } function emitRef(props, emit, key) { return customRef((track, trigger) => { return { get() { track(); return props[key]; }, set(val) { trigger(); emit(`update:${key.toString()}`, val); } }; }); } function rangeRef(model, arrColName) { return customRef((track, trigger) => { return { get() { track(); const tmp = []; arrColName.forEach((col) => { tmp.push(model[col]); }); return tmp; }, set(arrVal) { trigger(); if (arrVal) { arrColName.forEach((col, i) => { if (i < arrVal.length) { model[col] = arrVal[i]; } else { model[col] = ""; } }); } else { arrColName.forEach((col) => { model[col] = ""; }); } } }; }); } function range2Ref(model, ...arrColName) { return customRef((track, trigger) => { return { get() { track(); const tmp = []; arrColName.forEach((col) => { tmp.push(model[col]); }); return tmp; }, set(arrVal) { trigger(); if (arrVal) { arrColName.forEach((col, i) => { if (i < arrVal.length) { model[col] = arrVal[i]; } else { model[col] = ""; } }); } else { arrColName.forEach((col) => { model[col] = ""; }); } } }; }); } function debounceRef(model, colName, events, delay = 500) { let timeout; let _value = model[colName]; events.run = () => { clearTimeout(timeout); model[colName] = _value; }; events.clear = () => { clearTimeout(timeout); }; return customRef((track, trigger) => { watch(() => model[colName], (v1) => { _value = v1; trigger(); }); return { get() { track(); return _value; }, set(val) { _value = val; trigger(); clearTimeout(timeout); timeout = setTimeout(() => { model[colName] = _value; }, delay); } }; }); } function loadController(props) { const { webAPI: webAPI$1, optionList } = props; const loadDict = () => { if (webAPI$1?.serviceId) { const url = `${webAPI$1.serviceId === "" ? "" : webAPI$1.serviceId}${webAPI$1.actionId === "" ? "" : webAPI$1.actionId}${webAPI$1.dataId === "" ? "" : webAPI$1.dataId}`; webAPI(url, "").then((res) => { if (Array.isArray(res)) { optionList.length = 0; optionList.push(...res); } }).catch((err) => { console.error("\u540E\u7AEF\u53CD\u9988 - err", err); }); } }; const loadDictById = (actionId, id) => { return new Promise((resolve, reject) => { if (webAPI$1.serviceId !== null) { const url = `${webAPI$1.serviceId === "" ? "" : webAPI$1.serviceId}/${actionId}/${id}`; webAPI(url, "").then((res) => { if (Array.isArray(res)) { resolve(res); } else { reject({ err: "\u4E0D\u662F\u6570\u7EC4" }); } }).catch((err) => { reject(err); }); } }); }; return { loadDict, loadDictById }; } function itemController(props, emit, events) { const { model, formItemMeta } = props; const ctlEvents = { run: () => { }, clear: () => { } }; const run = () => { ctlEvents.run(); }; const clear = (e) => { if (e.key !== "Backspace") { ctlEvents.clear(); } }; let value; if (model) { let isMoreColumn = false; const colName = props.colName ?? formItemMeta.colName; let tmpArrayColName = []; if (typeof colName === "string") { tmpArrayColName = colName.split("_"); isMoreColumn = tmpArrayColName.length > 1; } if (isMoreColumn && tmpArrayColName) { value = rangeRef(model, tmpArrayColName); } else { if (formItemMeta.delay && formItemMeta.delay > 0) { value = debounceRef(model, colName, ctlEvents, formItemMeta.delay); } else { value = modelRef(model, colName); } } } else { if (formItemMeta.delay && formItemMeta.delay > 0) { value = debounceRef$1(props, emit, "modelValue", ctlEvents, formItemMeta.delay); } else { value = emitRef(props, emit, "modelValue"); } } return { value, run, clear }; } const moreColName = (m, formModel, defVal = []) => { const arr = m.colName.split("_"); if (arr.length === 1) { formModel[m.colName] = defVal; } else { arr.forEach((col) => { formModel[col] = ""; }); } }; const createModel = (meta, colOrder) => { const formModel = reactive({}); colOrder.forEach((key) => { const m = meta[key].formItemMeta; switch (m.controlType) { case 1: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 140: case 141: case 142: formModel[m.colName] = ""; break; case 110: case 111: case 112: formModel[m.colName] = 0; break; case 120: case 121: case 122: case 124: case 123: formModel[m.colName] = ""; break; case 125: case 126: case 127: case 128: moreColName(m, formModel); break; case 130: case 132: formModel[m.colName] = ""; break; case 131: case 133: moreColName(m, formModel); break; case 150: case 151: formModel[m.colName] = false; break; case 152: formModel[m.colName] = []; break; case 153: case 160: case 162: case 165: formModel[m.colName] = null; break; case 161: case 163: case 166: formModel[m.colName] = []; break; case 164: moreColName(m, formModel); break; case 170: moreColName(m, formModel); break; default: moreColName(m, formModel); break; } if (typeof m.defValue !== "undefined" && m.controlType !== 162) { switch (m.defValue) { case "": break; case "{}": formModel[m.colName] = {}; break; case "[]": formModel[m.colName] = []; break; case "{{now}}": formModel[m.colName] = new Date(); break; default: formModel[m.colName] = m.defValue; break; } } }); return formModel; }; const getColSpan = (columnsNumber, itemMeta) => { const formColSpan = reactive({}); const setFormColSpan = (num = columnsNumber) => { const moreColSpan = 24 / num; for (const key in itemMeta) { const m = itemMeta[key].formItemMeta; if (typeof m.colCount === "number") { if (num === 1) { formColSpan[m.columnId] = m.colCount >= 1 ? moreColSpan : moreColSpan / (0 - m.colCount); } else { formColSpan[m.columnId] = m.colCount < 1 ? moreColSpan : moreColSpan * m.colCount; } if (formColSpan[m.columnId] > 24) { formColSpan[m.columnId] = 24; } } else { formColSpan[m.columnId] = moreColSpan; } } }; return { formColSpan, setFormColSpan }; }; const createPartModel = (model, partModel, itemMeta, showCol) => { for (const key in partModel) { delete partModel[key]; } for (const key in showCol) { if (showCol[key]) { const colName = itemMeta[key].formItemMeta.colName; const arr = colName.split("_"); if (arr.length === 1) { partModel[colName] = model[colName] || ""; } else { partModel[colName] = model[colName] || ""; arr.forEach((i) => { partModel[i] = model[i] || ""; }); } } } }; const setControlShow = (formMeta, itemMeta, model, partModel) => { const { linkageMeta, colOrder } = formMeta; const showCol = reactive({}); const setShow = () => { if (typeof itemMeta === "object") { for (const key in itemMeta) { showCol[key] = true; } } }; const setFormColShow = () => { setShow(); if (typeof linkageMeta === "object" && Object.keys(linkageMeta).length > 0) { for (const key in linkageMeta) { const ctl = linkageMeta[key]; const colName = itemMeta[key].formItemMeta.colName; if (typeof model[colName] !== "undefined") { watch(() => model[colName], (v1, v2) => { if (v1 === null) { Object.keys(itemMeta).forEach((key2) => { showCol[key2] = true; }); } else if (typeof ctl[v1] !== "undefined") { if (typeof v1 === "boolean") { ctl[v1].forEach((id) => { let _id = id; let bl = v1; if (Array.isArray(id)) { _id = id[0]; const colName2 = itemMeta[_id].formItemMeta.colName; model[colName2] = id[1]; } if (typeof _id === "string") { bl = !v1; } showCol[_id] = bl; }); } else { Object.keys(itemMeta).forEach((key2) => { showCol[key2] = false; }); ctl[v1].forEach((id) => { showCol[id] = true; }); } createPartModel(model, partModel, itemMeta, showCol); } }, { immediate: true }); } } if (typeof partModel !== "undefined") { watch(model, () => { for (const key in model) { if (typeof partModel[key] !== "undefined") { partModel[key] = model[key]; } } }); } } }; setFormColShow(); watch(() => colOrder, (order) => { order.forEach((id) => { showCol[id] = true; }); }); return { showCol, setFormColShow }; }; function formController(formMeta, itemMeta, model, partModel) { const { ruleMeta, colOrder } = formMeta; const defauleModel = createModel(itemMeta, colOrder); if (Object.keys(model).length < Object.keys(defauleModel).length) { for (const key in defauleModel) { if (typeof model[key] === "undefined") { model[key] = defauleModel[key]; } } } const { formColSpan, setFormColSpan } = getColSpan(formMeta.columnsNumber, itemMeta); watch(() => formMeta.columnsNumber, (num) => { setFormColSpan(num); }, { immediate: true }); watch(itemMeta, (v1) => { setFormColSpan(); }); const { showCol, setFormColShow } = setControlShow(formMeta, itemMeta, model, partModel); watch(formMeta.linkageMeta, () => { setFormColShow(); }); for (const key in itemMeta) { if (typeof ruleMeta[key] === "undefined") ; } watch(formMeta.colOrder, () => { setFormColShow(); setFormColSpan(); }); formMeta.reset = () => { setFormColShow(); }; return { formColSpan, showCol, setFormColShow }; } const findKindDict = { 21: { id: 21, name: " = ", where: "{col} = ?" }, 22: { id: 22, name: " \u2260 ", where: "{col} <> ?" }, 23: { id: 23, name: "\u5305\u542B", where: '{col} like "%?%"' }, 24: { id: 24, name: "no\u5305\u542B", where: '{col} not like "%?%"' }, 25: { id: 25, name: "\u8D77\u59CB\u4E8E", where: '{col} like "?%"' }, 26: { id: 26, name: "\u7ED3\u675F\u4E8E", where: '{col} like "%?"' }, 27: { id: 27, name: "no\u8D77\u59CB", where: '{col} not like "?%"' }, 28: { id: 28, name: "no\u7ED3\u675F", where: '{col} not like "%?"' }, 13: { id: 13, name: " > ", where: "{col} > ?" }, 14: { id: 14, name: " \u2265 ", where: "{col} >= ?" }, 15: { id: 15, name: " < ", where: "{col} < ?" }, 16: { id: 16, name: " \u2264 ", where: "{col} <= ?" }, 17: { id: 17, name: "\u4ECE", where: "{col} between ? and ?" }, 18: { id: 18, name: "< X \u2264", where: "{col} > ? and {col} <= ?" }, 19: { id: 19, name: "\u2264 X <", where: "{col} >= ? and {col} < ?" }, 40: { id: 40, name: " \u5305\u542B ", where: "( {col} like %?% or {col} like %?% ... ) " }, 41: { id: 41, name: " \u5305\u542B ", where: "{col} in (?)" }, 42: { id: 42, name: " \u4E0D\u5305\u542B ", where: "{col} not in (?)" } }; function createDataList(meta, count = 10) { const list = reactive([]); const create = (flag) => { const list2 = {}; for (const key in meta) { const m = meta[key].formItemMeta; switch (m.controlType) { case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: list2[m.colName] = "\u6587\u672C" + flag; break; case 120: list2[m.colName] = "2021-10-10"; break; case 121: list2[m.colName] = "2021-10-10 12:06:66"; break; case 122: list2[m.colName] = "2021-10"; break; case 124: list2[m.colName] = "2021\u5E74"; break; case 123: list2[m.colName] = "2021-w23"; break; case 125: list2[m.colName] = ["2021-10-10", "2022-01-01"]; break; case 126: list2[m.colName] = ["2021-10-10 10:22:22", "2022-01-01 14:33:33"]; break; case 127: list2[m.colName] = ["2021-12", "2022-02"]; break; case 128: list2[m.colName] = ["2021-10-10", "2022-01-01"]; break; case 130: list2[m.colName] = "12:02:06"; break; case 131: list2[m.colName] = "9:30"; break; case 110: case 111: list2[m.colName] = 100 + flag * 1; break; case 112: list2[m.colName] = 3; break; case 150: case 151: list2[m.colName] = false; break; case 153: case 160: list2[m.colName] = 2; break; case 164: m.colName.split("_").forEach((col) => { list2[col] = flag; }); break; case 152: case 161: list2[m.colName] = [8, flag]; break; } if (typeof m.defValue !== "undefined") { switch (m.defValue) { case "": break; case "{}": break; case "[]": break; case "{{now}}": list2[m.colName] = new Date(); break; default: if (Array.isArray(m.defValue)) { if (m.defValue.length > 0) { list2[m.colName] = m.defValue; } } else { list2[m.colName] = m.defValue; } break; } } } if (typeof list2.ID === "undefined") { list2.ID = flag; } return list2; }; for (let i = 0; i < count; i++) { list.push(create(i)); } return list; } /** * 键盘按键的监听,监听一个按键 * @param {*} key 要监听的按键 * @param {*} callback 按键触发后的回调函数。event:按键事件的参数;isAlt:是否按过alt键 */ function mykeydown(key, callback) { // 是否按过 alt let isAlt = false; // 按下的事件 const butKeydown = (event) => { if (event.key === "Alt") { isAlt = true; return } if (event.key === key) { callback(event, isAlt); } isAlt = false; }; // 监听事件 onMounted((info) => { // 创建 document.addEventListener("keydown", butKeydown); // document.addEventListener("keyup", butKeyup) }); // 撤销监听 onUnmounted((info) => { // 卸载 document.removeEventListener("keydown", butKeydown); // document.removeEventListener("keyup", butKeyup) }); } const _keyDict = { Home: 'h', // 首页 f: 'h', // 首页 End: 'e', // 末页 e: 'e', // 末页 w: '-', // 向前翻页 a: '-', // 向前翻页 s: '+', // 向后翻页 d: '+', // 向后翻页 ArrowLeft: '-', // 向前翻页 ArrowRight: '+', // 向后翻页 ArrowUp: '-', // 向前翻页 ArrowDown:'+' // 向后翻页 }; /** * 键盘按键的监听,监听一个按键 * @param {*} pagerInfo 分页信息 * * size: 10, // 一页记录数 * * total: 200, // 总数 * * count: 20, // 页数 * * index: 1 // 当前页号 * @param {*} dict 按键的对应关系 */ function mykeypager(pagerInfo, dict = {}) { // 防抖输入 let oldKey = ''; let timeOut = null; const keyDict = {}; Object.assign(keyDict, _keyDict, dict); // 方向键翻页,包含home、end等 const _movePager = (key) => { switch (key) { case 'h': pagerInfo.index = 1; break case 'e': pagerInfo.index = pagerInfo.count; break case '-': if (pagerInfo.index > 1) { pagerInfo.index -= 1; } break case '+': if (pagerInfo.index < pagerInfo.count) { pagerInfo.index += 1; } break } }; // 防抖的数字翻页 const _debouncePager = (key) => { // 快捷数字键,做防抖,可以输入 > 9 的页号 oldKey += key; clearTimeout(timeOut); timeOut = setTimeout(() => { const tmp = parseInt(oldKey); if (tmp <= 1){ pagerInfo.index = 1; } else if (tmp <= pagerInfo.count){ pagerInfo.index = tmp; } else { pagerInfo.index = pagerInfo.count; } oldKey = ''; }, 300); }; // 数字键,不防抖,1-9。0:10 const _numPager = (key) => { const tmp = key === '0' ? 10 : parseInt(key); if (tmp <= pagerInfo.count) { pagerInfo.index = tmp; } }; // 按下的事件 const butKeydown = (event) => { const re = Object.prototype.toString.call(event.target) === '[object HTMLBodyElement]'; if (re) { // 来自于 body if (event.code.includes('Num')) { // 防抖,合并翻页 _debouncePager(event.key); } else if (event.code.includes('Dig')){ // 数字键,不防抖,1-9。0:10 _numPager(event.key); } else { // 方向键翻页 _movePager(keyDict[event.key]); } } }; // 监听事件 onMounted((info) => { // 创建 document.addEventListener("keydown", butKeydown); // document.addEventListener("keyup", butKeyup) }); // 撤销监听 onUnmounted((info) => { // 卸载 document.removeEventListener("keydown", butKeydown); // document.removeEventListener("keyup", butKeyup) }); } /** * 拖拽 dialog 的函数,目前支持 element-plus */ function dialogDrag () { /** * 设置拖拽事件 * @param {*} container 大容器,比如蒙版。 * @param {*} dialog 被拖拽的窗口 * @param {*} dialogTitle 拖拽的标题 * @param {*} width 宽度 */ const setDialog = (container, dialog, dialogTitle, width) => { // 可视窗口的宽度 const clientWidth = document.documentElement.clientWidth; // 可视窗口的高度 const clientHeight = document.documentElement.clientHeight; // 计算百分数 let tmpWidth = width; // binding.value.replace('%', '') // tmpWidth = clientWidth * (100 - tmpWidth) / 200; const domset = { x: tmpWidth, y: clientHeight * 15 / 100 // 根据 15vh 计算 }; // 重新设置上、左距离 dialog.style.marginTop = domset.y + 'px'; dialog.style.marginLeft = domset.x + 'px'; // 记录拖拽开始的光标坐标,0 表示没有拖拽 const start = { x: 0, y: 0 }; // 移动中记录偏移量 const move = { x: 0, y: 0 }; // 经过时改变鼠标指针形状 dialogTitle.onmouseover = (e) => { dialogTitle.style.cursor = 'move'; // 改变光标形状 }; // 鼠标按下,开始拖拽 dialogTitle.onmousedown = (e) => { // 判断对话框是否重新打开 if (dialog.style.marginTop === '15vh') { // 重新打开,设置 domset.y top domset.y = clientHeight * 15 / 100; } start.x = e.clientX; start.y = e.clientY; dialogTitle.style.cursor = 'move'; // 改变光标形状 }; // 鼠标移动,实时跟踪 dialog container.onmousemove = (e) => { if (start.x === 0) { // 不是拖拽状态 return } move.x = e.clientX - start.x; move.y = e.clientY - start.y; // 初始位置 + 拖拽距离 dialog.style.marginLeft = (domset.x + move.x) + 'px'; dialog.style.marginTop = (domset.y + move.y) + 'px'; }; // 鼠标抬起,结束拖拽 container.onmouseup = (e) => { // alert(start.x) if (start.x === 0) { // 不是拖拽状态 return } move.x = e.clientX - start.x; move.y = e.clientY - start.y; // 记录新坐标,作为下次拖拽的初始位置 domset.x += move.x; domset.y += move.y; dialogTitle.style.cursor = ''; dialog.style.marginLeft = domset.x + 'px'; dialog.style.marginTop = domset.y + 'px'; // 结束拖拽 start.x = 0; }; }; const unload = (container, dialogTitle) => { dialogTitle.onmouseover = null; dialogTitle.onmousedown = null; container.onmousemove = null; container.onmouseup = null; }; return { setDialog, // 设置 unload // 卸载,移除事件 } } class domDrag$1 { dom; align; order; removeDom; modCol; constructor(_dom, colOrder, dragInfo, colId, dragEvent) { this.dom = _dom; this.align = dragEvent.setAlign; this.order = dragEvent.setOrder; this.removeDom = dragEvent.removeDom; this.modCol = dragEvent.modCol; this.dom.onclick = (event) => { if (event.ctrlKey) { if (typeof this.modCol === "function") { this.modCol(colId, event); } } }; this.dom.setAttribute("draggable", true); this.dom.ondragstart = null; this.dom.ondragstart = (event) => { dragInfo.state = "pending"; dragInfo.sourceId = colId; dragInfo.targetLabel = event.target.outerText; dragInfo.target = event.target; dragInfo.sourceIndex = colOrder.findIndex((a) => a === dragInfo.sourceId); }; this.dom.ondragover = null; this.dom.ondragover = (event) => { event.preventDefault(); clearTimeout(dragInfo.timeout); dragInfo.oldDom = event.target; dragInfo.isLeft = event.offsetX < event.target.offsetWidth / 2; const borderStyle = dragInfo.isLeft ? "none none none {}" : "none {} none none"; const borderStyle2 = "ridge"; if (dragInfo.targetLabel === event.target.outerText) { if (event.ctrlKey) { event.target.style.border = "5px dashed #7FFF01"; event.target.style.borderStyle = borderStyle.replace("{}", "dashed"); } else { event.target.style.border = "5px dotted #A52A2f"; event.target.style.borderStyle = borderStyle.replace("{}", "dotted"); } } else { if (event.ctrlKey) { event.target.style.border = "1px double #eb982c"; event.target.style.borderStyle = borderStyle2; dragInfo.target.style.border = "1px double #eb982c"; dragInfo.target.style.borderStyle = borderStyle2; } else { event.target.style.border = "4px double #2140c9"; event.target.style.borderStyle = borderStyle.replace(/\{\}/g, "groove"); dragInfo.target.style.border = ""; dragInfo.target.style.borderStyle = ""; } } }; this.dom.ondragleave = null; this.dom.ondragleave = (event) => { clearTimeout(dragInfo.timeout); dragInfo.oldDom.style.border = ""; dragInfo.timeout = setTimeout(() => { if (dragInfo.state !== "end") { this.removeDom(); } }, 800); }; this.dom.ondrop = null; this.dom.ondrop = (event) => { clearTimeout(dragInfo.timeout); dragInfo.oldDom.style.border = ""; dragInfo.state = "end"; dragInfo.offsetX = event.offsetX; dragInfo.isLeft = dragInfo.offsetX < event.target.offsetWidth / 2; dragInfo.ctrl = event.ctrlKey; dragInfo.targetId = colId; dragInfo.targetIndex = colOrder.findIndex((a) => a === dragInfo.targetId); if (dragInfo.sourceId === dragInfo.targetId) { this.align(); } else { this.order(); } }; } } function setOrder(colOrder, dragInfo) { const _swapPlaces = () => { colOrder[dragInfo.sourceIndex] = dragInfo.targetId; colOrder[dragInfo.targetIndex] = dragInfo.sourceId; }; const _order = () => { const offsetTarget = dragInfo.isLeft ? 0 : 1; const offsetSource = dragInfo.sourceIndex < dragInfo.targetIndex ? 0 : 1; colOrder.splice(dragInfo.targetIndex + offsetTarget, 0, dragInfo.sourceId); colOrder.splice(dragInfo.sourceIndex + offsetSource, 1); }; if (dragInfo.ctrl) { _swapPlaces(); } else { _order(); } } function gridDrag(gridMeta, itemMeta, table, deleteDom, modCol) { const _setRemove = (dragInfo2) => { const col = itemMeta[dragInfo2.sourceId]; deleteDom(col, () => { gridMeta.colOrder.splice(dragInfo2.sourceIndex, 1); }); }; const _setThAlgin = (dragInfo2) => { const alignKind = dragInfo2.ctrl ? "header-align" : "align"; const col = itemMeta[dragInfo2.sourceId]; switch (col[alignKind]) { case "left": col[alignKind] = dragInfo2.isLeft ? "left" : "center"; break; case "center": col[alignKind] = dragInfo2.isLeft ? "left" : "right"; break; case "right": col[alignKind] = dragInfo2.isLeft ? "center" : "right"; break; } }; const _setThWidth = (e) => { setTimeout(() => { const arr = Array.from(table.rows[0].cells); let i = -1; arr.forEach((element) => { if (i === -1) { i = 0; } else { itemMeta[gridMeta.colOrder[i++]].width = element.offsetWidth; } }); }, 1e3); }; const dragInfo = reactive({ timeout: null, oldDom: { style: { border: "", borderStyle: "" } }, state: "", offsetX: 0, isLeft: true, ctrl: false, sourceId: "", targetLabel: "", target: void 0, targetId: "", sourceIndex: 0, targetIndex: 0 }); const _dragEvent = { setAlign() { _setThAlgin(dragInfo); }, setOrder() { setOrder(gridMeta.colOrder, dragInfo); }, removeDom() { _setRemove(dragInfo); }, modCol(colId, event) { if (typeof modCol === "function") modCol(colId, dragInfo, event); } }; const girdSetup = () => { table.removeEventListener("mouseup", _setThWidth); table.addEventListener("mouseup", _setThWidth); const tr = table.rows[0]; const tdCount = tr.cells.length; const start = tdCount - gridMeta.colOrder.length; for (let i = start; i < tdCount; i++) { const th = tr.cells[i]; const colId = gridMeta.colOrder[i - start]; new domDrag$1(th, gridMeta.colOrder, dragInfo, colId, _dragEvent); } }; watch(gridMeta, () => { nextTick(() => { setTimeout(() => { girdSetup(); }, 500); }); }); return { girdSetup }; } function formDrag(formMeta, itemMeta, form, deleteCol, modCol) { const _setRemove = (dragInfo) => { const col = itemMeta[dragInfo.sourceId]; deleteCol(col, () => { formMeta.colOrder.splice(dragInfo.sourceIndex, 1); }); }; const _setThAlgin = (dragInfo) => { if (dragInfo.ctrl) { if (dragInfo.isLeft) { if (formMeta.columnsNumber > 1) formMeta.columnsNumber--; } else { if (formMeta.columnsNumber < 8) formMeta.columnsNumber++; } } else { const id = dragInfo.sourceId; const colMeta = itemMeta[id]; if (typeof colMeta.formItemMeta.colCount !== "number") colMeta.formItemMeta.colCount = 1; const colCount = colMeta.formItemMeta.colCount; if (dragInfo.isLeft) { if (colCount > -7) colMeta.formItemMeta.colCount--; if (colMeta.formItemMeta.colCount === 0) colMeta.formItemMeta.colCount = -2; } else { if (colCount < 8) colMeta.formItemMeta.colCount++; if (colMeta.formItemMeta.colCount === -1) colMeta.formItemMeta.colCount = 1; } } }; const formSetup = () => { const dragInfo = reactive({ timeout: null, oldDom: { style: { border: "" } }, state: "", offsetX: 0, isLeft: true, ctrl: false, sourceId: "", targetId: "", sourceIndex: 0, targetIndex: 0 }); const formItem = Array.from(form.children); const _dragEvent = { setAlign() { _setThAlgin(dragInfo); }, setOrder() { setOrder(formMeta.colOrder, dragInfo); }, removeDom() { _setRemove(dragInfo); }, modCol(colId, event) { if (typeof modCol === "function") modCol(colId, dragInfo, event); } }; formItem.forEach((element, i) => { const label = element.children[0].children[0]; element.children[0].children[1]; const colId = formMeta.colOrder[i]; new domDrag$1(label, formMeta.colOrder, dragInfo, colId, _dragEvent); }); document.ondrop = (event) => { }; }; watch(formMeta, () => { nextTick(() => { setTimeout(() => { formSetup(); }, 500); }); }); return { formSetup }; } const domDrag = (th, meta, dragInfo, colId) => new domDrag$1(th, meta, dragInfo, colId); export { cascaderManage, createDataList, createModel, createRouter, modelRef as custmerRef, debounceRef$1 as debounceRef, dialogDrag, domDrag, debounceRef$1 as emitDebRef, emitRef, findKindDict, findProps, formController, formDrag, formProps, getChildren, getChildrenOne, gridDrag, gridProps, itemController, itemProps, lifecycle, loadController, debounceRef as modelDebRef, modelRef, mykeydown, mykeypager, range2Ref, rangeRef, webAPI as service, config as serviceConfig, shallowToDeep, useRouter }; //# sourceMappingURL=nf-ui-core.es.js.map