chore: 优化 Table 渲染性能

This commit is contained in:
2betop 2023-09-06 16:00:44 +08:00
parent df59d92a4d
commit fd93dedf2f
25 changed files with 865 additions and 526 deletions

View File

@ -1845,6 +1845,7 @@ popOver 的其它配置请参考 [popover](./popover)
| resizable | `boolean` | `true` | 列宽度是否支持调整 | |
| selectable | `boolean` | `false` | 支持勾选 | |
| multiple | `boolean` | `false` | 勾选 icon 是否为多选样式`checkbox` 默认为`radio` | |
| lazyRenderAfter | `number` | `100` | 用来控制从第几行开始懒渲染行,用来渲染大表格时有用 | |
### 列配置属性表

View File

@ -1,4 +1,4 @@
module.exports = [
const list = [
{
engine: 'Trident',
browser: 'Internet Explorer 4.0',
@ -1202,8 +1202,21 @@ module.exports = [
version: '-',
grade: 'U'
}
].map(function (item, index) {
return Object.assign({}, item, {
id: index + 1
];
// 多来点测试数据
module.exports = list
.concat(list)
.concat(list)
.concat(list)
.concat(list)
.concat(list)
.concat(list)
.concat(list)
.concat(list)
.concat(list)
.map(function (item, index) {
return Object.assign({}, item, {
id: index + 1
});
});
});

View File

@ -57,3 +57,22 @@ export const createMockMediaMatcher =
return true;
}
});
// Mock IntersectionObserver
class IntersectionObserver {
observe = jest.fn();
disconnect = jest.fn();
unobserve = jest.fn();
}
Object.defineProperty(window, 'IntersectionObserver', {
writable: true,
configurable: true,
value: IntersectionObserver
});
Object.defineProperty(global, 'IntersectionObserver', {
writable: true,
configurable: true,
value: IntersectionObserver
});

View File

@ -46,7 +46,7 @@
"esm"
],
"dependencies": {
"amis-formula": "^3.4.0",
"amis-formula": "*",
"classnames": "2.3.2",
"file-saver": "^2.0.2",
"hoist-non-react-statics": "^3.3.2",
@ -58,8 +58,8 @@
"moment": "^2.19.4",
"papaparse": "^5.3.0",
"qs": "6.9.7",
"react-intersection-observer": "9.5.2",
"react-json-view": "1.21.3",
"react-visibility-sensor": "5.1.1",
"tslib": "^2.3.1",
"uncontrollable": "7.2.1"
},

View File

