feat: add image preview and Labelary ZPL render preview
This commit is contained in:
142
cmd/web/main.go
142
cmd/web/main.go
@@ -8,11 +8,13 @@ import (
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/anthonynsimon/bild/blur"
|
||||
"github.com/anthonynsimon/bild/effect"
|
||||
@@ -163,10 +165,61 @@ func previewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, `{"width":%d,"height":%d}`, cfg.Width, cfg.Height)
|
||||
}
|
||||
|
||||
var labelaryClient = &http.Client{Timeout: 15 * time.Second}
|
||||
|
||||
func renderHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
dpmm := r.URL.Query().Get("dpmm")
|
||||
width := r.URL.Query().Get("width")
|
||||
height := r.URL.Query().Get("height")
|
||||
if dpmm == "" {
|
||||
dpmm = "8"
|
||||
}
|
||||
if width == "" {
|
||||
width = "4"
|
||||
}
|
||||
if height == "" {
|
||||
height = "6"
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to read body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("http://api.labelary.com/v1/printers/%s/labels/%sx%s/0/", dpmm, width, height)
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
http.Error(w, "failed to build request", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "image/png")
|
||||
|
||||
resp, err := labelaryClient.Do(req)
|
||||
if err != nil {
|
||||
http.Error(w, "labelary unreachable: "+err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
http.Error(w, "labelary returned "+resp.Status, http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
io.Copy(w, resp.Body)
|
||||
}
|
||||
|
||||
func main() {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/convert", convertHandler)
|
||||
mux.HandleFunc("/preview", previewHandler)
|
||||
mux.HandleFunc("/render", renderHandler)
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Write([]byte(indexHTML))
|
||||
@@ -302,6 +355,34 @@ const indexHTML = `<!DOCTYPE html>
|
||||
.dl-btn { margin-top: 0.75rem; background: #2d6a4f; }
|
||||
.dl-btn:hover { background: #215040; }
|
||||
.error { color: #fc8181; font-size: 0.85rem; margin-top: 0.75rem; display: none; }
|
||||
|
||||
/* previews */
|
||||
.preview-panel {
|
||||
margin-bottom: 1.5rem; display: none;
|
||||
}
|
||||
.preview-panel .panel-header {
|
||||
font-size: 0.8rem; font-weight: 600; color: #a0aec0; margin-bottom: 0.5rem;
|
||||
}
|
||||
.preview-panel img {
|
||||
max-width: 100%; max-height: 260px; object-fit: contain;
|
||||
border-radius: 6px; border: 1px solid #2d3348; background: #fff;
|
||||
display: block;
|
||||
}
|
||||
.preview-panel .panel-meta {
|
||||
font-size: 0.75rem; color: #718096; margin-top: 0.35rem;
|
||||
}
|
||||
.label-preview-wrap {
|
||||
margin-top: 1.25rem; display: none;
|
||||
}
|
||||
.label-preview-wrap .panel-header {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
font-size: 0.8rem; font-weight: 600; color: #a0aec0; margin-bottom: 0.5rem;
|
||||
}
|
||||
.label-preview-wrap img {
|
||||
max-width: 100%; border-radius: 6px; border: 1px solid #2d3348;
|
||||
background: #fff; display: block;
|
||||
}
|
||||
.render-status { font-size: 0.75rem; color: #718096; font-weight: 400; }
|
||||
.spinner {
|
||||
display: none; width: 18px; height: 18px;
|
||||
border: 2px solid #ffffff40; border-top-color: #fff;
|
||||
@@ -324,6 +405,13 @@ const indexHTML = `<!DOCTYPE html>
|
||||
<div class="preview-info" id="previewInfo"></div>
|
||||
</div>
|
||||
|
||||
<!-- Image preview (original) -->
|
||||
<div class="preview-panel" id="imgPreviewPanel">
|
||||
<div class="panel-header">Image Preview</div>
|
||||
<img id="imgPreviewEl" alt="preview">
|
||||
<div class="panel-meta" id="imgPreviewMeta"></div>
|
||||
</div>
|
||||
|
||||
<!-- Unit toggle + DPI -->
|
||||
<div class="unit-row">
|
||||
<span>Dimensions in</span>
|
||||
@@ -382,6 +470,15 @@ const indexHTML = `<!DOCTYPE html>
|
||||
</div>
|
||||
<textarea id="zplOutput" readonly></textarea>
|
||||
<button class="dl-btn" id="dlBtn">⬇ Download .zpl</button>
|
||||
|
||||
<!-- Labelary rendered preview -->
|
||||
<div class="label-preview-wrap" id="labelPreviewWrap">
|
||||
<div class="panel-header">
|
||||
<span>Label Preview <span style="font-weight:400;color:#718096">(rendered by Labelary)</span></span>
|
||||
<span class="render-status" id="renderStatus"></span>
|
||||
</div>
|
||||
<img id="labelPreviewImg" alt="label preview">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -398,6 +495,7 @@ const errorEl = document.getElementById('error');
|
||||
let selectedFile = null;
|
||||
let currentUnit = 'px'; // 'px' or 'cm'
|
||||
let origPxW = 0, origPxH = 0; // image native pixel dimensions
|
||||
let imgObjectURL = null;
|
||||
|
||||
function getDPI() { return parseInt(document.getElementById('dpi').value, 10); }
|
||||
|
||||
@@ -473,6 +571,12 @@ function setFile(file) {
|
||||
previewInfo.textContent = 'Loading…';
|
||||
convertBtn.disabled = true;
|
||||
|
||||
// Show image preview immediately
|
||||
if (imgObjectURL) URL.revokeObjectURL(imgObjectURL);
|
||||
imgObjectURL = URL.createObjectURL(file);
|
||||
document.getElementById('imgPreviewEl').src = imgObjectURL;
|
||||
document.getElementById('imgPreviewPanel').style.display = 'block';
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fetch('/preview', { method: 'POST', body: fd })
|
||||
@@ -496,6 +600,9 @@ function setFile(file) {
|
||||
file.name + ' — ' + origPxW + ' × ' + origPxH + ' px' +
|
||||
' (' + cmW + ' × ' + cmH + ' cm at ' + getDPI() + ' dpi)';
|
||||
|
||||
document.getElementById('imgPreviewMeta').textContent =
|
||||
origPxW + ' × ' + origPxH + ' px | ' + cmW + ' × ' + cmH + ' cm at ' + getDPI() + ' dpi';
|
||||
|
||||
updateSubLabels();
|
||||
convertBtn.disabled = false;
|
||||
})
|
||||
@@ -515,12 +622,46 @@ function getPixelDimensions() {
|
||||
return { w: Math.round(w), h: Math.round(h) };
|
||||
}
|
||||
|
||||
function dpmmFromDPI(dpi) {
|
||||
const map = { 203: 8, 300: 12, 600: 24 };
|
||||
return map[dpi] || 8;
|
||||
}
|
||||
|
||||
async function fetchLabelPreview(zpl, pxW, pxH) {
|
||||
const dpi = getDPI();
|
||||
const dpmm = dpmmFromDPI(dpi);
|
||||
// Labelary needs label size in inches; clamp minimum to avoid API errors
|
||||
const wIn = Math.max(pxW / dpi, 0.1).toFixed(4);
|
||||
const hIn = Math.max(pxH / dpi, 0.1).toFixed(4);
|
||||
|
||||
const wrap = document.getElementById('labelPreviewWrap');
|
||||
const status = document.getElementById('renderStatus');
|
||||
wrap.style.display = 'block';
|
||||
status.textContent = 'Rendering…';
|
||||
document.getElementById('labelPreviewImg').src = '';
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
'/render?dpmm=' + dpmm + '&width=' + wIn + '&height=' + hIn,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: zpl }
|
||||
);
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
document.getElementById('labelPreviewImg').src = url;
|
||||
status.textContent = wIn + '" × ' + hIn + '" at ' + dpi + ' dpi';
|
||||
} catch (e) {
|
||||
status.textContent = 'Preview unavailable: ' + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
convertBtn.addEventListener('click', async () => {
|
||||
if (!selectedFile) return;
|
||||
errorEl.style.display = 'none';
|
||||
convertBtn.style.display = 'none';
|
||||
spinner.style.display = 'block';
|
||||
output.style.display = 'none';
|
||||
document.getElementById('labelPreviewWrap').style.display = 'none';
|
||||
|
||||
const { w, h } = getPixelDimensions();
|
||||
const edits = [...document.querySelectorAll('input[name=edit]:checked')].map(c => c.value);
|
||||
@@ -540,6 +681,7 @@ convertBtn.addEventListener('click', async () => {
|
||||
const text = await res.text();
|
||||
zplOutput.value = text;
|
||||
output.style.display = 'block';
|
||||
fetchLabelPreview(text, w || origPxW, h || origPxH);
|
||||
} catch (e) {
|
||||
errorEl.textContent = 'Error: ' + e.message;
|
||||
errorEl.style.display = 'block';
|
||||
|
||||
Reference in New Issue
Block a user