-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2289 lines (2066 loc) · 82 KB
/
Copy pathapp.js
File metadata and controls
2289 lines (2066 loc) · 82 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const svg = document.getElementById("flowCanvas");
const gridLayer = document.getElementById("gridLayer");
const headerLayer = document.getElementById("headerLayer");
const laneLayer = document.getElementById("laneLayer");
const selectionLayer = document.getElementById("selectionLayer");
const edgeLayer = document.getElementById("edgeLayer");
const nodeLayer = document.getElementById("nodeLayer");
const titleInput = document.getElementById("diagramTitle");
const statusText = document.getElementById("statusText");
const zoomLevel = document.getElementById("zoomLevel");
const nodeText = document.getElementById("nodeText");
const nodeOwner = document.getElementById("nodeOwner");
const nodeShape = document.getElementById("nodeShape");
const nodeWidth = document.getElementById("nodeWidth");
const lanesEnabledInput = document.getElementById("lanesEnabled");
const laneNamesInput = document.getElementById("laneNames");
const lanesHorizontalBtn = document.getElementById("lanesHorizontalBtn");
const lanesVerticalBtn = document.getElementById("lanesVerticalBtn");
const headerEnabledInput = document.getElementById("headerEnabled");
const headerCompanyInput = document.getElementById("headerCompany");
const headerDocumentInput = document.getElementById("headerDocument");
const headerResponsibleInput = document.getElementById("headerResponsible");
const headerCodeInput = document.getElementById("headerCode");
const headerDateInput = document.getElementById("headerDate");
const headerVersionInput = document.getElementById("headerVersion");
const headerPeriodInput = document.getElementById("headerPeriod");
const headerLeftLogoInput = document.getElementById("headerLeftLogoInput");
const headerRightLogoInput = document.getElementById("headerRightLogoInput");
const appVersionBadge = document.getElementById("appVersion");
const currentUserLabel = document.getElementById("currentUserLabel");
const userSelect = document.getElementById("userSelect");
const authView = document.getElementById("authView");
const appShell = document.getElementById("appShell");
const loginForm = document.getElementById("loginForm");
const registerForm = document.getElementById("registerForm");
const signOutButton = document.getElementById("signOutButton");
const manageUsersButton = document.getElementById("manageUsersButton");
const usersDialog = document.getElementById("usersDialog");
const usersForm = document.getElementById("usersForm");
const usersList = document.getElementById("usersList");
const appVersion = "0.4.6";
const NS = "http://www.w3.org/2000/svg";
const storeKey = "flujos-sgc-diagram-v1";
const currentRecordKey = "flujos-sgc-current-record-v1";
const sessionUserKey = "flujos-sgc-session-user-v1";
const cloudCollection = "diagramas";
const workspace = { w: 16000, h: 10400 };
const defaultView = { x: 0, y: 0, w: 1600, h: 1000 };
const headerLayout = { x: 20, y: 20, w: 1560, topH: 125, gap: 22, bottomH: 96, reserve: 300 };
const minZoom = 0.09;
const maxZoom = 2.5;
const shapeSize = {
terminator: { w: 220, h: 94 },
process: { w: 240, h: 110 },
subprocess: { w: 260, h: 110 },
data: { w: 250, h: 110 },
decision: { w: 220, h: 150 },
document: { w: 240, h: 122 },
text: { w: 190, h: 64 },
};
const diagramThemes = {
sgi: { name: "Caborca Flow", stroke: "#0f766e", fills: { terminator: "#e8f7f3", process: "#ffffff", subprocess: "#ffffff", data: "#f0fdf4", decision: "#fff7ed", document: "#eff6ff" } },
blue: { name: "Azul", stroke: "#2563eb", fills: { terminator: "#dbeafe", process: "#ffffff", subprocess: "#ffffff", data: "#e0f2fe", decision: "#fef3c7", document: "#eef2ff" } },
amber: { name: "Ambar", stroke: "#d97706", fills: { terminator: "#fef3c7", process: "#ffffff", subprocess: "#ffffff", data: "#fffbeb", decision: "#fed7aa", document: "#fff7ed" } },
slate: { name: "Grafito", stroke: "#475569", fills: { terminator: "#f1f5f9", process: "#ffffff", subprocess: "#ffffff", data: "#e2e8f0", decision: "#f8fafc", document: "#f1f5f9" } },
rose: { name: "Vino", stroke: "#be123c", fills: { terminator: "#ffe4e6", process: "#ffffff", subprocess: "#ffffff", data: "#fff1f2", decision: "#ffedd5", document: "#fdf2f8" } },
};
let state = {
title: "Proceso Caborca Flow",
nodes: [],
edges: [],
header: defaultHeader(),
lanes: { enabled: false, orientation: "horizontal", names: ["Direccion", "Calidad", "Produccion"] },
theme: "sgi",
};
let selectedNodeId = null;
let selectedEdgeId = null;
let selectedNodeIds = new Set();
let drag = null;
let laneResize = null;
let pan = null;
let selectBox = null;
let selectMode = false;
let connectMode = false;
let connectFrom = null;
let deferredInstall = null;
let view = { ...defaultView };
let internalClipboard = null;
let undoStack = [];
let lastStateSnapshot = "";
let historyPaused = false;
let currentRecordId = localStorage.getItem(currentRecordKey) || "";
let sessionUser = localStorage.getItem(sessionUserKey) || "";
let authUser = null;
let currentProfile = null;
let usersCache = [];
if (sessionUser === "Hermenegildo Perez") sessionUser = "Hermenegildo Pérez";
if (sessionUser === "Omar Martinez") sessionUser = "Omar Martínez";
function uid(prefix) {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
}
function setStatus(message) {
statusText.textContent = message;
window.clearTimeout(setStatus.timer);
setStatus.timer = window.setTimeout(() => {
statusText.textContent = "Listo";
}, 2200);
}
function updateSessionUI() {
if (!currentUserLabel) return;
const role = currentProfile?.role === "admin" ? "Admin" : "Usuario";
currentUserLabel.textContent = sessionUser ? `${role}: ${sessionUser}` : "Sin sesion";
currentUserLabel.classList.toggle("active", Boolean(sessionUser));
if (manageUsersButton) manageUsersButton.hidden = !isAdmin();
if (userSelect) userSelect.value = sessionUser;
}
function setSessionUser(value) {
sessionUser = value || "";
if (sessionUser) {
localStorage.setItem(sessionUserKey, sessionUser);
setStatus(`Sesion iniciada: ${sessionUser}`);
} else {
localStorage.removeItem(sessionUserKey);
setStatus("Selecciona usuario para guardar cambios");
}
updateSessionUI();
}
function requireSession() {
if (sessionUser) return true;
setStatus("Inicia sesion para guardar cambios");
showAuthMode("login");
return false;
}
function normalizeEmail(value) {
return String(value || "").trim().toLowerCase();
}
function normalizeUserProfile(user = {}, id = user.id) {
return {
id,
name: user.name || user.email || "Usuario",
email: normalizeEmail(user.email),
role: ["admin", "usuario"].includes(user.role) ? user.role : "usuario",
};
}
function isAdmin() {
return currentProfile?.role === "admin";
}
async function inferInitialRole(tools) {
try {
const usersSnapshot = await tools.getDocs(tools.collection(tools.db, "users"));
return usersSnapshot.docs.length === 0 ? "admin" : "usuario";
} catch {
return "admin";
}
}
async function ensureUserProfile(user) {
const tools = await firebaseTools();
const ref = tools.doc(tools.db, "users", user.uid);
let snapshot = null;
try {
snapshot = await tools.getDoc(ref);
} catch {
snapshot = null;
}
if (snapshot?.exists()) {
const profile = normalizeUserProfile(snapshot.data(), user.uid);
await tools.setDoc(ref, {
name: profile.name || user.displayName || user.email || "Usuario",
email: profile.email || normalizeEmail(user.email),
updatedAt: tools.serverTimestamp(),
}, { merge: true });
return profile;
}
const profile = {
name: user.displayName || user.email || "Usuario",
email: normalizeEmail(user.email),
role: await inferInitialRole(tools),
createdAt: new Date().toISOString(),
updatedAt: tools.serverTimestamp(),
};
await tools.setDoc(ref, profile, { merge: true });
return normalizeUserProfile(profile, user.uid);
}
async function loadUsers() {
const tools = await firebaseTools();
const snapshot = await tools.getDocs(tools.query(tools.collection(tools.db, "users"), tools.orderBy("email", "asc")));
usersCache = snapshot.docs.map((item) => normalizeUserProfile(item.data(), item.id));
}
function renderUsersEditor() {
if (!usersList) return;
usersList.innerHTML = "";
if (!usersCache.length) {
usersList.innerHTML = '<p class="dialog-note">No hay usuarios registrados.</p>';
return;
}
usersCache.forEach((user) => {
const row = document.createElement("article");
row.className = "user-row";
row.dataset.id = user.id;
row.innerHTML = `
<div><strong>${escapeXml(user.name)}</strong><p>${escapeXml(user.email)}</p></div>
<label>Rol<select data-field="role"><option value="admin">Admin</option><option value="usuario">Usuario</option></select></label>
<span class="role-pill" data-role="${escapeXml(user.role)}">${user.role === "admin" ? "Admin" : "Usuario"}</span>
`;
row.querySelector('[data-field="role"]').value = user.role;
usersList.appendChild(row);
});
}
async function openUsersDialog() {
if (!isAdmin() || !usersDialog) return;
await loadUsers();
renderUsersEditor();
usersDialog.showModal();
}
async function saveUsersRoles() {
if (!isAdmin()) return;
const tools = await firebaseTools();
const updates = [...document.querySelectorAll(".user-row")].map((row) => tools.setDoc(tools.doc(tools.db, "users", row.dataset.id), {
role: row.querySelector('[data-field="role"]').value,
updatedAt: tools.serverTimestamp(),
}, { merge: true }));
await Promise.all(updates);
await loadUsers();
const ownProfile = usersCache.find((user) => user.id === authUser?.uid);
if (ownProfile) currentProfile = ownProfile;
updateSessionUI();
usersDialog?.close();
}
function setAuthMessage(selector, text, tone = "error") {
const node = document.querySelector(selector);
if (!node) return;
node.textContent = text;
node.dataset.tone = tone;
}
function authErrorMessage(error) {
const code = error?.code || "";
const messages = {
"auth/invalid-credential": "Correo o contraseña incorrectos, o el usuario no existe.",
"auth/user-not-found": "No existe una cuenta con ese correo. Usa Agregar cuenta primero.",
"auth/wrong-password": "La contraseña no coincide con ese correo.",
"auth/invalid-email": "El correo no tiene un formato válido.",
"auth/email-already-in-use": "Ese correo ya está registrado. Inicia sesión con esa cuenta.",
"auth/weak-password": "La contraseña debe tener al menos 6 caracteres.",
"auth/operation-not-allowed": "Email/Password no está habilitado en Firebase Authentication.",
"auth/api-key-not-valid": "La API key de Firebase no es válida o está restringida.",
"auth/network-request-failed": "No se pudo conectar con Firebase. Revisa internet o bloqueos de red.",
"permission-denied": "Firebase bloqueó la operación por reglas de Firestore.",
};
return messages[code] || `Firebase respondió: ${code || "error desconocido"}`;
}
function showAuthMode(mode) {
if (!authView || !appShell) return;
const isRegister = mode === "register";
authView.hidden = false;
appShell.hidden = true;
if (loginForm) loginForm.hidden = isRegister;
if (registerForm) registerForm.hidden = !isRegister;
}
function showAppShell() {
if (!authView || !appShell) return;
authView.hidden = true;
appShell.hidden = false;
}
function authDisplayName(user) {
return user?.displayName || user?.email || "Usuario";
}
async function applyAuthUser(user) {
authUser = user || null;
currentProfile = null;
if (!authUser) {
sessionUser = "";
localStorage.removeItem(sessionUserKey);
updateSessionUI();
showAuthMode("login");
return;
}
try {
currentProfile = await ensureUserProfile(authUser);
} catch {
currentProfile = { id: authUser.uid, name: authDisplayName(authUser), email: normalizeEmail(authUser.email), role: "usuario" };
}
sessionUser = currentProfile.name || authDisplayName(authUser);
localStorage.setItem(sessionUserKey, sessionUser);
updateSessionUI();
showAppShell();
}
function authToolsReady() {
return window.flujosFirebaseAuth;
}
async function waitForAuthTools() {
if (authToolsReady()) return authToolsReady();
await new Promise((resolve) => {
const timer = window.setTimeout(resolve, 3500);
window.addEventListener("flujos:auth-ready", () => {
window.clearTimeout(timer);
resolve();
}, { once: true });
window.addEventListener("flujos:auth-error", () => {
window.clearTimeout(timer);
resolve();
}, { once: true });
});
if (!authToolsReady()) throw new Error("Auth no disponible");
return authToolsReady();
}
async function startAuthSession() {
try {
const tools = await waitForAuthTools();
tools.onAuthStateChanged(tools.auth, applyAuthUser);
} catch {
setAuthMessage("#loginMessage", "No se pudo conectar el acceso seguro. Revisa tu conexion.");
showAuthMode("login");
}
}
function revisionEntry(version, action) {
return {
version,
action,
by: sessionUser || "Sin sesion",
at: new Date().toISOString(),
appVersion,
};
}
function createSvg(name, attrs = {}) {
const el = document.createElementNS(NS, name);
Object.entries(attrs).forEach(([key, value]) => el.setAttribute(key, value));
return el;
}
function defaultHeader() {
return {
enabled: false,
company: "BOTAS CABORCA S.A. DE C.V.",
document: "Documento: Identificacion de Molduras",
responsible: "Jefe de Implementaciones",
code: "FO-DES-032",
date: "27/05/26",
version: "00",
period: "V - 2026",
leftLogo: "CABORCA\nGROUP",
rightLogo: "SISTEMA DE TRABAJO\nCABORCA",
leftLogoImage: "",
rightLogoImage: "",
};
}
function ensureHeader() {
if (!state.header) state.header = defaultHeader();
state.header = { ...defaultHeader(), ...state.header };
}
function ensureTheme() {
if (!state.theme || !diagramThemes[state.theme]) state.theme = "sgi";
}
function activeTheme() {
ensureTheme();
return diagramThemes[state.theme];
}
function themeFill(shape) {
const theme = activeTheme();
return theme.fills[shape] || theme.fills.process || "#ffffff";
}
function themeStroke(node) {
return selectedNodeIds.has(node.id) ? "#f59e0b" : activeTheme().stroke;
}
function setDiagramTheme(themeId) {
if (!diagramThemes[themeId]) return;
state.theme = themeId;
save();
render();
setStatus(`Tema aplicado: ${diagramThemes[themeId].name}`);
}
function syncHeaderControls() {
ensureHeader();
headerEnabledInput.checked = Boolean(state.header.enabled);
headerCompanyInput.value = state.header.company;
headerDocumentInput.value = state.header.document;
headerResponsibleInput.value = state.header.responsible;
headerCodeInput.value = state.header.code;
headerDateInput.value = state.header.date;
headerVersionInput.value = state.header.version;
headerPeriodInput.value = state.header.period;
}
function addMultilineSvgText(group, text, x, y, attrs = {}) {
String(text || "").split("\n").forEach((line, index) => {
group.appendChild(createSvg("text", { x, y: y + index * 28, ...attrs })).textContent = line;
});
}
function addHeaderLogo(group, imageData, fallbackText, x, y, w, h) {
if (imageData) {
group.appendChild(createSvg("image", {
class: "doc-header-image",
href: imageData,
x,
y,
width: w,
height: h,
preserveAspectRatio: "xMidYMid meet",
}));
return;
}
addMultilineSvgText(group, fallbackText, x + w / 2, y + h / 2 - 12, { class: "doc-header-logo", "text-anchor": "middle" });
}
function headerReservedHeight() {
ensureHeader();
return state.header.enabled ? headerLayout.reserve : 0;
}
function makeRoomForHeader() {
const topLimit = headerReservedHeight() + 40;
if (!topLimit || !state.nodes?.length) return;
const minY = Math.min(...state.nodes.map((node) => node.y));
if (minY >= topLimit) return;
const deltaY = topLimit - minY;
state.nodes.forEach((node) => {
const size = getNodeSize(node);
node.y = clamp(node.y + deltaY, 20, workspace.h - size.h - 20);
});
}
function renderHeader(targetLayer = headerLayer, options = {}) {
ensureHeader();
targetLayer.innerHTML = "";
if (!state.header.enabled) return;
const x = options.x ?? headerLayout.x;
const y = options.y ?? headerLayout.y;
const w = options.w ?? headerLayout.w;
const topH = headerLayout.topH;
const bottomH = headerLayout.bottomH;
const leftW = 320;
const rightW = 360;
const centerW = w - leftW - rightW;
const group = createSvg("g", { class: "doc-header" });
group.appendChild(createSvg("rect", { class: "doc-header-box", x, y, width: w, height: topH }));
group.appendChild(createSvg("rect", { class: "doc-header-box", x, y: y + topH + headerLayout.gap, width: w, height: bottomH }));
group.appendChild(createSvg("line", { class: "doc-header-line", x1: x + leftW, y1: y, x2: x + leftW, y2: y + topH }));
group.appendChild(createSvg("line", { class: "doc-header-line", x1: x + leftW + centerW, y1: y, x2: x + leftW + centerW, y2: y + topH }));
addHeaderLogo(group, state.header.leftLogoImage, state.header.leftLogo, x + 28, y + 14, leftW - 56, topH - 28);
group.appendChild(createSvg("text", { class: "doc-header-company", x: x + leftW + centerW / 2, y: y + 48, "text-anchor": "middle" })).textContent = state.header.company;
group.appendChild(createSvg("text", { class: "doc-header-document", x: x + leftW + centerW / 2, y: y + 88, "text-anchor": "middle" })).textContent = state.header.document;
addHeaderLogo(group, state.header.rightLogoImage, state.header.rightLogo, x + leftW + centerW + 28, y + 14, rightW - 56, topH - 28);
const infoY = y + topH + headerLayout.gap + 36;
group.appendChild(createSvg("text", { class: "doc-header-info", x: x + 24, y: infoY })).textContent = `Responsable: ${state.header.responsible}`;
group.appendChild(createSvg("text", { class: "doc-header-info", x: x + 24, y: infoY + 42 })).textContent = `Codigo: ${state.header.code}`;
group.appendChild(createSvg("text", { class: "doc-header-info", x: x + 570, y: infoY })).textContent = `Fecha Revision: ${state.header.date}`;
group.appendChild(createSvg("text", { class: "doc-header-info", x: x + 570, y: infoY + 42 })).textContent = `Version: ${state.header.version}`;
group.appendChild(createSvg("rect", { class: "doc-header-period", x: x + w - 240, y: y + topH + headerLayout.gap + 14, width: 220, height: 48, rx: 8 }));
group.appendChild(createSvg("text", { class: "doc-header-period-text", x: x + w - 130, y: y + topH + headerLayout.gap + 46, "text-anchor": "middle" })).textContent = state.header.period;
targetLayer.appendChild(group);
}
function laneContentExtent(axis) {
if (!Array.isArray(state.nodes) || !state.nodes.length) return 0;
return state.nodes.reduce((max, node) => {
const bounds = nodeBounds(node);
return Math.max(max, axis === "x" ? bounds.x + bounds.w : bounds.y + bounds.h);
}, 0);
}
function laneTotalSize() {
ensureHeader();
const count = Math.max(1, state.lanes?.names?.length || 1);
if (state.lanes?.orientation === "vertical") {
const current = Array.isArray(state.lanes.sizes) ? state.lanes.sizes.map(Number).filter((size) => Number.isFinite(size) && size > 0) : [];
if (current.length === count) return Math.min(workspace.w, current.reduce((acc, size) => acc + size, 0));
const minimumByLanes = count * 420;
const minimumByHeader = state.header?.enabled ? headerLayout.x + headerLayout.w + 260 : 0;
const minimumByContent = laneContentExtent("x") + 360;
return Math.min(workspace.w, Math.max(minimumByLanes, minimumByHeader, minimumByContent, defaultView.w));
}
return workspace.h - headerReservedHeight();
}
function normalizeLaneSizes() {
const total = laneTotalSize();
const count = state.lanes.names.length;
const current = Array.isArray(state.lanes.sizes) ? state.lanes.sizes.map(Number).filter((size) => Number.isFinite(size) && size > 0) : [];
if (current.length !== count) {
state.lanes.sizes = Array.from({ length: count }, () => total / count);
return;
}
const sum = current.reduce((acc, size) => acc + size, 0);
state.lanes.sizes = sum > 0 ? current.map((size) => (size / sum) * total) : Array.from({ length: count }, () => total / count);
}
function laneStarts() {
normalizeLaneSizes();
const starts = [];
state.lanes.sizes.reduce((offset, size) => {
starts.push(offset);
return offset + size;
}, 0);
return starts;
}
function ensureLanes() {
if (!state.lanes) {
state.lanes = { enabled: false, orientation: "horizontal", names: ["Direccion", "Calidad", "Produccion"] };
}
if (state.lanes.orientation !== "vertical") state.lanes.orientation = "horizontal";
if (!Array.isArray(state.lanes.names) || !state.lanes.names.length) {
state.lanes.names = ["Direccion", "Calidad", "Produccion"];
}
normalizeLaneSizes();
}
function syncLaneControls() {
ensureLanes();
lanesEnabledInput.checked = Boolean(state.lanes.enabled);
laneNamesInput.value = state.lanes.names.join("\n");
lanesHorizontalBtn.classList.toggle("active", state.lanes.orientation === "horizontal");
lanesVerticalBtn.classList.toggle("active", state.lanes.orientation === "vertical");
}
function renderLanes(targetLayer = laneLayer, options = {}) {
ensureLanes();
targetLayer.innerHTML = "";
if (!state.lanes.enabled) return;
const clipX = options.x ?? 0;
const clipY = options.y ?? 0;
const clipW = options.w ?? workspace.w;
const clipH = options.h ?? workspace.h;
const laneTop = headerReservedHeight();
const laneHeight = workspace.h - laneTop;
const vertical = state.lanes.orientation === "vertical";
const starts = laneStarts();
const interactive = options.interactive ?? targetLayer === laneLayer;
state.lanes.names.forEach((name, index) => {
const size = state.lanes.sizes[index];
if (vertical) {
const x = starts[index];
if (x > clipX + clipW || x + size < clipX || laneTop > clipY + clipH || laneTop + laneHeight < clipY) return;
targetLayer.appendChild(createSvg("rect", {
class: `lane-bg lane-bg-${index % 2}`,
x,
y: laneTop,
width: size,
height: laneHeight,
}));
targetLayer.appendChild(createSvg("line", {
class: "lane-line",
x1: x,
y1: laneTop,
x2: x,
y2: laneTop + laneHeight,
}));
targetLayer.appendChild(createSvg("text", {
class: "lane-label lane-label-vertical",
x: x + size / 2,
y: laneTop + 42,
"text-anchor": "middle",
})).textContent = name || `Calle ${index + 1}`;
if (interactive && index > 0) addLaneResizeHandle(targetLayer, index, x, laneTop, x, laneTop + laneHeight, "vertical");
return;
}
const y = laneTop + starts[index];
if (y > clipY + clipH || y + size < clipY) return;
targetLayer.appendChild(createSvg("rect", {
class: `lane-bg lane-bg-${index % 2}`,
x: clipX,
y,
width: clipW,
height: size,
}));
targetLayer.appendChild(createSvg("line", {
class: "lane-line",
x1: clipX,
y1: y,
x2: clipX + clipW,
y2: y,
}));
targetLayer.appendChild(createSvg("text", {
class: "lane-label",
x: clipX + 24,
y: y + 34,
})).textContent = name || `Calle ${index + 1}`;
if (interactive && index > 0) addLaneResizeHandle(targetLayer, index, clipX, y, clipX + clipW, y, "horizontal");
});
}
function addLaneResizeHandle(targetLayer, index, x1, y1, x2, y2, orientation) {
const handle = createSvg("line", {
class: `lane-resize-handle lane-resize-${orientation}`,
x1,
y1,
x2,
y2,
"data-lane-index": index,
});
handle.addEventListener("pointerdown", (event) => {
event.stopPropagation();
const point = getPoint(event);
laneResize = {
index,
orientation,
startPoint: point,
sizes: [...state.lanes.sizes],
};
svg.setPointerCapture(event.pointerId);
setStatus("Arrastra para ajustar la calle");
});
targetLayer.appendChild(handle);
}
function drawGrid() {
gridLayer.innerHTML = "";
for (let x = 0; x <= workspace.w; x += 40) {
gridLayer.appendChild(createSvg("line", { x1: x, y1: 0, x2: x, y2: workspace.h, stroke: "#d9e8e5", "stroke-width": 1 }));
}
for (let y = 0; y <= workspace.h; y += 40) {
gridLayer.appendChild(createSvg("line", { x1: 0, y1: y, x2: workspace.w, y2: y, stroke: "#d9e8e5", "stroke-width": 1 }));
}
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
function setViewBox(nextView) {
const nextW = clamp(nextView.w, defaultView.w / maxZoom, defaultView.w / minZoom);
const nextH = clamp(nextView.h, defaultView.h / maxZoom, defaultView.h / minZoom);
view = {
x: clamp(nextView.x, 0, Math.max(0, workspace.w - nextW)),
y: clamp(nextView.y, 0, Math.max(0, workspace.h - nextH)),
w: nextW,
h: nextH,
};
svg.setAttribute("viewBox", `${view.x} ${view.y} ${view.w} ${view.h}`);
zoomLevel.textContent = `${Math.round((defaultView.w / view.w) * 100)}%`;
}
function zoomAt(factor, point = { x: view.x + view.w / 2, y: view.y + view.h / 2 }) {
const nextW = clamp(view.w / factor, defaultView.w / maxZoom, defaultView.w / minZoom);
const nextH = clamp(view.h / factor, defaultView.h / maxZoom, defaultView.h / minZoom);
const rx = (point.x - view.x) / view.w;
const ry = (point.y - view.y) / view.h;
setViewBox({
x: point.x - nextW * rx,
y: point.y - nextH * ry,
w: nextW,
h: nextH,
});
}
function resetZoom() {
setViewBox(defaultView);
}
function updateFullscreenButton() {
const button = document.getElementById("fullscreenBtn");
if (!button) return;
button.textContent = document.fullscreenElement ? "Salir" : "Pantalla";
}
async function toggleFullscreen() {
const target = document.querySelector(".canvas-wrap");
try {
if (document.fullscreenElement) {
await document.exitFullscreen();
setStatus("Pantalla completa cerrada");
} else if (target?.requestFullscreen) {
await target.requestFullscreen();
fitToDiagram();
setStatus("Modo presentacion activo");
} else {
setStatus("Pantalla completa no disponible");
}
} catch {
setStatus("No se pudo activar pantalla completa");
}
updateFullscreenButton();
}
function fitToDiagram() {
if (!state.nodes.length) {
resetZoom();
return;
}
const padding = 160;
const bounds = state.nodes.reduce((box, node) => {
const size = getNodeSize(node);
return {
minX: Math.min(box.minX, node.x),
minY: Math.min(box.minY, node.y),
maxX: Math.max(box.maxX, node.x + size.w),
maxY: Math.max(box.maxY, node.y + size.h),
};
}, { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity });
const wantedW = Math.max(bounds.maxX - bounds.minX + padding * 2, 700);
const wantedH = Math.max(bounds.maxY - bounds.minY + padding * 2, 440);
const scale = Math.max(wantedW / defaultView.w, wantedH / defaultView.h);
const nextW = clamp(defaultView.w * scale, defaultView.w / maxZoom, defaultView.w / minZoom);
const nextH = clamp(defaultView.h * scale, defaultView.h / maxZoom, defaultView.h / minZoom);
setViewBox({
x: (bounds.minX + bounds.maxX) / 2 - nextW / 2,
y: (bounds.minY + bounds.maxY) / 2 - nextH / 2,
w: nextW,
h: nextH,
});
}
function centerOf(node) {
const size = getNodeSize(node);
return { x: node.x + size.w / 2, y: node.y + size.h / 2 };
}
function connectionPoint(node, side) {
const size = getNodeSize(node);
const center = centerOf(node);
if (side === "left") return { x: node.x, y: center.y };
if (side === "right") return { x: node.x + size.w, y: center.y };
if (side === "top") return { x: center.x, y: node.y };
return { x: center.x, y: node.y + size.h };
}
function automaticConnectionSides(from, to) {
const fromCenter = centerOf(from);
const toCenter = centerOf(to);
const dx = toCenter.x - fromCenter.x;
const dy = toCenter.y - fromCenter.y;
const vertical = Math.abs(dy) > Math.abs(dx);
return {
fromSide: vertical ? (dy >= 0 ? "bottom" : "top") : (dx >= 0 ? "right" : "left"),
toSide: vertical ? (dy >= 0 ? "top" : "bottom") : (dx >= 0 ? "left" : "right"),
};
}
function edgeConnectionSides(edge, from, to) {
const auto = automaticConnectionSides(from, to);
return {
fromSide: edge?.fromSide || auto.fromSide,
toSide: edge?.toSide || auto.toSide,
};
}
function sideDirection(side) {
if (side === "left") return { x: -1, y: 0 };
if (side === "right") return { x: 1, y: 0 };
if (side === "top") return { x: 0, y: -1 };
return { x: 0, y: 1 };
}
function edgePath(from, to, edge = null) {
const { fromSide, toSide } = edgeConnectionSides(edge, from, to);
const a = connectionPoint(from, fromSide);
const b = connectionPoint(to, toSide);
const verticalFlow = (fromSide === "bottom" && toSide === "top") || (fromSide === "top" && toSide === "bottom");
const horizontalFlow = (fromSide === "right" && toSide === "left") || (fromSide === "left" && toSide === "right");
if (verticalFlow) {
const distance = Math.abs(b.y - a.y);
const curve = Math.max(24, Math.min(90, distance * 0.28));
const direction = Math.sign(b.y - a.y || (fromSide === "bottom" ? 1 : -1));
return `M ${a.x} ${a.y} C ${a.x} ${a.y + direction * curve}, ${b.x} ${b.y - direction * curve}, ${b.x} ${b.y}`;
}
if (horizontalFlow) {
const distance = Math.abs(b.x - a.x);
const curve = Math.max(24, Math.min(100, distance * 0.28));
const direction = Math.sign(b.x - a.x || (fromSide === "right" ? 1 : -1));
return `M ${a.x} ${a.y} C ${a.x + direction * curve} ${a.y}, ${b.x - direction * curve} ${b.y}, ${b.x} ${b.y}`;
}
const fromDirection = sideDirection(fromSide);
const toDirection = sideDirection(toSide);
const curve = Math.max(55, Math.min(160, Math.hypot(b.x - a.x, b.y - a.y) * 0.2));
const c1 = { x: a.x + fromDirection.x * curve, y: a.y + fromDirection.y * curve };
const c2 = { x: b.x + toDirection.x * curve, y: b.y + toDirection.y * curve };
return `M ${a.x} ${a.y} C ${c1.x} ${c1.y}, ${c2.x} ${c2.y}, ${b.x} ${b.y}`;
}
function renderEdgeAnchors(edge, from, to) {
const sides = ["top", "right", "bottom", "left"];
const { fromSide, toSide } = edgeConnectionSides(edge, from, to);
[{ node: from, end: "from", active: fromSide }, { node: to, end: "to", active: toSide }].forEach((item) => {
sides.forEach((side) => {
const point = connectionPoint(item.node, side);
const group = createSvg("g", { class: `edge-anchor-group${side === item.active ? " active" : ""}` });
const hitArea = createSvg("circle", {
class: "edge-anchor-hit",
cx: point.x,
cy: point.y,
r: 34,
"data-edge-end": item.end,
"data-edge-side": side,
});
const visibleHandle = createSvg("circle", {
class: "edge-anchor",
cx: point.x,
cy: point.y,
r: 14,
});
group.addEventListener("pointerdown", (event) => {
event.stopPropagation();
edge[`${item.end}Side`] = side;
save();
render();
setStatus(`Conexion ajustada al lado ${side}`);
});
group.appendChild(hitArea);
group.appendChild(visibleHandle);
edgeLayer.appendChild(group);
});
});
}
function nodeBounds(node) {
const size = getNodeSize(node);
return { x: node.x, y: node.y, w: size.w, h: size.h };
}
function rectsIntersect(a, b) {
return a.x <= b.x + b.w && a.x + a.w >= b.x && a.y <= b.y + b.h && a.y + a.h >= b.y;
}
function normalizeBox(start, end) {
return {
x: Math.min(start.x, end.x),
y: Math.min(start.y, end.y),
w: Math.abs(end.x - start.x),
h: Math.abs(end.y - start.y),
};
}
function setSelectedNodes(ids, primaryId = null) {
selectedNodeIds = new Set(ids);
selectedNodeId = primaryId || ids[ids.length - 1] || null;
selectedEdgeId = null;
}
function clearSelection() {
selectedNodeIds = new Set();
selectedNodeId = null;
selectedEdgeId = null;
}
function selectedNodes() {
return state.nodes.filter((node) => selectedNodeIds.has(node.id));
}
function shapeStyle(node) {
return `--node-stroke:${activeTheme().stroke}`;
}
function detailStyle(node) {
return `--node-stroke:${activeTheme().stroke}`;
}
function shapeElement(node) {
const size = getNodeSize(node);
if (node.shape === "text") {
return createSvg("rect", { class: "node-shape text-box-shape", x: node.x, y: node.y, width: size.w, height: size.h, rx: 4, fill: "transparent" });
}
if (node.shape === "terminator") {
return createSvg("rect", { class: "node-shape", x: node.x, y: node.y, width: size.w, height: size.h, rx: Math.min(size.h / 2, 54), fill: themeFill(node.shape), style: shapeStyle(node) });
}
if (node.shape === "subprocess") {
const group = createSvg("g");
group.appendChild(createSvg("rect", { class: "node-shape", x: node.x, y: node.y, width: size.w, height: size.h, rx: 8, fill: themeFill(node.shape), style: shapeStyle(node) }));
group.appendChild(createSvg("line", { class: "node-shape-detail", x1: node.x + 24, y1: node.y + 8, x2: node.x + 24, y2: node.y + size.h - 8, style: detailStyle(node) }));
group.appendChild(createSvg("line", { class: "node-shape-detail", x1: node.x + size.w - 24, y1: node.y + 8, x2: node.x + size.w - 24, y2: node.y + size.h - 8, style: detailStyle(node) }));
return group;
}
if (node.shape === "data") {
const slant = Math.min(34, size.w * 0.16);
return createSvg("polygon", {
class: "node-shape",
points: `${node.x + slant},${node.y} ${node.x + size.w},${node.y} ${node.x + size.w - slant},${node.y + size.h} ${node.x},${node.y + size.h}`,
fill: themeFill(node.shape),
style: shapeStyle(node),
});
}
if (node.shape === "decision") {
const cx = node.x + size.w / 2;
const cy = node.y + size.h / 2;
return createSvg("polygon", {
class: "node-shape",
points: `${cx},${node.y} ${node.x + size.w},${cy} ${cx},${node.y + size.h} ${node.x},${cy}`,
fill: themeFill(node.shape),
style: shapeStyle(node),
});
}
if (node.shape === "document") {
const d = [
`M ${node.x} ${node.y}`,
`H ${node.x + size.w}`,
`V ${node.y + size.h - 24}`,
`C ${node.x + size.w - 60} ${node.y + size.h + 8}, ${node.x + 60} ${node.y + size.h - 56}, ${node.x} ${node.y + size.h - 18}`,
"Z",
].join(" ");
return createSvg("path", { class: "node-shape", d, fill: themeFill(node.shape), style: shapeStyle(node) });
}
return createSvg("rect", { class: "node-shape", x: node.x, y: node.y, width: size.w, height: size.h, rx: 8, fill: themeFill(node.shape), style: shapeStyle(node) });
}
function wrapTextLines(text, maxChars, maxLines = Infinity) {
const words = String(text || "").split(/\s+/).filter(Boolean);
const lines = [];
let current = "";
words.forEach((word) => {
const next = current ? `${current} ${word}` : word;
if (next.length > maxChars && current) {
lines.push(current);
current = word;
} else {
current = next;
}
});
if (current) lines.push(current);
if (!lines.length) lines.push("Sin texto");
if (Number.isFinite(maxLines) && lines.length > maxLines) {
const kept = lines.slice(0, maxLines);
kept[maxLines - 1] = `${kept[maxLines - 1].replace(/\.\.\.$/, "")}...`;
return kept;
}
return lines;
}
function nodeTextMaxChars(node) {
return node.shape === "text" ? 22 : 18;
}
function nodeMaxTextLines() {
return 20;
}
function getNodeSize(node) {
const base = shapeSize[node.shape] || shapeSize.process;
const lines = wrapTextLines(node.text, nodeTextMaxChars(node), nodeMaxTextLines());
const baseSize = node.shape === "text" ? 20 : 22;
const fontSize = Math.max(16, baseSize - Math.max(0, lines.length - 2) * 2);
const lineHeight = Math.round(fontSize * 1.18);
const ownerSpace = node.owner && node.shape !== "text" ? 34 : 0;
const padding = node.shape === "decision" ? 76 : node.shape === "text" ? 28 : 48;
return {
w: node.w || base.w,
h: Math.max(node.h || base.h, lines.length * lineHeight + ownerSpace + padding),
};
}
function addWrappedText(group, text, cx, cy, maxChars, className, options = {}) {
const maxLines = options.maxLines ?? nodeMaxTextLines();
const baseSize = options.fontSize || 22;
const minSize = options.minFontSize || 16;
const lineGap = options.lineGap || 1.18;
const lines = wrapTextLines(text, maxChars, maxLines);
const fontSize = Math.max(minSize, baseSize - Math.max(0, lines.length - 2) * 2);
const lineHeight = Math.round(fontSize * lineGap);
const firstY = cy - ((lines.length - 1) * lineHeight) / 2;
lines.forEach((line, index) => {
group.appendChild(createSvg("text", {
class: className,
x: cx,
y: firstY + index * lineHeight,
"dominant-baseline": "middle",
"font-size": fontSize,
"text-anchor": "middle",
})).textContent = line;
});
}
function render() {
renderHeader();
renderLanes();