summary refs log tree commit diff stats
path: root/compiler/passes.nim
Commit message (Collapse)AuthorAgeFilesLines
* GC: get rid of pathological behaviour for stack markingAraq2015-03-081-49/+49
|
* Make reading from stdin work again.def2015-03-011-1/+1
| | | | Bootstrapping tested on Linux from csources.
* bootstrapping works again on WindowsAraq2015-03-011-1/+1
|
* When compiling from stdin write binary to stdinfiledef2015-02-281-1/+1
|
* Rename stdin fake module name to stdinFiledef2015-02-281-1/+1
|
* Make compiler read files from stdindef2015-02-221-1/+5
| | | | Special "-" file as stdin.
* nimsuggest: sane dirty buffer handlingAraq2015-01-291-1/+1
|
* nimsuggest: first versionAraq2015-01-271-1/+1
|
* Nimrod renamed to NimAraq2014-08-281-1/+1
|
* renamefestAraq2014-08-231-1/+1
|
* removed flawed thread analysis passAraq2014-04-201-2/+3
|
* case consistency part 4Araq2013-12-271-4/+4
|
* Removes executable bit for text files.Grzegorz Adam Hankiewicz2013-03-161-0/+0
|
* fixed a regression: compiling projects not residing in the current directoryZahary Karadjov2013-01-201-1/+1
|
* CaaS in-memory cachingZahary Karadjov2012-11-281-23/+21
| | | | | removed some redundant filepath params and variables and switched to canonical paths in most places
* caas is now drivable through stdinZahary Karadjov2012-11-281-17/+41
| | | | | * added idetools --eval * streams.readLine recognises and applies the backspace character
* cas improvementsAraq2012-10-241-4/+7
|
* first steps towards term rewriting macrosAraq2012-08-301-14/+1
|
* preparations for making 'closure' the default calling convention for proc typesAraq2012-07-161-6/+6
|
* year 2012 for most copyright headersAraq2012-01-021-1/+1
|
* thoughts about implicit includes and importsAraq2011-11-291-11/+16
|
* New algorithm for locating and loading nimrod config files.Zahary Karadjov2011-11-251-0/+14
| | | | Some new options added to the compiler (see news.txt for details)
* bugfixes for ROD file generation; nimcache dir is now flatAraq2011-10-201-4/+22
|
* much more efficient rod file generationAraq2011-10-181-1/+1
|
* further improvements for thread analysisAraq2011-06-131-4/+4
|
* got rid of some arcane module namesAraq2011-04-211-2/+2
|
* big repo cleanupAraq2011-04-121-0/+155
475'>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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Folders in Folders in Folders</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: beige;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        #navigation {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            margin: 0.625em 0;
        }
        #navigation button {
            margin: 0.3125em;
            padding: 0.625em 0.9375em;
            font-size: 1em;
            flex-grow: 1;
            min-width: 7.5em;
        }
        #currentPath {
            font-weight: bold;
            margin: 0.625em 0;
        }
        ul {
            list-style-type: none;
            width: 100%;
            max-width: 37.5em;
        }
        li {
            margin: 0.3125em 0;
            cursor: pointer;
        }
        .folder {
            display: flex;
            align-items: center;
            padding: 0.5em;
            margin: 0;
            border-radius: 0;
            transition: background-color 0.2s;
            width: 100%;
            padding-left: 2em;
        }
        .folder:hover {
            background-color: rgba(0, 0, 0, 0.05);
        }
        .folder.dragging {
            opacity: 0.5;
        }
        .folder.drag-over {
            background-color: rgba(0, 120, 250, 0.1);
            border: 2px dashed #0078fa;
        }
        .folder::before {
            content: "📁";
            margin-right: 0.5em;
            margin-left: -1.5em;
        }
        ul {
            padding-left: 1.5em;
            border-left: 1px solid #e0e0e0;
            margin: 0;
            width: calc(100% - 1.5em);
        }
        li {
            margin: 0;
            padding: 0;
            width: 100%;
        }
        #editor {
            margin-top: 1.25em;
            width: 100%;
            max-width: 37.5em;
            cursor: move;
            min-width: 200px;
            min-height: 150px;
            resize: both;
            overflow: auto;
        }
        #editor textarea {
            width: 100%;
            height: calc(100% - 3em);
            font-size: 1em;
            padding: 0.625em;
            box-sizing: border-box;
            resize: none;
            margin-bottom: 0;
        }
        h1 {
            text-align: center;
            font-size: 1.5em;
            margin-top: 0.625em;
        }
        @media (max-width: 37.5em) {
            h1 {
                font-size: 1.25em;
            }
            #navigation button {
                font-size: 0.875em;
                padding: 0.5em 0.625em;
            }
            .folder {
                font-size: 1em;
            }
            #editor textarea {
                height: 7.5em;
                font-size: 0.875em;
            }
        }
        #navigation {
            display: none; /* Hide the button navigation by default */
        }

        .context-menu {
            position: fixed;
            background: white;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-shadow: 2px 2px 5px rgba(0,0,0,0.2);
            padding: 0.5em 0;
            min-width: 150px;
            z-index: 1000;
            display: none;
        }

        .context-menu.active {
            display: block;
        }

        .context-menu-item {
            padding: 0.5em 1em;
            cursor: pointer;
            display: flex;
            align-items: center;
        }

        .context-menu-item:hover {
            background-color: #f0f0f0;
        }

        .context-menu-item::before {
            margin-right: 0.5em;
        }

        .context-menu-item.new-folder::before {
            content: "📁";
        }

        .context-menu-item.rename::before {
            content: "✏️";
        }

        .context-menu-item.copy::before {
            content: "📋";
        }

        .context-menu-item.paste::before {
            content: "📥";
        }

        .context-menu-item.delete::before {
            content: "🗑️";
        }

        #editor {
            display: none; /* Hide editor by default */
            position: fixed;
            right: 20px;
            top: 20px;
            background: white;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 1em;
            box-shadow: 2px 2px 5px rgba(0,0,0,0.2);
        }

        .folder.selected {
            background-color: rgba(0, 120, 250, 0.1);
        }

        #fileSystemContainer {
            width: 100%;
            max-width: 37.5em;
            min-height: 300px;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 1em;
            margin-top: 1em;
            box-sizing: border-box;
            overflow: hidden;
        }

        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 200px;
            color: #666;
            text-align: center;
        }

        .empty-state::before {
            content: "📁";
            font-size: 3em;
            margin-bottom: 0.5em;
            opacity: 0.5;
        }

        .empty-state-text {
            font-size: 1.1em;
            margin-bottom: 1em;
        }

        .root-folder {
            padding: 0.5em;
            padding-left: 2em;
            margin: 0;
            width: 100%;
            border-radius: 0;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .root-folder:hover {
            background-color: rgba(0, 0, 0, 0.05);
        }

        .root-folder.selected {
            background-color: rgba(0, 120, 250, 0.1);
        }

        #editorHeader {
            padding: 0.5em;
            background-color: #f5f5f5;
            border-bottom: 1px solid #ccc;
            margin: -1em -1em 1em -1em;
            border-radius: 4px 4px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 0.5em;
        }

        #editorHeader h2 {
            margin: 0;
            font-size: 1.1em;
        }

        .editor-controls {
            display: flex;
            gap: 0.3em;
        }

        .editor-button {
            cursor: pointer;
            padding: 0.2em 0.5em;
            border-radius: 3px;
            font-size: 0.9em;
            color: #666;
        }

        .editor-button:hover {
            background-color: #e0e0e0;
        }

        .resize-handle {
            position: absolute;
            width: 10px;
            height: 10px;
            background-color: #f5f5f5;
            border: 1px solid #ccc;
        }

        .resize-handle.se {
            right: 0;
            bottom: 0;
            cursor: se-resize;
        }

        .resize-handle.sw {
            left: 0;
            bottom: 0;
            cursor: sw-resize;
        }

        .resize-handle.ne {
            right: 0;
            top: 0;
            cursor: ne-resize;
        }

        .resize-handle.nw {
            left: 0;
            top: 0;
            cursor: nw-resize;
        }

        .resize-handle:hover {
            background-color: #e0e0e0;
        }

        /* Update the inchworm styles */
        .inchworm {
            position: absolute;
            top: -16px;
            left: 0;
            font-size: 22px;
            animation: inch 18s infinite linear;
            transform-origin: center;
            color: green;
        }

        @keyframes inch {
            /* Forward */
            0% { 
                left: 0; 
                transform: scaleX(1) scaleY(1);
            }
            5% { 
                left: 0; 
                transform: scaleX(0.4) scaleY(1.4);
            }
            10% { 
                left: 30px; 
                transform: scaleX(1.3) scaleY(0.7);
            }
            15% { 
                left: 30px; 
                transform: scaleX(0.4) scaleY(1.4);
            }
            20% { 
                left: 60px; 
                transform: scaleX(1.3) scaleY(0.7);
            }
            25% { 
                left: 60px; 
                transform: scaleX(0.4) scaleY(1.4);
            }
            30% { 
                left: 90px; 
                transform: scaleX(1.3) scaleY(0.7);
            }
            35% { 
                left: 90px; 
                transform: scaleX(0.4) scaleY(1.4);
            }
            40% { 
                left: 120px; 
                transform: scaleX(1.3) scaleY(0.7);
            }
            
            /* Rest */
            42% { 
                left: 120px; 
                transform: scaleX(1) scaleY(1);
            }
            
            /* Backwards */
            45% { 
                left: 120px; 
                transform: scaleX(0.4) scaleY(1.4);
            }
            50% { 
                left: 90px; 
                transform: scaleX(1.3) scaleY(0.7);
            }
            55% { 
                left: 90px; 
                transform: scaleX(0.4) scaleY(1.4);
            }
            60% { 
                left: 60px; 
                transform: scaleX(1.3) scaleY(0.7);
            }
            65% { 
                left: 60px; 
                transform: scaleX(0.4) scaleY(1.4);
            }
            70% { 
                left: 30px; 
                transform: scaleX(1.3) scaleY(0.7);
            }
            75% { 
                left: 30px; 
                transform: scaleX(0.4) scaleY(1.4);
            }
            80% { 
                left: 0; 
                transform: scaleX(1.3) scaleY(0.7);
            }
            
            /* Rest */
            85% { 
                left: 0; 
                transform: scaleX(1) scaleY(1);
            }
            100% { 
                left: 0; 
                transform: scaleX(1) scaleY(1);
            }
        }

        .folder.editing {
            padding: 0;
            margin: 0;
        }

        .folder.editing input {
            font-size: 1em;
            padding: 0.5em;
            margin: 0.25em 0;
            width: calc(100% - 2em);
            border: 1px solid #ccc;
            border-radius: 4px;
            outline: none;
        }

        .folder.editing input:focus {
            border-color: #0078fa;
        }

        #viewControls {
            position: absolute;
            top: 1em;
            right: 1em;
        }

        .view-toggle {
            padding: 0.5em;
            border: 1px solid #ccc;
            border-radius: 4px;
            background: white;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .view-toggle:hover {
            background-color: #f0f0f0;
        }

        #breadcrumbs {
            padding: 0.5em 1em;
            margin: 0;
            border-bottom: 1px solid #e0e0e0;
            display: none;
            text-align: left;
            background-color: #f8f8f8;
            border-radius: 4px 4px 0 0;
            white-space: normal;
            word-break: keep-all;
            line-height: 1.8;
        }

        .breadcrumb-item {
            display: inline-block;
            cursor: pointer;
            padding: 0.2em 0.5em;
            border-radius: 3px;
            color: #666;
            white-space: nowrap;
        }

        .breadcrumb-item:hover {
            background-color: rgba(0, 0, 0, 0.05);
            color: #000;
        }

        .breadcrumb-separator {
            margin: 0 0.2em;
            color: #999;
            user-select: none;
            display: inline-block;
        }

        /* Grid view styles */
        .grid-view {
            display: none;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 1em;
            padding: 1em;
        }

        .grid-folder {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 1em;
            cursor: pointer;
            border-radius: 4px;
            text-align: center;
        }

        .grid-folder:hover {
            background-color: rgba(0, 0, 0, 0.05);
        }

        .grid-folder-icon {
            font-size: 2em;
            margin-bottom: 0.5em;
        }

        .grid-folder-name {
            font-size: 0.9em;
            word-break: break-word;
            max-width: 100%;
        }

        #fileSystemContainer {
            display: flex;
            flex-direction: column;
        }

        .grid-view {
            padding-top: 0;
        }
    </style>
