lodash#flatten TypeScript Examples
The following examples show how to use
lodash#flatten.
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: analysis-utils.ts From prism-frontend with MIT License | 7 votes |
function mergeFeaturesByProperty(
baselineFeatures: Feature[],
aggregateData: Array<object>,
id: string,
): Feature[] {
const features = baselineFeatures.map(feature1 => {
const aggregateProperties = aggregateData.filter(
item => get(item, id) === get(feature1, ['properties', id]) && item,
);
const filteredProperties = aggregateProperties.map(filteredProperty => {
// We use geometry from response. If not, use whole admin boundary.
const filteredGeometry = get(filteredProperty, 'geometry');
const propertyItems = filteredGeometry
? omit(filteredProperty, 'geometry')
: filteredProperty;
const properties = {
...get(feature1, 'properties'),
...propertyItems,
impactValue: get(feature1, 'properties.data'),
};
const feature = filteredGeometry
? { ...feature1, geometry: filteredGeometry, properties }
: { ...feature1, properties };
return feature;
});
return filteredProperties;
});
return flatten(features);
}
Example #2
Source File: util.ts From S2 with MIT License | 7 votes |
generateSwitchResult = (state: SwitcherState): SwitcherResult => {
const generateFieldResult = (items: SwitcherItem[]): SwitcherResultItem => {
const flattenValues = (list: SwitcherItem[]) =>
flatten(
map(list, ({ children, ...rest }) => {
return [{ ...rest }, ...flattenValues(children)];
}),
);
const allItems = flattenValues(items);
// get all hidden values
const hideItems = filter(
allItems,
(item: SwitcherItem) => item.checked === false,
);
return {
items: allItems,
hideItems,
};
};
return {
[FieldType.Rows]: generateFieldResult(state[FieldType.Rows]),
[FieldType.Cols]: generateFieldResult(state[FieldType.Cols]),
[FieldType.Values]: generateFieldResult(state[FieldType.Values]),
};
}
Example #3
Source File: RunDetails.tsx From kfp-tekton-backend with Apache License 2.0 | 6 votes |
private async _loadAllOutputs(): Promise<void> {
const workflow = this.state.workflow;
if (!workflow) {
return;
}
const outputPathsList = WorkflowParser.loadAllOutputPathsWithStepNames(workflow);
const configLists = await Promise.all(
outputPathsList.map(({ stepName, path }) =>
OutputArtifactLoader.load(path, workflow?.metadata?.namespace).then(configs =>
configs.map(config => ({ config, stepName })),
),
),
);
const allArtifactConfigs = flatten(configLists);
this.setStateSafe({ allArtifactConfigs });
}
Example #4
Source File: flattenTreeDataListAndCalcRowSpan.ts From next-basics with GNU General Public License v3.0 | 6 votes |
/**
* 将树形数据列表按照 `options.flattenConfigs` 进行展平,并生成相应的行合并数据
* @param treeDataList 树形数据列表
* @param options 函数选项
* @param depth 当前展平的深度,用于确定 `options.flattenConfigs` 中的当前层级的展平配置
* @returns 展平后的列表,除了按照 `options.flattenConfigs` 进行展平外,还会生成相应层级以 `options.flattenConfigs[].parentInChildKey + "RowSpan"` 为 key 的行合并数据
*/
export function flattenTreeDataListAndCalcRowSpan(
treeDataList: Record<string, unknown>[],
options: FlattenTreeDataListAndCalcRowSpanOptions,
depth = 0
): Record<string, unknown>[] {
const { flattenConfigs, omitChildrenInParent } = options;
const flattenConfig = flattenConfigs[depth];
const { childrenKey, parentInChildKey } = flattenConfig;
return flatten(
treeDataList.map((treeData) => {
let children = treeData[childrenKey] as Record<string, unknown>[];
const parent = omitChildrenInParent
? omit(treeData, [childrenKey])
: treeData;
if (depth < flattenConfigs.length - 2) {
children = flattenTreeDataListAndCalcRowSpan(
children,
options,
depth + 1
);
}
return children.map((child, index) => ({
...child,
[parentInChildKey]: parent,
[`${parentInChildKey}RowSpan`]: index === 0 ? children.length : 0,
}));
})
);
}
Example #5
Source File: search.repository.ts From linkedin-private-api with MIT License | 6 votes |
private async fetchPeople({
skip = 0,
limit = 10,
filters = {},
keywords,
}: {
skip?: number;
limit?: number;
filters?: PeopleSearchFilters;
keywords?: string;
} = {}): Promise<PeopleSearchHit[]> {
const response = await this.client.request.search.searchBlended({
keywords,
skip,
limit,
filters: { ...filters, resultType: LinkedInSearchType.PEOPLE },
});
const profiles = keyBy(getProfilesFromResponse<GetBlendedSearchResponse>(response), 'entityUrn');
const searchHits = flatten(
response.data.elements.filter(e => e.type === SearchResultType.SEARCH_HITS && e.elements).map(e => e.elements!),
);
return searchHits.map(searchHit => ({
...searchHit,
profile: profiles[searchHit.targetUrn],
}));
}
Example #6
Source File: PluginHost.ts From language-tools with MIT License | 6 votes |
async getDiagnostics(textDocument: TextDocumentIdentifier): Promise<Diagnostic[]> {
const document = this.getDocument(textDocument.uri);
if (
(document.getFilePath()?.includes('/node_modules/') ||
document.getFilePath()?.includes('\\node_modules\\')) &&
// Sapper convention: Put stuff inside node_modules below src
!(
document.getFilePath()?.includes('/src/node_modules/') ||
document.getFilePath()?.includes('\\src\\node_modules\\')
)
) {
// Don't return diagnostics for files inside node_modules. These are considered read-only (cannot be changed)
// and in case of svelte-check they would pollute/skew the output
return [];
}
return flatten(
await this.execute<Diagnostic[]>(
'getDiagnostics',
[document],
ExecuteMode.Collect,
'high'
)
);
}
Example #7
Source File: unionType.ts From genql with MIT License | 6 votes |
unionType = (type: GraphQLUnionType, _: RenderContext) => {
const types = type.getTypes()
const typeObj: FieldMap<string> = types.reduce<FieldMap<string>>((r, t) => {
r[`on_${t.name}`] = { type: t.name }
return r
}, {})
const commonInterfaces = uniq(flatten(types.map((x) => x.getInterfaces())))
commonInterfaces.forEach((t) => {
typeObj[`on_${t.name}`] = { type: t.name }
})
typeObj.__typename = { type: 'String' }
return typeObj
}
Example #8
Source File: wsrun-wrapper.ts From magic-js with MIT License | 6 votes |
/**
* Wraps `wsrun` with a prompt for selecting which monorepo package to use.
*/
async function main() {
const input = process.argv.slice(2);
let PKG: string[] = ['*'];
if (input[0] === '--all') {
input.shift();
} else {
PKG = [await promptForPackage()];
}
if (PKG.length === 1 && PKG[0].includes(',')) {
PKG = PKG[0].split(',');
}
const args = flatten([
'--bin',
`${process.env.INIT_CWD}/scripts/bin/wsrun/bin.ts`,
...PKG.filter((p) => p !== '*').map((p) => p && ['-p', p]),
...input,
]).filter(Boolean);
await execa('wsrun', args as any, {
stdio: 'inherit',
env: {
PKG: PKG.join(','),
NODE_OPTIONS: '--max_old_space_size=4096',
},
});
}
Example #9
Source File: PluginHost.ts From language-tools with MIT License | 6 votes |
async formatDocument(
textDocument: TextDocumentIdentifier,
options: FormattingOptions
): Promise<TextEdit[]> {
const document = this.getDocument(textDocument.uri);
return flatten(
await this.execute<TextEdit[]>(
'formatDocument',
[document, options],
ExecuteMode.Collect,
'high'
)
);
}
Example #10
Source File: CompareUtils.ts From kfp-tekton-backend with Apache License 2.0 | 6 votes |
/**
* Given a list of run and worklow objects, returns CompareTableProps containing parameter
* names on y axis, run names on x axis, and parameter values in rows.
* runs and workflowObjects are required to be in the same order, so workflowObject[i]
* is run[i]'s parsed workflow object
*/
public static getParamsCompareProps(
runs: ApiRunDetail[],
workflowObjects: Workflow[],
): CompareTableProps {
if (runs.length !== workflowObjects.length) {
// Should never happen
logger.error('Numbers of passed in runs and workflows do not match');
}
const yLabels = chain(flatten(workflowObjects.map(w => WorkflowParser.getParameters(w))))
.countBy(p => p.name) // count by parameter name
.map((k, v) => ({ name: v, count: k })) // convert to counter objects
.orderBy('count', 'desc') // sort on count field, descending
.map(o => o.name)
.value();
const rows = yLabels.map(name => {
return workflowObjects.map(w => {
const params = WorkflowParser.getParameters(w);
const param = params.find(p => p.name === name);
return param ? param.value || '' : '';
});
});
return {
rows,
xLabels: runs.map(r => r.run!.name!),
yLabels,
};
}
Example #11
Source File: s3-sync.ts From lift with MIT License | 6 votes |
async function listFilesRecursively(directory: string): Promise<string[]> {
const items = await readdir(directory);
const files = await Promise.all(
items.map(async (fileName) => {
const fullPath = path.posix.join(directory, fileName);
const fileStat = await stat(fullPath);
if (fileStat.isFile()) {
return [fileName];
} else if (fileStat.isDirectory()) {
const subFiles = await listFilesRecursively(fullPath);
return subFiles.map((subFileName) => path.posix.join(fileName, subFileName));
}
return [];
})
);
return flatten(files);
}
Example #12
Source File: azure-translator.ts From attranslate with MIT License | 6 votes |
async translateStrings(args: TServiceArgs): Promise<TResult[]> {
const apiKey = args.serviceConfig;
if (!apiKey) {
logFatal("Set '--serviceConfig' to an Azure API key");
}
const batches = chunk(args.strings, 50);
const results = await Promise.all(
batches.map((batch) => this.translateBatch(batch, args, apiKey))
);
return flatten(results);
}
Example #13
Source File: plugin.ts From lift with MIT License | 6 votes |
private appendPermissions(): void {
// Automatic permissions can be disabled via a `lift.automaticPermissions` flag in serverless.yml
const liftConfiguration = get(this.serverless.configurationInput, "lift", {}) as LiftConfig;
if (liftConfiguration.automaticPermissions === false) {
return;
}
const constructs = this.getConstructs();
const statements = flatten(
Object.entries(constructs).map(([, construct]) => {
return (construct.permissions ? construct.permissions() : []) as unknown as AwsIamPolicyStatements;
})
);
if (statements.length === 0) {
return;
}
const role = this.serverless.service.provider.iam?.role;
if (typeof role === "object" && "statements" in role) {
role.statements?.push(...statements);
return;
}
this.serverless.service.provider.iamRoleStatements = this.serverless.service.provider.iamRoleStatements ?? [];
this.serverless.service.provider.iamRoleStatements.push(...statements);
}
Example #14
Source File: interface.ts From free-swagger with MIT License | 6 votes |
uniqInterfaceNameImports = (imports: string[]) =>
uniq(
flatten(
imports.map((item) =>
flatInterfaceName(item)
// 排除 ts 内置类型
.filter((item) => !Object.values(TYPE_MAP).includes(item))
// 排除一些特殊的泛型 Map<string,string>
.filter((item) => isWord.test(item))
// 如果是 Java 内建类型则转换成自定义泛型
.map((item) =>
buildInInterfaces[item] ? buildInInterfaces[item].formatName : item
)
)
)
)
Example #15
Source File: PluginHost.ts From language-tools with MIT License | 6 votes |
async getColorPresentations(
textDocument: TextDocumentIdentifier,
range: Range,
color: Color
): Promise<ColorPresentation[]> {
const document = this.getDocument(textDocument.uri);
return flatten(
await this.execute<ColorPresentation[]>(
'getColorPresentations',
[document, range, color],
ExecuteMode.Collect,
'high'
)
);
}
Example #16
Source File: updateBillReferences.ts From advocacy-maps with MIT License | 6 votes |
getCommitteeUpdates(): BillUpdates {
const billsInCommittee = flatten(
this.committees.map(c => c.content.DocumentsBeforeCommittee)
)
const billsOutOfCommittee = difference(this.billIds, billsInCommittee)
const updates: BillUpdates = new Map()
// Set the committee on bills listed in a committee
this.committees.forEach(c =>
c.content.DocumentsBeforeCommittee.forEach(billId => {
updates.set(billId, {
currentCommittee: {
id: c.id,
name: c.content.FullName,
houseChair: this.formatChair(c.content.HouseChairperson),
senateChair: this.formatChair(c.content.SenateChairperson)
}
})
})
)
// Clear the committee on bills not in committee
billsOutOfCommittee.forEach(id => {
updates.set(id, {
currentCommittee: FieldValue.delete()
})
})
return updates
}
Example #17
Source File: PluginHost.ts From language-tools with MIT License | 6 votes |
async getDocumentSymbols(
textDocument: TextDocumentIdentifier,
cancellationToken: CancellationToken
): Promise<SymbolInformation[]> {
const document = this.getDocument(textDocument.uri);
return flatten(
await this.execute<SymbolInformation[]>(
'getDocumentSymbols',
[document, cancellationToken],
ExecuteMode.Collect,
'low'
)
);
}
Example #18
Source File: utils.ts From aqualink-app with MIT License | 6 votes |
calculateAxisLimits = (
datasets: ChartProps["datasets"],
startDate: ChartProps["startDate"],
endDate: ChartProps["endDate"],
temperatureThreshold: ChartProps["temperatureThreshold"]
) => {
const timestampsToConsiderForXAxis = getDatasetsTimestamps(
datasets?.filter((dataset) => dataset.considerForXAxisLimits)
);
const accumulatedYAxisData = flatten(
map(datasets, ({ data }) =>
map(
filter(data, ({ value }) => !isNil(value)),
({ value }) => value
)
)
);
// x axis limits calculation
const datasetsXMin = minBy(
timestampsToConsiderForXAxis,
(timestamp) => new Date(timestamp)
);
const datasetsXMax = maxBy(
timestampsToConsiderForXAxis,
(timestamp) => new Date(timestamp)
);
const xAxisMin = startDate || datasetsXMin;
const xAxisMax = endDate || datasetsXMax;
// y axis limits calculation
const datasetsYMin = Math.min(...accumulatedYAxisData);
const datasetsYMax = Math.max(...accumulatedYAxisData);
const ySpacing = Math.ceil(
Y_SPACING_PERCENTAGE * (datasetsYMax - datasetsYMin)
); // Set ySpacing as a percentage of the data range
const yAxisMinTemp = datasetsYMin - ySpacing;
const yAxisMaxTemp = datasetsYMax + ySpacing;
const yAxisMin = Math.round(
temperatureThreshold
? Math.min(yAxisMinTemp, temperatureThreshold - ySpacing)
: yAxisMinTemp
);
const yAxisMax = Math.round(
temperatureThreshold
? Math.max(yAxisMaxTemp, temperatureThreshold + ySpacing)
: yAxisMaxTemp
);
return { xAxisMin, xAxisMax, yAxisMin, yAxisMax };
}
Example #19
Source File: PluginHost.ts From language-tools with MIT License | 6 votes |
async getDocumentColors(textDocument: TextDocumentIdentifier): Promise<ColorInformation[]> {
const document = this.getDocument(textDocument.uri);
return flatten(
await this.execute<ColorInformation[]>(
'getDocumentColors',
[document],
ExecuteMode.Collect,
'low'
)
);
}
Example #20
Source File: GoalInputContainer.tsx From calculate-my-odds with MIT License | 6 votes |
componentDidUpdate(prevProps: Props) {
if (this.props.tables !== prevProps.tables) {
const items = flatten(this.props.tables.map(x => x.items));
const newGoals = {...this.state.rootGoal};
this.uniqueItemNames = uniq(items.map(x => x.name));
this.uniqueItemNames.sort();
updateGoalFromProbabilityTables(newGoals, new Set(this.uniqueItemNames), this.props.nameChange);
this.setState({
rootGoal: newGoals
});
}
}
Example #21
Source File: PluginHost.ts From language-tools with MIT License | 6 votes |
async getCodeActions(
textDocument: TextDocumentIdentifier,
range: Range,
context: CodeActionContext,
cancellationToken: CancellationToken
): Promise<CodeAction[]> {
const document = this.getDocument(textDocument.uri);
return flatten(
await this.execute<CodeAction[]>(
'getCodeActions',
[document, range, context, cancellationToken],
ExecuteMode.Collect,
'high'
)
);
}
Example #22
Source File: mod-dependencies-state.ts From ow-mod-manager with MIT License | 6 votes |
requiredDependencyIdsState = selector({
key: 'RequiredDependencyIds',
get: ({ get }) =>
flatten(
Object.values(get(localModMap))
.filter((mod) => mod.isEnabled)
.map((mod) => mod.dependencies)
),
})
Example #23
Source File: api.ts From ovineherd with Apache License 2.0 | 5 votes |
getLayoutReqOpt = {
url: 'fakeAsideLayoutApi',
onFakeRequest: async (option) => {
const { designMode } = option.data
const isMounted = typeof designMode !== 'undefined'
const isSysAdmin = isMounted ? designMode : isSysAdminRoute()
const isStashLayout = stashLayoutCtrl('get')
const routeItems = await getAppRouteItems()
// 修改 布局 schema
const nextState = produce(layoutState, (d) => {
d.resetRoute = !isStashLayout
d.routeTabs.storage = isStashLayout
d.header.brand = getBrandSchema(isSysAdmin)
if (checkLimit('designApp')) {
d.header.items[0] = getModeBtnSchema(isSysAdmin)
}
const adminRoutes = getSysAdmRoutes()
let menuRoutes = routeStore[0]
// 更新路由信息
if (!isMounted || !isSysAdmin) {
menuRoutes = getAppRoutes(routeItems)
}
adminRoutes[0].limitOnly = !isSysAdmin
menuRoutes[0].limitOnly = isSysAdmin
routeStore = [menuRoutes, adminRoutes]
d.routes = flatten(routeStore)
d.rootRoute = isSysAdmin ? getLink('appSystem', 'page') : '/'
})
return nextState
},
}
Example #24
Source File: plugin.ts From lift with MIT License | 5 votes |
private getAllConstructClasses(): StaticConstructInterface[] {
const result = flatten(
LiftPlugin.getAllProviderClasses().map((providerClass) => providerClass.getAllConstructClasses())
);
return result;
}
Example #25
Source File: runRequest.ts From grafana-chinese with Apache License 2.0 | 5 votes |
/*
* This function should handle composing a PanelData from multiple responses
*/
export function processResponsePacket(packet: DataQueryResponse, state: RunningQueryState): RunningQueryState {
const request = state.panelData.request;
const packets: MapOfResponsePackets = {
...state.packets,
};
packets[packet.key || 'A'] = packet;
let loadingState = packet.state || LoadingState.Done;
let error: DataQueryError | undefined = undefined;
// Update the time range
const range = { ...request.range };
const timeRange = isString(range.raw.from)
? {
from: dateMath.parse(range.raw.from, false),
to: dateMath.parse(range.raw.to, true),
raw: range.raw,
}
: range;
const combinedData = flatten(
lodashMap(packets, (packet: DataQueryResponse) => {
if (packet.error) {
loadingState = LoadingState.Error;
error = packet.error;
}
return packet.data;
})
);
const panelData = {
state: loadingState,
series: combinedData,
error,
request,
timeRange,
};
return { packets, panelData };
}
Example #26
Source File: PluginHost.ts From language-tools with MIT License | 5 votes |
async getCompletions(
textDocument: TextDocumentIdentifier,
position: Position,
completionContext?: CompletionContext,
cancellationToken?: CancellationToken
): Promise<CompletionList> {
const document = this.getDocument(textDocument.uri);
const completions = await Promise.all(
this.plugins.map(async (plugin) => {
const result = await this.tryExecutePlugin(
plugin,
'getCompletions',
[document, position, completionContext, cancellationToken],
null
);
if (result) {
return { result: result as CompletionList, plugin: plugin.__name };
}
})
).then((completions) => completions.filter(isNotNullOrUndefined));
const html = completions.find((completion) => completion.plugin === 'html');
const ts = completions.find((completion) => completion.plugin === 'ts');
if (html && ts && getNodeIfIsInHTMLStartTag(document.html, document.offsetAt(position))) {
// Completion in a component or html start tag and both html and ts
// suggest something -> filter out all duplicates from TS completions
const htmlCompletions = new Set(html.result.items.map((item) => item.label));
ts.result.items = ts.result.items.filter((item) => {
const label = item.label;
if (htmlCompletions.has(label)) {
return false;
}
if (label[0] === '"' && label[label.length - 1] === '"') {
// this will result in a wrong completion regardless, remove the quotes
item.label = item.label.slice(1, -1);
if (htmlCompletions.has(item.label)) {
// "aria-label" -> aria-label -> exists in html completions
return false;
}
}
if (label.startsWith('on')) {
if (htmlCompletions.has('on:' + label.slice(2))) {
// onclick -> on:click -> exists in html completions
return false;
}
}
// adjust sort text so it does appear after html completions
item.sortText = 'Z' + (item.sortText || '');
return true;
});
}
let flattenedCompletions = flatten(
completions.map((completion) => completion.result.items)
);
const isIncomplete = completions.reduce(
(incomplete, completion) => incomplete || completion.result.isIncomplete,
false as boolean
);
// If the result is incomplete, we need to filter the results ourselves
// to throw out non-matching results. VSCode does filter client-side,
// but other IDEs might not.
if (isIncomplete && this.pluginHostConfig.filterIncompleteCompletions) {
const offset = document.offsetAt(position);
// Assumption for performance reasons:
// Noone types import names longer than 20 characters and still expects perfect autocompletion.
const text = document.getText().substring(Math.max(0, offset - 20), offset);
const start = regexLastIndexOf(text, /[\W\s]/g) + 1;
const filterValue = text.substring(start).toLowerCase();
flattenedCompletions = flattenedCompletions.filter((comp) =>
comp.label.toLowerCase().includes(filterValue)
);
}
return CompletionList.create(flattenedCompletions, isIncomplete);
}
Example #27
Source File: format-lines.ts From openzeppelin-transpiler with MIT License | 5 votes |
export function formatLines(indent: number, lines: Line[]): string {
function indentEach(indent: number, lines: Line[]): Line[] {
return lines.map(line =>
Array.isArray(line) ? indentEach(indent + 1, line) : line && ' '.repeat(indent) + line,
);
}
return flatten(indentEach(indent, lines)).join('\n') + '\n';
}
Example #28
Source File: index.tsx From next-basics with GNU General Public License v3.0 | 5 votes |
// istanbul ignore next
private _handleSelectAll = (
selected: boolean,
selectedRows: Record<string, any>[],
changeRows: Record<string, any>[]
): void => {
this._selected = selected;
this._isInSelect = true;
const rowKey =
this.rowKey ?? this._fields.rowKey ?? this.configProps?.rowKey;
if (this.selectAllChildren) {
const allParentKeys = map(this._dataSource, rowKey);
const changedParentRows = changeRows.filter((v) =>
allParentKeys.includes(v[rowKey])
);
const toChangedChildrenKeys = flatten(
map(changedParentRows, (r) =>
map(this._getSelectedRowsWithChildren(r), (cr) => cr[rowKey])
)
);
const allChildren = flatten(
map(changedParentRows, (r) =>
map(this._getSelectedRowsWithChildren(r), (cr) => cr)
)
);
this._allChildren = allChildren;
if (!this.autoSelectParentWhenAllChildrenSelected) {
if (selected) {
this._disabledChildrenKeys = uniq(
this._disabledChildrenKeys.concat(toChangedChildrenKeys)
);
} else {
// disabled children in changeRows should be removed
this._disabledChildrenKeys = this._disabledChildrenKeys.filter(
(v) => !toChangedChildrenKeys.includes(v)
);
}
}
}
if (this.storeCheckedByUrl && !!rowKey) {
this._updateUrlChecked(map(changeRows, rowKey), selected);
}
};
Example #29
Source File: cluster-form.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
AddClusterModal = (props: IProps) => {
const { initData, toggleModal, visible, onSubmit, clusterList, clusterType } = props;
const handleSubmit = (values: any) => {
const { scheduler, opsConfig, credential } = values;
const postData = { ...values };
if (every(opsConfig, (item) => isEmpty(item))) {
postData.opsConfig = null;
}
const credentialContent = get(credential, 'content');
const credentialAddress = get(credential, 'address');
const cpuSubscribeRatio = get(scheduler, 'cpuSubscribeRatio');
cpuSubscribeRatio && (postData.scheduler.cpuSubscribeRatio = `${cpuSubscribeRatio}`);
credentialContent && (credential.content = `${credentialContent.trim()}`);
credentialAddress && (credential.address = `${credentialAddress.trim()}`);
onSubmit?.({ ...postData, type: clusterType });
toggleModal();
};
const formData: FormData = (initData && { ...initData }) || ({} as FormData);
if (TYPE_K8S_AND_EDAS.includes(clusterType) && initData) {
const { manageConfig } = initData as Obj;
const { credentialSource, address } = manageConfig || {};
formData.credentialType = credentialSource;
formData.credential = { ...formData.credential, address };
}
return (
<FormModal
width={800}
name={i18n.t('cmp:{type} cluster', {
type: get(find(flatten(clusterTypeMap), { type: clusterType }), 'name', ''),
})}
title={
clusterType === 'k8s'
? formData
? i18n.t('dop:Edit cluster configuration')
: i18n.t('cmp:import an existing Erda {type} cluster', { type: 'Kubernetes' })
: undefined
}
visible={visible}
onOk={handleSubmit}
onCancel={() => toggleModal(true)}
PureForm={ClusterAddForm}
formData={formData}
clusterList={clusterList}
clusterType={clusterType}
modalProps={{
destroyOnClose: true,
maskClosable: false,
}}
/>
);
}