const KITCHEN_CATEGORY_ID = '0124f923-6612-475b-bbfb-9ccb7131d293'; const DOORS_WINDOWS_CATEGORY_ID = '858a8cb2-fdf8-4d6f-b057-67dba26975b2'; const CATEGORY_CACHE_MS = 60000; const KITCHEN_PRESETS = [ { file: 'kitchen-1-L-2.json', name: 'Rohová - světlá' }, { file: 'kitchen-1-L-1.json', name: 'Rohová - zelená' }, { file: 'kitchen-2-single-line-1.json', name: 'Jednoduchá - černá - varianta 1' }, { file: 'kitchen-2-single-line-2.json', name: 'Jednoduchá - černá - varianta 2' }, { file: 'kitchen-2-single-line-3.json', name: 'Jednoduchá - světlá' }, { file: 'kitchen-3-double-line-1.json', name: 'S ostrůvkem - světla' }, { file: 'kitchen-3-double-line-2.json', name: 'S ostrůvkem - tmavá' }, { file: 'kitchen-4-U-1.json', name: 'Tvar U - černá' }, { file: 'kitchen-4-U-2.json', name: 'Tvar U - světlá' } ]; const WALL_COLORS = [ '#FEC5BB', '#FCD5CE', '#D8E2DC', '#FFE5D9', '#FFC89A', '#CB997E', '#EDDCD2', '#FFF0E6', '#E8E8E4', '#DDBEA9', '#A5A58D', '#B7B7A4', '#F6F6F6', '#F5F5F5', '#EAECEF', '#DEE2E6', '#CED4DA', '#ACB5BD' ]; const FLOOR_MATERIALS = [ { id: 'Parquet', name: 'Parkety' }, { id: 'StuccoWall', name: 'Štuk' }, { id: 'FloorDarkWood', name: 'Tmavé dřevo' }, { id: 'FloorLightOak', name: 'Světlý dub' }, { id: 'FloorRusticOak', name: 'Rustikální dub' }, { id: 'FloorTiles', name: 'Dlažba' }, { id: 'FloorGrayTiles', name: 'Šedá dlažba' } ]; var catalogCreatePending = null; var createOrigins = []; function accessoryIdFor(accessory) { const variant = accessory.primaryVariant; return variant && variant.id && variant.isDefault === false ? variant.id : (accessory.id || undefined); } function modelSourceFor(accessory) { const variant = accessory.primaryVariant; const model = (variant && variant.model) || accessory.model; if (model && model.url) { return { url: model.url, addressableName: undefined }; } return { url: undefined, addressableName: (variant && variant.addressableName) || accessory.addressableName || accessory.id || undefined }; } function addAccessoryToScene(accessory, onAdd) { const name = accessory.name || 'Item'; const accesoryId = accessoryIdFor(accessory); const source = modelSourceFor(accessory); if (!accesoryId || !(source.url || source.addressableName)) { toast(name + ' could not be added (no model)', 'error'); return; } if (!applicationInstance) { toast('Unity not ready', 'error'); return; } catalogCreatePending = { name, onAdd }; createOrigins.push('catalog'); sendToUnity('Create', JSON.stringify({ x: 0, y: 0, z: 0, addressableName: source.addressableName, url: source.url, snapType: 1, accesoryId })); sceneSaver.saveNow(); if (source.url) { toast(name + ' adding…'); } } function devCreate(payload) { if (applicationInstance) { createOrigins.push('dev'); } sendDev('Create', JSON.stringify(payload)); } function returnCreateStatus(status) { console.log('Create status: ' + status); const origin = createOrigins.shift(); if (origin !== 'catalog' || !catalogCreatePending) { return; } const pending = catalogCreatePending; catalogCreatePending = null; if (status === 'success') { if (pending.onAdd) { pending.onAdd(); } toast(pending.name + ' added', 'ok'); } else { toast(pending.name + ' could not be added', 'error'); } } function createProductList(container) { let generation = 0; let page = 1; let loader = null; const header = el('div', { class: 'muted small product-count' }); const grid = el('div', { class: 'product-grid' }); const status = el('p', { class: 'status' }); const more = el('button', { type: 'button', class: 'btn hidden', text: 'Load more' }); container.innerHTML = ''; container.append(header, grid, status, more); const fetchPage = async (pageNumber, run) => { setStatus(status, 'Loading…'); more.disabled = true; try { const [result] = await Promise.all([loader(pageNumber), loadManufacturers()]); if (run !== generation) { return; } result.items.forEach((accessory) => grid.appendChild(renderProductCard(accessory))); const count = grid.children.length; header.textContent = (result.total !== null && result.total !== undefined ? result.total : count + (result.hasMore ? '+' : '')) + ' products'; setStatus(status, count === 0 ? 'No products.' : ''); setHidden(more, !result.hasMore); page = pageNumber; } catch (error) { if (run === generation) { setStatus(status, 'Could not load products: ' + error.message, 'error'); } } finally { more.disabled = false; } }; more.addEventListener('click', () => fetchPage(page + 1, generation)); return { load(newLoader) { generation++; loader = newLoader; grid.innerHTML = ''; header.textContent = ''; setHidden(more, true); if (offlineMode) { setStatus(status, 'Offline mode: catalog unavailable. Use Dev tools for addressable/generic items.'); return; } fetchPage(1, generation); }, clear() { generation++; grid.innerHTML = ''; header.textContent = ''; setStatus(status, ''); setHidden(more, true); } }; } function renderProductCard(accessory) { const variant = accessory.primaryVariant; const image = primaryImageUrl(variant && variant.images) || primaryImageUrl(accessory.images); const price = Number(variant && variant.price); return el('article', { class: 'product-card' }, [ el('button', { type: 'button', class: 'product-image', title: 'Add to scene', onclick: () => addAccessoryToScene(accessory) }, [ image ? el('img', { src: image, alt: '', loading: 'lazy' }) : el('span', { class: 'muted small', text: 'no image' }) ]), el('div', { class: 'product-text' }, [ el('span', { class: 'muted small', text: manufacturerName(accessory) }), el('strong', { text: accessory.name || accessory.id }), el('span', { text: Number.isFinite(price) ? formatCzk(price) : '' }), el('span', { class: 'muted small', text: formatDimensions(variant) }) ]), el('button', { type: 'button', class: 'btn info-btn', text: 'i', title: 'Product information', onclick: () => openAccessoryInfo(accessory) }) ]); } const categoryCache = new Map(); function cachedCategories(key, request) { const hit = categoryCache.get(key); if (hit && Date.now() - hit.at < CATEGORY_CACHE_MS) { return hit.promise; } const promise = request().then(hydraMembers); categoryCache.set(key, { at: Date.now(), promise }); promise.catch(() => categoryCache.delete(key)); return promise; } const furniture = { categoryId: null, query: '', options: [], active: new Map(), products: null, run: 0 }; function initFurnitureTab() { furniture.products = createProductList($('#catalog-products')); const search = $('#catalog-search'); const runSearch = debounce(() => { furniture.query = search.value.trim(); loadFurnitureProducts(); }, 300); search.addEventListener('input', runSearch); $('#catalog-filter-button').addEventListener('click', () => { const panel = $('#catalog-filters'); setHidden(panel, !panel.classList.contains('hidden')); }); } function openFurnitureCategory(categoryId) { furniture.categoryId = categoryId; furniture.active = new Map(); const run = ++furniture.run; renderCategories(run); renderBreadcrumb(run); loadFilterOptions(run); loadFurnitureProducts(); } async function renderCategories(run) { const grid = $('#catalog-categories'); grid.innerHTML = ''; if (offlineMode) { return; } try { const id = furniture.categoryId; const categories = await cachedCategories('categories-' + (id || 'null'), () => id ? backend.childCategories(id) : backend.rootCategories()); if (run !== furniture.run) { return; } categories.forEach((category) => { const image = category.previewImage && category.previewImage.url; grid.appendChild(el('button', { type: 'button', class: 'category-card', onclick: () => openFurnitureCategory(category.id) }, [ image ? el('img', { src: image, alt: '', loading: 'lazy' }) : null, el('span', { text: category.name }) ])); }); } catch (error) { grid.appendChild(el('p', { class: 'status error', text: 'Could not load categories: ' + error.message })); } } async function renderBreadcrumb(run) { const crumbs = $('#catalog-breadcrumb'); crumbs.innerHTML = ''; const trail = []; let id = furniture.categoryId; try { while (id && trail.length < 10) { const category = await cachedCategory(id); trail.unshift(category); id = category.parentId; } } catch (error) { console.warn('breadcrumb failed', error); } if (run !== furniture.run) { return; } crumbs.appendChild(el('button', { type: 'button', class: 'link', text: 'All categories', onclick: () => openFurnitureCategory(null) })); trail.forEach((category) => { crumbs.appendChild(el('span', { class: 'muted', text: ' / ' })); crumbs.appendChild(el('button', { type: 'button', class: 'link', text: category.name, onclick: () => openFurnitureCategory(category.id) })); }); } function cachedCategory(id) { const key = 'category-' + id; const hit = categoryCache.get(key); if (hit && Date.now() - hit.at < CATEGORY_CACHE_MS) { return hit.promise; } const promise = api('/accessory-categories/' + encodeURIComponent(id)); categoryCache.set(key, { at: Date.now(), promise }); promise.catch(() => categoryCache.delete(key)); return promise; } function isFiltering() { return furniture.active.size > 0; } function serializeFilters() { const filters = []; furniture.active.forEach((entry, fieldPath) => { if (entry.type === 'exact' && entry.values.size > 0) { filters.push({ name: fieldPath, value: Array.from(entry.values) }); } else if (entry.type === 'range' && (entry.min !== null || entry.max !== null)) { const filter = { name: fieldPath }; if (entry.min !== null) { filter.min = entry.min; } if (entry.max !== null) { filter.max = entry.max; } filters.push(filter); } }); return filters; } function loadFurnitureProducts() { const categoryId = furniture.categoryId; $('#catalog-filter-button').textContent = isFiltering() ? 'Filter (' + furniture.active.size + ')' : 'Filter'; if (furniture.query) { const q = furniture.query; furniture.products.load((page) => backend.search(q, page, categoryId || undefined).then((data) => hydraPage(data, 20))); } else if (isFiltering()) { const filters = serializeFilters(); furniture.products.load((page) => backend.filter(categoryId, filters, page).then((data) => hydraPage(data, 20))); } else { furniture.products.load((page) => backend.accessories(categoryId || undefined, page).then((data) => hydraPage(data, 20))); } } const scheduleFilterLoad = debounce(loadFurnitureProducts, 300); async function loadFilterOptions(run) { const panel = $('#catalog-filters'); panel.innerHTML = ''; furniture.options = []; const button = $('#catalog-filter-button'); button.disabled = true; if (offlineMode) { return; } try { const data = await backend.filterOptions(furniture.categoryId); if (run !== furniture.run) { return; } furniture.options = ((data && data.filters) || []) .filter((option) => option.type === 'exact' ? (option.options || []).length > 0 : option.type === 'range' ? (option.min ?? 0) !== (option.max ?? 0) : false) .sort((a, b) => (a.position || 0) - (b.position || 0)); renderFilterPanel(); button.disabled = furniture.options.length === 0; } catch (error) { panel.appendChild(el('p', { class: 'status error', text: 'Filter options failed: ' + error.message })); button.disabled = false; } } function renderFilterPanel() { const panel = $('#catalog-filters'); panel.innerHTML = ''; furniture.options.forEach((option) => { const fieldPath = option.fieldPath || ''; const group = el('fieldset', { class: 'filter-group' }, [el('legend', { text: option.name || fieldPath })]); if (option.type === 'exact') { const values = (option.options || []).map((o) => typeof o === 'string' ? { value: o, label: o } : o); values.forEach((o) => { const active = furniture.active.get(fieldPath); const checkbox = el('input', { type: 'checkbox', checked: !!(active && active.values.has(o.value)) }); checkbox.addEventListener('change', () => setExactFilter(fieldPath, o.value, checkbox.checked)); group.appendChild(el('label', { class: 'filter-option' }, [ checkbox, o.swatch ? el('span', { class: 'swatch small', style: 'background:' + o.swatch }) : null, o.label || o.value ])); }); } else { const lower = option.min ?? 0; const upper = option.max ?? 100; const active = furniture.active.get(fieldPath); const minInput = el('input', { type: 'number', min: String(lower), max: String(upper), value: String(active && active.min !== null ? active.min : lower) }); const maxInput = el('input', { type: 'number', min: String(lower), max: String(upper), value: String(active && active.max !== null ? active.max : upper) }); const onChange = () => { const min = Number(minInput.value); const max = Number(maxInput.value); setRangeFilter(fieldPath, !Number.isFinite(min) || min === lower ? null : min, !Number.isFinite(max) || max === upper ? null : max); }; minInput.addEventListener('change', onChange); maxInput.addEventListener('change', onChange); group.appendChild(el('div', { class: 'range-row' }, [minInput, el('span', { text: '–' }), maxInput])); } panel.appendChild(group); }); panel.appendChild(el('button', { type: 'button', class: 'btn', text: 'Clear filters', onclick: () => { furniture.active = new Map(); renderFilterPanel(); scheduleFilterLoad(); } })); } function setExactFilter(fieldPath, value, checked) { const entry = furniture.active.get(fieldPath) || { type: 'exact', values: new Set() }; const values = new Set(entry.values); if (checked) { values.add(value); } else { values.delete(value); } if (values.size === 0) { furniture.active.delete(fieldPath); } else { furniture.active.set(fieldPath, { type: 'exact', values }); } scheduleFilterLoad(); } function setRangeFilter(fieldPath, min, max) { if (min === null && max === null) { furniture.active.delete(fieldPath); } else { furniture.active.set(fieldPath, { type: 'range', min, max }); } scheduleFilterLoad(); } var kitchenProducts = null; var doorsProducts = null; function initKitchenTab() { kitchenProducts = createProductList($('#kitchen-products')); const grid = $('#kitchen-presets'); KITCHEN_PRESETS.forEach((preset) => { grid.appendChild(el('button', { type: 'button', class: 'preset-card', onclick: () => loadKitchenPreset(preset) }, [ el('strong', { text: preset.name }), el('span', { class: 'muted small', text: preset.file }) ])); }); } async function loadKitchenPreset(preset) { try { const response = await fetch('TemplateData/kitchens/' + preset.file + '?v=1'); if (!response.ok) { throw new Error('HTTP ' + response.status); } const json = await response.json(); sendToUnity('AddJson', JSON.stringify(json)); } catch (error) { toast('Kitchen preset failed: ' + error.message, 'error'); } } function initDoorsTab() { doorsProducts = createProductList($('#doors-products')); } function initWallsTab() { const grid = $('#wall-swatches'); WALL_COLORS.forEach((hex) => { grid.appendChild(el('button', { type: 'button', class: 'swatch', title: hex, style: 'background:' + hex, onclick: () => setWallColor(hex) })); }); $('#wall-custom-color').addEventListener('input', (event) => setWallColor(event.target.value.toLowerCase())); } function setWallColor(color) { sendToUnity('Color', color); sceneSaver.saveNow(); } function initFloorTab() { const grid = $('#floor-materials'); FLOOR_MATERIALS.forEach((material) => { grid.appendChild(el('button', { type: 'button', class: 'floor-card', onclick: () => sendToUnity('Floor', material.id) }, [ el('strong', { text: material.name }), el('span', { class: 'muted small', text: material.id }) ])); }); }