function get_filename(filePath) { if (!filePath) return ""; return filePath.split(/[/\\]/).pop(); } function escapeAttr(s) { if (s == null) return ""; return String(s).replace(/&/g, "&").replace(/"/g, """).replace(//g, ">"); } var SOON_EMPTY_IMG = '../assets/images/web/empty-state.png'; function soonEmptyBlock(title, hint, extraHtml) { var html = '
' + '' + '

' + escapeAttr(title) + '

'; if (hint) { html += '

' + escapeAttr(hint) + '

'; } if (extraHtml) html += extraHtml; html += '
'; return html; } let s_lan = "zh"; function language_str(str) { let t = { "noFile": { zh: "当前文件不存在!", ozh: "This file does not exist!", en: "File not found!" }, "saveTime": { zh: "保存时间:", ozh: "保存時間:", en: "Saved on:" }, "selectFile": { zh: "请选择文件", ozh: "請選擇文件", en: "Please select a file" }, "comfirm": { zh: "确认", ozh: "確認", en: "Confirm" }, "cancel": { zh: "取消", ozh: "取消", en: "Cancel" }, "SDFile": { zh: "SoonDesign模板文件", ozh: "SoonDesign模闆文件", en: "SoonDesign Template File" }, "lost": { zh: "(文件已丢失)", ozh: "(文件已丟失)", en: "(File Lost)" }, "clickToDelete": { zh: "文件已丢失,点击删除此记录", ozh: "文件已丟失,點擊刪除此記錄", en: "File lost, click to remove" }, "deleted": { zh: "已删除", ozh: "已刪除", en: "Deleted" }, "whetherSave": { zh: "是否保存当前文件?", ozh: "是否保存當前文件?", en: "Save current file?" }, "delTitle": { zh: "警告", ozh: "警告", en: "Warning" }, "delContent": { zh: "文件已丢失,确认是否删除?", ozh: "文件已丟失,確認是否刪除?", en: "File lost, confirm delete?" }, "deleteFileConfirm": { zh: "确认删除该文件?删除后无法恢复。", ozh: "確認刪除該文件?刪除後無法恢復。", en: "Delete this file? This cannot be undone." }, "deleteBtn": { zh: "删除", ozh: "刪除", en: "Delete" } }; return t[str][s_lan] || t[str]['zh']; } function openDesign(type, filePath) { if (window.platformBridge && window.platformBridge.openDesignPage) { window.platformBridge.openDesignPage(filePath || '', type); } } layui.use(['layer', 'form', 'jquery'], function () { var $ = layui.$; var layer = layui.layer; layer.config({ skin: 'soon-layer' }); if (window.sysAPI && window.sysAPI.getAppVersion) { window.sysAPI.getAppVersion().then(function (ver) { $("#app-version").text("v" + ver); }).catch(function () {}); } function langua_ge(lan) { lan = lan || 'zh'; $("[language='m']").each(function () { $(this).html($(this).attr(lan)); }); $("[language='t']").each(function () { $(this).attr("title", $(this).attr(lan)); }); } window.soonResolveLocale(function (code) { s_lan = code; langua_ge(s_lan); $("#language_select").val(s_lan); try { localStorage.setItem("lang", s_lan); } catch (e) {} }); $('#language_select').on('change', function () { langua_ge($(this).find('option:selected').val()); s_lan = $(this).find('option:selected').val(); localStorage.setItem("lang", s_lan); loadHistory(); }); function hasCloudAuth() { if (typeof window.soonGetAccessToken === 'function') return !!window.soonGetAccessToken(); try { return !!localStorage.getItem('soon_access'); } catch (e) { return false; } } var fileListState = { page: 1, size: 12, total: 0, items: [] }; var templateListState = { page: 1, size: 8, total: 0, items: [] }; function displayNameFromPath(path) { if (!path) return 'design.soon'; if (typeof window.soonDisplayFileName === 'function') { var fromHelper = window.soonDisplayFileName(path); if (fromHelper) return fromHelper; } var sessionPrefix = 'soondesign_session:'; if (path.indexOf(sessionPrefix) === 0) { var slug = path.substring(sessionPrefix.length).replace(/-\d{10,}$/, ''); return /\.soon$/i.test(slug) ? slug : (slug + '.soon'); } if (path.indexOf('soondesign_file:') === 0) { var meta = window._soonFileMeta; if (meta && meta.name) return meta.name; return path.replace(/^soondesign_file:(\d+).*/, '文件 #$1'); } return get_filename(path) || 'design.soon'; } async function fetchCloudItems() { if (!hasCloudAuth() || !window.platformBridge || !window.platformBridge.listCloudFiles) return []; try { var data = await window.platformBridge.listCloudFiles({ page: 1, size: 50 }); return (data && data.items) ? data.items : []; } catch (e) { return []; } } function removeLocalHistoryPath(path) { if (!path) return Promise.resolve(); if (typeof window.soonRecentRemove === 'function') window.soonRecentRemove(path); if (typeof window.soonLocalRemove === 'function') { return window.soonLocalRemove(path); } return Promise.resolve(); } function recentFallbackThumb(type) { var t = Number(type) || 1; return soonAsset(t === 2 ? 'bg_2.png' : 'bg_1.png'); } async function resolveRecentThumb(item) { var realType = item.type || 1; var fallback = recentFallbackThumb(realType); var thumbKey = item.thumbRef || item.filePath || item.key; if (typeof window.soonLocalGetThumb === 'function' && thumbKey) { var localThumb = await window.soonLocalGetThumb(thumbKey); if (localThumb) { return typeof soonSafeImageUrl === 'function' ? soonSafeImageUrl(localThumb, fallback) : localThumb; } } if (item.kind === 'template' && item.filePath) { var tplMatch = String(item.filePath).match(/^soondesign_template:(\d+)/); if (tplMatch) { var base = (window.SOON_DEPLOY_CONFIG && window.SOON_DEPLOY_CONFIG.api_v1_base) || ''; if (base) { var v = item.updated_at ? ('?v=' + encodeURIComponent(item.updated_at)) : ''; return base + '/templates/' + tplMatch[1] + '/thumb' + v; } } } if (item.kind === 'cloud' && item.fileId && hasCloudAuth()) { var apiBase = (window.SOON_DEPLOY_CONFIG && window.SOON_DEPLOY_CONFIG.api_v1_base) || ''; if (apiBase) return apiBase + '/files/' + item.fileId + '/thumb'; } return fallback; } function recentDownloadBtnHtml() { return ''; } function recentDeleteBtnHtml() { return ''; } function renderFilePager() { var el = document.getElementById('filePager'); if (!el) return; var page = fileListState.page; var size = fileListState.size; var total = fileListState.total; var pages = Math.max(1, Math.ceil(total / size)); if (total === 0) { el.innerHTML = ''; return; } el.innerHTML = '
' + '' + '第 ' + page + ' / ' + pages + ' 页,共 ' + total + ' 个' + '
'; var prev = document.getElementById('filePrev'); var next = document.getElementById('fileNext'); if (prev && !prev.disabled) { prev.onclick = function () { fileListState.page = Math.max(1, fileListState.page - 1); loadHistory(); }; } if (next && !next.disabled) { next.onclick = function () { fileListState.page = Math.min(pages, fileListState.page + 1); loadHistory(); }; } } var _recentLoadedAt = 0; async function loadHistory(force) { try { if (!force && _recentLoadedAt && (Date.now() - _recentLoadedAt) < 60000) { return; } if (typeof window.soonRecentMigrateFromHistory === 'function') { window.soonRecentMigrateFromHistory(); } var recentCountEl = document.getElementById('recentCount'); var items = typeof window.soonRecentList === 'function' ? window.soonRecentList() : []; var mapped = items.map(function (it) { return { kind: it.kind || (typeof window.soonRecentKindFromKey === 'function' ? window.soonRecentKindFromKey(it.key) : 'local'), filePath: it.key, fileId: it.fileId, name: it.name, type: it.type, thumbRef: it.thumbRef || it.key, updated_at: it.updated_at || '' }; }); if (hasCloudAuth() && typeof window.soonRecentEnrichFromCloud === 'function') { var cloudItems = await fetchCloudItems(); mapped = window.soonRecentEnrichFromCloud(mapped, cloudItems); } fileListState.items = mapped; fileListState.total = mapped.length; var pages = Math.max(1, Math.ceil(fileListState.total / fileListState.size)); if (fileListState.page > pages) fileListState.page = pages; _recentLoadedAt = Date.now(); if (recentCountEl) recentCountEl.textContent = String(fileListState.total); if (!mapped.length) { $(".card-list").html(soonEmptyBlock('暂无文件', '点击「打开文件」导入,或新建模板开始设计')); renderFilePager(); return; } var start = (fileListState.page - 1) * fileListState.size; var slice = mapped.slice(start, start + fileListState.size); var thumbRows = await Promise.all(slice.map(async function (item) { var realType = item.type || 1; return { item: item, src: await resolveRecentThumb(item), fallbackSrc: recentFallbackThumb(realType) }; })); let h = ""; for (let row of thumbRows) { let item = row.item; let filePath = item.filePath; let realType = item.type || 1; let src = row.src; let fallbackSrc = row.fallbackSrc; let displayName = item.name || displayNameFromPath(filePath); let cardTitle = displayName; var cardClass = 'card'; var actions = recentDownloadBtnHtml() + recentDeleteBtnHtml(); h += `
${actions}
${escapeAttr(displayName)}
`; } $(".card-list").html(h); renderFilePager(); } catch (e) { console.error("加载文件列表出错", e); $(".card-list").html(soonEmptyBlock('加载失败', '请刷新页面重试', '')); var retry = document.getElementById('fileListRetry'); if (retry) retry.onclick = function () { loadHistory(true); }; if (document.getElementById('filePager')) document.getElementById('filePager').innerHTML = ''; } } function renderTemplatesError(message) { var grid = document.getElementById('templatesGrid'); var countEl = document.getElementById('templateCount'); if (!grid) return; templateListState.items = []; templateListState.total = 0; templateListState.page = 1; grid.innerHTML = soonEmptyBlock(message, null, ''); if (countEl) countEl.textContent = '!'; renderTemplatePager(); var btn = document.getElementById('templatesRetry'); if (btn) btn.onclick = loadTemplates; } function templateFallbackThumb(type) { var t = Number(type) || 1; return soonAsset(t === 2 ? 'bg_2.png' : 'bg_1.png'); } function resolveTemplateItem(m, base) { var type = Number(m.type) || 1; var id = m.id; var v = m.updated_at ? ('?v=' + encodeURIComponent(m.updated_at)) : ''; return { id: id, name: m.name || m.title || '模板', type: type, updated_at: m.updated_at || '', thumbSrc: id ? (base + '/templates/' + id + '/thumb' + v) : templateFallbackThumb(type) }; } function openTemplateItem(m) { var type = Number(m.type) || 1; var id = m && m.id; if (!id) { if (typeof window.soonToast === 'function') window.soonToast('模板不可用', 'error'); return; } window._soonTemplateMeta = { id: id, name: m.name || m.title || '模板', type: type, updated_at: m.updated_at || '' }; var templateKey = typeof window.soonMakeTemplateKey === 'function' ? window.soonMakeTemplateKey(id) : ('soondesign_template:' + id); openDesign(type, templateKey); } function templateCardHtml(m, itemIndex) { var type = Number(m.type) || 1; var fallback = templateFallbackThumb(type); var thumbSrc = m.thumbSrc || fallback; var esc = typeof soonEscapeHtml === 'function' ? soonEscapeHtml : escapeAttr; var name = esc(m.name || m.title || '模板'); var rectClass = 'rect' + (type == 2 ? ' rect1' : ''); return '
' + '
' + '' + '
' + name + '
' + '
'; } function bindTemplateCards(grid) { if (!grid) return; grid.querySelectorAll('.card[data-index]').forEach(function (card) { card.onclick = function () { var idx = Number(card.dataset.index); var m = templateListState.items[idx]; if (m) openTemplateItem(m); }; }); } function renderTemplatePager() { var prevNav = document.getElementById('templatePrev'); var nextNav = document.getElementById('templateNext'); var page = templateListState.page; var size = templateListState.size; var total = templateListState.total; var pages = Math.max(1, Math.ceil(total / size)); if (prevNav) prevNav.disabled = total === 0 || page <= 1; if (nextNav) nextNav.disabled = total === 0 || page >= pages; } function goTemplatePage(page) { var pages = Math.max(1, Math.ceil(templateListState.total / templateListState.size)); templateListState.page = Math.max(1, Math.min(pages, page)); renderTemplatesPage(); } function renderTemplatesPage() { var grid = document.getElementById('templatesGrid'); var countEl = document.getElementById('templateCount'); if (!grid) return; var items = templateListState.items || []; templateListState.total = items.length; if (countEl) countEl.textContent = String(items.length); if (!items.length) { grid.innerHTML = soonEmptyBlock('暂无模板'); renderTemplatePager(); return; } var start = (templateListState.page - 1) * templateListState.size; var slice = items.slice(start, start + templateListState.size); grid.innerHTML = slice.map(function (m, i) { return templateCardHtml(m, start + i); }).join(''); bindTemplateCards(grid); renderTemplatePager(); } var _templatesLoadedAt = 0; async function loadTemplates(force) { var grid = document.getElementById('templatesGrid'); var countEl = document.getElementById('templateCount'); if (!grid) return; if (!force && _templatesLoadedAt && (Date.now() - _templatesLoadedAt) < 60000) { return; } var base = (window.SOON_DEPLOY_CONFIG && window.SOON_DEPLOY_CONFIG.api_v1_base) || ''; if (!base) { templateListState.items = []; templateListState.total = 0; templateListState.page = 1; grid.innerHTML = soonEmptyBlock('暂不可用', '请稍后重试'); if (countEl) countEl.textContent = '0'; renderTemplatePager(); return; } try { var r = await fetch(base + '/templates'); var j = await r.json(); if (!j.ok) { renderTemplatesError(j.message || '模板加载失败'); return; } var items = (j.data && j.data.items) ? j.data.items : []; templateListState.items = items.map(function (it) { return resolveTemplateItem(it, base); }); templateListState.total = templateListState.items.length; templateListState.page = 1; renderTemplatesPage(); _templatesLoadedAt = Date.now(); } catch (e) { renderTemplatesError('网络错误,请稍后重试'); } } loadHistory(true); loadTemplates(); window.soonReloadRecentFiles = function () { loadHistory(true); }; window.soonReloadTemplates = function () { loadTemplates(true); }; document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') { loadTemplates(false); loadHistory(false); } }); window.addEventListener('pageshow', function (e) { if (e.persisted) { loadTemplates(false); loadHistory(false); } }); var templatePrevNav = document.getElementById('templatePrev'); var templateNextNav = document.getElementById('templateNext'); if (templatePrevNav) { templatePrevNav.onclick = function () { if (!templatePrevNav.disabled) goTemplatePage(templateListState.page - 1); }; } if (templateNextNav) { templateNextNav.onclick = function () { if (!templateNextNav.disabled) goTemplatePage(templateListState.page + 1); }; } $("#openfile").click(function () { OpenDialog(); }); $("#new1").click(function () { openDesign(1, ''); }); $("#new2").click(function () { openDesign(2, ''); }); function confirmDeleteCloudFile(fileId, message, onDone) { if (!fileId) return; layer.open({ type: 1, skin: 'soon-layer', title: language_str("delTitle"), content: '
' + message + '
', btn: [language_str("comfirm"), language_str("cancel")], btnAlign: 'r', area: ['320px', 'auto'], resize: false, shadeClose: true, yes: async function (index) { if (window.platformBridge && window.platformBridge.deleteCloudFile) { try { await window.platformBridge.deleteCloudFile(fileId); } catch (e) { /* ignore */ } } if (typeof window.soonRecentList === 'function') { window.soonRecentList().forEach(function (it) { if (it.fileId === fileId) { if (typeof window.soonRecentRemove === 'function') window.soonRecentRemove(it.key); if (typeof window.soonLocalRemove === 'function') window.soonLocalRemove(it.key); } }); } layer.msg(language_str("deleted"), { icon: 1, time: 1000 }); if (typeof onDone === 'function') onDone(); layer.close(index); } }); } $(".card-list").on("click", '.soon-file-card__download', function (e) { e.stopPropagation(); var card = $(this).closest('.card'); var filePath = card.attr('data-file') || ''; var kind = card.attr('data-kind') || 'local'; var fileId = parseInt(card.attr('data-id'), 10); var name = card.attr('data-name') || 'design.soon'; var type = parseInt(card.attr('data-type'), 10) || 1; var item = { kind: kind, filePath: filePath, key: filePath, fileId: fileId || undefined, name: name, type: type }; if (typeof window.soonDownloadRecentItem === 'function') { window.soonDownloadRecentItem(item); } }); $(".card-list").on("click", '.soon-file-card__delete', function (e) { e.stopPropagation(); var card = $(this).closest('.card'); var kind = card.attr('data-kind') || 'cloud'; var fileId = parseInt(card.attr('data-id'), 10); var filePath = card.attr('data-file') || ''; if (kind === 'local' || !fileId) { layer.open({ type: 1, skin: 'soon-layer', title: language_str("delTitle"), content: '
' + language_str('deleteFileConfirm') + '
', btn: [language_str("comfirm"), language_str("cancel")], btnAlign: 'r', area: ['320px', 'auto'], resize: false, shadeClose: true, yes: function (index) { removeLocalHistoryPath(filePath).then(function () { if (filePath.indexOf('soondesign_session:') === 0) { try { sessionStorage.removeItem(filePath); localStorage.removeItem(filePath); } catch (err) { /* ignore */ } } layer.msg(language_str("deleted"), { icon: 1, time: 1000 }); loadHistory(true); layer.close(index); }); } }); return; } confirmDeleteCloudFile(fileId, language_str('deleteFileConfirm'), function () { loadHistory(true); }); }); $(".card-list").on("click", '.card', function () { let filePath = $(this).attr("data-file") || $(this).attr("data"); let type = Number($(this).attr("data-type")) || 1; if (typeof window.soonBindFileMeta === 'function') { window.soonBindFileMeta(filePath, { name: $(this).attr('data-name') || '' }); } openDesign(type, filePath); }); function OpenDialog() { var dialogApi = window.platformBridge && window.platformBridge.showOpenDialog ? { showOpenDialog: function (opts) { return window.platformBridge.showOpenDialog(opts); } } : null; if (!dialogApi) return; dialogApi.showOpenDialog({ title: language_str("selectFile"), buttonLabel: language_str("comfirm"), filters: [{ name: language_str("SDFile"), extensions: ['soon'] }] }).then(async function (result) { if (result.canceled) return; var file = (result.files && result.files[0]) || result.file; if (!file || !file.text) { layer.msg(language_str("noFile")); return; } var fileName = file.name || 'design.soon'; var soonData; try { soonData = JSON.parse(await file.text()); } catch (e) { layer.msg(language_str("noFile")); return; } var openP = window.soonOpenSoonJsonLocally(soonData, fileName); if (openP && typeof openP.then === 'function') { openP.catch(function () {}); } }).catch(function (err) { console.log(err); }); } });