/** * 统一「插入资源 / 论文 / 课题 / 项目 / 学位论文」选择器 * 配合 templates/macros/insert_resource.html、entity_content_field / entity_content_view * * IARInsertResource.open({ * targetId, targetEl, fieldId, hint, onInserted, mode, * pickKind: 'resource'|'paper'|'topic'|'project'|'thesis', * allowedTypes: ['literature','template',...], // 仅 resource * allowedScopes: ['personal','team','organization'], * }); * mode: 'insert' | 'clipboard' * 插入链接带 title="iar|kind|scope|owner|typeLabel",点击打开「插入的XX」对话框 */ (function (global) { 'use strict'; var MODAL_ID = 'iarInsertResourceModal'; var VIEW_MODAL_ID = 'iarInsertedItemModal'; var ALL_RESOURCE_TYPES = [ 'literature', 'template', 'tool', 'platform', 'tutorial', 'note', 'dataset', ]; var ALL_SCOPES = ['personal', 'team', 'organization']; var ALL_VIEW_OPS = ['view', 'open', 'copy', 'download']; var VIEW_OP_LABELS = { view: '查看详情', open: '打开链接', copy: '复制链接', download: '下载', }; var KIND_LABELS = { literature: '文献', template: '文档模板', tool: '工具', platform: '平台链接', tutorial: '教程', note: '笔记', dataset: '数据集', paper: '论文', topic: '课题', project: '项目', thesis: '学位论文', }; var KIND_ICONS = { literature: 'fa-book-open', template: 'fa-file-alt', tool: 'fa-wrench', platform: 'fa-link', tutorial: 'fa-chalkboard-teacher', note: 'fa-sticky-note', dataset: 'fa-database', paper: 'fa-book', topic: 'fa-flask', project: 'fa-project-diagram', thesis: 'fa-graduation-cap', resource: 'fa-paperclip', }; var STATE = { type: 'literature', items: [], selected: null, pickKind: 'resource' }; var _ctx = { targetId: null, targetEl: null, fieldId: null, hint: '编辑框', mode: 'insert', onInserted: null, pickKind: 'resource', allowedTypes: ALL_RESOURCE_TYPES.slice(), allowedScopes: ALL_SCOPES.slice(), allowedViewOps: ALL_VIEW_OPS.slice(), }; var _sourceCache = { personal: '', team: '', organization: '' }; function _esc(s) { return String(s == null ? '' : s) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function typeLabel(kind) { return KIND_LABELS[kind] || String(kind || '资源'); } function insertedModalTitle(kind) { if (kind === 'template') return '插入文档模板'; return '插入的' + typeLabel(kind); } function normalizeOps(ops) { var list; if (Array.isArray(ops)) list = ops; else if (ops == null || String(ops).trim() === '') list = []; else list = String(ops).split(/[,|;]/).map(function (s) { return s.trim(); }).filter(Boolean); var out = []; list.forEach(function (op) { op = String(op || '').trim().toLowerCase(); if (ALL_VIEW_OPS.indexOf(op) >= 0 && out.indexOf(op) < 0) out.push(op); }); if (out.indexOf('view') < 0) out.unshift('view'); return out; } function encodeInsertTitle(meta) { meta = meta || {}; var ops = normalizeOps(meta.ops || meta.allowedOps || ['view', 'open', 'copy']); return [ 'iar', meta.kind || '', meta.scope || 'personal', encodeURIComponent(meta.owner || ''), encodeURIComponent(meta.typeLabel || typeLabel(meta.kind)), encodeURIComponent(ops.join(',')), ].join('|'); } function parseInsertTitle(title) { var t = title == null ? '' : String(title).trim(); // 兼容 title 被 HTML 实体解码前后、或前后有空白 var idx = t.indexOf('iar|'); if (idx < 0) return null; t = t.slice(idx); var parts = t.split('|'); if (parts.length < 5) return null; try { var opsStr = parts.length >= 6 ? decodeURIComponent(parts[5] || '') : 'view,open,copy'; return { kind: parts[1] || '', scope: parts[2] || 'personal', owner: decodeURIComponent(parts[3] || ''), typeLabel: decodeURIComponent(parts[4] || ''), ops: normalizeOps(opsStr), }; } catch (e) { return null; } } function appendInsertMetaToUrl(url, meta) { meta = meta || {}; var base = (url == null || String(url).trim() === '') ? '#' : String(url).trim(); // 去掉旧的 iar_* 参数,避免重复叠加 try { var hash = ''; var hashIdx = base.indexOf('#'); if (hashIdx >= 0) { hash = base.slice(hashIdx); base = base.slice(0, hashIdx); } var qIdx = base.indexOf('?'); var path = qIdx >= 0 ? base.slice(0, qIdx) : base; var q = qIdx >= 0 ? base.slice(qIdx + 1) : ''; var kept = []; if (q) { q.split('&').forEach(function (pair) { var k = pair.split('=')[0]; if (k === 'iar_kind' || k === 'iar_scope' || k === 'iar_owner' || k === 'iar_type' || k === 'iar_ops' || k === 'iar_path') return; if (pair) kept.push(pair); }); } var ops = normalizeOps(meta.ops || meta.allowedOps || ['view', 'open', 'copy']); kept.push('iar_kind=' + encodeURIComponent(meta.kind || '')); kept.push('iar_scope=' + encodeURIComponent(meta.scope || 'personal')); kept.push('iar_owner=' + encodeURIComponent(meta.owner || '')); kept.push('iar_type=' + encodeURIComponent(meta.typeLabel || typeLabel(meta.kind))); kept.push('iar_ops=' + encodeURIComponent(ops.join(','))); if (meta.path) kept.push('iar_path=' + encodeURIComponent(meta.path)); return path + '?' + kept.join('&') + hash; } catch (e) { return base; } } function parseInsertFromHref(href) { var h = href == null ? '' : String(href); if (!h) return null; try { var q = ''; var qIdx = h.indexOf('?'); if (qIdx < 0) return null; q = h.slice(qIdx + 1); var hashIdx = q.indexOf('#'); if (hashIdx >= 0) q = q.slice(0, hashIdx); var params = {}; q.split('&').forEach(function (pair) { if (!pair) return; var i = pair.indexOf('='); var k = i >= 0 ? pair.slice(0, i) : pair; var v = i >= 0 ? pair.slice(i + 1) : ''; try { params[k] = decodeURIComponent(v.replace(/\+/g, ' ')); } catch (e2) { params[k] = v; } }); if (!params.iar_kind) return null; return { kind: params.iar_kind || '', scope: params.iar_scope || 'personal', owner: params.iar_owner || '', typeLabel: params.iar_type || typeLabel(params.iar_kind), ops: normalizeOps(params.iar_ops || 'view,open,copy'), path: params.iar_path || '', }; } catch (e) { return null; } } function parseInsertFromAnchor(a) { if (!a || !a.getAttribute) return null; if (a.getAttribute('data-iar-insert-kind')) { return { kind: a.getAttribute('data-iar-insert-kind') || '', scope: a.getAttribute('data-iar-insert-scope') || 'personal', owner: a.getAttribute('data-iar-insert-owner') || '', typeLabel: a.getAttribute('data-iar-insert-type-label') || '', ops: normalizeOps(a.getAttribute('data-iar-insert-ops') || 'view,open,copy'), }; } var fromTitle = parseInsertTitle(a.getAttribute('title') || ''); if (fromTitle && fromTitle.kind) return fromTitle; return parseInsertFromHref(a.getAttribute('href') || a.href || ''); } function buildSnippet(label, url, meta) { var title = encodeInsertTitle(meta); var href = appendInsertMetaToUrl(url, meta); // Markdown 链接:title + URL 参数双通道,预览点击更稳 return '[' + (label || '链接') + '](' + href + ' "' + title + '")'; } function displayUrl(href) { var h = href == null ? '' : String(href); if (!h) return '#'; try { var hashIdx = h.indexOf('#'); var hash = hashIdx >= 0 ? h.slice(hashIdx) : ''; var main = hashIdx >= 0 ? h.slice(0, hashIdx) : h; var qIdx = main.indexOf('?'); if (qIdx < 0) return h; var path = main.slice(0, qIdx); var kept = []; main.slice(qIdx + 1).split('&').forEach(function (pair) { var k = pair.split('=')[0]; if (k === 'iar_kind' || k === 'iar_scope' || k === 'iar_owner' || k === 'iar_type') return; if (pair) kept.push(pair); }); return path + (kept.length ? ('?' + kept.join('&')) : '') + hash; } catch (e) { return h; } } function _parseListAttr(raw, fallback) { if (raw == null || String(raw).trim() === '') return fallback.slice(); return String(raw) .split(/[,|;]/) .map(function (s) { return s.trim(); }) .filter(Boolean); } function _currentUserDisplayName() { if (global.__IAR_USER_DISPLAY_NAME__) return String(global.__IAR_USER_DISPLAY_NAME__); var nameEl = document.querySelector('.user-info .user-name'); if (nameEl) { var clone = nameEl.cloneNode(true); var label = clone.querySelector('.user-name-label'); if (label) label.remove(); var n = (clone.textContent || '').trim(); if (n) return n; } return '当前用户'; } async function _resolveOwnerName(scope) { var sc = scope || 'personal'; if (sc === 'personal') { _sourceCache.personal = _currentUserDisplayName(); return _sourceCache.personal; } if (sc === 'team') { if (_sourceCache.team) return _sourceCache.team; try { var r = await fetch('/api/current_team', { credentials: 'same-origin' }); var d = await r.json(); if (d.success && d.team && d.team.name) { _sourceCache.team = d.team.name; return _sourceCache.team; } } catch (e) { /* ignore */ } return '当前团队'; } if (sc === 'organization') { if (_sourceCache.organization) return _sourceCache.organization; try { var r2 = await fetch('/api/current_organization', { credentials: 'same-origin' }); var d2 = await r2.json(); if (d2.success && d2.organization && d2.organization.name) { _sourceCache.organization = d2.organization.name; return _sourceCache.organization; } } catch (e2) { /* ignore */ } return '当前机构'; } return _currentUserDisplayName(); } function ensureModal() { var existing = document.getElementById(MODAL_ID); if (existing) { if (!document.getElementById('iarInsertAllowedOps')) { var body = existing.querySelector('.modal-body'); if (body) { var hintP = body.querySelector('#iarInsertResourceTargetHint'); var opsWrap = document.createElement('div'); opsWrap.className = 'mt-3'; opsWrap.id = 'iarInsertAllowedOpsWrap'; opsWrap.innerHTML = '
允许的操作 (点击已插入链接后可执行)
' + '
'; if (hintP && hintP.parentNode) { hintP.parentNode.insertBefore(opsWrap, hintP); } else { body.appendChild(opsWrap); } } } if (!existing.__iarInsertEventsBound) { existing.__iarInsertEventsBound = true; _bindModalEvents(); } return existing; } var wrap = document.createElement('div'); wrap.innerHTML = ''; var modal = wrap.firstChild; document.body.appendChild(modal); modal.__iarInsertEventsBound = true; _bindModalEvents(); return modal; } function ensureViewModal() { var existing = document.getElementById(VIEW_MODAL_ID); if (existing) { if (!existing.__iarViewEventsBound) { existing.__iarViewEventsBound = true; _bindViewModalEvents(); } return existing; } var wrap = document.createElement('div'); wrap.innerHTML = ''; var modal = wrap.firstChild; document.body.appendChild(modal); modal.__iarViewEventsBound = true; _bindViewModalEvents(); return modal; } function _bindViewModalEvents() { var copyBtn = document.getElementById('iarInsertedItemCopyBtn'); if (copyBtn && !copyBtn.__iarBound) { copyBtn.__iarBound = true; copyBtn.addEventListener('click', function () { var linkEl = document.getElementById('iarInsertedItemLink'); var url = linkEl ? (linkEl.getAttribute('data-clean-href') || displayUrl(linkEl.getAttribute('href') || '') || '') : ''; _copyClipboard(url).then(function (ok) { alert(ok ? '已复制链接' : '复制失败'); }); }); } } function _renderAllowedOpsChecks(allowed, selected) { var box = document.getElementById('iarInsertAllowedOps'); if (!box) return; var opts = (allowed && allowed.length) ? allowed : ALL_VIEW_OPS.slice(); var sel = normalizeOps(selected && selected.length ? selected : opts); box.innerHTML = ''; opts.forEach(function (op) { op = String(op).toLowerCase(); if (ALL_VIEW_OPS.indexOf(op) < 0) return; var id = 'iarInsertOp_' + op; var wrap = document.createElement('div'); wrap.className = 'form-check form-check-inline mb-0'; var checked = sel.indexOf(op) >= 0 ? ' checked' : ''; var disabled = op === 'view' ? ' disabled' : ''; wrap.innerHTML = '' + ''; box.appendChild(wrap); }); } function _readSelectedOps() { var box = document.getElementById('iarInsertAllowedOps'); if (!box) return normalizeOps(['view', 'open', 'copy']); var ops = ['view']; box.querySelectorAll('[data-iar-view-op]').forEach(function (inp) { var op = inp.getAttribute('data-iar-view-op'); if (op === 'view') return; if (inp.checked && ops.indexOf(op) < 0) ops.push(op); }); return normalizeOps(ops); } function _guessDownloadUrl(kind, rawUrl, path) { if (path) { return '/api/files/download/' + String(path).replace(/^\/+/, '') + '?page=' + encodeURIComponent(kind || 'literature'); } var clean = displayUrl(rawUrl || '') || ''; if (/\/api\/files\/download\//.test(clean)) return clean; return ''; } function _stackModalOnTop(modalEl) { if (!modalEl) return; var openCount = document.querySelectorAll('.modal.show').length; var z = 1080 + openCount * 20; modalEl.style.zIndex = String(z); // 下一帧再抬高最新 backdrop,避免被外层「新建/查看」对话框挡住 setTimeout(function () { var backs = document.querySelectorAll('.modal-backdrop'); if (backs.length) { var last = backs[backs.length - 1]; last.style.zIndex = String(z - 1); last.classList.add('iar-inserted-item-backdrop'); } }, 10); } function openInsertedViewer(opts) { opts = opts || {}; ensureViewModal(); var kind = opts.kind || 'literature'; var typeLab = opts.typeLabel || typeLabel(kind); var owner = opts.owner || '未知'; var label = opts.label || opts.title || '(未命名)'; var subtitle = opts.subtitle || opts.path || ''; var url = displayUrl(opts.url || '#') || '#'; var ops = normalizeOps(opts.ops || opts.allowedOps || ['view', 'open', 'copy']); var downloadUrl = opts.downloadUrl || _guessDownloadUrl(kind, opts.url, opts.path); var titleEl = document.getElementById('iarInsertedItemModalTitle'); if (titleEl) { var icon = KIND_ICONS[kind] || 'fa-paperclip'; titleEl.innerHTML = ' ' + _esc(insertedModalTitle(kind)); } var sourceEl = document.getElementById('iarInsertedItemSource'); if (sourceEl) { sourceEl.textContent = '来源:【' + owner + '】的【' + typeLab + '】'; } var typeEl = document.getElementById('iarInsertedItemType'); if (typeEl) typeEl.textContent = typeLab; var labelEl = document.getElementById('iarInsertedItemLabel'); if (labelEl) labelEl.textContent = label; var subEl = document.getElementById('iarInsertedItemSubtitle'); if (subEl) subEl.textContent = subtitle || '—'; var linkEl = document.getElementById('iarInsertedItemLink'); if (linkEl) { linkEl.href = url; linkEl.setAttribute('data-clean-href', url); linkEl.textContent = url; } var openBtn = document.getElementById('iarInsertedItemOpenBtn'); if (openBtn) { openBtn.href = url; openBtn.classList.toggle('d-none', ops.indexOf('open') < 0); } var copyBtn = document.getElementById('iarInsertedItemCopyBtn'); if (copyBtn) copyBtn.classList.toggle('d-none', ops.indexOf('copy') < 0); var dlBtn = document.getElementById('iarInsertedItemDownloadBtn'); if (dlBtn) { var canDl = ops.indexOf('download') >= 0 && !!downloadUrl; dlBtn.classList.toggle('d-none', !canDl); if (canDl) dlBtn.href = downloadUrl; } var modalEl = document.getElementById(VIEW_MODAL_ID); if (global.bootstrap && modalEl) { _stackModalOnTop(modalEl); var inst = bootstrap.Modal.getOrCreateInstance(modalEl, { backdrop: true, keyboard: true, focus: true }); inst.show(); modalEl.addEventListener('shown.bs.modal', function onShown() { modalEl.removeEventListener('shown.bs.modal', onShown); _stackModalOnTop(modalEl); }); } else if (modalEl) { modalEl.classList.add('show'); modalEl.style.display = 'block'; _stackModalOnTop(modalEl); } } function _getScope() { var sel = document.getElementById('iarInsertResourceScope'); var v = sel ? String(sel.value || '').trim() : ''; if (v === 'team' || v === 'organization' || v === 'personal') return v; return 'personal'; } function _applyTypeOptions(allowedTypes, preferred) { var typeSel = document.getElementById('iarInsertResourceType'); if (!typeSel) return; var types = (allowedTypes && allowedTypes.length) ? allowedTypes : ALL_RESOURCE_TYPES.slice(); typeSel.innerHTML = ''; types.forEach(function (t) { var opt = document.createElement('option'); opt.value = t; opt.textContent = typeLabel(t); typeSel.appendChild(opt); }); var pref = preferred && types.indexOf(preferred) >= 0 ? preferred : types[0]; if (pref) typeSel.value = pref; } function _applyScopeOptions(allowedScopes, preferred) { var scopeSel = document.getElementById('iarInsertResourceScope'); if (!scopeSel) return; var scopes = (allowedScopes && allowedScopes.length) ? allowedScopes : ALL_SCOPES.slice(); var labels = { personal: '个人资源', team: '团队资源(当前团队)', organization: '机构资源(当前机构)', }; scopeSel.innerHTML = ''; scopes.forEach(function (s) { var opt = document.createElement('option'); opt.value = s; opt.textContent = labels[s] || s; scopeSel.appendChild(opt); }); var pref = preferred && scopes.indexOf(preferred) >= 0 ? preferred : scopes[0]; if (pref) scopeSel.value = pref; } function _configurePickerUI(pickKind) { var titleEl = document.getElementById('iarInsertResourceModalTitle'); var scopeWrap = document.getElementById('iarInsertResourceScopeWrap'); var typeWrap = document.getElementById('iarInsertResourceTypeWrap'); var searchWrap = document.getElementById('iarInsertResourceSearchWrap'); var isResource = !pickKind || pickKind === 'resource'; var icon = KIND_ICONS[pickKind] || KIND_ICONS.resource; var titleText = isResource ? '插入资源' : ('插入' + typeLabel(pickKind)); if (titleEl) { titleEl.innerHTML = ' ' + _esc(titleText); } if (scopeWrap) scopeWrap.classList.toggle('d-none', !isResource); if (typeWrap) typeWrap.classList.toggle('d-none', !isResource); if (searchWrap) { searchWrap.className = isResource ? 'col-md-4' : 'col-12'; } } function _resolveTargetEl(targetId, targetEl, fieldId) { if (targetEl && targetEl.nodeType === 1) return targetEl; if (targetId) { var el = document.getElementById(targetId); if (el) return el; } if (fieldId && global.IAREntityContent) { var wrap = document.querySelector('[data-iar-content-id="' + fieldId + '"]'); if (wrap) { var fmt = wrap.getAttribute('data-iar-content-format') || 'plain'; if (fmt === 'markdown') { return document.getElementById(wrap.getAttribute('data-iar-md-id')); } if (fmt === 'rich') { return document.getElementById(wrap.getAttribute('data-iar-rich-id')); } return document.getElementById(wrap.getAttribute('data-iar-plain-id')); } } return null; } function insertText(targetIdOrEl, text) { var el = typeof targetIdOrEl === 'string' ? document.getElementById(targetIdOrEl) : targetIdOrEl; if (!el) return false; var ins = text == null ? '' : String(text); if (el.isContentEditable || (el.getAttribute && el.getAttribute('contenteditable') === 'true')) { el.focus(); try { document.execCommand('insertText', false, ins); } catch (e) { el.textContent = (el.textContent || '') + ins; } el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new CustomEvent('iar-rich-input', { bubbles: true })); return true; } if (typeof el.value === 'string' || el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') { var start = el.selectionStart != null ? el.selectionStart : el.value.length; var end = el.selectionEnd != null ? el.selectionEnd : el.value.length; var before = el.value.slice(0, start); var after = el.value.slice(end); el.value = before + ins + after; var pos = (before + ins).length; el.focus(); try { el.setSelectionRange(pos, pos); } catch (e2) { /* ignore */ } el.dispatchEvent(new Event('input', { bubbles: true })); return true; } return false; } function insertHtmlLink(targetEl, label, url, meta) { if (!targetEl) return false; var href = appendInsertMetaToUrl(url, meta); if (!(targetEl.isContentEditable || (targetEl.getAttribute && targetEl.getAttribute('contenteditable') === 'true'))) { return insertText(targetEl, buildSnippet(label, url, meta)); } targetEl.focus(); var a = document.createElement('a'); a.href = href; a.textContent = label || '链接'; a.title = encodeInsertTitle(meta); a.className = 'iar-inserted-link'; a.setAttribute('data-iar-insert-kind', meta.kind || ''); a.setAttribute('data-iar-insert-scope', meta.scope || 'personal'); a.setAttribute('data-iar-insert-owner', meta.owner || ''); a.setAttribute('data-iar-insert-type-label', meta.typeLabel || typeLabel(meta.kind)); a.setAttribute('data-iar-insert-ops', normalizeOps(meta.ops || ['view', 'open', 'copy']).join(',')); if (meta.path) a.setAttribute('data-iar-insert-path', meta.path); if (meta.subtitle) a.setAttribute('data-iar-insert-subtitle', meta.subtitle); a.setAttribute('data-iar-insert-url', href); try { var sel = global.getSelection && getSelection(); if (sel && sel.rangeCount) { var range = sel.getRangeAt(0); range.deleteContents(); range.insertNode(a); range.setStartAfter(a); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } else { targetEl.appendChild(a); } } catch (e) { targetEl.appendChild(a); } targetEl.dispatchEvent(new Event('input', { bubbles: true })); targetEl.dispatchEvent(new CustomEvent('iar-rich-input', { bubbles: true })); return true; } function _copyClipboard(text) { var t = text == null ? '' : String(text); if (global.navigator && navigator.clipboard && navigator.clipboard.writeText) { return navigator.clipboard.writeText(t).then(function () { return true; }).catch(function () { return _copyFallback(t); }); } return Promise.resolve(_copyFallback(t)); } function _copyFallback(t) { try { var ta = document.createElement('textarea'); ta.value = t; ta.setAttribute('readonly', ''); ta.style.position = 'fixed'; ta.style.left = '-9999px'; document.body.appendChild(ta); ta.select(); var ok = document.execCommand('copy'); document.body.removeChild(ta); return !!ok; } catch (e) { return false; } } async function _ensureScopeOk() { var resScope = _getScope(); if (resScope === 'team') { try { var r = await fetch('/api/current_team', { credentials: 'same-origin' }); if (!r.ok) throw new Error('未选择团队'); var d = await r.json(); if (!d.success || !d.team) throw new Error('未选择团队'); if (d.team.name) _sourceCache.team = d.team.name; } catch (e) { alert('请先在页面顶部选择「当前团队」,再插入团队资源。'); var scopeSel = document.getElementById('iarInsertResourceScope'); if (scopeSel) scopeSel.value = 'personal'; } } else if (resScope === 'organization') { try { var r2 = await fetch('/api/current_organization', { credentials: 'same-origin' }); if (!r2.ok) throw new Error('未选择机构'); var d2 = await r2.json(); if (!d2.success || !d2.organization) throw new Error('未选择机构'); if (d2.organization.name) _sourceCache.organization = d2.organization.name; } catch (e2) { alert('请先在页面顶部选择「当前机构」,再插入机构资源。'); var scopeSel2 = document.getElementById('iarInsertResourceScope'); if (scopeSel2) scopeSel2.value = 'personal'; } } } async function _loadEntityItems(kind) { var items = []; if (kind === 'paper') { var res = await fetch('/api/newpaper', { credentials: 'same-origin' }); var data = await res.json(); if (data.success && Array.isArray(data.papers)) { items = data.papers.map(function (p) { return { id: p.id, title: p.paper_title || ('论文 #' + p.id), subtitle: [p.internal_number, p.author].filter(Boolean).join(' · '), url: '/paper_writing?paper_id=' + encodeURIComponent(p.id), kind: 'paper', owner: p.owner_display || _currentUserDisplayName(), scope: 'personal', }; }); } } else if (kind === 'topic') { var resT = await fetch('/api/newproj', { credentials: 'same-origin' }); var dataT = await resT.json(); if (dataT.success && Array.isArray(dataT.projects)) { items = dataT.projects.map(function (p) { return { id: p.id, title: p.project_title || p.project_name || ('课题 #' + p.id), subtitle: [p.internal_number, p.project_level].filter(Boolean).join(' · '), url: '/proj_prps?project_id=' + encodeURIComponent(p.id), kind: 'topic', owner: _currentUserDisplayName(), scope: 'personal', }; }); } } else if (kind === 'project') { var resP = await fetch('/api/projects?scope=joined', { credentials: 'same-origin' }); var dataP = await resP.json(); if (dataP.success && Array.isArray(dataP.projects)) { items = dataP.projects.map(function (p) { return { id: p.id, title: p.project_name || ('项目 #' + p.id), subtitle: [p.project_number, p.project_status].filter(Boolean).join(' · '), url: '/projects?project_id=' + encodeURIComponent(p.id), kind: 'project', owner: p.leader_name || p.initiator_name || _currentUserDisplayName(), scope: 'organization', }; }); } } else if (kind === 'thesis') { var resTh = await fetch('/api/theses?scope=authored', { credentials: 'same-origin' }); var dataTh = await resTh.json(); if (dataTh.success && Array.isArray(dataTh.theses)) { items = dataTh.theses.map(function (t) { return { id: t.id, title: t.title || t.thesis_number || ('学位论文 #' + t.id), subtitle: [t.thesis_number, t.degree_display || t.degree].filter(Boolean).join(' · '), url: '/teaching/thesis?thesis_id=' + encodeURIComponent(t.id), kind: 'thesis', owner: t.author_name || _currentUserDisplayName(), scope: 'personal', }; }); } } return items; } async function loadList() { var pickKind = STATE.pickKind || 'resource'; STATE.items = []; STATE.selected = null; var loading = document.getElementById('iarInsertResourceLoading'); var empty = document.getElementById('iarInsertResourceEmpty'); var list = document.getElementById('iarInsertResourceList'); if (list) list.innerHTML = ''; if (empty) empty.classList.add('d-none'); if (loading) loading.classList.remove('d-none'); try { if (pickKind !== 'resource') { STATE.type = pickKind; STATE.items = await _loadEntityItems(pickKind); } else { await _ensureScopeOk(); var typeSel = document.getElementById('iarInsertResourceType'); var type = typeSel ? (typeSel.value || 'literature') : 'literature'; STATE.type = type; var sc = _getScope(); var items = []; if (type === 'platform') { var res = await fetch('/api/platform?resource_type=' + encodeURIComponent(sc), { credentials: 'same-origin' }); var data = await res.json(); if (data.success && Array.isArray(data.platforms)) { items = data.platforms.map(function (p) { return { id: p.id, title: p.name || ('平台链接 ' + p.id), subtitle: p.url || '', url: p.url || '', kind: 'platform', scope: sc, }; }); } } else if (type === 'note') { var resN = await fetch('/notes/api/notes?resource_type=' + encodeURIComponent(sc), { credentials: 'same-origin' }); var dataN = await resN.json(); if (dataN.success && Array.isArray(dataN.data)) { items = dataN.data.map(function (n) { return { id: n.id, title: n.title || ('笔记 ' + n.id), subtitle: n.descry || '', url: '/notes?scope=' + encodeURIComponent(sc) + '¬e_id=' + encodeURIComponent(n.id), kind: 'note', scope: sc, }; }); } } else { var page = type; var resF = await fetch( '/api/files?page=' + encodeURIComponent(page) + '&metadata=1&resource_type=' + encodeURIComponent(sc), { credentials: 'same-origin' } ); var dataF = await resF.json(); if (dataF.success && Array.isArray(dataF.files)) { items = dataF.files.map(function (f) { var path = typeof f === 'string' ? f : f.path || ''; var filename = typeof f === 'string' ? String(f).split('/').pop() || String(f) : f.filename || path.split('/').pop() || path; return { id: path, title: filename || path || '(未命名)', subtitle: path || '', url: '/' + page + '?scope=' + encodeURIComponent(sc), kind: page, path: path, scope: sc, }; }); } } STATE.items = items; } } catch (e) { STATE.items = []; } finally { if (loading) loading.classList.add('d-none'); renderList(); } } function renderList() { var qEl = document.getElementById('iarInsertResourceSearch'); var q = qEl && qEl.value ? qEl.value.trim().toLowerCase() : ''; var list = document.getElementById('iarInsertResourceList'); var empty = document.getElementById('iarInsertResourceEmpty'); if (!list) return; list.innerHTML = ''; var filtered = (STATE.items || []).filter(function (it) { if (!q) return true; return (it.title || '').toLowerCase().indexOf(q) >= 0 || (it.subtitle || '').toLowerCase().indexOf(q) >= 0; }); if (!filtered.length) { if (empty) empty.classList.remove('d-none'); return; } if (empty) empty.classList.add('d-none'); filtered.slice(0, 500).forEach(function (it) { var li = document.createElement('li'); li.className = 'list-group-item list-group-item-action py-2'; var isSel = STATE.selected && STATE.selected.id === it.id && STATE.selected.kind === it.kind; if (isSel) li.classList.add('active'); li.style.cursor = 'pointer'; li.innerHTML = '
' + _esc(it.title) + '
' + '
' + _esc(it.subtitle || it.url || '') + '
'; li.addEventListener('click', function () { STATE.selected = it; renderList(); }); li.addEventListener('dblclick', function () { STATE.selected = it; confirmInsert(); }); list.appendChild(li); }); } async function confirmInsert() { var it = STATE.selected; if (!it) { alert('请先选择一项'); return; } var label = it.title || '资源'; var url = it.url || ''; var kind = it.kind || STATE.type || 'literature'; var scope = it.scope || (STATE.pickKind === 'resource' ? _getScope() : 'personal'); var owner = it.owner || (await _resolveOwnerName(scope)); var meta = { kind: kind, scope: scope, owner: owner, typeLabel: typeLabel(kind), ops: _readSelectedOps(), path: it.path || '', subtitle: it.subtitle || '', }; var snippet = buildSnippet(label, url, meta); var mode = _ctx.mode || 'insert'; function done() { var modalEl = document.getElementById(MODAL_ID); if (modalEl && global.bootstrap) { var inst = bootstrap.Modal.getInstance(modalEl); if (inst) inst.hide(); } if (typeof _ctx.onInserted === 'function') { try { _ctx.onInserted(snippet, it, _ctx, meta); } catch (e) { /* ignore */ } } if (_ctx.fieldId && global.IAREntityContent) { try { IAREntityContent.syncHidden(_ctx.fieldId); } catch (e2) { /* ignore */ } } // 插入后预览可能异步渲染,稍后补强链接 data-* setTimeout(function () { try { enhanceLinks(document); } catch (e3) { /* ignore */ } }, 400); } if (mode === 'clipboard') { _copyClipboard(snippet).then(function (ok) { alert(ok ? '已复制 Markdown 链接到剪贴板' : '复制失败,请手动复制:\n' + snippet); done(); }); return; } var target = _resolveTargetEl(_ctx.targetId, _ctx.targetEl, _ctx.fieldId); if (!target) { alert('未找到可插入的编辑框'); return; } if (target.isContentEditable || (target.getAttribute && target.getAttribute('contenteditable') === 'true')) { insertHtmlLink(target, label, url, meta); } else { insertText(target, snippet); } done(); } function _bindModalEvents() { var confirmBtn = document.getElementById('iarInsertResourceConfirmBtn'); var scopeSel = document.getElementById('iarInsertResourceScope'); var typeSel = document.getElementById('iarInsertResourceType'); var searchEl = document.getElementById('iarInsertResourceSearch'); if (confirmBtn && !confirmBtn.__iarBound) { confirmBtn.__iarBound = true; confirmBtn.addEventListener('click', function () { confirmInsert(); }); } if (scopeSel && !scopeSel.__iarBound) { scopeSel.__iarBound = true; scopeSel.addEventListener('change', loadList); } if (typeSel && !typeSel.__iarBound) { typeSel.__iarBound = true; typeSel.addEventListener('change', loadList); } if (searchEl && !searchEl.__iarBound) { searchEl.__iarBound = true; searchEl.addEventListener('input', renderList); } } function open(opts) { opts = opts || {}; ensureModal(); ensureViewModal(); _ctx.targetId = opts.targetId || null; _ctx.targetEl = opts.targetEl || null; _ctx.fieldId = opts.fieldId || null; _ctx.hint = opts.hint || '编辑框'; _ctx.mode = opts.mode === 'clipboard' ? 'clipboard' : 'insert'; _ctx.onInserted = opts.onInserted || null; _ctx.pickKind = opts.pickKind || 'resource'; _ctx.allowedTypes = (opts.allowedTypes && opts.allowedTypes.length) ? opts.allowedTypes : ALL_RESOURCE_TYPES.slice(); _ctx.allowedScopes = (opts.allowedScopes && opts.allowedScopes.length) ? opts.allowedScopes : ALL_SCOPES.slice(); _ctx.allowedViewOps = (opts.allowedViewOps && opts.allowedViewOps.length) ? normalizeOps(opts.allowedViewOps) : ALL_VIEW_OPS.slice(); STATE.pickKind = _ctx.pickKind; STATE.selected = null; _configurePickerUI(_ctx.pickKind); if (_ctx.pickKind === 'resource') { _applyScopeOptions(_ctx.allowedScopes, 'personal'); _applyTypeOptions(_ctx.allowedTypes, opts.defaultType || _ctx.allowedTypes[0] || 'literature'); } _renderAllowedOpsChecks( _ctx.allowedViewOps, opts.defaultViewOps || ['view', 'open', 'copy'] ); var hintEl = document.getElementById('iarInsertResourceTargetHint'); if (hintEl) hintEl.textContent = _ctx.hint; var searchEl = document.getElementById('iarInsertResourceSearch'); if (searchEl) searchEl.value = ''; var confirmBtn = document.getElementById('iarInsertResourceConfirmBtn'); if (confirmBtn) { confirmBtn.innerHTML = _ctx.mode === 'clipboard' ? ' 复制链接' : ' 插入'; } var modalEl = document.getElementById(MODAL_ID); if (global.bootstrap && modalEl) { _stackModalOnTop(modalEl); var inst = bootstrap.Modal.getOrCreateInstance(modalEl); inst.show(); modalEl.addEventListener('shown.bs.modal', function onShown() { modalEl.removeEventListener('shown.bs.modal', onShown); _stackModalOnTop(modalEl); }); } loadList(); } function _readBtnCtx(btn) { return { fieldId: btn.getAttribute('data-iar-content-field') || null, targetId: btn.getAttribute('data-iar-insert-target') || null, hint: btn.getAttribute('data-iar-insert-hint') || '编辑框', mode: btn.getAttribute('data-iar-insert-mode') || 'insert', allowedTypes: _parseListAttr(btn.getAttribute('data-iar-allowed-types'), ALL_RESOURCE_TYPES), allowedScopes: _parseListAttr(btn.getAttribute('data-iar-allowed-scopes'), ALL_SCOPES), allowedViewOps: _parseListAttr(btn.getAttribute('data-iar-allowed-view-ops'), ALL_VIEW_OPS), }; } var IMAGE_UPLOAD_API = '/api/utils/upload-image'; var _imageUploadInput = null; var _imageInsertCtx = null; function _ensureImageUploader() { if (_imageUploadInput && document.body.contains(_imageUploadInput)) return _imageUploadInput; var input = document.createElement('input'); input.type = 'file'; input.accept = 'image/png,image/jpeg,image/jpg,image/gif,image/webp,image/bmp,.png,.jpg,.jpeg,.gif,.webp,.bmp'; input.className = 'd-none'; input.id = 'iarInsertImageUploader'; input.setAttribute('aria-hidden', 'true'); input.addEventListener('change', function () { var file = input.files && input.files[0] ? input.files[0] : null; input.value = ''; if (!file) return; uploadAndInsertImage(file, _imageInsertCtx).catch(function (err) { alert('插入图片失败:' + ((err && err.message) ? err.message : '未知错误')); }); }); document.body.appendChild(input); _imageUploadInput = input; return input; } function _normalizeUploadImageFile(file) { if (!file || !file.name) return file; var n = String(file.name); var needShort = n.length > 100 || /[?#&=]/.test(n) || /:\/\//.test(n) || /[<>:"|*]/.test(n); if (!needShort) return file; var sub = 'png'; if (file.type === 'image/jpeg' || file.type === 'image/jpg') sub = 'jpg'; else if (file.type === 'image/gif') sub = 'gif'; else if (file.type === 'image/webp') sub = 'webp'; else if (file.type === 'image/bmp') sub = 'bmp'; else if (file.type === 'image/png') sub = 'png'; else { var m = n.match(/\.([a-zA-Z0-9]{1,8})$/); if (m && /^png|jpe?g|gif|webp|bmp$/i.test(m[1])) { sub = m[1].toLowerCase().replace('jpeg', 'jpg'); } } try { return new File([file], 'img_' + Date.now() + '.' + sub, { type: file.type || ('image/' + (sub === 'jpg' ? 'jpeg' : sub)), }); } catch (e) { return file; } } function _buildImageMarkdown(url, alt) { var a = String(alt || 'image').replace(/[\[\]]/g, ''); return '![' + a + '](' + String(url || '') + ')'; } function _insertImageHtml(targetEl, url, alt) { if (!targetEl) return false; targetEl.focus(); var img = document.createElement('img'); img.src = url; img.alt = alt || 'image'; img.style.maxWidth = '100%'; try { var sel = global.getSelection && getSelection(); if (sel && sel.rangeCount) { var range = sel.getRangeAt(0); if (targetEl.contains(range.commonAncestorContainer)) { range.deleteContents(); range.insertNode(img); range.setStartAfter(img); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } else { targetEl.appendChild(img); } } else { targetEl.appendChild(img); } } catch (e) { targetEl.appendChild(img); } targetEl.dispatchEvent(new Event('input', { bubbles: true })); targetEl.dispatchEvent(new CustomEvent('iar-rich-input', { bubbles: true })); return true; } async function uploadAndInsertImage(file, ctx) { ctx = ctx || {}; file = _normalizeUploadImageFile(file); var formData = new FormData(); formData.append('image', file); var res = await fetch(IMAGE_UPLOAD_API, { method: 'POST', credentials: 'same-origin', body: formData, }); var data = await res.json().catch(function () { return {}; }); if (!res.ok || !data.success) { throw new Error((data && data.message) || ('HTTP ' + res.status)); } var url = data.data && data.data.url ? data.data.url : ''; if (!url) throw new Error('服务端未返回图片地址'); var alt = (data.data && data.data.name) ? String(data.data.name).replace(/\.[^/.]+$/, '') : 'image'; var markdown = _buildImageMarkdown(url, alt); var mode = ctx.mode || 'insert'; if (mode === 'clipboard') { var ok = await _copyClipboard(markdown); alert(ok ? '已复制图片 Markdown 到剪贴板' : ('复制失败,请手动复制:\n' + markdown)); return; } var target = _resolveTargetEl(ctx.targetId, ctx.targetEl, ctx.fieldId); if (!target) { throw new Error('未找到可插入的编辑框'); } if (target.isContentEditable || (target.getAttribute && target.getAttribute('contenteditable') === 'true')) { _insertImageHtml(target, url, alt); } else { insertText(target, markdown + '\n'); } if (ctx.fieldId && global.IAREntityContent) { try { IAREntityContent.syncHidden(ctx.fieldId); } catch (e2) { /* ignore */ } } } function triggerImageUpload(ctx) { _imageInsertCtx = ctx || {}; var input = _ensureImageUploader(); input.value = ''; input.click(); } function _bindToolbars(root) { var scope = root && root.querySelectorAll ? root : document; scope.querySelectorAll('[data-iar-insert-resource-btn]').forEach(function (btn) { if (btn.__iarInsertBound) return; btn.__iarInsertBound = true; btn.addEventListener('click', function () { var ctx = _readBtnCtx(btn); open({ fieldId: ctx.fieldId, targetId: ctx.targetId, hint: ctx.hint, mode: ctx.mode, pickKind: 'resource', allowedTypes: ctx.allowedTypes, allowedScopes: ctx.allowedScopes, allowedViewOps: ctx.allowedViewOps, }); }); }); scope.querySelectorAll('[data-iar-insert-entity-btn]').forEach(function (btn) { if (btn.__iarEntityBound) return; btn.__iarEntityBound = true; btn.addEventListener('click', function () { var kind = btn.getAttribute('data-iar-insert-entity-btn'); if (!kind) return; var ctx = _readBtnCtx(btn); open({ fieldId: ctx.fieldId, targetId: ctx.targetId, hint: ctx.hint, mode: ctx.mode, pickKind: kind, allowedScopes: ctx.allowedScopes, allowedViewOps: ctx.allowedViewOps, }); }); }); scope.querySelectorAll('[data-iar-insert-image-btn]').forEach(function (btn) { if (btn.__iarImageBound) return; btn.__iarImageBound = true; btn.addEventListener('click', function () { triggerImageUpload(_readBtnCtx(btn)); }); }); } function _bindInsertedLinkClicks() { if (document.__iarInsertedLinkBound) return; document.__iarInsertedLinkBound = true; document.addEventListener('click', function (e) { var a = e.target && e.target.closest ? e.target.closest('a') : null; if (!a) return; // 查看对话框内「打开链接」按钮不拦截 if (a.id === 'iarInsertedItemLink' || a.id === 'iarInsertedItemOpenBtn' || a.id === 'iarInsertedItemDownloadBtn') return; if (a.closest && a.closest('#' + VIEW_MODAL_ID + ' .modal-footer')) return; var meta = parseInsertFromAnchor(a); if (!meta || !meta.kind) return; e.preventDefault(); e.stopPropagation(); if (typeof e.stopImmediatePropagation === 'function') e.stopImmediatePropagation(); openInsertedViewer({ kind: meta.kind, typeLabel: meta.typeLabel || typeLabel(meta.kind), owner: meta.owner || '未知', label: (a.textContent || '').trim() || '(未命名)', subtitle: a.getAttribute('data-iar-insert-subtitle') || '', path: a.getAttribute('data-iar-insert-path') || meta.path || '', ops: meta.ops, url: a.getAttribute('data-iar-insert-url') || a.getAttribute('href') || '#', downloadUrl: a.getAttribute('data-iar-insert-download') || '', }); }, true); } /** 为预览/查看区中的插入链接补充 data-*,便于点击识别 */ function enhanceLinks(root) { var scope = root && root.querySelectorAll ? root : document; var anchors = scope.querySelectorAll ? scope.querySelectorAll('a[href], a[title]') : []; anchors.forEach(function (a) { var meta = parseInsertFromAnchor(a); if (!meta || !meta.kind) { // 兼容仅 title 含 iar|、但尚未写入 data 的情况 meta = parseInsertTitle(a.getAttribute('title') || ''); } if (!meta || !meta.kind) return; a.classList.add('iar-inserted-link'); a.setAttribute('data-iar-insert-kind', meta.kind); a.setAttribute('data-iar-insert-scope', meta.scope || 'personal'); a.setAttribute('data-iar-insert-owner', meta.owner || ''); a.setAttribute('data-iar-insert-type-label', meta.typeLabel || typeLabel(meta.kind)); a.setAttribute('data-iar-insert-ops', (meta.ops || normalizeOps(['view', 'open', 'copy'])).join(',')); if (meta.path) a.setAttribute('data-iar-insert-path', meta.path); if (!a.getAttribute('data-iar-insert-url')) { a.setAttribute('data-iar-insert-url', a.getAttribute('href') || ''); } if (!a.getAttribute('title') || String(a.getAttribute('title')).indexOf('iar|') < 0) { a.setAttribute('title', encodeInsertTitle(meta)); } }); } function initAll(root) { ensureModal(); ensureViewModal(); _bindToolbars(root || document); _bindInsertedLinkClicks(); } if (typeof document !== 'undefined') { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { initAll(document); }); } else { initAll(document); } } global.IARInsertResource = { KIND_LABELS: KIND_LABELS, ALL_RESOURCE_TYPES: ALL_RESOURCE_TYPES, ALL_VIEW_OPS: ALL_VIEW_OPS, ensureModal: ensureModal, ensureViewModal: ensureViewModal, open: open, openInsertedViewer: openInsertedViewer, insertText: insertText, buildSnippet: buildSnippet, parseInsertTitle: parseInsertTitle, parseInsertFromHref: parseInsertFromHref, parseInsertFromAnchor: parseInsertFromAnchor, encodeInsertTitle: encodeInsertTitle, appendInsertMetaToUrl: appendInsertMetaToUrl, normalizeOps: normalizeOps, typeLabel: typeLabel, insertedModalTitle: insertedModalTitle, enhanceLinks: enhanceLinks, triggerImageUpload: triggerImageUpload, uploadAndInsertImage: uploadAndInsertImage, initAll: initAll, }; })(typeof window !== 'undefined' ? window : this);