lodash#findIndex TypeScript Examples
The following examples show how to use
lodash#findIndex.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From gant-design with MIT License | 7 votes |
export function replaceRowData({
rowData,
targetData,
newData,
getRowNodeId,
up,
}: {
rowData: any[];
targetData: any;
newData: any[];
getRowNodeId: any;
up: boolean;
}): any[] {
const targetIndex = findIndex(
rowData,
itemData => getRowNodeId(targetData) === getRowNodeId(itemData),
);
const newDataSource = up
? [...rowData.slice(0, targetIndex), ...newData, ...rowData.slice(targetIndex)]
: [
...rowData.slice(0, targetIndex),
rowData[targetIndex],
...newData,
...rowData.slice(targetIndex + 1),
];
return newDataSource;
}
Example #2
Source File: utils.ts From gant-design with MIT License | 7 votes |
function findColumnIndex(itemCol, localColumns) {
const itemIndex = findIndex(
localColumns,
localItemCol =>
get(localItemCol, 'colId') === get(itemCol, 'colId') ||
get(localItemCol, 'colId') === get(itemCol, 'field'),
);
return itemIndex;
}
Example #3
Source File: utils.ts From gant-design with MIT License | 7 votes |
export function removeTagData(removeNodes: RowNode[], rowData: any[], getRowNodeId: any) {
const hisRecords: any[] = [],
newRecords: any[] = [],
removeRecords: any[] = [],
removeIndexs: any[] = [];
removeNodes.map(itemNode => {
const itemData = get(itemNode, 'data', {});
let recordItem = { ...itemData, _rowType: DataActions.removeTag };
if (itemData._rowType === DataActions.removeTag || itemData._rowType === DataActions.remove)
return console.warn('Deleted data cannot be deleted');
let hisRecordItem = { ...itemData };
itemData._rowType !== DataActions.add
? newRecords.push(recordItem)
: removeRecords.push(itemData);
const rowIndex = findIndex(
rowData,
rowItemData => getRowNodeId(rowItemData) === getRowNodeId(itemData),
);
removeIndexs.unshift(rowIndex);
hisRecords.unshift(hisRecordItem);
});
return { newRecords, hisRecords, removeIndexs, removeRecords };
}
Example #4
Source File: utils.ts From gant-design with MIT License | 7 votes |
export function getModifyData(records, getRowItemData, oldRecords, getRowNodeId) {
const hisRecords: any[] = [],
newRecords: any[] = [];
records.map((item, index) => {
const oldIndex = findIndex(oldRecords, oldItem => getRowNodeId(oldItem) === getRowNodeId(item));
var { data } = getRowItemData(item, get(oldRecords, `[${oldIndex}]`, undefined));
if (isEqualObj(data, item)) return;
let { _rowData, _rowType = null, ...oldData } = data;
let { _rowData: nextRowData, _rowType: nextRowType, ...newData } = item;
if (nextRowType === DataActions.remove || nextRowType === DataActions.removeTag)
return console.warn('Cannot modify deleted data');
_rowData = isEmpty(_rowData) ? oldData : _rowData;
const hasChange = !isEqualObj(_rowData, newData);
_rowType =
!_rowType || _rowType === DataActions.modify
? hasChange
? DataActions.modify
: null
: _rowType;
let recordItem = { ...newData, _rowData, _rowType };
let hisRecordItem = data;
newRecords.push(recordItem);
hisRecords.push(hisRecordItem);
});
return { newRecords, hisRecords };
}
Example #5
Source File: dice-yaml-editor.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
private onKeyUp = (e: any) => {
const { points } = this.state;
if (this.selectedLine && e.keyCode === 8) {
const { fromPoint } = this.selectedLine.point;
const { toPoint } = this.selectedLine.point;
// @ts-ignore
const lineTo = points[fromPoint.groupIndex][fromPoint.index].lineTo || [];
const index = findIndex(lineTo, (o) => {
return o === toPoint.name;
});
lineTo.splice(index, 1);
this.setState({
points: cloneDeep(points),
});
this.selectedLine.line.remove();
this.selectedLine = null;
}
};
Example #6
Source File: index.ts From gant-design with MIT License | 6 votes |
//批量更新数据 返回更新后的gird数据
batchUpdateDataSource(params: BatchUpdateDataSourceParams, keys: string | string[] = []) {
const { getRowNodeId } = this.agGridConfig;
const dataSource: any = [];
const { add, modify, remove } = params;
const update = uniqBy([...add, ...modify], 'dataNumber');
const removeKeys = remove.map(item => getRowNodeId(item));
const removeNodes = getAllChildrenNode(removeKeys, this.agGridApi, false);
const assignKeys = typeof keys === 'string' ? [keys] : keys;
this.agGridApi.forEachNode(function(node, index) {
const removeIndex = findIndex(
removeNodes,
item => getRowNodeId(get(node, 'data')) === getRowNodeId(get(item, 'data')),
);
if (removeIndex >= 0) return;
const updateIndex = findIndex(update, item => item.dataNumber === index);
const { _rowType, _rowData, _rowCut, _rowError, treeDataPath, ...data } = get(
node,
'data',
{},
);
if (updateIndex >= 0) {
const mergeData = {};
assignKeys.map(item => {
mergeData[item] = data[item];
});
const updateItem = { ...update[updateIndex], ...mergeData };
return dataSource.push(updateItem);
}
dataSource.push(data);
} as any);
console.log('batchUpdateDataSource');
return dataSource;
}
Example #7
Source File: index.ts From gant-design with MIT License | 6 votes |
//移除;
@hisDecorator()
remove(targetid, deleteChildren = false) {
if (typeof targetid !== 'number' && isEmpty(targetid)) return;
const { getRowNodeId } = this.agGridConfig;
let targetArray = Array.isArray(targetid) ? targetid : [targetid];
if (targetArray.length <= 0) return;
const recordsIndex: number[] = [];
const records: any[] = [];
const rowData = this.getRowData();
const removeNodes = getAllChildrenNode(targetArray, this.agGridApi, deleteChildren);
removeNodes.map(itemNode => {
const { data, childIndex } = itemNode;
if (data) {
const rowIndex = findIndex(
rowData,
itemData => getRowNodeId(itemData) === getRowNodeId(data),
);
recordsIndex.unshift(rowIndex);
records.unshift(data);
}
});
this.historyStack.push({
type: DataActions.remove,
recordsIndex: recordsIndex,
records: records,
});
this.batchUpdateGrid({
remove: records,
});
return records;
}
Example #8
Source File: traceSummary.ts From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
// returns 'critical' if one of the spans has an ERROR binary annotation, else
// returns 'transient' if one of the spans has an ERROR annotation, else
// returns 'none'
export function getTraceErrorType(spans: any) {
let traceType = 'none';
for (let i = 0; i < spans.length; i++) {
const span = spans[i];
if (findIndex(span.binaryAnnotations || [], (ann: any) => ann.key === Constants.ERROR) !== -1) {
return 'critical';
} else if (
traceType === 'none' &&
findIndex(span.annotations || [], (ann: any) => ann.value === Constants.ERROR) !== -1
) {
traceType = 'transient';
}
}
return traceType;
}
Example #9
Source File: properties-file.ts From relate with GNU General Public License v3.0 | 6 votes |
private setEntry(key: string, val: string | boolean): void {
const configEntries: PropertyEntries = [...this.config];
const entryIndex = findIndex(configEntries, (configEntry) => includes([`#${key}`, key], configEntry[0]));
if (entryIndex >= 0) {
const entry = configEntries[entryIndex];
if (includes(entry[0], '#')) {
entry[0] = key;
}
entry[1] = `${val}`;
this.config = configEntries;
return;
}
this.config = [...configEntries, [key, `${val}`]];
}
Example #10
Source File: edit-global-variable.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
private deleteVariable = (key: string) => {
const { globalVariableList } = this.state;
const index = findIndex(globalVariableList, (item: any) => item.key === key);
globalVariableList.splice(index, 1);
this.setState({
globalVariableList: cloneDeep(globalVariableList),
});
};
Example #11
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
registerFormComponent = (props: IRegisterFormProps[]) => {
map(props, (item) => {
const { componentConfig, formConfig, key } = item;
componentFormConfig[key] = { ...formConfig[key] };
let curIndex = findIndex(components, { name: key });
if (curIndex === -1) curIndex = components.length;
set(components, `[${curIndex}]`, { ...componentConfig, name: key });
});
registComponents(components);
}
Example #12
Source File: utils.ts From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
convertDataForGantt = (
data: { expandList: CP_GANTT.IData[]; updateList: CP_GANTT.IData[]; refresh?: boolean },
prevList: CP_GANTT.IGanttData[],
) => {
const { expandList, updateList, refresh } = data;
let ganttData: CP_GANTT.IGanttData[] = refresh ? [] : [...prevList];
const timeConvert = (start: number, end: number) => {
let _start = start && moment(start).startOf('day');
let _end = end && moment(end).endOf('day');
if (!start && end) {
// no start time
_start = moment(_end).startOf('day');
} else if (!end && start) {
_end = moment(_start).endOf('day');
}
return {
start: _start && new Date(_start.valueOf()),
end: _end && new Date(_end.valueOf()),
};
};
const prevDataGroup = { ...groupBy(ganttData, 'pId'), ...expandList };
const convert = (dataTemp: CP_GANTT.IData[], level = 0, pId?: string) => {
dataTemp.forEach((item) => {
const { key, title, start, end, isLeaf = true, hideChildren, ...rest } = item;
const validTime = timeConvert(start, end);
const curData = {
type: !isLeaf ? 'project' : ('task' as CP_GANTT.TaskType),
id: key,
name: title,
start: validTime.start,
end: validTime.end,
progress: 0,
isLeaf,
hideChildren: hideChildren === undefined ? (!isLeaf ? !prevDataGroup[key]?.length : undefined) : hideChildren,
level,
pId: pId || 0,
...(pId ? { project: pId } : {}),
...rest,
};
ganttData.push(curData);
if (prevDataGroup[curData.id]) {
convert(prevDataGroup[curData.id], level + 1, curData.id);
}
});
};
if (expandList) {
ganttData = [];
convert(prevDataGroup['0']); // root: 0
}
if (updateList?.length) {
updateList.forEach((item) => {
const curDataIndex = findIndex(ganttData, (gItem) => gItem.id === item.key);
if (curDataIndex !== -1) {
const { key, title, start, end, isLeaf = true, hideChildren, ...rest } = item;
set(ganttData, `[${curDataIndex}]`, {
...ganttData[curDataIndex],
...rest,
isLeaf,
hideChildren: hideChildren === undefined ? (!isLeaf ? !prevDataGroup[key]?.length : undefined) : hideChildren,
id: key,
name: title,
start: start && new Date(start),
end: end && new Date(end),
type: !isLeaf ? 'project' : 'task',
});
}
});
}
return ganttData;
}
Example #13
Source File: properties-file.ts From relate with GNU General Public License v3.0 | 6 votes |
public get(key: string): string | undefined {
const entryIndex = findIndex(this.config, (configEntry) => key === configEntry[0]);
if (entryIndex >= 0) {
return this.config[entryIndex][1];
}
return this.defaults[key];
}
Example #14
Source File: utils.ts From S2 with MIT License | 6 votes |
calculateInViewIndexes = (
scrollX: number,
scrollY: number,
widths: number[],
heights: ViewCellHeights,
viewport: SimpleBBox,
rowRemainWidth?: number,
): Indexes => {
// 1. 计算 x min、max
let xMin = findIndex(
widths,
(width: number, idx: number) => {
const x =
scrollX - (isNil(rowRemainWidth) ? 0 : rowRemainWidth) + viewport.x;
return x >= width && x < widths[idx + 1];
},
0,
);
xMin = Math.max(xMin, 0);
let xMax = findIndex(
widths,
(width: number, idx: number) => {
const x = viewport.width + scrollX + viewport.x;
return x >= width && x < widths[idx + 1];
},
xMin,
);
xMax = Math.min(xMax === -1 ? Infinity : xMax, widths.length - 2);
const { start: yMin, end: yMax } = heights.getIndexRange(
scrollY + viewport.y,
viewport.height + scrollY + viewport.y,
);
// use direction
// const halfWidthSize = Math.ceil(xMax - xMin / 4);
// const halfHeightSize = Math.ceil(yMax - yMin / 4);
// xMin = Math.max(0, xMin - halfWidthSize)
// xMax = xMax + halfWidthSize;
// yMin = Math.max(0, yMin - halfHeightSize);
// yMax = yMax + halfHeightSize;
return [xMin, xMax, yMin, yMax];
}
Example #15
Source File: outputInterpreter.ts From nautilus-wallet with MIT License | 6 votes |
private getSendingAssets(): OutputAsset[] {
const assets = [] as OutputAsset[];
assets.push({
tokenId: ERG_TOKEN_ID,
name: "ERG",
amount: decimalize(toBigNumber(this._box.value)!, ERG_DECIMALS)
});
if (isEmpty(this._box.assets)) {
return assets;
}
const tokens = this._box.assets.map((t) => {
return {
tokenId: t.tokenId,
name: this._assetInfo[t.tokenId]?.name,
amount: this._assetInfo[t.tokenId]?.decimals
? decimalize(toBigNumber(t.amount)!, this._assetInfo[t.tokenId].decimals ?? 0)
: toBigNumber(t.amount)
} as OutputAsset;
});
const minting = this.getMintingToken();
if (minting) {
const index = findIndex(tokens, (t) => t.tokenId === minting.tokenId);
if (index > -1) {
tokens[index] = minting;
}
}
return assets.concat(tokens);
}
Example #16
Source File: objectPool.ts From nautilus-wallet with MIT License | 6 votes |
public alloc(object: ObjectType, key: KeyType): ObjectType {
const item = this.getPoolItem(key);
if (item) {
item.alive = true;
item.object = object;
} else {
const index = findIndex(this._pool, item => !item.alive);
if (index > -1) {
this._pool[index].object = object;
this._pool[index].key = key;
this._pool[index].alive = true;
}
this._pool.push({ key, object, alive: true });
}
return object;
}
Example #17
Source File: schema.ts From nebula-studio with Apache License 2.0 | 5 votes |
addTagsName = (payload: any) => {
const { tag, tagFields } = payload;
const index = findIndex(this.tagsFields, item => item.tag === tag);
this.tagsFields[!~index ? this.tagsFields.length : index] = { tag, fields: tagFields };
};
Example #18
Source File: gantt.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
getTreeLine = (task: CP_GANTT.IGanttData, tasksGroup: Obj<CP_GANTT.IGanttData[]>, rowHeight = 38) => {
const { level, id, project } = task;
const indentHeight = rowHeight;
const curGroup = project && tasksGroup[project] ? tasksGroup[project] : [];
let isLast = false;
if (curGroup?.length && findIndex(curGroup, (item) => item.id === id) === curGroup.length - 1) {
isLast = true;
}
const LineComp: React.ReactNode[] = new Array(level > 1 ? level - 1 : 0)
.fill('')
.map((_, idx) => (
<div key={`${idx}`} className="erda-tree-indent-full" style={{ width: indentWidth, height: indentHeight }} />
));
if (LineComp.length)
LineComp.unshift(<div key={`${id}-holder`} style={{ width: indentWidth / 2 }} className="h-full" />);
if (level !== 0) {
const indentMargin = LineComp.length ? 0 : indentWidth / 2;
LineComp.push(
<div key={`${id}-left`} className="h-full" style={{ width: indentWidth }}>
<div
className={`erda-tree-indent-left ${isLast ? 'last-item' : ''}`}
style={{
width: indentWidth / 2,
height: indentHeight / 2,
marginLeft: indentMargin,
}}
/>
{!isLast ? (
<div
className="erda-tree-indent-left-bottom"
style={{ width: 1, height: indentHeight / 2, marginLeft: indentMargin }}
/>
) : null}
</div>,
);
}
if (tasksGroup[id]) {
// has children
LineComp.push(
<div
key={`${id}-right`}
style={{ height: indentHeight / 4, width: 1, right: -9, bottom: 0 }}
className="absolute erda-tree-indent-right"
/>,
);
}
if (LineComp.length) {
return <div className="flex erda-tree-indent relative h-full">{LineComp}</div>;
}
return null;
}
Example #19
Source File: facet.ts From S2 with MIT License | 5 votes |
getIndexRangeWithOffsets = (
heights: number[],
minHeight: number,
maxHeight: number,
) => {
if (maxHeight <= 0) {
return {
start: 0,
end: 0,
};
}
let yMin = findIndex(
heights,
(height: number, idx: number) => {
const y = minHeight;
return y >= height && y < heights[idx + 1];
},
0,
);
yMin = Math.max(yMin, 0);
let yMax =
maxHeight === minHeight
? yMin
: findIndex(
heights,
(height: number, idx: number) => {
const y = maxHeight;
return y > height && y <= heights[idx + 1];
},
yMin,
);
yMax = Math.min(yMax === -1 ? Infinity : yMax, heights.length - 2);
return {
start: yMin,
end: yMax,
};
}
Example #20
Source File: ergoApiHandlers.ts From nautilus-wallet with MIT License | 5 votes |
export async function handleGetBoxesRequest(
request: RpcMessage,
port: chrome.runtime.Port,
session?: Session
) {
if (!validateRequest(session, request, port)) {
return;
}
let tokenId = ERG_TOKEN_ID;
let amount = new BigNumber(0);
if (request.params) {
tokenId = request.params[1] as string;
if (!tokenId || tokenId === "ERG") {
tokenId = ERG_TOKEN_ID;
}
let error: APIError | undefined = undefined;
if (request.params[0]) {
amount = toBigNumber(request.params[0]) || new BigNumber(0);
}
if (request.params[2]) {
error = {
code: APIErrorCode.InvalidRequest,
info: "pagination is not implemented"
};
}
if (error) {
postErrorMessage(error, request, port);
}
}
let selected = await fetchBoxes(session!.walletId!);
if (tokenId != ERG_TOKEN_ID) {
selected = selected.filter((box) => findIndex(box.assets, (a) => a.tokenId === tokenId) > -1);
}
if (!amount.isZero()) {
let acc = new BigNumber(0);
if (tokenId === ERG_TOKEN_ID) {
selected = selected.filter((box) => {
if (acc.isGreaterThanOrEqualTo(amount)) {
return false;
}
acc = acc.plus(toBigNumber(box.value)!);
return true;
});
} else {
selected = selected.filter((box) => {
if (acc.isGreaterThanOrEqualTo(amount)) {
return false;
}
acc = acc.plus(toBigNumber(find(box.assets, (a) => a.tokenId === tokenId)?.amount ?? 0)!);
return true;
});
}
}
postConnectorResponse(
{
isSuccess: true,
data: selected
},
request,
port
);
}
Example #21
Source File: index.ts From gant-design with MIT License | 5 votes |
//
private changeDiff() {
const { getRowNodeId } = this.agGridConfig;
const diffRecords: any = [];
const diffArray: any[] = [];
const defaultDiff: Diff = {
add: [],
modify: [],
remove: [],
};
if (!this.agGridApi) return defaultDiff;
const nowHistoryStack = cloneDeep(this.historyStack);
nowHistoryStack.reverse().map(hisItem => {
const { type, recordsIndex, records } = hisItem;
records.map((recordItem, recordItemIndex) => {
const isRecorded = diffRecords.indexOf(getRowNodeId(recordItem)) >= 0;
if (isRecorded) return;
const rowNode = this.agGridApi.getRowNode(getRowNodeId(recordItem));
const _nextRowData = get(rowNode, 'data', recordItem);
let { _rowData, _rowType, _rowError, undefined, ...data } = _nextRowData;
_rowData = isEmpty(_rowData) ? data : _rowData;
diffRecords.push(getRowNodeId(_nextRowData));
switch (type) {
case DataActions.add:
return diffArray.push({ ...data, actionType: DataActions.add });
case DataActions.modify:
if (!isEqualObj(_rowData, data) && _rowType !== DataActions.add) {
diffArray.push({ ...data, actionType: DataActions.modify });
} else if (_rowType === DataActions.add) {
diffArray.push({ ...data, actionType: DataActions.add });
}
return;
default:
if (_rowType !== DataActions.add) {
diffArray.push({ ..._rowData, actionType: DataActions.remove });
}
return;
}
});
});
this.agGridApi.forEachNode(function(node, index) {
const diffIndex = findIndex(diffArray, item => {
return getRowNodeId(item) === getRowNodeId(get(node, 'data', {}));
});
if (diffIndex >= 0) {
diffArray[diffIndex] = { ...diffArray[diffIndex], dataNumber: index };
}
} as any);
const diff: Diff = groupBy(diffArray, 'actionType');
return isEmpty(diff) ? defaultDiff : { ...defaultDiff, ...diff };
}
Example #22
Source File: index.ts From gant-design with MIT License | 5 votes |
private toggleUndoRedo(hisStack: OperationAction, undo: boolean = true) {
const { getRowNodeId } = this.agGridConfig;
let rowData = this.getRowData();
if (rowData.length == 0) this.agGridApi.setRowData([]);
let { records, recordsIndex, type } = hisStack;
if (type === DataActions.remove) {
recordsIndex.map((removeIndex, index) => {
rowData = [...rowData.slice(0, removeIndex), records[index], ...rowData.slice(removeIndex)];
});
this.agGridApi.setRowData(rowData);
recordsIndex = [];
type = DataActions.add;
} else if (type === DataActions.add) {
recordsIndex = [];
records.map(itemRecord => {
const removeIndex = findIndex(
rowData,
data => getRowNodeId(data) === getRowNodeId(itemRecord),
);
rowData = [...rowData.slice(0, removeIndex), ...rowData.slice(removeIndex + 1)];
recordsIndex.unshift(removeIndex);
});
records = records.reverse();
type = DataActions.remove;
this.batchUpdateGrid({
remove: records,
});
} else if (type === DataActions.modify) {
const hisRecords: any[] = [];
const newRecords = records.map(item => {
const rowNode = this.agGridApi.getRowNode(getRowNodeId(item));
const { _nextRowData, ...data } = item;
hisRecords.push({ ...get(rowNode, 'data', {}) });
return item;
});
records = hisRecords;
this.batchUpdateGrid({ update: newRecords });
} else {
const hisRecords: any[] = [];
recordsIndex.map((removeIndex, index) => {
const item = records[index];
if (item._rowType === DataActions.add) {
if (undo) {
rowData = [...rowData.slice(0, removeIndex), item, ...rowData.slice(removeIndex)];
} else {
rowData = [...rowData.slice(0, removeIndex), ...rowData.slice(removeIndex + 1)];
}
hisRecords.push(item);
} else {
rowData = [...rowData.slice(0, removeIndex), item, ...rowData.slice(removeIndex + 1)];
const rowNode = this.agGridApi.getRowNode(getRowNodeId(item));
hisRecords.push({ ...get(rowNode, 'data', {}) });
}
});
records = hisRecords.reverse();
recordsIndex = recordsIndex.reverse();
this.agGridApi.setRowData(rowData);
}
return { type, records, recordsIndex };
}
Example #23
Source File: index.ts From gant-design with MIT License | 5 votes |
// 创建;
@hisDecorator()
public create(
records: any,
targetId?: boolean | string | string[] | number | number[],
isSub: boolean = true,
) {
const { getRowNodeId } = this.agGridConfig;
let addRecords = Array.isArray(records) ? records : [records];
if (addRecords.length <= 0) return;
let rowData = this.getRowData();
this.agGridApi.setSortModel([]);
if ((typeof targetId !== 'number' && !targetId) || typeof targetId === 'boolean') {
const isFirst: boolean = typeof targetId === 'boolean' && targetId;
addRecords = addRecords.map(item => ({ ...item, _rowType: DataActions.add }));
this.agGridApi.setRowData(
isFirst ? [...addRecords, ...rowData] : [...rowData, ...addRecords],
);
this.validate(addRecords);
this.historyStack.push({
type: DataActions.add,
records: addRecords,
});
return;
}
let targetArray = Array.isArray(targetId) ? targetId : [targetId];
addRecords = addRecords;
let hisRecords: any[] = [];
const newRecords: any[] = [];
targetArray.map((itemId, index) => {
let targetIndex = findIndex(rowData, data => getRowNodeId(data) == itemId);
targetIndex = isSub ? targetIndex + 1 : targetIndex;
let addTarget = get(addRecords, `[${index}]`, addRecords);
addTarget = Array.isArray(addTarget) ? addTarget : addRecords;
addTarget = addTarget.map(item => ({ ...item, _rowType: DataActions.add }));
rowData = [...rowData.slice(0, targetIndex), ...addTarget, ...rowData.slice(targetIndex)];
newRecords.push(...addTarget);
hisRecords = [...hisRecords, ...addTarget];
});
this.agGridApi.setRowData([...rowData]);
this.validate(newRecords);
this.historyStack.push({
type: DataActions.add,
records: hisRecords,
});
}
Example #24
Source File: case-footer.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
CaseFooter = ({ scope, caseList, editMode, onClose, onOk }: IProps) => {
const caseDetail = testCaseStore.useStore((s) => s.caseDetail);
const { getCaseDetail } = testCaseStore.effects;
const { updateCasesStatus } = testPlanStore.effects;
if (scope === 'testPlan' && editMode) {
let prevCase = undefined as any;
let nextCase = undefined as any;
const index = findIndex(caseList, { id: caseDetail.planRelationCaseID });
prevCase = caseList[index - 1];
nextCase = caseList[index + 1];
const passAndNext = (status: string) => {
updateCasesStatus({ relationIDs: [caseDetail.planRelationCaseID], execStatus: status });
nextCase && getCaseDetail({ id: nextCase.id, scope });
};
const toPrev = () => {
prevCase && getCaseDetail({ id: prevCase.id, scope });
};
const toNext = () => {
nextCase && getCaseDetail({ id: nextCase.id, scope });
};
return (
<>
<PassAndNext current={caseDetail.execStatus} hasNext={!!nextCase} onClick={passAndNext} />
<Button.Group className="ml-3">
<Button>
<span style={{ lineHeight: '1.5' }}>
{index + 1} / {caseList.length}
</span>
</Button>
<Button disabled={!prevCase} onClick={toPrev}>
<CustomIcon type="chevron-up" />
</Button>
<Button disabled={!nextCase} onClick={toNext}>
<CustomIcon type="chevron-down" />
</Button>
</Button.Group>
</>
);
}
if (editMode) {
return (
<>
<Button type="primary" onClick={onClose}>
{i18n.t('close')}
</Button>
</>
);
}
return (
<>
<Button onClick={onClose}>{i18n.t('Cancel')}</Button>
<Button
className="ml-3"
type="primary"
ghost
onClick={() => {
onOk(false);
}}
>
{i18n.t('dop:Save and Add')}
</Button>
<Button
className="ml-3"
type="primary"
onClick={() => {
onOk(true);
}}
>
{i18n.t('Save')}
</Button>
</>
);
}
Example #25
Source File: schema.ts From nebula-studio with Apache License 2.0 | 5 votes |
addEdgesName = async (payload: any) => {
const { edgeType, edgeFields } = payload;
const index = findIndex(this.edgesFields, edgeType);
this.edgesFields[!~index ? this.edgesFields.length : index] = { [edgeType]: edgeFields };
}
Example #26
Source File: utils.ts From gant-design with MIT License | 5 votes |
mapColumns = <T>(
columns: Columns<T>[],
getRowNodeId: any,
defaultSelection: boolean,
defaultSelectionCol: ColDef,
rowSelection,
serialNumber,
size: Size,
): {
columnDefs: Col[];
validateFields: Rules;
requireds: string[];
} => {
// 移除所有已添加事件
function getColumnDefs(columns: Columns<T>[]) {
let validateFields: Rules = {};
let requireds = [];
const columnDefs = columns.map(
(
{
title: headerName,
fieldName: field,
children,
render,
editConfig,
fixed,
headerClass,
cellClassRules,
cellClass,
cellRendererParams,
...item
},
index,
) => {
const ColEditable = typeof editConfig !== 'undefined';
const colDef = {
headerName,
field,
cellRendererParams: {
render,
...cellRendererParams,
},
headerTooltip: headerName,
cellClass: cellClass,
cellClassRules: {
'gant-grid-cell': () => true,
'gant-grid-cell-modify': params => {
const {
data: { _rowType, ...itemData } = {} as any,
colDef: { field },
} = params;
const value = get(itemData, field);
const _rowData = get(itemData, `_rowData`, itemData);
const originValue = get(_rowData, field);
return _rowType === DataActions.modify && !isEqualObj(value, originValue);
},
'gant-grid-cell-edit': (params: any) => {
const {
context: { globalEditable },
data,
} = params;
const editable = get(editConfig, 'editable', false);
if (typeof editable == 'boolean') return editable;
return editable(data, params);
},
...cellClassRules,
},
cellRenderer: render ? 'gantRenderCol' : undefined,
headerClass,
...item,
} as Col;
if (!itemisgroup(colDef, children)) {
// 当前列允许编辑
if (ColEditable) {
const { props, changeFormatter, component, rules, signable, ...params } = editConfig;
let required = false;
const validateField = field.replace(/\./g, '-');
if (Array.isArray(rules)) {
const fieldsRules: RuleItem[] = rules.map(item => {
const hasRequired = Reflect.has(item, 'required');
required = hasRequired ? Reflect.get(item, 'required') : required;
return { ...item };
});
validateFields[validateField] = fieldsRules;
} else {
if (!isEmpty(rules)) {
validateFields[validateField] = { ...rules };
required = get(rules, 'required', false);
}
}
if (required) {
requireds.push(field);
}
colDef.cellEditorParams = {
props,
changeFormatter,
rowkey: getRowNodeId,
required,
valueGetter: item.valueGetter,
...params,
};
colDef.cellEditorFramework = EditorCol(component);
colDef.editable = ColEditableFn(editConfig.editable);
switch (typeof headerClass) {
case 'string':
colDef.headerClass = classnames(
headerClass,
required ? 'gant-header-cell-required' : 'gant-header-cell-edit',
);
break;
case 'object':
if (Array.isArray(headerClass)) {
colDef.headerClass = [
...headerClass,
required ? 'gant-header-cell-required' : 'gant-header-cell-edit',
];
}
break;
case 'function':
colDef.headerClass = (params: any) => {
const _class = headerClass(params);
if (typeof _class === 'string')
return classnames(
_class,
required ? 'gant-header-cell-required' : 'gant-header-cell-edit',
);
return [
..._class,
required ? 'gant-header-cell-required' : 'gant-header-cell-edit',
];
};
default:
colDef.headerClass = classnames(
required ? 'gant-header-cell-required' : 'gant-header-cell-edit',
);
}
if (typeof signable === 'boolean' || typeof signable === 'function')
colDef.cellClassRules = {
'gant-cell-validate-sign': params => {
const show = typeof signable === 'boolean' ? signable : signable(params);
if (!show) return false;
const {
data: { _rowError, ...itemData } = {} as any,
colDef: { field },
} = params;
return typeof get(_rowError, field, null) === 'string';
},
...colDef.cellClassRules,
};
}
if (fixed) colDef.pinned = fixed;
} else if (itemisgroup(colDef, children)) {
if (children && children.length) {
const groupChildren = getColumnDefs(children);
colDef.children = groupChildren.columnDefs;
colDef.marryChildren = true;
validateFields = { ...validateFields, ...groupChildren.validateFields };
}
}
return colDef;
},
);
return { columnDefs, validateFields, requireds };
}
let { columnDefs, validateFields, requireds } = getColumnDefs(columns);
columnDefs = serialNumber
? typeof serialNumber === 'boolean'
? [serialNumberCol, ...columnDefs]
: [
{
...serialNumberCol,
...serialNumber,
cellClassRules: { ...serialNumberCol.cellClassRules, ...serialNumber.cellClassRules },
},
...columnDefs,
]
: columnDefs;
columnDefs = defaultSelection
? [
{
...defaultCheckboxColSelectionCol,
width: sizeNumber[size],
headerCheckboxSelection: rowSelection === 'multiple',
...defaultSelectionCol,
cellClassRules: {
'gant-grid-cell-checkbox-indeterminate': params => {
const { node, context } = params;
const { groupSelectsChildren, selectedRows, getRowNodeId } = context;
const index = findIndex(selectedRows, item => getRowNodeId(item) === node.id);
if (!groupSelectsChildren) return false;
if (!node.isSelected() && index < 0) return false;
const { allLeafChildren = [] } = node;
for (let itemNode of allLeafChildren) {
if (!itemNode.isSelected()) return true;
}
return false;
},
...get(defaultSelectionCol, 'cellClassRules', {}),
},
},
...columnDefs,
]
: columnDefs;
return { columnDefs, validateFields, requireds };
}
Example #27
Source File: DataDoc.tsx From querybook with Apache License 2.0 | 5 votes |
@bind
public autoFocusCell(props: Partial<IProps>, nextProps: Partial<IProps>) {
const { dataDoc: oldDataDoc } = props;
const { dataDoc } = nextProps;
if (!('cells' in (oldDataDoc || {})) && dataDoc && 'cells' in dataDoc) {
const queryParam = getQueryString();
if (queryParam && 'cellId' in queryParam) {
const cellId = Number(queryParam['cellId']);
if (dataDoc.dataDocCells) {
const cellIndex = findIndex(
dataDoc.dataDocCells,
(cell) => cell.id === cellId
);
if (cellIndex >= 0) {
// This is to quickly snap to the element, and then in case
// if the cell above/below pushes the element out of view we
// try to scroll it back
scrollToCell(
dataDoc.dataDocCells[cellIndex].id,
0
).then(() =>
// Setting the highlight cell index to turn on the
// blue aura animation
this.setState(
{
highlightCellIndex: cellIndex,
},
() => {
scrollToCell(
dataDoc.dataDocCells[cellIndex].id,
200,
5
);
// The highlight animation should last 5 seconds
// Remove the index so subsequent render does not
// show this
setTimeout(
() =>
this.setState({
highlightCellIndex: null,
}),
5000
);
}
)
);
}
}
}
}
}
Example #28
Source File: query-params-config.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
QueryParamsConfig = (props: IProps) => {
const [{ paramsData }, updater] = useUpdate({
paramsData: {},
});
const { onChange, formData, paramIn, isEditMode, resourceKey } = props;
const { updateFormErrorNum } = apiDesignStore;
React.useEffect(() => {
const _paramList = formData.parameters || {};
const properties = {};
forEach(_paramList, (item) => {
if (item?.in === paramIn) {
properties[item[API_FORM_KEY] || item.name] = item?.schema || item;
}
});
const tempObj = {
type: 'object',
properties,
};
tempObj[API_FORM_KEY] = 'parameters';
updater.paramsData(tempObj);
}, [updater, formData, paramIn, resourceKey]);
const updateParamList = React.useCallback(
(formKey: string, _formData: any, extraProps?: Obj) => {
const { typeQuotePath, quoteTypeName } = extraProps || {};
const _extraProps = { quoteTypeName, typeQuotePath: [] } as IExtraProps;
if (formKey) {
const tempDetail = produce(formData, (draft) => {
const newParameters = map(values(_formData?.properties), (item) => {
const tempItem = {
in: paramIn,
name: item[API_FORM_KEY],
required: item[API_PROPERTY_REQUIRED],
schema: item,
};
tempItem[API_FORM_KEY] = item[API_FORM_KEY];
return tempItem;
});
const parametersWithoutChange = filter(formData?.parameters, (item) => item?.in !== paramIn) || [];
const allParameters = [...newParameters, ...parametersWithoutChange];
if (typeQuotePath && quoteTypeName) {
const targetParamName = typeQuotePath.split('.')[2];
const targetIndex = findIndex(allParameters, { [API_FORM_KEY]: targetParamName });
const newPath = ['parameters', targetIndex];
_extraProps.typeQuotePath = newPath;
}
set(draft, 'parameters', allParameters);
});
onChange(paramIn, tempDetail, _extraProps);
}
},
[formData, onChange, paramIn],
);
return (
<div className="basic-params-config">
{!isEmpty(paramsData) && (
<PropertyItemForm
onFormErrorNumChange={updateFormErrorNum}
formData={paramsData}
detailVisible
formType="Parameters"
onChange={updateParamList}
isEditMode={isEditMode}
/>
)}
{!isEditMode && isEmpty(paramsData?.properties) && <EmptyHolder relative />}
</div>
);
}
Example #29
Source File: tabs.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
Tabs = (props: IProps) => {
const { defaultActiveKey, activeKey: actKey, onChange, tabs } = props;
const [activeKey, setActiveKey] = React.useState(defaultActiveKey || get(tabs, '[0].key'));
React.useEffect(() => {
actKey && setActiveKey(actKey);
}, [actKey]);
const activeIndex = findIndex(tabs, { key: activeKey });
React.useEffect(() => {
onChange && onChange(activeKey);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeKey]);
return (
<div className="dice-form-tabs">
<div className="tabs-menu">
{map(tabs, ({ key, name }) => {
return (
<div
className={`tabs-menu-item ${activeKey === key ? 'is-active' : ''}`}
key={key}
onClick={() => setActiveKey(key)}
>
{name}
</div>
);
})}
</div>
<div
className="tabs-content"
style={{
marginLeft: `${-activeIndex * 100}%`,
}}
>
{map(tabs, ({ key, content }, index: number) => {
const pos = index > activeIndex ? 'right' : index === activeIndex ? 'center' : 'left';
return (
<div className={`tabs-content-item ${pos}`} key={key}>
{content}
</div>
);
})}
</div>
</div>
);
}