all repos — cameraman @ 59a0805822a71f9ab7fcd9630c3bc6cad3a4d575

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">{{ .Name }}</td>
133            <td data-field="description">{{ .Description }}</td>
134            <td data-field="date">{{ padZero .Day }}/{{ padZero .Month }}</td>
135            <td data-field="notify"><input type="checkbox" {{if .Notify}}checked{{end}} disabled></td>
136            <td data-field="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, a.querySelector('td[data-field="date"]').innerText);
186                const dateB = parseDateString(now, b.querySelector('td[data-field="date"]').innerText);
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">${name}</td>
234                <td data-field="description">${description}</td>
235                <td data-field="date">${padNumber(day)}/${padNumber(month)}</td>
236                <td data-field="notify"><input type="checkbox" ${notify ? 'checked' : ''} disabled></td>
237                <td data-field="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            return `
247                <td><input class="big-input" type="text" value="${name || ''}" id="name-${id}" onkeydown="handleInputKeyDown(event, ${id})"></td>
248                <td><input class="big-input" type="text" value="${description || ''}" id="description-${id}" onkeydown="handleInputKeyDown(event, ${id})"></td>
249                <td class="date-inputs">
250                    <input type="number" value="${day || '01'}" id="day-${id}" class="small-input" min="1" max="31" onchange="this.value = padMax(this.value, 31);" onclick="this.select()" onkeydown="handleInputKeyDown(event, ${id})"> /
251                    <input type="number" value="${month || '01'}" id="month-${id}" class="small-input" min="1" max="12" onchange="this.value = padMax(this.value, 12);" onclick="this.select()" onkeydown="handleInputKeyDown(event, ${id})">
252                </td>
253                <td><input type="checkbox" id="notify-${id}" ${notify ? 'checked' : ''}></td>
254                <td><input type="checkbox" id="notified-${id}" ${notified ? 'checked' : 'disabled'}></td>
255                <td class="actions">
256                    ${isNew ? '' : `
257                    <i class="fas fa-save" title="Save" onclick="saveOccurrence(${id})"></i>
258                    <i class="fas fa-times" title="Cancel" onclick="cancelEdit(${id}, '${name}', '${description}', ${day}, ${month}, ${notify})"></i>
259                    `}
260                </td>
261            `;
262        }
263
264        function editOccurrence(id) {
265            const row = document.getElementById(`occurrence-${id}`);
266            const cells = row.getElementsByTagName('td');
267
268            const name = cells[0].innerText;
269            const description = cells[1].innerText;
270            const [day, month] = cells[2].innerText.split('/');
271            const notify = cells[3].getElementsByTagName('input')[0].checked;
272            const notified = cells[4].getElementsByTagName('input')[0].checked;
273
274            row.innerHTML = createInputFields(id, name, description, day, month, notify, notified, false);
275            row.classList.add('editing');
276        }
277
278        function cancelEdit(id, name, description, day, month, notify) {
279            const row = document.getElementById(`occurrence-${id}`);
280            row.innerHTML = createRow(id, name, description, day, month, notify);
281        }
282
283        function saveOccurrence(id) {
284            const name = document.getElementById(`name-${id}`).value;
285            const description = document.getElementById(`description-${id}`).value;
286            const day = parseInt(document.getElementById(`day-${id}`).value);
287            const month = parseInt(document.getElementById(`month-${id}`).value);
288            const notify = document.getElementById(`notify-${id}`).checked;
289            const notified = document.getElementById(`notified-${id}`).checked;
290
291            const isNew = id === '0';
292            const updatedData = {
293                id: isNew ? undefined : id,
294                name: name,
295                description: description,
296                month: month,
297                day: day,
298                notify: notify,
299                notified: notified
300            };
301
302            fetch('/occurrences', {
303                method: 'POST',
304                headers: {
305                    'Content-Type': 'application/json'
306                },
307                body: JSON.stringify(updatedData)
308            })
309                .then(response => {
310                    if (!response.ok) {
311                        console.error('Error:', response.status);
312                        alert('Controlla che i campi siano validi.');
313                        return;
314                    }
315                    if (isNew) {
316                        cancelNewOccurrence();
317                        mainTable.insertRow(-1).id = `occurrence-${id}`
318                    }
319                    updateRow(`occurrence-${id}`, response);
320                })
321                .catch(error => {
322                    console.error('Error:', error);
323                    alert(dataError);
324                });
325        }
326
327        function addNewOccurrenceRow() {
328            const newRow = mainTable.insertRow(-1);
329            newRow.id = 'new-occurrence';
330            newRow.innerHTML = createInputFields('0', '', '', '', '', true, false, true);
331
332            hideAddButton();
333            // updateRowDisplay();
334        }
335        function hideAddButton() {
336            addButton.classList.add(hiddenClass);
337            saveButton.classList.remove(hiddenClass);
338            cancelButton.classList.remove(hiddenClass);
339        }
340
341        function showAddButton() {
342            addButton.classList.remove(hiddenClass);
343            saveButton.classList.add(hiddenClass);
344            cancelButton.classList.add(hiddenClass);
345        }
346
347        function updateRow(rowElementId, response) {
348            const newRow = document.getElementById(rowElementId);
349            response.json().then((res) => {
350                newRow.id = `occurrence-${res.id}`;
351                newRow.innerHTML = createRow(res.id, res.name, res.description, res.day, res.month, res.notify, res.notified);
352                newRow.classList.remove('editing');
353                updateRowDisplay()
354            });
355        }
356
357        function cancelNewOccurrence() {
358            const newRow = document.getElementById('new-occurrence');
359            newRow.parentNode.removeChild(newRow);
360            showAddButton();
361            updateRowDisplay();
362        }
363
364        function parseDateString(now, dateString) {
365            const [day, month] = dateString.split('/').map((x) => Number(x));
366            return new Date(now.getFullYear(), month - 1, day, 23, 59, 59);
367        }
368
369        function findNextOccurrence() {
370            if (currentNext !== null) {
371                currentNext.classList.remove('next');
372            }
373            const now = new Date();
374            const occurrenceRows = Array.from(mainTable.querySelectorAll("tr[id]:not(#occurrence-none):not(#new-occurrence)"));
375            const occurrences = occurrenceRows.map((row) => {
376                const tds = Array.from(row.getElementsByTagName('td'));
377
378                const id = row.id.split('-')[1];
379                const dateString = tds.find((td) => td.getAttribute('data-field') === 'date').innerText;
380                const date = parseDateString(now, dateString);
381
382                return { id, date }
383            });
384
385            const deltas = occurrences.map((x) => ({ ...x, distance: x.date - now })).filter((x) => x.distance > 0);
386            if (deltas.length == 0) return;
387
388            const distances = deltas.map((x) => x.distance);
389            const minDistance = Math.min(...distances);
390            const minDelta = deltas.find((x) => x.distance == minDistance);
391
392            currentNext = occurrenceRows.find((row) => row.id === `occurrence-${minDelta.id}`);
393            currentNext.classList.add('next');
394        }
395
396        updateRowDisplay();
397    </script>
398
399</body>
400
401</html>