Przeglądaj źródła

Add drop indicator and resizable details columns

File Manager drag and drop:
- Highlight the folder a drop would land in and show a hint pill naming it (upload / move / copy).
- Refuse drops of a folder into itself or its subfolder, and skip items already in the target folder, before the request is sent.
- Fix dropToFolder so it parses the payload safely and stores the correct cut mode.

Details view:
- New columns.js lets users drag header cells to reorder columns and drag the grip between headers to resize; double-clicking a grip resets the widths.
- Order and widths are saved per user under file_explorer/detailsColumns.
- Rows and header render in the saved column order.

Adds the new strings to the file_explorer locale in all five languages.
Toby Chui 3 tygodni temu
rodzic
commit
417790c06d

+ 125 - 0
src/web/SystemAO/file_system/file_explorer.css

@@ -3645,3 +3645,128 @@ i.blue{
 
 
 /* Menu entries that only make sense on a touch device */
 /* Menu entries that only make sense on a touch device */
 .fmMobileOnly { display: none; }
 .fmMobileOnly { display: none; }
+
+/* ---------- Drop target indicator ----------
+   dragdrop.js marks the folder a drop would land in: the folder row under
+   the cursor, or the whole file area for the current folder. */
+#folderView.fmDropTarget {
+    box-shadow: inset 0 0 0 2px var(--fs-accent);
+    background-color: color-mix(in srgb, var(--fs-accent) 5%, transparent);
+}
+.fileviewList .fileObject.item.fmDropTarget,
+.fileviewList .fileObject.card.fmDropTarget,
+.fsSideItem.fmDropTarget {
+    background: var(--fs-accent-soft) !important;
+    box-shadow: inset 0 0 0 2px var(--fs-accent);
+}
+/* Shadows on a <tr> are unreliable, so the row outline is drawn per cell */
+.detailstable tr.fileObject.details.fmDropTarget td {
+    background: var(--fs-accent-soft) !important;
+    box-shadow: inset 0 2px 0 var(--fs-accent), inset 0 -2px 0 var(--fs-accent);
+}
+.detailstable tr.fileObject.details.fmDropTarget td:first-child {
+    box-shadow: inset 0 2px 0 var(--fs-accent), inset 0 -2px 0 var(--fs-accent), inset 2px 0 0 var(--fs-accent);
+}
+.detailstable tr.fileObject.details.fmDropTarget td:last-child {
+    box-shadow: inset 0 2px 0 var(--fs-accent), inset 0 -2px 0 var(--fs-accent), inset -2px 0 0 var(--fs-accent);
+}
+
+#fmDropHint {
+    position: fixed;
+    z-index: 998;
+    transform: translate(-50%, -100%) translateY(6px);
+    padding: 5px 14px;
+    border-radius: 999px;
+    background-color: var(--fs-accent);
+    color: var(--fs-primary-fg);
+    box-shadow: 0px 4px 14px rgba(0, 0, 0, 0.25);
+    font-size: 12.5px;
+    line-height: 1.4;
+    white-space: nowrap;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    opacity: 0;
+    visibility: hidden;
+    pointer-events: none;
+    transition: opacity 0.12s ease, transform 0.12s ease, visibility 0s linear 0.12s;
+}
+#fmDropHint.visible {
+    opacity: 1;
+    visibility: visible;
+    transform: translate(-50%, -100%);
+    transition: opacity 0.12s ease, transform 0.12s ease;
+}
+/* A drop that would be refused reads as the toast does, not as a target */
+#fmDropHint.invalid {
+    background-color: var(--fs-toast-bg);
+    color: var(--fs-toast-fg);
+}
+/* The id wins over ao.css's blanket themed span colour */
+#fmDropHint .fmDropHintText { color: inherit; }
+
+/* ---------- Details view: column drag and resize (columns.js) ---------- */
+#fmListHeader th.fmSortable {
+    position: relative;
+    overflow: hidden;
+    text-overflow: ellipsis;
+}
+#fmListHeader .fmHeaderLabel {
+    color: inherit;
+    pointer-events: none;
+}
+/* Grip on each header cell's right edge, with a hairline that shows on hover */
+#fmListHeader .fmColResize {
+    position: absolute;
+    top: 0;
+    right: 0;
+    width: 7px;
+    height: 100%;
+    cursor: col-resize;
+    z-index: 1;
+}
+/* The last column ends at the table edge: nothing to trade width with */
+#fmListHeader th:last-child .fmColResize { display: none; }
+#fmListHeader .fmColResize::after {
+    content: "";
+    position: absolute;
+    top: 25%;
+    right: 3px;
+    width: 1px;
+    height: 50%;
+    background: var(--fs-line);
+}
+#fmListHeader th.fmSortable:hover .fmColResize::after,
+#fmListHeader .fmColResize:hover::after {
+    background: var(--fs-text-faint);
+}
+#fmListHeader th.fmColDragging {
+    opacity: 0.35;
+}
+body.fmColResizing,
+body.fmColResizing * { cursor: col-resize !important; user-select: none !important; }
+body.fmColMoving,
+body.fmColMoving * { cursor: grabbing !important; user-select: none !important; }
+
+#fmColGhost {
+    position: fixed;
+    z-index: 1000;
+    display: flex;
+    align-items: center;
+    padding: 0 8px;
+    border-radius: 4px;
+    background: var(--fs-surface);
+    color: var(--fs-text);
+    box-shadow: 0px 4px 14px var(--fs-shadow);
+    font-size: 13px;
+    white-space: nowrap;
+    overflow: hidden;
+    opacity: 0.92;
+    pointer-events: none;
+}
+#fmColDropMarker {
+    position: fixed;
+    z-index: 1001;
+    width: 2px;
+    background: var(--fs-accent);
+    pointer-events: none;
+}