</head>
<body>

<div id="navigation">
    <button onclick="goToRoot()">Go to Root</button>
    <button onclick="goUp()">Go Up One Level</button>
    <button onclick="createFolderPrompt()">Create Folder</button>
    <button onclick="copyItem()">Copy</button>
    <button onclick="pasteItem()">Paste</button>
    <button onclick="deleteItem()">Delete</button>
</div>

<div id="fileSystemContainer" oncontextmenu="showContextMenu(event, 'root')">
    <div id="breadcrumbs"></div>
    <div class="root-folder" onclick="selectFolder('root')">~</div>
    <ul id="fileSystemTree"></ul>
    <div class="grid-view"></div>
    <div class="empty-state" style="display: none;">
        <div class="empty-state-text">No folders yet.</div>
        <div class="empty-state-hint">Right-click and use the context menu to create a folder.</div>
    </div>
</div>

<div id="editor">
    <div id="editorHeader">
        <h2><span id="editorPath">/</span></h2>
        <div class="editor-controls">
            <span class="editor-button" onclick="setEditorSize('normal')" title="Normal Size"></span>
            <span class="editor-button" onclick="setEditorSize('vertical')" title="Vertical Split"></span>
            <span class="editor-button" onclick="setEditorSize('horizontal')" title="Horizontal Split"></span>
            <span class="editor-button" onclick="setEditorSize('full')" title="Full Screen"></span>
            <span class="editor-button" id="closeEditor" onclick="hideEditor()" title="Close"></span>
        </div>
    </div>
    <div class="inchworm">O</div>
    <textarea id="folderContent" placeholder="Select a folder to edit its contents"></textarea>
