新增 build:test 方便构建线上的测试环境,优化分享码功能的交互

This commit is contained in:
eafonyang
2026-06-17 16:51:43 +08:00
parent a045db235a
commit 0d577f939c
12 changed files with 216 additions and 21 deletions
+1
View File
@@ -19,6 +19,7 @@ build/
# IDE and editor files
.vscode/
.idea/
.qoder/
*.swp
*.swo
*~
+47 -4
View File
@@ -407,7 +407,7 @@ export function readBootSoundFromState(state: DeviceState | null | undefined): n
// Mock data for demo/offline mode
// ============================================================
export const MOCK_DEVICE_STATE: DeviceState = {
device: "Luxsin-X9",
device: "Luxsin-X8",
version: "1.2.3",
mac: "AA:BB:CC:DD:EE:FF",
language: 0,
@@ -629,6 +629,26 @@ export async function fetchLuxsinAudioCurve(
// Share Code API — shareCreate / shareList / shareQuery / shareAccept
// ============================================================
const SHARE_DEVICE_MODELS = ["Luxsin-X9", "Luxsin-X8"] as const;
export type ShareDeviceModel = (typeof SHARE_DEVICE_MODELS)[number];
/** Map DeviceState.device to app-api share code model enum. */
export function resolveShareDeviceModel(device: string): ShareDeviceModel | null {
const trimmed = device.trim();
if ((SHARE_DEVICE_MODELS as readonly string[]).includes(trimmed)) {
return trimmed as ShareDeviceModel;
}
const hyphenated = trimmed.replace(/\s+/g, "-");
if ((SHARE_DEVICE_MODELS as readonly string[]).includes(hyphenated)) {
return hyphenated as ShareDeviceModel;
}
const lower = trimmed.toLowerCase();
if (lower.includes("x9")) return "Luxsin-X9";
if (lower.includes("x8")) return "Luxsin-X8";
return null;
}
export interface ShareCodeCreateResponse {
code: number;
msg: string;
@@ -653,6 +673,7 @@ export interface ShareCodeAcceptResponse {
code: number;
msg: string;
eq_data?: Record<string, unknown>;
model?: string;
}
export interface ShareCodeQueryResponse {
@@ -660,6 +681,7 @@ export interface ShareCodeQueryResponse {
msg: string;
eq_data?: Record<string, unknown>;
expire_at?: string;
model?: string;
}
/** Unwrap stringified PEQ filters (remove JSON escape layers) for API submit. */
@@ -683,6 +705,7 @@ export function normalizePeqFiltersForSubmit(filters: unknown): PeqFilter[] {
/** POST `/audio/shareCreate` — 创建 EQ 分享码,返回 share_code + expire_at + eq_data */
export async function createShareCode(
mac: string,
model: ShareDeviceModel,
eqData: Record<string, unknown>,
): Promise<ShareCodeCreateResponse> {
const payload = {
@@ -694,7 +717,7 @@ export async function createShareCode(
const res = await fetch(buildLuxsinAudioUrl("shareCreate"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mac, eq_data: payload }),
body: JSON.stringify({ mac, model, eq_data: payload }),
});
if (!res.ok) throw new Error(`shareCreate HTTP ${res.status}`);
return (await res.json()) as ShareCodeCreateResponse;
@@ -718,16 +741,36 @@ export async function queryShareCode(shareCode: string): Promise<ShareCodeQueryR
return (await res.json()) as ShareCodeQueryResponse;
}
/** GET `/audio/shareAccept?mac=...&shareCode=...` — 确认导入分享码并记录流水 */
/** GET `/audio/shareAccept?mac=...&model=...&shareCode=...` — 确认导入分享码并记录流水 */
export async function acceptShareCode(
mac: string,
model: ShareDeviceModel,
shareCode: string,
): Promise<ShareCodeAcceptResponse> {
const res = await fetch(
buildLuxsinAudioUrl(
`shareAccept?mac=${encodeURIComponent(mac)}&shareCode=${encodeURIComponent(shareCode)}`,
`shareAccept?mac=${encodeURIComponent(mac)}&model=${encodeURIComponent(model)}&shareCode=${encodeURIComponent(shareCode)}`,
),
);
if (!res.ok) throw new Error(`shareAccept HTTP ${res.status}`);
return (await res.json()) as ShareCodeAcceptResponse;
}
export interface ShareCodeDeleteResponse {
code: number;
msg: string;
}
/** GET `/audio/shareDelete?mac=...&shareCode=...` — 删除分享码 */
export async function deleteShareCode(
mac: string,
shareCode: string,
): Promise<ShareCodeDeleteResponse> {
const res = await fetch(
buildLuxsinAudioUrl(
`shareDelete?mac=${encodeURIComponent(mac)}&shareCode=${encodeURIComponent(shareCode)}`,
),
);
if (!res.ok) throw new Error(`shareDelete HTTP ${res.status}`);
return (await res.json()) as ShareCodeDeleteResponse;
}
+8 -1
View File
@@ -362,6 +362,8 @@
"importQuerying": "Querying…",
"importCodeNotFound": "Share code not found or expired",
"importEqName": "EQ Name",
"importEqNameHint": "You can customize the name",
"importSourceModel": "Source device",
"importButton": "Import",
"importSaving": "Importing…",
"importSuccess": "EQ imported successfully",
@@ -371,7 +373,12 @@
"mySharesEmpty": "No shared EQ yet",
"mySharesCode": "Code",
"mySharesName": "EQ Name",
"mySharesLoadFail": "Failed to load share list"
"mySharesLoadFail": "Failed to load share list",
"mySharesDeleteConfirmTitle": "Delete share code",
"mySharesDeleteConfirmDesc": "Delete share code {{code}}? It will no longer be available for import.",
"mySharesDeleteConfirmOk": "Delete",
"mySharesDeleteSuccess": "Share code deleted",
"mySharesDeleteFail": "Failed to delete share code"
},
"share": "Share EQ"
},
+8 -1
View File
@@ -362,6 +362,8 @@
"importQuerying": "查詢中…",
"importCodeNotFound": "分享碼不存在或已過期",
"importEqName": "EQ 名稱",
"importEqNameHint": "可自訂名稱",
"importSourceModel": "來源設備",
"importButton": "匯入",
"importSaving": "匯入中…",
"importSuccess": "EQ 匯入成功",
@@ -371,7 +373,12 @@
"mySharesEmpty": "暫無分享記錄",
"mySharesCode": "分享碼",
"mySharesName": "EQ 名稱",
"mySharesLoadFail": "載入分享列表失敗"
"mySharesLoadFail": "載入分享列表失敗",
"mySharesDeleteConfirmTitle": "刪除分享碼",
"mySharesDeleteConfirmDesc": "確定刪除分享碼 {{code}}?刪除後將無法再通過該碼匯入。",
"mySharesDeleteConfirmOk": "刪除",
"mySharesDeleteSuccess": "分享碼已刪除",
"mySharesDeleteFail": "刪除分享碼失敗"
},
"share": "分享 EQ"
},
+8 -1
View File
@@ -362,6 +362,8 @@
"importQuerying": "查询中…",
"importCodeNotFound": "分享码不存在或已过期",
"importEqName": "EQ 名称",
"importEqNameHint": "可自定义名称",
"importSourceModel": "来源设备",
"importButton": "导入",
"importSaving": "导入中…",
"importSuccess": "EQ 导入成功",
@@ -371,7 +373,12 @@
"mySharesEmpty": "暂无分享记录",
"mySharesCode": "分享码",
"mySharesName": "EQ 名称",
"mySharesLoadFail": "加载分享列表失败"
"mySharesLoadFail": "加载分享列表失败",
"mySharesDeleteConfirmTitle": "删除分享码",
"mySharesDeleteConfirmDesc": "确定删除分享码 {{code}}?删除后将无法再通过该码导入。",
"mySharesDeleteConfirmOk": "删除",
"mySharesDeleteSuccess": "分享码已删除",
"mySharesDeleteFail": "删除分享码失败"
},
"share": "分享 EQ"
},
+1
View File
@@ -1821,6 +1821,7 @@ export default function EQPage() {
eqUi={eqUi}
peqCardLabels={peqCardLabels}
mac={deviceState?.mac ?? ""}
device={deviceState?.device ?? ""}
isDemoMode={isDemoMode}
onImportEq={handleImportSharedEq}
/>
@@ -1,3 +1,4 @@
import { useRef } from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import {
AlertDialog,
@@ -32,11 +33,16 @@ export function PeqOverwriteConfirmDialog({
onConfirm: () => void;
onCancel: () => void;
}) {
const actionTakenRef = useRef(false);
return (
<AlertDialog
open={open}
onOpenChange={(next) => {
if (!next) onCancel();
if (!next) {
if (!actionTakenRef.current) onCancel();
actionTakenRef.current = false;
}
}}
>
<AlertDialogPortal>
@@ -56,13 +62,18 @@ export function PeqOverwriteConfirmDialog({
<AlertDialogFooter>
<AlertDialogCancel
className="border-white/20 bg-transparent text-white hover:bg-white/10"
onPointerDown={(e) => e.preventDefault()}
onClick={onCancel}
>
{cancelLabel}
</AlertDialogCancel>
<AlertDialogAction
className="bg-[#00FFF6] text-black hover:brightness-95 focus-visible:ring-[#00FFF6]"
onClick={onConfirm}
onPointerDown={(e) => e.preventDefault()}
onClick={() => {
actionTakenRef.current = true;
onConfirm();
}}
>
{confirmLabel}
</AlertDialogAction>
+97 -9
View File
@@ -1,10 +1,12 @@
import { useState } from "react";
import { X, Copy, Loader2 } from "lucide-react";
import { X, Copy, Loader2, Trash2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { acceptShareCode, createShareCode, listShareCodes, queryShareCode } from "@/lib/luxsinApi";
import { acceptShareCode, createShareCode, deleteShareCode, listShareCodes, queryShareCode, resolveShareDeviceModel } from "@/lib/luxsinApi";
import type { PeqEqUi } from "../types";
import { resolveShareApiMessage } from "../shareMessages";
import { eqInterp } from "../eqFormatters";
import { PeqOverwriteConfirmDialog } from "./PeqOverwriteConfirmDialog";
type PeqItem = {
name: string;
@@ -40,6 +42,7 @@ export function ShareDialog({
eqUi,
peqCardLabels,
mac,
device,
isDemoMode,
onImportEq,
}: {
@@ -50,6 +53,7 @@ export function ShareDialog({
eqUi: PeqEqUi;
peqCardLabels: PeqCardLabels;
mac: string;
device: string;
isDemoMode: boolean;
onImportEq: (data: ImportedEqData, shareCode: string) => void | Promise<void>;
}) {
@@ -63,9 +67,34 @@ export function ShareDialog({
const [importPresetName, setImportPresetName] = useState("");
const [queriedShareCode, setQueriedShareCode] = useState("");
const [importedEqData, setImportedEqData] = useState<ImportedEqData | null>(null);
const [importedSourceModel, setImportedSourceModel] = useState<string | null>(null);
const [shareCodeExpireAt, setShareCodeExpireAt] = useState<string | null>(null);
const [mySharesList, setMySharesList] = useState<Array<{ share_code: string; expire_at: string; eq_data: Record<string, unknown> }>>([]);
const [mySharesLoading, setMySharesLoading] = useState(false);
const [deleteConfirmCode, setDeleteConfirmCode] = useState<string | null>(null);
const [deletingShareCode, setDeletingShareCode] = useState<string | null>(null);
const handleDeleteConfirm = () => {
const code = deleteConfirmCode;
if (!code || !mac || deletingShareCode) return;
setDeleteConfirmCode(null);
setDeletingShareCode(code);
void (async () => {
try {
const res = await deleteShareCode(mac, code);
if (res.code !== 200) {
toast.error(resolveShareApiMessage("delete", res, eqUi));
return;
}
setMySharesList((prev) => prev.filter((item) => item.share_code !== code));
toast.success(eqUi.mySharesDeleteSuccess);
} catch {
toast.error(resolveShareApiMessage("delete", { code: 500 }, eqUi));
} finally {
setDeletingShareCode(null);
}
})();
};
const handleImportClick = async () => {
if (importSaving || !importedEqData || !queriedShareCode) return;
@@ -75,7 +104,12 @@ export function ShareDialog({
setImportSaving(true);
try {
if (!isDemoMode && mac) {
const acceptRes = await acceptShareCode(mac, queriedShareCode);
const shareDeviceModel = resolveShareDeviceModel(device);
if (!shareDeviceModel) {
toast.error(eqUi.shareInvalidParams);
return;
}
const acceptRes = await acceptShareCode(mac, shareDeviceModel, queriedShareCode);
if (acceptRes.code !== 200) {
toast.error(resolveShareApiMessage("accept", acceptRes, eqUi));
return;
@@ -108,10 +142,13 @@ export function ShareDialog({
};
return (
<>
<div
className="fixed inset-0 z-[120] flex items-center justify-center bg-black/65 px-4"
onClick={() => {
if (!importSaving) onClose();
onClick={(e) => {
if (e.target !== e.currentTarget) return;
if (importSaving || deleteConfirmCode !== null || deletingShareCode) return;
onClose();
}}
>
<div
@@ -260,7 +297,12 @@ export function ShareDialog({
autoPre: selectedPeq.autoPre ?? 0,
preamp: selectedPeq.preamp ?? 0,
};
const res = await createShareCode(mac, eqData);
const shareDeviceModel = resolveShareDeviceModel(device);
if (!shareDeviceModel) {
toast.error(eqUi.shareInvalidParams);
return;
}
const res = await createShareCode(mac, shareDeviceModel, eqData);
if (res.code !== 200) {
toast.error(resolveShareApiMessage("create", res, eqUi));
return;
@@ -352,6 +394,7 @@ export function ShareDialog({
next[i] = val;
setImportCodeInputs(next);
setImportedEqData(null);
setImportedSourceModel(null);
setImportPresetName("");
setQueriedShareCode("");
// auto-focus next box
@@ -367,6 +410,7 @@ export function ShareDialog({
next[i - 1] = "";
setImportCodeInputs(next);
setImportedEqData(null);
setImportedSourceModel(null);
setImportPresetName("");
setQueriedShareCode("");
const prev = (e.target as HTMLElement).previousElementSibling as HTMLInputElement | null;
@@ -383,6 +427,7 @@ export function ShareDialog({
}
setImportCodeInputs(next);
setImportedEqData(null);
setImportedSourceModel(null);
setImportPresetName("");
setQueriedShareCode("");
// focus last filled or last box
@@ -412,6 +457,7 @@ export function ShareDialog({
const code = importCodeInputs.join("");
setImportQuerying(true);
setImportedEqData(null);
setImportedSourceModel(null);
setImportPresetName("");
setQueriedShareCode("");
try {
@@ -437,6 +483,7 @@ export function ShareDialog({
autoPre: eq.autoPre as number | undefined,
});
setImportPresetName(fetchedName);
setImportedSourceModel(res.model ?? null);
setQueriedShareCode(code);
} catch {
toast.error(resolveShareApiMessage("query", { code: 500 }, eqUi));
@@ -458,8 +505,16 @@ export function ShareDialog({
{/* imported EQ result */}
{importedEqData && (
<div className="mt-4 rounded-[10px] p-3 space-y-3" style={{ background: "rgba(0,255,246,0.06)", border: "1px solid rgba(0,255,246,0.2)" }}>
{importedSourceModel && (
<p className="text-[12px] text-white/60">
{eqUi.importSourceModel}: <span className="text-white/90">{importedSourceModel}</span>
</p>
)}
<div>
<p className="text-[12px] text-white/40 font-medium mb-1.5">{eqUi.importEqName}</p>
<p className="text-[12px] text-white/40 font-medium mb-1.5">
{eqUi.importEqName}
<span className="font-normal text-white/35">{eqUi.importEqNameHint}</span>
</p>
<input
value={importPresetName}
onChange={(e) => setImportPresetName(e.target.value)}
@@ -543,15 +598,33 @@ export function ShareDialog({
</p>
)}
</div>
{/* copy code button */}
{/* copy + delete */}
<button
type="button"
className="shrink-0 w-7 h-7 rounded-[6px] flex items-center justify-center text-[#00FFF6]/70 active:scale-95 transition-transform"
disabled={!!deletingShareCode}
className="shrink-0 w-7 h-7 rounded-[6px] flex items-center justify-center text-[#00FFF6]/70 active:scale-95 transition-transform disabled:opacity-40"
style={{ background: "rgba(0,255,246,0.08)", border: "1px solid rgba(0,255,246,0.15)" }}
onClick={() => void copyToClipboard(item.share_code)}
>
<Copy size={13} />
</button>
<button
type="button"
disabled={!!deletingShareCode || !mac}
className="shrink-0 w-7 h-7 rounded-[6px] flex items-center justify-center text-red-400/80 active:scale-95 transition-transform disabled:opacity-40"
style={{ background: "rgba(239,68,68,0.08)", border: "1px solid rgba(239,68,68,0.2)" }}
title={eqUi.mySharesDeleteConfirmTitle}
onClick={() => {
if (deletingShareCode) return;
setDeleteConfirmCode(item.share_code);
}}
>
{deletingShareCode === item.share_code ? (
<Loader2 size={13} className="animate-spin" />
) : (
<Trash2 size={13} />
)}
</button>
</div>
))}
</div>
@@ -560,5 +633,20 @@ export function ShareDialog({
)}
</div>
</div>
<PeqOverwriteConfirmDialog
open={deleteConfirmCode !== null}
title={eqUi.mySharesDeleteConfirmTitle}
description={
deleteConfirmCode
? eqInterp(eqUi.mySharesDeleteConfirmDesc, { code: deleteConfirmCode })
: ""
}
cancelLabel={eqUi.cancel}
confirmLabel={eqUi.mySharesDeleteConfirmOk}
onConfirm={handleDeleteConfirm}
onCancel={() => setDeleteConfirmCode(null)}
/>
</>
);
}
+14 -1
View File
@@ -1,6 +1,6 @@
import type { PeqEqUi } from "./types";
export type ShareApiAction = "create" | "query" | "accept" | "list";
export type ShareApiAction = "create" | "query" | "accept" | "list" | "delete";
export function resolveShareApiMessage(
action: ShareApiAction,
@@ -13,6 +13,19 @@ export function resolveShareApiMessage(
return eqUi.mySharesLoadFail ?? "Failed to load share list";
}
if (action === "delete") {
if (res.code === 0) {
return eqUi.mySharesDeleteFail ?? "Failed to delete share code";
}
if (res.code === 400) {
return eqUi.shareInvalidParams ?? eqUi.mySharesDeleteFail ?? "Invalid request";
}
if (res.code === 500) {
return eqUi.shareSystemError ?? eqUi.mySharesDeleteFail ?? "System error";
}
return eqUi.mySharesDeleteFail ?? "Failed to delete share code";
}
if (res.code === 0) {
if (action === "create") {
return eqUi.shareActiveExists ?? eqUi.shareCreateFail ?? "Failed to generate share code";
+3
View File
@@ -9,6 +9,9 @@
"build": "pnpm build:legacy && pnpm build:modern",
"build:modern": "vite build",
"build:legacy": "vite build --config vite.legacy.config.ts",
"build:test": "pnpm build:test:legacy && pnpm build:test:modern",
"build:test:modern": "DEPLOY_ENV=test vite build",
"build:test:legacy": "DEPLOY_ENV=test vite build --config vite.legacy.config.ts",
"start": "NODE_ENV=production tsx server/index.ts",
"preview": "vite preview --host",
"check": "tsc --noEmit",
+8 -1
View File
@@ -49,9 +49,16 @@ const plugins = [
vitePluginCopyRouterEntry(),
];
/* ── Deploy base path ── */
const DEPLOY_ENV = process.env.DEPLOY_ENV || "production";
const isProd = process.env.NODE_ENV === "production";
const deployBase = isProd
? (DEPLOY_ENV === "test" ? "/x8/test/modern/" : "/x8/v2/modern/")
: "/";
export default defineConfig({
plugins,
base: process.env.NODE_ENV === "production" ? "/x8/v2/modern/" : "/",
base: deployBase,
resolve: {
alias: {
"@": path.resolve(import.meta.dirname, "client", "src"),
+8 -1
View File
@@ -43,12 +43,19 @@ function legacySkipModernCssPlugin(): Plugin {
};
}
/* ── Deploy base path ── */
const DEPLOY_ENV = process.env.DEPLOY_ENV || "production";
const isProd = process.env.NODE_ENV === "production";
const deployBase = isProd
? (DEPLOY_ENV === "test" ? "/x8/test/legacy/" : "/x8/v2/legacy/")
: "/";
export default defineConfig({
plugins: [legacySkipModernCssPlugin(), legacyIndexRewritePlugin(), react(), jsxLocPlugin()],
define: {
"import.meta.env.VITE_X8_LEGACY": JSON.stringify("1"),
},
base: process.env.NODE_ENV === "production" ? "/x8/v2/legacy/" : "/",
base: deployBase,
resolve: {
alias: {
"@": path.resolve(PROJECT_ROOT, "client", "src"),