feat: v4.0 - multi-day horizontal canvas, duration input, overnight blocks, PDF horizontal layout
Some checks failed
Build & Push Docker / build (push) Has been cancelled

This commit is contained in:
2026-02-20 17:31:41 +01:00
parent e3a5330cc2
commit 47add509ca
11 changed files with 1188 additions and 773 deletions

View File

@@ -1,11 +1,11 @@
/**
* Main application logic for Scenar Creator v3.
* State management, UI wiring, modal handling.
* Main application logic for Scenar Creator v4.
* Multi-day state, duration input, horizontal canvas.
*/
const App = {
state: {
event: { title: '', subtitle: '', date: '', location: '' },
event: { title: '', subtitle: '', date_from: '', date_to: '', location: '' },
program_types: [],
blocks: []
},
@@ -15,20 +15,72 @@ const App = {
this.newScenario();
},
// --- State ---
// ─── Helpers ───────────────────────────────────────────────────────
uid() {
return 'b_' + Math.random().toString(36).slice(2, 10);
},
parseTimeToMin(str) {
if (!str) return 0;
const [h, m] = str.split(':').map(Number);
return (h || 0) * 60 + (m || 0);
},
minutesToTime(totalMin) {
const h = Math.floor(totalMin / 60);
const m = totalMin % 60;
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
},
// Return sorted list of all dates from date_from to date_to (inclusive)
getDates() {
const from = this.state.event.date_from || this.state.event.date;
const to = this.state.event.date_to || from;
if (!from) return [];
const dates = [];
const cur = new Date(from + 'T12:00:00');
const end = new Date((to || from) + 'T12:00:00');
// Safety: max 31 days
let safety = 0;
while (cur <= end && safety < 31) {
dates.push(cur.toISOString().slice(0, 10));
cur.setDate(cur.getDate() + 1);
safety++;
}
return dates;
},
// ─── State ────────────────────────────────────────────────────────
getDocument() {
this.syncEventFromUI();
return {
version: '1.0',
event: { ...this.state.event },
event: {
...this.state.event,
date: this.state.event.date_from, // backward compat
},
program_types: this.state.program_types.map(pt => ({ ...pt })),
blocks: this.state.blocks.map(b => ({ ...b }))
};
},
loadDocument(doc) {
this.state.event = { ...doc.event };
const ev = doc.event || {};
// Backward compat: if only date exists, use it as date_from = date_to
const date_from = ev.date_from || ev.date || '';
const date_to = ev.date_to || date_from;
this.state.event = {
title: ev.title || '',
subtitle: ev.subtitle || '',
date_from,
date_to,
location: ev.location || '',
};
this.state.program_types = (doc.program_types || []).map(pt => ({ ...pt }));
this.state.blocks = (doc.blocks || []).map(b => ({
...b,
@@ -40,9 +92,9 @@ const App = {
},
newScenario() {
const today = new Date().toISOString().split('T')[0];
const today = new Date().toISOString().slice(0, 10);
this.state = {
event: { title: 'Nová akce', subtitle: '', date: today, location: '' },
event: { title: 'Nová akce', subtitle: '', date_from: today, date_to: today, location: '' },
program_types: [
{ id: 'main', name: 'Hlavní program', color: '#3B82F6' },
{ id: 'rest', name: 'Odpočinek', color: '#22C55E' }
@@ -54,23 +106,25 @@ const App = {
this.renderCanvas();
},
// --- Sync sidebar <-> state ---
// ─── Sync sidebar <-> state ───────────────────────────────────────
syncEventFromUI() {
this.state.event.title = document.getElementById('eventTitle').value.trim() || 'Nová akce';
this.state.event.subtitle = document.getElementById('eventSubtitle').value.trim() || null;
this.state.event.date = document.getElementById('eventDate').value || null;
this.state.event.date_from = document.getElementById('eventDateFrom').value || null;
this.state.event.date_to = document.getElementById('eventDateTo').value || this.state.event.date_from;
this.state.event.location = document.getElementById('eventLocation').value.trim() || null;
},
syncEventToUI() {
document.getElementById('eventTitle').value = this.state.event.title || '';
document.getElementById('eventSubtitle').value = this.state.event.subtitle || '';
document.getElementById('eventDate').value = this.state.event.date || '';
document.getElementById('eventDateFrom').value = this.state.event.date_from || '';
document.getElementById('eventDateTo').value = this.state.event.date_to || this.state.event.date_from || '';
document.getElementById('eventLocation').value = this.state.event.location || '';
},
// --- Program types ---
// ─── Program types ────────────────────────────────────────────────
renderTypes() {
const container = document.getElementById('programTypesContainer');
@@ -83,16 +137,13 @@ const App = {
<input type="text" value="${pt.name}" placeholder="Název typu" data-idx="${i}">
<button class="type-remove" data-idx="${i}">&times;</button>
`;
// Color change
row.querySelector('input[type="color"]').addEventListener('change', (e) => {
this.state.program_types[i].color = e.target.value;
this.renderCanvas();
});
// Name change
row.querySelector('input[type="text"]').addEventListener('change', (e) => {
this.state.program_types[i].name = e.target.value.trim();
});
// Remove
row.querySelector('.type-remove').addEventListener('click', () => {
this.state.program_types.splice(i, 1);
this.renderTypes();
@@ -102,150 +153,222 @@ const App = {
});
},
addType() {
const id = 'type_' + this.uid().substring(0, 6);
this.state.program_types.push({
id,
name: 'Nový typ',
color: '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')
});
this.renderTypes();
},
// --- Blocks ---
createBlock(date, start, end) {
const typeId = this.state.program_types.length > 0 ? this.state.program_types[0].id : 'main';
const block = {
id: this.uid(),
date: date || this.state.event.date || new Date().toISOString().split('T')[0],
start: start || '09:00',
end: end || '10:00',
title: 'Nový blok',
type_id: typeId,
responsible: null,
notes: null
};
this.state.blocks.push(block);
this.renderCanvas();
this.editBlock(block.id);
},
updateBlockTime(blockId, start, end) {
const block = this.state.blocks.find(b => b.id === blockId);
if (block) {
block.start = start;
block.end = end;
this.renderCanvas();
}
},
deleteBlock(blockId) {
this.state.blocks = this.state.blocks.filter(b => b.id !== blockId);
this.renderCanvas();
},
// --- Canvas rendering ---
// ─── Canvas ───────────────────────────────────────────────────────
renderCanvas() {
const dates = this.getUniqueDates();
Canvas.renderTimeAxis();
Canvas.renderDayColumns(dates);
Canvas.renderBlocks(this.state.blocks, this.state.program_types);
Canvas.render(this.state);
},
getUniqueDates() {
const dateSet = new Set();
this.state.blocks.forEach(b => dateSet.add(b.date));
if (this.state.event.date) dateSet.add(this.state.event.date);
const dates = Array.from(dateSet).sort();
return dates.length > 0 ? dates : [new Date().toISOString().split('T')[0]];
},
// ─── Block modal ──────────────────────────────────────────────────
// --- Modal ---
editBlock(blockId) {
// Open modal to edit existing block
openBlockModal(blockId) {
const block = this.state.blocks.find(b => b.id === blockId);
if (!block) return;
document.getElementById('modalTitle').textContent = 'Upravit blok';
document.getElementById('modalBlockId').value = block.id;
document.getElementById('modalBlockTitle').value = block.title;
document.getElementById('modalBlockStart').value = block.start;
document.getElementById('modalBlockEnd').value = block.end;
document.getElementById('modalBlockTitle').value = block.title || '';
document.getElementById('modalBlockStart').value = block.start || '';
document.getElementById('modalBlockEnd').value = block.end || '';
document.getElementById('modalBlockResponsible').value = block.responsible || '';
document.getElementById('modalBlockNotes').value = block.notes || '';
this._updateDuration();
// Populate type select
const select = document.getElementById('modalBlockType');
select.innerHTML = '';
this._populateTypeSelect(block.type_id);
document.getElementById('modalBlockDate').value = block.date || '';
document.getElementById('modalDeleteBtn').style.display = 'inline-block';
document.getElementById('blockModal').classList.remove('hidden');
},
// Open modal to create new block
openNewBlockModal(date, start, end) {
document.getElementById('modalTitle').textContent = 'Nový blok';
document.getElementById('modalBlockId').value = '';
document.getElementById('modalBlockTitle').value = '';
document.getElementById('modalBlockStart').value = start || '09:00';
document.getElementById('modalBlockEnd').value = end || '10:00';
document.getElementById('modalBlockResponsible').value = '';
document.getElementById('modalBlockNotes').value = '';
document.getElementById('modalBlockDate').value = date || '';
this._updateDuration();
this._populateTypeSelect(null);
document.getElementById('modalDeleteBtn').style.display = 'none';
document.getElementById('blockModal').classList.remove('hidden');
},
_populateTypeSelect(selectedId) {
const sel = document.getElementById('modalBlockType');
sel.innerHTML = '';
this.state.program_types.forEach(pt => {
const opt = document.createElement('option');
opt.value = pt.id;
opt.textContent = pt.name;
if (pt.id === block.type_id) opt.selected = true;
select.appendChild(opt);
if (pt.id === selectedId) opt.selected = true;
sel.appendChild(opt);
});
document.getElementById('blockModal').classList.remove('hidden');
},
saveBlockFromModal() {
const blockId = document.getElementById('modalBlockId').value;
const block = this.state.blocks.find(b => b.id === blockId);
if (!block) return;
block.title = document.getElementById('modalBlockTitle').value.trim() || 'Blok';
block.type_id = document.getElementById('modalBlockType').value;
block.start = document.getElementById('modalBlockStart').value;
block.end = document.getElementById('modalBlockEnd').value;
block.responsible = document.getElementById('modalBlockResponsible').value.trim() || null;
block.notes = document.getElementById('modalBlockNotes').value.trim() || null;
this.closeModal();
this.renderCanvas();
},
closeModal() {
document.getElementById('blockModal').classList.add('hidden');
},
// --- Toast ---
toast(message, type) {
const el = document.getElementById('toast');
el.textContent = message;
el.className = 'toast ' + (type || 'info');
setTimeout(() => el.classList.add('hidden'), 3000);
},
// --- PDF ---
async generatePdf() {
try {
const doc = this.getDocument();
if (doc.blocks.length === 0) {
this.toast('Přidejte alespoň jeden blok', 'error');
return;
}
const blob = await API.postBlob('/api/generate-pdf', doc);
API.downloadBlob(blob, 'scenar_timetable.pdf');
this.toast('PDF vygenerován', 'success');
} catch (err) {
this.toast('Chyba: ' + err.message, 'error');
_updateDuration() {
const startVal = document.getElementById('modalBlockStart').value;
const endVal = document.getElementById('modalBlockEnd').value;
if (!startVal || !endVal) {
document.getElementById('modalBlockDuration').value = '';
return;
}
const s = this.parseTimeToMin(startVal);
let e = this.parseTimeToMin(endVal);
if (e < s) e += 24 * 60; // overnight
const dur = e - s;
document.getElementById('modalBlockDuration').value = this.minutesToTime(dur);
},
// --- Utility ---
_saveModal() {
const blockId = document.getElementById('modalBlockId').value;
const date = document.getElementById('modalBlockDate').value;
const title = document.getElementById('modalBlockTitle').value.trim();
const type_id = document.getElementById('modalBlockType').value;
const start = document.getElementById('modalBlockStart').value;
const end = document.getElementById('modalBlockEnd').value;
const responsible = document.getElementById('modalBlockResponsible').value.trim() || null;
const notes = document.getElementById('modalBlockNotes').value.trim() || null;
uid() {
return 'xxxx-xxxx-xxxx'.replace(/x/g, () =>
Math.floor(Math.random() * 16).toString(16)
);
if (!title) { this.toast('Zadejte název bloku', 'error'); return; }
if (!start || !end) { this.toast('Zadejte čas začátku a konce', 'error'); return; }
if (blockId) {
// Edit existing
const idx = this.state.blocks.findIndex(b => b.id === blockId);
if (idx !== -1) {
Object.assign(this.state.blocks[idx], { date, title, type_id, start, end, responsible, notes });
}
} else {
// New block
this.state.blocks.push({ id: this.uid(), date, title, type_id, start, end, responsible, notes });
}
document.getElementById('blockModal').classList.add('hidden');
this.renderCanvas();
this.toast('Blok uložen', 'success');
},
// --- Event binding ---
_deleteBlock() {
const blockId = document.getElementById('modalBlockId').value;
if (!blockId) return;
this.state.blocks = this.state.blocks.filter(b => b.id !== blockId);
document.getElementById('blockModal').classList.add('hidden');
this.renderCanvas();
this.toast('Blok smazán', 'success');
},
// ─── Toast ────────────────────────────────────────────────────────
toast(message, type = 'success') {
const el = document.getElementById('toast');
if (!el) return;
el.textContent = message;
el.className = `toast ${type}`;
el.classList.remove('hidden');
clearTimeout(this._toastTimer);
this._toastTimer = setTimeout(() => el.classList.add('hidden'), 3000);
},
// ─── Events ───────────────────────────────────────────────────────
bindEvents() {
// Import JSON
document.getElementById('importJsonInput').addEventListener('change', (e) => {
if (e.target.files[0]) importJson(e.target.files[0]);
e.target.value = '';
});
// Export JSON
document.getElementById('exportJsonBtn').addEventListener('click', () => exportJson());
// New scenario
document.getElementById('newScenarioBtn').addEventListener('click', () => {
if (!confirm('Vytvořit nový scénář? Neuložené změny budou ztraceny.')) return;
this.newScenario();
});
// Generate PDF
document.getElementById('generatePdfBtn').addEventListener('click', async () => {
this.syncEventFromUI();
const doc = this.getDocument();
if (!doc.blocks.length) {
this.toast('Žádné bloky k exportu', 'error');
return;
}
try {
this.toast('Generuji PDF…', 'success');
const blob = await API.postBlob('/api/generate-pdf', doc);
API.downloadBlob(blob, 'scenar.pdf');
this.toast('PDF staženo', 'success');
} catch (err) {
this.toast('Chyba PDF: ' + err.message, 'error');
}
});
// Add block button
document.getElementById('addBlockBtn').addEventListener('click', () => {
const dates = this.getDates();
const date = dates[0] || new Date().toISOString().slice(0, 10);
this.openNewBlockModal(date, '09:00', '10:00');
});
// Add type
document.getElementById('addTypeBtn').addEventListener('click', () => {
this.state.program_types.push({
id: 'type_' + Math.random().toString(36).slice(2, 6),
name: 'Nový typ',
color: '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')
});
this.renderTypes();
});
// Modal close
document.getElementById('modalClose').addEventListener('click', () => {
document.getElementById('blockModal').classList.add('hidden');
});
document.getElementById('modalSaveBtn').addEventListener('click', () => this._saveModal());
document.getElementById('modalDeleteBtn').addEventListener('click', () => this._deleteBlock());
// Duration ↔ end sync
document.getElementById('modalBlockDuration').addEventListener('input', (e) => {
const durStr = e.target.value.trim();
const startVal = document.getElementById('modalBlockStart').value;
if (!startVal || !durStr) return;
const durParts = durStr.split(':').map(Number);
if (durParts.length < 2 || isNaN(durParts[0]) || isNaN(durParts[1])) return;
const durMin = durParts[0] * 60 + durParts[1];
if (durMin <= 0) return;
const startMin = this.parseTimeToMin(startVal);
const endMin = startMin + durMin;
document.getElementById('modalBlockEnd').value = this.minutesToTime(endMin % 1440 || endMin);
});
document.getElementById('modalBlockEnd').addEventListener('input', () => {
this._updateDuration();
});
document.getElementById('modalBlockStart').addEventListener('input', () => {
this._updateDuration();
});
// Date range sync: if dateFrom changes and dateTo < dateFrom, set dateTo = dateFrom
document.getElementById('eventDateFrom').addEventListener('change', (e) => {
const toEl = document.getElementById('eventDateTo');
if (!toEl.value || toEl.value < e.target.value) {
toEl.value = e.target.value;
}
this.syncEventFromUI();
this.renderCanvas();
});
document.getElementById('eventDateTo').addEventListener('change', () => {
this.syncEventFromUI();
this.renderCanvas();
});
// Tabs
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
@@ -256,49 +379,11 @@ const App = {
});
});
// Header buttons
document.getElementById('newScenarioBtn').addEventListener('click', () => this.newScenario());
document.getElementById('exportJsonBtn').addEventListener('click', () => exportJson());
document.getElementById('generatePdfBtn').addEventListener('click', () => this.generatePdf());
// Import JSON
document.getElementById('importJsonInput').addEventListener('change', (e) => {
if (e.target.files[0]) importJson(e.target.files[0]);
e.target.value = '';
});
// Sidebar
document.getElementById('addTypeBtn').addEventListener('click', () => this.addType());
document.getElementById('addBlockBtn').addEventListener('click', () => this.createBlock());
// Modal
document.getElementById('modalSaveBtn').addEventListener('click', () => this.saveBlockFromModal());
document.getElementById('modalClose').addEventListener('click', () => this.closeModal());
document.getElementById('modalDeleteBtn').addEventListener('click', () => {
const blockId = document.getElementById('modalBlockId').value;
this.closeModal();
this.deleteBlock(blockId);
});
// Close modal on overlay click
document.getElementById('blockModal').addEventListener('click', (e) => {
if (e.target.classList.contains('modal-overlay')) this.closeModal();
if (e.target === document.getElementById('blockModal')) {
document.getElementById('blockModal').classList.add('hidden');
}
});
// Drag & drop JSON on canvas
const canvasWrapper = document.querySelector('.canvas-wrapper');
if (canvasWrapper) {
canvasWrapper.addEventListener('dragover', (e) => e.preventDefault());
canvasWrapper.addEventListener('drop', (e) => {
e.preventDefault();
const file = e.dataTransfer.files[0];
if (file && file.name.endsWith('.json')) {
importJson(file);
}
});
}
}
},
};
// Boot
document.addEventListener('DOMContentLoaded', () => App.init());

View File

@@ -1,32 +1,34 @@
/**
* Canvas editor for Scenar Creator v3.
* Renders schedule blocks on a time-grid canvas with drag & drop via interact.js.
* Canvas editor for Scenar Creator v4.
* Horizontal layout: X = time, Y = days.
* interact.js for drag (horizontal) and resize (right edge).
*/
const Canvas = {
GRID_MINUTES: 15,
PX_PER_SLOT: 30, // 30px per 15 min
START_HOUR: 7,
END_HOUR: 23,
ROW_H: 52, // px height of one day row
TIME_LABEL_W: 80, // px width of date label column
HEADER_H: 28, // px height of time axis header
MIN_BLOCK_MIN: 15, // minimum block duration in minutes
// Time range (auto-derived from blocks, with fallback)
_startMin: 7 * 60,
_endMin: 22 * 60,
get pxPerMinute() {
return this.PX_PER_SLOT / this.GRID_MINUTES;
},
get totalSlots() {
return ((this.END_HOUR - this.START_HOUR) * 60) / this.GRID_MINUTES;
},
get totalHeight() {
return this.totalSlots * this.PX_PER_SLOT;
const slots = (this._endMin - this._startMin) / this.GRID_MINUTES;
const container = document.getElementById('canvasScrollArea');
if (!container) return 2;
const avail = container.clientWidth - this.TIME_LABEL_W - 4;
return avail / ((this._endMin - this._startMin));
},
minutesToPx(minutes) {
return (minutes - this.START_HOUR * 60) * this.pxPerMinute;
return (minutes - this._startMin) * this.pxPerMinute;
},
pxToMinutes(px) {
return Math.round(px / this.pxPerMinute + this.START_HOUR * 60);
return px / this.pxPerMinute + this._startMin;
},
snapMinutes(minutes) {
@@ -34,234 +36,295 @@ const Canvas = {
},
formatTime(totalMinutes) {
const h = Math.floor(totalMinutes / 60);
const m = totalMinutes % 60;
const norm = ((totalMinutes % 1440) + 1440) % 1440;
const h = Math.floor(norm / 60);
const m = norm % 60;
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
},
parseTime(str) {
if (!str) return 0;
const [h, m] = str.split(':').map(Number);
return h * 60 + m;
return (h || 0) * 60 + (m || 0);
},
isLightColor(hex) {
const h = hex.replace('#', '');
const r = parseInt(h.substring(0, 2), 16);
const g = parseInt(h.substring(2, 4), 16);
const b = parseInt(h.substring(4, 6), 16);
const h = (hex || '#888888').replace('#', '');
const r = parseInt(h.substring(0, 2), 16) || 128;
const g = parseInt(h.substring(2, 4), 16) || 128;
const b = parseInt(h.substring(4, 6), 16) || 128;
return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6;
},
renderTimeAxis() {
const axis = document.getElementById('timeAxis');
axis.innerHTML = '';
axis.style.height = this.totalHeight + 'px';
for (let slot = 0; slot <= this.totalSlots; slot++) {
const minutes = this.START_HOUR * 60 + slot * this.GRID_MINUTES;
const isHour = minutes % 60 === 0;
const isHalf = minutes % 30 === 0;
if (isHour || isHalf) {
const label = document.createElement('div');
label.className = 'time-label';
label.style.top = (slot * this.PX_PER_SLOT) + 'px';
label.textContent = this.formatTime(minutes);
if (!isHour) {
label.style.fontSize = '9px';
label.style.opacity = '0.6';
}
axis.appendChild(label);
}
// Derive time range from blocks (with default fallback)
_computeRange(blocks) {
if (!blocks || blocks.length === 0) {
this._startMin = 7 * 60;
this._endMin = 22 * 60;
return;
}
let minStart = 24 * 60;
let maxEnd = 0;
for (const b of blocks) {
const s = this.parseTime(b.start);
let e = this.parseTime(b.end);
if (e <= s) e += 24 * 60; // overnight
if (s < minStart) minStart = s;
if (e > maxEnd) maxEnd = e;
}
// Round to hour boundaries, add small padding
this._startMin = Math.max(0, Math.floor(minStart / 60) * 60);
this._endMin = Math.min(48 * 60, Math.ceil(maxEnd / 60) * 60);
// Ensure minimum range of 2h
if (this._endMin - this._startMin < 120) {
this._endMin = this._startMin + 120;
}
},
renderDayColumns(dates) {
const header = document.getElementById('canvasHeader');
const columns = document.getElementById('dayColumns');
header.innerHTML = '';
columns.innerHTML = '';
render(state) {
const dates = App.getDates();
this._computeRange(state.blocks);
if (dates.length === 0) dates = [new Date().toISOString().split('T')[0]];
const timeAxisEl = document.getElementById('timeAxis');
const dayRowsEl = document.getElementById('dayRows');
if (!timeAxisEl || !dayRowsEl) return;
dates.forEach(dateStr => {
// Header
const dh = document.createElement('div');
dh.className = 'day-header';
dh.textContent = dateStr;
header.appendChild(dh);
timeAxisEl.innerHTML = '';
dayRowsEl.innerHTML = '';
// Column
const col = document.createElement('div');
col.className = 'day-column';
col.dataset.date = dateStr;
col.style.height = this.totalHeight + 'px';
// Grid lines
for (let slot = 0; slot <= this.totalSlots; slot++) {
const minutes = this.START_HOUR * 60 + slot * this.GRID_MINUTES;
const line = document.createElement('div');
line.className = 'grid-line ' + (minutes % 60 === 0 ? 'hour' : 'half');
line.style.top = (slot * this.PX_PER_SLOT) + 'px';
col.appendChild(line);
}
// Click area for creating blocks
const clickArea = document.createElement('div');
clickArea.className = 'day-column-click-area';
clickArea.addEventListener('click', (e) => {
if (e.target !== clickArea) return;
const rect = col.getBoundingClientRect();
const y = e.clientY - rect.top;
const minutes = this.snapMinutes(this.pxToMinutes(y));
const endMinutes = Math.min(minutes + 60, this.END_HOUR * 60);
App.createBlock(dateStr, this.formatTime(minutes), this.formatTime(endMinutes));
});
col.appendChild(clickArea);
columns.appendChild(col);
});
this._renderTimeAxis(timeAxisEl, dates);
this._renderDayRows(dayRowsEl, dates, state);
},
renderBlocks(blocks, programTypes) {
// Remove existing blocks
document.querySelectorAll('.schedule-block').forEach(el => el.remove());
_renderTimeAxis(container, dates) {
container.style.display = 'flex';
container.style.alignItems = 'stretch';
container.style.height = this.HEADER_H + 'px';
container.style.minWidth = (this.TIME_LABEL_W + this._canvasWidth()) + 'px';
// Date label placeholder
const corner = document.createElement('div');
corner.className = 'time-corner';
corner.style.cssText = `width:${this.TIME_LABEL_W}px;min-width:${this.TIME_LABEL_W}px;`;
container.appendChild(corner);
// Time labels wrapper
const labelsWrap = document.createElement('div');
labelsWrap.style.cssText = `position:relative;flex:1;height:${this.HEADER_H}px;`;
const totalMin = this._endMin - this._startMin;
for (let m = this._startMin; m <= this._endMin; m += 60) {
const pct = (m - this._startMin) / totalMin * 100;
const label = document.createElement('div');
label.className = 'time-tick';
label.style.left = `calc(${pct}% - 1px)`;
label.textContent = this.formatTime(m);
labelsWrap.appendChild(label);
}
container.appendChild(labelsWrap);
},
_canvasWidth() {
const container = document.getElementById('canvasScrollArea');
if (!container) return 800;
return Math.max(600, container.clientWidth - this.TIME_LABEL_W - 20);
},
_renderDayRows(container, dates, state) {
const typeMap = {};
programTypes.forEach(pt => { typeMap[pt.id] = pt; });
for (const pt of state.program_types) typeMap[pt.id] = pt;
blocks.forEach(block => {
const col = document.querySelector(`.day-column[data-date="${block.date}"]`);
if (!col) return;
for (const date of dates) {
const row = document.createElement('div');
row.className = 'day-row';
row.style.height = this.ROW_H + 'px';
row.dataset.date = date;
const pt = typeMap[block.type_id] || { color: '#94a3b8', name: '?' };
const startMin = this.parseTime(block.start);
const endMin = this.parseTime(block.end);
const top = this.minutesToPx(startMin);
const height = (endMin - startMin) * this.pxPerMinute;
const isLight = this.isLightColor(pt.color);
// Date label
const label = document.createElement('div');
label.className = 'day-label';
label.style.width = this.TIME_LABEL_W + 'px';
label.style.minWidth = this.TIME_LABEL_W + 'px';
label.textContent = this._formatDate(date);
row.appendChild(label);
const el = document.createElement('div');
el.className = 'schedule-block' + (isLight ? ' light-bg' : '');
el.dataset.blockId = block.id;
el.style.top = top + 'px';
el.style.height = Math.max(height, 20) + 'px';
el.style.backgroundColor = pt.color;
// Timeline area
const timeline = document.createElement('div');
timeline.className = 'day-timeline';
timeline.style.position = 'relative';
timeline.dataset.date = date;
el.innerHTML = `
<div class="block-color-bar" style="background:${this.darkenColor(pt.color)}"></div>
<div class="block-title">${this.escapeHtml(block.title)}</div>
<div class="block-time">${block.start} ${block.end}</div>
${block.responsible ? `<div class="block-responsible">${this.escapeHtml(block.responsible)}</div>` : ''}
<div class="resize-handle"></div>
`;
// Grid lines (every hour)
const totalMin = this._endMin - this._startMin;
for (let m = this._startMin; m < this._endMin; m += 60) {
const line = document.createElement('div');
line.className = 'grid-line';
line.style.left = ((m - this._startMin) / totalMin * 100) + '%';
timeline.appendChild(line);
}
// Click to edit
el.addEventListener('click', (e) => {
if (e.target.classList.contains('resize-handle')) return;
App.editBlock(block.id);
// Click on empty timeline to add block
timeline.addEventListener('click', (e) => {
if (e.target !== timeline) return;
const rect = timeline.getBoundingClientRect();
const relX = e.clientX - rect.left;
const totalW = rect.width;
const clickMin = this._startMin + (relX / totalW) * (this._endMin - this._startMin);
const snapStart = this.snapMinutes(clickMin);
const snapEnd = snapStart + 60; // default 1h
App.openNewBlockModal(date, this.formatTime(snapStart), this.formatTime(Math.min(snapEnd, this._endMin)));
});
col.appendChild(el);
// Render blocks for this date
const dayBlocks = state.blocks.filter(b => b.date === date);
for (const block of dayBlocks) {
const el = this._createBlockEl(block, typeMap, totalMin);
if (el) timeline.appendChild(el);
}
row.appendChild(timeline);
container.appendChild(row);
}
},
_formatDate(dateStr) {
const d = new Date(dateStr + 'T12:00:00');
return d.toLocaleDateString('cs-CZ', { weekday: 'short', day: 'numeric', month: 'numeric' });
},
_createBlockEl(block, typeMap, totalMin) {
const pt = typeMap[block.type_id];
const color = pt ? pt.color : '#888888';
const light = this.isLightColor(color);
const s = this.parseTime(block.start);
let e = this.parseTime(block.end);
const isOvernight = e <= s;
if (isOvernight) e = this._endMin; // clip to end of day
// Clamp to time range
const cs = Math.max(s, this._startMin);
const ce = Math.min(e, this._endMin);
if (ce <= cs) return null;
const totalRange = this._endMin - this._startMin;
const leftPct = (cs - this._startMin) / totalRange * 100;
const widthPct = (ce - cs) / totalRange * 100;
const el = document.createElement('div');
el.className = 'block-el' + (isOvernight ? ' overnight' : '');
el.dataset.id = block.id;
el.style.cssText = `
left:${leftPct}%;
width:${widthPct}%;
background:${color};
color:${light ? '#1a1a1a' : '#ffffff'};
top:4px;
height:${this.ROW_H - 8}px;
position:absolute;
`;
// Block label
const inner = document.createElement('div');
inner.className = 'block-inner';
const timeLabel = `${block.start}${block.end}`;
const nameEl = document.createElement('span');
nameEl.className = 'block-title';
nameEl.textContent = block.title;
const timeEl = document.createElement('span');
timeEl.className = 'block-time';
timeEl.textContent = timeLabel + (isOvernight ? ' →' : '');
inner.appendChild(nameEl);
inner.appendChild(timeEl);
el.appendChild(inner);
// Click to edit
el.addEventListener('click', (e) => {
e.stopPropagation();
App.openBlockModal(block.id);
});
this.initInteract();
},
initInteract() {
if (typeof interact === 'undefined') return;
interact('.schedule-block').draggable({
inertia: false,
modifiers: [
interact.modifiers.snap({
targets: [interact.snappers.grid({
x: 1, y: this.PX_PER_SLOT
})],
range: Infinity,
relativePoint: { x: 0, y: 0 }
}),
interact.modifiers.restrict({
restriction: 'parent',
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
// interact.js drag (horizontal only)
if (window.interact) {
interact(el)
.draggable({
axis: 'x',
listeners: {
move: (event) => this._onDragMove(event, block),
end: (event) => this._onDragEnd(event, block),
},
modifiers: [
interact.modifiers.snap({
targets: [interact.snappers.grid({ x: this._minutesPx(this.GRID_MINUTES), y: 1000 })],
range: Infinity,
relativePoints: [{ x: 0, y: 0 }]
}),
interact.modifiers.restrict({ restriction: 'parent' })
],
inertia: false,
})
],
listeners: {
start: (event) => {
event.target.style.zIndex = 50;
event.target.style.opacity = '0.9';
},
move: (event) => {
const target = event.target;
const y = (parseFloat(target.dataset.dragY) || 0) + event.dy;
target.dataset.dragY = y;
const currentTop = parseFloat(target.style.top) || 0;
const newTop = currentTop + event.dy;
target.style.top = newTop + 'px';
},
end: (event) => {
const target = event.target;
target.style.zIndex = '';
target.style.opacity = '';
target.dataset.dragY = 0;
.resizable({
edges: { right: true },
listeners: {
move: (event) => this._onResizeMove(event, block),
end: (event) => this._onResizeEnd(event, block),
},
modifiers: [
interact.modifiers.snapSize({
targets: [interact.snappers.grid({ width: this._minutesPx(this.GRID_MINUTES) })]
}),
interact.modifiers.restrictSize({ minWidth: this._minutesPx(this.MIN_BLOCK_MIN) })
],
});
}
const blockId = target.dataset.blockId;
const newTop = parseFloat(target.style.top);
const height = parseFloat(target.style.height);
const startMin = Canvas.snapMinutes(Canvas.pxToMinutes(newTop));
const endMin = Canvas.snapMinutes(Canvas.pxToMinutes(newTop + height));
App.updateBlockTime(blockId, Canvas.formatTime(startMin), Canvas.formatTime(endMin));
}
}
}).resizable({
edges: { bottom: '.resize-handle' },
modifiers: [
interact.modifiers.snap({
targets: [interact.snappers.grid({
x: 1, y: this.PX_PER_SLOT
})],
range: Infinity,
relativePoint: { x: 0, y: 0 },
offset: 'self'
}),
interact.modifiers.restrictSize({
min: { width: 0, height: this.PX_PER_SLOT }
})
],
listeners: {
move: (event) => {
const target = event.target;
target.style.height = event.rect.height + 'px';
},
end: (event) => {
const target = event.target;
const blockId = target.dataset.blockId;
const top = parseFloat(target.style.top);
const height = parseFloat(target.style.height);
const startMin = Canvas.snapMinutes(Canvas.pxToMinutes(top));
const endMin = Canvas.snapMinutes(Canvas.pxToMinutes(top + height));
App.updateBlockTime(blockId, Canvas.formatTime(startMin), Canvas.formatTime(endMin));
}
}
});
return el;
},
darkenColor(hex) {
const h = hex.replace('#', '');
const r = Math.max(0, parseInt(h.substring(0, 2), 16) - 30);
const g = Math.max(0, parseInt(h.substring(2, 4), 16) - 30);
const b = Math.max(0, parseInt(h.substring(4, 6), 16) - 30);
return `rgb(${r},${g},${b})`;
_minutesPx(minutes) {
return minutes * this.pxPerMinute;
},
escapeHtml(str) {
if (!str) return '';
const d = document.createElement('div');
d.textContent = str;
return d.innerHTML;
}
_onDragMove(event, block) {
const target = event.target;
const x = (parseFloat(target.style.left) || 0);
// Convert delta px to minutes
const deltaPx = event.dx;
const deltaMin = deltaPx / this.pxPerMinute;
const newStartMin = this.snapMinutes(this.parseTime(block.start) + deltaMin);
const duration = this.parseTime(block.end) - this.parseTime(block.start);
const clampedStart = Math.max(this._startMin, Math.min(this._endMin - duration, newStartMin));
const newEnd = clampedStart + duration;
block.start = this.formatTime(clampedStart);
block.end = this.formatTime(newEnd);
const totalRange = this._endMin - this._startMin;
const leftPct = (clampedStart - this._startMin) / totalRange * 100;
target.style.left = leftPct + '%';
},
_onDragEnd(event, block) {
App.renderCanvas();
},
_onResizeMove(event, block) {
const target = event.target;
const newWidthPx = event.rect.width;
const totalRange = this._endMin - this._startMin;
const containerW = target.parentElement.clientWidth;
const minutesPerPx = totalRange / containerW;
const newDuration = this.snapMinutes(Math.round(newWidthPx * minutesPerPx));
const clampedDuration = Math.max(this.MIN_BLOCK_MIN, newDuration);
const startMin = this.parseTime(block.start);
const endMin = Math.min(this._endMin, startMin + clampedDuration);
block.end = this.formatTime(endMin);
const widthPct = (endMin - startMin) / totalRange * 100;
target.style.width = widthPct + '%';
},
_onResizeEnd(event, block) {
App.renderCanvas();
},
};