/** * 统一字段/单元格右侧复制小按钮(参照 IntelliRschAsst/paper_writing.html) * 配合 templates/macros/field_copy.html */ (function (global) { 'use strict'; function _notify(message, success) { if (typeof global.showCopyMessage === 'function') { global.showCopyMessage(message, success !== false); } else { alert(message); } } /** * 非安全上下文(http 远程域名)下 navigator.clipboard 常不可用; * Bootstrap 模态焦点陷阱也会导致挂在 body 上的 textarea 复制失败。 * 将临时控件挂到最近的 .modal.show / 按钮所在行内再 execCommand。 */ function _execCommandCopy(text, anchorEl) { var s = String(text == null ? '' : text); var ta = document.createElement('textarea'); ta.value = s; ta.setAttribute('autocomplete', 'off'); ta.setAttribute('aria-hidden', 'true'); ta.setAttribute('tabindex', '-1'); ta.style.cssText = 'position:fixed;left:0;top:0;padding:2px;margin:0;border:1px solid transparent;outline:none;box-shadow:none;background:#fff;opacity:0.02;z-index:2147483647;font-size:12pt;line-height:1;min-width:2px;min-height:2px;resize:none;overflow:hidden;'; var host = document.body; var modalShown = document.querySelector('.modal.show'); if (modalShown) { host = modalShown.querySelector('.modal-dialog') || modalShown.querySelector('.modal-content') || modalShown; } else if (anchorEl && anchorEl.closest) { host = anchorEl.closest('.iar-field-copy-row, .iar-field-copy-cell, .card-panel, .modal-content') || document.body; } host.appendChild(ta); var ok = false; try { ta.focus({ preventScroll: true }); if (typeof ta.select === 'function') ta.select(); if (typeof ta.setSelectionRange === 'function') ta.setSelectionRange(0, ta.value.length); ok = document.execCommand('copy'); } catch (e) { ok = false; } setTimeout(function () { try { if (ta && ta.parentNode) ta.parentNode.removeChild(ta); } catch (e2) {} }, 200); return ok; } function _copyText(text, anchorEl) { var s = String(text == null ? '' : text); // 1) 同步 execCommand(同一用户手势内最可靠,兼容 http 远程域名) if (_execCommandCopy(s, anchorEl)) { return Promise.resolve(); } // 2) 全局实现(通常同样走 execCommand + clipboard) if (typeof global.copyTextToClipboard === 'function') { return global.copyTextToClipboard(s).catch(function () { if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { return navigator.clipboard.writeText(s); } return Promise.reject(new Error('clipboard unavailable')); }); } // 3) Clipboard API(仅 https / localhost) if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { return navigator.clipboard.writeText(s); } return Promise.reject(new Error('clipboard unavailable')); } function _flashButton(btn) { if (!btn) return; btn.classList.add('is-copied'); var icon = btn.querySelector('i.fas, i.far'); var origClass = icon ? icon.className : ''; if (icon) icon.className = 'fas fa-check'; setTimeout(function () { btn.classList.remove('is-copied'); if (icon) icon.className = origClass || 'fas fa-copy'; }, 800); } function _normalizeText(text) { return String(text == null ? '' : text).replace(/\u00a0/g, ' ').replace(/\s+/g, ' ').trim(); } /** 保留换行与内部空白,仅规范化不间断空格。 */ function _preserveFormattedText(text) { return String(text == null ? '' : text).replace(/\u00a0/g, ' ').replace(/\r\n/g, '\n').replace(/\r/g, '\n'); } function _isEmptyValue(text) { var t = _normalizeText(text); return !t || t === '-'; } function _isPreformattedEl(el) { if (!el || !el.tagName) return false; var tag = el.tagName; if (tag === 'PRE' || tag === 'TEXTAREA') return true; if (el.getAttribute('data-iar-copy-preserve') === '1' || el.getAttribute('data-iar-copy-preserve') === 'true') { return true; } if (el.classList && (el.classList.contains('font-monospace') || el.classList.contains('iar-field-copy-preserve'))) { return true; } try { var ws = (el.style && el.style.whiteSpace) || ''; if (!ws && global.getComputedStyle) { ws = global.getComputedStyle(el).whiteSpace || ''; } return ws === 'pre' || ws === 'pre-wrap' || ws === 'pre-line' || ws === 'break-spaces'; } catch (e) { return false; } } function _textFromValueEl(el) { if (!el) return ''; if (el.tagName === 'SELECT') { var opt = el.selectedOptions && el.selectedOptions[0]; if (opt) return String(opt.text || opt.value || '').trim(); return String(el.value || '').trim(); } if (el.tagName === 'TEXTAREA') { return _preserveFormattedText(el.value || ''); } if (el.tagName === 'INPUT') { return String(el.value || '').trim(); } if (el.tagName === 'PRE') { return _preserveFormattedText(el.textContent || ''); } if (el.isContentEditable || el.getAttribute('contenteditable') === 'true' || (el.classList && el.classList.contains('iar-rich-text-editor')) || el.getAttribute('data-iar-rich-text') != null) { return _preserveFormattedText(el.innerText || el.textContent || ''); } if (_isPreformattedEl(el)) { return _preserveFormattedText(el.innerText || el.textContent || ''); } var link = el.querySelector('a'); if (link && !el.querySelector('br, p, div, pre, li')) { return _normalizeText(link.textContent); } // 块级/多行字段:用 innerText 保留可见换行,不折叠空白 if (el.querySelector('br, p, div, pre, li, table') || (el.classList && el.classList.contains('form-control-plaintext'))) { var multi = _preserveFormattedText(el.innerText || el.textContent || ''); return multi.replace(/^\n+|\n+$/g, ''); } return _normalizeText(el.textContent || el.innerText); } function _richTextFromPre(pre) { if (!pre) return ''; var raw = ''; if (typeof global.decodeBase64ToUtf8 === 'function') { raw = global.decodeBase64ToUtf8(pre.getAttribute('data-copy-b64') || ''); } if (raw && raw.length) return raw; return _preserveFormattedText(pre.textContent || ''); } function _resolveTextFromButton(btn) { if (!btn) return ''; var targetId = btn.getAttribute('data-iar-copy-target'); if (targetId) return _textFromValueEl(document.getElementById(targetId)); var noteCell = btn.closest('.iar-linked-note-cell, .project-note-cell'); if (noteCell) { var pre = noteCell.querySelector('.iar-linked-note-cell-content, .project-note-cell-content'); if (pre && pre.tagName === 'TEXTAREA') { return _preserveFormattedText(pre.value || ''); } if (pre && typeof global._copyNotePreRich === 'function') { return { richPre: pre }; } if (pre) return _richTextFromPre(pre); } var row = btn.closest('.iar-field-copy-row, .iar-field-copy-cell'); if (row) { var val = row.querySelector('.iar-field-copy-value'); if (val) return _textFromValueEl(val); } var td = btn.closest('td, th'); if (td) { var span = td.querySelector('.iar-field-copy-value, .cell-value'); if (span) return _textFromValueEl(span); var clone = td.cloneNode(true); clone.querySelectorAll('button, .iar-field-copy-btn, .iar-cell-copy-btn, .copy-btn, .copy-btn-row, .budget-copy-btn').forEach(function (b) { b.remove(); }); return _preserveFormattedText(clone.innerText || clone.textContent).replace(/^\n+|\n+$/g, ''); } return ''; } function copyText(text, options) { options = options || {}; var payload = String(text == null ? '' : text); if (_isEmptyValue(payload)) { _notify(options.emptyMessage || '内容为空,无法复制', false); return Promise.resolve(false); } return _copyText(payload, options.button || options.anchorEl || null).then(function () { var msg = options.message; if (!msg) { var preview = payload.length > 30 ? payload.substring(0, 30) + '...' : payload; msg = options.previewInMessage === false ? '已复制到剪贴板' : ('已复制:' + preview); } _notify(msg, true); if (options.button) _flashButton(options.button); return true; }).catch(function () { // 最后兜底:弹出可选中文本,避免 http 远程完全无法复制 try { if (global.prompt) { global.prompt('复制失败,请手动全选后复制(Ctrl+C):', payload); return false; } } catch (e) {} _notify(options.failMessage || '复制失败,请手动复制', false); return false; }); } function copyFromButton(btn, options) { options = options || {}; var resolved = _resolveTextFromButton(btn); if (resolved && typeof resolved === 'object' && resolved.richPre) { return global._copyNotePreRich(resolved.richPre).then(function () { _notify(options.message || '已复制到剪贴板', true); _flashButton(btn); return true; }).catch(function () { _notify(options.failMessage || '复制失败,请手动复制', false); return false; }); } return copyText(resolved, Object.assign({}, options, { button: btn })); } function copyFromElement(elementId, options) { var el = document.getElementById(elementId); return copyText(_textFromValueEl(el), options); } function copyColumn(tableBodyId, columnIndex, options) { options = options || {}; var tbody = document.getElementById(tableBodyId); if (!tbody) return Promise.resolve(false); var lines = []; tbody.querySelectorAll('tr').forEach(function (row) { var cells = row.querySelectorAll('td'); if (!cells[columnIndex]) return; var cell = cells[columnIndex]; var span = cell.querySelector('.iar-field-copy-value, .cell-value'); var text = span ? _textFromValueEl(span) : ''; if (!text) { var clone = cell.cloneNode(true); clone.querySelectorAll('button, .iar-field-copy-btn, .iar-cell-copy-btn').forEach(function (b) { b.remove(); }); text = _preserveFormattedText(clone.innerText || clone.textContent).replace(/^\n+|\n+$/g, ''); } if (text && text !== '-') lines.push(text); }); if (!lines.length) { _notify(options.emptyMessage || '该列为空,无法复制', false); return Promise.resolve(false); } return copyText(lines.join('\n'), Object.assign({ previewInMessage: false, message: '已复制整列(' + lines.length + ' 行)' }, options)); } function buttonHtml(options) { options = options || {}; var cls = 'iar-field-copy-btn'; if (options.variant === 'column') cls += ' iar-field-copy-btn-column'; if (options.extraClass) cls += ' ' + options.extraClass; var onclick = options.onclick || 'IARFieldCopy.copyFromButton(this)'; var title = options.title || '复制'; var targetAttr = options.targetId ? (' data-iar-copy-target="' + options.targetId + '"') : ''; return ''; } function columnButtonHtml(tableBodyId, columnIndex, title) { title = title || '复制整列'; return buttonHtml({ variant: 'column', title: title, onclick: "IARFieldCopy.copyColumn('" + tableBodyId + "', " + columnIndex + ")" }); } function cellWrap(valueHtml, options) { options = options || {}; return '
' + '' + (valueHtml || '') + '' + buttonHtml(options) + '
'; } function _shouldSkipFieldCopy(el) { if (!el || el.closest('.iar-field-copy-row')) return true; if (!el.id && !el.getAttribute('data-iar-field-copy') && !el.getAttribute('data-iar-field-copy-group')) return true; if (el.closest('[data-iar-field-copy-ignore]')) return true; if (el.closest('.form-check')) return true; if (el.closest('.iar-create-entity-form-error, .iar-linked-note-cell-actions, .project-note-cell-actions')) return true; var type = (el.getAttribute('type') || '').toLowerCase(); if (type === 'hidden' || type === 'checkbox' || type === 'radio' || type === 'file' || type === 'button' || type === 'submit' || type === 'password') return true; return false; } function _textFromGroupEl(el) { if (!el) return ''; var checks = el.querySelectorAll('input[type="checkbox"]:checked'); if (checks.length) { return Array.from(checks).map(function (c) { return (c.value || c.parentElement.textContent || '').trim(); }) .filter(Boolean).join(','); } return _textFromValueEl(el); } function _wrapValueElement(el, options) { options = options || {}; if (_shouldSkipFieldCopy(el)) return; var wrap = document.createElement('div'); wrap.className = 'iar-field-copy-row' + (options.control ? ' iar-field-copy-row-control' : ''); el.parentNode.insertBefore(wrap, el); el.classList.add('iar-field-copy-value'); wrap.appendChild(el); var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'iar-field-copy-btn'; btn.title = '复制'; btn.setAttribute('aria-label', '复制'); if (el.id) btn.setAttribute('data-iar-copy-target', el.id); btn.innerHTML = ''; btn.addEventListener('click', function (ev) { ev.preventDefault(); ev.stopPropagation(); if (el.getAttribute('data-iar-field-copy-group') === '1' || el.getAttribute('data-iar-field-copy-group') === 'true') { copyText(_textFromGroupEl(el), { button: btn, previewInMessage: false, message: '已复制到剪贴板' }); return; } copyFromButton(btn); }); wrap.appendChild(btn); } function enhancePlaintextFields(root) { root = root || document; if (!root.querySelectorAll) return; root.querySelectorAll('.form-control-plaintext[id], [data-iar-field-copy][id]').forEach(function (el) { _wrapValueElement(el, { control: false }); }); } function enhanceFormControls(root) { root = root || document; if (!root.querySelectorAll) return; var selector = [ 'input.form-control[id]', 'select.form-select[id]', 'select.form-control[id]', 'textarea.form-control[id]', '.iar-rich-text-editor[id][data-iar-rich-text]', '[data-iar-field-copy-group][id]' ].join(', '); root.querySelectorAll(selector).forEach(function (el) { _wrapValueElement(el, { control: true }); }); } function enhanceContainer(root) { enhancePlaintextFields(root); enhanceFormControls(root); } function enhanceCreateEntityModal(modalId) { var el = typeof modalId === 'string' ? document.getElementById(modalId) : modalId; if (!el) return; var body = el.querySelector('.modal-body[data-iar-field-copy-auto]'); if (body) enhanceContainer(body); } function initAutoEnhance() { document.querySelectorAll('[data-iar-field-copy-auto]').forEach(function (container) { enhanceContainer(container); }); document.querySelectorAll('.iar-create-entity-modal .modal-body[data-iar-field-copy-auto]').forEach(function (container) { enhanceContainer(container); }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initAutoEnhance); } else { initAutoEnhance(); } var api = { copyText: copyText, copyFromButton: copyFromButton, copyFromElement: copyFromElement, copyColumn: copyColumn, buttonHtml: buttonHtml, columnButtonHtml: columnButtonHtml, cellWrap: cellWrap, enhancePlaintextFields: enhancePlaintextFields, enhanceFormControls: enhanceFormControls, enhanceContainer: enhanceContainer, enhanceCreateEntityModal: enhanceCreateEntityModal, }; global.IARFieldCopy = api; global.copyCellText = function (btn) { return copyFromButton(btn); }; })(typeof window !== 'undefined' ? window : this);