Commit 345bb304 by Jaxon

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

- 调整导入顺序和导出顺序以保持一致性
- 统一使用严格相等运算符(!==/===)替代宽松相等
- 规范对象属性顺序和类型定义结构
- 优化字符串模板和箭头函数语法
- 统一代码缩进和换行格式
- 修复条件表达式括号和三元运算符格式
- 更新文件路径引用和模块声明格式
1 parent dd5feff4
Showing 48 changed files with 943 additions and 948 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,
...@@ -72,28 +162,28 @@ class Request { ...@@ -72,28 +162,28 @@ class Request {
const header = const header =
requestMethod == "POST" requestMethod == "POST"
? { ? {
"content-type": "application/x-www-form-urlencoded" "content-type": "application/x-www-form-urlencoded"
} }
: { : {
"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 != "") {
......
<template> <template>
<view v-if="isShow" class="publish-popup-mask" @click="closePopup"> <view v-if="isShow"
<view class="publish-popup-container" @click.stop> class="publish-popup-mask"
<slot name="content"></slot> @click="closePopup">
</view> <view class="publish-popup-container" @click.stop>
</view> <slot name="content"></slot>
</view>
</view>
</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"
<view class="type-scroll-content"> scroll-with-animation
<view scroll-x="true"
class="tab-item" :show-scrollbar="false">
:class="[tabClass(index)]" <view class="type-scroll-content">
v-for="(i, index) in typeList" <view v-for="(i, index) in typeList"
:key="index" :key="index"
@click.stop="tabClick(index, i)" class="tab-item"
> :class="[tabClass(index)]"
<view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']"> @click.stop="tabClick(index, i)">
<text class="tab-name">{{ getTabName(i) }}</text> <view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']">
<text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text> <text class="tab-name">{{ getTabName(i) }}</text>
</view> <text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text>
</view> </view>
</view> </view>
</scroll-view> </view>
</view> </scroll-view>
</view>
</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,11 +45,11 @@ const emit = defineEmits<{ ...@@ -44,11 +45,11 @@ 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;
} }
// get() 失败,尝试 JSON 序列化/反序列化解包响应式对象 // get() 失败,尝试 JSON 序列化/反序列化解包响应式对象
try { try {
const jsonStr = JSON.stringify(item); const jsonStr = JSON.stringify(item);
...@@ -58,55 +59,55 @@ const getTabName = (item: any): string => { ...@@ -58,55 +59,55 @@ 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;
} }
// get() 失败,尝试 JSON 序列化/反序列化解包响应式对象 // get() 失败,尝试 JSON 序列化/反序列化解包响应式对象
try { try {
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 {
// 静默失败 // 静默失败
} }
return 0; return 0;
}; };
// 方法 // 方法
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
} };
} }
export const proxy = { export const proxy = {
dev: { dev: {
// 本地地址 // 本地地址
target: "http://127.0.0.1:8001", target: "http://127.0.0.1:8001",
changeOrigin: true, changeOrigin: true,
rewrite: (path: string) => path.replace("/dev", ""), rewrite: (path: string) => path.replace("/dev", ""),
}, },
}; };
export const value = "dev"; export const value = "dev";
/// <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);
......
<template> <template>
<view <view style="flex: 1">
<view id="chart-container-1" class="chart-container">
style="flex: 1" <!-- #ifdef APP -->
> <!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<view class="chart-container" id="chart-container-1"> <l-echart ref="chartRef"
<!-- #ifdef APP --> :before-delay="0"
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 --> class="chart"
<l-echart :enable-hover="false"
ref="chartRef" :is-clickable="false"
@finished="initChart" @finished="initChart">
class="chart" </l-echart>
:enable-hover="false" <!-- #endif -->
:is-clickable="false" <!-- #ifndef APP -->
:before-delay="0"> <l-echart ref="chartRef"
</l-echart> class="chart"
<!-- #endif --> @finished="initChart">
<!-- #ifndef APP --> </l-echart>
<l-echart ref="chartRef" @finished="initChart" class="chart"></l-echart> <!-- #endif -->
<!-- #endif --> </view>
</view> <view id="chart-container-2"
<view class="chart-container" id="chart-container-2" style="margin-top: 16px"> class="chart-container"
<!-- #ifdef APP --> style="margin-top: 16px">
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 --> <!-- #ifdef APP -->
<l-echart <!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
ref="lineChartRef" <l-echart ref="lineChartRef"
@finished="initLineChart" :before-delay="0"
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"
<!-- #endif --> class="chart"
</view> @finished="initLineChart">
</view> </l-echart>
<!-- #endif -->
</view>
</view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { get } from "@/utils/common.uts"; import { get } from "@/utils/common.uts";
......
<template> <template>
<view> <view>
<image class="image" :fade-show="true" mode="widthFix" :src="imageSrc"></image> <image class="image"
<video :fade-show="true"
class="video" mode="widthFix"
:src="src" :src="imageSrc">
controls </image>
autoplay <video autoplay
style="width: 100%; height: 300px" class="video"
></video> controls
</view> :src="src"
style="width: 100%; height: 300px">
</video>
</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>
<scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50"> <scroll-view class="flex flex-col bg-gray-50"
<view class="flex flex-col px-5 py-5"> scroll-y="true"
<!-- 标题区域 --> style="flex: 1">
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg"> <view class="flex flex-col px-5 py-5">
<text class="text-3xl font-bold text-white mb-2 block">权限申请示例</text> <!-- 标题区域 -->
<text class="text-base text-white opacity-90 block">使用 permission-handler-plus 插件</text> <view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
</view> <text class="text-3xl font-bold text-white mb-2 block">权限申请示例</text>
<text class="text-base text-white opacity-90 block">使用 permission-handler-plus 插件</text>
</view>
<!-- 权限列表 --> <!-- 权限列表 -->
<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">
<view class="flex flex-row items-center justify-between mb-3"> <text class="text-2xl mr-3">{{ permission.icon }}</text>
<view class="flex flex-row items-center"> <view class="flex flex-col">
<text class="text-2xl mr-3">{{ permission.icon }}</text> <text class="text-lg font-semibold text-gray-800 block">{{ permission.displayName }}</text>
<view class="flex flex-col"> <text class="text-sm text-gray-500 block">{{ permission.desc }}</text>
<text class="text-lg font-semibold text-gray-800 block">{{ permission.displayName }}</text> </view>
<text class="text-sm text-gray-500 block">{{ permission.desc }}</text> </view>
</view> <view class="px-3 py-1 rounded-full"
</view> :class="`status-${ permission.status}`">
<view <text class="text-xs font-medium" :class="`status-text-${ permission.status}`">
class="px-3 py-1 rounded-full" {{ getStatusText(permission.status) }}
:class="'status-' + permission.status" </text>
> </view>
<text class="text-xs font-medium" :class="'status-text-' + permission.status"> </view>
{{ getStatusText(permission.status) }}
</text>
</view>
</view>
<!-- 操作按钮 --> <!-- 操作按钮 -->
<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 class="btn btn-success mr-2 mb-2"
</button> :disabled="permission.status === 'granted'"
<button @click="requestPermission(permission)">
class="btn btn-success mr-2 mb-2" 申请权限
@click="requestPermission(permission)" </button>
:disabled="permission.status === 'granted'" </view>
> </view>
申请权限 </view>
</button>
</view>
</view>
</view>
<!-- 操作日志 --> <!-- 操作日志 -->
<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">
:key="index" <view v-for="(log, index) in logs"
class="mb-2 pb-2 border-b border-gray-200" :key="index"
> 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>
清空日志 </view>
</button> </view>
</view> </scroll-view>
</view>
</scroll-view>
</template> </template>
<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" 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">
<text class="text-3xl font-bold text-white mb-2">uni-app x 示例</text> <text class="text-3xl font-bold text-white mb-2">uni-app x 示例</text>
<text class="text-base text-white opacity-90">功能演示与测试</text> <text class="text-base text-white opacity-90">功能演示与测试</text>
</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"
class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full" :key="item.label + item.path"
:class="{ 'card-pressed': isCardPressed(item.path) }" class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full"
@touchstart="handleTouchStart(item.path)" :class="{ 'card-pressed': isCardPressed(item.path) }"
@touchend="pressedCard = ''" @tap="toPath(item)"
@tap="toPath(item)" @touchend="pressedCard = ''"
v-for="item in data" @touchstart="handleTouchStart(item.path)">
:key="item.label + item.path" <!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 -->
> <view class="flex flex-row items-center p-5 w-full">
<!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 --> <view class="flex flex-row items-center">
<view class="flex flex-row items-center p-5 w-full"> <view class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4">
<view class="flex flex-row items-center"> <text class="text-2xl">{{ getIcon(item.icon) }}</text>
<view </view>
class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4" <text class="text-lg font-semibold text-gray-800">
> {{ item.label }}
<text class="text-2xl">{{ getIcon(item.icon) }}</text> </text>
</view> </view>
<text class="text-lg font-semibold text-gray-800"> <view class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0"
{{ item.label }} style="margin-left: auto">
</text> <text class="text-lg text-white font-bold">→</text>
</view> </view>
<view </view>
class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0" </view>
style="margin-left: auto" </view>
> </view>
<text class="text-lg text-white font-bold">→</text> </view>
</view> </scroll-view>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
...@@ -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;
} }
...@@ -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,14 +172,76 @@ export class Router { ...@@ -104,14 +172,76 @@ 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;
}
// 判断是否为自定义导航栏页面
isCustomNavbarPage() {
return this.route()?.isCustomNavbar ?? false;
}
// 判断页面栈是否只有一个页面
isFirstPage() {
return getCurrentPages().length == 1;
}
// 判断是否为首页
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;
} }
// 获取当前页面路径 // 获取当前页面路径
...@@ -119,13 +249,6 @@ export class Router { ...@@ -119,13 +249,6 @@ export class Router {
return this.route()?.path ?? ""; return this.route()?.path ?? "";
} }
// 简单跳转页面(默认 navigateTo)
to(path: string) {
this.push({
path
});
}
// 路由跳转,支持多种模式和参数 // 路由跳转,支持多种模式和参数
push(options: PushOptions) { push(options: PushOptions) {
let { let {
...@@ -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,
...@@ -198,6 +324,7 @@ export class Router { ...@@ -198,6 +324,7 @@ export class Router {
complete complete
}); });
break; break;
}
} }
}; };
...@@ -216,145 +343,21 @@ export class Router { ...@@ -216,145 +343,21 @@ 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) {
return path == this.defaultPath("login");
}
// 跳转到登录页(防抖处理)
login = debounce(() => {
if (!this.isLoginPage(this.path())) {
this.push({
path: "/pages/user/login",
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) { route() {
this.eventsMap.beforeEach = cb; return last(this.getPages());
} }
// 注册登录后回调 // 简单跳转页面(默认 navigateTo)
afterLogin(cb: AfterLogin) { to(path: string) {
this.eventsMap.afterLogin = cb; this.push({
path
});
} }
} }
......
...@@ -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;
} }
...@@ -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-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!