</div>

<div class="context-menu" id="contextMenu">
    <div class="context-menu-item new-folder" onclick="createFolderPrompt()">New Folder</div>
    <div class="context-menu-item rename" onclick="renameFolder()">Rename</div>
    <div class="context-menu-item copy" onclick="copyItem()">Copy</div>
    <div class="context-menu-item paste" onclick="pasteItem()">Paste</div>
    <div class="context-menu-item delete" onclick="deleteItem()">Delete</div>
</div>

<div id="viewControls">
    <button class="view-toggle" onclick="toggleView()" title="Toggle View">
        <span class="tree-icon">🌳</span>/<span class="grid-icon">📱</span>
    </button>
</div>

<script>
const initialState = () => ({
    root: { type: 'folder', children: {}, content: '' }
});

const loadFileSystem = () => JSON.parse(localStorage.getItem('fileSystem')) || initialState();

const state = {
    fileSystem: loadFileSystem(),
    currentFolderPath: 'root',
    copiedFolderData: null,
    copiedItemPath: null,
    draggedPath: null,
    viewMode: 'tree' // 'tree' or 'grid'
};

const clone = (obj) => JSON.parse(JSON.stringify(obj));

const updateFileSystem = (newFileSystem) => {
    state.fileSystem = newFileSystem;
    saveFileSystem(newFileSystem);
};

