|
| 1 | +/** |
| 2 | + * Attaches `input` handlers to markdown rendered tasklist checkboxes in comments. |
| 3 | + * |
| 4 | + * When a checkbox value changes, the corresponding [ ] or [x] in the markdown string |
| 5 | + * is set accordingly and sent to the server. On success it updates the raw-content on |
| 6 | + * error it resets the checkbox to its original value. |
| 7 | + */ |
| 8 | + |
| 9 | +const preventListener = (e) => e.preventDefault(); |
| 10 | + |
| 11 | +export function initMarkupTasklist() { |
| 12 | + for (const el of document.querySelectorAll(`.markup[data-can-edit=true]`) || []) { |
| 13 | + const container = el.parentNode; |
| 14 | + const checkboxes = el.querySelectorAll(`.task-list-item input[type=checkbox]`); |
| 15 | + |
| 16 | + for (const checkbox of checkboxes) { |
| 17 | + if (checkbox.dataset.editable) return; |
| 18 | + checkbox.dataset.editable = 'true'; |
| 19 | + checkbox.addEventListener('input', async () => { |
| 20 | + const checkboxCharacter = checkbox.checked ? 'x' : ' '; |
| 21 | + const position = parseInt(checkbox.dataset.sourcePosition) + 1; |
| 22 | + |
| 23 | + const rawContent = container.querySelector('.raw-content'); |
| 24 | + const oldContent = rawContent.textContent; |
| 25 | + const newContent = oldContent.substring(0, position) + checkboxCharacter + oldContent.substring(position + 1); |
| 26 | + if (newContent === oldContent) return; |
| 27 | + |
| 28 | + // Prevent further inputs until the request is done. This does not use the |
| 29 | + // `disabled` attribute because it causes the border to flash on click. |
| 30 | + for (const checkbox of checkboxes) { |
| 31 | + checkbox.addEventListener('click', preventListener); |
| 32 | + } |
| 33 | + |
| 34 | + try { |
| 35 | + const editContentZone = container.querySelector('.edit-content-zone'); |
| 36 | + const {updateUrl, context} = editContentZone.dataset; |
| 37 | + |
| 38 | + await $.post(updateUrl, { |
| 39 | + _csrf: window.config.csrf, |
| 40 | + content: newContent, |
| 41 | + context, |
| 42 | + }); |
| 43 | + |
| 44 | + rawContent.textContent = newContent; |
| 45 | + } catch (err) { |
| 46 | + checkbox.checked = !checkbox.checked; |
| 47 | + console.error(err); |
| 48 | + } |
| 49 | + |
| 50 | + // Enable input on checkboxes again |
| 51 | + for (const checkbox of checkboxes) { |
| 52 | + checkbox.removeEventListener('click', preventListener); |
| 53 | + } |
| 54 | + }); |
| 55 | + } |
| 56 | + |
| 57 | + // Enable the checkboxes as they are initially disabled by the markdown renderer |
| 58 | + for (const checkbox of checkboxes) { |
| 59 | + checkbox.disabled = false; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments