This repository has been archived on 2026-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MetaLab/templates/MetaLab-2026/html/settings/index.html
Victor_Jay c3dec09dae feat(settings): 个人资料编辑 + 头像上传/裁切 + 自定义裁切弹窗
**新增功能:**

用户名编辑:输入框替换静态文本,白名单验证(中文/英文/数字/下划线/连字符),前端计数器(n/16),utf8对齐PG VARCHAR,XSS防控。

个性签名编辑:Textarea,128字符上限,实时计数器。

头像上传管线:校验→解码→裁切→CatmullRom缩放→WebP二分编码≤100KB→原子写入(.tmp→os.Rename)。限制5MB,128-3840px,JPEG/PNG/WebP。输出512x512 WebP。文件名 {uid}_{timestamp}.webp。清理旧头像。

自定义裁切弹窗:浅色主题,固定裁切框+图片平移/缩放(1×-3×滚轮),box-shadow遮罩,三等分网格。坐标映射pan/zoom→原图像素→subImage。

CSP修复:img-src允许data:URI(FileReader预览)。

**文件变更:**
修改: README, docs/{development,structure}.md, go.{mod,sum}, cmd/server/main.go, controller/settings, middleware/security, router, templates/settings/{index.html,css}
新增: internal/service/avatar_service.go, docs/settings.md
2026-05-27 01:03:16 +08:00