const getFolder = (path, fileSystem = state.fileSystem) => {
    const parts = path.split('/').filter(part => part !== 'root');
    return parts.reduce((current, part) => {
        if (!current || !current.children[part]) {
            return null;
        }
        return current.children[part];
    }, fileSystem.root);
};

const updateFolder = (fileSystem, path, updateFn) => {
    const rootCopy = clone(fileSystem);
    const folderToUpdate = getFolder(path, rootCopy);
    if (!folderToUpdate) {
        alert(`Folder not found for path: ${path}`);
        return null;
    }

    updateFn(folderToUpdate);
    return rootCopy;
};

const addFolder = (path, name, folderData, fileSystem) => {
    return updateFolder(fileSystem, path, (folder) => {
        if (folder.children[name]) {
            alert(`Folder with name "${name}" already exists.`);
            return;
        }
        folder.children[name] = folderData || { type: 'folder', children: {}, content: '' };
    });
};

const deleteFolder = (path, fileSystem) => {
    if (path === 'root') {
        return fileSystem;
    }

    if (!path.includes('/')) {
        const newFileSystem = clone(fileSystem);
        delete newFileSystem.root.children[path];
        return newFileSystem;
    }

    const [parentPath, folderName] = path.split(/\/([^\/]+)$/);
    return updateFolder(fileSystem, parentPath, (folder) => {
        delete folder.children[folderName];
    });
};

