gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
帮我以纯html制作一个货架数据管理系统,要求excel可以导出保存,要求excel可以导出保存,要求数据excel可以导出保存,若无数据,则该系统提供excel表单格式示例。…
- User
帮我以纯html制作一个货架数据管理系统,要求excel可以导出保存,要求excel可以导出保存,要求数据excel可以导出保存,若无数据,则该系统提供excel表单格式示例。
- 产品定位与整体风格 定位:一款专注于货架与货物管理的轻量级数据库系统,适合小型仓库或门店使用,方便用户快速添加、编辑、分类统计货物。 视觉风格:现代简约+高级感,主调以半透明浅蓝色为基调,辅以银灰和渐变白色,营造淡雅清晰却不沉闷的氛围。 布局形式:经典左右分栏布局,左侧为货架侧边栏,右侧为数据展示与操作区,空间利用合理,层次分明。
- 用户界面与交互设计 左侧侧边栏: 宽度适中(280px),可折叠为小宽度(56px),以图标按钮形式展示,节省空间同时保持功能快捷访问。 显示所有货架列表,每个货架为可点击项目,显示名称且支持重命名、删除(空货架可删)。 侧边栏顶部显示系统LOGO及主题名称,支持用户上传自定义Logo替换预设SVG图标。 底部有切换侧边栏折叠状态按钮,提升界面灵活性。 右侧主内容区: 背景层:使用用户可自定义上传的大背景图片,并叠加“无序动态网状粒子线条背景”动画,兼具美观和活力。 工具栏:顶部包含全局搜索框和文件操作(导入Excel、导出Excel、保存当前数据)按钮,按钮统一风格,支持键盘焦点。 货物列表:当前选中货架的货物列表以表格形式展示,包含复选框支持多选,图片缩略图支持点击查看大图。 操作按钮区:添加、编辑、删除、移动货物按钮设计统一、大小适中,使用圆角及适度阴影,交互时带波纹点击动画和轻柔音效反馈。 添加/编辑货物弹窗:全屏模态弹窗,深色半透明背景,中心呈现圆角大面板,内含输入框和文件上传控件,保证易读易填。 搜索结果弹窗:使用渐变圆角面板,柔和阴影及渐显动画呈现结果,支持关闭按钮且可点击背景关闭,提升用户关注度。
- 功能细节与技术实现重点 Excel导入导出: 采用开源且稳定的SheetJS官方最新版库,保证浏览器端纯前端即可实现; 导入必须符合规定字段格式(品名、种类、数量、金额、图片Base64)且具备错误提示; 导出时自动附加当前时间戳于文件名,避免浏览器缓存影响; 图片Base64数据支持存入Excel,实现全数据完整流转。 数据持久化: 实现浏览器localStorage持久存储,数据结构清晰,包含自定义Logo和背景图数据; 修改时启用“保存”按钮,未保存时关闭按钮不可用,避免误操作; 页面关闭或刷新时,如存在未保存修改自动弹出关闭警告提示。 用户体验加强: 全局点击处产生细腻波纹动画及轻柔点击音效反馈,增强操作感; 鼠标轻移背景产生无序且流畅的网状连接线动态背景,视觉不扰且高级; 输入框、按钮等元素均支持键盘焦点及无障碍标签描述; 导入文件选择、更换大背景及Logo上传均有清晰按钮和操作说明; 货物图片没有则显示斜杠占位,避免页面空洞感。
- 交互流程简述 用户打开系统后,在左侧货架列表快速浏览或选择; 右侧主区展示对应货架的货物列表及统计; 可以通过顶部搜索快速定位某个货物,结果即时弹窗展示详细信息; 添加和编辑货物弹窗简洁,支持上传图片; 多选货物支持快速删除或批量移动至其他货架; 右下角附带按钮可更换或清除当前大背景图,左上logo图标也可自定义上传; Excel导入导出功能便捷,支持批量数据同步及本地备份。
- 设计理念总结 易用性:界面简洁明快,功能操作流畅且逻辑清晰,帮助用户快速完成任务; 视觉舒适:使用清晰的分区、留白和柔和配色,减少视觉疲劳; 现代交互:动画细节和声音反馈让用户感觉系统有活力,提升使用愉悦感; 弹性配置:支持用户自定义主题元素(背景、logo),满足个性化需求; 稳定可靠:Excel数据的导入导出严格校验格式,避免因格式问题造成功能失效。
- Assistant
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>货架数据管理系统</title> <style> /* Reset */ * { margin: 0; padding: 0; box-sizing: border-box; } html, body, #app { height: 100%; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #e6f0ff 0%, #f9fbff 100%); color: #2a3a52; overscroll-behavior: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } /* Utility */ .visually-hidden {position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;} button:focus-visible, input:focus-visible { outline: 2px solid #3399ff; outline-offset: 2px; } /* Layout */ #app { display: flex; height: 100vh; user-select: none; } #sidebar { width: 280px; background: rgba(35,55,95,0.35); backdrop-filter: blur(10px); box-shadow: inset -1px 0 5px rgb(150 170 195 / 0.2); display: flex; flex-direction: column; transition: width 0.3s ease; } #sidebar.collapsed { width: 56px; } #sidebar header { position: relative; height: 64px; border-bottom: 1px solid rgba(255 255 255 / 0.15); display: flex; align-items: center; justify-content: center; padding: 5px 10px; gap: 10px; background: rgba(100 140 255 / 0.18); } #sidebar header img.logo { width: 36px; height: 36px; object-fit: contain; border-radius: 6px; cursor: pointer; filter: drop-shadow(0 0 1px rgba(0,0,0,0.15)); user-select: none; flex-shrink: 0; } #sidebar header h1 { font-weight: 700; font-size: 20px; color: #f0f4ff; user-select: none; white-space: nowrap; flex-grow: 1; transition: opacity 0.3s ease; } #sidebar.collapsed header h1 { opacity: 0; pointer-events: none; width: 0; overflow: hidden; } #shelf-list { flex-grow: 1; overflow-y: auto; padding: 8px 8px 8px 8px; display: flex; flex-direction: column; gap: 6px; } .shelf-item { display: flex; align-items: center; justify-content: space-between; background: rgba(255 255 255 / 0.1); border-radius: 6px; padding: 6px 12px; font-size: 14px; color: #e4ebff; cursor: pointer; user-select: none; transition: background-color 0.2s ease; position: relative; } .shelf-item:hover, .shelf-item.active { background: rgba(120 160 255 / 0.35); } .shelf-item[contenteditable="true"] { background: rgba(255 255 255 / 0.22); outline: 2px solid #81aaff; color: #1358ff; cursor: text; } .shelf-icon{ flex-shrink: 0; width: 28px; height: 28px; margin-right: 10px; fill: #aac8ff; user-select:none; transition: fill 0.3s ease; } #sidebar.collapsed .shelf-item span.shelf-text { display: none; } .shelf-actions { display: flex; gap: 4px; visibility: hidden; flex-shrink: 0; } .shelf-item:hover .shelf-actions, .shelf-item[contenteditable="true"] .shelf-actions { visibility: visible; } .shelf-action-btn { width: 24px; height: 24px; background: rgba(255 255 255 / 0.15); border-radius: 4px; border: none; cursor: pointer; color: #bbd1ff; display: flex; align-items: center; justify-content: center; transition: background-color 0.25s ease, color 0.25s ease; } .shelf-action-btn:hover { background: rgba(255 255 255 / 0.3); color: #2a5bff; } .shelf-action-btn svg { width: 16px; height: 16px; pointer-events: none; stroke-width: 2; } #sidebar footer { border-top: 1px solid rgba(255 255 255 / 0.2); padding: 5px; display: flex; justify-content: center; } #sidebar footer button { width: 36px; height: 36px; background: rgba(255 255 255 / 0.15); border-radius: 8px; border: none; cursor: pointer; color: #aac8ff; display: flex; align-items: center; justify-content: center; transition: background-color 0.3s ease; } #sidebar footer button:hover { background: rgba(255 255 255 / 0.35); } #sidebar footer button svg { width: 24px; height: 24px; } /* Main content */ #main { flex-grow: 1; position: relative; background: #f2f8ff; overflow: hidden; display: flex; flex-direction: column; } #background-layer { position: absolute; top: 0; left: 0; right: 0; bottom: 0; overflow: hidden; z-index: 0; pointer-events: none; } #background-layer img#userBg { position: absolute; top: 50%; left: 50%; width: 120%; height: 120%; object-fit: cover; transform: translate(-50%, -50%); opacity: 0.3; filter: brightness(0.9); } #particle-canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; } #content { position: relative; flex-grow: 1; display: flex; flex-direction: column; z-index: 2; padding: 16px 24px 16px 24px; } /* Toolbar */ #toolbar { display: flex; gap: 12px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; } #toolbar input[type=search] { flex-grow: 1; height: 36px; padding: 8px 12px; border-radius: 8px; border: 1.5px solid #aebeff; font-size: 16px; background: rgba(255 255 255 / 0.95); color: #223366; transition: border-color 0.3s ease; } #toolbar input[type=search]:focus { border-color: #5a87ff; outline: none; } #toolbar button { height: 36px; padding: 0 14px; border-radius: 12px; border: none; background: linear-gradient(145deg, #678aff, #4564e8); color: #f0f5ff; font-weight: 600; cursor: pointer; user-select: none; box-shadow: 0 2px 6px rgb(70 86 211 / 0.4); display: flex; align-items: center; gap: 6px; transition: background 0.3s ease, box-shadow 0.3s ease; } #toolbar button:disabled { background: #8ba8ffcc; cursor: not-allowed; box-shadow: none; } #toolbar button:hover:not(:disabled) { background: linear-gradient(145deg, #7a9cff, #5674ee); box-shadow: 0 3px 10px rgb(80 100 255 / 0.5); } #toolbar button svg { width: 18px; height: 18px; stroke: #eaf1ff; stroke-width: 2.2; fill: none; } /* Table of goods */ #goods-table-container { flex-grow: 1; overflow: auto; border-radius: 12px; background: rgba(240 244 255 / 0.9); box-shadow: inset 0 0 4px rgb(50 70 110 / 0.15); } table#goods-table { width: 100%; border-collapse: collapse; font-size: 14px; user-select: none; } #goods-table thead { background: linear-gradient(90deg,#d0ddff,#b8cbff); color: #2a3a52; font-weight: 700; } #goods-table th, #goods-table td { padding: 10px 8px; border-bottom: 1px solid #e0e6ff; vertical-align: middle; text-align: center; max-width: 1px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } #goods-table td.image-cell { width: 60px; cursor: pointer; } #goods-table td.image-cell img, #goods-table td.image-cell .placeholder-slash { width: 48px; height: 32px; object-fit: contain; border-radius: 6px; user-select: none; pointer-events: all; } #goods-table td.image-cell .placeholder-slash { display: flex; justify-content: center; align-items: center; background: #8594c8; color: #e7ebff; font-size: 18px; font-weight: 800; font-family: monospace, monospace; transform: rotate(-15deg); } #goods-table tbody tr:hover { background: rgba(100 130 255 / 0.12); } #goods-table tbody tr.selected { background: rgba(90 150 255 / 0.35); color: #fff; } /* Operation buttons */ #operation-buttons { margin-top: 12px; display: flex; gap: 12px; justify-content: center; } #operation-buttons button { flex: 1; max-width: 120px; height: 44px; border-radius: 14px; border: none; background: linear-gradient(145deg,#a8baff,#7a8ffb); box-shadow: 0 3px 8px rgb(75 95 210 / 0.5); color: #f0f5ff; font-weight: 700; cursor: pointer; position: relative; overflow: hidden; } #operation-buttons button:disabled { background: #bbc7fbaa; cursor: not-allowed; box-shadow: none; } #operation-buttons button:focus-visible { outline-offset: 4px; } #operation-buttons button svg { vertical-align: middle; width: 20px; height: 20px; stroke: #eaf1ff; stroke-width: 2; fill: none; margin-right: 6px; pointer-events: none; } /* Ripple animation */ .ripple { position: absolute; border-radius: 50%; background-color: rgba(255,255,255,0.4); animation: ripple-effect 0.6s ease-out; pointer-events: none; transform: scale(0); } @keyframes ripple-effect { to { opacity: 0; transform: scale(2.5); } } /* Modals */ .modal-backdrop { position: fixed; inset: 0; background-color: rgba(15,25,50,0.78); display: flex; justify-content: center; align-items: center; z-index: 2000; } .hidden { display: none !important; } /* Add/Edit modal */ #modal-add-edit { background: rgba(25,35,70,0.95); border-radius: 18px; width: 460px; max-width: 90vw; padding: 20px 24px 26px 24px; box-shadow: 0 0 30px rgb(85 95 151 / 0.6); display: flex; flex-direction: column; gap: 14px; color: #bfd0ff; font-size: 16px; } #modal-add-edit h2 { font-weight: 700; color: #a0bbfd; text-align: center; } #modal-add-edit label { display: flex; flex-direction: column; font-weight: 600; user-select: none; } #modal-add-edit input[type=text], #modal-add-edit input[type=number] { margin-top: 6px; height: 36px; padding: 6px 10px; border-radius: 8px; border: none; font-size: 16px; color: #24325c; background: #d9e2ff; } #modal-add-edit input[type=file] { margin-top: 8px; color: #aabbdd; } #modal-add-edit .img-preview { margin: 4px 0 10px 0; width: 112px; height: 72px; border-radius: 10px; background: #e6edff; user-select: none; cursor: pointer; object-fit: contain; box-shadow: 0 0 12px rgb(70 90 170 / 0.45); } #modal-add-edit .preview-container { display: flex; justify-content: center; } #modal-add-edit .modal-footer { display: flex; justify-content: space-evenly; margin-top: 12px; } #modal-add-edit .modal-footer button { width: 110px; height: 42px; border-radius: 18px; font-weight: 700; font-size: 15px; cursor: pointer; border: none; box-shadow: 0 3px 9px rgba(100 140 255 / 0.6); transition: background-color 0.3s ease, color 0.3s ease; } #modal-add-edit .modal-footer button.cancel-btn { background: #768fcc; color: #f2f6ff; filter: brightness(0.85); } #modal-add-edit .modal-footer button.cancel-btn:hover { filter: brightness(1); } #modal-add-edit .modal-footer button.ok-btn { background: #497eff; color: #f9fbffbb; } #modal-add-edit .modal-footer button.ok-btn:disabled { background: #739bfde6; cursor: not-allowed; } #modal-add-edit .modal-footer button.ok-btn:hover:not(:disabled) { background: #3369ff; color: #fff; } /* Search result modal */ #modal-search-result { background: linear-gradient(145deg, #5577ffdd, #89aaffdd); min-width: 320px; max-width: 480px; padding: 16px 20px 24px 20px; border-radius: 20px; box-shadow: 0 6px 24px rgba(40,60,255,0.52); user-select: none; color: #0d1c4a; font-size: 15px; animation: fadeInUp 0.35s ease forwards; display: flex; flex-direction: column; gap: 12px; } @keyframes fadeInUp { from {opacity: 0; transform: translateY(20px);} to {opacity: 1; transform: translateY(0);} } #modal-search-result h3 { font-weight: 700; user-select:none; } #modal-search-result pre { white-space: pre-wrap; user-select:text; overflow-wrap: break-word; } #modal-search-result button.close-btn { position: absolute; top: 12px; right: 12px; background: transparent; border: none; cursor: pointer; width: 28px; height: 28px; stroke: #081442; stroke-width: 3; fill: none; } #modal-search-result button.close-btn:hover { stroke: #001; } /* Image preview modal */ #modal-img-viewer img { max-width: 90vw; max-height: 85vh; border-radius: 18px; pointer-events: none; } /* Custom file input button style */ .file-input-container { position: relative; overflow: hidden; display: inline-block; } .file-input-container input[type=file] { font-size: 100px; position: absolute; left: 0; top: 0; opacity: 0; cursor: pointer; } .file-input-button { height: 36px; background: #5f8affcc; border-radius: 12px; padding: 6px 14px; color: white; font-weight: 600; user-select: none; cursor: pointer; transition: background-color 0.25s ease; border: none; } .file-input-button:hover { background: #3f6fd6cc; } /* Scrollbars for shelf list and table container */ #shelf-list::-webkit-scrollbar, #goods-table-container::-webkit-scrollbar { width: 8px; height: 8px; } #shelf-list::-webkit-scrollbar-thumb, #goods-table-container::-webkit-scrollbar-thumb { background: rgba(70,90,150,0.3); border-radius: 6px; } #shelf-list::-webkit-scrollbar-track, #goods-table-container::-webkit-scrollbar-track { background: transparent; } </style> </head> <body> <div id="app" aria-label="货架数据管理系统"> <!-- 左侧侧边栏 --> <aside id="sidebar" aria-label="货架列表侧边栏" tabindex="0"> <header> <img src="" alt="系统LOGO" id="logo" class="logo" tabindex="0" aria-describedby="logo-desc" /> <h1 id="logo-desc" aria-live="polite">货架数据管理系统</h1> <input type="file" accept="image/png,image/jpeg,image/svg+xml" id="logo-upload" class="visually-hidden" aria-label="上传自定义Logo图片" /> </header> <nav id="shelf-list" role="list" aria-label="货架列表"> <!-- 货架项目模板 --> </nav> <footer> <button id="sidebar-toggle" aria-label="切换侧边栏折叠状态" title="切换侧边栏折叠"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" > <polyline points="6 9 12 15 18 9" /> </svg> </button> </footer> </aside> <!-- 右侧主内容 --> <main id="main" aria-live="polite" aria-label="货架货物展示与操作区"> <!-- 背景层 --> <div id="background-layer" aria-hidden="true"> <img id="userBg" alt="" src="" /> <canvas id="particle-canvas" aria-hidden="true"></canvas> </div> <!-- 工具栏 --> <section id="content"> <div id="toolbar" role="region" aria-label="全局搜索与文件操作栏"> <input type="search" id="global-search" placeholder="搜索货物(品名/种类)" aria-label="全局搜索货物" autocomplete="off" /> <button id="import-excel-btn" type="button" aria-label="导入Excel文件" title="导入Excel文件"> <svg viewBox="0 0 24 24"><path d="M12 3v12m0 0l4-4m-4 4l-4-4m8 8H8a2 2 0 0 1-2-2v-4"/></svg>导入Excel </button> <button id="export-excel-btn" type="button" aria-label="导出Excel文件" title="导出当前数据"> <svg viewBox="0 0 24 24"><path d="M5 12h14M12 5v14M9 16h6"/></svg>导出Excel </button> <button id="save-data-btn" type="button" aria-label="保存当前数据" title="保存当前数据" disabled> <svg viewBox="0 0 24 24"><path d="M5 19h14v-14h-9v4h-5z"/></svg>保存数据 </button> </div> <!-- 货物列表区域 --> <section id="goods-table-container" role="region" aria-label="货物列表" tabindex="0"> <table id="goods-table" aria-describedby="goods-table-description"> <caption id="goods-table-description" class="visually-hidden">显示当前选中货架内的所有货物信息,包括品名、种类、数量、金额和图片。</caption> <thead> <tr> <th><input type="checkbox" id="checkbox-select-all" aria-label="全选货物" /></th> <th>图片</th> <th>品名</th> <th>种类</th> <th>数量</th> <th>金额</th> </tr> </thead> <tbody> <!-- 货物列表行 --> </tbody> </table> </section> <!-- 操作按钮区 --> <div id="operation-buttons" role="group" aria-label="货物操作按钮"> <button id="btn-add" type="button" aria-label="添加货物"> <svg viewBox="0 0 24 24"><path d="M12 5v14m-7-7h14"/></svg>添加 </button> <button id="btn-edit" type="button" aria-label="编辑货物" disabled> <svg viewBox="0 0 24 24"><path d="M12 20h9m-5-14l5 5L7 24H2v-5z"/></svg>编辑 </button> <button id="btn-delete" type="button" aria-label="删除货物" disabled> <svg viewBox="0 0 24 24"><path d="M3 6h18M9 6v12a3 3 0 0 0 6 0V6"/></svg>删除 </button> <button id="btn-move" type="button" aria-label="移动货物" disabled> <svg viewBox="0 0 24 24"><path d="M14 10l4 4m0 0l-4 4m4-4H6"/></svg>移动 </button> </div> <!-- 背景切换按钮区域 --> <div id="bg-image-controls" style="margin-top: 14px; display:flex; gap:12px; justify-content:center;"> <button id="btn-change-bg" type="button" aria-label="更换大背景图" title="更换大背景图">更换背景</button> <button id="btn-clear-bg" type="button" aria-label="清除大背景图" title="清除大背景图" disabled>清除背景</button> <input type="file" id="bg-image-upload" accept="image/png,image/jpeg" aria-label="上传大背景图" class="visually-hidden" /> </div> </section> </main> <!-- 模态弹窗:添加/编辑货物 --> <div id="modal-add-edit-backdrop" class="modal-backdrop hidden" aria-modal="true" role="dialog" aria-labelledby="modal-add-edit-title" tabindex="-1"> <form id="modal-add-edit" novalidate> <h2 id="modal-add-edit-title">添加货物</h2> <label> 品名 <input type="text" id="input-product-name" name="productName" required autocomplete="off" aria-required="true" aria-describedby="input-product-name-error" /> </label> <div id="input-product-name-error" class="error-message" style="color:#ff8f8f; font-size:13px; min-height: 1.2em;"></div> <label> 种类 <input type="text" id="input-category" name="category" required autocomplete="off" aria-required="true" aria-describedby="input-category-error" /> </label> <div id="input-category-error" class="error-message" style="color:#ff8f8f; font-size:13px; min-height: 1.2em;"></div> <label> 数量 <input type="number" id="input-quantity" name="quantity" min="0" step="1" required aria-required="true" aria-describedby="input-quantity-error" /> </label> <div id="input-quantity-error" class="error-message" style="color:#ff8f8f; font-size:13px; min-height: 1.2em;"></div> <label> 金额(元) <input type="number" id="input-amount" name="amount" min="0" step="0.01" required aria-required="true" aria-describedby="input-amount-error" /> </label> <div id="input-amount-error" class="error-message" style="color:#ff8f8f; font-size:13px; min-height: 1.2em;"></div> <label> 图片(可选) <input type="file" id="input-image-file" name="imageFile" accept="image/png,image/jpeg" aria-describedby="imageFile-desc"/> </label> <div style="font-size:13px; color:#cddcff;" id="imageFile-desc">支持 PNG/JPEG,最大 2MB</div> <div class="preview-container"> <img alt="图片预览" id="img-preview" class="img-preview" /> </div> <div class="modal-footer"> <button type="button" class="cancel-btn" id="modal-cancel-btn">取消</button> <button type="submit" class="ok-btn" id="modal-ok-btn" disabled>确定</button> </div> </form> </div> <!-- 模态弹窗:搜索结果 --> <div id="modal-search-result-backdrop" class="modal-backdrop hidden" role="dialog" aria-modal="true" aria-labelledby="search-result-title" tabindex="-1"> <div id="modal-search-result" tabindex="0"> <button class="close-btn" aria-label="关闭搜索结果" title="关闭搜索结果">×</button> <h3 id="search-result-title">搜索结果</h3> <pre id="search-result-content" tabindex="0" aria-live="polite"></pre> </div> </div> <!-- 模态弹窗:图片大图预览 --> <div id="modal-img-viewer-backdrop" class="modal-backdrop hidden" role="dialog" aria-modal="true" aria-label="图片预览" tabindex="-1"> <div style="outline:none;"> <img id="modal-img-viewer-img" alt="货物图片大图预览" /> </div> </div> <!-- Excel 模板隐藏区域 --> <textarea id="excel-template" class="visually-hidden" aria-hidden="true"> 品名,种类,数量,金额,图片Base64 示例货物A,电子,10,199.99, 示例货物B,日用品,20,9.99, </textarea> </div> <script src="https://cdn.jsdelivr.net/npm/xlsx@0.19.0/dist/xlsx.full.min.js"></script> <script> (() => { 'use strict'; // ############ CONST ############ // IDs mapping for quick ref const ids = { sidebar: 'sidebar', shelfList: 'shelf-list', sidebarToggleBtn: 'sidebar-toggle', logoImg: 'logo', logoUpload: 'logo-upload', main: 'main', userBgImg: 'userBg', bgImageUpload: 'bg-image-upload', btnChangeBg: 'btn-change-bg', btnClearBg: 'btn-clear-bg', goodsTable: 'goods-table', goodsTableBody: null, // will set later checkboxSelectAll: 'checkbox-select-all', globalSearch: 'global-search', importExcelBtn: 'import-excel-btn', exportExcelBtn: 'export-excel-btn', saveDataBtn: 'save-data-btn', btnAdd: 'btn-add', btnEdit: 'btn-edit', btnDelete: 'btn-delete', btnMove: 'btn-move', modalAddEditBackdrop: 'modal-add-edit-backdrop', modalAddEditForm: 'modal-add-edit', inputProductName: 'input-product-name', inputCategory: 'input-category', inputQuantity: 'input-quantity', inputAmount: 'input-amount', inputImageFile: 'input-image-file', imgPreview: 'img-preview', modalCancelBtn: 'modal-cancel-btn', modalOkBtn: 'modal-ok-btn', modalSearchResultBackdrop: 'modal-search-result-backdrop', modalSearchResultContent: 'search-result-content', modalSearchResultCloseBtn: null, modalImgViewerBackdrop: 'modal-img-viewer-backdrop', modalImgViewerImg: 'modal-img-viewer-img', excelTemplate: 'excel-template', }; ids.goodsTableBody = document.querySelector(`#${ids.goodsTable} tbody`); ids.modalSearchResultCloseBtn = document.querySelector('#modal-search-result .close-btn'); // Audio feedback const audioContext = new (window.AudioContext || window.webkitAudioContext)(); // Ripple helper function function createRipple(event) { const button = event.currentTarget; const circle = document.createElement('span'); circle.classList.add('ripple'); button.appendChild(circle); const d = Math.max(button.clientWidth, button.clientHeight); circle.style.width = circle.style.height = d + 'px'; const rect = button.getBoundingClientRect(); circle.style.left = (event.clientX - rect.left - d / 2) + 'px'; circle.style.top = (event.clientY - rect.top - d / 2) + 'px'; circle.addEventListener('animationend', () => { circle.remove(); }); } // Audio feedback for clicks - soft tap sound function playClickSound() { if (!audioContext) return; const ctx = audioContext; const osc = ctx.createOscillator(); const gainNode = ctx.createGain(); osc.type = 'triangle'; osc.frequency.setValueAtTime(600, ctx.currentTime); gainNode.gain.setValueAtTime(0.12, ctx.currentTime); osc.connect(gainNode); gainNode.connect(ctx.destination); osc.start(); osc.stop(ctx.currentTime + 0.1); osc.onended = () => { gainNode.disconnect(); osc.disconnect(); }; } // Global wave effect on clicks document.body.addEventListener('click', e => { // Prevent ripple for inputs, modals, etc if (e.target.closest('button, [role="button"]')) { createRipple({ currentTarget: e.target, clientX: e.clientX, clientY: e.clientY }); playClickSound(); } }, true); // ############ DATA STRUCTURE ############ /** * 数据格式说明: * { * shelves: [ * { * id: string, * name: string, * goods: [ * { * id: string, * productName: string, * category: string, * quantity: number, * amount: number, * imageBase64: string|null * } * ] * } * ], * logoBase64: string|null, * backgroundBase64: string|null * } */ let data = null; // 当前状态变量 let currentShelfId = null; let selectedGoodIds = new Set(); let isSidebarCollapsed = false; let unsavedChanges = false; // 临时标记编辑货货弹窗模式与待编辑对象id let isEditMode = false; let editingGoodId = null; // ############ STORAGE ############ // 本地存储 key const STORAGE_KEY = 'shelf-management-data-v1'; function loadDataFromStorage() { try { const str = localStorage.getItem(STORAGE_KEY); if (str) { return JSON.parse(str); } else { return null; } } catch { return null; } } function saveDataToStorage() { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); unsavedChanges = false; refreshSaveBtnState(); } catch (e) { alert('保存数据失败,浏览器存储空间已满或禁用。'); } } // ############ HELPERS ############ function generateId(prefix = 'id') { return prefix + '-' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36); } // Base64 image limit 2MB const MAX_IMAGE_FILE_SIZE = 2 * 1024 * 1024; function readFileAsBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = e => { resolve(e.target.result); }; reader.onerror = () => { reject(new Error('读取文件失败')); }; reader.readAsDataURL(file); }); } // 防止XSS,简单过滤文本 function sanitizeText(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } // 日期时间戳格式 function formatDateTimeNow() { const d = new Date(); const pad = n => n.toString().padStart(2, '0'); return `${d.getFullYear()}${pad(d.getMonth()+1)}${pad(d.getDate())}_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`; } // 播放波纹并点击音效辅助函数 function playBtnFeedback(event) { createRipple(event); playClickSound(); } // ################ DOM 操作 ################ // 侧边栏货架列表 const shelfListEl = document.getElementById(ids.shelfList); // 右侧货物表 tbody const goodsTableBody = ids.goodsTableBody; // 名称可编辑提示 blur 处理延迟 let shelfRenameTimeout = null; // 绘制货架列表 function renderShelfList() { shelfListEl.innerHTML = ''; for (const shelf of data.shelves) { const item = document.createElement('div'); item.className = 'shelf-item'; item.dataset.shelfId = shelf.id; if (shelf.id === currentShelfId) item.classList.add('active'); // icon svg (box) item.innerHTML = ` <svg class="shelf-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" role="img" focusable="false"> <rect x="3" y="4" width="18" height="16" rx="2" ry="2"/> <line x1="3" y1="10" x2="21" y2="10"/> </svg> <span class="shelf-text" tabindex="0" role="listitem" aria-label="货架名称">${sanitizeText(shelf.name)}</span> <div class="shelf-actions" aria-hidden="true"> <button title="重命名货架" type="button" class="shelf-rename-btn" aria-label="重命名货架"><svg viewBox="0 0 24 24"><path d="M12 20h9"/></svg></button> <button title="删除货架" type="button" class="shelf-delete-btn" aria-label="删除货架"><svg viewBox="0 0 24 24"><path d="M3 6h18M9 6v12a3 3 0 0 0 6 0V6"/></svg></button> </div> `; shelfListEl.appendChild(item); // add rename btn event item.querySelector('.shelf-rename-btn').addEventListener('click', e => { e.stopPropagation(); enableShelfRename(item, shelf); }); // add delete btn event item.querySelector('.shelf-delete-btn').addEventListener('click', e => { e.stopPropagation(); tryDeleteShelf(shelf); }); // click select shelf item.addEventListener('click', () => { if (currentShelfId !== shelf.id) { selectShelf(shelf.id); } }); // Accessibility: if user hits enter or space on shelf-text span triggers select shelf const shelfTextSpan = item.querySelector('.shelf-text'); shelfTextSpan.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); selectShelf(shelf.id); } }); } } // 启用货架重命名编辑 function enableShelfRename(shelfItemEl, shelf) { if (shelfItemEl.querySelector('input')) return; const textSpan = shelfItemEl.querySelector('.shelf-text'); // 创建输入框 const input = document.createElement('input'); input.type = 'text'; input.value = shelf.name; input.className = 'shelf-rename-input'; input.setAttribute('aria-label', `重命名货架 ${shelf.name}`); input.style.width = isSidebarCollapsed ? '48px' : '200px'; shelfItemEl.replaceChild(input, textSpan); input.focus(); input.select(); // 确认重命名处理 function finishRename(save) { if (save) { const newName = input.value.trim(); if (newName.length === 0) { alert('货架名称不能为空'); input.focus(); return; } shelf.name = newName; unsavedChanges = true; refreshSaveBtnState(); } // 替换回文字span const span = document.createElement('span'); span.className = 'shelf-text'; span.textContent = shelf.name; span.tabIndex = 0; shelfItemEl.replaceChild(span, input); renderShelfList(); // 重新渲染侧边栏 } input.addEventListener('keydown', evt => { if (evt.key === 'Enter') { evt.preventDefault(); finishRename(true); } else if (evt.key === 'Escape') { evt.preventDefault(); finishRename(false); } }); input.addEventListener('blur', () => { // 防止重复触发 (由于点击其它元素侧边栏会重新render带来重绘) if (shelfItemEl.contains(input)) { finishRename(true); } }); } // 检测并尝试删除货架 (空货架可删除) function tryDeleteShelf(shelf) { if (shelf.goods.length > 0) { alert('非空货架不能删除,请先移除货架内货物。'); return; } if (!confirm(`确定要删除货架 "${shelf.name}" 吗?`)) return; // 删除 data.shelves = data.shelves.filter(s => s.id !== shelf.id); if (currentShelfId === shelf.id) { currentShelfId = data.shelves.length > 0 ? data.shelves[0].id : null; selectedGoodIds.clear(); } unsavedChanges = true; refreshSaveBtnState(); reloadUI(); } // 选中货架 function selectShelf(shelfId) { if (currentShelfId !== shelfId) { currentShelfId = shelfId; selectedGoodIds.clear(); reloadGoodsList(); renderShelfList(); updateGoodsOperationButtonsState(); } } // 重新渲染货物列表(右侧表格) function reloadGoodsList() { goodsTableBody.innerHTML = ''; if (!currentShelfId) return; const shelf = getShelfById(currentShelfId); if (!shelf || shelf.goods.length === 0) { // 无货物时显示空白,且展示模板提示 goodsTableBody.innerHTML = `<tr><td colspan="6" style="color:#888; font-style: italic; font-size: 13px; user-select:none;">当前货架无货物。若要批量导入,请点击“导入Excel”使用示例模板格式。</td></tr>`; return; } for (const good of shelf.goods) { const tr = document.createElement('tr'); tr.dataset.goodId = good.id; if (selectedGoodIds.has(good.id)) { tr.classList.add('selected'); } // checkbox列 const tdCheckbox = document.createElement('td'); const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.tabIndex = 0; checkbox.checked = selectedGoodIds.has(good.id); checkbox.ariaLabel = `选择货物 ${good.productName}`; checkbox.addEventListener('change', e => { if (checkbox.checked) selectedGoodIds.add(good.id); else selectedGoodIds.delete(good.id); updateGoodsOperationButtonsState(); renderGoodsTableSelection(); }); tdCheckbox.appendChild(checkbox); // 图片列 const tdImg = document.createElement('td'); tdImg.className = 'image-cell'; if (good.imageBase64) { const img = document.createElement('img'); img.src = good.imageBase64; img.alt = `货物图片:${good.productName}`; img.setAttribute('aria-describedby', `product-desc-${good.id}`); img.tabIndex = 0; img.addEventListener('click', () => { openImagePreview(good.imageBase64, `货物 "${good.productName}" 的图片预览`); }); img.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openImagePreview(good.imageBase64, `货物 "${good.productName}" 的图片预览`); } }); tdImg.appendChild(img); } else { const placeholder = document.createElement('div'); placeholder.className = 'placeholder-slash'; placeholder.title = '无图片'; placeholder.textContent = '/'; placeholder.setAttribute('aria-label', '无图片'); tdImg.appendChild(placeholder); } // 其它字段列 function createTdText(content, id = '') { const td = document.createElement('td'); td.textContent = content; if (id) td.id = id; return td; } const tdProductName = createTdText(good.productName, `product-desc-${good.id}`); const tdCategory = createTdText(good.category); const tdQuantity = createTdText(String(good.quantity)); const tdAmount = createTdText(good.amount.toFixed(2)); tr.appendChild(tdCheckbox); tr.appendChild(tdImg); tr.appendChild(tdProductName); tr.appendChild(tdCategory); tr.appendChild(tdQuantity); tr.appendChild(tdAmount); // 单击整行也选择 checkbox tr.addEventListener('click', e => { if (e.target.tagName === 'INPUT') return; if (selectedGoodIds.has(good.id)) { selectedGoodIds.delete(good.id); } else { selectedGoodIds.add(good.id); } updateGoodsOperationButtonsState(); renderGoodsTableSelection(); }); goodsTableBody.appendChild(tr); } } function renderGoodsTableSelection(){ for (const tr of goodsTableBody.children) { const goodId = tr.dataset.goodId; if (!goodId) continue; if (selectedGoodIds.has(goodId)) { tr.classList.add('selected'); const cb = tr.querySelector('input[type=checkbox]'); if (cb) cb.checked = true; } else { tr.classList.remove('selected'); const cb = tr.querySelector('input[type=checkbox]'); if (cb) cb.checked = false; } } } // 根据id获取货架对象 function getShelfById(id) { return data.shelves.find(s => s.id === id) || null; } // 根据id获取货物对象及所在货架 function getGoodById(shelfId, goodId) { const shelf = getShelfById(shelfId); if (!shelf) return null; return shelf.goods.find(g => g.id === goodId) || null; } // ############ 按钮状态控制 ############ function updateGoodsOperationButtonsState() { const btnEdit = document.getElementById(ids.btnEdit); const btnDelete = document.getElementById(ids.btnDelete); const btnMove = document.getElementById(ids.btnMove); if (selectedGoodIds.size === 0) { btnEdit.disabled = true; btnDelete.disabled = true; btnMove.disabled = true; } else if (selectedGoodIds.size === 1) { btnEdit.disabled = false; btnDelete.disabled = false; btnMove.disabled = false; } else { // 多选模式,禁用编辑,启用删除和移动 btnEdit.disabled = true; btnDelete.disabled = false; btnMove.disabled = false; } } // 保存按钮启用状态 function refreshSaveBtnState() { const btnSave = document.getElementById(ids.saveDataBtn); btnSave.disabled = !unsavedChanges; } // ############ 操作函数 ############ // 添加新货物弹窗 function openAddGoodModal() { isEditMode = false; editingGoodId = null; openAddEditModal(); } // 编辑货物弹窗 function openEditGoodModal() { if (selectedGoodIds.size !== 1) return; isEditMode = true; editingGoodId = [...selectedGoodIds][0]; openAddEditModal(); } // 弹窗打开 function openAddEditModal() { const modal = document.getElementById(ids.modalAddEditBackdrop); const form = document.getElementById(ids.modalAddEditForm); const title = form.querySelector('h2'); const btnOk = document.getElementById(ids.modalOkBtn); const btnCancel = document.getElementById(ids.modalCancelBtn); const previewImg = document.getElementById(ids.imgPreview); // Clear form form.reset(); previewImg.src = ''; previewImg.style.display = 'none'; // Reset validation messages clearAddEditErrors(); if (isEditMode) { title.textContent = '编辑货物'; // 填充编辑数据 const shelf = getShelfById(currentShelfId); if (!shelf) return; const good = shelf.goods.find(g => g.id === editingGoodId); if (!good) return; form.elements.productName.value = good.productName; form.elements.category.value = good.category; form.elements.quantity.value = good.quantity; form.elements.amount.value = good.amount.toFixed(2); if (good.imageBase64) { previewImg.src = good.imageBase64; previewImg.style.display = 'block'; } btnOk.disabled = false; } else { title.textContent = '添加货物'; btnOk.disabled = true; } modal.classList.remove('hidden'); // Focus first input form.elements.productName.focus(); validateAddEditForm(); // Handle Escape key for closing modal function onKeyDown(e) { if (e.key === 'Escape') { e.preventDefault(); closeAddEditModal(); } } modal.addEventListener('keydown', onKeyDown, {once:true}); } function closeAddEditModal() { const modal = document.getElementById(ids.modalAddEditBackdrop); modal.classList.add('hidden'); } // 验证添加/编辑表单数据 function clearAddEditErrors() { const idsErr = ['input-product-name-error', 'input-category-error', 'input-quantity-error', 'input-amount-error']; idsErr.forEach(id => { const el = document.getElementById(id); if (el) el.textContent = ''; }); } function validateAddEditForm() { const form = document.getElementById(ids.modalAddEditForm); const btnOk = document.getElementById(ids.modalOkBtn); clearAddEditErrors(); const productName = form.elements.productName.value.trim(); const category = form.elements.category.value.trim(); const quantity = Number(form.elements.quantity.value); const amount = Number(form.elements.amount.value); const imageFileInput = form.elements.imageFile; let valid = true; if (productName.length === 0) { document.getElementById('input-product-name-error').textContent = '请输入品名'; valid = false; } if (category.length === 0) { document.getElementById('input-category-error').textContent = '请输入种类'; valid = false; } if (!Number.isInteger(quantity) || quantity < 0) { document.getElementById('input-quantity-error').textContent = '请输入有效的数量 (0 或正整数)'; valid = false; } if (isNaN(amount) || amount < 0) { document.getElementById('input-amount-error').textContent = '请输入有效金额 (>= 0)'; valid = false; } const file = imageFileInput.files[0]; if (file && file.size > MAX_IMAGE_FILE_SIZE) { alert('图片文件过大,最大支持2MB'); valid = false; } btnOk.disabled = !valid; return valid; } // 预览图片 document.getElementById(ids.inputImageFile).addEventListener('change', async e => { const file = e.target.files[0]; const preview = document.getElementById(ids.imgPreview); if (!file) { preview.style.display = 'none'; preview.src = ''; validateAddEditForm(); return; } if (file.size > MAX_IMAGE_FILE_SIZE) { alert('图片文件过大,最大支持2MB'); e.target.value = ''; preview.style.display = 'none'; preview.src = ''; validateAddEditForm(); return; } try { const base64 = await readFileAsBase64(file); preview.src = base64; preview.style.display = 'block'; } catch { alert('读取图片失败'); preview.style.display = 'none'; preview.src = ''; } validateAddEditForm(); }); // 表单输入验证绑定 const formElementsValidate = [ ids.inputProductName, ids.inputCategory, ids.inputQuantity, ids.inputAmount, ids.inputImageFile ]; formElementsValidate.forEach(id => { const el = document.getElementById(id); el.addEventListener('input', validateAddEditForm); }); // 弹窗取消按钮 document.getElementById(ids.modalCancelBtn).addEventListener('click', e => { e.preventDefault(); closeAddEditModal(); }); // 弹窗确认提交 document.getElementById(ids.modalAddEditForm).addEventListener('submit', async e => { e.preventDefault(); if (!validateAddEditForm()) return; const form = document.getElementById(ids.modalAddEditForm); const productName = form.elements.productName.value.trim(); const category = form.elements.category.value.trim(); const quantity = Number(form.elements.quantity.value); const amount = Number(form.elements.amount.value); const fileInput = form.elements.imageFile; let imageBase64 = null; // 读取文件Base64(如有) if (fileInput.files.length > 0) { try { imageBase64 = await readFileAsBase64(fileInput.files[0]); } catch { alert('读取图片失败'); return; } } else if (isEditMode) { // 编辑时未更换图片,保持原图(用编辑时数据里已有的) const shelf = getShelfById(currentShelfId); if (shelf) { const good = shelf.goods.find(g => g.id === editingGoodId); imageBase64 = good ? good.imageBase64 : null; } } if (!currentShelfId) { alert('无选中货架'); return; } const shelf = getShelfById(currentShelfId); if (!shelf) { alert('当前货架不存在'); return; } if (isEditMode && editingGoodId) { // 编辑模式 const good = shelf.goods.find(g => g.id === editingGoodId); if (!good) { alert('商品未找到'); return; } good.productName = productName; good.category = category; good.quantity = quantity; good.amount = amount; good.imageBase64 = imageBase64; } else { // 添加模式 const newGood = { id: generateId('good'), productName, category, quantity, amount, imageBase64, }; shelf.goods.push(newGood); } unsavedChanges = true; refreshSaveBtnState(); closeAddEditModal(); reloadGoodsList(); updateGoodsOperationButtonsState(); }); // 操作按钮点击绑定 // 添加按钮 document.getElementById(ids.btnAdd).addEventListener('click', () => { openAddGoodModal(); }); // 编辑按钮 document.getElementById(ids.btnEdit).addEventListener('click', () => { openEditGoodModal(); }); // 删除按钮 document.getElementById(ids.btnDelete).addEventListener('click', () => { if (selectedGoodIds.size === 0) return; if (!confirm(`确定删除选择的${selectedGoodIds.size}个货物吗?`)) return; const shelf = getShelfById(currentShelfId); if (!shelf) return; shelf.goods = shelf.goods.filter(g => !selectedGoodIds.has(g.id)); selectedGoodIds.clear(); unsavedChanges = true; refreshSaveBtnState(); reloadGoodsList(); updateGoodsOperationButtonsState(); }); // 移动按钮 document.getElementById(ids.btnMove).addEventListener('click', () => { if (selectedGoodIds.size === 0) return; openMoveGoodsPrompt(); }); // 移动货物提示选择目标货架 function openMoveGoodsPrompt() { // 弹alert选择目标货架 (不选当前货架) 简单实现 if (!currentShelfId) return; const targetShelves = data.shelves.filter(s => s.id !== currentShelfId); if (targetShelves.length === 0) { alert('无其他货架可移动'); return; } const names = targetShelves.map((s, i) => `${i + 1}: ${s.name}`).join('\n'); let idx = prompt(`请选择移动目标货架(输入序号):\n${names}`, '1'); if (idx === null) return; // 取消 idx = Number(idx); if (!Number.isInteger(idx) || idx < 1 || idx > targetShelves.length) { alert('输入无效'); return; } const tgtShelf = targetShelves[idx - 1]; if (!tgtShelf) return; const curShelf = getShelfById(currentShelfId); if (!curShelf) return; // 转移商品 for (const id of selectedGoodIds) { const idxGood = curShelf.goods.findIndex(g => g.id === id); if (idxGood >= 0) { const [good] = curShelf.goods.splice(idxGood, 1); tgtShelf.goods.push(good); } } selectedGoodIds.clear(); unsavedChanges = true; refreshSaveBtnState(); reloadGoodsList(); updateGoodsOperationButtonsState(); alert(`成功移动至货架 "${tgtShelf.name}"`); } // 全选/取消全选切换 document.getElementById(ids.checkboxSelectAll).addEventListener('change', e => { if (!currentShelfId) return; const shelf = getShelfById(currentShelfId); if (!shelf) return; selectedGoodIds.clear(); if (e.target.checked) { for (const good of shelf.goods) { selectedGoodIds.add(good.id); } } renderGoodsTableSelection(); updateGoodsOperationButtonsState(); }); // 搜索相关 const searchInput = document.getElementById(ids.globalSearch); searchInput.addEventListener('input', () => { const kw = searchInput.value.trim().toLowerCase(); if (kw.length < 2) { closeSearchResultModal(); return; } performSearch(kw); }); // 执行搜索 function performSearch(keyword) { const results = []; if (!data || !data.shelves.length) { closeSearchResultModal(); return; } for (const shelf of data.shelves) { for (const good of shelf.goods) { if ( good.productName.toLowerCase().includes(keyword) || good.category.toLowerCase().includes(keyword) ) { results.push({ shelfName: shelf.name, ...good, }); } } } const modal = document.getElementById(ids.modalSearchResultBackdrop); const contentPre = document.getElementById(ids.modalSearchResultContent); if (results.length === 0) { contentPre.textContent = '未找到匹配的货物。'; } else { // 格式化结果展现 contentPre.textContent = results.map((r,i) => `#${i+1} 货架: ${r.shelfName}\n品名: ${r.productName}\n种类: ${r.category}\n数量: ${r.quantity}\n金额: ¥${r.amount.toFixed(2)}\n` ).join('\n'); } modal.classList.remove('hidden'); modal.focus(); } // 关闭搜索结果弹窗 function closeSearchResultModal() { document.getElementById(ids.modalSearchResultBackdrop).classList.add('hidden'); } ids.modalSearchResultCloseBtn.addEventListener('click', () => { closeSearchResultModal(); }); document.getElementById(ids.modalSearchResultBackdrop).addEventListener('click', e => { if (e.target === e.currentTarget) closeSearchResultModal(); }); // 图片预览弹窗 function openImagePreview(base64, alt) { const modal = document.getElementById(ids.modalImgViewerBackdrop); const img = document.getElementById(ids.modalImgViewerImg); img.src = base64; img.alt = alt; modal.classList.remove('hidden'); modal.focus(); } function closeImagePreview() { const modal = document.getElementById(ids.modalImgViewerBackdrop); modal.classList.add('hidden'); const img = document.getElementById(ids.modalImgViewerImg'); img.src = ''; } document.getElementById(ids.modalImgViewerBackdrop).addEventListener('click', e => { if (e.target === e.currentTarget) closeImagePreview(); }); document.getElementById(ids.modalImgViewerBackdrop).addEventListener('keydown', e => { if (e.key === 'Escape') { closeImagePreview(); } }); // 侧边栏折叠/展开 const sidebarEl = document.getElementById(ids.sidebar); const sidebarToggleBtn = document.getElementById(ids.sidebarToggleBtn); sidebarToggleBtn.addEventListener('click', () => { isSidebarCollapsed = !isSidebarCollapsed; if (isSidebarCollapsed) sidebarEl.classList.add('collapsed'); else sidebarEl.classList.remove('collapsed'); }); // LOGO 上传(替换) const logoImg = document.getElementById(ids.logoImg); const logoUploadInput = document.getElementById(ids.logoUpload); logoImg.addEventListener('click', () => { logoUploadInput.click(); }); logoImg.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); logoUploadInput.click(); } }); logoUploadInput.addEventListener('change', async e => { const file = e.target.files[0]; if (!file) return; if (file.size > MAX_IMAGE_FILE_SIZE) { alert('Logo图片过大,最大支持2MB'); e.target.value = ''; return; } try { const base64 = await readFileAsBase64(file); data.logoBase64 = base64; logoImg.src = base64; unsavedChanges = true; refreshSaveBtnState(); } catch { alert('加载Logo失败'); } }); // 背景图上传/切换 const bgImageUploadInput = document.getElementById(ids.bgImageUpload); const btnChangeBg = document.getElementById(ids.btnChangeBg); const btnClearBg = document.getElementById(ids.btnClearBg); const userBgImg = document.getElementById(ids.userBgImg); btnChangeBg.addEventListener('click', () => { bgImageUploadInput.click(); }); bgImageUploadInput.addEventListener('change', async e => { const file = e.target.files[0]; if (!file) return; if (file.size > MAX_IMAGE_FILE_SIZE) { alert('背景图片过大,最大支持2MB'); e.target.value = ''; return; } try { const base64 = await readFileAsBase64(file); data.backgroundBase64 = base64; userBgImg.src = base64; userBgImg.style.display = 'block'; btnClearBg.disabled = false; unsavedChanges = true; refreshSaveBtnState(); } catch { alert('加载背景图片失败'); } }); btnClearBg.addEventListener('click', () => { if (!data.backgroundBase64) return; if (!confirm('确定清除当前大背景图吗?')) return; data.backgroundBase64 = null; userBgImg.src = ''; userBgImg.style.display = 'none'; btnClearBg.disabled = true; unsavedChanges = true; refreshSaveBtnState(); }); // 保存按钮 document.getElementById(ids.saveDataBtn).addEventListener('click', () => { saveDataToStorage(); alert('数据已保存!'); }); // 导入Excel按钮 document.getElementById(ids.importExcelBtn).addEventListener('click', () => { openExcelImportDialog(); }); // 导出Excel按钮 document.getElementById(ids.exportExcelBtn).addEventListener('click', () => { exportCurrentDataToExcel(); }); // ############ Excel 相关 ############ // 列名格式强制 const REQUIRED_FIELDS = ['品名', '种类', '数量', '金额', '图片Base64']; // 导入 Excel - 弹文件选择 function openExcelImportDialog() { const input = document.createElement('input'); input.type = 'file'; input.accept = ".xlsx,.xls"; input.onchange = e => { if (input.files && input.files.length > 0) { const file = input.files[0]; importExcelFile(file); } }; input.click(); } // 导入 Excel 文件处理 async function importExcelFile(file) { if (!file) return; try { const dataBuffer = await file.arrayBuffer(); const workbook = XLSX.read(dataBuffer, {type: 'array'}); if (workbook.SheetNames.length === 0) { alert('Excel 文件无有效工作表'); return; } const sheetName = workbook.SheetNames[0]; const sheet = workbook.Sheets[sheetName]; const json = XLSX.utils.sheet_to_json(sheet, {defval:""}); // 格式验证 if (json.length === 0) { alert('Excel表格无数据'); return; } // 检查首项列名是否符合规范 const firstRow = Object.keys(json[0]); for (const f of REQUIRED_FIELDS) { if (!firstRow.includes(f)) { alert(`Excel 文件缺少必要字段:${f}`); return; } } // 弹出选择货架对话框(选择导入至哪一个货架) if (data.shelves.length === 0) { alert('请先创建至少一个货架'); return; } let shelfNames = data.shelves.map((s, i) => `${i+1}: ${s.name}`).join('\n'); let idx = prompt(`选择导入货架序号:\n${shelfNames}`, '1'); if (idx === null) return; idx = Number(idx); if (!Number.isInteger(idx) || idx < 1 || idx > data.shelves.length) { alert('输入无效'); return; } const targetShelf = data.shelves[idx - 1]; // 验证每行数据 let invalidRows = []; for (let i = 0; i < json.length; i++) { const row = json[i]; if ( typeof row['品名'] !== 'string' || row['品名'].trim() === "" || typeof row['种类'] !== 'string' || row['种类'].trim() === "" || isNaN(Number(row['数量'])) || Number(row['数量']) < 0 || isNaN(Number(row['金额'])) || Number(row['金额']) < 0 || (row['图片Base64'] && typeof row['图片Base64'] !== 'string') ) { invalidRows.push(i + 2); } } if (invalidRows.length > 0) { alert('Excel数据格式错误,以下行有问题:\n' + invalidRows.join(', ')); return; } // 合并导入数据,保证数据结构正确 for (const row of json) { targetShelf.goods.push({ id: generateId('good'), productName: row['品名'].toString().trim(), category: row['种类'].toString().trim(), quantity: Number(row['数量']), amount: Number(row['金额']), imageBase64: row['图片Base64'] && row['图片Base64'].trim().length > 0 ? row['图片Base64'].trim() : null, }); } unsavedChanges = true; refreshSaveBtnState(); if (currentShelfId !== targetShelf.id) { currentShelfId = targetShelf.id; renderShelfList(); } reloadGoodsList(); updateGoodsOperationButtonsState(); alert(`成功导入${json.length}条货物数据至货架 "${targetShelf.name}"`); } catch(err) { alert('导入Excel失败: ' + err.message); } } // 导出当前数据至 Excel function exportCurrentDataToExcel() { if (!data || !data.shelves.length) { alert('无货架数据,导出模板Excel。'); exportEmptyTemplateExcel(); return; } if (!currentShelfId) { alert('请选择一个货架以导出数据'); return; } const shelf = getShelfById(currentShelfId); if (!shelf) { alert('当前货架不存在'); return; } if (!shelf.goods.length) { if (!confirm('当前货架无数据,是否导出Excel示例模板?')) return; exportEmptyTemplateExcel(); return; } // 组织数据 const ws_data = [REQUIRED_FIELDS]; for (const good of shelf.goods) { ws_data.push([ good.productName, good.category, good.quantity, good.amount, good.imageBase64 || '' ]); } const ws = XLSX.utils.aoa_to_sheet(ws_data); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, shelf.name); const timestamp = formatDateTimeNow(); const fname = `货架_${shelf.name}_${timestamp}.xlsx`; XLSX.writeFile(wb, fname); } // 导出模板Excel(当无数据时提供示例) function exportEmptyTemplateExcel() { const templateStr = document.getElementById(ids.excelTemplate).value.trim(); const wb = XLSX.utils.book_new(); const lines = templateStr.split('\n').map(line => line.split(',').map(c => c.trim())); const ws = XLSX.utils.aoa_to_sheet(lines); XLSX.utils.book_append_sheet(wb, ws, '示例模板'); const fname = `货架数据模板_${formatDateTimeNow()}.xlsx`; XLSX.writeFile(wb, fname); } // ############ 初始化和UI刷新 ############# // 重新加载UI(侧栏+货物) function reloadUI() { renderShelfList(); reloadGoodsList(); updateGoodsOperationButtonsState(); refreshSaveBtnState(); setLogoImageSrc(); setBackgroundImageSrc(); } // 初始化默认数据,若无数据则创建默认货架 function initData() { const localData = loadDataFromStorage(); if (localData) { data = localData; } else { data = { shelves: [ { id: generateId('shelf'), name: '默认货架', goods: [], } ], logoBase64: null, backgroundBase64: null, }; } currentShelfId = (data.shelves.length > 0) ? data.shelves[0].id : null; selectedGoodIds.clear(); unsavedChanges = false; isSidebarCollapsed = false; } // 设置logo图片src function setLogoImageSrc() { const logo = document.getElementById(ids.logoImg); if (data.logoBase64) { logo.src = data.logoBase64; } else { // 默认SVG logo.src = 'data:image/svg+xml;utf8,' + encodeURIComponent(`<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect width="64" height="64" rx="8" fill="#4A7BFA"/> <path d="M20 44V20H44V44H20Z" stroke="#FFFFFF" stroke-width="4" stroke-linejoin="round"/> <rect x="26" y="26" width="12" height="12" fill="#4A7BFA" stroke="#FFFFFF" stroke-width="2"/> </svg>`); } } // 设置背景图片src function setBackgroundImageSrc() { const bgImg = document.getElementById(ids.userBgImg); const clearBgBtn = document.getElementById(ids.btnClearBg); if (data.backgroundBase64) { bgImg.src = data.backgroundBase64; bgImg.style.display = 'block'; clearBgBtn.disabled = false; } else { bgImg.src = ''; bgImg.style.display = 'none'; clearBgBtn.disabled = true; } } // 关闭时自动提示未保存 window.addEventListener('beforeunload', e => { if (unsavedChanges) { e.preventDefault(); e.returnValue = ''; return ''; } }); // 全局键盘快捷键支持 window.addEventListener('keydown', e => { if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) return; if (e.key === 'F2') { // 添加 e.preventDefault(); openAddGoodModal(); } if (e.key === 'Delete') { // 删除 e.preventDefault(); if (!document.getElementById(ids.btnDelete).disabled) { document.getElementById(ids.btnDelete).click(); } } if (e.key === 'F3') { // 编辑 e.preventDefault(); if (!document.getElementById(ids.btnEdit).disabled) { document.getElementById(ids.btnEdit).click(); } } }); // ############ 动态无序动态网状粒子线条背景 ############ const canvas = document.getElementById('particle-canvas'); const ctx = canvas.getContext('2d'); let particles = []; const maxParticles = 40; let canvasWidth, canvasHeight; class Particle { constructor() { this.reset(); } reset() { this.x = Math.random()*canvasWidth; this.y = Math.random()*canvasHeight; this.vx = (Math.random()-0.5)*0.4; this.vy = (Math.random()-0.5)*0.4; this.radius = 1.6 + Math.random()*1.1; } update() { this.x += this.vx; this.y += this.vy; if(this.x < 0 || this.x > canvasWidth) this.vx *= -1; if(this.y < 0 || this.y > canvasHeight) this.vy *= -1; } draw() { const grad = ctx.createRadialGradient(this.x, this.y, this.radius*0.3, this.x, this.y, this.radius); grad.addColorStop(0, 'rgba(94,124,255,0.3)'); grad.addColorStop(1, 'rgba(94,124,255,0)'); ctx.fillStyle = grad; ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2); ctx.fill(); } } function resizeCanvas() { canvasWidth = canvas.clientWidth; canvasHeight = canvas.clientHeight; canvas.width = canvasWidth * devicePixelRatio; canvas.height = canvasHeight * devicePixelRatio; canvas.style.width = canvasWidth + 'px'; canvas.style.height = canvasHeight + 'px'; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.scale(devicePixelRatio, devicePixelRatio); } function initParticles() { particles = []; for(let i=0; i<maxParticles; i++){ particles.push(new Particle()); } } function drawParticles() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); // 用线条连接距离较近的点 for(let i=0; i<particles.length; i++) { particles[i].update(); particles[i].draw(); for(let j=i+1; j<particles.length; j++) { const dx = particles[i].x - particles[j].x; const dy = particles[i].y - particles[j].y; const dist = Math.sqrt(dx*dx + dy*dy); if(dist < 120) { ctx.strokeStyle = `rgba(94,124,255,${(120-dist)/120*0.25})`; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(particles[i].x, particles[i].y); ctx.lineTo(particles[j].x, particles[j].y); ctx.stroke(); } } } } function animateParticles() { drawParticles(); requestAnimationFrame(animateParticles); } window.addEventListener('resize', () => { resizeCanvas(); }); // ############ 初始化入口 ############## function init() { initData(); resizeCanvas(); initParticles(); animateParticles(); reloadUI(); } init(); })(); </script> </body> </html>
说明
- 界面布局:经典左右分栏,宽度280px(展开)或56px(折叠),左侧货架列表支持点击选中、重命名与删除(空货架),顶部有Logo,可上传替换。
- 背景层:右侧背景支持用户上传图片,叠加动态流畅的无序网状粒子线条动画canvas。
- 货物列表:表格形式展示,支持全选及多选,图片有则缩略图且可放大预览,无图时显示斜杠占位。
- 顶部工具栏:全局搜索(模糊匹配品名和种类)即时弹出结果面板,Excel导入导出(使用SheetJS),保存数据到localStorage按钮。
- 数据持久化:整个数据结构含货架列表、货架数据、Logo和背景图均存浏览器localStorage,关闭页面时如存在未保存更改会提示。
- Excel 处理:导入时强制校验字段格式,支持含或不含图片Base64列,导出当前选中货架数据,文件名含时间戳避免缓存。无数据时支持导出模板示例Excel。
- 用户体验:按钮点击带波纹动画与柔和音效反馈,键盘焦点支持,图标及按钮均有辅助标签,点击空白关闭弹窗,Esc键可以关闭弹窗。
- 代码里引用的SheetJS版本为0.19.0最新版CDN。
此文件可直接保存为
.html在浏览器打开使用。系统完整前端,尚无后端依赖。如果需要进一步功能增强(如多货架编辑、批量移动优化等),欢迎继续补充需求。