467 lines
18 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{{template "layout/header.html" .}}
<body>
{{template "layout/nav.html" .}}
<div class="settings-toast" id="settingsToast"></div>
<div class="settings-layout">
<aside class="settings-sidebar">
<nav class="settings-nav">
<a href="/settings/profile"
class="settings-nav-item {{if eq .ActiveTab "profile"}}active{{end}}">
<svg class="settings-nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 4-7 8-7s8 3 8 7"/>
</svg>
个人资料
</a>
<a href="/settings/account"
class="settings-nav-item {{if eq .ActiveTab "account"}}active{{end}}">
<svg class="settings-nav-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
<circle cx="12" cy="16" r="1"/>
</svg>
账号信息
</a>
</nav>
</aside>
<main class="settings-main">
{{if eq .ActiveTab "profile"}}
<!-- 个人资料 -->
<div class="settings-card">
<div class="settings-card-header">
<h2>个人资料</h2>
<p class="settings-card-desc">你的公开信息和基本资料</p>
</div>
<div class="settings-card-body">
<div class="info-row">
<span class="info-label">用户名</span>
<span class="info-value">
<input type="text" id="usernameInput" class="settings-text-input" value="{{.User.Username}}" maxlength="16" autocomplete="off">
<span class="char-counter" id="usernameCounter"></span>
</span>
</div>
<div class="info-row">
<span class="info-label">头像</span>
<span class="info-value">
<div class="avatar-upload-wrap" id="avatarWrap">
{{if .User.Avatar}}
<img src="{{.User.Avatar}}?v={{.User.UpdatedAt.Unix}}" alt="avatar" class="avatar-preview" id="avatarPreview">
{{else}}
<div class="avatar-placeholder" id="avatarPreview">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="24" height="24"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 4-7 8-7s8 3 8 7"/></svg>
</div>
{{end}}
<span class="avatar-hint">点击更换</span>
</div>
<input type="file" id="avatarInput" class="avatar-input-hidden" accept="image/jpeg,image/png,image/webp">
</span>
</div>
<div class="info-row">
<span class="info-label">个性签名</span>
<span class="info-value">
<textarea id="bioInput" class="settings-textarea" maxlength="128" placeholder="写一句话介绍自己...">{{.User.Bio}}</textarea>
<div class="char-counter" id="bioCounter"></div>
</span>
</div>
<div class="info-row">
<span class="info-label">角色</span>
<span class="info-value">
<span class="role-tag role-{{.User.Role}}">{{.RoleName}}</span>
</span>
</div>
<div class="settings-card-footer">
<button id="saveProfileBtn" class="settings-save-btn">保存</button>
</div>
</div>
</div>
{{else}}
<!-- 账号信息 -->
<div class="settings-card">
<div class="settings-card-header">
<h2>账号信息</h2>
<p class="settings-card-desc">账号安全和基本状态</p>
</div>
<div class="settings-card-body">
<div class="info-row">
<span class="info-label">用户 ID</span>
<span class="info-value">{{.User.ID}}</span>
</div>
<div class="info-row">
<span class="info-label">邮箱</span>
<span class="info-value">{{.User.Email}}</span>
</div>
<div class="info-row">
<span class="info-label">账号状态</span>
<span class="info-value">
<span class="status-badge status-{{.User.Status}}">{{.StatusName}}</span>
</span>
</div>
<div class="info-row">
<span class="info-label">注册时间</span>
<span class="info-value">{{.User.CreatedAt.Format "2006-01-02 15:04:05"}}</span>
</div>
<div class="info-row">
<span class="info-label">最后更新</span>
<span class="info-value">{{.User.UpdatedAt.Format "2006-01-02 15:04:05"}}</span>
</div>
</div>
</div>
{{end}}
</main>
</div>
{{template "layout/footer.html" .}}
<!-- 头像裁切弹窗 -->
<div class="crop-overlay" id="cropOverlay">
<div class="crop-dialog">
<div class="crop-header">调整裁切范围</div>
<div class="crop-stage" id="cropStage">
<img id="cropImageEl" draggable="false">
<div class="crop-mask" id="cropMask"></div>
<div class="crop-frame" id="cropFrame">
<div class="crop-grid"></div>
</div>
</div>
<div class="crop-footer">
<button class="crop-btn crop-btn-cancel" id="cropCancelBtn">取消</button>
<button class="crop-btn crop-btn-confirm" id="cropConfirmBtn">确认</button>
</div>
</div>
</div>
<script src="/static/js/common.js"></script>
<script>
(function () {
'use strict';
var usernameInput = document.getElementById('usernameInput');
var bioInput = document.getElementById('bioInput');
var btn = document.getElementById('saveProfileBtn');
if (!usernameInput || !bioInput || !btn) return;
var toastEl = document.getElementById('settingsToast');
var toastTimer = null;
function showSettingsToast(msg, isError) {
if (!toastEl) return;
clearTimeout(toastTimer);
toastEl.textContent = msg;
toastEl.className = 'settings-toast' + (isError ? ' error' : '');
void toastEl.offsetWidth;
toastEl.classList.add('show');
toastTimer = setTimeout(function () {
toastEl.classList.remove('show');
}, 5000);
}
// ---- 字符计数器 ----
var usernameCounter = document.getElementById('usernameCounter');
var bioCounterEl = document.getElementById('bioCounter');
function updateCounters() {
if (usernameCounter) {
usernameCounter.textContent = usernameInput.value.length + '/16';
}
if (bioCounterEl) {
bioCounterEl.textContent = bioInput.value.length + '/128';
}
}
usernameInput.addEventListener('input', updateCounters);
bioInput.addEventListener('input', updateCounters);
updateCounters();
// ---- 原始值(用于判断是否变更) ----
var origUsername = usernameInput.value.trim();
var origBio = bioInput.value;
// 与后端一致的合法字符集:中文、英文大小写、数字、下划线、连字符
var usernameRe = /^[\u4e00-\u9fffa-zA-Z0-9_-]+$/;
btn.addEventListener('click', function () {
var username = usernameInput.value.trim();
var bio = bioInput.value;
// 用户名校验
if (!username) {
showSettingsToast('用户名不能为空', true);
return;
}
if (username.length > 16) {
showSettingsToast('用户名不能超过 16 个字符', true);
return;
}
if (!usernameRe.test(username)) {
showSettingsToast('用户名仅支持中英文、数字、下划线、连字符', true);
return;
}
// 个性签名校验
if (bio.length > 128) {
showSettingsToast('个性签名不能超过 128 个字符', true);
return;
}
// 无变更判断
if (username === origUsername && bio === origBio) {
showSettingsToast('内容未变更,无需保存');
return;
}
btn.disabled = true;
btn.textContent = '保存中...';
var xhr = new XMLHttpRequest();
xhr.open('PUT', '/api/settings/profile', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
btn.disabled = false;
btn.textContent = '保存';
try {
var res = JSON.parse(xhr.responseText);
if (res.success) {
showSettingsToast(res.message || '个人资料已更新');
origUsername = username;
origBio = bio;
} else {
showSettingsToast(res.message || '保存失败', true);
}
} catch (e) {
showSettingsToast('保存失败', true);
}
};
xhr.send(JSON.stringify({ username: username, bio: bio }));
});
// ---- 头像裁切上传 ----
var avatarWrap = document.getElementById('avatarWrap');
var avatarInput = document.getElementById('avatarInput');
var avatarPreview = document.getElementById('avatarPreview');
var cropOverlay = document.getElementById('cropOverlay');
var cropStage = document.getElementById('cropStage');
var cropImageEl = document.getElementById('cropImageEl');
var cropFrame = document.getElementById('cropFrame');
var cropMask = document.getElementById('cropMask');
var cropCancelBtn = document.getElementById('cropCancelBtn');
var cropConfirmBtn = document.getElementById('cropConfirmBtn');
var pendingFile = null;
var imgNW, imgNH; // 原图像素尺寸
var imgDW, imgDH; // 图片缩放后显示尺寸zoom=1 基准)
var zoom = 1; // 图片缩放系数 1.0 ~ 3.0
var panX = 0, panY = 0; // 图片平移偏移量
var fSize, fLeft, fTop; // 裁切框的固定屏幕像素:边长、左、顶
// 更新裁切框固定参数(图片加载时计算一次,之后不变)
function initFrame() {
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
fSize = Math.min(imgDW, imgDH); // 短边长度填满可见区域
fLeft = Math.round((sw - fSize) / 2);
fTop = Math.round((sh - fSize) / 2);
}
// 约束 panX/panY确保裁切框始终在图片范围内
function clampPan() {
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
var iw = imgDW * zoom, ih = imgDH * zoom;
var cx = Math.round((sw - iw) / 2); // 图片居中时的基准偏移
var cy = Math.round((sh - ih) / 2);
// 图片左边界必须在框左边之左cx + panX <= fLeft → panX <= fLeft - cx
// 图片右边界必须在框右边之右cx + panX + iw >= fLeft + fSize → panX >= fLeft + fSize - cx - iw
panX = Math.max(fLeft + fSize - cx - iw, Math.min(panX, fLeft - cx));
panY = Math.max(fTop + fSize - cy - ih, Math.min(panY, fTop - cy));
}
function renderCrop() {
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
var iw = imgDW * zoom, ih = imgDH * zoom;
var ox = Math.round((sw - iw) / 2) + panX;
var oy = Math.round((sh - ih) / 2) + panY;
cropImageEl.style.width = iw + 'px';
cropImageEl.style.height = ih + 'px';
cropImageEl.style.left = ox + 'px';
cropImageEl.style.top = oy + 'px';
// 裁切框固定不变
cropFrame.style.left = fLeft + 'px';
cropFrame.style.top = fTop + 'px';
cropFrame.style.width = fSize + 'px';
cropFrame.style.height = fSize + 'px';
cropMask.style.left = fLeft + 'px';
cropMask.style.top = fTop + 'px';
cropMask.style.width = fSize + 'px';
cropMask.style.height = fSize + 'px';
}
function openCrop(file) {
var reader = new FileReader();
reader.onload = function (e) {
cropImageEl.src = e.target.result;
cropImageEl.onload = function () {
imgNW = cropImageEl.naturalWidth;
imgNH = cropImageEl.naturalHeight;
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
var fit = Math.min(sw / imgNW, sh / imgNH);
imgDW = Math.round(imgNW * fit);
imgDH = Math.round(imgNH * fit);
zoom = 1;
panX = 0;
panY = 0;
initFrame();
renderCrop();
};
};
reader.readAsDataURL(file);
cropOverlay.classList.add('active');
}
function closeCrop() {
cropOverlay.classList.remove('active');
avatarInput.value = '';
pendingFile = null;
}
// 将裁切框映射回原图像素坐标
function getCropParams() {
var sw = cropStage.clientWidth, sh = cropStage.clientHeight;
var iw = imgDW * zoom, ih = imgDH * zoom;
var ox = Math.round((sw - iw) / 2) + panX;
var oy = Math.round((sh - ih) / 2) + panY;
// 裁切框中心在 zoom=1 图片坐标中的位置
var cx = (fLeft + fSize / 2 - ox) / zoom;
var cy = (fTop + fSize / 2 - oy) / zoom;
var cs = fSize / zoom; // zoom=1 坐标中的裁切边长
var sx = imgNW / imgDW, sy = imgNH / imgDH;
return {
x: Math.round((cx - cs / 2) * sx),
y: Math.round((cy - cs / 2) * sy),
size: Math.round(cs * sx)
};
}
// ---- 图片平移(点击拖拽 stage 任意位置) ----
var panning = false, panStartX = 0, panStartY = 0, panInitX = 0, panInitY = 0;
function startPan(clientX, clientY) {
panning = true;
panStartX = clientX;
panStartY = clientY;
panInitX = panX;
panInitY = panY;
cropStage.style.cursor = 'grabbing';
}
function movePan(clientX, clientY) {
panX = panInitX + (clientX - panStartX);
panY = panInitY + (clientY - panStartY);
clampPan();
renderCrop();
}
cropStage.addEventListener('mousedown', function (e) {
e.preventDefault();
startPan(e.clientX, e.clientY);
});
document.addEventListener('mousemove', function (e) {
if (!panning) return;
movePan(e.clientX, e.clientY);
});
document.addEventListener('mouseup', function () {
panning = false;
cropStage.style.cursor = 'grab';
});
// 触屏平移
cropStage.addEventListener('touchstart', function (e) {
e.preventDefault();
var t = e.touches[0];
startPan(t.clientX, t.clientY);
});
document.addEventListener('touchmove', function (e) {
if (!panning) return;
var t = e.touches[0];
movePan(t.clientX, t.clientY);
}, { passive: true });
document.addEventListener('touchend', function () {
panning = false;
cropStage.style.cursor = 'grab';
});
// ---- 滚轮缩放 ----
cropStage.addEventListener('wheel', function (e) {
e.preventDefault();
if (panning) return;
var newZoom = Math.max(1, Math.min(zoom * (e.deltaY < 0 ? 1.1 : 1 / 1.1), 3));
if (newZoom === zoom) return;
zoom = newZoom;
clampPan();
renderCrop();
}, { passive: false });
cropCancelBtn.addEventListener('click', closeCrop);
cropOverlay.addEventListener('click', function (e) {
if (e.target === cropOverlay) closeCrop();
});
cropConfirmBtn.addEventListener('click', function () {
if (!pendingFile) return;
var params = getCropParams();
var formData = new FormData();
formData.append('avatar', pendingFile);
formData.append('crop_x', params.x);
formData.append('crop_y', params.y);
formData.append('crop_size', params.size);
cropConfirmBtn.disabled = true;
cropConfirmBtn.textContent = '处理中...';
showSettingsToast('上传中...');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/settings/avatar', true);
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
cropConfirmBtn.disabled = false;
cropConfirmBtn.textContent = '确认';
closeCrop();
try {
var res = JSON.parse(xhr.responseText);
if (res.success) {
showSettingsToast('头像已更新');
if (avatarPreview.tagName === 'IMG') {
avatarPreview.src = res.data.url + '?t=' + Date.now();
}
} else {
showSettingsToast(res.message || '上传失败', true);
}
} catch (err) {
showSettingsToast('上传失败', true);
}
};
xhr.send(formData);
});
if (avatarWrap && avatarInput) {
avatarWrap.addEventListener('click', function () {
avatarInput.click();
});
avatarInput.addEventListener('change', function () {
var file = avatarInput.files[0];
if (!file) return;
pendingFile = file;
openCrop(file);
});
}
})();
</script>
</body>
</html>