const saveFileSystem = (fileSystem) => {
    localStorage.setItem('fileSystem', JSON.stringify(fileSystem));
};

const goToRoot = () => {
    state.currentFolderPath = 'root';
    render();
};

const goUp = () => {
    const parts = state.currentFolderPath.split('/');
    if (parts.length > 1) {
        parts.pop();
        state.currentFolderPath = parts.join('/');
        render();
    }
};

const createFolder = (path, name) => {
    const updatedFileSystem = addFolder(path, name, null, state.fileSystem);
    if (updatedFileSystem) {
        updateFileSystem(updatedFileSystem);
        render();
    } else {
        console.error('Error creating folder', path, name);
        alert('Error creating folder');
    }
};

const deleteItem = () => {
    console.log('Attempting to delete:', state.currentFolderPath); // Debug log
    
    // Basic validation
    if (state.currentFolderPath === 'root') {
        alert("Can't delete root!");
        return;
    }

    // Get parent path and folder name
    const parts = state.currentFolderPath.split('/');
    const folderName = parts[parts.length - 1];
    const parentPath = parts.slice(0, -1).join('/') || 'root';

    // Create new file system and delete the folder
    const newFileSystem = clone(state.fileSystem);
    const parent = parentPath === 'root' ? 
        newFileSystem.root : 
        getFolder(parentPath, newFileSystem);

    if (parent && parent.children) {
        delete parent.children[folderName];
        updateFileSystem(newFileSystem);
        state.currentFolderPath = parentPath;
        document.getElementById('editor').style.display = 'none';
        render();
    }
    hideContextMenu();
};

const copyItem = () => {
    const folder = getFolder(state.currentFolderPath);
    if (folder) {
        state.copiedFolderData = clone(folder); // Store a deep copy of the folder
        state.copiedItemPath = state.currentFolderPath; // Store the path so that we can remove later
    }
    hideContextMenu();
};

const pasteItem = () => {
    if (!state.copiedItemPath || !state.copiedFolderData) {
        alert('No item to paste');
        hideContextMenu();
        return;
    }

    const [oldPath, folderName] = state.copiedItemPath.split(/\/([^\/]+)$/);
    const updatedFileSystem = addFolder(state.currentFolderPath, folderName, state.copiedFolderData, state.fileSystem);

    if (updatedFileSystem) {
        updateFileSystem(deleteFolder(oldPath, updatedFileSystem)); // Remove original
        state.copiedFolderData = null; // Clear the copied data
        state.copiedItemPath = null;
        render();
    } else {
        alert('Error pasting item');
    }
    hideContextMenu();
};

const saveFolderContent = () => {
    const updatedFileSystem = updateFolder(state.fileSystem, state.currentFolderPath, (folder) => {
        folder.content = document.getElementById('folderContent').value;
    });
    if (updatedFileSystem) {
        updateFileSystem(updatedFileSystem);
    }
};

document.getElementById('folderContent').addEventListener('input', () => {
    saveFolderContent();
});

const handleDragStart = (e, path) => {
    e.target.classList.add('dragging');
    e.dataTransfer.setData('text/plain', path);
    state.draggedPath = path;
};

const handleDragEnd = (e) => {
    e.target.classList.remove('dragging');
    document.querySelectorAll('.folder').forEach(f => {
        f.classList.remove('drag-over');
    });
};

const handleDragOver = (e) => {
    e.preventDefault();
    e.target.classList.add('drag-over');
};

const handleDragLeave = (e) => {
    e.target.classList.remove('drag-over');
};

const handleDrop = (e, targetPath) => {
    e.preventDefault();
    e.target.classList.remove('drag-over');
    
    if (!state.draggedPath || state.draggedPath === targetPath) return;
    
    const sourcePath = state.draggedPath;
    const sourceFolder = getFolder(sourcePath);
    
    if (!sourceFolder) return;
    
    // Create a copy of the dragged folder
    const [, folderName] = sourcePath.split(/\/([^\/]+)$/);
    const updatedFileSystem = addFolder(targetPath, folderName, clone(sourceFolder), state.fileSystem);
    
    if (updatedFileSystem) {
        // Remove the original folder
        updateFileSystem(deleteFolder(sourcePath, updatedFileSystem));
        state.draggedPath = null;
        render();
    }
};

