@visactor/vue-vtable
Version:
The vue version of VTable
1,280 lines (1,268 loc) • 76.8 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@visactor/vtable'), require('vue'), require('@visactor/vutils'), require('@visactor/vtable/es/vrender')) :
typeof define === 'function' && define.amd ? define(['exports', '@visactor/vtable', 'vue', '@visactor/vutils', '@visactor/vtable/es/vrender'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.VueVTable = {}, global.VTable, global.Vue, global.VUtils, global.VTable.vrender));
})(this, (function (exports, VTable, vue, vutils, vrender) { 'use strict';
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var VTable__namespace = /*#__PURE__*/_interopNamespaceDefault(VTable);
// 将连字符形式的字符串转换为驼峰形式
function toCamelCase(str) {
return str.replace(/-([a-z])/g, g => g[1].toUpperCase());
}
// 将 vnode.props 中的所有属性名转换为驼峰形式
function convertPropsToCamelCase(props) {
const newProps = {};
for (const key in props) {
if (props.hasOwnProperty(key)) {
const camelCaseKey = toCamelCase(key);
newProps[camelCaseKey] = props[key];
}
}
return newProps;
}
// 展平嵌套的虚拟节点
function flattenVNodes(vnodes) {
return vnodes.flatMap(vnode => (Array.isArray(vnode.children) ? flattenVNodes(vnode.children) : vnode));
}
// 检查属性是否为事件
function isEventProp(key, props) {
return key.startsWith('on') && vutils.isFunction(props[key]);
}
// 创建自定义布局
function createCustomLayout(children, isHeader, args) {
// 同一 cell 内多个 vue Group 的计数器,每次 createCustomLayout 调用时归零
let vueIndex = 0;
// 组件映射
const componentMap = {
Group: VTable__namespace.CustomLayout.Group,
Image: VTable__namespace.CustomLayout.Image,
Text: VTable__namespace.CustomLayout.Text,
Tag: VTable__namespace.CustomLayout.Tag,
Radio: VTable__namespace.CustomLayout.Radio,
CheckBox: VTable__namespace.CustomLayout.CheckBox
};
// 创建组件的函数
function createComponent(child) {
var _a, _b;
if (!child) {
return null;
}
const { type, children: childChildren } = child;
const props = convertPropsToCamelCase(child.props);
const componentName = (type === null || type === void 0 ? void 0 : type.symbol) || (type === null || type === void 0 ? void 0 : type.name);
const ComponentClass = componentMap[componentName];
if (!ComponentClass) {
return null;
}
// 创建组件实例
const component = new ComponentClass(Object.assign({}, props));
// 绑定组件事件
bindComponentEvents(component, props);
// 递归创建子组件
const subChildren = resolveChildren(childChildren);
if (vutils.isObject(props === null || props === void 0 ? void 0 : props.vue)) {
// vue 自定义节点:无需继续循环子节点
const { element } = props.vue;
let targetVNode = element !== null && element !== void 0 ? element : subChildren.find(node => (node === null || node === void 0 ? void 0 : node.type) !== Symbol.for('v-cmt'));
if (vue.isVNode(targetVNode)) {
// node 标记 key 增加唯一项标记,避免重复渲染
targetVNode = !targetVNode.key
? vue.cloneVNode(targetVNode, { key: `row_${args.row}_col_${args.col}` })
: targetVNode;
}
else {
targetVNode = null;
}
// 注入稳定 ID:基于 cell 坐标 + 递增索引,确保场景图重建后缓存 key 不变
const stableId = vutils.isNil(props.vue.id) ? `cell_${args.col}_${args.row}_${vueIndex++}` : undefined;
Object.assign(child.props.vue, Object.assign({ element: targetVNode,
// 不接入外部指定
container: isHeader ? (_a = args === null || args === void 0 ? void 0 : args.table) === null || _a === void 0 ? void 0 : _a.headerDomContainer : (_b = args === null || args === void 0 ? void 0 : args.table) === null || _b === void 0 ? void 0 : _b.bodyDomContainer }, (stableId ? { id: stableId } : {})));
return component;
}
subChildren.forEach((subChild) => {
const subComponent = createComponent(subChild);
if (subComponent) {
component.add(subComponent);
}
else if (subChild.type === Symbol.for('v-fgt')) {
subChild.children.forEach((nestedChild) => {
const nestedComponent = createComponent(nestedChild);
if (nestedComponent) {
component.add(nestedComponent);
}
});
}
});
return component;
}
// 处理子节点
function resolveChildren(childChildren) {
var _a;
return ((_a = childChildren === null || childChildren === void 0 ? void 0 : childChildren.default) === null || _a === void 0 ? void 0 : _a.call(childChildren)) || childChildren || [];
}
// 绑定组件事件
function bindComponentEvents(component, props) {
Object.keys(props).forEach(key => {
if (isEventProp(key, props)) {
let eventName;
if (key.startsWith('on')) {
eventName = key.slice(2).toLowerCase(); // 去掉'on'前缀并转换为小写
}
else {
eventName = toCamelCase(key.slice(2)).toLowerCase(); // 转换为camelCase
}
component.addEventListener(eventName, props[key]);
}
});
}
// 返回root组件和refs
return { rootComponent: createComponent(children) };
}
function createCustomLayoutHandler(children, isHeader) {
return (args) => {
const { table, row, col, rect } = args;
const record = table.getCellOriginRecord(col, row);
const { height, width } = rect !== null && rect !== void 0 ? rect : table.getCellRect(col, row);
const customLayoutKey = isHeader ? 'headerCustomLayout' : 'customLayout';
if (!children[customLayoutKey]) {
return null;
}
const rootContainer = children[customLayoutKey]({ table, row, col, rect, record, height, width })[0];
const { rootComponent } = createCustomLayout(rootContainer, isHeader, args);
return {
rootContainer: rootComponent,
renderDefault: false
};
};
}
/**
* @description: 自定义渲染式编辑器
*/
class DynamicRenderEditor {
constructor(currentContext) {
this.currentContext = currentContext;
this.tableContainer = null;
this.currentValue = null;
this.wrapContainer = null;
this.nodeMap = new Map();
}
registerNode(tableId, key, getNode) {
if (!vutils.isValid(tableId) || !vutils.isValid(key) || typeof getNode !== 'function') {
return;
}
if (!this.nodeMap.has(tableId)) {
this.nodeMap.set(tableId, new Map());
}
this.nodeMap.get(tableId).set(key, getNode);
}
getNode(tableId, key) {
var _a;
return (_a = this.nodeMap.get(tableId)) === null || _a === void 0 ? void 0 : _a.get(key);
}
removeNode(tableId) {
this.nodeMap.delete(tableId);
}
release(tableId) {
if (!vutils.isValid(tableId)) {
this.nodeMap.clear();
}
else {
this.removeNode(tableId);
}
}
async onStart(editorContext) {
const { value } = editorContext;
// 先设置初始值(因为校验不通过也会走正常流程)
this.setValue(value);
if (!(await this.createElement(editorContext))) {
return;
}
}
async createElement(editorContext) {
const { row, col, value, table, container, referencePosition } = editorContext;
if (!container) {
return false;
}
const define = table.getBodyColumnDefine(col, row);
const { editConfig } = define || {};
const { id } = table;
const key = this.getColumnKeyField(define);
if (!vutils.isValid(key) || !vutils.isValid(id)) {
return false;
}
if (typeof (editConfig === null || editConfig === void 0 ? void 0 : editConfig.editBefore) === 'function') {
// 编辑前校验
const v = await editConfig.editBefore(editorContext);
if (!v) {
table.showTooltip(col, row, {
// TODO 多语言
content: editConfig.disablePrompt || 'This field is not allowed to be edited',
referencePosition: { rect: referencePosition === null || referencePosition === void 0 ? void 0 : referencePosition.rect, placement: VTable.TYPES.Placement.top },
style: {
bgColor: 'black',
color: 'white',
arrowMark: true
},
disappearDelay: 1000
});
return false;
}
}
const record = table === null || table === void 0 ? void 0 : table.getCellOriginRecord(col, row);
const renderVNodeFn = this.getNode(id, key);
if (!renderVNodeFn) {
return false;
}
const vnode = vue.h(renderVNodeFn, {
row,
col,
value,
refValue: vue.customRef((track, trigger) => {
return {
get: () => {
track();
return this.getValue();
},
set: value => {
this.setValue(value);
trigger();
}
};
}),
record,
table,
onChange: (value) => this.setValue(value)
});
if (!vnode || !vue.isVNode(vnode)) {
return false;
}
this.checkToPassAppContext(vnode, table);
// 创建包裹容器
const wrapContainer = document.createElement('div');
wrapContainer.style.position = 'absolute';
wrapContainer.style.width = '100%';
wrapContainer.style.boxSizing = 'border-box';
const { bgColor } = table.getCellStyle(col, row) || {};
wrapContainer.style.backgroundColor = bgColor || '#FFFFFF';
this.wrapContainer = wrapContainer;
this.tableContainer = container;
this.tableContainer.appendChild(wrapContainer);
vue.render(vnode, wrapContainer);
// 位置同步
if (referencePosition === null || referencePosition === void 0 ? void 0 : referencePosition.rect) {
this.adjustPosition(referencePosition.rect);
}
return true;
}
/**
* @description: 校验并传递上下文
* @param {VNode} vnode
* @param {any} table
* @return {*}
*/
checkToPassAppContext(vnode, table) {
var _a, _b, _c, _d;
try {
const userAppContext = (_d = (_c = (_b = (_a = table.options) === null || _a === void 0 ? void 0 : _a.customConfig) === null || _b === void 0 ? void 0 : _b.getVueUserAppContext) === null || _c === void 0 ? void 0 : _c.call(_b)) !== null && _d !== void 0 ? _d : this.currentContext;
// 简单校验合法性
if (!!(userAppContext === null || userAppContext === void 0 ? void 0 : userAppContext.components) && !!(userAppContext === null || userAppContext === void 0 ? void 0 : userAppContext.directives)) {
vnode.appContext = userAppContext;
}
}
catch (error) { }
}
/**
* @description: 获取渲染式编辑器的列配置主键
* @param {any} column
* @return {*}
*/
getColumnKeyField(column) {
const { field, key } = column || {};
// 兼容取 field
return vutils.isValid(key) ? key : field;
}
getValue() {
return this.currentValue;
}
setValue(value) {
this.currentValue = value;
}
adjustPosition(rect) {
if (this.wrapContainer) {
this.wrapContainer.style.top = `${rect.top}px`;
this.wrapContainer.style.left = `${rect.left}px`;
this.wrapContainer.style.width = `${rect.width}px`;
this.wrapContainer.style.height = `${rect.height}px`;
}
}
async validateValue(value, oldValue, editCell, table) {
const { col, row } = editCell || {};
if (!vutils.isValid(col) || !vutils.isValid(row)) {
return true;
}
const define = table.getBodyColumnDefine(col, row);
const { editConfig } = define || {};
if (typeof (editConfig === null || editConfig === void 0 ? void 0 : editConfig.validateValue) === 'function') {
const validate = await editConfig.validateValue({ col, row, value, oldValue, table });
if (validate === false) {
const rect = table.getVisibleCellRangeRelativeRect({ col, row });
table.showTooltip(col, row, {
content: editConfig.invalidPrompt || 'invalid',
referencePosition: { rect, placement: VTable.TYPES.Placement.top },
style: {
bgColor: 'red',
color: 'white',
arrowMark: true
},
disappearDelay: 1000
});
return false;
}
return validate;
}
return true;
}
onEnd() {
if (this.wrapContainer && this.tableContainer) {
vue.render(null, this.wrapContainer);
this.tableContainer.removeChild(this.wrapContainer);
}
this.wrapContainer = null;
this.tableContainer = null;
}
isEditorElement(target) {
var _a;
return ((_a = this.wrapContainer) === null || _a === void 0 ? void 0 : _a.contains(target)) || this.isClickEditorElement(target);
}
isClickEditorElement(target) {
while (target) {
// 约定的类名
if (target.classList && target.classList.contains('table-editor-element')) {
return true;
}
target = target.parentNode;
}
return false;
}
}
/** 动态渲染编辑器名称 */
const DYNAMIC_RENDER_EDITOR = 'dynamic-render-editor';
/**
* @description: 校验动态渲染式编辑器
* @param {any} column
* @param {any} getEditCustomNode
* @return {*}
*/
function checkRenderEditor(column, getEditCustomNode) {
const { editor } = column || {};
const key = getRenderEditorColumnKeyField(column);
if (!vutils.isValid(key) || editor !== DYNAMIC_RENDER_EDITOR) {
return false;
}
if (typeof getEditCustomNode === 'function') {
column.getEditCustomNode = getEditCustomNode;
// 处理子列
if (Array.isArray(column.columns) && column.columns.length) {
for (const childColumn of column.columns) {
checkRenderEditor(childColumn, getEditCustomNode);
}
}
return true;
}
return typeof column.getEditCustomNode === 'function';
}
/**
* @description: 获取渲染式编辑器的列配置主键
* @param {any} column
* @return {*}
*/
function getRenderEditorColumnKeyField(column) {
const { field, key } = column || {};
// 兼容取 field
return vutils.isValid(key) ? key : field;
}
/**
* @description: 获取动态渲染式编辑器
* @param {boolean} create
* @param {any} currentContext
* @return {*}
*/
function getRenderEditor(create, currentContext) {
const registeredEditor = VTable.register.editor(DYNAMIC_RENDER_EDITOR);
let renderEditor = registeredEditor
? registeredEditor
: undefined;
if (!renderEditor && !!create) {
// 注册自定义编辑器
renderEditor = new DynamicRenderEditor(currentContext);
VTable.register.editor(DYNAMIC_RENDER_EDITOR, renderEditor);
}
return renderEditor;
}
function extractPivotSlotOptions(vnodes) {
const options = {
columns: [],
columnHeaderTitle: [],
rows: [],
rowHeaderTitle: [],
indicators: [],
corner: {},
tooltip: {},
menu: {}
};
const typeMapping = {
PivotColumnDimension: 'columns',
PivotColumnHeaderTitle: 'columnHeaderTitle',
PivotRowDimension: 'rows',
PivotRowHeaderTitle: 'rowHeaderTitle',
PivotCorner: 'corner',
PivotIndicator: 'indicators',
Tooltip: 'tooltip',
Menu: 'menu'
};
vnodes.forEach(vnode => {
var _a, _b;
vnode.props = convertPropsToCamelCase(vnode.props);
const typeName = ((_a = vnode.type) === null || _a === void 0 ? void 0 : _a.symbol) || ((_b = vnode.type) === null || _b === void 0 ? void 0 : _b.name);
const optionKey = typeMapping[typeName];
if (optionKey) {
if (Array.isArray(options[optionKey])) {
if (vnode.props.hasOwnProperty('objectHandler')) {
options[optionKey].push(vnode.props.objectHandler);
}
else {
options[optionKey].push(vnode.props);
}
}
else {
options[optionKey] = vnode.props;
}
}
});
return options;
}
function extractListSlotOptions(vnodes) {
const options = {
columns: [],
tooltip: {},
menu: {}
};
const typeMapping = {
ListColumn: 'columns',
Tooltip: 'tooltip',
Menu: 'menu'
};
vnodes.forEach(vnode => {
var _a, _b;
vnode.props = convertPropsToCamelCase(vnode.props);
const typeName = ((_a = vnode.type) === null || _a === void 0 ? void 0 : _a.symbol) || ((_b = vnode.type) === null || _b === void 0 ? void 0 : _b.name);
const optionKey = typeMapping[typeName];
if (optionKey) {
if (optionKey === 'columns' && vnode.children) {
if (vnode.children.customLayout) {
vnode.props.customLayout = createCustomLayoutHandler(vnode.children);
}
if (vnode.children.headerCustomLayout) {
vnode.props.headerCustomLayout = createCustomLayoutHandler(vnode.children, true);
}
// 校验编辑器
checkRenderEditor(vnode.props, vnode.children.edit);
}
if (Array.isArray(options[optionKey])) {
options[optionKey].push(vnode.props);
}
else {
options[optionKey] = vnode.props;
}
}
});
return options;
}
function mergeSlotOptions(propsOptions, slotOptions) {
return Object.assign(Object.assign({}, propsOptions), { columns: slotOptions.columns && slotOptions.columns.length ? slotOptions.columns : propsOptions.columns, columnHeaderTitle: slotOptions.columnHeaderTitle && slotOptions.columnHeaderTitle.length
? slotOptions.columnHeaderTitle
: propsOptions.columnHeaderTitle, rows: slotOptions.rows && slotOptions.rows.length ? slotOptions.rows : propsOptions.rows, rowHeaderTitle: slotOptions.rowHeaderTitle && slotOptions.rowHeaderTitle.length
? slotOptions.rowHeaderTitle
: propsOptions.rowHeaderTitle, indicators: slotOptions.indicators && slotOptions.indicators.length ? slotOptions.indicators : propsOptions.indicators, corner: Object.keys(propsOptions.corner || {}).length ? propsOptions.corner : slotOptions.corner, tooltip: Object.keys(slotOptions.tooltip || {}).length ? slotOptions.tooltip : propsOptions.tooltip, menu: Object.keys(slotOptions.menu || {}).length ? slotOptions.menu : propsOptions.menu });
}
const EVENT_TYPE = Object.assign(Object.assign(Object.assign({}, VTable.ListTable.EVENT_TYPE), VTable.PivotTable.EVENT_TYPE), VTable.PivotChart.EVENT_TYPE);
const TABLE_EVENTS = {
onClickCell: EVENT_TYPE.CLICK_CELL,
onDblClickCell: EVENT_TYPE.DBLCLICK_CELL,
onMouseDownCell: EVENT_TYPE.MOUSEDOWN_CELL,
onMouseUpCell: EVENT_TYPE.MOUSEUP_CELL,
onSelectedCell: EVENT_TYPE.SELECTED_CELL,
onKeyDown: EVENT_TYPE.KEYDOWN,
onMouseEnterTable: EVENT_TYPE.MOUSEENTER_TABLE,
onMouseLeaveTable: EVENT_TYPE.MOUSELEAVE_TABLE,
onMouseDownTable: EVENT_TYPE.MOUSEDOWN_TABLE,
onMouseMoveCell: EVENT_TYPE.MOUSEMOVE_CELL,
onMouseEnterCell: EVENT_TYPE.MOUSEENTER_CELL,
onMouseLeaveCell: EVENT_TYPE.MOUSELEAVE_CELL,
onContextMenuCell: EVENT_TYPE.CONTEXTMENU_CELL,
onContextMenuCanvas: EVENT_TYPE.CONTEXTMENU_CANVAS,
onResizeColumn: EVENT_TYPE.RESIZE_COLUMN,
onResizeColumnEnd: EVENT_TYPE.RESIZE_COLUMN_END,
onChangeHeaderPosition: EVENT_TYPE.CHANGE_HEADER_POSITION,
onChangeHeaderPositionStart: EVENT_TYPE.CHANGE_HEADER_POSITION_START,
onChangeHeaderPositionFail: EVENT_TYPE.CHANGE_HEADER_POSITION_FAIL,
onSortClick: EVENT_TYPE.SORT_CLICK,
onFreezeClick: EVENT_TYPE.FREEZE_CLICK,
onScroll: EVENT_TYPE.SCROLL,
onDropdownMenuClick: EVENT_TYPE.DROPDOWN_MENU_CLICK,
onMouseOverChartSymbol: EVENT_TYPE.MOUSEOVER_CHART_SYMBOL,
onDragSelectEnd: EVENT_TYPE.DRAG_SELECT_END,
onDropdownIconClick: EVENT_TYPE.DROPDOWN_ICON_CLICK,
onDropdownMenuClear: EVENT_TYPE.DROPDOWN_MENU_CLEAR,
onTreeHierarchyStateChange: EVENT_TYPE.TREE_HIERARCHY_STATE_CHANGE,
onShowMenu: EVENT_TYPE.SHOW_MENU,
onHideMenu: EVENT_TYPE.HIDE_MENU,
onIconClick: EVENT_TYPE.ICON_CLICK,
onLegendItemClick: EVENT_TYPE.LEGEND_ITEM_CLICK,
onLegendItemHover: EVENT_TYPE.LEGEND_ITEM_HOVER,
onLegendItemUnHover: EVENT_TYPE.LEGEND_ITEM_UNHOVER,
onLegendChange: EVENT_TYPE.LEGEND_CHANGE,
onMouseEnterAxis: EVENT_TYPE.MOUSEENTER_AXIS,
onMouseLeaveAxis: EVENT_TYPE.MOUSELEAVE_AXIS,
onCheckboxStateChange: EVENT_TYPE.CHECKBOX_STATE_CHANGE,
onRadioStateChange: EVENT_TYPE.RADIO_STATE_CHANGE,
onAfterRender: EVENT_TYPE.AFTER_RENDER,
onInitialized: EVENT_TYPE.INITIALIZED,
// pivot table only
onPivotSortClick: EVENT_TYPE.PIVOT_SORT_CLICK,
onDrillMenuClick: EVENT_TYPE.DRILLMENU_CLICK,
// pivot chart only
onVChartEventType: EVENT_TYPE.VCHART_EVENT_TYPE,
onChangeCellValue: EVENT_TYPE.CHANGE_CELL_VALUE,
onMousedownFillHandle: EVENT_TYPE.MOUSEDOWN_FILL_HANDLE,
onDragFillHandleEnd: EVENT_TYPE.DRAG_FILL_HANDLE_END,
onDblclickFillHandle: EVENT_TYPE.DBLCLICK_FILL_HANDLE,
onScrollVerticalEnd: EVENT_TYPE.SCROLL_VERTICAL_END,
onScrollHorizontalEnd: EVENT_TYPE.SCROLL_HORIZONTAL_END,
onChangCellValue: EVENT_TYPE.CHANGE_CELL_VALUE,
onEmptyTipClick: EVENT_TYPE.EMPTY_TIP_CLICK,
onEmptyTipDblClick: EVENT_TYPE.EMPTY_TIP_DBLCLICK,
onButtonClick: EVENT_TYPE.BUTTON_CLICK,
onBeforeCacheChartImage: EVENT_TYPE.BEFORE_CACHE_CHART_IMAGE,
onPastedData: EVENT_TYPE.PASTED_DATA,
onSelectedClear: EVENT_TYPE.SELECTED_CLEAR
};
const TABLE_EVENTS_KEYS = Object.keys(TABLE_EVENTS);
// export const findEventProps = <T extends EventsProps>(
// props: T,
// supportedEvents: Record<string, string> = TABLE_EVENTS
// ): EventsProps => {
// const result: EventsProps = {};
// Object.keys(props).forEach(key => {
// if (supportedEvents[key] && props[key]) {
// result[key] = props[key];
// }
// });
// return result;
// };
// export const bindEventsToTable = <T>(
// table: IVTable,
// newProps?: T | null,
// prevProps?: T | null,
// supportedEvents: Record<string, string> = TABLE_EVENTS
// ) => {
// if (!table) return false;
// const prevEventProps = prevProps ? findEventProps(prevProps, supportedEvents) : {};
// const newEventProps = newProps ? findEventProps(newProps, supportedEvents) : {};
// Object.keys(supportedEvents).forEach(eventKey => {
// const prevHandler = prevEventProps[eventKey];
// const newHandler = newEventProps[eventKey];
// if (prevHandler !== newHandler) {
// if (prevHandler) {
// table.off(supportedEvents[eventKey], prevHandler);
// }
// if (newHandler) {
// table.on(supportedEvents[eventKey] as keyof TYPES.TableEventHandlersEventArgumentMap, newHandler);
// }
// }
// });
// return true;
// };
/**
* 编辑渲染器
* @param props
* @param tableRef
*/
function useEditorRender(props, tableRef) {
/** 当前实例 */
const instance = vue.getCurrentInstance();
/** 需要渲染编辑器的列 */
const validColumns = vue.computed(() => {
var _a;
const columns = flattenColumns(((_a = props.options) === null || _a === void 0 ? void 0 : _a.columns) || []);
if (!vutils.isArray(columns)) {
return [];
}
return columns.filter(col => !!vutils.isObject(col) && !!checkRenderEditor(col));
});
vue.watchEffect(() => {
resolveRenderEditor();
});
vue.onBeforeUnmount(() => {
releaseRenderEditor();
});
/**
* @description: 动态渲染式编辑器
* @return {*}
*/
function resolveRenderEditor() {
const id = getTableId();
if (!vutils.isValid(id)) {
return;
}
// 移除原本已存在的编辑器
let renderEditor = getRenderEditor();
if (renderEditor) {
renderEditor.removeNode(id);
}
else if (validColumns.value.length > 0) {
// 注册编辑器
renderEditor = getRenderEditor(true, instance === null || instance === void 0 ? void 0 : instance.appContext);
}
validColumns.value.forEach(column => {
const { getEditCustomNode } = column;
const key = getRenderEditorColumnKeyField(column);
renderEditor.registerNode(id, key, getEditCustomNode);
delete column.editCustomNode;
});
}
/**
* @description: 释放动态渲染式编辑器
* @return {*}
*/
function releaseRenderEditor() {
const id = getTableId();
if (!vutils.isValid(id)) {
return;
}
const renderEditor = getRenderEditor();
renderEditor === null || renderEditor === void 0 ? void 0 : renderEditor.release(id);
}
/**
* @description: 获取表格 id
* @return {*}
*/
function getTableId() {
var _a;
return (_a = tableRef.value) === null || _a === void 0 ? void 0 : _a.id;
}
}
/**
* @description: 获取所有扁平化的 columns
* @param {any} columns
*/
function flattenColumns(columns) {
return columns.flatMap(column => (Array.isArray(column.columns) ? flattenColumns(column.columns) : column));
}
var __rest = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
/**
* 表格自定义组件集成插件
*/
class VTableVueAttributePlugin extends vrender.HtmlAttributePlugin {
constructor(currentContext) {
super();
this.name = 'VTableVueAttributePlugin';
/** 渲染队列 */
this.renderQueue = new Set();
/** 是否正在渲染 */
this.isRendering = false;
/** 最大缓存节点数(兜底值) */
this.MAX_CACHE_COUNT = 100;
/** 记录节点访问顺序(LRU用) */
this.accessQueue = [];
/** 目标可视区区(可视区外一定范围内的节点,保留) */
this.VIEWPORT_BUFFER = 100;
/** 缓冲区(非可视区且非缓冲区的节点需清理) */
this.BUFFER_ZONE = 500;
// 新增批量更新队列
this.styleUpdateQueue = new Map();
/** 样式更新中 */
this.styleUpdateRequested = false;
/** 事件集 */
this.eventHandlers = new WeakMap();
this.currentContext = currentContext;
}
/**
* @description: 单元格变化后重新渲染组件,由 HtmlAttributePlugin 插件触发
* @param {IGraphic} graphic
* @return {*}
*/
renderGraphicHTML(graphic) {
var _a;
if (!this.checkNeedRender(graphic)) {
return;
}
// 缓存命中时同步渲染:立即更新 renderId,防止 clearCacheContainer 误清
const opts = this.getGraphicOptions(graphic);
if (opts) {
const targetMap = (_a = this.htmlMap) === null || _a === void 0 ? void 0 : _a[opts.id];
if (targetMap && this.checkDom(targetMap.wrapContainer)) {
this.doRenderGraphic(graphic);
return;
}
}
// 无缓存或 DOM 不在文档中,走异步渲染队列
this.renderQueue.add(graphic);
this.scheduleRender();
}
/**
* @description: 渲染调度
* @return {*}
*/
scheduleRender() {
if (this.isRendering) {
return;
}
this.isRendering = true;
vrender.vglobal.getRequestAnimationFrame()(() => {
this.renderQueue.forEach(graphic => {
try {
this.doRenderGraphic(graphic);
}
catch (error) {
const { id } = this.getGraphicOptions(graphic) || {};
this.removeElement(id, true);
}
});
this.renderQueue.clear();
this.isRendering = false;
});
}
/**
* @description: 单元格变化后实际组件渲染方法
* @param {IGraphic} graphic
* @return {*}
*/
doRenderGraphic(graphic) {
var _a;
const { id, options } = this.getGraphicOptions(graphic);
if (!id) {
return;
}
const stage = graphic.stage;
const { element, container: expectedContainer } = options;
// 获取实际容器
const actualContainer = expectedContainer ? checkFrozenContainer(graphic) : expectedContainer;
// 检查是否需要移除旧容器
let targetMap = (_a = this.htmlMap) === null || _a === void 0 ? void 0 : _a[id];
if (targetMap && actualContainer && actualContainer !== targetMap.container) {
// 容器变更
this.removeElement(id);
targetMap = null;
}
// 校验并传递上下文
this.checkToPassAppContext(element, graphic);
// 渲染或更新 Vue 组件
if (!targetMap || !this.checkDom(targetMap.wrapContainer)) {
// 缓存节点检查
this.checkAndClearCache(graphic);
const { wrapContainer, nativeContainer, reuse } = this.getWrapContainer(stage, actualContainer, { id, options });
if (wrapContainer) {
const dataRenderId = `${this.renderId}`;
wrapContainer.id = id;
wrapContainer.setAttribute('data-vue-renderId', dataRenderId);
// 先隐藏
wrapContainer.style.display = 'none';
if (!reuse) {
// 仅在非复用时需要重新渲染
vue.render(element, wrapContainer);
}
targetMap = {
wrapContainer,
nativeContainer,
container: actualContainer,
renderId: this.renderId,
graphic,
isInViewport: true,
lastPosition: null,
lastStyle: {}
};
this.htmlMap[id] = targetMap;
}
}
// 更新样式并记录渲染 ID
if (targetMap) {
targetMap.renderId = this.renderId;
targetMap.graphic = graphic;
targetMap.lastAccessed = Date.now();
this.updateAccessQueue(id);
this.updateStyleOfWrapContainer(graphic, stage, targetMap.wrapContainer, targetMap.nativeContainer);
}
}
/**
* @description: 获取渲染参数
* @param {IGraphic} graphic
* @return {*}
*/
getGraphicOptions(graphic) {
var _a;
// TODO render 组件接入 vue 类型
//@ts-ignore
const { vue } = (graphic === null || graphic === void 0 ? void 0 : graphic.attribute) || {};
if (!vue) {
return null;
}
const id = vutils.isNil(vue.id) ? (_a = graphic.id) !== null && _a !== void 0 ? _a : graphic._uid : vue.id;
return { id: `vue_${id}`, options: vue };
}
/**
* @description: 校验并传递上下文
* @param {VNode} vnode
* @param {IGraphic} graphic
* @return {*}
*/
checkToPassAppContext(vnode, graphic) {
var _a, _b;
try {
const customConfig = this.getCustomConfig(graphic);
const userAppContext = (_b = (_a = customConfig === null || customConfig === void 0 ? void 0 : customConfig.getVueUserAppContext) === null || _a === void 0 ? void 0 : _a.call(customConfig)) !== null && _b !== void 0 ? _b : this.currentContext;
// 简单校验合法性
if (!!(userAppContext === null || userAppContext === void 0 ? void 0 : userAppContext.components) && !!(userAppContext === null || userAppContext === void 0 ? void 0 : userAppContext.directives)) {
vnode.appContext = userAppContext;
}
}
catch (error) { }
}
/**
* @description: 获取自定义配置
* @param {IGraphic} graphic
* @return {*}
*/
getCustomConfig(graphic) {
var _a, _b, _c;
const target = getTargetGroup(graphic);
return (_c = (_b = (_a = target === null || target === void 0 ? void 0 : target.stage) === null || _a === void 0 ? void 0 : _a.table) === null || _b === void 0 ? void 0 : _b.options) === null || _c === void 0 ? void 0 : _c.customConfig;
}
/**
* @description: 检查是否需要渲染
* @param {IGraphic} graphic
* @return {*}
*/
checkNeedRender(graphic) {
const { id, options } = this.getGraphicOptions(graphic) || {};
if (!id) {
return false;
}
const stage = graphic.stage;
if (!stage) {
return false;
}
const { element } = options;
if (!element) {
return false;
}
const isInViewport = this.checkInViewport(graphic);
// 不在可视区内暂时不需要移除,因为在 clearCacheContainer 方法中提前被移除了
return isInViewport;
}
/**
* @description: 判断是否在可视范围内
* @param {IGraphic} graphic
* @return {*}
*/
checkInViewport(graphic) {
return this.checkInViewportByZone(graphic, this.VIEWPORT_BUFFER);
}
/**
* @description: 判断是否在缓冲区内
* @param {IGraphic} graphic
* @return {*}
*/
checkInBuffer(graphic) {
return this.checkInViewportByZone(graphic, this.BUFFER_ZONE);
}
/**
* @description: 判断当前是否在指定视口范围内
* @param {IGraphic} graphic
* @param {number} buffer
* @return {*}
*/
checkInViewportByZone(graphic, buffer = 0) {
const { stage, globalAABBBounds: cBounds } = graphic;
if (!stage) {
return false;
}
// 获取视口的AABB边界
//@ts-ignore
const { AABBBounds: vBounds } = stage;
// 扩展视口判断范围
const eBounds = {
x1: vBounds.x1 - buffer,
x2: vBounds.x2 + buffer,
y1: vBounds.y1 - buffer,
y2: vBounds.y2 + buffer
};
// 判断两个区域是否相交
const isIntersecting = cBounds.x1 < eBounds.x2 && cBounds.x2 > eBounds.x1 && cBounds.y1 < eBounds.y2 && cBounds.y2 > eBounds.y1;
return isIntersecting;
}
/**
* @description: 节点访问顺序队列
* @param {string} id
* @return {*}
*/
updateAccessQueue(id) {
// 移除旧记录
const index = this.accessQueue.indexOf(id);
if (index > -1) {
this.accessQueue.splice(index, 1);
}
// 添加到队列头部
this.accessQueue.unshift(id);
}
/**
* @description: 在添加新节点前检查缓存大小
* @param {IGraphic} graphic
* @return {*}
*/
checkAndClearCache(graphic) {
var _a;
const { viewportNodes, bufferNodes, cacheNodes } = this.classifyNodes();
const total = viewportNodes.length + bufferNodes.length + cacheNodes.length;
const customConfig = this.getCustomConfig(graphic);
const maxTotal = (_a = customConfig === null || customConfig === void 0 ? void 0 : customConfig.maxDomCacheCount) !== null && _a !== void 0 ? _a : this.MAX_CACHE_COUNT;
// 仅当总数超过阈值时清理
if (total <= maxTotal) {
return;
}
const exceedingCount = total - maxTotal;
// 优先清理缓存区节点: 移除缓存区的前 exceedingCount 个节点
let toRemove = cacheNodes.slice(0, exceedingCount);
// 若缓存区节点不满足阈值,为了控制内存占用率,按最后访问时间清除最早访问的缓冲区节点
if (toRemove.length < exceedingCount) {
const bufferCandidates = bufferNodes
.sort((a, b) => this.htmlMap[a].lastAccessed - this.htmlMap[b].lastAccessed)
.slice(0, exceedingCount - toRemove.length);
toRemove = toRemove.concat(bufferCandidates);
}
// 执行清理
toRemove.forEach(id => this.removeElement(id, true));
}
/**
* @description: 节点按可视区/缓存区/缓冲区分类
* @return {*}
*/
classifyNodes() {
/** 可视区节点 */
const viewportNodes = [];
/** 缓冲区节点 */
const bufferNodes = [];
/** 既不在可视区也不在缓冲区的节点 */
const cacheNodes = [];
Object.keys(this.htmlMap).forEach(id => {
const node = this.htmlMap[id];
if (node.isInViewport) {
viewportNodes.push(id);
}
else if (this.checkInBuffer(node.graphic)) {
bufferNodes.push(id);
}
else {
cacheNodes.push(id);
}
});
return {
viewportNodes,
bufferNodes,
cacheNodes
};
}
/**
* @description: 检查 dom 是否存在
* @param {HTMLElement} dom
* @return {*}
*/
checkDom(dom) {
if (!dom) {
return false;
}
return document.contains(dom);
}
/**
* @description: 清除所有 dom
* @param {IGraphic} g
* @return {*}
*/
removeAllDom(g) {
if (this.htmlMap) {
Object.keys(this.htmlMap).forEach(key => {
this.removeElement(key, true);
});
this.htmlMap = null;
}
}
/**
* @description: 移除元素
* @param {string} id
* @param {boolean} clear 强制清除
* @return {*}
* 目前涉及到页面重绘的操作(比如列宽拖动会使得图形重绘,id变更),会有短暂的容器插拔现象
*/
removeElement(id, clear) {
var _a;
const record = (_a = this.htmlMap) === null || _a === void 0 ? void 0 : _a[id];
if (!record) {
return;
}
const { wrapContainer } = record;
if (!wrapContainer) {
return;
}
if (!clear) {
// 移除 dom 但保留在 htmlMap 中,供下次进入可视区时快速复用
wrapContainer.remove();
// 标记不在视口
record.isInViewport = false;
// 清理访问队列
const index = this.accessQueue.indexOf(id);
if (index > -1) {
this.accessQueue.splice(index, 1);
}
}
else {
// 卸载子组件
vue.render(null, wrapContainer);
this.checkDom(wrapContainer) && super.removeElement(id);
// 清理引用
delete this.htmlMap[id];
}
// 清理事件
this.removeWrapContainerEventListener(wrapContainer);
}
/**
* @description: 获取包裹容器
* @param {IStage} stage
* @param {string} userContainer
* @param {CreateDOMParamsType} domParams
* @return {*}
*/
getWrapContainer(stage, userContainer, domParams) {
var _a;
let nativeContainer;
if (userContainer) {
nativeContainer =
typeof userContainer === 'string' ? vrender.application.global.getElementById(userContainer) : userContainer;
}
else {
nativeContainer = stage.window.getContainer();
}
const { id } = domParams || {};
// 从 htmlMap 查找可复用 dom
const record = (_a = this.htmlMap) === null || _a === void 0 ? void 0 : _a[id];
if (record && !record.isInViewport) {
const { wrapContainer } = record;
if (!this.checkDom(wrapContainer)) {
// 添加游离节点
nativeContainer.appendChild(wrapContainer);
}
return {
reuse: true,
wrapContainer,
nativeContainer
};
}
return {
wrapContainer: vrender.application.global.createDom({ tagName: 'div', parent: nativeContainer }),
nativeContainer
};
}
/**
* @description: 更新包裹容器样式
* @param {IGraphic} graphic
* @param {IStage} stage
* @param {HTMLElement} wrapContainer
* @param {HTMLElement} nativeContainer
* @return {*}
*/
updateStyleOfWrapContainer(graphic, stage, wrapContainer, nativeContainer) {
const { attribute, type } = graphic;
//@ts-ignore
const _a = attribute || {}, { vue: options, width, height, visible, display } = _a, rest = __rest(_a, ["vue", "width", "height", "visible", "display"]);
const { x: left, y: top } = this.calculatePosition(graphic, options.anchorType);
const { left: offsetX, top: offsetTop } = this.calculateOffset(stage, nativeContainer, left, top);
const { id } = this.getGraphicOptions(graphic) || {};
const record = id ? this.htmlMap[id] : null;
if (!record) {
return;
}
// 位置变化检查
const positionChanged = !record.lastPosition || record.lastPosition.x !== offsetX || record.lastPosition.y !== offsetTop;
if (!positionChanged) {
// 位置没有变化,无需更新样式
return;
}
// 默认自定义区域内也可带动表格画布滚动
const { pointerEvents } = options;
const calculateStyle = this.parseDefaultStyleFromGraphic(graphic);
// 单元格样式
const style = this.convertCellStyle(graphic);
Object.assign(calculateStyle, Object.assign(Object.assign(Object.assign({ width: `${width}px`, height: `${height}px`, overflow: 'hidden' }, (style || {})), (rest || {})), { transform: `translate(${offsetX}px, ${offsetTop}px)`, boxSizing: 'border-box', display: visible !== false ? display || 'block' : 'none', pointerEvents: pointerEvents === true ? 'all' : pointerEvents || 'none', position: 'absolute' }));
if (calculateStyle.pointerEvents !== 'none') {
this.checkToAddEventListener(wrapContainer);
}
if (type === 'text' && options.anchorType === 'position') {
Object.assign(calculateStyle, this.getTransformOfText(graphic));
}
this.applyUserStyles(options, calculateStyle, { offsetX, offsetTop, graphic, wrapContainer });
// 样式变化检查
const styleChanged = !vutils.isEqual(record.lastStyle, calculateStyle);
if (styleChanged) {
this.styleUpdateQueue.set(wrapContainer.id, calculateStyle);
// 请求批量更新
this.requestStyleUpdate();
// TODO 确认是否需要对接 VTableBrowserEnvContribution
// application.global.updateDom(wrapContainer, {
// width,
// height,
// style: calculateStyle
// });
record.lastStyle = calculateStyle;
}
}
/**
* @description: 事件监听器管理
* @param {HTMLElement} wrapContainer
* @return {*}
*/
checkToAddEventListener(wrapContainer) {
if (!this.eventHandlers.has(wrapContainer)) {
const handler = (e) => {
e.preventDefault();
this.onWheel(e);
};
wrapContainer.addEventListener('wheel', handler, { passive: false });
this.eventHandlers.set(wrapContainer, handler);
}
}
/**
* @description: 样式更新
* @return {*}
*/
requestStyleUpdate() {
if (!this.styleUpdateRequested) {
this.styleUpdateRequested = true;
vrender.vglobal.getRequestAnimationFrame()(() => {
this.styleUpdateQueue.forEach((changes, id) => {
var _a, _b;
const container = (_b = (_a = this.htmlMap) === null || _a === void 0 ? void 0 : _a[id]) === null || _b === void 0 ? void 0 : _b.wrapContainer;
if (container) {
Object.assign(container.style, changes);
}
});
this.styleUpdateQueue.clear();
this.styleUpdateRequested = false;
});
}
}
/**
* @description: 转换单元格样式
* @param {IGraphic} graphic
* @return {*}
*/
convertCellStyle(graphic) {
var _a;
const { col, row, stage } = getTargetGroup(graphic);
const style = (_a = stage === null || stage === void 0 ? void 0 : stage.table) === null || _a === void 0 ? void 0 : _a.getCellStyle(col, row);
if (!vutils.isObject(style)) {
return;
}
const _b = style, { lineHeight, padding } = _b, rest = __rest(_b, ["lineHeight", "padding"]);
// TODO 表格提供具体解析方法,暂时只解析padding
return Object.assign(Object.assign({}, rest), { padding: vutils.isArray(padding) ? padding.map(value => `${value}px`).join(' ') : padding });
}
/**
* @description: 位置计算
* @param {IGraphic} graphic
* @param {string} anchorType
* @return {*}
*/
calculatePosition(graphic, anchorType) {
const bounds = graphic.globalAABBBounds;
if (anchorType === 'position' || bounds.empty()) {
const matrix = graphic.globalTransMatrix;
return { x: matrix.e, y: matrix.f };
}
return vutils.calculateAnchorOfBounds(bounds, anchorType || 'top-left');
}
/**
* @description: 偏移计算
* @param {IStage} stage
* @param {HTMLElement} nativeContainer
* @param {number} x
* @param {number} y
* @return {*}
*/
calculateOffset(stage, nativeContainer, x, y) {
const containerTL = vrender.application.global.getElementTopLeft(nativeContainer, false);
const windowTL = stage.window.getTopLeft(false);
return {
left: x + windowTL.left - containerTL.left,
top: y + windowTL.top - containerTL.top
};
}
/**
* @description: 应用用户样式
* @param {SimpleDomStyleOptions & CommonDomOptions} options
* @param {Record<string, any>} baseStyle
* @param {Object} context
* @return {*}
*/
applyUserStyles(options, baseStyle, context) {
if (vutils.isFunction(options.style)) {
const userStyle = options.style({
top: context.offsetTop,
left: context.offsetX,
width: context.graphic.globalAABBBounds.width(),
height: context.graphic.globalAABBBounds.height()
}, context.graphic, context.wrapContainer);
Object.assign(baseStyle, userStyle);
}
else if (vutils.isObject(options.style)) {
Object.assign(baseStyle, options.style);
}
else if (vutils.isString(options.style)) {
Object.assign(baseStyle, vutils.styleStringToObject(options.style));
}
}
}
/**
* @description: 检查冻结容器
* @param {IGraphic} graphic
* @return {*}
*/
function checkFrozenContainer(graphic) {
var _a;
const { col, row, stage } = getTargetGroup(graphic);
// @ts-ignore
let container