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

@@ -33,8 +33,9 @@ async def validate_scenario(doc: ScenarioDocument):
for i, block in enumerate(doc.blocks): for i, block in enumerate(doc.blocks):
if block.type_id not in type_ids: if block.type_id not in type_ids:
errors.append(f"Block {i+1}: unknown type '{block.type_id}'") errors.append(f"Block {i+1}: unknown type '{block.type_id}'")
if block.start >= block.end: if block.start == block.end:
errors.append(f"Block {i+1}: start time must be before end time") errors.append(f"Block {i+1}: start time must differ from end time")
# Note: end < start is allowed for overnight blocks (block crosses midnight)
return ValidationResponse(valid=len(errors) == 0, errors=errors) return ValidationResponse(valid=len(errors) == 0, errors=errors)

View File

@@ -1,5 +1,5 @@
"""Application configuration.""" """Application configuration."""
VERSION = "3.0.0" VERSION = "4.0.0"
MAX_FILE_SIZE_MB = 10 MAX_FILE_SIZE_MB = 10
DEFAULT_COLOR = "#ffffff" DEFAULT_COLOR = "#ffffff"

View File

@@ -1,6 +1,7 @@
""" """
PDF generation for Scenar Creator v3 using ReportLab Canvas API. PDF generation for Scenar Creator v4 using ReportLab Canvas API.
Generates A4 landscape timetable — always exactly one page. Layout: rows = days, columns = time slots (15 min).
Always exactly one page, A4 landscape.
""" """
from io import BytesIO from io import BytesIO
@@ -18,25 +19,25 @@ logger = logging.getLogger(__name__)
PAGE_W, PAGE_H = landscape(A4) PAGE_W, PAGE_H = landscape(A4)
MARGIN = 10 * mm MARGIN = 10 * mm
# Color palette for UI # Colors
HEADER_BG = (0.118, 0.161, 0.231) # dark navy HEADER_BG = (0.118, 0.161, 0.231) # dark navy
GRID_LINE = (0.85, 0.85, 0.85)
HEADER_TEXT = (1.0, 1.0, 1.0) HEADER_TEXT = (1.0, 1.0, 1.0)
BODY_ALT = (0.97, 0.97, 0.97) AXIS_BG = (0.96, 0.96, 0.97)
AXIS_TEXT = (0.45, 0.45, 0.45)
GRID_HOUR = (0.78, 0.78, 0.82)
GRID_15MIN = (0.90, 0.90, 0.93)
ALT_ROW = (0.975, 0.975, 0.98)
FOOTER_TEXT = (0.6, 0.6, 0.6) FOOTER_TEXT = (0.6, 0.6, 0.6)
LABEL_TEXT = (0.35, 0.35, 0.35) BORDER = (0.82, 0.82, 0.86)
def hex_to_rgb(hex_color: str) -> tuple: def hex_to_rgb(hex_color: str) -> tuple:
h = hex_color.lstrip('#') h = (hex_color or '#888888').lstrip('#')
if len(h) == 8: if len(h) == 8:
h = h[2:] h = h[2:]
if len(h) != 6: if len(h) != 6:
return (0.8, 0.8, 0.8) return (0.7, 0.7, 0.7)
r = int(h[0:2], 16) / 255.0 return (int(h[0:2], 16) / 255.0, int(h[2:4], 16) / 255.0, int(h[4:6], 16) / 255.0)
g = int(h[2:4], 16) / 255.0
b = int(h[4:6], 16) / 255.0
return (r, g, b)
def is_light(hex_color: str) -> bool: def is_light(hex_color: str) -> bool:
@@ -44,13 +45,14 @@ def is_light(hex_color: str) -> bool:
return (0.299 * r + 0.587 * g + 0.114 * b) > 0.6 return (0.299 * r + 0.587 * g + 0.114 * b) > 0.6
def time_to_minutes(s: str) -> int: def time_to_min(s: str) -> int:
h, m = s.split(":") parts = s.split(':')
return int(h) * 60 + int(m) return int(parts[0]) * 60 + int(parts[1])
def fmt_time(total_minutes: int) -> str: def fmt_time(total_minutes: int) -> str:
return f"{total_minutes // 60:02d}:{total_minutes % 60:02d}" norm = total_minutes % 1440
return f"{norm // 60:02d}:{norm % 60:02d}"
def set_fill(c, rgb): def set_fill(c, rgb):
@@ -61,33 +63,32 @@ def set_stroke(c, rgb):
c.setStrokeColorRGB(*rgb) c.setStrokeColorRGB(*rgb)
def draw_rect_filled(c, x, y, w, h, fill_rgb, stroke_rgb=None, stroke_width=0.5): def fill_rect(c, x, y, w, h, fill, stroke=None, sw=0.4):
set_fill(c, fill_rgb) set_fill(c, fill)
if stroke_rgb: if stroke:
set_stroke(c, stroke_rgb) set_stroke(c, stroke)
c.setLineWidth(stroke_width) c.setLineWidth(sw)
c.rect(x, y, w, h, fill=1, stroke=1) c.rect(x, y, w, h, fill=1, stroke=1)
else: else:
c.rect(x, y, w, h, fill=1, stroke=0) c.rect(x, y, w, h, fill=1, stroke=0)
def draw_text_clipped(c, text, x, y, w, h, font, size, rgb, align="center"): def draw_clipped_text(c, text, x, y, w, h, font, size, rgb, align='center'):
"""Draw text centered/left in a bounding box, clipped to width.""" if not text:
return
c.saveState() c.saveState()
c.rect(x, y, w, h, fill=0, stroke=0)
c.clipPath(c.beginPath(), stroke=0, fill=0)
# Use a proper clip path
p = c.beginPath() p = c.beginPath()
p.rect(x, y, w, h) p.rect(x + 1, y, w - 2, h)
c.clipPath(p, stroke=0, fill=0) c.clipPath(p, stroke=0, fill=0)
set_fill(c, rgb) set_fill(c, rgb)
c.setFont(font, size) c.setFont(font, size)
if align == "center": ty = y + (h - size) / 2
c.drawCentredString(x + w / 2, y + (h - size) / 2 + 1, text) if align == 'center':
elif align == "right": c.drawCentredString(x + w / 2, ty, text)
c.drawRightString(x + w - 2, y + (h - size) / 2 + 1, text) elif align == 'right':
c.drawRightString(x + w - 2, ty, text)
else: else:
c.drawString(x + 2, y + (h - size) / 2 + 1, text) c.drawString(x + 2, ty, text)
c.restoreState() c.restoreState()
@@ -100,218 +101,251 @@ def generate_pdf(doc) -> bytes:
if block.type_id not in type_map: if block.type_id not in type_map:
raise ScenarsError(f"Missing type definition: '{block.type_id}'") raise ScenarsError(f"Missing type definition: '{block.type_id}'")
# Group by date # Collect dates + time range
blocks_by_date = defaultdict(list) sorted_dates = doc.get_sorted_dates()
for b in doc.blocks: num_days = len(sorted_dates)
blocks_by_date[b.date].append(b)
sorted_dates = sorted(blocks_by_date.keys())
# Time range (round to 30-min boundaries) all_starts = [time_to_min(b.start) for b in doc.blocks]
all_starts = [time_to_minutes(b.start) for b in doc.blocks] all_ends_raw = []
all_ends = [time_to_minutes(b.end) for b in doc.blocks] for b in doc.blocks:
t_start = (min(all_starts) // 30) * 30 s = time_to_min(b.start)
t_end = ((max(all_ends) + 29) // 30) * 30 e = time_to_min(b.end)
slot_minutes = 30 if e <= s:
num_slots = (t_end - t_start) // slot_minutes e += 24 * 60 # overnight: extend past midnight
all_ends_raw.append(e)
t_start = (min(all_starts) // 60) * 60
t_end = ((max(all_ends_raw) + 14) // 15) * 15
# Guard: clamp to reasonable range
t_start = max(0, t_start)
t_end = min(t_start + 24 * 60, t_end)
total_min = t_end - t_start
buf = BytesIO() buf = BytesIO()
c = rl_canvas.Canvas(buf, pagesize=landscape(A4)) c = rl_canvas.Canvas(buf, pagesize=landscape(A4))
# ── Layout constants ────────────────────────────────────────────── # ── Layout ────────────────────────────────────────────────────────
x0 = MARGIN x0 = MARGIN
y_top = PAGE_H - MARGIN y_top = PAGE_H - MARGIN
# Header block # Header block (title + subtitle + info)
title_size = 16 TITLE_SIZE = 16
subtitle_size = 10 SUB_SIZE = 10
info_size = 8 INFO_SIZE = 8
header_h = title_size + 4
has_subtitle = bool(doc.event.subtitle) header_h = TITLE_SIZE + 5
has_info = bool(doc.event.date or doc.event.location) if doc.event.subtitle:
if has_subtitle: header_h += SUB_SIZE + 3
header_h += subtitle_size + 2 has_info = bool(doc.event.date or doc.event.date_from or doc.event.location)
if has_info: if has_info:
header_h += info_size + 2 header_h += INFO_SIZE + 3
header_h += 4 # bottom padding header_h += 4
# Legend block (one row per type) # Legend: one row per type, multi-column
legend_item_h = 12 LEGEND_ITEM_H = 12
legend_h = len(doc.program_types) * legend_item_h + 6 LEGEND_BOX_W = 10 * mm
LEGEND_TEXT_W = 48 * mm
LEGEND_STRIDE = LEGEND_BOX_W + LEGEND_TEXT_W + 3 * mm
available_w_for_legend = PAGE_W - 2 * MARGIN
legend_cols = max(1, int(available_w_for_legend / LEGEND_STRIDE))
legend_rows = (len(doc.program_types) + legend_cols - 1) // legend_cols
LEGEND_H = legend_rows * LEGEND_ITEM_H + LEGEND_ITEM_H + 4 # +label row
# Footer FOOTER_H = 10
footer_h = 10 TIME_AXIS_H = 18
DATE_COL_W = 18 * mm
# Available height for timetable # Available area for the timetable grid
avail_h = PAGE_H - 2 * MARGIN - header_h - legend_h - footer_h - 6 avail_h = PAGE_H - 2 * MARGIN - header_h - LEGEND_H - FOOTER_H - TIME_AXIS_H - 6
row_h = max(8, avail_h / max(num_slots, 1)) row_h = max(10, avail_h / max(num_days, 1))
# Time axis width avail_w = PAGE_W - 2 * MARGIN - DATE_COL_W
time_col_w = 14 * mm # 15-min slot width
# Column widths for dates num_15min_slots = total_min // 15
avail_w = PAGE_W - 2 * MARGIN - time_col_w slot_w = avail_w / max(num_15min_slots, 1)
day_col_w = avail_w / max(len(sorted_dates), 1)
# Font sizes scale with row height # font sizes scale with row/col
cell_font_size = max(5.5, min(8.0, row_h * 0.45)) date_font = max(5.5, min(8.5, row_h * 0.38))
time_font_size = max(5.0, min(7.0, row_h * 0.42)) block_title_font = max(5.0, min(8.0, min(row_h, slot_w * 4) * 0.38))
header_col_size = max(6.0, min(9.0, day_col_w * 0.08)) block_time_font = max(4.0, min(6.0, block_title_font - 1.0))
time_axis_font = max(5.5, min(8.0, slot_w * 3))
# ── Draw header ─────────────────────────────────────────────────── # ── Draw header ───────────────────────────────────────────────────
y = y_top y = y_top
c.setFont("Helvetica-Bold", title_size) c.setFont('Helvetica-Bold', TITLE_SIZE)
set_fill(c, HEADER_BG) set_fill(c, HEADER_BG)
c.drawString(x0, y - title_size, doc.event.title) c.drawString(x0, y - TITLE_SIZE, doc.event.title)
y -= title_size + 4 y -= TITLE_SIZE + 5
if has_subtitle: if doc.event.subtitle:
c.setFont("Helvetica", subtitle_size) c.setFont('Helvetica', SUB_SIZE)
set_fill(c, (0.4, 0.4, 0.4)) set_fill(c, (0.4, 0.4, 0.4))
c.drawString(x0, y - subtitle_size, doc.event.subtitle) c.drawString(x0, y - SUB_SIZE, doc.event.subtitle)
y -= subtitle_size + 2 y -= SUB_SIZE + 3
if has_info: if has_info:
parts = [] parts = []
if doc.event.date: date_display = doc.event.date_from or doc.event.date
parts.append(f"Datum: {doc.event.date}") date_to_display = doc.event.date_to
if date_display:
if date_to_display and date_to_display != date_display:
parts.append(f'Datum: {date_display} {date_to_display}')
else:
parts.append(f'Datum: {date_display}')
if doc.event.location: if doc.event.location:
parts.append(f"Místo: {doc.event.location}") parts.append(f'Místo: {doc.event.location}')
c.setFont("Helvetica", info_size) c.setFont('Helvetica', INFO_SIZE)
set_fill(c, (0.5, 0.5, 0.5)) set_fill(c, (0.5, 0.5, 0.5))
c.drawString(x0, y - info_size, " | ".join(parts)) c.drawString(x0, y - INFO_SIZE, ' | '.join(parts))
y -= info_size + 2 y -= INFO_SIZE + 3
y -= 4 # padding
y -= 6 # padding before table # ── Time axis header ──────────────────────────────────────────────
table_top = y - TIME_AXIS_H
# Date column header (empty corner)
fill_rect(c, x0, table_top, DATE_COL_W, TIME_AXIS_H, AXIS_BG, BORDER, 0.4)
# Time labels (only whole hours)
for m in range(t_start, t_end + 1, 60):
slot_idx = (m - t_start) // 15
tx = x0 + DATE_COL_W + slot_idx * slot_w
# tick line
set_stroke(c, GRID_HOUR)
c.setLineWidth(0.5)
c.line(tx, table_top, tx, table_top + TIME_AXIS_H)
# label
label = fmt_time(m)
c.setFont('Helvetica', time_axis_font)
set_fill(c, AXIS_TEXT)
c.drawCentredString(tx, table_top + (TIME_AXIS_H - time_axis_font) / 2, label)
# Right border of time axis
fill_rect(c, x0, table_top, DATE_COL_W + avail_w, TIME_AXIS_H, AXIS_BG, BORDER, 0.3)
# Re-draw to not cover tick lines: draw border rectangle only
set_stroke(c, BORDER)
c.setLineWidth(0.4)
c.rect(x0, table_top, DATE_COL_W + avail_w, TIME_AXIS_H, fill=0, stroke=1)
# Re-draw time labels on top of border rect
for m in range(t_start, t_end + 1, 60):
slot_idx = (m - t_start) // 15
tx = x0 + DATE_COL_W + slot_idx * slot_w
c.setFont('Helvetica', time_axis_font)
set_fill(c, AXIS_TEXT)
c.drawCentredString(tx, table_top + (TIME_AXIS_H - time_axis_font) / 2, fmt_time(m))
# ── Draw day rows ─────────────────────────────────────────────────
blocks_by_date = defaultdict(list)
for b in doc.blocks:
blocks_by_date[b.date].append(b)
# ── Draw column headers ───────────────────────────────────────────
col_header_h = 16
# Time axis header cell
draw_rect_filled(c, x0, y - col_header_h, time_col_w, col_header_h, HEADER_BG)
# Date header cells
for di, date_key in enumerate(sorted_dates): for di, date_key in enumerate(sorted_dates):
cx = x0 + time_col_w + di * day_col_w row_y = table_top - (di + 1) * row_h
draw_rect_filled(c, cx, y - col_header_h, day_col_w, col_header_h, HEADER_BG, GRID_LINE)
c.saveState()
p = c.beginPath()
p.rect(cx + 1, y - col_header_h + 1, day_col_w - 2, col_header_h - 2)
c.clipPath(p, stroke=0, fill=0)
set_fill(c, HEADER_TEXT)
c.setFont("Helvetica-Bold", header_col_size)
c.drawCentredString(cx + day_col_w / 2, y - col_header_h + (col_header_h - header_col_size) / 2, date_key)
c.restoreState()
y -= col_header_h # Alternating row background
row_bg = (1.0, 1.0, 1.0) if di % 2 == 0 else ALT_ROW
fill_rect(c, x0 + DATE_COL_W, row_y, avail_w, row_h, row_bg, BORDER, 0.3)
# ── Draw time grid ──────────────────────────────────────────────── # Date label cell
table_top = y fill_rect(c, x0, row_y, DATE_COL_W, row_h, AXIS_BG, BORDER, 0.4)
table_bottom = y - num_slots * row_h draw_clipped_text(c, date_key, x0, row_y, DATE_COL_W, row_h,
'Helvetica-Bold', date_font, AXIS_TEXT, 'center')
for slot_i in range(num_slots): # Vertical grid lines (15-min slots, hour lines darker)
slot_min = t_start + slot_i * slot_minutes for slot_i in range(num_15min_slots + 1):
slot_label = fmt_time(slot_min) min_at_slot = t_start + slot_i * 15
row_y = y - slot_i * row_h tx = x0 + DATE_COL_W + slot_i * slot_w
is_hour = (min_at_slot % 60 == 0)
line_col = GRID_HOUR if is_hour else GRID_15MIN
set_stroke(c, line_col)
c.setLineWidth(0.5 if is_hour else 0.25)
c.line(tx, row_y, tx, row_y + row_h)
# Alternating row bg for day columns # Draw program blocks
alt_bg = BODY_ALT if slot_i % 2 == 1 else (1.0, 1.0, 1.0)
for di in range(len(sorted_dates)):
cx = x0 + time_col_w + di * day_col_w
draw_rect_filled(c, cx, row_y - row_h, day_col_w, row_h, alt_bg, GRID_LINE, 0.3)
# Time axis cell
draw_rect_filled(c, x0, row_y - row_h, time_col_w, row_h, (0.96, 0.96, 0.96), GRID_LINE, 0.3)
set_fill(c, LABEL_TEXT)
c.setFont("Helvetica", time_font_size)
c.drawRightString(x0 + time_col_w - 2, row_y - row_h + (row_h - time_font_size) / 2, slot_label)
# ── Draw program blocks ───────────────────────────────────────────
for di, date_key in enumerate(sorted_dates):
cx = x0 + time_col_w + di * day_col_w
for block in blocks_by_date[date_key]: for block in blocks_by_date[date_key]:
b_start = time_to_minutes(block.start) s = time_to_min(block.start)
b_end = time_to_minutes(block.end) e = time_to_min(block.end)
if b_start < t_start or b_end > t_end: overnight = e <= s
if overnight:
e_draw = min(t_end, s + (e + 1440 - s)) # cap at t_end
else:
e_draw = e
cs = max(s, t_start)
ce = min(e_draw, t_end)
if ce <= cs:
continue continue
offset_slots_start = (b_start - t_start) / slot_minutes
offset_slots_end = (b_end - t_start) / slot_minutes bx = x0 + DATE_COL_W + (cs - t_start) / 15 * slot_w
block_top = table_top - offset_slots_start * row_h bw = (ce - cs) / 15 * slot_w
block_bot = table_top - offset_slots_end * row_h
block_h = block_top - block_bot
pt = type_map[block.type_id] pt = type_map[block.type_id]
fill_rgb = hex_to_rgb(pt.color) fill_rgb = hex_to_rgb(pt.color)
text_rgb = (0.1, 0.1, 0.1) if is_light(pt.color) else (1.0, 1.0, 1.0) text_rgb = (0.08, 0.08, 0.08) if is_light(pt.color) else (1.0, 1.0, 1.0)
# Block rectangle with slight inset
inset = 0.5
bx = cx + inset
by = block_bot + inset
bw = day_col_w - 2 * inset
bh = block_h - 2 * inset
inset = 1.0
c.saveState() c.saveState()
draw_rect_filled(c, bx, by, bw, bh, fill_rgb, GRID_LINE, 0.5) # Draw block rectangle
set_fill(c, fill_rgb)
set_stroke(c, (0.0, 0.0, 0.0) if False else fill_rgb) # no border stroke
c.roundRect(bx + inset, row_y + inset, bw - 2 * inset, row_h - 2 * inset,
2, fill=1, stroke=0)
# Clip text to block # Draw text clipped to block
p = c.beginPath() p = c.beginPath()
p.rect(bx + 1, by + 1, bw - 2, bh - 2) p.rect(bx + inset + 1, row_y + inset + 1, bw - 2 * inset - 2, row_h - 2 * inset - 2)
c.clipPath(p, stroke=0, fill=0) c.clipPath(p, stroke=0, fill=0)
set_fill(c, text_rgb) set_fill(c, text_rgb)
lines = [block.title]
if block.responsible:
lines.append(block.responsible)
if len(lines) == 1 or bh < cell_font_size * 2.5: title_line = block.title + ('' if overnight else '')
c.setFont("Helvetica-Bold", cell_font_size) if row_h > block_title_font * 2.2 and block.responsible:
c.drawCentredString(bx + bw / 2, by + (bh - cell_font_size) / 2, lines[0]) # Two lines: title + responsible
c.setFont('Helvetica-Bold', block_title_font)
c.drawCentredString(bx + bw / 2, row_y + row_h / 2 + 1, title_line)
c.setFont('Helvetica', block_time_font)
set_fill(c, (text_rgb[0] * 0.8, text_rgb[1] * 0.8, text_rgb[2] * 0.8)
if is_light(pt.color) else (0.85, 0.85, 0.85))
c.drawCentredString(bx + bw / 2, row_y + row_h / 2 - block_title_font + 1,
block.responsible)
else: else:
c.setFont("Helvetica-Bold", cell_font_size) c.setFont('Helvetica-Bold', block_title_font)
c.drawCentredString(bx + bw / 2, by + bh / 2 + 1, lines[0]) c.drawCentredString(bx + bw / 2, row_y + (row_h - block_title_font) / 2, title_line)
c.setFont("Helvetica", max(4.5, cell_font_size - 1.0))
set_fill(c, (text_rgb[0] * 0.85, text_rgb[1] * 0.85, text_rgb[2] * 0.85) if is_light(pt.color)
else (0.9, 0.9, 0.9))
c.drawCentredString(bx + bw / 2, by + bh / 2 - cell_font_size + 1, lines[1])
c.restoreState() c.restoreState()
# ── Legend ──────────────────────────────────────────────────────── # ── Legend ────────────────────────────────────────────────────────
legend_y = table_bottom - 8 legend_y_top = table_top - num_days * row_h - 6
legend_x = x0
legend_label_h = legend_item_h
c.setFont("Helvetica-Bold", 7) c.setFont('Helvetica-Bold', 7)
set_fill(c, HEADER_BG) set_fill(c, HEADER_BG)
c.drawString(legend_x, legend_y, "Legenda:") c.drawString(x0, legend_y_top, 'Legenda:')
legend_y -= 4 legend_y_top -= LEGEND_ITEM_H
legend_box_w = 10 * mm
legend_text_w = 50 * mm
legend_col_stride = legend_box_w + legend_text_w + 4 * mm
cols = max(1, int((PAGE_W - 2 * MARGIN) / legend_col_stride))
for i, pt in enumerate(doc.program_types): for i, pt in enumerate(doc.program_types):
col = i % cols col = i % legend_cols
row_idx = i // cols row_idx = i // legend_cols
lx = legend_x + col * legend_col_stride lx = x0 + col * LEGEND_STRIDE
ly = legend_y - row_idx * legend_label_h ly = legend_y_top - row_idx * LEGEND_ITEM_H
fill_rgb = hex_to_rgb(pt.color) fill_rgb = hex_to_rgb(pt.color)
text_rgb = (0.1, 0.1, 0.1) if is_light(pt.color) else (1.0, 1.0, 1.0)
draw_rect_filled(c, lx, ly - legend_label_h + 2, legend_box_w, legend_label_h - 2, fill_rgb, GRID_LINE, 0.3) # Colored square (NO text inside, just the color)
c.setFont("Helvetica-Bold", 6.5) fill_rect(c, lx, ly - LEGEND_ITEM_H + 2, LEGEND_BOX_W, LEGEND_ITEM_H - 2,
set_fill(c, text_rgb) fill_rgb, BORDER, 0.3)
c.drawCentredString(lx + legend_box_w / 2, ly - legend_label_h + 2 + (legend_label_h - 2 - 6.5) / 2, pt.name[:10])
c.setFont("Helvetica", 7) # Type name NEXT TO the square
set_fill(c, LABEL_TEXT) c.setFont('Helvetica', 7)
c.drawString(lx + legend_box_w + 2, ly - legend_label_h + 2 + (legend_label_h - 2 - 7) / 2, pt.name) set_fill(c, (0.15, 0.15, 0.15))
c.drawString(lx + LEGEND_BOX_W + 3,
ly - LEGEND_ITEM_H + 2 + (LEGEND_ITEM_H - 2 - 7) / 2,
pt.name)
# ── Footer ──────────────────────────────────────────────────────── # ── Footer ────────────────────────────────────────────────────────
gen_date = datetime.now().strftime("%d.%m.%Y %H:%M") gen_date = datetime.now().strftime('%d.%m.%Y %H:%M')
c.setFont("Helvetica-Oblique", 6.5) c.setFont('Helvetica-Oblique', 6.5)
set_fill(c, FOOTER_TEXT) set_fill(c, FOOTER_TEXT)
c.drawCentredString(PAGE_W / 2, MARGIN - 2, f"Vygenerováno Scenár Creatorem | {gen_date}") c.drawCentredString(PAGE_W / 2, MARGIN - 2, f'Vygenerováno Scenár Creatorem v4 | {gen_date}')
c.save() c.save()
return buf.getvalue() return buf.getvalue()

View File

@@ -1,6 +1,7 @@
"""Pydantic v2 models for Scenar Creator v3.""" """Pydantic v2 models for Scenar Creator v4."""
import uuid import uuid
from datetime import date as date_type, timedelta
from typing import List, Optional from typing import List, Optional
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
@@ -9,8 +10,8 @@ from pydantic import BaseModel, Field
class Block(BaseModel): class Block(BaseModel):
id: str = Field(default_factory=lambda: str(uuid.uuid4())) id: str = Field(default_factory=lambda: str(uuid.uuid4()))
date: str # "YYYY-MM-DD" date: str # "YYYY-MM-DD"
start: str # "HH:MM" start: str # "HH:MM" (can be > 24:00 for overnight continuation)
end: str # "HH:MM" end: str # "HH:MM" (if end < start → overnight block)
title: str title: str
type_id: str type_id: str
responsible: Optional[str] = None responsible: Optional[str] = None
@@ -26,7 +27,10 @@ class ProgramType(BaseModel):
class EventInfo(BaseModel): class EventInfo(BaseModel):
title: str title: str
subtitle: Optional[str] = None subtitle: Optional[str] = None
date: Optional[str] = None # Multi-day: date_from → date_to (inclusive). Backward compat: date = date_from.
date: Optional[str] = None # legacy / backward compat
date_from: Optional[str] = None
date_to: Optional[str] = None
location: Optional[str] = None location: Optional[str] = None
@@ -35,3 +39,8 @@ class ScenarioDocument(BaseModel):
event: EventInfo event: EventInfo
program_types: List[ProgramType] program_types: List[ProgramType]
blocks: List[Block] blocks: List[Block]
def get_sorted_dates(self) -> List[str]:
"""Return sorted list of unique block dates."""
dates = sorted(set(b.date for b in self.blocks))
return dates

View File

@@ -709,3 +709,169 @@ body {
background: var(--border); background: var(--border);
color: var(--text); color: var(--text);
} }
/* ============================================================
v4 — Horizontal Canvas (X=time, Y=days)
============================================================ */
.canvas-wrapper {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--bg);
}
.canvas-scroll-area {
flex: 1;
overflow: auto;
padding: 12px 16px;
}
/* Time axis row */
.time-axis-row {
display: flex;
align-items: flex-end;
margin-bottom: 2px;
}
.time-corner {
background: transparent;
flex-shrink: 0;
}
.time-tick {
position: absolute;
top: 4px;
font-size: 10px;
color: var(--text-light);
transform: translateX(-50%);
font-variant-numeric: tabular-nums;
pointer-events: none;
white-space: nowrap;
}
/* Day rows */
.day-rows {
display: flex;
flex-direction: column;
gap: 4px;
}
.day-row {
display: flex;
align-items: stretch;
background: var(--white);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
overflow: hidden;
}
.day-label {
display: flex;
align-items: center;
justify-content: flex-end;
padding: 0 10px 0 6px;
font-size: 11px;
font-weight: 600;
color: var(--text-light);
background: #f8fafc;
border-right: 1px solid var(--border);
flex-shrink: 0;
white-space: nowrap;
}
.day-timeline {
flex: 1;
position: relative;
background: var(--white);
cursor: crosshair;
overflow: hidden;
}
/* Hour grid lines in timeline */
.grid-line {
position: absolute;
top: 0;
bottom: 0;
width: 1px;
background: var(--border);
pointer-events: none;
z-index: 1;
}
/* Block element (horizontal) */
.block-el {
position: absolute;
border-radius: 4px;
overflow: hidden;
cursor: grab;
z-index: 10;
box-shadow: 0 1px 3px rgba(0,0,0,0.18);
transition: box-shadow 0.12s;
user-select: none;
touch-action: none;
display: flex;
align-items: center;
}
.block-el:hover {
box-shadow: 0 3px 8px rgba(0,0,0,0.25);
z-index: 20;
}
.block-el:active {
cursor: grabbing;
}
.block-el.overnight {
opacity: 0.85;
border-right: 3px dashed rgba(255,255,255,0.5);
}
.block-inner {
padding: 2px 6px;
overflow: hidden;
display: flex;
flex-direction: column;
justify-content: center;
min-width: 0;
width: 100%;
}
.block-title {
font-size: 11px;
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
line-height: 1.3;
}
.block-time {
font-size: 9px;
opacity: 0.8;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
line-height: 1.2;
}
/* Resize handle on right edge */
.block-el::after {
content: '';
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 6px;
cursor: ew-resize;
background: rgba(255,255,255,0.2);
border-radius: 0 4px 4px 0;
opacity: 0;
transition: opacity 0.12s;
}
.block-el:hover::after {
opacity: 1;
}

View File

@@ -13,7 +13,7 @@
<header class="header"> <header class="header">
<div class="header-left"> <div class="header-left">
<h1 class="header-title">Scenár Creator</h1> <h1 class="header-title">Scenár Creator</h1>
<span class="header-version">v3.0</span> <span class="header-version">v4.0</span>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<label class="btn btn-secondary btn-sm" id="importJsonBtn"> <label class="btn btn-secondary btn-sm" id="importJsonBtn">
@@ -44,9 +44,15 @@
<label>Podtitul</label> <label>Podtitul</label>
<input type="text" id="eventSubtitle" placeholder="Podtitul"> <input type="text" id="eventSubtitle" placeholder="Podtitul">
</div> </div>
<div class="form-row">
<div class="form-group"> <div class="form-group">
<label>Datum</label> <label>Od</label>
<input type="date" id="eventDate"> <input type="date" id="eventDateFrom">
</div>
<div class="form-group">
<label>Do</label>
<input type="date" id="eventDateTo">
</div>
</div> </div>
<div class="form-group"> <div class="form-group">
<label>Místo</label> <label>Místo</label>
@@ -66,69 +72,75 @@
</aside> </aside>
<main class="canvas-wrapper"> <main class="canvas-wrapper">
<div class="canvas-header" id="canvasHeader"></div> <div id="canvasScrollArea" class="canvas-scroll-area">
<div class="canvas-scroll"> <div id="timeAxis" class="time-axis-row"></div>
<div class="canvas" id="canvas"> <div id="dayRows" class="day-rows"></div>
<div class="time-axis" id="timeAxis"></div>
<div class="day-columns" id="dayColumns"></div>
</div>
</div> </div>
</main> </main>
</div> </div>
</div> </div>
<!-- Documentation tab -->
<div class="tab-content hidden" id="tab-docs"> <div class="tab-content hidden" id="tab-docs">
<div class="docs-container"> <div class="docs-container">
<h2>Dokumentace — Scenár Creator v3</h2> <h2>Dokumentace — Scenár Creator v4</h2>
<h3>Jak začít</h3> <h3>Jak začít</h3>
<p>Máte dvě možnosti:</p>
<ol> <ol>
<li><strong>Nový scénář</strong> — klikněte na tlačítko "Nový scénář" v záhlaví. Vytvoří se prázdný scénář s jedním dnem.</li> <li><strong>Nový scénář</strong> — klikněte na "Nový scénář" v záhlaví.</li>
<li><strong>Import JSON</strong> — klikněte na "Import JSON" a vyberte dříve uložený .json soubor. Můžete také přetáhnout JSON soubor přímo na plochu editoru.</li> <li><strong>Import JSON</strong> — klikněte na "Import JSON" a vyberte uložený .json soubor.</li>
</ol> </ol>
<h3>Nastavení akce</h3>
<p>V postranním panelu nastavte:</p>
<ul>
<li><strong>Od / Do</strong> — rozsah dat akce. Každý den se zobrazí jako jeden řádek v editoru.</li>
<li>Jedno datum = jednodnenní akce, více datumů = vícedenní kurz.</li>
</ul>
<h3>Práce s bloky</h3> <h3>Práce s bloky</h3>
<ul> <ul>
<li><strong>Přidání bloku:</strong> Klikněte na "+ Přidat blok" v postranním panelu, nebo klikněte na prázdné místo na časové ose.</li> <li><strong>Přidání bloku:</strong> Klikněte na "+ Přidat blok" nebo klikněte na prázdné místo v časové ose.</li>
<li><strong>Přesun bloku:</strong> Chytněte blok myší a přetáhněte ho na jiný čas. Bloky se přichytávají na 15minutovou mřížku.</li> <li><strong>Přesun bloku:</strong> Chytněte blok a táhněte doleva/doprava po časové ose. Snap na 15 min.</li>
<li><strong>Změna délky:</strong> Chytněte dolní okraj bloku a tažením změňte dobu trvání.</li> <li><strong>Změna délky:</strong> Chytněte pravý okraj bloku a táhněte.</li>
<li><strong>Úprava bloku:</strong> Klikněte na blok pro otevření editačního popup okna, kde můžete upravit název, typ, garanta a poznámku.</li> <li><strong>Úprava bloku:</strong> Klikněte na blok.</li>
<li><strong>Smazání bloku:</strong> V editačním popup okně klikněte na tlačítko "Smazat blok".</li> <li><strong>Smazání bloku:</strong> V editačním okně klikněte na "Smazat blok".</li>
</ul>
<h3>Čas bloku</h3>
<ul>
<li>Zadejte <strong>Začátek</strong> a <strong>Konec</strong> (HH:MM).</li>
<li>Nebo zadejte <strong>Začátek</strong> a <strong>Trvání</strong> (HH:MM) — konec se vypočítá automaticky.</li>
<li>Lze zadat i <strong>program přes půlnoc</strong> — konec může být menší než začátek (např. 23:00 → 01:30).</li>
</ul> </ul>
<h3>Typy programů a barvy</h3> <h3>Typy programů a barvy</h3>
<p>V postranním panelu v sekci "Typy programů" můžete:</p>
<ul> <ul>
<li>Přidat nový typ kliknutím na "+ Přidat typ"</li> <li>Přidejte typ kliknutím na "+ Přidat typ".</li>
<li>Pojmenovat typ a vybrat barvu pomocí barevného výběru</li> <li>Nastavte název a barvu pomocí barevného výběru.</li>
<li>Odebrat typ kliknutím na tlačítko ×</li>
</ul> </ul>
<h3>Export JSON</h3> <h3>Export</h3>
<p>Kliknutím na "Export JSON" stáhnete aktuální stav scénáře jako .json soubor. Tento soubor můžete později znovu importovat a pokračovat v úpravách.</p> <ul>
<li><strong>Export JSON</strong> — uloží scénář jako .json soubor pro pozdější použití.</li>
<h3>Generování PDF</h3> <li><strong>Generovat PDF</strong> — vytvoří tisknutelný PDF timetable (A4, jedna stránka, barvy, legenda).</li>
<p>Kliknutím na "Generovat PDF" se scénář odešle na server a vygeneruje se přehledný PDF dokument ve formátu A4 na šířku s barevnými bloky a legendou.</p> <li><strong>Vzorový JSON</strong><a href="/api/sample">stáhnout sample.json</a></li>
</ul>
<h3>Formát JSON</h3> <h3>Formát JSON</h3>
<table class="docs-table"> <table class="docs-table">
<thead> <thead><tr><th>Pole</th><th>Typ</th><th>Popis</th></tr></thead>
<tr><th>Pole</th><th>Typ</th><th>Popis</th></tr>
</thead>
<tbody> <tbody>
<tr><td>version</td><td>string</td><td>Verze formátu (1.0)</td></tr>
<tr><td>event.title</td><td>string</td><td>Název akce</td></tr> <tr><td>event.title</td><td>string</td><td>Název akce</td></tr>
<tr><td>event.subtitle</td><td>string?</td><td>Podtitul</td></tr> <tr><td>event.date_from</td><td>string</td><td>Začátek akce (YYYY-MM-DD)</td></tr>
<tr><td>event.date</td><td>string?</td><td>Datum (YYYY-MM-DD)</td></tr> <tr><td>event.date_to</td><td>string</td><td>Konec akce (YYYY-MM-DD)</td></tr>
<tr><td>event.location</td><td>string?</td><td>Místo</td></tr> <tr><td>event.location</td><td>string?</td><td>Místo konání</td></tr>
<tr><td>program_types[].id</td><td>string</td><td>Unikátní ID typu</td></tr> <tr><td>program_types[].id</td><td>string</td><td>Unikátní ID typu</td></tr>
<tr><td>program_types[].name</td><td>string</td><td>Název typu</td></tr> <tr><td>program_types[].name</td><td>string</td><td>Název typu</td></tr>
<tr><td>program_types[].color</td><td>string</td><td>Barva (#RRGGBB)</td></tr> <tr><td>program_types[].color</td><td>string</td><td>Barva (#RRGGBB)</td></tr>
<tr><td>blocks[].id</td><td>string</td><td>Unikátní ID bloku</td></tr> <tr><td>blocks[].date</td><td>string</td><td>Datum bloku (YYYY-MM-DD)</td></tr>
<tr><td>blocks[].date</td><td>string</td><td>Datum (YYYY-MM-DD)</td></tr>
<tr><td>blocks[].start</td><td>string</td><td>Začátek (HH:MM)</td></tr> <tr><td>blocks[].start</td><td>string</td><td>Začátek (HH:MM)</td></tr>
<tr><td>blocks[].end</td><td>string</td><td>Konec (HH:MM)</td></tr> <tr><td>blocks[].end</td><td>string</td><td>Konec (HH:MM) — může být &lt; start pro přes-půlnoční blok</td></tr>
<tr><td>blocks[].title</td><td>string</td><td>Název bloku</td></tr> <tr><td>blocks[].title</td><td>string</td><td>Název bloku</td></tr>
<tr><td>blocks[].type_id</td><td>string</td><td>ID typu programu</td></tr> <tr><td>blocks[].type_id</td><td>string</td><td>ID typu programu</td></tr>
<tr><td>blocks[].responsible</td><td>string?</td><td>Garant</td></tr> <tr><td>blocks[].responsible</td><td>string?</td><td>Garant</td></tr>
@@ -136,12 +148,12 @@
</tbody> </tbody>
</table> </table>
<h3>Vzorový JSON</h3> <h3>API dokumentace</h3>
<p><a href="/api/sample" class="btn btn-secondary btn-sm">Stáhnout sample.json</a></p> <p><a href="/docs" class="btn btn-secondary btn-sm" target="_blank">Swagger UI</a></p>
</div> </div>
</div> </div>
<!-- Block edit modal --> <!-- Block edit/create modal -->
<div class="modal-overlay hidden" id="blockModal"> <div class="modal-overlay hidden" id="blockModal">
<div class="modal"> <div class="modal">
<div class="modal-header"> <div class="modal-header">
@@ -154,6 +166,10 @@
<label>Název bloku</label> <label>Název bloku</label>
<input type="text" id="modalBlockTitle" placeholder="Název"> <input type="text" id="modalBlockTitle" placeholder="Název">
</div> </div>
<div class="form-group">
<label>Den</label>
<input type="date" id="modalBlockDate">
</div>
<div class="form-group"> <div class="form-group">
<label>Typ programu</label> <label>Typ programu</label>
<select id="modalBlockType"></select> <select id="modalBlockType"></select>
@@ -168,6 +184,10 @@
<input type="time" id="modalBlockEnd"> <input type="time" id="modalBlockEnd">
</div> </div>
</div> </div>
<div class="form-group">
<label>Nebo trvání</label>
<input type="text" id="modalBlockDuration" placeholder="HH:MM (např. 1:30)">
</div>
<div class="form-group"> <div class="form-group">
<label>Garant</label> <label>Garant</label>
<input type="text" id="modalBlockResponsible" placeholder="Garant"> <input type="text" id="modalBlockResponsible" placeholder="Garant">
@@ -192,5 +212,8 @@
<script src="/static/js/canvas.js"></script> <script src="/static/js/canvas.js"></script>
<script src="/static/js/export.js"></script> <script src="/static/js/export.js"></script>
<script src="/static/js/app.js"></script> <script src="/static/js/app.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => App.init());
</script>
</body> </body>
</html> </html>

View File

@@ -1,11 +1,11 @@
/** /**
* Main application logic for Scenar Creator v3. * Main application logic for Scenar Creator v4.
* State management, UI wiring, modal handling. * Multi-day state, duration input, horizontal canvas.
*/ */
const App = { const App = {
state: { state: {
event: { title: '', subtitle: '', date: '', location: '' }, event: { title: '', subtitle: '', date_from: '', date_to: '', location: '' },
program_types: [], program_types: [],
blocks: [] blocks: []
}, },
@@ -15,20 +15,72 @@ const App = {
this.newScenario(); 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() { getDocument() {
this.syncEventFromUI(); this.syncEventFromUI();
return { return {
version: '1.0', 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 })), program_types: this.state.program_types.map(pt => ({ ...pt })),
blocks: this.state.blocks.map(b => ({ ...b })) blocks: this.state.blocks.map(b => ({ ...b }))
}; };
}, },
loadDocument(doc) { 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.program_types = (doc.program_types || []).map(pt => ({ ...pt }));
this.state.blocks = (doc.blocks || []).map(b => ({ this.state.blocks = (doc.blocks || []).map(b => ({
...b, ...b,
@@ -40,9 +92,9 @@ const App = {
}, },
newScenario() { newScenario() {
const today = new Date().toISOString().split('T')[0]; const today = new Date().toISOString().slice(0, 10);
this.state = { this.state = {
event: { title: 'Nová akce', subtitle: '', date: today, location: '' }, event: { title: 'Nová akce', subtitle: '', date_from: today, date_to: today, location: '' },
program_types: [ program_types: [
{ id: 'main', name: 'Hlavní program', color: '#3B82F6' }, { id: 'main', name: 'Hlavní program', color: '#3B82F6' },
{ id: 'rest', name: 'Odpočinek', color: '#22C55E' } { id: 'rest', name: 'Odpočinek', color: '#22C55E' }
@@ -54,23 +106,25 @@ const App = {
this.renderCanvas(); this.renderCanvas();
}, },
// --- Sync sidebar <-> state --- // ─── Sync sidebar <-> state ───────────────────────────────────────
syncEventFromUI() { syncEventFromUI() {
this.state.event.title = document.getElementById('eventTitle').value.trim() || 'Nová akce'; this.state.event.title = document.getElementById('eventTitle').value.trim() || 'Nová akce';
this.state.event.subtitle = document.getElementById('eventSubtitle').value.trim() || null; 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; this.state.event.location = document.getElementById('eventLocation').value.trim() || null;
}, },
syncEventToUI() { syncEventToUI() {
document.getElementById('eventTitle').value = this.state.event.title || ''; document.getElementById('eventTitle').value = this.state.event.title || '';
document.getElementById('eventSubtitle').value = this.state.event.subtitle || ''; 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 || ''; document.getElementById('eventLocation').value = this.state.event.location || '';
}, },
// --- Program types --- // ─── Program types ────────────────────────────────────────────────
renderTypes() { renderTypes() {
const container = document.getElementById('programTypesContainer'); const container = document.getElementById('programTypesContainer');
@@ -83,16 +137,13 @@ const App = {
<input type="text" value="${pt.name}" placeholder="Název typu" data-idx="${i}"> <input type="text" value="${pt.name}" placeholder="Název typu" data-idx="${i}">
<button class="type-remove" data-idx="${i}">&times;</button> <button class="type-remove" data-idx="${i}">&times;</button>
`; `;
// Color change
row.querySelector('input[type="color"]').addEventListener('change', (e) => { row.querySelector('input[type="color"]').addEventListener('change', (e) => {
this.state.program_types[i].color = e.target.value; this.state.program_types[i].color = e.target.value;
this.renderCanvas(); this.renderCanvas();
}); });
// Name change
row.querySelector('input[type="text"]').addEventListener('change', (e) => { row.querySelector('input[type="text"]').addEventListener('change', (e) => {
this.state.program_types[i].name = e.target.value.trim(); this.state.program_types[i].name = e.target.value.trim();
}); });
// Remove
row.querySelector('.type-remove').addEventListener('click', () => { row.querySelector('.type-remove').addEventListener('click', () => {
this.state.program_types.splice(i, 1); this.state.program_types.splice(i, 1);
this.renderTypes(); this.renderTypes();
@@ -102,150 +153,222 @@ const App = {
}); });
}, },
addType() { // ─── Canvas ───────────────────────────────────────────────────────
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 ---
renderCanvas() { renderCanvas() {
const dates = this.getUniqueDates(); Canvas.render(this.state);
Canvas.renderTimeAxis();
Canvas.renderDayColumns(dates);
Canvas.renderBlocks(this.state.blocks, this.state.program_types);
}, },
getUniqueDates() { // ─── Block modal ──────────────────────────────────────────────────
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]];
},
// --- Modal --- // Open modal to edit existing block
openBlockModal(blockId) {
editBlock(blockId) {
const block = this.state.blocks.find(b => b.id === blockId); const block = this.state.blocks.find(b => b.id === blockId);
if (!block) return; if (!block) return;
document.getElementById('modalTitle').textContent = 'Upravit blok';
document.getElementById('modalBlockId').value = block.id; document.getElementById('modalBlockId').value = block.id;
document.getElementById('modalBlockTitle').value = block.title; document.getElementById('modalBlockTitle').value = block.title || '';
document.getElementById('modalBlockStart').value = block.start; document.getElementById('modalBlockStart').value = block.start || '';
document.getElementById('modalBlockEnd').value = block.end; document.getElementById('modalBlockEnd').value = block.end || '';
document.getElementById('modalBlockResponsible').value = block.responsible || ''; document.getElementById('modalBlockResponsible').value = block.responsible || '';
document.getElementById('modalBlockNotes').value = block.notes || ''; document.getElementById('modalBlockNotes').value = block.notes || '';
this._updateDuration();
// Populate type select this._populateTypeSelect(block.type_id);
const select = document.getElementById('modalBlockType'); document.getElementById('modalBlockDate').value = block.date || '';
select.innerHTML = ''; 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 => { this.state.program_types.forEach(pt => {
const opt = document.createElement('option'); const opt = document.createElement('option');
opt.value = pt.id; opt.value = pt.id;
opt.textContent = pt.name; opt.textContent = pt.name;
if (pt.id === block.type_id) opt.selected = true; if (pt.id === selectedId) opt.selected = true;
select.appendChild(opt); sel.appendChild(opt);
}); });
document.getElementById('blockModal').classList.remove('hidden');
}, },
saveBlockFromModal() { _updateDuration() {
const blockId = document.getElementById('modalBlockId').value; const startVal = document.getElementById('modalBlockStart').value;
const block = this.state.blocks.find(b => b.id === blockId); const endVal = document.getElementById('modalBlockEnd').value;
if (!block) return; if (!startVal || !endVal) {
document.getElementById('modalBlockDuration').value = '';
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; return;
} }
const blob = await API.postBlob('/api/generate-pdf', doc); const s = this.parseTimeToMin(startVal);
API.downloadBlob(blob, 'scenar_timetable.pdf'); let e = this.parseTimeToMin(endVal);
this.toast('PDF vygenerován', 'success'); if (e < s) e += 24 * 60; // overnight
} catch (err) { const dur = e - s;
this.toast('Chyba: ' + err.message, 'error'); document.getElementById('modalBlockDuration').value = this.minutesToTime(dur);
},
_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;
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');
}, },
// --- Utility --- _deleteBlock() {
const blockId = document.getElementById('modalBlockId').value;
uid() { if (!blockId) return;
return 'xxxx-xxxx-xxxx'.replace(/x/g, () => this.state.blocks = this.state.blocks.filter(b => b.id !== blockId);
Math.floor(Math.random() * 16).toString(16) document.getElementById('blockModal').classList.add('hidden');
); this.renderCanvas();
this.toast('Blok smazán', 'success');
}, },
// --- Event binding --- // ─── 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() { 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 // Tabs
document.querySelectorAll('.tab').forEach(tab => { document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => { 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 // Close modal on overlay click
document.getElementById('blockModal').addEventListener('click', (e) => { 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. * Canvas editor for Scenar Creator v4.
* Renders schedule blocks on a time-grid canvas with drag & drop via interact.js. * Horizontal layout: X = time, Y = days.
* interact.js for drag (horizontal) and resize (right edge).
*/ */
const Canvas = { const Canvas = {
GRID_MINUTES: 15, GRID_MINUTES: 15,
PX_PER_SLOT: 30, // 30px per 15 min ROW_H: 52, // px height of one day row
START_HOUR: 7, TIME_LABEL_W: 80, // px width of date label column
END_HOUR: 23, 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() { get pxPerMinute() {
return this.PX_PER_SLOT / this.GRID_MINUTES; const slots = (this._endMin - this._startMin) / this.GRID_MINUTES;
}, const container = document.getElementById('canvasScrollArea');
if (!container) return 2;
get totalSlots() { const avail = container.clientWidth - this.TIME_LABEL_W - 4;
return ((this.END_HOUR - this.START_HOUR) * 60) / this.GRID_MINUTES; return avail / ((this._endMin - this._startMin));
},
get totalHeight() {
return this.totalSlots * this.PX_PER_SLOT;
}, },
minutesToPx(minutes) { minutesToPx(minutes) {
return (minutes - this.START_HOUR * 60) * this.pxPerMinute; return (minutes - this._startMin) * this.pxPerMinute;
}, },
pxToMinutes(px) { pxToMinutes(px) {
return Math.round(px / this.pxPerMinute + this.START_HOUR * 60); return px / this.pxPerMinute + this._startMin;
}, },
snapMinutes(minutes) { snapMinutes(minutes) {
@@ -34,234 +36,295 @@ const Canvas = {
}, },
formatTime(totalMinutes) { formatTime(totalMinutes) {
const h = Math.floor(totalMinutes / 60); const norm = ((totalMinutes % 1440) + 1440) % 1440;
const m = totalMinutes % 60; const h = Math.floor(norm / 60);
const m = norm % 60;
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`; return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
}, },
parseTime(str) { parseTime(str) {
if (!str) return 0;
const [h, m] = str.split(':').map(Number); const [h, m] = str.split(':').map(Number);
return h * 60 + m; return (h || 0) * 60 + (m || 0);
}, },
isLightColor(hex) { isLightColor(hex) {
const h = hex.replace('#', ''); const h = (hex || '#888888').replace('#', '');
const r = parseInt(h.substring(0, 2), 16); const r = parseInt(h.substring(0, 2), 16) || 128;
const g = parseInt(h.substring(2, 4), 16); const g = parseInt(h.substring(2, 4), 16) || 128;
const b = parseInt(h.substring(4, 6), 16); const b = parseInt(h.substring(4, 6), 16) || 128;
return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6; return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6;
}, },
renderTimeAxis() { // Derive time range from blocks (with default fallback)
const axis = document.getElementById('timeAxis'); _computeRange(blocks) {
axis.innerHTML = ''; if (!blocks || blocks.length === 0) {
axis.style.height = this.totalHeight + 'px'; 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;
}
},
for (let slot = 0; slot <= this.totalSlots; slot++) { render(state) {
const minutes = this.START_HOUR * 60 + slot * this.GRID_MINUTES; const dates = App.getDates();
const isHour = minutes % 60 === 0; this._computeRange(state.blocks);
const isHalf = minutes % 30 === 0;
if (isHour || isHalf) { const timeAxisEl = document.getElementById('timeAxis');
const dayRowsEl = document.getElementById('dayRows');
if (!timeAxisEl || !dayRowsEl) return;
timeAxisEl.innerHTML = '';
dayRowsEl.innerHTML = '';
this._renderTimeAxis(timeAxisEl, dates);
this._renderDayRows(dayRowsEl, dates, state);
},
_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'); const label = document.createElement('div');
label.className = 'time-label'; label.className = 'time-tick';
label.style.top = (slot * this.PX_PER_SLOT) + 'px'; label.style.left = `calc(${pct}% - 1px)`;
label.textContent = this.formatTime(minutes); label.textContent = this.formatTime(m);
if (!isHour) { labelsWrap.appendChild(label);
label.style.fontSize = '9px';
label.style.opacity = '0.6';
}
axis.appendChild(label);
}
} }
container.appendChild(labelsWrap);
}, },
renderDayColumns(dates) { _canvasWidth() {
const header = document.getElementById('canvasHeader'); const container = document.getElementById('canvasScrollArea');
const columns = document.getElementById('dayColumns'); if (!container) return 800;
header.innerHTML = ''; return Math.max(600, container.clientWidth - this.TIME_LABEL_W - 20);
columns.innerHTML = '';
if (dates.length === 0) dates = [new Date().toISOString().split('T')[0]];
dates.forEach(dateStr => {
// Header
const dh = document.createElement('div');
dh.className = 'day-header';
dh.textContent = dateStr;
header.appendChild(dh);
// 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);
});
}, },
renderBlocks(blocks, programTypes) { _renderDayRows(container, dates, state) {
// Remove existing blocks
document.querySelectorAll('.schedule-block').forEach(el => el.remove());
const typeMap = {}; const typeMap = {};
programTypes.forEach(pt => { typeMap[pt.id] = pt; }); for (const pt of state.program_types) typeMap[pt.id] = pt;
blocks.forEach(block => { for (const date of dates) {
const col = document.querySelector(`.day-column[data-date="${block.date}"]`); const row = document.createElement('div');
if (!col) return; row.className = 'day-row';
row.style.height = this.ROW_H + 'px';
row.dataset.date = date;
const pt = typeMap[block.type_id] || { color: '#94a3b8', name: '?' }; // Date label
const startMin = this.parseTime(block.start); const label = document.createElement('div');
const endMin = this.parseTime(block.end); label.className = 'day-label';
const top = this.minutesToPx(startMin); label.style.width = this.TIME_LABEL_W + 'px';
const height = (endMin - startMin) * this.pxPerMinute; label.style.minWidth = this.TIME_LABEL_W + 'px';
const isLight = this.isLightColor(pt.color); label.textContent = this._formatDate(date);
row.appendChild(label);
// Timeline area
const timeline = document.createElement('div');
timeline.className = 'day-timeline';
timeline.style.position = 'relative';
timeline.dataset.date = date;
// 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 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)));
});
// 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'); const el = document.createElement('div');
el.className = 'schedule-block' + (isLight ? ' light-bg' : ''); el.className = 'block-el' + (isOvernight ? ' overnight' : '');
el.dataset.blockId = block.id; el.dataset.id = block.id;
el.style.top = top + 'px'; el.style.cssText = `
el.style.height = Math.max(height, 20) + 'px'; left:${leftPct}%;
el.style.backgroundColor = pt.color; width:${widthPct}%;
background:${color};
el.innerHTML = ` color:${light ? '#1a1a1a' : '#ffffff'};
<div class="block-color-bar" style="background:${this.darkenColor(pt.color)}"></div> top:4px;
<div class="block-title">${this.escapeHtml(block.title)}</div> height:${this.ROW_H - 8}px;
<div class="block-time">${block.start} ${block.end}</div> position:absolute;
${block.responsible ? `<div class="block-responsible">${this.escapeHtml(block.responsible)}</div>` : ''}
<div class="resize-handle"></div>
`; `;
// 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 // Click to edit
el.addEventListener('click', (e) => { el.addEventListener('click', (e) => {
if (e.target.classList.contains('resize-handle')) return; e.stopPropagation();
App.editBlock(block.id); App.openBlockModal(block.id);
}); });
col.appendChild(el); // interact.js drag (horizontal only)
}); if (window.interact) {
interact(el)
this.initInteract(); .draggable({
axis: 'x',
listeners: {
move: (event) => this._onDragMove(event, block),
end: (event) => this._onDragEnd(event, block),
}, },
modifiers: [
initInteract() { interact.modifiers.snap({
if (typeof interact === 'undefined') return; targets: [interact.snappers.grid({ x: this._minutesPx(this.GRID_MINUTES), y: 1000 })],
range: Infinity,
interact('.schedule-block').draggable({ relativePoints: [{ x: 0, y: 0 }]
}),
interact.modifiers.restrict({ restriction: 'parent' })
],
inertia: false, 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 }
}) })
], .resizable({
edges: { right: true },
listeners: { listeners: {
start: (event) => { move: (event) => this._onResizeMove(event, block),
event.target.style.zIndex = 50; end: (event) => this._onResizeEnd(event, block),
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;
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: [ modifiers: [
interact.modifiers.snap({ interact.modifiers.snapSize({
targets: [interact.snappers.grid({ targets: [interact.snappers.grid({ width: this._minutesPx(this.GRID_MINUTES) })]
x: 1, y: this.PX_PER_SLOT
})],
range: Infinity,
relativePoint: { x: 0, y: 0 },
offset: 'self'
}), }),
interact.modifiers.restrictSize({ interact.modifiers.restrictSize({ minWidth: this._minutesPx(this.MIN_BLOCK_MIN) })
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));
}
}
}); });
},
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})`;
},
escapeHtml(str) {
if (!str) return '';
const d = document.createElement('div');
d.textContent = str;
return d.innerHTML;
} }
return el;
},
_minutesPx(minutes) {
return minutes * this.pxPerMinute;
},
_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();
},
}; };

View File

@@ -3,136 +3,101 @@
"event": { "event": {
"title": "Zimní výjezd oddílu", "title": "Zimní výjezd oddílu",
"subtitle": "Víkendový zážitkový kurz pro mladé", "subtitle": "Víkendový zážitkový kurz pro mladé",
"date_from": "2026-03-01",
"date_to": "2026-03-02",
"date": "2026-03-01", "date": "2026-03-01",
"location": "Chata Horní Lhota" "location": "Chata Horní Lhota"
}, },
"program_types": [ "program_types": [
{ { "id": "morning", "name": "Ranní program", "color": "#F97316" },
"id": "morning", { "id": "main", "name": "Hlavní program", "color": "#3B82F6" },
"name": "Ranní program", { "id": "rest", "name": "Odpočinek / jídlo", "color": "#22C55E" },
"color": "#F97316" { "id": "evening", "name": "Večerní program", "color": "#8B5CF6" }
},
{
"id": "main",
"name": "Hlavní program",
"color": "#3B82F6"
},
{
"id": "rest",
"name": "Odpočinek",
"color": "#22C55E"
}
], ],
"blocks": [ "blocks": [
{ {
"id": "b1", "id": "d1_b1", "date": "2026-03-01",
"date": "2026-03-01", "start": "08:00", "end": "08:30",
"start": "08:00", "title": "Budíček a rozcvička", "type_id": "morning",
"end": "08:30", "responsible": "Kuba", "notes": "Venkovní rozcvička"
"title": "Budíček a rozcvička",
"type_id": "morning",
"responsible": "Kuba",
"notes": "Venkovní rozcvička, pokud počasí dovolí"
}, },
{ {
"id": "b2", "id": "d1_b2", "date": "2026-03-01",
"date": "2026-03-01", "start": "08:30", "end": "09:00",
"start": "08:30", "title": "Snídaně", "type_id": "rest",
"end": "09:00", "responsible": "Kuchyň", "notes": null
"title": "Snídaně",
"type_id": "rest",
"responsible": "Kuchyň",
"notes": null
}, },
{ {
"id": "b3", "id": "d1_b3", "date": "2026-03-01",
"date": "2026-03-01", "start": "09:00", "end": "11:00",
"start": "09:00", "title": "Stopovací hra v lese", "type_id": "main",
"end": "10:30", "responsible": "Lucka", "notes": "4 skupiny"
"title": "Stopovací hra v lese",
"type_id": "main",
"responsible": "Lucka",
"notes": "Rozdělení do 4 skupin, mapky připraveny"
}, },
{ {
"id": "b4", "id": "d1_b4", "date": "2026-03-01",
"date": "2026-03-01", "start": "11:00", "end": "11:15",
"start": "10:30", "title": "Svačina", "type_id": "rest",
"end": "11:00", "responsible": null, "notes": null
"title": "Svačina a pauza",
"type_id": "rest",
"responsible": null,
"notes": null
}, },
{ {
"id": "b5", "id": "d1_b5", "date": "2026-03-01",
"date": "2026-03-01", "start": "11:15", "end": "13:00",
"start": "11:00", "title": "Stavba přístřešků", "type_id": "main",
"end": "12:30", "responsible": "Petr", "notes": "Soutěž"
"title": "Stavba iglú / přístřešků",
"type_id": "main",
"responsible": "Petr",
"notes": "Soutěž o nejlepší stavbu, potřeba lopaty a plachty"
}, },
{ {
"id": "b6", "id": "d1_b6", "date": "2026-03-01",
"date": "2026-03-01", "start": "13:00", "end": "14:30",
"start": "12:30", "title": "Oběd a polední klid", "type_id": "rest",
"end": "14:00", "responsible": "Kuchyň", "notes": "Guláš"
"title": "Oběd a polední klid",
"type_id": "rest",
"responsible": "Kuchyň",
"notes": "Guláš + čaj"
}, },
{ {
"id": "b7", "id": "d1_b7", "date": "2026-03-01",
"date": "2026-03-01", "start": "14:30", "end": "17:00",
"start": "14:00", "title": "Orientační běh", "type_id": "main",
"end": "16:00", "responsible": "Honza", "notes": "Trasa 3 km"
"title": "Orientační běh",
"type_id": "main",
"responsible": "Honza",
"notes": "Trasa 3 km, kontroly rozmístěny od rána"
}, },
{ {
"id": "b8", "id": "d1_b8", "date": "2026-03-01",
"date": "2026-03-01", "start": "17:00", "end": "18:00",
"start": "16:00", "title": "Workshopy", "type_id": "morning",
"end": "16:30", "responsible": "Lucka + Petr", "notes": "Uzlování / Orientace"
"title": "Svačina",
"type_id": "rest",
"responsible": null,
"notes": null
}, },
{ {
"id": "b9", "id": "d1_b9", "date": "2026-03-01",
"date": "2026-03-01", "start": "18:00", "end": "19:00",
"start": "16:30", "title": "Večeře", "type_id": "rest",
"end": "18:00", "responsible": "Kuchyň", "notes": null
"title": "Workshopy dle výběru",
"type_id": "morning",
"responsible": "Lucka + Petr",
"notes": "Uzlování / Orientace s buzolou / Kresba mapy"
}, },
{ {
"id": "b10", "id": "d1_b10", "date": "2026-03-01",
"date": "2026-03-01", "start": "19:00", "end": "21:30",
"start": "18:00", "title": "Noční hra Světlušky", "type_id": "evening",
"end": "19:00", "responsible": "Honza + Kuba", "notes": "Čelovky, reflexní pásky"
"title": "Večeře",
"type_id": "rest",
"responsible": "Kuchyň",
"notes": null
}, },
{ {
"id": "b11", "id": "d2_b1", "date": "2026-03-02",
"date": "2026-03-01", "start": "08:00", "end": "09:00",
"start": "19:00", "title": "Snídaně + balení", "type_id": "rest",
"end": "21:00", "responsible": "Kuchyň", "notes": null
"title": "Noční hra Světlušky", },
"type_id": "main", {
"responsible": "Honza + Kuba", "id": "d2_b2", "date": "2026-03-02",
"notes": "Potřeba: čelovky, reflexní pásky, vysílačky" "start": "09:00", "end": "11:30",
"title": "Závěrečná hra Poklad", "type_id": "main",
"responsible": "Lucka", "notes": "Finálová aktivita víkendu"
},
{
"id": "d2_b3", "date": "2026-03-02",
"start": "11:30", "end": "12:30",
"title": "Oběd + vyhodnocení", "type_id": "rest",
"responsible": "Všichni", "notes": "Ceny pro vítěze"
},
{
"id": "d2_b4", "date": "2026-03-02",
"start": "12:30", "end": "14:00",
"title": "Odjezd domů", "type_id": "morning",
"responsible": "Martin", "notes": "Autobus 13:45"
} }
] ]
} }

View File

@@ -1,5 +1,5 @@
""" """
API endpoint tests for Scenar Creator v3. API endpoint tests for Scenar Creator v4.
""" """
import pytest import pytest
@@ -13,12 +13,8 @@ def client():
return TestClient(app) return TestClient(app)
def make_valid_doc(): def make_valid_doc(multiday=False):
return { blocks = [{
"version": "1.0",
"event": {"title": "Test Event"},
"program_types": [{"id": "ws", "name": "Workshop", "color": "#FF0000"}],
"blocks": [{
"id": "b1", "id": "b1",
"date": "2026-03-01", "date": "2026-03-01",
"start": "09:00", "start": "09:00",
@@ -26,6 +22,24 @@ def make_valid_doc():
"title": "Opening", "title": "Opening",
"type_id": "ws" "type_id": "ws"
}] }]
if multiday:
blocks.append({
"id": "b2",
"date": "2026-03-02",
"start": "10:00",
"end": "11:30",
"title": "Day 2 Session",
"type_id": "ws"
})
return {
"version": "1.0",
"event": {
"title": "Test Event",
"date_from": "2026-03-01",
"date_to": "2026-03-02" if multiday else "2026-03-01"
},
"program_types": [{"id": "ws", "name": "Workshop", "color": "#FF0000"}],
"blocks": blocks
} }
@@ -34,7 +48,7 @@ def test_health(client):
assert r.status_code == 200 assert r.status_code == 200
data = r.json() data = r.json()
assert data["status"] == "ok" assert data["status"] == "ok"
assert data["version"] == "3.0.0" assert data["version"] == "4.0.0"
def test_root_returns_html(client): def test_root_returns_html(client):
@@ -63,17 +77,6 @@ def test_validate_unknown_type(client):
assert any("UNKNOWN" in e for e in data["errors"]) assert any("UNKNOWN" in e for e in data["errors"])
def test_validate_bad_time_order(client):
doc = make_valid_doc()
doc["blocks"][0]["start"] = "10:00"
doc["blocks"][0]["end"] = "09:00"
r = client.post("/api/validate", json=doc)
assert r.status_code == 200
data = r.json()
assert data["valid"] is False
assert any("start time" in e for e in data["errors"])
def test_validate_no_blocks(client): def test_validate_no_blocks(client):
doc = make_valid_doc() doc = make_valid_doc()
doc["blocks"] = [] doc["blocks"] = []
@@ -98,17 +101,14 @@ def test_sample_endpoint(client):
data = r.json() data = r.json()
assert data["version"] == "1.0" assert data["version"] == "1.0"
assert data["event"]["title"] == "Zimní výjezd oddílu" assert data["event"]["title"] == "Zimní výjezd oddílu"
assert len(data["program_types"]) == 3 assert len(data["program_types"]) >= 3
assert len(data["blocks"]) >= 8 # multi-day sample
assert data["event"]["date_from"] == "2026-03-01"
assert data["event"]["date_to"] == "2026-03-02"
def test_sample_blocks_valid(client): # blocks for both days
r = client.get("/api/sample") dates = {b["date"] for b in data["blocks"]}
data = r.json() assert "2026-03-01" in dates
type_ids = {pt["id"] for pt in data["program_types"]} assert "2026-03-02" in dates
for block in data["blocks"]:
assert block["type_id"] in type_ids
assert block["start"] < block["end"]
def test_generate_pdf(client): def test_generate_pdf(client):
@@ -119,6 +119,23 @@ def test_generate_pdf(client):
assert r.content[:5] == b'%PDF-' assert r.content[:5] == b'%PDF-'
def test_generate_pdf_multiday(client):
doc = make_valid_doc(multiday=True)
r = client.post("/api/generate-pdf", json=doc)
assert r.status_code == 200
assert r.content[:5] == b'%PDF-'
def test_generate_pdf_overnight_block(client):
"""Block that crosses midnight: end < start."""
doc = make_valid_doc()
doc["blocks"][0]["start"] = "23:00"
doc["blocks"][0]["end"] = "01:30" # overnight
r = client.post("/api/generate-pdf", json=doc)
assert r.status_code == 200
assert r.content[:5] == b'%PDF-'
def test_generate_pdf_no_blocks(client): def test_generate_pdf_no_blocks(client):
doc = make_valid_doc() doc = make_valid_doc()
doc["blocks"] = [] doc["blocks"] = []
@@ -126,21 +143,26 @@ def test_generate_pdf_no_blocks(client):
assert r.status_code == 422 assert r.status_code == 422
def test_generate_pdf_multiday(client):
doc = make_valid_doc()
doc["blocks"].append({
"id": "b2",
"date": "2026-03-02",
"start": "14:00",
"end": "15:00",
"title": "Day 2 Session",
"type_id": "ws"
})
r = client.post("/api/generate-pdf", json=doc)
assert r.status_code == 200
assert r.content[:5] == b'%PDF-'
def test_swagger_docs(client): def test_swagger_docs(client):
r = client.get("/docs") r = client.get("/docs")
assert r.status_code == 200 assert r.status_code == 200
def test_backward_compat_date_field(client):
"""Old JSON with 'date' (not date_from/date_to) should still validate."""
doc = {
"version": "1.0",
"event": {"title": "Old Format", "date": "2026-03-01"},
"program_types": [{"id": "t1", "name": "Type", "color": "#0000FF"}],
"blocks": [{
"id": "bx",
"date": "2026-03-01",
"start": "10:00",
"end": "11:00",
"title": "Session",
"type_id": "t1"
}]
}
r = client.post("/api/validate", json=doc)
assert r.status_code == 200
assert r.json()["valid"] is True

View File

@@ -1,5 +1,5 @@
""" """
PDF generation tests for Scenar Creator v3. PDF generation tests for Scenar Creator v4.
""" """
import pytest import pytest
@@ -11,7 +11,8 @@ from app.models.event import ScenarioDocument, Block, ProgramType, EventInfo
def make_doc(**kwargs): def make_doc(**kwargs):
defaults = { defaults = {
"version": "1.0", "version": "1.0",
"event": EventInfo(title="Test PDF", subtitle="Subtitle"), "event": EventInfo(title="Test PDF", subtitle="Subtitle",
date_from="2026-03-01", date_to="2026-03-01"),
"program_types": [ "program_types": [
ProgramType(id="ws", name="Workshop", color="#0070C0"), ProgramType(id="ws", name="Workshop", color="#0070C0"),
], ],
@@ -32,8 +33,18 @@ def test_generate_pdf_basic():
assert pdf_bytes[:5] == b'%PDF-' assert pdf_bytes[:5] == b'%PDF-'
def test_generate_pdf_is_single_page():
import re
doc = make_doc()
pdf_bytes = generate_pdf(doc)
# Count /Type /Page (not /Pages) occurrences
pages = len(re.findall(rb'/Type\s*/Page[^s]', pdf_bytes))
assert pages == 1, f"Expected 1 page, got {pages}"
def test_generate_pdf_multiday(): def test_generate_pdf_multiday():
doc = make_doc( doc = make_doc(
event=EventInfo(title="Multi-day", date_from="2026-03-01", date_to="2026-03-02"),
program_types=[ program_types=[
ProgramType(id="key", name="Keynote", color="#FF0000"), ProgramType(id="key", name="Keynote", color="#FF0000"),
ProgramType(id="ws", name="Workshop", color="#0070C0"), ProgramType(id="ws", name="Workshop", color="#0070C0"),
@@ -50,6 +61,18 @@ def test_generate_pdf_multiday():
assert pdf_bytes[:5] == b'%PDF-' assert pdf_bytes[:5] == b'%PDF-'
def test_generate_pdf_overnight_block():
"""Block crossing midnight (end < start) should render without error."""
doc = make_doc(
blocks=[
Block(id="b1", date="2026-03-01", start="22:00", end="01:30",
title="Noční hra", type_id="ws", responsible="Honza"),
]
)
pdf_bytes = generate_pdf(doc)
assert pdf_bytes[:5] == b'%PDF-'
def test_generate_pdf_empty_blocks(): def test_generate_pdf_empty_blocks():
doc = make_doc(blocks=[]) doc = make_doc(blocks=[])
with pytest.raises(ScenarsError): with pytest.raises(ScenarsError):
@@ -67,14 +90,27 @@ def test_generate_pdf_missing_type():
generate_pdf(doc) generate_pdf(doc)
def test_generate_pdf_with_event_info(): def test_generate_pdf_with_full_event_info():
doc = make_doc( doc = make_doc(
event=EventInfo( event=EventInfo(
title="Full Event", title="Full Event",
subtitle="With all fields", subtitle="With all fields",
date="2026-03-01", date_from="2026-03-01",
date_to="2026-03-03",
location="Prague" location="Prague"
) ),
program_types=[
ProgramType(id="ws", name="Workshop", color="#0070C0"),
ProgramType(id="rest", name="Odpočinek", color="#22C55E"),
],
blocks=[
Block(id="b1", date="2026-03-01", start="09:00", end="10:00",
title="Session 1", type_id="ws"),
Block(id="b2", date="2026-03-02", start="10:00", end="11:00",
title="Session 2", type_id="rest"),
Block(id="b3", date="2026-03-03", start="08:00", end="09:00",
title="Session 3", type_id="ws"),
]
) )
pdf_bytes = generate_pdf(doc) pdf_bytes = generate_pdf(doc)
assert pdf_bytes[:5] == b'%PDF-' assert pdf_bytes[:5] == b'%PDF-'
@@ -93,3 +129,14 @@ def test_generate_pdf_multiple_blocks_same_day():
) )
pdf_bytes = generate_pdf(doc) pdf_bytes = generate_pdf(doc)
assert pdf_bytes[:5] == b'%PDF-' assert pdf_bytes[:5] == b'%PDF-'
def test_generate_pdf_many_types_legend():
"""Many program types should fit in multi-column legend."""
types = [ProgramType(id=f"t{i}", name=f"Typ {i}", color=f"#{'%06x' % (i * 20000)}")
for i in range(1, 9)]
blocks = [Block(id=f"b{i}", date="2026-03-01", start=f"{8+i}:00", end=f"{9+i}:00",
title=f"Blok {i}", type_id=f"t{i}") for i in range(1, 9)]
doc = make_doc(program_types=types, blocks=blocks)
pdf_bytes = generate_pdf(doc)
assert pdf_bytes[:5] == b'%PDF-'