+ 8 - 0
src/web/SystemAO/file_system/file_explorer.html

@@ -516,6 +516,13 @@
             </div>
             </div>
         </div>
         </div>
 
 
+        <!--
+            Names the folder a drag would land in. Positioned over the bottom
+            of the file area by dragdrop.js; never takes pointer events, so it
+            cannot become the drop target itself.
+        -->
+        <div id="fmDropHint"><span class="fmDropHintText"></span></div>
+
         <!--
         <!--
             Toast. Lives at body level so its position:fixed is resolved against
             Toast. Lives at body level so its position:fixed is resolved against
             the viewport and cannot be captured by a transformed ancestor.
             the viewport and cannot be captured by a transformed ancestor.
@@ -694,6 +701,7 @@
         <script type="text/javascript" src="js/explorer/properties.js"></script>
         <script type="text/javascript" src="js/explorer/properties.js"></script>
         <script type="text/javascript" src="js/explorer/thumbnail.js"></script>
         <script type="text/javascript" src="js/explorer/thumbnail.js"></script>
         <script type="text/javascript" src="js/explorer/render.js"></script>
         <script type="text/javascript" src="js/explorer/render.js"></script>
+        <script type="text/javascript" src="js/explorer/columns.js"></script>
         <script type="text/javascript" src="js/explorer/listing.js"></script>
         <script type="text/javascript" src="js/explorer/listing.js"></script>
         <script type="text/javascript" src="js/explorer/selection.js"></script>
         <script type="text/javascript" src="js/explorer/selection.js"></script>
         <script type="text/javascript" src="js/explorer/keyboard.js"></script>
         <script type="text/javascript" src="js/explorer/keyboard.js"></script>

+ 3 - 0
src/web/SystemAO/file_system/js/explorer/boot.js

@@ -44,6 +44,9 @@ $(document).ready(function(){
             updateHiddenFilesToggle();
             updateHiddenFilesToggle();
         });
         });
 
 
