-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
1473 lines (1267 loc) · 60.3 KB
/
index.ts
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
import { LitElementWw } from '@webwriter/lit';
import { html, css, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { v4 as uuidv4 } from 'uuid';
import { GraphNode } from './src/definitions/GraphNode';
import { Arrow } from './src/definitions/Arrow';
import { ItemList } from './src/definitions/ItemList';
import { drawButton } from './src/modules/drawer/drawButton';
import { drawGraphNode, drawNodeAnchors } from './src/modules/drawer/drawGraphNode';
import { drawArrow, drawTempArrow, generateArrowPoints, drawArrowAnchor } from './src/modules/drawer/drawArrow';
import { drawSelectionField } from './src/modules/drawer/drawSelectionField';
import {
handleNodeDragStart,
handleArrowDragStart,
handleMultipleNodesDragStart,
} from './src/modules/handler/mouseDownHandler';
import { handleGrabRelease, handleNodeDragStop, handleArrowCreation } from './src/modules/handler/mouseUpHandler';
import { handleSequenceSelection } from './src/modules/handler/handleSequenceSelection';
import { handleGraphNodeDoubleClick, handleArrowDoubleClick } from './src/modules/handler/doubleClickHandler';
import { toggleMenu } from './src/modules/ui/toggleMenu';
import { addHelp, renderHelpList } from './src/modules/ui/helpMenu';
import { addTask, renderTasks } from './src/modules/ui/taskMenu';
import {
createTooltip,
removeTooltip,
updateDisabledState,
grabCanvas,
autoDeleteEmptyItems,
} from './src/modules/ui/generalUI';
import {
snapNodePosition,
removeOldConnection,
isNodeInRectangle,
findLastGraphNode,
findGraphNodeLastIndex,
} from './src/modules/helper/utilities';
import { isArrowClicked } from './src/modules/helper/arrowHelper';
import { getAnchors, highlightAnchor } from './src/modules/helper/anchorHelper';
import { createArrowsFromGraphNodes, updatePresetIds } from './src/modules/helper/presetHelper';
import { flowchartPresets } from './src/modules/presets/flowchartPresets';
import { helpPresets } from './src/modules/presets/helpPresets';
import { papWidgetStyles } from './src/modules/styles/styles';
import { CustomPrompt } from './src/components/custom-prompt';
import './src/components/custom-prompt';
import { ConfirmPrompt } from './src/components/confirm-prompt';
import './src/components/confirm-prompt';
import { PropertyValueMap } from '@lit/reactive-element';
@customElement('webwriter-flowchart')
export class FlowchartWidget extends LitElementWw {
@property({ type: Array, reflect: true, attribute: true }) accessor graphNodes: GraphNode[] = [];
@property({ type: Object }) accessor selectedNode: GraphNode;
@property({ type: Array }) accessor arrows: Arrow[] = [];
@property({ type: Object }) accessor selectedArrow?: Arrow;
getGraphNodes = () => this.graphNodes;
getArrows = () => this.arrows;
@property({ type: Array, reflect: true, attribute: true }) accessor taskList: ItemList[] = [];
@property({ type: Array, reflect: true, attribute: true }) accessor helpList: ItemList[] = [];
@property({ type: Number, reflect: true, attribute: true }) accessor height: number = 400;
@property({ type: Number }) accessor currentHeight: number = this.height;
@property({ type: Array }) accessor presetList: { name: string; graphNodes: GraphNode[] }[] = flowchartPresets;
@property({ type: Object }) accessor graphSettings = { font: 'Courier New', fontSize: 16, theme: 'standard' };
@property({ type: Number, reflect: true, attribute: true }) accessor zoomLevel: number = 100; // in Prozent
private gridSize: number = 50;
private dotSize: number = 1.5;
@property({ type: Number, reflect: true, attribute: true }) accessor canvasOffsetX: number = 0;
@property({ type: Number, reflect: true, attribute: true }) accessor canvasOffsetY: number = 0;
@property({ type: Boolean, reflect: true, attribute: true }) accessor allowStudentEdit: boolean = false;
@property({ type: Boolean, reflect: true, attribute: true }) accessor alowStudentPan: boolean = false;
@property({ type: String, reflect: true, attribute: true }) accessor font = 'Courier New';
@property({ type: Number, reflect: true, attribute: true }) accessor fontSize = 16;
@property({ type: String, reflect: true, attribute: true }) accessor theme = 'standard';
@property({ type: Boolean }) accessor fullscreen = false;
static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };
private canvas: HTMLCanvasElement;
private ctx: CanvasRenderingContext2D;
private isDragging = false;
private draggedNode: GraphNode;
private dragOffset = { x: 0, y: 0 };
private draggedNodes: GraphNode[] = [];
private isDrawingArrow = false;
private arrowStart?: { node: GraphNode; anchor: number };
private tempArrowEnd?: { x: number; y: number };
private isGrabbing = false;
private grabStartPosition?: { x: number; y: number };
private grabStartOffset?: { x: number; y: number };
private hoveredAnchor?: { element: GraphNode; anchor: number };
private isArrowAnchorHovered: boolean;
private _isSelectingSequence = false;
private selectedSequence: { id: string; order: number; type: string }[] = [];
getSelectedSequence = () => this.selectedSequence;
private activeSequenceButton: HTMLButtonElement | null = null;
getActiveSequenceButton = () => this.activeSequenceButton;
setActiveSequenceButton = (btn: HTMLButtonElement | null) => {
this.activeSequenceButton = btn;
};
get isSelectingSequence() {
return this._isSelectingSequence;
}
set isSelectingSequence(value: boolean) {
const oldValue = this._isSelectingSequence;
this._isSelectingSequence = value;
if (oldValue !== value) {
//this.showSolutionMenu();
}
}
private promptType: 'node' | 'arrow' | null;
private promptIndex: number | null;
@property({ type: String }) accessor solutionMessage: string = '';
@property({ type: Boolean }) accessor showSolution: boolean = false;
@property({ type: Array }) accessor selectedNodes: GraphNode[] = [];
private selectionRectangle?: { x: number; y: number; width: number; height: number };
private checkOffset = true;
static style = papWidgetStyles;
public isEditable(): boolean {
return this.contentEditable === 'true' || this.contentEditable === '';
}
render() {
console.log('render', this);
return html`
<style>
${papWidgetStyles}
</style>
${this.isEditable() ? this.renderToolMenu() : ''}
<div class="workspace" @scroll="${this.handleScroll}">
<canvas
width="100%"
height="${this.currentHeight}"
@mousedown="${this.handleMouseDown}"
@mouseup="${this.handleMouseUp}"
@mousemove="${this.handleMouseMove}"
@dblclick="${this.handleDoubleClick}"
@click="${(event: MouseEvent) => {
this.handleClick(event);
this.toggleMenu('context');
}}"
@contextmenu="${(event: MouseEvent) => {
event.preventDefault();
this.showContextMenu(event);
}}"
@wheel="${this.handleWheel}"
></canvas>
<div class="action-menu" style=${this.fullscreen ? 'top:10px;left:10px;' : ''}>
<button
id="grab-button"
@mouseenter="${(e) => createTooltip(e, 'Bewegen des Canvas')}"
@mouseleave="${removeTooltip}"
@click="${this.grabCanvas}"
class="${this.isGrabbing ? 'active' : ''}"
style=${!this.alowStudentPan ? 'display:none' : ''}
>
${drawButton('grab', 'tool')}
</button>
<button
@mouseenter="${(e) => createTooltip(e, 'Aufgabenmenü')}"
@mouseleave="${removeTooltip}"
@click="${() => this.toggleMenu('task')}"
style=${!this.isEditable() && this.taskList?.length == 0 ? 'display:none' : ''}
>
${drawButton('task', 'tool')}
</button>
<button
@mouseenter="${(e) => createTooltip(e, 'Hinweise')}"
@mouseleave="${removeTooltip}"
@click="${() => this.toggleMenu('help')}"
style=${!this.isEditable() && this.helpList?.length == 0 ? 'display:none' : ''}
>
${drawButton('help', 'tool')}
</button>
<button
@mouseenter="${(e) => createTooltip(e, 'Lösche alles')}"
@mouseleave="${removeTooltip}"
@click="${this.showConfirmPrompt}"
style=${!this.allowStudentEdit ? 'display:none' : ''}
>
${drawButton('delete', 'tool')}
</button>
<button
@mouseenter="${(e) => createTooltip(e, 'Fullscreen')}"
@mouseleave="${removeTooltip}"
@click="${this.toggleFullscreen}"
class="fullscreen-button"
>
<svg xmlns="http://www.w3.org/2000/svg" height="16" width="14" viewBox="0 0 448 512">
<!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.-->
<path
d="M32 32C14.3 32 0 46.3 0 64v96c0 17.7 14.3 32 32 32s32-14.3 32-32V96h64c17.7 0 32-14.3 32-32s-14.3-32-32-32H32zM64 352c0-17.7-14.3-32-32-32s-32 14.3-32 32v96c0 17.7 14.3 32 32 32h96c17.7 0 32-14.3 32-32s-14.3-32-32-32H64V352zM320 32c-17.7 0-32 14.3-32 32s14.3 32 32 32h64v64c0 17.7 14.3 32 32 32s32-14.3 32-32V64c0-17.7-14.3-32-32-32H320zM448 352c0-17.7-14.3-32-32-32s-32 14.3-32 32v64H320c-17.7 0-32 14.3-32 32s14.3 32 32 32h96c17.7 0 32-14.3 32-32V352z"
/>
</svg>
</button>
</div>
<div class="flowchart-menu" style=${!this.allowStudentEdit ? 'display:none' : ''}>
<button class="close-button" @click="${() => this.toggleMenu('flow')}">×</button>
<button @click="${() => this.addGraphNode('start', 'Start')}">
${drawButton('start', 'flow')}
</button>
<button @click="${() => this.addGraphNode('op', 'Operation')}">${drawButton('op', 'flow')}</button>
<button @click="${() => this.addGraphNode('decision', ' Verzweigung ')}">
${drawButton('decision', 'flow')}
</button>
<button @click="${() => this.addGraphNode('i/o', 'Ein-/Ausgabe')}">
${drawButton('i/o', 'flow')}
</button>
<button @click="${() => this.addGraphNode('sub', 'Unterprogramm')}">
${drawButton('sub', 'flow')}
</button>
<button @click="${() => this.addGraphNode('connector', '')}">
${drawButton('connector', 'flow')}
</button>
<button @click="${() => this.addGraphNode('end', 'Ende')}">${drawButton('end', 'flow')}</button>
<button @click="${() => this.addGraphNode('text', 'Kommentar')}">
${drawButton('text', 'flow')}
</button>
</div>
<button class="show-flowchart-button hidden" @click="${() => this.toggleMenu('flow')}">+</button>
<div class="solution-menu hidden">
<div class="solution-titel">Pfad überprüfen</div>
${this.taskList?.map((task) =>
task.sequence
? html`<button class="solution-button" @click="${() => this.checkSolution(task)}">
${task.titel}
</button>`
: ''
)}
</div>
<div class="task-menu hidden" style=${this.fullscreen ? 'top:10px;right:10px;' : ''}>
<button class="close-button" @click="${() => this.toggleMenu('task')}">×</button>
<div class="task-menu-wrapper">
${this.taskList?.length === 0
? html`<p class="no-tasks-message">Keine Aufgaben!</p>`
: renderTasks.bind(this)(this.taskList)}
<button class="add-task-button editMode" @click="${this.addTask}">
${drawButton('addTask', 'task')}
</button>
</div>
</div>
<div class="help-menu hidden" style=${this.fullscreen ? 'top:10px;right:10px;' : ''}>
<button class="close-button" @click="${() => this.toggleMenu('help')}">×</button>
${this.helpList?.length === 0
? html`<p class="no-help-message">Keine Hinweise!</p>`
: renderHelpList.bind(this)(this.helpList)}
<button class="add-help-button editMode" @click="${this.addHelp}">
${drawButton('addHelp', 'help')}
</button>
</div>
<div class="translate-menu hidden">
<button class="close-button" @click="${() => this.toggleMenu('translate')}">×</button>
<div class="translate-menu-container">
<button class="translate-button" @click="${() => this.translateFlowchart('natural')}">
${drawButton('naturalLanguage', 'translate')}
</button>
<textarea id="naturalLanguageOutput" class="output-textarea hidden" disabled></textarea>
</div>
<div class="translate-menu-container">
<button class="translate-button" @click="${() => this.translateFlowchart('pseudo')}">
${drawButton('pseudoCode', 'translate')}
</button>
<textarea id="pseudoCodeOutput" class="output-textarea hidden" disabled></textarea>
</div>
</div>
<div id="context-menu" class="context-menu">
<div class="context-menu-item" @click="${() => this.deleteSelectedObject()}">Löschen</div>
</div>
<custom-prompt
label="Geben Sie einen neuen Text ein:"
@submit="${(event: CustomEvent) => this.handlePromptSubmit(event)}"
@cancel="${this.hidePrompt}"
class="hidden"
></custom-prompt>
<confirm-prompt
label="Sind Sie sicher, dass Sie alles löschen möchten?"
.onConfirm="${this.clearAll}"
.onCancel="${this.hidePrompt}"
class="hidden"
></confirm-prompt>
<div class="prompt ${this.showSolution ? '' : 'hidden'}">
<p>${this.solutionMessage}</p>
<button @click="${this.closeSolution}">Schließen</button>
</div>
</div>
<div
class="y-rezise"
@dragend="${this.handleYResizeEnd}"
draggable="true"
style=${!this.allowStudentEdit || this.fullscreen ? 'display:none' : ''}
></div>
`;
}
private renderToolMenu() {
return html`<aside class="tool-menu" part="options">
<h2>Einstellungen</h2>
<div class="setting-menu-container">
<div class="setting-item">
<label>Schriftart:</label>
<select id="font-selector"
@change="${(e) => {
this.font = e.target.value;
this.graphSettings.font = e.target.value;
this.redrawCanvas();
}}"
>
<option value="Arial">Arial</option>
<option value="Verdana">Verdana</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Courier New" selected>Courier New</option>
</select>
</div>
<div class="setting-item">
<label>Schriftgröße:</label>
<select id="font-size-selector"
@change="${(e) => {
this.fontSize = e.target.value;
this.graphSettings.fontSize = parseInt(e.target.value);
this.redrawCanvas();
}}"
>
<option value="12">12</option>
<option value="14">14</option>
<option value="16" selected>16</option>
<option value="18">18</option>
<option value="20">20</option>
<option value="22">22</option>
</select>
</div>
<div class="setting-item">
<label>Farbthema:</label>
<select id="color-theme-selector"
@change="${(e) => {
this.theme = e.target.value;
this.graphSettings.theme = e.target.value;
this.redrawCanvas();
}}"
>
<option value="standard" selected>Standard</option>
<option value="pastel">Pastel</option>
<option value="mono">Mono</option>
<option value="s/w">Schwarz/Weiß</option>
</select>
</div>
<div class="setting-item">
<label>Zoomen:</label>
<div class="zoom-selector">
<button id="zoom-out-button" class="zoom-button"
@click="${(e) => {
this.zoomLevel = Math.max(this.zoomLevel - 10, 50); // Begrenze den Zoom auf 50%
this.applyZoom();
}}"
>-</button>
<span id="zoom-percentage" class="zoom-text">${this.zoomLevel}%</span>
<button id="zoom-in-button" class="zoom-button"
@click="${(e) => {
this.zoomLevel = Math.min(this.zoomLevel + 10, 200); // Begrenze den Zoom auf 200%
this.applyZoom();
}}"
>+</button>
</div>
</div>
<div class="setting-item">
<label>Bearbeiten erlauben:</label>
<input
type="checkbox"
id="editable-checkbox"
@change="${(e) => {
this.allowStudentEdit = e.target.checked;
}}"
?checked="${this.allowStudentEdit}"
/>
</div>
<div class="setting-item">
<label>Bewegen erlauben:</label>
<input
type="checkbox"
id="panable-checkbox"
@change="${(e) => {
this.alowStudentPan = e.target.checked;
if (e.target.checked) {
this.canvasOffsetX = 0;
this.canvasOffsetY = 0;
} else {
this.canvasOffsetX = parseFloat(this.canvas.style.getPropertyValue('--offset-x'));
this.canvasOffsetY = parseFloat(this.canvas.style.getPropertyValue('--offset-y'));
}
}}"
?checked="${this.alowStudentPan}"
/>
</div>
<h2>Beispiele</h2>
<div class="preset-container">
<label>Beispiele:</label>
<button class="preset-button" @click="${() => this.showPreset('Erklärung')}">Erkärung</button>
<button class="preset-button" @click="${() => this.showPreset('Beispiel')}">Beispiel</button>
<button class="preset-button" @click="${() => this.showPreset('If/Else')}">If/Else</button>
<button class="preset-button" @click="${() => this.showPreset('For-Schleife')}">
For-Schleife
</button>
<button class="preset-button" @click="${() => this.showPreset('Switch')}">Switch</button>
</div>
</aside>`;
}
// ------------------------ User interface Funktionen ------------------------
// private getUserSettings() {
// const fontSelector = this.shadowRoot?.querySelector('#font-selector') as HTMLSelectElement;
// const fontSizeSelector = this.shadowRoot?.querySelector('#font-size-selector') as HTMLSelectElement;
// const themeSelector = this.shadowRoot?.querySelector('#color-theme-selector') as HTMLSelectElement;
// this.graphSettings.font = fontSelector.value;
// this.graphSettings.fontSize = parseInt(fontSizeSelector.value);
// this.graphSettings.theme = themeSelector.value;
// }
// Variante ohne Netlify
// private translateFlowchart(language: 'natural' | 'pseudo') {
// const messages = this.generateMessages(language);
// document.body.style.cursor = 'wait';
// fetch('https://api.openai.com/v1/chat/completions', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// 'Authorization': `Bearer `,
// },
// body: JSON.stringify({
// "model": "gpt-3.5-turbo",
// "messages": messages,
// "max_tokens": 2000,
// }),
// })
// .then(response => response.json())
// .then(data => {
// console.log(data)
// const text = data.choices[0].message['content'].trim();
// if (language === 'natural') {
// let textAreaElement = this.shadowRoot.getElementById('naturalLanguageOutput') as HTMLTextAreaElement;
// textAreaElement.value = text;
// textAreaElement.classList.remove('hidden');
// } else {
// let textAreaElement = this.shadowRoot.getElementById('pseudoCodeOutput') as HTMLTextAreaElement;
// textAreaElement.value = text;
// textAreaElement.classList.remove('hidden');
// }
// })
// .finally(() => {
// document.body.style.cursor = 'auto';
// });;
// }
private translateFlowchart(language: 'natural' | 'pseudo') {
const messages = this.generateMessages(language);
const translateButtons = this.shadowRoot.querySelectorAll('.translate-button');
translateButtons.forEach((button: HTMLElement) => (button.style.cursor = 'wait'));
document.body.style.cursor = 'wait';
fetch('/.netlify/functions/translateFlowchart', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: messages,
max_tokens: 2000,
}),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
if (language === 'natural') {
let textAreaElement = this.shadowRoot.getElementById(
'naturalLanguageOutput'
) as HTMLTextAreaElement;
textAreaElement.value = data.translation;
textAreaElement.classList.remove('hidden');
} else {
let textAreaElement = this.shadowRoot.getElementById('pseudoCodeOutput') as HTMLTextAreaElement;
textAreaElement.value = data.translation;
textAreaElement.classList.remove('hidden');
}
})
.finally(() => {
translateButtons.forEach((button: HTMLElement) => (button.style.cursor = 'pointer'));
document.body.style.cursor = 'auto';
});
}
private generateMessages(language: 'natural' | 'pseudo'): Array<{ role: string; content: string }> {
let systemMessage: string;
if (language === 'natural') {
systemMessage =
'Die folgenden Daten stellen ein Programmablaufplan dar. Beschreibe den Ablaufplan in einfachen natürlichen Worten.';
} else {
systemMessage =
'Die folgenden Daten stellen ein Programmablaufplan dar. Erzeuge aus den gegebenen Daten Pseudocode.';
}
let userMessage: string = '';
// Füge dem Prompt this.graphNodes hinzu
this.graphNodes.forEach((node) => {
userMessage += '\nID: ' + node.id;
userMessage += '\nNode: ' + node.node;
userMessage += '\nText: ' + node.text;
if (node.connections) {
userMessage += '\nConnections: ';
node.connections.forEach((connection) => {
userMessage += '\nAnchor: ' + connection.anchor;
userMessage += '\nDirection: ' + connection.direction;
userMessage += '\nConnected To ID: ' + connection.connectedToId;
if (connection.text) {
userMessage += '\nText: ' + connection.text;
}
});
}
userMessage += '\n';
});
return [
{
role: 'system',
content: systemMessage,
},
{
role: 'user',
content: userMessage,
},
];
}
selectSequence() {
// Setze css style von Icon auf aktiv
const selectButton = this.shadowRoot.getElementById('select-button');
!this.isSelectingSequence ? selectButton?.classList.add('active') : selectButton?.classList.remove('active');
this.isSelectingSequence = !this.isSelectingSequence;
if (!this.isSelectingSequence) {
this.selectedSequence = [];
}
// Deaktive alles ausgewählten Graphelemente
this.selectedNode = undefined;
this.selectedArrow = undefined;
this.selectionRectangle = undefined;
this.redrawCanvas();
}
checkSolution(task: ItemList) {
// Prüfe, ob die Längen der ausgewählten Sequenz und der Aufgabensequenz übereinstimmen
if (task.sequence && this.selectedSequence.length === task.sequence.length) {
for (let i = 0; i < this.selectedSequence.length; i++) {
// Prüfe, ob die IDs und der Typ jeder Sequenz übereinstimmen
if (
this.selectedSequence[i].id !== task.sequence[i].id ||
this.selectedSequence[i].type !== task.sequence[i].type
) {
this.showSolutionWithMessage('Der ausgewählte Pfad ist leider falsch!');
return;
}
}
this.showSolutionWithMessage('Der ausgewählte Pfad ist korrekt!');
} else {
this.showSolutionWithMessage('Der ausgewählte Pfad ist leider falsch!');
}
}
// Zeige oder verstecke die angefragten Benutzeroberflächen
private toggleMenu(menu: 'task' | 'flow' | 'context' | 'preset' | 'help' | 'translate' | 'setting') {
toggleMenu(this, menu);
this.focus();
}
// Zeige das Kontextmenü an, wenn ein Element angeklickt wurde
private showContextMenu(event: MouseEvent) {
if (!this.allowStudentEdit) {
return;
}
const { x, y } = this.getMouseCoordinates(event);
// Finde den angeklickten Knoten oder Verbindung und speichere sie
const clickedNode = findLastGraphNode(this.ctx, this.graphNodes, x, y);
const clickedArrowIndex = this.arrows.findIndex((arrow) => isArrowClicked(x, y, arrow.points));
// Falls ein Element angeklickt wurde, wird das Kontextmenü angezeigt
if (clickedNode || clickedArrowIndex !== -1) {
const contextMenu = this.shadowRoot.getElementById('context-menu');
if (contextMenu) {
contextMenu.style.display = 'block';
contextMenu.style.left = `${event.clientX}px`;
contextMenu.style.top = `${event.clientY}px`;
if (clickedNode) {
this.selectedNode = clickedNode;
this.selectedArrow = undefined;
} else {
this.selectedArrow = this.arrows[clickedArrowIndex];
this.selectedNode = undefined;
}
}
}
}
setSelectedSequence = (sequence: { id: string; order: number; type: string }[]) => {
this.selectedSequence = sequence;
};
private addTask() {
this.taskList = [...this.taskList, { titel: 'Titel', content: 'Aufgabe' }];
}
private addHelp() {
this.helpList = [...this.helpList, { titel: 'Titel', content: 'Hinweis' }];
}
private showSolutionMenu() {
const solutionMenuElement = this.shadowRoot?.querySelector('.solution-menu');
if (!solutionMenuElement) {
return;
}
// Prüfen, ob es eine Aufgabe mit einer Sequence gibt
const taskWithSequenceExists = this.taskList.some((task) => task.sequence?.length);
if (this.isSelectingSequence && taskWithSequenceExists && !this.isEditable()) {
solutionMenuElement.classList.remove('hidden');
} else {
solutionMenuElement.classList.add('hidden');
}
}
private showPreset(presetName: string) {
const preset = this.presetList.find((p) => p.name === presetName);
if (preset) {
const updatedPreset = updatePresetIds(preset.graphNodes);
this.graphNodes = [...this.graphNodes, ...updatedPreset];
this.arrows = createArrowsFromGraphNodes(this.arrows, this.graphNodes);
this.reconnectArrows();
this.redrawCanvas();
} else {
console.error(`Preset "${presetName}" nicht gefunden`);
}
}
// Aktiviere Bewegungsmodus für das Canvas
private grabCanvas() {
this.isGrabbing = grabCanvas(this, this.isGrabbing);
this.selectedNode = undefined;
}
// ------------------------ Reconnect Arrow Funktionen ------------------------
private reconnectArrows() {
this.arrows.forEach((arrow) => {
const fromId = arrow.from.id;
const toId = arrow.to.id;
const fromNode = this.graphNodes.find((node) => node.id === fromId);
const toNode = this.graphNodes.find((node) => node.id === toId);
if (fromNode && toNode) {
arrow.from = fromNode;
arrow.to = toNode;
}
});
}
// ------------------------ Drawer Funktionen ------------------------
private redrawCanvas() {
// Bereinige das Canvas und berücksichtigt den Zoom Faktor
const scaleFactor = this.zoomLevel / 100;
this.ctx.resetTransform();
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.scale(scaleFactor, scaleFactor);
// this.getUserSettings();
this.reconnectArrows();
// Zeichne alle Verbindungen
this.arrows.forEach((arrow) => {
const isSelected = arrow === this.selectedArrow;
arrow.points = generateArrowPoints(this.ctx, arrow);
drawArrow(this.ctx, arrow, this.graphSettings, isSelected, this.selectedSequence);
});
// Zeichne alle Knoten
this.graphNodes?.forEach((element) => {
drawGraphNode(this.ctx, element, this.graphSettings, this.selectedNodes, this.selectedSequence);
});
// Zeichne die Ankerpunkte für das ausgewählte Element, falls vorhanden
if (this.selectedNode) {
drawNodeAnchors(this.ctx, this.selectedNode, this.hoveredAnchor);
}
// Zeichne Ankerpunkte des Pfeils, wenn dieser ausgewählt ist
this.arrows.forEach((arrow) => {
const isSelected = arrow === this.selectedArrow;
if (isSelected) {
drawArrowAnchor(this.ctx, arrow, this.isArrowAnchorHovered, this.graphSettings);
}
});
//Zeichne eine temporäre Verbindung beim ziehen zwischen zwei Elementen, falls vorhanden
if (this.isDrawingArrow && this.arrowStart && this.tempArrowEnd) {
drawTempArrow(this.ctx, this.arrowStart, this.tempArrowEnd);
}
if (this.selectionRectangle) {
drawSelectionField(this.ctx, this.selectionRectangle);
}
// Speichere die aktuellen Knoten und Verbindungen als Attribute
// this.setAttribute('graph-nodes', JSON.stringify(this.graphNodes));
// this.setAttribute('task-list', JSON.stringify(this.taskList));
// this.setAttribute('help-list', JSON.stringify(this.helpList));
}
// Speichere die Position für den nächsten Knoten
private addGraphNodeIndex = 0;
private addGraphNode(
node: 'start' | 'end' | 'op' | 'decision' | 'connector' | 'i/o' | 'sub' | 'text',
text: string
) {
const workspace = this.shadowRoot?.querySelector('.workspace') as HTMLElement;
let centerX = this.canvas.width * 0.45 + workspace.scrollLeft;
let centerY = this.canvas.height * 0.45 + workspace.scrollTop;
switch (this.addGraphNodeIndex) {
case 0:
centerX += 0;
centerY += 0;
break;
case 1:
centerX -= 40;
centerY += 20;
break;
case 2:
centerX += 40;
centerY += 40;
break;
default:
centerX += 0;
centerY += 0;
}
const element: GraphNode = {
id: uuidv4(),
node: node,
text: text,
x: centerX,
y: centerY,
};
this.addGraphNodeIndex = (this.addGraphNodeIndex + 1) % 3;
this.graphNodes = [...this.graphNodes, element];
this.reconnectArrows();
drawGraphNode(this.ctx, element, this.graphSettings, this.selectedNodes, this.selectedSequence);
}
// ------------------------ Mouse-Events ------------------------
private handleMouseDown(event: MouseEvent) {
const { x, y } = this.getMouseCoordinates(event);
const nodeUnderCursor = findLastGraphNode(this.ctx, this.graphNodes, x, y);
if (!nodeUnderCursor || !this.selectedNodes.includes(nodeUnderCursor)) {
this.selectedNodes = [];
this.draggedNodes = [];
}
// Handhabung wenn Knoten gezogen wird
if (!this.isGrabbing) {
if (!this.allowStudentEdit) {
return;
}
if (this.selectedNodes.length > 1) {
const { draggedNodes, isDragging, dragOffset } = handleMultipleNodesDragStart(
this.ctx,
x,
y,
this.selectedNodes,
this.selectedArrow
);
this.draggedNodes = draggedNodes;
this.isDragging = isDragging;
this.dragOffset = dragOffset;
} else {
const { draggedNode, isDragging, dragOffset } = handleNodeDragStart(
this.ctx,
x,
y,
this.graphNodes,
this.selectedArrow
);
this.draggedNode = draggedNode;
this.isDragging = isDragging;
this.dragOffset = dragOffset;
}
}
if (this.isGrabbing) {
// Update Offset von Canvwas wenn dieser gezogen wird
this.grabStartPosition = { x, y };
const offsetX = parseFloat(this.canvas.style.getPropertyValue('--offset-x'));
const offsetY = parseFloat(this.canvas.style.getPropertyValue('--offset-y'));
this.grabStartOffset = { x: offsetX, y: offsetY };
} else {
// Wenn ein Pfeil gezogen wird, wird ein temporärer gestrichelter Pfeil gezeichnet
const { arrowToMove, arrowStart } = handleArrowDragStart(
this.ctx,
x,
y,
this.graphNodes,
this.selectedArrow,
this.handleAnchorClick.bind(this)
);
if (arrowToMove && arrowStart) {
this.arrowStart = arrowStart;
this.arrows = this.arrows.filter((arrow) => arrow !== arrowToMove);
}
}
if (!nodeUnderCursor && !this.isGrabbing && !this.selectedNode) {
if (!this.allowStudentEdit) {
return;
}
this.selectionRectangle = { x, y, width: 0, height: 0 };
}
}
private handleMouseUp(event: MouseEvent) {
if (this.selectionRectangle) {
this.selectionRectangle = undefined;
} else if (this.isGrabbing && this.grabStartPosition) {
// Setze die Grabposition des Canvas zurück, nachdem dieser gezogen wurde
const { grabStartPosition, grabStartOffset } = handleGrabRelease();
this.grabStartPosition = grabStartPosition;
this.grabStartOffset = grabStartOffset;
} else {
if (this.isDragging) {
// Füge diese Zeile hinzu, um die Knotenposition basierend auf dem Schwellenwert zu aktualisieren
if (this.selectedNodes.length === 0) {
snapNodePosition(this.ctx, this.draggedNode, this.graphNodes, 8);
}
// Setze die Informationen zurück, nachdem ein Knoten gezogen wurde
const { isDragging } = handleNodeDragStop();
this.isDragging = isDragging;
} else if (this.isDrawingArrow) {
// Erstelle ggf. die Pfeilverbindung, nachdem ein Pfeil losgelassen wurde
const { x, y } = this.getMouseCoordinates(event);
const { tempArrowEnd, arrowStart, arrows } = handleArrowCreation(
this.ctx,
x,
y,
this.arrowStart,
this.graphNodes,
this.arrows
);
this.tempArrowEnd = tempArrowEnd;
this.arrowStart = arrowStart;
this.arrows = arrows;
this.isDrawingArrow = false;
}
}
// Resette einmalige Schranke fürs draggen mehrerer Knoten
this.checkOffset = true;
this.graphNodes = [...this.graphNodes];
}
private handleMouseMove(event: MouseEvent) {
const { x, y } = this.getMouseCoordinates(event);
if (this.selectionRectangle) {
this.selectionRectangle.width = x - this.selectionRectangle.x;
this.selectionRectangle.height = y - this.selectionRectangle.y;
this.selectedNodes = this.graphNodes.filter((node) =>
isNodeInRectangle(this.ctx, node, this.selectionRectangle)
);
this.redrawCanvas();
} else if (this.isGrabbing && this.grabStartPosition && this.grabStartOffset) {
const deltaX = x - this.grabStartPosition.x;
const deltaY = y - this.grabStartPosition.y;
// Aktualisiere die Koordinaten der Knoten und Verbindungen
this.graphNodes.forEach((element) => {
element.x += deltaX;
element.y += deltaY;
});
this.arrows.forEach((arrow) => {
if (arrow.points) {
arrow.points.forEach((point) => {
point.x += deltaX;
point.y += deltaY;
});
}
});
// Aktualisiere das Canvas anhand der Mausbewegung
const offsetX = parseFloat(this.canvas.style.getPropertyValue('--offset-x'));
const offsetY = parseFloat(this.canvas.style.getPropertyValue('--offset-y'));
this.canvas.style.setProperty('--offset-x', `${offsetX + (deltaX * this.zoomLevel) / 100}px`);
this.canvas.style.setProperty('--offset-y', `${offsetY + (deltaY * this.zoomLevel) / 100}px`);
// Zeichne das aktualisierte Canvas
this.redrawCanvas();
// Aktualisiere die grabStartPosition auf die aktuelle Mausposition
this.grabStartPosition = { x, y };
} else {
if (this.isDragging && this.draggedNodes.length > 1) {
let deltaX: number;
let deltaY: number;
if (this.checkOffset) {
deltaX = this.dragOffset.x;
deltaY = this.dragOffset.y;
const nodeUnderCursor = findLastGraphNode(this.ctx, this.graphNodes, x, y);
this.draggedNodes.forEach((node) => {
node.x = node.x + deltaX + (nodeUnderCursor.x - x);
node.y = node.y + deltaY + (nodeUnderCursor.y - y);
});
this.checkOffset = false;
} else {
deltaX = x - this.dragOffset.x;
deltaY = y - this.dragOffset.y;
this.draggedNodes.forEach((node) => {
node.x += deltaX;
node.y += deltaY;
});
}
this.dragOffset = { x, y };
this.redrawCanvas();
} else if (this.isDragging && this.draggedNode) {
this.draggedNode.x = x - this.dragOffset.x;
this.draggedNode.y = y - this.dragOffset.y;
this.redrawCanvas();
} else if (this.isDrawingArrow && this.arrowStart && (this.selectedNode || this.selectedArrow)) {
const { x, y } = this.getMouseCoordinates(event);
this.tempArrowEnd = { x, y };