import { loadCatalog, sizesFor, imageAt, formatPrice } from './catalog.js';
import { A_SIZES, FINISHES, printDims, buildPrint, buildArrangement, loadImage, makeArtTexture, makeOakTexture } from './print-model.js';
import { wallArSupported, startWallAr } from './ar-wall.js';
import { startCameraAr, askForMotion, cameraAvailable, goFullScreen } from './ar-camera.js';
import { renderPrintImage } from './print-render.js';
import { photosFromFiles } from './room/capture.js';
import { analyseRoom, artPalettes, rankArt } from './room/recommend.js';
import { hex } from './room/colour.js';
import { RoomComposer } from './room/composer.js';
import { place } from './room/layouts.js';
import { plan3D, bestForCount, arrangementFits, SIZES } from './room/planner.js';
const $ = (id) => document.getElementById(id);
const root = document.querySelector('.viewer');
const STORE = root.dataset.store.replace(/\/$/, '');
const ui = {
stage: $('stage-section'), status: $('stage-status'), title: $('art-title'), openPicker: $('open-picker'),
finishGroup: $('finish-group'), finishNote: $('finish-note'), sizeList: $('size-list'), footprint: $('footprint'),
arButton: $('ar-button'), saveButton: $('save-button'), arNote: $('ar-note'), buy: $('buy-link'),
picker: $('picker'), pickerTitle: $('picker-title'), pickerGrid: $('picker-grid'), pickerSearch: $('picker-search'), pickerEmpty: $('picker-empty'),
qr: $('qr'), qrCode: $('qr-code'), qrText: $('qr-text'),
roomStart: $('room-start'), roomCompose: $('room-compose'), roomError: $('room-error'), startTitle: $('start-title'), wallChoice: $('wall-choice'),
photoInput: $('photo-input'), roomPhotos: $('room-photos'), scaleNote: $('scale-note'),
scaleForm: $('scale-form'), scaleRef: $('scale-ref'), scaleCustom: $('scale-custom'), scaleCm: $('scale-cm'),
picks: $('picks'), picksStatus: $('picks-status'), picksNote: $('picks-note'), why: $('room-why'), swatches: $('room-swatches'),
ask: $('art-ask'), askText: $('art-ask-text'), changeChoice: $('change-choice'), getPicks: $('get-picks'),
options: $('options'), suits: $('suits'), suitsTitle: $('suits-title'), suitsGrid: $('suits-grid'), suitsMore: $('suits-more'), tray: $('tray-list'), trayNote: $('tray-note'),
};
const oakTex = makeOakTexture();
const composer = new RoomComposer($('room-canvas'), $('scale-svg'));
const fmtCm = (n) => n.toFixed(1).replace(/\.0$/, '');
const FINISH_NOTES = {
canvas: 'Stretched canvas, 2.5 cm deep, wrapped round the edges',
poster: 'Paper print in a slim black frame',
photorag: 'Fine-art paper with a white mat in an oak frame',
};
const SINGLE = { template: 'single', side: 1, slots: [0], existingCm: null };
const state = {
catalog: [], images: new Map(), textures: new Map(),
// What hangs: pieces positioned by a layout from their real sizes (offsets in cm from the anchor).
pieces: [], focus: 0, layout: SINGLE,
ghost: null, // [w, h] cm of a piece the customer already owns, kept in an arrangement
anchor: null, // [x, y] photo fractions where the layout hangs in the room photo
hide: null, // { photo, box } existing art painted out of a room photo when replacing it
mode: 'room', photos: [], photo: 0, palettes: null, sideboard: { width: 244, height: 68 },
advice: null, adviceRun: 0, choice: null, activeOption: null, pickerMode: 'swap',
};
const piece = () => state.pieces[state.focus];
const byHandle = (h) => state.catalog.find((a) => a.handle === h);
const mainExisting = () => state.advice?.existing_art?.[0] || null;
const material = (p = piece()) => FINISHES[p.finish].material;
const dimsOf = (q, size = q.size, finish = q.finish) => printDims(finish, size, q.art.landscape).outer;
// The wall the pieces are planned for: the customer's wall (from the advisor) or the 3D wall.
function activePlan() {
const plans = state.advice?.plans;
if (plans) return state.ghost && plans.around ? plans.around : plans.base;
return plan3D(state.sideboard);
}
// The wall map only applies on the photo it was made from.
const onPlannedPhoto = () => state.advice && state.mode === 'room' && state.photo === state.advice.plans.base.photo;
// ---------- startup ----------
async function start() {
showStatus('Loading the collection');
try {
state.catalog = await loadCatalog(STORE, root.dataset.catalog);
} catch {
showStatus(`Couldn't reach ${new URL(STORE).host}. Check your connection, then try again.`, true);
return;
}
if (!state.catalog.length) return showStatus('The shop has no artworks to show yet.');
const q = new URLSearchParams(location.search);
state.pieces = [{
art: byHandle(q.get('art')) || state.catalog[0],
finish: FINISHES[q.get('finish')] ? q.get('finish') : 'canvas',
size: A_SIZES[q.get('size')] ? q.get('size') : 'A2',
offset: [0, 0],
}];
ui.openPicker.disabled = false;
renderPicker();
await selectArt(piece().art);
if (q.get('open') === 'camera') openArtViewer(false);
}
function showStatus(text, retry = false) {
ui.status.hidden = false;
ui.status.replaceChildren(text);
if (retry) {
const b = Object.assign(document.createElement('button'), { className: 'button button--primary', textContent: 'Try again' });
b.addEventListener('click', start);
ui.status.append(b);
}
}
async function ensureImage(art) {
if (state.images.has(art.handle)) return true;
showStatus(`Hanging ${art.title}`);
try {
state.images.set(art.handle, await loadImage(imageAt(art.image, 2048)));
return true;
} catch {
showStatus(`The image for ${art.title} didn't load. Choose another artwork or try again later.`);
return false;
}
}
// ---------- what hangs ----------
// Puts `art` in the focused spot.
async function selectArt(art) {
piece().art = art;
renderPanel();
if (!(await ensureImage(art)) || piece().art !== art) return;
ui.status.hidden = true;
update();
}
// Replaces what hangs: the pieces, the layout that positions them, and where it hangs in the room photo.
async function applyLayout({ pieces, layout = SINGLE, ghost = null, anchor = null, hide = null, focus = 0 }) {
state.pieces = pieces;
state.layout = layout;
state.focus = Math.min(focus, pieces.length - 1);
state.ghost = ghost;
state.anchor = anchor;
state.anchorFresh = !!anchor; // hang at the planned spot once; after that the customer may drag it
state.hide = hide;
reflow();
renderPanel();
const ok = await Promise.all(pieces.map((p) => ensureImage(p.art)));
if (state.pieces !== pieces || ok.includes(false)) return;
ui.status.hidden = true;
update();
}
// Positions always come from the layout and the pieces' real sizes, so changing a piece re-flows the group
// and nothing can overlap.
function reflow() {
const { offsets } = place(state.layout, state.pieces.map((q) => dimsOf(q)), state.layout.existingCm);
state.pieces.forEach((q, i) => { q.offset = offsets[i]; });
}
function specFor(p) {
const [pw, ph] = printDims(p.finish, p.size, p.art.landscape).print;
const key = `${p.art.handle}:${(pw / ph).toFixed(4)}`;
if (!state.textures.has(key)) state.textures.set(key, makeArtTexture(state.images.get(p.art.handle), pw / ph, p.art.squeeze));
return { finish: p.finish, size: p.size, landscape: p.art.landscape, artTex: state.textures.get(key), oakTex };
}
const grouped = () => state.pieces.length > 1 || !!state.ghost;
function buildScene() {
const specs = state.pieces.map(specFor);
return grouped()
? buildArrangement(specs.map((spec, i) => ({ spec, offset: state.pieces[i].offset })), state.ghost)
: buildPrint(specs[0]);
}
function update() {
reflow();
const p = piece();
const variant = p.art.variants[material()][p.size];
ui.buy.href = `${STORE}/cart/add?id=${variant.id}&quantity=1`; // adds the chosen print and size, then shows the cart
ui.buy.textContent = grouped() ? 'Buy this piece' : 'Buy this print';
const scene = buildScene();
const [w, h] = dimsOf(p);
let text = `${fmtCm(w)} × ${fmtCm(h)} cm${p.finish === 'canvas' ? '' : ' with the frame'}, ${formatPrice(variant.price)}.`;
if (grouped()) text += ` Whole group ${fmtCm(scene.userData.dims.outer[0])} × ${fmtCm(scene.userData.dims.outer[1])} cm.`;
ui.footprint.textContent = text;
const params = { art: p.art.handle, finish: p.finish, size: p.size };
history.replaceState(null, '', `?${new URLSearchParams(params)}`);
// The room-photo pictures need their own renderer: only make them in the room view (saves memory on phones).
if (state.mode === 'room') composer.setLayout(
state.awaitingChoice ? [] : state.pieces.map((q) => {
const d = printDims(q.finish, q.size, q.art.landscape);
return { image: renderPrintImage(buildPrint(specFor(q))), outerCm: d.outer, depthCm: d.depth, offsetCm: q.offset };
}),
state.anchorFresh ? state.anchor : null,
state.hide && state.hide.photo === state.photo ? state.hide.box : null,
);
if (state.mode === 'room') state.anchorFresh = false;
renderSizes();
ui.arButton.disabled = false;
ui.arButton.textContent = grouped() ? 'See the group on your wall' : 'See it on your wall';
}
// The customer can only drag the group around the wall the advisor mapped.
composer.allowed = (anchorPx) => {
if (!onPlannedPhoto() || !composer.photo) return true;
return arrangementFits(activePlan(), state.layout, state.pieces.map((q) => dimsOf(q)), [anchorPx.x / composer.photo.width, anchorPx.y / composer.photo.height]);
};
// ---------- the panel: pieces tray, finish and size ----------
function renderPanel() {
renderTray();
renderFinishes();
renderSizes();
renderOptionsActive();
}
const icon = (d) => ``;
function renderTray() {
const items = [];
if (state.ghost) {
const li = Object.assign(document.createElement('li'), { className: 'tray__item' });
li.append(Object.assign(document.createElement('span'), { className: 'tray__yours', textContent: 'Your piece' }));
items.push(li);
}
state.pieces.forEach((q, i) => {
const li = Object.assign(document.createElement('li'), { className: 'tray__item' });
const b = Object.assign(document.createElement('button'), { type: 'button', className: 'tray__piece' });
b.setAttribute('aria-pressed', String(i === state.focus));
b.setAttribute('aria-label', `Edit ${q.art.title}`);
b.append(Object.assign(new Image(52, 70), { src: imageAt(q.art.image, 120), alt: '' }));
b.addEventListener('click', () => { state.focus = i; renderPanel(); });
li.append(b);
if (state.pieces.length > 1) {
const x = Object.assign(document.createElement('button'), { type: 'button', className: 'tray__remove', innerHTML: icon('M6 6l12 12M18 6L6 18') });
x.setAttribute('aria-label', `Remove ${q.art.title}`);
x.addEventListener('click', () => removePiece(i));
li.append(x);
}
items.push(li);
});
const li = Object.assign(document.createElement('li'), { className: 'tray__item' });
const add = Object.assign(document.createElement('button'), { type: 'button', className: 'tray__add', innerHTML: `${icon('M12 5v14M5 12h14')}Add` });
add.setAttribute('aria-label', 'Add a piece from the collection');
add.addEventListener('click', () => openPicker('add'));
li.append(add);
items.push(li);
ui.tray.replaceChildren(...items);
const p = piece();
ui.title.textContent = p.art.title;
ui.startTitle.textContent = p.art.title;
document.title = `${p.art.title} on your wall | BlueCairo ARt Viewer`;
}
function renderFinishes() {
const p = piece();
for (const input of ui.finishGroup.querySelectorAll('input')) {
input.disabled = !sizesFor(p.art, FINISHES[input.value].material).length;
input.checked = input.value === p.finish;
}
if (!sizesFor(p.art, material()).length) p.finish = ui.finishGroup.querySelector('input:not(:disabled)').value;
ui.finishGroup.querySelector(`input[value="${p.finish}"]`).checked = true;
ui.finishNote.textContent = FINISH_NOTES[p.finish];
}
// One line of sizes; a size is unavailable when sold out, or when the group would no longer fit the wall.
function renderSizes() {
const p = piece();
const sizes = sizesFor(p.art, material());
if (!sizes.includes(p.size)) p.size = sizes.includes('A2') ? 'A2' : sizes[0];
const plan = activePlan();
const anchor = onPlannedPhoto() ? composer.anchorFrac : null;
ui.sizeList.replaceChildren(...sizes.map((size) => {
const v = p.art.variants[material()][size];
const dims = state.pieces.map((q, i) => (i === state.focus ? dimsOf(q, size) : dimsOf(q)));
const fits = size === p.size || arrangementFits(plan, state.layout, dims, anchor);
const label = Object.assign(document.createElement('label'), { className: 'chip' });
label.title = !v.available ? 'Sold out' : !fits ? 'Too big for this wall' : `${formatPrice(v.price)}`;
label.innerHTML = `${size}`;
const input = label.querySelector('input');
input.checked = size === p.size;
input.disabled = !v.available || !fits;
input.setAttribute('aria-label', `${size}${!v.available ? ', sold out' : !fits ? ', too big for this wall' : `, ${formatPrice(v.price)}`}`);
return label;
}));
}
ui.finishGroup.addEventListener('change', (e) => {
if (e.target.name !== 'finish') return;
piece().finish = e.target.value;
renderFinishes();
// A frame adds width: step down a size if the group would no longer fit.
const plan = activePlan();
const anchor = onPlannedPhoto() ? composer.anchorFrac : null;
const fits = (s) => arrangementFits(plan, state.layout, state.pieces.map((q, i) => (i === state.focus ? dimsOf(q, s) : dimsOf(q))), anchor);
if (!fits(piece().size)) {
const smaller = SIZES.slice(0, SIZES.indexOf(piece().size)).reverse().find((s) => sizesFor(piece().art, material()).includes(s) && fits(s));
if (smaller) piece().size = smaller;
}
if (state.images.has(piece().art.handle)) update();
});
$('size-group').addEventListener('change', (e) => {
if (e.target.name !== 'size') return;
piece().size = e.target.value;
if (state.images.has(piece().art.handle)) update();
});
// ---------- adding and removing pieces ----------
// Re-plans the wall for a new set of artworks with the same rules the advisor uses, keeping the chosen finish.
function replan(arts) {
const plan = activePlan();
const keep = piece()?.finish || 'canvas';
return bestForCount(plan, arts, () => keep);
}
function hangPlanned(o, arts, focus) {
const ex = mainExisting();
applyLayout({
pieces: (o.order ? o.order.map((i) => arts[i]) : arts).map((art, i) => ({ art, finish: o.finish, size: o.sizes[i], offset: [0, 0] })),
layout: { template: o.template, side: o.side, slots: o.slots, slope: o.slope, existingCm: state.ghost },
ghost: state.ghost,
anchor: state.ghost && ex ? [(ex.box[0] + ex.box[2]) / 2, (ex.box[1] + ex.box[3]) / 2] : onPlannedPhoto() || state.advice ? o.anchor : state.anchor,
hide: state.hide,
focus: o.order ? o.order.indexOf(focus) : focus, // the balance order may move the piece just added
});
state.activeOption = null;
}
function addPiece(art) {
if (state.pieces.some((q) => q.art === art)) {
ui.trayNote.textContent = `${art.title} is already on your wall.`;
return;
}
const arts = [...state.pieces.map((q) => q.art), art];
const o = replan(arts);
if (!o) {
ui.trayNote.textContent = `There is no room on this wall for another piece. Remove one, or choose smaller sizes.`;
return;
}
ui.trayNote.textContent = '';
hangPlanned(o, arts, arts.length - 1);
}
function removePiece(i) {
const arts = state.pieces.map((q) => q.art).filter((_, j) => j !== i);
const o = replan(arts);
ui.trayNote.textContent = '';
if (o) hangPlanned(o, arts, Math.max(0, i - 1));
else applyLayout({ pieces: state.pieces.filter((_, j) => j !== i), layout: arts.length === 1 && !state.ghost ? SINGLE : state.layout, ghost: state.ghost, hide: state.hide });
}
// ---------- AR ----------
// Two AR modes, one set of controls. Chrome on Android: wall-tracking AR (js/ar-wall.js). Every other browser,
// Brave included (it opens AR but draws nothing in it): the camera view (js/ar-camera.js). No camera at all: a QR
// code for a phone.
let liveAr = false;
wallArSupported().then((ok) => { liveAr = ok; });
let brave = false;
navigator.brave?.isBrave?.().then((v) => { brave = !!v; }).catch(() => {});
const ANDROID = /Android/i.test(navigator.userAgent);
const xrEls = {
root: $('xr'), top: $('xr-top'), sheet: $('xr-sheet'), hint: $('xr-hint'), close: $('xr-close'), video: $('xr-video'),
title: $('xr-title'), sizes: $('xr-sizes'), arts: $('xr-arts'), artsLabel: $('xr-arts-label'), artsNote: $('xr-arts-note'),
artsToggle: $('xr-arts-toggle'), zoomIn: $('xr-zoom-in'), zoomOut: $('xr-zoom-out'),
handle: $('xr-handle'), handleText: $('xr-handle-text'), sheetBody: $('xr-sheet-body'), aim: $('xr-aim'), measure: $('xr-measure'), shutter: $('xr-shutter'),
};
// What the camera view can change (the artwork and size of the focused piece) and what it recommends.
const arShop = {
build: () => buildScene(),
current() {
const p = piece();
const [w, h] = dimsOf(p);
const sizes = sizesFor(p.art, material()).filter((s) => p.art.variants[material()][s]?.available !== false);
return { handle: p.art.handle, title: p.art.title, size: p.size, sizes, label: `${fmtCm(w)} × ${fmtCm(h)} cm` };
},
items: () => state.catalog.map((a) => ({ handle: a.handle, title: a.title, thumb: imageAt(a.image, 160) })),
async setArt(handle) {
const art = byHandle(handle);
if (!art) return null;
await selectArt(art);
return piece().art === art && state.images.has(handle) ? buildScene() : null;
},
async setSize(size) {
piece().size = size;
update();
return buildScene();
},
// Picks from an earlier room scan come at once (returns false: no camera picture needed). Otherwise, given a
// camera picture, a quick colour match comes first and the room advisor's picks replace it when ready.
recommend(picture, report) {
const earlier = state.advice?.suitable || state.arPicks;
if (earlier?.length) {
report({ handles: earlier.map((s) => s.handle || s), status: '' });
return false;
}
if (!picture) return true;
(async () => {
const palettes = await ensurePalettes();
const colour = rankArt(state.catalog, palettes, analyseRoom([picture]), 8).map((r) => r.art.handle);
report({ handles: colour, status: '' });
try {
const { adviseRoom } = await import('./room/advisor.js');
const advice = await adviseRoom({ photos: [picture], catalog: state.catalog, palettes, onProgress: () => {} });
const handles = advice.suitable.map((s) => s.handle);
if (handles.length) {
state.arPicks = handles;
report({ handles: [...new Set([...handles, ...colour])] });
}
} catch (err) {
console.warn('[ar] room reader', err); // the colour match stays
}
})().catch((err) => {
console.warn('[ar] recommendations', err);
report({ handles: [], status: '' });
});
return false;
},
};
ui.arButton.addEventListener('click', () => {
ui.arNote.textContent = '';
ui.wallChoice.showModal();
});
// ARt Viewer: the live camera view of the customer's own wall. From a tap, or straight away when the shop's pop-up
// sent the customer here with ?open=camera (then an iPhone asks about motion on the first tap inside the view).
for (const b of document.querySelectorAll('[data-open-camera]')) b.addEventListener('click', () => openArtViewer(true));
function openArtViewer(fromTap) {
if (ui.wallChoice.open) ui.wallChoice.close();
ui.arNote.textContent = '';
// A computer's webcam faces the customer, not the wall: offer the page on a phone instead.
if (!matchMedia('(pointer: coarse)').matches) { openQr(); return; }
const done = () => { ui.arNote.textContent = ''; };
// Every print that hangs must have its picture before it can be drawn (a layout picked for an uploaded photo may
// still be fetching them).
const loaded = () => state.pieces.every((q) => state.images.has(q.art.handle));
const ready = loaded() ? Promise.resolve(true) : Promise.all(state.pieces.map((q) => ensureImage(q.art))).then((ok) => !ok.includes(false));
if (ANDROID && liveAr && !brave) {
ready.then((ok) => (ok ? startWallAr(xrEls, arShop, done) : Promise.reject(new Error('pictures missing')))).catch((err) => {
console.warn('[ar] wall tracking unavailable, using the camera view', err);
openCameraView(Promise.resolve('granted'));
});
} else if (cameraAvailable()) {
if (fromTap) goFullScreen(); // both must come straight from a tap
openCameraView(fromTap ? askForMotion() : Promise.resolve('later')); // iPhones ask about motion sensors here
} else {
openQr();
}
function openCameraView(motion) {
ready.then((ok) => {
if (!ok) throw new Error('A picture didn’t load. Check your connection, then try again.');
ui.status.hidden = true;
return startCameraAr(xrEls, arShop, motion, done);
}).catch((err) => {
ui.arNote.textContent = `${err.message} You can also open this page on your phone:`;
openQr();
});
}
}
function openQr() {
const url = location.href;
const shareable = /^https:/.test(url) && !/localhost|127\.0\.0\.1/.test(location.hostname);
ui.qrCode.hidden = !shareable;
if (shareable && window.qrcode) {
const qr = window.qrcode(0, 'M');
qr.addData(url);
qr.make();
ui.qrCode.innerHTML = qr.createSvgTag({ cellSize: 4, margin: 0, scalable: true });
ui.qrText.textContent = 'Scan this code with your phone camera. The page opens with this print and size, ready to place on your wall.';
} else {
ui.qrText.textContent = 'AR needs a phone. Open this page on an iPhone or Android phone once it is published on the shop.';
}
ui.qr.showModal();
}
ui.getPicks.addEventListener('click', () => {
if (!state.photos.length) ui.wallChoice.showModal();
});
// ---------- your room: photos and scan ----------
function showRoom(step) {
ui.roomStart.hidden = step !== 'start';
ui.roomCompose.hidden = step !== 'compose';
ui.saveButton.hidden = step !== 'compose';
ui.arButton.hidden = step === 'compose'; // with a photo up, "Use my camera" sits in the photo's tools
}
const drop = $('room-drop');
drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('is-over'); });
drop.addEventListener('dragleave', () => drop.classList.remove('is-over'));
drop.addEventListener('drop', async (e) => {
e.preventDefault();
drop.classList.remove('is-over');
const photos = await photosFromFiles(e.dataTransfer.files);
if (!photos.length) { ui.roomError.textContent = "That file isn't a photo this browser can open. Try JPEG or PNG."; return; }
addPhotos(photos);
});
for (const b of document.querySelectorAll('[data-add-photos]')) b.addEventListener('click', () => {
if (ui.wallChoice.open) ui.wallChoice.close();
ui.photoInput.click();
});
ui.photoInput.addEventListener('change', async () => {
const photos = await photosFromFiles(ui.photoInput.files);
ui.photoInput.value = '';
if (!photos.length) { ui.roomError.textContent = "Those files aren't photos this browser can open. Try JPEG or PNG."; return; }
addPhotos(photos);
});
function addPhotos(photos) {
const first = !state.photos.length;
ui.getPicks.hidden = true;
state.photos.push(...photos);
showRoom('compose');
renderPhotoStrip();
if (first) choosePhoto(0);
colourMatch();
askAdvisor();
}
function renderPhotoStrip() {
ui.roomPhotos.replaceChildren(...state.photos.map((photo, i) => {
const li = document.createElement('li');
const b = Object.assign(document.createElement('button'), { type: 'button' });
b.setAttribute('aria-label', `Use photo ${i + 1} as the wall`);
b.setAttribute('aria-pressed', String(i === state.photo));
b.append(Object.assign(new Image(56, 42), { src: photo.toDataURL('image/jpeg', 0.6), alt: '' }));
b.addEventListener('click', () => choosePhoto(i));
li.append(b);
return li;
}));
}
function choosePhoto(i) {
state.photo = i;
composer.setPhoto(state.photos[i], i);
for (const [j, b] of [...ui.roomPhotos.querySelectorAll('button')].entries()) b.setAttribute('aria-pressed', String(j === i));
if (state.pieces.length && state.images.has(piece().art.handle)) update();
}
composer.onChange = () => {
const s = composer.scale;
ui.scaleNote.textContent = !s.label
? 'Size is a guess until you set the scale. Drag the art along the wall to move it.'
: s.estimated
? `Size estimated from the ${s.label}. Set the scale for an exact fit, or drag the art along the wall.`
: `True size, measured from the ${s.label}. Drag the art along the wall to move it.`;
};
$('room-reset').addEventListener('click', () => {
state.photos = [];
state.photo = 0;
state.advice = null;
state.adviceRun++;
state.choice = null;
state.hide = null;
state.ghost = null;
composer.photo = null;
composer.scales.clear();
ui.picks.hidden = true;
ui.options.replaceChildren();
ui.suits.hidden = true;
ui.getPicks.hidden = false;
state.awaitingChoice = false;
showRoom('start');
applyLayout({ pieces: [state.pieces[state.focus] || state.pieces[0]] });
});
// ---------- your room: scale ----------
const roomBar = document.querySelector('.room__bar');
function scaleMode(on) { ui.scaleForm.hidden = !on; roomBar.hidden = on; }
$('scale-start').addEventListener('click', () => {
composer.startScale();
scaleMode(true);
ui.scaleRef.focus();
});
ui.scaleRef.addEventListener('change', () => {
ui.scaleCustom.hidden = ui.scaleRef.value !== 'custom';
if (!ui.scaleCustom.hidden) ui.scaleCm.focus();
});
ui.scaleForm.addEventListener('submit', (e) => {
e.preventDefault();
const custom = ui.scaleRef.value === 'custom';
const cm = Number(custom ? ui.scaleCm.value : ui.scaleRef.value);
if (!(cm > 0)) { ui.scaleCm.focus(); return; }
const label = custom ? `${fmtCm(cm)} cm you marked` : ui.scaleRef.selectedOptions[0].textContent.replace(/, .*$/, '').toLowerCase();
composer.applyScale(cm, label);
scaleMode(false);
});
$('scale-cancel').addEventListener('click', () => { composer.cancelScale(); scaleMode(false); });
// ---------- your room: save ----------
ui.saveButton.addEventListener('click', async () => {
const blob = await composer.toBlob();
const name = `bluecairo-${piece().art.handle}-${piece().size}-in-my-room.jpg`;
const file = new File([blob], name, { type: 'image/jpeg' });
// Phones get the share sheet (save to Photos, send to someone); computers download the file.
if (matchMedia('(pointer: coarse)').matches && navigator.canShare?.({ files: [file] })) {
try { await navigator.share({ files: [file], title: piece().art.title }); return; } catch { /* closed the share sheet */ }
}
const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(blob), download: name });
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
ui.arNote.textContent = 'Saved to your downloads.';
});
// ---------- recommendations: quick colour match while the room reader works ----------
function swatch(name, hexColour) {
const li = document.createElement('li');
const dot = document.createElement('i');
dot.style.background = hexColour;
li.append(dot, name);
return li;
}
async function colourMatch() {
const run = state.adviceRun;
ui.picks.hidden = false;
const room = analyseRoom(state.photos);
if (!state.advice) ui.swatches.replaceChildren(...room.colours.slice(0, 6).map((c) => swatch(c === room.wall ? `${c.name} wall` : c.name, hex(c.rgb))));
await ensurePalettes();
if (state.advice || run !== state.adviceRun) return;
state.colourPicks = rankArt(state.catalog, state.palettes, room, 4);
}
// Artwork palettes are worked out once and shared by the colour match and the advisor.
function ensurePalettes(onProgress) {
if (state.palettes && state.palettes.size >= state.catalog.length) return Promise.resolve(state.palettes);
state.palettesPromise ??= artPalettes(state.catalog, onProgress).then((p) => { state.palettes = p; state.palettesPromise = null; return p; });
return state.palettesPromise;
}
// ---------- recommendations: the room advisor (on this device) ----------
function advisorProgress(p) {
if (p.step === 'load' && p.status === 'progress' && /\.onnx$/.test(p.file || '')) {
ui.picksStatus.textContent = `Getting the room reader ready. This happens once and takes a moment: ${Math.round(p.progress)}%`;
} else if (p.step === 'style') {
ui.picksStatus.textContent = 'Reading the style of your room';
} else if (p.step === 'plan') {
ui.picksStatus.textContent = 'Choosing art and layouts for your wall';
} else if (p.step === 'look') {
ui.picksStatus.textContent = p.of > 1 ? `Looking at your room, photo ${p.photo} of ${p.of}` : 'Looking at your room, its furniture and its walls';
}
}
async function askAdvisor() {
const run = ++state.adviceRun;
state.advice = null;
state.choice = null;
state.advisorBusy = true;
ui.ask.hidden = true;
ui.changeChoice.hidden = true;
ui.picksNote.textContent = '';
ui.why.textContent = '';
ui.picksStatus.textContent = 'Looking at your room, its furniture and its walls';
try {
const [{ adviseRoom }, palettes] = await Promise.all([import('./room/advisor.js'), ensurePalettes()]);
const advice = await adviseRoom({ photos: state.photos, catalog: state.catalog, palettes, onProgress: (p) => run === state.adviceRun && advisorProgress(p) });
if (run !== state.adviceRun) return;
state.advice = advice;
applyAdvice();
} catch (e) {
if (run !== state.adviceRun) return;
console.error('[advisor]', e);
ui.picksStatus.textContent = '';
ui.picksNote.textContent = "This device couldn't run the room reader, so this pick matches your room's colours only.";
const top = state.colourPicks?.[0];
if (top) applyLayout({ pieces: [{ art: top.art, finish: piece().finish, size: piece().size, offset: [0, 0] }] });
} finally {
if (run === state.adviceRun) state.advisorBusy = false;
}
}
function applyAdvice() {
const a = state.advice;
ui.picksStatus.textContent = '';
ui.why.textContent = a.care ? `${a.why} ${a.care}` : a.why;
ui.swatches.replaceChildren(swatch(`${a.room.wall.name} wall`, a.room.wall.hex), ...a.room.palette.slice(0, 5).map((c) => swatch(c.name, c.hex)));
// Real-size estimates, best source first; a scale the customer measured always wins.
const ex = mainExisting();
if (a.scale) composer.estimateScale(a.scale.photo, state.photos[a.scale.photo], a.scale.box, a.scale.length_cm, a.scale.axis, a.scale.reference);
for (const e of a.existing_art) composer.estimateScale(e.photo, state.photos[e.photo], e.box, e.width_cm, 'horizontal', `${e.description} (about ${Math.round(e.width_cm)} cm wide)`);
choosePhoto(a.main_photo);
if (ex) {
state.awaitingChoice = true;
update();
ui.askText.textContent = `We spotted ${ex.description} on your wall. Would you like to replace it, or keep it and add to it?`;
ui.ask.hidden = false;
ui.options.replaceChildren();
ui.suits.hidden = true;
} else {
showOptions('new');
}
}
for (const b of ui.ask.querySelectorAll('[data-choice]')) b.addEventListener('click', () => showOptions(b.dataset.choice));
ui.changeChoice.addEventListener('click', () => {
state.awaitingChoice = true;
update();
ui.ask.hidden = false;
ui.changeChoice.hidden = true;
ui.options.replaceChildren();
ui.suits.hidden = true;
ui.ask.querySelector('[data-choice]').focus();
});
function showOptions(choice) {
const a = state.advice;
state.choice = choice;
state.awaitingChoice = false;
ui.ask.hidden = true;
ui.changeChoice.hidden = choice === 'new';
ui.picksNote.textContent = '';
const options = choice === 'add' ? [...a.layouts.around, ...a.layouts.swap] : a.layouts.fresh;
state.options = options;
ui.options.replaceChildren(...options.map(optionTile));
renderSuits(choice);
const first = options.find((o) => o.recommended) || options[0];
if (first) applyOption(first);
else ui.picksNote.textContent = 'There is not enough free wall here for our sizes. Try a photo of a different wall.';
}
function applyOption(o) {
const ex = mainExisting();
const replacing = !o.existing && state.choice !== 'new' && ex; // replacing or swapping: paint the old piece out
state.activeOption = o.id;
choosePhoto(state.advice.main_photo);
applyLayout({
pieces: o.pieces.map((p) => ({ art: byHandle(p.handle), finish: p.finish, size: p.size, offset: [0, 0] })),
layout: { template: o.template, side: o.side, slots: o.slots, slope: o.slope, existingCm: o.existing ? [ex.width_cm, ex.height_cm] : null },
ghost: o.existing ? [ex.width_cm, ex.height_cm] : null,
anchor: o.anchor,
hide: replacing ? { photo: ex.photo, box: ex.box } : null,
});
}
// A small picture of a layout: each piece where it hangs, the customer's own piece dashed.
function optionTile(o) {
const ex = mainExisting();
const pieces = o.pieces.map((p) => ({ art: byHandle(p.handle), finish: p.finish, size: p.size }));
const dims = pieces.map((q) => dimsOf(q));
const exCm = o.existing ? [ex.width_cm, ex.height_cm] : null;
const { offsets } = place({ template: o.template, side: o.side, slots: o.slots, slope: o.slope }, dims, exCm);
const rects = pieces.map((q, i) => ({ x: offsets[i][0] - dims[i][0] / 2, y: offsets[i][1] - dims[i][1] / 2, w: dims[i][0], h: dims[i][1], q }));
if (exCm) rects.push({ x: -exCm[0] / 2, y: -exCm[1] / 2, w: exCm[0], h: exCm[1], yours: true });
const x0 = Math.min(...rects.map((r) => r.x)), y0 = Math.min(...rects.map((r) => r.y));
const x1 = Math.max(...rects.map((r) => r.x + r.w)), y1 = Math.max(...rects.map((r) => r.y + r.h));
const pad = Math.max(x1 - x0, y1 - y0) * 0.06;
const svg = ``;
const label = o.id.startsWith('swap') ? 'Swap yours' : o.existing ? `Yours + ${o.count}` : `${o.count} ${o.count > 1 ? 'pieces' : 'piece'}`;
const li = document.createElement('li');
const b = Object.assign(document.createElement('button'), { type: 'button', className: 'option' });
b.dataset.option = o.id;
b.innerHTML = `${svg}${label}${o.recommended ? 'Best fit' : ''}`;
b.setAttribute('aria-label', `${label}${o.recommended ? ', recommended' : ''}: ${pieces.map((q) => `${q.art.title}, ${q.size}`).join('; ')}`);
b.addEventListener('click', () => applyOption(o));
li.append(b);
return li;
}
function renderOptionsActive() {
for (const b of ui.options.querySelectorAll('.option')) b.setAttribute('aria-pressed', String(b.dataset.option === state.activeOption));
for (const b of ui.suitsGrid.querySelectorAll('.suit')) b.setAttribute('aria-pressed', String(b.dataset.option === state.activeOption));
}
// Every piece that suits the room, each hung on its own (beside the customer's piece when they keep it).
const SUITS_SHOWN = 8;
function renderSuits(choice) {
const list = state.advice.suitable.map((s) => ({ ...s, option: choice === 'add' ? s.beside : s.single })).filter((s) => s.option);
ui.suits.hidden = !list.length;
if (!list.length) return;
ui.suitsTitle.textContent = list.length === 1 ? 'The one piece that suits this room' : `All ${list.length} pieces that suit this room`;
ui.suitsGrid.replaceChildren(...list.map((s, i) => {
const art = byHandle(s.handle);
const li = document.createElement('li');
li.hidden = i >= SUITS_SHOWN;
const b = Object.assign(document.createElement('button'), { type: 'button', className: 'suit', title: s.reason });
b.dataset.option = s.option.id;
b.setAttribute('aria-label', `${art.title}, ${s.option.pieces[0].size}. ${s.reason}`);
b.append(Object.assign(new Image(), { src: imageAt(art.image, 200), alt: '', loading: 'lazy' }),
Object.assign(document.createElement('span'), { textContent: art.title }));
b.addEventListener('click', () => applyOption(s.option));
li.append(b);
return li;
}));
ui.suitsMore.hidden = list.length <= SUITS_SHOWN;
ui.suitsMore.textContent = `Show all ${list.length}`;
}
ui.suitsMore.addEventListener('click', () => {
for (const li of ui.suitsGrid.children) li.hidden = false;
ui.suitsMore.hidden = true;
ui.suitsGrid.children[SUITS_SHOWN]?.querySelector('button').focus();
});
// ---------- picker: swap the selected piece, or add one ----------
function openPicker(mode) {
state.pickerMode = mode;
ui.pickerTitle.textContent = mode === 'add' ? 'Add a piece to your wall' : 'Choose an artwork';
ui.pickerSearch.value = '';
filterPicker();
for (const li of ui.pickerGrid.children) {
li.firstElementChild.setAttribute('aria-current', String(mode === 'swap' && li.dataset.handle === piece()?.art.handle));
}
ui.picker.showModal();
}
function renderPicker() {
ui.pickerGrid.replaceChildren(...state.catalog.map((art) => {
const li = document.createElement('li');
li.dataset.title = art.title.toLowerCase();
li.dataset.handle = art.handle;
const button = Object.assign(document.createElement('button'), { type: 'button', className: 'picker-item' });
const img = Object.assign(new Image(128, 171), { src: imageAt(art.image, 300), alt: '', loading: 'lazy' });
button.append(img, Object.assign(document.createElement('span'), { textContent: art.title }));
li.append(button);
button.addEventListener('click', () => {
ui.picker.close();
if (state.pickerMode === 'add') addPiece(art);
else if (art !== piece().art) { state.activeOption = null; selectArt(art); }
});
return li;
}));
}
ui.openPicker.addEventListener('click', () => openPicker('swap'));
function filterPicker() {
const q = ui.pickerSearch.value.trim().toLowerCase();
let shown = 0;
for (const li of ui.pickerGrid.children) {
li.hidden = !!q && !li.dataset.title.includes(q);
if (!li.hidden) shown++;
}
ui.pickerEmpty.hidden = shown > 0;
}
ui.pickerSearch.addEventListener('input', filterPicker);
// For automated checks only: ?debug exposes the state to the test scripts.
if (new URLSearchParams(location.search).has('debug')) window.__viewer = { state, composer, activePlan };
start();