+        //Restore the details view's column order and widths
+        loadDetailsColumns();
+
         //Restore the saved grid tile size
         //Restore the saved grid tile size
         loadPreference("file_explorer/gridZoom", function(value){
         loadPreference("file_explorer/gridZoom", function(value){
             let z = parseInt(value);
             let z = parseInt(value);

+ 341 - 0
src/web/SystemAO/file_system/js/explorer/columns.js

@@ -0,0 +1,341 @@
+/*
+    columns.js
+
+    Rearranging and resizing the details view's columns.
+
+    A header cell dragged sideways moves its column; the grip between two
+    header cells moves the boundary between those two columns, and double
+    clicking the grip puts their default widths back. Both are plain mouse handling rather than HTML5 drag
+    and drop: a native drag over #folderView would light up the file drop
+    indicator and end up in drop().
+
+    Name is the one fluid column. It takes whatever the fixed columns leave,
+    so the table keeps filling the file area.
+
+    Widths are applied through one generated style sheet keyed on the .fmCol*
+    classes, the same way file_explorer.css sizes them, so the header table
+    and the row tables stay in step. Saved per user under
+    file_explorer/detailsColumns as "name,date,type,size|date:170,size:90".
+
+    Part of the ArozOS File Manager. Loaded as a plain script from
+    file_explorer.html - see the <script> block at the end of that file.
+*/
+
+const FM_COLUMN_MIN_WIDTH = 60;     //Narrowest a fixed column can be dragged
+const FM_NAME_MIN_WIDTH = 140;      //Room the fluid name column always keeps
+const FM_COLUMN_DRAG_THRESHOLD = 5; //Pixels of travel before a press becomes a drag
+
+let detailsColumnOrder = ["name", "date", "type", "size"];
+let detailsColumnWidths = {};       //key -> px, only columns the user resized
+let columnDragEndedAt = 0;          //Lets the sort click that follows a drag be ignored
+
+function detailsColumnByKey(key){
+    return FM_SORT_COLUMNS.filter(function(c){ return c.key == key; })[0];
+}
+
+//FM_SORT_COLUMNS in the user's order
+function orderedDetailsColumns(){
+    return detailsColumnOrder.map(detailsColumnByKey).filter(function(col){
+        return col != undefined;
+    });
+}
+
+/* ---------------------------------------------------------------------- */
+/*  Saving and restoring                                                   */
+/* ---------------------------------------------------------------------- */
+function loadDetailsColumns(){
+    loadPreference("file_explorer/detailsColumns", function(value){
+        if (typeof value !== "string" || value == ""){
+            return;
+        }
+        let parts = value.split("|");
+
+        //Keep only known keys, each once, and append any the saved order
+        //predates so a new column never disappears
+        let order = [];
+        (parts[0] || "").split(",").forEach(function(key){
+            if (detailsColumnByKey(key) != undefined && order.indexOf(key) < 0){
+                order.push(key);
+            }
+        });
+        FM_SORT_COLUMNS.forEach(function(col){
+            if (order.indexOf(col.key) < 0){
+                order.push(col.key);
+            }
+        });
+
+        let widths = {};
+        (parts[1] || "").split(",").forEach(function(entry){
+            let kv = entry.split(":");
+            let w = parseInt(kv[1]);
+            if (kv[0] != "name" && detailsColumnByKey(kv[0]) != undefined && !isNaN(w)){
+                widths[kv[0]] = Math.max(FM_COLUMN_MIN_WIDTH, w);
+            }
+        });
+
+        detailsColumnOrder = order;
+        detailsColumnWidths = widths;
+        applyDetailsColumnWidths();
+        //The listing may already be on screen by the time this arrives
+        applyDetailsColumnOrder();
+    });
+}
+
+function saveDetailsColumns(){
+    let widths = Object.keys(detailsColumnWidths).map(function(key){
+        return key + ":" + Math.round(detailsColumnWidths[key]);
+    });
+    setPreference("file_explorer/detailsColumns",
+        encodeURIComponent(detailsColumnOrder.join(",") + "|" + widths.join(",")));
+}
+
+/* ---------------------------------------------------------------------- */
+/*  Applying                                                               */
+/* ---------------------------------------------------------------------- */
+function applyDetailsColumnWidths(){
+    let sheet = document.getElementById("fmColumnWidths");
+    if (sheet == null){
+        sheet = document.createElement("style");
+        sheet.id = "fmColumnWidths";
+        document.head.appendChild(sheet);
+    }
+    //The id outranks the defaults in file_explorer.css
+    sheet.textContent = Object.keys(detailsColumnWidths).map(function(key){
+        return "#folderView .detailstable ." + detailsColumnByKey(key).cls +
+               "{width:" + Math.round(detailsColumnWidths[key]) + "px;}";
+    }).join("\n");
+}
+
+//Reorders the cells of the rendered header and rows in place, no re-render
+function applyDetailsColumnOrder(){
+    let columns = orderedDetailsColumns();
+    $("#fmListHeader tr, #folderView .detailTableContent > tr").each(function(){
+        let row = this;
+        columns.forEach(function(col){
+            let cell = row.querySelector(":scope > ." + col.cls);
+            if (cell != null){
+                row.appendChild(cell);
+            }
+        });
+    });
+}
+
+//True for the click a column drag leaves behind, which must not sort
+function columnHeaderClickSuppressed(){
+    return Date.now() - columnDragEndedAt < 300;
+}
+
+function visibleHeaderCells(){
+    return $("#fmListHeader th.fmSortable").filter(":visible").toArray();
+}
+
+/* ---------------------------------------------------------------------- */
+/*  Resizing                                                               */
+/* ---------------------------------------------------------------------- */
+/*
+    The grip on a header cell's right edge is the boundary between that
+    column and the next visible one. Dragging it trades width between those
+    two only: the left column's start and the right column's end stay put,
+    so no other column moves. The last column has nothing to trade with and
+    shows no grip.
+
+    The name column is never given a width. When it is one of the pair, only
+    the other column's width is set and name takes up the difference, which
+    comes to the same thing because the other columns do not change.
+*/
+function resizePairFor(grip){
+    let th = $(grip).closest("th")[0];
+    let cells = visibleHeaderCells();
+    let next = cells[cells.indexOf(th) + 1];
+    if (next == undefined){
+        return null;
+    }
+    return {
+        left: th,
+        right: next,
+        leftKey: $(th).attr("data-sortkey"),
+        rightKey: $(next).attr("data-sortkey")
+    };
+}
+
+function columnMinWidth(key){
+    return key == "name" ? FM_NAME_MIN_WIDTH : FM_COLUMN_MIN_WIDTH;
+}
+
+function startColumnResize(event, grip){
+    let pair = resizePairFor(grip);
+    if (pair == null){
+        return;
+    }
+
+    let startX = event.clientX;
+    let startLeft = pair.left.offsetWidth;
+    let total = startLeft + pair.right.offsetWidth;
+    let minLeft = columnMinWidth(pair.leftKey);
+    let maxLeft = Math.max(minLeft, total - columnMinWidth(pair.rightKey));
+    let moved = false;
+
+    $("body").addClass("fmColResizing");
+
+    function onMove(e){
+        let left = Math.min(maxLeft, Math.max(minLeft, startLeft + e.clientX - startX));
+        if (pair.leftKey != "name"){
+            detailsColumnWidths[pair.leftKey] = left;
+        }
+        if (pair.rightKey != "name"){
+            detailsColumnWidths[pair.rightKey] = total - left;
+        }
+        moved = moved || left != startLeft;
+        applyDetailsColumnWidths();
+    }
+
+    function onUp(){
+        $(document).off("mousemove.fmcolresize mouseup.fmcolresize");
+        $("body").removeClass("fmColResizing");
+        columnDragEndedAt = Date.now();
+        if (moved){
+            saveDetailsColumns();
+        }
+    }
+
+    $(document).on("mousemove.fmcolresize", onMove).on("mouseup.fmcolresize", onUp);
+}
+
+//Double click on a grip: both columns it sits between go back to their defaults
+function resetColumnWidth(grip){
+    let pair = resizePairFor(grip);
+    if (pair == null){
+        return;
+    }
+    delete detailsColumnWidths[pair.leftKey];
+    delete detailsColumnWidths[pair.rightKey];
+    applyDetailsColumnWidths();
+    saveDetailsColumns();
+}
+
+/* ---------------------------------------------------------------------- */
+/*  Reordering                                                             */
+/* ---------------------------------------------------------------------- */
+function startColumnMove(event, th){
+    let startX = event.clientX;
+    let key = $(th).attr("data-sortkey");
+    let ghost = null;
+    let marker = null;
+    let beforeKey = null;   //Column the dragged one lands in front of; null = last
+
+    function begin(){
+        let rect = th.getBoundingClientRect();
+        ghost = $('<div id="fmColGhost"></div>').text($(th).text()).css({
+            left: rect.left + "px",
+            top: rect.top + "px",
+            width: rect.width + "px",
+            height: rect.height + "px"
+        }).appendTo("body");
+        marker = $('<div id="fmColDropMarker"></div>').css({
+            top: rect.top + "px",
+            height: rect.height + "px"
+        }).appendTo("body");
+        ghost.data("left", rect.left);
+        $(th).addClass("fmColDragging");
+        $("body").addClass("fmColMoving");
+    }
+
+    function onMove(e){
+        let dx = e.clientX - startX;
+        if (ghost == null){
+            if (Math.abs(dx) < FM_COLUMN_DRAG_THRESHOLD){
+                return;
+            }
+            begin();
+        }
+        ghost.css("left", (ghost.data("left") + dx) + "px");
+
+        //Lands in front of the first column whose middle is right of the cursor
+        let cells = visibleHeaderCells();
+        beforeKey = null;
+        let markerX = null;
+        for (let i = 0; i < cells.length; i++){
+            let r = cells[i].getBoundingClientRect();
+            if (e.clientX < r.left + r.width / 2){
+                beforeKey = $(cells[i]).attr("data-sortkey");
+                markerX = r.left;
+                break;
+            }
+        }
+        if (markerX == null && cells.length > 0){
+            markerX = cells[cells.length - 1].getBoundingClientRect().right;
+        }
+        marker.css("left", (markerX - 1) + "px");
+    }
+
+    function onUp(){
+        $(document).off("mousemove.fmcolmove mouseup.fmcolmove");
+        if (ghost == null){
+            //A plain click - leave it to the sort handler
+            return;
+        }
+        ghost.remove();
+        marker.remove();
+        $(th).removeClass("fmColDragging");
+        $("body").removeClass("fmColMoving");
+        columnDragEndedAt = Date.now();
+
+        if (beforeKey == key){
+            return;
+        }
+        let order = detailsColumnOrder.filter(function(k){ return k != key; });
+        let at = beforeKey == null ? order.length : order.indexOf(beforeKey);
+        order.splice(at, 0, key);
+        if (order.join(",") != detailsColumnOrder.join(",")){
+            detailsColumnOrder = order;
+            applyDetailsColumnOrder();
+            saveDetailsColumns();
+        }
+    }
+
+    $(document).on("mousemove.fmcolmove", onMove).on("mouseup.fmcolmove", onUp);
+}
+
+//Bound once from boot, delegated because the header is redrawn per listing
+function bindDetailsColumnEvents(){
+    let header = $("#fmListHeader");
+
+    header.on("mousedown", ".fmColResize", function(event){
+        if (event.button != 0){
+            return;
+        }
+        event.preventDefault();
+        event.stopPropagation();
+        startColumnResize(event, this);
+    });
+
+    header.on("dblclick", ".fmColResize", function(event){
+        event.stopPropagation();
+        resetColumnWidth(this);
+    });
+
+    //A click on the grip must not sort the column it belongs to
+    header.on("click", ".fmColResize", function(event){
+        event.stopPropagation();
+    });
+
+    header.on("mousedown", "th.fmSortable", function(event){
+        if (event.button != 0){
+            return;
+        }
+        //Keeps the press from starting a text selection across the header
+        event.preventDefault();
+        startColumnMove(event, this);
+    });
+}
+
+
+/*
+    Reachable from outside this file: inline on* attributes in the markup,
+    handlers generated in template strings, or another frame. Renaming any
+    of these means updating those call sites too.
+*/
+window.bindDetailsColumnEvents = bindDetailsColumnEvents;
+window.columnHeaderClickSuppressed = columnHeaderClickSuppressed;
+window.loadDetailsColumns = loadDetailsColumns;
+window.orderedDetailsColumns = orderedDetailsColumns;

+ 282 - 36
src/web/SystemAO/file_system/js/explorer/dragdrop.js

@@ -36,12 +36,17 @@
         });
         });
         
         
         event.dataTransfer.setData("filedata", JSON.stringify(fileList));
         event.dataTransfer.setData("filedata", JSON.stringify(fileList));
