Merge pull request #110 from rafaelfoster/main

Consistent upload option in the calendar, and fiz images rendering
This commit is contained in:
ulsklyc
2026-04-30 07:15:27 +02:00
committed by GitHub
8 changed files with 323 additions and 83 deletions
+5 -19
View File
@@ -31,6 +31,11 @@
<link rel="modulepreload" href="/router.js" />
<link rel="modulepreload" href="/rrule-ui.js" />
<!-- Theme: explizite Nutzer-Overrides vor CSS-Rendering anwenden (Flash-Prevention).
System-Präferenz wird durch @media (prefers-color-scheme: dark) in tokens.css
direkt per CSS behandelt — kein JS-matchMedia erforderlich. -->
<script src="/theme-init.js"></script>
<!-- Styles (Basis - seitenspezifische CSS wird vom Router on-demand geladen) -->
<link rel="stylesheet" href="/styles/tokens.css" />
<link rel="stylesheet" href="/styles/reset.css" />
@@ -39,30 +44,11 @@
<link rel="stylesheet" href="/styles/glass.css" />
<link rel="stylesheet" href="/styles/kitchen-tabs.css" />
<link rel="stylesheet" href="/styles/login.css" />
<!-- Theme: explizite Nutzer-Overrides vor CSS-Rendering anwenden (Flash-Prevention).
System-Präferenz wird durch @media (prefers-color-scheme: dark) in tokens.css
direkt per CSS behandelt — kein JS-matchMedia erforderlich. -->
<script>
(function() {
var stored = localStorage.getItem('oikos-theme');
if (stored === 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
} else if (stored === 'light') {
document.documentElement.setAttribute('data-theme', 'light');
} else {
document.documentElement.removeAttribute('data-theme');
}
// System/null: tokens.css @media (prefers-color-scheme: dark) übernimmt
})();
</script>
<!-- Lucide Icons (lokal, v0.469.0) -->
<script src="/lucide.min.js"></script>
</head>
<body>
<!-- Skip-Link: sichtbar bei Keyboard-Fokus, verknüpft mit <main id="main-content"> -->
<a href="#main-content" class="sr-only">Zum Hauptinhalt springen</a>
<!-- Offline-Banner: sichtbar wenn navigator.onLine === false -->
<div id="offline-banner" class="offline-banner" hidden aria-live="polite" role="status">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"
+118 -47
View File
@@ -327,22 +327,43 @@ function readFileAsDataUrl(file) {
});
}
function attachmentDataUrl(data, mime) {
const raw = String(data || '');
if (!raw) return '';
if (raw.startsWith('data:')) return raw;
return mime ? `data:${mime};base64,${raw}` : raw;
}
function attachmentHtml(event) {
if (!event?.attachment_data) return '';
const name = esc(event.attachment_name || t('calendar.attachmentFallback'));
const src = esc(attachmentDataUrl(event.attachment_data, event.attachment_mime));
if (isImageAttachment(event.attachment_mime)) {
return `
<div class="event-popup__attachment event-popup__attachment--image">
<img src="${event.attachment_data}" alt="${name}">
<img src="${src}" alt="${name}">
</div>`;
}
return `
<a class="event-popup__attachment event-popup__attachment--file" href="${event.attachment_data}" download="${name}">
<a class="event-popup__attachment event-popup__attachment--file" href="${src}" download="${name}">
<i data-lucide="paperclip" aria-hidden="true"></i>
<span>${name}</span>
</a>`;
}
function attachmentPreviewHtml(event) {
if (!event?.attachment_data) return '';
const name = esc(event.attachment_name || t('calendar.attachmentFallback'));
const src = esc(attachmentDataUrl(event.attachment_data, event.attachment_mime));
return isImageAttachment(event.attachment_mime)
? `<img src="${src}" alt="${name}">`
: `<a href="${src}" download="${name}">${name}</a>`;
}
function selectedAttachmentLabel(name) {
return t('documents.selectedFileLabel', { name: name || t('calendar.attachmentFallback') });
}
function bindDateInputs(root) {
root.querySelectorAll('.js-date-input').forEach((input) => {
input.addEventListener('blur', () => {
@@ -1028,12 +1049,24 @@ function showEventPopup(ev, anchor) {
popup.querySelector('.event-popup__actions').before(resetLink);
}
// Positionierung
// Positionierung: erst messen, dann im Viewport halten.
const rect = anchor.getBoundingClientRect();
const top = Math.min(rect.bottom + 8, window.innerHeight - 280);
const left = Math.min(rect.left, window.innerWidth - 340);
popup.style.top = `${Math.max(8, top)}px`;
popup.style.left = `${Math.max(8, left)}px`;
const gap = 8;
const margin = 8;
const popupRect = popup.getBoundingClientRect();
const viewportWidth = document.documentElement.clientWidth;
const viewportHeight = document.documentElement.clientHeight;
const fitsBelow = rect.bottom + gap + popupRect.height <= viewportHeight - margin;
const top = fitsBelow
? rect.bottom + gap
: Math.max(margin, rect.top - gap - popupRect.height);
const left = Math.min(
Math.max(margin, rect.left),
Math.max(margin, viewportWidth - popupRect.width - margin)
);
const maxTop = Math.max(margin, viewportHeight - popupRect.height - margin);
popup.style.top = `${Math.min(Math.max(margin, top), maxTop)}px`;
popup.style.left = `${left}px`;
popup.querySelector('#popup-edit').addEventListener('click', async () => {
popup.remove();
@@ -1257,6 +1290,7 @@ function openEventModal({ mode, event = null, date = null, reminder = null }) {
const reminderOffset = panel.querySelector('#modal-reminder-offset');
const reminderCustom = panel.querySelector('#modal-reminder-custom');
const attachmentInput = panel.querySelector('#modal-attachment');
const selectedAttachment = panel.querySelector('#modal-selected-attachment');
const attachmentPreview = panel.querySelector('#modal-attachment-preview');
const attachmentState = {
name: event?.attachment_name || null,
@@ -1264,39 +1298,55 @@ function openEventModal({ mode, event = null, date = null, reminder = null }) {
size: event?.attachment_size || null,
data: event?.attachment_data || null,
};
const syncAttachmentPreview = () => {
if (!attachmentPreview) return;
attachmentPreview.replaceChildren();
if (!attachmentState.data) {
attachmentPreview.hidden = true;
return;
}
attachmentPreview.hidden = false;
if (isImageAttachment(attachmentState.mime)) {
attachmentPreview.insertAdjacentHTML('beforeend', `<img src="${attachmentState.data}" alt="${esc(attachmentState.name || '')}">`);
} else {
attachmentPreview.insertAdjacentHTML('beforeend', `<a href="${attachmentState.data}" download="${esc(attachmentState.name || '')}">${esc(attachmentState.name || '')}</a>`);
}
const syncSelectedAttachment = () => {
if (!selectedAttachment) return;
selectedAttachment.hidden = !attachmentState.name;
selectedAttachment.textContent = attachmentState.name ? selectedAttachmentLabel(attachmentState.name) : '';
};
attachmentInput?.addEventListener('change', async () => {
const syncAttachmentSelection = () => {
if (!selectedAttachment) return;
const file = attachmentInput.files?.[0];
if (!file) return;
if (file.size > MAX_ATTACHMENT_BYTES) {
window.oikos?.showToast(t('calendar.attachmentTooLarge'), 'error');
attachmentInput.value = '';
if (file) {
selectedAttachment.hidden = false;
selectedAttachment.textContent = selectedAttachmentLabel(file.name);
if (attachmentPreview) {
attachmentPreview.replaceChildren();
attachmentPreview.hidden = true;
}
return;
}
try {
attachmentState.data = await readFileAsDataUrl(file);
attachmentState.name = file.name;
attachmentState.mime = file.type || 'application/octet-stream';
attachmentState.size = file.size;
syncAttachmentPreview();
} catch (err) {
window.oikos?.showToast(err.message, 'danger');
}
});
syncAttachmentPreview();
syncSelectedAttachment();
};
attachmentInput?.addEventListener('change', syncAttachmentSelection);
const attachmentDropzone = panel.querySelector('#modal-attachment-dropzone');
if (attachmentDropzone && attachmentInput) {
['dragenter', 'dragover'].forEach((eventName) => {
attachmentDropzone.addEventListener(eventName, (dropEvent) => {
dropEvent.preventDefault();
attachmentDropzone.classList.add('document-dropzone--active');
});
});
['dragleave', 'drop'].forEach((eventName) => {
attachmentDropzone.addEventListener(eventName, (dropEvent) => {
dropEvent.preventDefault();
attachmentDropzone.classList.remove('document-dropzone--active');
});
});
attachmentDropzone.addEventListener('drop', (dropEvent) => {
const file = dropEvent.dataTransfer?.files?.[0];
if (!file) return;
const transfer = new DataTransfer();
transfer.items.add(file);
attachmentInput.files = transfer.files;
syncAttachmentSelection();
});
}
syncSelectedAttachment();
reminderOffset?.addEventListener('change', () => {
if (reminderCustom) reminderCustom.hidden = reminderOffset.value !== 'custom';
});
@@ -1445,14 +1495,20 @@ function buildEventModalContent({ mode, event, date, reminder = null }) {
<div class="form-group">
<label class="form-label" for="modal-attachment">${t('calendar.attachmentLabel')}</label>
<input class="form-input" id="modal-attachment" type="file" accept="image/png,image/jpeg,image/webp,image/gif,application/pdf,text/plain,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
<label class="document-dropzone" id="modal-attachment-dropzone" for="modal-attachment">
<input class="sr-only" id="modal-attachment" type="file" accept="image/png,image/jpeg,image/webp,image/gif,application/pdf,text/plain,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
<span class="document-dropzone__icon">
<i data-lucide="file-up" aria-hidden="true"></i>
</span>
<span class="document-dropzone__title">${t('documents.dropzoneTitle')}</span>
<span class="document-dropzone__hint">${t('documents.dropzoneHint')}</span>
<span class="document-dropzone__file" id="modal-selected-attachment" ${isEdit && event.attachment_name ? '' : 'hidden'}>
${isEdit && event.attachment_name ? esc(selectedAttachmentLabel(event.attachment_name)) : ''}
</span>
</label>
<div class="form-help">${t('calendar.attachmentHint')}</div>
<div class="event-attachment-preview" id="modal-attachment-preview" ${isEdit && event.attachment_data ? '' : 'hidden'}>
${isEdit && event.attachment_data
? (isImageAttachment(event.attachment_mime)
? `<img src="${event.attachment_data}" alt="${esc(event.attachment_name || '')}">`
: `<a href="${event.attachment_data}" download="${esc(event.attachment_name || '')}">${esc(event.attachment_name || '')}</a>`)
: ''}
${isEdit && event.attachment_data ? attachmentPreviewHtml(event) : ''}
</div>
</div>
@@ -1524,15 +1580,30 @@ async function saveEvent(overlay, mode, eventId, existingReminder = null, attach
saveBtn.textContent = mode === 'edit' ? t('common.save') : t('common.create');
return;
}
const attachmentPayload = {
name: attachmentState?.name || null,
mime: attachmentState?.mime || null,
size: attachmentState?.size || null,
data: attachmentState?.data || null,
};
const attachmentFile = overlay.querySelector('#modal-attachment')?.files?.[0];
if (attachmentFile) {
if (attachmentFile.size > MAX_ATTACHMENT_BYTES) throw new Error(t('calendar.attachmentTooLarge'));
attachmentPayload.name = attachmentFile.name;
attachmentPayload.mime = attachmentFile.type || 'application/octet-stream';
attachmentPayload.size = attachmentFile.size;
attachmentPayload.data = await readFileAsDataUrl(attachmentFile);
}
const body = {
title, description, start_datetime, end_datetime,
all_day: allday ? 1 : 0,
location, color, icon, assigned_to: assigned_to ? parseInt(assigned_to, 10) : null,
recurrence_rule: rrule.recurrence_rule,
attachment_name: attachmentState?.name || null,
attachment_mime: attachmentState?.mime || null,
attachment_size: attachmentState?.size || null,
attachment_data: attachmentState?.data || null,
attachment_name: attachmentPayload.name,
attachment_mime: attachmentPayload.mime,
attachment_size: attachmentPayload.size,
attachment_data: attachmentPayload.data,
};
let savedEventId = eventId;
@@ -1573,7 +1644,7 @@ async function saveEvent(overlay, mode, eventId, existingReminder = null, attach
renderView();
window.oikos?.showToast(mode === 'create' ? t('calendar.createdToast') : t('calendar.savedToast'), 'success');
} catch (err) {
window.oikos?.showToast(err.data?.error ?? t('calendar.saveError'), 'error');
window.oikos?.showToast(err.data?.error ?? err.message ?? t('calendar.saveError'), 'error');
saveBtn.disabled = false;
saveBtn.textContent = mode === 'edit' ? t('common.save') : t('common.create');
}
+61
View File
@@ -445,6 +445,67 @@
word-break: break-word;
}
.document-dropzone {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-2);
min-height: 148px;
padding: var(--space-5);
border: 1.5px dashed color-mix(in srgb, var(--module-accent) 48%, var(--color-border));
border-radius: var(--radius-md);
background: color-mix(in srgb, var(--module-accent) 7%, var(--color-surface));
color: var(--color-text-secondary);
text-align: center;
cursor: pointer;
transition: border-color var(--transition-fast), background-color var(--transition-fast), transform var(--transition-fast);
}
.document-dropzone:hover,
.document-dropzone--active {
border-color: var(--module-accent);
background: color-mix(in srgb, var(--module-accent) 12%, var(--color-surface));
}
.document-dropzone--active {
transform: translateY(-1px);
}
.document-dropzone__icon {
width: 42px;
height: 42px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-md);
color: var(--module-accent);
background: color-mix(in srgb, var(--module-accent) 15%, transparent);
}
.document-dropzone__icon svg {
width: 22px;
height: 22px;
}
.document-dropzone__title {
color: var(--color-text-primary);
font-weight: var(--font-weight-semibold);
}
.document-dropzone__hint,
.document-dropzone__file {
max-width: 100%;
color: var(--color-text-tertiary);
font-size: var(--text-xs);
overflow-wrap: anywhere;
}
.document-dropzone__file {
color: var(--module-accent);
font-weight: var(--font-weight-medium);
}
/* --------------------------------------------------------
* Tagesansicht
* -------------------------------------------------------- */
+9 -5
View File
@@ -922,9 +922,13 @@
background-color: var(--color-overlay);
z-index: var(--z-modal);
display: flex;
align-items: flex-end;
align-items: center;
justify-content: center;
overflow: hidden;
padding: max(var(--space-3), env(safe-area-inset-top))
max(var(--space-3), env(safe-area-inset-right))
max(var(--space-3), env(safe-area-inset-bottom))
max(var(--space-3), env(safe-area-inset-left));
animation: modal-overlay-in 0.2s ease forwards;
/* iOS Safari: click-Events auf non-interactive divs erfordern cursor:pointer */
cursor: pointer;
@@ -932,7 +936,6 @@
@media (min-width: 768px) {
.modal-overlay {
align-items: center;
padding: var(--space-6);
}
}
@@ -940,11 +943,11 @@
.modal-panel {
background-color: var(--color-surface);
width: 100%;
max-height: 90dvh;
max-height: calc(100dvh - (2 * var(--space-3)) - env(safe-area-inset-top) - env(safe-area-inset-bottom));
overflow: hidden;
display: flex;
flex-direction: column;
border-radius: var(--radius-lg) var(--radius-lg) 0 0;
border-radius: var(--radius-lg);
border: 1px solid var(--color-border-subtle);
box-shadow: var(--shadow-lg);
animation: modal-slide-up 0.25s var(--ease-out) forwards;
@@ -955,6 +958,7 @@
@media (min-width: 768px) {
.modal-panel {
max-width: 520px;
max-height: calc(100dvh - (2 * var(--space-6)));
border-radius: var(--radius-lg);
animation: modal-scale-in 0.2s var(--ease-out) forwards;
}
@@ -1106,7 +1110,7 @@
@keyframes sheet-out {
from { transform: translateY(0); }
to { transform: translateY(100%); }
to { transform: translateY(16px); opacity: 0; }
}
@media (prefers-reduced-motion: reduce) {
+10
View File
@@ -0,0 +1,10 @@
(function() {
var stored = localStorage.getItem('oikos-theme');
if (stored === 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
} else if (stored === 'light') {
document.documentElement.setAttribute('data-theme', 'light');
} else {
document.documentElement.removeAttribute('data-theme');
}
})();
+1 -7
View File
@@ -55,13 +55,7 @@ app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: [
"'self'",
// Inline-Script: Theme-Detection (Flash-Prevention)
"'sha256-vqqBNo1oitnzIntwkG83UaYqkUAnV/oZ/RkvcA41Y6A='",
// Alpine.js CDN (optional, falls verwendet)
'https://cdn.jsdelivr.net',
],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:'],
connectSrc: ["'self'"],
+98
View File
@@ -498,6 +498,103 @@ function buildPaths() {
put: op({ summary: 'Update budget entry', tag: 'Budget', params: [idParam()], stateChanging: true, requestBody: jsonBody(null) }),
delete: op({ summary: 'Delete budget entry', tag: 'Budget', params: [idParam()], stateChanging: true }),
},
'/api/v1/documents/meta/options': {
get: op({
summary: 'Get family document options',
tag: 'Documents',
description: 'Returns supported categories, visibility modes, statuses, storage providers, file size limit and MIME types.',
}),
},
'/api/v1/documents': {
get: op({
summary: 'List family documents',
tag: 'Documents',
params: [
{
name: 'status',
in: 'query',
required: false,
schema: { type: 'string', enum: ['active', 'archived'], default: 'active' },
},
{
name: 'category',
in: 'query',
required: false,
schema: {
type: 'string',
enum: ['medical', 'school', 'identity', 'insurance', 'finance', 'home', 'vehicle', 'legal', 'travel', 'pets', 'warranty', 'taxes', 'work', 'other'],
},
},
],
}),
post: op({
summary: 'Upload family document',
tag: 'Documents',
stateChanging: true,
description: 'Stores a local document with family, restricted, or private visibility. File content is sent as a base64 data URL in `content_data`.',
requestBody: jsonBody(null),
responses: {
201: { description: 'Document created' },
400: { $ref: '#/components/responses/BadRequest' },
401: { $ref: '#/components/responses/Unauthorized' },
500: { $ref: '#/components/responses/InternalServerError' },
},
}),
},
'/api/v1/documents/{id}': {
put: op({
summary: 'Update family document metadata',
tag: 'Documents',
params: [idParam()],
stateChanging: true,
description: 'Updates name, description, category, status, visibility and allowed member IDs. Only the owner or an admin can update a document.',
requestBody: jsonBody(null),
}),
delete: op({
summary: 'Delete family document',
tag: 'Documents',
params: [idParam()],
stateChanging: true,
description: 'Deletes a document. Only the owner or an admin can delete it.',
responses: {
204: { description: 'Document deleted' },
401: { $ref: '#/components/responses/Unauthorized' },
403: { $ref: '#/components/responses/Forbidden' },
404: { description: 'Document not found' },
500: { $ref: '#/components/responses/InternalServerError' },
},
}),
},
'/api/v1/documents/{id}/archive': {
patch: op({
summary: 'Archive or restore family document',
tag: 'Documents',
params: [idParam()],
stateChanging: true,
description: 'Archives the document by default. Send `{ "archived": false }` to restore it to active status.',
requestBody: jsonBody(null),
}),
},
'/api/v1/documents/{id}/download': {
get: op({
summary: 'Download family document file',
tag: 'Documents',
params: [idParam()],
responses: {
200: {
description: 'Document file bytes',
content: {
'application/octet-stream': {
schema: { type: 'string', format: 'binary' },
},
},
},
401: { $ref: '#/components/responses/Unauthorized' },
404: { description: 'Document not found' },
500: { $ref: '#/components/responses/InternalServerError' },
},
}),
},
'/api/v1/weather': { get: op({ summary: 'Get weather data', tag: 'Weather' }) },
'/api/v1/weather/icon/{code}': {
get: op({ summary: 'Get weather icon asset', tag: 'Weather', params: [{ name: 'code', in: 'path', required: true, schema: { type: 'string' } }] }),
@@ -549,6 +646,7 @@ function buildOpenApiSpec(req, appVersion) {
{ name: 'Contacts' },
{ name: 'Birthdays' },
{ name: 'Budget' },
{ name: 'Documents' },
{ name: 'Backup' },
{ name: 'Weather' },
{ name: 'Preferences' },
+21 -5
View File
@@ -86,6 +86,21 @@ function parseAttachment(dataUrl) {
return { name: null, mime, size: buffer.length, data: base64 };
}
function attachmentDataUrl(event) {
if (!event?.attachment_data) return event?.attachment_data ?? null;
if (String(event.attachment_data).startsWith('data:')) return event.attachment_data;
if (!event.attachment_mime) return event.attachment_data;
return `data:${event.attachment_mime};base64,${event.attachment_data}`;
}
function serializeEvent(event) {
if (!event) return event;
return {
...event,
attachment_data: attachmentDataUrl(event),
};
}
// --------------------------------------------------------
// RRULE-Expansion: alle Vorkommen eines wiederkehrenden Events
// innerhalb [from, to] generieren (inklusive beider Grenzen).
@@ -225,7 +240,7 @@ router.get('/', (req, res) => {
sql += ' ORDER BY e.start_datetime ASC, e.all_day DESC';
const rawEvents = db.get().prepare(sql).all(...params);
const events = expandRecurringEvents(rawEvents, from, to);
const events = expandRecurringEvents(rawEvents, from, to).map(serializeEvent);
res.json({ data: events, from, to });
} catch (err) {
log.error('', err);
@@ -271,7 +286,8 @@ router.get('/upcoming', (req, res) => {
const expanded = expandRecurringEvents(rawEvents, nowDate, future)
.filter((e) => e.start_datetime >= new Date().toISOString())
.slice(0, limit);
.slice(0, limit)
.map(serializeEvent);
res.json({ data: expanded });
} catch (err) {
@@ -571,7 +587,7 @@ router.get('/:id', (req, res) => {
`).get(id);
if (!event) return res.status(404).json({ error: 'Termin nicht gefunden', code: 404 });
res.json({ data: event });
res.json({ data: serializeEvent(event) });
} catch (err) {
log.error('', err);
res.status(500).json({ error: 'Interner Fehler', code: 500 });
@@ -649,7 +665,7 @@ router.post('/', (req, res) => {
WHERE e.id = ?
`).get(result.lastInsertRowid);
res.status(201).json({ data: event });
res.status(201).json({ data: serializeEvent(event) });
} catch (err) {
log.error('', err);
res.status(500).json({ error: 'Interner Fehler', code: 500 });
@@ -743,7 +759,7 @@ router.put('/:id', (req, res) => {
WHERE e.id = ?
`).get(id);
res.json({ data: updated });
res.json({ data: serializeEvent(updated) });
} catch (err) {
log.error('', err);
res.status(500).json({ error: 'Interner Fehler', code: 500 });