const renderFolderTree = (folder, path = 'root') => {
    const entries = Object.entries(folder.children);
    return entries.length ? entries.map(([name, item]) => {
        const fullPath = path === 'root' ? name : `${path}/${name}`;
        return `
            <li>
                <div class="folder" 
                    onclick="selectFolder('${fullPath}')"
                    oncontextmenu="showContextMenu(event, '${fullPath}')"
                    draggable="true"
                    ondragstart="handleDragStart(event, '${fullPath}')"
                    ondragend="handleDragEnd(event)"
                    ondragover="handleDragOver(event)"
                    ondragleave="handleDragLeave(event)"
                    ondrop="handleDrop(event, '${fullPath}')"
                >${name}</div>
                <ul>${renderFolderTree(item, fullPath)}</ul>
            </li>
        `;
    }).join('') : '';
};

const selectFolder = (path) => {
    // Don't proceed if no path is provided
    if (!path) return;

    const folder = path === 'root' ? state.fileSystem.root : getFolder(path);
    if (folder) {
        // Remove previous selection
        document.querySelectorAll('.folder.selected, .root-folder.selected').forEach(f => {
            f.classList.remove('selected');
        });
        
        // Add selection to current folder
        if (path === 'root') {
            document.querySelector('.root-folder').classList.add('selected');
        } else {
            const folderElement = document.querySelector(`.folder[onclick*="${path}"]`);
            if (folderElement) {
                folderElement.classList.add('selected');
            }
        }
        
        // Set the current path
        state.currentFolderPath = path;
        
        // Update editor content
        document.getElementById('folderContent').value = folder.content || '';
        
        // Show editor in normal size
        editor.style.display = 'block';
        setEditorSize('normal');
        
        render();
    }
};

const render = () => {
    if (!state.fileSystem.root) {
        console.error('File system is not initialized correctly', state.fileSystem);
        alert('File system is not initialized correctly');
        return;
    }

    // Show/hide breadcrumbs and root folder based on view mode
    document.getElementById('breadcrumbs').style.display = 
        state.viewMode === 'grid' ? 'block' : 'none';
    document.querySelector('.root-folder').style.display = 
        state.viewMode === 'grid' ? 'none' : 'block';

    // Update current folder content based on view mode
    if (state.viewMode === 'tree') {
        document.getElementById('fileSystemTree').style.display = 'block';
        document.querySelector('.grid-view').style.display = 'none';
        document.getElementById('fileSystemTree').innerHTML = 
            renderFolderTree(state.fileSystem.root);
    } else {
        document.getElementById('fileSystemTree').style.display = 'none';
        document.querySelector('.grid-view').style.display = 'grid';
        const currentFolder = state.currentFolderPath === 'root' ? 
            state.fileSystem.root : 
            getFolder(state.currentFolderPath);
        document.querySelector('.grid-view').innerHTML = 
            renderGridView(currentFolder);
    }

    renderBreadcrumbs();

    // Update path displays
    const currentPath = state.currentFolderPath.replace('root', '') || '/';
    document.title = `Folder: ${currentPath}`;
    document.getElementById('editorPath').textContent = currentPath;
    
    // Update root folder selection state
    const rootFolder = document.querySelector('.root-folder');
    if (state.currentFolderPath === 'root') {
        rootFolder.classList.add('selected');
    } else {
        rootFolder.classList.remove('selected');
    }

    // Update folder tree and empty state
    document.getElementById('fileSystemTree').innerHTML = renderFolderTree(state.fileSystem.root);
    const emptyState = document.querySelector('.empty-state');
    const hasNoFolders = Object.keys(state.fileSystem.root.children).length === 0;
    emptyState.style.display = hasNoFolders ? 'flex' : 'none';
};

const createFolderPrompt = () => {
    const name = prompt('Enter folder name:');
    if (name) createFolder(state.currentFolderPath, name);
    hideContextMenu();
};

const contextMenu = document.getElementById('contextMenu');

// Prevent default context menu
document.addEventListener('contextmenu', (e) => {
    e.preventDefault();
});

// Hide context menu when clicking outside
document.addEventListener('click', (e) => {
    if (!contextMenu.contains(e.target)) {
        contextMenu.classList.remove('active');
    }
});

