/**
* 统一目录操作(Tab 单树 / 多列布局),业务页默认 tabsMode 单树。
*/
(function (global) {
'use strict';
const _registry = {};
const _lastOpenEntityByOps = {};
const _COPY_ENTITY_STORE_KEY = 'iar_dir_ops_entity:';
/** 拍照:打开相机弹窗前暂存上传目标 */
const _pendingPhotoByOps = {};
/** getUserMedia 拍照弹窗(单例,叠在目录操作对话框之上);支持连拍与多选 */
var _cameraUi = {
stream: null,
/** @type {{ blob: Blob, url: string }[]} */
photos: [],
bound: false,
activeOpsId: null,
};
function _resolveGetUserMedia() {
var media = navigator.mediaDevices;
if (media && typeof media.getUserMedia === 'function') {
return function (constraints) { return media.getUserMedia(constraints); };
}
var legacy = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
if (!legacy) return null;
return function (constraints) {
return new Promise(function (resolve, reject) {
legacy.call(navigator, constraints, resolve, reject);
});
};
}
function _cameraEls() {
return {
modal: document.getElementById('iarDirOpsCameraModal'),
video: document.getElementById('iarDirOpsCameraVideo'),
canvas: document.getElementById('iarDirOpsCameraCanvas'),
previewList: document.getElementById('iarDirOpsCameraPreviewList'),
message: document.getElementById('iarDirOpsCameraMessage'),
openBtn: document.getElementById('iarDirOpsCameraOpen'),
takeBtn: document.getElementById('iarDirOpsCameraTake'),
closeCamBtn: document.getElementById('iarDirOpsCameraCloseCam'),
chooseBtn: document.getElementById('iarDirOpsCameraChoose'),
chooseInput: document.getElementById('iarDirOpsCameraChooseInput'),
clearBtn: document.getElementById('iarDirOpsCameraClear'),
saveBtn: document.getElementById('iarDirOpsCameraSave'),
cancelBtn: document.getElementById('iarDirOpsCameraCancel'),
targetHint: document.getElementById('iarDirOpsCameraTargetHint'),
};
}
function _setCameraMessage(text) {
var el = document.getElementById('iarDirOpsCameraMessage');
if (el) el.textContent = text || '';
}
function _updateCameraSaveUi() {
var els = _cameraEls();
var n = (_cameraUi.photos || []).length;
if (els.saveBtn) {
els.saveBtn.disabled = n < 1;
els.saveBtn.textContent = n > 0 ? ('保存到目录(' + n + ' 张)') : '保存到目录';
}
if (els.clearBtn) {
els.clearBtn.disabled = n < 1;
els.clearBtn.hidden = false;
}
}
function _stopCameraStream() {
if (_cameraUi.stream) {
try {
_cameraUi.stream.getTracks().forEach(function (t) { t.stop(); });
} catch (e) { /* ignore */ }
_cameraUi.stream = null;
}
var els = _cameraEls();
if (els.video) els.video.srcObject = null;
if (els.takeBtn) els.takeBtn.disabled = true;
if (els.closeCamBtn) els.closeCamBtn.disabled = true;
}
function _clearCameraPhotos() {
(_cameraUi.photos || []).forEach(function (item) {
if (item && item.url) {
try { URL.revokeObjectURL(item.url); } catch (e) { /* ignore */ }
}
});
_cameraUi.photos = [];
var els = _cameraEls();
if (els.previewList) els.previewList.innerHTML = '';
_updateCameraSaveUi();
}
function _renderCameraPreviewList() {
var els = _cameraEls();
if (!els.previewList) return;
els.previewList.innerHTML = '';
(_cameraUi.photos || []).forEach(function (item, idx) {
var card = document.createElement('div');
card.className = 'position-relative border rounded overflow-hidden bg-light';
card.style.cssText = 'width:96px;height:96px;flex:0 0 auto;';
var img = document.createElement('img');
img.src = item.url;
img.alt = '预览 ' + (idx + 1);
img.style.cssText = 'width:100%;height:100%;object-fit:cover;display:block;';
var rm = document.createElement('button');
rm.type = 'button';
rm.className = 'btn btn-sm btn-danger position-absolute top-0 end-0 p-0';
rm.style.cssText = 'width:22px;height:22px;line-height:1;font-size:12px;opacity:0.9;';
rm.setAttribute('aria-label', '移除');
rm.innerHTML = '×';
rm.addEventListener('click', function () {
_removeCameraPhotoAt(idx);
});
card.appendChild(img);
card.appendChild(rm);
els.previewList.appendChild(card);
});
_updateCameraSaveUi();
}
function _removeCameraPhotoAt(index) {
var item = _cameraUi.photos[index];
if (!item) return;
if (item.url) {
try { URL.revokeObjectURL(item.url); } catch (e) { /* ignore */ }
}
_cameraUi.photos.splice(index, 1);
_renderCameraPreviewList();
var n = _cameraUi.photos.length;
_setCameraMessage(n ? ('已选 ' + n + ' 张,可继续拍照或选择图片。') : '已清空预览,可重新拍照或选择图片。');
}
function _addCameraPhotos(blobs) {
var list = Array.isArray(blobs) ? blobs : (blobs ? [blobs] : []);
list.forEach(function (blob) {
if (!blob) return;
var url = URL.createObjectURL(blob);
_cameraUi.photos.push({ blob: blob, url: url });
});
_renderCameraPreviewList();
var n = _cameraUi.photos.length;
_setCameraMessage(
n
? ('已准备 ' + n + ' 张,可继续连拍或再选图片,完成后点击「保存到目录」。')
: '请拍照或选择图片。'
);
}
function _upgradeCameraModalDom(modal) {
if (!modal) return;
var input = modal.querySelector('#iarDirOpsCameraChooseInput');
if (input) {
input.setAttribute('multiple', 'multiple');
input.removeAttribute('capture');
}
var chooseBtn = modal.querySelector('#iarDirOpsCameraChoose');
if (chooseBtn) {
chooseBtn.innerHTML = '选择图片(可多选)';
}
var oldPreview = modal.querySelector('#iarDirOpsCameraPreview');
if (oldPreview && oldPreview.parentNode) {
var list = document.createElement('div');
list.id = 'iarDirOpsCameraPreviewList';
list.className = 'd-flex flex-wrap gap-2 mt-2';
list.setAttribute('aria-label', '已选照片预览');
oldPreview.parentNode.replaceChild(list, oldPreview);
}
if (!modal.querySelector('#iarDirOpsCameraPreviewList')) {
var body = modal.querySelector('.modal-body');
if (body) {
var list2 = document.createElement('div');
list2.id = 'iarDirOpsCameraPreviewList';
list2.className = 'd-flex flex-wrap gap-2 mt-2';
body.appendChild(list2);
}
}
if (!modal.querySelector('#iarDirOpsCameraClear')) {
var toolbar = modal.querySelector('.modal-body .d-flex.flex-wrap.gap-2');
if (toolbar) {
var clearBtn = document.createElement('button');
clearBtn.type = 'button';
clearBtn.className = 'btn btn-sm btn-outline-danger';
clearBtn.id = 'iarDirOpsCameraClear';
clearBtn.disabled = true;
clearBtn.innerHTML = '清空预览';
toolbar.appendChild(clearBtn);
}
}
var hint = modal.querySelector('.modal-body .form-text');
if (hint) {
hint.textContent =
'可连拍多张或一次多选相册图片;手机/电脑均可。若无法调用相机(需 HTTPS 或 localhost),请使用「选择图片(可多选)」。';
}
}
function _ensureCameraModal() {
var existing = document.getElementById('iarDirOpsCameraModal');
if (existing) {
_upgradeCameraModalDom(existing);
_bindCameraModalOnce();
return;
}
var wrap = document.createElement('div');
wrap.innerHTML =
'
' +
'
' +
'
' +
'' +
'
' +
'
' +
'
' +
'' +
'' +
'' +
'' +
'' +
'' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
可连拍多张或一次多选相册图片;手机/电脑均可。若无法调用相机(需 HTTPS 或 localhost),请使用「选择图片(可多选)」。
' +
'
' +
'' +
'
';
document.body.appendChild(wrap.firstChild);
_bindCameraModalOnce();
}
function _bindCameraClearBtn(els) {
if (!els || !els.clearBtn || els.clearBtn.getAttribute('data-iar-bound') === '1') return;
els.clearBtn.setAttribute('data-iar-bound', '1');
els.clearBtn.addEventListener('click', function () {
_clearCameraPhotos();
_setCameraMessage('已清空预览,可重新拍照或选择图片。');
});
}
function _bindCameraModalOnce() {
var els = _cameraEls();
if (!els.modal) return;
// 升级旧 DOM 后补绑「清空」按钮
_bindCameraClearBtn(els);
if (_cameraUi.bound) return;
_cameraUi.bound = true;
els.openBtn.addEventListener('click', async function () {
var getUserMedia = _resolveGetUserMedia();
if (!getUserMedia) {
_setCameraMessage('当前环境无法调用相机,请使用 HTTPS / localhost 访问,或点击「选择图片(可多选)」。');
return;
}
els.openBtn.disabled = true;
_stopCameraStream();
_setCameraMessage('正在打开相机,请允许摄像头访问…');
try {
_cameraUi.stream = await getUserMedia({
audio: false,
video: {
facingMode: { ideal: 'environment' },
width: { ideal: 1920 },
height: { ideal: 1080 },
},
});
els.video.srcObject = _cameraUi.stream;
els.video.style.display = 'block';
await els.video.play();
els.takeBtn.disabled = false;
els.closeCamBtn.disabled = false;
var n = (_cameraUi.photos || []).length;
_setCameraMessage(
n
? ('相机已打开,可继续连拍(已有 ' + n + ' 张)。')
: '相机已打开,请点击「拍照」;可连续拍摄多张。'
);
} catch (error) {
_stopCameraStream();
if (els.video) els.video.style.display = 'none';
var tips = {
NotAllowedError: '相机访问未获允许,请检查浏览器权限;手机远程访问需使用 HTTPS。',
NotFoundError: '未找到可用摄像头。',
NotReadableError: '无法读取摄像头,可能被其他程序占用。',
SecurityError: '当前页面不是安全上下文,无法调用相机,请使用 HTTPS 或选择图片。',
};
_setCameraMessage(tips[error && error.name] || ('打开相机失败:' + ((error && error.message) || error)));
} finally {
els.openBtn.disabled = false;
}
});
els.takeBtn.addEventListener('click', function () {
if (!els.video.videoWidth || !els.video.videoHeight) {
_setCameraMessage('相机画面尚未准备好,请稍后重试。');
return;
}
els.canvas.width = els.video.videoWidth;
els.canvas.height = els.video.videoHeight;
els.canvas.getContext('2d').drawImage(els.video, 0, 0);
els.canvas.toBlob(function (blob) {
if (!blob) {
_setCameraMessage('拍照失败,请重试。');
return;
}
// 连拍:加入预览列表,保持相机开启以便继续拍
_addCameraPhotos([blob]);
}, 'image/jpeg', 0.92);
});
els.closeCamBtn.addEventListener('click', function () {
_stopCameraStream();
if (els.video) els.video.style.display = 'none';
var n = (_cameraUi.photos || []).length;
_setCameraMessage(n ? ('相机已关闭,已有 ' + n + ' 张待保存。') : '相机已关闭。');
});
els.chooseBtn.addEventListener('click', function () {
els.chooseInput.value = '';
els.chooseInput.click();
});
els.chooseInput.addEventListener('change', function () {
var files = els.chooseInput.files;
if (!files || !files.length) return;
var imgs = [];
for (var i = 0; i < files.length; i++) {
if (files[i] && String(files[i].type || '').indexOf('image/') === 0) {
imgs.push(files[i]);
} else if (files[i]) {
imgs.push(files[i]);
}
}
if (!imgs.length) return;
// 选图时不必关相机;若用户只想从相册选,可自行关相机
_addCameraPhotos(imgs);
});
_bindCameraClearBtn(els);
els.saveBtn.addEventListener('click', function () {
var opsId = _cameraUi.activeOpsId;
var photos = (_cameraUi.photos || []).map(function (p) { return p.blob; }).filter(Boolean);
if (!opsId || !photos.length) return;
var inst = _registry[opsId];
if (!inst || typeof inst.completeTakePhoto !== 'function') {
_setCameraMessage('目录操作未就绪,请关闭后重试。');
return;
}
els.saveBtn.disabled = true;
_setCameraMessage('正在保存 ' + photos.length + ' 张到目录…');
try {
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
bootstrap.Modal.getOrCreateInstance(els.modal).hide();
}
} catch (e) { /* ignore */ }
inst.completeTakePhoto(photos);
});
els.modal.addEventListener('shown.bs.modal', function () {
// 叠在「目录操作」对话框之上
els.modal.style.zIndex = '1065';
var backs = document.querySelectorAll('.modal-backdrop');
if (backs.length) {
backs[backs.length - 1].style.zIndex = '1060';
}
});
els.modal.addEventListener('hidden.bs.modal', function () {
_stopCameraStream();
_clearCameraPhotos();
_cameraUi.activeOpsId = null;
if (els.video) els.video.style.display = 'none';
_setCameraMessage('');
if (els.openBtn) els.openBtn.disabled = false;
});
window.addEventListener('pagehide', function () {
_stopCameraStream();
_clearCameraPhotos();
});
}
function _openCameraModal(opsId, targetPath) {
_ensureCameraModal();
var els = _cameraEls();
if (!els.modal) {
alert('无法打开拍照窗口');
return;
}
_cameraUi.activeOpsId = opsId;
_stopCameraStream();
_clearCameraPhotos();
if (els.video) els.video.style.display = 'none';
if (els.targetHint) {
els.targetHint.textContent = targetPath
? ('保存目录:' + targetPath)
: '请确认已选中目标目录。';
}
_setCameraMessage('可打开相机连拍多张,或一次多选相册图片,再保存到目录。');
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
bootstrap.Modal.getOrCreateInstance(els.modal).show();
} else {
els.modal.style.display = 'block';
els.modal.classList.add('show');
}
}
/** Windows 非法字符 <>:"/\\|?* 替换为下划线,与后端 sanitize_fs_name 一致 */
function sanitizeFsName(name) {
let s = String(name == null ? '' : name).replace(/[\x00-\x1f]/g, '');
s = s.replace(/[<>:"/\\|?*]/g, '_').replace(/^[\s.]+|[\s.]+$/g, '');
return s || '未命名';
}
function _rememberOpenEntity(opsId, entityId) {
const id = String(entityId || '').trim();
if (!opsId || !id) return;
_lastOpenEntityByOps[opsId] = id;
try {
sessionStorage.setItem(_COPY_ENTITY_STORE_KEY + opsId, id);
} catch (e) { /* ignore */ }
}
function resolveCopyTargetEntityId(opsId, cfg) {
if (!opsId) return '';
const c = cfg || (_registry[opsId] && _registry[opsId].cfg);
if (!c) return '';
let id = '';
if (typeof c.getEntityId === 'function') {
id = String(c.getEntityId() || '').trim();
}
if (!id && c.entityIdInputId) {
const el = document.getElementById(c.entityIdInputId);
id = el ? String(el.value || '').trim() : '';
}
if (!id && _lastOpenEntityByOps[opsId]) {
id = String(_lastOpenEntityByOps[opsId]).trim();
}
if (!id) {
try {
const stored = sessionStorage.getItem(_COPY_ENTITY_STORE_KEY + opsId);
if (stored) id = String(stored).trim();
} catch (e) { /* ignore */ }
}
return id;
}
const DEFAULT_FEATURES = {
wps: true,
backup: true,
dirStructure: true,
presetRename: true,
};
function createInstance(cfg) {
const features = Object.assign({}, DEFAULT_FEATURES, cfg.features || {});
const apiParamKey = cfg.apiParamKey || 'subdir';
const pathBasedMode = apiParamKey === 'path' && cfg.pathBasedMode !== false;
const ceKey = cfg.crossEntityField;
const clipColField = cfg.columnClipboardField || ('from_' + apiParamKey);
const toParamField = 'to_' + apiParamKey;
const fromParamField = 'from_' + apiParamKey;
const tabsMode = !!cfg.tabsMode;
const columns = cfg.columns || [];
const listIdToKey = {};
const keyToColumn = {};
const sharedListId = cfg.fileListId || null;
columns.forEach(function (col) {
if (tabsMode && sharedListId) col.listId = sharedListId;
listIdToKey[col.listId] = col.key;
keyToColumn[col.key] = col;
});
const rootListIds = tabsMode && sharedListId
? [sharedListId]
: columns.map(function (c) { return c.listId; });
const rootUlSelector = rootListIds.map(function (id) { return '#' + id; }).join(', ');
let filesData = {};
let activeColumnKey = columns.length ? columns[0].key : null;
/** HTML 会把属性名小写化;驼峰 prefix 时用大小写不敏感读取 */
function _getSubdirAttr(el) {
if (!el || !cfg.subdirDataAttr) return '';
let v = el.getAttribute(cfg.subdirDataAttr);
if (v != null && String(v) !== '') return String(v);
const want = String(cfg.subdirDataAttr).toLowerCase();
if (!el.attributes) return '';
for (let i = 0; i < el.attributes.length; i++) {
const a = el.attributes[i];
if (a && String(a.name || '').toLowerCase() === want) {
return a.value != null ? String(a.value) : '';
}
}
return '';
}
function _subdirTabButtons(tabs) {
if (!tabs) return [];
let list = cfg.subdirTabClass
? tabs.querySelectorAll('.' + cfg.subdirTabClass)
: null;
if (!list || !list.length) {
list = tabs.querySelectorAll('button.nav-link, .nav-link[data-bs-toggle], [role="tab"]');
}
return list || [];
}
function _markTabsActiveSubdir(tabs, colKey) {
if (!tabs) return;
if (colKey) tabs.setAttribute('data-active-subdir', colKey);
else tabs.removeAttribute('data-active-subdir');
}
function _readActiveSubdirFromDom() {
if (!tabsMode || !cfg.subdirTabsId) return '';
const tabs = _qs(cfg.subdirTabsId);
if (!tabs) return '';
// 优先读 switchSubdir 写入的标记,避免仅依赖 .active 类时落到首个选项卡
const marked = String(tabs.getAttribute('data-active-subdir') || '').trim();
if (marked && keyToColumn[marked]) return marked;
const buttons = _subdirTabButtons(tabs);
for (let i = 0; i < buttons.length; i++) {
const btn = buttons[i];
if (!btn || !btn.classList || !btn.classList.contains('active')) continue;
const sd = _getSubdirAttr(btn);
if (sd && keyToColumn[sd]) return sd;
}
return '';
}
function _syncSubdirTabs(colKey) {
if (!tabsMode || !cfg.subdirTabsId) return;
const tabs = _qs(cfg.subdirTabsId);
if (!tabs) return;
const target = colKey || (columns[0] ? columns[0].key : '');
_markTabsActiveSubdir(tabs, target);
const buttons = _subdirTabButtons(tabs);
for (let i = 0; i < buttons.length; i++) {
const btn = buttons[i];
const sd = _getSubdirAttr(btn);
if (sd === target) {
btn.classList.add('active');
btn.setAttribute('aria-selected', 'true');
} else {
btn.classList.remove('active');
btn.setAttribute('aria-selected', 'false');
}
}
}
function switchSubdir(colKey) {
if (!tabsMode) return;
if (colKey != null && typeof colKey !== 'string') colKey = null;
const nextKey = colKey || _readActiveSubdirFromDom() || (columns[0] ? columns[0].key : null);
if (dirLastFocus && dirLastFocus.columnKey && dirLastFocus.columnKey !== nextKey) {
dirLastFocus = null;
}
activeColumnKey = nextKey;
if (sharedListId) listIdToKey[sharedListId] = activeColumnKey;
_syncSubdirTabs(activeColumnKey);
_renderColumn(activeColumnKey);
_updateSelectedPathDisplay(activeColumnKey);
}
let dirLastFocus = null;
/** 刷新时保存各树滚动位置:{ listId: { top, left } } */
let pendingTreeScroll = null;
/** 重载前保存各列已展开目录:{ colKey: string[] } */
let pendingExpandedByCol = null;
let directoryClipboard = null;
function _qs(id) { return document.getElementById(id); }
function _entityId() {
if (typeof cfg.getEntityId === 'function') {
const fromFn = String(cfg.getEntityId() || '').trim();
if (fromFn) return fromFn;
}
if (cfg.entityIdInputId) {
const el = _qs(cfg.entityIdInputId);
const fromInput = el ? String(el.value || '').trim() : '';
if (fromInput) return fromInput;
}
return resolveCopyTargetEntityId(cfg.opsId, cfg);
}
function _filesApi(entityId) {
return cfg.apiFiles(entityId);
}
function _listApi(entityId) {
if (typeof cfg.apiListUrl === 'function') {
return cfg.apiListUrl(entityId);
}
return _filesApi(entityId);
}
function _urlWithRoot(url) {
if (typeof cfg.apiBodyExtra !== 'function') return url;
const extra = cfg.apiBodyExtra();
const root = extra && extra.root;
if (!root) return url;
const sep = url.indexOf('?') >= 0 ? '&' : '?';
return url + sep + 'root=' + encodeURIComponent(root);
}
function _resolveColKey(colKey) {
if (colKey && typeof colKey === 'string') return colKey;
// Tab 布局:优先用 switchSubdir 维护的内存态,再回退 DOM 标记 / .active
// (旧逻辑优先读 .active,若同步失败会一直落到第一个选项卡)
if (tabsMode) {
if (activeColumnKey && keyToColumn[activeColumnKey]) {
return activeColumnKey;
}
const fromDom = _readActiveSubdirFromDom();
if (fromDom) {
activeColumnKey = fromDom;
if (sharedListId) listIdToKey[sharedListId] = activeColumnKey;
return fromDom;
}
}
return activeColumnKey || (columns[0] ? columns[0].key : null);
}
function _col(key) {
return keyToColumn[key] || null;
}
function _apiParamValue(colKey) {
colKey = _resolveColKey(colKey);
const col = _col(colKey);
if (!col) return colKey;
if (col.apiParamValue != null) return col.apiParamValue;
if (typeof cfg.apiParamValue === 'function') return cfg.apiParamValue(colKey, col);
return colKey;
}
function _guardWrite() {
if (typeof cfg.guardWrite === 'function' && cfg.guardWrite() === false) return false;
return true;
}
function _paramBody(colKey, path, extra) {
const body = Object.assign({}, extra || {});
colKey = _resolveColKey(colKey);
if (typeof cfg.apiBodyExtra === 'function') {
Object.assign(body, cfg.apiBodyExtra());
}
if (pathBasedMode) {
if (path !== undefined && path !== null && String(path).trim() !== '') {
body.path = path;
} else {
body.path = _apiParamValue(colKey);
}
} else {
body[apiParamKey] = _apiParamValue(colKey);
if (path !== undefined) body.path = path;
}
return body;
}
function _uploadParentPath(colKey, parentPath, toRoot) {
if (pathBasedMode) {
if (toRoot) return _apiParamValue(colKey);
return parentPath || _apiParamValue(colKey);
}
return parentPath || '';
}
function _copyText(text) {
if (typeof global.copyTextToClipboard === 'function') {
return global.copyTextToClipboard(text);
}
return navigator.clipboard.writeText(String(text || ''));
}
function escapeHtml(s) {
if (s == null) return '';
const div = document.createElement('div');
div.textContent = s;
return div.innerHTML;
}
function showCopyMessage(message) {
const el = document.createElement('div');
el.className = cfg.toastClass;
el.textContent = message;
document.body.appendChild(el);
setTimeout(function () { el.remove(); }, 2000);
}
function _rootUlFromLi(li) {
let rootUl = li ? li.closest('ul') : null;
while (rootUl && rootUl.parentElement) {
if (listIdToKey[rootUl.id]) return rootUl;
const parentUl = rootUl.parentElement.closest('ul');
if (!parentUl) break;
rootUl = parentUl;
}
return null;
}
function _columnKeyFromLi(li) {
const rootUl = _rootUlFromLi(li);
return rootUl ? listIdToKey[rootUl.id] : null;
}
function _otherRootUls(exceptUl) {
if (tabsMode) return [];
return rootListIds.map(function (id) { return _qs(id); })
.filter(function (ul) { return ul && ul !== exceptUl; });
}
function _updateSelectedPathDisplay(colKey) {
if (!cfg.selectedPathElId) return;
const el = _qs(cfg.selectedPathElId);
if (!el) return;
const key = _resolveColKey(colKey);
const items = getSelectedFiles(key);
if (!items.length) {
el.textContent = '-';
return;
}
const last = items[items.length - 1];
const p = last.path ? String(last.path).replace(/\\/g, '/') : '';
const n = items.length;
el.textContent = (n > 1 ? ('已选 ' + n + ' 项,末项:') : '') + p;
}
function _syncSelectionFromTree(selected, primary, rootUl) {
if (rootUl && listIdToKey[rootUl.id]) {
activeColumnKey = listIdToKey[rootUl.id];
}
_rememberDirFocusFromSelection();
_updateSelectedPathDisplay(activeColumnKey);
}
function _treeClick(e, li) {
const rootUl = _rootUlFromLi(li);
if (!rootUl || !global.IARDirTreeMultiSelect) return;
IARDirTreeMultiSelect.handleClick(e, li, rootUl, {
clearOtherRoots: _otherRootUls(rootUl),
onChange: _syncSelectionFromTree,
});
}
function _parseFilesData(data) {
if (typeof cfg.parseFilesData === 'function') {
return cfg.parseFilesData(data);
}
if (cfg.dataKeys) {
const out = {};
columns.forEach(function (col) {
const dk = cfg.dataKeys[col.key];
out[col.key] = dk ? (data[dk] || []) : [];
});
return out;
}
if (data.files) return data.files;
const out = {};
columns.forEach(function (col) {
out[col.key] = data[col.key] || [];
});
return out;
}
function _ancestorDirPaths(relPath) {
const parts = String(relPath || '').replace(/\\/g, '/').split('/').filter(Boolean);
const out = [];
let prefix = '';
for (let i = 0; i < parts.length - 1; i++) {
prefix = prefix ? prefix + '/' + parts[i] : parts[i];
out.push(prefix);
}
return out;
}
function _applyDirFocusMeta(focus) {
if (!focus || !focus.path) return;
focus.path = String(focus.path).replace(/\\/g, '/');
focus.expandPaths = _ancestorDirPaths(focus.path);
}
function _setDirLastFocus(columnKey, path) {
if (!columnKey || !path) return;
dirLastFocus = { columnKey: columnKey, path: String(path).replace(/\\/g, '/') };
_applyDirFocusMeta(dirLastFocus);
}
function _captureExpandedPaths() {
var map = {};
function captureCol(colKey, listId) {
if (!colKey || !listId || !global.IARDirTreeView) return;
var ul = _qs(listId);
if (!ul) return;
var set = IARDirTreeView.collectExpandedPaths(ul);
if (set && set.size) map[colKey] = Array.from(set);
}
if (tabsMode) {
var key = activeColumnKey || (columns[0] && columns[0].key);
var listId = sharedListId || (columns[0] && columns[0].listId);
captureCol(key, listId);
} else {
columns.forEach(function (col) { captureCol(col.key, col.listId); });
}
pendingExpandedByCol = map;
}
function _mergeExpandedIntoFocus(colKey, ul) {
if (!dirLastFocus || !colKey || !ul || !global.IARDirTreeView) return;
if (dirLastFocus.columnKey !== colKey) return;
if (!Array.isArray(dirLastFocus.expandPaths)) dirLastFocus.expandPaths = [];
var seen = {};
dirLastFocus.expandPaths.forEach(function (p) { seen[p] = true; });
IARDirTreeView.collectExpandedPaths(ul).forEach(function (p) {
if (!seen[p]) {
seen[p] = true;
dirLastFocus.expandPaths.push(p);
}
});
}
function _rememberDirFocusFromSelection() {
const colKey = activeColumnKey;
if (!colKey) return;
const col = _col(colKey);
if (!col) return;
const ul = _qs(col.listId);
if (!ul || !global.IARDirTreeMultiSelect) return;
const primary = IARDirTreeMultiSelect.getPrimaryLi(ul);
if (!primary) {
if (dirLastFocus && dirLastFocus.columnKey && dirLastFocus.columnKey !== colKey) {
dirLastFocus = null;
}
return;
}
const path = (primary.getAttribute('data-path') || '').trim();
if (!path) return;
_setDirLastFocus(colKey, path);
_mergeExpandedIntoFocus(colKey, ul);
}
function _findTreeScrollParent(el) {
var node = el && el.parentElement;
while (node && node !== document.documentElement) {
var style = window.getComputedStyle(node);
var oy = style.overflowY;
var ox = style.overflowX;
if (oy === 'auto' || oy === 'scroll' || oy === 'overlay' ||
ox === 'auto' || ox === 'scroll' || ox === 'overlay') {
return node;
}
node = node.parentElement;
}
return null;
}
function _captureTreeScroll() {
var map = {};
function captureList(listId) {
if (!listId) return;
var ul = _qs(listId);
if (!ul) return;
var sp = _findTreeScrollParent(ul);
if (!sp) return;
map[listId] = { top: sp.scrollTop, left: sp.scrollLeft };
}
if (tabsMode) {
captureList(sharedListId || (columns[0] && columns[0].listId));
} else {
columns.forEach(function (col) { captureList(col.listId); });
}
pendingTreeScroll = map;
}
function _restoreTreeScroll() {
if (!pendingTreeScroll) return;
var map = pendingTreeScroll;
pendingTreeScroll = null;
function apply() {
Object.keys(map).forEach(function (listId) {
var ul = _qs(listId);
if (!ul) return;
var sp = _findTreeScrollParent(ul);
if (!sp) return;
var s = map[listId];
if (!s) return;
sp.scrollTop = s.top;
sp.scrollLeft = s.left;
});
}
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(function () { requestAnimationFrame(apply); });
} else {
setTimeout(apply, 0);
}
}
function _restoreDirFocus() {
var keepScroll = !!pendingTreeScroll;
if (!dirLastFocus) {
if (keepScroll) _restoreTreeScroll();
return;
}
const colKey = dirLastFocus.columnKey;
const targetPath = dirLastFocus.path;
if (!colKey || !targetPath) {
if (keepScroll) _restoreTreeScroll();
return;
}
if (tabsMode && colKey !== activeColumnKey) {
if (keepScroll) _restoreTreeScroll();
return;
}
if (tabsMode) {
if (sharedListId) listIdToKey[sharedListId] = activeColumnKey;
_syncSubdirTabs(activeColumnKey);
}
const col = _col(colKey);
if (!col) {
if (keepScroll) _restoreTreeScroll();
return;
}
const ul = _qs(col.listId);
if (!ul) {
if (keepScroll) _restoreTreeScroll();
return;
}
if (global.IARDirTreeView) {
(dirLastFocus.expandPaths || []).forEach(function (prefix) {
const folderLi = ul.querySelector('li[data-path="' + CSS.escape(prefix) + '"]');
if (!folderLi) return;
const childUl = folderLi.querySelector(':scope > ul.iar-tree-children');
const toggle = folderLi.querySelector(':scope > .iar-tree-row > .iar-tree-toggle');
if (childUl && toggle && childUl.classList.contains('d-none')) {
IARDirTreeView.toggleFolder(folderLi);
}
});
}
const li = ul.querySelector('li[data-path="' + CSS.escape(targetPath) + '"]');
if (li) {
ul.querySelectorAll('li.selected').forEach(function (x) { x.classList.remove('selected'); });
li.classList.add('selected');
activeColumnKey = colKey;
_updateSelectedPathDisplay(colKey);
if (!keepScroll) li.scrollIntoView({ block: 'center' });
}
if (keepScroll) _restoreTreeScroll();
}
function _dirClipboardHydrate() {
if (!global.IARDirClipboard) return;
const o = typeof IARDirClipboard.loadFileClip === 'function'
? IARDirClipboard.loadFileClip(cfg.clipScope)
: IARDirClipboard.load(cfg.clipScope);
directoryClipboard = o && typeof o === 'object' ? o : null;
}
function _dirClipboardSave() {
if (!global.IARDirClipboard || !directoryClipboard) return;
if (typeof IARDirClipboard.saveFileClip === 'function') {
IARDirClipboard.saveFileClip(cfg.clipScope, directoryClipboard);
} else {
IARDirClipboard.save(cfg.clipScope, directoryClipboard);
}
}
function _dirClipboardClear() {
directoryClipboard = null;
if (!global.IARDirClipboard) return;
if (typeof IARDirClipboard.clearFileClip === 'function') {
IARDirClipboard.clearFileClip(cfg.clipScope);
} else {
IARDirClipboard.clear(cfg.clipScope);
}
}
function _clipFromCol(clip) {
if (!clip) return '';
if (clip.from_col != null && String(clip.from_col).trim() !== '') {
return String(clip.from_col).trim();
}
const field = clip.from_clip_col_field || clipColField;
if (field && clip[field] != null && String(clip[field]).trim() !== '') {
return String(clip[field]).trim();
}
if (clip.from_subdir) return String(clip.from_subdir).trim();
if (clip.from_type) return String(clip.from_type).trim();
return '';
}
function _buildClipPayload(paths, colKey, type) {
const entityId = _entityId();
const clip = {
from_path: paths[0],
from_paths: paths,
type: type,
from_ops_id: cfg.opsId,
from_entity_id: entityId,
from_ce_key: ceKey || '',
from_api_param_key: apiParamKey,
from_clip_col_field: clipColField,
from_col: colKey,
};
if (ceKey) clip[ceKey] = entityId;
if (!pathBasedMode) clip[clipColField] = colKey;
return clip;
}
async function _postCrossDirOp(isMove, payload) {
const url = isMove ? '/api/dir-ops/cross-move' : '/api/dir-ops/cross-copy';
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
return res.json();
}
function getSelectedFiles(colKey) {
colKey = _resolveColKey(colKey);
const col = _col(colKey);
if (!col) return [];
const ul = _qs(col.listId);
if (!ul || !global.IARDirTreeMultiSelect) return [];
return IARDirTreeMultiSelect.getSelectedItems(ul).map(function (it) {
return {
path: it.path,
columnKey: colKey,
type: it.type,
itemType: it.type,
li: it.li,
};
});
}
function getSelectedFile(colKey) {
const key = colKey || activeColumnKey;
const items = getSelectedFiles(key);
return items.length ? items[items.length - 1] : null;
}
function getPasteTargetParentPath(colKey) {
const items = getSelectedFiles(colKey);
if (!items.length || !global.IARDirTreeMultiSelect) return '';
return IARDirTreeMultiSelect.pasteTargetParentFromItems(items);
}
function _parentPath(relPath) {
const p = String(relPath || '').replace(/\\/g, '/');
const idx = p.lastIndexOf('/');
return idx >= 0 ? p.substring(0, idx) : '';
}
function _columnLabel(colKey) {
const col = _col(colKey);
return col ? (col.label || colKey) : colKey;
}
function _setLoadingAll() {
if (tabsMode && sharedListId) {
const ul = _qs(sharedListId);
if (ul) ul.innerHTML = '加载中...';
return;
}
columns.forEach(function (col) {
const ul = _qs(col.listId);
if (ul) ul.innerHTML = '加载中...';
});
}
function _fetchFiles(entityId, onDone) {
if (cfg.opsId && entityId) _rememberOpenEntity(cfg.opsId, entityId);
var listUrl = _urlWithRoot(_listApi(entityId));
listUrl += (listUrl.indexOf('?') >= 0 ? '&' : '?') + '_ts=' + Date.now();
return fetch(listUrl, { cache: 'no-store' }).then(function (res) { return res.json(); }).then(function (data) {
if (!data.success) {
columns.forEach(function (col) {
const ul = _qs(col.listId);
if (ul) ul.innerHTML = '加载失败';
});
return;
}
filesData = _parseFilesData(data);
if (cfg.subdirRootsKey) {
global[cfg.subdirRootsKey] = data.subdir_roots || {};
}
if (cfg.filesCacheKey) {
global[cfg.filesCacheKey] = filesData;
}
loadColumns();
if (typeof cfg.onAfterFetch === 'function') cfg.onAfterFetch(data);
if (typeof onDone === 'function') onDone(data);
}).catch(function () {
columns.forEach(function (col) {
const ul = _qs(col.listId);
if (ul) ul.innerHTML = '加载失败';
});
});
}
function fetchFilesData(entityId) {
return fetch(_urlWithRoot(_listApi(entityId))).then(function (res) { return res.json(); }).then(function (data) {
if (!data.success) throw new Error(data.message || '加载失败');
return _parseFilesData(data);
});
}
/** keepFocus=true:保留已写入的 dirLastFocus(重命名后用,避免从 DOM 读回旧路径) */
function _reloadFiles(keepFocus) {
_dirClipboardHydrate();
_captureExpandedPaths();
if (!keepFocus) _rememberDirFocusFromSelection();
const entityId = _entityId();
if (!entityId) return Promise.resolve();
_setLoadingAll();
return _fetchFiles(entityId);
}
function refresh() {
_captureTreeScroll();
return _reloadFiles(false);
}
function _doOpenModal(entityId) {
entityId = String(entityId || '').trim();
if (cfg.opsId) _rememberOpenEntity(cfg.opsId, entityId);
if (cfg.entityIdInputId) {
const idEl = _qs(cfg.entityIdInputId);
if (idEl) idEl.value = entityId;
}
if (tabsMode) {
activeColumnKey = cfg.defaultSubdir || (columns.length ? columns[0].key : null);
if (sharedListId && activeColumnKey) listIdToKey[sharedListId] = activeColumnKey;
_syncSubdirTabs(activeColumnKey);
}
if (cfg.selectedPathElId) {
const sp = _qs(cfg.selectedPathElId);
if (sp) sp.textContent = '-';
}
if (cfg.opsId && global.IARDirOpsDirSource && IARDirOpsDirSource.isEnabled(cfg.opsId)) {
IARDirOpsDirSource.prepareModalOpen(cfg.opsId);
}
_dirClipboardHydrate();
if (features.wps) {
try {
const input = cfg.wpsInputId ? _qs(cfg.wpsInputId) : null;
if (input && global.localStorage) {
input.value = localStorage.getItem('wpsCustomExePath') || '';
}
} catch (e) { /* ignore */ }
}
_setLoadingAll();
_fetchFiles(entityId);
const modalEl = _qs(cfg.modalId);
if (modalEl) new bootstrap.Modal(modalEl).show();
}
function openModal(entityId) {
if (typeof cfg.onBeforeOpen === 'function') {
try {
const r = cfg.onBeforeOpen(entityId);
if (r && typeof r.then === 'function') {
return r.then(function () { _doOpenModal(entityId); });
}
} catch (e) { /* ignore */ }
}
_doOpenModal(entityId);
}
function openRootDirectory() {
const entityId = _entityId();
if (!entityId) {
alert('无法获取当前' + (cfg.entityLabel || '实体'));
return;
}
const rootBody = cfg.openRootUsesPath || pathBasedMode
? { path: '' }
: { open_root: true };
fetch(_filesApi(entityId) + '/open-directory', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(rootBody),
}).then(function (r) { return r.json(); })
.then(function (d) { if (!d.success) alert(d.message || '打开根目录失败'); })
.catch(function () { alert('打开根目录失败'); });
}
function loadColumns() {
if (tabsMode) {
if (sharedListId) listIdToKey[sharedListId] = activeColumnKey;
_syncSubdirTabs(activeColumnKey);
_renderColumn(activeColumnKey || (columns[0] ? columns[0].key : null));
_restoreDirFocus();
pendingExpandedByCol = null;
return;
}
columns.forEach(function (col) {
_renderColumn(col.key);
});
_restoreDirFocus();
pendingExpandedByCol = null;
}
function refreshTreeView() {
_captureExpandedPaths();
_rememberDirFocusFromSelection();
loadColumns();
}
function _bindTreeItemEvents(ul, colKey) {
ul.querySelectorAll('li[data-path]').forEach(function (li) {
li.addEventListener('click', function (e) {
e.stopPropagation();
if (global.IARDirTreeView) {
var toggle = e.target.closest('.iar-tree-toggle');
if (toggle && !toggle.classList.contains('iar-tree-toggle-leaf')) {
IARDirTreeView.toggleFolder(li);
}
}
_treeClick(e, li);
});
li.addEventListener('dblclick', function (ev) {
ev.preventDefault();
ev.stopPropagation();
const entityId = _entityId();
const path = this.dataset.path;
const typ = this.dataset.type;
const ck = this.dataset.column || colKey;
if (!entityId || !path) return;
if (typ === 'directory') {
fetch(_filesApi(entityId) + '/open-directory', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(_paramBody(ck, path)),
}).then(function (r) { return r.json(); }).then(function (d) {
if (!d.success) alert(d.message || '打开目录失败');
}).catch(function () { alert('打开目录失败'); });
} else {
let body = _paramBody(ck, path);
if (features.wps && cfg.wpsRadioName) {
const openWith = (document.querySelector('input[name="' + cfg.wpsRadioName + '"]:checked') || {}).value || 'default';
body.open_with = openWith;
if (openWith === 'wps' && cfg.wpsInputId) {
const input = _qs(cfg.wpsInputId);
if (input) body.wps_exe = (input.value || '').trim() || null;
}
}
fetch(_filesApi(entityId) + '/open-file', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).then(function (r) { return r.json(); }).then(function (d) {
if (!d.success) alert(d.message || '打开文件失败');
}).catch(function () { alert('打开文件失败'); });
}
});
});
}
function _renderColumn(colKey) {
const col = _col(colKey);
if (!col) return;
// 勿用 `filesData[colKey] || []`:null 表示子目录未匹配,会被当成空数组显示「暂无文件」
const items = Object.prototype.hasOwnProperty.call(filesData, colKey) ? filesData[colKey] : [];
const ul = _qs(col.listId);
if (!ul) return;
const dirClass = cfg.dirItemClass || '';
const fileClass = cfg.fileItemClass || '';
if (items === null) {
ul.innerHTML = '' + escapeHtml(cfg.missingSubdirMessage || '该默认目录尚不存在,请点击标题栏「确保目录存在」') + '';
} else if (!items.length) {
ul.innerHTML = '暂无文件';
} else if (global.IARDirTreeView) {
const sortSelectId = col.listId + 'TreeSort';
const sort = IARDirTreeView.readSortFromSelect(sortSelectId);
const expandedPaths = IARDirTreeView.collectExpandedPaths(ul);
if (dirLastFocus && dirLastFocus.columnKey === colKey && dirLastFocus.expandPaths) {
dirLastFocus.expandPaths.forEach(function (p) { expandedPaths.add(p); });
}
if (pendingExpandedByCol && pendingExpandedByCol[colKey]) {
pendingExpandedByCol[colKey].forEach(function (p) { expandedPaths.add(p); });
}
IARDirTreeView.renderInto(ul, items, {
sort: sort,
colKey: colKey,
dirItemClass: dirClass,
fileItemClass: fileClass,
expandedPaths: expandedPaths,
buildDisplayPath: function (it, basePath) {
return global.IARDirTreeHoverInfo
? IARDirTreeHoverInfo.buildTreeDisplayPath(it, basePath)
: (basePath ? (basePath + '/' + (it.name || '')) : (it.name || ''));
},
buildHoverTitle: function (fullPath, it) {
return global.IARDirTreeHoverInfo
? IARDirTreeHoverInfo.buildHoverTitle(fullPath, it)
: fullPath;
},
});
_bindTreeItemEvents(ul, colKey);
} else {
function render(treeItems, indent, basePath) {
let html = '';
basePath = basePath || '';
(treeItems || []).forEach(function (it) {
const pad = (indent || 0) + 'px';
const fullPath = global.IARDirTreeHoverInfo
? IARDirTreeHoverInfo.buildTreeDisplayPath(it, basePath)
: (basePath ? (basePath + '/' + (it.name || '')) : (it.name || ''));
const hoverTitle = global.IARDirTreeHoverInfo
? IARDirTreeHoverInfo.buildHoverTitle(fullPath, it)
: fullPath;
const titleAttr = ' title="' + escapeHtml(hoverTitle) + '"';
const fpa = it.full_path ? ' data-full-path="' + escapeHtml(it.full_path) + '"' : '';
const colAttr = ' data-column="' + escapeHtml(colKey) + '"';
if (it.type === 'directory') {
html += '📁 ' + escapeHtml(it.name) + '';
if (it.children && it.children.length) html += render(it.children, (indent || 0) + 16, fullPath);
} else {
html += '📄 ' + escapeHtml(it.name) + '';
}
});
return html;
}
ul.innerHTML = render(items, 0);
_bindTreeItemEvents(ul, colKey);
}
}
function _joinAbsPath(base, rel) {
if (!base) return '';
const useFwd = base.indexOf('/') >= 0 && base.indexOf('\\') < 0;
const sep = useFwd ? '/' : '\\';
const b = base.replace(/[\\/]+$/, '');
const parts = String(rel || '').split('/').join(sep).split('\\').join(sep).split(sep).filter(Boolean);
return parts.length ? b + sep + parts.join(sep) : b;
}
function copyViewRelPath(colKey) {
colKey = _resolveColKey(colKey);
const label = _columnLabel(colKey);
const sel = getSelectedFile(colKey);
let rel;
if (pathBasedMode) {
rel = (sel && sel.path)
? String(sel.path).replace(/\\/g, '/')
: (_apiParamValue(colKey) || colKey || '');
} else {
rel = (sel && sel.path)
? (label + '/' + String(sel.path).replace(/\\/g, '/'))
: (label || colKey || '');
}
if (!rel) {
alert('暂无可用路径,请等待目录加载完成');
return;
}
_copyText(rel).then(function () { showCopyMessage('已复制相对路径'); }).catch(function () { alert('复制到剪贴板失败'); });
}
function copyViewAbsPath(colKey) {
colKey = _resolveColKey(colKey);
const col = _col(colKey);
if (!col) {
alert('暂无可用路径,请等待目录加载完成');
return;
}
const sel = getSelectedFile(colKey);
if (pathBasedMode && cfg.dirBaseElId) {
const base = (_qs(cfg.dirBaseElId).textContent || '').trim();
if (!base) { alert('暂无可用路径,请等待目录加载完成'); return; }
const rel = (sel && sel.path)
? String(sel.path).trim()
: (_apiParamValue(colKey) || colKey || '');
const abs = _joinAbsPath(base, rel);
if (!abs) { alert('暂无可用路径,请等待目录加载完成'); return; }
_copyText(abs).then(function () { showCopyMessage('已复制绝对路径'); }).catch(function () { alert('复制到剪贴板失败'); });
return;
}
let abs = '';
if (sel && sel.li) {
abs = sel.li.getAttribute('data-full-path') || '';
}
if (!abs) {
const li = document.querySelector('#' + col.listId + ' li.selected');
abs = (li && li.getAttribute('data-full-path')) || '';
}
if (!abs && cfg.subdirRootsKey) {
const roots = global[cfg.subdirRootsKey] || {};
abs = roots[colKey] || roots[_apiParamValue(colKey)] || '';
}
if (!abs) { alert('暂无可用路径,请等待目录加载完成'); return; }
_copyText(String(abs)).then(function () { showCopyMessage('已复制绝对路径'); }).catch(function () { alert('复制到剪贴板失败'); });
}
async function copyFileName(colKey) {
colKey = _resolveColKey(colKey);
const items = getSelectedFiles(colKey);
if (!global.IARDirTreeMultiSelect || !IARDirTreeMultiSelect.requireAny(items, '请先选中要复制名称的文件或目录')) return;
const names = items.map(function (it) { return (it.path || '').replace(/\\/g, '/').split('/').pop() || it.path; });
try {
await _copyText(names.join('\n'));
showCopyMessage('已复制 ' + names.length + ' 个名称');
} catch (e) { alert('复制失败:' + (e.message || e)); }
}
function copyPath(colKey) {
if (!_guardWrite()) return;
colKey = _resolveColKey(colKey);
const items = getSelectedFiles(colKey);
if (!global.IARDirTreeMultiSelect || !IARDirTreeMultiSelect.requireAny(items, '请先选中要复制的文件或目录')) return;
const entityId = _entityId();
if (!entityId) { alert('无法获取当前' + (cfg.entityLabel || '实体')); return; }
const paths = items.map(function (it) { return it.path; });
const label = _columnLabel(colKey);
const pathStr = pathBasedMode
? paths.map(function (p) { return String(p).replace(/\\/g, '/'); }).join('\n')
: paths.map(function (p) { return label + '/' + String(p).replace(/\\/g, '/'); }).join('\n');
directoryClipboard = _buildClipPayload(paths, colKey, 'copy');
_dirClipboardSave();
_copyText(pathStr).then(function () { showCopyMessage('已复制 ' + paths.length + ' 项,可粘贴到目标目录'); }).catch(function () { alert('复制到剪贴板失败'); });
}
function cutPath(colKey) {
if (!_guardWrite()) return;
colKey = _resolveColKey(colKey);
const items = getSelectedFiles(colKey);
if (!global.IARDirTreeMultiSelect || !IARDirTreeMultiSelect.requireAny(items, '请先选中要剪切的文件或目录')) return;
const entityId = _entityId();
if (!entityId) { alert('无法获取当前' + (cfg.entityLabel || '实体')); return; }
const paths = items.map(function (it) { return it.path; });
const label = _columnLabel(colKey);
const pathStr = pathBasedMode
? paths.map(function (p) { return String(p).replace(/\\/g, '/'); }).join('\n')
: paths.map(function (p) { return label + '/' + String(p).replace(/\\/g, '/'); }).join('\n');
directoryClipboard = _buildClipPayload(paths, colKey, 'cut');
_dirClipboardSave();
_copyText(pathStr).then(function () { showCopyMessage('已剪切 ' + paths.length + ' 项,请到目标目录点击“粘贴”'); }).catch(function () { alert('复制到剪贴板失败'); });
}
async function pastePath(colKey, toRoot) {
if (tabsMode && typeof colKey === 'boolean') {
toRoot = colKey;
colKey = null;
}
if (!_guardWrite()) return;
colKey = _resolveColKey(colKey);
if (!colKey && !pathBasedMode) {
alert('请先选择目标子目录');
return;
}
_dirClipboardHydrate();
if (!directoryClipboard) { alert('请先使用“复制”或“剪切”选中文件或目录'); return; }
const entityId = _entityId();
if (!entityId) { alert('无法获取当前' + (cfg.entityLabel || '实体')); return; }
let toParent;
if (toRoot) {
toParent = pathBasedMode ? _apiParamValue(colKey) : '';
} else {
const items = getSelectedFiles(colKey);
if (!global.IARDirTreeMultiSelect || !IARDirTreeMultiSelect.requireAny(items, '请先选中目标目录或文件')) return;
toParent = getPasteTargetParentPath(colKey);
if (pathBasedMode && !toParent) toParent = _apiParamValue(colKey);
}
const paths = directoryClipboard.from_paths && directoryClipboard.from_paths.length
? directoryClipboard.from_paths
: (directoryClipboard.from_path ? [directoryClipboard.from_path] : []);
if (!paths.length) { alert('剪贴板无有效路径'); return; }
if (!global.IARDirPasteNameDialog) { alert('粘贴名称对话框未加载'); return; }
const fromOpsId = directoryClipboard.from_ops_id || cfg.opsId;
const fromEntityId = String(
directoryClipboard.from_entity_id
|| (directoryClipboard.from_ce_key && directoryClipboard[directoryClipboard.from_ce_key])
|| (ceKey && directoryClipboard[ceKey])
|| ''
).trim();
const fromColKey = _clipFromCol(directoryClipboard);
const isCrossOps = !!(fromOpsId && fromOpsId !== cfg.opsId);
const isCut = directoryClipboard.type === 'cut';
const fromLabel = fromColKey ? (
(isCrossOps ? ((directoryClipboard.from_ops_id || '') + '/') : '') + fromColKey
) : '';
const targetHint = pathBasedMode
? String(toParent || _apiParamValue(colKey)).replace(/\\/g, '/')
: (_columnLabel(colKey) + (toParent ? '/' + String(toParent).replace(/\\/g, '/') : ''));
const actionLabel = isCut ? '确定移动' : '确定粘贴';
const url = isCut
? _filesApi(entityId) + '/move'
: _filesApi(entityId) + '/copy';
let ok = 0;
let fail = 0;
let lastMsg = '';
let cancelled = false;
for (let i = 0; i < paths.length; i++) {
const fromPath = paths[i];
const destName = await IARDirPasteNameDialog.prompt({
defaultName: IARDirPasteNameDialog.basename(fromPath),
sourcePathDisplay: pathBasedMode
? String(fromPath).replace(/\\/g, '/')
: ((fromLabel ? fromLabel + '/' : '') + String(fromPath).replace(/\\/g, '/')),
targetHint: targetHint,
itemIndex: i + 1,
itemCount: paths.length,
actionLabel: actionLabel,
});
if (destName === null) { cancelled = true; break; }
try {
let data;
if (isCrossOps) {
if (!fromEntityId || !fromColKey) {
fail++;
lastMsg = '跨模块粘贴缺少源信息,请重新复制';
continue;
}
if (!colKey) {
fail++;
lastMsg = '跨模块粘贴缺少目标子目录';
continue;
}
data = await _postCrossDirOp(isCut, {
from_ops_id: fromOpsId,
from_entity_id: fromEntityId,
from_col: fromColKey,
from_path: fromPath,
to_ops_id: cfg.opsId,
to_entity_id: entityId,
to_col: colKey,
to_parent_path: toParent,
dest_name: destName,
});
} else {
const body = {
from_path: fromPath,
to_parent_path: toParent,
dest_name: destName,
};
if (!pathBasedMode) {
body[fromParamField] = fromColKey || colKey;
body[toParamField] = colKey;
}
if (fromEntityId && ceKey && String(fromEntityId) !== String(entityId)) {
body[ceKey] = fromEntityId;
} else if (directoryClipboard[ceKey] != null && String(directoryClipboard[ceKey]).trim() !== '') {
body[ceKey] = directoryClipboard[ceKey];
}
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
data = await res.json();
}
if (data.success) ok++;
else { fail++; lastMsg = data.message || '操作失败'; }
} catch (e) {
fail++;
lastMsg = e.message || String(e);
}
}
if (cancelled && !ok && !fail) return;
if (ok && directoryClipboard.type === 'cut') _dirClipboardClear();
if (ok) refresh();
alert((ok ? ('成功 ' + ok + ' 项') : '') + (fail ? (';失败 ' + fail + ' 项' + (lastMsg ? ':' + lastMsg : '')) : '') || lastMsg || '操作完成');
}
function _buildCopyTargets(excludeColKey) {
const sourceEntityId = _entityId();
const out = [];
(columns || []).forEach(function (col) {
const disabled = !sourceEntityId;
out.push({
opsId: cfg.opsId,
colKey: col.key,
colLabel: col.label || col.key,
boxLabel: cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId,
pageLabel: cfg.copyToPageLabel || cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId,
pageKey: cfg.opsId,
entityId: sourceEntityId,
isCurrent: true,
disabled: disabled,
disabledReason: disabled ? '请先打开目录' : '',
isSourceCol: col.key === excludeColKey,
});
});
if (typeof global.IARDirOpsColumns.listCopyTargets === 'function') {
global.IARDirOpsColumns.listCopyTargets(cfg.opsId).forEach(function (t) {
if (t.opsId === cfg.opsId) return;
out.push(t);
});
}
return out;
}
async function _performCopyTo(fromColKey, paths, target) {
const tgtInst = _registry[target.opsId];
if (!tgtInst) {
alert('目标目录框未注册');
return;
}
const tgtCfg = tgtInst.cfg;
if (typeof tgtCfg.guardWrite === 'function' && tgtCfg.guardWrite() === false) {
alert('目标为备份目录视图,不能写入');
return;
}
const fromEntityId = _entityId();
const toEntityId = String(target.entityId || '').trim();
if (!fromEntityId) {
alert('无法获取当前' + (cfg.entityLabel || '实体'));
return;
}
if (!toEntityId) {
alert('目标目录未打开,请先在对应页面打开目录操作对话框');
return;
}
if (!global.IARDirPasteNameDialog) {
alert('粘贴名称对话框未加载');
return;
}
const tgtPathBased = tgtCfg.apiParamKey === 'path' && tgtCfg.pathBasedMode !== false;
const tgtApiParamKey = tgtCfg.apiParamKey || 'subdir';
const tgtToParam = 'to_' + tgtApiParamKey;
const tgtFromParam = 'from_' + tgtApiParamKey;
const tgtCeKey = tgtCfg.crossEntityField;
const tgtCol = (tgtCfg.columns || []).find(function (c) { return c.key === target.colKey; });
const toColKey = target.colKey;
let toParent = target.toRoot ? '' : (target.toParentPath || '');
if (tgtPathBased && target.toRoot) {
toParent = typeof tgtInst.getApiParamValue === 'function'
? tgtInst.getApiParamValue(toColKey)
: toColKey;
}
const fromLabel = _columnLabel(fromColKey);
const toLabel = tgtCol ? (tgtCol.label || toColKey) : toColKey;
const targetHint = tgtPathBased
? String(toParent || toColKey).replace(/\\/g, '/')
: (toLabel + (toParent ? '/' + String(toParent).replace(/\\/g, '/') : ''));
const url = tgtCfg.apiFiles(toEntityId) + '/copy';
let ok = 0;
let fail = 0;
let lastMsg = '';
let cancelled = false;
for (let i = 0; i < paths.length; i++) {
const fromPath = paths[i];
const destName = await IARDirPasteNameDialog.prompt({
defaultName: IARDirPasteNameDialog.basename(fromPath),
sourcePathDisplay: pathBasedMode
? String(fromPath).replace(/\\/g, '/')
: (fromLabel + '/' + String(fromPath).replace(/\\/g, '/')),
targetHint: (tgtCfg.copyToBoxLabel || tgtCfg.entityLabel || target.opsId) + ' / ' + targetHint,
itemIndex: i + 1,
itemCount: paths.length,
actionLabel: '确定复制',
});
if (destName === null) {
cancelled = true;
break;
}
const body = {
from_path: fromPath,
to_parent_path: toParent,
dest_name: destName,
};
if (!tgtPathBased) {
body[tgtFromParam] = fromColKey;
body[tgtToParam] = toColKey;
}
if (tgtCeKey && String(fromEntityId) !== String(toEntityId)) {
body[tgtCeKey] = fromEntityId;
}
try {
let data;
if (target.opsId !== cfg.opsId) {
data = await _postCrossDirOp(false, {
from_ops_id: cfg.opsId,
from_entity_id: fromEntityId,
from_col: fromColKey,
from_path: fromPath,
to_ops_id: target.opsId,
to_entity_id: toEntityId,
to_col: toColKey,
to_parent_path: toParent,
dest_name: destName,
});
} else {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
data = await res.json();
}
if (data.success) ok++;
else {
fail++;
lastMsg = data.message || '复制失败';
}
} catch (e) {
fail++;
lastMsg = e.message || String(e);
}
}
if (cancelled && !ok && !fail) return;
refresh();
if (target.opsId !== cfg.opsId && typeof tgtInst.refresh === 'function') {
tgtInst.refresh();
}
alert((ok ? ('成功复制 ' + ok + ' 项') : '') +
(fail ? (';失败 ' + fail + ' 项' + (lastMsg ? ':' + lastMsg : '')) : '') ||
lastMsg || '复制完成');
}
async function openCopyTo(colKey) {
if (!_guardWrite()) return;
if (tabsMode && typeof colKey === 'boolean') colKey = null;
colKey = _resolveColKey(colKey);
const items = getSelectedFiles(colKey);
if (!global.IARDirTreeMultiSelect || !IARDirTreeMultiSelect.requireAny(items, '请先选中要复制的文件或目录')) return;
if (!global.IARDirCopyToDialog) {
alert('「复制到」对话框未加载');
return;
}
const paths = items.map(function (it) { return it.path; });
const allTargets = _buildCopyTargets(colKey);
const result = await IARDirCopyToDialog.open({
boxLabel: cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId,
sourceColLabel: _columnLabel(colKey),
sourcePaths: paths,
targets: allTargets,
otherPages: typeof global.IARDirOpsColumns.listCopyTargetPages === 'function'
? IARDirOpsColumns.listCopyTargetPages(cfg.opsId)
: [],
refreshOtherTargets: function () {
return global.IARDirOpsColumns.listCopyTargets(cfg.opsId);
},
sourceOpsId: cfg.opsId,
fetchTree: function (opsId, entityId) {
return global.IARDirOpsColumns.fetchTargetTree(opsId, entityId);
},
});
if (!result) return;
await _performCopyTo(colKey, paths, result);
}
function _buildLocalCopyTargets() {
const entityId = _entityId();
return (columns || []).map(function (col) {
const disabled = !entityId;
return {
opsId: cfg.opsId,
colKey: col.key,
colLabel: col.label || col.key,
boxLabel: cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId,
pageLabel: cfg.copyToPageLabel || cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId,
pageKey: cfg.opsId,
entityId: entityId,
disabled: disabled,
disabledReason: disabled ? '请先打开目录' : '',
};
});
}
function _buildPageSourceTargets() {
const entityId = _entityId();
return (columns || []).map(function (col) {
const disabled = !entityId;
return {
opsId: cfg.opsId,
colKey: col.key,
colLabel: col.label || col.key,
boxLabel: cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId,
pageLabel: cfg.copyToPageLabel || cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId,
pageKey: cfg.opsId,
entityId: entityId,
disabled: disabled,
disabledReason: disabled ? '请先打开目录' : '',
};
});
}
function _resolveCopyFromLockedTarget(colKey) {
colKey = _resolveColKey(colKey);
let items = getSelectedFiles(colKey);
if (!items.length && dirLastFocus && dirLastFocus.columnKey === colKey && dirLastFocus.path) {
const col = _col(colKey);
const ul = col ? _qs(col.listId) : null;
const li = ul
? ul.querySelector('li[data-path="' + CSS.escape(dirLastFocus.path) + '"]')
: null;
if (li) {
items = [{
path: dirLastFocus.path,
columnKey: colKey,
type: (li.getAttribute('data-type') || '').trim(),
itemType: (li.getAttribute('data-type') || '').trim(),
li: li,
}];
}
}
if (!items.length) return null;
const toParent = global.IARDirTreeMultiSelect
? IARDirTreeMultiSelect.pasteTargetParentFromItems(items)
: '';
const colLabel = _columnLabel(colKey);
const display = toParent
? (colLabel + ' / ' + String(toParent).replace(/\\/g, '/'))
: (colLabel + '(根目录)');
return {
colKey: colKey,
toParentPath: toParent || '',
toRoot: !toParent,
colLabel: colLabel,
display: display,
};
}
function _resolveCopyFromToParent(target) {
const toColKey = target.colKey;
const parent = String(target.toParentPath || '').trim();
if (parent) return parent;
return _uploadParentPath(toColKey, '', !!target.toRoot);
}
async function _performCopyFrom(pairs) {
if (!pairs || !pairs.length) return;
if (!_guardWrite()) return;
const toEntityId = _entityId();
if (!toEntityId) {
alert('无法获取当前' + (cfg.entityLabel || '实体'));
return;
}
if (!global.IARDirPasteNameDialog) {
alert('粘贴名称对话框未加载');
return;
}
const url = _filesApi(toEntityId) + '/copy';
let ok = 0;
let fail = 0;
let lastMsg = '';
let cancelled = false;
let i;
for (i = 0; i < pairs.length; i++) {
const pair = pairs[i];
const source = pair.source || {};
const target = pair.target || {};
const isLocal = !!source.isLocal;
const fromEntityId = isLocal ? '' : String(source.entityId || '').trim();
const fromColKey = source.colKey;
const fromPath = source.fromPath;
const toColKey = target.colKey;
if (!fromPath) {
fail++;
lastMsg = '源路径为空';
continue;
}
if (!isLocal && !fromEntityId) {
fail++;
lastMsg = '源目录未打开,请先在对应页面打开目录操作对话框';
continue;
}
const toParent = _resolveCopyFromToParent(target);
const fromLabel = isLocal ? '本机' : (source.colLabel || fromColKey);
const toLabel = target.colLabel || _columnLabel(toColKey);
const targetHint = pathBasedMode
? String(toParent || toColKey).replace(/\\/g, '/')
: (toLabel + (toParent ? '/' + String(toParent).replace(/\\/g, '/') : ''));
const destName = await IARDirPasteNameDialog.prompt({
defaultName: IARDirPasteNameDialog.basename(fromPath),
sourcePathDisplay: isLocal
? String(fromPath).replace(/\\/g, '/')
: (pathBasedMode
? String(fromPath).replace(/\\/g, '/')
: (fromLabel + '/' + String(fromPath).replace(/\\/g, '/'))),
targetHint: (cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId) + ' / ' + targetHint,
itemIndex: i + 1,
itemCount: pairs.length,
actionLabel: '确定复制',
});
if (destName === null) {
cancelled = true;
break;
}
const body = isLocal
? {
from_abs_path: fromPath,
to_parent_path: toParent,
dest_name: destName,
}
: {
from_path: fromPath,
to_parent_path: toParent,
dest_name: destName,
};
if (!pathBasedMode) {
if (!isLocal) body[fromParamField] = fromColKey;
body[toParamField] = toColKey;
}
if (!isLocal && ceKey && String(fromEntityId) !== String(toEntityId)) {
body[ceKey] = fromEntityId;
}
try {
let data;
const srcOpsId = isLocal ? '' : String(source.opsId || cfg.opsId);
if (!isLocal && srcOpsId && srcOpsId !== cfg.opsId) {
data = await _postCrossDirOp(false, {
from_ops_id: srcOpsId,
from_entity_id: fromEntityId,
from_col: fromColKey,
from_path: fromPath,
to_ops_id: cfg.opsId,
to_entity_id: toEntityId,
to_col: toColKey,
to_parent_path: toParent,
dest_name: destName,
});
} else {
const res = await fetch(_urlWithRoot(url), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
data = await res.json();
}
if (data.success) ok++;
else {
fail++;
lastMsg = data.message || '复制失败';
}
} catch (e) {
fail++;
lastMsg = e.message || String(e);
}
}
if (cancelled && !ok && !fail) return;
refresh();
alert((ok ? ('成功复制 ' + ok + ' 项') : '') +
(fail ? (';失败 ' + fail + ' 项' + (lastMsg ? ':' + lastMsg : '')) : '') ||
lastMsg || '复制完成');
}
async function openCopyFrom(colKey) {
if (!_guardWrite()) return;
if (tabsMode && typeof colKey === 'boolean') colKey = null;
colKey = _resolveColKey(colKey);
_rememberDirFocusFromSelection();
const lockedSnapshot = _resolveCopyFromLockedTarget(colKey);
if (!global.IARDirCopyFromDialog) {
alert('「从其他处复制到此处」对话框未加载');
return;
}
const localTargets = _buildLocalCopyTargets();
const pageSourceTargets = _buildPageSourceTargets();
const otherSourceTargets = typeof global.IARDirOpsColumns.listCopyTargets === 'function'
? IARDirOpsColumns.listCopyTargets(cfg.opsId)
: [];
const result = await IARDirCopyFromDialog.open({
boxLabel: cfg.copyToBoxLabel || cfg.entityLabel || cfg.opsId,
targetColLabel: _columnLabel(colKey),
lockedTarget: lockedSnapshot,
getLockedTarget: function () { return _resolveCopyFromLockedTarget(colKey); },
localTargets: localTargets,
pageSourceTargets: pageSourceTargets,
otherSourceTargets: otherSourceTargets,
sourceOpsId: cfg.opsId,
defaultTargetColKey: colKey,
refreshOtherTargets: function () {
return global.IARDirOpsColumns.listCopyTargets(cfg.opsId);
},
fetchTree: function (opsId, entityId) {
return global.IARDirOpsColumns.fetchTargetTree(opsId, entityId);
},
});
if (!result || !result.length) return;
await _performCopyFrom(result);
}
function getDropTargetFromEvent(e) {
if (tabsMode && cfg.subdirDropzoneClass) {
const zone = e.target.closest('.' + cfg.subdirDropzoneClass);
if (zone) {
const sd = _getSubdirAttr(zone);
const tgt = {};
if (!pathBasedMode) tgt[toParamField] = sd;
tgt.to_parent_path = pathBasedMode ? sd : '';
return tgt;
}
}
const dropUl = e.target.closest(rootUlSelector);
if (!dropUl || !dropUl.id) return null;
const toColKey = tabsMode ? activeColumnKey : listIdToKey[dropUl.id];
if (!toColKey) return null;
const dropLi = e.target.closest('#' + cfg.modalId + ' li[data-path]');
if (dropLi && dropUl.contains(dropLi)) {
const typ = dropLi.dataset.type;
const path = dropLi.dataset.path;
let to_parent_path;
if (typ === 'directory') to_parent_path = path;
else to_parent_path = _parentPath(path);
const tgt = {};
tgt[toParamField] = toColKey;
tgt.to_parent_path = to_parent_path;
return tgt;
}
const tgt = {};
if (!pathBasedMode) tgt[toParamField] = toColKey;
tgt.to_parent_path = pathBasedMode ? toColKey : '';
return tgt;
}
function isInvalidDragMove(fromColKey, from_path, toColKey, to_parent_path) {
const fp = String(from_path || '').replace(/\\/g, '/');
const tp = String(to_parent_path || '').replace(/\\/g, '/');
if (fromColKey === toColKey) {
if (fp === tp) return '不能移动到自身';
if (_parentPath(fp) === tp) return '已在目标文件夹中';
if (tp.startsWith(fp + '/')) return '不能移动到自身的子目录内';
}
return null;
}
async function executeDragMove(fromColKey, from_path, toColKey, to_parent_path, ceIdOpt) {
if (!_guardWrite()) return;
const entityId = _entityId();
if (!entityId) { alert('无法获取当前' + (cfg.entityLabel || '实体')); return; }
const err = isInvalidDragMove(fromColKey, from_path, toColKey, to_parent_path);
if (err) { alert(err); return; }
const body = {
from_path: from_path,
to_parent_path: to_parent_path,
};
if (!pathBasedMode) {
body[fromParamField] = fromColKey;
body[toParamField] = toColKey;
}
const srcId = ceIdOpt != null && String(ceIdOpt).trim() !== '' ? ceIdOpt : entityId;
if (srcId && ceKey) body[ceKey] = srcId;
try {
const res = await fetch(_filesApi(entityId) + '/move', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const data = await res.json();
if (data.success) {
dirLastFocus = { columnKey: toColKey, path: from_path };
_applyDirFocusMeta(dirLastFocus);
activeColumnKey = toColKey;
if (tabsMode) switchSubdir(toColKey);
_setLoadingAll();
_fetchFiles(entityId);
} else {
alert(data.message || '移动失败');
}
} catch (e) { alert('移动失败:' + (e.message || e)); }
}
function initDragDrop() {
const modal = _qs(cfg.modalId);
if (!modal) return;
let dragOverEl = null;
const dragOverClass = cfg.dragOverClass || '';
function clearDragOver() {
if (dragOverEl) {
dragOverEl.classList.remove(dragOverClass);
dragOverEl = null;
}
if (dragOverClass) {
modal.querySelectorAll('.' + dragOverClass).forEach(function (el) { el.classList.remove(dragOverClass); });
}
}
modal.addEventListener('dragstart', function (e) {
const li = e.target.closest('li[data-path]');
if (!li || !modal.contains(li)) return;
const rootUl = _rootUlFromLi(li);
if (!rootUl) return;
const fromColKey = tabsMode ? activeColumnKey : listIdToKey[rootUl.id];
if (!fromColKey) return;
const dragCatalogId = _entityId();
const payload = {
from_path: li.dataset.path,
dragType: li.dataset.type || 'file',
[ceKey]: dragCatalogId,
};
payload[clipColField] = fromColKey;
global[cfg.dragStateKey] = payload;
try { e.dataTransfer.setData('application/json', JSON.stringify(payload)); } catch (x) { /* ignore */ }
e.dataTransfer.effectAllowed = 'move';
});
modal.addEventListener('dragend', function () {
global[cfg.dragStateKey] = null;
clearDragOver();
});
modal.addEventListener('dragover', function (e) {
if (!global[cfg.dragStateKey]) return;
const tgt = getDropTargetFromEvent(e);
if (!tgt) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
clearDragOver();
const zone = tabsMode && cfg.subdirDropzoneClass
? e.target.closest('.' + cfg.subdirDropzoneClass) : null;
const dropLi = e.target.closest('#' + cfg.modalId + ' li[data-path]');
const listUl = e.target.closest(rootUlSelector);
dragOverEl = zone || dropLi || listUl;
if (dragOverEl && dragOverClass) dragOverEl.classList.add(dragOverClass);
});
modal.addEventListener('drop', function (e) {
e.preventDefault();
clearDragOver();
let src = global[cfg.dragStateKey];
if (!src) {
try { src = JSON.parse(e.dataTransfer.getData('application/json')); } catch (x) { return; }
}
if (!src || !src.from_path) return;
const tgt = getDropTargetFromEvent(e);
if (!tgt) return;
const fromColKey = src[clipColField];
const toColKey = tgt[toParamField];
if (fromColKey === toColKey && src.from_path === tgt.to_parent_path) return;
executeDragMove(fromColKey, src.from_path, toColKey, tgt.to_parent_path, src[ceKey]);
});
}
function browseFile(colKey) {
const entityId = _entityId();
const sel = getSelectedFile(colKey);
if (!entityId || !sel || !sel.path) { alert('请先选择文件'); return; }
if (sel.type === 'directory') { alert('不能浏览目录,请选择文件'); return; }
const url = _urlWithRoot(pathBasedMode
? (_filesApi(entityId) + '/browse?path=' + encodeURIComponent(sel.path))
: (_filesApi(entityId) + '/browse?' + apiParamKey + '=' + encodeURIComponent(_apiParamValue(colKey)) + '&path=' + encodeURIComponent(sel.path)));
global.open(url, '_blank');
}
function downloadFile(colKey) {
const entityId = _entityId();
const sel = getSelectedFile(colKey);
if (!entityId || !sel || !sel.path) { alert('请先选择文件'); return; }
if (sel.type === 'directory') { alert('不能下载目录,请选择文件'); return; }
const url = _urlWithRoot(pathBasedMode
? (_filesApi(entityId) + '/download?path=' + encodeURIComponent(sel.path))
: (_filesApi(entityId) + '/download?' + apiParamKey + '=' + encodeURIComponent(_apiParamValue(colKey)) + '&path=' + encodeURIComponent(sel.path)));
global.open(url, '_blank');
}
function addFile(colKey) {
if (!_guardWrite()) return;
const entityId = _entityId();
if (!entityId) { alert((cfg.entityLabel || '实体') + 'ID缺失'); return; }
const parentPath = getPasteTargetParentPath(colKey);
const input = document.createElement('input');
input.type = 'file';
input.onchange = function (e) {
const f = e.target.files[0];
if (!f) return;
const fd = new FormData();
fd.append('file', f);
if (pathBasedMode) {
fd.append('path', _uploadParentPath(colKey, parentPath, false));
} else {
fd.append(apiParamKey, _apiParamValue(colKey));
fd.append('path', parentPath || '');
}
fetch(_filesApi(entityId) + '/upload', { method: 'POST', body: fd })
.then(function (r) { return r.json(); }).then(function (d) {
if (d.success) openModal(entityId);
else alert(d.message || '上传失败');
})
.catch(function () { alert('上传失败'); });
};
input.click();
}
function addFileToRoot(colKey) {
if (!_guardWrite()) return;
const entityId = _entityId();
if (!entityId) { alert((cfg.entityLabel || '实体') + 'ID缺失'); return; }
const input = document.createElement('input');
input.type = 'file';
input.onchange = function (e) {
const f = e.target.files[0];
if (!f) return;
const fd = new FormData();
fd.append('file', f);
if (pathBasedMode) {
fd.append('path', _uploadParentPath(colKey, '', true));
} else {
fd.append(apiParamKey, _apiParamValue(colKey));
fd.append('path', '');
}
fetch(_filesApi(entityId) + '/upload', { method: 'POST', body: fd })
.then(function (r) { return r.json(); }).then(function (d) {
if (d.success) openModal(entityId);
else alert(d.message || '上传失败');
})
.catch(function () { alert('上传失败'); });
};
input.click();
}
function _photoFileWithTimestamp(file, index) {
const type = (file && file.type) || '';
let ext = 'jpg';
const m = /\.([a-zA-Z0-9]+)$/.exec((file && file.name) || '');
if (m && m[1]) ext = m[1].toLowerCase();
else if (type.indexOf('png') >= 0) ext = 'png';
else if (type.indexOf('webp') >= 0) ext = 'webp';
else if (type.indexOf('jpeg') >= 0 || type.indexOf('jpg') >= 0) ext = 'jpg';
if (ext === 'jpeg') ext = 'jpg';
const now = new Date();
function pad(n) { return n < 10 ? '0' + n : String(n); }
function pad3(n) {
n = Number(n) || 0;
if (n < 10) return '00' + n;
if (n < 100) return '0' + n;
return String(n);
}
const stamp = now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + '_' +
pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '_' + pad3(now.getMilliseconds());
const seq = (index != null && index >= 0) ? ('_' + pad3(index + 1)) : '';
const name = 'photo_' + stamp + seq + '.' + ext;
try {
return new File([file], name, { type: type || 'image/jpeg', lastModified: Date.now() });
} catch (e) {
return file;
}
}
function prepareTakePhoto(colKey) {
if (!_guardWrite()) return false;
const entityId = _entityId();
if (!entityId) {
alert((cfg.entityLabel || '实体') + 'ID缺失');
return false;
}
const sel = getSelectedFile(colKey);
if (!sel || !sel.path || sel.type !== 'directory') {
alert('请先选中要保存照片的目录');
return false;
}
_pendingPhotoByOps[cfg.opsId] = {
colKey: colKey || null,
entityId: entityId,
parentPath: sel.path
};
return true;
}
function completeTakePhoto(rawFiles) {
const pending = _pendingPhotoByOps[cfg.opsId];
delete _pendingPhotoByOps[cfg.opsId];
const sheet = document.getElementById('iarDirOpsTakePhotoSheet');
if (sheet && sheet.parentNode) sheet.parentNode.removeChild(sheet);
const list = Array.isArray(rawFiles) ? rawFiles : (rawFiles ? [rawFiles] : []);
if (!list.length || !pending) return;
function doUpload() {
_uploadPhotoFiles(pending.colKey, pending.entityId, pending.parentPath, list);
}
const perm = cfg.permissions && cfg.permissions.takePhoto;
if (perm && typeof cfg.permissionCheck === 'function') {
cfg.permissionCheck(perm, doUpload);
} else {
doUpload();
}
}
/** 打开网页内相机(getUserMedia),支持连拍与多选图片 */
function takePhoto(colKey) {
if (!prepareTakePhoto(colKey)) return;
const pending = _pendingPhotoByOps[cfg.opsId];
_openCameraModal(cfg.opsId, pending && pending.parentPath);
}
function _uploadPhotoFiles(colKey, entityId, parentPath, rawFiles) {
const files = Array.isArray(rawFiles) ? rawFiles.filter(Boolean) : (rawFiles ? [rawFiles] : []);
if (!files.length) return;
let done = 0;
let fail = 0;
let lastMsg = '';
function runNext(i) {
if (i >= files.length) {
if (done) openModal(entityId);
const okMsg = done === 1
? '照片已保存到选中目录'
: ('已保存 ' + done + ' 张照片到选中目录');
const failMsg = fail ? (';失败 ' + fail + ' 张' + (lastMsg ? ':' + lastMsg : '')) : '';
if (typeof showCopyMessage === 'function' && !fail) showCopyMessage(okMsg);
else alert(okMsg + failMsg);
return;
}
const f = _photoFileWithTimestamp(files[i], i);
const fd = new FormData();
const uploadName = (f && f.name) ? f.name : ('photo_' + (i + 1) + '.jpg');
fd.append('file', f, uploadName);
if (pathBasedMode) {
fd.append('path', _uploadParentPath(colKey, parentPath, false));
} else {
fd.append(apiParamKey, _apiParamValue(colKey));
fd.append('path', parentPath || '');
}
fetch(_filesApi(entityId) + '/upload', { method: 'POST', body: fd })
.then(function (r) { return r.json(); }).then(function (d) {
if (d.success) done++;
else { fail++; lastMsg = d.message || '拍照保存失败'; }
runNext(i + 1);
})
.catch(function () {
fail++;
lastMsg = '拍照保存失败';
runNext(i + 1);
});
}
runNext(0);
}
function _uploadPhotoFile(colKey, entityId, parentPath, rawFile) {
_uploadPhotoFiles(colKey, entityId, parentPath, rawFile ? [rawFile] : []);
}
function deleteFile(colKey) {
if (!_guardWrite()) return;
_rememberDirFocusFromSelection();
const entityId = _entityId();
const items = getSelectedFiles(colKey);
if (!entityId || !global.IARDirTreeMultiSelect || !IARDirTreeMultiSelect.requireAny(items, '请先选择文件或目录')) return;
const msg = items.length > 1 ? ('确定要删除选中的 ' + items.length + ' 项吗?') : '确定要删除选中的文件/目录吗?';
if (!confirm(msg)) return;
let done = 0;
let fail = 0;
let lastMsg = '';
function runNext(i) {
if (i >= items.length) {
if (done) {
// 就地刷新:保留当前子目录选项卡、展开状态和滚动位置。
// openModal 会把选项卡重置为 defaultSubdir(第一个默认子目录)。
const stayKey = _resolveColKey((items[0] && items[0].columnKey) || colKey);
const deleted = {};
items.forEach(function (it) {
if (it && it.path) deleted[String(it.path).replace(/\\/g, '/')] = true;
});
const primary = items[items.length - 1];
let stayPath = primary && primary.path ? _parentPath(primary.path) : '';
while (stayPath && deleted[stayPath]) stayPath = _parentPath(stayPath);
_captureTreeScroll();
if (stayKey && stayPath) _setDirLastFocus(stayKey, stayPath);
else dirLastFocus = null;
_reloadFiles(true);
}
alert((done ? ('成功删除 ' + done + ' 项') : '') + (fail ? (';失败 ' + fail + ' 项' + (lastMsg ? ':' + lastMsg : '')) : '') || lastMsg || '操作完成');
return;
}
fetch(_filesApi(entityId) + '/delete', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(_paramBody(colKey, items[i].path)),
}).then(function (r) { return r.json(); }).then(function (d) {
if (d.success) done++;
else { fail++; lastMsg = d.message || '删除失败'; }
runNext(i + 1);
}).catch(function () {
fail++;
lastMsg = '删除失败';
runNext(i + 1);
});
}
runNext(0);
}
function backupFile(colKey) {
if (!features.backup) return;
if (!_guardWrite()) return;
_rememberDirFocusFromSelection();
const entityId = _entityId();
const sel = getSelectedFile(colKey);
if (!entityId || !sel || !sel.path) { alert('请先选择文件或目录'); return; }
if (!confirm('确定要备份选中的文件/目录吗?')) return;
fetch(_filesApi(entityId) + '/backup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(_paramBody(colKey, sel.path)),
}).then(function (r) { return r.json(); }).then(function (d) {
alert(d.success ? '备份成功' : (d.message || '备份失败'));
}).catch(function () { alert('备份失败'); });
}
async function renameFile(colKey) {
if (!_guardWrite()) return;
colKey = _resolveColKey(colKey);
_rememberDirFocusFromSelection();
const entityId = _entityId();
const sel = getSelectedFile(colKey);
if (!entityId || !sel || !sel.path) { alert('请先选择要重命名的文件或目录'); return; }
const detectedKey = sel.li ? _columnKeyFromLi(sel.li) : colKey;
const finalKey = _resolveColKey(detectedKey || colKey);
const oldName = String(sel.path).replace(/\\/g, '/').split('/').filter(Boolean).pop() || '';
if (!global.IARDirRenameDialog) {
alert('重命名对话框未加载');
return;
}
const rawName = await IARDirRenameDialog.prompt({
defaultName: oldName,
pathDisplay: sel.path,
isDirectory: sel.type === 'directory',
});
if (!rawName || rawName.trim() === '' || rawName.trim() === oldName) return;
const trimmed = rawName.trim();
const newName = sanitizeFsName(trimmed);
if (newName !== trimmed) {
if (!confirm('名称含 Windows 不允许的字符(如 : * ? " < > | / \\),将自动替换为下划线:\n\n' + newName + '\n\n是否继续?')) {
return;
}
}
try {
const r = await fetch(_filesApi(entityId) + '/rename', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.assign(_paramBody(finalKey, sel.path), { new_name: newName })),
});
const d = await r.json();
if (d.success) {
const oldPath = String(sel.path).replace(/\\/g, '/');
const idx = oldPath.lastIndexOf('/');
_setDirLastFocus(finalKey, (idx >= 0 ? oldPath.substring(0, idx + 1) : '') + (d.new_name || newName));
await _reloadFiles(true);
alert('重命名成功');
return;
}
alert(d.message || '重命名失败');
} catch (e) {
alert('重命名失败');
}
}
function renameFileWithTimestamp(colKey) {
if (!_guardWrite()) return;
colKey = _resolveColKey(colKey);
_rememberDirFocusFromSelection();
const entityId = _entityId();
const sel = getSelectedFile(colKey);
if (!entityId || !sel || !sel.path) { alert('请先选择要重命名的文件或目录'); return; }
const detectedKey = sel.li ? _columnKeyFromLi(sel.li) : colKey;
const finalKey = _resolveColKey(detectedKey || colKey);
fetch(_filesApi(entityId) + '/rename', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.assign(_paramBody(finalKey, sel.path), { mode: 'timestamp' })),
}).then(function (r) { return r.json(); }).then(function (d) {
if (d.success) {
const oldPath = String(sel.path).replace(/\\/g, '/');
const idx = oldPath.lastIndexOf('/');
_setDirLastFocus(finalKey, (idx >= 0 ? oldPath.substring(0, idx + 1) : '') + (d.new_name || ''));
return _reloadFiles(true).then(function () {
alert('重命名成功');
});
}
alert(d.message || '重命名失败');
}).catch(function () { alert('重命名失败'); });
}
function openFileDirectory(colKey) {
colKey = _resolveColKey(colKey);
const entityId = _entityId();
if (!entityId) {
alert('无法获取当前' + (cfg.entityLabel || '实体'));
return;
}
const sel = getSelectedFile(colKey);
const path = sel && sel.path ? sel.path : null;
const payload = _paramBody(colKey, path);
fetch(_filesApi(entityId) + '/open-directory', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
}).then(function (r) { return r.json(); }).then(function (d) {
if (!d.success) alert(d.message || '打开目录失败');
}).catch(function () { alert('打开目录失败'); });
}
function createDirectory(colKey) {
if (!_guardWrite()) return;
// 忽略误传入的 Event/boolean
if (colKey != null && typeof colKey !== 'string') colKey = null;
// Tab 单树:以当前激活选项卡为准(内存态优先,见 _resolveColKey)
if (tabsMode) {
colKey = activeColumnKey || _readActiveSubdirFromDom() || null;
}
colKey = _resolveColKey(colKey);
const entityId = _entityId();
if (!entityId) return;
if (!colKey && !pathBasedMode) {
alert('请先选择子目录选项卡');
return;
}
// 在 prompt 前固定目标子目录,避免异步/焦点变化导致落到首个选项卡
const mkdirColKey = colKey;
const sel = getSelectedFile(mkdirColKey);
let parentPath = (sel && sel.type === 'directory' && sel.path) ? sel.path : '';
if (pathBasedMode && !parentPath) parentPath = _apiParamValue(mkdirColKey);
const name = (prompt('请输入新目录名称:', '') || '').trim();
if (!name) return;
const payload = Object.assign(_paramBody(mkdirColKey, parentPath), { name: name });
if (!pathBasedMode && apiParamKey && !payload[apiParamKey]) {
payload[apiParamKey] = _apiParamValue(mkdirColKey);
}
fetch(_filesApi(entityId) + '/mkdir', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
.then(function (r) { return r.json(); })
.then(function (d) {
if (d.success) {
// 刷新列表时保持当前选项卡,勿回落到默认/第一个子目录
if (tabsMode && mkdirColKey) {
activeColumnKey = mkdirColKey;
if (sharedListId) listIdToKey[sharedListId] = activeColumnKey;
_syncSubdirTabs(activeColumnKey);
}
_reloadFiles(false);
alert('目录创建成功');
} else {
alert(d.message || '创建失败');
}
})
.catch(function () { alert('创建目录失败'); });
}
function _extractDirTreeOnly(items) {
const out = {};
(items || []).forEach(function (it) {
if (!it || it.type !== 'directory') return;
out[it.name] = _extractDirTreeOnly(it.children || []);
});
return out;
}
function _buildPathMap(items, map) {
(items || []).forEach(function (it) {
if (!it || !it.path) return;
map[it.path] = it;
if (it.type === 'directory' && it.children && it.children.length) {
_buildPathMap(it.children, map);
}
});
}
function _getSelectedItem(colKey) {
const col = _col(colKey);
if (!col) return null;
const ul = _qs(col.listId);
if (!ul) return null;
const li = ul.querySelector('li.selected');
if (!li) return null;
return {
path: (li.getAttribute('data-path') || '').trim(),
type: (li.getAttribute('data-type') || '').trim(),
};
}
function _getPasteTargetParentPathForStructure(colKey) {
const sel = _getSelectedItem(colKey);
if (!sel || !sel.path) return '';
if (sel.type === 'directory') return sel.path;
const idx = sel.path.replace(/\\/g, '/').lastIndexOf('/');
return idx >= 0 ? sel.path.substring(0, idx) : '';
}
async function copyDirectoryStructure(colKey) {
if (!features.dirStructure) return;
if (colKey != null && typeof colKey !== 'string') colKey = null;
colKey = _resolveColKey(colKey);
const entityId = _entityId();
if (!entityId) { alert('无法获取当前' + (cfg.entityLabel || '实体')); return; }
const items = filesData ? (filesData[colKey] || []) : [];
if (!items) { alert('目录数据尚未加载完成,请稍后重试。'); return; }
const sel = _getSelectedItem(colKey);
let fromPath = '';
if (sel && sel.path) {
if (sel.type === 'directory') fromPath = sel.path;
else fromPath = _getPasteTargetParentPathForStructure(colKey);
}
let treeObj = {};
if (!fromPath) {
treeObj = _extractDirTreeOnly(items);
} else {
const map = {};
_buildPathMap(items, map);
const node = map[fromPath];
if (!node || node.type !== 'directory') {
alert('未找到选中目录对应的结构,请先展开/刷新后重试。');
return;
}
treeObj = _extractDirTreeOnly(node.children || []);
}
const payload = {
from_path: fromPath,
tree: treeObj,
copied_at: new Date().toISOString(),
};
payload[apiParamKey] = _apiParamValue(colKey);
try {
await fetch('/api/dir-structure/copy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ scope: cfg.structureScope, payload: payload }),
}).then(function (r) { return r.json(); }).then(function (d) {
if (!d.success) throw new Error(d.message || '复制失败');
});
alert('已复制目录结构(不含文件)。\n\n可在目标父目录点击“粘贴目录结构”。');
} catch (e) {
alert('复制失败:' + (e && e.message ? e.message : e));
}
}
async function _mkdir(entityId, colKey, parentPath, name) {
const res = await fetch(_filesApi(entityId) + '/mkdir', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.assign(_paramBody(colKey, parentPath || ''), { name: name })),
});
return await res.json();
}
async function _pasteTree(entityId, colKey, parentPath, tree) {
const ok = [];
const bad = [];
const entries = Object.keys(tree || {});
for (let i = 0; i < entries.length; i++) {
const dirName = entries[i];
const r = await _mkdir(entityId, colKey, parentPath, dirName);
if (r && r.success) ok.push((parentPath ? (parentPath + '/') : '') + dirName);
else bad.push({ path: (parentPath ? (parentPath + '/') : '') + dirName, message: (r && r.message) ? r.message : '创建失败' });
const nextParent = parentPath ? (parentPath.replace(/\/+$/g, '') + '/' + dirName) : dirName;
const child = tree[dirName];
if (child && typeof child === 'object' && Object.keys(child).length) {
const childRes = await _pasteTree(entityId, colKey, nextParent, child);
ok.push.apply(ok, childRes.ok);
bad.push.apply(bad, childRes.bad);
}
}
return { ok: ok, bad: bad };
}
async function pasteDirectoryStructure(colKey) {
if (!features.dirStructure) return;
if (!_guardWrite()) return;
if (colKey != null && typeof colKey !== 'string') colKey = null;
colKey = _resolveColKey(colKey);
const entityId = _entityId();
if (!entityId) { alert('无法获取当前' + (cfg.entityLabel || '实体')); return; }
let payload = null;
try {
payload = await fetch('/api/dir-structure/latest?scope=' + encodeURIComponent(cfg.structureScope), { cache: 'no-store' }).then(function (r) { return r.json(); });
} catch (e) { /* ignore */ }
const p = payload && payload.success ? payload.payload : null;
if (!p || !p.tree) {
alert('没有可粘贴的目录结构,请先点击“复制目录结构”。');
return;
}
const parentPath = _getPasteTargetParentPathForStructure(colKey) || '';
const label = _columnLabel(colKey);
if (!confirm('确定要把已复制的目录结构粘贴到:\n\n' + (label + '/' + (parentPath || '(根目录)')) + '\n\n(只会创建目录,不会复制文件)')) return;
try {
const result = await _pasteTree(entityId, colKey, parentPath, p.tree);
let msg = '';
if (result.ok.length) msg += '成功创建 ' + result.ok.length + ' 个目录:\n- ' + result.ok.slice(0, 50).join('\n- ') + (result.ok.length > 50 ? '\n...(已省略)' : '') + '\n';
if (result.bad.length) msg += '\n失败 ' + result.bad.length + ' 个:\n- ' + result.bad.slice(0, 50).map(function (x) { return x.path + ':' + x.message; }).join('\n- ') + (result.bad.length > 50 ? '\n...(已省略)' : '');
alert(msg.trim() || '操作完成');
_fetchFiles(entityId);
} catch (e) {
alert('粘贴失败:' + (e && e.message ? e.message : e));
}
}
function openFile(colKey) {
const entityId = _entityId();
const sel = getSelectedFile(colKey);
if (!entityId || !sel || !sel.path) { alert('请先选择文件'); return; }
if (sel.type === 'directory') { alert('不能打开目录,请选择文件'); return; }
let body = _paramBody(colKey, sel.path);
if (features.wps && cfg.wpsRadioName) {
const openWith = (document.querySelector('input[name="' + cfg.wpsRadioName + '"]:checked') || {}).value || 'default';
body.open_with = openWith;
if (openWith === 'wps' && cfg.wpsInputId) {
const input = _qs(cfg.wpsInputId);
if (input) body.wps_exe = (input.value || '').trim() || null;
}
}
fetch(_filesApi(entityId) + '/open-file', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).then(function (r) { return r.json(); }).then(function (d) {
if (!d.success) alert(d.message || '打开文件失败');
}).catch(function () { alert('打开文件失败'); });
}
function saveWpsOpenPath() {
if (!features.wps) return;
if (global.IARDirOpsWps) {
IARDirOpsWps.saveFromInput(cfg.wpsInputId);
return;
}
const input = cfg.wpsInputId ? _qs(cfg.wpsInputId) : null;
if (!input || !global.localStorage) return;
const val = (input.value || '').trim();
if (val) {
localStorage.setItem('wpsCustomExePath', val);
alert('WPS 路径已保存');
} else {
localStorage.removeItem('wpsCustomExePath');
alert('已清空 WPS 路径,将使用自动查找');
}
}
function openPresetRenameModal(colKey) {
if (!features.presetRename) return;
colKey = _resolveColKey(colKey);
_rememberDirFocusFromSelection();
const entityId = _entityId();
const sel = getSelectedFile(colKey);
if (!entityId || !sel || !sel.path) { alert('请先选择要重命名的文件或目录'); return; }
if (!global.IARPresetRename) { alert('预置重命名模块未加载'); return; }
const ctx = {
kind: cfg.presetRenameKind,
id: entityId,
path: sel.path,
};
if (!pathBasedMode) ctx[apiParamKey] = _apiParamValue(colKey);
IARPresetRename.open({
context: ctx,
onApply: function (applyCtx, newName) {
const body = { path: applyCtx.path, new_name: newName };
if (!pathBasedMode) body[apiParamKey] = applyCtx[apiParamKey];
return fetch(_filesApi(applyCtx.id) + '/rename', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).then(function (r) { return r.json(); }).then(function (d) {
if (d && d.success) {
const oldPath = String(applyCtx.path || '').replace(/\\/g, '/');
const idx = oldPath.lastIndexOf('/');
_setDirLastFocus(colKey, (idx >= 0 ? oldPath.substring(0, idx + 1) : '') + (d.new_name || newName));
return _reloadFiles(true).then(function () { return d; });
}
return d;
});
},
});
}
const api = {
cfg: cfg,
openModal: openModal,
openRootDirectory: openRootDirectory,
refresh: refresh,
refreshTreeView: refreshTreeView,
switchSubdir: switchSubdir,
loadColumns: loadColumns,
copyPath: copyPath,
cutPath: cutPath,
pastePath: pastePath,
openCopyTo: openCopyTo,
openCopyFrom: openCopyFrom,
copyFileName: copyFileName,
copyViewRelPath: copyViewRelPath,
copyViewAbsPath: copyViewAbsPath,
browseFile: browseFile,
downloadFile: downloadFile,
addFile: addFile,
addFileToRoot: addFileToRoot,
takePhoto: takePhoto,
prepareTakePhoto: prepareTakePhoto,
completeTakePhoto: completeTakePhoto,
deleteFile: deleteFile,
backupFile: backupFile,
renameFile: renameFile,
renameFileWithTimestamp: renameFileWithTimestamp,
openFileDirectory: openFileDirectory,
createDirectory: createDirectory,
copyDirectoryStructure: copyDirectoryStructure,
pasteDirectoryStructure: pasteDirectoryStructure,
openFile: openFile,
saveWpsOpenPath: saveWpsOpenPath,
openPresetRenameModal: openPresetRenameModal,
getActiveColumnKey: function () { return _resolveColKey(null); },
getApiParamValue: function (colKey) { return _apiParamValue(colKey); },
fetchFilesData: fetchFilesData,
getSelectedFiles: getSelectedFiles,
getSelectedFile: getSelectedFile,
};
initDragDrop();
return api;
}
function register(opsId, cfg) {
cfg.opsId = opsId;
const inst = createInstance(cfg);
_registry[opsId] = inst;
if (cfg.legacy) {
Object.keys(cfg.legacy).forEach(function (k) {
const fnName = cfg.legacy[k];
if (fnName && typeof inst[k] === 'function') {
global[fnName] = function () { return inst[k].apply(inst, arguments); };
}
});
}
return inst;
}
function invoke(opsId, method) {
const inst = _registry[opsId];
if (!inst || typeof inst[method] !== 'function') {
console.error('IARDirOpsColumns: unknown', opsId, method);
return;
}
const args = Array.prototype.slice.call(arguments, 2);
// 拍照:先打开相机弹窗,权限在确认保存时再校验(见 completeTakePhoto)
if (method === 'takePhoto') {
return inst[method].apply(inst, args);
}
const cfg = inst.cfg;
if (cfg && cfg.permissions && cfg.permissionCheck) {
let perm = cfg.permissions[method];
if (typeof perm === 'function') {
perm = perm.apply(inst, args);
}
if (perm) {
return cfg.permissionCheck(perm, function () {
return inst[method].apply(inst, args);
});
}
}
return inst[method].apply(inst, args);
}
function get(opsId) { return _registry[opsId]; }
/** 读取当前激活的子目录键(优先 DOM 选项卡) */
function getActiveSubdir(opsId) {
const inst = _registry[opsId];
if (!inst || typeof inst.getActiveColumnKey !== 'function') return null;
return inst.getActiveColumnKey() || null;
}
function listCopyTargets(excludeOpsId) {
const out = [];
const registryKeys = Object.keys(_registry);
Object.keys(_registry).forEach(function (opsId) {
if (opsId === excludeOpsId) return;
const inst = _registry[opsId];
const c = inst && inst.cfg;
if (!c || c.copyToTargetPage === false) return;
const entityId = resolveCopyTargetEntityId(opsId, c);
const disabled = !entityId;
const pageLabel = c.copyToPageLabel || c.copyToBoxLabel || c.entityLabel || opsId;
(c.columns || []).forEach(function (col) {
out.push({
opsId: opsId,
colKey: col.key,
colLabel: col.label || col.key,
boxLabel: c.copyToBoxLabel || c.entityLabel || opsId,
pageLabel: pageLabel,
pageKey: opsId,
entityId: entityId,
isCurrent: false,
disabled: disabled,
disabledReason: disabled ? '请先在对应页面打开目录操作对话框' : '',
});
});
});
return out;
}
function listCopyTargetPages(excludeOpsId) {
const pages = [];
const seen = {};
listCopyTargets(excludeOpsId).forEach(function (t) {
if (seen[t.pageKey]) {
if (!t.disabled) {
seen[t.pageKey].disabled = false;
seen[t.pageKey].disabledReason = '';
}
return;
}
const page = {
opsId: t.pageKey,
pageLabel: t.pageLabel,
entityId: t.entityId,
disabled: !!t.disabled,
disabledReason: t.disabledReason || '',
};
seen[t.pageKey] = page;
pages.push(page);
});
pages.sort(function (a, b) {
return String(a.pageLabel).localeCompare(String(b.pageLabel), 'zh-CN');
});
return pages;
}
function fetchTargetTree(opsId, entityId) {
const inst = _registry[opsId];
if (!inst || typeof inst.fetchFilesData !== 'function') {
return Promise.reject(new Error('目录框未就绪'));
}
return inst.fetchFilesData(entityId);
}
global.IARDirOpsColumns = {
register: register,
invoke: invoke,
getActiveSubdir: getActiveSubdir,
get: get,
listCopyTargets: listCopyTargets,
listCopyTargetPages: listCopyTargetPages,
resolveCopyTargetEntityId: resolveCopyTargetEntityId,
fetchTargetTree: fetchTargetTree,
};
})(typeof window !== 'undefined' ? window : this);