-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathtables.ts
More file actions
225 lines (177 loc) · 6.14 KB
/
tables.ts
File metadata and controls
225 lines (177 loc) · 6.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import { FieldType } from "@/lib/schemas/field-schema";
import { RelationshipType } from "@/lib/schemas/relationship-schema";
import { TableType } from "@/lib/schemas/table-schema";
import { Node } from "@xyflow/react";
import ELK from "elkjs/lib/elk.bundled.js";
import { cloneField } from "./field";
import { v4 } from "uuid";
import { getTimestamp } from "./utils";
import { SortableTable } from "@/lib/table";
const elk = new ELK();
const adjustTablesPositions = async (
nodes: Node[],
relationships: RelationshipType[]
): Promise<TableType[]> => {
// Extract tables (same as before)
const tables: TableType[] = nodes.map((node: Node) => (
{ ...node.data.table as TableType }
)) as TableType[];
// Build the ELK graph structure
const graph = {
id: "root",
layoutOptions: {
'elk.algorithm': 'layered',
'elk.layered.spacing.nodeNodeBetweenLayers': '100',
'elk.spacing.nodeNode': '80',
},
children: nodes.map((node) => ({
id: node.id,
width: node.measured?.width ?? 224,
height: node.measured?.height ?? ((node.data?.table as TableType)?.fields?.length * 32 + 36),
})),
edges: relationships.map((rel) => ({
id: `${rel.sourceTableId}->${rel.targetTableId}`,
sources: [rel.sourceTableId],
targets: [rel.targetTableId],
})),
};
// Run ELK layout (async)
const layoutedGraph = await elk.layout(graph);
// Map positions back to your tables
tables.forEach((table) => {
const node = layoutedGraph?.children?.find((n) => n.id === table.id);
if (node) {
// ELK positions are top-left, adjust to center like before
table.posX = (node.x || 0);
table.posY = (node.y || 0);
}
});
return tables;
};
const isTablesOverlapping = (tableA: TableType, tableB: TableType) => {
const tableAWidth: number = 224;
const tableAHeight: number = tableA.fields.length * 32 + 36;
const tableBWidth: number = 224;
const tableBHeight: number = tableB.fields.length * 32 + 36;
const a = {
left: tableA.posX,
right: tableA.posX + tableAWidth,
top: tableA.posY,
bottom: tableA.posY + tableAHeight,
};
const b = {
left: tableB.posX,
right: tableB.posX + tableBWidth,
top: tableB.posY,
bottom: tableB.posY + tableBHeight,
};
return !(a.right <= b.left || a.left >= b.right || a.bottom <= b.top || a.top >= b.bottom);
}
const getDefaultTableOverlapping = (table: TableType, tables: TableType[]): boolean => {
for (let index: number = 0; index < tables.length; index++) {
if (table.id == tables[index].id) continue;
if (isTablesOverlapping(table, tables[index]))
return true;
}
return false;
}
const cloneTable = (table: TableType): TableType => {
return {
...table,
id: v4(),
name: `${table.name}_copy`,
fields: table.fields.map((field: FieldType) => cloneField(field)),
posX: table.posX - 360,
createdAt: getTimestamp()
}
}
function orderTables(tables: SortableTable[]): string[] {
// Build adjacency list and in-degree count
const graph = new Map();
const inDegree = new Map();
// Initialize graph and in-degree map
tables.forEach(({ tableId, relationships }) => {
graph.set(tableId, new Set());
inDegree.set(tableId, 0);
});
// Populate the graph and in-degree map
tables.forEach(({ tableId, relationships }) => {
relationships.forEach(fk => {
if (graph.has(fk)) {
graph.get(fk).add(tableId);
inDegree.set(tableId, (inDegree.get(tableId) || 0) + 1);
}
});
});
// Find tables with no dependencies (in-degree = 0)
const queue: string[] = [];
inDegree.forEach((count, table) => {
if (count === 0) queue.push(table);
});
// Process tables in topological order
const sortedOrder: string[] = [];
while (queue.length > 0) {
const table = queue.shift();
sortedOrder.push(table as string);
// Reduce in-degree of dependent tables
graph.get(table).forEach((dependent: string) => {
inDegree.set(dependent, inDegree.get(dependent) - 1);
if (inDegree.get(dependent) === 0) {
queue.push(dependent);
}
});
}
// If not all tables are processed, a cycle exists
if (sortedOrder.length !== tables.length) {
const visited = new Set<string>();
const onStack = new Set<string>();
const path: string[] = [];
let cycle: string[] = [];
function dfs(node: string): boolean {
visited.add(node);
onStack.add(node);
path.push(node);
for (const neighbor of graph.get(node)!) {
if (!visited.has(neighbor)) {
if (dfs(neighbor)) return true;
} else if (onStack.has(neighbor)) {
// Found the cycle
const cycleStartIndex = path.indexOf(neighbor);
cycle = path.slice(cycleStartIndex);
cycle.push(neighbor); // close the loop
return true;
}
}
onStack.delete(node);
path.pop();
return false;
}
for (const node of graph.keys()) {
if (!visited.has(node)) {
if (dfs(node)) break;
}
}
throw {
success: false,
message: "Cycle detected",
cycle: cycle,
};
}
return sortedOrder;
}
const getTableNextSequence = (tables: TableType[]): number => {
if (tables.length == 0)
return 0;
const maxSequenceItem = tables.reduce((max, table: TableType) => {
return table.sequence > max.sequence ? table : max;
});
return maxSequenceItem.sequence + 1;
}
export {
adjustTablesPositions,
getDefaultTableOverlapping,
isTablesOverlapping,
cloneTable,
orderTables,
getTableNextSequence
}