From 0b7c8d6c56b4641eb41bce25f3a95d863f74e1c1 Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Mon, 20 Apr 2020 16:34:38 +1000 Subject: [PATCH] Added map grid size detection from file name --- src/components/AddMapButton.js | 12 +++++++++--- src/modals/AddMapModal.js | 22 ++++++++++++++++++++-- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/components/AddMapButton.js b/src/components/AddMapButton.js index ff16071..16baa75 100644 --- a/src/components/AddMapButton.js +++ b/src/components/AddMapButton.js @@ -19,14 +19,14 @@ function AddMapButton({ onMapChange }) { const mapDataRef = useRef(null); const [mapSource, setMapSource] = useState(null); - function handleImageUpload(file) { + function handleImageUpload(file, fileGridX, fileGridY) { const url = URL.createObjectURL(file); let image = new Image(); image.onload = function () { mapDataRef.current = { file, - gridX: gridX, - gridY: gridY, + gridX: fileGridX || gridX, + gridY: fileGridY || gridY, width: image.width, height: image.height, }; @@ -34,6 +34,12 @@ function AddMapButton({ onMapChange }) { }; image.src = url; setMapSource(url); + if (fileGridX) { + setGridX(fileGridX); + } + if (fileGridY) { + setGridY(fileGridY); + } } function handleDone() { diff --git a/src/modals/AddMapModal.js b/src/modals/AddMapModal.js index 8edc778..dedd74c 100644 --- a/src/modals/AddMapModal.js +++ b/src/modals/AddMapModal.js @@ -25,6 +25,24 @@ function AddMapModal({ }) { const fileInputRef = useRef(); + function handleImageUpload(file) { + if (file.name) { + // Match against a regex to find the grid size in the file name + // e.g. Cave 22x23 will return [["22x22", "22", "x", "23"]] + const gridMatches = [...file.name.matchAll(/(\d+) ?(x|X) ?(\d+)/g)]; + if (gridMatches.length > 0) { + const lastMatch = gridMatches[gridMatches.length - 1]; + const matchX = parseInt(lastMatch[1]); + const matchY = parseInt(lastMatch[3]); + if (!isNaN(matchX) && !isNaN(matchY)) { + onImageUpload(file, matchX, matchY); + return; + } + } + } + onImageUpload(file); + } + function openImageDialog() { if (fileInputRef.current) { fileInputRef.current.click(); @@ -49,7 +67,7 @@ function AddMapModal({ event.stopPropagation(); const file = event.dataTransfer.files[0]; if (file && file.type.startsWith("image")) { - onImageUpload(file); + handleImageUpload(file); } setDragging(false); } @@ -65,7 +83,7 @@ function AddMapModal({ onDragEnter={handleImageDragEnter} > onImageUpload(event.target.files[0])} + onChange={(event) => handleImageUpload(event.target.files[0])} type="file" accept="image/*" style={{ display: "none" }}