Desktop: drag and drop profile photo; share drop-zone hook with post form

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-26 23:27:40 +03:00
parent abd6f83535
commit 16b886081b
9 changed files with 209 additions and 45 deletions

View File

@@ -0,0 +1,58 @@
import { useRef, useState } from "react";
const isFileDrag = (e) => Array.from(e.dataTransfer?.types || []).includes("Files");
/**
* Зона для перетаскивания файлов (drag & drop).
*
* zoneProps вешаются на элемент-зону: подсветка (dragOver) и приём файлов
* в onFiles. strayDropProps — на всё окно: файл, отпущенный мимо зоны,
* браузер открыл бы вместо сайта, и введённые в форму данные пропали бы.
*
* dragenter/dragleave приходят и от дочерних элементов зоны, поэтому
* считаем глубину, иначе подсветка мигает при движении над содержимым.
*
* @param {{ enabled: boolean, busy?: boolean, onFiles: (files: FileList) => void }} options
* enabled — выключенная зона не вешает обработчики (мобильная раскладка);
* busy — файлы ещё обрабатываются: новый drop игнорируется.
*/
export function useFileDropZone({ enabled, busy = false, onFiles }) {
const [dragOver, setDragOver] = useState(false);
const depthRef = useRef(0);
if (!enabled) return { dragOver: false, zoneProps: {}, strayDropProps: {} };
const zoneProps = {
onDragEnter: (e) => {
if (!isFileDrag(e)) return;
e.preventDefault();
depthRef.current += 1;
setDragOver(true);
},
onDragOver: (e) => {
if (!isFileDrag(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = busy ? "none" : "copy";
},
onDragLeave: (e) => {
if (!isFileDrag(e)) return;
depthRef.current = Math.max(0, depthRef.current - 1);
if (depthRef.current === 0) setDragOver(false);
},
onDrop: (e) => {
if (!isFileDrag(e)) return;
e.preventDefault();
e.stopPropagation();
depthRef.current = 0;
setDragOver(false);
if (!busy) onFiles(e.dataTransfer.files);
},
};
const strayDropProps = {
onDragOver: (e) => { if (isFileDrag(e)) e.preventDefault(); },
onDrop: (e) => { if (isFileDrag(e)) e.preventDefault(); },
};
return { dragOver, zoneProps, strayDropProps };
}