const showContextMenu = (e, path) => {
    e.preventDefault();
    e.stopPropagation();
    
    // Just update the current path without selecting the folder
    if (path) {
        state.currentFolderPath = path;
    }
    
    // Position the menu
    contextMenu.style.left = `${e.pageX}px`;
    contextMenu.style.top = `${e.pageY}px`;
    
    // Show the menu
    contextMenu.classList.add('active');
    
    // Enable/disable paste option
    const pasteOption = contextMenu.querySelector('.paste');
    pasteOption.style.opacity = state.copiedFolderData ? '1' : '0.5';
    
    // Prevent menu from going off-screen
    const rect = contextMenu.getBoundingClientRect();
    if (rect.right > window.innerWidth) {
        contextMenu.style.left = `${e.pageX - rect.width}px`;
    }
    if (rect.bottom > window.innerHeight) {
        contextMenu.style.top = `${e.pageY - rect.height}px`;
    }
};

// Add double-click handler to show/hide editor
document.addEventListener('dblclick', (e) => {
    if (!e.target.classList.contains('folder')) {
        document.getElementById('editor').style.display = 'none';
    }
});

const editor = document.getElementById('editor');
const editorHeader = document.getElementById('editorHeader');

let isDragging = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;

const dragStart = (e) => {
    if (e.target.closest('#closeEditor') || e.target.classList.contains('resize-handle')) return;
    
    if (e.type === "touchstart") {
        initialX = e.touches[0].clientX - xOffset;
        initialY = e.touches[0].clientY - yOffset;
    } else {
        initialX = e.clientX - xOffset;
        initialY = e.clientY - yOffset;
    }

    if (e.target === editorHeader || e.target.closest('#editorHeader')) {
        isDragging = true;
    }
};

const dragEnd = () => {
    initialX = currentX;
    initialY = currentY;
    isDragging = false;
};

const drag = (e) => {
    if (isDragging) {
        e.preventDefault();

        if (e.type === "touchmove") {
            currentX = e.touches[0].clientX - initialX;
            currentY = e.touches[0].clientY - initialY;
        } else {
            currentX = e.clientX - initialX;
            currentY = e.clientY - initialY;
        }

        xOffset = currentX;
        yOffset = currentY;

        setTranslate(currentX, currentY, editor);
    }
};

const setTranslate = (xPos, yPos, el) => {
    el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
};

const hideEditor = () => {
    editor.style.display = 'none';
};

// Add event listeners for drag functionality
editorHeader.addEventListener("touchstart", dragStart, false);
editorHeader.addEventListener("touchend", dragEnd, false);
editorHeader.addEventListener("touchmove", drag, false);

editorHeader.addEventListener("mousedown", dragStart, false);
document.addEventListener("mousemove", drag, false);
document.addEventListener("mouseup", dragEnd, false);

const setEditorSize = (mode, editorElement = editor) => {
    // Reset any existing transforms and positioning
    editorElement.style.transform = 'none';
    editorElement.style.transition = 'all 0.3s ease';
    
    // Get viewport dimensions and convert padding to pixels
    const vw = window.innerWidth;
    const vh = window.innerHeight;
    const padding = '2em';
    const paddingPx = parseFloat(getComputedStyle(document.documentElement).fontSize) * 2;
    const fullModePadding = '4em';
    const fullModePaddingPx = parseFloat(getComputedStyle(document.documentElement).fontSize) * 4;
    
    // Reset all positioning first
    editorElement.style.position = 'fixed';
    editorElement.style.margin = '0';
    editorElement.style.maxWidth = 'none';
    editorElement.style.bottom = padding;
    
    switch (mode) {
        case 'normal':
            editorElement.style.width = '37.5em';
            editorElement.style.height = '300px';
            editorElement.style.left = '20px';
            editorElement.style.top = '20px';
            editorElement.style.right = 'auto';
            editorElement.style.bottom = 'auto';
            break;
            
        case 'vertical':
            // Take up the left half of the viewport
            editorElement.style.width = `${(vw - paddingPx * 3) / 2}px`;
            editorElement.style.height = `${vh - paddingPx * 2}px`;
            editorElement.style.left = padding;
            editorElement.style.top = padding;
            editorElement.style.right = 'auto';
            break;
            
        case 'horizontal':
            // Take up the top half of the viewport
            editorElement.style.width = `${vw - paddingPx * 2}px`;
            editorElement.style.height = `${(vh - paddingPx * 3) / 2}px`;
            editorElement.style.left = padding;
            editorElement.style.top = padding;
            editorElement.style.right = padding;
            break;
            
        case 'full':
            // Take up the full viewport with larger padding
            editorElement.style.width = `${vw - fullModePaddingPx * 2}px`;
            editorElement.style.height = `${vh - fullModePaddingPx * 2}px`;
            editorElement.style.top = fullModePadding;
            editorElement.style.left = fullModePadding;
            editorElement.style.right = fullModePadding;
            editorElement.style.bottom = fullModePadding;
            break;
    }
    
    // Reset offsets used by drag functionality
    xOffset = 0;
    yOffset = 0;
    
    // Ensure the editor is visible
    editorElement.style.display = 'block';
};