+        setDragSources(fileList.map(function(file){
+            return file.filepath;
+        }));
     }
     }
 
 
     //Function for getting file objects in the same row
     //Function for getting file objects in the same row
     //Handle drag drop upload
     //Handle drag drop upload
     function drop(event){
     function drop(event){
         event.preventDefault();
         event.preventDefault();
+        hideDropIndicator();
+        clearDragSources();
 
 
         /*
         /*
             A drop on a folder row belongs to dropToFolder(). That handler is
             A drop on a folder row belongs to dropToFolder(). That handler is
@@ -127,36 +132,31 @@
 
 
                     //Start processing the local files
                     //Start processing the local files
                     let currentVroot = currentPath.split(":/").shift();
                     let currentVroot = currentPath.split(":/").shift();
-                    clipboard = [];
 
 
                     //Assume all files are from the same directory
                     //Assume all files are from the same directory
                     if (localFiles.length > 0){
                     if (localFiles.length > 0){
-                        //Check if drag drop from the same directory
-                        let currentDirname = currentPath.split("/")
-                        currentDirname.pop();
-                        currentDirname = currentDirname.join("/");
-                        let firstFileDirname = localFiles[0].filepath.split("/")
-                        firstFileDirname.pop();
-                        firstFileDirname = firstFileDirname.join("/");
-                        if (currentDirname == firstFileDirname){
-                            //Drag start and drop location are the same directory
-                            msgbox("red remove",applocale.getString("message/destIdentical", "Source and destination file names are the same"));
+                        let fileVroot = localFiles[0].filepath.split(":/").shift();
+                        let isMove = (currentVroot == fileVroot);
+
+                        /*
+                            Caught here rather than left to the server: a drop
+                            back where the files came from, or a folder into
+                            itself, would otherwise open the file operation
+                            dialog just to report an error.
+                        */
+                        let checked = checkDropSources(localFiles.map(function(file){
+                            return file.filepath;
+                        }), currentPath, isMove);
+                        if (checked.error != null){
+                            showRefusedDrop(checked.error);
                             return;
                             return;
                         }
                         }
 
 
-                        let fileVroot = localFiles[0].filepath.split(":/").shift();
-                        if (currentVroot == fileVroot){
-                            //Same device same root. Move the file
-                            cutMode = true;
-                        }else{
-                            //Same device differnet root. Copy the file
-                            cutMode = false;
-                        }
+                        //Same device same root moves, a different root copies
+                        cutMode = isMove;
 
 
                         //Move all localFiles into clipboard
                         //Move all localFiles into clipboard
-                        localFiles.forEach(file => {
-                            clipboard.push(file.filepath);
-                        });
+                        clipboard = checked.paths.slice();
 
 
                         if (useLocalstorage){
                         if (useLocalstorage){
                             localStorage.setItem("ao/file_system/clipboard",JSON.stringify(clipboard));
                             localStorage.setItem("ao/file_system/clipboard",JSON.stringify(clipboard));
@@ -215,6 +215,8 @@
 function dropToFolder(event, folderObject=undefined){
 function dropToFolder(event, folderObject=undefined){
     event.preventDefault();
     event.preventDefault();
     event.stopImmediatePropagation();
     event.stopImmediatePropagation();
+    hideDropIndicator();
+    clearDragSources();
     console.log("Drop to folder detected");
     console.log("Drop to folder detected");
 
 
     //A special view's rows are not directories to paste into; drop() has
     //A special view's rows are not directories to paste into; drop() has
@@ -256,26 +258,35 @@ function dropToFolder(event, folderObject=undefined){
     }else if (event.dataTransfer.getData("filedata") != ""){
     }else if (event.dataTransfer.getData("filedata") != ""){
         var targetVroot = targetPath.split(":/").shift();
         var targetVroot = targetPath.split(":/").shift();
         //Get the source files
         //Get the source files
-        var filelist = JSON.parse(event.dataTransfer.getData("filedata"));
+        var filelist = [];
+        try {
+            filelist = JSON.parse(event.dataTransfer.getData("filedata"));
+        } catch (ex){
+            msgbox("red remove",applocale.getString("message/decodeFilelistFail", "File drop failed. Unable to decode filelist."));
+            return;
+        }
         if (filelist.length > 0){
         if (filelist.length > 0){
             var srcVroot = filelist[0].filepath.split(":/").shift();
             var srcVroot = filelist[0].filepath.split(":/").shift();
-            if (srcVroot == targetVroot){
-                //Use move mode
-                cutMode = true;
-                
-            }else{
-                //Use copy mode
-                cutMode = false;
+            //Same root moves, a different root copies
+            cutMode = (srcVroot == targetVroot);
+
+            /*
+                A folder dropped onto its own row - easy to do by accident
+                with a short drag - is a move into itself. Stop it here
+                instead of letting the server answer with an error dialog.
+            */
+            var checked = checkDropSources(filelist.map(function(file){
+                return file.filepath;
+            }), targetPath, cutMode);
+            if (checked.error != null){
+                showRefusedDrop(checked.error);
+                return;
             }
             }
 
 
-            //Parse the filelist
-            clipboard = [];
-            filelist.forEach(file=>{
-                clipboard.push(file.filepath);
-            });
+            clipboard = checked.paths.slice();
             if (useLocalstorage){
             if (useLocalstorage){
                 localStorage.setItem("ao/file_system/clipboard",JSON.stringify(clipboard));
                 localStorage.setItem("ao/file_system/clipboard",JSON.stringify(clipboard));
-                localStorage.setItem("ao/file_system/cutmode","true");
+                localStorage.setItem("ao/file_system/cutmode", cutMode ? "true" : "false");
             }
             }
             
             
             //Perform operations
             //Perform operations
@@ -295,6 +306,8 @@ function dropToFolder(event, folderObject=undefined){
 function dropToSpecialView(event, sentinelPath){
 function dropToSpecialView(event, sentinelPath){
     event.preventDefault();
     event.preventDefault();
     event.stopImmediatePropagation();
     event.stopImmediatePropagation();
+    hideDropIndicator();
+    clearDragSources();
 
 
     let payload = event.dataTransfer.getData("filedata");
     let payload = event.dataTransfer.getData("filedata");
     if (payload == undefined || payload == ""){
     if (payload == undefined || payload == ""){
@@ -321,12 +334,245 @@ function allowDrop(event){
 }
 }
 
 
 
 
+/* ---------------------------------------------------------------------- */
+/*  Drop checks                                                            */
+/* ---------------------------------------------------------------------- */
+//Path without its trailing slash, keeping the one a root ("user:/") needs
+function normaliseDropPath(path){
+    path = String(path);
+    while (path.length > 1 && path.endsWith("/") && !path.endsWith(":/")){
+        path = path.substring(0, path.length - 1);
+    }
+    return path;
+}
+
+function parentDirOfPath(path){
+    path = normaliseDropPath(path);
+    let cut = path.lastIndexOf("/");
+    if (cut < 0){
+        return path;
+    }
+    let parent = path.substring(0, cut);
+    return parent.endsWith(":") ? parent + "/" : parent;
+}
+
+/*
+    Which of the dragged paths can go into targetDir. Returns
+    {error, paths}: error is the message to show when the drop must not be
+    sent at all, otherwise paths is what is left to move or copy.
+
+    A folder into itself or one of its own subfolders is refused outright.
+    Items already sitting in targetDir are skipped on a move, and only when
+    that leaves nothing is the drop refused - so a drag of several files that
+    happens to include one already there still moves the rest.
+*/
+function checkDropSources(sourcePaths, targetDir, isMove){
+    let target = normaliseDropPath(targetDir);
+    let remaining = [];
+    for (let i = 0; i < sourcePaths.length; i++){
+        let src = normaliseDropPath(sourcePaths[i]);
+        if (src == target){
+            return {error: applocale.getString("message/drop/intoItself", "A folder cannot be moved into itself"), paths: []};
+        }
+        if (target.indexOf(src + "/") == 0){
+            return {error: applocale.getString("message/drop/intoSubfolder", "A folder cannot be moved into its own subfolder"), paths: []};
+        }
+        if (isMove && parentDirOfPath(src) == target){
+            continue;
+        }
+        remaining.push(sourcePaths[i]);
+    }
+    if (remaining.length == 0){
+        return {error: applocale.getString("message/drop/alreadyHere", "Already in this folder"), paths: []};
+    }
+    return {error: null, paths: remaining};
+}
+
+
+/* ---------------------------------------------------------------------- */
+/*  Drop target indicator                                                  */
+/* ---------------------------------------------------------------------- */
+/*
+    While something is dragged over the file area, the folder it would land
+    in is highlighted - the row under the cursor when that is a folder, the
+    whole file area otherwise - and a pill at the bottom names it. Dropping
+    onto a neighbouring folder row instead of the empty space beside it was
+    an easy way to upload into the wrong place without noticing.
+
+    dragenter / dragleave fire for every child the cursor crosses, so they
+    are not used. dragover repeats for as long as the cursor is over a drop
+    zone, even standing still, so each one refreshes the indicator and
+    re-arms a short timer that clears it once they stop.
+
+    The paths being dragged are not readable from dataTransfer until the
+    drop. Drags started in a File Manager window record them in localStorage
+    (shared by every File Manager window on this origin, which is how a drag
+    from another window still gets "cannot move into itself"); the drop
+    itself always re-checks against the real payload.
+*/
+const DRAG_SOURCES_KEY = "ao/file_system/dragsources";
+let dragSourcesFallback = [];
+let dropIndicatorTimer = null;
+
+function setDragSources(paths){
+    dragSourcesFallback = paths;
+    try {
+        localStorage.setItem(DRAG_SOURCES_KEY, JSON.stringify(paths));
+    } catch (ex){}
+}
+
+function clearDragSources(){
+    dragSourcesFallback = [];
+    try {
+        localStorage.removeItem(DRAG_SOURCES_KEY);
+    } catch (ex){}
+}
+
+function getDragSources(){
+    try {
+        let stored = localStorage.getItem(DRAG_SOURCES_KEY);
+        if (stored){
+            return JSON.parse(stored);
+        }
+    } catch (ex){}
+    return dragSourcesFallback;
+}
+
+function dragTypes(event){
+    let dt = event.dataTransfer;
+    return (dt && dt.types) ? Array.prototype.slice.call(dt.types) : [];
+}
+
+//Last segment of a path, or the root itself ("user:/") for a root
+function displayNameOfPath(path){
+    path = normaliseDropPath(path);
+    if (path.endsWith(":/")){
+        return path;
+    }
+    return path.split("/").pop();
+}
+
+/*
+    dragover on #folderView. Works out what a drop at the cursor would do
+    and shows it.
+*/
+function updateDropIndicator(event){
+    let types = dragTypes(event);
+    let isUpload = types.indexOf("Files") >= 0;
+    let isInternal = types.indexOf("filedata") >= 0;
+    if ((!isUpload && !isInternal) || isSpecialViewPath(currentPath)){
+        hideDropIndicator();
+        return;
+    }
+
+    let row = $(event.target).closest(".fileObject[type='folder']");
+    let targetPath = row.length > 0 ? row.attr("filepath") : currentPath;
+    let label;
+    let valid = true;
+
+    if (isUpload && !isInternal){
+        label = applocale.getString("drop/uploadTo", "Upload to “{name}”");
+    }else{
+        let sources = getDragSources();
+        let isMove = sources.length == 0 ||
+            sources[0].split(":/").shift() == targetPath.split(":/").shift();
+        let checked = checkDropSources(sources, targetPath, isMove);
+        if (sources.length > 0 && checked.error != null){
+            label = checked.error;
+            valid = false;
+        }else if (isMove){
+            label = applocale.getString("drop/moveTo", "Move to “{name}”");
+        }else{
+            label = applocale.getString("drop/copyTo", "Copy to “{name}”");
+        }
+    }
+
+    showDropIndicator(row.length > 0 ? row : $("#folderView"),
+        label.replace("{name}", displayNameOfPath(targetPath)), valid);
+}
+
+/*
+    dragover on a sidebar special view (the trash bin). Those only take
+    files already inside ArozOS.
+*/
+function updateSpecialViewDropIndicator(event, item){
+    if (dragTypes(event).indexOf("filedata") < 0){
+        hideDropIndicator();
+        return;
+    }
+    let name = $(item).text().trim();
+    showDropIndicator($(item),
+        applocale.getString("drop/moveTo", "Move to “{name}”").replace("{name}", name), true);
+}
+
+function showDropIndicator(target, label, valid){
+    $(".fmDropTarget").not(target).removeClass("fmDropTarget");
+    target.toggleClass("fmDropTarget", valid);
+
+    showDropHint(label, valid);
+    $("#fmDropHint").removeClass("refused");
+
+    clearTimeout(dropIndicatorTimer);
+    dropIndicatorTimer = setTimeout(hideDropIndicator, 160);
+}
+
+function showDropHint(label, valid){
+    let hint = $("#fmDropHint");
+    hint.toggleClass("invalid", !valid);
+    hint.find(".fmDropHintText").text(label);
+
+    //Pinned to the bottom of the file area, which scrolls, so it sits over
+    //it rather than inside it
+    let area = document.getElementById("folderView").getBoundingClientRect();
+    hint.css({
+        left: (area.left + area.width / 2) + "px",
+        top: (area.bottom - 16) + "px",
+        maxWidth: Math.max(160, area.width - 32) + "px"
+    });
+    hint.addClass("visible");
+}
+
+/*
+    A drop the checks refused. The hint pill was already saying why while
+    the drag hovered, so it stays up a moment longer with the same text
+    rather than a second message appearing in the toast.
+*/
+function showRefusedDrop(label){
+    $(".fmDropTarget").removeClass("fmDropTarget");
+    showDropHint(label, false);
+    $("#fmDropHint").addClass("refused");
+    clearTimeout(dropIndicatorTimer);
+    dropIndicatorTimer = setTimeout(hideDropIndicator, 1800);
+}
+
+function hideDropIndicator(){
+    clearTimeout(dropIndicatorTimer);
+    $(".fmDropTarget").removeClass("fmDropTarget");
+    $("#fmDropHint").removeClass("visible refused");
+}
+
+//dragend on the dragged row, which fires after the drop has been handled
+function onFileObjectDragEnd(){
+    clearDragSources();
+    //A refused drop's message is still meant to be read
+    if (!$("#fmDropHint").hasClass("refused")){
+        hideDropIndicator();
+    }
+}
+
+
 /*
 /*
     Reachable from outside this file: inline on* attributes in the markup,
     Reachable from outside this file: inline on* attributes in the markup,
     handlers generated in template strings, or another frame. Renaming any
     handlers generated in template strings, or another frame. Renaming any
     of these means updating those call sites too.
     of these means updating those call sites too.
 */
 */
 window.allowDrop = allowDrop;
 window.allowDrop = allowDrop;
+window.checkDropSources = checkDropSources;
+window.clearDragSources = clearDragSources;
+window.hideDropIndicator = hideDropIndicator;
+window.onFileObjectDragEnd = onFileObjectDragEnd;
+window.updateDropIndicator = updateDropIndicator;
+window.updateSpecialViewDropIndicator = updateSpecialViewDropIndicator;
 window.dropToSpecialView = dropToSpecialView;
 window.dropToSpecialView = dropToSpecialView;
 window.disableDrag = disableDrag;
 window.disableDrag = disableDrag;
 window.drop = drop;
 window.drop = drop;

+ 17 - 9
src/web/SystemAO/file_system/js/explorer/render.js

@@ -231,12 +231,17 @@ function renderDetailsRow(d){
     });
     });
     let size = d.isDir ? "--" : d.displaysize;
     let size = d.isDir ? "--" : d.displaysize;
 
 
-    return `<tr class="fileObject details" ${fileObjectAttributes(d)}>
-                <td class="fmColName"><span class="fmNameCell"><span class="fmRowIcon">${FileThumb.smallGlyph(d.filename, d.isDir)}</span><span class="filename">${d.displayName}</span>${sharedMark}</span></td>
-                <td class="fmColDate light-text">${d.modTimeText}</td>
-                <td class="fmColType light-text">${typeName}</td>
-                <td class="fmColSize light-text">${size}</td>
-            </tr>`;
+    //Cells follow the user's column order (columns.js)
+    let cells = {
+        name: `<td class="fmColName"><span class="fmNameCell"><span class="fmRowIcon">${FileThumb.smallGlyph(d.filename, d.isDir)}</span><span class="filename">${d.displayName}</span>${sharedMark}</span></td>`,
+        date: `<td class="fmColDate light-text">${d.modTimeText}</td>`,
+        type: `<td class="fmColType light-text">${typeName}</td>`,
+        size: `<td class="fmColSize light-text">${size}</td>`
+    };
+
+    return `<tr class="fileObject details" ${fileObjectAttributes(d)}>` +
+           orderedDetailsColumns().map(function(col){ return cells[col.key]; }).join("") +
+           `</tr>`;
 }
 }
 
 
 /*
 /*
@@ -244,7 +249,8 @@ function renderDetailsRow(d){
     than in a <colgroup>. With table-layout:fixed the first row defines the
     than in a <colgroup>. With table-layout:fixed the first row defines the
     columns, so CSS widths apply to the header table and the row tables alike,
     columns, so CSS widths apply to the header table and the row tables alike,
     and a column can be hidden outright when the file area gets narrow - which a
     and a column can be hidden outright when the file area gets narrow - which a
-    <colgroup> cannot do.
+    <colgroup> cannot do. Widths the user dragged are layered on top by
+    columns.js.
 */
 */
 
 
 /*
 /*
@@ -260,11 +266,13 @@ var FM_SORT_COLUMNS = [
 ];
 ];
 
 
 function renderDetailsHeader(){
 function renderDetailsHeader(){
-    let cells = FM_SORT_COLUMNS.map(function(col){
+    //Each header cell carries a grip on its right edge for resizing
+    let cells = orderedDetailsColumns().map(function(col){
         let active = (sortMode == col.asc) ? "asc" : ((sortMode == col.desc) ? "desc" : "");
         let active = (sortMode == col.asc) ? "asc" : ((sortMode == col.desc) ? "desc" : "");
         let mark = active == "asc" ? "&#8593;" : (active == "desc" ? "&#8595;" : "");
         let mark = active == "asc" ? "&#8593;" : (active == "desc" ? "&#8595;" : "");
         return `<th class="${col.cls} fmSortable ${active ? "sorted" : ""}" data-sortkey="${col.key}">` +
         return `<th class="${col.cls} fmSortable ${active ? "sorted" : ""}" data-sortkey="${col.key}">` +
-               `${applocale.getString(col.label, col.fallback)}<span class="fmSortMark">${mark}</span></th>`;
+               `<span class="fmHeaderLabel">${applocale.getString(col.label, col.fallback)}<span class="fmSortMark">${mark}</span></span>` +
+               `<span class="fmColResize" title="${applocale.getString("list/resizeColumn", "Drag to resize, double click to reset")}"></span></th>`;
     }).join("");
     }).join("");
 
 
     return `<table class="ui very basic unstackable table detailstable fmHeaderTable">
     return `<table class="ui very basic unstackable table detailstable fmHeaderTable">

+ 17 - 0
src/web/SystemAO/file_system/js/explorer/selection.js

@@ -551,6 +551,15 @@ function bindFileListDelegates(){
         dropToFolder(event.originalEvent || event, this);
         dropToFolder(event.originalEvent || event, this);
     });
     });
 
 
+    //Highlights where a drop would land, for uploads and moves alike
+    view.on("dragover", function(event){
+        updateDropIndicator(event.originalEvent || event);
+    });
+
+    view.on("dragend", ".fileObject", function(){
+        onFileObjectDragEnd();
+    });
+
     /*
     /*
         The sidebar's special views accept drops too - dragging onto the trash
         The sidebar's special views accept drops too - dragging onto the trash
         bin is how every other desktop deletes something. The rows are redrawn
         bin is how every other desktop deletes something. The rows are redrawn
@@ -559,6 +568,7 @@ function bindFileListDelegates(){
     */
     */
     $("#storageroot").off("dragover.specialview").on("dragover.specialview", ".fmSpecialSideItem", function(event){
     $("#storageroot").off("dragover.specialview").on("dragover.specialview", ".fmSpecialSideItem", function(event){
         allowDrop(event.originalEvent || event);
         allowDrop(event.originalEvent || event);
+        updateSpecialViewDropIndicator(event.originalEvent || event, this);
     });
     });
 
 
     $("#storageroot").off("drop.specialview").on("drop.specialview", ".fmSpecialSideItem", function(event){
     $("#storageroot").off("drop.specialview").on("drop.specialview", ".fmSpecialSideItem", function(event){
@@ -567,8 +577,15 @@ function bindFileListDelegates(){
 
 
     //Sortable column headers in details view
     //Sortable column headers in details view
     $("#fmListHeader").on("click", ".fmSortable", function(){
     $("#fmListHeader").on("click", ".fmSortable", function(){
+        //A column that was just dragged or resized is not a sort request
+        if (columnHeaderClickSuppressed()){
+            return;
+        }
         sortByColumn($(this).attr("data-sortkey"));
         sortByColumn($(this).attr("data-sortkey"));
     });
     });
+
+    //Rearranging and resizing the details columns
+    bindDetailsColumnEvents();
 }
 }
 
 
 //Status bar tile zoom. Grid only; re-renders so tiles pick up the new width.
 //Status bar tile zoom. Grid only; re-renders so tiles pick up the new width.