/** * Toggle visibility groups field based on visibility selection */ function toggleVisibilityGroupsEdit() { const visibility = document.getElementById('visibilitySelect')?.value; const groupsField = document.getElementById('visibilityGroupsField'); if (groupsField) { groupsField.classList.toggle('is-hidden', visibility !== 'internal'); } } /** * Get selected visibility groups */ function getSelectedVisibilityGroups() { const checkboxes = document.querySelectorAll('.visibility-group-checkbox:checked'); return Array.from(checkboxes).map(cb => cb.value); } function saveTicket() { const editables = document.querySelectorAll('.editable'); const data = {}; const ticketId = getTicketIdFromUrl(); if (!ticketId) { return; } editables.forEach(field => { if (field.dataset.field) { // For contenteditable divs, use textContent/innerText; for inputs/textareas, use value if (field.hasAttribute('contenteditable')) { data[field.dataset.field] = field.textContent.trim(); } else { data[field.dataset.field] = field.value; } } }); // Get visibility settings const visibilitySelect = document.getElementById('visibilitySelect'); if (visibilitySelect) { data.visibility = visibilitySelect.value; if (data.visibility === 'internal') { data.visibility_groups = getSelectedVisibilityGroups(); } } // Include optimistic lock timestamp so the server can detect concurrent edits if (window.ticketData && window.ticketData.updated_at) { data.expected_updated_at = window.ticketData.updated_at; } // Use the correct API path lt.api.post('/api/update_ticket.php', { ticket_id: ticketId, ...data }) .then(resp => { if (resp.success) { const statusDisplay = document.getElementById('statusDisplay'); if (statusDisplay) { statusDisplay.className = `status-${resp.status}`; statusDisplay.textContent = resp.status; } // Keep local updated_at in sync so the next save uses the right lock key if (resp.updated_at && window.ticketData) { window.ticketData.updated_at = resp.updated_at; } lt.toast.success('Ticket updated successfully'); } else if (resp.conflict) { lt.toast.error('This ticket was modified by someone else while you were editing. Reload to see the latest version.', 8000); } else { lt.toast.error('Error saving ticket: ' + (resp.error || 'Unknown error')); } }) .catch(error => { lt.toast.error('Error saving ticket: ' + error.message); }); } // ── Description read/edit helpers ──────────────────────────────────────────── // Read mode: styled lt-markdown div (full contrast, even on OLED). // Edit mode: raw textarea (enabled for editing). function renderDescriptionView() { var viewDiv = document.getElementById('ticketDescriptionView'); var textarea = document.querySelector('textarea[data-field="description"]'); if (!viewDiv || !textarea) return; var raw = textarea.value || ''; if (!raw.trim()) { viewDiv.innerHTML = '
No description provided.
'; } else { // Descriptions are markdown, rendered like comments (#114). // parseMarkdown() escapes HTML first and allowlists link protocols. viewDiv.innerHTML = parseMarkdown(raw); } } function showDescriptionView() { var v = document.getElementById('ticketDescriptionView'); var t = document.querySelector('textarea[data-field="description"]'); if (v) v.style.display = ''; if (t) t.style.display = 'none'; } function showDescriptionEdit() { var v = document.getElementById('ticketDescriptionView'); var t = document.querySelector('textarea[data-field="description"]'); if (v) v.style.display = 'none'; if (t) t.style.display = ''; } function toggleEditMode() { const editButton = document.getElementById('editButton'); const titleField = document.querySelector('.title-input'); const descriptionField = document.querySelector('textarea[data-field="description"]'); const metadataFields = document.querySelectorAll('.editable-metadata'); const isEditing = editButton.classList.contains('active'); if (!isEditing) { editButton.textContent = 'Save Changes'; editButton.classList.add('active'); // Enable title (contenteditable div) if (titleField) { titleField.setAttribute('contenteditable', 'true'); titleField.focus(); } // Enable description (swap to textarea) if (descriptionField) { showDescriptionEdit(); descriptionField.disabled = false; descriptionField.style.height = 'auto'; descriptionField.style.height = descriptionField.scrollHeight + 'px'; } // Enable metadata fields (priority, category, type) — remove display-only class metadataFields.forEach(field => { field.classList.remove('lt-display-field'); }); // Show edit-mode selects for category/type, hide their read-mode tags document.querySelectorAll('.read-mode-tag').forEach(el => { el.style.display = 'none'; }); document.querySelectorAll('.edit-mode-field').forEach(el => { el.style.display = ''; }); } else { saveTicket(); editButton.textContent = 'Edit Ticket'; editButton.classList.remove('active'); // Disable title if (titleField) { titleField.setAttribute('contenteditable', 'false'); } // Re-render description view div with latest content if (descriptionField) { descriptionField.disabled = true; renderDescriptionView(); showDescriptionView(); } // Return metadata fields to display-only using .lt-display-field (not disabled) metadataFields.forEach(field => { field.classList.add('lt-display-field'); }); // Hide edit-mode selects, show and update read-mode tags document.querySelectorAll('.edit-mode-field').forEach(el => { el.style.display = 'none'; }); var catSel = document.getElementById('categorySelect'); var typSel = document.getElementById('typeSelect'); var catTag = document.getElementById('categoryTag'); var typTag = document.getElementById('typeTag'); if (catTag) { if (catSel) catTag.textContent = catSel.options[catSel.selectedIndex].text; catTag.style.display = ''; } if (typTag) { if (typSel) typTag.textContent = typSel.options[typSel.selectedIndex].text; typTag.style.display = ''; } document.querySelectorAll('.read-mode-tag:not(#categoryTag):not(#typeTag)').forEach(el => { el.style.display = ''; }); } } /** * CRC-32 (IEEE 802.3 / zlib polynomial), matching PHP's crc32(). Operates on * the UTF-8 byte sequence, same as PHP, so results agree for non-ASCII names. */ function crc32(str) { var bytes = unescape(encodeURIComponent(str)); var table = crc32._table || (crc32._table = (function () { var t = []; for (var n = 0; n < 256; n++) { var c = n; for (var k = 0; k < 8; k++) { c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1); } t[n] = c; } return t; })()); var crc = -1; for (var i = 0; i < bytes.length; i++) { crc = (crc >>> 8) ^ table[(crc ^ bytes.charCodeAt(i)) & 0xFF]; } return (crc ^ -1) >>> 0; } /** * Compute avatar color class from display name (mirrors PHP's crc32 % 4 logic) */ function avatarColorClass(displayName) { var colors = ['lt-avatar--orange', 'lt-avatar--green', 'lt-avatar--purple', '']; return colors[crc32(displayName) % 4]; } /** * Build a comment/reply DOM element matching the server-rendered structure */ function buildCommentElement(opts) { // opts: { commentId, userId, displayName, createdAt, commentText, isMarkdown, // depth, parentId, canModify } var depth = opts.depth || 0; var depthClass = 'thread-depth-' + Math.min(depth, 3); var threadClass = opts.parentId ? 'comment-reply' : 'comment-root'; var words = (opts.displayName || '').trim().split(/\s+/).filter(Boolean); var initials = words.slice(0, 2).map(function(w) { return w[0].toUpperCase(); }).join(''); var color = avatarColorClass(opts.displayName || ''); var avatarImg = opts.userId > 0 ? '${lt.escHtml(message)}
`; } if (dependentsList) { dependentsList.innerHTML = `${lt.escHtml(message)}
`; } } function _depStatusBadge(status) { const slug = (status || '').toLowerCase().replace(/ /g, '-'); const cls = status === 'Closed' ? 'lt-badge-closed' : status === 'Open' ? 'lt-badge-open' : 'lt-badge-sm'; return `${lt.escHtml(status)}`; } function renderDependencies(dependencies) { const container = document.getElementById('dependenciesList'); if (!container) return; const typeLabels = { 'blocks': 'Blocks', 'blocked_by': 'Blocked By', 'relates_to': 'Relates To', 'duplicates': 'Duplicates' }; // Check for open "blocked_by" dependencies — show alert const blockers = (dependencies['blocked_by'] || []).filter(d => d.status !== 'Closed'); const blockerAlert = document.getElementById('blockerAlert'); if (blockers.length > 0) { const alertHtml = `No dependencies configured.
'; } function renderDependents(dependents) { const container = document.getElementById('dependentsList'); if (!container) return; if (!dependents.length) { container.innerHTML = 'No tickets depend on this one.
'; return; } const relLabels = { 'blocks':'blocks', 'blocked_by':'blocked by', 'relates_to':'relates to', 'duplicates':'duplicates' }; let html = ''; dependents.forEach(dep => { const relLabel = relLabels[dep.dependency_type] || dep.dependency_type; html += `Error loading attachments.
'; } else { lt.toast.error('Error loading more attachments'); } }) .catch(error => { if (!append) { container.innerHTML = 'Error loading attachments.
'; } else { lt.toast.error('Error loading more attachments'); } }); } function renderAttachments(attachments, append, hasMore) { const container = document.getElementById('attachmentsList'); if (!container) return; if (!append && attachments.length === 0) { container.innerHTML = 'No files attached to this ticket.
'; return; } let grid = append ? container.querySelector('.attachments-grid') : null; let html = ''; attachments.forEach(att => { const uploaderName = att.display_name || att.username || 'Unknown'; const uploadDateFormatted = new Date(att.uploaded_at).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); const uploadDate = `${lt.time.ago(att.uploaded_at)}`; const isImage = /^image\//i.test(att.mime_type || ''); const imgUrl = `/api/download_attachment.php?id=${att.attachment_id}&inline=1`; // Grid preview requests the resized thumbnail (server falls back to the // full-size original for attachments with none, e.g. uploaded before // thumbnail generation existed); the lightbox link stays on the // full-size original since that's what it displays when opened. const thumbUrl = `${imgUrl}&thumb=1`; const iconHtml = isImage ? `