const renameFolder = () => {
    console.log('Attempting to rename:', state.currentFolderPath); // Debug log
    
    // Basic validation
    if (state.currentFolderPath === 'root') {
        alert("Can't rename root!");
        return;
    }

    // Get parent path and folder name
    const parts = state.currentFolderPath.split('/');
    const oldName = parts[parts.length - 1];
    const parentPath = parts.slice(0, -1).join('/') || 'root';

    const newName = prompt(`Rename "${oldName}" to:`, oldName);
    if (!newName || newName === oldName) return;

    // Create new file system and rename the folder
    const newFileSystem = clone(state.fileSystem);
    const parent = parentPath === 'root' ? 
        newFileSystem.root : 
        getFolder(parentPath, newFileSystem);

    if (parent && parent.children) {
        if (parent.children[newName]) {
            alert('A folder with this name already exists');
            return;
        }

        parent.children[newName] = parent.children[oldName];
        delete parent.children[oldName];
        updateFileSystem(newFileSystem);
        state.currentFolderPath = parentPath === 'root' ? 
            newName : 
            `${parentPath}/${newName}`;
        render();
    }
    hideContextMenu();
};

// Add double-click to rename
const handleFolderDoubleClick = (e) => {
    const folderElement = e.target.closest('.folder');
    if (folderElement && !folderElement.classList.contains('editing')) {
        e.preventDefault();
        e.stopPropagation();
        renameFolder();
    }
};

document.addEventListener('dblclick', handleFolderDoubleClick);

const toggleView = () => {
    state.viewMode = state.viewMode === 'tree' ? 'grid' : 'tree';
    render();
};

const navigateTo = (path, openDetails = false) => {
    state.currentFolderPath = path;
    
    // Only open folder details if explicitly requested (from breadcrumbs)
    if (openDetails) {
        const folder = path === 'root' ? state.fileSystem.root : getFolder(path);
        if (folder) {
            document.getElementById('folderContent').value = folder.content || '';
            editor.style.display = 'block';
            setEditorSize('normal');
        }
    }
    
    render();
};

const renderBreadcrumbs = () => {
    // Start with root, but ensure we don't duplicate it
    const parts = state.currentFolderPath.split('/').filter(part => part !== 'root');
    const fullPath = ['root', ...parts];
    
    // Generate breadcrumbs from the full path
    const breadcrumbs = fullPath.map((part, index) => {
        const path = fullPath.slice(0, index + 1).join('/');
        const isLastItem = index === fullPath.length - 1;
        
        return `
            <span class="breadcrumb-item" 
                onclick="navigateTo('${path}', ${isLastItem})">${part === 'root' ? '~' : part}</span>
            ${index < fullPath.length - 1 ? '<span class="breadcrumb-separator">/</span>' : ''}
        `;
    }).join('');

    document.getElementById('breadcrumbs').innerHTML = breadcrumbs;
};

const renderGridView = (folder) => {
    const entries = Object.entries(folder.children);
    return entries.map(([name, item]) => `
        <div class="grid-folder" 
            onclick="navigateTo('${state.currentFolderPath}/${name}')"
            oncontextmenu="showContextMenu(event, '${state.currentFolderPath}/${name}')">
            <div class="grid-folder-icon">📁</div>
            <div class="grid-folder-name">${name}</div>
        </div>
    `).join('');
};

const hideContextMenu = () => {
    contextMenu.classList.remove('active');
};

render();
</script>

</body>
</html>