all repos — cameraman @ fa6b49105426b79e9dfc57e5185bde30f5f92960

templates/index.html (view raw)

  1<!DOCTYPE html>
  2<html>
  3
  4<head>
  5    <title>Ricorrenze</title>
  6    <link rel="icon"
  7        href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%2210 0 100 100%22><text y=%22.90em%22 font-size=%2290%22>📅</text></svg>">
  8    </link>
  9    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
 10    <style>
 11        :root {
 12            color-scheme: light dark;
 13            --text: #000;
 14            --bg: #fff;
 15            --green: #4CAF50;
 16            --hover-green: #45a049;
 17            --red: #af4c4c;
 18            --hover-red: #a14545;
 19        }
 20
 21        @media (prefers-color-scheme: dark) {
 22            :root {
 23                color-scheme: dark light;
 24                --text: #fff;
 25                --bg: #121212;
 26                --green: #265929;
 27                --hover-green: #214d23;
 28                --red: #592626;
 29                --hover-red: #4d2121;
 30            }
 31        }
 32
 33        body {
 34            font-family: Arial, sans-serif;
 35            background-color: var(--bg);
 36            color: var(--text);
 37        }
 38
 39        table {
 40            width: 100%;
 41            border-collapse: collapse;
 42        }
 43
 44        table,
 45        th,
 46        td {
 47            border: 1px solid var(--text);
 48        }
 49
 50        th,
 51        td {
 52            padding: 10px;
 53            text-align: left;
 54        }
 55
 56        th {
 57            background-color: var(--bg);
 58        }
 59
 60        .next {
 61            background-color: var(--red);
 62            color: white;
 63        }
 64
 65        .date-inputs {
 66            display: flex;
 67            align-items: center;
 68            border: none;
 69            gap: 2px;
 70        }
 71
 72        .small-input {
 73            width: 32px;
 74        }
 75
 76        .big-input {
 77            width: 100%;
 78        }
 79
 80        .actions i {
 81            cursor: pointer;
 82            padding-right: 5px;
 83        }
 84
 85        .cute-button {
 86            margin-top: 20px;
 87            background-color: var(--green);
 88            border: none;
 89            color: white;
 90            padding: 10px 20px;
 91            text-align: center;
 92            text-decoration: none;
 93            display: inline-block;
 94            font-size: 16px;
 95            margin: 4px 2px;
 96            transition-duration: 0.4s;
 97            cursor: pointer;
 98            border-radius: 12px;
 99        }
