-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathRemoteFunctions.js
More file actions
4599 lines (3967 loc) · 181 KB
/
RemoteFunctions.js
File metadata and controls
4599 lines (3967 loc) · 181 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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2012 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/*jslint forin: true */
/*global Node, MessageEvent */
/*theseus instrument: false */
/**
* RemoteFunctions define the functions to be executed in the browser. This
* modules should define a single function that returns an object of all
* exported functions.
*/
function RemoteFunctions(config = {}) {
// this will store the element that was clicked previously (before the new click)
// we need this so that we can remove click styling from the previous element when a new element is clicked
let previouslyClickedElement = null;
var req, timeout;
var animateHighlight = function (time) {
if(req) {
window.cancelAnimationFrame(req);
window.clearTimeout(timeout);
}
req = window.requestAnimationFrame(redrawHighlights);
timeout = setTimeout(function () {
window.cancelAnimationFrame(req);
req = null;
}, time * 1000);
};
/**
* @type {DOMEditHandler}
*/
var _editHandler;
var HIGHLIGHT_CLASSNAME = "__brackets-ld-highlight";
// auto-scroll variables to auto scroll the live preview when an element is dragged to the top/bottom
let _autoScrollTimer = null;
let _isAutoScrolling = false; // to disable highlights when auto scrolling
const AUTO_SCROLL_SPEED = 12; // pixels per scroll
const AUTO_SCROLL_EDGE_SIZE = 0.05; // 5% of viewport height (either top/bottom)
// to track the state as we want to have a selected state for image gallery
let imageGallerySelected = false;
/**
* this function is responsible to auto scroll the live preview when
* dragging an element to the viewport edges
* @param {number} clientY - curr mouse Y position
*/
function _handleAutoScroll(clientY) {
const viewportHeight = window.innerHeight;
const scrollEdgeSize = viewportHeight * AUTO_SCROLL_EDGE_SIZE;
// Clear existing timer
if (_autoScrollTimer) {
clearInterval(_autoScrollTimer);
_autoScrollTimer = null;
}
let scrollDirection = 0;
// check if near top edge (scroll up)
if (clientY <= scrollEdgeSize) {
scrollDirection = -AUTO_SCROLL_SPEED;
} else if (clientY >= viewportHeight - scrollEdgeSize) {
// check if near bottom edge (scroll down)
scrollDirection = AUTO_SCROLL_SPEED;
}
// Start scrolling if needed
if (scrollDirection !== 0) {
_isAutoScrolling = true;
_autoScrollTimer = setInterval(() => {
window.scrollBy(0, scrollDirection);
}, 16); // 16 is ~60fps
}
}
// stop autoscrolling
function _stopAutoScroll() {
if (_autoScrollTimer) {
clearInterval(_autoScrollTimer);
_autoScrollTimer = null;
}
_isAutoScrolling = false;
}
// determine whether an event should be processed for Live Development
function _validEvent(event) {
if (window.navigator.platform.substr(0, 3) === "Mac") {
// Mac
return event.metaKey;
}
// Windows
return event.ctrlKey;
}
/**
* This is a checker function for editable elements, it makes sure that the element satisfies all the required checks
* - When onlyHighlight is false → config.isProUser must be true
* - When onlyHighlight is true → config.isProUser can be true or false (doesn't matter)
* @param {DOMElement} element
* @param {boolean} [onlyHighlight=false] - If true, bypasses the isProUser check
* @returns {boolean} - True if the element is editable else false
*/
function isElementEditable(element, onlyHighlight = false) {
if(!config.isProUser && !onlyHighlight) {
return false;
}
if(element && // element should exist
element.hasAttribute("data-brackets-id") && // should have the data-brackets-id attribute
element.tagName.toLowerCase() !== "body" && // shouldn't be the body tag
element.tagName.toLowerCase() !== "html" && // shouldn't be the HTML tag
!_isInsideHeadTag(element)) { // shouldn't be inside the head tag like meta tags and all
return true;
}
return false;
}
// helper function to check if an element is inside the HEAD tag
// we need this because we don't wanna trigger the element highlights on head tag and its children,
// except for <style> tags which should be allowed
function _isInsideHeadTag(element) {
let parent = element;
while (parent && parent !== window.document) {
if (parent.tagName.toLowerCase() === "head") {
// allow <style> tags inside <head>
return element.tagName.toLowerCase() !== "style";
}
parent = parent.parentElement;
}
return false;
}
// helper function to check if an element is inside an SVG tag
// we need this because SVG elements don't support contenteditable
function _isInsideSVGTag(element) {
let parent = element;
while (parent && parent !== window.document) {
if (parent.tagName.toLowerCase() === "svg") {
return true;
}
parent = parent.parentElement;
}
return false;
}
// compute the screen offset of an element
function _screenOffset(element) {
var elemBounds = element.getBoundingClientRect(),
body = window.document.body,
offsetTop,
offsetLeft;
if (window.getComputedStyle(body).position === "static") {
offsetLeft = elemBounds.left + window.pageXOffset;
offsetTop = elemBounds.top + window.pageYOffset;
} else {
var bodyBounds = body.getBoundingClientRect();
offsetLeft = elemBounds.left - bodyBounds.left;
offsetTop = elemBounds.top - bodyBounds.top;
}
return { left: offsetLeft, top: offsetTop };
}
// set an event on a element
function _trigger(element, name, value, autoRemove) {
var key = "data-ld-" + name;
if (value !== undefined && value !== null) {
element.setAttribute(key, value);
if (autoRemove) {
window.setTimeout(element.removeAttribute.bind(element, key));
}
} else {
element.removeAttribute(key);
}
}
// Checks if the element is in Viewport in the client browser
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var html = window.document.documentElement;
return (
rect.top >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight)
);
}
/**
* this function checks whether the image gallery overlaps the image element
* because if it does we scroll the image element a bit above so that users can see the whole image clearly
* @param {DOMElement} element - the image element
* @param {DOMElement} imageGalleryElement - the image gallery container
*/
function scrollImageToViewportIfRequired(element, imageGalleryElement) {
let elementRect = element.getBoundingClientRect();
let galleryRect = imageGalleryElement._shadow.querySelector('.phoenix-image-ribbon').getBoundingClientRect();
// this will get true when the image element and the image gallery overlaps each other
if (elementRect.bottom >= galleryRect.top) {
const scrollValue = window.scrollY + (elementRect.bottom - galleryRect.top) + 10;
window.scrollTo(0, scrollValue);
}
}
// Checks if an element is actually visible to the user (not hidden, collapsed, or off-screen)
function isElementVisible(element) {
// Check if element has zero dimensions (indicates it's hidden or collapsed)
const rect = element.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) {
return false;
}
// Check computed styles for visibility
const computedStyle = window.getComputedStyle(element);
if (computedStyle.display === 'none' ||
computedStyle.visibility === 'hidden' ||
computedStyle.opacity === '0') {
return false;
}
// Check if any parent element is hidden
let parent = element.parentElement;
while (parent && parent !== document.body) {
const parentStyle = window.getComputedStyle(parent);
if (parentStyle.display === 'none' ||
parentStyle.visibility === 'hidden') {
return false;
}
parent = parent.parentElement;
}
return true;
}
// returns the distance from the top of the closest relatively positioned parent element
function getDocumentOffsetTop(element) {
return element.offsetTop + (element.offsetParent ? getDocumentOffsetTop(element.offsetParent) : 0);
}
/**
* This function gets called when the AI button is clicked
* it shows a AI prompt box to the user
* @param {Event} event
* @param {DOMElement} element - the HTML DOM element that was clicked
*/
function _handleAIOptionClick(event, element) {
// make sure there is no existing AI prompt box, and no other box as well
dismissAllUIBoxes();
_aiPromptBox = new AIPromptBox(element); // create a new one
}
/**
* This function gets called when the image gallery button is clicked
* it shows the image ribbon gallery at the bottom of the live preview
* @param {Event} event
* @param {DOMElement} element - the HTML DOM element that was clicked (should be an image)
*/
function _handleImageGalleryOptionClick(event, element) {
dismissImageRibbonGallery();
if (imageGallerySelected) {
imageGallerySelected = false;
} else {
imageGallerySelected = true;
_imageRibbonGallery = new ImageRibbonGallery(element);
scrollImageToViewportIfRequired(element, _imageRibbonGallery);
}
}
/**
* This function gets called when the delete button is clicked
* it sends a message to the editor using postMessage to delete the element from the source code
* @param {Event} event
* @param {DOMElement} element - the HTML DOM element that was clicked. it is to get the data-brackets-id attribute
*/
function _handleDeleteOptionClick(event, element) {
if (isElementEditable(element)) {
const tagId = element.getAttribute("data-brackets-id");
window._Brackets_MessageBroker.send({
livePreviewEditEnabled: true,
element: element,
event: event,
tagId: Number(tagId),
delete: true
});
} else {
console.error("The TagID might be unavailable or the element tag is directly body or html");
}
}
/**
* this is for duplicate button. Read '_handleDeleteOptionClick' jsdoc to understand more on how this works
* @param {Event} event
* @param {DOMElement} element - the HTML DOM element that was clicked. it is to get the data-brackets-id attribute
*/
function _handleDuplicateOptionClick(event, element) {
if (isElementEditable(element)) {
const tagId = element.getAttribute("data-brackets-id");
window._Brackets_MessageBroker.send({
livePreviewEditEnabled: true,
element: element,
event: event,
tagId: Number(tagId),
duplicate: true
});
} else {
console.error("The TagID might be unavailable or the element tag is directly body or html");
}
}
/**
* this is for select-parent button
* When user clicks on this option for a particular element, we get its parent element and trigger a click on it
* @param {Event} event
* @param {DOMElement} element - the HTML DOM element that was clicked. it is to get the data-brackets-id attribute
*/
function _handleSelectParentOptionClick(event, element) {
if (!isElementEditable(element)) {
return;
}
const parentElement = element.parentElement;
if (isElementEditable(parentElement)) {
// Check if parent element has .click() method (HTML elements)
// SVG elements don't have .click() method, so we use _selectElement for them
if (typeof parentElement.click === 'function') {
parentElement.click();
} else {
activateHoverLock();
_selectElement(parentElement);
}
} else {
console.error("The TagID might be unavailable or the parent element tag is directly body or html");
}
}
/**
* This function will get triggered when from the multiple advance DOM buttons, one is clicked
* this function just checks which exact button was clicked and call the required function
* @param {Event} e
* @param {String} action - the data-action attribute to differentiate between buttons
* @param {DOMElement} element - the selected DOM element
*/
function handleOptionClick(e, action, element) {
if (action === "select-parent") {
_handleSelectParentOptionClick(e, element);
} else if (action === "edit-text") {
startEditing(element);
} else if (action === "duplicate") {
_handleDuplicateOptionClick(e, element);
} else if (action === "delete") {
_handleDeleteOptionClick(e, element);
} else if (action === "ai") {
_handleAIOptionClick(e, element);
} else if (action === "image-gallery") {
_handleImageGalleryOptionClick(e, element);
}
}
function _dragStartChores(element) {
element._originalDragOpacity = element.style.opacity;
element.style.opacity = 0.4;
}
function _dragEndChores(element) {
if (element._originalDragOpacity) {
element.style.opacity = element._originalDragOpacity;
} else {
element.style.opacity = 1;
}
delete element._originalDragOpacity;
}
// CSS class names for drop markers
let DROP_MARKER_CLASSNAME = "__brackets-drop-marker-horizontal";
let DROP_MARKER_VERTICAL_CLASSNAME = "__brackets-drop-marker-vertical";
let DROP_MARKER_INSIDE_CLASSNAME = "__brackets-drop-marker-inside";
let DROP_MARKER_ARROW_CLASSNAME = "__brackets-drop-marker-arrow";
/**
* This function is responsible to determine whether to show vertical/horizontal indicators
*
* @param {DOMElement} element - the target element
* @returns {String} 'vertical' or 'horizontal'
*/
function _getIndicatorType(element) {
// we need to check the parent element's property if its a flex container
const parent = element.parentElement;
if (!parent) {
return 'horizontal';
}
const parentStyle = window.getComputedStyle(parent);
const display = parentStyle.display;
const flexDirection = parentStyle.flexDirection;
if ((display === "flex" || display === "inline-flex") && flexDirection.startsWith("row")) {
return "vertical";
}
// default is horizontal
return 'horizontal';
}
/**
* this function is to determine if an element can accept children (inside drops)
*
* @param {DOMElement} element - The target element
* @returns {Boolean} true if element can accept children
*/
function _canAcceptChildren(element) {
// self-closing elements, cannot have children
const voidElements = [
"IMG",
"BR",
"HR",
"INPUT",
"META",
"LINK",
"AREA",
"BASE",
"COL",
"EMBED",
"SOURCE",
"TRACK",
"WBR"
];
// Elements that shouldn't accept visual children
const nonContainerElements = [
"SCRIPT", "STYLE", "NOSCRIPT", "CANVAS", "SVG", "VIDEO", "AUDIO", "IFRAME", "OBJECT"
];
const tagName = element.tagName.toUpperCase();
if (voidElements.includes(tagName) || nonContainerElements.includes(tagName)) {
return false;
}
return true;
}
/**
* it is to check if a source element can be placed inside a target element according to HTML rules
*
* @param {DOMElement} sourceElement - The element being dragged
* @param {DOMElement} targetElement - The target container element
* @returns {Boolean} true if the nesting is valid
*/
function _isValidNesting(sourceElement, targetElement) {
const sourceTag = sourceElement.tagName.toUpperCase();
const targetTag = targetElement.tagName.toUpperCase();
// block elements, cannot come inside inline elements
const blockElements = [
"DIV",
"P",
"H1",
"H2",
"H3",
"H4",
"H5",
"H6",
"SECTION",
"ARTICLE",
"HEADER",
"FOOTER",
"NAV",
"ASIDE",
"MAIN",
"BLOCKQUOTE",
"PRE",
"TABLE",
"UL",
"OL",
"LI",
"DL",
"DT",
"DD",
"FORM",
"FIELDSET",
"ADDRESS",
"FIGURE",
"FIGCAPTION",
"DETAILS",
"SUMMARY"
];
// inline elements that can't contain block elements
const inlineElements = [
"SPAN",
"A",
"STRONG",
"EM",
"B",
"I",
"U",
"SMALL",
"CODE",
"KBD",
"SAMP",
"VAR",
"SUB",
"SUP",
"MARK",
"DEL",
"INS",
"Q",
"CITE",
"ABBR",
"TIME",
"DATA",
"OUTPUT"
];
// interactive elements that can't be nested inside each other
const interactiveElements = [
"A",
"BUTTON",
"INPUT",
"SELECT",
"TEXTAREA",
"LABEL",
"DETAILS",
"SUMMARY",
"AUDIO",
"VIDEO",
"EMBED",
"IFRAME",
"OBJECT"
];
// Sectioning content - semantic HTML5 sections
const sectioningContent = ["ARTICLE", "ASIDE", "NAV", "SECTION"];
// Elements that can't contain themselves (prevent nesting)
const noSelfNesting = [
"P",
"A",
"BUTTON",
"LABEL",
"FORM",
"HEADER",
"FOOTER",
"NAV",
"MAIN",
"ASIDE",
"SECTION",
"ARTICLE",
"ADDRESS",
"H1",
"H2",
"H3",
"H4",
"H5",
"H6",
"FIGURE",
"FIGCAPTION",
"DETAILS",
"SUMMARY"
];
// Special cases - elements that have specific content restrictions
const restrictedContainers = {
// List elements
UL: ["LI"],
OL: ["LI"],
DL: ["DT", "DD"],
// Table elements
TABLE: ["THEAD", "TBODY", "TFOOT", "TR", "CAPTION", "COLGROUP"],
THEAD: ["TR"],
TBODY: ["TR"],
TFOOT: ["TR"],
TR: ["TD", "TH"],
COLGROUP: ["COL"],
// Form elements
SELECT: ["OPTION", "OPTGROUP"],
OPTGROUP: ["OPTION"],
DATALIST: ["OPTION"],
// Media elements
PICTURE: ["SOURCE", "IMG"],
AUDIO: ["SOURCE", "TRACK"],
VIDEO: ["SOURCE", "TRACK"],
// Other specific containers
FIGURE: ["FIGCAPTION", "DIV", "P", "IMG", "CANVAS", "SVG", "TABLE", "PRE", "CODE"],
DETAILS: ["SUMMARY"] // SUMMARY should be the first child
};
// 1. Check self-nesting (elements that can't contain themselves)
if (noSelfNesting.includes(sourceTag) && sourceTag === targetTag) {
return false;
}
// 2. Check block elements inside inline elements
if (blockElements.includes(sourceTag) && inlineElements.includes(targetTag)) {
return false;
}
// 3. Check restricted containers (strict parent-child relationships)
if (restrictedContainers[targetTag]) {
return restrictedContainers[targetTag].includes(sourceTag);
}
// 4. Special case: P tags can't contain block elements (phrasing content only)
if (targetTag === "P" && blockElements.includes(sourceTag)) {
return false;
}
// 5. Interactive elements can't contain other interactive elements
if (interactiveElements.includes(targetTag) && interactiveElements.includes(sourceTag)) {
return false;
}
// 6. Semantic HTML5 sectioning rules
if (targetTag === "HEADER") {
// Header can't contain other headers, footers, or main
if (["HEADER", "FOOTER", "MAIN"].includes(sourceTag)) {
return false;
}
}
if (targetTag === "FOOTER") {
// Footer can't contain headers, footers, or main
if (["HEADER", "FOOTER", "MAIN"].includes(sourceTag)) {
return false;
}
}
if (targetTag === "MAIN") {
// Main can't contain other mains
if (sourceTag === "MAIN") {
return false;
}
}
if (targetTag === "ADDRESS") {
// Address can't contain sectioning content, headers, footers, or address
if (sectioningContent.includes(sourceTag) || ["HEADER", "FOOTER", "ADDRESS", "MAIN"].includes(sourceTag)) {
return false;
}
}
// 7. Form-related validation
if (targetTag === "FORM") {
// Form can't contain other forms
if (sourceTag === "FORM") {
return false;
}
}
if (targetTag === "FIELDSET") {
// Fieldset should have legend as first child (but we'll allow it anywhere for flexibility)
// No specific restrictions beyond normal content
}
if (targetTag === "LABEL") {
// Label can't contain other labels or form controls (except one input)
if (["LABEL", "BUTTON", "SELECT", "TEXTAREA"].includes(sourceTag)) {
return false;
}
}
// 8. Heading hierarchy validation (optional - can be strict or flexible)
if (["H1", "H2", "H3", "H4", "H5", "H6"].includes(targetTag)) {
// Headings can't contain block elements (should only contain phrasing content)
if (blockElements.includes(sourceTag)) {
return false;
}
}
// 9. List item specific rules
if (sourceTag === "LI") {
// LI can only be inside UL, OL, or MENU
if (!["UL", "OL", "MENU"].includes(targetTag)) {
return false;
}
}
if (["DT", "DD"].includes(sourceTag)) {
// DT and DD can only be inside DL
if (targetTag !== "DL") {
return false;
}
}
// 10. Table-related validation
if (["THEAD", "TBODY", "TFOOT"].includes(sourceTag)) {
if (targetTag !== "TABLE") {
return false;
}
}
if (sourceTag === "TR") {
if (!["TABLE", "THEAD", "TBODY", "TFOOT"].includes(targetTag)) {
return false;
}
}
if (["TD", "TH"].includes(sourceTag)) {
if (targetTag !== "TR") {
return false;
}
}
if (sourceTag === "CAPTION") {
if (targetTag !== "TABLE") {
return false;
}
}
// 11. Media and embedded content
if (["SOURCE", "TRACK"].includes(sourceTag)) {
if (!["AUDIO", "VIDEO", "PICTURE"].includes(targetTag)) {
return false;
}
}
// 12. Ruby annotation elements (if supported)
if (["RP", "RT"].includes(sourceTag)) {
if (targetTag !== "RUBY") {
return false;
}
}
// 13. Option elements
if (sourceTag === "OPTION") {
if (!["SELECT", "OPTGROUP", "DATALIST"].includes(targetTag)) {
return false;
}
}
return true;
}
/**
* this function determines the drop zone based on cursor position relative to element
*
* @param {DOMElement} element - The target element
* @param {Number} clientX - x pos
* @param {Number} clientY - y pos
* @param {String} indicatorType - 'vertical' or 'horizontal'
* @param {DOMElement} sourceElement - The element being dragged (for validation)
* @returns {String} 'before', 'inside', or 'after'
*/
function _getDropZone(element, clientX, clientY, indicatorType, sourceElement) {
const rect = element.getBoundingClientRect();
const canAcceptChildren = _canAcceptChildren(element);
const isValidNesting = sourceElement ? _isValidNesting(sourceElement, element) : true;
if (indicatorType === "vertical") {
const leftThird = rect.left + rect.width * 0.3;
const rightThird = rect.right - rect.width * 0.3;
if (clientX < leftThird) {
return "before";
} else if (clientX > rightThird) {
return "after";
} else if (canAcceptChildren && isValidNesting) {
return "inside";
}
// If can't accept children or invalid nesting, use middle as "after"
return clientX < rect.left + rect.width / 2 ? "before" : "after";
}
const topThird = rect.top + rect.height * 0.3;
const bottomThird = rect.bottom - rect.height * 0.3;
if (clientY < topThird) {
return "before";
} else if (clientY > bottomThird) {
return "after";
} else if (canAcceptChildren && isValidNesting) {
return "inside";
}
// If can't accept children or invalid nesting, use middle as "after"
return clientY < rect.top + rect.height / 2 ? "before" : "after";
}
/**
* this is to create a marker to indicate a valid drop position
*
* @param {DOMElement} element - The element where the drop is possible
* @param {String} dropZone - 'before', 'inside', or 'after'
* @param {String} indicatorType - 'vertical' or 'horizontal'
*/
function _createDropMarker(element, dropZone, indicatorType = "horizontal") {
// clean any existing marker from that element
_removeDropMarkerFromElement(element);
if (element._originalDragBackgroundColor === undefined) {
element._originalDragBackgroundColor = element.style.backgroundColor;
}
element.style.backgroundColor = "rgba(66, 133, 244, 0.22)";
// create the marker element
let marker = window.document.createElement("div");
// Set marker class based on drop zone
if (dropZone === "inside") {
marker.className = DROP_MARKER_INSIDE_CLASSNAME;
} else {
marker.className = indicatorType === "vertical" ? DROP_MARKER_VERTICAL_CLASSNAME : DROP_MARKER_CLASSNAME;
}
let rect = element.getBoundingClientRect();
marker.style.position = "fixed";
marker.style.zIndex = "2147483647";
marker.style.borderRadius = "2px";
marker.style.pointerEvents = "none";
// for the arrow indicator
let arrow = window.document.createElement("div");
arrow.className = DROP_MARKER_ARROW_CLASSNAME;
arrow.style.position = "fixed";
arrow.style.zIndex = "2147483648";
arrow.style.pointerEvents = "none";
arrow.style.fontWeight = "bold";
arrow.style.color = "#4285F4";
if (dropZone === "inside") {
// inside marker - outline around the element
marker.style.border = "2px dashed #4285F4";
marker.style.backgroundColor = "rgba(66, 133, 244, 0.05)";
marker.style.left = rect.left + "px";
marker.style.top = rect.top + "px";
marker.style.width = rect.width + "px";
marker.style.height = rect.height + "px";
// exclusive or symbol (plus inside circle) we use when dropping inside
arrow.style.fontSize = "16px";
arrow.innerHTML = "⊕";
arrow.style.left = (rect.left + rect.width / 2) + "px";
arrow.style.top = (rect.top + rect.height / 2) + "px";
arrow.style.transform = "translate(-50%, -50%)";
} else {
// Before/After markers - lines
marker.style.background = "linear-gradient(90deg, #4285F4, #1976D2)";
marker.style.boxShadow = "0 0 8px rgba(66, 133, 244, 0.5)";
arrow.style.fontSize = "22px";
if (indicatorType === "vertical") {
// Vertical marker (for flex row containers)
marker.style.width = "3px";
marker.style.height = rect.height + "px";
marker.style.top = rect.top + "px";
arrow.style.top = (rect.top + rect.height / 2) + "px";
if (dropZone === "after") {
marker.style.left = rect.right + 3 + "px";
// Right arrow
arrow.innerHTML = "→";
arrow.style.left = (rect.right + 5) + "px";
arrow.style.transform = "translateY(-50%)";
} else {
marker.style.left = rect.left - 5 + "px";
// Left arrow
arrow.innerHTML = "←";
arrow.style.left = (rect.left - 15) + "px";
arrow.style.transform = "translate(-50%, -50%)";
}
} else {
// Horizontal marker (for block/grid containers)
marker.style.width = rect.width + "px";
marker.style.height = "3px";
marker.style.left = rect.left + "px";
arrow.style.left = (rect.left + rect.width / 2) + "px";
if (dropZone === "after") {
marker.style.top = rect.bottom + 3 + "px";
// Down arrow
arrow.innerHTML = "↓";
arrow.style.top = rect.bottom + "px";
arrow.style.transform = "translateX(-50%)";
} else {
marker.style.top = rect.top - 5 + "px";
// Up arrow
arrow.innerHTML = "↑";
arrow.style.top = (rect.top - 15) + "px";
arrow.style.transform = "translate(-50%, -50%)";
}
}
}
element._dropMarker = marker; // we need this in the _removeDropMarkerFromElement function
element._dropArrow = arrow; // store arrow reference too
window.document.body.appendChild(marker);
window.document.body.appendChild(arrow);
}
/**
* This function removes a drop marker from a specific element
* @param {DOMElement} element - The element to remove the marker from
*/
function _removeDropMarkerFromElement(element) {
if (element._dropMarker && element._dropMarker.parentNode) {
element._dropMarker.parentNode.removeChild(element._dropMarker);
delete element._dropMarker;
}
if (element._dropArrow && element._dropArrow.parentNode) {
element._dropArrow.parentNode.removeChild(element._dropArrow);
delete element._dropArrow;
}
}
/**
* this function is to clear all the drop markers from the document
*/
function _clearDropMarkers() {
// Clear all types of markers
let horizontalMarkers = window.document.querySelectorAll("." + DROP_MARKER_CLASSNAME);
let verticalMarkers = window.document.querySelectorAll("." + DROP_MARKER_VERTICAL_CLASSNAME);
let insideMarkers = window.document.querySelectorAll("." + DROP_MARKER_INSIDE_CLASSNAME);
let arrows = window.document.querySelectorAll("." + DROP_MARKER_ARROW_CLASSNAME);
for (let i = 0; i < horizontalMarkers.length; i++) {
if (horizontalMarkers[i].parentNode) {
horizontalMarkers[i].parentNode.removeChild(horizontalMarkers[i]);
}
}
for (let i = 0; i < verticalMarkers.length; i++) {
if (verticalMarkers[i].parentNode) {
verticalMarkers[i].parentNode.removeChild(verticalMarkers[i]);
}
}
for (let i = 0; i < insideMarkers.length; i++) {
if (insideMarkers[i].parentNode) {
insideMarkers[i].parentNode.removeChild(insideMarkers[i]);
}
}
for (let i = 0; i < arrows.length; i++) {
if (arrows[i].parentNode) {
arrows[i].parentNode.removeChild(arrows[i]);
}
}
// Also clear any element references
let elements = window.document.querySelectorAll("[data-brackets-id]");
for (let j = 0; j < elements.length; j++) {
delete elements[j]._dropMarker;
delete elements[j]._dropArrow;
// only restore the styles that were modified by drag operations
if (elements[j]._originalDragBackgroundColor !== undefined) {
elements[j].style.backgroundColor = elements[j]._originalDragBackgroundColor;
delete elements[j]._originalDragBackgroundColor;
}
if (elements[j]._originalDragTransform !== undefined) {
elements[j].style.transform = elements[j]._originalDragTransform;
delete elements[j]._originalDragTransform;
}
if (elements[j]._originalDragTransition !== undefined) {
elements[j].style.transition = elements[j]._originalDragTransition;
delete elements[j]._originalDragTransition;
}
}
}
/**
* this function is for finding the best target element on where to drop the dragged element
* for ex: div > image...here both the div and image are of the exact same size, then when user is dragging some
* other element, then almost everytime they want to drop it before/after the div and not like div>newEle+img
* @param {Element} target - The current target element
* @returns {Element|null} - The outermost parent with all edges aligned, or null
*/
function _findBestParentTarget(target) {
if (!target) {
return null;
}