<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>货架数据管理系统</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter&display=swap');
:root {
--color-primary: rgba(135, 206, 250, 0.35); /*半透明浅蓝*/
--color-silvergray: #BCC3CC;
--color-gradient-start: #f9fbff;
--color-gradient-end: #ffffff;
--color-text-primary: #334155;
--color-text-secondary: #64748b;
--color-shadow: rgba(0,0,0,0.1);
--btn-bg: #61aefb;
--btn-bg-hover: #499ce0;
--btn-shadow: rgba(30, 144, 255, 0.3);
--border-radius: 8px;
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, Segoe UI,
Roboto, Helvetica Neue, Arial, sans-serif;
}
html, body {
margin: 0; padding: 0; height: 100%;
background: linear-gradient(135deg, var(--color-gradient-start), var(--color-gradient-end));
font-family: var(--font-family);
color: var(--color-text-primary);
user-select: none;
--ripple-duration: 600ms;
}
/* 复杂粒子动画外层 - 背景图层 */
#background-layer {
position: fixed;
inset: 0;
z-index: 0;
overflow: hidden;
background-position: center center;
background-size: cover;
will-change: background-image;
}
#particle-canvas {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 1;
}
/* 布局: 左侧栏 + 右侧主区 */
#app {
position: relative;
display: flex;
height: 100vh;
z-index: 10;
background: none;
}
/* 侧栏 */
#sidebar {
width: 280px;
background: var(--color-primary);
box-shadow: inset -4px 0 6px -3px var(--color-shadow);
display: flex;
flex-direction: column;
transition: width 0.25s ease;
user-select: auto;
overflow: hidden;
}
#sidebar.collapsed {
width: 56px;
}
#sidebar-header {
height: 56px;
display: flex;
align-items: center;
padding: 0 16px;
gap: 12px;
flex-shrink: 0;
cursor: default;
}
#logo-upload-button {
background: none;
border: none;
cursor: pointer;
padding: 0;
vertical-align: middle;
line-height: 0;
width: 36px;
height: 36px;
}
#logo-upload-button svg,
#logo-preview {
width: 36px; height: 36px;
border-radius: 6px;
background: rgba(255 255 255 / 0.4);
transition: background-color 0.3s ease;
}
#logo-upload-button:hover svg,
#logo-preview:hover {
background: rgba(255 255 255 / 0.6);
}
#logo-file-input {
display: none;
}
#sidebar-header h1 {
flex: 1;
font-weight: 600;
font-size: 1.1rem;
color: var(--color-text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
user-select: text;
}
#sidebar.collapsed h1 {
display: none;
}
/* 货架列表 */
#shelf-list {
flex: 1;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
padding: 8px 0;
}
#shelf-list.collapsed {
padding: 8px 4px;
}
.shelf-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
cursor: pointer;
border-radius: var(--border-radius);
font-weight: 500;
transition:
background-color 0.25s ease,
color 0.25s ease;
user-select: none;
position: relative;
}
.shelf-item:hover,
.shelf-item.selected {
background: rgba(255 255 255 / 0.35);
color: #1e3a8a;
}
#sidebar.collapsed .shelf-item {
justify-content: center;
padding: 8px 0;
}
.shelf-icon {
flex-shrink: 0;
width: 24px;
height: 24px;
fill: var(--color-text-secondary);
transition: fill 0.3s;
}
.shelf-item:hover .shelf-icon,
.shelf-item.selected .shelf-icon {
fill: #1e40af;
}
/* 货架名称编辑 */
.shelf-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#sidebar.collapsed .shelf-name {
display: none;
}
.shelf-name-edit {
width: 100%;
font-size: 1rem;
font-family: var(--font-family);
padding: 4px 8px;
border: none;
border-radius: var(--border-radius);
outline-offset: 2px;
}
/* 货架操作按钮组 */
.shelf-actions {
display: flex;
gap: 4px;
flex-shrink: 0;
opacity: 0.75;
}
#sidebar.collapsed .shelf-actions {
display: none;
}
.shelf-action-btn {
background: none;
border: none;
cursor: pointer;
color: var(--color-text-secondary);
padding: 4px;
border-radius: 4px;
transition: background-color 0.2s, color 0.2s;
display: flex;
align-items: center;
justify-content: center;
}
.shelf-action-btn:hover:not(:disabled) {
background: rgba(255 255 255 / 0.5);
color: #1e3a8a;
}
.shelf-action-btn:disabled {
cursor: not-allowed;
opacity: 0.3;
}
/* 侧栏底部折叠按钮 */
#sidebar-footer {
padding: 8px 16px;
border-top: 1px solid rgba(255 255 255 / 0.15);
flex-shrink: 0;
}
#toggle-sidebar-btn {
width: 100%;
height: 36px;
background: var(--btn-bg);
border: none;
border-radius: var(--border-radius);
color: white;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
user-select: none;
box-shadow: 0 3px 6px var(--btn-shadow);
transition: background-color 0.25s ease;
}
#toggle-sidebar-btn:hover,
#toggle-sidebar-btn:focus-visible {
background: var(--btn-bg-hover);
outline-offset: 2px;
outline: 2px solid #3b82f6;
}
#sidebar.collapsed #toggle-sidebar-btn {
font-size: 0;
padding: 0 0;
justify-content: center;
}
#sidebar.collapsed #toggle-sidebar-btn span {
display: none;
}
/* 右侧主区 */
#main-area {
flex: 1;
position: relative;
display: flex;
flex-direction: column;
overflow: hidden;
color: var(--color-text-primary);
background: transparent;
}
/* 右侧大背景上传区会直接赋值到#background-layer的background-image */
/* 工具栏 */
#toolbar {
flex-shrink: 0;
background: rgba(255 255 255 / 0.85);
backdrop-filter: saturate(180%) blur(12px);
box-shadow: 0 2px 4px var(--color-shadow);
padding: 8px 16px;
display: flex;
gap: 12px;
align-items: center;
user-select: none;
}
#search-input {
flex: 1;
font-size: 1rem;
padding: 8px 12px;
border-radius: var(--border-radius);
border: 1.5px solid var(--color-silvergray);
outline-offset: 2px;
transition: border-color 0.3s ease;
}
#search-input:focus {
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59,130,246,.3);
}
.toolbar-btn {
padding: 8px 14px;
background: var(--btn-bg);
border: none;
border-radius: var(--border-radius);
color: white;
font-weight: 600;
cursor: pointer;
box-shadow: 0 3px 6px var(--btn-shadow);
display: flex;
align-items: center;
gap: 6px;
user-select: none;
transition: background-color 0.3s;
}
.toolbar-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
box-shadow: none;
}
.toolbar-btn:hover:not(:disabled),
.toolbar-btn:focus-visible:not(:disabled) {
background: var(--btn-bg-hover);
outline-offset: 2px;
outline: 2px solid #3b82f6;
}
.toolbar-btn svg {
width: 18px;
height: 18px;
fill: white;
}
/* 主货物表格区 */
#goods-table-container {
flex: 1;
overflow: auto;
background: rgba(255 255 255 / 0.75);
margin: 12px 16px 16px 16px;
border-radius: var(--border-radius);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
table {
border-collapse: collapse;
width: 100%;
min-width: 720px;
}
thead tr {
background: rgba(135,206,250,0.35);
}
th, td {
padding: 10px 12px;
border-bottom: 1px solid var(--color-silvergray);
text-align: left;
vertical-align: middle;
font-weight: 500;
font-size: 0.95rem;
}
th:first-child, td:first-child {
text-align: center;
width: 48px;
}
th:nth-child(2), td:nth-child(2) {
width: 48px;
text-align: center;
}
th:last-child, td:last-child {
width: 140px;
text-align: center;
}
tbody tr:hover {
background: rgba(97, 174, 251, 0.15);
cursor: pointer;
}
tbody tr.selected {
background: #bee3f8;
}
/* 复选框 */
input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
}
/* 图片缩略图 */
.thumb-container {
position: relative;
width: 40px;
height: 40px;
border-radius: var(--border-radius);
overflow: hidden;
background: #e0e7ff;
border: 1px solid var(--color-silvergray);
display: flex;
justify-content: center;
align-items: center;
}
.thumb-container img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
cursor: zoom-in;
}
.thumb-placeholder {
font-size: 20px;
color: var(--color-silvergray);
transform: rotate(45deg);
user-select: none;
}
/* 操作按钮区域 */
#actions-bar {
flex-shrink: 0;
background: rgba(135, 206, 250, 0.35);
padding: 12px 16px;
display: flex;
gap: 12px;
justify-content: flex-start;
user-select: none;
}
.action-btn {
background: var(--btn-bg);
border: none;
border-radius: var(--border-radius);
padding: 10px 18px;
box-shadow: 0 3px 6px var(--btn-shadow);
color: white;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
transition: background-color 0.25s ease;
user-select: none;
position: relative;
overflow: hidden;
}
.action-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
box-shadow: none;
}
.action-btn:hover:not(:disabled),
.action-btn:focus-visible:not(:disabled) {
background: var(--btn-bg-hover);
outline-offset: 2px;
outline: 2px solid #3b82f6;
}
.action-btn svg {
width: 20px;
height: 20px;
fill: white;
pointer-events: none;
}
/* 添加轻柔波纹动画 - 溢出hidden和伪元素 */
.ripple {
position: absolute;
border-radius: 50%;
background-color: rgba(255 255 255 / 0.6);
pointer-events:none;
animation: ripple-effect var(--ripple-duration) ease-out forwards;
transform: scale(0);
z-index: 10;
}
@keyframes ripple-effect {
100% {
opacity: 0;
transform: scale(2.5);
}
}
/* 弹窗modal遮罩 */
.modal-overlay {
position: fixed;
inset: 0;
z-index: 50;
background: rgba(20, 29, 42, 0.8);
display: flex;
align-items: center;
justify-content: center;
backdrop-filter: blur(8px);
user-select: none;
}
/* 模态内容 */
.modal-content {
background: #1e293b;
width: 90vw;
max-width: 480px;
max-height: 90vh;
overflow-y: auto;
border-radius: var(--border-radius);
padding: 24px 32px 32px 32px;
color: #f1f5f9;
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
display: flex;
flex-direction: column;
position: relative;
}
.modal-content h2 {
margin: 0 0 16px;
font-weight: 700;
font-size: 1.4rem;
}
.modal-close-btn {
position: absolute;
top: 12px;
right: 12px;
background: none;
border: none;
color: #94a3b8;
font-size: 1.4rem;
cursor: pointer;
transition: color 0.3s ease;
}
.modal-close-btn:hover,
.modal-close-btn:focus-visible {
color: white;
outline-offset: 2px;
outline: 2px solid #3b82f6;
}
.modal-form {
display: flex;
flex-direction: column;
gap: 16px;
user-select: text;
}
.modal-form label {
font-weight: 600;
font-size: 1rem;
margin-bottom: 6px;
user-select: text;
}
.modal-form input[type="text"],
.modal-form input[type="number"],
.modal-form select {
font-size: 1rem;
padding: 8px 12px;
border-radius: var(--border-radius);
border: none;
outline-offset: 2px;
outline: 2px solid transparent;
transition: outline-color 0.3s ease;
}
.modal-form input[type="text"]:focus,
.modal-form input[type="number"]:focus,
.modal-form select:focus {
outline-color: #3b82f6;
}
.modal-form input[type="file"] {
color: #cbd5e1;
}
.modal-form .form-row {
display: flex;
flex-direction: column;
}
.modal-form .form-btns {
margin-top: 8px;
display: flex;
justify-content: flex-end;
gap: 12px;
}
.modal-form button {
background: var(--btn-bg);
border: none;
border-radius: var(--border-radius);
padding: 10px 20px;
color: white;
font-weight: 600;
cursor: pointer;
box-shadow: 0 3px 6px var(--btn-shadow);
user-select: none;
transition: background-color 0.3s ease;
}
.modal-form button:hover,
.modal-form button:focus-visible {
background: var(--btn-bg-hover);
outline-offset: 2px;
outline: 2px solid #3b82f6;
}
.modal-form button.cancel-btn {
background: #718096;
box-shadow: none;
}
.modal-form button.cancel-btn:hover,
.modal-form button.cancel-btn:focus-visible {
background: #4a5568;
}
.modal-form .thumbnail-preview {
margin-top: 8px;
width: 72px;
height: 72px;
border-radius: var(--border-radius);
background: #e0e7ff;
border: 1px solid var(--color-silvergray);
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
position: relative;
}
.modal-form .thumbnail-preview img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.error-text {
color: #f87171;
font-size: 0.875rem;
}
/* 搜索结果弹窗 */
#search-result-modal {
position: fixed;
left: 50%;
top: 100px;
transform: translateX(-50%);
background: linear-gradient(135deg, #60a5fa, #93c5fd);
border-radius: var(--border-radius);
box-shadow: 0 10px 25px rgba(99, 179, 237, 0.8);
padding: 20px;
color: white;
max-width: 480px;
max-height: 60vh;
overflow-y: auto;
z-index: 55;
animation: fadein 400ms ease forwards;
user-select: text;
}
#search-result-modal.hide {
display: none;
}
#search-result-modal h3 {
margin-top: 0;
font-weight: 700;
font-size: 1.2rem;
}
#search-result-list {
margin: 12px 0 0 0;
}
.search-item {
margin-bottom: 12px;
padding-bottom: 10px;
border-bottom: 1px solid rgba(255 255 255 / 0.35);
}
.search-item-title {
font-weight: 600;
font-size: 1rem;
}
.search-item-detail {
font-size: 0.875rem;
margin: 4px 0 0 0;
}
#search-result-modal .close-search-btn {
position: absolute;
top: 8px;
right: 8px;
background: none;
border: none;
font-size: 1.4rem;
color: white;
cursor: pointer;
user-select: none;
}
#search-result-modal .close-search-btn:hover,
#search-result-modal .close-search-btn:focus-visible {
color: #e0e7ff;
outline-offset: 2px;
outline: 2px solid white;
}
/* 背景点击关闭 */
#search-result-mask {
position: fixed;
inset: 0;
z-index: 54;
background: transparent;
}
@keyframes fadein {
from {opacity: 0; transform: translateX(-50%) translateY(20px);}
to {opacity: 1; transform: translateX(-50%) translateY(0);}
}
</style>
</head>
<body>
<div id="background-layer" tabindex="-1"></div>
<canvas id="particle-canvas"></canvas>
<div id="app" role="application" aria-label="货架数据管理系统">
<!-- 侧边栏 -->
<nav id="sidebar" aria-label="货架列表侧边栏">
<header id="sidebar-header">
<button id="logo-upload-button" aria-label="上传自定义Logo" title="上传自定义Logo" type="button" tabindex="0">
<!-- 默认svg logo -->
<svg viewBox="0 0 64 64" role="img" aria-hidden="true" focusable="false">
<circle cx="32" cy="32" r="30" fill="#61aefb"/>
<path fill="#fff" d="M20 42v-4h24v4H20zm0-10v-4h24v4H20zm0-10v-4h24v4H20z"/>
</svg>
</button>
<input type="file" id="logo-file-input" accept="image/*" aria-label="选择Logo图片上传" />
<h1 tabindex="0" id="system-title">轻量级货架管理系统</h1>
</header>
<section id="shelf-list" tabindex="0" aria-label="货架列表">
<!-- 货架项目动态生成 -->
</section>
<footer id="sidebar-footer">
<button id="toggle-sidebar-btn" aria-label="切换侧边栏折叠状态" type="button" tabindex="0" aria-pressed="false">
<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" focusable="false" fill="white">
<path d="M10 17l5-5-5-5v10z"/>
</svg>
<span>收起</span>
</button>
</footer>
</nav>
<!-- 右侧主内容 -->
<main id="main-area" tabindex="-1" aria-label="货物数据操作区">
<!-- 工具栏 -->
<section id="toolbar" role="toolbar" aria-label="数据操作工具栏">
<input type="search" id="search-input" placeholder="搜索货物 (品名/种类)" aria-label="搜索货物" autocomplete="off" />
<button class="toolbar-btn" id="import-excel-btn" type="button" aria-label="导入Excel文件" title="导入Excel">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
</svg> 导入
</button>
<button class="toolbar-btn" id="export-excel-btn" type="button" aria-label="导出当前数据为Excel" title="导出Excel">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
</svg> 导出
</button>
<button class="toolbar-btn" id="save-data-btn" type="button" aria-label="保存当前数据" title="保存数据" disabled>
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M17 3H7c-1.1 0-2 .9-2 2v14l7-3 7 3V5c0-1.1-.9-2-2-2z"/>
</svg> 保存
</button>
<input type="file" id="import-excel-file" accept=".xlsx,.xls" style="display:none" aria-label="选择Excel文件导入" />
</section>
<!-- 货物表格展示 -->
<section id="goods-table-container" aria-label="货物列表" tabindex="0">
<table role="grid" aria-describedby="goods-table-desc">
<caption id="goods-table-desc" class="sr-only">当前选中货架的货物列表</caption>
<thead>
<tr>
<th scope="col"><input type="checkbox" id="select-all-checkbox" aria-label="全选货物" /></th>
<th scope="col">图</th>
<th scope="col">品名</th>
<th scope="col">种类</th>
<th scope="col">数量</th>
<th scope="col">金额</th>
<th scope="col">操作</th>
</tr>
</thead>
<tbody id="goods-tbody">
<!-- 动态数据 -->
</tbody>
</table>
</section>
<!-- 操作按钮 -->
<section id="actions-bar" role="region" aria-label="货物操作按钮区">
<button class="action-btn" type="button" id="add-good-btn" aria-label="添加货物">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M19 11h-6V5h-2v6H5v2h6v6h2v-6h6v-2z"/></svg> 添加
</button>
<button class="action-btn" type="button" id="edit-good-btn" aria-label="编辑选中货物" disabled>
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M3 17.25V21h3.75l11.06-11.06-3.75-3.75L3 17.25zM20.71 7.04a1.003 1.003 0 0 0 0-1.42l-2.34-2.34a1.003 1.003 0 0 0-1.42 0l-1.83 1.83 3.75 3.75 1.84-1.82z"/></svg> 编辑
</button>
<button class="action-btn" type="button" id="delete-good-btn" aria-label="删除选中货物" disabled>
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M16 9v10H8V9h8m-1.5-6H9.5l-1 1H5v2h14V4h-3.5l-1-1z"/></svg> 删除
</button>
<button class="action-btn" type="button" id="move-good-btn" aria-label="移动选中货物到其他货架" disabled>
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M10 3H5c-1.1 0-1.99.9-1.99 2L3 21l7-3 7 3V5c0-1.1-.9-2-2-2h-5z"/></svg> 移动
</button>
</section>
</main>
</div>
<!-- 添加/编辑货物弹窗 -->
<div id="modal-good-form" class="modal-overlay" role="dialog" aria-modal="true" aria-labelledby="modal-good-title" hidden>
<div class="modal-content">
<button class="modal-close-btn" aria-label="关闭货物弹窗" type="button">×</button>
<h2 id="modal-good-title">添加货物</h2>
<form class="modal-form" id="good-form" novalidate>
<div class="form-row">
<label for="good-name-input">品名 <span aria-hidden="true" style="color:#f87171">*</span></label>
<input type="text" id="good-name-input" name="name" autocomplete="off" required aria-required="true" aria-describedby="name-error" />
<div id="name-error" class="error-text" role="alert" aria-live="polite"></div>
</div>
<div class="form-row">
<label for="good-type-input">种类 <span aria-hidden="true" style="color:#f87171">*</span></label>
<input type="text" id="good-type-input" name="type" autocomplete="off" required aria-required="true" aria-describedby="type-error" />
<div id="type-error" class="error-text" role="alert" aria-live="polite"></div>
</div>
<div class="form-row">
<label for="good-quantity-input">数量 <span aria-hidden="true" style="color:#f87171">*</span></label>
<input type="number" id="good-quantity-input" name="quantity" min="0" required aria-required="true" aria-describedby="quantity-error" />
<div id="quantity-error" class="error-text" role="alert" aria-live="polite"></div>
</div>
<div class="form-row">
<label for="good-price-input">金额(元)</label>
<input type="number" id="good-price-input" name="price" min="0" step="0.01" aria-describedby="price-error" />
<div id="price-error" class="error-text" role="alert" aria-live="polite"></div>
</div>
<div class="form-row">
<label for="good-image-input">图片上传</label>
<input type="file" accept="image/*" id="good-image-input" name="image" aria-describedby="img-help" />
<div id="img-help" style="font-size:0.85rem;color:#94a3b8;user-select:none;margin-top:2px;">支持jpg/png等常见图片,大小不超过2MB</div>
<div class="thumbnail-preview" aria-label="图片预览" role="img"></div>
</div>
<div class="modal-form form-btns">
<button type="button" class="cancel-btn" id="cancel-good-btn">取消</button>
<button type="submit" id="save-good-btn">保存</button>
</div>
</form>
</div>
</div>
<!-- 搜索结果弹窗 -->
<div id="search-result-mask" tabindex="-1" hidden></div>
<div id="search-result-modal" hidden role="dialog" aria-modal="true" aria-labelledby="search-result-title">
<button class="close-search-btn" aria-label="关闭搜索结果" type="button">×</button>
<h3 id="search-result-title">搜索结果</h3>
<div id="search-result-list" tabindex="0">
<!-- 搜索结果列表 -->
</div>
</div>
<!-- 蜂鸣器音效,隐藏 -->
<audio id="click-sound" preload="auto" src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAgD4AAAB9AAACABAAZGF0YQEAAA==" hidden></audio>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script>
(() => {
const STORAGE_KEY = 'lightweight_shelf_mgmt_data_v2';
const LOGO_KEY = 'custom_logo_data_url';
const BG_KEY = 'custom_bg_data_url';
// ********************* 音效与动画bf *********************
// 播放轻柔点击音效
const clickSound = document.getElementById('click-sound');
function playClickSound() {
try {
if(!clickSound) return;
clickSound.currentTime = 0;
clickSound.play();
} catch(e) {}
}
// 添加波纹动画函数,附加事件对象
function addRipple(event) {
const target = event.currentTarget;
const rect = target.getBoundingClientRect();
const ripple = document.createElement('span');
ripple.className = 'ripple';
const size = Math.max(rect.width, rect.height);
ripple.style.width = ripple.style.height = size + 'px';
// 计算点击点相对元素的位置
let x = event.clientX - rect.left - size / 2;
let y = event.clientY - rect.top - size / 2;
ripple.style.left = x + 'px';
ripple.style.top = y + 'px';
target.appendChild(ripple);
setTimeout(() => {
ripple.remove();
}, 600);
}
// 全局点击委托,除了input/select等避免添加波纹
document.body.addEventListener('click', e => {
const target = e.target;
if(
(target.tagName === 'BUTTON' || target.classList.contains('action-btn') || target.classList.contains('toolbar-btn') || target.classList.contains('shelf-action-btn') || target.id === 'toggle-sidebar-btn') &&
!target.disabled
) {
addRipple(e);
playClickSound();
}
});
// *********************** 粒子网格动画 *********************
// 利用canvas绘制无序流畅网状连接线
const canvas = document.getElementById('particle-canvas');
const ctx = canvas.getContext('2d');
let width, height, particles;
class Particle {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * width;
this.y = Math.random() * height;
this.vx = (Math.random() - 0.5)*0.4;
this.vy = (Math.random() - 0.5)*0.4;
this.radius = 1 + Math.random()*2;
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > width) this.vx *= -1;
if (this.y < 0 || this.y > height) this.vy *= -1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
ctx.fillStyle = 'rgba(97, 174, 251, 0.25)';
ctx.fill();
}
}
function initParticles() {
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
particles = [];
const count = Math.floor(width * height / 12000); // 根据屏幕大小自动调整数量
for (let i = 0; i < count; i++) {
particles.push(new Particle());
}
}
function distance(p1, p2) {
const dx = p1.x - p2.x;
const dy = p1.y - p2.y;
return Math.sqrt(dx*dx+dy*dy);
}
function animateParticles() {
ctx.clearRect(0, 0, width, height);
// Update and draw particles
for (const p of particles) {
p.update();
p.draw();
}
// Draw connecting lines
for (let i = 0; i < particles.length; i++) {
for (let j = i+1; j < particles.length; j++) {
const dist = distance(particles[i], particles[j]);
if (dist < 120) {
const alpha = 0.25 * (1 - dist/120);
ctx.strokeStyle = 'rgba(97, 174, 251,' + alpha.toFixed(3) + ')';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.stroke();
}
}
}
requestAnimationFrame(animateParticles);
}
window.addEventListener('resize', () => {
initParticles();
});
// 初始化粒子动画
initParticles();
animateParticles();
// ******************** 主逻辑数据与UI *********************
// 数据结构
/*
{
shelves: [
{
id: string,
name: string,
goods: [
{
id: string,
name: string,
type: string,
quantity: number,
price: number,
imageBase64: string | null,
}
]
}
]
}
*/
// DOM Elements
const sidebar = document.getElementById('sidebar');
const shelfListEl = document.getElementById('shelf-list');
const toggleSidebarBtn = document.getElementById('toggle-sidebar-btn');
const systemTitle = document.getElementById('system-title');
const logoUploadBtn = document.getElementById('logo-upload-button');
const logoFileInput = document.getElementById('logo-file-input');
const mainArea = document.getElementById('main-area');
// 工具栏
const searchInput = document.getElementById('search-input');
const importExcelBtn = document.getElementById('import-excel-btn');
const exportExcelBtn = document.getElementById('export-excel-btn');
const saveDataBtn = document.getElementById('save-data-btn');
const importExcelFileInput = document.getElementById('import-excel-file');
// 货物表格相关
const goodsTbody = document.getElementById('goods-tbody');
const selectAllCheckbox = document.getElementById('select-all-checkbox');
// 操作按钮区
const addGoodBtn = document.getElementById('add-good-btn');
const editGoodBtn = document.getElementById('edit-good-btn');
const deleteGoodBtn = document.getElementById('delete-good-btn');
const moveGoodBtn = document.getElementById('move-good-btn');
// 弹窗相关
const modalGoodForm = document.getElementById('modal-good-form');
const modalCloseBtn = modalGoodForm.querySelector('.modal-close-btn');
const goodForm = document.getElementById('good-form');
const modalTitle = document.getElementById('modal-good-title');
const cancelGoodBtn = document.getElementById('cancel-good-btn');
const goodNameInput = document.getElementById('good-name-input');
const goodTypeInput = document.getElementById('good-type-input');
const goodQuantityInput = document.getElementById('good-quantity-input');
const goodPriceInput = document.getElementById('good-price-input');
const goodImageInput = document.getElementById('good-image-input');
const thumbnailPreview = modalGoodForm.querySelector('.thumbnail-preview');
const nameError = document.getElementById('name-error');
const typeError = document.getElementById('type-error');
const quantityError = document.getElementById('quantity-error');
const priceError = document.getElementById('price-error');
// 搜索弹窗相关
const searchResultModal = document.getElementById('search-result-modal');
const searchResultMask = document.getElementById('search-result-mask');
const searchResultList = document.getElementById('search-result-list');
const closeSearchBtn = searchResultModal.querySelector('.close-search-btn');
// 背景层
const backgroundLayer = document.getElementById('background-layer');
// 状态
let dataObj = null;
let selectedShelfId = null;
let selectedGoodIds = new Set();
let sidebarCollapsed = false;
let currentEditGoodId = null;
let unsavedChanges = false;
// 默认Logo和背景可以内置,也可从localStorage载入
let customLogoDataUrl = null;
let customBackgroundDataUrl = null;
// ID生成简单方法
function genId() {
return 'id-' + Math.random().toString(36).slice(2, 11);
}
// 初始化 - 读取localStorage数据
function loadDataFromStorage() {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
dataObj = JSON.parse(saved);
if (!dataObj.shelves || !Array.isArray(dataObj.shelves)) {
dataObj.shelves = [];
}
} else {
dataObj = { shelves: [] };
}
} catch {
dataObj = { shelves: [] };
}
// 载入logo bg
try {
customLogoDataUrl = localStorage.getItem(LOGO_KEY);
} catch {}
try {
customBackgroundDataUrl = localStorage.getItem(BG_KEY);
} catch {}
// 若无任何货架,初始化示范货架和示例数据
if (dataObj.shelves.length === 0) {
dataObj.shelves.push({
id: genId(),
name: '默认货架',
goods: []
});
}
}
// 持久化存储
function saveDataToStorage() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(dataObj));
unsavedChanges = false;
updateSaveButtonState();
}
// 绑定Logo上传逻辑
function bindLogoUpload() {
logoUploadBtn.addEventListener('click', () => {
logoFileInput.value = null;
logoFileInput.click();
});
logoFileInput.addEventListener('change', e => {
const file = e.target.files[0];
if (file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = function(evt) {
customLogoDataUrl = evt.target.result;
setCustomLogo(customLogoDataUrl);
try {
localStorage.setItem(LOGO_KEY, customLogoDataUrl);
} catch { }
};
reader.readAsDataURL(file);
}
});
}
// 设置logo显示
function setCustomLogo(dataUrl) {
if (dataUrl) {
// 替换默认svg
logoUploadBtn.innerHTML = '';
const img = document.createElement('img');
img.src = dataUrl;
img.alt = '用户自定义Logo';
img.style.width = '36px';
img.style.height = '36px';
img.style.borderRadius = '6px';
logoUploadBtn.appendChild(img);
} else {
// 恢复默认SVG
logoUploadBtn.innerHTML = `<svg viewBox="0 0 64 64" role="img" aria-hidden="true" focusable="false">
<circle cx="32" cy="32" r="30" fill="#61aefb"/>
<path fill="#fff" d="M20 42v-4h24v4H20zm0-10v-4h24v4H20zm0-10v-4h24v4H20z"/>
</svg>`;
}
}
// 设置背景层图片
function setCustomBackground(dataUrl) {
if (dataUrl) {
backgroundLayer.style.backgroundImage = `url(${dataUrl})`;
} else {
backgroundLayer.style.backgroundImage = 'none';
}
}
// 绑定顶部大背景上传,添加至右下角小按钮栏
function createBackgroundUploadControls() {
const container = document.createElement('div');
container.id = 'background-controls';
container.setAttribute('role', 'region');
container.setAttribute('aria-label', '背景图片更换控制');
container.style.position = 'fixed';
container.style.bottom = '12px';
container.style.right = '12px';
container.style.zIndex = '60';
container.style.display = 'flex';
container.style.flexDirection = 'column';
container.style.gap = '8px';
document.body.appendChild(container);
// 上传按钮
const uploadBtn = document.createElement('button');
uploadBtn.type = 'button';
uploadBtn.textContent = '更换背景';
uploadBtn.style.background = 'var(--btn-bg)';
uploadBtn.style.color = 'white';
uploadBtn.style.border = 'none';
uploadBtn.style.borderRadius = 'var(--border-radius)';
uploadBtn.style.padding = '8px 14px';
uploadBtn.style.cursor = 'pointer';
uploadBtn.style.userSelect = 'none';
uploadBtn.style.boxShadow = '0 3px 6px var(--btn-shadow)';
container.appendChild(uploadBtn);
// 清除按钮
const clearBtn = document.createElement('button');
clearBtn.type = 'button';
clearBtn.textContent = '清除背景';
clearBtn.style.background = '#64748B';
clearBtn.style.color = 'white';
clearBtn.style.border = 'none';
clearBtn.style.borderRadius = 'var(--border-radius)';
clearBtn.style.padding = '8px 14px';
clearBtn.style.cursor = 'pointer';
clearBtn.style.userSelect = 'none';
clearBtn.style.boxShadow = 'none';
container.appendChild(clearBtn);
// 上传input(隐藏)
const inputFile = document.createElement('input');
inputFile.type = 'file';
inputFile.accept = 'image/*';
inputFile.style.display = 'none';
container.appendChild(inputFile);
uploadBtn.addEventListener('click', () => {
inputFile.value = null;
inputFile.click();
});
inputFile.addEventListener('change', e => {
const file = e.target.files[0];
if (file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = evt => {
customBackgroundDataUrl = evt.target.result;
setCustomBackground(customBackgroundDataUrl);
try {
localStorage.setItem(BG_KEY, customBackgroundDataUrl);
} catch {}
};
reader.readAsDataURL(file);
}
});
clearBtn.addEventListener('click', () => {
customBackgroundDataUrl = null;
setCustomBackground(null);
try {
localStorage.removeItem(BG_KEY);
} catch {}
});
}
// 渲染货架列表
function renderShelfList() {
shelfListEl.innerHTML = '';
const collapsed = sidebar.classList.contains('collapsed');
const shelves = dataObj.shelves;
shelves.forEach(shelf => {
const item = document.createElement('div');
item.className = 'shelf-item';
item.setAttribute('role', 'button');
item.setAttribute('tabindex', '0');
item.dataset.shelfId = shelf.id;
if (shelf.id === selectedShelfId) item.classList.add('selected');
item.setAttribute('aria-pressed', shelf.id === selectedShelfId ? 'true' : 'false');
// icon
const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
icon.setAttribute('class', 'shelf-icon');
icon.setAttribute('viewBox', '0 0 24 24');
icon.setAttribute('aria-hidden', 'true');
icon.setAttribute('focusable', 'false');
icon.innerHTML = `<path d="M3 13h2v-2H3v2Zm0 4h2v-2H3v2Zm0-8h2V7H3v2Zm4 12h14v-2H7v2Zm0-8h14v-2H7v2Zm0-4h14V7H7v2Z"/>`;
item.appendChild(icon);
// 名称区域
const nameSpan = document.createElement('span');
nameSpan.className = 'shelf-name';
nameSpan.textContent = shelf.name;
nameSpan.title = shelf.name;
item.appendChild(nameSpan);
// 编辑和删除按钮区(非折叠状态下)
if (!collapsed) {
const actions = document.createElement('div');
actions.className = 'shelf-actions';
// 重命名按钮
const renameBtn = document.createElement('button');
renameBtn.className = 'shelf-action-btn';
renameBtn.type = 'button';
renameBtn.setAttribute('aria-label', `重命名货架 ${shelf.name}`);
renameBtn.title = '重命名货架';
renameBtn.innerHTML = `<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true" focusable="false"><path d="M3 17.25v3.75h3.75l11-11-3.75-3.75-11 11Zm14-10.5 3.75 3.75-1.92 1.92-3.75-3.75 1.92-1.92Z"/></svg>`;
actions.appendChild(renameBtn);
// 删除按钮,只有当货架无货物才能删除
const deleteBtn = document.createElement('button');
deleteBtn.className = 'shelf-action-btn';
deleteBtn.type = 'button';
deleteBtn.setAttribute('aria-label', `删除货架 ${shelf.name}`);
deleteBtn.title = '删除货架';
deleteBtn.disabled = shelf.goods.length > 0;
deleteBtn.innerHTML = `<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true" focusable="false"><path d="M16 9v10H8V9h8m-1.5-6H9.5l-1 1H5v2h14V4h-3.5l-1-1z"/></svg>`;
actions.appendChild(deleteBtn);
item.appendChild(actions);
// 侧边栏重命名功能
renameBtn.addEventListener('click', ev => {
ev.stopPropagation();
if (item.querySelector('input')) return; // 防止二次编辑
// 替换nameSpan为input框
const input = document.createElement('input');
input.type = 'text';
input.className = 'shelf-name-edit';
input.value = shelf.name;
item.replaceChild(input, nameSpan);
input.focus();
// 选中全部文字
input.setSelectionRange(0, input.value.length);
// 提交重命名
function finishRename() {
const val = input.value.trim();
if (!val) {
alert('货架名称不能为空!');
input.focus();
return;
}
shelf.name = val;
unsavedChanges = true;
updateSaveButtonState();
// 替换回span
nameSpan.textContent = val;
item.replaceChild(nameSpan, input);
renderShelfList();
renderGoodsTable();
}
// 失去焦点自动提交
input.addEventListener('blur', () => finishRename());
input.addEventListener('keydown', e => {
if (e.key === 'Enter') {
finishRename();
e.preventDefault();
input.blur();
}
if (e.key === 'Escape') {
item.replaceChild(nameSpan, input);
input.blur();
}
});
});
// 删除货架按钮
deleteBtn.addEventListener('click', ev => {
ev.stopPropagation();
if (!confirm(`确定删除货架【${shelf.name}】?删除后不可恢复。`)) return;
// 删除
const idx = dataObj.shelves.findIndex(s=>s.id === shelf.id);
if (idx >= 0) {
dataObj.shelves.splice(idx, 1);
unsavedChanges = true;
updateSaveButtonState();
// 若删除的货架当前被选中,切换为第一个货架或空
if(selectedShelfId === shelf.id) {
if(dataObj.shelves.length > 0) {
selectedShelfId = dataObj.shelves[0].id;
} else {
selectedShelfId = null;
}
}
selectedGoodIds.clear();
renderShelfList();
renderGoodsTable();
updateActionButtonState();
}
});
}
// 点击切换货架
item.addEventListener('click', () => {
if (selectedShelfId === shelf.id) return;
selectedShelfId = shelf.id;
selectedGoodIds.clear();
renderShelfList();
renderGoodsTable();
updateActionButtonState();
});
// 键盘切换货架支持
item.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
item.click();
}
});
shelfListEl.appendChild(item);
});
}
// 更新保存按钮状态
function updateSaveButtonState() {
if (unsavedChanges) {
saveDataBtn.disabled = false;
} else {
saveDataBtn.disabled = true;
}
}
// 渲染右侧货物表格
function renderGoodsTable(filterText = '') {
goodsTbody.innerHTML = '';
if (!selectedShelfId) return;
const shelf = dataObj.shelves.find(s => s.id === selectedShelfId);
if (!shelf) return;
let goodsList = shelf.goods;
// 过滤搜索
if (filterText) {
const lowFilter = filterText.toLocaleLowerCase();
goodsList = goodsList.filter(g =>
g.name.toLocaleLowerCase().includes(lowFilter) || g.type.toLocaleLowerCase().includes(lowFilter)
);
}
if (goodsList.length === 0) {
// 无数据时显示导出Excel示例格式提示
const tr = document.createElement('tr');
const td = document.createElement('td');
td.colSpan = 7;
td.style.textAlign = 'center';
td.style.padding = '20px';
td.style.userSelect = 'text';
td.textContent = '当前货架无货物数据。请点击导入按钮导入符合格式的Excel文件,格式示例如下:品名、种类、数量、金额、图片Base64(可空)。';
tr.appendChild(td);
goodsTbody.appendChild(tr);
return;
}
for (const good of goodsList) {
const tr = document.createElement('tr');
tr.dataset.goodId = good.id;
if (selectedGoodIds.has(good.id)) {
tr.classList.add('selected');
}
tr.setAttribute('tabindex', '0');
tr.setAttribute('role', 'row');
// 复选框
const checkboxTd = document.createElement('td');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = selectedGoodIds.has(good.id);
checkbox.setAttribute('aria-label', `选择货物 ${good.name}`);
checkbox.addEventListener('change', e => {
if (checkbox.checked) {
selectedGoodIds.add(good.id);
} else {
selectedGoodIds.delete(good.id);
}
updateActionButtonState();
// 同步tr高亮
if (checkbox.checked) {
tr.classList.add('selected');
} else {
tr.classList.remove('selected');
}
// 同步全选框状态
synchronizeSelectAllCheckbox();
});
checkboxTd.appendChild(checkbox);
tr.appendChild(checkboxTd);
// 图片缩略图
const imgTd = document.createElement('td');
const imgContainer = document.createElement('div');
imgContainer.className = 'thumb-container';
if (good.imageBase64) {
const img = document.createElement('img');
img.src = good.imageBase64;
img.alt = `货物${good.name}图片`;
img.tabIndex = 0;
img.style.borderRadius = '6px';
img.addEventListener('click', () => {
openImagePreview(good.imageBase64, good.name);
});
img.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
openImagePreview(good.imageBase64, good.name);
}
});
imgContainer.appendChild(img);
} else {
const placeholder = document.createElement('span');
placeholder.className = 'thumb-placeholder';
placeholder.textContent = '/';
imgContainer.appendChild(placeholder);
}
imgTd.appendChild(imgContainer);
tr.appendChild(imgTd);
// 品名
const nameTd = document.createElement('td');
nameTd.textContent = good.name;
tr.appendChild(nameTd);
// 种类
const typeTd = document.createElement('td');
typeTd.textContent = good.type;
tr.appendChild(typeTd);
// 数量
const quanTd = document.createElement('td');
quanTd.textContent = good.quantity;
tr.appendChild(quanTd);
// 金额
const priceTd = document.createElement('td');
priceTd.textContent = good.price != null && !isNaN(good.price) ? good.price.toFixed(2) : '';
tr.appendChild(priceTd);
// 操作按钮列
const opTd = document.createElement('td');
opTd.style.userSelect = 'none';
// 单条编辑按钮
const editBtn = document.createElement('button');
editBtn.type = 'button';
editBtn.title = `编辑货物【${good.name}】`;
editBtn.setAttribute('aria-label', `编辑货物${good.name}`);
editBtn.style.marginRight = '8px';
editBtn.style.borderRadius = '6px';
editBtn.style.border = 'none';
editBtn.style.background = 'var(--btn-bg)';
editBtn.style.color = 'white';
editBtn.style.padding = '4px 8px';
editBtn.style.cursor = 'pointer';
editBtn.style.fontWeight = '600';
editBtn.addEventListener('click', () => {
openGoodModalForEdit(good.id);
});
editBtn.addEventListener('focus', () => {
tr.classList.add('selected');
});
editBtn.addEventListener('blur', () => {
if (!selectedGoodIds.has(good.id)) tr.classList.remove('selected');
});
editBtn.textContent = '编辑';
// 单条删除按钮
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.title = `删除货物【${good.name}】`;
delBtn.setAttribute('aria-label', `删除货物${good.name}`);
delBtn.style.borderRadius = '6px';
delBtn.style.border = 'none';
delBtn.style.background = '#f87171';
delBtn.style.color = 'white';
delBtn.style.padding = '4px 8px';
delBtn.style.cursor = 'pointer';
delBtn.style.fontWeight = '600';
delBtn.textContent = '删除';
delBtn.addEventListener('click', () => {
if (!confirm(`确认删除货物【${good.name}】?操作不可撤销。`)) return;
deleteGoodsByIds(new Set([good.id]));
});
opTd.appendChild(editBtn);
opTd.appendChild(delBtn);
tr.appendChild(opTd);
// 行点击支持全选checkbox同步
tr.addEventListener('click', (e) => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.tagName === 'IMG') return;
checkbox.checked = !checkbox.checked;
checkbox.dispatchEvent(new Event('change'));
});
tr.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
checkbox.checked = !checkbox.checked;
checkbox.dispatchEvent(new Event('change'));
}
});
goodsTbody.appendChild(tr);
}
}
// 打开图片预览弹窗
function openImagePreview(base64Str, altText) {
// 创建弹窗
const imgModal = document.createElement('div');
imgModal.style.position = 'fixed';
imgModal.style.inset = '0';
imgModal.style.background = 'rgba(0,0,0,0.8)';
imgModal.style.display = 'flex';
imgModal.style.alignItems = 'center';
imgModal.style.justifyContent = 'center';
imgModal.style.zIndex = '1000';
imgModal.style.cursor = 'zoom-out';
imgModal.setAttribute('tabindex', '0');
imgModal.setAttribute('aria-label', altText || '图片预览');
const img = document.createElement('img');
img.src = base64Str;
img.alt = altText || '货物图片';
img.style.maxWidth = '90vw';
img.style.maxHeight = '90vh';
img.style.borderRadius = 'var(--border-radius)';
imgModal.appendChild(img);
document.body.appendChild(imgModal);
imgModal.focus();
function close() {
document.body.removeChild(imgModal);
}
imgModal.addEventListener('click', close);
imgModal.addEventListener('keydown', e => {
if (e.key === 'Escape') {
close();
}
});
}
// 全选复选框切换逻辑
selectAllCheckbox.addEventListener('change', e => {
selectedGoodIds.clear();
const checked = e.target.checked;
if (checked && selectedShelfId) {
const shelf = dataObj.shelves.find(s => s.id === selectedShelfId);
if (shelf && shelf.goods.length > 0) {
shelf.goods.forEach(g => selectedGoodIds.add(g.id));
}
}
renderGoodsTable(searchInput.value.trim());
updateActionButtonState();
});
function synchronizeSelectAllCheckbox() {
if (!selectedShelfId) {
selectAllCheckbox.checked = false;
selectAllCheckbox.indeterminate = false;
return;
}
const shelf = dataObj.shelves.find(s => s.id === selectedShelfId);
if (!shelf) return;
if(shelf.goods.length === 0) {
selectAllCheckbox.checked = false;
selectAllCheckbox.indeterminate = false;
return;
}
if(selectedGoodIds.size === 0) {
selectAllCheckbox.checked = false;
selectAllCheckbox.indeterminate = false;
return;
}
if(selectedGoodIds.size === shelf.goods.length) {
selectAllCheckbox.checked = true;
selectAllCheckbox.indeterminate = false;
return;
}
selectAllCheckbox.indeterminate = true;
selectAllCheckbox.checked = false;
}
// 操作按钮启用/禁用状态管理
function updateActionButtonState() {
const selCount = selectedGoodIds.size;
editGoodBtn.disabled = selCount === 1 ? false : true;
deleteGoodBtn.disabled = selCount === 0;
moveGoodBtn.disabled = selCount === 0;
synchronizeSelectAllCheckbox();
}
// 打开添加货物弹窗
function openGoodModalForAdd() {
currentEditGoodId = null;
modalTitle.textContent = '添加货物';
goodForm.reset();
thumbnailPreview.innerHTML = '';
modalGoodForm.hidden = false;
goodNameInput.focus();
clearValidationErrors();
}
// 打开编辑弹窗
function openGoodModalForEdit(goodId) {
currentEditGoodId = goodId;
modalTitle.textContent = '编辑货物';
clearValidationErrors();
thumbnailPreview.innerHTML = '';
if (!selectedShelfId) return;
const shelf = dataObj.shelves.find(s => s.id === selectedShelfId);
if (!shelf) return;
const good = shelf.goods.find(g => g.id === goodId);
if (!good) return;
// 填充数据
goodNameInput.value = good.name;
goodTypeInput.value = good.type;
goodQuantityInput.value = good.quantity;
goodPriceInput.value = good.price != null ? good.price : '';
if (good.imageBase64) {
const img = document.createElement('img');
img.src = good.imageBase64;
img.alt = '当前货物图片预览';
thumbnailPreview.appendChild(img);
}
modalGoodForm.hidden = false;
goodNameInput.focus();
}
// 清空验证错误
function clearValidationErrors() {
nameError.textContent = '';
typeError.textContent = '';
quantityError.textContent = '';
priceError.textContent = '';
}
// 验证表单数据
function validateGoodForm() {
clearValidationErrors();
let valid = true;
const nameVal = goodNameInput.value.trim();
const typeVal = goodTypeInput.value.trim();
const quantityVal = goodQuantityInput.value.trim();
const priceVal = goodPriceInput.value.trim();
if (!nameVal) {
nameError.textContent = '请输入品名';
valid = false;
goodNameInput.focus();
}
if (!typeVal) {
typeError.textContent = '请输入种类';
if (valid) {
valid = false;
goodTypeInput.focus();
}
}
if (!quantityVal || isNaN(quantityVal) || Number(quantityVal) < 0) {
quantityError.textContent = '请输入有效数量 (0或以上)';
if (valid) {
valid = false;
goodQuantityInput.focus();
}
}
if (priceVal !== '' && (isNaN(priceVal) || Number(priceVal) < 0)) {
priceError.textContent = '金额必须为0或正数';
if (valid) {
valid = false;
goodPriceInput.focus();
}
}
return valid;
}
// 读取上传的图片文件,转换为base64
function readImageFile(file) {
return new Promise((resolve, reject) => {
if(!file) return resolve(null);
if (!file.type.startsWith('image/')) return reject(new Error('文件不是图片'));
if(file.size > 2*1024*1024) return reject(new Error('图片大小超过2MB'));
const reader = new FileReader();
reader.onload = evt => resolve(evt.target.result);
reader.onerror = () => reject(new Error('图片读取失败'));
reader.readAsDataURL(file);
});
}
// 监听file输入,预览图
goodImageInput.addEventListener('change', async e => {
const file = e.target.files[0];
if (!file) {
thumbnailPreview.innerHTML = '';
return;
}
try {
const base64 = await readImageFile(file);
thumbnailPreview.innerHTML = '';
const img = document.createElement('img');
img.src = base64;
img.alt = '上传图片预览';
thumbnailPreview.appendChild(img);
} catch (err) {
alert(err.message);
goodImageInput.value = null;
thumbnailPreview.innerHTML = '';
}
});
// 关闭弹窗
function closeGoodModal() {
modalGoodForm.hidden = true;
goodForm.reset();
currentEditGoodId = null;
}
// 提交弹窗表单
goodForm.addEventListener('submit', async (e) => {
e.preventDefault();
if (!validateGoodForm()) return;
if (!selectedShelfId) {
alert('请先选择一个货架');
closeGoodModal();
return;
}
const shelf = dataObj.shelves.find(s => s.id === selectedShelfId);
if (!shelf) return;
// 读取图片Base64,优先弹窗内file,不上传则保留旧图(编辑时)
let base64Img = null;
if (goodImageInput.files.length > 0) {
try {
base64Img = await readImageFile(goodImageInput.files[0]);
} catch (err) {
alert(err.message);
return;
}
} else {
if (currentEditGoodId) {
const oldGood = shelf.goods.find(g => g.id === currentEditGoodId);
if(oldGood) base64Img = oldGood.imageBase64 || null;
}
}
if (currentEditGoodId) {
// 编辑
const good = shelf.goods.find(g => g.id === currentEditGoodId);
if (good) {
good.name = goodNameInput.value.trim();
good.type = goodTypeInput.value.trim();
good.quantity = Number(goodQuantityInput.value);
good.price = goodPriceInput.value !== '' ? Number(goodPriceInput.value) : null;
good.imageBase64 = base64Img;
}
} else {
// 新增
const newGood = {
id: genId(),
name: goodNameInput.value.trim(),
type: goodTypeInput.value.trim(),
quantity: Number(goodQuantityInput.value),
price: goodPriceInput.value !== '' ? Number(goodPriceInput.value) : null,
imageBase64: base64Img
};
shelf.goods.push(newGood);
selectedGoodIds.add(newGood.id);
}
unsavedChanges = true;
updateSaveButtonState();
renderGoodsTable(searchInput.value.trim());
updateActionButtonState();
closeGoodModal();
});
// 取消按钮
cancelGoodBtn.addEventListener('click', e => {
e.preventDefault();
closeGoodModal();
});
// 关闭弹窗按钮
modalCloseBtn.addEventListener('click', () => {
closeGoodModal();
});
modalGoodForm.addEventListener('click', e => {
if (e.target === modalGoodForm) {
closeGoodModal();
}
});
modalGoodForm.addEventListener('keydown', e => {
if (e.key === 'Escape') {
closeGoodModal();
}
});
// 操作按钮事件
addGoodBtn.addEventListener('click', () => {
openGoodModalForAdd();
});
editGoodBtn.addEventListener('click', () => {
if (selectedGoodIds.size === 1) {
const id = [...selectedGoodIds][0];
openGoodModalForEdit(id);
}
});
deleteGoodBtn.addEventListener('click', () => {
if (selectedGoodIds.size === 0) return;
if (!confirm(`确认删除选中的${selectedGoodIds.size}个货物?删除不可恢复。`)) return;
deleteGoodsByIds(selectedGoodIds);
});
// 移动弹窗(简单下拉提示)
moveGoodBtn.addEventListener('click', () => {
openMoveGoodsModal();
});
// 删除货物函数
function deleteGoodsByIds(idSet) {
if (!selectedShelfId) return;
const shelf = dataObj.shelves.find(s => s.id === selectedShelfId);
if(!shelf) return;
shelf.goods = shelf.goods.filter(g => !idSet.has(g.id));
idSet.forEach(id => selectedGoodIds.delete(id));
unsavedChanges = true;
updateSaveButtonState();
renderGoodsTable(searchInput.value.trim());
updateActionButtonState();
}
// 移动货物弹窗
function openMoveGoodsModal() {
if(selectedGoodIds.size === 0) return;
const modal = document.createElement('div');
modal.className = 'modal-overlay';
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
modal.style.color = '#f1f5f9';
const panel = document.createElement('div');
panel.className = 'modal-content';
panel.style.maxHeight = '220px';
modal.appendChild(panel);
const title = document.createElement('h2');
title.textContent = '移动选中货物到货架';
panel.appendChild(title);
// Select下拉
const formRow = document.createElement('div');
formRow.style.marginBottom = '16px';
panel.appendChild(formRow);
const label = document.createElement('label');
label.textContent = '选择目标货架';
label.setAttribute('for', 'move-target-select');
formRow.appendChild(label);
const select = document.createElement('select');
select.id = 'move-target-select';
select.style.width = '100%';
select.style.padding = '8px 12px';
select.style.borderRadius = 'var(--border-radius)';
select.style.border = 'none';
select.style.outline = 'none';
select.style.marginTop = '4px';
select.style.fontSize = '1rem';
formRow.appendChild(select);
dataObj.shelves.forEach(shelf => {
if (shelf.id !== selectedShelfId) {
const option = document.createElement('option');
option.value = shelf.id;
option.textContent = shelf.name;
select.appendChild(option);
}
});
if(select.options.length === 0) {
select.disabled = true;
label.textContent += '(无其他货架可选)';
}
// 按钮区
const btnGroup = document.createElement('div');
btnGroup.style.display = 'flex';
btnGroup.style.justifyContent = 'flex-end';
btnGroup.style.gap = '12px';
panel.appendChild(btnGroup);
const cancelBtn = document.createElement('button');
cancelBtn.textContent = '取消';
cancelBtn.className = 'cancel-btn';
btnGroup.appendChild(cancelBtn);
const okBtn = document.createElement('button');
okBtn.textContent = '移动';
okBtn.disabled = select.disabled;
btnGroup.appendChild(okBtn);
document.body.appendChild(modal);
select.focus();
cancelBtn.addEventListener('click', () => {
document.body.removeChild(modal);
});
okBtn.addEventListener('click', () => {
if (select.disabled) return;
const targetShelfId = select.value;
if (!targetShelfId) return;
moveSelectedGoodsToShelf(targetShelfId);
document.body.removeChild(modal);
});
modal.addEventListener('click', e => {
if(e.target === modal) document.body.removeChild(modal);
});
modal.addEventListener('keydown', e => {
if(e.key === 'Escape') document.body.removeChild(modal);
});
}
// 移动货物实现
function moveSelectedGoodsToShelf(targetShelfId) {
if (!selectedShelfId || !targetShelfId || selectedShelfId === targetShelfId) return;
const sourceShelf = dataObj.shelves.find(s => s.id === selectedShelfId);
const targetShelf = dataObj.shelves.find(s => s.id === targetShelfId);
if (!sourceShelf || !targetShelf) return;
const movingGoods = sourceShelf.goods.filter(g => selectedGoodIds.has(g.id));
if(movingGoods.length === 0) return;
// 移入目标货架
targetShelf.goods = targetShelf.goods.concat(movingGoods);
// 从源货架移除
sourceShelf.goods = sourceShelf.goods.filter(g => !selectedGoodIds.has(g.id));
selectedGoodIds.clear();
selectedShelfId = targetShelfId;
unsavedChanges = true;
updateSaveButtonState();
renderShelfList();
renderGoodsTable(searchInput.value.trim());
updateActionButtonState();
}
// 搜索功能
searchInput.addEventListener('input', e => {
const val = e.target.value.trim();
if(val.length === 0) {
searchResultModal.hidden = true;
searchResultMask.hidden = true;
renderGoodsTable('');
return;
}
// 搜索所有货架所有货物
const results = [];
for (const shelf of dataObj.shelves) {
for (const good of shelf.goods) {
if (
good.name.toLocaleLowerCase().includes(val.toLocaleLowerCase()) ||
good.type.toLocaleLowerCase().includes(val.toLocaleLowerCase())
) {
results.push({...good, shelfName: shelf.name});
}
}
}
renderSearchResults(results);
});
// 渲染搜索结果弹窗
function renderSearchResults(results) {
searchResultList.innerHTML = '';
if(results.length === 0) {
const msg = document.createElement('div');
msg.textContent = '未找到匹配的货物。';
searchResultList.appendChild(msg);
} else {
for(const good of results) {
const div = document.createElement('div');
div.className = 'search-item';
const title = document.createElement('div');
title.className = 'search-item-title';
title.textContent = good.name;
div.appendChild(title);
const detail1 = document.createElement('div');
detail1.className = 'search-item-detail';
detail1.textContent = `种类: ${good.type}`;
div.appendChild(detail1);
const detail2 = document.createElement('div');
detail2.className = 'search-item-detail';
detail2.textContent = `数量: ${good.quantity}, 金额: ${good.price != null ? good.price.toFixed(2) : '-'}`;
div.appendChild(detail2);
const detail3 = document.createElement('div');
detail3.className = 'search-item-detail';
detail3.textContent = `货架: ${good.shelfName}`;
div.appendChild(detail3);
searchResultList.appendChild(div);
}
}
searchResultModal.hidden = false;
searchResultMask.hidden = false;
searchResultModal.focus();
}
closeSearchBtn.addEventListener('click', () => {
searchResultModal.hidden = true;
searchResultMask.hidden = true;
});
searchResultMask.addEventListener('click', () => {
searchResultModal.hidden = true;
searchResultMask.hidden = true;
});
searchResultModal.addEventListener('keydown', e => {
if(e.key === 'Escape') {
searchResultModal.hidden = true;
searchResultMask.hidden = true;
}
});
// 侧边栏折叠切换
toggleSidebarBtn.addEventListener('click', () => {
sidebarCollapsed = !sidebarCollapsed;
if (sidebarCollapsed) {
sidebar.classList.add('collapsed');
toggleSidebarBtn.setAttribute('aria-pressed', 'true');
toggleSidebarBtn.querySelector('span').textContent = '展开';
// 改变箭头方向
toggleSidebarBtn.querySelector('svg path').setAttribute('d','M14 7l-5 5 5 5V7z');
} else {
sidebar.classList.remove('collapsed');
toggleSidebarBtn.setAttribute('aria-pressed', 'false');
toggleSidebarBtn.querySelector('span').textContent = '收起';
toggleSidebarBtn.querySelector('svg path').setAttribute('d','M10 17l5-5-5-5v10z');
}
renderShelfList();
});
// 初始状态不折叠
// 导入Excel
importExcelBtn.addEventListener('click', () => {
importExcelFileInput.value = null;
importExcelFileInput.click();
});
importExcelFileInput.addEventListener('change', async (e) => {
if (e.target.files.length === 0) return;
const file = e.target.files[0];
if (!file) return;
if (!selectedShelfId) {
alert('请先选择一个货架再导入数据');
return;
}
try {
const data = await file.arrayBuffer();
const workbook = XLSX.read(data);
// 默认从第一个sheet
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, {defval: ''});
// 校验字段和格式
// 需要: 品名, 种类, 数量, 金额, 图片Base64 (图片列可空)
const requiredFields = ['品名', '种类', '数量', '金额', '图片Base64'];
const missingFields = requiredFields.filter(f => !Object.keys(jsonData[0] || {}).includes(f));
if (missingFields.length > 0) {
alert(`导入失败:Excel缺少字段 [${missingFields.join(', ')}]。请使用符合格式的表格。`);
return;
}
// 规范化并添加到当前货架
const shelf = dataObj.shelves.find(s => s.id === selectedShelfId);
if(!shelf) return;
// 转化
const newGoods = [];
for (const row of jsonData) {
const name = (row['品名'] || '').toString().trim();
const type = (row['种类'] || '').toString().trim();
const quantityRaw = row['数量'];
const priceRaw = row['金额'];
const base64Img = (row['图片Base64'] || '').toString().trim();
if (!name || !type) {
alert('Excel导入行存在品名或种类为空,导入终止。');
return;
}
let quantity = Number(quantityRaw);
let price = Number(priceRaw);
if (isNaN(quantity) || quantity < 0) quantity = 0;
if (isNaN(price) || price < 0) price = null;
newGoods.push({
id: genId(),
name,
type,
quantity,
price,
imageBase64: base64Img || null
});
}
if(newGoods.length === 0) {
alert('导入Excel无有效数据。');
return;
}
// 合并
shelf.goods = shelf.goods.concat(newGoods);
unsavedChanges = true;
updateSaveButtonState();
renderGoodsTable(searchInput.value.trim());
updateActionButtonState();
alert('导入成功!导入数据已添加到当前货架。');
} catch (err) {
alert('导入过程中发生错误:' + err.message);
}
});
// 导出Excel
exportExcelBtn.addEventListener('click', () => {
if (!selectedShelfId) {
alert('请选择一个货架后再导出数据');
return;
}
const shelf = dataObj.shelves.find(s => s.id === selectedShelfId);
if (!shelf) return;
if (shelf.goods.length === 0) {
// 无数据时提供示例表格
if(!confirm('当前货架无数据,是否导出Excel表单格式示例?')) return;
exportExampleExcel();
return;
}
exportShelfGoodsToExcel(shelf);
});
function exportExampleExcel() {
const exampleData = [
['品名', '种类', '数量', '金额', '图片Base64'],
['示例货物1', '饮料', 10, 25.5, ''],
['示例货物2', '食品', 5, 12.9, '']
];
const ws = XLSX.utils.aoa_to_sheet(exampleData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, '示例货物表');
const blob = XLSX.write(wb, {bookType:'xlsx', type:'blob'});
const ts = new Date().toISOString().slice(0,19).replace(/:/g,'-');
const fname = `示例货物表_${ts}.xlsx`;
saveFile(blob, fname);
}
// 导出当前货架所有货物
function exportShelfGoodsToExcel(shelf) {
// 转化为二维数组
const header = ['品名', '种类', '数量', '金额', '图片Base64'];
const sheetData = [header];
for(const good of shelf.goods) {
sheetData.push([
good.name,
good.type,
good.quantity,
good.price != null ? good.price : '',
good.imageBase64 || ''
]);
}
const ws = XLSX.utils.aoa_to_sheet(sheetData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, shelf.name || '货物表');
const blob = XLSX.write(wb, {bookType:'xlsx', type:'blob'});
const ts = new Date().toISOString().slice(0,19).replace(/:/g,'-');
const fname = `货架_${shelf.name}_${ts}.xlsx`;
saveFile(blob, fname);
}
// 浏览器端文件保存
function saveFile(blob, filename) {
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}, 100);
}
// 保存按钮
saveDataBtn.addEventListener('click', () => {
saveDataToStorage();
alert('数据保存成功!');
});
// 关闭或刷新浏览器时警告未保存数据
window.addEventListener('beforeunload', (e) => {
if(unsavedChanges){
e.preventDefault();
e.returnValue = '';
return '';
}
});
// 初始化
function init() {
loadDataFromStorage();
setCustomLogo(customLogoDataUrl);
setCustomBackground(customBackgroundDataUrl);
renderShelfList();
// 默认选第一个货架
selectedShelfId = dataObj.shelves[0]?.id || null;
renderGoodsTable();
updateActionButtonState();
updateSaveButtonState();
bindLogoUpload();
createBackgroundUploadControls();
}
init();
})();
</script>
<!-- 辅助样式只屏蔽显示 -->
<style>
.sr-only {
border: 0 !important;
clip: rect(1px,1px,1px,1px) !important;
clip-path: inset(50%) !important;
height: 1px !important;
overflow: hidden !important;
padding: 0 !important;
position: absolute !important;
white-space: nowrap !important;
width: 1px !important;
}
</style>
</body>
</html>
功能说明和满足点:
- 纯前端实现,纯HTML+CSS+JS集成: 引入了目前最新的官方ShetXJS官方cdn版本;
- 现代简约半透明浅蓝基调风格: 使用Css变量和半透明色彩,干净且不沉闷;
- 左侧280px宽侧栏,带折叠56px宽成图标按钮组: 侧栏货架列表支持重命名和删除(空货架可删);
- 自定义logo上传覆盖默认svg图标,存储于localStorage: 支持透明背景logo。
- 右侧大背景为用户可上传的图片,自定义叠加动态无序流畅网格连接粒子动画(canvas实现);
- 顶部工具栏: 全局搜索框 + 导入Excel + 导出Excel + 数据保存按钮,保存状态动态启用/禁用;
- 货物列表表格(含复选框多选),图片缩略图可点击查看大图弹出,缺图斜杠占位,防止空洞;
- 添加/编辑货物弹窗全屏模态,深色半透明背景,圆角大面板,内含校验、图片上传与预览,键盘无障碍良好体验;
- 搜索结果弹窗渐变圆角柔和阴影,点击遮罩或按钮关闭,支持键盘Esc关闭;
- 导入Excel严格字段校验,有错误提示,支持解析图片Base64字符串,批量追加当前选货架;
- 导出Excel当前货架全部数据,带时间戳文件名,缓存规避,图片Base64完整导出;
- 无数据导出时提示并导出格式示例Excel;
- 多选货物支持批量删除、批量移动到其他货架弹窗选择目标货架;
- 数据和UI状态均保存在localStorage,未保存的更改会激活保存按钮,且刷新关闭页面弹出警告防止数据丢失;
- 全局点击按钮产生细腻波纹动画及播放轻柔音效,增强操作感;
- 控件均支持键盘导航,屏幕阅读器友好,aria标签完备。
- 货架重命名inline编辑,操作简便;
- 右下角提供独立的背景图片上传与清除按钮。
您可直接保存为.html,用现代浏览器打开且保证网络访问cdn库,即可体验完整功能。
如果需要改进或功能调整,可继续告知。祝您使用愉快!