Add drag-to-pan + zoom photo repositioning for card/avatar crops

Every photo upload (session setup, novena group, Rosary Builder title
photo) gets shown two ways: full-size on the presentation cover slide
(unaffected, stays untouched), and cropped to a fixed box everywhere else
— home page cards, profile cards, the novena day-picker's circular hero
photo, and each admin form's own preview thumbnail. All of those crops
used to just take the image's dead center, with no way to control what
part of the photo that was — cropping out people's heads on portrait
photos.

- New sessions/novena_groups columns: photo_focal_x, photo_focal_y (0-100%),
  photo_zoom (1-3x), defaulting to 50/50/1 — today's exact centered/
  unzoomed behavior, so this is fully backward compatible until someone
  actively repositions a photo.

- New assets/js/photo-crop.js: a reusable drag-to-pan + zoom modal editor.
  The crop frame renders with the *exact* CSS recipe used at final render
  time (object-position + transform:scale/transform-origin), so the editor
  is a truthful live preview, not an approximation. A reference thumbnail
  shows the full photo dimmed outside a rectangle marking the current crop.
  All math reads actual rendered box dimensions rather than assuming fixed
  pixel sizes, so it holds up responsively at any viewport width — caught
  and fixed a real mismatch bug here by testing the widget standalone in a
  browser before wiring it into any PHP form.

- New includes/photo.php: photo_crop_style() builds the inline style="..."
  from a session/group row, used everywhere a crop is displayed.

- Wired into all three upload locations (admin/setup.php,
  admin/novena_group.php, admin/builder.php) with a "Reposition" button,
  and persisted through api/save_session.php, admin/novena_group.php's
  save handler, and api/builder_session.php.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-15 15:10:43 -07:00
