/** * 统一「提交 XX」对话框 * 配合 templates/macros/submit_entity_modal.html * * IARSubmitEntityModal.register(modalId, { * entityLabel: '迭代待办事项', * onOpen: function (itemId, ctx) { ... return true/false }, * onSubmit: async function (ctx) { ... }, // ctx.attachments * onFilesSelected: function (files, modalId) { ... }, * insertAttachmentLinks: true/false, // 选中后向正文插入 [文件名](attachment:文件名) * resolveUserName: function (userId) { return name; }, * historyEmptyText: '...', * }); * IARSubmitEntityModal.open(modalId, itemId, { historyRaw, content, hint, attachments }); */ (function (global) { 'use strict'; var _registry = {}; /** @type {Object.>} */ var _attachments = {}; function _cfg(modalId) { return _registry[modalId] || {}; } function _modalEl(modalId) { return document.getElementById(modalId); } function _attr(modalId, name, fallback) { var el = _modalEl(modalId); if (el) { var v = el.getAttribute(name); if (v) return v; } return fallback; } function _byAttr(modalId, dataAttr, fallbackSuffix) { var id = _attr(modalId, dataAttr, null); if (!id) id = modalId + fallbackSuffix; return document.getElementById(id); } function escapeHtml(s) { if (s == null) return ''; return String(s) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function _escapeChunkWithBr(s) { return escapeHtml(s).replace(/\n/g, '
'); } function _formatSize(n) { var size = Number(n) || 0; if (size < 1024) return size + ' B'; if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'; return (size / (1024 * 1024)).toFixed(1) + ' MB'; } function _uid() { return 'att_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8); } /** * 轻量 Markdown:图片 ![alt](url) + 链接 [标题](链接);换行转
。 * 完整预览请用 fillMarkdownPreview(与 create_entity_modal 同一套 markdown-preview API)。 */ function renderMarkdownLinksToHtml(raw, emptyHtml) { var s = isolateMarkdownImageNewlines(raw == null ? '' : String(raw)); if (!s.trim()) return emptyHtml || '(暂无内容)'; // 先匹配图片 ![...](...),再匹配普通链接 [...](...),避免把图片当成链接并吞掉换行语义 var re = /(!\[([^\]]*)\]\(([^)\s]+)\)|\[([^\]]+)\]\(([^)\s]+)\))/g; var out = ''; var i = 0; var m; while ((m = re.exec(s)) !== null) { out += _escapeChunkWithBr(s.slice(i, m.index)); if (m[0].charAt(0) === '!') { var alt = m[2] != null ? m[2] : ''; var src = m[3] || ''; if (src) { out += '' +
            escapeHtml(alt) +
            ''; } else { out += _escapeChunkWithBr(m[0]); } } else { var label = m[4]; var u = m[5]; if (u) { var isHttp = /^https?:\/\//i.test(u); var ext = isHttp ? ' target="_blank" rel="noopener noreferrer"' : ''; out += '' + escapeHtml(label) + ''; } else { out += _escapeChunkWithBr(m[0]); } } i = m.index + m[0].length; } out += _escapeChunkWithBr(s.slice(i)); return out; } /** 图片前后仅单换行时补成空行,保证预览中图片单独成段 */ function isolateMarkdownImageNewlines(raw) { var s = raw == null ? '' : String(raw); s = s.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); if (s.indexOf('![') < 0) return s; s = s.replace(/([^\n])\n(!\[[^\]]*\]\([^)\s]+\))/g, '$1\n\n$2'); s = s.replace(/(!\[[^\]]*\]\([^)\s]+\))\n([^\n])/g, '$1\n\n$2'); return s; } /** 与新建对话框一致:优先走 /api/utils/markdown-preview,失败时回退轻量渲染 */ function fillMarkdownPreview(el, raw, emptyHtml) { if (!el) return; var s = isolateMarkdownImageNewlines(raw == null ? '' : String(raw)); var empty = emptyHtml || '(暂无内容)'; if (!String(s).trim()) { el.innerHTML = empty; return; } function applyHtml(html) { el.innerHTML = html && String(html).trim() ? html : empty; if (global.IARInsertResource && typeof IARInsertResource.enhanceLinks === 'function') { try { IARInsertResource.enhanceLinks(el); } catch (e) { /* ignore */ } } } if (global.IAREntityContent && typeof IAREntityContent.fetchMarkdownHtml === 'function') { var seq = (el._iarMdSeq = (el._iarMdSeq || 0) + 1); el.innerHTML = 'Markdown 渲染中…'; IAREntityContent.fetchMarkdownHtml(s).then(function (html) { if (el._iarMdSeq !== seq) return; applyHtml(html); }).catch(function () { if (el._iarMdSeq !== seq) return; applyHtml(renderMarkdownLinksToHtml(s, empty)); }); return; } applyHtml(renderMarkdownLinksToHtml(s, empty)); } function parseHistoryField(raw) { if (raw == null || raw === '') return []; if (Array.isArray(raw)) return raw.filter(function (x) { return x && typeof x === 'object'; }); try { var arr = JSON.parse(String(raw)); return Array.isArray(arr) ? arr.filter(function (x) { return x && typeof x === 'object'; }) : []; } catch (e) { return []; } } function renderHistoryPanel(historyRaw, containerEl, options) { if (!containerEl) return; options = options || {}; var items = parseHistoryField(historyRaw); var emptyText = options.emptyText || '暂无历史提交说明'; var resolveUserName = options.resolveUserName || function () { return ''; }; if (!items.length) { containerEl.innerHTML = '

' + escapeHtml(emptyText) + '

'; return; } var html = ''; items.forEach(function (entry, idx) { var at = escapeHtml(entry.at || ''); var whoRaw = resolveUserName(entry.user_id) || (entry.user_id ? '用户#' + entry.user_id : ''); var who = escapeHtml(whoRaw); html += '
'; html += '
第 ' + (idx + 1) + ' 次提交 · ' + at + (who ? ' · ' + who : '') + '
'; html += '
'; }); containerEl.innerHTML = html; items.forEach(function (entry, idx) { var bodyEl = containerEl.querySelector('[data-iar-md-body="' + idx + '"]'); fillMarkdownPreview( bodyEl, entry.content || '', '(无内容)' ); }); } function syncPreview(modalId) { var contentEl = _byAttr(modalId, 'data-iar-content-id', 'Content'); var previewEl = _byAttr(modalId, 'data-iar-preview-id', 'ContentPreview'); if (!contentEl || !previewEl) return; fillMarkdownPreview( previewEl, contentEl.value, '(暂无提交说明,可在上方编辑或插入资源)' ); } function showError(modalId, msg) { var box = _byAttr(modalId, 'data-iar-error-id', 'Error'); if (!box) return; box.textContent = msg || ''; box.classList.toggle('d-none', !msg); } function hideError(modalId) { showError(modalId, ''); } function getBootstrapModal(modalId) { var el = _modalEl(modalId); if (!el) return null; if (typeof bootstrap !== 'undefined' && bootstrap.Modal) { return bootstrap.Modal.getOrCreateInstance(el); } return null; } function show(modalId) { var m = getBootstrapModal(modalId); if (m) m.show(); else { var el = _modalEl(modalId); if (el) { el.style.display = 'block'; el.classList.add('show'); } } } function hide(modalId) { var m = getBootstrapModal(modalId); if (m) m.hide(); else { var el = _modalEl(modalId); if (el) { el.style.display = 'none'; el.classList.remove('show'); } } } function getItemId(modalId) { var el = _byAttr(modalId, 'data-iar-item-id-field', 'ItemId'); return el ? el.value : ''; } function setItemId(modalId, id) { var el = _byAttr(modalId, 'data-iar-item-id-field', 'ItemId'); if (el) el.value = id == null ? '' : String(id); } function getContent(modalId) { var el = _byAttr(modalId, 'data-iar-content-id', 'Content'); return el ? el.value : ''; } function setContent(modalId, text) { var el = _byAttr(modalId, 'data-iar-content-id', 'Content'); if (el) el.value = text == null ? '' : String(text); syncPreview(modalId); } function setHint(modalId, text) { var el = _byAttr(modalId, 'data-iar-hint-id', 'Hint'); if (!el) return; if (text) { el.textContent = text; el.classList.remove('d-none'); } else { el.textContent = ''; el.classList.add('d-none'); } } function setHistory(modalId, historyRaw, emptyText) { var panel = _byAttr(modalId, 'data-iar-history-id', 'HistoryPanel'); var cfg = _cfg(modalId); renderHistoryPanel(historyRaw, panel, { emptyText: emptyText || cfg.historyEmptyText || '暂无历史提交说明', resolveUserName: cfg.resolveUserName, }); } function getAttachments(modalId) { return (_attachments[modalId] || []).slice(); } function _renderAttachList(modalId) { var listEl = _byAttr(modalId, 'data-iar-attach-list-id', 'AttachList'); if (!listEl) return; var items = _attachments[modalId] || []; if (!items.length) { listEl.innerHTML = '

暂无附件,点击「添加附件」选择文件

'; return; } listEl.innerHTML = items .map(function (it) { var nameHtml; if (it.url) { nameHtml = '' + escapeHtml(it.name) + ''; } else { nameHtml = '' + escapeHtml(it.name) + ''; } var meta = it.size ? escapeHtml(_formatSize(it.size)) : (it.existing ? '已上传' : ''); return ( '
' + nameHtml + '' + meta + '' + '' + '
' ); }) .join(''); } function setAttachments(modalId, list) { var arr = Array.isArray(list) ? list : []; _attachments[modalId] = arr.map(function (x) { if (!x) return null; if (typeof File !== 'undefined' && x instanceof File) { return { id: _uid(), name: x.name, size: x.size, file: x }; } return { id: x.id || _uid(), name: x.name || '未命名', size: x.size || 0, file: x.file || null, url: x.url || '', existing: !!x.existing, }; }).filter(Boolean); _renderAttachList(modalId); } function clearAttachments(modalId) { _attachments[modalId] = []; var input = _byAttr(modalId, 'data-iar-attach-input-id', 'AttachInput'); if (input) input.value = ''; _renderAttachList(modalId); } function addAttachments(modalId, fileList) { if (!_attachments[modalId]) _attachments[modalId] = []; var files = Array.prototype.slice.call(fileList || []); var added = []; files.forEach(function (f) { if (!f) return; var item = { id: _uid(), name: f.name, size: f.size, file: f }; _attachments[modalId].push(item); added.push(item); }); _renderAttachList(modalId); var cfg = _cfg(modalId); if (cfg.insertAttachmentLinks !== false && added.length) { var contentEl = _byAttr(modalId, 'data-iar-content-id', 'Content'); if (contentEl) { var snippets = added .map(function (it) { return '[' + it.name + '](attachment:' + it.name + ')'; }) .join('\n'); var cur = contentEl.value || ''; contentEl.value = cur ? cur.replace(/\s*$/, '') + '\n' + snippets + '\n' : snippets + '\n'; syncPreview(modalId); } } if (typeof cfg.onFilesSelected === 'function') { try { cfg.onFilesSelected(added, modalId); } catch (e) { /* ignore page handler errors */ } } return added; } function removeAttachment(modalId, attachId) { var list = _attachments[modalId] || []; _attachments[modalId] = list.filter(function (x) { return x.id !== attachId; }); _renderAttachList(modalId); } function register(modalId, options) { _registry[modalId] = options || {}; if (!_attachments[modalId]) _attachments[modalId] = []; var contentEl = _byAttr(modalId, 'data-iar-content-id', 'Content'); if (contentEl && !contentEl.getAttribute('data-iar-preview-bound')) { contentEl.setAttribute('data-iar-preview-bound', '1'); contentEl.addEventListener('input', function () { syncPreview(modalId); }); } _renderAttachList(modalId); return api; } /** * @param {string} modalId * @param {string|number} itemId * @param {object} [ctx] { historyRaw, content, hint, historyEmptyText, attachments } */ function open(modalId, itemId, ctx) { ctx = ctx || {}; var cfg = _cfg(modalId); if (typeof cfg.onOpen === 'function') { var ok = cfg.onOpen(itemId, ctx); if (ok === false) return false; } setItemId(modalId, itemId); setHint(modalId, ctx.hint || ''); if (ctx.historyRaw !== undefined || _byAttr(modalId, 'data-iar-history-id', 'HistoryPanel')) { setHistory(modalId, ctx.historyRaw, ctx.historyEmptyText); } if (ctx.content !== undefined) setContent(modalId, ctx.content); else syncPreview(modalId); if (ctx.attachments !== undefined) setAttachments(modalId, ctx.attachments); else clearAttachments(modalId); hideError(modalId); show(modalId); return true; } async function confirm(modalId) { var cfg = _cfg(modalId); hideError(modalId); var ctx = { modalId: modalId, itemId: getItemId(modalId), content: getContent(modalId), attachments: getAttachments(modalId), }; try { var handlerName = _attr(modalId, 'data-iar-submit-handler', ''); if (typeof cfg.onSubmit === 'function') { await cfg.onSubmit(ctx); } else if (handlerName && typeof global[handlerName] === 'function') { await global[handlerName](ctx); } else { throw new Error('未配置提交处理函数'); } if (typeof cfg.onAfterSubmit === 'function') cfg.onAfterSubmit(ctx); } catch (e) { showError(modalId, e.message || String(e)); throw e; } } function _onDocClick(e) { var attachBtn = e.target && e.target.closest ? e.target.closest('.iar-submit-add-attach-btn') : null; if (attachBtn) { var mid = attachBtn.getAttribute('data-iar-submit-modal'); if (!mid) { var m = attachBtn.closest('.iar-submit-entity-modal'); mid = m ? m.id : ''; } if (!mid) return; e.preventDefault(); var input = _byAttr(mid, 'data-iar-attach-input-id', 'AttachInput'); if (input) input.click(); return; } var removeBtn = e.target && e.target.closest ? e.target.closest('.iar-submit-attach-remove') : null; if (removeBtn) { e.preventDefault(); removeAttachment( removeBtn.getAttribute('data-iar-submit-modal') || '', removeBtn.getAttribute('data-attach-id') || '' ); return; } var btn = e.target && e.target.closest ? e.target.closest('.iar-submit-entity-confirm-btn') : null; if (!btn) return; var modalId = btn.getAttribute('data-iar-submit-modal'); if (!modalId) { var modal = btn.closest('.iar-submit-entity-modal'); modalId = modal ? modal.id : ''; } if (!modalId) return; e.preventDefault(); confirm(modalId).catch(function () { /* error already shown */ }); } function _onDocChange(e) { var input = e.target; if (!input || !input.classList || !input.classList.contains('iar-submit-attach-input')) return; var modalId = input.getAttribute('data-iar-submit-modal') || ''; if (!modalId) { var modal = input.closest('.iar-submit-entity-modal'); modalId = modal ? modal.id : ''; } if (!modalId) return; addAttachments(modalId, input.files); input.value = ''; } if (typeof document !== 'undefined') { document.addEventListener('click', _onDocClick); document.addEventListener('change', _onDocChange); } var api = { register: register, open: open, show: show, hide: hide, confirm: confirm, showError: showError, hideError: hideError, getItemId: getItemId, setItemId: setItemId, getContent: getContent, setContent: setContent, setHint: setHint, setHistory: setHistory, syncPreview: syncPreview, getAttachments: getAttachments, setAttachments: setAttachments, clearAttachments: clearAttachments, addAttachments: addAttachments, removeAttachment: removeAttachment, renderMarkdownLinksToHtml: renderMarkdownLinksToHtml, fillMarkdownPreview: fillMarkdownPreview, renderHistoryPanel: renderHistoryPanel, parseHistoryField: parseHistoryField, escapeHtml: escapeHtml, }; global.IARSubmitEntityModal = api; })(typeof window !== 'undefined' ? window : this);