@ -440,14 +440,7 @@ export class SchemaRenderer extends React.Component<SchemaRendererProps, any> {
exprProps = {};
}
// style 支持公式
if (schema.style) {
// schema.style是readonly属性
schema = {...schema, style: buildStyle(schema.style, detectData)};
}
const isClassComponent = Component.prototype?.isReactComponent;
const $schema = {...schema, ...exprProps};
let props = {
...theme.getRendererConfig(renderer.name),
...restSchema,
@ -459,7 +452,7 @@ export class SchemaRenderer extends React.Component<SchemaRendererProps, any> {
defaultActiveKey: defaultActiveKey,
propKey: propKey,
$path: $path,
$schema: $schema,
$schema: schema,
ref: this.refFn,
render: this.renderChild,
rootStore,
@ -468,6 +461,11 @@ export class SchemaRenderer extends React.Component<SchemaRendererProps, any> {
mobileUI: schema.useMobileUI === false ? false : rest.mobileUI
};
// style 支持公式
if (schema.style) {
(props as any).style = buildStyle(schema.style, detectData);
}
if (disable !== undefined) {
(props as any).disabled = disable;
}
@ -478,7 +476,7 @@ export class SchemaRenderer extends React.Component<SchemaRendererProps, any> {
// 自动解析变量模式,主要是方便直接引入第三方组件库,无需为了支持变量封装一层
if (renderer.autoVar) {
for (const key of Object.keys($schema)) {
for (const key of Object.keys(schema)) {
if (typeof props[key] === 'string') {
props[key] = resolveVariableAndFilter(
props[key],

View File

@ -5,7 +5,7 @@
*/
import React from 'react';
import VisibilitySensor from 'react-visibility-sensor';
import {InView} from 'react-intersection-observer';
export interface LazyComponentProps {
component?: React.ElementType;
@ -13,7 +13,6 @@ export interface LazyComponentProps {
placeholder?: React.ReactNode;
unMountOnHidden?: boolean;
childProps?: object;
visiblilityProps?: object;
[propName: string]: any;
}
@ -56,7 +55,7 @@ export default class LazyComponent extends React.Component<
this.mounted = false;
}
handleVisibleChange(visible: boolean) {
handleVisibleChange(visible: boolean, entry?: any) {
this.setState({
visible: visible
});
@ -91,7 +90,6 @@ export default class LazyComponent extends React.Component<
placeholder,
unMountOnHidden,
childProps,
visiblilityProps,
partialVisibility,
children,
...rest
@ -102,33 +100,42 @@ export default class LazyComponent extends React.Component<
// 需要监听从可见到不可见。
if (unMountOnHidden) {
return (
<VisibilitySensor
{...visiblilityProps}
partialVisibility={partialVisibility}
<InView
onChange={this.handleVisibleChange}
threshold={partialVisibility ? 0 : 1}
>
<div className="visibility-sensor">
{Component && visible ? (
<Component {...rest} {...childProps} />
) : children && visible ? (
children
) : (
placeholder
)}
</div>
</VisibilitySensor>
{({ref}) => {
return (
<div
ref={ref}
className={`visibility-sensor ${visible ? 'in' : ''}`}
>
{Component && visible ? (
<Component {...rest} {...childProps} />
) : children && visible ? (
children
) : (
placeholder
)}
</div>
);
}}
</InView>
);
}
if (!visible) {
return (
<VisibilitySensor
{...visiblilityProps}
partialVisibility={partialVisibility}
<InView
onChange={this.handleVisibleChange}
threshold={partialVisibility ? 0 : 1}
>
<div className="visibility-sensor">{placeholder}</div>
</VisibilitySensor>
{({ref}) => (
<div ref={ref} className="visibility-sensor">
{placeholder}
</div>
)}
</InView>
);
} else if (Component) {
// 只监听不可见到可见,一旦可见了,就销毁检查。

View File

@ -3,7 +3,7 @@ import {IFormStore, IFormItemStore} from '../store/form';
import debouce from 'lodash/debounce';
import isEqual from 'lodash/isEqual';
import {RendererProps, Renderer} from '../factory';
import {RendererProps, Renderer, getRendererByName} from '../factory';
import {ComboStore, IComboStore, IUniqueGroup} from '../store/combo';
import {
anyChanged,
@ -32,7 +32,7 @@ import {FormBaseControl, FormItemWrap} from './Item';
import {Api} from '../types';
import {TableStore} from '../store/table';
import pick from 'lodash/pick';
import {callStrFunction} from '../utils';
import {callStrFunction, changedEffect} from '../utils';
export interface ControlOutterProps extends RendererProps {
formStore?: IFormStore;
@ -121,6 +121,8 @@ export function wrapControl<
onChange,
data,
inputGroupControl,
colIndex,
rowIndex,
$schema: {
name,
id,
@ -154,17 +156,14 @@ export function wrapControl<
this.setPrinstineValue = this.setPrinstineValue.bind(this);
this.controlRef = this.controlRef.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.validate = this.validate.bind(this);
this.flushChange = this.flushChange.bind(this);
if (!name) {
// 一般情况下这些表单项都是需要 name 的,提示一下
if (
typeof type === 'string' &&
(type.startsWith('input-') ||
type.endsWith('select') ||
type === 'switch' ||
type === 'textarea' ||
type === 'radios') &&
type !== 'input-group'
getRendererByName(type)?.isFormItem
) {
console.warn('name is required', this.props.$schema);
}
@ -178,7 +177,9 @@ export function wrapControl<
path: this.props.$path,
storeType: FormItemStore.name,
parentId: store?.id,
name
name,
colIndex: colIndex !== undefined ? colIndex : undefined,
rowIndex: rowIndex !== undefined ? rowIndex : undefined
}) as IFormItemStore;
this.model = model;
// @issue 打算干掉这个
@ -226,6 +227,7 @@ export function wrapControl<
if (propValue !== undefined && propValue !== null) {
// 同步 value: 优先使用 props 中的 value
model.changeTmpValue(propValue, 'controlled');
model.setIsControlled(true);
} else {
const isExp = isExpression(value);
@ -332,12 +334,10 @@ export function wrapControl<
componentDidUpdate(prevProps: OuterProps) {
const props = this.props;
const form = props.formStore;
const model = this.model;
if (
model &&
anyChanged(
model &&
changedEffect(
[
'id',
'validations',
@ -362,34 +362,17 @@ export function wrapControl<
'extraName'
],
prevProps.$schema,
props.$schema
)
) {
model.config({
required: props.$schema.required,
id: props.$schema.id,
unique: props.$schema.unique,
value: props.$schema.value,
isValueSchemaExp: isExpression(props.$schema.value),
rules: props.$schema.validations,
multiple: props.$schema.multiple,
delimiter: props.$schema.delimiter,
valueField: props.$schema.valueField,
labelField: props.$schema.labelField,
joinValues: props.$schema.joinValues,
extractValue: props.$schema.extractValue,
messages: props.$schema.validationErrors,
selectFirst: props.$schema.selectFirst,
autoFill: props.$schema.autoFill,
clearValueOnHidden: props.$schema.clearValueOnHidden,
validateApi: props.$schema.validateApi,
minLength: props.$schema.minLength,
maxLength: props.$schema.maxLength,
label: props.$schema.label,
inputGroupControl: props?.inputGroupControl,
extraName: props.$schema.extraName
});
}
props.$schema,
changes => {
model.config({
...changes,
// todo 优化后面两个
isValueSchemaExp: isExpression(props.$schema.value),
inputGroupControl: props?.inputGroupControl
} as any);
}
);
// 此处需要同时考虑 defaultValue 和 value
if (model && typeof props.value !== 'undefined') {
@ -605,13 +588,16 @@ export function wrapControl<
result = [await this.model.validate(data)];
}
if (result && result.length) {
if (result.indexOf(false) > -1) {
formItemDispatchEvent('formItemValidateError', data);
} else {
formItemDispatchEvent('formItemValidateSucc', data);
}
}
const valid = !result.some(item => item === false);
formItemDispatchEvent?.(
valid ? 'formItemValidateSucc' : 'formItemValidateError',
data
);
return valid;
}
flushChange() {
this.lazyEmitChange.flush();
}
handleChange(
@ -862,6 +848,8 @@ export function wrapControl<
getValue: this.getValue,
prinstine: model ? model.prinstine : undefined,
setPrinstineValue: this.setPrinstineValue,
onValidate: this.validate,
onFlushChange: this.flushChange,
// !没了这个, tree 里的 options 渲染会出问题
_filteredOptions: this.model?.filteredOptions
};

View File

@ -117,26 +117,27 @@ export const CRUDStore = ServiceStore.named('CRUDStore')
replace: boolean = false
) {
const originQuery = self.query;
self.query = replace
const query: any = replace
? {
...values
}
: {
...self.query,
...originQuery,
...values
};
if (self.query[pageField || 'page']) {
self.page = parseInt(self.query[pageField || 'page'], 10);
}
if (isObjectShallowModified(originQuery, query, false)) {
if (query[pageField || 'page']) {
self.page = parseInt(query[pageField || 'page'], 10);
}
if (self.query[perPageField || 'perPage']) {
self.perPage = parseInt(self.query[perPageField || 'perPage'], 10);
}
if (query[perPageField || 'perPage']) {
self.perPage = parseInt(query[perPageField || 'perPage'], 10);
}
updater &&
isObjectShallowModified(originQuery, self.query, false) &&
setTimeout(updater.bind(null, `?${qsstringify(self.query)}`), 4);
self.query = query;
updater && setTimeout(updater.bind(null, `?${qsstringify(query)}`), 4);
}
}
const fetchInitData: (

View File

@ -49,7 +49,7 @@ export const FormStore = ServiceStore.named('FormStore')
while (pool.length) {
const current = pool.shift()!;
if (current.storeType === 'FormItemStore') {
if (current.storeType === 'FormItemStore' && !current.isControlled) {
formItems.push(current);
} else if (
!['ComboStore', 'TableStore', 'FormStore'].includes(current.storeType)

View File

@ -67,6 +67,7 @@ const getSelectedOptionsCache: any = {
export const FormItemStore = StoreNode.named('FormItemStore')
.props({
isFocused: false,
isControlled: false, // 是否是受控表单项,通常是用在别的组件里面
type: '',
label: '',
unique: false,
@ -107,7 +108,9 @@ export const FormItemStore = StoreNode.named('FormItemStore')
resetValue: types.optional(types.frozen(), ''),
validateOnChange: false,
/** 当前表单项所属的InputGroup父元素, 用于收集InputGroup的子元素 */
inputGroupControl: types.optional(types.frozen(), {})
inputGroupControl: types.optional(types.frozen(), {}),
colIndex: types.frozen(),
rowIndex: types.frozen()
})
.views(self => {
function getForm(): any {
@ -358,28 +361,30 @@ export const FormItemStore = StoreNode.named('FormItemStore')
inputGroupControl?.name != null &&
(self.inputGroupControl = inputGroupControl);
rules = {
...rules,
isRequired: self.required || rules?.isRequired
};
if (typeof rules !== 'undefined' || self.required) {
rules = {
...rules,
isRequired: self.required || rules?.isRequired
};
// todo 这个弄个配置由渲染器自己来决定
// 暂时先这样
if (~['input-text', 'textarea'].indexOf(self.type)) {
if (typeof minLength === 'number') {
rules.minLength = minLength;
// todo 这个弄个配置由渲染器自己来决定
// 暂时先这样
if (~['input-text', 'textarea'].indexOf(self.type)) {
if (typeof minLength === 'number') {
rules.minLength = minLength;
}
if (typeof maxLength === 'number') {
rules.maxLength = maxLength;
}
}
if (typeof maxLength === 'number') {
rules.maxLength = maxLength;
if (isObjectShallowModified(rules, self.rules)) {
self.rules = rules;
clearError('builtin');
self.validated = false;
}
}
if (isObjectShallowModified(rules, self.rules)) {
self.rules = rules;
clearError('builtin');
self.validated = false;
}
}
function focus() {
@ -1334,6 +1339,10 @@ export const FormItemStore = StoreNode.named('FormItemStore')
}
}
function setIsControlled(value: any) {
self.isControlled = !!value;
}
return {
focus,
blur,
@ -1359,7 +1368,8 @@ export const FormItemStore = StoreNode.named('FormItemStore')
changeEmitedValue,
addSubFormItem,
removeSubFormItem,
loadAutoUpdateData
loadAutoUpdateData,
setIsControlled
};
});

View File

@ -1,7 +1,11 @@
import {Instance, types} from 'mobx-state-tree';
import {parseQuery} from '../utils/helper';
import {ServiceStore} from './service';
import {createObjectFromChain, extractObjectChain} from '../utils';
import {
createObjectFromChain,
extractObjectChain,
isObjectShallowModified
} from '../utils';
export const RootStore = ServiceStore.named('RootStore')
.props({
@ -42,7 +46,10 @@ export const RootStore = ServiceStore.named('RootStore')
self.runtimeErrorStack = errorStack;
},
updateLocation(location?: any, parseFn?: Function) {
self.query = parseFn ? parseFn(location) : parseQuery(location);
const query = parseFn ? parseFn(location) : parseQuery(location);
if (isObjectShallowModified(query, self.query, false)) {
self.query = query;
}
}
}));

View File

@ -111,6 +111,7 @@ export const Row = types
rowSpans: types.frozen({} as any),
index: types.number,
newIndex: types.number,
nth: 0,
path: '', // 行数据的位置
expandable: false,
checkdisable: false,
@ -119,7 +120,9 @@ export const Row = types
types.array(types.late((): IAnyModelType => Row)),
[]
),
depth: types.number // 当前children位于第几层便于使用getParent获取最顶层TableStore
depth: types.number, // 当前children位于第几层便于使用getParent获取最顶层TableStore
appeared: true,
lazyRender: false
})
.views(self => ({
get checked(): boolean {
@ -321,6 +324,10 @@ export const Row = types
index++;
}
}
},
markAppeared(value: any) {
value && (self.appeared = !!value);
}
}));
@ -344,6 +351,8 @@ export const TableStore = iRendererStore
),
'asc'
),
loading: false,
canAccessSuperData: false,
draggable: false,
dragging: false,
selectable: false,
@ -365,7 +374,8 @@ export const TableStore = iRendererStore
keepItemSelectionOnPageChange: false,
// 导出 Excel 按钮的 loading 状态
exportExcelLoading: false,
searchFormExpanded: false // 用来控制搜索框是否展开了,那个自动根据 searchable 生成的表单 autoGenerateFilter
searchFormExpanded: false, // 用来控制搜索框是否展开了,那个自动根据 searchable 生成的表单 autoGenerateFilter
lazyRenderAfter: 100
})
.views(self => {
function getColumnsExceptBuiltinTypes() {
@ -688,10 +698,12 @@ export const TableStore = iRendererStore
return getUnSelectedRows();
},
get falttenedRows() {
return flattenTree<IRow>(self.rows);
},
get checkableRows() {
return flattenTree<IRow>(self.rows).filter(
(item: IRow) => item.checkable
);
return this.falttenedRows.filter((item: IRow) => item.checkable);
},
get expandableRows() {
@ -821,6 +833,10 @@ export const TableStore = iRendererStore
style.right = right;
}
return [style, stickyClassName];
},
get items() {
return self.rows.concat();
}
};
})
@ -832,46 +848,60 @@ export const TableStore = iRendererStore
}
function update(config: Partial<STableStore>) {
config.primaryField !== void 0 &&
config.primaryField !== undefined &&
(self.primaryField = config.primaryField);
config.selectable !== void 0 && (self.selectable = config.selectable);
config.columnsTogglable !== void 0 &&
config.selectable !== undefined && (self.selectable = config.selectable);
config.columnsTogglable !== undefined &&
(self.columnsTogglable = config.columnsTogglable);
config.draggable !== void 0 && (self.draggable = config.draggable);
config.draggable !== undefined && (self.draggable = config.draggable);
if (typeof config.orderBy === 'string') {
if (
typeof config.orderBy === 'string' ||
typeof config.orderDir === 'string'
) {
setOrderByInfo(
config.orderBy,
config.orderDir === 'desc' ? 'desc' : 'asc'
config.orderBy ?? self.orderBy,
config.orderDir !== undefined
? config.orderDir === 'desc'
? 'desc'
: 'asc'
: self.orderDir
);
}
config.multiple !== void 0 && (self.multiple = config.multiple);
config.footable !== void 0 && (self.footable = config.footable);
config.expandConfig !== void 0 &&
config.multiple !== undefined && (self.multiple = config.multiple);
config.footable !== undefined && (self.footable = config.footable);
config.expandConfig !== undefined &&
(self.expandConfig = config.expandConfig);
config.itemCheckableOn !== void 0 &&
config.itemCheckableOn !== undefined &&
(self.itemCheckableOn = config.itemCheckableOn);
config.itemDraggableOn !== void 0 &&
config.itemDraggableOn !== undefined &&
(self.itemDraggableOn = config.itemDraggableOn);
config.hideCheckToggler !== void 0 &&
config.hideCheckToggler !== undefined &&
(self.hideCheckToggler = !!config.hideCheckToggler);
config.combineNum !== void 0 &&
config.combineNum !== undefined &&
(self.combineNum = parseInt(config.combineNum as any, 10) || 0);
config.combineFromIndex !== void 0 &&
config.combineFromIndex !== undefined &&
(self.combineFromIndex =
parseInt(config.combineFromIndex as any, 10) || 0);
config.maxKeepItemSelectionLength !== void 0 &&
config.maxKeepItemSelectionLength !== undefined &&
(self.maxKeepItemSelectionLength = config.maxKeepItemSelectionLength);
config.keepItemSelectionOnPageChange !== void 0 &&
config.keepItemSelectionOnPageChange !== undefined &&
(self.keepItemSelectionOnPageChange =
config.keepItemSelectionOnPageChange);
config.exportExcelLoading !== undefined &&
(self.exportExcelLoading = config.exportExcelLoading);
config.loading !== undefined && (self.loading = config.loading);
config.canAccessSuperData !== undefined &&
(self.canAccessSuperData = !!config.canAccessSuperData);
typeof config.lazyRenderAfter === 'number' &&
self.lazyRenderAfter === config.lazyRenderAfter;
if (config.columns && Array.isArray(config.columns)) {
let columns: Array<SColumn> = config.columns
.filter(column => column)
@ -1112,7 +1142,8 @@ export const TableStore = iRendererStore
depth: number,
pindex: number,
parentId: string,
path: string = ''
path: string = '',
nThRef: {index: number}
): any {
depth += 1;
return children.map((item, index) => {
@ -1131,6 +1162,7 @@ export const TableStore = iRendererStore
path: `${path}${index}`,
depth: depth,
index: index,
nth: nThRef.index++,
newIndex: index,
pristine: item,
data: item,
@ -1142,7 +1174,8 @@ export const TableStore = iRendererStore
depth,
index,
id,
`${path}${index}.`
`${path}${index}.`,
nThRef
)
: [],
expandable: !!(
@ -1164,6 +1197,7 @@ export const TableStore = iRendererStore
/* 避免输入内容为非数组挂掉 */
rows = !Array.isArray(rows) ? [] : rows;
const nThRef = {index: 0};
let arr: Array<SRow> = rows.map((item, index) => {
if (!isObject(item)) {
item = {
@ -1180,6 +1214,7 @@ export const TableStore = iRendererStore
key: String(`${index}-1-${index}`),
depth: 1, // 最大父节点默认为第一层,逐层叠加
index: index,
nth: nThRef.index++,
newIndex: index,
pristine: item,
path: `${index}`,
@ -1187,7 +1222,7 @@ export const TableStore = iRendererStore
rowSpans: {},
children:
item && Array.isArray(item.children)
? initChildren(item.children, 1, index, id, `${index}.`)
? initChildren(item.children, 1, index, id, `${index}.`, nThRef)
: [],
expandable: !!(
(item && Array.isArray(item.children) && item.children.length) ||
@ -1208,6 +1243,21 @@ export const TableStore = iRendererStore
replaceRow(arr, reUseRow);
self.isNested = self.rows.some(item => item.children.length);
// 前 20 个直接渲染,后面的按需渲染
if (
self.lazyRenderAfter &&
self.falttenedRows.length > self.lazyRenderAfter
) {
for (
let i = self.lazyRenderAfter, len = self.falttenedRows.length;
i < len;
i++
) {
self.falttenedRows[i].appeared = false;
self.falttenedRows[i].lazyRender = true;
}
}
const expand = self.footable && self.footable.expand;
if (
expand === 'first' ||

View File

@ -502,3 +502,30 @@ export function warning(cat: Category, msg: string, ext?: object) {
console.groupEnd();
store.logs.push(log);
}
// 辅助定位是因为什么属性变化导致了组件更新
export function traceProps(props: any, prevProps: any, componentName: string) {
console.log(
componentName,
Object.keys(props)
.map(key => {
if (props[key] !== prevProps[key]) {
if (key === 'data') {
return `data[${Object.keys(props[key])
.map(item => {
if (props[key][item] !== prevProps[key][item]) {
return `data.${item}`;
}
return '';
})
.filter(item => item)
.join(', ')}]`;
}
return key;
}
return '';
})
.filter(item => item)
);
}

View File

@ -1,14 +1,14 @@
import React from 'react';
import moment from 'moment';
import {isObservable, isObservableArray} from 'mobx';
import uniq from 'lodash/uniq'
import last from 'lodash/last'
import merge from 'lodash/merge'
import isPlainObject from 'lodash/isPlainObject'
import isEqual from 'lodash/isEqual'
import isNaN from 'lodash/isNaN'
import isNumber from 'lodash/isNumber'
import isString from 'lodash/isString'
import uniq from 'lodash/uniq';
import last from 'lodash/last';
import merge from 'lodash/merge';
import isPlainObject from 'lodash/isPlainObject';
import isEqual from 'lodash/isEqual';
import isNaN from 'lodash/isNaN';
import isNumber from 'lodash/isNumber';
import isString from 'lodash/isString';
import qs from 'qs';
import type {Schema, PlainObject, FunctionPropertyNames} from '../types';
@ -196,9 +196,37 @@ export function anyChanged(
to: {[propName: string]: any},
strictMode: boolean = true
): boolean {
return (typeof attrs === 'string' ? attrs.split(/\s*,\s*/) : attrs).some(
key => (strictMode ? from[key] !== to[key] : from[key] != to[key])
);
return (
typeof attrs === 'string'
? attrs.split(',').map(item => item.trim())
: attrs
).some(key => (strictMode ? from[key] !== to[key] : from[key] != to[key]));
}
type Mutable<T> = {
-readonly [k in keyof T]: T[k];
};
export function changedEffect<T extends Record<string, any>>(
attrs: string | Array<string>,
origin: T,
data: T,
effect: (changes: Partial<Mutable<T>>) => void,
strictMode: boolean = true
) {
const changes: Partial<T> = {};
const keys =
typeof attrs === 'string'
? attrs.split(',').map(item => item.trim())
: attrs;
keys.forEach(key => {
if (strictMode ? origin[key] !== data[key] : origin[key] != data[key]) {
(changes as any)[key] = data[key];
}
});
Object.keys(changes).length && effect(changes);
}
export function rmUndefined(obj: PlainObject) {

View File

@ -15,4 +15,8 @@
width: 100%;
height: 100%;
}
> .visibility-sensor {
height: 100%; // 修复图表高度为 0 visibility-sensor 无法触发的问题
}
}

View File

@ -1027,6 +1027,13 @@
}
}
}
// table 骨架样式
&-emptyBlock {
background-color: #eaebed;
border-radius: 5px;
line-height: 15px;
}
}
.#{$ns}InputTable {
@ -1074,6 +1081,7 @@
> .#{$ns}Button,
> .#{$ns}Button--disabled-wrap > .#{$ns}Button {
margin: px2rem(3px);
height: auto;
}
> .#{$ns}Button--disabled-wrap > .#{$ns}Button--link {

View File

@ -440,7 +440,7 @@ exports[`Renderer:input table add 1`] = `
/>
<col
data-index="5"
style="width: 100px;"
style="width: 150px;"
/>
</colgroup>
<thead>
@ -520,34 +520,24 @@ exports[`Renderer:input table add 1`] = `
class=""
>
<div
class="cxd-Form cxd-Form--normal cxd-Form--quickEdit"
novalidate=""
class="cxd-Form-item cxd-Form-item--normal"
data-role="form-item"
>
<input
style="display: none;"
type="submit"
value="aa"
/>
<div
class="cxd-Form-item cxd-Form-item--normal"
data-role="form-item"
class="cxd-Form-control cxd-TextControl"
>
<div
class="cxd-Form-control cxd-TextControl"
class="cxd-TextControl-input"
>
<div
class="cxd-TextControl-input"
>
<input
autocomplete="off"
class=""
name="a"
placeholder=""
size="10"
type="text"
value="bb"
/>
</div>
<input
autocomplete="off"
class=""
name="a"
placeholder=""
size="10"
type="text"
value="aa"
/>
</div>
</div>
</div>
@ -556,33 +546,24 @@ exports[`Renderer:input table add 1`] = `
class=""
>
<div
class="cxd-Form cxd-Form--normal cxd-Form--quickEdit"
novalidate=""
class="cxd-Form-item cxd-Form-item--normal"
data-role="form-item"
>
<input
style="display: none;"
type="submit"
/>
<div
class="cxd-Form-item cxd-Form-item--normal"
data-role="form-item"
class="cxd-Form-control cxd-TextControl"
>
<div
class="cxd-Form-control cxd-TextControl"
class="cxd-TextControl-input"
>
<div
class="cxd-TextControl-input"
>
<input
autocomplete="off"
class=""
name="b"
placeholder=""
size="10"
type="text"
value=""
/>
</div>
<input
autocomplete="off"
class=""
name="b"
placeholder=""
size="10"
type="text"
value="bb"
/>
</div>
</div>
</div>
@ -867,74 +848,65 @@ exports[`Renderer:input-table cell selects delete 1`] = `
class=""
>
<div
class="cxd-Form cxd-Form--normal cxd-Form--quickEdit"
novalidate=""
class="cxd-Form-item cxd-Form-item--normal"
data-role="form-item"
>
<input
style="display: none;"
type="submit"
/>
<div
class="cxd-Form-item cxd-Form-item--normal"
data-role="form-item"
class="cxd-SelectControl cxd-Form-control"
>
<div
class="cxd-SelectControl cxd-Form-control"
aria-expanded="false"
aria-haspopup="listbox"
class="cxd-Select cxd-Select--multi"
role="combobox"
tabindex="0"
>
<div
aria-expanded="false"
aria-haspopup="listbox"
class="cxd-Select cxd-Select--multi"
role="combobox"
tabindex="0"
class="cxd-Select-valueWrap"
>
<div
class="cxd-Select-valueWrap"
class="cxd-Select-value"
>
<div
class="cxd-Select-value"
<span
class="cxd-Select-valueLabel"
>
<span
class="cxd-Select-valueLabel"
>
s2
</span>
<span
class="cxd-Select-valueIcon"
>
<icon-mock
classname="icon icon-close"
icon="close"
/>
</span>
</div>
<div
class="cxd-Select-value"
s2
</span>
<span
class="cxd-Select-valueIcon"
>
<span
class="cxd-Select-valueLabel"
>
s3
</span>
<span
class="cxd-Select-valueIcon"
>
<icon-mock
classname="icon icon-close"
icon="close"
/>
</span>
</div>
<icon-mock
classname="icon icon-close"
icon="close"
/>
</span>
</div>
<span
class="cxd-Select-arrow"
<div
class="cxd-Select-value"
>
<icon-mock
classname="icon icon-right-arrow-bold"
icon="right-arrow-bold"
/>
</span>
<span
class="cxd-Select-valueLabel"
>
s3
</span>
<span
class="cxd-Select-valueIcon"
>
<icon-mock
classname="icon icon-close"
icon="close"
/>
</span>
</div>
</div>
<span
class="cxd-Select-arrow"
>
<icon-mock
classname="icon icon-right-arrow-bold"
icon="right-arrow-bold"
/>
</span>
</div>
</div>
</div>
@ -1265,128 +1237,119 @@ exports[`Renderer:input-table with combo column 1`] = `
class=""
>
<div
class="cxd-Form cxd-Form--normal cxd-Form--quickEdit"
novalidate=""
class="cxd-Form-item cxd-Form-item--normal"
data-role="form-item"
>
<input
style="display: none;"
type="submit"
/>
<div
class="cxd-Form-item cxd-Form-item--normal"
data-role="form-item"
class="cxd-ComboControl cxd-Form-control"
>
<div
class="cxd-ComboControl cxd-Form-control"
class="cxd-Combo cxd-Combo--single cxd-Combo--hor"
>
<div
class="cxd-Combo cxd-Combo--single cxd-Combo--hor"
class="cxd-Combo-item"
>
<div
class="cxd-Combo-item"
class="cxd-Combo-itemInner"
>
<div
class="cxd-Combo-itemInner"
class="cxd-Form cxd-Form--row cxd-Combo-form"
novalidate=""
>
<input
style="display: none;"
type="submit"
/>
<div
class="cxd-Form cxd-Form--row cxd-Combo-form"
novalidate=""
class="cxd-Form-row"
>
<input
style="display: none;"
type="submit"
/>
<div
class="cxd-Form-row"
class="cxd-Form-col"
>
<div
class="cxd-Form-col"
class="cxd-Form-item cxd-Form-item--row"
data-role="form-item"
>
<div
class="cxd-Form-item cxd-Form-item--row"
data-role="form-item"
class="cxd-Form-rowInner"
>
<div
class="cxd-Form-rowInner"
class="cxd-NumberControl cxd-Form-control"
>
<div
class="cxd-NumberControl cxd-Form-control"
class="cxd-Number cxd-Number--borderFull"
>
<div
class="cxd-Number cxd-Number--borderFull"
class="cxd-Number-handler-wrap"
>
<div
class="cxd-Number-handler-wrap"
<span
aria-disabled="false"
aria-label="Increase Value"
class="cxd-Number-handler cxd-Number-handler-up"
role="button"
unselectable="on"
>
<span
aria-disabled="false"
aria-label="Increase Value"
class="cxd-Number-handler cxd-Number-handler-up"
role="button"
class="cxd-Number-handler-up-inner"
unselectable="on"
>
<span
class="cxd-Number-handler-up-inner"
unselectable="on"
/>
</span>
<span
aria-disabled="false"
aria-label="Decrease Value"
class="cxd-Number-handler cxd-Number-handler-down"
role="button"
unselectable="on"
>
<span
class="cxd-Number-handler-down-inner"
unselectable="on"
/>
</span>
</div>
<div
class="cxd-Number-input-wrap"
>
<input
aria-valuenow="88"
autocomplete="off"
class="cxd-Number-input"
placeholder="请手动输入分数"
role="spinbutton"
step="1"
value="88"
/>
</div>
</span>
<span
aria-disabled="false"
aria-label="Decrease Value"
class="cxd-Number-handler cxd-Number-handler-down"
role="button"
unselectable="on"
>
<span
class="cxd-Number-handler-down-inner"
unselectable="on"
/>
</span>
</div>
<div
class="cxd-Number-input-wrap"
>
<input
aria-valuenow="88"
autocomplete="off"
class="cxd-Number-input"
placeholder="请手动输入分数"
role="spinbutton"
step="1"
value="88"
/>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="cxd-Form-col"
>
<div
class="cxd-Form-col"
class="cxd-Form-item cxd-Form-item--row"
data-role="form-item"
>
<div
class="cxd-Form-item cxd-Form-item--row"
data-role="form-item"
class="cxd-Form-rowInner"
>
<div
class="cxd-Form-rowInner"
class="cxd-Form-control cxd-TextControl"
>
<div
class="cxd-Form-control cxd-TextControl"
class="cxd-TextControl-input"
>
<div
class="cxd-TextControl-input"
>
<input
autocomplete="off"
class=""
name="comment"
placeholder="请手动输入意见"
size="10"
type="text"
value="this is comment msg!!"
/>
</div>
<input
autocomplete="off"
class=""
name="comment"
placeholder="请手动输入意见"
size="10"
type="text"
value="this is comment msg!!"
/>
</div>
</div>
</div>

View File

@ -72,7 +72,8 @@
"sortablejs": "1.15.0",
"tslib": "^2.3.1",
"video-react": "0.15.0",
"xlsx": "^0.18.5"
"xlsx": "^0.18.5",
"react-intersection-observer": "9.5.2"
},
"devDependencies": {
"@fortawesome/fontawesome-free": "^6.1.1",

View File

@ -58,6 +58,7 @@ import {
import type {PaginationProps} from './Pagination';
import {isAlive} from 'mobx-state-tree';
import isPlainObject from 'lodash/isPlainObject';
import memoize from 'lodash/memoize';
export type CRUDBultinToolbarType =
| 'columns-toggler'
@ -473,6 +474,10 @@ export default class CRUD extends React.Component<CRUDProps, any> {
/** 父容器, 主要用于定位CRUD内部popover的挂载点 */
parentContainer: Element | null;
filterOnEvent = memoize(onEvent =>
omitBy(onEvent, (event, key: any) => !INNER_EVENTS.includes(key))
);
constructor(props: CRUDProps) {
super(props);
@ -548,8 +553,8 @@ export default class CRUD extends React.Component<CRUDProps, any> {
}
componentDidMount() {
const {store, autoGenerateFilter, columns} = this.props;
if (this.props.perPage) {
const {store, autoGenerateFilter, perPageField, columns} = this.props;
if (this.props.perPage && !store.query[perPageField || 'perPage']) {
store.changePage(store.page, this.props.perPage);
}
@ -662,6 +667,7 @@ export default class CRUD extends React.Component<CRUDProps, any> {
componentWillUnmount() {
this.mounted = false;
clearTimeout(this.timer);
this.filterOnEvent.cache.clear?.();
}
/** 查找CRUD最近层级的父窗口 */
@ -2451,10 +2457,7 @@ export default class CRUD extends React.Component<CRUDProps, any> {
...rest,
// 通用事件 例如cus-event 如果直接透传给table 则会被触发2次
// 因此只将下层组件table、cards中自定义事件透传下去 否则通过crud配置了也不会执行
onEvent: omitBy(
onEvent,
(event, key: any) => !INNER_EVENTS.includes(key)
),
onEvent: this.filterOnEvent(onEvent),
columns: store.columns ?? rest.columns,
type: mode || 'table'
},

View File

@ -19,7 +19,6 @@ import {
ApiObject,
autobind,
isExpression,
ITableStore,
isPureVariable,
resolveVariableAndFilter,
getRendererByName,
@ -283,9 +282,9 @@ export default class FormTable extends React.Component<TableProps, TableState> {
entries: SimpleMap<any, number>;
entityId: number = 1;
subForms: any = {};
subFormItems: any = {};
rowPrinstine: Array<any> = [];
editting: any = {};
tableStore?: ITableStore;
constructor(props: TableProps) {
super(props);
@ -305,6 +304,7 @@ export default class FormTable extends React.Component<TableProps, TableState> {
this.handleRadioChange = this.handleRadioChange.bind(this);
this.getEntryId = this.getEntryId.bind(this);
this.subFormRef = this.subFormRef.bind(this);
this.subFormItemRef = this.subFormItemRef.bind(this);
this.handlePageChange = this.handlePageChange.bind(this);
this.emitValue = this.emitValue.bind(this);
}
@ -382,6 +382,10 @@ export default class FormTable extends React.Component<TableProps, TableState> {
this.subForms[`${x}-${y}`] = form;
}
subFormItemRef(form: any, x: number, y: number) {
this.subFormItems[`${x}-${y}`] = form;
}
async validate(): Promise<string | void> {
const {value, translate: __, columns} = this.props;
const minLength = this.resolveVariableProps(this.props, 'minLength');
@ -442,16 +446,18 @@ export default class FormTable extends React.Component<TableProps, TableState> {
}
}
if (!this.tableStore) return;
// 校验子项
const children = this.tableStore.children.filter(
item => item?.storeType === 'FormItemStore'
const subFormItemss: Array<any> = [];
Object.keys(this.subFormItems).forEach(
key =>
this.subFormItems[key] && subFormItemss.push(this.subFormItems[key])
);
const results = await Promise.all(
children.map(item => item.validate(this.props.value))
subFormItemss.map(item => item.props.onValidate())
);
let msg = ~results.indexOf(false) ? __('Form.validateFailed') : '';
return msg;
}
async emitValue() {
@ -728,6 +734,12 @@ export default class FormTable extends React.Component<TableProps, TableState> {
);
subForms.forEach(form => form.flush());
const subFormItems: Array<any> = [];
Object.keys(this.subFormItems).forEach(
key => this.subFormItems[key] && subFormItems.push(this.subFormItems[key])
);
subFormItems.forEach(item => item.props.onFlushChange?.());
const validateForms: Array<any> = [];
Object.keys(this.subForms).forEach(key => {
const arr = key.split('-');
@ -1229,7 +1241,7 @@ export default class FormTable extends React.Component<TableProps, TableState> {
label: __('Table.operation'),
className: 'v-middle nowrap',
fixed: 'right',
width: 100,
width: 150,
innerClassName: 'm-n'
};
columns.push(operation);
@ -1468,7 +1480,6 @@ export default class FormTable extends React.Component<TableProps, TableState> {
while (ref && ref.getWrappedInstance) {
ref = ref.getWrappedInstance();
}
this.tableStore = ref?.props?.store;
}
computedAddBtnDisabled() {
@ -1553,6 +1564,7 @@ export default class FormTable extends React.Component<TableProps, TableState> {
onSaveOrder: this.handleSaveTableOrder,
buildItemProps: this.buildItemProps,
quickEditFormRef: this.subFormRef,
quickEditFormItemRef: this.subFormItemRef,
columnsTogglable: columnsTogglable,
combineNum: combineNum,
combineFromIndex: combineFromIndex,

View File

@ -5,7 +5,7 @@
import React from 'react';
import {findDOMNode} from 'react-dom';
import {RendererProps, noop} from 'amis-core';
import {RendererProps, getRendererByName, noop} from 'amis-core';
import hoistNonReactStatic from 'hoist-non-react-statics';
import {ActionObject} from 'amis-core';
import keycode from 'keycode';
@ -121,8 +121,10 @@ export const HocQuickEdit =
this.handleWindowKeyPress = this.handleWindowKeyPress.bind(this);
this.handleWindowKeyDown = this.handleWindowKeyDown.bind(this);
this.formRef = this.formRef.bind(this);
this.formItemRef = this.formItemRef.bind(this);
this.handleInit = this.handleInit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleFormItemChange = this.handleFormItemChange.bind(this);
this.state = {
isOpened: false
@ -152,6 +154,17 @@ export const HocQuickEdit =
quickEditFormRef(ref, colIndex, rowIndex);
}
}
formItemRef(ref: any) {
const {quickEditFormItemRef, rowIndex, colIndex} = this.props;
if (quickEditFormItemRef) {
while (ref && ref.getWrappedInstance) {
ref = ref.getWrappedInstance();
}
quickEditFormItemRef(ref, colIndex, rowIndex);
}
}
handleWindowKeyPress(e: Event) {
const ns = this.props.classPrefix;
@ -337,6 +350,17 @@ export const HocQuickEdit =
);
}
handleFormItemChange(value: any) {
const {onQuickChange, quickEdit, name} = this.props;
onQuickChange(
{[name!]: value},
(quickEdit as QuickEditConfig).saveImmediately,
false,
quickEdit as QuickEditConfig
);
}
openQuickEdit() {
currentOpened = this;
this.setState({
@ -526,6 +550,51 @@ export const HocQuickEdit =
);
}
renderInlineForm() {
const {
render,
classnames: cx,
canAccessSuperData,
disabled,
value,
name
} = this.props;
const schema: any = this.buildSchema();
// 有且只有一个表单项时,直接渲染表单项
if (
Array.isArray(schema.body) &&
schema.body.length === 1 &&
!schema.body[0].unique && // 唯一模式还不支持
!schema.body[0].value && // 不能有默认值表达式什么的情况
schema.body[0].name &&
schema.body[0].name === name &&
schema.body[0].type &&
getRendererByName(schema.body[0].type)?.isFormItem
) {
return render('inline-form-item', schema.body[0], {
mode: 'normal',
value: value || '',
onChange: this.handleFormItemChange,
ref: this.formItemRef
});
}
return render('inline-form', schema, {
value: undefined,
wrapperComponent: 'div',
className: cx('Form--quickEdit'),
ref: this.formRef,
simpleMode: true,
onInit: this.handleInit,
onChange: this.handleChange,
formLazyChange: false,
canAccessSuperData,
disabled
});
}
render() {
const {
onQuickChange,
@ -556,20 +625,7 @@ export const HocQuickEdit =
(quickEdit as QuickEditConfig).isFormMode
) {
return (
<Component {...this.props}>
{render('inline-form', this.buildSchema(), {
value: undefined,
wrapperComponent: 'div',
className: cx('Form--quickEdit'),
ref: this.formRef,
simpleMode: true,
onInit: this.handleInit,
onChange: this.handleChange,
formLazyChange: false,
canAccessSuperData,
disabled
})}
</Component>
<Component {...this.props}>{this.renderInlineForm()}</Component>
);
} else {
return (

View File

@ -2,7 +2,7 @@ import React from 'react';
import {ClassNamesFn, RendererEvent} from 'amis-core';
import {SchemaNode, ActionObject} from 'amis-core';
import {TableRow} from './TableRow';
import TableRow from './TableRow';
import {filter} from 'amis-core';
import {observer} from 'mobx-react';
import {trace, reaction} from 'mobx';
@ -91,7 +91,8 @@ export class TableBody extends React.Component<TableBodyProps> {
onRowClick,
onRowDbClick,
onRowMouseEnter,
onRowMouseLeave
onRowMouseLeave,
store
} = this.props;
return rows.map((item: IRow, rowIndex: number) => {
@ -99,6 +100,7 @@ export class TableBody extends React.Component<TableBodyProps> {
const doms = [
<TableRow
{...itemProps}
store={store}
itemAction={itemAction}
classnames={cx}
checkOnItemClick={checkOnItemClick}
@ -136,6 +138,7 @@ export class TableBody extends React.Component<TableBodyProps> {
doms.push(
<TableRow
{...itemProps}
store={store}
itemAction={itemAction}
classnames={cx}
checkOnItemClick={checkOnItemClick}

View File

@ -81,53 +81,60 @@ export interface TableContentProps extends LocaleProps {
dispatchEvent?: Function;
onEvent?: OnEventProps;
loading?: boolean;
columnWidthReady?: boolean;
// 以下纯粹是为了监控
someChecked?: boolean;
allChecked?: boolean;
isSelectionThresholdReached?: boolean;
orderBy?: string;
orderDir?: string;
}
@observer
export class TableContent extends React.Component<TableContentProps> {
static renderItemActions(
props: Pick<
TableContentProps,
'itemActions' | 'render' | 'store' | 'classnames'
>
) {
const {itemActions, render, store, classnames: cx} = props;
export function renderItemActions(
props: Pick<
TableContentProps,
'itemActions' | 'render' | 'store' | 'classnames'
>
) {
const {itemActions, render, store, classnames: cx} = props;
if (!store.hoverRow) {
return null;
}
const finalActions = Array.isArray(itemActions)
? itemActions.filter(action => !action.hiddenOnHover)
: [];
if (!finalActions.length) {
return null;
}
return (
<ItemActionsWrapper store={store} classnames={cx}>
<div className={cx('Table-itemActions')}>
{finalActions.map((action, index) =>
render(
`itemAction/${index}`,
{
...(action as any),
isMenuItem: true
},
{
key: index,
item: store.hoverRow,
data: store.hoverRow!.locals,
rowIndex: store.hoverRow!.index
}
)
)}
</div>
</ItemActionsWrapper>
);
if (!store.hoverRow) {
return null;
}
const finalActions = Array.isArray(itemActions)
? itemActions.filter(action => !action.hiddenOnHover)
: [];
if (!finalActions.length) {
return null;
}
return (
<ItemActionsWrapper store={store} classnames={cx}>
<div className={cx('Table-itemActions')}>
{finalActions.map((action, index) =>
render(
`itemAction/${index}`,
{
...(action as any),
isMenuItem: true
},
{
key: index,
item: store.hoverRow,
data: store.hoverRow!.locals,
rowIndex: store.hoverRow!.index
}
)
)}
</div>
</ItemActionsWrapper>
);
}
export class TableContent extends React.PureComponent<TableContentProps> {
render() {
const {
placeholder,
@ -166,7 +173,8 @@ export class TableContent extends React.Component<TableContentProps> {
store,
dispatchEvent,
onEvent,
loading
loading,
columnWidthReady
} = this.props;
const tableClassName = cx('Table-table', this.props.tableClassName);
@ -182,7 +190,7 @@ export class TableContent extends React.Component<TableContentProps> {
ref={tableRef}
className={cx(
tableClassName,
store.columnWidthReady ? 'is-layout-fixed' : undefined
columnWidthReady ? 'is-layout-fixed' : undefined
)}
>
<ColGroup columns={columns} store={store} />
@ -293,7 +301,6 @@ export class TableContent extends React.Component<TableContentProps> {
affixRow={affixRow}
data={data}
rowsProps={{
data,
dispatchEvent,
onEvent
}}
@ -304,3 +311,27 @@ export class TableContent extends React.Component<TableContentProps> {
);
}
}
export default observer((props: TableContentProps) => {
const store = props.store;
// 分析 table/index.tsx 中的 renderHeadCell 依赖了以下属性
// store.someChecked;
// store.allChecked;
// store.isSelectionThresholdReached;
// store.allExpanded;
// store.orderBy
// store.orderDir
return (
<TableContent
{...props}
columnWidthReady={store.columnWidthReady}
someChecked={store.someChecked}
allChecked={store.allChecked}
isSelectionThresholdReached={store.isSelectionThresholdReached}
orderBy={store.orderBy}
orderDir={store.orderDir}
/>
);
});

View File

@ -1,9 +1,10 @@
import {observer} from 'mobx-react';
import React from 'react';
import type {IColumn, IRow} from 'amis-core/lib/store/table';
import {RendererEvent, RendererProps} from 'amis-core';
import {RendererEvent, RendererProps, autobind, traceProps} from 'amis-core';
import {Action} from '../Action';
import {isClickOnInput, createObject} from 'amis-core';
import {isClickOnInput} from 'amis-core';
import {useInView} from 'react-intersection-observer';
interface TableRowProps extends Pick<RendererProps, 'render'> {
onCheck: (item: IRow, value: boolean, shift?: boolean) => Promise<void>;
@ -38,31 +39,36 @@ interface TableRowProps extends Pick<RendererProps, 'render'> {
[propName: string]: any;
}
@observer
export class TableRow extends React.Component<TableRowProps> {
// reaction?: () => void;
constructor(props: TableRowProps) {
super(props);
this.handleAction = this.handleAction.bind(this);
this.handleQuickChange = this.handleQuickChange.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
this.handleDbClick = this.handleDbClick.bind(this);
this.handleMouseEnter = this.handleMouseEnter.bind(this);
this.handleMouseLeave = this.handleMouseLeave.bind(this);
export class TableRow extends React.PureComponent<
TableRowProps & {
expanded: boolean;
id: string;
newIndex: number;
isHover: boolean;
checked: boolean;
modified: boolean;
moved: boolean;
depth: number;
expandable: boolean;
appeard?: boolean;
checkdisable: boolean;
trRef?: React.Ref<any>;
}
> {
@autobind
handleMouseEnter(e: React.MouseEvent<HTMLTableRowElement>) {
const {item, itemIndex, onRowMouseEnter} = this.props;
onRowMouseEnter?.(item?.data, itemIndex);
}
@autobind
handleMouseLeave(e: React.MouseEvent<HTMLTableRowElement>) {
const {item, itemIndex, onRowMouseLeave} = this.props;
onRowMouseLeave?.(item?.data, itemIndex);
}
// 定义点击一行的行为,通过 itemAction配置
@autobind
async handleItemClick(e: React.MouseEvent<HTMLTableRowElement>) {
if (isClickOnInput(e)) {
return;
@ -92,16 +98,19 @@ export class TableRow extends React.Component<TableRowProps> {
}
}
@autobind
handleDbClick(e: React.MouseEvent<HTMLTableRowElement>) {
const {item, itemIndex, onRowDbClick} = this.props;
onRowDbClick?.(item?.data, itemIndex);
}
@autobind
handleAction(e: React.UIEvent<any>, action: Action, ctx: any) {
const {onAction, item} = this.props;
onAction && onAction(e, action, ctx || item.locals);
}
@autobind
handleQuickChange(
values: object,
saveImmediately?: boolean,
@ -116,6 +125,7 @@ export class TableRow extends React.Component<TableRowProps> {
onQuickChange(item, values, saveImmediately, savePristine, options);
}
@autobind
handleChange(
value: any,
name: string,
@ -157,18 +167,32 @@ export class TableRow extends React.Component<TableRowProps> {
parent,
itemAction,
onEvent,
expanded,
id,
newIndex,
isHover,
checked,
modified,
moved,
depth,
expandable,
appeard,
trRef,
...rest
} = this.props;
if (footableMode) {
if (!item.expanded) {
if (!expanded) {
return null;
}
return (
<tr
data-id={item.id}
data-index={item.newIndex}
ref={trRef}
data-id={id}
data-index={newIndex}
onClick={
checkOnItemClick || itemAction || onEvent?.rowClick
? this.handleItemClick
@ -178,10 +202,10 @@ export class TableRow extends React.Component<TableRowProps> {
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
className={cx(itemClassName, {
'is-hovered': item.isHover,
'is-checked': item.checked,
'is-modified': item.modified,
'is-moved': item.moved,
'is-hovered': isHover,
'is-checked': checked,
'is-modified': modified,
'is-moved': moved,
[`Table-tr--hasItemAction`]: itemAction, // 就是为了加鼠标效果
[`Table-tr--odd`]: itemIndex % 2 === 0,
[`Table-tr--even`]: itemIndex % 2 === 1
@ -208,20 +232,26 @@ export class TableRow extends React.Component<TableRowProps> {
</th>
) : null}
{renderCell(
`${regionPrefix}${itemIndex}/${column.index}`,
column,
item,
{
...rest,
width: null,
rowIndex: itemIndex,
colIndex: column.index,
key: column.index,
onAction: this.handleAction,
onQuickChange: this.handleQuickChange,
onChange: this.handleChange
}
{appeard ? (
renderCell(
`${regionPrefix}${itemIndex}/${column.index}`,
column,
item,
{
...rest,
width: null,
rowIndex: itemIndex,
colIndex: column.index,
key: column.index,
onAction: this.handleAction,
onQuickChange: this.handleQuickChange,
onChange: this.handleChange
}
)
) : (
<td key={column.index}>
<div className={cx('Table-emptyBlock')}>&nbsp;</div>
</td>
)}
</tr>
))}
@ -238,6 +268,7 @@ export class TableRow extends React.Component<TableRowProps> {
return (
<tr
ref={trRef}
onClick={
checkOnItemClick || itemAction || onEvent?.rowClick
? this.handleItemClick
@ -246,36 +277,79 @@ export class TableRow extends React.Component<TableRowProps> {
onDoubleClick={this.handleDbClick}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
data-index={item.depth === 1 ? item.newIndex : undefined}
data-id={item.id}
data-index={depth === 1 ? newIndex : undefined}
data-id={id}
className={cx(
itemClassName,
{
'is-hovered': item.isHover,
'is-checked': item.checked,
'is-modified': item.modified,
'is-moved': item.moved,
'is-expanded': item.expanded && item.expandable,
'is-expandable': item.expandable,
'is-hovered': isHover,
'is-checked': checked,
'is-modified': modified,
'is-moved': moved,
'is-expanded': expanded && expandable,
'is-expandable': expandable,
[`Table-tr--hasItemAction`]: itemAction,
[`Table-tr--odd`]: itemIndex % 2 === 0,
[`Table-tr--even`]: itemIndex % 2 === 1
},
`Table-tr--${item.depth}th`
`Table-tr--${depth}th`
)}
>
{columns.map(column =>
renderCell(`${itemIndex}/${column.index}`, column, item, {
...rest,
rowIndex: itemIndex,
colIndex: column.index,
key: column.index,
onAction: this.handleAction,
onQuickChange: this.handleQuickChange,
onChange: this.handleChange
})
appeard ? (
renderCell(`${itemIndex}/${column.index}`, column, item, {
...rest,
rowIndex: itemIndex,
colIndex: column.index,
key: column.index,
onAction: this.handleAction,
onQuickChange: this.handleQuickChange,
onChange: this.handleChange
})
) : (
<td key={column.index}>
<div className={cx('Table-emptyBlock')}>&nbsp;</div>
</td>
)
)}
</tr>
);
}
}
// 换成 mobx-react-lite 模式
export default observer((props: TableRowProps) => {
const item = props.item;
const store = props.store;
const columns = props.columns;
const canAccessSuperData =
store.canAccessSuperData ||
columns.some(item => item.pristine.canAccessSuperData);
const {ref, inView} = useInView({
threshold: 0,
onChange: item.markAppeared,
skip: !item.lazyRender
});
return (
<TableRow
{...props}
trRef={ref}
expanded={item.expanded}
id={item.id}
newIndex={item.newIndex}
isHover={item.isHover}
checked={item.checked}
modified={item.modified}
moved={item.moved}
depth={item.depth}
expandable={item.expandable}
checkdisable={item.checkdisable}
// data 在 TableRow 里面没有使用,这里写上是为了当列数据变化的时候 TableRow 重新渲染,
// 不是 item.locals 的原因是 item.locals 会变化多次,比如父级上下文变化也会进来,但是 item.data 只会变化一次。
data={canAccessSuperData ? item.locals : item.data}
appeard={item.lazyRender ? item.appeared || inView : true}
/>
);
});

View File

@ -17,6 +17,7 @@ import {Button} from 'amis-ui';
import {TableStore, ITableStore, padArr} from 'amis-core';
import {
anyChanged,
changedEffect,
getScrollParent,
difference,
autobind,
@ -38,7 +39,7 @@ import {TableCell} from './TableCell';
import type {AutoGenerateFilterObject} from '../CRUD';
import {HeadCellFilterDropDown} from './HeadCellFilterDropdown';
import {HeadCellSearchDropDown} from './HeadCellSearchDropdown';
import {TableContent} from './TableContent';
import TableContent, {renderItemActions} from './TableContent';
import {
BaseSchema,
SchemaApi,
@ -183,6 +184,12 @@ export type TableColumnObject = {
*/
canAccessSuperData?: boolean;
/**
* 100
* @default 100
*/
lazyRenderAfter?: number;
/**
* style作为单元格自定义样式的配置
*/
@ -569,7 +576,10 @@ export default class Table extends React.Component<TableProps, object> {
keepItemSelectionOnPageChange,
maxKeepItemSelectionLength,
onQuery,
autoGenerateFilter
autoGenerateFilter,
loading,
canAccessSuperData,
lazyRenderAfter
} = props;
let combineNum = props.combineNum;
@ -597,7 +607,10 @@ export default class Table extends React.Component<TableProps, object> {
combineNum,
combineFromIndex,
keepItemSelectionOnPageChange,
maxKeepItemSelectionLength
maxKeepItemSelectionLength,
loading,
canAccessSuperData,
lazyRenderAfter
});
if (
@ -770,58 +783,49 @@ export default class Table extends React.Component<TableProps, object> {
const props = this.props;
const store = props.store;
if (
anyChanged(
[
'selectable',
'columnsTogglable',
'draggable',
'orderBy',
'orderDir',
'multiple',
'footable',
'primaryField',
'itemCheckableOn',
'itemDraggableOn',
'hideCheckToggler',
'combineNum',
'combineFromIndex',
'expandConfig'
],
prevProps,
props
)
) {
let combineNum = props.combineNum;
if (typeof combineNum === 'string') {
combineNum = parseInt(
resolveVariableAndFilter(combineNum, props.data, '| raw'),
10
);
changedEffect(
[
'selectable',
'columnsTogglable',
'draggable',
'orderBy',
'orderDir',
'multiple',
'footable',
'primaryField',
'itemCheckableOn',
'itemDraggableOn',
'hideCheckToggler',
'combineNum',
'combineFromIndex',
'expandConfig',
'columns',
'loading',
'canAccessSuperData',
'lazyRenderAfter'
],
prevProps,
props,
changes => {
if (
changes.hasOwnProperty('combineNum') &&
typeof changes.combineNum === 'string'
) {
changes.combineNum = parseInt(
resolveVariableAndFilter(
changes.combineNum as string,
props.data,
'| raw'
),
10
);
}
if (changes.orderBy && !props.onQuery) {
delete changes.orderBy;
}
store.update(changes as any);
}
store.update({
selectable: props.selectable,
columnsTogglable: props.columnsTogglable,
draggable: props.draggable,
orderBy: props.onQuery ? props.orderBy : undefined,
orderDir: props.orderDir,
multiple: props.multiple,
primaryField: props.primaryField,
footable: props.footable,
itemCheckableOn: props.itemCheckableOn,
itemDraggableOn: props.itemDraggableOn,
hideCheckToggler: props.hideCheckToggler,
combineNum: combineNum,
combineFromIndex: props.combineFromIndex,
expandConfig: props.expandConfig
});
}
if (prevProps.columns !== props.columns) {
store.update({
columns: props.columns
});
}
);
if (
anyChanged(['source', 'value', 'items'], prevProps, props) ||
@ -1091,6 +1095,27 @@ export default class Table extends React.Component<TableProps, object> {
}
}
// 校验直接放在单元格里面的表单项
const subFormItems = store.children.filter(
item => item?.storeType === 'FormItemStore'
);
if (subFormItems.length) {
const result = await Promise.all(
subFormItems.map(item => {
let ctx = {};
if (item.rowIndex && store.rows[item.rowIndex]) {
ctx = store.rows[item.rowIndex].data;
}
return item.validate(ctx);
})
);
if (~result.indexOf(false)) {
return;
}
}
const rows = store.modifiedRows.map(item => item.data);
const rowIndexes = store.modifiedRows.map(item => item.path);
const diff = store.modifiedRows.map(item =>
@ -1149,6 +1174,14 @@ export default class Table extends React.Component<TableProps, object> {
key => this.subForms[key] && subForms.push(this.subForms[key])
);
subForms.forEach(item => item.clearErrors());
// 去掉错误提示
const subFormItems = store.children.filter(
item => item?.storeType === 'FormItemStore'
);
if (subFormItems.length) {
subFormItems.map(item => item.reset());
}
}
bulkUpdate(value: any, items: Array<object>) {
@ -1824,6 +1857,9 @@ export default class Table extends React.Component<TableProps, object> {
data
} = this.props;
// 注意,这里用关了哪些 store 里面的东西TableContent 里面得也用一下
// 因为 renderHeadCell 是 TableContent 回调的tableContent 不重新渲染,这里面也不会重新渲染
const style = {...props.style};
const [stickyStyle, stickyClassName] = store.getStickyStyles(
column,
@ -2713,7 +2749,6 @@ export default class Table extends React.Component<TableProps, object> {
itemActions,
dispatchEvent,
onEvent,
loading = false,
loadingConfig
} = this.props;
@ -2723,7 +2758,7 @@ export default class Table extends React.Component<TableProps, object> {
return (
<>
{TableContent.renderItemActions({
{renderItemActions({
store,
classnames: cx,
render,
@ -2746,7 +2781,7 @@ export default class Table extends React.Component<TableProps, object> {
classnames={cx}
columns={store.filteredColumns}
columnsGroup={store.columnGroup}
rows={store.rows}
rows={store.items} // store.rows 是没有变更的,所以不会触发更新
placeholder={placeholder}
render={render}
onMouseMove={
@ -2781,10 +2816,10 @@ export default class Table extends React.Component<TableProps, object> {
translate={translate}
dispatchEvent={dispatchEvent}
onEvent={onEvent}
loading={loading}
loading={store.loading} // store 的同步较慢,所以统一用 store 来下发,否则会出现 props 和 store 变化触发子节点两次 re-rerender
/>
<Spinner loadingConfig={loadingConfig} overlay show={loading} />
<Spinner loadingConfig={loadingConfig} overlay show={store.loading} />
</>
);
}