100
101        .cute-button:hover {
102            background-color: var(--hover-green);
103        }
104
105        .cute-button-red {
106            background-color: var(--red);
107        }
108
109        .cute-button-red:hover {
110            background-color: var(--hover-red);
111        }
112
113        .hidden {
114            display: none;
115        }
116    </style>
117</head>
118
119<body>
120    <h1>Ricorrenze</h1>
121    <table id="main-table">
122        <tr>
123            <th data-field="name">Nome</th>
124            <th data-field="description">Descrizione</th>
125            <th data-field="date">Data (gg/mm)</th>
126            <th data-field="notify">Notifica</th>
127            <th data-field="notified">Inviata</th>
128            <th data-field="actions">Azioni</th>
129        </tr>
130        {{ range .Occurrences }}
131        <tr id="occurrence-{{ .ID }}">
132            <td data-field="name" data-value="{{ .Name }}">{{ .Name }}</td>
133            <td data-field="description" data-value="{{ .Description }}">{{ .Description }}</td>
134            <td data-field="date" data-value="{{ padZero .Day }}/{{ padZero .Month }}">{{ padZero .Day }}/{{ padZero .Month }}</td>
135            <td data-field="notify" data-value="{{ .Notify }}"><input type="checkbox" {{if .Notify}}checked{{end}} disabled></td>
136            <td data-field="notified" data-value="{{ .Notified }}"><input type="checkbox" {{if .Notified}}checked{{end}} disabled></td>
137            <td data-field="actions" class="actions">
138                <i class="fas fa-edit" title="Modifica" onclick="editOccurrence('{{ .ID }}')"></i>
139                <i class="fas fa-trash-alt" title="Elimina" onclick="deleteOccurrence('{{ .ID }}')"></i>
140            </td>
141        </tr>
142        {{ end }}
143        <tr id="occurrence-none" class="hidden">
144            <td colspan="6">Nessuna ricorrenza.</td>
145        </tr>
146    </table>
147    <div style="margin-top: 10px; text-align: center;">
148        <button id="add-row-button" class="cute-button" onclick="addNewOccurrenceRow()">
149            <i class="fas fa-plus"></i> Aggiungi</button>
150        <button id="save-row-button" class="cute-button hidden" onclick="saveOccurrence('0')">
151            <i class="fas fa-save"></i> Salva
152        </button>
153        <button id="cancel-row-button" class="cute-button cute-button-red hidden" onclick="cancelNewOccurrence()">
154            <i class="fas fa-times"></i> Annulla
155        </button>
156    </div>
157
158    <script>
159        const hiddenClass = 'hidden';
160        const addButton = document.getElementById('add-row-button');
161        const saveButton = document.getElementById('save-row-button');
162        const cancelButton = document.getElementById('cancel-row-button');
163        const mainTable = document.getElementById('main-table');
164        const noneRow = document.getElementById('occurrence-none');
165
166        const dataError = 'Controlla che i dati (e le date) siano corretti.';
167
168        let currentNext = null;
169
170        function updateRowDisplay() {
171            const tbody = mainTable.querySelector('tbody');
172            const rows = Array.from(tbody.querySelectorAll('tr[id]:not(#occurrence-none):not(#new-occurrence)'));
173
174            if (rows.length === 0) {
175                noneRow.classList.remove(hiddenClass);
176                return;
177            }
178            noneRow.classList.add(hiddenClass);
179
180            const valueRows = rows.filter((row) => !row.classList.contains('editing'));
181
182            // Sort rows by date
183            now = new Date();
184            valueRows.sort((a, b) => {
185                const dateA = parseDateString(now, getValueFromRow(a, 'date'));
186                const dateB = parseDateString(now, getValueFromRow(b, 'date'));
187                return dateA - dateB;
188            });
189
190            // Re-append sorted rows to tbody
191            valueRows.forEach(row => tbody.appendChild(row));
192
193            findNextOccurrence();
194        }
195
196        function deleteOccurrence(id) {
197            if (confirm('Sei sicuro di voler eliminare questa ricorrenza?')) {
198                fetch(`/occurrences/${id}`, {
199                    method: 'DELETE'
200                })
201                    .then(response => {
202                        if (!response.ok) {
203                            console.error('Error:', response.status);
204                            alert('Eliminazione fallita.');
205                            return;
206                        }
207                        const deletedRow = document.getElementById(`occurrence-${id}`);
208                        deletedRow.parentElement.removeChild(deletedRow);
209                        updateRowDisplay();
210                    })
211                    .catch(error => {
212                        console.error('Error:', error);
213                        alert(dataError);
214                    });
215            }
216        }
217
218        function padNumber(input, n = 2) {
219            return input.toString().padStart(n, '0');
220        }
221
222        function padMax(input, max = 31) {
223            return padNumber(Math.max(1, Math.min(input, max)))
224        }
225
226        function handleInputKeyDown(event, id) {
227            if (event.key !== 'Enter') return;
228            saveOccurrence(id);
229        }
230
231        function createRow(id, name, description, day, month, notify, notified) {
232            return `
233                <td data-field="name" data-value="${name}">${name}</td>
234                <td data-field="description" data-value="${description}">${description}</td>
235                <td data-field="date" data-value="${padNumber(day)}/${padNumber(month)}">${padNumber(day)}/${padNumber(month)}</td>
236                <td data-field="notify" data-value="${notify}"><input type="checkbox" ${notify ? 'checked' : ''} disabled></td>
237                <td data-field="notified" data-value="${notified}"><input type="checkbox" ${notified ? 'checked' : ''} disabled></td>
238                <td data-field="actions" class="actions">
239                    <i class="fas fa-edit" title="Edit" onclick="editOccurrence(${id})"></i>
240                    <i class="fas fa-trash-alt" title="Delete" onclick="deleteOccurrence(${id})"></i>
241                </td>
242            `;
243        }
244
245        function createInputFields(id, name, description, day, month, notify, notified, isNew) {
246            const myName = name || '';
247            const myDescription = description || '';
248            const myDay = day || '01';
249            const myMonth = month || '01';
250            return `
251                <td data-field="name" data-value="${myName}"><input class="big-input" type="text" value="${myName}" id="name-${id}" onkeydown="handleInputKeyDown(event, ${id})"></td>
252                <td data-field="description" data-value="${myDescription}"><input class="big-input" type="text" value="${myDescription}" id="description-${id}" onkeydown="handleInputKeyDown(event, ${id})"></td>
253                <td data-field="date" data-value="${myDay}/${myMonth}" class="date-inputs">
254                    <input type="number" value="${myDay}" id="day-${id}" class="small-input" min="1" max="31" onchange="this.value = padMax(this.value, this.max);" onclick="this.select()" onkeydown="handleInputKeyDown(event, ${id})"> /
255                    <input type="number" value="${myMonth}" id="month-${id}" class="small-input" min="1" max="12" onchange="this.value = padMax(this.value, this.max);" onclick="this.select()" onkeydown="handleInputKeyDown(event, ${id})">
256                </td>
257                <td data-field="notify" data-value="${notify}"><input type="checkbox" id="notify-${id}" ${notify ? 'checked' : ''}></td>
258                <td data-field="notified" data-value="${notified}"><input type="checkbox" id="notified-${id}" ${notified ? 'checked' : 'disabled'}></td>
259                <td class="actions">
260                    ${isNew ? '' : `
261                    <i class="fas fa-save" title="Save" onclick="saveOccurrence(${id})"></i>
262                    <i class="fas fa-times" title="Cancel" onclick="cancelEdit(${id}, '${name}', '${description}', ${day}, ${month}, ${notify})"></i>
263                    `}
264                </td>
265            `;
266        }
267
268        function editOccurrence(id) {
269            const row = document.getElementById(`occurrence-${id}`);
270            const cells = row.getElementsByTagName('td');
271
272            const name = getValueFromRow(row, 'name');
273            const description = getValueFromRow(row, 'description');
274            const [day, month] = getValueFromRow(row, 'date').split('/');
275            const notify = cells[3].getElementsByTagName('input')[0].checked;
276            const notified = cells[4].getElementsByTagName('input')[0].checked;
277
278            row.innerHTML = createInputFields(id, name, description, day, month, notify, notified, false);
279            row.classList.add('editing');
280        }
281
282        function cancelEdit(id, name, description, day, month, notify) {
283            const row = document.getElementById(`occurrence-${id}`);
284            row.innerHTML = createRow(id, name, description, day, month, notify);
285        }
286
287        function saveOccurrence(id) {
288            const name = document.getElementById(`name-${id}`).value;
289            const description = document.getElementById(`description-${id}`).value;
290            const day = parseInt(document.getElementById(`day-${id}`).value);
291            const month = parseInt(document.getElementById(`month-${id}`).value);
292            const notify = document.getElementById(`notify-${id}`).checked;
293            const notified = document.getElementById(`notified-${id}`).checked;
294
295            const isNew = id === '0';
296            const updatedData = {
297                id: isNew ? undefined : id,
298                name: name,
299                description: description,
300                month: month,
301                day: day,
302                notify: notify,
303                notified: notified
304            };
305
306            fetch('/occurrences', {
307                method: 'POST',
308                headers: {
309                    'Content-Type': 'application/json'
310                },
311                body: JSON.stringify(updatedData)
312            })
313                .then(response => {
314                    if (!response.ok) {
315                        console.error('Error:', response.status);
316                        alert('Controlla che i campi siano validi.');
317                        return;
318                    }
319                    if (isNew) {
320                        cancelNewOccurrence();
321                        mainTable.insertRow(-1).id = `occurrence-${id}`
322                    }
323                    updateRow(`occurrence-${id}`, response);
324                })
325                .catch(error => {
326                    console.error('Error:', error);
327                    alert(dataError);
328                });
329        }
330
331        function addNewOccurrenceRow() {
332            const newRow = mainTable.insertRow(-1);
333            newRow.id = 'new-occurrence';
334            newRow.innerHTML = createInputFields('0', '', '', '', '', true, false, true);
335
336            hideAddButton();
337            // updateRowDisplay();
338        }
339        function hideAddButton() {
340            addButton.classList.add(hiddenClass);
341            saveButton.classList.remove(hiddenClass);
342            cancelButton.classList.remove(hiddenClass);
343        }
344
345        function showAddButton() {
346            addButton.classList.remove(hiddenClass);
347            saveButton.classList.add(hiddenClass);
348            cancelButton.classList.add(hiddenClass);
349        }
350
351        function updateRow(rowElementId, response) {
352            const newRow = document.getElementById(rowElementId);
353            response.json().then((res) => {
354                newRow.id = `occurrence-${res.id}`;
355                newRow.innerHTML = createRow(res.id, res.name, res.description, res.day, res.month, res.notify, res.notified);
356                newRow.classList.remove('editing');
357                updateRowDisplay()
358            });
359        }
360
361        function cancelNewOccurrence() {
362            const newRow = document.getElementById('new-occurrence');
363            newRow.parentNode.removeChild(newRow);
364            showAddButton();
365            updateRowDisplay();
366        }
367
368        function getValueFromRow(row, field) {
369            return row.querySelector(`td[data-field="${field}"]`).getAttribute('data-value');
370        }
371
372        function parseDateString(now, dateString) {
373            const [day, month] = dateString.split('/').map((x) => Number(x));
374            return new Date(now.getFullYear(), month - 1, day, 23, 59, 59);
375        }
376
377        function findNextOccurrence() {
378            if (currentNext !== null) {
379                currentNext.classList.remove('next');
380            }
381            const now = new Date();
382            const occurrenceRows = Array.from(mainTable.querySelectorAll("tr[id]:not(#occurrence-none):not(#new-occurrence)"));
383            const occurrences = occurrenceRows.map((row) => {
384                const id = row.id.split('-')[1];
385                const dateString = getValueFromRow(row, 'date');
386                const date = parseDateString(now, dateString);
387
388                return { id, date };
389            });
390
391            const deltas = occurrences.map((x) => ({ ...x, distance: x.date - now })).filter((x) => x.distance > 0);
392            if (deltas.length == 0) return;
393
394            const distances = deltas.map((x) => x.distance);
395            const minDistance = Math.min(...distances);
396            const minDelta = deltas.find((x) => x.distance == minDistance);
397
398            currentNext = occurrenceRows.find((row) => row.id === `occurrence-${minDelta.id}`);
399            currentNext.classList.add('next');
400        }
401
402        updateRowDisplay();
403    </script>
404
405</body>
406
407</html>