Commit 345bb304 by Jaxon

style(uniapp-x-tape): 统一代码格式并优化语法一致性

- 调整导入顺序和导出顺序以保持一致性
- 统一使用严格相等运算符(!==/===)替代宽松相等
- 规范对象属性顺序和类型定义结构
- 优化字符串模板和箭头函数语法
- 统一代码缩进和换行格式
- 修复条件表达式括号和三元运算符格式
- 更新文件路径引用和模块声明格式
1 parent dd5feff4
Showing 48 changed files with 2420 additions and 2381 deletions
<script lang="uts"> <script lang="uts">
let firstBackTime = 0; let firstBackTime = 0;
export default { export default {
onLaunch: function () { onLaunch () {
console.log("App Launch"); console.log("App Launch");
}, },
onShow: function () { onShow () {
console.log("App Show"); console.log("App Show");
}, },
onHide: function () { onHide () {
console.log("App Hide"); console.log("App Hide");
}, },
// #ifdef APP-ANDROID // #ifdef APP-ANDROID
onLastPageBackPress: function () { onLastPageBackPress () {
console.log("App LastPageBackPress"); console.log("App LastPageBackPress");
if (firstBackTime == 0) { if (firstBackTime == 0) {
uni.showToast({ uni.showToast({
...@@ -28,7 +28,7 @@ export default { ...@@ -28,7 +28,7 @@ export default {
} }
}, },
// #endif // #endif
onExit: function () { onExit () {
console.log("App Exit"); console.log("App Exit");
} }
}; };
......
...@@ -163,4 +163,4 @@ export const signSecretKey: SignSecretKeyItem = signSecretKeyMap[currentTarget] ...@@ -163,4 +163,4 @@ export const signSecretKey: SignSecretKeyItem = signSecretKeyMap[currentTarget]
export const pathEnum: UTSJSONObject = PATH_ENUM; export const pathEnum: UTSJSONObject = PATH_ENUM;
export const pathEnumExport: UTSJSONObject = PATH_ENUM; export const pathEnumExport: UTSJSONObject = PATH_ENUM;
// env 仅用于区分当前环境标签,这里直接按 TARGET_INDEX 映射为字符串 // env 仅用于区分当前环境标签,这里直接按 TARGET_INDEX 映射为字符串
export const env: string = TARGET_INDEX == 3 ? "production" : TARGET_INDEX == 1 ? "develop" : "test"; export const env: string = TARGET_INDEX == 3 ? "production" : (TARGET_INDEX == 1 ? "develop" : "test");
import { sign } from "./sign.uts";
import { secretKey, pathEnum, domain, djDomain, merchantDomain, djSecretKey } from "../env.uts";
import { storage } from "../../utils/storage.uts"; import { storage } from "../../utils/storage.uts";
import { djDomain, djSecretKey, domain, merchantDomain, pathEnum, secretKey } from "../env.uts";
import { sign } from "./sign.uts";
type HostType = "scrm" | "dj" | "merchant" | "ip"; type HostType = "dj" | "ip" | "merchant" | "scrm";
const HOST: Record<HostType, string> = { const HOST: Record<HostType, string> = {
scrm: domain, scrm: domain,
...@@ -18,14 +18,6 @@ const HOST: Record<HostType, string> = { ...@@ -18,14 +18,6 @@ const HOST: Record<HostType, string> = {
* - 处理业务 code 及登录态失效跳转 * - 处理业务 code 及登录态失效跳转
*/ */
class Request { class Request {
get(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType): Promise<any> {
return this.request("GET", params, returnAll, hostType);
}
post(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType, timeout?: number): Promise<any> {
return this.request("POST", params, returnAll, hostType, timeout);
}
/** /**
* 业务方法调用封装 * 业务方法调用封装
* @param method ROP 接口方法名 * @param method ROP 接口方法名
...@@ -36,17 +28,115 @@ class Request { ...@@ -36,17 +28,115 @@ class Request {
fetch(method: string, data: UTSJSONObject, returnAll: boolean = true, hostType?: HostType): Promise<any> { fetch(method: string, data: UTSJSONObject, returnAll: boolean = true, hostType?: HostType): Promise<any> {
const payload = {} as UTSJSONObject; const payload = {} as UTSJSONObject;
// method // method
payload["method"] = method; payload.method = method;
// 合并业务参数 // 合并业务参数
const dataKeys = Object.keys(data as any) as string[]; const dataKeys = Object.keys(data as any) as string[];
for (let i = 0; i < dataKeys.length; i++) { for (const key of dataKeys) {
const key = dataKeys[i];
// @ts-ignore // @ts-ignore
payload[key] = (data as UTSJSONObject)[key]; payload[key] = (data as UTSJSONObject)[key];
} }
return this.post(payload, returnAll, hostType); return this.post(payload, returnAll, hostType);
} }
get(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType): Promise<any> {
return this.request("GET", params, returnAll, hostType);
}
post(params: UTSJSONObject, returnAll: boolean = false, hostType?: HostType, timeout?: number): Promise<any> {
return this.request("POST", params, returnAll, hostType, timeout);
}
/**
* 简单的原始 uni.request 封装
*/
uni_request(options: {
data?: UTSJSONObject;
dataType?: string;
header?: UTSJSONObject;
method?: "GET" | "POST";
responseType?: string;
url: string;
}): Promise<any> {
return new Promise((resolve) => {
uni.request({
url: options.url,
data: options.data ?? ({} as UTSJSONObject),
method: options.method ?? "GET",
header: options.header ?? ({} as UTSJSONObject),
dataType: options.dataType ?? "json",
responseType: options.responseType ?? "text",
success: (response) => {
resolve(response.data);
}
});
});
}
/**
* 组装 ROP 请求参数并完成签名
*/
private getData(params: UTSJSONObject, hostType: HostType): UTSJSONObject {
let projectName = (params.projectName ?? "") as string;
if (projectName == "") {
projectName = this.getRopProject(params.method as string);
} else {
// 使用后删除 projectName 字段
delete params.projectName;
}
let appKey = "48e5e13229b82c1b4e6e8c96151f0637";
let secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b";
const projectSecret = secretKey[projectName];
if (projectSecret != null) {
appKey = projectSecret.appKey;
secret = projectSecret.secret;
}
if (hostType == "dj") {
appKey = djSecretKey.appKey;
secret = djSecretKey.secret;
}
const sessionId = storage.get("sessionId") as null | string;
let noSignAttr: string[] = [];
if (params.sessionId == null && sessionId != null && sessionId != "") {
params.sessionId = sessionId;
}
if (params.delSessionId != null) {
delete params.sessionId;
delete params.delSessionId;
}
if (params.noSignAttr != null) {
noSignAttr = params.noSignAttr as string[];
delete params.noSignAttr;
}
params.v = "1.0.0";
params.format = "json";
params.locale = "zh_CN";
params.source = "app";
params.appKey = appKey;
return sign(params, secret, noSignAttr);
}
/**
* 根据 method 解析出 rop 项目名
* @example sso.xxx.xxx => 第三个段作为项目名
*/
private getRopProject(method: string): string {
const parts = method.split(".");
if (parts.length >= 3) {
return parts[2];
}
return "";
}
private request( private request(
requestMethod: "GET" | "POST", requestMethod: "GET" | "POST",
params: UTSJSONObject, params: UTSJSONObject,
...@@ -78,22 +168,22 @@ class Request { ...@@ -78,22 +168,22 @@ class Request {
"Cache-Control": "no-cache" "Cache-Control": "no-cache"
}; };
let projectName = (params["projectName"] ?? "") as string; let projectName = (params.projectName ?? "") as string;
if (projectName == "") { if (projectName == "") {
projectName = this.getRopProject(params["method"] as string); projectName = this.getRopProject(params.method as string);
} }
const path = pathEnum[projectName] ?? ""; const path = pathEnum[projectName] ?? "";
const requestData = this.getData(params, finalHostType); const requestData = this.getData(params, finalHostType);
uni.request({ uni.request({
url: `${HOST[finalHostType]}${path}router?method=${requestData["method"]}`, url: `${HOST[finalHostType]}${path}router?method=${requestData.method}`,
data: requestData, data: requestData,
method: requestMethod, method: requestMethod,
header, header,
dataType: "json", dataType: "json",
responseType: "text", responseType: "text",
timeout: timeout ?? 60000, timeout: timeout ?? 60_000,
success: (response) => { success: (response) => {
const data: any = response.data; const data: any = response.data;
const statusCode = response.statusCode; const statusCode = response.statusCode;
...@@ -110,7 +200,7 @@ class Request { ...@@ -110,7 +200,7 @@ class Request {
return; return;
} }
const code = (data.code ?? "") as string | number; const code = (data.code ?? "") as number | string;
const message = (data.message ?? "") as string; const message = (data.message ?? "") as string;
if (returnAll) { if (returnAll) {
...@@ -142,11 +232,11 @@ class Request { ...@@ -142,11 +232,11 @@ class Request {
fail: (error) => { fail: (error) => {
uni.hideLoading(); uni.hideLoading();
let title = "系统异常"; let title = "系统异常";
if (typeof error == "string") { if (typeof error === "string") {
title = error; title = error;
} else { } else {
// @ts-ignore // @ts-ignore
const errMsg = (error as any).errMsg as string | null; const errMsg = (error as any).errMsg as null | string;
if (errMsg != null && errMsg != "") { if (errMsg != null && errMsg != "") {
title = errMsg; title = errMsg;
} else { } else {
...@@ -154,7 +244,7 @@ class Request { ...@@ -154,7 +244,7 @@ class Request {
} }
} }
console.error(`${params["method"]} 接口异常:`, error); console.error(`${params.method} 接口异常:`, error);
uni.showToast({ uni.showToast({
title, title,
icon: "error" icon: "error"
...@@ -169,97 +259,6 @@ class Request { ...@@ -169,97 +259,6 @@ class Request {
}); });
}); });
} }
/**
* 组装 ROP 请求参数并完成签名
*/
private getData(params: UTSJSONObject, hostType: HostType): UTSJSONObject {
let projectName = (params["projectName"] ?? "") as string;
if (projectName == "") {
projectName = this.getRopProject(params["method"] as string);
} else {
// 使用后删除 projectName 字段
delete params["projectName"];
}
let appKey = "48e5e13229b82c1b4e6e8c96151f0637";
let secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b";
const projectSecret = secretKey[projectName];
if (projectSecret != null) {
appKey = projectSecret.appKey;
secret = projectSecret.secret;
}
if (hostType == "dj") {
appKey = djSecretKey.appKey;
secret = djSecretKey.secret;
}
const sessionId = storage.get("sessionId") as string | null;
let noSignAttr: string[] = [];
if (params["sessionId"] == null && sessionId != null && sessionId != "") {
params["sessionId"] = sessionId;
}
if (params["delSessionId"] != null) {
delete params["sessionId"];
delete params["delSessionId"];
}
if (params["noSignAttr"] != null) {
noSignAttr = params["noSignAttr"] as string[];
delete params["noSignAttr"];
}
params["v"] = "1.0.0";
params["format"] = "json";
params["locale"] = "zh_CN";
params["source"] = "app";
params["appKey"] = appKey;
return sign(params, secret, noSignAttr);
}
/**
* 根据 method 解析出 rop 项目名
* @example sso.xxx.xxx => 第三个段作为项目名
*/
private getRopProject(method: string): string {
const parts = method.split(".");
if (parts.length >= 3) {
return parts[2];
}
return "";
}
/**
* 简单的原始 uni.request 封装
*/
uni_request(options: {
url: string;
method?: "GET" | "POST";
data?: UTSJSONObject;
header?: UTSJSONObject;
dataType?: string;
responseType?: string;
}): Promise<any> {
return new Promise((resolve) => {
uni.request({
url: options.url,
data: options.data ?? ({} as UTSJSONObject),
method: options.method ?? "GET",
header: options.header ?? ({} as UTSJSONObject),
dataType: options.dataType ?? "json",
responseType: options.responseType ?? "text",
success: (response) => {
resolve(response.data);
}
});
});
}
} }
export const request = new Request(); export const request = new Request();
......
...@@ -9,19 +9,19 @@ function encodeUTF8(s: string): number[] { ...@@ -9,19 +9,19 @@ function encodeUTF8(s: string): number[] {
const c = s.charCodeAt(i); const c = s.charCodeAt(i);
if (c < 0x80) { if (c < 0x80) {
r.push(c); r.push(c);
} else if (c < 0x800) { } else if (c < 0x8_00) {
r.push(0xc0 + ((c >> 6) & 0x1f), 0x80 + (c & 0x3f)); r.push(0xC0 + ((c >> 6) & 0x1F), 0x80 + (c & 0x3F));
} else { } else {
const x = c ^ 0xd800; const x = c ^ 0xD8_00;
if (x >> 10 == 0) { if (x >> 10 == 0) {
const next = s.charCodeAt(i + 1) ^ 0xdc00; const next = s.charCodeAt(i + 1) ^ 0xDC_00;
const code = (x << 10) + next + 0x10000; const code = (x << 10) + next + 0x1_00_00;
r.push(0xf0 + ((code >> 18) & 0x7), 0x80 + ((code >> 12) & 0x3f)); r.push(0xF0 + ((code >> 18) & 0x7), 0x80 + ((code >> 12) & 0x3F));
i++; i++;
} else { } else {
r.push(0xe0 + (c >> 12)); r.push(0xE0 + (c >> 12));
} }
r.push(0x80 + ((c >> 6) & 0x3f), 0x80 + (c & 0x3f)); r.push(0x80 + ((c >> 6) & 0x3F), 0x80 + (c & 0x3F));
} }
i++; i++;
} }
...@@ -45,12 +45,12 @@ export function sha1(s: string): string { ...@@ -45,12 +45,12 @@ export function sha1(s: string): string {
s32[l - 1] = data.length << 3; s32[l - 1] = data.length << 3;
const w: number[] = []; const w: number[] = [];
const k = [1518500249, 1859775393, -1894007588, -899497514]; const k = [1_518_500_249, 1_859_775_393, -1_894_007_588, -899_497_514];
let m0 = 1732584193; let m0 = 1_732_584_193;
let m1 = -271733879; let m1 = -271_733_879;
let m2 = ~1732584193; let m2 = ~1_732_584_193;
let m3 = ~(-271733879); let m3 = ~(-271_733_879);
let m4 = -1009589776; let m4 = -1_009_589_776;
const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c)); const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c));
const f0 = (): number => (m1 & m2) | (~m1 & m3); const f0 = (): number => (m1 & m2) | (~m1 & m3);
......
import { get, keys, set } from "../../utils/common.uts";
import { sha1 } from "./sha1.uts"; import { sha1 } from "./sha1.uts";
import { keys, get, set } from "../../utils/common.uts";
/** /**
* 参数签名方法(从 gl_tape/api/request/sign.js 迁移) * 参数签名方法(从 gl_tape/api/request/sign.js 迁移)
...@@ -18,8 +18,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] ...@@ -18,8 +18,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
// 先将入参拷贝到 realObj 中,并清理 sign 字段 // 先将入参拷贝到 realObj 中,并清理 sign 字段
const rawKeys = keys(params); const rawKeys = keys(params);
for (let i = 0; i < rawKeys.length; i++) { for (const key of rawKeys) {
const key = rawKeys[i];
if (key == "sign") { if (key == "sign") {
continue; continue;
} }
...@@ -32,13 +31,12 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] ...@@ -32,13 +31,12 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
sortedKeys.sort((a, b) => a.localeCompare(b)); sortedKeys.sort((a, b) => a.localeCompare(b));
// 归一化 value:null -> "",对象 -> JSON 字符串 // 归一化 value:null -> "",对象 -> JSON 字符串
for (let i = 0; i < sortedKeys.length; i++) { for (const key of sortedKeys) {
const key = sortedKeys[i];
let obj: any | null = get(realObj, key); let obj: any | null = get(realObj, key);
if (obj == null) { if (obj == null) {
obj = ""; obj = "";
} else if (typeof obj == "object") { } else if (typeof obj === "object") {
obj = JSON.stringify(obj); obj = JSON.stringify(obj);
} }
...@@ -47,8 +45,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] ...@@ -47,8 +45,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
// 组装待签名字符串(排除 noSignAttr 指定的字段) // 组装待签名字符串(排除 noSignAttr 指定的字段)
const segments: string[] = []; const segments: string[] = [];
for (let i = 0; i < sortedKeys.length; i++) { for (const key of sortedKeys) {
const key = sortedKeys[i];
if (noSignAttr.indexOf(key) >= 0) { if (noSignAttr.indexOf(key) >= 0) {
continue; continue;
} }
......
import { evaluationDomain, pathEnum, signSecretKey } from "../env.uts";
import { storage } from "../../utils/storage.uts"; import { storage } from "../../utils/storage.uts";
import { evaluationDomain, pathEnum, signSecretKey } from "../env.uts";
type GscPostConfig = { type GscPostConfig = {
duplicatePrevention?: boolean;
returnAll?: boolean; returnAll?: boolean;
timeout?: number; timeout?: number;
duplicatePrevention?: boolean;
}; };
/** /**
...@@ -35,30 +35,29 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig ...@@ -35,30 +35,29 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig
return; return;
} }
const baseURL = `${evaluationDomain}${pathEnum["evaluation"]}`; const baseURL = `${evaluationDomain}${pathEnum.evaluation}`;
const fullUrl = `${baseURL}${url}`; const fullUrl = `${baseURL}${url}`;
// 组装请求体,自动注入 sessionId // 组装请求体,自动注入 sessionId
const payload = {} as UTSJSONObject; const payload = {} as UTSJSONObject;
const dataKeys = Object.keys(data as any) as string[]; const dataKeys = Object.keys(data as any) as string[];
for (let i = 0; i < dataKeys.length; i++) { for (const key of dataKeys) {
const key = dataKeys[i];
// @ts-ignore // @ts-ignore
payload[key] = (data as UTSJSONObject)[key]; payload[key] = (data as UTSJSONObject)[key];
} }
// sessionId 自动注入 // sessionId 自动注入
const sessionId = storage.get("sessionId") as string | null; const sessionId = storage.get("sessionId") as null | string;
if (sessionId != null && sessionId != "" && payload["sessionId"] == null) { if (sessionId != null && sessionId != "" && payload.sessionId == null) {
payload["sessionId"] = sessionId; payload.sessionId = sessionId;
} }
// 简单的重复提交防护:可选地附加一次性请求标识(仅客户端语义) // 简单的重复提交防护:可选地附加一次性请求标识(仅客户端语义)
if (finalConfig.duplicatePrevention == true) { if (finalConfig.duplicatePrevention == true) {
payload["__duplicateKey"] = `${Date.now()}_${Math.random()}`; payload.__duplicateKey = `${Date.now()}_${Math.random()}`;
} }
const timeout = finalConfig.timeout ?? 300000; const timeout = finalConfig.timeout ?? 300_000;
// 将 appId / appSecret 通过 header 传递给后端(近似旧项目 glsk-toolkit 行为) // 将 appId / appSecret 通过 header 传递给后端(近似旧项目 glsk-toolkit 行为)
const header = { const header = {
...@@ -114,7 +113,7 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig ...@@ -114,7 +113,7 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig
fail: (error) => { fail: (error) => {
let title = "业务异常"; let title = "业务异常";
// @ts-ignore // @ts-ignore
const errMsg = (error as any).errMsg as string | null; const errMsg = (error as any).errMsg as null | string;
if (errMsg == "request:fail") { if (errMsg == "request:fail") {
title = "网络异常"; title = "网络异常";
} else if (errMsg != null && errMsg != "") { } else if (errMsg != null && errMsg != "") {
......
// 登录相关接口封装,对齐 gl_tape 中的 ROP 网关调用(http.fetch) // 登录相关接口封装,对齐 gl_tape 中的 ROP 网关调用(http.fetch)
import { djDomain, djSecretKey, pathEnum } from '@/api/env.uts' import { djDomain, djSecretKey, pathEnum } from "@/api/env.uts";
import { storage } from '@/utils/storage.uts' import { storage } from "@/utils/storage.uts";
const BOUTIQUE_PATH = pathEnum['boutique'] as string const BOUTIQUE_PATH = pathEnum.boutique as string;
// 简化版 SHA1,实现同 lib/sha1.js,用于生成 sign // 简化版 SHA1,实现同 lib/sha1.js,用于生成 sign
function encodeUTF8(input: string): number[] { function encodeUTF8(input: string): number[] {
const result: number[] = [] const result: number[] = [];
let i = 0 let i = 0;
while (i < input.length) { while (i < input.length) {
const cNum = input.charCodeAt(i) as number const cNum = input.charCodeAt(i) as number;
if (cNum < 0x80) { if (cNum < 0x80) {
result.push(cNum) result.push(cNum);
} else if (cNum < 0x800) { } else if (cNum < 0x8_00) {
result.push(0xc0 + ((cNum >> 6) & 0x1f), 0x80 + (cNum & 0x3f)) result.push(0xC0 + ((cNum >> 6) & 0x1F), 0x80 + (cNum & 0x3F));
} else { } else {
let x = cNum ^ 0xd800 const x = cNum ^ 0xD8_00;
if (x >> 10 == 0) { if (x >> 10 == 0) {
i++ i++;
const c2 = input.charCodeAt(i) as number const c2 = input.charCodeAt(i) as number;
const uni = (x << 10) + (c2 ^ 0xdc00) + 0x10000 const uni = (x << 10) + (c2 ^ 0xDC_00) + 0x1_00_00;
result.push( result.push(
0xf0 + ((uni >> 18) & 0x7), 0xF0 + ((uni >> 18) & 0x7),
0x80 + ((uni >> 12) & 0x3f), 0x80 + ((uni >> 12) & 0x3F),
0x80 + ((uni >> 6) & 0x3f), 0x80 + ((uni >> 6) & 0x3F),
0x80 + (uni & 0x3f) 0x80 + (uni & 0x3F)
) );
} else { } else {
result.push( result.push(
0xe0 + ((cNum >> 12) & 0x0f), 0xE0 + ((cNum >> 12) & 0x0F),
0x80 + ((cNum >> 6) & 0x3f), 0x80 + ((cNum >> 6) & 0x3F),
0x80 + (cNum & 0x3f) 0x80 + (cNum & 0x3F)
) );
} }
} }
i++ i++;
} }
return result return result;
} }
function sha1Hex(input: string): string { function sha1Hex(input: string): string {
const dataArr = encodeUTF8(input) const dataArr = encodeUTF8(input);
const data = new Uint8Array(dataArr) const data = new Uint8Array(dataArr);
const l = (((data.length + 8) >>> 6) << 4) + 16 const l = (((data.length + 8) >>> 6) << 4) + 16;
const buffer = new Uint8Array(l << 2) const buffer = new Uint8Array(l << 2);
const dataBuf: ArrayBuffer = data.buffer as ArrayBuffer const dataBuf: ArrayBuffer = data.buffer as ArrayBuffer;
buffer.set(new Uint8Array(dataBuf)) buffer.set(new Uint8Array(dataBuf));
const buf: ArrayBuffer = buffer.buffer as ArrayBuffer const buf: ArrayBuffer = buffer.buffer as ArrayBuffer;
const s = new Uint32Array(buf) const s = new Uint32Array(buf);
const sBuf: ArrayBuffer = s.buffer as ArrayBuffer const sBuf: ArrayBuffer = s.buffer as ArrayBuffer;
const dv = new DataView(sBuf) const dv = new DataView(sBuf);
let i = 0 let i = 0;
while (i < l) { while (i < l) {
s[i] = dv.getUint32(i << 2) s[i] = dv.getUint32(i << 2);
i++ i++;
} }
const idx = data.length >> 2 const idx = data.length >> 2;
s[idx] = s[idx] | (0x80 << (24 - ((data.length & 3) * 8))) s[idx] = s[idx] | (0x80 << (24 - ((data.length & 3) * 8)));
s[l - 1] = data.length << 3 s[l - 1] = data.length << 3;
const w: number[] = [] const w: number[] = [];
const f = [ const f = [
(m: number[]): number => (m[1] & m[2]) | (~m[1] & m[3]), (m: number[]): number => (m[1] & m[2]) | (~m[1] & m[3]),
(m: number[]): number => m[1] ^ m[2] ^ m[3], (m: number[]): number => m[1] ^ m[2] ^ m[3],
(m: number[]): number => (m[1] & m[2]) | (m[1] & m[3]) | (m[2] & m[3]), (m: number[]): number => (m[1] & m[2]) | (m[1] & m[3]) | (m[2] & m[3]),
(m: number[]): number => m[1] ^ m[2] ^ m[3] (m: number[]): number => m[1] ^ m[2] ^ m[3]
] ];
const k = [1518500249, 1859775393, -1894007588, -899497514] const k = [1_518_500_249, 1_859_775_393, -1_894_007_588, -899_497_514];
const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c)) const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c));
const m: number[] = [1732584193, -271733879, 0, 0, -1009589776] const m: number[] = [1_732_584_193, -271_733_879, 0, 0, -1_009_589_776];
m[2] = ~m[0] m[2] = ~m[0];
m[3] = ~m[1] m[3] = ~m[1];
let j = 0 let j = 0;
for (i = 0; i < s.length; i += 16) { for (i = 0; i < s.length; i += 16) {
const o = [m[0], m[1], m[2], m[3], m[4]] const o = [m[0], m[1], m[2], m[3], m[4]];
for (j = 0; j < 80; j++) { for (j = 0; j < 80; j++) {
if (j < 16) { if (j < 16) {
w[j] = s[i + j] w[j] = s[i + j];
} else { } else {
w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1) w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
} }
const t = (rol(m[0], 5) + f[(j / 20) | 0](m) + m[4] + w[j] + k[(j / 20) | 0]) | 0 const t = (rol(m[0], 5) + f[(j / 20) | 0](m) + m[4] + w[j] + k[(j / 20) | 0]) | 0;
m[4] = m[3] m[4] = m[3];
m[3] = m[2] m[3] = m[2];
m[2] = rol(m[1], 30) m[2] = rol(m[1], 30);
m[1] = m[0] m[1] = m[0];
m[0] = t m[0] = t;
} }
for (j = 0; j < 5; j++) { for (j = 0; j < 5; j++) {
m[j] = (m[j] + o[j]) | 0 m[j] = (m[j] + o[j]) | 0;
} }
} }
const mArr = new Uint32Array(m) const mArr = new Uint32Array(m);
const mBuf: ArrayBuffer = mArr.buffer as ArrayBuffer const mBuf: ArrayBuffer = mArr.buffer as ArrayBuffer;
const out = new Uint8Array(mBuf) const out = new Uint8Array(mBuf);
let hex = '' let hex = "";
for (i = 0; i < out.length; i++) { for (i = 0; i < out.length; i++) {
const v = out[i] const v = out[i];
hex += (v < 16 ? '0' : '') + v.toString(16) hex += (v < 16 ? "0" : "") + v.toString(16);
} }
return hex return hex;
} }
// 按老项目 http.getData + sign.js 逻辑生成最终请求参数 // 按老项目 http.getData + sign.js 逻辑生成最终请求参数
function buildSignedParams(method: string, payload: UTSJSONObject): UTSJSONObject { function buildSignedParams(method: string, payload: UTSJSONObject): UTSJSONObject {
const params: UTSJSONObject = {} const params: UTSJSONObject = {};
// 复制调用参数 // 复制调用参数
for (const key in payload) { for (const key in payload) {
params[key] = payload[key] params[key] = payload[key];
} }
// 基础字段 // 基础字段
params['method'] = method params.method = method;
params['v'] = '1.0.0' params.v = "1.0.0";
params['format'] = 'json' params.format = "json";
params['locale'] = 'zh_CN' params.locale = "zh_CN";
params['source'] = 'app' params.source = "app";
// appKey / secret // appKey / secret
let appKey = djSecretKey['appKey'] as string const appKey = djSecretKey.appKey as string;
let secret = djSecretKey['secret'] as string const secret = djSecretKey.secret as string;
params['appKey'] = appKey params.appKey = appKey;
// sessionId(如果存在) // sessionId(如果存在)
const sessionId = storage.get('sessionId') as string | null const sessionId = storage.get("sessionId") as null | string;
if (sessionId != null && sessionId != '') { if (sessionId != null && sessionId != "") {
params['sessionId'] = sessionId params.sessionId = sessionId;
} }
// sign 计算:按照 key 排序、拼接 key+value // sign 计算:按照 key 排序、拼接 key+value
const realObj: UTSJSONObject = {} const realObj: UTSJSONObject = {};
for (const k in params) { for (const k in params) {
const v = params[k] const v = params[k];
if (v == null) { if (v == null) {
realObj[k] = '' realObj[k] = "";
} else if (typeof v === 'object') { } else if (typeof v === "object") {
realObj[k] = JSON.stringify(v) realObj[k] = JSON.stringify(v);
} else { } else {
realObj[k] = v realObj[k] = v;
} }
} }
const keys: string[] = [] const keys: string[] = [];
for (const k in realObj) { for (const k in realObj) {
keys.push(k) keys.push(k);
} }
keys.sort() keys.sort();
const parts: string[] = [] const parts: string[] = [];
for (let idx = 0; idx < keys.length; idx++) { for (const k of keys) {
const k = keys[idx] const vAny = realObj[k];
const vAny = realObj[k] const vStr = `${vAny}`;
const vStr = `${vAny}` parts.push(k + vStr);
parts.push(k + vStr)
} }
const signStr = secret + parts.join('') + secret const signStr = secret + parts.join("") + secret;
// 目前关闭本地 SHA1 计算,直接透传待签名串,方便后端放宽或调试 // 目前关闭本地 SHA1 计算,直接透传待签名串,方便后端放宽或调试
console.log('rop signStr (sha disabled)', signStr) console.log("rop signStr (sha disabled)", signStr);
params['sign'] = signStr params.sign = signStr;
return params return params;
} }
// 统一 ROP 请求封装:/router?method=xxx // 统一 ROP 请求封装:/router?method=xxx
async function postRop(method: string, payload: UTSJSONObject): Promise<UTSJSONObject> { async function postRop(method: string, payload: UTSJSONObject): Promise<UTSJSONObject> {
const url = `${djDomain}${BOUTIQUE_PATH}router?method=${method}` const url = `${djDomain}${BOUTIQUE_PATH}router?method=${method}`;
const data = buildSignedParams(method, payload) const data = buildSignedParams(method, payload);
console.log('rop request', url, data) console.log("rop request", url, data);
return await new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
uni.request({ uni.request({
url, url,
data, data,
method: 'POST', method: "POST",
header: { header: {
'content-type': 'application/x-www-form-urlencoded' "content-type": "application/x-www-form-urlencoded"
}, },
dataType: 'json', dataType: "json",
success: (res) => { success: (res) => {
console.log('rop response', res.data) console.log("rop response", res.data);
resolve(res.data as UTSJSONObject) resolve(res.data as UTSJSONObject);
}, },
fail: (err) => { fail: (err) => {
console.log('rop error', err) console.log("rop error", err);
reject(err) reject(err);
} }
}) });
}) });
} }
// 获取短信验证码:dj.api.smartcarlife.sms.get.code // 获取短信验证码:dj.api.smartcarlife.sms.get.code
export async function apiGetSmsCode(params: UTSJSONObject): Promise<UTSJSONObject> { export async function apiGetSmsCode(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
...params ...params
} };
return await postRop('dj.api.smartcarlife.sms.get.code', data) return await postRop("dj.api.smartcarlife.sms.get.code", data);
} }
// 手机验证码登录:dj.api.smartcarlife.sms.applogin // 手机验证码登录:dj.api.smartcarlife.sms.applogin
export async function apiSmsLogin(params: UTSJSONObject): Promise<UTSJSONObject> { export async function apiSmsLogin(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
...params ...params
} };
// 与旧项目保持一致的固定参数 // 与旧项目保持一致的固定参数
data['source'] = 'MINIAPP' data.source = "MINIAPP";
data['productCode'] = 'PC00c2' data.productCode = "PC00c2";
return await postRop('dj.api.smartcarlife.sms.applogin', data) return await postRop("dj.api.smartcarlife.sms.applogin", data);
} }
// 免登:dj.api.smartcarlife.sms.noSignIn.login // 免登:dj.api.smartcarlife.sms.noSignIn.login
export async function apiAutoLogin(params: UTSJSONObject): Promise<UTSJSONObject> { export async function apiAutoLogin(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
...params ...params
} };
return await postRop('dj.api.smartcarlife.sms.noSignIn.login', data) return await postRop("dj.api.smartcarlife.sms.noSignIn.login", data);
} }
<template> <template>
<view v-if="isShow" class="publish-popup-mask" @click="closePopup"> <view v-if="isShow"
class="publish-popup-mask"
@click="closePopup">
<view class="publish-popup-container" @click.stop> <view class="publish-popup-container" @click.stop>
<slot name="content"></slot> <slot name="content"></slot>
</view> </view>
...@@ -7,13 +9,13 @@ ...@@ -7,13 +9,13 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ref } from 'vue'; import { ref } from "vue";
// Props // Props
const props = defineProps<{ const props = defineProps<{
type?: string;
isShowFooter?: boolean; isShowFooter?: boolean;
showTitle?: boolean; showTitle?: boolean;
type?: string;
}>(); }>();
// 响应式数据 // 响应式数据
......
<template> <template>
<view class="type-tab"> <view class="type-tab">
<scroll-view class="type-box" scroll-x="true" :show-scrollbar="false" scroll-with-animation> <scroll-view class="type-box"
scroll-with-animation
scroll-x="true"
:show-scrollbar="false">
<view class="type-scroll-content"> <view class="type-scroll-content">
<view <view v-for="(i, index) in typeList"
:key="index"
class="tab-item" class="tab-item"
:class="[tabClass(index)]" :class="[tabClass(index)]"
v-for="(i, index) in typeList" @click.stop="tabClick(index, i)">
:key="index"
@click.stop="tabClick(index, i)"
>
<view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']"> <view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']">
<text class="tab-name">{{ getTabName(i) }}</text> <text class="tab-name">{{ getTabName(i) }}</text>
<text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text> <text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text>
...@@ -20,23 +21,23 @@ ...@@ -20,23 +21,23 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ref, computed } from 'vue';
import { get } from '@/utils/common.uts'; import { get } from "@/utils/common.uts";
// Props 类型:使用 any[] 避免响应式对象类型转换问题 // Props 类型:使用 any[] 避免响应式对象类型转换问题
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
typeList: any[];
tabIndex: number;
nameKey?: string;
isShowCount?: boolean; isShowCount?: boolean;
nameKey?: string;
tabIndex: number;
typeList: any[];
}>(), { }>(), {
nameKey: 'tabName', nameKey: "tabName",
isShowCount: false isShowCount: false
}); });
// Emits // Emits
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'tabClick', index: number, item: any): void; (e: "tabClick", index: number, item: any): void;
}>(); }>();
...@@ -44,7 +45,7 @@ const emit = defineEmits<{ ...@@ -44,7 +45,7 @@ const emit = defineEmits<{
// 响应式对象在 app 端无法通过 get() 访问,使用 JSON 序列化/反序列化解包 // 响应式对象在 app 端无法通过 get() 访问,使用 JSON 序列化/反序列化解包
const getTabName = (item: any): string => { const getTabName = (item: any): string => {
// 先尝试 get() // 先尝试 get()
let name = get(item, props.nameKey); const name = get(item, props.nameKey);
if (name != null) { if (name != null) {
return name as string; return name as string;
} }
...@@ -58,21 +59,21 @@ const getTabName = (item: any): string => { ...@@ -58,21 +59,21 @@ const getTabName = (item: any): string => {
if (name1 != null) { if (name1 != null) {
return name1 as string; return name1 as string;
} }
const name2 = get(parsed, 'tabName'); const name2 = get(parsed, "tabName");
if (name2 != null) { if (name2 != null) {
return name2 as string; return name2 as string;
} }
} }
} catch (e: any) { } catch {
// 静默失败 // 静默失败
} }
return '未知'; return "未知";
}; };
const getTabCount = (item: any): number => { const getTabCount = (item: any): number => {
// 先尝试 get() // 先尝试 get()
let count = get(item, 'count'); const count = get(item, "count");
if (count != null) { if (count != null) {
return count as number; return count as number;
} }
...@@ -82,12 +83,12 @@ const getTabCount = (item: any): number => { ...@@ -82,12 +83,12 @@ const getTabCount = (item: any): number => {
const jsonStr = JSON.stringify(item); const jsonStr = JSON.stringify(item);
const parsed = JSON.parse(jsonStr) as any; const parsed = JSON.parse(jsonStr) as any;
if (parsed != null) { if (parsed != null) {
const countValue = get(parsed, 'count'); const countValue = get(parsed, "count");
if (countValue != null) { if (countValue != null) {
return countValue as number; return countValue as number;
} }
} }
} catch (e: any) { } catch {
// 静默失败 // 静默失败
} }
...@@ -96,17 +97,17 @@ const getTabCount = (item: any): number => { ...@@ -96,17 +97,17 @@ const getTabCount = (item: any): number => {
// 方法 // 方法
const tabClass = (index: number): string => { const tabClass = (index: number): string => {
let className = ''; let className = "";
if (props.tabIndex == index) { if (props.tabIndex == index) {
className = 'active '; className = "active ";
if (index == 0) className += 'first-nav'; if (index == 0) className += "first-nav";
else className += 'second-nav'; else className += "second-nav";
} }
return className; return className;
}; };
const tabClick = (index: number, item: any) => { const tabClick = (index: number, item: any) => {
emit('tabClick', index, item); emit("tabClick", index, item);
}; };
</script> </script>
......
// composables/useTheme.uts // composables/useTheme.uts
// 主题 Composable - 提供响应式主题变量和切换接口 // 主题 Composable - 提供响应式主题变量和切换接口
import { ref, computed, onMounted } from 'vue' import { computed, onMounted, ref } from "vue";
import { getThemeManager, ThemeName, ThemeVariables } from '@/utils/theme-manager.uts'
import { getScreenSize } from '@/utils/screen-adapt.uts' import { getThemeManager, ThemeName, ThemeVariables } from "@/utils/theme-manager.uts";
/** /**
* 主题 Composable * 主题 Composable
* 类似 i18n 的使用方式,提供主题变量和切换接口 * 类似 i18n 的使用方式,提供主题变量和切换接口
*/ */
export function useTheme() { export function useTheme() {
const themeManager = getThemeManager() const themeManager = getThemeManager();
const currentThemeName = ref<ThemeName>(themeManager.getCurrentThemeName()) const currentThemeName = ref<ThemeName>(themeManager.getCurrentThemeName());
const theme = ref<ThemeVariables | null>(themeManager.getCurrentTheme()) const theme = ref<null | ThemeVariables>(themeManager.getCurrentTheme());
/** /**
* 设置主题 * 设置主题
*/ */
function setTheme(themeName: ThemeName): boolean { function setTheme(themeName: ThemeName): boolean {
const success = themeManager.setTheme(themeName) const success = themeManager.setTheme(themeName);
if (success) { if (success) {
currentThemeName.value = themeName currentThemeName.value = themeName;
theme.value = themeManager.getCurrentTheme() theme.value = themeManager.getCurrentTheme();
} }
return success return success;
} }
/** /**
* 自动选择主题(根据屏幕尺寸) * 自动选择主题(根据屏幕尺寸)
*/ */
function autoSelectTheme(): void { function autoSelectTheme(): void {
themeManager.autoSelectTheme() themeManager.autoSelectTheme();
currentThemeName.value = themeManager.getCurrentThemeName() currentThemeName.value = themeManager.getCurrentThemeName();
theme.value = themeManager.getCurrentTheme() theme.value = themeManager.getCurrentTheme();
} }
/** /**
...@@ -40,50 +40,50 @@ export function useTheme() { ...@@ -40,50 +40,50 @@ export function useTheme() {
*/ */
const spacing = computed(() => { const spacing = computed(() => {
return (key: string): number => { return (key: string): number => {
return themeManager.getSpacing(key) return themeManager.getSpacing(key);
} };
}) });
/** /**
* 获取圆角值 * 获取圆角值
*/ */
const borderRadius = computed(() => { const borderRadius = computed(() => {
return (key: string): number => { return (key: string): number => {
return themeManager.getBorderRadius(key) return themeManager.getBorderRadius(key);
} };
}) });
/** /**
* 获取字体大小 * 获取字体大小
*/ */
const fontSize = computed(() => { const fontSize = computed(() => {
return (key: string): number => { return (key: string): number => {
return themeManager.getFontSize(key) return themeManager.getFontSize(key);
} };
}) });
/** /**
* 获取尺寸值 * 获取尺寸值
*/ */
const size = computed(() => { const size = computed(() => {
return (key: string): number => { return (key: string): number => {
return themeManager.getSize(key) return themeManager.getSize(key);
} };
}) });
/** /**
* 获取行高值 * 获取行高值
*/ */
const lineHeight = computed(() => { const lineHeight = computed(() => {
return (key: string): number => { return (key: string): number => {
return themeManager.getLineHeight(key) return themeManager.getLineHeight(key);
} };
}) });
// 初始化时自动选择主题 // 初始化时自动选择主题
onMounted(() => { onMounted(() => {
autoSelectTheme() autoSelectTheme();
}) });
return { return {
// 当前主题名称 // 当前主题名称
...@@ -104,5 +104,5 @@ export function useTheme() { ...@@ -104,5 +104,5 @@ export function useTheme() {
size, size,
// 获取行高值 // 获取行高值
lineHeight lineHeight
} };
} }
// composables/useThemeVariables.uts // composables/useThemeVariables.uts
// CSS 变量主题 Composable // CSS 变量主题 Composable
import { ref, computed, onMounted } from 'vue' import { computed, onMounted, ref } from "vue";
import { getThemeVariablesStyle } from '@/utils/theme-variables.uts'
import { useTheme } from './useTheme.uts' import { getThemeVariablesStyle } from "@/utils/theme-variables.uts";
import { useTheme } from "./useTheme.uts";
/** /**
* CSS 变量主题 Composable * CSS 变量主题 Composable
* 提供响应式的 CSS 变量样式对象 * 提供响应式的 CSS 变量样式对象
*/ */
export function useThemeVariables() { export function useThemeVariables() {
const { currentThemeName, autoSelectTheme } = useTheme() const { currentThemeName, autoSelectTheme } = useTheme();
const themeVars = ref<Record<string, string>>({}) const themeVars = ref<Record<string, string>>({});
/** /**
* 更新 CSS 变量 * 更新 CSS 变量
*/ */
function updateThemeVariables(): void { function updateThemeVariables(): void {
themeVars.value = getThemeVariablesStyle() themeVars.value = getThemeVariablesStyle();
} }
// 初始化时设置 CSS 变量 // 初始化时设置 CSS 变量
onMounted(() => { onMounted(() => {
updateThemeVariables() updateThemeVariables();
}) });
// 监听主题变化,自动更新 CSS 变量 // 监听主题变化,自动更新 CSS 变量
const themeVarsComputed = computed(() => { const themeVarsComputed = computed(() => {
// 当主题名称变化时,重新计算 CSS 变量 // 当主题名称变化时,重新计算 CSS 变量
return getThemeVariablesStyle() return getThemeVariablesStyle();
}) });
return { return {
// CSS 变量样式对象(用于 :style 绑定) // CSS 变量样式对象(用于 :style 绑定)
themeVars: themeVarsComputed, themeVars: themeVarsComputed,
// 手动更新 CSS 变量 // 手动更新 CSS 变量
updateThemeVariables updateThemeVariables
} };
} }
/// <reference types="vite/client" /> // / <reference types="vite/client" />
declare module "*.uvue" {
import { DefineComponent } from "vue";
declare module '*.uvue' {
import { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<{}, {}, any>;
export default component; export default component;
} }
declare module '*.vue' { declare module "*.vue" {
import { DefineComponent } from 'vue'; import { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<{}, {}, any>;
export default component; export default component;
} }
......
import { createSSRApp } from "vue"; import { createSSRApp } from "vue";
import { appMixin } from "./utilsApi";
import App from "./App.uvue"; import App from "./App.uvue";
import { appMixin } from "./utilsApi";
export function createApp() { export function createApp() {
const app = createSSRApp(App); const app = createSSRApp(App);
......
...@@ -6,81 +6,62 @@ ...@@ -6,81 +6,62 @@
<text class="sub-title">手机号码登录</text> <text class="sub-title">手机号码登录</text>
<view class="input"> <view class="input">
<input <input v-model="mobile"
type="tel"
v-model="mobile"
placeholder="请输入手机号"
maxlength="11"
auto-blur auto-blur
/> maxlength="11"
<view placeholder="请输入手机号"
v-if="mobile != ''" type="tel" />
<view v-if="mobile != ''"
class="icon" class="icon"
@click="clearMobile" @click="clearMobile">
> <icon color="#000"
<icon
type="clear"
size="16" size="16"
color="#000" type="clear">
></icon> </icon>
</view> </view>
</view> </view>
<view class="input"> <view class="input">
<input <input v-model="code"
type="number"
v-model="code"
placeholder="请输入验证码"
maxlength="4"
auto-blur auto-blur
/> maxlength="4"
<view placeholder="请输入验证码"
v-if="code != ''" type="number" />
<view v-if="code != ''"
class="icon" class="icon"
@click="clearCode" @click="clearCode">
> <icon color="#000"
<icon
type="clear"
size="16" size="16"
color="#000" type="clear">
></icon> </icon>
</view> </view>
<view <view class="code-btn"
:class="['code-btn', count > 0 ? 'code-disabled' : '']" :class="[count > 0 ? 'code-disabled' : '']"
@click="getSmsCode" @click="getSmsCode">
>
{{ count > 0 ? `重新发送(${count}s)` : '获取验证码' }} {{ count > 0 ? `重新发送(${count}s)` : '获取验证码' }}
</view> </view>
</view> </view>
<button <button class="btn"
class="btn" @click="login">
@click="login"
>
登录 登录
</button> </button>
<view class="form-footer"> <view class="form-footer">
<view <view class="autoLogin"
class="autoLogin" @click="toggleReadingStatus">
@click="toggleReadingStatus" <radio :checked="readingStatus"
> color="#2C66F7">
<radio </radio>
:checked="readingStatus"
color="#2C66F7"
></radio>
我已阅读并同意 我已阅读并同意
<text @click.stop="openPrivacy">《隐私协议》</text> <text @click.stop="openPrivacy">《隐私协议》</text>
</view> </view>
<view <view class="autoLogin"
class="autoLogin" @click="toggleNoSignIn">
@click="toggleNoSignIn" <radio :checked="noSignIn"
> color="#2C66F7">
<radio </radio>
:checked="noSignIn"
color="#2C66F7"
></radio>
30天内免登录 30天内免登录
</view> </view>
</view> </view>
...@@ -88,292 +69,292 @@ ...@@ -88,292 +69,292 @@
<view class="app-code flex"> <view class="app-code flex">
APP编码:{{ deviceId }} APP编码:{{ deviceId }}
<view <view class="sprite-icon icon-clone"
class="sprite-icon icon-clone" @click="copyDeviceId">
@click="copyDeviceId"
></view>
</view> </view>
</view> </view>
</template> </view>
</template>
<script setup lang="uts">
import { ref, watch } from "vue";
<script setup lang="uts"> import { apiAutoLogin, apiGetSmsCode, apiSmsLogin } from "@/api/user-api.uts";
import { ref, watch } from 'vue' import { storage } from "@/utils/storage.uts";
import { onLoad } from '@dcloudio/uni-app' import { onLoad } from "@dcloudio/uni-app";
import { apiSmsLogin, apiGetSmsCode, apiAutoLogin } from '@/api/user-api.uts'
import { storage } from '@/utils/storage.uts'
// 手机号正则 // 手机号正则
const phoneRex = /^[1]([3-9])[0-9]{9}$/ const phoneRex = /^1([3-9])\d{9}$/;
// 登录返回 data 的结构(这里只挑我们需要的字段) // 登录返回 data 的结构(这里只挑我们需要的字段)
type LoginResultData = { type LoginResultData = {
loginUserInfoList: any[] | null loginUserInfoList: any[] | null
noSignInUuid: string | null noSignInUuid: null | string
sessionId: string | null sessionId: null | string
} }
const mobile = ref<string>('') const mobile = ref<string>("");
const code = ref<string>('') const code = ref<string>("");
const count = ref<number>(0) const count = ref<number>(0);
const noSignIn = ref<boolean>(true) const noSignIn = ref<boolean>(true);
const readingStatus = ref<boolean>(false) const readingStatus = ref<boolean>(false);
const deviceId = ref<string>('') const deviceId = ref<string>("");
// 简单登录节流,防止连续点击 // 简单登录节流,防止连续点击
let lastLoginAt = 0 let lastLoginAt = 0;
const LOGIN_INTERVAL_MS = 200 const LOGIN_INTERVAL_MS = 200;
// 先定义会被其他函数调用的函数:getAccountLoginList / jump / doLogin / login / countDown // 先定义会被其他函数调用的函数:getAccountLoginList / jump / doLogin / login / countDown
const getAccountLoginList = (loginUserInfoList: any[]): void => { const getAccountLoginList = (loginUserInfoList: any[]): void => {
const stepIndex = loginUserInfoList.length == 1 ? 1 : 0 const stepIndex = loginUserInfoList.length == 1 ? 1 : 0;
uni.navigateTo({ uni.navigateTo({
url: `/pages/common/accountItems?stepIndex=${stepIndex}` url: `/pages/common/accountItems?stepIndex=${stepIndex}`
}) });
} };
const jump = (data: any, remember: boolean): void => { const jump = (data: any, remember: boolean): void => {
const loginData = data as LoginResultData const loginData = data as LoginResultData;
const loginUserInfoList = loginData.loginUserInfoList const loginUserInfoList = loginData.loginUserInfoList;
const sessionIdVal = loginData.sessionId const sessionIdVal = loginData.sessionId;
const noSignInUuidVal = loginData.noSignInUuid const noSignInUuidVal = loginData.noSignInUuid;
if (loginUserInfoList != null && loginUserInfoList.length > 0) { if (loginUserInfoList != null && loginUserInfoList.length > 0) {
if (sessionIdVal != null && sessionIdVal != '') { if (sessionIdVal != null && sessionIdVal != "") {
storage.set('sessionId', sessionIdVal, 0) storage.set("sessionId", sessionIdVal, 0);
} }
if (noSignInUuidVal != null && noSignInUuidVal != '' && remember) { if (noSignInUuidVal != null && noSignInUuidVal != "" && remember) {
storage.set('noSignInUuid', noSignInUuidVal, 0) storage.set("noSignInUuid", noSignInUuidVal, 0);
} }
getAccountLoginList(loginUserInfoList) getAccountLoginList(loginUserInfoList);
} else { } else {
uni.reLaunch({ uni.reLaunch({
url: '/pages/common/nothing' url: "/pages/common/nothing"
}) });
}
} }
};
const doLogin = async (): Promise<void> => { const doLogin = async (): Promise<void> => {
console.log('doLogin',mobile) console.log("doLogin", mobile);
const m = mobile.value const m = mobile.value;
const smsCode = code.value const smsCode = code.value;
const remember = noSignIn.value const remember = noSignIn.value;
const agreed = readingStatus.value const agreed = readingStatus.value;
try { try {
if (m == '') { if (m == "") {
throw new Error('请输入手机号') throw new Error("请输入手机号");
} }
if (!phoneRex.test(m)) { if (!phoneRex.test(m)) {
throw new Error('请输入正确的手机号') throw new Error("请输入正确的手机号");
} }
if (smsCode == '') { if (smsCode == "") {
throw new Error('请输入验证码') throw new Error("请输入验证码");
} }
if (!agreed) { if (!agreed) {
throw new Error('请您阅读并同意《隐私协议》') throw new Error("请您阅读并同意《隐私协议》");
} }
const params: UTSJSONObject = { const params: UTSJSONObject = {
mobile: m, mobile: m,
code: smsCode code: smsCode
} };
if (remember) { if (remember) {
params['noSignIn'] = remember params.noSignIn = remember;
} }
uni.showLoading({ uni.showLoading({
title: '加载中', title: "加载中",
mask: true mask: true
}) });
console.log('res9032903920') console.log("res9032903920");
const res = await apiSmsLogin(params) const res = await apiSmsLogin(params);
console.log('res',res) console.log("res", res);
uni.hideLoading() uni.hideLoading();
const resCode = res != null ? (res.code as number | null) : null const resCode = res != null ? (res.code as null | number) : null;
const data = res != null ? (res.data as any | null) : null const data = res != null ? (res.data as any | null) : null;
const message = res != null ? (res.message as string | null) : null const message = res != null ? (res.message as null | string) : null;
if (resCode == 0 && data != null) { if (resCode == 0 && data != null) {
jump(data, remember) jump(data, remember);
} else { } else {
uni.showModal({ uni.showModal({
title: '温馨提示', title: "温馨提示",
content: message ?? '登录失败', content: message ?? "登录失败",
showCancel: false, showCancel: false,
confirmText: '知道了', confirmText: "知道了",
confirmColor: '#347BFF' confirmColor: "#347BFF"
}) });
console.log(`${m}登录失败,失败原因:${message}`) console.log(`${m}登录失败,失败原因:${message}`);
} }
} catch (err) { } catch (error) {
const msg = `${err}` const msg = `${error}`;
uni.hideLoading() uni.hideLoading();
uni.showToast({ uni.showToast({
title: msg, title: msg,
icon: 'none' icon: "none"
}) });
}
} }
};
const login = (): void => { const login = (): void => {
const now = Date.now() const now = Date.now();
if (now - lastLoginAt < LOGIN_INTERVAL_MS) { if (now - lastLoginAt < LOGIN_INTERVAL_MS) {
return return;
} }
lastLoginAt = now lastLoginAt = now;
doLogin() doLogin();
} };
function countDown(initial: number): void { function countDown(initial: number): void {
if (initial > 0) { if (initial > 0) {
count.value = initial count.value = initial;
} }
setTimeout(() => { setTimeout(() => {
const current = count.value const current = count.value;
const next = current - 1 const next = current - 1;
count.value = next count.value = next;
if (next > 0) { if (next > 0) {
countDown(next) countDown(next);
} else { } else {
count.value = 0 count.value = 0;
}
}, 1000)
} }
}, 1000);
}
// 下面是其余业务函数 // 下面是其余业务函数
const autoLoginByMobile = (): void => { const autoLoginByMobile = (): void => {
const m = mobile.value const m = mobile.value;
const c = code.value const c = code.value;
if (c != '' && m != '' && c.length == 4 && phoneRex.test(m)) { if (c != "" && m != "" && c.length == 4 && phoneRex.test(m)) {
login() login();
}
} }
};
const clearMobile = (): void => { const clearMobile = (): void => {
mobile.value = '' mobile.value = "";
} };
const clearCode = (): void => { const clearCode = (): void => {
code.value = '' code.value = "";
} };
const copyDeviceId = (): void => { const copyDeviceId = (): void => {
uni.setClipboardData({ uni.setClipboardData({
data: deviceId.value, data: deviceId.value,
success() { success() {
uni.showToast({ uni.showToast({
title: '复制成功', title: "复制成功",
icon: 'success' icon: "success"
}) });
}
})
} }
});
};
const autoLogin = async (noSignInUuid: string): Promise<void> => { const autoLogin = async (noSignInUuid: string): Promise<void> => {
if (noSignInUuid == '') return if (noSignInUuid == "") return;
uni.showLoading({ uni.showLoading({
title: '加载中', title: "加载中",
mask: true mask: true
}) });
try { try {
const res = await apiAutoLogin({ const res = await apiAutoLogin({
noSignInUuid noSignInUuid
} as UTSJSONObject) } as UTSJSONObject);
uni.hideLoading() uni.hideLoading();
const data = res != null ? (res.data as any | null) : null const data = res != null ? (res.data as any | null) : null;
if (data != null) { if (data != null) {
jump(data, true) jump(data, true);
}
} catch (error) {
uni.hideLoading()
} }
} catch {
uni.hideLoading();
} }
};
const getSmsCode = async (): Promise<void> => { const getSmsCode = async (): Promise<void> => {
const m = mobile.value const m = mobile.value;
const c = count.value const c = count.value;
try { try {
if (m == '') { if (m == "") {
throw new Error('请输入手机号') throw new Error("请输入手机号");
} }
if (!phoneRex.test(m)) { if (!phoneRex.test(m)) {
throw new Error('请输入正确的手机号') throw new Error("请输入正确的手机号");
} }
if (c > 0) { if (c > 0) {
throw new Error('验证码发送过于频繁,请稍后再试') throw new Error("验证码发送过于频繁,请稍后再试");
} }
uni.showLoading({ uni.showLoading({
title: '加载中', title: "加载中",
mask: true mask: true
}) });
const res = await apiGetSmsCode({ const res = await apiGetSmsCode({
mobile: m mobile: m
} as UTSJSONObject) } as UTSJSONObject);
uni.hideLoading() uni.hideLoading();
const codeVal = res != null ? (res.code as string | null) : null const codeVal = res != null ? (res.code as null | string) : null;
const message = res != null ? (res.message as string | null) : null const message = res != null ? (res.message as null | string) : null;
if (codeVal == '0') { if (codeVal == "0") {
uni.showToast({ uni.showToast({
title: '验证码已发送', title: "验证码已发送",
icon: 'none' icon: "none"
}) });
countDown(60) countDown(60);
} else { } else {
throw new Error(message ?? '发送验证码失败') throw new Error(message ?? "发送验证码失败");
} }
} catch (err) { } catch (error) {
const msg = `${err}` const msg = `${error}`;
uni.hideLoading() uni.hideLoading();
uni.showToast({ uni.showToast({
title: msg, title: msg,
icon: 'none' icon: "none"
}) });
}
} }
};
const openPrivacy = (): void => { const openPrivacy = (): void => {
const url = 'https://img01.glsx.com.cn/weapp/resource/saas/app/privacy.html' const url = "https://img01.glsx.com.cn/weapp/resource/saas/app/privacy.html";
uni.navigateTo({ uni.navigateTo({
url: `/pages/common/webview?url=${url}` url: `/pages/common/webview?url=${url}`
}) });
} };
onLoad((options: UTSJSONObject | null) => { onLoad((options: null | UTSJSONObject) => {
const optMobile = options != null ? (options['mobile'] as string | null) : null const optMobile = options != null ? (options.mobile as null | string) : null;
if (optMobile != null && optMobile != '') { if (optMobile != null && optMobile != "") {
mobile.value = optMobile mobile.value = optMobile;
} }
const noSignInUuid = storage.get('noSignInUuid') as string | null const noSignInUuid = storage.get("noSignInUuid") as null | string;
if (noSignInUuid != null && noSignInUuid != '') { if (noSignInUuid != null && noSignInUuid != "") {
autoLogin(noSignInUuid) autoLogin(noSignInUuid);
} }
const info = uni.getDeviceInfo() const info = uni.getDeviceInfo();
if (info != null && info.deviceId != null) { if (info != null && info.deviceId != null) {
deviceId.value = info.deviceId deviceId.value = info.deviceId;
} }
}) });
watch(mobile, () => { watch(mobile, () => {
autoLoginByMobile() autoLoginByMobile();
}) });
watch(code, () => { watch(code, () => {
autoLoginByMobile() autoLoginByMobile();
}) });
function toggleReadingStatus(): void { function toggleReadingStatus(): void {
readingStatus.value = !readingStatus.value readingStatus.value = !readingStatus.value;
} }
function toggleNoSignIn(): void { function toggleNoSignIn(): void {
noSignIn.value = !noSignIn.value noSignIn.value = !noSignIn.value;
} }
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.layout { .layout {
......
<template> <template>
<view <view style="flex: 1">
<view id="chart-container-1" class="chart-container">
style="flex: 1"
>
<view class="chart-container" id="chart-container-1">
<!-- #ifdef APP --> <!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 --> <!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart <l-echart ref="chartRef"
ref="chartRef" :before-delay="0"
@finished="initChart"
class="chart" class="chart"
:enable-hover="false" :enable-hover="false"
:is-clickable="false" :is-clickable="false"
:before-delay="0"> @finished="initChart">
</l-echart> </l-echart>
<!-- #endif --> <!-- #endif -->
<!-- #ifndef APP --> <!-- #ifndef APP -->
<l-echart ref="chartRef" @finished="initChart" class="chart"></l-echart> <l-echart ref="chartRef"
class="chart"
@finished="initChart">
</l-echart>
<!-- #endif --> <!-- #endif -->
</view> </view>
<view class="chart-container" id="chart-container-2" style="margin-top: 16px"> <view id="chart-container-2"
class="chart-container"
style="margin-top: 16px">
<!-- #ifdef APP --> <!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 --> <!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart <l-echart ref="lineChartRef"
ref="lineChartRef" :before-delay="0"
@finished="initLineChart"
class="chart" class="chart"
:enable-hover="false" :enable-hover="false"
:is-clickable="false" :is-clickable="false"
:before-delay="0"> @finished="initLineChart">
</l-echart> </l-echart>
<!-- #endif --> <!-- #endif -->
<!-- #ifndef APP --> <!-- #ifndef APP -->
<l-echart ref="lineChartRef" @finished="initLineChart" class="chart"></l-echart> <l-echart ref="lineChartRef"
class="chart"
@finished="initLineChart">
</l-echart>
<!-- #endif --> <!-- #endif -->
</view> </view>
</view> </view>
......
<template> <template>
<!-- 和首页同样的写法:scroll-view 自己 flex:1,并且本身是纵向 flex 容器 --> <!-- 和首页同样的写法:scroll-view 自己 flex:1,并且本身是纵向 flex 容器 -->
<scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50"> <scroll-view class="flex flex-col bg-gray-50"
scroll-y="true"
style="flex: 1">
<!-- 内层不再额外设 flex 布局,避免干扰 scroll-view 高度计算 --> <!-- 内层不再额外设 flex 布局,避免干扰 scroll-view 高度计算 -->
<!-- 顶部标题区域(渐变改为纯色,兼容 App) --> <!-- 顶部标题区域(渐变改为纯色,兼容 App) -->
<view class="bg-blue-500 px-6 py-8 flex-col"> <view class="bg-blue-500 px-6 py-8 flex-col">
...@@ -18,8 +20,12 @@ ...@@ -18,8 +20,12 @@
<text class="text-sm text-gray-600 block">新代码:getAppVersion()</text> <text class="text-sm text-gray-600 block">新代码:getAppVersion()</text>
</view> </view>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleGetVersion">获取版本号</button> <button class="btn btn-primary mr-2 mb-2" @click="handleGetVersion">
<button class="btn btn-primary mr-2 mb-2" @click="handleOpenURL">打开URL</button> 获取版本号
</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleOpenURL">
打开URL
</button>
</view> </view>
<view v-if="runtimeResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="runtimeResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ runtimeResult }}</text> <text class="text-sm text-gray-800">{{ runtimeResult }}</text>
...@@ -34,9 +40,15 @@ ...@@ -34,9 +40,15 @@
<text class="text-sm text-gray-600 block">新代码:lockOrientation() + manifest.json配置</text> <text class="text-sm text-gray-600 block">新代码:lockOrientation() + manifest.json配置</text>
</view> </view>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-success mr-2 mb-2" @click="handleLockPortrait">锁定竖屏</button> <button class="btn btn-success mr-2 mb-2" @click="handleLockPortrait">
<button class="btn btn-success mr-2 mb-2" @click="handleLockLandscape">锁定横屏</button> 锁定竖屏
<button class="btn btn-success mr-2 mb-2" @click="handleKeepScreenOn">保持常亮</button> </button>
<button class="btn btn-success mr-2 mb-2" @click="handleLockLandscape">
锁定横屏
</button>
<button class="btn btn-success mr-2 mb-2" @click="handleKeepScreenOn">
保持常亮
</button>
</view> </view>
<view v-if="screenResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="screenResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ screenResult }}</text> <text class="text-sm text-gray-800">{{ screenResult }}</text>
...@@ -51,9 +63,15 @@ ...@@ -51,9 +63,15 @@
<text class="text-sm text-gray-600 block">新代码:uni.getFileSystemManager()</text> <text class="text-sm text-gray-600 block">新代码:uni.getFileSystemManager()</text>
</view> </view>
<view class="flex flex-wrap"> <view class="flex flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleGetFilePath">获取文件路径</button> <button class="btn btn-primary mr-2 mb-2" @click="handleGetFilePath">
<button class="btn btn-primary mr-2 mb-2" @click="handleWriteFile">写入文件</button> 获取文件路径
<button class="btn btn-primary mr-2 mb-2" @click="handleReadFile">读取文件</button> </button>
<button class="btn btn-primary mr-2 mb-2" @click="handleWriteFile">
写入文件
</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleReadFile">
读取文件
</button>
</view> </view>
<view v-if="ioResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="ioResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800 break-words">{{ ioResult }}</text> <text class="text-sm text-gray-800 break-words">{{ ioResult }}</text>
...@@ -68,7 +86,9 @@ ...@@ -68,7 +86,9 @@
<text class="text-sm text-gray-600 block">新代码:isIOS() / isAndroid()</text> <text class="text-sm text-gray-600 block">新代码:isIOS() / isAndroid()</text>
</view> </view>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-warning mr-2 mb-2" @click="handleCheckOS">检测系统</button> <button class="btn btn-warning mr-2 mb-2" @click="handleCheckOS">
检测系统
</button>
</view> </view>
<view v-if="osResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="osResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ osResult }}</text> <text class="text-sm text-gray-800">{{ osResult }}</text>
...@@ -83,7 +103,9 @@ ...@@ -83,7 +103,9 @@
<text class="text-sm text-gray-600 block">新代码:getStatusbarHeight()</text> <text class="text-sm text-gray-600 block">新代码:getStatusbarHeight()</text>
</view> </view>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-secondary mr-2 mb-2" @click="handleGetStatusbarHeight">获取状态栏高度</button> <button class="btn btn-secondary mr-2 mb-2" @click="handleGetStatusbarHeight">
获取状态栏高度
</button>
</view> </view>
<view v-if="navigatorResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="navigatorResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ navigatorResult }}</text> <text class="text-sm text-gray-800">{{ navigatorResult }}</text>
...@@ -120,45 +142,45 @@ ...@@ -120,45 +142,45 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { getAppVersion, openURL, getAppInfo } from "@/utils/plus-runtime" import { getFilePath, readFile, writeFile } from "@/utils/plus-io";
import { lockOrientation, unlockOrientation, setKeepScreenOn } from "@/utils/plus-screen" import { getStatusbarHeight } from "@/utils/plus-navigator";
import { getFilePath, writeFile, readFile } from "@/utils/plus-io" import { getOSName, isAndroid, isIOS } from "@/utils/plus-os";
import { isIOS, isAndroid, getOSName } from "@/utils/plus-os" import { getAppInfo, getAppVersion, openURL } from "@/utils/plus-runtime";
import { getStatusbarHeight } from "@/utils/plus-navigator" import { lockOrientation, setKeepScreenOn } from "@/utils/plus-screen";
const runtimeResult = ref<string>("") const runtimeResult = ref<string>("");
const screenResult = ref<string>("") const screenResult = ref<string>("");
const ioResult = ref<string>("") const ioResult = ref<string>("");
const osResult = ref<string>("") const osResult = ref<string>("");
const navigatorResult = ref<string>("") const navigatorResult = ref<string>("");
// plus.runtime 示例 // plus.runtime 示例
const handleGetVersion = () => { const handleGetVersion = () => {
const version = getAppVersion() const version = getAppVersion();
const appInfo = getAppInfo() const appInfo = getAppInfo();
runtimeResult.value = `版本号: ${version}\nAppID: ${appInfo.appid}` runtimeResult.value = `版本号: ${version}\nAppID: ${appInfo.appid}`;
} };
const handleOpenURL = () => { const handleOpenURL = () => {
openURL("https://uniapp.dcloud.net.cn/") openURL("https://uniapp.dcloud.net.cn/");
runtimeResult.value = "已尝试打开 uni-app 官网" runtimeResult.value = "已尝试打开 uni-app 官网";
} };
// plus.screen 示例 // plus.screen 示例
const handleLockPortrait = () => { const handleLockPortrait = () => {
lockOrientation("portrait-primary") lockOrientation("portrait-primary");
screenResult.value = "已锁定竖屏(实际需要在 manifest.json 中配置)" screenResult.value = "已锁定竖屏(实际需要在 manifest.json 中配置)";
} };
const handleLockLandscape = () => { const handleLockLandscape = () => {
lockOrientation("landscape-primary") lockOrientation("landscape-primary");
screenResult.value = "已锁定横屏(实际需要在 manifest.json 中配置)" screenResult.value = "已锁定横屏(实际需要在 manifest.json 中配置)";
} };
const handleKeepScreenOn = () => { const handleKeepScreenOn = () => {
setKeepScreenOn(true) setKeepScreenOn(true);
screenResult.value = "已设置屏幕常亮" screenResult.value = "已设置屏幕常亮";
} };
// plus.io 示例 // plus.io 示例
const handleGetFilePath = async () => { const handleGetFilePath = async () => {
...@@ -173,12 +195,12 @@ const handleGetFilePath = async () => { ...@@ -173,12 +195,12 @@ const handleGetFilePath = async () => {
// #ifndef APP // #ifndef APP
path = await getFilePath(); path = await getFilePath();
// #endif // #endif
ioResult.value = `文件路径: ${path}` ioResult.value = `文件路径: ${path}`;
} catch (error: any) { } catch (error: any) {
// UTS 不支持 String() 构造函数,使用字符串模板或 toString() // UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `获取路径失败: ${error != null ? error.toString() : "未知错误"}` ioResult.value = `获取路径失败: ${error != null ? error.toString() : "未知错误"}`;
} }
} };
const handleWriteFile = async () => { const handleWriteFile = async () => {
try { try {
...@@ -189,14 +211,14 @@ const handleWriteFile = async () => { ...@@ -189,14 +211,14 @@ const handleWriteFile = async () => {
// #ifndef APP // #ifndef APP
testPath = `${await getFilePath()}/hello.txt`; testPath = `${await getFilePath()}/hello.txt`;
// #endif // #endif
await writeFile(testPath, "Hello uni-app x!") await writeFile(testPath, "Hello uni-app x!");
ioResult.value = `文件写入成功: ${testPath}` ioResult.value = `文件写入成功: ${testPath}`;
} catch (error: any) { } catch (error: any) {
console.error("writeFile fail: ", error); console.error("writeFile fail:", error);
// UTS 不支持 String() 构造函数,使用字符串模板或 toString() // UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `写入失败: ${error != null ? error.toString() : "未知错误"}` ioResult.value = `写入失败: ${error != null ? error.toString() : "未知错误"}`;
} }
} };
const handleReadFile = async () => { const handleReadFile = async () => {
try { try {
...@@ -207,27 +229,27 @@ const handleReadFile = async () => { ...@@ -207,27 +229,27 @@ const handleReadFile = async () => {
// #ifndef APP // #ifndef APP
testPath = `${await getFilePath()}/hello.txt`; testPath = `${await getFilePath()}/hello.txt`;
// #endif // #endif
const content = await readFile(testPath) const content = await readFile(testPath);
ioResult.value = `文件内容: ${content}` ioResult.value = `文件内容: ${content}`;
} catch (error: any) { } catch (error: any) {
// UTS 不支持 String() 构造函数,使用字符串模板或 toString() // UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `读取失败: ${error != null ? error.toString() : "未知错误"}` ioResult.value = `读取失败: ${error != null ? error.toString() : "未知错误"}`;
} }
} };
// plus.os 示例 // plus.os 示例
const handleCheckOS = () => { const handleCheckOS = () => {
const osName = getOSName() const osName = getOSName();
const isIOSDevice = isIOS() const isIOSDevice = isIOS();
const isAndroidDevice = isAndroid() const isAndroidDevice = isAndroid();
osResult.value = `系统: ${osName}\n是否iOS: ${isIOSDevice}\n是否Android: ${isAndroidDevice}` osResult.value = `系统: ${osName}\n是否iOS: ${isIOSDevice}\n是否Android: ${isAndroidDevice}`;
} };
// plus.navigator 示例 // plus.navigator 示例
const handleGetStatusbarHeight = () => { const handleGetStatusbarHeight = () => {
const height = getStatusbarHeight() const height = getStatusbarHeight();
navigatorResult.value = `状态栏高度: ${height}px` navigatorResult.value = `状态栏高度: ${height}px`;
} };
</script> </script>
<style> <style>
......
<template> <template>
<scroll-view class="flex flex-col p-5 bg-gray-100" style="flex: 1" scroll-y="true"> <scroll-view class="flex flex-col p-5 bg-gray-100"
scroll-y="true"
style="flex: 1">
<view class="flex flex-col mb-5 p-5 bg-white rounded-lg shadow-sm flex-shrink-0"> <view class="flex flex-col mb-5 p-5 bg-white rounded-lg shadow-sm flex-shrink-0">
<text class="text-2xl font-bold text-gray-800 mb-2">SqliteStore 示例</text> <text class="text-2xl font-bold text-gray-800 mb-2">SqliteStore 示例</text>
<text class="text-sm text-gray-600">基于 SQLite 的本地存储方案(解决并发同步问题)</text> <text class="text-sm text-gray-600">基于 SQLite 的本地存储方案(解决并发同步问题)</text>
...@@ -13,11 +15,21 @@ ...@@ -13,11 +15,21 @@
<view class="flex flex-col p-4 bg-white rounded-lg shadow-sm"> <view class="flex flex-col p-4 bg-white rounded-lg shadow-sm">
<text class="text-base font-bold text-gray-800 mb-3 relative pb-2 border-b-2 border-gray-200">基础操作</text> <text class="text-base font-bold text-gray-800 mb-3 relative pb-2 border-b-2 border-gray-200">基础操作</text>
<view class="flex flex-wrap"> <view class="flex flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleInsert">插入数据</button> <button class="btn btn-primary mr-2 mb-2" @click="handleInsert">
<button class="btn btn-secondary mr-2 mb-2" @click="handleInsertWithId">指定ID插入</button> 插入数据
<button class="btn btn-secondary mr-2 mb-2" @click="handleQuery">查询数据</button> </button>
<button class="btn btn-warning mr-2 mb-2" @click="handleUpdate">更新数据</button> <button class="btn btn-secondary mr-2 mb-2" @click="handleInsertWithId">
<button class="btn btn-danger mr-2 mb-2" @click="handleDeleteSelected">删除选中</button> 指定ID插入
</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQuery">
查询数据
</button>
<button class="btn btn-warning mr-2 mb-2" @click="handleUpdate">
更新数据
</button>
<button class="btn btn-danger mr-2 mb-2" @click="handleDeleteSelected">
删除选中
</button>
</view> </view>
</view> </view>
...@@ -27,10 +39,18 @@ ...@@ -27,10 +39,18 @@
查询操作 查询操作
</text> </text>
<view class="flex flex-wrap"> <view class="flex flex-wrap">
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryAdults">查询成年人</button> <button class="btn btn-secondary mr-2 mb-2" @click="handleQueryAdults">
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryActive">查询活跃用户</button> 查询成年人
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryByEmail">按邮箱查询</button> </button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryAll">查询全部</button> <button class="btn btn-secondary mr-2 mb-2" @click="handleQueryActive">
查询活跃用户
</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryByEmail">
按邮箱查询
</button>
<button class="btn btn-secondary mr-2 mb-2" @click="handleQueryAll">
查询全部
</button>
</view> </view>
</view> </view>
...@@ -40,16 +60,20 @@ ...@@ -40,16 +60,20 @@
批量操作 批量操作
</text> </text>
<view class="flex flex-wrap"> <view class="flex flex-wrap">
<button class="btn btn-success mr-2 mb-2" @click="handleBatchInsert">批量插入</button> <button class="btn btn-success mr-2 mb-2" @click="handleBatchInsert">
<button class="btn btn-success mr-2 mb-2" @click="handleBatchUpdate">批量更新</button> 批量插入
<button class="btn btn-danger mr-2 mb-2" @click="handleBatchDelete">批量删除</button> </button>
<button class="btn btn-success mr-2 mb-2" @click="handleBatchUpdate">
批量更新
</button>
<button class="btn btn-danger mr-2 mb-2" @click="handleBatchDelete">
批量删除
</button>
</view> </view>
<view class="flex flex-wrap mt-2"> <view class="flex flex-wrap mt-2">
<button <button class="btn btn-success mr-2 mb-2"
class="btn btn-success mr-2 mb-2"
:disabled="isInserting" :disabled="isInserting"
@click="handleLargeBatchInsert" @click="handleLargeBatchInsert">
>
{{ isInserting ? '插入中...' : '大数据批量插入' }} {{ isInserting ? '插入中...' : '大数据批量插入' }}
</button> </button>
</view> </view>
...@@ -61,8 +85,12 @@ ...@@ -61,8 +85,12 @@
工具操作 工具操作
</text> </text>
<view class="flex flex-wrap"> <view class="flex flex-wrap">
<button class="btn btn-dark mr-2 mb-2" @click="handleGetStats">统计信息</button> <button class="btn btn-dark mr-2 mb-2" @click="handleGetStats">
<button class="btn btn-dark mr-2 mb-2" @click="handleClear">清空数据</button> 统计信息
</button>
<button class="btn btn-dark mr-2 mb-2" @click="handleClear">
清空数据
</button>
</view> </view>
</view> </view>
</view> </view>
...@@ -80,9 +108,7 @@ ...@@ -80,9 +108,7 @@
</view> </view>
<!-- 数据列表:右侧区域上半部分,高度约 50%,内部可滚动 --> <!-- 数据列表:右侧区域上半部分,高度约 50%,内部可滚动 -->
<view <view class="flex-1 flex flex-col p-4 bg-white rounded-lg shadow-sm overflow-hidden min-h-0 border border-black border-opacity-5">
class="flex-1 flex flex-col p-4 bg-white rounded-lg shadow-sm overflow-hidden min-h-0 border border-black border-opacity-5"
>
<view class="flex justify-between items-center mb-3 pb-3 border-b-2 border-gray-200"> <view class="flex justify-between items-center mb-3 pb-3 border-b-2 border-gray-200">
<text class="text-lg font-semibold text-gray-800 block relative"> <text class="text-lg font-semibold text-gray-800 block relative">
<text class="absolute left-[-12px] top-1/2 transform -translate-y-1/2 w-1 h-5 bg-gradient-to-b from-indigo-500 to-purple-500 rounded"></text> <text class="absolute left-[-12px] top-1/2 transform -translate-y-1/2 w-1 h-5 bg-gradient-to-b from-indigo-500 to-purple-500 rounded"></text>
...@@ -101,7 +127,7 @@ ...@@ -101,7 +127,7 @@
<text class="text-sm text-gray-500">加载中...</text> <text class="text-sm text-gray-500">加载中...</text>
</view> </view>
</view> </view>
<view v-else-if="dataList.length == 0" class="flex justify-center items-center p-10"> <view v-else-if="dataList.length === 0" class="flex justify-center items-center p-10">
<text class="text-sm text-gray-400">暂无数据,点击左侧按钮进行操作</text> <text class="text-sm text-gray-400">暂无数据,点击左侧按钮进行操作</text>
</view> </view>
...@@ -109,11 +135,9 @@ ...@@ -109,11 +135,9 @@
<!-- 表头 --> <!-- 表头 -->
<view class="flex flex-row bg-gray-100 border-b-2 border-gray-300"> <view class="flex flex-row bg-gray-100 border-b-2 border-gray-300">
<view class="table-col-checkbox" @click.stop="toggleSelectAll"> <view class="table-col-checkbox" @click.stop="toggleSelectAll">
<checkbox <checkbox :checked="isAllSelected()"
value="select-all" value="select-all"
:checked="isAllSelected()" @click.stop="toggleSelectAll" />
@click.stop="toggleSelectAll"
/>
</view> </view>
<view class="table-col-id"> <view class="table-col-id">
<text class="text-sm text-gray-700 font-bold">ID</text> <text class="text-sm text-gray-700 font-bold">ID</text>
...@@ -136,13 +160,14 @@ ...@@ -136,13 +160,14 @@
</view> </view>
<!-- 表格内容 --> <!-- 表格内容 -->
<view v-for="(item, index) in dataList" :key="item.id" class="flex flex-row border-b border-gray-200 bg-white" :class="index % 2 == 1 ? 'bg-gray-50' : ''"> <view v-for="(item, index) in dataList"
:key="item.id"
class="flex flex-row border-b border-gray-200 bg-white"
:class="index % 2 == 1 ? 'bg-gray-50' : ''">
<view class="table-col-checkbox" @click.stop="toggleSelect(item.id)"> <view class="table-col-checkbox" @click.stop="toggleSelect(item.id)">
<checkbox <checkbox :checked="isSelected(item.id)"
:value="item.id" :value="item.id"
:checked="isSelected(item.id)" @click.stop="toggleSelect(item.id)" />
@click.stop="toggleSelect(item.id)"
/>
</view> </view>
<view class="table-col-id"> <view class="table-col-id">
<text class="text-sm text-gray-800">{{ item.id }}</text> <text class="text-sm text-gray-800">{{ item.id }}</text>
...@@ -157,10 +182,8 @@ ...@@ -157,10 +182,8 @@
<text class="text-sm text-gray-800">{{ item.email }}</text> <text class="text-sm text-gray-800">{{ item.email }}</text>
</view> </view>
<view class="table-col-status"> <view class="table-col-status">
<text <text class="px-2 py-1 rounded text-xs"
class="px-2 py-1 rounded text-xs" :class="item.status == 'active' ? 'bg-green-500 text-white' : 'bg-gray-400 text-white'">
:class="item.status == 'active' ? 'bg-green-500 text-white' : 'bg-gray-400 text-white'"
>
{{ item.status == "active" ? "活跃" : "非活跃" }} {{ item.status == "active" ? "活跃" : "非活跃" }}
</text> </text>
</view> </view>
...@@ -173,19 +196,19 @@ ...@@ -173,19 +196,19 @@
</view> </view>
<!-- 日志区域:右侧区域下半部分,高度约 50%,内部可滚动 --> <!-- 日志区域:右侧区域下半部分,高度约 50%,内部可滚动 -->
<view <view class="flex-1 flex flex-col p-4 bg-white rounded-lg shadow-sm overflow-hidden min-h-0 border border-black border-opacity-5">
class="flex-1 flex flex-col p-4 bg-white rounded-lg shadow-sm overflow-hidden min-h-0 border border-black border-opacity-5"
>
<view class="flex justify-between items-center mb-3 pb-3 border-b-2 border-gray-200"> <view class="flex justify-between items-center mb-3 pb-3 border-b-2 border-gray-200">
<text class="text-lg font-semibold text-gray-800 block relative"> <text class="text-lg font-semibold text-gray-800 block relative">
<text class="absolute left-[-12px] top-1/2 transform -translate-y-1/2 w-1 h-5 bg-gradient-to-b from-indigo-500 to-purple-500 rounded"></text> <text class="absolute left-[-12px] top-1/2 transform -translate-y-1/2 w-1 h-5 bg-gradient-to-b from-indigo-500 to-purple-500 rounded"></text>
操作日志 操作日志
</text> </text>
<button class="btn btn-danger text-xs" @click="clearLogs">清空日志</button> <button class="btn btn-danger text-xs" @click="clearLogs">
清空日志
</button>
</view> </view>
<!-- 日志内容 --> <!-- 日志内容 -->
<view class="flex-1 overflow-hidden min-h-0"> <view class="flex-1 overflow-hidden min-h-0">
<view v-if="logs.length == 0" class="flex justify-center items-center p-10"> <view v-if="logs.length === 0" class="flex justify-center items-center p-10">
<text class="text-sm text-gray-400">暂无日志</text> <text class="text-sm text-gray-400">暂无日志</text>
</view> </view>
...@@ -201,7 +224,10 @@ ...@@ -201,7 +224,10 @@
</view> </view>
<!-- 表格内容 --> <!-- 表格内容 -->
<view v-for="(log, index) in logs" :key="index" class="flex flex-row border-b border-gray-200 bg-white" :class="index % 2 == 1 ? 'bg-gray-50' : ''"> <view v-for="(log, index) in logs"
:key="index"
class="flex flex-row border-b border-gray-200 bg-white"
:class="index % 2 == 1 ? 'bg-gray-50' : ''">
<view class="table-log-time"> <view class="table-log-time">
<text class="text-xs text-indigo-500 font-medium">{{ log.time }}</text> <text class="text-xs text-indigo-500 font-medium">{{ log.time }}</text>
</view> </view>
...@@ -218,18 +244,18 @@ ...@@ -218,18 +244,18 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { get } from "@/utils/common.uts";
// 使用 SqliteStore,基于 SQLite 的本地存储方案 // 使用 SqliteStore,基于 SQLite 的本地存储方案
import SqliteStore from "@/utils/sqlite-store.uts"; import SqliteStore from "@/utils/sqlite-store.uts";
import { get } from "@/utils/common.uts";
// 定义用户数据类型 // 定义用户数据类型
type UserData = { type UserData = {
id: string;
name: string;
age: number; age: number;
created_at: number;
email: string; email: string;
id: string;
name: string;
status: string; status: string;
created_at: number;
updated_at: number; updated_at: number;
}; };
...@@ -248,8 +274,8 @@ const isLoading = ref<boolean>(false); ...@@ -248,8 +274,8 @@ const isLoading = ref<boolean>(false);
// 日志列表 // 日志列表
type LogItem = { type LogItem = {
time: string;
message: string; message: string;
time: string;
}; };
const logs = ref<LogItem[]>([]); const logs = ref<LogItem[]>([]);
...@@ -269,7 +295,7 @@ const addLog = (message: string) => { ...@@ -269,7 +295,7 @@ const addLog = (message: string) => {
// UTS 需要显式声明类型,避免类型推断为 UTSJSONObject // UTS 需要显式声明类型,避免类型推断为 UTSJSONObject
const logItem: LogItem = { const logItem: LogItem = {
time: timeStr, time: timeStr,
message: message message
}; };
logs.value.push(logItem); logs.value.push(logItem);
// 限制日志数量 // 限制日志数量
...@@ -284,8 +310,7 @@ const refreshData = () => { ...@@ -284,8 +310,7 @@ const refreshData = () => {
userStore.select((results) => { userStore.select((results) => {
const newList: Array<UserData> = []; const newList: Array<UserData> = [];
for (let i = 0; i < results.length; i++) { for (const row of results) {
const row = results[i];
// 使用 get() 辅助函数安全访问属性,避免 UTS 编译器 error18 // 使用 get() 辅助函数安全访问属性,避免 UTS 编译器 error18
newList.push({ newList.push({
id: get(row, "id", "") as string, id: get(row, "id", "") as string,
...@@ -334,7 +359,7 @@ const handleInsert = () => { ...@@ -334,7 +359,7 @@ const handleInsert = () => {
userStore.insert({ userStore.insert({
name: names[randomIndex], name: names[randomIndex],
age: age, age,
email: emails[randomIndex], email: emails[randomIndex],
status: Math.random() > 0.5 ? "active" : "inactive" status: Math.random() > 0.5 ? "active" : "inactive"
}, (id) => { }, (id) => {
...@@ -422,7 +447,7 @@ const toggleSelect = (id: string) => { ...@@ -422,7 +447,7 @@ const toggleSelect = (id: string) => {
// 检查是否全选 // 检查是否全选
const isAllSelected = (): boolean => { const isAllSelected = (): boolean => {
if (dataList.value.length == 0) return false; if (dataList.value.length === 0) return false;
return selectedIds.value.length == dataList.value.length && selectedIds.value.length > 0; return selectedIds.value.length == dataList.value.length && selectedIds.value.length > 0;
}; };
...@@ -447,7 +472,7 @@ const toggleSelectAll = () => { ...@@ -447,7 +472,7 @@ const toggleSelectAll = () => {
const handleDeleteSelected = () => { const handleDeleteSelected = () => {
const ids = selectedIds.value; const ids = selectedIds.value;
if (ids.length == 0) { if (ids.length === 0) {
addLog("请先选择要删除的数据"); addLog("请先选择要删除的数据");
return; return;
} }
...@@ -472,14 +497,14 @@ const handleQueryAdults = () => { ...@@ -472,14 +497,14 @@ const handleQueryAdults = () => {
userStore.select( userStore.select(
(results) => { (results) => {
const newList: Array<UserData> = []; const newList: Array<UserData> = [];
for (let i = 0; i < results.length; i++) { for (const result of results) {
const row = results[i] as UTSJSONObject; const row = result as UTSJSONObject;
const age = row.get("age") as number; const age = row.get("age") as number;
if (age >= 18) { if (age >= 18) {
newList.push({ newList.push({
id: row.get("id") as string, id: row.get("id") as string,
name: row.get("name") as string, name: row.get("name") as string,
age: age, age,
email: row.get("email") as string, email: row.get("email") as string,
status: row.get("status") as string, status: row.get("status") as string,
created_at: row.get("created_at") as number, created_at: row.get("created_at") as number,
...@@ -500,8 +525,8 @@ const handleQueryActive = () => { ...@@ -500,8 +525,8 @@ const handleQueryActive = () => {
userStore.select( userStore.select(
(results) => { (results) => {
const newList: Array<UserData> = []; const newList: Array<UserData> = [];
for (let i = 0; i < results.length; i++) { for (const result of results) {
const row = results[i] as UTSJSONObject; const row = result as UTSJSONObject;
const status = row.get("status") as string; const status = row.get("status") as string;
if (status == "active") { if (status == "active") {
newList.push({ newList.push({
...@@ -509,7 +534,7 @@ const handleQueryActive = () => { ...@@ -509,7 +534,7 @@ const handleQueryActive = () => {
name: row.get("name") as string, name: row.get("name") as string,
age: row.get("age") as number, age: row.get("age") as number,
email: row.get("email") as string, email: row.get("email") as string,
status: status, status,
created_at: row.get("created_at") as number, created_at: row.get("created_at") as number,
updated_at: row.get("updated_at") as number updated_at: row.get("updated_at") as number
} as UserData); } as UserData);
...@@ -528,15 +553,15 @@ const handleQueryByEmail = () => { ...@@ -528,15 +553,15 @@ const handleQueryByEmail = () => {
userStore.select( userStore.select(
(results) => { (results) => {
const newList: Array<UserData> = []; const newList: Array<UserData> = [];
for (let i = 0; i < results.length; i++) { for (const result of results) {
const row = results[i] as UTSJSONObject; const row = result as UTSJSONObject;
const email = row.get("email") as string; const email = row.get("email") as string;
if (email.indexOf("example") != -1) { if (email.indexOf("example") != -1) {
newList.push({ newList.push({
id: row.get("id") as string, id: row.get("id") as string,
name: row.get("name") as string, name: row.get("name") as string,
age: row.get("age") as number, age: row.get("age") as number,
email: email, email,
status: row.get("status") as string, status: row.get("status") as string,
created_at: row.get("created_at") as number, created_at: row.get("created_at") as number,
updated_at: row.get("updated_at") as number updated_at: row.get("updated_at") as number
...@@ -585,15 +610,15 @@ const handleBatchDelete = () => { ...@@ -585,15 +610,15 @@ const handleBatchDelete = () => {
userStore.select( userStore.select(
(results) => { (results) => {
const idsToDelete: string[] = []; const idsToDelete: string[] = [];
for (let i = 0; i < results.length; i++) { for (const result of results) {
const row = results[i] as UTSJSONObject; const row = result as UTSJSONObject;
const age = row.get("age") as number; const age = row.get("age") as number;
if (age < 20) { if (age < 20) {
idsToDelete.push(row.get("id") as string); idsToDelete.push(row.get("id") as string);
} }
} }
if (idsToDelete.length == 0) { if (idsToDelete.length === 0) {
addLog(`批量删除: 没有找到符合条件的记录(年龄<20)`); addLog(`批量删除: 没有找到符合条件的记录(年龄<20)`);
return; return;
} }
......
<template> <template>
<view> <view>
<image class="image" :fade-show="true" mode="widthFix" :src="imageSrc"></image> <image class="image"
<video :fade-show="true"
mode="widthFix"
:src="imageSrc">
</image>
<video autoplay
class="video" class="video"
:src="src"
controls controls
autoplay :src="src"
style="width: 100%; height: 300px" style="width: 100%; height: 300px">
></video> </video>
</view> </view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
const src =ref('https://qiniu-web-assets.dcloud.net.cn/video/sample/2minute-demo.mp4') const src =ref("https://qiniu-web-assets.dcloud.net.cn/video/sample/2minute-demo.mp4");
const imageSrc =ref('https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/1762827440132_9hivo0xz.jpg') const imageSrc =ref("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/1762827440132_9hivo0xz.jpg");
</script> </script>
<template> <template>
<!-- #ifdef APP --> <!-- #ifdef APP -->
<scroll-view style="flex: 1" scroll-y="true"> <scroll-view scroll-y="true" style="flex: 1">
<!-- #endif --> <!-- #endif -->
<view class="content flex-col"> <view class="content flex-col">
<view class="search-box flex"> <view class="search-box flex">
<view class="form-item form-item-input"> <view class="form-item form-item-input">
<view class="form-item-box align-center"> <view class="form-item-box align-center">
<input <input v-model="searchText"
:maxlength="20"
v-model="searchText"
class="input flex-1" class="input flex-1"
:maxlength="20"
placeholder="请输入车架号" placeholder="请输入车架号"
@focus="focusIndex = 0"
@blur="resetFocusIndex"
placeholder-class="placeholder" placeholder-class="placeholder"
/> @blur="resetFocusIndex"
@focus="focusIndex = 0" />
<text class="sprite-icon icon-vinScan" @click.stop="scan">📷</text> <text class="sprite-icon icon-vinScan" @click.stop="scan">📷</text>
</view> </view>
</view> </view>
<view class="btn search" @click="search"><text class="btn-text">查询</text></view> <view class="btn search" @click="search">
<view class="btn reset" @click="reset"><text class="btn-text">重置</text></view> <text class="btn-text">查询</text>
</view>
<view class="btn reset" @click="reset">
<text class="btn-text">重置</text>
</view>
</view> </view>
<view class="list-box"> <view class="list-box">
<!-- 类型标签页组件 --> <!-- 类型标签页组件 -->
<type-tab-component :typeList="typeList" :isShowCount="true" :tabIndex="tabIndex" @tabClick="tabBarClick"></type-tab-component> <TypeTabComponent :is-show-count="true"
:tab-index="tabIndex"
:type-list="typeList"
@tab-click="tabBarClick">
</TypeTabComponent>
<!-- z-paging-x 列表 --> <!-- z-paging-x 列表 -->
<z-paging-x <z-paging-x ref="paging"
ref="paging"
v-model="list" v-model="list"
list-is="scroll-view" list-is="scroll-view"
@query="getCheckReportPageList" @query="getCheckReportPageList">
>
<template #empty> <template #empty>
<view class="nothing flex"> <view class="nothing flex">
<text class="noDataImg">📋</text> <text class="noDataImg">📋</text>
...@@ -42,12 +46,10 @@ ...@@ -42,12 +46,10 @@
<!-- 列表容器,按照原项目结构(放在默认插槽中) --> <!-- 列表容器,按照原项目结构(放在默认插槽中) -->
<view class="item-list"> <view class="item-list">
<view <view v-for="(i, index) in list"
v-for="(i, index) in list"
:key="index" :key="index"
class="item flex-col" class="item flex-col"
@click="toDetail(i)" @click="toDetail(i)">
>
<view class="flex align-center justify-between mb-28"> <view class="flex align-center justify-between mb-28">
<view class="flex align-center"> <view class="flex align-center">
<view class="sprite-icon" :class="getReportType(i) === 0 ? 'icon-accident' : 'icon-weibao'"> <view class="sprite-icon" :class="getReportType(i) === 0 ? 'icon-accident' : 'icon-weibao'">
...@@ -55,7 +57,7 @@ ...@@ -55,7 +57,7 @@
</view> </view>
<text class="reportTypeName">{{ getReportType(i) === 0 ? '事故报告' : '维保报告' }}</text> <text class="reportTypeName">{{ getReportType(i) === 0 ? '事故报告' : '维保报告' }}</text>
</view> </view>
<text class="reportStatus" :class="['reportStatus' + getStatus(i)]">{{ getStatusText(getStatus(i)) }}</text> <text class="reportStatus" :class="[`reportStatus${ getStatus(i)}`]">{{ getStatusText(getStatus(i)) }}</text>
</view> </view>
<view class="cell flex align-center mb-28"> <view class="cell flex align-center mb-28">
<text class="label">车架号</text> <text class="label">车架号</text>
...@@ -84,7 +86,10 @@ ...@@ -84,7 +86,10 @@
</view> </view>
<!-- 新增报告弹窗 --> <!-- 新增报告弹窗 -->
<PublishPopup ref="publishPopup" type="center" :isShowFooter="false" :showTitle="false"> <PublishPopup ref="publishPopup"
:is-show-footer="false"
:show-title="false"
type="center">
<template #content> <template #content>
<view class="popup-content"> <view class="popup-content">
<view class="popup-top-box flex align-center"> <view class="popup-top-box flex align-center">
...@@ -100,14 +105,18 @@ ...@@ -100,14 +105,18 @@
<text>报告类型</text> <text>报告类型</text>
</view> </view>
<view> <view>
<view class="flex align-start mb-28 tabItem" :class="{ active0: addParams.reportType === 0 }" @click="changeReportType(0)"> <view class="flex align-start mb-28 tabItem"
:class="{ active0: addParams.reportType === 0 }"
@click="changeReportType(0)">
<text class="sprite-icon icon-accident">🚗</text> <text class="sprite-icon icon-accident">🚗</text>
<view> <view>
<text class="title">事故报告</text> <text class="title">事故报告</text>
<text class="desc">含出险,理赔记录</text> <text class="desc">含出险,理赔记录</text>
</view> </view>
</view> </view>
<view class="flex align-start tabItem" :class="{ active1: addParams.reportType === 1 }" @click="changeReportType(1)"> <view class="flex align-start tabItem"
:class="{ active1: addParams.reportType === 1 }"
@click="changeReportType(1)">
<text class="sprite-icon icon-weibao">🔧</text> <text class="sprite-icon icon-weibao">🔧</text>
<view> <view>
<text class="title">维保报告</text> <text class="title">维保报告</text>
...@@ -127,14 +136,12 @@ ...@@ -127,14 +136,12 @@
<text class="required">*</text> <text class="required">*</text>
</view> </view>
<view class="flex vinInput justify-between"> <view class="flex vinInput justify-between">
<input <input v-model="addParams.vin"
:maxlength="17"
v-model="addParams.vin"
class="input flex-1" class="input flex-1"
:maxlength="17"
placeholder="请输入17位VIN" placeholder="请输入17位VIN"
placeholder-class="placeholder" placeholder-class="placeholder"
@blur="vinBlur" @blur="vinBlur" />
/>
<text class="sprite-icon icon-vinScan" @click.stop="scanVin">📷</text> <text class="sprite-icon icon-vinScan" @click.stop="scanVin">📷</text>
</view> </view>
</view> </view>
...@@ -144,7 +151,7 @@ ...@@ -144,7 +151,7 @@
<text class="required">*</text> <text class="required">*</text>
</view> </view>
<view class="img-list flex"> <view class="img-list flex">
<template v-if="imgList.length < 1"> <template v-if="imgList.length === 0">
<view class="img-item upload flex align-center justify-center" @click="chooseImage"> <view class="img-item upload flex align-center justify-center" @click="chooseImage">
<text class="sprite-icon icon-uploadIcon">📤</text> <text class="sprite-icon icon-uploadIcon">📤</text>
<text class="sprite-icon icon-takePhotoIcon">📷</text> <text class="sprite-icon icon-takePhotoIcon">📷</text>
...@@ -152,7 +159,10 @@ ...@@ -152,7 +159,10 @@
</template> </template>
<template v-for="(i, index) in imgList" :key="index"> <template v-for="(i, index) in imgList" :key="index">
<view class="img-item"> <view class="img-item">
<image :src="i" class="img" mode="aspectFill" @click="previewMedia(i)" /> <image class="img"
mode="aspectFill"
:src="i"
@click="previewMedia(i)" />
<view class="del flex" @click="delImage(index)"> <view class="del flex" @click="delImage(index)">
<text style="color: #fff; font-size: 20rpx;">✕</text> <text style="color: #fff; font-size: 20rpx;">✕</text>
</view> </view>
...@@ -162,15 +172,17 @@ ...@@ -162,15 +172,17 @@
</view> </view>
<view class="flex align-center justify-between mt-108"> <view class="flex align-center justify-between mt-108">
<view class="flex align-center"> <view class="flex align-center">
<checkbox <checkbox :checked="isConfirmChecked"
value="cb"
:checked="isConfirmChecked"
@click="checkboxChange"
style="transform: scale(0.6)" style="transform: scale(0.6)"
/> value="cb"
@click="checkboxChange" />
<text class="checkboxLabel">确认信息真实有效</text> <text class="checkboxLabel">确认信息真实有效</text>
</view> </view>
<view :class="['btn flex justify-center', { disabled: !canSubmit }]" @click="comfirm"><text class="btn-text">提交申请</text></view> <view class="btn flex justify-center"
:class="[{ disabled: !canSubmit }]"
@click="comfirm">
<text class="btn-text">提交申请</text>
</view>
</view> </view>
</view> </view>
</view> </view>
...@@ -183,55 +195,58 @@ ...@@ -183,55 +195,58 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ref, computed, onMounted, nextTick, type ComponentPublicInstance } from 'vue'; import type { ComponentPublicInstance } from "vue";
import TypeTabComponent from '@/components/evaluationForm/TypeTabComponent.uvue';
import PublishPopup from '@/components/PublishPopup.uvue'; import { computed, nextTick, onMounted, ref } from "vue";
import { get } from '@/utils/common.uts';
import TypeTabComponent from "@/components/evaluationForm/TypeTabComponent.uvue";
import PublishPopup from "@/components/PublishPopup.uvue";
import { get } from "@/utils/common.uts";
// 类型定义 // 类型定义
type TypeTabItem = { type TypeTabItem = {
tabName: string;
count: number; count: number;
key: string; key: string;
tabName: string;
}; };
type ReportItem = { type ReportItem = {
acquireTime: number;
id: string; id: string;
reportType: number; reportType: number;
vin: string;
acquireTime: number;
status: number; status: number;
vin: string;
}; };
type AddReportParams = { type AddReportParams = {
licenseUrl: string;
reportType: number; reportType: number;
vin: string; vin: string;
licenseUrl: string;
}; };
// 常量 // 常量
const ORDER_STATUS = { const ORDER_STATUS = {
'0': '待审核', "0": "待审核",
'1': '已通过', "1": "已通过",
'2': '已拒绝', "2": "已拒绝",
'3': '已完成' "3": "已完成"
}; };
// 响应式数据 // 响应式数据
const typeList = ref<TypeTabItem[]>([ const typeList = ref<TypeTabItem[]>([
{ tabName: '全部', count: 0, key: '' }, { tabName: "全部", count: 0, key: "" },
{ tabName: '事故报告', count: 0, key: '0' }, { tabName: "事故报告", count: 0, key: "0" },
{ tabName: '维保报告', count: 0, key: '1' } { tabName: "维保报告", count: 0, key: "1" }
]); ]);
const tabIndex = ref<number>(0); const tabIndex = ref<number>(0);
const searchText = ref<string>(''); const searchText = ref<string>("");
const focusIndex = ref<number>(-1); const focusIndex = ref<number>(-1);
const list = ref<any[]>([]); const list = ref<any[]>([]);
const addParams = ref<AddReportParams>({ const addParams = ref<AddReportParams>({
reportType: 0, reportType: 0,
vin: '', vin: "",
licenseUrl: '' licenseUrl: ""
}); });
const imgList = ref<string[]>([]); const imgList = ref<string[]>([]);
const isConfirmChecked = ref<boolean>(false); const isConfirmChecked = ref<boolean>(false);
...@@ -241,57 +256,56 @@ const publishPopup = ref<ComponentPublicInstance | null>(null); ...@@ -241,57 +256,56 @@ const publishPopup = ref<ComponentPublicInstance | null>(null);
// Mock 数据 // Mock 数据
const mockData: ReportItem[] = [ const mockData: ReportItem[] = [
{ {
id: '1', id: "1",
reportType: 0, reportType: 0,
vin: 'SALWA2BU6LA713964', vin: "SALWA2BU6LA713964",
acquireTime: Date.now() - 86400000, acquireTime: Date.now() - 86_400_000,
status: 0 status: 0
}, },
{ {
id: '2', id: "2",
reportType: 1, reportType: 1,
vin: 'WDC0J6EB6KF571271', vin: "WDC0J6EB6KF571271",
acquireTime: Date.now() - 172800000, acquireTime: Date.now() - 172_800_000,
status: 1 status: 1
}, },
{ {
id: '3', id: "3",
reportType: 0, reportType: 0,
vin: 'LFMCM1CX9L0095398', vin: "LFMCM1CX9L0095398",
acquireTime: Date.now() - 259200000, acquireTime: Date.now() - 259_200_000,
status: 3 status: 3
}, },
{ {
id: '4', id: "4",
reportType: 0, reportType: 0,
vin: 'LFMCM1CX9L0095398', vin: "LFMCM1CX9L0095398",
acquireTime: Date.now() - 259200000, acquireTime: Date.now() - 259_200_000,
status: 3 status: 3
}, },
{ {
id: '5', id: "5",
reportType: 0, reportType: 0,
vin: 'LFMCM1CX9L0095398', vin: "LFMCM1CX9L0095398",
acquireTime: Date.now() - 259200000, acquireTime: Date.now() - 259_200_000,
status: 3 status: 3
}, },
{ {
id: '6', id: "6",
reportType: 0, reportType: 0,
vin: 'LFMCM1CX9L0095398', vin: "LFMCM1CX9L0095398",
acquireTime: Date.now() - 259200000, acquireTime: Date.now() - 259_200_000,
status: 3 status: 3
} }
]; ];
// 根据 mockData 计算各类型数量,保证 tab count 与实际数据一致 // 根据 mockData 计算各类型数量,保证 tab count 与实际数据一致
const updateTypeCount = () => { const updateTypeCount = () => {
let all = mockData.length; const all = mockData.length;
let accident = 0; let accident = 0;
let weibo = 0; let weibo = 0;
for (let i = 0; i < mockData.length; i++) { for (const item of mockData) {
const item = mockData[i];
if (item.reportType == 0) { if (item.reportType == 0) {
accident = accident + 1; accident = accident + 1;
} else if (item.reportType == 1) { } else if (item.reportType == 1) {
...@@ -301,12 +315,10 @@ const updateTypeCount = () => { ...@@ -301,12 +315,10 @@ const updateTypeCount = () => {
// 避免 UTS 推断为 UTSArray<UTSJSONObject>,显式构造 TypeTabItem[] 再赋值 // 避免 UTS 推断为 UTSArray<UTSJSONObject>,显式构造 TypeTabItem[] 再赋值
const newList: TypeTabItem[] = []; const newList: TypeTabItem[] = [];
newList.push({ tabName: '全部', count: all, key: '' }); newList.push({ tabName: "全部", count: all, key: "" }, { tabName: "事故报告", count: accident, key: "0" }, { tabName: "维保报告", count: weibo, key: "1" });
newList.push({ tabName: '事故报告', count: accident, key: '0' });
newList.push({ tabName: '维保报告', count: weibo, key: '1' });
typeList.value = newList; typeList.value = newList;
console.log('[updateTypeCount]', { console.log("[updateTypeCount]", {
all, all,
accident, accident,
weibo, weibo,
...@@ -317,7 +329,7 @@ const updateTypeCount = () => { ...@@ -317,7 +329,7 @@ const updateTypeCount = () => {
// 计算属性 // 计算属性
const canSubmit = computed<boolean>(() => { const canSubmit = computed<boolean>(() => {
return addParams.value.vin !== '' && imgList.value.length > 0 && isConfirmChecked.value; return addParams.value.vin !== "" && imgList.value.length > 0 && isConfirmChecked.value;
}); });
// 辅助方法:安全访问 any 类型的属性 // 辅助方法:安全访问 any 类型的属性
...@@ -339,11 +351,11 @@ const getAcquireTime = (item: any): number => { ...@@ -339,11 +351,11 @@ const getAcquireTime = (item: any): number => {
// 获取状态文本 // 获取状态文本
const getStatusText = (status: number): string => { const getStatusText = (status: number): string => {
if (status == 0) return '待审核'; if (status == 0) return "待审核";
if (status == 1) return '已通过'; if (status == 1) return "已通过";
if (status == 2) return '已拒绝'; if (status == 2) return "已拒绝";
if (status == 3) return '已完成'; if (status == 3) return "已完成";
return '未知'; return "未知";
}; };
// z-paging-x 加载数据(本地 mock) // z-paging-x 加载数据(本地 mock)
...@@ -372,20 +384,20 @@ const getCheckReportPageList = (pageNo: number, pageSize: number) => { ...@@ -372,20 +384,20 @@ const getCheckReportPageList = (pageNo: number, pageSize: number) => {
const end = start + pageSize; const end = start + pageSize;
const pageData = filteredData.slice(start, end); const pageData = filteredData.slice(start, end);
console.log('[getCheckReportPageList]', { console.log("[getCheckReportPageList]", {
pageNo, pageNo,
pageSize, pageSize,
tabIndex: tabIndex.value, tabIndex: tabIndex.value,
filteredDataLength: filteredData.length, filteredDataLength: filteredData.length,
pageDataLength: pageData.length, pageDataLength: pageData.length,
pageData: pageData pageData
}); });
// 将请求结果通过 complete 传给 z-paging-x 处理,同时也代表请求结束,这一行必须调用 // 将请求结果通过 complete 传给 z-paging-x 处理,同时也代表请求结束,这一行必须调用
// 按照文档:(this.$refs['pagingX'] as ZPagingXComponentPublicInstance).complete(res['data'] as any[]) // 按照文档:(this.$refs['pagingX'] as ZPagingXComponentPublicInstance).complete(res['data'] as any[])
// 在 uni-app x Composition API 中,使用 $callMethod 调用组件方法 // 在 uni-app x Composition API 中,使用 $callMethod 调用组件方法
if (paging.value != null) { if (paging.value != null) {
paging.value.$callMethod('complete', pageData as any[]); paging.value.$callMethod("complete", pageData as any[]);
// (this.$refs['pagingX'] as ZPagingXComponentPublicInstance).complete(pageData as any[]) // (this.$refs['pagingX'] as ZPagingXComponentPublicInstance).complete(pageData as any[])
} }
}, 300); }, 300);
...@@ -394,13 +406,13 @@ const getCheckReportPageList = (pageNo: number, pageSize: number) => { ...@@ -394,13 +406,13 @@ const getCheckReportPageList = (pageNo: number, pageSize: number) => {
// 查询 // 查询
const search = () => { const search = () => {
if (paging.value != null) { if (paging.value != null) {
paging.value.$callMethod('reload'); paging.value.$callMethod("reload");
} }
}; };
// 重置 // 重置
const reset = () => { const reset = () => {
searchText.value = ''; searchText.value = "";
search(); search();
}; };
...@@ -416,7 +428,7 @@ const toDetail = (item: any) => { ...@@ -416,7 +428,7 @@ const toDetail = (item: any) => {
const reportItem = item as ReportItem; const reportItem = item as ReportItem;
uni.showToast({ uni.showToast({
title: `查看报告: ${reportItem.vin}`, title: `查看报告: ${reportItem.vin}`,
icon: 'none' icon: "none"
}); });
}; };
...@@ -424,10 +436,10 @@ const toDetail = (item: any) => { ...@@ -424,10 +436,10 @@ const toDetail = (item: any) => {
const formatTime = (timestamp: number): string => { const formatTime = (timestamp: number): string => {
const date = new Date(timestamp); const date = new Date(timestamp);
const year = date.getFullYear(); const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0'); const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, "0");
const hours = date.getHours().toString().padStart(2, '0'); const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}`; return `${year}-${month}-${day} ${hours}:${minutes}`;
}; };
...@@ -439,29 +451,29 @@ const resetFocusIndex = () => { ...@@ -439,29 +451,29 @@ const resetFocusIndex = () => {
// 扫描识别 // 扫描识别
const scan = () => { const scan = () => {
uni.showToast({ uni.showToast({
title: 'VIN识别功能待实现', title: "VIN识别功能待实现",
icon: 'none' icon: "none"
}); });
}; };
const scanVin = () => { const scanVin = () => {
uni.showToast({ uni.showToast({
title: 'VIN识别功能待实现', title: "VIN识别功能待实现",
icon: 'none' icon: "none"
}); });
}; };
// 打开弹窗 // 打开弹窗
const openShowPopup = () => { const openShowPopup = () => {
if (publishPopup.value != null) { if (publishPopup.value != null) {
publishPopup.value.$callMethod('openPopup'); publishPopup.value.$callMethod("openPopup");
} }
}; };
// 关闭弹窗 // 关闭弹窗
const closePublishPopup = () => { const closePublishPopup = () => {
if (publishPopup.value != null) { if (publishPopup.value != null) {
publishPopup.value.$callMethod('closePopup'); publishPopup.value.$callMethod("closePopup");
} }
}; };
...@@ -473,10 +485,10 @@ const changeReportType = (type: number) => { ...@@ -473,10 +485,10 @@ const changeReportType = (type: number) => {
// VIN输入验证 // VIN输入验证
const vinBlur = () => { const vinBlur = () => {
const vin = addParams.value.vin; const vin = addParams.value.vin;
if (vin != '' && vin.length != 17) { if (vin != "" && vin.length != 17) {
uni.showToast({ uni.showToast({
title: 'VIN码必须为17位', title: "VIN码必须为17位",
icon: 'none' icon: "none"
}); });
} }
}; };
...@@ -486,8 +498,8 @@ const chooseImage = () => { ...@@ -486,8 +498,8 @@ const chooseImage = () => {
uni.chooseImage({ uni.chooseImage({
count: 1, count: 1,
success: (res: any) => { success: (res: any) => {
const tempFilePaths = get(res, 'tempFilePaths'); const tempFilePaths = get(res, "tempFilePaths");
if (tempFilePaths != null && tempFilePaths instanceof Array) { if (tempFilePaths != null && Array.isArray(tempFilePaths)) {
const paths = tempFilePaths as string[]; const paths = tempFilePaths as string[];
if (paths.length > 0) { if (paths.length > 0) {
imgList.value.push(paths[0]); imgList.value.push(paths[0]);
...@@ -520,14 +532,14 @@ const comfirm = () => { ...@@ -520,14 +532,14 @@ const comfirm = () => {
if (!canSubmit.value) return; if (!canSubmit.value) return;
uni.showToast({ uni.showToast({
title: '提交成功(模拟)', title: "提交成功(模拟)",
icon: 'success' icon: "success"
}); });
addParams.value = { addParams.value = {
reportType: 0, reportType: 0,
vin: '', vin: "",
licenseUrl: '' licenseUrl: ""
} as AddReportParams; } as AddReportParams;
imgList.value = []; imgList.value = [];
isConfirmChecked.value = false; isConfirmChecked.value = false;
...@@ -542,7 +554,7 @@ onMounted(() => { ...@@ -542,7 +554,7 @@ onMounted(() => {
// 首次进入页面主动触发一次加载,避免必须点"查询"才看到列表 // 首次进入页面主动触发一次加载,避免必须点"查询"才看到列表
nextTick(() => { nextTick(() => {
if (paging.value != null) { if (paging.value != null) {
paging.value.$callMethod('reload'); paging.value.$callMethod("reload");
} }
}); });
// TODO: 将来接入 uni.$track // TODO: 将来接入 uni.$track
......
<template> <template>
<scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50"> <scroll-view class="flex flex-col bg-gray-50"
scroll-y="true"
style="flex: 1">
<view class="flex flex-col px-5 py-5"> <view class="flex flex-col px-5 py-5">
<!-- 标题区域 --> <!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg"> <view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
...@@ -9,11 +11,9 @@ ...@@ -9,11 +11,9 @@
<!-- 权限列表 --> <!-- 权限列表 -->
<view class="flex flex-col"> <view class="flex flex-col">
<view <view v-for="permission in permissions"
v-for="permission in permissions"
:key="permission.name" :key="permission.name"
class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col" class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col">
>
<!-- 权限名称和状态 --> <!-- 权限名称和状态 -->
<view class="flex flex-row items-center justify-between mb-3"> <view class="flex flex-row items-center justify-between mb-3">
<view class="flex flex-row items-center"> <view class="flex flex-row items-center">
...@@ -23,11 +23,9 @@ ...@@ -23,11 +23,9 @@
<text class="text-sm text-gray-500 block">{{ permission.desc }}</text> <text class="text-sm text-gray-500 block">{{ permission.desc }}</text>
</view> </view>
</view> </view>
<view <view class="px-3 py-1 rounded-full"
class="px-3 py-1 rounded-full" :class="`status-${ permission.status}`">
:class="'status-' + permission.status" <text class="text-xs font-medium" :class="`status-text-${ permission.status}`">
>
<text class="text-xs font-medium" :class="'status-text-' + permission.status">
{{ getStatusText(permission.status) }} {{ getStatusText(permission.status) }}
</text> </text>
</view> </view>
...@@ -35,17 +33,13 @@ ...@@ -35,17 +33,13 @@
<!-- 操作按钮 --> <!-- 操作按钮 -->
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button <button class="btn btn-primary mr-2 mb-2"
class="btn btn-primary mr-2 mb-2" @click="checkPermission(permission)">
@click="checkPermission(permission)"
>
检查权限 检查权限
</button> </button>
<button <button class="btn btn-success mr-2 mb-2"
class="btn btn-success mr-2 mb-2"
@click="requestPermission(permission)"
:disabled="permission.status === 'granted'" :disabled="permission.status === 'granted'"
> @click="requestPermission(permission)">
申请权限 申请权限
</button> </button>
</view> </view>
...@@ -55,19 +49,17 @@ ...@@ -55,19 +49,17 @@
<!-- 操作日志 --> <!-- 操作日志 -->
<view class="bg-white rounded-lg p-4 shadow-sm mt-4 flex-col"> <view class="bg-white rounded-lg p-4 shadow-sm mt-4 flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text> <text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text>
<scroll-view style="max-height: 300px" scroll-y="true" class="flex flex-col"> <scroll-view class="flex flex-col"
<view scroll-y="true"
v-for="(log, index) in logs" style="max-height: 300px">
<view v-for="(log, index) in logs"
:key="index" :key="index"
class="mb-2 pb-2 border-b border-gray-200" class="mb-2 pb-2 border-b border-gray-200">
>
<text class="text-sm text-gray-600 block">{{ log }}</text> <text class="text-sm text-gray-600 block">{{ log }}</text>
</view> </view>
</scroll-view> </scroll-view>
<button <button class="btn btn-secondary mt-3"
class="btn btn-secondary mt-3" @click="clearLogs">
@click="clearLogs"
>
清空日志 清空日志
</button> </button>
</view> </view>
...@@ -78,16 +70,15 @@ ...@@ -78,16 +70,15 @@
<script setup lang="uts"> <script setup lang="uts">
// 统一导入,编译器会自动根据平台选择对应的实现 // 统一导入,编译器会自动根据平台选择对应的实现
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus"; import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { get } from "@/utils/common.uts"; import { get } from "@/utils/common.uts";
type PermissionStatus = "unknown" | "granted" | "denied" | "restricted" | "limited" | "permanentlyDenied" | "provisional"; type PermissionStatus = "denied" | "granted" | "limited" | "permanentlyDenied" | "provisional" | "restricted" | "unknown";
type Permission = { type Permission = {
name: string;
displayName: string;
desc: string; desc: string;
displayName: string;
icon: string; icon: string;
name: string;
status: PermissionStatus; status: PermissionStatus;
}; };
...@@ -187,7 +178,7 @@ const checkPermission = (permission: Permission) => { ...@@ -187,7 +178,7 @@ const checkPermission = (permission: Permission) => {
// 更新权限状态 // 更新权限状态
const index = permissions.value.findIndex((p) => p.name == permission.name); const index = permissions.value.findIndex((p) => p.name == permission.name);
if (index >= 0) { if (index !== -1) {
// 将插件返回的状态字符串转换为我们的状态类型 // 将插件返回的状态字符串转换为我们的状态类型
let status: PermissionStatus = "unknown"; let status: PermissionStatus = "unknown";
if (result == "granted") { if (result == "granted") {
...@@ -229,7 +220,7 @@ const requestPermission = (permission: Permission) => { ...@@ -229,7 +220,7 @@ const requestPermission = (permission: Permission) => {
// 更新权限状态 // 更新权限状态
const index = permissions.value.findIndex((p) => p.name == permission.name); const index = permissions.value.findIndex((p) => p.name == permission.name);
if (index >= 0) { if (index !== -1) {
let status: PermissionStatus = "unknown"; let status: PermissionStatus = "unknown";
if (statusStr == "granted") { if (statusStr == "granted") {
status = "granted"; status = "granted";
......
<template> <template>
<scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50"> <scroll-view class="flex flex-col bg-gray-50"
scroll-y="true"
style="flex: 1">
<view class="flex flex-col px-5 py-5"> <view class="flex flex-col px-5 py-5">
<!-- 标题区域 --> <!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg"> <view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
...@@ -14,10 +16,8 @@ ...@@ -14,10 +16,8 @@
<text class="text-base font-semibold text-yellow-800 block">需要麦克风权限</text> <text class="text-base font-semibold text-yellow-800 block">需要麦克风权限</text>
</view> </view>
<text class="text-sm text-yellow-700 mb-3 block">录音功能需要访问您的麦克风,请先授予权限。</text> <text class="text-sm text-yellow-700 mb-3 block">录音功能需要访问您的麦克风,请先授予权限。</text>
<button <button class="btn btn-warning"
class="btn btn-warning" @click="requestRecordPermission">
@click="requestRecordPermission"
>
申请麦克风权限 申请麦克风权限
</button> </button>
</view> </view>
...@@ -26,17 +26,13 @@ ...@@ -26,17 +26,13 @@
<view class="bg-white rounded-lg p-4 shadow-sm flex-col mb-4"> <view class="bg-white rounded-lg p-4 shadow-sm flex-col mb-4">
<text class="text-lg font-semibold text-gray-800 mb-3 block">录音控制</text> <text class="text-lg font-semibold text-gray-800 mb-3 block">录音控制</text>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button <button class="btn btn-primary mr-2 mb-2"
class="btn btn-primary mr-2 mb-2"
@click="startRecord"
:disabled="!hasPermission" :disabled="!hasPermission"
> @click="startRecord">
开始录音 开始录音
</button> </button>
<button <button class="btn btn-secondary mr-2 mb-2"
class="btn btn-secondary mr-2 mb-2" @click="stopRecord">
@click="stopRecord"
>
停止录音 停止录音
</button> </button>
</view> </view>
...@@ -52,21 +48,17 @@ ...@@ -52,21 +48,17 @@
<text v-if="recordList.length > 0" class="text-sm text-gray-500">({{ recordList.length }} 条)</text> <text v-if="recordList.length > 0" class="text-sm text-gray-500">({{ recordList.length }} 条)</text>
</text> </text>
<view v-if="recordList.length == 0" class="flex flex-row items-center"> <view v-if="recordList.length === 0" class="flex flex-row items-center">
<text class="text-sm text-gray-500 block">暂无录音,先录一段试试吧~</text> <text class="text-sm text-gray-500 block">暂无录音,先录一段试试吧~</text>
</view> </view>
<scroll-view <scroll-view v-else
v-else
style="max-height: 400px"
scroll-y="true"
class="flex flex-col" class="flex flex-col"
> scroll-y="true"
<view style="max-height: 400px">
v-for="record in recordList" <view v-for="record in recordList"
:key="record.id" :key="record.id"
class="flex flex-col mb-3 pb-3 border-b border-gray-200" class="flex flex-col mb-3 pb-3 border-b border-gray-200">
>
<!-- 录音信息 --> <!-- 录音信息 -->
<view class="flex flex-row items-center justify-between mb-2"> <view class="flex flex-row items-center justify-between mb-2">
<view class="flex flex-col"> <view class="flex flex-col">
...@@ -75,24 +67,18 @@ ...@@ -75,24 +67,18 @@
<text class="text-xs text-gray-500 block">时间: {{ formatTime(record.createTime) }}</text> <text class="text-xs text-gray-500 block">时间: {{ formatTime(record.createTime) }}</text>
</view> </view>
<view class="flex flex-row"> <view class="flex flex-row">
<button <button v-if="!record.isPlaying"
v-if="!record.isPlaying"
class="btn btn-primary mr-2" class="btn btn-primary mr-2"
@click="playRecord(record)" @click="playRecord(record)">
>
播放 播放
</button> </button>
<button <button v-else
v-else
class="btn btn-secondary mr-2" class="btn btn-secondary mr-2"
@click="stopPlay(record)" @click="stopPlay(record)">
>
停止 停止
</button> </button>
<button <button class="btn btn-danger"
class="btn btn-danger" @click="deleteRecord(record)">
@click="deleteRecord(record)"
>
删除 删除
</button> </button>
</view> </view>
...@@ -106,19 +92,17 @@ ...@@ -106,19 +92,17 @@
<!-- 操作日志 --> <!-- 操作日志 -->
<view class="bg-white rounded-lg p-4 shadow-sm flex-col"> <view class="bg-white rounded-lg p-4 shadow-sm flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text> <text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text>
<scroll-view style="max-height: 300px" scroll-y="true" class="flex flex-col"> <scroll-view class="flex flex-col"
<view scroll-y="true"
v-for="(log, index) in logs" style="max-height: 300px">
<view v-for="(log, index) in logs"
:key="index" :key="index"
class="mb-2 pb-2 border-b border-gray-200" class="mb-2 pb-2 border-b border-gray-200">
>
<text class="text-sm text-gray-600 block">{{ log }}</text> <text class="text-sm text-gray-600 block">{{ log }}</text>
</view> </view>
</scroll-view> </scroll-view>
<button <button class="btn btn-secondary mt-3"
class="btn btn-secondary mt-3" @click="clearLogs">
@click="clearLogs"
>
清空日志 清空日志
</button> </button>
</view> </view>
...@@ -127,19 +111,19 @@ ...@@ -127,19 +111,19 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { import {
startRecord as uniStartRecord, startRecord as uniStartRecord,
stopRecord as uniStopRecord stopRecord as uniStopRecord
} from "@/uni_modules/uts-recorder"; } from "@/uni_modules/uts-recorder";
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { get } from "@/utils/common.uts"; import { get } from "@/utils/common.uts";
// 录音文件信息类型 // 录音文件信息类型
type RecordFileInfo = { type RecordFileInfo = {
id: string;
filePath: string;
duration: number;
createTime: number; createTime: number;
duration: number;
filePath: string;
id: string;
isPlaying: boolean; isPlaying: boolean;
}; };
...@@ -171,7 +155,7 @@ const checkRecordPermission = () => { ...@@ -171,7 +155,7 @@ const checkRecordPermission = () => {
hasPermission.value = status == "granted"; hasPermission.value = status == "granted";
addLog(`当前麦克风权限状态: ${status}`); addLog(`当前麦克风权限状态: ${status}`);
}); });
} };
// 申请录音权限 // 申请录音权限
const requestRecordPermission = () => { const requestRecordPermission = () => {
...@@ -184,7 +168,7 @@ const requestRecordPermission = () => { ...@@ -184,7 +168,7 @@ const requestRecordPermission = () => {
// result 是一个 Map<string, string> // result 是一个 Map<string, string>
// 使用 get() 辅助函数访问 Map // 使用 get() 辅助函数访问 Map
const micStatus = get(result, "Microphone") as string | null; const micStatus = get(result, "Microphone") as null | string;
if (micStatus != null) { if (micStatus != null) {
const granted = micStatus == "granted"; const granted = micStatus == "granted";
hasPermission.value = granted; hasPermission.value = granted;
...@@ -213,7 +197,7 @@ const requestRecordPermission = () => { ...@@ -213,7 +197,7 @@ const requestRecordPermission = () => {
}); });
} }
}); });
} };
// 开始录音 - 使用标准 uni API 模式 // 开始录音 - 使用标准 uni API 模式
const startRecord = () => { const startRecord = () => {
...@@ -345,7 +329,7 @@ const stopPlay = (record: RecordFileInfo) => { ...@@ -345,7 +329,7 @@ const stopPlay = (record: RecordFileInfo) => {
const deleteRecord = (record: RecordFileInfo) => { const deleteRecord = (record: RecordFileInfo) => {
// 从列表中移除 // 从列表中移除
const index = recordList.value.findIndex(item => item.id == record.id); const index = recordList.value.findIndex(item => item.id == record.id);
if (index > -1) { if (index !== -1) {
recordList.value.splice(index, 1); recordList.value.splice(index, 1);
addLog(`已删除录音,剩余 ${recordList.value.length} 条`); addLog(`已删除录音,剩余 ${recordList.value.length} 条`);
} }
...@@ -356,15 +340,15 @@ const formatDuration = (ms: number): string => { ...@@ -356,15 +340,15 @@ const formatDuration = (ms: number): string => {
const seconds = Math.floor(ms / 1000); const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60); const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60; const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`; return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
}; };
// 格式化时间 // 格式化时间
const formatTime = (timestamp: number): string => { const formatTime = (timestamp: number): string => {
const date = new Date(timestamp); const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0'); const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, '0'); const seconds = date.getSeconds().toString().padStart(2, "0");
return `${hours}:${minutes}:${seconds}`; return `${hours}:${minutes}:${seconds}`;
}; };
......
<template> <template>
<!-- #ifdef APP --> <!-- #ifdef APP -->
<scroll-view style="flex: 1" class="min-h-screen bg-gray-50"> <scroll-view class="min-h-screen bg-gray-50" style="flex: 1">
<!-- #endif --> <!-- #endif -->
<!-- #ifndef APP --> <!-- #ifndef APP -->
<view class="min-h-screen bg-gray-50"> <view class="min-h-screen bg-gray-50">
...@@ -128,16 +128,32 @@ ...@@ -128,16 +128,32 @@
<view class="bg-white rounded-lg p-4 shadow-sm"> <view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">按钮样式</text> <text class="text-lg font-semibold text-gray-800 mb-4 block">按钮样式</text>
<view class="flex flex-wrap gap-3"> <view class="flex flex-wrap gap-3">
<button class="px-6 py-3 rounded-lg font-medium text-white bg-blue-500 active:bg-blue-600">Primary</button> <button class="px-6 py-3 rounded-lg font-medium text-white bg-blue-500 active:bg-blue-600">
<button class="px-6 py-3 rounded-lg font-medium text-white bg-gray-500 active:bg-gray-600">Secondary</button> Primary
<button class="px-6 py-3 rounded-lg font-medium text-white bg-green-500 active:bg-green-600">Success</button> </button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-red-500 active:bg-red-600">Danger</button> <button class="px-6 py-3 rounded-lg font-medium text-white bg-gray-500 active:bg-gray-600">
<button class="px-6 py-3 rounded-lg font-medium text-white bg-yellow-500 active:bg-yellow-600">Warning</button> Secondary
<button class="px-6 py-3 rounded-lg font-medium text-white bg-purple-500 active:bg-purple-600">Info</button> </button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-green-500 active:bg-green-600">
Success
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-red-500 active:bg-red-600">
Danger
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-yellow-500 active:bg-yellow-600">
Warning
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-purple-500 active:bg-purple-600">
Info
</button>
</view> </view>
<view class="mt-3 flex flex-wrap gap-3"> <view class="mt-3 flex flex-wrap gap-3">
<button class="px-4 py-2 rounded text-sm font-medium text-white bg-blue-500 active:bg-blue-600">Small</button> <button class="px-4 py-2 rounded text-sm font-medium text-white bg-blue-500 active:bg-blue-600">
<button class="px-8 py-4 rounded-lg text-lg font-medium text-white bg-blue-500 active:bg-blue-600">Large</button> Small
</button>
<button class="px-8 py-4 rounded-lg text-lg font-medium text-white bg-blue-500 active:bg-blue-600">
Large
</button>
</view> </view>
</view> </view>
...@@ -150,7 +166,9 @@ ...@@ -150,7 +166,9 @@
<text class="text-gray-600 text-sm leading-relaxed block">这是一个使用 Tailwind CSS 构建的卡片组件,展示了阴影、圆角、间距等样式。weapp-tailwindcss 会自动将 Tailwind 类名转换为对应平台的样式。</text> <text class="text-gray-600 text-sm leading-relaxed block">这是一个使用 Tailwind CSS 构建的卡片组件,展示了阴影、圆角、间距等样式。weapp-tailwindcss 会自动将 Tailwind 类名转换为对应平台的样式。</text>
</view> </view>
<view class="px-4 py-3 bg-gray-50 border-t border-gray-200 flex justify-end"> <view class="px-4 py-3 bg-gray-50 border-t border-gray-200 flex justify-end">
<button class="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded active:bg-blue-600">操作</button> <button class="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded active:bg-blue-600">
操作
</button>
</view> </view>
</view> </view>
...@@ -245,10 +263,18 @@ ...@@ -245,10 +263,18 @@
</view> </view>
</view> </view>
<view class="mt-4 flex flex-wrap gap-3"> <view class="mt-4 flex flex-wrap gap-3">
<view class="px-4 py-2 border-2 border-blue-500 rounded">border-2</view> <view class="px-4 py-2 border-2 border-blue-500 rounded">
<view class="px-4 py-2 border-4 border-green-500 rounded">border-4</view> border-2
<view class="px-4 py-2 border-l-4 border-purple-500 rounded">border-l-4</view> </view>
<view class="px-4 py-2 border-t-4 border-red-500 rounded">border-t-4</view> <view class="px-4 py-2 border-4 border-green-500 rounded">
border-4
</view>
<view class="px-4 py-2 border-l-4 border-purple-500 rounded">
border-l-4
</view>
<view class="px-4 py-2 border-t-4 border-red-500 rounded">
border-t-4
</view>
</view> </view>
</view> </view>
...@@ -349,6 +375,7 @@ ...@@ -349,6 +375,7 @@
</view> </view>
</view> </view>
<!-- #ifdef APP --> <!-- #ifdef APP -->
</view>
</scroll-view> </scroll-view>
<!-- #endif --> <!-- #endif -->
<!-- #ifndef APP --> <!-- #ifndef APP -->
......
<template> <template>
<scroll-view style="flex: 1" class="flex flex-col bg-indigo-500"> <scroll-view class="flex flex-col bg-indigo-500" style="flex: 1">
<view class="flex flex-col"> <view class="flex flex-col">
<view class="flex flex-col"> <view class="flex flex-col">
<view class="flex flex-col px-8 pt-10 pb-8 items-center"> <view class="flex flex-col px-8 pt-10 pb-8 items-center">
...@@ -8,31 +8,25 @@ ...@@ -8,31 +8,25 @@
</view> </view>
<view class="flex flex-col px-12 py-12 flex-1 bg-gray-50 rounded-t-3xl"> <view class="flex flex-col px-12 py-12 flex-1 bg-gray-50 rounded-t-3xl">
<view <view v-for="item in data"
:key="item.label + item.path"
class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full" class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full"
:class="{ 'card-pressed': isCardPressed(item.path) }" :class="{ 'card-pressed': isCardPressed(item.path) }"
@touchstart="handleTouchStart(item.path)"
@touchend="pressedCard = ''"
@tap="toPath(item)" @tap="toPath(item)"
v-for="item in data" @touchend="pressedCard = ''"
:key="item.label + item.path" @touchstart="handleTouchStart(item.path)">
>
<!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 --> <!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 -->
<view class="flex flex-row items-center p-5 w-full"> <view class="flex flex-row items-center p-5 w-full">
<view class="flex flex-row items-center"> <view class="flex flex-row items-center">
<view <view class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4">
class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4"
>
<text class="text-2xl">{{ getIcon(item.icon) }}</text> <text class="text-2xl">{{ getIcon(item.icon) }}</text>
</view> </view>
<text class="text-lg font-semibold text-gray-800"> <text class="text-lg font-semibold text-gray-800">
{{ item.label }} {{ item.label }}
</text> </text>
</view> </view>
<view <view class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0"
class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0" style="margin-left: auto">
style="margin-left: auto"
>
<text class="text-lg text-white font-bold">→</text> <text class="text-lg text-white font-bold">→</text>
</view> </view>
</view> </view>
...@@ -48,12 +42,12 @@ import { get } from "@/utils/common.uts"; ...@@ -48,12 +42,12 @@ import { get } from "@/utils/common.uts";
// import { router } from "@/utils/router.uts"; // import { router } from "@/utils/router.uts";
type Item = { type Item = {
label: string; children?: Item[];
icon?: string;
path?: string;
disabled?: boolean; disabled?: boolean;
hidden?: boolean; hidden?: boolean;
children?: Item[]; icon?: string;
label: string;
path?: string;
}; };
const data = computed<Item[]>(() => { const data = computed<Item[]>(() => {
...@@ -134,8 +128,8 @@ const toPath = (item: Item) => { ...@@ -134,8 +128,8 @@ const toPath = (item: Item) => {
// 使用索引访问属性,避免 error18 // 使用索引访问属性,避免 error18
// NavigateToFailImpl 类型特殊,需要先转换为 UTSJSONObject 或使用索引访问 // NavigateToFailImpl 类型特殊,需要先转换为 UTSJSONObject 或使用索引访问
let errMsg = "未知错误"; let errMsg = "未知错误";
let errCode: number | null = null; let errCode: null | number = null;
let errSubject: string | null = null; let errSubject: null | string = null;
// 尝试使用 UTSJSONObject 转换 // 尝试使用 UTSJSONObject 转换
try { try {
...@@ -154,7 +148,7 @@ const toPath = (item: Item) => { ...@@ -154,7 +148,7 @@ const toPath = (item: Item) => {
if (errSubjectTemp != null) { if (errSubjectTemp != null) {
errSubject = errSubjectTemp as string; errSubject = errSubjectTemp as string;
} }
} catch (e: any) { } catch {
// 如果转换失败,尝试使用 JSON 序列化/反序列化 // 如果转换失败,尝试使用 JSON 序列化/反序列化
try { try {
const jsonStr = JSON.stringify(err); const jsonStr = JSON.stringify(err);
...@@ -172,8 +166,8 @@ const toPath = (item: Item) => { ...@@ -172,8 +166,8 @@ const toPath = (item: Item) => {
if (errSubjectTemp != null) { if (errSubjectTemp != null) {
errSubject = errSubjectTemp as string; errSubject = errSubjectTemp as string;
} }
} catch (e2: any) { } catch (error: any) {
console.error("无法解析错误对象:", e2); console.error("无法解析错误对象:", error);
} }
} }
......
const path = require("node:path");
const { r } = require("./shared"); const { r } = require("./shared");
const path = require("path");
// 确保能找到 tailwindcss-rem2px-preset 模块 // 确保能找到 tailwindcss-rem2px-preset 模块
// 使用 resolve 来查找模块路径,支持不同的工作目录 // 使用 resolve 来查找模块路径,支持不同的工作目录
......
...@@ -2,19 +2,19 @@ ...@@ -2,19 +2,19 @@
"extends": "@vue/tsconfig/tsconfig.json", "extends": "@vue/tsconfig/tsconfig.json",
"compilerOptions": { "compilerOptions": {
"ignoreDeprecations": "5.0", "ignoreDeprecations": "5.0",
"verbatimModuleSyntax": true,
"experimentalDecorators": true,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"noImplicitAny": false,
"types": ["@dcloudio/types", "vue"],
"lib": ["esnext", "dom"], "lib": ["esnext", "dom"],
"outDir": "esbuild", "experimentalDecorators": true,
"paths": { "paths": {
"@/*": ["./src/*"], "@/*": ["./src/*"],
"$/*": ["./uni_modules/*"] "$/*": ["./uni_modules/*"]
} },
"resolveJsonModule": true,
"types": ["@dcloudio/types", "vue"],
"noImplicitAny": false,
"outDir": "esbuild",
"sourceMap": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true
}, },
"vueCompilerOptions": { "vueCompilerOptions": {
"extensions": [".vue", ".uvue"] "extensions": [".vue", ".uvue"]
......
export type UserInfo = { export type UserInfo = {
unionid: string; // 用户唯一id
id: number; // 用户id
nickName: string; // 昵称
avatarUrl?: string; // 头像 avatarUrl?: string; // 头像
phone: string; // 手机号 birthday?: string; // 生日
gender: number; // 性别 city?: string; // 城市
status: number; // 状态 createTime: string; // 创建时间
description?: string; // 描述 description?: string; // 描述
district?: string; // 区县
gender: number; // 性别
id: number; // 用户id
loginType: number; // 登录类型 loginType: number; // 登录类型
nickName: string; // 昵称
phone: string; // 手机号
province?: string; // 省份 province?: string; // 省份
city?: string; // 城市 status: number; // 状态
district?: string; // 区县 unionid: string; // 用户唯一id
birthday?: string; // 生日
createTime: string; // 创建时间
updateTime: string; // 更新时间 updateTime: string; // 更新时间
}; };
export type PushAnimationType = export type PushAnimationType =
| "auto" | "auto"
| "fade-in"
| "none" | "none"
| "slide-in-right" | "pop-in"
| "slide-in-bottom"
| "slide-in-left" | "slide-in-left"
| "slide-in-right"
| "slide-in-top" | "slide-in-top"
| "slide-in-bottom"
| "fade-in"
| "zoom-out"
| "zoom-fade-out" | "zoom-fade-out"
| "pop-in"; | "zoom-out";
export type BackAnimationType = export type BackAnimationType =
| "auto" | "auto"
| "fade-out"
| "none" | "none"
| "slide-out-right" | "pop-out"
| "slide-out-bottom"
| "slide-out-left" | "slide-out-left"
| "slide-out-right"
| "slide-out-top" | "slide-out-top"
| "slide-out-bottom"
| "fade-out"
| "zoom-in"
| "zoom-fade-in" | "zoom-fade-in"
| "pop-out"; | "zoom-in";
export type PushMode = "navigateTo" | "redirectTo" | "reLaunch" | "switchTab"; export type PushMode = "navigateTo" | "redirectTo" | "reLaunch" | "switchTab";
export type BackOptions = { export type BackOptions = {
delta?: number;
animationType?: BackAnimationType;
animationDuration?: number; animationDuration?: number;
success?: (result: any) => void; animationType?: BackAnimationType;
fail?: (result: any) => void;
complete?: (result: any) => void; complete?: (result: any) => void;
delta?: number;
fail?: (result: any) => void;
success?: (result: any) => void;
}; };
export type PushOptions = { export type PushOptions = {
path: string; animationDuration?: number;
mode?: PushMode; animationType?: PushAnimationType;
complete?: (result: any) => void;
events?: any; events?: any;
query?: UTSJSONObject; fail?: (result: any) => void;
isAuth?: boolean; isAuth?: boolean;
mode?: PushMode;
params?: UTSJSONObject; params?: UTSJSONObject;
animationType?: PushAnimationType; path: string;
animationDuration?: number; query?: UTSJSONObject;
success?: (result: any) => void; success?: (result: any) => void;
fail?: (result: any) => void;
complete?: (result: any) => void;
}; };
export type PageInstance = { export type PageInstance = {
path: string;
vm: any;
style?: UTSJSONObject;
query: UTSJSONObject;
exposed: any; exposed: any;
isCustomNavbar: boolean; isCustomNavbar: boolean;
meta?: UTSJSONObject; meta?: UTSJSONObject;
path: string;
query: UTSJSONObject;
style?: UTSJSONObject;
vm: any;
}; };
declare module "@dcloudio/vite-plugin-uni"; declare module "@dcloudio/vite-plugin-uni";
declare type Theme = "light" | "dark"; declare type Theme = "dark" | "light";
declare interface Uni { declare interface Uni {
rpx2px(px: number): number; rpx2px(px: number): number;
...@@ -16,28 +16,28 @@ declare interface Uni { ...@@ -16,28 +16,28 @@ declare interface Uni {
} }
declare interface JSON { declare interface JSON {
parseObject<T>(text: string): T | null; parseObject<T>(text: string): null | T;
} }
declare type UTSJSONObject = { declare type UTSJSONObject = {
[key: string]: any; [key: string]: any;
parse?<T>(): T | null;
get?(key: string): any | null; get?(key: string): any | null;
set?(key: string, value: any | null): void;
getAny?(key: string): any | null; getAny?(key: string): any | null;
getAny?(key: string, def: any): any; getAny?(key: string, def: any): any;
getArray?<T>(key: string): null | T[];
getArray?<T>(key: string, def: T[]): T[];
getArray?(key: string): any[] | null;
getArray?(key: string, def: any[]): any[];
getBoolean?(key: string): boolean | null; getBoolean?(key: string): boolean | null;
getBoolean?(key: string, def: any): boolean; getBoolean?(key: string, def: any): boolean;
getNumber?(key: string): number | null; getJSON?(key: string): null | UTSJSONObject;
getJSON?(key: string, def: any): UTSJSONObject;
getNumber?(key: string): null | number;
getNumber?(key: string, def: any): number; getNumber?(key: string, def: any): number;
getString?(key: string): string | null; getString?(key: string): null | string;
getString?(key: string, def: any): string; getString?(key: string, def: any): string;
getJSON?(key: string): UTSJSONObject | null; parse?<T>(): null | T;
getJSON?(key: string, def: any): UTSJSONObject; set?(key: string, value: any | null): void;
getArray?<T>(key: string): T[] | null;
getArray?<T>(key: string, def: T[]): T[];
getArray?(key: string): any[] | null;
getArray?(key: string, def: any[]): any[];
toMap?(): Map<string, any>; toMap?(): Map<string, any>;
}; };
...@@ -49,14 +49,14 @@ declare interface ChooseImageTempFile { ...@@ -49,14 +49,14 @@ declare interface ChooseImageTempFile {
} }
declare type RequestMethod = declare type RequestMethod =
| "OPTIONS" | "CONNECT"
| "DELETE"
| "GET" | "GET"
| "HEAD" | "HEAD"
| "OPTIONS"
| "POST" | "POST"
| "PUT" | "PUT"
| "DELETE" | "TRACE";
| "TRACE"
| "CONNECT";
declare interface DOMRect { declare interface DOMRect {
x: number; x: number;
...@@ -82,33 +82,33 @@ declare interface UniElement { ...@@ -82,33 +82,33 @@ declare interface UniElement {
style: CSSStyleDeclaration; style: CSSStyleDeclaration;
classList: string[]; classList: string[];
takeSnapshot(options: { takeSnapshot(options: {
success?: (res: { tempFilePath: string }) => void;
fail?: (err: { errCode: number; errMsg: string }) => void; fail?: (err: { errCode: number; errMsg: string }) => void;
success?: (res: { tempFilePath: string }) => void;
}): void; }): void;
getBoundingClientRectAsync(): Promise<DOMRect>; getBoundingClientRectAsync(): Promise<DOMRect>;
getDrawableContext(): DrawableContext; getDrawableContext(): DrawableContext;
animate( animate(
keyframes: UniAnimationKeyframe | UniAnimationKeyframe[], keyframes: UniAnimationKeyframe | UniAnimationKeyframe[],
options?: options?:
| number
| { | {
delay?: number; delay?: number;
direction?: "normal" | "reverse" | "alternate" | "alternate-reverse"; direction?: "alternate" | "alternate-reverse" | "normal" | "reverse";
duration?: number; duration?: number;
easing?: easing?:
| "cubic-bezier"
| "ease" | "ease"
| "ease-in" | "ease-in"
| "ease-out"
| "ease-in-out" | "ease-in-out"
| "linear" | "ease-out"
| "cubic-bezier"; | "linear";
fill?: "backwards" | "forwards" | "both" | "none"; fill?: "backwards" | "both" | "forwards" | "none";
iterations?: number; iterations?: number;
} }
| number ): null | {
): {
id: string; id: string;
playState: "running" | "paused" | "finished" | "idle"; playState: "finished" | "idle" | "paused" | "running";
} | null; };
} }
declare interface CanvasContext extends HTMLCanvasElement { declare interface CanvasContext extends HTMLCanvasElement {
......
...@@ -13,7 +13,7 @@ export function isArray(value: any): boolean { ...@@ -13,7 +13,7 @@ export function isArray(value: any): boolean {
* @example isObject([]) // false * @example isObject([]) // false
*/ */
export function isObject(value: any): boolean { export function isObject(value: any): boolean {
return typeof value == "object" && !Array.isArray(value) && !isNull(value); return typeof value === "object" && !Array.isArray(value) && !isNull(value);
} }
/** /**
...@@ -22,7 +22,7 @@ export function isObject(value: any): boolean { ...@@ -22,7 +22,7 @@ export function isObject(value: any): boolean {
* @example isString(123) // false * @example isString(123) // false
*/ */
export function isString(value: any): boolean { export function isString(value: any): boolean {
return typeof value == "string"; return typeof value === "string";
} }
/** /**
...@@ -31,7 +31,7 @@ export function isString(value: any): boolean { ...@@ -31,7 +31,7 @@ export function isString(value: any): boolean {
* @example isNumber('123') // false * @example isNumber('123') // false
*/ */
export function isNumber(value: any): boolean { export function isNumber(value: any): boolean {
return typeof value == "number" && !isNaN(value); return typeof value === "number" && !isNaN(value);
} }
/** /**
...@@ -40,7 +40,7 @@ export function isNumber(value: any): boolean { ...@@ -40,7 +40,7 @@ export function isNumber(value: any): boolean {
* @example isBoolean(1) // false * @example isBoolean(1) // false
*/ */
export function isBoolean(value: any): boolean { export function isBoolean(value: any): boolean {
return typeof value == "boolean"; return typeof value === "boolean";
} }
/** /**
...@@ -49,7 +49,7 @@ export function isBoolean(value: any): boolean { ...@@ -49,7 +49,7 @@ export function isBoolean(value: any): boolean {
* @example isFunction({}) // false * @example isFunction({}) // false
*/ */
export function isFunction(value: any): boolean { export function isFunction(value: any): boolean {
return typeof value == "function"; return typeof value === "function";
} }
/** /**
...@@ -75,7 +75,7 @@ export function isNull(value?: any | null): boolean { ...@@ -75,7 +75,7 @@ export function isNull(value?: any | null): boolean {
*/ */
export function isEmpty(value: any): boolean { export function isEmpty(value: any): boolean {
if (isArray(value)) { if (isArray(value)) {
return (value as any[]).length == 0; return (value as any[]).length === 0;
} }
if (isString(value)) { if (isString(value)) {
...@@ -83,7 +83,7 @@ export function isEmpty(value: any): boolean { ...@@ -83,7 +83,7 @@ export function isEmpty(value: any): boolean {
} }
if (isObject(value)) { if (isObject(value)) {
return keys(value).length == 0; return keys(value).length === 0;
} }
return false; return false;
...@@ -103,7 +103,7 @@ export function keys(value: any): string[] { ...@@ -103,7 +103,7 @@ export function keys(value: any): string[] {
* @example first([1, 2, 3]) // 1 * @example first([1, 2, 3]) // 1
* @example first([]) // null * @example first([]) // null
*/ */
export function first<T>(array: T[]): T | null { export function first<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[0] : null; return isArray(array) && array.length > 0 ? array[0] : null;
} }
...@@ -112,7 +112,7 @@ export function first<T>(array: T[]): T | null { ...@@ -112,7 +112,7 @@ export function first<T>(array: T[]): T | null {
* @example last([1, 2, 3]) // 3 * @example last([1, 2, 3]) // 3
* @example last([]) // null * @example last([]) // null
*/ */
export function last<T>(array: T[]): T | null { export function last<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[array.length - 1] : null; return isArray(array) && array.length > 0 ? array[array.length - 1] : null;
} }
...@@ -179,8 +179,8 @@ export function map<T, U>(array: T[], iteratee: (item: T, index: number) => U): ...@@ -179,8 +179,8 @@ export function map<T, U>(array: T[], iteratee: (item: T, index: number) => U):
if (!isArray(array)) return result; if (!isArray(array)) return result;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
result.push(iteratee(array[i], i)); result.push(iteratee(element, i));
} }
return result; return result;
...@@ -198,8 +198,8 @@ export function reduce<T, U>( ...@@ -198,8 +198,8 @@ export function reduce<T, U>(
if (!isArray(array)) return initialValue; if (!isArray(array)) return initialValue;
let accumulator: U = initialValue; let accumulator: U = initialValue;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
accumulator = iteratee(accumulator, array[i], i); accumulator = iteratee(accumulator, element, i);
} }
return accumulator; return accumulator;
...@@ -212,8 +212,8 @@ export function reduce<T, U>( ...@@ -212,8 +212,8 @@ export function reduce<T, U>(
export function every<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean { export function every<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return true; if (!isArray(array)) return true;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (!predicate(array[i], i)) { if (!predicate(element, i)) {
return false; return false;
} }
} }
...@@ -228,8 +228,8 @@ export function every<T>(array: T[], predicate: (value: T, index: number) => boo ...@@ -228,8 +228,8 @@ export function every<T>(array: T[], predicate: (value: T, index: number) => boo
export function some<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean { export function some<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return false; if (!isArray(array)) return false;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (predicate(array[i], i)) { if (predicate(element, i)) {
return true; return true;
} }
} }
...@@ -247,8 +247,7 @@ export function uniq<T>(array: T[]): T[] { ...@@ -247,8 +247,7 @@ export function uniq<T>(array: T[]): T[] {
const result: T[] = []; const result: T[] = [];
const seen = new Map<T, boolean>(); const seen = new Map<T, boolean>();
for (let i = 0; i < array.length; i++) { for (const item of array) {
const item = array[i];
const key = item; const key = item;
if (!seen.has(item)) { if (!seen.has(item)) {
seen.set(key, true); seen.set(key, true);
...@@ -268,8 +267,7 @@ export function flatten(array: any[]): any[] { ...@@ -268,8 +267,7 @@ export function flatten(array: any[]): any[] {
const result: any[] = []; const result: any[] = [];
for (let i = 0; i < array.length; i++) { for (const item of array) {
const item = array[i];
if (isArray(item)) { if (isArray(item)) {
result.push(...(item as any[])); result.push(...(item as any[]));
} else { } else {
...@@ -289,8 +287,7 @@ export function flattenDeep(array: any[]): any[] { ...@@ -289,8 +287,7 @@ export function flattenDeep(array: any[]): any[] {
const result: any[] = []; const result: any[] = [];
for (let i = 0; i < array.length; i++) { for (const item of array) {
const item = array[i];
if (isArray(item)) { if (isArray(item)) {
result.push(...flattenDeep(item as any[])); result.push(...flattenDeep(item as any[]));
} else { } else {
...@@ -310,11 +307,11 @@ export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] { ...@@ -310,11 +307,11 @@ export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] {
const result = [...array]; const result = [...array];
return result.sort((a, b) => { return result.sort((a, b) => {
if (typeof a == "number" && typeof b == "number") { if (typeof a === "number" && typeof b === "number") {
return order == "asc" ? a - b : b - a; return order == "asc" ? a - b : b - a;
} }
if (typeof a == "string" && typeof b == "string") { if (typeof a === "string" && typeof b === "string") {
return order == "asc" ? a.localeCompare(b) : b.localeCompare(a); return order == "asc" ? a.localeCompare(b) : b.localeCompare(a);
} }
...@@ -354,15 +351,14 @@ export function groupBy<T>(array: T[], key: string) { ...@@ -354,15 +351,14 @@ export function groupBy<T>(array: T[], key: string) {
const result = {}; const result = {};
for (let i = 0; i < array.length; i++) { for (const item of array) {
const item = array[i];
let value = get(item as any, key)!; let value = get(item as any, key)!;
if (typeof value == "number") { if (typeof value === "number") {
value = value.toString(); value = value.toString();
} }
if (typeof value == "string") { if (typeof value === "string") {
if (!isArray(result[value])) { if (!isArray(result[value])) {
result[value] = new Array<T>(); result[value] = new Array<T>();
} }
...@@ -388,7 +384,7 @@ export function assign(...items: any[]) { ...@@ -388,7 +384,7 @@ export function assign(...items: any[]) {
* @example nth([1, 2, 3], 1) // 2 * @example nth([1, 2, 3], 1) // 2
* @example nth([1, 2, 3], -1) // 3 * @example nth([1, 2, 3], -1) // 3
*/ */
export function nth<T>(array: T[], index: number): T | null { export function nth<T>(array: T[], index: number): null | T {
if (index >= 0) { if (index >= 0) {
return array[index]; return array[index];
} }
...@@ -415,9 +411,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo ...@@ -415,9 +411,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo
const result: T[] = []; const result: T[] = [];
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (!predicate(array[i], i)) { if (!predicate(element, i)) {
result.push(array[i]); result.push(element);
} }
} }
...@@ -432,9 +428,9 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi ...@@ -432,9 +428,9 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
if (isArray(data)) { if (isArray(data)) {
const array = data as T[]; const array = data as T[];
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (array[i] != null) { if (element != null) {
iteratee(array[i], i); iteratee(element, i);
} }
} }
} }
...@@ -444,12 +440,12 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi ...@@ -444,12 +440,12 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
* 查找数组中第一个满足条件的元素 * 查找数组中第一个满足条件的元素
* @example find([1, 2, 3, 4], x => x > 2) // 3 * @example find([1, 2, 3, 4], x => x > 2) // 3
*/ */
export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): T | null { export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): null | T {
if (!isArray(array)) return null; if (!isArray(array)) return null;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (predicate(array[i], i)) { if (predicate(element, i)) {
return array[i]; return element;
} }
} }
return null; return null;
...@@ -462,8 +458,7 @@ export function find<T>(array: T[], predicate: (value: T, index: number) => bool ...@@ -462,8 +458,7 @@ export function find<T>(array: T[], predicate: (value: T, index: number) => bool
export function forInObject(data: any, iteratee: (value: any, key: string) => void): void { export function forInObject(data: any, iteratee: (value: any, key: string) => void): void {
if (isObject(data)) { if (isObject(data)) {
const objKeys = keys(data); const objKeys = keys(data);
for (let i = 0; i < objKeys.length; i++) { for (const key of objKeys) {
const key = objKeys[i];
iteratee(get(data, key)!, key); iteratee(get(data, key)!, key);
} }
} }
...@@ -585,9 +580,9 @@ export function random(min: number, max: number): number { ...@@ -585,9 +580,9 @@ export function random(min: number, max: number): number {
*/ */
export function base64ToBlob(data: string, type: string = "image/jpeg"): Blob { export function base64ToBlob(data: string, type: string = "image/jpeg"): Blob {
// #ifdef H5 // #ifdef H5
let bytes = window.atob(data.split(",")[1]); const bytes = window.atob(data.split(",")[1]);
let ab = new ArrayBuffer(bytes.length); const ab = new ArrayBuffer(bytes.length);
let ia = new Uint8Array(ab); const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) { for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i); ia[i] = bytes.charCodeAt(i);
} }
......
import { isArray, parse } from "../utils"; import { isArray, parse } from "../utils";
type Page = { type Page = {
meta?: UTSJSONObject;
path: string; path: string;
style?: UTSJSONObject; style?: UTSJSONObject;
meta?: UTSJSONObject;
}; };
type SubPackage = { type SubPackage = {
root: string;
pages: Page[]; pages: Page[];
root: string;
}; };
export type TabBarItem = { export type TabBarItem = {
text?: string;
pagePath: string;
iconPath?: string; iconPath?: string;
pagePath: string;
selectedIconPath?: string; selectedIconPath?: string;
text?: string;
visible?: boolean; visible?: boolean;
}; };
export type TabBar = { export type TabBar = {
custom?: boolean;
color?: string;
selectedColor?: string;
backgroundColor?: string; backgroundColor?: string;
borderStyle?: string; backgroundImage?: string;
backgroundRepeat?: "no-repeat" | "repeat" | "repeat-x" | "repeat-y";
blurEffect?: "dark" | "extralight" | "light" | "none"; blurEffect?: "dark" | "extralight" | "light" | "none";
list?: TabBarItem[]; borderStyle?: string;
position?: "top" | "bottom"; color?: string;
custom?: boolean;
fontSize?: string; fontSize?: string;
iconWidth?: string;
spacing?: string;
height?: string; height?: string;
backgroundImage?: string; iconWidth?: string;
backgroundRepeat?: "repeat" | "repeat-x" | "repeat-y" | "no-repeat"; list?: TabBarItem[];
position?: "bottom" | "top";
redDotColor?: string; redDotColor?: string;
selectedColor?: string;
spacing?: string;
}; };
export type Ctx = { export type Ctx = {
appid: string; appid: string;
color: UTSJSONObject;
globalStyle: UTSJSONObject; globalStyle: UTSJSONObject;
pages: Page[]; pages: Page[];
uniIdRouter: UTSJSONObject;
theme: UTSJSONObject;
tabBar: TabBar;
subPackages: SubPackage[];
SAFE_CHAR_MAP_LOCALE: string[][]; SAFE_CHAR_MAP_LOCALE: string[][];
color: UTSJSONObject; subPackages: SubPackage[];
tabBar: TabBar;
theme: UTSJSONObject;
uniIdRouter: UTSJSONObject;
}; };
// 初始化 ctx 对象,不可修改!! // 初始化 ctx 对象,不可修改!!
...@@ -64,7 +64,7 @@ if (isArray(ctx.subPackages)) { ...@@ -64,7 +64,7 @@ if (isArray(ctx.subPackages)) {
ctx.subPackages.forEach((a) => { ctx.subPackages.forEach((a) => {
a.pages.forEach((b) => { a.pages.forEach((b) => {
PAGES.push({ PAGES.push({
path: a.root + "/" + b.path, // 拼接子包根路径和页面路径 path: `${a.root }/${ b.path}`, // 拼接子包根路径和页面路径
style: b.style, style: b.style,
meta: b.meta meta: b.meta
}); });
...@@ -75,7 +75,7 @@ if (isArray(ctx.subPackages)) { ...@@ -75,7 +75,7 @@ if (isArray(ctx.subPackages)) {
// 确保每个页面路径都以 "/" 开头,符合 uni-app x 规范 // 确保每个页面路径都以 "/" 开头,符合 uni-app x 规范
PAGES.forEach((e) => { PAGES.forEach((e) => {
if (!e.path.startsWith("/")) { if (!e.path.startsWith("/")) {
e.path = "/" + e.path; e.path = `/${ e.path}`;
} }
}); });
......
export * from "./storage.uts";
export * from "./common.uts"; export * from "./common.uts";
export * from "./parse.uts"; export * from "./parse.uts";
export * from "./storage.uts";
...@@ -9,11 +9,11 @@ import LocalStore from "./local-store"; ...@@ -9,11 +9,11 @@ import LocalStore from "./local-store";
// ===== 1. 定义数据 Schema ===== // ===== 1. 定义数据 Schema =====
type UserSchema = { type UserSchema = {
name: string;
age: number; age: number;
createdAt: number;
email: string; email: string;
name: string;
status: "active" | "inactive"; status: "active" | "inactive";
createdAt: number;
updatedAt: number; updatedAt: number;
}; };
...@@ -199,10 +199,10 @@ try { ...@@ -199,10 +199,10 @@ try {
// 场景1:用户收藏管理 // 场景1:用户收藏管理
type FavoriteSchema = { type FavoriteSchema = {
userId: string;
itemId: string;
itemType: "article" | "video" | "product";
createdAt: number; createdAt: number;
itemId: string;
itemType: "article" | "product" | "video";
userId: string;
}; };
const favoriteStore = new LocalStore<FavoriteSchema>("favorite", { const favoriteStore = new LocalStore<FavoriteSchema>("favorite", {
...@@ -230,11 +230,11 @@ const userFavorites = favoriteStore.find({ ...@@ -230,11 +230,11 @@ const userFavorites = favoriteStore.find({
// 场景2:购物车管理 // 场景2:购物车管理
type CartItemSchema = { type CartItemSchema = {
addedAt: number;
price: number;
productId: string; productId: string;
productName: string; productName: string;
price: number;
quantity: number; quantity: number;
addedAt: number;
}; };
const cartStore = new LocalStore<CartItemSchema>("cart", { const cartStore = new LocalStore<CartItemSchema>("cart", {
...@@ -262,6 +262,6 @@ if (cartItems.length > 0) { ...@@ -262,6 +262,6 @@ if (cartItems.length > 0) {
// 计算购物车总价 // 计算购物车总价
let totalPrice = 0; let totalPrice = 0;
for (let i = 0; i < cartItems.length; i++) { for (const cartItem of cartItems) {
totalPrice += cartItems[i].price * cartItems[i].quantity; totalPrice += cartItem.price * cartItem.quantity;
} }
...@@ -35,7 +35,7 @@ ...@@ -35,7 +35,7 @@
* ``` * ```
*/ */
import { isNull, isObject, isArray, keys, get, has, set } from "./common"; import { get, has, isArray, isNull, keys, set } from "./common";
// 更新数据类型 // 更新数据类型
// UTS 不支持 Partial<T>,使用 any 类型,运行时检查 // UTS 不支持 Partial<T>,使用 any 类型,运行时检查
...@@ -44,15 +44,15 @@ type UpdateData<T> = any; ...@@ -44,15 +44,15 @@ type UpdateData<T> = any;
// 查询操作符类型 // 查询操作符类型
type QueryOperator = type QueryOperator =
| "$eq" | "$eq"
| "$ne" | "$exists"
| "$gt" | "$gt"
| "$gte" | "$gte"
| "$lt"
| "$lte"
| "$in" | "$in"
| "$nin"
| "$like" | "$like"
| "$exists"; | "$lt"
| "$lte"
| "$ne"
| "$nin";
// 字段查询操作符类型(UTS 不支持内联对象字面量类型和条件类型,需要先定义) // 字段查询操作符类型(UTS 不支持内联对象字面量类型和条件类型,需要先定义)
// 注意:由于 UTS 不支持条件类型,这里使用 number 和 string 类型 // 注意:由于 UTS 不支持条件类型,这里使用 number 和 string 类型
...@@ -61,15 +61,15 @@ type QueryOperator = ...@@ -61,15 +61,15 @@ type QueryOperator =
// 运行时会在 matchCondition 方法中进行类型检查 // 运行时会在 matchCondition 方法中进行类型检查
type FieldQueryOperator<FieldType> = { type FieldQueryOperator<FieldType> = {
$eq?: FieldType; $eq?: FieldType;
$ne?: FieldType; $exists?: boolean;
$gt?: number; // 比较操作符用于数字类型 $gt?: number; // 比较操作符用于数字类型
$gte?: number; $gte?: number;
$in?: FieldType[];
$like?: string; // like 操作符用于字符串类型
$lt?: number; $lt?: number;
$lte?: number; $lte?: number;
$in?: FieldType[]; $ne?: FieldType;
$nin?: FieldType[]; $nin?: FieldType[];
$like?: string; // like 操作符用于字符串类型
$exists?: boolean;
}; };
// 查询条件类型 // 查询条件类型
...@@ -93,16 +93,16 @@ type SortOption<T> = { ...@@ -93,16 +93,16 @@ type SortOption<T> = {
// 查询选项 // 查询选项
type FindOptions<T> = { type FindOptions<T> = {
where?: QueryCondition<T>;
sort?: SortOption<T>[];
limit?: number; limit?: number;
skip?: number; skip?: number;
sort?: SortOption<T>[];
where?: QueryCondition<T>;
}; };
// 统计信息类型 // 统计信息类型
type Stats = { type Stats = {
total: number;
size: number; size: number;
total: number;
}; };
/** /**
...@@ -110,9 +110,6 @@ type Stats = { ...@@ -110,9 +110,6 @@ type Stats = {
*/ */
// UTS 不支持 Record<string, any>,使用 any 约束 // UTS 不支持 Record<string, any>,使用 any 约束
class LocalStore<T extends any> { class LocalStore<T extends any> {
// 存储前缀
private prefix: string;
// Schema 默认值 // Schema 默认值
private defaults: T; private defaults: T;
...@@ -122,6 +119,9 @@ class LocalStore<T extends any> { ...@@ -122,6 +119,9 @@ class LocalStore<T extends any> {
// 索引存储前缀 // 索引存储前缀
private indexPrefix: string; private indexPrefix: string;
// 存储前缀
private prefix: string;
/** /**
* 构造函数 * 构造函数
* @param name 存储名称(作为命名空间前缀) * @param name 存储名称(作为命名空间前缀)
...@@ -135,175 +135,416 @@ class LocalStore<T extends any> { ...@@ -135,175 +135,416 @@ class LocalStore<T extends any> {
} }
/** /**
* 生成唯一 ID * 清空所有记录
* 使用时间戳 + 随机字符串,确保唯一性
*/ */
private generateId(): string { clear(): void {
return `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`; const ids = this.getIds();
for (const id of ids) {
const key = this.getRecordKey(id);
uni.removeStorageSync(key);
} }
this.saveIds([]);
/**
* 获取记录的存储 key
*/
private getRecordKey(id: string | number): string {
// UTS 不支持 String() 构造函数,使用 toString() 或模板字符串
const idStr = typeof id == "string" ? id : id.toString();
return `${this.prefix}:${idStr}`;
} }
/** /**
* 获取索引的存储 key * 统计记录数量
*/ */
private getIndexKey(field: string, value: any): string { count(where?: QueryCondition<T>): number {
const valueStr = typeof value == "string" ? value : JSON.stringify(value); if (where == null) {
return `${this.indexPrefix}:${field}:${valueStr}`; return this.getIds().length;
}
return this.find({ where }).length;
} }
/** /**
* 深拷贝对象 * 创建索引(用于快速查找)
* @param field 要建立索引的字段名
*/ */
private deepClone(obj: any): any | null { // UTS 不支持 keyof T,使用 string 类型
// UTS 要求返回类型明确包含 null createIndex(field: string): void {
if (obj == null) { // 获取所有记录
return null; const records = this.findAll();
// 清空该字段的旧索引
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
uni.removeStorageSync(indexKey);
// 建立新索引:字段值 -> ID 列表
// UTS 不支持 Record 类型,使用 any 类型
const index: any = {};
for (const record of records) {
// UTS 对象属性访问需要使用 get 函数
const value = get(record, field);
// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
const valueKey =
value != null ? (typeof value === "string" ? value : value.toString()) : "__null__";
// 使用 set 和 get 维护索引,避免直接使用下标访问
// 显式指定空数组类型为 any[]
const emptyArray: any[] = [];
if (!has(index, valueKey)) {
set(index, valueKey, emptyArray);
} }
if (typeof obj == "object") { let idList = get(index, valueKey) as any[] | null;
return JSON.parse(JSON.stringify(obj)); // 确保 idList 不为 null,强制断言为非空数组
if (isNull(idList) || !isArray(idList)) {
idList = [];
} }
return obj; // 使用非空断言,确保 idList 是数组类型
const idListArray = idList as any[];
const recordAny = record as any;
const idValue = get(recordAny, "id");
// idValue 可能为 null,需要检查后使用类型断言
if (!isNull(idValue)) {
// idListArray 是非空数组,idValue 也不为 null
idListArray.push(idValue as any);
}
set(index, valueKey, idListArray);
}
// 保存索引
uni.setStorageSync(indexKey, index);
} }
/** /**
* 获取所有记录的 ID 列表 * 删除记录
*/ */
private getIds(): (string | number)[] { delete(id: number | string): boolean {
const ids = uni.getStorageSync(this.idsKey); if (!this.exists(id)) {
if (isNull(ids) || !isArray(ids)) { return false;
return [];
} }
return ids as (string | number)[];
const key = this.getRecordKey(id);
try {
uni.removeStorageSync(key);
} catch (error) {
console.error(`[LocalStore] 删除失败:`, error);
return false;
} }
/** // 从 ID 列表中移除
* 保存 ID 列表 this.removeId(id);
*/
private saveIds(ids: (string | number)[]): void { return true;
uni.setStorageSync(this.idsKey, ids);
} }
/** /**
* 添加 ID 到列表 * 批量删除(优化版本,直接操作 ID 列表)
* @param ids 要删除的 ID 数组
*/ */
private addId(id: string | number): void { deleteByIds(ids: (number | string)[]): number {
const ids = this.getIds(); if (ids.length === 0) {
if (!ids.includes(id)) { return 0;
ids.push(id); }
this.saveIds(ids);
let count = 0;
const allIds = this.getIds();
// 批量删除存储
for (const id of ids) {
const key = this.getRecordKey(id);
try {
uni.removeStorageSync(key);
count++;
} catch (error) {
console.error(`[LocalStore] 删除失败 ID=${id}:`, error);
} }
} }
/** // 批量更新 ID 列表(一次性操作)
* 从列表中移除 ID const remainingIds: (number | string)[] = [];
*/ for (const allId of allIds) {
private removeId(id: string | number): void { if (!ids.includes(allId)) {
const ids = this.getIds(); remainingIds.push(allId);
const index = ids.indexOf(id); }
if (index != -1) {
ids.splice(index, 1);
this.saveIds(ids);
} }
this.saveIds(remainingIds);
return count;
} }
/** /**
* 验证数据是否符合 schema * 批量删除
*/ */
// UTS 不支持 Partial<T>,使用 any 类型 deleteMany(where: QueryCondition<T>): number {
// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组 const records = this.find({ where });
private validateData(data: any): boolean { if (records.length === 0) {
const dataKeys = keys(data); return 0;
for (let i = 0; i < dataKeys.length; i++) { }
const key = dataKeys[i];
if (!has(this.defaults, key)) { let count = 0;
console.warn(`[LocalStore] 未知字段 "${key}" 在 store "${this.prefix}" 中`); for (const record of records) {
return false; const recordAny = record as any;
// 通过 get 获取 id,避免直接访问属性导致类型问题
const idValue = get(recordAny, "id") as null | number | string;
if (record != null && !isNull(idValue) && this.delete(idValue as number | string)) {
count++;
} }
} }
return true; return count;
} }
/** /**
* 合并默认值 * 删除索引
*/ */
// UTS 不支持 Partial<T>,使用 any 类型 // UTS 不支持 keyof T,使用 string 类型
// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组 dropIndex(field: string): void {
// UTS 对象属性访问需要使用 UTSJSONObject 方式 // UTS 不支持 String() 构造函数,field 已经是 string 类型
private mergeDefaults(data: any): T { const indexKey = `${this.indexPrefix}:${field}:__all__`;
const result = this.deepClone(this.defaults) as T; uni.removeStorageSync(indexKey);
const dataKeys = keys(data);
for (let i = 0; i < dataKeys.length; i++) {
const key = dataKeys[i];
if (has(this.defaults, key)) {
// UTS 对象属性访问需要使用 get 和 set 函数
const value = get(data, key);
set(result, key, value);
}
}
return result;
} }
/** /**
* 检查记录是否存在 * 检查记录是否存在
*/ */
exists(id: string | number): boolean { exists(id: number | string): boolean {
const key = this.getRecordKey(id); const key = this.getRecordKey(id);
const record = uni.getStorageSync(key); const record = uni.getStorageSync(key);
return record != null && record != ""; return record != null && record != "";
} }
/** /**
* 获取单条记录 * 查询记录
*/ */
get(id: string | number): RecordWithId<T> | null { find(options?: FindOptions<T>): RecordWithId<T>[] {
if (!this.exists(id)) { const ids = this.getIds();
return null; let results: RecordWithId<T>[] = [];
}
const key = this.getRecordKey(id); // 获取所有记录
const record = uni.getStorageSync(key) as T | null; for (const id of ids) {
const record = this.get(id);
if (record != null) {
results.push(record);
}
}
if (isNull(record)) { // 应用查询条件
return null; if (options != null && options.where != null) {
results = results.filter((record) => this.matchCondition(record, options.where!));
} }
// 合并默认值,确保所有字段都存在 // 应用排序
// record 已经检查过不为 null,使用类型断言 if (options != null && options.sort != null && options.sort.length > 0) {
const merged = this.mergeDefaults(record as any); results.sort((a, b) => {
// UTS 不支持对象展开运算符,需要手动创建对象 for (let i = 0; i < options.sort!.length; i++) {
const result: any = {}; const sortOption = options.sort![i];
const mergedKeys = keys(merged); const field = sortOption.field;
for (let i = 0; i < mergedKeys.length; i++) { // UTS 对象属性访问需要使用 get 函数,get 返回 any | null
const key = mergedKeys[i]; const aValueAny = get(a, field);
const value = get(merged, key); const bValueAny = get(b, field);
set(result, key, value);
// 如果值为 null,跳过比较(null 值排在最后)
if (isNull(aValueAny) || isNull(bValueAny)) {
if (isNull(aValueAny) && isNull(bValueAny)) {
continue; // 两个都是 null,继续下一个字段
} }
set(result, "id", id); // 一个为 null,另一个不为 null,null 排在后面
return result as RecordWithId<T>; return isNull(aValueAny) ? 1 : -1;
} }
/** // 确保值不为 null,使用类型断言
* 插入新记录 const aValue = aValueAny as any;
* @param idOrData 可以是 ID(string/number),也可以是数据对象(此时自动生成 ID) const bValue = bValueAny as any;
* @param data 如果第一个参数是 ID,则此为数据;否则忽略
* @returns 实际使用的 ID
*/
// UTS 不支持 Partial<T>,使用 any 类型
insert(idOrData: string | number | any, data?: any): string | number {
let id: string | number;
let finalData: any;
if (typeof idOrData == "object") { let comparison = 0;
// 调用方式:store.insert({ name: 'Alice' }) if (typeof aValue === "number" && typeof bValue === "number") {
finalData = idOrData; comparison = aValue - bValue;
} else if (typeof aValue === "string" && typeof bValue === "string") {
// UTS 不支持直接使用 < > 比较字符串,手动实现字符串比较
const aStr = aValue as string;
const bStr = bValue as string;
const aLen = aStr.length;
const bLen = bStr.length;
const minLen = Math.min(aLen, bLen);
// 逐个字符比较(使用字符串索引访问)
for (let j = 0; j < minLen; j++) {
// UTS 字符串索引访问,charCodeAt 返回 Number?,这里断言为 number
const aCharCode = aStr.charCodeAt(j) as number;
const bCharCode = bStr.charCodeAt(j) as number;
if (aCharCode < bCharCode) {
comparison = -1;
break;
} else if (aCharCode > bCharCode) {
comparison = 1;
break;
}
}
// 如果前面的字符都相同,比较长度
if (comparison == 0) {
if (aLen < bLen) {
comparison = -1;
} else if (aLen > bLen) {
comparison = 1;
}
}
}
if (comparison != 0) {
return sortOption.order == "asc" ? comparison : -comparison;
}
}
return 0;
});
}
// 应用 skip
if (options != null && options.skip != null) {
const skipValue = options.skip;
if (skipValue > 0) {
results = results.slice(skipValue);
}
}
// 应用 limit
if (options != null && options.limit != null) {
const limitValue = options.limit;
if (limitValue > 0) {
results = results.slice(0, limitValue);
}
}
return results;
}
/**
* 获取所有记录
*/
findAll(): RecordWithId<T>[] {
// UTS 要求显式传入参数,这里传入空配置对象
const emptyOptions: any = {};
return this.find(emptyOptions as FindOptions<T>);
}
/**
* 根据索引查找记录
* @param field 索引字段
* @param value 字段值
*/
// UTS 不支持 keyof T,使用 string 类型
findByIndex(field: string, value: any): RecordWithId<T>[] {
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
// UTS 不支持 Record 类型,使用 any 类型
const index = uni.getStorageSync(indexKey) as any | null;
if (isNull(index)) {
// 索引不存在,使用普通查询
// UTS 不支持计算属性名 [field],需要先创建对象
const whereCondition: any = {};
set(whereCondition, field, value);
return this.find({ where: whereCondition as QueryCondition<T> });
}
// index 已经检查过不为 null,使用类型断言
// UTS 不支持 Record 类型,使用 any 类型
const indexObj = index as any;
// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
const valueKey =
value != null ? (typeof value === "string" ? value : value.toString()) : "__null__";
// 使用 get 获取 ids,避免下标访问
const idsAny = get(indexObj, valueKey);
if (isNull(idsAny) || !isArray(idsAny)) {
return [];
}
// 确保 ids 是数组类型
const ids = idsAny as any[];
const results: RecordWithId<T>[] = [];
for (const id of ids) {
const record = this.get(id);
if (record != null) {
results.push(record);
}
}
return results;
}
/**
* 查找第一条匹配的记录
*/
findFirst(where?: QueryCondition<T>): null | RecordWithId<T> {
const results = this.find({ where, limit: 1 });
return results.length > 0 ? results[0] : null;
}
/**
* 查找单条记录
*/
findOne(id: number | string): null | RecordWithId<T> {
return this.get(id);
}
/**
* 获取单条记录
*/
get(id: number | string): null | RecordWithId<T> {
if (!this.exists(id)) {
return null;
}
const key = this.getRecordKey(id);
const record = uni.getStorageSync(key) as null | T;
if (isNull(record)) {
return null;
}
// 合并默认值,确保所有字段都存在
// record 已经检查过不为 null,使用类型断言
const merged = this.mergeDefaults(record as any);
// UTS 不支持对象展开运算符,需要手动创建对象
const result: any = {};
const mergedKeys = keys(merged);
for (const key of mergedKeys) {
const value = get(merged, key);
set(result, key, value);
}
set(result, "id", id);
return result as RecordWithId<T>;
}
/**
* 获取存储统计信息
*/
getStats(): Stats {
const ids = this.getIds();
let totalSize = 0;
// 估算存储大小(简单实现)
for (const id of ids) {
const record = this.get(id);
if (record != null) {
const recordStr = JSON.stringify(record);
totalSize += recordStr.length;
}
}
return {
total: ids.length,
size: totalSize
};
}
/**
* 插入新记录
* @param idOrData 可以是 ID(string/number),也可以是数据对象(此时自动生成 ID)
* @param data 如果第一个参数是 ID,则此为数据;否则忽略
* @returns 实际使用的 ID
*/
// UTS 不支持 Partial<T>,使用 any 类型
insert(idOrData: any | number | string, data?: any): number | string {
let id: number | string;
let finalData: any;
if (typeof idOrData === "object") {
// 调用方式:store.insert({ name: 'Alice' })
finalData = idOrData;
id = this.generateId(); id = this.generateId();
} else { } else {
// 调用方式:store.insert('user_123', { name: 'Alice' }) // 调用方式:store.insert('user_123', { name: 'Alice' })
...@@ -339,9 +580,66 @@ class LocalStore<T extends any> { ...@@ -339,9 +580,66 @@ class LocalStore<T extends any> {
} }
/** /**
* 批量插入
* 内部自动分批处理,避免一次性操作过多导致性能问题
* @param items 要插入的数据数组
* @param batchSize 每批处理的条数,默认100条
*/
// UTS 不支持 Partial<T>,使用 any 类型
insertMany(items: any[], batchSize: number = 100): (number | string)[] {
const ids: (number | string)[] = [];
const total = items.length;
// 如果数据量小于批次大小,直接处理
if (total <= batchSize) {
for (const item of items) {
try {
// UTS 不支持 undefined,使用 null 作为可选参数占位
const id = this.insert(item, null);
ids.push(id);
} catch (error) {
console.error(`[LocalStore] 批量插入失败:`, error);
}
}
return ids;
}
// 大数据量时,分批处理
const batchCount = Math.ceil(total / batchSize);
for (let batch = 0; batch < batchCount; batch++) {
const start = batch * batchSize;
const end = Math.min(start + batchSize, total);
// 处理当前批次
for (let i = start; i < end; i++) {
try {
// UTS 不支持 undefined,使用 null 作为可选参数占位
const id = this.insert(items[i], null);
ids.push(id);
} catch (error) {
console.error(`[LocalStore] 批量插入失败 [${i + 1}/${total}]:`, error);
}
}
}
return ids;
}
/**
* 重建所有索引(在数据迁移后使用)
*/
// UTS 不支持 keyof T,使用 string[] 类型
rebuildIndexes(fields: string[]): void {
for (const field of fields) {
this.createIndex(field);
}
}
/**
* 更新记录(部分更新) * 更新记录(部分更新)
*/ */
update(id: string | number, updates: UpdateData<T>): boolean { update(id: number | string, updates: UpdateData<T>): boolean {
if (!this.exists(id)) { if (!this.exists(id)) {
console.warn(`[LocalStore] 记录 "${id}" 不存在`); console.warn(`[LocalStore] 记录 "${id}" 不存在`);
return false; return false;
...@@ -366,8 +664,7 @@ class LocalStore<T extends any> { ...@@ -366,8 +664,7 @@ class LocalStore<T extends any> {
const updated: any = {}; const updated: any = {};
// 先复制 existing 的所有属性 // 先复制 existing 的所有属性
const existingKeys = keys(existingAny); const existingKeys = keys(existingAny);
for (let i = 0; i < existingKeys.length; i++) { for (const key of existingKeys) {
const key = existingKeys[i];
if (key != "id") { if (key != "id") {
// 跳过 id 字段 // 跳过 id 字段
const value = get(existingAny, key); const value = get(existingAny, key);
...@@ -376,8 +673,7 @@ class LocalStore<T extends any> { ...@@ -376,8 +673,7 @@ class LocalStore<T extends any> {
} }
// 再复制 updates 的所有属性(覆盖 existing) // 再复制 updates 的所有属性(覆盖 existing)
const updatesKeys = keys(updates); const updatesKeys = keys(updates);
for (let i = 0; i < updatesKeys.length; i++) { for (const key of updatesKeys) {
const key = updatesKeys[i];
const value = get(updates, key); const value = get(updates, key);
set(updated, key, value); set(updated, key, value);
} }
...@@ -396,61 +692,81 @@ class LocalStore<T extends any> { ...@@ -396,61 +692,81 @@ class LocalStore<T extends any> {
} }
/** /**
* 删除记录 * 批量更新
*/ */
delete(id: string | number): boolean { updateMany(where: QueryCondition<T>, updates: UpdateData<T>): number {
if (!this.exists(id)) { const records = this.find({ where });
return false; let count = 0;
for (const record of records) {
const recordAny = record as any;
// 通过 get 获取 id,避免直接访问属性导致类型问题
const idValue = get(recordAny, "id") as null | number | string;
if (!isNull(idValue) && this.update(idValue as number | string, updates)) {
count++;
} }
}
const key = this.getRecordKey(id); return count;
try {
uni.removeStorageSync(key);
} catch (error) {
console.error(`[LocalStore] 删除失败:`, error);
return false;
} }
// 从 ID 列表中移除 /**
this.removeId(id); * 添加 ID 到列表
*/
return true; private addId(id: number | string): void {
const ids = this.getIds();
if (!ids.includes(id)) {
ids.push(id);
this.saveIds(ids);
}
} }
/** /**
* 批量删除(优化版本,直接操作 ID 列表) * 深拷贝对象
* @param ids 要删除的 ID 数组
*/ */
deleteByIds(ids: (string | number)[]): number { private deepClone(obj: any): any | null {
if (ids.length == 0) { // UTS 要求返回类型明确包含 null
return 0; if (obj == null) {
return null;
}
if (typeof obj === "object") {
return JSON.parse(JSON.stringify(obj));
}
return obj;
} }
let count = 0; /**
const allIds = this.getIds(); * 生成唯一 ID
* 使用时间戳 + 随机字符串,确保唯一性
*/
private generateId(): string {
return `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
}
// 批量删除存储 /**
for (let i = 0; i < ids.length; i++) { * 获取所有记录的 ID 列表
const id = ids[i]; */
const key = this.getRecordKey(id); private getIds(): (number | string)[] {
try { const ids = uni.getStorageSync(this.idsKey);
uni.removeStorageSync(key); if (isNull(ids) || !isArray(ids)) {
count++; return [];
} catch (error) {
console.error(`[LocalStore] 删除失败 ID=${id}:`, error);
} }
return ids as (number | string)[];
} }
// 批量更新 ID 列表(一次性操作) /**
const remainingIds: (string | number)[] = []; * 获取索引的存储 key
for (let i = 0; i < allIds.length; i++) { */
if (!ids.includes(allIds[i])) { private getIndexKey(field: string, value: any): string {
remainingIds.push(allIds[i]); const valueStr = typeof value === "string" ? value : JSON.stringify(value);
} return `${this.indexPrefix}:${field}:${valueStr}`;
} }
this.saveIds(remainingIds);
return count; /**
* 获取记录的存储 key
*/
private getRecordKey(id: number | string): string {
// UTS 不支持 String() 构造函数,使用 toString() 或模板字符串
const idStr = typeof id === "string" ? id : id.toString();
return `${this.prefix}:${idStr}`;
} }
/** /**
...@@ -459,8 +775,7 @@ class LocalStore<T extends any> { ...@@ -459,8 +775,7 @@ class LocalStore<T extends any> {
// UTS 不支持 for...in 循环,使用 keys() 函数获取键数组 // UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
private matchCondition(record: RecordWithId<T>, condition: QueryCondition<T>): boolean { private matchCondition(record: RecordWithId<T>, condition: QueryCondition<T>): boolean {
const conditionKeys = keys(condition); const conditionKeys = keys(condition);
for (let i = 0; i < conditionKeys.length; i++) { for (const field of conditionKeys) {
const field = conditionKeys[i];
// UTS 对象属性访问需要使用 get 函数 // UTS 对象属性访问需要使用 get 函数
const fieldValue = get(record, field); const fieldValue = get(record, field);
const conditionValue = get(condition, field); const conditionValue = get(condition, field);
...@@ -470,7 +785,7 @@ class LocalStore<T extends any> { ...@@ -470,7 +785,7 @@ class LocalStore<T extends any> {
} }
// 简单值匹配(等于) // 简单值匹配(等于)
if (typeof conditionValue != "object") { if (typeof conditionValue !== "object") {
if (fieldValue != conditionValue) { if (fieldValue != conditionValue) {
return false; return false;
} }
...@@ -500,7 +815,7 @@ class LocalStore<T extends any> { ...@@ -500,7 +815,7 @@ class LocalStore<T extends any> {
// $gt - 大于 // $gt - 大于
if (has(operators, "$gt")) { if (has(operators, "$gt")) {
const gtValue = get(operators, "$gt") as number; const gtValue = get(operators, "$gt") as number;
if (typeof fieldValue != "number") { if (typeof fieldValue !== "number") {
return false; return false;
} }
const numValue = fieldValue as number; const numValue = fieldValue as number;
...@@ -512,7 +827,7 @@ class LocalStore<T extends any> { ...@@ -512,7 +827,7 @@ class LocalStore<T extends any> {
// $gte - 大于等于 // $gte - 大于等于
if (has(operators, "$gte")) { if (has(operators, "$gte")) {
const gteValue = get(operators, "$gte") as number; const gteValue = get(operators, "$gte") as number;
if (typeof fieldValue != "number") { if (typeof fieldValue !== "number") {
return false; return false;
} }
const numValue = fieldValue as number; const numValue = fieldValue as number;
...@@ -524,7 +839,7 @@ class LocalStore<T extends any> { ...@@ -524,7 +839,7 @@ class LocalStore<T extends any> {
// $lt - 小于 // $lt - 小于
if (has(operators, "$lt")) { if (has(operators, "$lt")) {
const ltValue = get(operators, "$lt") as number; const ltValue = get(operators, "$lt") as number;
if (typeof fieldValue != "number") { if (typeof fieldValue !== "number") {
return false; return false;
} }
const numValue = fieldValue as number; const numValue = fieldValue as number;
...@@ -536,7 +851,7 @@ class LocalStore<T extends any> { ...@@ -536,7 +851,7 @@ class LocalStore<T extends any> {
// $lte - 小于等于 // $lte - 小于等于
if (has(operators, "$lte")) { if (has(operators, "$lte")) {
const lteValue = get(operators, "$lte") as number; const lteValue = get(operators, "$lte") as number;
if (typeof fieldValue != "number") { if (typeof fieldValue !== "number") {
return false; return false;
} }
const numValue = fieldValue as number; const numValue = fieldValue as number;
...@@ -572,10 +887,10 @@ class LocalStore<T extends any> { ...@@ -572,10 +887,10 @@ class LocalStore<T extends any> {
// $like - 字符串匹配(简单实现) // $like - 字符串匹配(简单实现)
if (has(operators, "$like")) { if (has(operators, "$like")) {
const likeValue = get(operators, "$like") as string; const likeValue = get(operators, "$like") as string;
if (typeof fieldValue != "string" || typeof likeValue != "string") { if (typeof fieldValue !== "string" || typeof likeValue !== "string") {
return false; return false;
} }
const pattern = likeValue.replace(/%/g, ".*"); const pattern = likeValue.replaceAll("%", ".*");
const regex = new RegExp(`^${pattern}$`); const regex = new RegExp(`^${pattern}$`);
if (!regex.test(fieldValue)) { if (!regex.test(fieldValue)) {
return false; return false;
...@@ -597,385 +912,59 @@ class LocalStore<T extends any> { ...@@ -597,385 +912,59 @@ class LocalStore<T extends any> {
} }
/** /**
* 查询记录 * 合并默认值
*/
find(options?: FindOptions<T>): RecordWithId<T>[] {
const ids = this.getIds();
let results: RecordWithId<T>[] = [];
// 获取所有记录
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const record = this.get(id);
if (record != null) {
results.push(record);
}
}
// 应用查询条件
if (options != null && options.where != null) {
results = results.filter((record) => this.matchCondition(record, options.where!));
}
// 应用排序
if (options != null && options.sort != null && options.sort.length > 0) {
results.sort((a, b) => {
for (let i = 0; i < options.sort!.length; i++) {
const sortOption = options.sort![i];
const field = sortOption.field;
// UTS 对象属性访问需要使用 get 函数,get 返回 any | null
const aValueAny = get(a, field);
const bValueAny = get(b, field);
// 如果值为 null,跳过比较(null 值排在最后)
if (isNull(aValueAny) || isNull(bValueAny)) {
if (isNull(aValueAny) && isNull(bValueAny)) {
continue; // 两个都是 null,继续下一个字段
}
// 一个为 null,另一个不为 null,null 排在后面
return isNull(aValueAny) ? 1 : -1;
}
// 确保值不为 null,使用类型断言
const aValue = aValueAny as any;
const bValue = bValueAny as any;
let comparison = 0;
if (typeof aValue == "number" && typeof bValue == "number") {
comparison = aValue - bValue;
} else if (typeof aValue == "string" && typeof bValue == "string") {
// UTS 不支持直接使用 < > 比较字符串,手动实现字符串比较
const aStr = aValue as string;
const bStr = bValue as string;
const aLen = aStr.length;
const bLen = bStr.length;
const minLen = aLen < bLen ? aLen : bLen;
// 逐个字符比较(使用字符串索引访问)
for (let j = 0; j < minLen; j++) {
// UTS 字符串索引访问,charCodeAt 返回 Number?,这里断言为 number
const aCharCode = aStr.charCodeAt(j) as number;
const bCharCode = bStr.charCodeAt(j) as number;
if (aCharCode < bCharCode) {
comparison = -1;
break;
} else if (aCharCode > bCharCode) {
comparison = 1;
break;
}
}
// 如果前面的字符都相同,比较长度
if (comparison == 0) {
if (aLen < bLen) {
comparison = -1;
} else if (aLen > bLen) {
comparison = 1;
}
}
}
if (comparison != 0) {
return sortOption.order == "asc" ? comparison : -comparison;
}
}
return 0;
});
}
// 应用 skip
if (options != null && options.skip != null) {
const skipValue = options.skip;
if (skipValue > 0) {
results = results.slice(skipValue);
}
}
// 应用 limit
if (options != null && options.limit != null) {
const limitValue = options.limit;
if (limitValue > 0) {
results = results.slice(0, limitValue);
}
}
return results;
}
/**
* 查找单条记录
*/
findOne(id: string | number): RecordWithId<T> | null {
return this.get(id);
}
/**
* 查找第一条匹配的记录
*/
findFirst(where?: QueryCondition<T>): RecordWithId<T> | null {
const results = this.find({ where, limit: 1 });
return results.length > 0 ? results[0] : null;
}
/**
* 统计记录数量
*/
count(where?: QueryCondition<T>): number {
if (where == null) {
return this.getIds().length;
}
return this.find({ where }).length;
}
/**
* 批量插入
* 内部自动分批处理,避免一次性操作过多导致性能问题
* @param items 要插入的数据数组
* @param batchSize 每批处理的条数,默认100条
*/ */
// UTS 不支持 Partial<T>,使用 any 类型 // UTS 不支持 Partial<T>,使用 any 类型
insertMany(items: any[], batchSize: number = 100): (string | number)[] { // UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
const ids: (string | number)[] = []; // UTS 对象属性访问需要使用 UTSJSONObject 方式
const total = items.length; private mergeDefaults(data: any): T {
const result = this.deepClone(this.defaults) as T;
// 如果数据量小于批次大小,直接处理 const dataKeys = keys(data);
if (total <= batchSize) { for (const key of dataKeys) {
for (let i = 0; i < items.length; i++) { if (has(this.defaults, key)) {
try { // UTS 对象属性访问需要使用 get 和 set 函数
// UTS 不支持 undefined,使用 null 作为可选参数占位 const value = get(data, key);
const id = this.insert(items[i], null); set(result, key, value);
ids.push(id);
} catch (error) {
console.error(`[LocalStore] 批量插入失败:`, error);
}
}
return ids;
}
// 大数据量时,分批处理
const batchCount = Math.ceil(total / batchSize);
for (let batch = 0; batch < batchCount; batch++) {
const start = batch * batchSize;
const end = Math.min(start + batchSize, total);
// 处理当前批次
for (let i = start; i < end; i++) {
try {
// UTS 不支持 undefined,使用 null 作为可选参数占位
const id = this.insert(items[i], null);
ids.push(id);
} catch (error) {
console.error(`[LocalStore] 批量插入失败 [${i + 1}/${total}]:`, error);
}
}
}
return ids;
}
/**
* 批量更新
*/
updateMany(where: QueryCondition<T>, updates: UpdateData<T>): number {
const records = this.find({ where });
let count = 0;
for (let i = 0; i < records.length; i++) {
const recordAny = records[i] as any;
// 通过 get 获取 id,避免直接访问属性导致类型问题
const idValue = get(recordAny, "id") as string | number | null;
if (!isNull(idValue) && this.update(idValue as string | number, updates)) {
count++;
}
}
return count;
}
/**
* 批量删除
*/
deleteMany(where: QueryCondition<T>): number {
const records = this.find({ where });
if (records.length == 0) {
return 0;
}
let count = 0;
for (let i = 0; i < records.length; i++) {
const record = records[i];
const recordAny = record as any;
// 通过 get 获取 id,避免直接访问属性导致类型问题
const idValue = get(recordAny, "id") as string | number | null;
if (record != null && !isNull(idValue) && this.delete(idValue as string | number)) {
count++;
} }
} }
return count; return result;
} }
/** /**
* 清空所有记录 * 从列表中移除 ID
*/ */
clear(): void { private removeId(id: number | string): void {
const ids = this.getIds(); const ids = this.getIds();
for (let i = 0; i < ids.length; i++) { const index = ids.indexOf(id);
const key = this.getRecordKey(ids[i]); if (index != -1) {
uni.removeStorageSync(key); ids.splice(index, 1);
} this.saveIds(ids);
this.saveIds([]);
}
/**
* 获取所有记录
*/
findAll(): RecordWithId<T>[] {
// UTS 要求显式传入参数,这里传入空配置对象
const emptyOptions: any = {};
return this.find(emptyOptions as FindOptions<T>);
}
/**
* 创建索引(用于快速查找)
* @param field 要建立索引的字段名
*/
// UTS 不支持 keyof T,使用 string 类型
createIndex(field: string): void {
// 获取所有记录
const records = this.findAll();
// 清空该字段的旧索引
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
uni.removeStorageSync(indexKey);
// 建立新索引:字段值 -> ID 列表
// UTS 不支持 Record 类型,使用 any 类型
const index: any = {};
for (let i = 0; i < records.length; i++) {
const record = records[i];
// UTS 对象属性访问需要使用 get 函数
const value = get(record, field);
// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
const valueKey =
value != null ? (typeof value == "string" ? value : value.toString()) : "__null__";
// 使用 set 和 get 维护索引,避免直接使用下标访问
// 显式指定空数组类型为 any[]
const emptyArray: any[] = [];
if (!has(index, valueKey)) {
set(index, valueKey, emptyArray);
}
let idList = get(index, valueKey) as any[] | null;
// 确保 idList 不为 null,强制断言为非空数组
if (isNull(idList) || !isArray(idList)) {
idList = [];
}
// 使用非空断言,确保 idList 是数组类型
const idListArray = idList as any[];
const recordAny = record as any;
const idValue = get(recordAny, "id");
// idValue 可能为 null,需要检查后使用类型断言
if (!isNull(idValue)) {
// idListArray 是非空数组,idValue 也不为 null
idListArray.push(idValue as any);
}
set(index, valueKey, idListArray);
}
// 保存索引
uni.setStorageSync(indexKey, index);
}
/**
* 根据索引查找记录
* @param field 索引字段
* @param value 字段值
*/
// UTS 不支持 keyof T,使用 string 类型
findByIndex(field: string, value: any): RecordWithId<T>[] {
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
// UTS 不支持 Record 类型,使用 any 类型
const index = uni.getStorageSync(indexKey) as any | null;
if (isNull(index)) {
// 索引不存在,使用普通查询
// UTS 不支持计算属性名 [field],需要先创建对象
const whereCondition: any = {};
set(whereCondition, field, value);
return this.find({ where: whereCondition as QueryCondition<T> });
}
// index 已经检查过不为 null,使用类型断言
// UTS 不支持 Record 类型,使用 any 类型
const indexObj = index as any;
// UTS 不支持 String() 构造函数,使用 toString() 或类型检查
const valueKey =
value != null ? (typeof value == "string" ? value : value.toString()) : "__null__";
// 使用 get 获取 ids,避免下标访问
const idsAny = get(indexObj, valueKey);
if (isNull(idsAny) || !isArray(idsAny)) {
return [];
}
// 确保 ids 是数组类型
const ids = idsAny as any[];
const results: RecordWithId<T>[] = [];
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const record = this.get(id);
if (record != null) {
results.push(record);
}
}
return results;
} }
/**
* 删除索引
*/
// UTS 不支持 keyof T,使用 string 类型
dropIndex(field: string): void {
// UTS 不支持 String() 构造函数,field 已经是 string 类型
const indexKey = `${this.indexPrefix}:${field}:__all__`;
uni.removeStorageSync(indexKey);
} }
/** /**
* 重建所有索引(在数据迁移后使用) * 保存 ID 列表
*/ */
// UTS 不支持 keyof T,使用 string[] 类型 private saveIds(ids: (number | string)[]): void {
rebuildIndexes(fields: string[]): void { uni.setStorageSync(this.idsKey, ids);
for (let i = 0; i < fields.length; i++) {
this.createIndex(fields[i]);
}
} }
/** /**
* 获取存储统计信息 * 验证数据是否符合 schema
*/ */
getStats(): Stats { // UTS 不支持 Partial<T>,使用 any 类型
const ids = this.getIds(); // UTS 不支持 for...in 循环,使用 keys() 函数获取键数组
let totalSize = 0; private validateData(data: any): boolean {
const dataKeys = keys(data);
// 估算存储大小(简单实现) for (const key of dataKeys) {
for (let i = 0; i < ids.length; i++) { if (!has(this.defaults, key)) {
const record = this.get(ids[i]); console.warn(`[LocalStore] 未知字段 "${key}" 在 store "${this.prefix}" 中`);
if (record != null) { return false;
const recordStr = JSON.stringify(record);
totalSize += recordStr.length;
} }
} }
return true;
return {
total: ids.length,
size: totalSize
};
} }
} }
export default LocalStore; export default LocalStore;
export type { QueryCondition, FindOptions, SortOption, RecordWithId, UpdateData, Stats }; export type { FindOptions, QueryCondition, RecordWithId, SortOption, Stats, UpdateData };
...@@ -4,7 +4,7 @@ import { forEach, forInObject, isArray, isObject, isString } from "./common"; ...@@ -4,7 +4,7 @@ import { forEach, forInObject, isArray, isObject, isString } from "./common";
* 解析数据 * 解析数据
* @example parse<Response>(res.data) * @example parse<Response>(res.data)
*/ */
export function parse<T>(data: any): T | null { export function parse<T>(data: any): null | T {
// #ifdef APP-ANDROID // #ifdef APP-ANDROID
// @ts-ignore // @ts-ignore
return (data as UTSJSONObject).parse<T>(); return (data as UTSJSONObject).parse<T>();
...@@ -20,7 +20,7 @@ export function parse<T>(data: any): T | null { ...@@ -20,7 +20,7 @@ export function parse<T>(data: any): T | null {
* @param data 要解析的数据 * @param data 要解析的数据
* @returns 解析后的JSON对象 * @returns 解析后的JSON对象
*/ */
export function parseObject<T>(data: string): T | null { export function parseObject<T>(data: string): null | T {
// #ifdef APP-ANDROID // #ifdef APP-ANDROID
return JSON.parseObject<T>(data); return JSON.parseObject<T>(data);
// #endif // #endif
...@@ -159,8 +159,8 @@ export const px2rpx = (px: number): number => { ...@@ -159,8 +159,8 @@ export const px2rpx = (px: number): number => {
* parseRpx('10px') // 返回 '10px' * parseRpx('10px') // 返回 '10px'
*/ */
export const parseRpx = (val: number | string): string => { export const parseRpx = (val: number | string): string => {
if (typeof val == "number") { if (typeof val === "number") {
return val + "rpx"; return `${val }rpx`;
} }
return val; return val;
...@@ -179,7 +179,7 @@ export const parseRpx = (val: number | string): string => { ...@@ -179,7 +179,7 @@ export const parseRpx = (val: number | string): string => {
export const getNum = (val: string): number => { export const getNum = (val: string): number => {
// 使用正则提取数字部分,支持小数和负数 // 使用正则提取数字部分,支持小数和负数
const match = val.match(/-?\d+(\.\d+)?/); const match = val.match(/-?\d+(\.\d+)?/);
return match != null ? parseFloat(match[0] ?? "0") : 0; return match != null ? Number.parseFloat(match[0] ?? "0") : 0;
}; };
/** /**
...@@ -205,7 +205,7 @@ export const getUnit = (val: string): string => { ...@@ -205,7 +205,7 @@ export const getUnit = (val: string): string => {
* @returns number - 返回对应的 rpx 数值 * @returns number - 返回对应的 rpx 数值
*/ */
export const getRpx = (val: number | string): number => { export const getRpx = (val: number | string): number => {
if (typeof val == "number") { if (typeof val === "number") {
return val; return val;
} }
...@@ -228,8 +228,8 @@ export const getRpx = (val: number | string): number => { ...@@ -228,8 +228,8 @@ export const getRpx = (val: number | string): number => {
* @param val - 输入值,可以是 "10rpx"、"10px" 或数字 10 * @param val - 输入值,可以是 "10rpx"、"10px" 或数字 10
* @returns number - 返回对应的 px 数值 * @returns number - 返回对应的 px 数值
*/ */
export const getPx = (val: string | number) => { export const getPx = (val: number | string) => {
if (typeof val == "number") { if (typeof val === "number") {
return rpx2px(val); return rpx2px(val);
} }
......
...@@ -59,12 +59,12 @@ export function openAppSettings(): void { ...@@ -59,12 +59,12 @@ export function openAppSettings(): void {
*/ */
export function getInstalledPackages(): Promise< export function getInstalledPackages(): Promise<
Array<{ Array<{
appName: string;
packName: string; packName: string;
versionName: string;
versionCode: number; versionCode: number;
appName: string; versionName: string;
}> }>
> { > {
// #ifdef APP-ANDROID // #ifdef APP-ANDROID
const packages = androidImpl.getInstalledPackages(); const packages = androidImpl.getInstalledPackages();
return Promise.resolve(packages); return Promise.resolve(packages);
......
...@@ -60,8 +60,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -60,8 +60,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.readFile({ fs.readFile({
filePath: filePath, filePath,
encoding: encoding, encoding,
success: (res: any) => { success: (res: any) => {
// ReadFileSuccessResult 类型,data 类型为 string | ArrayBuffer // ReadFileSuccessResult 类型,data 类型为 string | ArrayBuffer
// 由于 ReadFileSuccessResult 不是 UTSJSONObject,需要特殊处理 // 由于 ReadFileSuccessResult 不是 UTSJSONObject,需要特殊处理
...@@ -77,10 +77,10 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -77,10 +77,10 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
if (parsed != null) { if (parsed != null) {
const temp = parsed.getAny("data"); const temp = parsed.getAny("data");
console.error("readFile getAny('data'): ", temp); console.error("readFile getAny('data'):", temp);
raw = temp != null ? temp as any : null; raw = temp != null ? temp as any : null;
} }
} catch (e: any) { } catch {
// 方法2:如果 parseObject 失败,尝试用普通 parse // 方法2:如果 parseObject 失败,尝试用普通 parse
try { try {
...@@ -90,16 +90,16 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -90,16 +90,16 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// 尝试从解析后的对象中获取 data // 尝试从解析后的对象中获取 data
if (parsed != null) { if (parsed != null) {
const temp = get(parsed as UTSJSONObject, "data"); const temp = get(parsed as UTSJSONObject, "data");
console.error("readFile get('data'): ", temp); console.error("readFile get('data'):", temp);
raw = temp != null ? temp as any : null; raw = temp != null ? temp as any : null;
} }
} catch (e2: any) { } catch (error: any) {
console.error("readFile method2 failed: ", e2); console.error("readFile method2 failed:", error);
} }
} }
if (raw != null) { if (raw != null) {
if (typeof raw == "string") { if (typeof raw === "string") {
text = raw as string; text = raw as string;
} else { } else {
// ArrayBuffer 类型,需要转换为字符串 // ArrayBuffer 类型,需要转换为字符串
...@@ -110,8 +110,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -110,8 +110,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// @ts-ignore // @ts-ignore
const decoder = new TextDecoder("utf-8"); const decoder = new TextDecoder("utf-8");
text = decoder.decode(raw as ArrayBuffer); text = decoder.decode(raw as ArrayBuffer);
} catch (e: any) { } catch (error: any) {
console.error("ArrayBuffer decode error: ", e); console.error("ArrayBuffer decode error:", error);
text = ""; text = "";
} }
// #endif // #endif
...@@ -121,11 +121,11 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -121,11 +121,11 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// #endif // #endif
} }
} }
console.error("readFile text final: ", text); console.error("readFile text final:", text);
resolve(text); resolve(text);
}, },
fail: (err: any) => { fail: (err: any) => {
console.error("readFile fail: ", err); console.error("readFile fail:", err);
reject(err); reject(err);
} }
}); });
...@@ -141,8 +141,8 @@ export function writeFile(filePath: string, data: string): Promise<void> { ...@@ -141,8 +141,8 @@ export function writeFile(filePath: string, data: string): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.writeFile({ fs.writeFile({
filePath: filePath, filePath,
data: data, data,
encoding: "utf-8", encoding: "utf-8",
success: () => { success: () => {
resolve(); resolve();
...@@ -162,7 +162,7 @@ export function deleteFile(filePath: string): Promise<void> { ...@@ -162,7 +162,7 @@ export function deleteFile(filePath: string): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.unlink({ fs.unlink({
filePath: filePath, filePath,
success: () => { success: () => {
resolve(); resolve();
}, },
...@@ -181,10 +181,10 @@ export function readDirectory(dirPath: string): Promise<string[]> { ...@@ -181,10 +181,10 @@ export function readDirectory(dirPath: string): Promise<string[]> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.readdir({ fs.readdir({
dirPath: dirPath, dirPath,
success: (res: any) => { success: (res: any) => {
const files = res.files; const files = res.files;
if (files instanceof Array) { if (Array.isArray(files)) {
resolve(files as string[]); resolve(files as string[]);
} else { } else {
resolve([]); resolve([]);
...@@ -206,8 +206,8 @@ export function createDirectory(dirPath: string, recursive: boolean = false): Pr ...@@ -206,8 +206,8 @@ export function createDirectory(dirPath: string, recursive: boolean = false): Pr
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.mkdir({ fs.mkdir({
dirPath: dirPath, dirPath,
recursive: recursive, recursive,
success: () => { success: () => {
resolve(); resolve();
}, },
...@@ -227,8 +227,8 @@ export function deleteDirectory(dirPath: string, recursive: boolean = false): Pr ...@@ -227,8 +227,8 @@ export function deleteDirectory(dirPath: string, recursive: boolean = false): Pr
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.rmdir({ fs.rmdir({
dirPath: dirPath, dirPath,
recursive: recursive, recursive,
success: () => { success: () => {
resolve(); resolve();
}, },
......
...@@ -35,7 +35,7 @@ export function setUserAgent(userAgent: string): void { ...@@ -35,7 +35,7 @@ export function setUserAgent(userAgent: string): void {
// #ifndef APP // #ifndef APP
// H5 可以设置 navigator.userAgent // H5 可以设置 navigator.userAgent
if (typeof navigator != "undefined") { if (typeof navigator !== "undefined") {
Object.defineProperty(navigator, "userAgent", { Object.defineProperty(navigator, "userAgent", {
get: () => userAgent, get: () => userAgent,
configurable: true configurable: true
......
...@@ -11,8 +11,8 @@ import { openSchema } from "@/uni_modules/uts-openSchema"; ...@@ -11,8 +11,8 @@ import { openSchema } from "@/uni_modules/uts-openSchema";
// 应用信息类型 // 应用信息类型
type AppInfo = { type AppInfo = {
version: string;
appid: string; appid: string;
version: string;
}; };
/** /**
...@@ -32,8 +32,8 @@ export function getAppVersion(): string { ...@@ -32,8 +32,8 @@ export function getAppVersion(): string {
} }
} }
// #endif // #endif
} catch (e: any) { } catch (error: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败: ", e); console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败:", error);
} }
// 其它平台或获取失败时返回空字符串,由上层决定是否展示 // 其它平台或获取失败时返回空字符串,由上层决定是否展示
...@@ -55,8 +55,8 @@ export function getAppId(): string { ...@@ -55,8 +55,8 @@ export function getAppId(): string {
} }
} }
// #endif // #endif
} catch (e: any) { } catch (error: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败: ", e); console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败:", error);
} }
return ""; return "";
...@@ -67,7 +67,7 @@ export function getAppId(): string { ...@@ -67,7 +67,7 @@ export function getAppId(): string {
* @param url 要打开的URL * @param url 要打开的URL
*/ */
export function openURL(url: string): void { export function openURL(url: string): void {
if (url == null || url.length == 0) { if (url == null || url.length === 0) {
console.error("[plus-runtime] URL不能为空"); console.error("[plus-runtime] URL不能为空");
return; return;
} }
...@@ -78,14 +78,14 @@ export function openURL(url: string): void { ...@@ -78,14 +78,14 @@ export function openURL(url: string): void {
try { try {
openSchema(url); openSchema(url);
return; return;
} catch (e: any) { } catch (error: any) {
console.error("[plus-runtime] 使用 openSchema 打开 URL 失败: ", e, " url=", url); console.error("[plus-runtime] 使用 openSchema 打开 URL 失败:", error, "url=", url);
} }
// #endif // #endif
// 其它平台或兜底逻辑:H5 使用 window.open // 其它平台或兜底逻辑:H5 使用 window.open
// #ifndef APP // #ifndef APP
if (typeof window != "undefined") { if (typeof window !== "undefined") {
window.open(url, "_blank"); window.open(url, "_blank");
} }
// #endif // #endif
......
import { PAGES, TABS } from "./ctx";
import type { BackOptions, PageInstance, PushOptions } from "../types/router"; import type { BackOptions, PageInstance, PushOptions } from "../types/router";
import { import {
storage, debounce,
last,
isNull,
isEmpty,
get, get,
isEmpty,
isFunction, isFunction,
toArray, isNull,
last,
map, map,
debounce,
nth, nth,
assign, storage,
parse toArray
} from "../utils"; } from "../utils";
import { PAGES, TABS } from "./ctx";
// 路由信息类型 // 路由信息类型
type RouteInfo = { type RouteInfo = {
isAuth?: boolean;
meta: UTSJSONObject;
path: string; path: string;
query: UTSJSONObject; query: UTSJSONObject;
meta: UTSJSONObject;
isAuth?: boolean;
}; };
// 跳转前钩子类型 // 跳转前钩子类型
...@@ -30,22 +29,81 @@ type AfterLogin = () => void; ...@@ -30,22 +29,81 @@ type AfterLogin = () => void;
// 路由事件集合 // 路由事件集合
type Events = { type Events = {
beforeEach?: BeforeEach;
afterLogin?: AfterLogin; afterLogin?: AfterLogin;
beforeEach?: BeforeEach;
}; };
// 路由核心类 // 路由核心类
export class Router { export class Router {
// 跳转到登录页(防抖处理)
login = debounce(() => {
if (!this.isLoginPage(this.path())) {
this.push({
path: "/pages/user/login",
mode: "reLaunch"
});
}
}, 300);
private eventsMap = {} as Events; // 事件存储 private eventsMap = {} as Events; // 事件存储
// 获取传递的 params 参数 // 注册登录后回调
params() { afterLogin(cb: AfterLogin) {
return (storage.get("router-params") ?? {}) as UTSJSONObject; this.eventsMap.afterLogin = cb;
} }
// 获取传递的 query 参数 // 返回上一页
query() { back(options: BackOptions | null = null) {
return this.route()?.query ?? {}; if (this.isFirstPage()) {
this.home();
} else {
const delta = options?.delta ?? 1;
// 执行跳转函数
const next = () => {
uni.navigateBack({ ...options });
};
// 跳转前钩子处理
if (this.eventsMap.beforeEach != null) {
// 当前页
const from = last(this.getPages());
// 上一页
const to = nth(this.getPages(), -delta - 1);
if (to != null) {
// 调用跳转前钩子
this.eventsMap.beforeEach(
{
path: to.path,
query: to.query,
meta: to.meta ?? ({} as UTSJSONObject)
},
from!,
next
);
} else {
console.error("[router] found to page is null");
}
} else {
next();
}
}
}
// 注册跳转前钩子
beforeEach(cb: BeforeEach) {
this.eventsMap.beforeEach = cb;
}
// 执行当前页面暴露的方法
callMethod(name: string, data?: any): any | null {
const fn = get(this.route()!, `$vm.$.exposed.${name}`) as (d?: any) => any | null;
if (isFunction(fn)) {
return fn(data);
}
return null;
} }
// 获取默认路径,支持 home 和 login // 获取默认路径,支持 home 和 login
...@@ -58,6 +116,16 @@ export class Router { ...@@ -58,6 +116,16 @@ export class Router {
return get(paths, name) as string; return get(paths, name) as string;
} }
// 获取页面元数据
getMeta(path: string) {
return PAGES.find((e) => path.includes(e.path))?.meta ?? ({} as UTSJSONObject);
}
// 获取指定路径的页面实例
getPage(path: string) {
return this.getPages().find((e) => e.path == path);
}
// 获取当前页面栈的所有页面实例 // 获取当前页面栈的所有页面实例
getPages(): PageInstance[] { getPages(): PageInstance[] {
return map(getCurrentPages(), (e) => { return map(getCurrentPages(), (e) => {
...@@ -70,7 +138,7 @@ export class Router { ...@@ -70,7 +138,7 @@ export class Router {
// 补全路径前缀 // 补全路径前缀
if (!path.startsWith("/")) { if (!path.startsWith("/")) {
path = "/" + path; path = `/${ path}`;
} }
// 获取页面样式 // 获取页面样式
...@@ -104,27 +172,82 @@ export class Router { ...@@ -104,27 +172,82 @@ export class Router {
}); });
} }
// 获取指定路径的页面实例 // 回到首页
getPage(path: string) { home() {
return this.getPages().find((e) => e.path == path); this.push({
path: this.defaultPath("home")
});
} }
// 获取当前路由页面实例 // 判断是否为当前页面
route() { isCurrentPage(path: string) {
return last(this.getPages()); return this.path() == path;
} }
// 获取当前页面路径 // 判断是否为自定义导航栏页面
path() { isCustomNavbarPage() {
return this.route()?.path ?? ""; return this.route()?.isCustomNavbar ?? false;
} }
// 简单跳转页面(默认 navigateTo) // 判断页面栈是否只有一个页面
to(path: string) { isFirstPage() {
this.push({ return getCurrentPages().length == 1;
path }
// 判断是否为首页
isHomePage() {
return this.path() == this.defaultPath("home");
}
// 判断是否为登录页
isLoginPage(path: string) {
return path == this.defaultPath("login");
}
// 判断是否为 tab 页面
isTabPage(path: null | string = null) {
if (path == null) {
path = this.path();
}
if (path == "/") {
path = this.defaultPath("home");
}
return !isNull(TABS.find((e) => path == e.pagePath));
}
// 登录成功后跳转逻辑
nextLogin() {
const pages = this.getPages();
// 找到登录页的索引
const index = pages.findIndex((e) => this.defaultPath("login").includes(e.path));
// 未找到,则跳回首页
if (index === -1) {
this.home();
} else {
this.back({
delta: pages.length - index
}); });
} }
// 登录后回调
if (this.eventsMap.afterLogin != null) {
this.eventsMap.afterLogin!();
}
// 触发全局 afterLogin 事件
uni.$emit("afterLogin");
}
// 获取传递的 params 参数
params() {
return (storage.get("router-params") ?? {}) as UTSJSONObject;
}
// 获取当前页面路径
path() {
return this.route()?.path ?? "";
}
// 路由跳转,支持多种模式和参数 // 路由跳转,支持多种模式和参数
push(options: PushOptions) { push(options: PushOptions) {
...@@ -147,7 +270,7 @@ export class Router { ...@@ -147,7 +270,7 @@ export class Router {
const arr = toArray(query, (v, k) => { const arr = toArray(query, (v, k) => {
return `${k}=${v}`; return `${k}=${v}`;
}); });
path += "?" + arr.join("&"); path += `?${ arr.join("&")}`;
} }
// params 通过 storage 临时存储 // params 通过 storage 临时存储
...@@ -163,7 +286,7 @@ export class Router { ...@@ -163,7 +286,7 @@ export class Router {
// 跳转执行函数 // 跳转执行函数
const next = () => { const next = () => {
switch (mode) { switch (mode) {
case "navigateTo": case "navigateTo": {
uni.navigateTo({ uni.navigateTo({
url: path, url: path,
success, success,
...@@ -174,7 +297,8 @@ export class Router { ...@@ -174,7 +297,8 @@ export class Router {
animationDuration animationDuration
}); });
break; break;
case "redirectTo": }
case "redirectTo": {
uni.redirectTo({ uni.redirectTo({
url: path, url: path,
success, success,
...@@ -182,7 +306,8 @@ export class Router { ...@@ -182,7 +306,8 @@ export class Router {
complete complete
}); });
break; break;
case "reLaunch": }
case "reLaunch": {
uni.reLaunch({ uni.reLaunch({
url: path, url: path,
success, success,
...@@ -190,7 +315,8 @@ export class Router { ...@@ -190,7 +315,8 @@ export class Router {
complete complete
}); });
break; break;
case "switchTab": }
case "switchTab": {
uni.switchTab({ uni.switchTab({
url: path, url: path,
success, success,
...@@ -199,6 +325,7 @@ export class Router { ...@@ -199,6 +325,7 @@ export class Router {
}); });
break; break;
} }
}
}; };
// 跳转前钩子处理 // 跳转前钩子处理
...@@ -216,146 +343,22 @@ export class Router { ...@@ -216,146 +343,22 @@ export class Router {
} }
} }
// 回到首页 // 获取传递的 query 参数
home() { query() {
this.push({ return this.route()?.query ?? {};
path: this.defaultPath("home")
});
}
// 返回上一页
back(options: BackOptions | null = null) {
if (this.isFirstPage()) {
this.home();
} else {
const delta = options?.delta ?? 1;
// 执行跳转函数
const next = () => {
uni.navigateBack({ ...(options ?? {}) });
};
// 跳转前钩子处理
if (this.eventsMap.beforeEach != null) {
// 当前页
const from = last(this.getPages());
// 上一页
const to = nth(this.getPages(), -delta - 1);
if (to != null) {
// 调用跳转前钩子
this.eventsMap.beforeEach(
{
path: to.path,
query: to.query,
meta: to.meta ?? ({} as UTSJSONObject)
},
from!,
next
);
} else {
console.error("[router] found to page is null");
}
} else {
next();
}
}
}
// 获取页面元数据
getMeta(path: string) {
return PAGES.find((e) => path.includes(e.path))?.meta ?? ({} as UTSJSONObject);
}
// 执行当前页面暴露的方法
callMethod(name: string, data?: any): any | null {
const fn = get(this.route()!, `$vm.$.exposed.${name}`) as (d?: any) => any | null;
if (isFunction(fn)) {
return fn(data);
}
return null;
}
// 判断页面栈是否只有一个页面
isFirstPage() {
return getCurrentPages().length == 1;
}
// 判断是否为首页
isHomePage() {
return this.path() == this.defaultPath("home");
}
// 判断是否为自定义导航栏页面
isCustomNavbarPage() {
return this.route()?.isCustomNavbar ?? false;
}
// 判断是否为当前页面
isCurrentPage(path: string) {
return this.path() == path;
}
// 判断是否为 tab 页面
isTabPage(path: string | null = null) {
if (path == null) {
path = this.path();
}
if (path == "/") {
path = this.defaultPath("home");
}
return !isNull(TABS.find((e) => path == e.pagePath));
} }
// 判断是否为登录页 // 获取当前路由页面实例
isLoginPage(path: string) { route() {
return path == this.defaultPath("login"); return last(this.getPages());
} }
// 跳转到登录页(防抖处理) // 简单跳转页面(默认 navigateTo)
login = debounce(() => { to(path: string) {
if (!this.isLoginPage(this.path())) {
this.push({ this.push({
path: "/pages/user/login", path
mode: "reLaunch"
});
}
}, 300);
// 登录成功后跳转逻辑
nextLogin() {
const pages = this.getPages();
// 找到登录页的索引
const index = pages.findIndex((e) => this.defaultPath("login").includes(e.path));
// 未找到,则跳回首页
if (index < 0) {
this.home();
} else {
this.back({
delta: pages.length - index
}); });
} }
// 登录后回调
if (this.eventsMap.afterLogin != null) {
this.eventsMap.afterLogin!();
}
// 触发全局 afterLogin 事件
uni.$emit("afterLogin");
}
// 注册跳转前钩子
beforeEach(cb: BeforeEach) {
this.eventsMap.beforeEach = cb;
}
// 注册登录后回调
afterLogin(cb: AfterLogin) {
this.eventsMap.afterLogin = cb;
}
} }
// 单例导出 // 单例导出
......
...@@ -17,20 +17,20 @@ export interface ScreenInfo { ...@@ -17,20 +17,20 @@ export interface ScreenInfo {
* 获取屏幕信息 * 获取屏幕信息
*/ */
export function getScreenInfo(): ScreenInfo { export function getScreenInfo(): ScreenInfo {
const windowInfo = uni.getWindowInfo() const windowInfo = uni.getWindowInfo();
return { return {
width: windowInfo.windowWidth, width: windowInfo.windowWidth,
height: windowInfo.windowHeight, height: windowInfo.windowHeight,
pixelRatio: windowInfo.pixelRatio, pixelRatio: windowInfo.pixelRatio,
screenWidth: windowInfo.screenWidth, screenWidth: windowInfo.screenWidth,
screenHeight: windowInfo.screenHeight screenHeight: windowInfo.screenHeight
} };
} }
/** /**
* 屏幕尺寸分类 * 屏幕尺寸分类
*/ */
export type ScreenSize = 'small' | 'medium' | 'large' | 'xlarge' export type ScreenSize = "large" | "medium" | "small" | "xlarge"
/** /**
* 获取屏幕尺寸分类 * 获取屏幕尺寸分类
...@@ -40,15 +40,15 @@ export type ScreenSize = 'small' | 'medium' | 'large' | 'xlarge' ...@@ -40,15 +40,15 @@ export type ScreenSize = 'small' | 'medium' | 'large' | 'xlarge'
* - xlarge: >= 1024px(平板、大屏设备) * - xlarge: >= 1024px(平板、大屏设备)
*/ */
export function getScreenSize(): ScreenSize { export function getScreenSize(): ScreenSize {
const width = getScreenInfo().width const width = getScreenInfo().width;
if (width < 480) { if (width < 480) {
return 'small' return "small";
} else if (width < 768) { } else if (width < 768) {
return 'medium' return "medium";
} else if (width < 1024) { } else if (width < 1024) {
return 'large' return "large";
} else { } else {
return 'xlarge' return "xlarge";
} }
} }
...@@ -68,25 +68,25 @@ export function getScreenSize(): ScreenSize { ...@@ -68,25 +68,25 @@ export function getScreenSize(): ScreenSize {
* const fontSize = responsiveFontSize(14, 12, 20) * const fontSize = responsiveFontSize(14, 12, 20)
*/ */
export function responsiveFontSize(baseSize: number, minSize: number = 12, maxSize: number = 48): number { export function responsiveFontSize(baseSize: number, minSize: number = 12, maxSize: number = 48): number {
const screenInfo = getScreenInfo() const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width const screenWidth = screenInfo.width;
// 设计稿基准宽度(通常为 375px 或 750px) // 设计稿基准宽度(通常为 375px 或 750px)
// 如果设计稿是 750px,这里改为 750,baseSize 也需要相应调整 // 如果设计稿是 750px,这里改为 750,baseSize 也需要相应调整
const designWidth = 375 const designWidth = 375;
// 计算缩放比例(限制在合理范围内) // 计算缩放比例(限制在合理范围内)
const scale = screenWidth / designWidth const scale = screenWidth / designWidth;
const scaledSize = baseSize * scale const scaledSize = baseSize * scale;
// 限制在最小值和最大值之间 // 限制在最小值和最大值之间
if (scaledSize < minSize) { if (scaledSize < minSize) {
return minSize return minSize;
} else if (scaledSize > maxSize) { } else if (scaledSize > maxSize) {
return maxSize return maxSize;
} }
return Math.round(scaledSize) return Math.round(scaledSize);
} }
/** /**
...@@ -104,20 +104,20 @@ export function responsiveFontSize(baseSize: number, minSize: number = 12, maxSi ...@@ -104,20 +104,20 @@ export function responsiveFontSize(baseSize: number, minSize: number = 12, maxSi
* const padding = responsiveSpacing(16, 12, 24) * const padding = responsiveSpacing(16, 12, 24)
*/ */
export function responsiveSpacing(baseSpacing: number, minSpacing: number = 4, maxSpacing: number = 64): number { export function responsiveSpacing(baseSpacing: number, minSpacing: number = 4, maxSpacing: number = 64): number {
const screenInfo = getScreenInfo() const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width const screenWidth = screenInfo.width;
const designWidth = 375 const designWidth = 375;
const scale = screenWidth / designWidth const scale = screenWidth / designWidth;
const scaledSpacing = baseSpacing * scale const scaledSpacing = baseSpacing * scale;
if (scaledSpacing < minSpacing) { if (scaledSpacing < minSpacing) {
return minSpacing return minSpacing;
} else if (scaledSpacing > maxSpacing) { } else if (scaledSpacing > maxSpacing) {
return maxSpacing return maxSpacing;
} }
return Math.round(scaledSpacing) return Math.round(scaledSpacing);
} }
/** /**
...@@ -133,35 +133,35 @@ export function responsiveSpacing(baseSpacing: number, minSpacing: number = 4, m ...@@ -133,35 +133,35 @@ export function responsiveSpacing(baseSpacing: number, minSpacing: number = 4, m
* const buttonWidth = responsiveWidth(200) * const buttonWidth = responsiveWidth(200)
*/ */
export function responsiveWidth(baseWidth: number): number { export function responsiveWidth(baseWidth: number): number {
const screenInfo = getScreenInfo() const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width const screenWidth = screenInfo.width;
const designWidth = 375 const designWidth = 375;
return Math.round(baseWidth * (screenWidth / designWidth)) return Math.round(baseWidth * (screenWidth / designWidth));
} }
/** /**
* 判断是否为横屏 * 判断是否为横屏
*/ */
export function isLandscape(): boolean { export function isLandscape(): boolean {
const screenInfo = getScreenInfo() const screenInfo = getScreenInfo();
return screenInfo.width > screenInfo.height return screenInfo.width > screenInfo.height;
} }
/** /**
* 判断是否为平板尺寸 * 判断是否为平板尺寸
*/ */
export function isTablet(): boolean { export function isTablet(): boolean {
const screenSize = getScreenSize() const screenSize = getScreenSize();
return screenSize === 'large' || screenSize === 'xlarge' return screenSize === "large" || screenSize === "xlarge";
} }
/** /**
* 判断是否为手机尺寸 * 判断是否为手机尺寸
*/ */
export function isMobile(): boolean { export function isMobile(): boolean {
const screenSize = getScreenSize() const screenSize = getScreenSize();
return screenSize === 'small' || screenSize === 'medium' return screenSize === "small" || screenSize === "medium";
} }
/** /**
...@@ -175,5 +175,5 @@ export function isMobile(): boolean { ...@@ -175,5 +175,5 @@ export function isMobile(): boolean {
* const columns = getColumns(1, 2) * const columns = getColumns(1, 2)
*/ */
export function getColumns(mobileColumns: number = 1, tabletColumns: number = 2): number { export function getColumns(mobileColumns: number = 1, tabletColumns: number = 2): number {
return isTablet() ? tabletColumns : mobileColumns return isTablet() ? tabletColumns : mobileColumns;
} }
...@@ -8,14 +8,16 @@ ...@@ -8,14 +8,16 @@
* 2. iOS平台需要自定义基座 * 2. iOS平台需要自定义基座
*/ */
import type { DatabaseOptions, SqlOperationOptions } from "@/uni_modules/lime-sqlite";
import { import {
openDatabase,
closeDatabase, closeDatabase,
executeSql, executeSql,
selectSql,
isOpenDatabase, isOpenDatabase,
type DatabaseOptions, openDatabase,
type SqlOperationOptions selectSql
} from "@/uni_modules/lime-sqlite"; } from "@/uni_modules/lime-sqlite";
// 说明: // 说明:
...@@ -24,8 +26,8 @@ import { ...@@ -24,8 +26,8 @@ import {
// - 这里在业务侧声明一个结构兼容的类型,避免跨端编译/运行时报错 // - 这里在业务侧声明一个结构兼容的类型,避免跨端编译/运行时报错
type SQLiteSuccess = { type SQLiteSuccess = {
data: any[]; data: any[];
result: UTSJSONObject[];
errMsg: string; errMsg: string;
result: UTSJSONObject[];
}; };
// 定义回调函数类型 // 定义回调函数类型
...@@ -45,12 +47,12 @@ class SqliteStore { ...@@ -45,12 +47,12 @@ class SqliteStore {
// 数据库名称 // 数据库名称
private dbName: string; private dbName: string;
// 表名
private tableName: string;
// 数据库是否已初始化 // 数据库是否已初始化
private initialized: boolean = false; private initialized: boolean = false;
// 表名
private tableName: string;
/** /**
* 构造函数 * 构造函数
* @param name 表名 * @param name 表名
...@@ -62,10 +64,166 @@ class SqliteStore { ...@@ -62,10 +64,166 @@ class SqliteStore {
} }
/** /**
* 清空表
* @param success 成功回调
* @param fail 失败回调
*/
clear(success: SuccessCallback, fail: FailCallback): void {
const sql = `DELETE FROM ${this.tableName}`;
const clearOptions = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 清空表成功: ${this.tableName}`);
success(res);
},
fail
} as SqlOperationOptions;
executeSql(clearOptions);
}
/**
* 关闭数据库连接
*/
close(): void {
const closeOptions = {
name: this.dbName,
success: (res: any) => {
console.log(`[SqliteStore] 数据库 ${this.dbName} 关闭成功`);
},
fail: (err: any) => {
console.error(`[SqliteStore] 数据库 ${this.dbName} 关闭失败:`, err);
}
} as DatabaseOptions;
closeDatabase(closeOptions);
}
/**
* 统计记录数
* @param success 成功回调
* @param fail 失败回调
*/
count(
success: CountSuccessCallback,
fail: FailCallback
): void {
const sql = `SELECT COUNT(*) as total FROM ${this.tableName}`;
const countOptions = {
name: this.dbName,
sql: [sql],
// 同样使用 any 作为参数类型,保持与插件类型解耦
success: (res: any) => {
// 统计查询同样返回 SQLiteSuccess,对 data/result 统一处理
console.log(`[SqliteStore] count res:`, res);
const successData = res as SQLiteSuccess;
let rows = [] as any[];
// 同样优先使用 result(对象数组,包含 total 字段)
if (successData.result != null && Array.isArray(successData.result)) {
rows = successData.result as any[];
} else if (successData.data != null && Array.isArray(successData.data)) {
rows = successData.data as any[];
}
if (rows.length > 0) {
const row = rows[0] as UTSJSONObject;
const total = row.get("total") as number;
success(total);
} else {
success(0);
}
},
fail
} as SqlOperationOptions;
selectSql(countOptions);
}
/**
* 删除记录
* @param id 记录 ID
* @param success 成功回调
* @param fail 失败回调
*/
deleteById(
id: string,
success: null | SuccessCallback,
fail: FailCallback | null
): void {
const sql = `DELETE FROM ${this.tableName} WHERE id = '${id}'`;
const options = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 删除成功: ${id}`);
if (success != null) {
success(res);
}
},
fail
} as SqlOperationOptions;
executeSql(options);
}
/**
* 批量删除
* @param ids ID 数组
* @param success 成功回调
* @param fail 失败回调
*/
deleteMany(
ids: any,
success: SuccessCallback,
fail: FailCallback
): void {
const idList = ids as string[];
const sql = `DELETE FROM ${this.tableName} WHERE id IN ('${idList.join("','")}')`;
const deleteManyOptions = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 批量删除成功: ${idList.length} 条`);
success(res);
},
fail
} as SqlOperationOptions;
executeSql(deleteManyOptions);
}
/**
* 执行 SQL 语句(增删改)
* @param sqls SQL 语句数组
* @param success 成功回调
* @param fail 失败回调
*/
executeSql(
sqls: string[],
success: null | SuccessCallback,
fail: FailCallback | null
): void {
executeSql({
name: this.dbName,
sql: sqls,
success: (res) => {
if (success != null) {
success(res);
}
},
fail: (err) => {
console.error(`[SqliteStore] SQL 执行失败:`, err);
if (fail != null) {
fail(err);
}
}
} as SqlOperationOptions);
}
/**
* 初始化数据库和表结构 * 初始化数据库和表结构
* @param callback 初始化完成后的回调函数 * @param callback 初始化完成后的回调函数
*/ */
init(callback: SuccessCallback | null): void { init(callback: null | SuccessCallback): void {
// 打开数据库 // 打开数据库
openDatabase({ openDatabase({
name: this.dbName, name: this.dbName,
...@@ -80,40 +238,59 @@ class SqliteStore { ...@@ -80,40 +238,59 @@ class SqliteStore {
} }
/** /**
* 创建表结构 * 插入记录
* 表结构:id (主键), name, age, email, status, created_at, updated_at * @param data 记录数据
* @param success 成功回调
* @param fail 失败回调
*/ */
private createTable(callback: SuccessCallback | null): void { insert(
data: any,
success: InsertSuccessCallback,
fail: FailCallback
): void {
const id = `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
const now = Date.now();
// 将 data 转换为 UTSJSONObject 以访问属性
const dataObj = data as UTSJSONObject;
const name = dataObj.get("name") as string;
const age = dataObj.get("age") as number;
const email = dataObj.get("email") as string;
const status = dataObj.get("status") as string;
const escapedName = name == null ? "" : name.replaceAll("'", "''");
const escapedEmail = email == null ? "" : email.replaceAll("'", "''");
const escapedStatus = status == null ? "" : status.replaceAll("'", "''");
const sql = ` const sql = `
CREATE TABLE IF NOT EXISTS ${this.tableName} ( INSERT INTO ${this.tableName} (id, name, age, email, status, created_at, updated_at)
id TEXT PRIMARY KEY, VALUES ('${id}', '${escapedName}', ${age}, '${escapedEmail}', '${escapedStatus}', ${now}, ${now})
name TEXT,
age INTEGER,
email TEXT,
status TEXT,
created_at INTEGER,
updated_at INTEGER
)
`; `;
const options = { const options = {
name: this.dbName, name: this.dbName,
sql: [sql], sql: [sql],
success: (res: any) => { success: (res: any) => {
console.log(`[SqliteStore] 表 ${this.tableName} 创建成功`); console.log(`[SqliteStore] 插入成功: ${id}`);
this.initialized = true; success(id);
if (callback != null) {
callback(res);
}
}, },
fail: (err: any) => { fail
console.error(`[SqliteStore] 表 ${this.tableName} 创建失败:`, err);
}
} as SqlOperationOptions; } as SqlOperationOptions;
executeSql(options); executeSql(options);
} }
/** /**
* 批量插入
* @param dataList 数据数组
* @param success 成功回调
* @param fail 失败回调
*/
insertMany(
dataList: any,
success: InsertManySuccessCallback,
fail: FailCallback
): void {}
/**
* 检查数据库是否打开 * 检查数据库是否打开
* @returns 是否打开 * @returns 是否打开
*/ */
...@@ -129,31 +306,44 @@ class SqliteStore { ...@@ -129,31 +306,44 @@ class SqliteStore {
} }
/** /**
* 执行 SQL 语句(增删改) * 查询所有记录
* @param sqls SQL 语句数组
* @param success 成功回调 * @param success 成功回调
* @param fail 失败回调 * @param fail 失败回调
*/ */
executeSql( select(
sqls: string[], success: SelectSuccessCallback,
success: SuccessCallback | null, fail?: FailCallback | null
fail: FailCallback | null
): void { ): void {
executeSql({ const sql = `SELECT * FROM ${this.tableName} ORDER BY created_at DESC`;
const options = {
name: this.dbName, name: this.dbName,
sql: sqls, sql: [sql],
success: (res) => { // 注意:这里使用 any 作为参数类型,避免与 lime-sqlite 内部的 SQLiteSuccess 名称冲突
if (success != null) { // 然后在函数体内按我们约定的结构进行访问
success(res); success: (res: any) => {
} // lime-sqlite 返回 SQLiteSuccess 对象,data 为原始数组,result 为对象数组
}, console.log(`[SqliteStore] 原始 res:`, res);
fail: (err) => {
console.error(`[SqliteStore] SQL 执行失败:`, err); const successData = res as SQLiteSuccess;
if (fail != null) { let rows = [] as any[];
fail(err);
// 页面代码普遍按 UTSJSONObject 来读取字段(row.get("xxx")),
// 因此优先使用 result(对象数组),只有在没有 result 时才退回 data。
if (successData.result != null && Array.isArray(successData.result)) {
rows = successData.result as any[];
} else if (successData.data != null && Array.isArray(successData.data)) {
rows = successData.data as any[];
} }
if (rows.length === 0) {
console.log(`[SqliteStore] 没有找到数据,返回空数组`);
} }
} as SqlOperationOptions);
success(rows);
},
fail
} as SqlOperationOptions;
selectSql(options);
} }
/** /**
...@@ -164,7 +354,7 @@ class SqliteStore { ...@@ -164,7 +354,7 @@ class SqliteStore {
*/ */
selectSql( selectSql(
sqls: string[], sqls: string[],
success: SelectSuccessCallback | null, success: null | SelectSuccessCallback,
fail: FailCallback | null fail: FailCallback | null
): void { ): void {
const selectOptions = { const selectOptions = {
...@@ -191,9 +381,9 @@ class SqliteStore { ...@@ -191,9 +381,9 @@ class SqliteStore {
resultData = parsed as any[]; resultData = parsed as any[];
} else { } else {
// 是对象,使用方括号语法访问属性 // 是对象,使用方括号语法访问属性
const data = parsed['data']; const data = parsed.data;
const rows = parsed['rows']; const rows = parsed.rows;
const result = parsed['result']; const result = parsed.result;
console.log(`[SqliteStore] data:`, data); console.log(`[SqliteStore] data:`, data);
console.log(`[SqliteStore] rows:`, rows); console.log(`[SqliteStore] rows:`, rows);
...@@ -230,47 +420,6 @@ class SqliteStore { ...@@ -230,47 +420,6 @@ class SqliteStore {
} }
/** /**
* 插入记录
* @param data 记录数据
* @param success 成功回调
* @param fail 失败回调
*/
insert(
data: any,
success: InsertSuccessCallback,
fail: FailCallback
): void {
const id = `${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
const now = Date.now();
// 将 data 转换为 UTSJSONObject 以访问属性
const dataObj = data as UTSJSONObject;
const name = dataObj.get("name") as string;
const age = dataObj.get("age") as number;
const email = dataObj.get("email") as string;
const status = dataObj.get("status") as string;
const escapedName = name == null ? "" : name.replace(/'/g, "''");
const escapedEmail = email == null ? "" : email.replace(/'/g, "''");
const escapedStatus = status == null ? "" : status.replace(/'/g, "''");
const sql = `
INSERT INTO ${this.tableName} (id, name, age, email, status, created_at, updated_at)
VALUES ('${id}', '${escapedName}', ${age}, '${escapedEmail}', '${escapedStatus}', ${now}, ${now})
`;
const options = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 插入成功: ${id}`);
success(id);
},
fail: fail
} as SqlOperationOptions;
executeSql(options);
}
/**
* 更新记录 * 更新记录
* @param id 记录 ID * @param id 记录 ID
* @param data 更新数据 * @param data 更新数据
...@@ -280,7 +429,7 @@ class SqliteStore { ...@@ -280,7 +429,7 @@ class SqliteStore {
update( update(
id: string, id: string,
data: any, data: any,
success: SuccessCallback | null, success: null | SuccessCallback,
fail: FailCallback | null fail: FailCallback | null
): void { ): void {
const now = Date.now(); const now = Date.now();
...@@ -291,7 +440,7 @@ class SqliteStore { ...@@ -291,7 +440,7 @@ class SqliteStore {
const name = dataObj.get("name"); const name = dataObj.get("name");
if (name != null) { if (name != null) {
const escapedName = (name as string).replace(/'/g, "''"); const escapedName = (name as string).replaceAll("'", "''");
updates.push(`name = '${escapedName}'`); updates.push(`name = '${escapedName}'`);
} }
...@@ -302,13 +451,13 @@ class SqliteStore { ...@@ -302,13 +451,13 @@ class SqliteStore {
const email = dataObj.get("email"); const email = dataObj.get("email");
if (email != null) { if (email != null) {
const escapedEmail = (email as string).replace(/'/g, "''"); const escapedEmail = (email as string).replaceAll("'", "''");
updates.push(`email = '${escapedEmail}'`); updates.push(`email = '${escapedEmail}'`);
} }
const status = dataObj.get("status"); const status = dataObj.get("status");
if (status != null) { if (status != null) {
const escapedStatus = (status as string).replace(/'/g, "''"); const escapedStatus = (status as string).replaceAll("'", "''");
updates.push(`status = '${escapedStatus}'`); updates.push(`status = '${escapedStatus}'`);
} }
...@@ -329,193 +478,44 @@ class SqliteStore { ...@@ -329,193 +478,44 @@ class SqliteStore {
success(res); success(res);
} }
}, },
fail: fail fail
} as SqlOperationOptions; } as SqlOperationOptions;
executeSql(updateOptions); executeSql(updateOptions);
} }
/**
* 删除记录
* @param id 记录 ID
* @param success 成功回调
* @param fail 失败回调
*/
deleteById(
id: string,
success: SuccessCallback | null,
fail: FailCallback | null
): void {
const sql = `DELETE FROM ${this.tableName} WHERE id = '${id}'`;
const options = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 删除成功: ${id}`);
if (success != null) {
success(res);
}
},
fail: fail
} as SqlOperationOptions;
executeSql(options);
}
/**
* 查询所有记录
* @param success 成功回调
* @param fail 失败回调
*/
select(
success: SelectSuccessCallback,
fail?: FailCallback | null
): void {
const sql = `SELECT * FROM ${this.tableName} ORDER BY created_at DESC`;
const options = {
name: this.dbName,
sql: [sql],
// 注意:这里使用 any 作为参数类型,避免与 lime-sqlite 内部的 SQLiteSuccess 名称冲突
// 然后在函数体内按我们约定的结构进行访问
success: (res: any) => {
// lime-sqlite 返回 SQLiteSuccess 对象,data 为原始数组,result 为对象数组
console.log(`[SqliteStore] 原始 res:`, res);
const successData = res as SQLiteSuccess;
let rows = [] as any[];
// 页面代码普遍按 UTSJSONObject 来读取字段(row.get("xxx")),
// 因此优先使用 result(对象数组),只有在没有 result 时才退回 data。
if (successData.result != null && Array.isArray(successData.result)) {
rows = successData.result as any[];
} else if (successData.data != null && Array.isArray(successData.data)) {
rows = successData.data as any[];
}
if (rows.length == 0) {
console.log(`[SqliteStore] 没有找到数据,返回空数组`);
}
success(rows);
},
fail: fail
} as SqlOperationOptions;
selectSql(options);
}
/**
* 批量插入
* @param dataList 数据数组
* @param success 成功回调
* @param fail 失败回调
*/
insertMany(
dataList: any,
success: InsertManySuccessCallback,
fail: FailCallback
): void {
}
/** /**
* 批量删除 * 创建表结构
* @param ids ID 数组 * 表结构:id (主键), name, age, email, status, created_at, updated_at
* @param success 成功回调
* @param fail 失败回调
*/
deleteMany(
ids: any,
success: SuccessCallback,
fail: FailCallback
): void {
const idList = ids as string[];
const sql = `DELETE FROM ${this.tableName} WHERE id IN ('${idList.join("','")}')`;
const deleteManyOptions = {
name: this.dbName,
sql: [sql],
success: (res: any) => {
console.log(`[SqliteStore] 批量删除成功: ${idList.length} 条`);
success(res);
},
fail: fail
} as SqlOperationOptions;
executeSql(deleteManyOptions);
}
/**
* 统计记录数
* @param success 成功回调
* @param fail 失败回调
*/ */
count( private createTable(callback: null | SuccessCallback): void {
success: CountSuccessCallback, const sql = `
fail: FailCallback CREATE TABLE IF NOT EXISTS ${this.tableName} (
): void { id TEXT PRIMARY KEY,
const sql = `SELECT COUNT(*) as total FROM ${this.tableName}`; name TEXT,
const countOptions = { age INTEGER,
name: this.dbName, email TEXT,
sql: [sql], status TEXT,
// 同样使用 any 作为参数类型,保持与插件类型解耦 created_at INTEGER,
success: (res: any) => { updated_at INTEGER
// 统计查询同样返回 SQLiteSuccess,对 data/result 统一处理 )
console.log(`[SqliteStore] count res:`, res); `;
const successData = res as SQLiteSuccess;
let rows = [] as any[];
// 同样优先使用 result(对象数组,包含 total 字段)
if (successData.result != null && Array.isArray(successData.result)) {
rows = successData.result as any[];
} else if (successData.data != null && Array.isArray(successData.data)) {
rows = successData.data as any[];
}
if (rows.length > 0) {
const row = rows[0] as UTSJSONObject;
const total = row.get("total") as number;
success(total);
} else {
success(0);
}
},
fail: fail
} as SqlOperationOptions;
selectSql(countOptions);
}
/** const options = {
* 清空表
* @param success 成功回调
* @param fail 失败回调
*/
clear(success: SuccessCallback, fail: FailCallback): void {
const sql = `DELETE FROM ${this.tableName}`;
const clearOptions = {
name: this.dbName, name: this.dbName,
sql: [sql], sql: [sql],
success: (res: any) => { success: (res: any) => {
console.log(`[SqliteStore] 清空表成功: ${this.tableName}`); console.log(`[SqliteStore] 表 ${this.tableName} 创建成功`);
success(res); this.initialized = true;
}, if (callback != null) {
fail: fail callback(res);
} as SqlOperationOptions;
executeSql(clearOptions);
} }
/**
* 关闭数据库连接
*/
close(): void {
const closeOptions = {
name: this.dbName,
success: (res: any) => {
console.log(`[SqliteStore] 数据库 ${this.dbName} 关闭成功`);
}, },
fail: (err: any) => { fail: (err: any) => {
console.error(`[SqliteStore] 数据库 ${this.dbName} 关闭失败:`, err); console.error(`[SqliteStore] 表 ${this.tableName} 创建失败:`, err);
} }
} as DatabaseOptions; } as SqlOperationOptions;
closeDatabase(closeOptions); executeSql(options);
} }
} }
......
...@@ -9,6 +9,18 @@ const EXPIRES_SUFFIX = "_deadtime"; ...@@ -9,6 +9,18 @@ const EXPIRES_SUFFIX = "_deadtime";
*/ */
class Storage { class Storage {
/** /**
* 清空所有存储数据
*
* 警告:此操作会删除所有本地存储数据,请谨慎使用
*
* @example
* storage.clear(); // 清空所有数据
*/
clear() {
uni.clearStorageSync();
}
/**
* 获取存储数据 * 获取存储数据
* *
* @param key 存储键名 * @param key 存储键名
...@@ -52,32 +64,6 @@ class Storage { ...@@ -52,32 +64,6 @@ class Storage {
} }
/** /**
* 设置存储数据
*
* @param key 存储键名
* @param value 要存储的数据,支持任意类型
* @param expires 过期时间(秒),默认为0表示永不过期
*
* @example
* // 存储永久数据
* storage.set('user', { name: '张三', age: 25 }, 0);
*
* // 存储5分钟后过期的数据
* storage.set('token', 'abc123', 300);
*/
set(key: string, value: any, expires: number): void {
// 存储主要数据
uni.setStorageSync(key, value);
// 如果设置了过期时间,则存储过期时间戳
if (expires > 0) {
// 计算过期时间戳:当前时间 + 过期时间(秒转毫秒)
const expireTime = new Date().getTime() + expires * 1000;
uni.setStorageSync(`${key}${EXPIRES_SUFFIX}`, expireTime);
}
}
/**
* 检查数据是否已过期 * 检查数据是否已过期
* *
* @param key 存储键名 * @param key 存储键名
...@@ -90,7 +76,7 @@ class Storage { ...@@ -90,7 +76,7 @@ class Storage {
*/ */
isExpired(key: string): boolean { isExpired(key: string): boolean {
// 获取过期时间戳 // 获取过期时间戳
const value = uni.getStorageSync(`${key}${EXPIRES_SUFFIX}`) as number | null; const value = uni.getStorageSync(`${key}${EXPIRES_SUFFIX}`) as null | number;
// 如果没有设置过期时间,视为已过期 // 如果没有设置过期时间,视为已过期
if (value == null) { if (value == null) {
...@@ -98,7 +84,29 @@ class Storage { ...@@ -98,7 +84,29 @@ class Storage {
} }
// 比较过期时间戳与当前时间,判断是否过期 // 比较过期时间戳与当前时间,判断是否过期
return value - new Date().getTime() <= 0; return value - Date.now() <= 0;
}
/**
* 获取数据后立即删除(一次性读取)
*
* 适用于临时数据、一次性令牌等场景
* 读取后数据会被自动删除,确保数据的一次性使用
*
* @param key 存储键名
* @returns 存储的数据,如果不存在则返回 null
*
* @example
* const tempToken = storage.once('temp_token');
* // tempToken 使用后,存储中的 temp_token 已被删除
*/
once(key: string): any | null {
// 先获取数据
const value = this.get(key);
// 立即删除数据
this.remove(key);
// 返回获取到的数据
return value;
} }
/** /**
...@@ -120,37 +128,29 @@ class Storage { ...@@ -120,37 +128,29 @@ class Storage {
} }
/** /**
* 清空所有存储数据 * 设置存储数据
*
* 警告:此操作会删除所有本地存储数据,请谨慎使用
*
* @example
* storage.clear(); // 清空所有数据
*/
clear() {
uni.clearStorageSync();
}
/**
* 获取数据后立即删除(一次性读取)
*
* 适用于临时数据、一次性令牌等场景
* 读取后数据会被自动删除,确保数据的一次性使用
* *
* @param key 存储键名 * @param key 存储键名
* @returns 存储的数据,如果不存在则返回 null * @param value 要存储的数据,支持任意类型
* @param expires 过期时间(秒),默认为0表示永不过期
* *
* @example * @example
* const tempToken = storage.once('temp_token'); * // 存储永久数据
* // tempToken 使用后,存储中的 temp_token 已被删除 * storage.set('user', { name: '张三', age: 25 }, 0);
*
* // 存储5分钟后过期的数据
* storage.set('token', 'abc123', 300);
*/ */
once(key: string): any | null { set(key: string, value: any, expires: number): void {
// 先获取数据 // 存储主要数据
const value = this.get(key); uni.setStorageSync(key, value);
// 立即删除数据
this.remove(key); // 如果设置了过期时间,则存储过期时间戳
// 返回获取到的数据 if (expires > 0) {
return value; // 计算过期时间戳:当前时间 + 过期时间(秒转毫秒)
const expireTime = Date.now() + expires * 1000;
uni.setStorageSync(`${key}${EXPIRES_SUFFIX}`, expireTime);
}
} }
} }
......
// utils/theme-classes.uts // utils/theme-classes.uts
// 主题化类名工具函数 - 让主题系统像 Tailwind 一样使用类名 // 主题化类名工具函数 - 让主题系统像 Tailwind 一样使用类名
import { getThemeManager } from './theme-manager.uts' import { getThemeManager } from "./theme-manager.uts";
/** /**
* Tailwind 风格类名工具函数 * Tailwind 风格类名工具函数
...@@ -15,17 +15,17 @@ import { getThemeManager } from './theme-manager.uts' ...@@ -15,17 +15,17 @@ import { getThemeManager } from './theme-manager.uts'
* // 返回: 'theme-mobile-medium p-4 rounded-lg' * // 返回: 'theme-mobile-medium p-4 rounded-lg'
*/ */
export function tw(...classes: string[]): string { export function tw(...classes: string[]): string {
const themeManager = getThemeManager() const themeManager = getThemeManager();
const themeName = themeManager.getCurrentThemeName() const themeName = themeManager.getCurrentThemeName();
const themePrefix = `theme-${themeName}` const themePrefix = `theme-${themeName}`;
return [themePrefix, ...classes].join(' ') return [themePrefix, ...classes].join(" ");
} }
/** /**
* 获取当前主题前缀 * 获取当前主题前缀
*/ */
export function getThemePrefix(): string { export function getThemePrefix(): string {
const themeManager = getThemeManager() const themeManager = getThemeManager();
const themeName = themeManager.getCurrentThemeName() const themeName = themeManager.getCurrentThemeName();
return `theme-${themeName}` return `theme-${themeName}`;
} }
// utils/theme-manager.uts // utils/theme-manager.uts
// 主题管理器 - 类似 i18n,管理多套主题的切换和获取 // 主题管理器 - 类似 i18n,管理多套主题的切换和获取
import { getScreenSize } from './screen-adapt.uts' import { get } from "./common.uts";
import { get } from './common.uts' import { getScreenSize } from "./screen-adapt.uts";
/** /**
* 主题名称类型 * 主题名称类型
*/ */
export type ThemeName = 'mobile-small' | 'mobile-medium' | 'mobile-large' | 'tablet' | 'tablet-large' export type ThemeName = "mobile-large" | "mobile-medium" | "mobile-small" | "tablet" | "tablet-large"
/** /**
* 主题变量接口 * 主题变量接口
...@@ -42,42 +42,42 @@ export type ThemeConfig = { ...@@ -42,42 +42,42 @@ export type ThemeConfig = {
* 实际项目中可以改为从 themes/themes.json 文件读取 * 实际项目中可以改为从 themes/themes.json 文件读取
*/ */
const defaultThemeConfig: ThemeConfig = { const defaultThemeConfig: ThemeConfig = {
'mobile-small': { "mobile-small": {
spacing: { '0': 0, xs: 4, sm: 6, md: 10, base: 12, lg: 16, xl: 20, '2xl': 24, '3xl': 32, '4xl': 40 }, spacing: { "0": 0, xs: 4, sm: 6, md: 10, base: 12, lg: 16, xl: 20, "2xl": 24, "3xl": 32, "4xl": 40 },
borderRadius: { none: 0, sm: 2, base: 4, md: 6, lg: 8, xl: 10, '2xl': 12, full: 9999 }, borderRadius: { none: 0, sm: 2, base: 4, md: 6, lg: 8, xl: 10, "2xl": 12, full: 9999 },
fontSize: { xs: 10, sm: 12, base: 14, md: 16, lg: 18, xl: 20, '2xl': 24, '3xl': 28, '4xl': 32 }, fontSize: { xs: 10, sm: 12, base: 14, md: 16, lg: 18, xl: 20, "2xl": 24, "3xl": 28, "4xl": 32 },
size: { xs: 16, sm: 24, md: 32, base: 40, lg: 48, xl: 64, '2xl': 80, '3xl': 96 }, size: { xs: 16, sm: 24, md: 32, base: 40, lg: 48, xl: 64, "2xl": 80, "3xl": 96 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 } lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
}, },
'mobile-medium': { "mobile-medium": {
spacing: { '0': 0, xs: 4, sm: 8, md: 12, base: 16, lg: 20, xl: 24, '2xl': 32, '3xl': 40, '4xl': 48 }, spacing: { "0": 0, xs: 4, sm: 8, md: 12, base: 16, lg: 20, xl: 24, "2xl": 32, "3xl": 40, "4xl": 48 },
borderRadius: { none: 0, sm: 2, base: 4, md: 6, lg: 8, xl: 12, '2xl': 16, full: 9999 }, borderRadius: { none: 0, sm: 2, base: 4, md: 6, lg: 8, xl: 12, "2xl": 16, full: 9999 },
fontSize: { xs: 10, sm: 12, base: 14, md: 16, lg: 18, xl: 20, '2xl': 24, '3xl': 30, '4xl': 36 }, fontSize: { xs: 10, sm: 12, base: 14, md: 16, lg: 18, xl: 20, "2xl": 24, "3xl": 30, "4xl": 36 },
size: { xs: 16, sm: 24, md: 32, base: 40, lg: 48, xl: 64, '2xl': 80, '3xl': 96 }, size: { xs: 16, sm: 24, md: 32, base: 40, lg: 48, xl: 64, "2xl": 80, "3xl": 96 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 } lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
}, },
'mobile-large': { "mobile-large": {
spacing: { '0': 0, xs: 6, sm: 10, md: 14, base: 18, lg: 24, xl: 28, '2xl': 36, '3xl': 44, '4xl': 56 }, spacing: { "0": 0, xs: 6, sm: 10, md: 14, base: 18, lg: 24, xl: 28, "2xl": 36, "3xl": 44, "4xl": 56 },
borderRadius: { none: 0, sm: 3, base: 6, md: 8, lg: 10, xl: 14, '2xl': 18, full: 9999 }, borderRadius: { none: 0, sm: 3, base: 6, md: 8, lg: 10, xl: 14, "2xl": 18, full: 9999 },
fontSize: { xs: 11, sm: 13, base: 15, md: 17, lg: 19, xl: 22, '2xl': 26, '3xl': 32, '4xl': 40 }, fontSize: { xs: 11, sm: 13, base: 15, md: 17, lg: 19, xl: 22, "2xl": 26, "3xl": 32, "4xl": 40 },
size: { xs: 20, sm: 28, md: 36, base: 44, lg: 52, xl: 68, '2xl': 84, '3xl': 100 }, size: { xs: 20, sm: 28, md: 36, base: 44, lg: 52, xl: 68, "2xl": 84, "3xl": 100 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 } lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
}, },
'tablet': { "tablet": {
spacing: { '0': 0, xs: 6, sm: 10, md: 16, base: 20, lg: 24, xl: 32, '2xl': 40, '3xl': 48, '4xl': 64 }, spacing: { "0": 0, xs: 6, sm: 10, md: 16, base: 20, lg: 24, xl: 32, "2xl": 40, "3xl": 48, "4xl": 64 },
borderRadius: { none: 0, sm: 4, base: 6, md: 8, lg: 12, xl: 16, '2xl': 20, full: 9999 }, borderRadius: { none: 0, sm: 4, base: 6, md: 8, lg: 12, xl: 16, "2xl": 20, full: 9999 },
fontSize: { xs: 12, sm: 14, base: 16, md: 18, lg: 20, xl: 24, '2xl': 28, '3xl': 36, '4xl': 44 }, fontSize: { xs: 12, sm: 14, base: 16, md: 18, lg: 20, xl: 24, "2xl": 28, "3xl": 36, "4xl": 44 },
size: { xs: 24, sm: 32, md: 40, base: 48, lg: 56, xl: 72, '2xl': 88, '3xl': 104 }, size: { xs: 24, sm: 32, md: 40, base: 48, lg: 56, xl: 72, "2xl": 88, "3xl": 104 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 } lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
}, },
'tablet-large': { "tablet-large": {
spacing: { '0': 0, xs: 8, sm: 12, md: 20, base: 24, lg: 32, xl: 40, '2xl': 48, '3xl': 64, '4xl': 80 }, spacing: { "0": 0, xs: 8, sm: 12, md: 20, base: 24, lg: 32, xl: 40, "2xl": 48, "3xl": 64, "4xl": 80 },
borderRadius: { none: 0, sm: 6, base: 8, md: 10, lg: 14, xl: 18, '2xl': 24, full: 9999 }, borderRadius: { none: 0, sm: 6, base: 8, md: 10, lg: 14, xl: 18, "2xl": 24, full: 9999 },
fontSize: { xs: 14, sm: 16, base: 18, md: 20, lg: 24, xl: 28, '2xl': 32, '3xl': 40, '4xl': 48 }, fontSize: { xs: 14, sm: 16, base: 18, md: 20, lg: 24, xl: 28, "2xl": 32, "3xl": 40, "4xl": 48 },
size: { xs: 28, sm: 36, md: 44, base: 52, lg: 64, xl: 80, '2xl': 96, '3xl': 112 }, size: { xs: 28, sm: 36, md: 44, base: 52, lg: 64, xl: 80, "2xl": 96, "3xl": 112 },
lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 } lineHeight: { tight: 1.2, normal: 1.5, relaxed: 1.75, loose: 2 }
} }
} };
/** /**
* 加载主题配置 * 加载主题配置
...@@ -91,31 +91,36 @@ function loadThemeConfig(): ThemeConfig { ...@@ -91,31 +91,36 @@ function loadThemeConfig(): ThemeConfig {
// 2. 使用 uni.getFileSystemManager() 读取本地文件 // 2. 使用 uni.getFileSystemManager() 读取本地文件
// 3. 使用静态 import(如果支持) // 3. 使用静态 import(如果支持)
return defaultThemeConfig return defaultThemeConfig;
} }
/** /**
* 根据屏幕尺寸自动选择主题 * 根据屏幕尺寸自动选择主题
*/ */
export function getThemeByScreenSize(): ThemeName { export function getThemeByScreenSize(): ThemeName {
const screenSize = getScreenSize() const screenSize = getScreenSize();
switch (screenSize) { switch (screenSize) {
case 'small': case "large": {
return 'mobile-small' return "mobile-large";
case 'medium': }
return 'mobile-medium' case "medium": {
case 'large': return "mobile-medium";
return 'mobile-large' }
case 'xlarge': case "small": {
return "mobile-small";
}
case "xlarge": {
// 根据屏幕宽度进一步判断是 tablet 还是 tablet-large // 根据屏幕宽度进一步判断是 tablet 还是 tablet-large
const windowInfo = uni.getWindowInfo() const windowInfo = uni.getWindowInfo();
if (windowInfo.windowWidth >= 1920) { if (windowInfo.windowWidth >= 1920) {
return 'tablet-large' return "tablet-large";
}
return "tablet";
}
default: {
return "mobile-medium";
} }
return 'tablet'
default:
return 'mobile-medium'
} }
} }
...@@ -123,66 +128,83 @@ export function getThemeByScreenSize(): ThemeName { ...@@ -123,66 +128,83 @@ export function getThemeByScreenSize(): ThemeName {
* 主题管理器类 * 主题管理器类
*/ */
export class ThemeManager { export class ThemeManager {
private themes: ThemeConfig | null = null private currentThemeName: ThemeName = "mobile-medium";
private currentThemeName: ThemeName = 'mobile-medium' private themes: null | ThemeConfig = null;
constructor() { constructor() {
this.themes = loadThemeConfig() this.themes = loadThemeConfig();
this.currentThemeName = getThemeByScreenSize() this.currentThemeName = getThemeByScreenSize();
} }
/** /**
* 获取当前主题名称 * 自动选择主题(根据屏幕尺寸)
*/ */
getCurrentThemeName(): ThemeName { autoSelectTheme(): void {
return this.currentThemeName this.currentThemeName = getThemeByScreenSize();
} }
/** /**
* 设置当前主题 * 获取圆角值
*/ */
setTheme(themeName: ThemeName): boolean { getBorderRadius(key: string): number {
return this.getValue("borderRadius", key, 0);
}
/**
* 获取当前主题变量
*/
getCurrentTheme(): null | ThemeVariables {
if (this.themes == null) { if (this.themes == null) {
console.warn('[theme-manager] Theme config not loaded') return null;
return false
} }
if (get(this.themes, themeName) == null) { return get(this.themes, this.currentThemeName) as null | ThemeVariables;
console.warn(`[theme-manager] Theme "${themeName}" not found`)
return false
} }
this.currentThemeName = themeName /**
return true * 获取当前主题名称
*/
getCurrentThemeName(): ThemeName {
return this.currentThemeName;
} }
/** /**
* 自动选择主题(根据屏幕尺寸) * 获取字体大小
*/ */
autoSelectTheme(): void { getFontSize(key: string): number {
this.currentThemeName = getThemeByScreenSize() return this.getValue("fontSize", key, 14);
} }
/** /**
* 获取当前主题变量 * 获取行高值
*/ */
getCurrentTheme(): ThemeVariables | null { getLineHeight(key: string): number {
if (this.themes == null) { return this.getValue("lineHeight", key, 1.5);
return null }
/**
* 获取尺寸值
*/
getSize(key: string): number {
return this.getValue("size", key, 0);
} }
return get(this.themes, this.currentThemeName) as ThemeVariables | null /**
* 获取间距值
*/
getSpacing(key: string): number {
return this.getValue("spacing", key, 0);
} }
/** /**
* 获取指定主题变量 * 获取指定主题变量
*/ */
getTheme(themeName: ThemeName): ThemeVariables | null { getTheme(themeName: ThemeName): null | ThemeVariables {
if (this.themes == null) { if (this.themes == null) {
return null return null;
} }
return get(this.themes, themeName) as ThemeVariables | null return get(this.themes, themeName) as null | ThemeVariables;
} }
/** /**
...@@ -192,69 +214,52 @@ export class ThemeManager { ...@@ -192,69 +214,52 @@ export class ThemeManager {
* @param defaultValue 默认值 * @param defaultValue 默认值
*/ */
getValue(category: string, key: string, defaultValue: number = 0): number { getValue(category: string, key: string, defaultValue: number = 0): number {
const theme = this.getCurrentTheme() const theme = this.getCurrentTheme();
if (theme == null) { if (theme == null) {
return defaultValue return defaultValue;
} }
const categoryObj = get(theme, category) as any const categoryObj = get(theme, category) as any;
if (categoryObj == null) { if (categoryObj == null) {
return defaultValue return defaultValue;
} }
const value = get(categoryObj, key) const value = get(categoryObj, key);
if (value == null || typeof value !== 'number') { if (value == null || typeof value !== "number") {
return defaultValue return defaultValue;
} }
return value return value;
}
/**
* 获取间距值
*/
getSpacing(key: string): number {
return this.getValue('spacing', key, 0)
}
/**
* 获取圆角值
*/
getBorderRadius(key: string): number {
return this.getValue('borderRadius', key, 0)
} }
/** /**
* 获取字体大小 * 设置当前主题
*/ */
getFontSize(key: string): number { setTheme(themeName: ThemeName): boolean {
return this.getValue('fontSize', key, 14) if (this.themes == null) {
console.warn("[theme-manager] Theme config not loaded");
return false;
} }
/** if (get(this.themes, themeName) == null) {
* 获取尺寸值 console.warn(`[theme-manager] Theme "${themeName}" not found`);
*/ return false;
getSize(key: string): number {
return this.getValue('size', key, 0)
} }
/** this.currentThemeName = themeName;
* 获取行高值 return true;
*/
getLineHeight(key: string): number {
return this.getValue('lineHeight', key, 1.5)
} }
} }
// 全局主题管理器实例 // 全局主题管理器实例
let globalThemeManager: ThemeManager | null = null let globalThemeManager: null | ThemeManager = null;
/** /**
* 获取全局主题管理器实例 * 获取全局主题管理器实例
*/ */
export function getThemeManager(): ThemeManager { export function getThemeManager(): ThemeManager {
if (globalThemeManager == null) { if (globalThemeManager == null) {
globalThemeManager = new ThemeManager() globalThemeManager = new ThemeManager();
} }
return globalThemeManager return globalThemeManager;
} }
// utils/theme-variables.uts // utils/theme-variables.uts
// CSS 变量主题系统 - 动态设置 CSS 变量值 // CSS 变量主题系统 - 动态设置 CSS 变量值
import { getThemeManager } from './theme-manager.uts' import { getThemeManager } from "./theme-manager.uts";
/** /**
* CSS 变量名称映射 * CSS 变量名称映射
...@@ -10,85 +10,85 @@ import { getThemeManager } from './theme-manager.uts' ...@@ -10,85 +10,85 @@ import { getThemeManager } from './theme-manager.uts'
*/ */
const CSS_VARIABLES: Record<string, string> = { const CSS_VARIABLES: Record<string, string> = {
// 间距 (Spacing) // 间距 (Spacing)
'--p-page': 'base', // p-page 使用 base 间距 "--p-page": "base", // p-page 使用 base 间距
'--p-xs': 'xs', "--p-xs": "xs",
'--p-sm': 'sm', "--p-sm": "sm",
'--p-md': 'md', "--p-md": "md",
'--p-base': 'base', "--p-base": "base",
'--p-lg': 'lg', "--p-lg": "lg",
'--p-xl': 'xl', "--p-xl": "xl",
'--p-2xl': '2xl', "--p-2xl": "2xl",
'--p-3xl': '3xl', "--p-3xl": "3xl",
'--p-4xl': '4xl', "--p-4xl": "4xl",
// 圆角 (Border Radius) // 圆角 (Border Radius)
'--r-none': 'none', "--r-none": "none",
'--r-sm': 'sm', "--r-sm": "sm",
'--r-base': 'base', "--r-base": "base",
'--r-md': 'md', "--r-md": "md",
'--r-lg': 'lg', "--r-lg": "lg",
'--r-xl': 'xl', "--r-xl": "xl",
'--r-2xl': '2xl', "--r-2xl": "2xl",
'--r-full': 'full', "--r-full": "full",
// 字体大小 (Font Size) // 字体大小 (Font Size)
'--t-xs': 'xs', "--t-xs": "xs",
'--t-sm': 'sm', "--t-sm": "sm",
'--t-base': 'base', "--t-base": "base",
'--t-md': 'md', "--t-md": "md",
'--t-lg': 'lg', "--t-lg": "lg",
'--t-xl': 'xl', "--t-xl": "xl",
'--t-2xl': '2xl', "--t-2xl": "2xl",
'--t-3xl': '3xl', "--t-3xl": "3xl",
'--t-4xl': '4xl', "--t-4xl": "4xl",
// 尺寸 (Size) // 尺寸 (Size)
'--s-xs': 'xs', "--s-xs": "xs",
'--s-sm': 'sm', "--s-sm": "sm",
'--s-md': 'md', "--s-md": "md",
'--s-base': 'base', "--s-base": "base",
'--s-lg': 'lg', "--s-lg": "lg",
'--s-xl': 'xl' "--s-xl": "xl"
} };
/** /**
* 设置 CSS 变量到根元素 * 设置 CSS 变量到根元素
* 注意:uni-app x 中需要在根 view 上设置 style * 注意:uni-app x 中需要在根 view 上设置 style
*/ */
export function setThemeVariables(rootElement: any = null): void { export function setThemeVariables(rootElement: any = null): void {
const themeManager = getThemeManager() const themeManager = getThemeManager();
const theme = themeManager.getCurrentTheme() const theme = themeManager.getCurrentTheme();
if (theme == null) { if (theme == null) {
console.warn('[theme-variables] Theme not loaded') console.warn("[theme-variables] Theme not loaded");
return return;
} }
// 构建 CSS 变量对象 // 构建 CSS 变量对象
const cssVars: Record<string, string> = {} const cssVars: Record<string, string> = {};
// 设置间距变量 // 设置间距变量
Object.keys(CSS_VARIABLES).forEach((cssVar) => { Object.keys(CSS_VARIABLES).forEach((cssVar) => {
const varName = CSS_VARIABLES[cssVar] const varName = CSS_VARIABLES[cssVar];
if (cssVar.startsWith('--p-')) { if (cssVar.startsWith("--p-")) {
// 间距变量 // 间距变量
cssVars[cssVar] = themeManager.getSpacing(varName) + 'px' cssVars[cssVar] = `${themeManager.getSpacing(varName) }px`;
} else if (cssVar.startsWith('--r-')) { } else if (cssVar.startsWith("--r-")) {
// 圆角变量 // 圆角变量
cssVars[cssVar] = themeManager.getBorderRadius(varName) + 'px' cssVars[cssVar] = `${themeManager.getBorderRadius(varName) }px`;
} else if (cssVar.startsWith('--t-')) { } else if (cssVar.startsWith("--t-")) {
// 字体大小变量 // 字体大小变量
cssVars[cssVar] = themeManager.getFontSize(varName) + 'px' cssVars[cssVar] = `${themeManager.getFontSize(varName) }px`;
} else if (cssVar.startsWith('--s-')) { } else if (cssVar.startsWith("--s-")) {
// 尺寸变量 // 尺寸变量
cssVars[cssVar] = themeManager.getSize(varName) + 'px' cssVars[cssVar] = `${themeManager.getSize(varName) }px`;
} }
}) });
// 在 uni-app x 中,需要通过 :style 绑定到根元素 // 在 uni-app x 中,需要通过 :style 绑定到根元素
// 这里返回样式对象,供组件使用 // 这里返回样式对象,供组件使用
return cssVars return cssVars;
} }
/** /**
...@@ -96,7 +96,7 @@ export function setThemeVariables(rootElement: any = null): void { ...@@ -96,7 +96,7 @@ export function setThemeVariables(rootElement: any = null): void {
* 用于绑定到根元素的 :style * 用于绑定到根元素的 :style
*/ */
export function getThemeVariablesStyle(): Record<string, string> { export function getThemeVariablesStyle(): Record<string, string> {
return setThemeVariables() return setThemeVariables();
} }
/** /**
......
import { join } from "node:path";
import uni from "@dcloudio/vite-plugin-uni";
import tailwindcss from "tailwindcss";
import { defineConfig } from "vite"; import { defineConfig } from "vite";
// import { cool } from "@cool-vue/vite-plugin"; // import { cool } from "@cool-vue/vite-plugin";
import { proxy } from "./config/proxy"; import { proxy } from "./config/proxy";
import { r } from "./shared.js"; import { r } from "./shared.js";
import { join } from "node:path";
import uni from "@dcloudio/vite-plugin-uni";
import tailwindcss from "tailwindcss";
const resolve = (dir: string) => join(__dirname, dir); const resolve = (dir: string) => join(__dirname, dir);
//为原代理路径添加带斜杠前缀的副本,兼容两种路径格式(如 /api/ 和 /api) // 为原代理路径添加带斜杠前缀的副本,兼容两种路径格式(如 /api/ 和 /api)
for (const i in proxy) { for (const i in proxy) {
proxy[`/${i}/`] = proxy[i]; proxy[`/${i}/`] = proxy[i];
} }
......
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!