tachybase_todo/packages/plugins/graph-collection-manager/src/client/utils.tsx

549 lines
15 KiB
TypeScript
Raw Normal View History

refactor(client)!: application, router and plugin (#2068) BREAKING CHANGE: * refactor: update umi version 3.x to version 4.x * refactor: update react-router-dom version to 6.x * refactor(react-router-dom): change Layout Component `props.children` to `<Outlet />` * refactor(react-router-dom): change <Route /> props and <RouteSwitch /> correct * refactor(react-router-dom): replace `<Redirect />` to `<Navigate replace />` * refactor(react-router-dom): replace `useHistory` to `useNavigate` * refactor(react-router-dom): replace `useRouteMatch` to `useParams` * refactor(react-router-dom & dumi): fix <RouteSwitch /> & umi document bug * refactor(react-router-dom): `useRoutes` Optimize `<RouteSwitch />` code * refactor(react-router-dom): update `Route` types and docs * refactor(react-router-dom): optimize RouteSwitch code * refactor(react-router-dom): `useLocation` no generics type * refactor(react-router-dom): add `less v3.9.0` to `resolutions` to solve the error of `gulp-less` * refactor(react-router-dom): fix `<RouteSwitch />` `props.routes` as an array is not handled * chore: upgrade `dumi` and refactor docs * fix: completed code review, add `targets` to solve browser compatibility & removed `chainWebpack` * refactor(dumi): upgraded dumi under `packages/core/client` * refactor(dumi): delete `packages/core/dumi-theme-nocobase` * refactor(dumi): degrade `react` & replace `dumi-theme-antd` to `dumi-theme-nocobase` * refactor(dumi): solve conflicts between multiple dumi applications * fix: login page error in react 17 * refactor(dumi): remove less resolutions * refactor(dumi): umi add `msfu: true` config * fix: merge bug * fix: self code review * fix: code reivew and test bug * refactor: upgrade react to 18 * refactor: degrade react types to 17 * chore: fix ci error * fix: support routerBase & fix workflow page params * fix(doc): menu externel link * fix: build error * fix: delete * fix: vitest error * fix: react-router new code replace * fix: vitest markdown error * fix: title is none when refresh * fix: merge error * fix: sidebar width is wrong * fix: useProps error * fix: side-menu-width * fix: menu selectId is wrong & useProps is string * fix: menu selected first default & side menu hide when change * fix: test error & v0.10 change log * fix: new compnent doc modify * fix: set umi `fastRefresh=false` * refactor: application v2 * fix: improve code * fix: bug * fix: page = 0 error * fix: workflow navigate error * feat: plugin manager * fix: afterAdd * feat: complete basic functional refactor * fix: performance Application * feat: support client and server build * refactor: nocobase build-in plugin and providers * fix: server can't start * refactor: all plugins package `Prodiver` change to `Plugin` * feat: nested router and change mobile client * feat: delete application-v1 and router-switch * feat: improve routes * fix: change mobile not nested * feat: delete RouteSwitchContext and change buildin Provider to Plugin * feat: delete RouteSwitchContext plugins * fix: refactor SchemaComponentOptions * feat: improve SchemaComponentOptions * fix: add useAdminSchemaUid * fix: merge master error * fix: vitest error * fix: bug * feat: bugs * fix: improve code * fix: restore code * feat: vitest * fix: bugs * fix: bugs * docs: update doc * feat: improve code * feat: add docs and imporve code * fix: bugs * feat: add tests * fix: remove deps * fix: muti app router error * fix: router error * fix: workflow error * fix: cli error * feat: change NoCobase -> Nocobase * fix: code review * fix: type error * fix: cli error and plugin demo * feat: update doc theme * fix: build error * fix: mobile router * fix: code rewview * fix: bug * fix: test bug * fix: bug * refactor: add the "client" directory to all plugins * refactor: modify samples client and plugin template * fix: merge error * fix: add files in package.json * refactor: add README to files in package.json * fix: adjust plugins depencies * refactor: completing plugins' devDependencies and dependencies * fix: bug * refactor: remove @emotion/css * refactor: jsonwebtoken deps * refactor: remove sequelize * refactor: dayjs and moment deps * fix: bugs * fix: bug * fix: cycle detect * fix: merge bug * feat: new plugin bug * fix: lang bug * fix: dynamic import bug * refactor: plugins and example add father config * feat: improve code * fix: add AppSpin and AppError components * Revert "refactor: plugins and example add father config" This reverts commit 483315bca5524e4b8cbbb20cbad77986f081089d. # Conflicts: # packages/plugins/auth/package.json # packages/plugins/multi-app-manager/package.json # packages/samples/command/package.json # packages/samples/custom-collection-template/package.json # packages/samples/ratelimit/package.json # packages/samples/shop-actions/package.json # packages/samples/shop-events/package.json # packages/samples/shop-modeling/package.json * feat: update doc --------- Co-authored-by: chenos <chenlinxh@gmail.com>
2023-07-07 14:35:22 +08:00
import { lodash } from '@nocobase/utils/client';
import { useTranslation } from 'react-i18next';
refactor(client)!: application, router and plugin (#2068) BREAKING CHANGE: * refactor: update umi version 3.x to version 4.x * refactor: update react-router-dom version to 6.x * refactor(react-router-dom): change Layout Component `props.children` to `<Outlet />` * refactor(react-router-dom): change <Route /> props and <RouteSwitch /> correct * refactor(react-router-dom): replace `<Redirect />` to `<Navigate replace />` * refactor(react-router-dom): replace `useHistory` to `useNavigate` * refactor(react-router-dom): replace `useRouteMatch` to `useParams` * refactor(react-router-dom & dumi): fix <RouteSwitch /> & umi document bug * refactor(react-router-dom): `useRoutes` Optimize `<RouteSwitch />` code * refactor(react-router-dom): update `Route` types and docs * refactor(react-router-dom): optimize RouteSwitch code * refactor(react-router-dom): `useLocation` no generics type * refactor(react-router-dom): add `less v3.9.0` to `resolutions` to solve the error of `gulp-less` * refactor(react-router-dom): fix `<RouteSwitch />` `props.routes` as an array is not handled * chore: upgrade `dumi` and refactor docs * fix: completed code review, add `targets` to solve browser compatibility & removed `chainWebpack` * refactor(dumi): upgraded dumi under `packages/core/client` * refactor(dumi): delete `packages/core/dumi-theme-nocobase` * refactor(dumi): degrade `react` & replace `dumi-theme-antd` to `dumi-theme-nocobase` * refactor(dumi): solve conflicts between multiple dumi applications * fix: login page error in react 17 * refactor(dumi): remove less resolutions * refactor(dumi): umi add `msfu: true` config * fix: merge bug * fix: self code review * fix: code reivew and test bug * refactor: upgrade react to 18 * refactor: degrade react types to 17 * chore: fix ci error * fix: support routerBase & fix workflow page params * fix(doc): menu externel link * fix: build error * fix: delete * fix: vitest error * fix: react-router new code replace * fix: vitest markdown error * fix: title is none when refresh * fix: merge error * fix: sidebar width is wrong * fix: useProps error * fix: side-menu-width * fix: menu selectId is wrong & useProps is string * fix: menu selected first default & side menu hide when change * fix: test error & v0.10 change log * fix: new compnent doc modify * fix: set umi `fastRefresh=false` * refactor: application v2 * fix: improve code * fix: bug * fix: page = 0 error * fix: workflow navigate error * feat: plugin manager * fix: afterAdd * feat: complete basic functional refactor * fix: performance Application * feat: support client and server build * refactor: nocobase build-in plugin and providers * fix: server can't start * refactor: all plugins package `Prodiver` change to `Plugin` * feat: nested router and change mobile client * feat: delete application-v1 and router-switch * feat: improve routes * fix: change mobile not nested * feat: delete RouteSwitchContext and change buildin Provider to Plugin * feat: delete RouteSwitchContext plugins * fix: refactor SchemaComponentOptions * feat: improve SchemaComponentOptions * fix: add useAdminSchemaUid * fix: merge master error * fix: vitest error * fix: bug * feat: bugs * fix: improve code * fix: restore code * feat: vitest * fix: bugs * fix: bugs * docs: update doc * feat: improve code * feat: add docs and imporve code * fix: bugs * feat: add tests * fix: remove deps * fix: muti app router error * fix: router error * fix: workflow error * fix: cli error * feat: change NoCobase -> Nocobase * fix: code review * fix: type error * fix: cli error and plugin demo * feat: update doc theme * fix: build error * fix: mobile router * fix: code rewview * fix: bug * fix: test bug * fix: bug * refactor: add the "client" directory to all plugins * refactor: modify samples client and plugin template * fix: merge error * fix: add files in package.json * refactor: add README to files in package.json * fix: adjust plugins depencies * refactor: completing plugins' devDependencies and dependencies * fix: bug * refactor: remove @emotion/css * refactor: jsonwebtoken deps * refactor: remove sequelize * refactor: dayjs and moment deps * fix: bugs * fix: bug * fix: cycle detect * fix: merge bug * feat: new plugin bug * fix: lang bug * fix: dynamic import bug * refactor: plugins and example add father config * feat: improve code * fix: add AppSpin and AppError components * Revert "refactor: plugins and example add father config" This reverts commit 483315bca5524e4b8cbbb20cbad77986f081089d. # Conflicts: # packages/plugins/auth/package.json # packages/plugins/multi-app-manager/package.json # packages/samples/command/package.json # packages/samples/custom-collection-template/package.json # packages/samples/ratelimit/package.json # packages/samples/shop-actions/package.json # packages/samples/shop-events/package.json # packages/samples/shop-modeling/package.json * feat: update doc --------- Co-authored-by: chenos <chenlinxh@gmail.com>
2023-07-07 14:35:22 +08:00
const { groupBy, reduce, uniq, uniqBy } = lodash;
2023-01-11 11:58:47 +08:00
const shape = {
ER: 'er-rect',
EDGE: 'edge',
};
export const useGCMTranslation = () => {
return useTranslation('graph-collection-manager');
};
2023-01-11 11:58:47 +08:00
export const getInheritCollections = (collections, name) => {
const parents = [];
const getParents = (name) => {
const collection = collections?.find((collection) => collection.name === name);
if (collection) {
const { inherits } = collection;
if (inherits) {
for (let index = 0; index < inherits.length; index++) {
const collectionKey = inherits[index];
parents.push(collectionKey);
getParents(collectionKey);
}
}
}
return uniq(parents);
};
return getParents(name);
};
export const getChildrenCollections = (collections, name) => {
const childrens = [];
const getChildrens = (name) => {
const inheritCollections = collections.filter((v) => {
return v.inherits?.includes(name);
});
inheritCollections.forEach((v) => {
const collectionKey = v.name;
childrens.push(v);
return getChildrens(collectionKey);
});
return childrens;
};
return getChildrens(name);
};
export const formatData = (data) => {
const edgeData = [];
const targetTablekeys = [];
const tableData = data.map((item, index) => {
const ports = [];
const totalFields = [...item.fields];
const inheritCollections = getInheritCollections(data, item.name);
const inheritedFields = reduce(
inheritCollections,
(result, value) => {
const arr = result;
const parentFields = data
.find((k) => k.name === value)
?.fields.map((v) => {
return { ...v, sourceCollectionName: item.name };
});
return arr.concat(parentFields);
},
[],
);
uniqBy(totalFields.concat(inheritedFields), 'name').forEach((field) => {
field.uiSchema &&
ports.push({
id: field.key,
group: 'list',
...field,
});
['obo', 'oho', 'o2o', 'o2m', 'm2o', 'm2m', 'linkTo'].includes(field.interface) && edgeData.push(field);
});
targetTablekeys.push(item.name);
const portsData = formatPortData(ports);
return {
id: item.name,
shape: shape.ER,
name: item.name,
title: item.title,
width: 250,
// height: 40 * portsData.initPorts?.length||40,
ports: [...(portsData.initPorts || []), ...(portsData.morePorts || [])],
item: item,
};
});
const edges = formatEdgeData(edgeData, targetTablekeys, tableData);
const inheritEdges = formatInheritEdgeData(data);
return { nodesData: tableData, edgesData: edges, inheritEdges };
};
export const formatPortData = (ports) => {
const portsData = groupBy(ports, (v) => {
if (
v.isForeignKey ||
v.primaryKey ||
['obo', 'oho', 'o2o', 'o2m', 'm2o', 'm2m', 'linkTo', 'id'].includes(v.interface)
) {
return 'initPorts';
} else {
return 'morePorts';
}
});
return portsData;
};
export const formatInheritEdgeData = (collections) => {
const commonAttrs = {
attrs: {
line: {
strokeWidth: 1,
textAnchor: 'middle',
textVerticalAnchor: 'middle',
stroke: '#ddd',
sourceMarker: null,
// targetMarker: null,
},
},
router: {
name: 'smooth',
args: {
direction: 'H',
},
},
labels: [
{
markup: [
{
tagName: 'ellipse',
selector: 'labelBody',
style: {
cursor: 'pointer',
},
},
{
tagName: 'text',
selector: 'labelText',
style: {
cursor: 'pointer',
},
},
],
attrs: {
labelText: {
text: 'inherits',
fill: 'rgba(0, 0, 0, 0.3)',
textAnchor: 'middle',
textVerticalAnchor: 'middle',
},
labelBody: {
ref: 'labelText',
refWidth: '100%',
refHeight: '100%',
fill: '#f0f2f5',
},
},
position: {
distance: 0.5,
args: {
keepGradient: true,
ensureLegibility: true,
},
},
},
],
};
const inheritEdges = [];
collections.forEach((v) => {
const parentCollectonKeys = v.inherits || [];
if (parentCollectonKeys.length) {
parentCollectonKeys.forEach((k) => {
inheritEdges.push({
id: v.name + k,
source: {
cell: v.name,
connectionPoint: 'rect',
},
target: {
cell: k,
connectionPoint: 'rect',
},
connector: 'rounded',
connectionType: 'inherited',
...commonAttrs,
});
});
}
});
return inheritEdges;
};
const formatEdgeData = (data, targetTables, tableData) => {
const edges = [];
for (let i = 0; i < data.length; i++) {
if (targetTables.includes(data[i].target)) {
const targetTable = tableData.find((v) => v.name === data[i].target);
const sourceTable = tableData.find((v) => v.name === (data[i].sourceCollectionName || data[i].collectionName));
const commonAttrs = {
attrs: {
line: {
strokeWidth: 1,
textAnchor: 'middle',
textVerticalAnchor: 'middle',
stroke: '#ddd',
sourceMarker: null,
targetMarker: null,
},
},
router:
sourceTable.id === targetTable.id
? {
name: 'oneSide',
args: {
side: 'left',
},
}
: {
name: 'er',
args: {
direction: 'H',
},
},
labels: [
{
markup: [
{
tagName: 'ellipse',
selector: 'labelBody',
style: {
cursor: 'pointer',
},
},
{
tagName: 'text',
selector: 'labelText',
style: {
cursor: 'pointer',
},
},
],
attrs: {
labelText: {
text: getRelationship(data[i].interface)[0],
fill: 'rgba(0, 0, 0, 0.3)',
textAnchor: 'middle',
textVerticalAnchor: 'middle',
},
labelBody: {
ref: 'labelText',
refWidth: '100%',
refHeight: '100%',
stroke: '#ddd',
fill: '#f0f2f5',
strokeWidth: 1,
rx: 10,
ry: 10,
},
},
position: {
distance: 0.3,
args: {
keepGradient: true,
ensureLegibility: true,
},
},
},
{
markup: [
{
tagName: 'ellipse',
selector: 'labelBody',
style: {
cursor: 'pointer',
},
},
{
tagName: 'text',
selector: 'labelText',
style: {
cursor: 'pointer',
},
},
],
attrs: {
labelText: {
text: getRelationship(data[i].interface)[1],
fill: 'rgba(0, 0, 0, 0.3)',
textAnchor: 'middle',
textVerticalAnchor: 'middle',
},
labelBody: {
ref: 'labelText',
refWidth: '100%',
refHeight: '100%',
stroke: '#ddd',
fill: '#f0f2f5',
rx: 10,
ry: 10,
strokeWidth: 1,
},
},
position: {
distance: 0.7,
args: {
keepGradient: true,
ensureLegibility: true,
},
},
},
],
};
const isuniq = (id) => {
const targetEdge = edges.find((v) => v.id === id);
if (targetEdge) {
targetEdge.associated.push(data[i].name);
return false;
}
return true;
};
if (['m2m', 'linkTo'].includes(data[i].interface)) {
const throughTable = tableData.find((v) => v.name === data[i].through);
if (throughTable) {
const sCellId1 = sourceTable.id;
const tCellId1 = throughTable.id;
const sPortId1 = sourceTable.ports.find((v) => v.name === data[i].sourceKey)?.id;
const tPortId1 = throughTable.ports.find((v) => v.name === data[i].foreignKey)?.id;
const sCellId2 = targetTable.id;
const tCellId2 = throughTable.id;
const sPortId2 = targetTable.ports.find((v) => v.name === data[i].targetKey)?.id;
const tPortId2 = throughTable.ports.find((v) => v.name === data[i].otherKey)?.id;
const id1 = sCellId1 + sPortId1 + tCellId1 + tPortId1;
const id2 = sCellId2 + sPortId2 + tCellId2 + tPortId2;
edges.push({
id: id1,
source: {
cell: sCellId1,
port: sPortId1,
anchor: {
name: 'right',
},
},
target: {
cell: tCellId1,
port: tPortId1,
anchor: {
name: 'left',
},
},
associated: [data[i].name],
m2m: [id1, id2],
...commonAttrs,
});
edges.push({
id: id2,
source: {
cell: sCellId2,
port: sPortId2,
anchor: {
name: 'right',
},
},
target: {
cell: tCellId2,
port: tPortId2,
anchor: {
name: 'left',
},
},
associated: [data[i].name],
m2m: [id1, id2],
...commonAttrs,
});
}
} else {
const isLegalEdge = tableData
.find((v) => v.name == (data[i].sourceCollectionName || data[i].collectionName))
.ports.find((v) => v.name === data[i].foreignKey);
const sCellId1 = sourceTable.id;
const tCellId1 = targetTable.id;
const sPortId1 = isLegalEdge?.id;
const tPortId1 = targetTable.ports.find((v) => v.name === data[i].targetKey)?.id;
const sCellId2 = sourceTable.id;
const tCellId2 = targetTable.id;
const sPortId2 = sourceTable.ports.find((v) => v.name === data[i].sourceKey)?.id;
const tPortId2 = targetTable.ports.find((v) => v.name === data[i].foreignKey)?.id;
const id1 = sCellId1 + sPortId1 + tCellId1 + tPortId1;
const id2 = sCellId2 + sPortId2 + tCellId2 + tPortId2;
isuniq(tCellId1 + tPortId1 + sCellId1 + sPortId1) &&
isLegalEdge &&
tPortId1 &&
edges.push({
id: id1,
source: {
cell: sCellId1,
port: sPortId1,
anchor: {
name: 'right',
},
},
target: {
cell: tCellId1,
port: tPortId1,
anchor: {
name: 'left',
},
},
associated: [data[i].name],
...commonAttrs,
});
isuniq(tCellId2 + tPortId2 + sCellId2 + sPortId2) &&
sPortId2 &&
tPortId2 &&
edges.push({
id: id2,
source: {
cell: sCellId2,
port: sPortId2,
anchor: {
name: 'right',
},
},
target: {
cell: tCellId2,
port: tPortId2,
anchor: {
name: 'left',
},
},
associated: [data[i].name],
...commonAttrs,
});
}
}
}
return uniqBy(edges, 'id');
};
const getRelationship = (relatioship) => {
switch (relatioship) {
case 'm2m':
case 'linkTo':
return ['1', 'N'];
case 'o2m':
return ['1', 'N'];
case 'm2o':
return ['N', '1'];
case 'obo':
case 'oho':
return ['1', '1'];
default:
return [];
}
};
export const getDiffNode = (newNodes, oldNodes) => {
const arr = [];
2023-01-11 11:58:47 +08:00
const length1 = newNodes.length;
const length2 = oldNodes.length;
for (let i = 0; i < length1; i++) {
if (!oldNodes.find((v) => v.id === newNodes[i].id)) {
arr.push({
status: 'add',
node: newNodes[i],
});
} else {
const oldNode = oldNodes.find((v) => v.id === newNodes[i].id);
const oldPorts = oldNode?.ports.items;
const newPorts = newNodes[i].ports;
if (oldNode) {
for (let h = 0; h < newPorts.length; h++) {
if (!oldPorts.find((v) => v.id === newPorts[h].id)) {
arr.push({
status: 'insertPort',
node: newNodes[i],
port: { index: h, port: newPorts[h] },
});
}
}
for (let k = 0; k < oldPorts.length; k++) {
if (!newPorts.find((v) => v.id === oldPorts[k].id)) {
arr.push({
status: 'deletePort',
node: newNodes[i],
port: oldPorts[k],
});
}
}
if (oldNode.title !== newNodes[i].title) {
arr.push({
status: 'updateNode',
node: newNodes[i],
});
}
}
}
}
for (let i = 0; i < length2; i++) {
if (!newNodes.find((v) => v.id === oldNodes[i].id)) {
arr.push({
status: 'delete',
node: oldNodes[i],
});
}
}
return arr;
};
export const getDiffEdge = (newEdges, oldEdges) => {
const length1 = newEdges.length;
const length2 = oldEdges?.length;
const edges = [];
for (let i = 0; i < length1; i++) {
if (!oldEdges.find((v) => v.id === newEdges[i].id)) {
edges.push({
status: 'add',
edge: newEdges[i],
});
}
}
for (let i = 0; i < length2; i++) {
if (!newEdges.find((v) => v.id === oldEdges[i].id)) {
edges.push({
status: 'delete',
edge: oldEdges[i],
});
}
}
return edges;
};
let graphContainer;
/**
* getPopupContainer divReact 18 concurrent
* https://ant.design/docs/react/migration-v5-cn#%E5%8D%87%E7%BA%A7%E5%87%86%E5%A4%87
*/
export const getPopupContainer = () => {
if (graphContainer) {
return graphContainer;
}
return (graphContainer = document.getElementById('graph_container'));
};