parent 524860df1f
commit 3a1433b71e
16 changed files with 655 additions and 42 deletions
+77
View File
@@ -97,6 +97,79 @@
// Save session
document.getElementById('btn-save').addEventListener('click', saveSession);
// Title page photo upload
document.getElementById('photo-file').addEventListener('change', uploadPhoto);
document.getElementById('photo-reposition').addEventListener('click', repositionPhoto);
}
/* ─────────────────────────────────────────────────────────
Title page photo
───────────────────────────────────────────────────────── */
function applyPhotoCropStyle() {
const previewImg = document.getElementById('photo-preview');
const fx = document.getElementById('photo-focal-x').value;
const fy = document.getElementById('photo-focal-y').value;
const zoom = document.getElementById('photo-zoom').value;
previewImg.style.cssText =
'object-position:' + fx + '% ' + fy + '%;transform:scale(' + zoom + ');transform-origin:' + fx + '% ' + fy + '%;';
}
function uploadPhoto() {
const fileInput = document.getElementById('photo-file');
const photoHidden = document.getElementById('photo-path');
const focalXHidden = document.getElementById('photo-focal-x');
const focalYHidden = document.getElementById('photo-focal-y');
const zoomHidden = document.getElementById('photo-zoom');
const photoStatus = document.getElementById('photo-status');
const previewWrap = document.querySelector('#photo-group .photo-preview-wrap');
const previewImg = document.getElementById('photo-preview');
const repositionBtn = document.getElementById('photo-reposition');
const file = fileInput.files[0];
if (!file) return;
const fd = new FormData();
fd.append('photo', file);
fd.append('csrf_token', CSRF_TOKEN);
photoStatus.textContent = 'Uploading…';
fetch(BASE_URL + '/api/upload_photo.php', { method: 'POST', body: fd })
.then(function (r) { return r.json(); })
.then(function (data) {
if (data.path) {
photoHidden.value = data.path;
// A newly uploaded photo starts centered/unzoomed — it's
// a different photo than whatever crop was set before.
focalXHidden.value = 50;
focalYHidden.value = 50;
zoomHidden.value = 1;
previewImg.src = '/' + data.path.replace(/^\//, '');
applyPhotoCropStyle();
previewWrap.style.display = '';
repositionBtn.style.display = '';
photoStatus.textContent = 'Photo ready.';
} else {
photoStatus.textContent = 'Upload failed: ' + (data.error || 'unknown error');
}
})
.catch(function () { photoStatus.textContent = 'Upload failed.'; });
}
function repositionPhoto() {
const previewImg = document.getElementById('photo-preview');
PhotoCrop.open({
imageUrl: previewImg.src,
focalX: parseFloat(document.getElementById('photo-focal-x').value),
focalY: parseFloat(document.getElementById('photo-focal-y').value),
zoom: parseFloat(document.getElementById('photo-zoom').value),
onApply: function (fx, fy, zoom) {
document.getElementById('photo-focal-x').value = fx;
document.getElementById('photo-focal-y').value = fy;
document.getElementById('photo-zoom').value = zoom;
applyPhotoCropStyle();
}
});
}
/* ─────────────────────────────────────────────────────────
@@ -453,6 +526,10 @@
subject_name: document.getElementById('subject-name').value.trim(),
subject_pronoun: document.getElementById('subject-pronoun').value,
subject_dates: document.getElementById('subject-dates').value.trim(),
photo_path: document.getElementById('photo-path').value.trim(),
photo_focal_x: parseFloat(document.getElementById('photo-focal-x').value) || 50,
photo_focal_y: parseFloat(document.getElementById('photo-focal-y').value) || 50,
photo_zoom: parseFloat(document.getElementById('photo-zoom').value) || 1,
steps: STEPS.map(s => s.step_type === 'bead'
? { step_type: 'bead', bead_type: s.bead_type }
: { step_type: 'prayer', prayer_id: s.prayer_id, attribution: s.attribution, bead_type: s.bead_type || null }),
+213
View File
@@ -0,0 +1,213 @@
/**
* photo-crop.js — reusable drag-to-pan + zoom photo crop editor.
*
* Usage:
* PhotoCrop.open({
* imageUrl: '/uploads/xyz.jpg',
* focalX: 50, focalY: 50, zoom: 1, // current stored values (0-100, 0-100, 1-2.5)
* onApply: function (focalX, focalY, zoom) { ... }
* });
*
* The crop frame uses the exact same CSS recipe (object-position + transform
* scale/transform-origin) that final card thumbnails use elsewhere in the
* app, so what you see here is what renders everywhere else.
*
* All math reads the frame/reference boxes' *actual rendered* size
* (getBoundingClientRect) rather than assuming fixed pixel dimensions —
* the boxes are responsive (aspect-ratio + max-width:100%), so this must
* hold at any viewport size, mobile included.
*/
var PhotoCrop = (function () {
'use strict';
var FRAME_DEFAULT_W = 320, FRAME_DEFAULT_H = 160; // initial size hint only
var REF_DEFAULT_W = 160, REF_DEFAULT_H = 160;
var ZOOM_MIN = 1, ZOOM_MAX = 2.5;
var els = null; // DOM refs, built once
var state = null; // { naturalW, naturalH, focalX, focalY, zoom, onApply }
var drag = null; // { startX, startY, startFocalX, startFocalY } while dragging
function ensureBuilt() {
if (els) return;
var overlay = document.createElement('div');
overlay.className = 'photo-crop-overlay';
overlay.innerHTML =
'<div class="photo-crop-box">' +
' <h3>Reposition Photo</h3>' +
' <div class="photo-crop-main">' +
' <div class="photo-crop-frame" style="width:' + FRAME_DEFAULT_W + 'px;height:' + FRAME_DEFAULT_H + 'px">' +
' <img class="photo-crop-frame-img" alt="">' +
' </div>' +
' <div class="photo-crop-ref" style="width:' + REF_DEFAULT_W + 'px;height:' + REF_DEFAULT_H + 'px">' +
' <img class="photo-crop-ref-img" alt="">' +
' <div class="photo-crop-ref-rect"></div>' +
' </div>' +
' </div>' +
' <div class="photo-crop-zoom-row">' +
' <label>Zoom</label>' +
' <input type="range" class="photo-crop-zoom-slider" min="' + ZOOM_MIN + '" max="' + ZOOM_MAX + '" step="0.05">' +
' </div>' +
' <p class="photo-crop-hint">Drag the photo to reposition it. Scroll or use the slider to zoom.</p>' +
' <div class="photo-crop-actions">' +
' <button type="button" class="btn btn-ghost photo-crop-reset">Reset</button>' +
' <div style="flex:1"></div>' +
' <button type="button" class="btn btn-ghost photo-crop-cancel">Cancel</button>' +
' <button type="button" class="btn btn-primary photo-crop-apply">Apply</button>' +
' </div>' +
'</div>';
document.body.appendChild(overlay);
els = {
overlay: overlay,
frame: overlay.querySelector('.photo-crop-frame'),
frameImg: overlay.querySelector('.photo-crop-frame-img'),
ref: overlay.querySelector('.photo-crop-ref'),
refImg: overlay.querySelector('.photo-crop-ref-img'),
refRect: overlay.querySelector('.photo-crop-ref-rect'),
zoomSlider: overlay.querySelector('.photo-crop-zoom-slider'),
};
overlay.addEventListener('click', function (e) {
if (e.target === overlay) close();
});
overlay.querySelector('.photo-crop-cancel').addEventListener('click', close);
overlay.querySelector('.photo-crop-reset').addEventListener('click', function () {
state.focalX = 50; state.focalY = 50; state.zoom = 1;
render();
});
overlay.querySelector('.photo-crop-apply').addEventListener('click', function () {
var cb = state.onApply;
var fx = state.focalX, fy = state.focalY, z = state.zoom;
close();
if (cb) cb(fx, fy, z);
});
els.zoomSlider.addEventListener('input', function () {
state.zoom = parseFloat(els.zoomSlider.value);
clampFocal();
render();
});
els.frame.addEventListener('wheel', function (e) {
e.preventDefault();
var delta = e.deltaY < 0 ? 0.1 : -0.1;
state.zoom = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, state.zoom + delta));
clampFocal();
render();
}, { passive: false });
els.frame.addEventListener('pointerdown', function (e) {
drag = { startX: e.clientX, startY: e.clientY, startFocalX: state.focalX, startFocalY: state.focalY };
els.frame.setPointerCapture(e.pointerId);
});
els.frame.addEventListener('pointermove', function (e) {
if (!drag) return;
var f = frameSize();
var coverScale = Math.max(f.w / state.naturalW, f.h / state.naturalH);
var effW = state.naturalW * coverScale * state.zoom;
var effH = state.naturalH * coverScale * state.zoom;
var dxPct = -((e.clientX - drag.startX) / effW) * 100;
var dyPct = -((e.clientY - drag.startY) / effH) * 100;
state.focalX = drag.startFocalX + dxPct;
state.focalY = drag.startFocalY + dyPct;
clampFocal();
render();
});
var endDrag = function () { drag = null; };
els.frame.addEventListener('pointerup', endDrag);
els.frame.addEventListener('pointercancel', endDrag);
}
function frameSize() {
var r = els.frame.getBoundingClientRect();
return { w: r.width, h: r.height };
}
function refSize() {
var r = els.ref.getBoundingClientRect();
return { w: r.width, h: r.height };
}
/** Keep the crop window within the image's natural bounds. */
function clampFocal() {
var f = frameSize();
var coverScale = Math.max(f.w / state.naturalW, f.h / state.naturalH);
var cropW = f.w / (coverScale * state.zoom);
var cropH = f.h / (coverScale * state.zoom);
var minX = (cropW / 2) / state.naturalW * 100;
var maxX = 100 - minX;
var minY = (cropH / 2) / state.naturalH * 100;
var maxY = 100 - minY;
// If the crop window is bigger than the image on an axis (zoom≈min),
// min > max — just center it.
state.focalX = minX <= maxX ? Math.max(minX, Math.min(maxX, state.focalX)) : 50;
state.focalY = minY <= maxY ? Math.max(minY, Math.min(maxY, state.focalY)) : 50;
}
function render() {
var fx = state.focalX.toFixed(2), fy = state.focalY.toFixed(2), z = state.zoom.toFixed(3);
var cropStyle = 'object-position:' + fx + '% ' + fy + '%;transform:scale(' + z + ');transform-origin:' + fx + '% ' + fy + '%;';
els.frameImg.style.cssText = cropStyle;
els.zoomSlider.value = state.zoom;
// Reference thumbnail: full image, contain-fit, with a rectangle
// overlay marking the current crop window (dimmed outside it via
// a CSS box-shadow "spotlight").
var f = frameSize(), rf = refSize();
var containScale = Math.min(rf.w / state.naturalW, rf.h / state.naturalH);
var imgW = state.naturalW * containScale, imgH = state.naturalH * containScale;
var offX = (rf.w - imgW) / 2, offY = (rf.h - imgH) / 2;
var coverScale = Math.max(f.w / state.naturalW, f.h / state.naturalH);
var cropNatW = f.w / (coverScale * state.zoom);
var cropNatH = f.h / (coverScale * state.zoom);
var centerXnat = (state.focalX / 100) * state.naturalW;
var centerYnat = (state.focalY / 100) * state.naturalH;
var cropLeftNat = centerXnat - cropNatW / 2;
var cropTopNat = centerYnat - cropNatH / 2;
var rectLeft = offX + cropLeftNat * containScale;
var rectTop = offY + cropTopNat * containScale;
var rectW = cropNatW * containScale;
var rectH = cropNatH * containScale;
els.refRect.style.left = rectLeft + 'px';
els.refRect.style.top = rectTop + 'px';
els.refRect.style.width = rectW + 'px';
els.refRect.style.height = rectH + 'px';
}
function open(opts) {
ensureBuilt();
state = {
naturalW: 0, naturalH: 0,
focalX: opts.focalX != null ? opts.focalX : 50,
focalY: opts.focalY != null ? opts.focalY : 50,
zoom: opts.zoom != null ? opts.zoom : 1,
onApply: opts.onApply,
};
els.overlay.classList.add('open');
els.frameImg.style.cssText = '';
els.refRect.style.display = 'none';
var loader = new Image();
loader.onload = function () {
state.naturalW = loader.naturalWidth;
state.naturalH = loader.naturalHeight;
els.frameImg.src = opts.imageUrl;
els.refImg.src = opts.imageUrl;
els.refRect.style.display = '';
clampFocal();
render();
};
loader.src = opts.imageUrl;
}
function close() {
if (els) els.overlay.classList.remove('open');
drag = null;
}
return { open: open, close: close };
})();
+38
View File
@@ -89,6 +89,34 @@
// ------------------------------------------------------------------
var photoUploading = false;
function applyPhotoCropStyle() {
var previewImg = document.getElementById('photo-preview');
var fx = document.getElementById('photo_focal_x').value;
var fy = document.getElementById('photo_focal_y').value;
var zoom = document.getElementById('photo_zoom').value;
previewImg.style.cssText =
'object-position:' + fx + '% ' + fy + '%;transform:scale(' + zoom + ');transform-origin:' + fx + '% ' + fy + '%;';
}
var repositionBtn = document.getElementById('photo-reposition');
if (repositionBtn) {
repositionBtn.addEventListener('click', function () {
var previewImg = document.getElementById('photo-preview');
PhotoCrop.open({
imageUrl: previewImg.src,
focalX: parseFloat(document.getElementById('photo_focal_x').value),
focalY: parseFloat(document.getElementById('photo_focal_y').value),
zoom: parseFloat(document.getElementById('photo_zoom').value),
onApply: function (fx, fy, zoom) {
document.getElementById('photo_focal_x').value = fx;
document.getElementById('photo_focal_y').value = fy;
document.getElementById('photo_zoom').value = zoom;
applyPhotoCropStyle();
}
});
});
}
if (photoInput) {
photoInput.addEventListener('change', async function () {
if (!this.files || !this.files[0]) return;
@@ -115,6 +143,16 @@
uploadStatus.textContent = 'Upload failed: ' + data.error;
} else {
document.getElementById('photo_path').value = data.path;
// A newly uploaded photo starts centered/unzoomed.
document.getElementById('photo_focal_x').value = 50;
document.getElementById('photo_focal_y').value = 50;
document.getElementById('photo_zoom').value = 1;
var previewImg = document.getElementById('photo-preview');
var previewWrap = document.querySelector('#field-photo .photo-preview-wrap');
previewImg.src = '/' + data.path.replace(/^\//, '');
applyPhotoCropStyle();
previewWrap.style.display = '';
document.getElementById('photo-reposition').style.display = '';
// Clear the file input so the file is not re-sent with the main form
photoInput.value = '';
uploadStatus.className = 'upload-status success';