Commit 345bb304 by Jaxon

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

- 调整导入顺序和导出顺序以保持一致性
- 统一使用严格相等运算符(!==/===)替代宽松相等
- 规范对象属性顺序和类型定义结构
- 优化字符串模板和箭头函数语法
- 统一代码缩进和换行格式
- 修复条件表达式括号和三元运算符格式
- 更新文件路径引用和模块声明格式
1 parent dd5feff4
Showing 48 changed files with 943 additions and 948 deletions
<script lang="uts">
let firstBackTime = 0;
export default {
onLaunch: function () {
onLaunch () {
console.log("App Launch");
},
onShow: function () {
onShow () {
console.log("App Show");
},
onHide: function () {
onHide () {
console.log("App Hide");
},
// #ifdef APP-ANDROID
onLastPageBackPress: function () {
onLastPageBackPress () {
console.log("App LastPageBackPress");
if (firstBackTime == 0) {
uni.showToast({
......@@ -28,7 +28,7 @@ export default {
}
},
// #endif
onExit: function () {
onExit () {
console.log("App Exit");
}
};
......
......@@ -163,4 +163,4 @@ export const signSecretKey: SignSecretKeyItem = signSecretKeyMap[currentTarget]
export const pathEnum: UTSJSONObject = PATH_ENUM;
export const pathEnumExport: UTSJSONObject = PATH_ENUM;
// 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 { 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> = {
scrm: domain,
......@@ -18,14 +18,6 @@ const HOST: Record<HostType, string> = {
* - 处理业务 code 及登录态失效跳转
*/
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 接口方法名
......@@ -36,17 +28,115 @@ class Request {
fetch(method: string, data: UTSJSONObject, returnAll: boolean = true, hostType?: HostType): Promise<any> {
const payload = {} as UTSJSONObject;
// method
payload["method"] = method;
payload.method = method;
// 合并业务参数
const dataKeys = Object.keys(data as any) as string[];
for (let i = 0; i < dataKeys.length; i++) {
const key = dataKeys[i];
for (const key of dataKeys) {
// @ts-ignore
payload[key] = (data as UTSJSONObject)[key];
}
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(
requestMethod: "GET" | "POST",
params: UTSJSONObject,
......@@ -72,28 +162,28 @@ class Request {
const header =
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 == "") {
projectName = this.getRopProject(params["method"] as string);
projectName = this.getRopProject(params.method as string);
}
const path = pathEnum[projectName] ?? "";
const requestData = this.getData(params, finalHostType);
uni.request({
url: `${HOST[finalHostType]}${path}router?method=${requestData["method"]}`,
url: `${HOST[finalHostType]}${path}router?method=${requestData.method}`,
data: requestData,
method: requestMethod,
header,
dataType: "json",
responseType: "text",
timeout: timeout ?? 60000,
timeout: timeout ?? 60_000,
success: (response) => {
const data: any = response.data;
const statusCode = response.statusCode;
......@@ -110,7 +200,7 @@ class Request {
return;
}
const code = (data.code ?? "") as string | number;
const code = (data.code ?? "") as number | string;
const message = (data.message ?? "") as string;
if (returnAll) {
......@@ -142,11 +232,11 @@ class Request {
fail: (error) => {
uni.hideLoading();
let title = "系统异常";
if (typeof error == "string") {
if (typeof error === "string") {
title = error;
} else {
// @ts-ignore
const errMsg = (error as any).errMsg as string | null;
const errMsg = (error as any).errMsg as null | string;
if (errMsg != null && errMsg != "") {
title = errMsg;
} else {
......@@ -154,7 +244,7 @@ class Request {
}
}
console.error(`${params["method"]} 接口异常:`, error);
console.error(`${params.method} 接口异常:`, error);
uni.showToast({
title,
icon: "error"
......@@ -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();
......
......@@ -9,19 +9,19 @@ function encodeUTF8(s: string): number[] {
const c = s.charCodeAt(i);
if (c < 0x80) {
r.push(c);
} else if (c < 0x800) {
r.push(0xc0 + ((c >> 6) & 0x1f), 0x80 + (c & 0x3f));
} else if (c < 0x8_00) {
r.push(0xC0 + ((c >> 6) & 0x1F), 0x80 + (c & 0x3F));
} else {
const x = c ^ 0xd800;
const x = c ^ 0xD8_00;
if (x >> 10 == 0) {
const next = s.charCodeAt(i + 1) ^ 0xdc00;
const code = (x << 10) + next + 0x10000;
r.push(0xf0 + ((code >> 18) & 0x7), 0x80 + ((code >> 12) & 0x3f));
const next = s.charCodeAt(i + 1) ^ 0xDC_00;
const code = (x << 10) + next + 0x1_00_00;
r.push(0xF0 + ((code >> 18) & 0x7), 0x80 + ((code >> 12) & 0x3F));
i++;
} 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++;
}
......@@ -45,12 +45,12 @@ export function sha1(s: string): string {
s32[l - 1] = data.length << 3;
const w: number[] = [];
const k = [1518500249, 1859775393, -1894007588, -899497514];
let m0 = 1732584193;
let m1 = -271733879;
let m2 = ~1732584193;
let m3 = ~(-271733879);
let m4 = -1009589776;
const k = [1_518_500_249, 1_859_775_393, -1_894_007_588, -899_497_514];
let m0 = 1_732_584_193;
let m1 = -271_733_879;
let m2 = ~1_732_584_193;
let m3 = ~(-271_733_879);
let m4 = -1_009_589_776;
const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c));
const f0 = (): number => (m1 & m2) | (~m1 & m3);
......
import { get, keys, set } from "../../utils/common.uts";
import { sha1 } from "./sha1.uts";
import { keys, get, set } from "../../utils/common.uts";
/**
* 参数签名方法(从 gl_tape/api/request/sign.js 迁移)
......@@ -18,8 +18,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
// 先将入参拷贝到 realObj 中,并清理 sign 字段
const rawKeys = keys(params);
for (let i = 0; i < rawKeys.length; i++) {
const key = rawKeys[i];
for (const key of rawKeys) {
if (key == "sign") {
continue;
}
......@@ -32,13 +31,12 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
sortedKeys.sort((a, b) => a.localeCompare(b));
// 归一化 value:null -> "",对象 -> JSON 字符串
for (let i = 0; i < sortedKeys.length; i++) {
const key = sortedKeys[i];
for (const key of sortedKeys) {
let obj: any | null = get(realObj, key);
if (obj == null) {
obj = "";
} else if (typeof obj == "object") {
} else if (typeof obj === "object") {
obj = JSON.stringify(obj);
}
......@@ -47,8 +45,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
// 组装待签名字符串(排除 noSignAttr 指定的字段)
const segments: string[] = [];
for (let i = 0; i < sortedKeys.length; i++) {
const key = sortedKeys[i];
for (const key of sortedKeys) {
if (noSignAttr.indexOf(key) >= 0) {
continue;
}
......
import { evaluationDomain, pathEnum, signSecretKey } from "../env.uts";
import { storage } from "../../utils/storage.uts";
import { evaluationDomain, pathEnum, signSecretKey } from "../env.uts";
type GscPostConfig = {
duplicatePrevention?: boolean;
returnAll?: boolean;
timeout?: number;
duplicatePrevention?: boolean;
};
/**
......@@ -35,30 +35,29 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig
return;
}
const baseURL = `${evaluationDomain}${pathEnum["evaluation"]}`;
const baseURL = `${evaluationDomain}${pathEnum.evaluation}`;
const fullUrl = `${baseURL}${url}`;
// 组装请求体,自动注入 sessionId
const payload = {} as UTSJSONObject;
const dataKeys = Object.keys(data as any) as string[];
for (let i = 0; i < dataKeys.length; i++) {
const key = dataKeys[i];
for (const key of dataKeys) {
// @ts-ignore
payload[key] = (data as UTSJSONObject)[key];
}
// sessionId 自动注入
const sessionId = storage.get("sessionId") as string | null;
if (sessionId != null && sessionId != "" && payload["sessionId"] == null) {
payload["sessionId"] = sessionId;
const sessionId = storage.get("sessionId") as null | string;
if (sessionId != null && sessionId != "" && payload.sessionId == null) {
payload.sessionId = sessionId;
}
// 简单的重复提交防护:可选地附加一次性请求标识(仅客户端语义)
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 行为)
const header = {
......@@ -114,7 +113,7 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig
fail: (error) => {
let title = "业务异常";
// @ts-ignore
const errMsg = (error as any).errMsg as string | null;
const errMsg = (error as any).errMsg as null | string;
if (errMsg == "request:fail") {
title = "网络异常";
} else if (errMsg != null && errMsg != "") {
......
<template>
<view v-if="isShow" class="publish-popup-mask" @click="closePopup">
<view class="publish-popup-container" @click.stop>
<slot name="content"></slot>
</view>
</view>
<view v-if="isShow"
class="publish-popup-mask"
@click="closePopup">
<view class="publish-popup-container" @click.stop>
<slot name="content"></slot>
</view>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue';
import { ref } from "vue";
// Props
const props = defineProps<{
type?: string;
isShowFooter?: boolean;
showTitle?: boolean;
type?: string;
}>();
// 响应式数据
......
<template>
<view class="type-tab">
<scroll-view class="type-box" scroll-x="true" :show-scrollbar="false" scroll-with-animation>
<view class="type-scroll-content">
<view
class="tab-item"
:class="[tabClass(index)]"
v-for="(i, index) in typeList"
:key="index"
@click.stop="tabClick(index, i)"
>
<view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']">
<text class="tab-name">{{ getTabName(i) }}</text>
<text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text>
</view>
</view>
</view>
</scroll-view>
</view>
<view class="type-tab">
<scroll-view class="type-box"
scroll-with-animation
scroll-x="true"
:show-scrollbar="false">
<view class="type-scroll-content">
<view v-for="(i, index) in typeList"
:key="index"
class="tab-item"
:class="[tabClass(index)]"
@click.stop="tabClick(index, i)">
<view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']">
<text class="tab-name">{{ getTabName(i) }}</text>
<text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text>
</view>
</view>
</view>
</scroll-view>
</view>
</template>
<script setup lang="uts">
import { ref, computed } from 'vue';
import { get } from '@/utils/common.uts';
import { get } from "@/utils/common.uts";
// Props 类型:使用 any[] 避免响应式对象类型转换问题
const props = withDefaults(defineProps<{
typeList: any[];
tabIndex: number;
nameKey?: string;
isShowCount?: boolean;
nameKey?: string;
tabIndex: number;
typeList: any[];
}>(), {
nameKey: 'tabName',
nameKey: "tabName",
isShowCount: false
});
// Emits
const emit = defineEmits<{
(e: 'tabClick', index: number, item: any): void;
(e: "tabClick", index: number, item: any): void;
}>();
......@@ -44,11 +45,11 @@ const emit = defineEmits<{
// 响应式对象在 app 端无法通过 get() 访问,使用 JSON 序列化/反序列化解包
const getTabName = (item: any): string => {
// 先尝试 get()
let name = get(item, props.nameKey);
const name = get(item, props.nameKey);
if (name != null) {
return name as string;
}
// get() 失败,尝试 JSON 序列化/反序列化解包响应式对象
try {
const jsonStr = JSON.stringify(item);
......@@ -58,55 +59,55 @@ const getTabName = (item: any): string => {
if (name1 != null) {
return name1 as string;
}
const name2 = get(parsed, 'tabName');
const name2 = get(parsed, "tabName");
if (name2 != null) {
return name2 as string;
}
}
} catch (e: any) {
} catch {
// 静默失败
}
return '未知';
return "未知";
};
const getTabCount = (item: any): number => {
// 先尝试 get()
let count = get(item, 'count');
const count = get(item, "count");
if (count != null) {
return count as number;
}
// get() 失败,尝试 JSON 序列化/反序列化解包响应式对象
try {
const jsonStr = JSON.stringify(item);
const parsed = JSON.parse(jsonStr) as any;
if (parsed != null) {
const countValue = get(parsed, 'count');
const countValue = get(parsed, "count");
if (countValue != null) {
return countValue as number;
}
}
} catch (e: any) {
} catch {
// 静默失败
}
return 0;
};
// 方法
const tabClass = (index: number): string => {
let className = '';
let className = "";
if (props.tabIndex == index) {
className = 'active ';
if (index == 0) className += 'first-nav';
else className += 'second-nav';
className = "active ";
if (index == 0) className += "first-nav";
else className += "second-nav";
}
return className;
};
const tabClick = (index: number, item: any) => {
emit('tabClick', index, item);
emit("tabClick", index, item);
};
</script>
......
// composables/useTheme.uts
// 主题 Composable - 提供响应式主题变量和切换接口
import { ref, computed, onMounted } from 'vue'
import { getThemeManager, ThemeName, ThemeVariables } from '@/utils/theme-manager.uts'
import { getScreenSize } from '@/utils/screen-adapt.uts'
import { computed, onMounted, ref } from "vue";
import { getThemeManager, ThemeName, ThemeVariables } from "@/utils/theme-manager.uts";
/**
* 主题 Composable
* 类似 i18n 的使用方式,提供主题变量和切换接口
*/
export function useTheme() {
const themeManager = getThemeManager()
const currentThemeName = ref<ThemeName>(themeManager.getCurrentThemeName())
const theme = ref<ThemeVariables | null>(themeManager.getCurrentTheme())
const themeManager = getThemeManager();
const currentThemeName = ref<ThemeName>(themeManager.getCurrentThemeName());
const theme = ref<null | ThemeVariables>(themeManager.getCurrentTheme());
/**
* 设置主题
*/
function setTheme(themeName: ThemeName): boolean {
const success = themeManager.setTheme(themeName)
const success = themeManager.setTheme(themeName);
if (success) {
currentThemeName.value = themeName
theme.value = themeManager.getCurrentTheme()
currentThemeName.value = themeName;
theme.value = themeManager.getCurrentTheme();
}
return success
return success;
}
/**
* 自动选择主题(根据屏幕尺寸)
*/
function autoSelectTheme(): void {
themeManager.autoSelectTheme()
currentThemeName.value = themeManager.getCurrentThemeName()
theme.value = themeManager.getCurrentTheme()
themeManager.autoSelectTheme();
currentThemeName.value = themeManager.getCurrentThemeName();
theme.value = themeManager.getCurrentTheme();
}
/**
......@@ -40,50 +40,50 @@ export function useTheme() {
*/
const spacing = computed(() => {
return (key: string): number => {
return themeManager.getSpacing(key)
}
})
return themeManager.getSpacing(key);
};
});
/**
* 获取圆角值
*/
const borderRadius = computed(() => {
return (key: string): number => {
return themeManager.getBorderRadius(key)
}
})
return themeManager.getBorderRadius(key);
};
});
/**
* 获取字体大小
*/
const fontSize = computed(() => {
return (key: string): number => {
return themeManager.getFontSize(key)
}
})
return themeManager.getFontSize(key);
};
});
/**
* 获取尺寸值
*/
const size = computed(() => {
return (key: string): number => {
return themeManager.getSize(key)
}
})
return themeManager.getSize(key);
};
});
/**
* 获取行高值
*/
const lineHeight = computed(() => {
return (key: string): number => {
return themeManager.getLineHeight(key)
}
})
return themeManager.getLineHeight(key);
};
});
// 初始化时自动选择主题
onMounted(() => {
autoSelectTheme()
})
autoSelectTheme();
});
return {
// 当前主题名称
......@@ -104,5 +104,5 @@ export function useTheme() {
size,
// 获取行高值
lineHeight
}
};
}
// composables/useThemeVariables.uts
// CSS 变量主题 Composable
import { ref, computed, onMounted } from 'vue'
import { getThemeVariablesStyle } from '@/utils/theme-variables.uts'
import { useTheme } from './useTheme.uts'
import { computed, onMounted, ref } from "vue";
import { getThemeVariablesStyle } from "@/utils/theme-variables.uts";
import { useTheme } from "./useTheme.uts";
/**
* CSS 变量主题 Composable
* 提供响应式的 CSS 变量样式对象
*/
export function useThemeVariables() {
const { currentThemeName, autoSelectTheme } = useTheme()
const themeVars = ref<Record<string, string>>({})
const { currentThemeName, autoSelectTheme } = useTheme();
const themeVars = ref<Record<string, string>>({});
/**
* 更新 CSS 变量
*/
function updateThemeVariables(): void {
themeVars.value = getThemeVariablesStyle()
themeVars.value = getThemeVariablesStyle();
}
// 初始化时设置 CSS 变量
onMounted(() => {
updateThemeVariables()
})
updateThemeVariables();
});
// 监听主题变化,自动更新 CSS 变量
const themeVarsComputed = computed(() => {
// 当主题名称变化时,重新计算 CSS 变量
return getThemeVariablesStyle()
})
return getThemeVariablesStyle();
});
return {
// CSS 变量样式对象(用于 :style 绑定)
themeVars: themeVarsComputed,
// 手动更新 CSS 变量
updateThemeVariables
}
};
}
export const proxy = {
dev: {
// 本地地址
target: "http://127.0.0.1:8001",
changeOrigin: true,
rewrite: (path: string) => path.replace("/dev", ""),
},
dev: {
// 本地地址
target: "http://127.0.0.1:8001",
changeOrigin: true,
rewrite: (path: string) => path.replace("/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>;
export default component;
}
declare module '*.vue' {
import { DefineComponent } from 'vue';
declare module "*.vue" {
import { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>;
export default component;
}
......
import { createSSRApp } from "vue";
import { appMixin } from "./utilsApi";
import App from "./App.uvue";
import { appMixin } from "./utilsApi";
export function createApp() {
const app = createSSRApp(App);
......
<template>
<view
style="flex: 1"
>
<view class="chart-container" id="chart-container-1">
<!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart
ref="chartRef"
@finished="initChart"
class="chart"
:enable-hover="false"
:is-clickable="false"
:before-delay="0">
</l-echart>
<!-- #endif -->
<!-- #ifndef APP -->
<l-echart ref="chartRef" @finished="initChart" class="chart"></l-echart>
<!-- #endif -->
</view>
<view class="chart-container" id="chart-container-2" style="margin-top: 16px">
<!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart
ref="lineChartRef"
@finished="initLineChart"
class="chart"
:enable-hover="false"
:is-clickable="false"
:before-delay="0">
</l-echart>
<!-- #endif -->
<!-- #ifndef APP -->
<l-echart ref="lineChartRef" @finished="initLineChart" class="chart"></l-echart>
<!-- #endif -->
</view>
</view>
<view style="flex: 1">
<view id="chart-container-1" class="chart-container">
<!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart ref="chartRef"
:before-delay="0"
class="chart"
:enable-hover="false"
:is-clickable="false"
@finished="initChart">
</l-echart>
<!-- #endif -->
<!-- #ifndef APP -->
<l-echart ref="chartRef"
class="chart"
@finished="initChart">
</l-echart>
<!-- #endif -->
</view>
<view id="chart-container-2"
class="chart-container"
style="margin-top: 16px">
<!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart ref="lineChartRef"
:before-delay="0"
class="chart"
:enable-hover="false"
:is-clickable="false"
@finished="initLineChart">
</l-echart>
<!-- #endif -->
<!-- #ifndef APP -->
<l-echart ref="lineChartRef"
class="chart"
@finished="initLineChart">
</l-echart>
<!-- #endif -->
</view>
</view>
</template>
<script setup lang="uts">
import { get } from "@/utils/common.uts";
......
<template>
<view>
<image class="image" :fade-show="true" mode="widthFix" :src="imageSrc"></image>
<video
class="video"
:src="src"
controls
autoplay
style="width: 100%; height: 300px"
></video>
</view>
<view>
<image class="image"
:fade-show="true"
mode="widthFix"
:src="imageSrc">
</image>
<video autoplay
class="video"
controls
:src="src"
style="width: 100%; height: 300px">
</video>
</view>
</template>
<script setup lang="uts">
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 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");
</script>
<template>
<scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50">
<view class="flex flex-col px-5 py-5">
<!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
<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>
<scroll-view class="flex flex-col bg-gray-50"
scroll-y="true"
style="flex: 1">
<view class="flex flex-col px-5 py-5">
<!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
<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
v-for="permission in permissions"
:key="permission.name"
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">
<text class="text-2xl mr-3">{{ permission.icon }}</text>
<view class="flex flex-col">
<text class="text-lg font-semibold text-gray-800 block">{{ permission.displayName }}</text>
<text class="text-sm text-gray-500 block">{{ permission.desc }}</text>
</view>
</view>
<view
class="px-3 py-1 rounded-full"
:class="'status-' + permission.status"
>
<text class="text-xs font-medium" :class="'status-text-' + permission.status">
{{ getStatusText(permission.status) }}
</text>
</view>
</view>
<!-- 权限列表 -->
<view class="flex flex-col">
<view v-for="permission in permissions"
:key="permission.name"
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">
<text class="text-2xl mr-3">{{ permission.icon }}</text>
<view class="flex flex-col">
<text class="text-lg font-semibold text-gray-800 block">{{ permission.displayName }}</text>
<text class="text-sm text-gray-500 block">{{ permission.desc }}</text>
</view>
</view>
<view class="px-3 py-1 rounded-full"
:class="`status-${ permission.status}`">
<text class="text-xs font-medium" :class="`status-text-${ permission.status}`">
{{ getStatusText(permission.status) }}
</text>
</view>
</view>
<!-- 操作按钮 -->
<view class="flex flex-row flex-wrap">
<button
class="btn btn-primary mr-2 mb-2"
@click="checkPermission(permission)"
>
检查权限
</button>
<button
class="btn btn-success mr-2 mb-2"
@click="requestPermission(permission)"
:disabled="permission.status === 'granted'"
>
申请权限
</button>
</view>
</view>
</view>
<!-- 操作按钮 -->
<view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2"
@click="checkPermission(permission)">
检查权限
</button>
<button class="btn btn-success mr-2 mb-2"
:disabled="permission.status === 'granted'"
@click="requestPermission(permission)">
申请权限
</button>
</view>
</view>
</view>
<!-- 操作日志 -->
<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>
<scroll-view style="max-height: 300px" scroll-y="true" class="flex flex-col">
<view
v-for="(log, index) in logs"
:key="index"
class="mb-2 pb-2 border-b border-gray-200"
>
<text class="text-sm text-gray-600 block">{{ log }}</text>
</view>
</scroll-view>
<button
class="btn btn-secondary mt-3"
@click="clearLogs"
>
清空日志
</button>
</view>
</view>
</scroll-view>
<!-- 操作日志 -->
<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>
<scroll-view class="flex flex-col"
scroll-y="true"
style="max-height: 300px">
<view v-for="(log, index) in logs"
:key="index"
class="mb-2 pb-2 border-b border-gray-200">
<text class="text-sm text-gray-600 block">{{ log }}</text>
</view>
</scroll-view>
<button class="btn btn-secondary mt-3"
@click="clearLogs">
清空日志
</button>
</view>
</view>
</scroll-view>
</template>
<script setup lang="uts">
// 统一导入,编译器会自动根据平台选择对应的实现
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
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 = {
name: string;
displayName: string;
desc: string;
displayName: string;
icon: string;
name: string;
status: PermissionStatus;
};
......@@ -187,7 +178,7 @@ const checkPermission = (permission: Permission) => {
// 更新权限状态
const index = permissions.value.findIndex((p) => p.name == permission.name);
if (index >= 0) {
if (index !== -1) {
// 将插件返回的状态字符串转换为我们的状态类型
let status: PermissionStatus = "unknown";
if (result == "granted") {
......@@ -229,7 +220,7 @@ const requestPermission = (permission: Permission) => {
// 更新权限状态
const index = permissions.value.findIndex((p) => p.name == permission.name);
if (index >= 0) {
if (index !== -1) {
let status: PermissionStatus = "unknown";
if (statusStr == "granted") {
status = "granted";
......
<template>
<scroll-view style="flex: 1" class="flex flex-col bg-indigo-500">
<view class="flex flex-col">
<view class="flex flex-col">
<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-base text-white opacity-90">功能演示与测试</text>
</view>
<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 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-base text-white opacity-90">功能演示与测试</text>
</view>
<view class="flex flex-col px-12 py-12 flex-1 bg-gray-50 rounded-t-3xl">
<view
class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full"
:class="{ 'card-pressed': isCardPressed(item.path) }"
@touchstart="handleTouchStart(item.path)"
@touchend="pressedCard = ''"
@tap="toPath(item)"
v-for="item in data"
:key="item.label + item.path"
>
<!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 -->
<view class="flex flex-row items-center p-5 w-full">
<view class="flex flex-row items-center">
<view
class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4"
>
<text class="text-2xl">{{ getIcon(item.icon) }}</text>
</view>
<text class="text-lg font-semibold text-gray-800">
{{ item.label }}
</text>
</view>
<view
class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0"
style="margin-left: auto"
>
<text class="text-lg text-white font-bold">→</text>
</view>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
<view class="flex flex-col px-12 py-12 flex-1 bg-gray-50 rounded-t-3xl">
<view v-for="item in data"
:key="item.label + item.path"
class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full"
:class="{ 'card-pressed': isCardPressed(item.path) }"
@tap="toPath(item)"
@touchend="pressedCard = ''"
@touchstart="handleTouchStart(item.path)">
<!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 -->
<view class="flex flex-row items-center p-5 w-full">
<view class="flex flex-row items-center">
<view class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4">
<text class="text-2xl">{{ getIcon(item.icon) }}</text>
</view>
<text class="text-lg font-semibold text-gray-800">
{{ item.label }}
</text>
</view>
<view class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0"
style="margin-left: auto">
<text class="text-lg text-white font-bold">→</text>
</view>
</view>
</view>
</view>
</view>
</view>
</scroll-view>
</template>
<script setup lang="uts">
......@@ -48,12 +42,12 @@ import { get } from "@/utils/common.uts";
// import { router } from "@/utils/router.uts";
type Item = {
label: string;
icon?: string;
path?: string;
children?: Item[];
disabled?: boolean;
hidden?: boolean;
children?: Item[];
icon?: string;
label: string;
path?: string;
};
const data = computed<Item[]>(() => {
......@@ -134,8 +128,8 @@ const toPath = (item: Item) => {
// 使用索引访问属性,避免 error18
// NavigateToFailImpl 类型特殊,需要先转换为 UTSJSONObject 或使用索引访问
let errMsg = "未知错误";
let errCode: number | null = null;
let errSubject: string | null = null;
let errCode: null | number = null;
let errSubject: null | string = null;
// 尝试使用 UTSJSONObject 转换
try {
......@@ -154,7 +148,7 @@ const toPath = (item: Item) => {
if (errSubjectTemp != null) {
errSubject = errSubjectTemp as string;
}
} catch (e: any) {
} catch {
// 如果转换失败,尝试使用 JSON 序列化/反序列化
try {
const jsonStr = JSON.stringify(err);
......@@ -172,8 +166,8 @@ const toPath = (item: Item) => {
if (errSubjectTemp != null) {
errSubject = errSubjectTemp as string;
}
} catch (e2: any) {
console.error("无法解析错误对象:", e2);
} catch (error: any) {
console.error("无法解析错误对象:", error);
}
}
......
const path = require("node:path");
const { r } = require("./shared");
const path = require("path");
// 确保能找到 tailwindcss-rem2px-preset 模块
// 使用 resolve 来查找模块路径,支持不同的工作目录
......
......@@ -2,19 +2,19 @@
"extends": "@vue/tsconfig/tsconfig.json",
"compilerOptions": {
"ignoreDeprecations": "5.0",
"verbatimModuleSyntax": true,
"experimentalDecorators": true,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"noImplicitAny": false,
"types": ["@dcloudio/types", "vue"],
"lib": ["esnext", "dom"],
"outDir": "esbuild",
"experimentalDecorators": true,
"paths": {
"@/*": ["./src/*"],
"$/*": ["./uni_modules/*"]
}
},
"resolveJsonModule": true,
"types": ["@dcloudio/types", "vue"],
"noImplicitAny": false,
"outDir": "esbuild",
"sourceMap": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"vueCompilerOptions": {
"extensions": [".vue", ".uvue"]
......
export type UserInfo = {
unionid: string; // 用户唯一id
id: number; // 用户id
nickName: string; // 昵称
avatarUrl?: string; // 头像
phone: string; // 手机号
gender: number; // 性别
status: number; // 状态
birthday?: string; // 生日
city?: string; // 城市
createTime: string; // 创建时间
description?: string; // 描述
district?: string; // 区县
gender: number; // 性别
id: number; // 用户id
loginType: number; // 登录类型
nickName: string; // 昵称
phone: string; // 手机号
province?: string; // 省份
city?: string; // 城市
district?: string; // 区县
birthday?: string; // 生日
createTime: string; // 创建时间
status: number; // 状态
unionid: string; // 用户唯一id
updateTime: string; // 更新时间
};
export type PushAnimationType =
| "auto"
| "fade-in"
| "none"
| "slide-in-right"
| "pop-in"
| "slide-in-bottom"
| "slide-in-left"
| "slide-in-right"
| "slide-in-top"
| "slide-in-bottom"
| "fade-in"
| "zoom-out"
| "zoom-fade-out"
| "pop-in";
| "zoom-out";
export type BackAnimationType =
| "auto"
| "fade-out"
| "none"
| "slide-out-right"
| "pop-out"
| "slide-out-bottom"
| "slide-out-left"
| "slide-out-right"
| "slide-out-top"
| "slide-out-bottom"
| "fade-out"
| "zoom-in"
| "zoom-fade-in"
| "pop-out";
| "zoom-in";
export type PushMode = "navigateTo" | "redirectTo" | "reLaunch" | "switchTab";
export type BackOptions = {
delta?: number;
animationType?: BackAnimationType;
animationDuration?: number;
success?: (result: any) => void;
fail?: (result: any) => void;
animationType?: BackAnimationType;
complete?: (result: any) => void;
delta?: number;
fail?: (result: any) => void;
success?: (result: any) => void;
};
export type PushOptions = {
path: string;
mode?: PushMode;
animationDuration?: number;
animationType?: PushAnimationType;
complete?: (result: any) => void;
events?: any;
query?: UTSJSONObject;
fail?: (result: any) => void;
isAuth?: boolean;
mode?: PushMode;
params?: UTSJSONObject;
animationType?: PushAnimationType;
animationDuration?: number;
path: string;
query?: UTSJSONObject;
success?: (result: any) => void;
fail?: (result: any) => void;
complete?: (result: any) => void;
};
export type PageInstance = {
path: string;
vm: any;
style?: UTSJSONObject;
query: UTSJSONObject;
exposed: any;
isCustomNavbar: boolean;
meta?: UTSJSONObject;
path: string;
query: UTSJSONObject;
style?: UTSJSONObject;
vm: any;
};
declare module "@dcloudio/vite-plugin-uni";
declare type Theme = "light" | "dark";
declare type Theme = "dark" | "light";
declare interface Uni {
rpx2px(px: number): number;
......@@ -16,28 +16,28 @@ declare interface Uni {
}
declare interface JSON {
parseObject<T>(text: string): T | null;
parseObject<T>(text: string): null | T;
}
declare type UTSJSONObject = {
[key: string]: any;
parse?<T>(): T | null;
get?(key: string): any | null;
set?(key: string, value: any | null): void;
getAny?(key: string): any | null;
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, 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;
getString?(key: string): string | null;
getString?(key: string): null | string;
getString?(key: string, def: any): string;
getJSON?(key: string): UTSJSONObject | null;
getJSON?(key: string, def: any): UTSJSONObject;
getArray?<T>(key: string): T[] | null;
getArray?<T>(key: string, def: T[]): T[];
getArray?(key: string): any[] | null;
getArray?(key: string, def: any[]): any[];
parse?<T>(): null | T;
set?(key: string, value: any | null): void;
toMap?(): Map<string, any>;
};
......@@ -49,14 +49,14 @@ declare interface ChooseImageTempFile {
}
declare type RequestMethod =
| "OPTIONS"
| "CONNECT"
| "DELETE"
| "GET"
| "HEAD"
| "OPTIONS"
| "POST"
| "PUT"
| "DELETE"
| "TRACE"
| "CONNECT";
| "TRACE";
declare interface DOMRect {
x: number;
......@@ -82,33 +82,33 @@ declare interface UniElement {
style: CSSStyleDeclaration;
classList: string[];
takeSnapshot(options: {
success?: (res: { tempFilePath: string }) => void;
fail?: (err: { errCode: number; errMsg: string }) => void;
success?: (res: { tempFilePath: string }) => void;
}): void;
getBoundingClientRectAsync(): Promise<DOMRect>;
getDrawableContext(): DrawableContext;
animate(
keyframes: UniAnimationKeyframe | UniAnimationKeyframe[],
options?:
| number
| {
delay?: number;
direction?: "normal" | "reverse" | "alternate" | "alternate-reverse";
direction?: "alternate" | "alternate-reverse" | "normal" | "reverse";
duration?: number;
easing?:
| "cubic-bezier"
| "ease"
| "ease-in"
| "ease-out"
| "ease-in-out"
| "linear"
| "cubic-bezier";
fill?: "backwards" | "forwards" | "both" | "none";
| "ease-out"
| "linear";
fill?: "backwards" | "both" | "forwards" | "none";
iterations?: number;
}
| number
): {
): null | {
id: string;
playState: "running" | "paused" | "finished" | "idle";
} | null;
playState: "finished" | "idle" | "paused" | "running";
};
}
declare interface CanvasContext extends HTMLCanvasElement {
......
......@@ -13,7 +13,7 @@ export function isArray(value: any): boolean {
* @example isObject([]) // false
*/
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 {
* @example isString(123) // false
*/
export function isString(value: any): boolean {
return typeof value == "string";
return typeof value === "string";
}
/**
......@@ -31,7 +31,7 @@ export function isString(value: any): boolean {
* @example isNumber('123') // false
*/
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 {
* @example isBoolean(1) // false
*/
export function isBoolean(value: any): boolean {
return typeof value == "boolean";
return typeof value === "boolean";
}
/**
......@@ -49,7 +49,7 @@ export function isBoolean(value: any): boolean {
* @example isFunction({}) // false
*/
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 {
*/
export function isEmpty(value: any): boolean {
if (isArray(value)) {
return (value as any[]).length == 0;
return (value as any[]).length === 0;
}
if (isString(value)) {
......@@ -83,7 +83,7 @@ export function isEmpty(value: any): boolean {
}
if (isObject(value)) {
return keys(value).length == 0;
return keys(value).length === 0;
}
return false;
......@@ -103,7 +103,7 @@ export function keys(value: any): string[] {
* @example first([1, 2, 3]) // 1
* @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;
}
......@@ -112,7 +112,7 @@ export function first<T>(array: T[]): T | null {
* @example last([1, 2, 3]) // 3
* @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;
}
......@@ -179,8 +179,8 @@ export function map<T, U>(array: T[], iteratee: (item: T, index: number) => U):
if (!isArray(array)) return result;
for (let i = 0; i < array.length; i++) {
result.push(iteratee(array[i], i));
for (const [i, element] of array.entries()) {
result.push(iteratee(element, i));
}
return result;
......@@ -198,8 +198,8 @@ export function reduce<T, U>(
if (!isArray(array)) return initialValue;
let accumulator: U = initialValue;
for (let i = 0; i < array.length; i++) {
accumulator = iteratee(accumulator, array[i], i);
for (const [i, element] of array.entries()) {
accumulator = iteratee(accumulator, element, i);
}
return accumulator;
......@@ -212,8 +212,8 @@ export function reduce<T, U>(
export function every<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return true;
for (let i = 0; i < array.length; i++) {
if (!predicate(array[i], i)) {
for (const [i, element] of array.entries()) {
if (!predicate(element, i)) {
return false;
}
}
......@@ -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 {
if (!isArray(array)) return false;
for (let i = 0; i < array.length; i++) {
if (predicate(array[i], i)) {
for (const [i, element] of array.entries()) {
if (predicate(element, i)) {
return true;
}
}
......@@ -247,8 +247,7 @@ export function uniq<T>(array: T[]): T[] {
const result: T[] = [];
const seen = new Map<T, boolean>();
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
const key = item;
if (!seen.has(item)) {
seen.set(key, true);
......@@ -268,8 +267,7 @@ export function flatten(array: any[]): any[] {
const result: any[] = [];
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
if (isArray(item)) {
result.push(...(item as any[]));
} else {
......@@ -289,8 +287,7 @@ export function flattenDeep(array: any[]): any[] {
const result: any[] = [];
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
if (isArray(item)) {
result.push(...flattenDeep(item as any[]));
} else {
......@@ -310,11 +307,11 @@ export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] {
const result = [...array];
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;
}
if (typeof a == "string" && typeof b == "string") {
if (typeof a === "string" && typeof b === "string") {
return order == "asc" ? a.localeCompare(b) : b.localeCompare(a);
}
......@@ -354,15 +351,14 @@ export function groupBy<T>(array: T[], key: string) {
const result = {};
for (let i = 0; i < array.length; i++) {
const item = array[i];
for (const item of array) {
let value = get(item as any, key)!;
if (typeof value == "number") {
if (typeof value === "number") {
value = value.toString();
}
if (typeof value == "string") {
if (typeof value === "string") {
if (!isArray(result[value])) {
result[value] = new Array<T>();
}
......@@ -388,7 +384,7 @@ export function assign(...items: any[]) {
* @example nth([1, 2, 3], 1) // 2
* @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) {
return array[index];
}
......@@ -415,9 +411,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo
const result: T[] = [];
for (let i = 0; i < array.length; i++) {
if (!predicate(array[i], i)) {
result.push(array[i]);
for (const [i, element] of array.entries()) {
if (!predicate(element, i)) {
result.push(element);
}
}
......@@ -432,9 +428,9 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
if (isArray(data)) {
const array = data as T[];
for (let i = 0; i < array.length; i++) {
if (array[i] != null) {
iteratee(array[i], i);
for (const [i, element] of array.entries()) {
if (element != null) {
iteratee(element, i);
}
}
}
......@@ -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
*/
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;
for (let i = 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return array[i];
for (const [i, element] of array.entries()) {
if (predicate(element, i)) {
return element;
}
}
return null;
......@@ -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 {
if (isObject(data)) {
const objKeys = keys(data);
for (let i = 0; i < objKeys.length; i++) {
const key = objKeys[i];
for (const key of objKeys) {
iteratee(get(data, key)!, key);
}
}
......@@ -585,9 +580,9 @@ export function random(min: number, max: number): number {
*/
export function base64ToBlob(data: string, type: string = "image/jpeg"): Blob {
// #ifdef H5
let bytes = window.atob(data.split(",")[1]);
let ab = new ArrayBuffer(bytes.length);
let ia = new Uint8Array(ab);
const bytes = window.atob(data.split(",")[1]);
const ab = new ArrayBuffer(bytes.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
......
import { isArray, parse } from "../utils";
type Page = {
meta?: UTSJSONObject;
path: string;
style?: UTSJSONObject;
meta?: UTSJSONObject;
};
type SubPackage = {
root: string;
pages: Page[];
root: string;
};
export type TabBarItem = {
text?: string;
pagePath: string;
iconPath?: string;
pagePath: string;
selectedIconPath?: string;
text?: string;
visible?: boolean;
};
export type TabBar = {
custom?: boolean;
color?: string;
selectedColor?: string;
backgroundColor?: string;
borderStyle?: string;
backgroundImage?: string;
backgroundRepeat?: "no-repeat" | "repeat" | "repeat-x" | "repeat-y";
blurEffect?: "dark" | "extralight" | "light" | "none";
list?: TabBarItem[];
position?: "top" | "bottom";
borderStyle?: string;
color?: string;
custom?: boolean;
fontSize?: string;
iconWidth?: string;
spacing?: string;
height?: string;
backgroundImage?: string;
backgroundRepeat?: "repeat" | "repeat-x" | "repeat-y" | "no-repeat";
iconWidth?: string;
list?: TabBarItem[];
position?: "bottom" | "top";
redDotColor?: string;
selectedColor?: string;
spacing?: string;
};
export type Ctx = {
appid: string;
color: UTSJSONObject;
globalStyle: UTSJSONObject;
pages: Page[];
uniIdRouter: UTSJSONObject;
theme: UTSJSONObject;
tabBar: TabBar;
subPackages: SubPackage[];
SAFE_CHAR_MAP_LOCALE: string[][];
color: UTSJSONObject;
subPackages: SubPackage[];
tabBar: TabBar;
theme: UTSJSONObject;
uniIdRouter: UTSJSONObject;
};
// 初始化 ctx 对象,不可修改!!
......@@ -64,7 +64,7 @@ if (isArray(ctx.subPackages)) {
ctx.subPackages.forEach((a) => {
a.pages.forEach((b) => {
PAGES.push({
path: a.root + "/" + b.path, // 拼接子包根路径和页面路径
path: `${a.root }/${ b.path}`, // 拼接子包根路径和页面路径
style: b.style,
meta: b.meta
});
......@@ -75,7 +75,7 @@ if (isArray(ctx.subPackages)) {
// 确保每个页面路径都以 "/" 开头,符合 uni-app x 规范
PAGES.forEach((e) => {
if (!e.path.startsWith("/")) {
e.path = "/" + e.path;
e.path = `/${ e.path}`;
}
});
......
export * from "./storage.uts";
export * from "./common.uts";
export * from "./parse.uts";
export * from "./storage.uts";
......@@ -9,11 +9,11 @@ import LocalStore from "./local-store";
// ===== 1. 定义数据 Schema =====
type UserSchema = {
name: string;
age: number;
createdAt: number;
email: string;
name: string;
status: "active" | "inactive";
createdAt: number;
updatedAt: number;
};
......@@ -199,10 +199,10 @@ try {
// 场景1:用户收藏管理
type FavoriteSchema = {
userId: string;
itemId: string;
itemType: "article" | "video" | "product";
createdAt: number;
itemId: string;
itemType: "article" | "product" | "video";
userId: string;
};
const favoriteStore = new LocalStore<FavoriteSchema>("favorite", {
......@@ -230,11 +230,11 @@ const userFavorites = favoriteStore.find({
// 场景2:购物车管理
type CartItemSchema = {
addedAt: number;
price: number;
productId: string;
productName: string;
price: number;
quantity: number;
addedAt: number;
};
const cartStore = new LocalStore<CartItemSchema>("cart", {
......@@ -262,6 +262,6 @@ if (cartItems.length > 0) {
// 计算购物车总价
let totalPrice = 0;
for (let i = 0; i < cartItems.length; i++) {
totalPrice += cartItems[i].price * cartItems[i].quantity;
for (const cartItem of cartItems) {
totalPrice += cartItem.price * cartItem.quantity;
}
......@@ -4,7 +4,7 @@ import { forEach, forInObject, isArray, isObject, isString } from "./common";
* 解析数据
* @example parse<Response>(res.data)
*/
export function parse<T>(data: any): T | null {
export function parse<T>(data: any): null | T {
// #ifdef APP-ANDROID
// @ts-ignore
return (data as UTSJSONObject).parse<T>();
......@@ -20,7 +20,7 @@ export function parse<T>(data: any): T | null {
* @param data 要解析的数据
* @returns 解析后的JSON对象
*/
export function parseObject<T>(data: string): T | null {
export function parseObject<T>(data: string): null | T {
// #ifdef APP-ANDROID
return JSON.parseObject<T>(data);
// #endif
......@@ -159,8 +159,8 @@ export const px2rpx = (px: number): number => {
* parseRpx('10px') // 返回 '10px'
*/
export const parseRpx = (val: number | string): string => {
if (typeof val == "number") {
return val + "rpx";
if (typeof val === "number") {
return `${val }rpx`;
}
return val;
......@@ -179,7 +179,7 @@ export const parseRpx = (val: number | string): string => {
export const getNum = (val: string): number => {
// 使用正则提取数字部分,支持小数和负数
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 => {
* @returns number - 返回对应的 rpx 数值
*/
export const getRpx = (val: number | string): number => {
if (typeof val == "number") {
if (typeof val === "number") {
return val;
}
......@@ -228,8 +228,8 @@ export const getRpx = (val: number | string): number => {
* @param val - 输入值,可以是 "10rpx"、"10px" 或数字 10
* @returns number - 返回对应的 px 数值
*/
export const getPx = (val: string | number) => {
if (typeof val == "number") {
export const getPx = (val: number | string) => {
if (typeof val === "number") {
return rpx2px(val);
}
......
......@@ -59,12 +59,12 @@ export function openAppSettings(): void {
*/
export function getInstalledPackages(): Promise<
Array<{
appName: string;
packName: string;
versionName: string;
versionCode: number;
appName: string;
versionName: string;
}>
> {
> {
// #ifdef APP-ANDROID
const packages = androidImpl.getInstalledPackages();
return Promise.resolve(packages);
......
......@@ -60,8 +60,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.readFile({
filePath: filePath,
encoding: encoding,
filePath,
encoding,
success: (res: any) => {
// ReadFileSuccessResult 类型,data 类型为 string | ArrayBuffer
// 由于 ReadFileSuccessResult 不是 UTSJSONObject,需要特殊处理
......@@ -77,10 +77,10 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
if (parsed != null) {
const temp = parsed.getAny("data");
console.error("readFile getAny('data'): ", temp);
console.error("readFile getAny('data'):", temp);
raw = temp != null ? temp as any : null;
}
} catch (e: any) {
} catch {
// 方法2:如果 parseObject 失败,尝试用普通 parse
try {
......@@ -90,16 +90,16 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// 尝试从解析后的对象中获取 data
if (parsed != null) {
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;
}
} catch (e2: any) {
console.error("readFile method2 failed: ", e2);
} catch (error: any) {
console.error("readFile method2 failed:", error);
}
}
if (raw != null) {
if (typeof raw == "string") {
if (typeof raw === "string") {
text = raw as string;
} else {
// ArrayBuffer 类型,需要转换为字符串
......@@ -110,8 +110,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// @ts-ignore
const decoder = new TextDecoder("utf-8");
text = decoder.decode(raw as ArrayBuffer);
} catch (e: any) {
console.error("ArrayBuffer decode error: ", e);
} catch (error: any) {
console.error("ArrayBuffer decode error:", error);
text = "";
}
// #endif
......@@ -121,11 +121,11 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// #endif
}
}
console.error("readFile text final: ", text);
console.error("readFile text final:", text);
resolve(text);
},
fail: (err: any) => {
console.error("readFile fail: ", err);
console.error("readFile fail:", err);
reject(err);
}
});
......@@ -141,8 +141,8 @@ export function writeFile(filePath: string, data: string): Promise<void> {
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.writeFile({
filePath: filePath,
data: data,
filePath,
data,
encoding: "utf-8",
success: () => {
resolve();
......@@ -162,7 +162,7 @@ export function deleteFile(filePath: string): Promise<void> {
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.unlink({
filePath: filePath,
filePath,
success: () => {
resolve();
},
......@@ -181,10 +181,10 @@ export function readDirectory(dirPath: string): Promise<string[]> {
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.readdir({
dirPath: dirPath,
dirPath,
success: (res: any) => {
const files = res.files;
if (files instanceof Array) {
if (Array.isArray(files)) {
resolve(files as string[]);
} else {
resolve([]);
......@@ -206,8 +206,8 @@ export function createDirectory(dirPath: string, recursive: boolean = false): Pr
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.mkdir({
dirPath: dirPath,
recursive: recursive,
dirPath,
recursive,
success: () => {
resolve();
},
......@@ -227,8 +227,8 @@ export function deleteDirectory(dirPath: string, recursive: boolean = false): Pr
return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager();
fs.rmdir({
dirPath: dirPath,
recursive: recursive,
dirPath,
recursive,
success: () => {
resolve();
},
......
......@@ -35,7 +35,7 @@ export function setUserAgent(userAgent: string): void {
// #ifndef APP
// H5 可以设置 navigator.userAgent
if (typeof navigator != "undefined") {
if (typeof navigator !== "undefined") {
Object.defineProperty(navigator, "userAgent", {
get: () => userAgent,
configurable: true
......
......@@ -11,8 +11,8 @@ import { openSchema } from "@/uni_modules/uts-openSchema";
// 应用信息类型
type AppInfo = {
version: string;
appid: string;
version: string;
};
/**
......@@ -32,8 +32,8 @@ export function getAppVersion(): string {
}
}
// #endif
} catch (e: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败: ", e);
} catch (error: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败:", error);
}
// 其它平台或获取失败时返回空字符串,由上层决定是否展示
......@@ -55,8 +55,8 @@ export function getAppId(): string {
}
}
// #endif
} catch (e: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败: ", e);
} catch (error: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败:", error);
}
return "";
......@@ -67,7 +67,7 @@ export function getAppId(): string {
* @param url 要打开的URL
*/
export function openURL(url: string): void {
if (url == null || url.length == 0) {
if (url == null || url.length === 0) {
console.error("[plus-runtime] URL不能为空");
return;
}
......@@ -78,14 +78,14 @@ export function openURL(url: string): void {
try {
openSchema(url);
return;
} catch (e: any) {
console.error("[plus-runtime] 使用 openSchema 打开 URL 失败: ", e, " url=", url);
} catch (error: any) {
console.error("[plus-runtime] 使用 openSchema 打开 URL 失败:", error, "url=", url);
}
// #endif
// 其它平台或兜底逻辑:H5 使用 window.open
// #ifndef APP
if (typeof window != "undefined") {
if (typeof window !== "undefined") {
window.open(url, "_blank");
}
// #endif
......
import { PAGES, TABS } from "./ctx";
import type { BackOptions, PageInstance, PushOptions } from "../types/router";
import {
storage,
last,
isNull,
isEmpty,
debounce,
get,
isEmpty,
isFunction,
toArray,
isNull,
last,
map,
debounce,
nth,
assign,
parse
storage,
toArray
} from "../utils";
import { PAGES, TABS } from "./ctx";
// 路由信息类型
type RouteInfo = {
isAuth?: boolean;
meta: UTSJSONObject;
path: string;
query: UTSJSONObject;
meta: UTSJSONObject;
isAuth?: boolean;
};
// 跳转前钩子类型
......@@ -30,22 +29,81 @@ type AfterLogin = () => void;
// 路由事件集合
type Events = {
beforeEach?: BeforeEach;
afterLogin?: AfterLogin;
beforeEach?: BeforeEach;
};
// 路由核心类
export class Router {
// 跳转到登录页(防抖处理)
login = debounce(() => {
if (!this.isLoginPage(this.path())) {
this.push({
path: "/pages/user/login",
mode: "reLaunch"
});
}
}, 300);
private eventsMap = {} as Events; // 事件存储
// 获取传递的 params 参数
params() {
return (storage.get("router-params") ?? {}) as UTSJSONObject;
// 注册登录后回调
afterLogin(cb: AfterLogin) {
this.eventsMap.afterLogin = cb;
}
// 获取传递的 query 参数
query() {
return this.route()?.query ?? {};
// 返回上一页
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();
}
}
}
// 注册跳转前钩子
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
......@@ -58,6 +116,16 @@ export class Router {
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[] {
return map(getCurrentPages(), (e) => {
......@@ -70,7 +138,7 @@ export class Router {
// 补全路径前缀
if (!path.startsWith("/")) {
path = "/" + path;
path = `/${ path}`;
}
// 获取页面样式
......@@ -104,14 +172,76 @@ export class Router {
});
}
// 获取指定路径的页面实例
getPage(path: string) {
return this.getPages().find((e) => e.path == path);
// 回到首页
home() {
this.push({
path: this.defaultPath("home")
});
}
// 获取当前路由页面实例
route() {
return last(this.getPages());
// 判断是否为当前页面
isCurrentPage(path: string) {
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 {
return this.route()?.path ?? "";
}
// 简单跳转页面(默认 navigateTo)
to(path: string) {
this.push({
path
});
}
// 路由跳转,支持多种模式和参数
push(options: PushOptions) {
let {
......@@ -147,7 +270,7 @@ export class Router {
const arr = toArray(query, (v, k) => {
return `${k}=${v}`;
});
path += "?" + arr.join("&");
path += `?${ arr.join("&")}`;
}
// params 通过 storage 临时存储
......@@ -163,7 +286,7 @@ export class Router {
// 跳转执行函数
const next = () => {
switch (mode) {
case "navigateTo":
case "navigateTo": {
uni.navigateTo({
url: path,
success,
......@@ -174,7 +297,8 @@ export class Router {
animationDuration
});
break;
case "redirectTo":
}
case "redirectTo": {
uni.redirectTo({
url: path,
success,
......@@ -182,7 +306,8 @@ export class Router {
complete
});
break;
case "reLaunch":
}
case "reLaunch": {
uni.reLaunch({
url: path,
success,
......@@ -190,7 +315,8 @@ export class Router {
complete
});
break;
case "switchTab":
}
case "switchTab": {
uni.switchTab({
url: path,
success,
......@@ -198,6 +324,7 @@ export class Router {
complete
});
break;
}
}
};
......@@ -216,145 +343,21 @@ export class Router {
}
}
// 回到首页
home() {
this.push({
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");
// 获取传递的 query 参数
query() {
return this.route()?.query ?? {};
}
// 注册跳转前钩子
beforeEach(cb: BeforeEach) {
this.eventsMap.beforeEach = cb;
// 获取当前路由页面实例
route() {
return last(this.getPages());
}
// 注册登录后回调
afterLogin(cb: AfterLogin) {
this.eventsMap.afterLogin = cb;
// 简单跳转页面(默认 navigateTo)
to(path: string) {
this.push({
path
});
}
}
......
......@@ -17,20 +17,20 @@ export interface ScreenInfo {
* 获取屏幕信息
*/
export function getScreenInfo(): ScreenInfo {
const windowInfo = uni.getWindowInfo()
const windowInfo = uni.getWindowInfo();
return {
width: windowInfo.windowWidth,
height: windowInfo.windowHeight,
pixelRatio: windowInfo.pixelRatio,
screenWidth: windowInfo.screenWidth,
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'
* - xlarge: >= 1024px(平板、大屏设备)
*/
export function getScreenSize(): ScreenSize {
const width = getScreenInfo().width
const width = getScreenInfo().width;
if (width < 480) {
return 'small'
return "small";
} else if (width < 768) {
return 'medium'
return "medium";
} else if (width < 1024) {
return 'large'
return "large";
} else {
return 'xlarge'
return "xlarge";
}
}
......@@ -68,25 +68,25 @@ export function getScreenSize(): ScreenSize {
* const fontSize = responsiveFontSize(14, 12, 20)
*/
export function responsiveFontSize(baseSize: number, minSize: number = 12, maxSize: number = 48): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width;
// 设计稿基准宽度(通常为 375px 或 750px)
// 如果设计稿是 750px,这里改为 750,baseSize 也需要相应调整
const designWidth = 375
const designWidth = 375;
// 计算缩放比例(限制在合理范围内)
const scale = screenWidth / designWidth
const scaledSize = baseSize * scale
const scale = screenWidth / designWidth;
const scaledSize = baseSize * scale;
// 限制在最小值和最大值之间
if (scaledSize < minSize) {
return minSize
return minSize;
} 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
* const padding = responsiveSpacing(16, 12, 24)
*/
export function responsiveSpacing(baseSpacing: number, minSpacing: number = 4, maxSpacing: number = 64): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
const designWidth = 375
const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width;
const designWidth = 375;
const scale = screenWidth / designWidth
const scaledSpacing = baseSpacing * scale
const scale = screenWidth / designWidth;
const scaledSpacing = baseSpacing * scale;
if (scaledSpacing < minSpacing) {
return minSpacing
return minSpacing;
} 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
* const buttonWidth = responsiveWidth(200)
*/
export function responsiveWidth(baseWidth: number): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
const designWidth = 375
const screenInfo = getScreenInfo();
const screenWidth = screenInfo.width;
const designWidth = 375;
return Math.round(baseWidth * (screenWidth / designWidth))
return Math.round(baseWidth * (screenWidth / designWidth));
}
/**
* 判断是否为横屏
*/
export function isLandscape(): boolean {
const screenInfo = getScreenInfo()
return screenInfo.width > screenInfo.height
const screenInfo = getScreenInfo();
return screenInfo.width > screenInfo.height;
}
/**
* 判断是否为平板尺寸
*/
export function isTablet(): boolean {
const screenSize = getScreenSize()
return screenSize === 'large' || screenSize === 'xlarge'
const screenSize = getScreenSize();
return screenSize === "large" || screenSize === "xlarge";
}
/**
* 判断是否为手机尺寸
*/
export function isMobile(): boolean {
const screenSize = getScreenSize()
return screenSize === 'small' || screenSize === 'medium'
const screenSize = getScreenSize();
return screenSize === "small" || screenSize === "medium";
}
/**
......@@ -175,5 +175,5 @@ export function isMobile(): boolean {
* const columns = getColumns(1, 2)
*/
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";
*/
class Storage {
/**
* 清空所有存储数据
*
* 警告:此操作会删除所有本地存储数据,请谨慎使用
*
* @example
* storage.clear(); // 清空所有数据
*/
clear() {
uni.clearStorageSync();
}
/**
* 获取存储数据
*
* @param key 存储键名
......@@ -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 存储键名
......@@ -90,7 +76,7 @@ class Storage {
*/
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) {
......@@ -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 {
}
/**
* 清空所有存储数据
*
* 警告:此操作会删除所有本地存储数据,请谨慎使用
*
* @example
* storage.clear(); // 清空所有数据
*/
clear() {
uni.clearStorageSync();
}
/**
* 获取数据后立即删除(一次性读取)
*
* 适用于临时数据、一次性令牌等场景
* 读取后数据会被自动删除,确保数据的一次性使用
* 设置存储数据
*
* @param key 存储键名
* @returns 存储的数据,如果不存在则返回 null
* @param value 要存储的数据,支持任意类型
* @param expires 过期时间(秒),默认为0表示永不过期
*
* @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 {
// 先获取数据
const value = this.get(key);
// 立即删除数据
this.remove(key);
// 返回获取到的数据
return value;
set(key: string, value: any, expires: number): void {
// 存储主要数据
uni.setStorageSync(key, value);
// 如果设置了过期时间,则存储过期时间戳
if (expires > 0) {
// 计算过期时间戳:当前时间 + 过期时间(秒转毫秒)
const expireTime = Date.now() + expires * 1000;
uni.setStorageSync(`${key}${EXPIRES_SUFFIX}`, expireTime);
}
}
}
......
// utils/theme-classes.uts
// 主题化类名工具函数 - 让主题系统像 Tailwind 一样使用类名
import { getThemeManager } from './theme-manager.uts'
import { getThemeManager } from "./theme-manager.uts";
/**
* Tailwind 风格类名工具函数
......@@ -15,17 +15,17 @@ import { getThemeManager } from './theme-manager.uts'
* // 返回: 'theme-mobile-medium p-4 rounded-lg'
*/
export function tw(...classes: string[]): string {
const themeManager = getThemeManager()
const themeName = themeManager.getCurrentThemeName()
const themePrefix = `theme-${themeName}`
return [themePrefix, ...classes].join(' ')
const themeManager = getThemeManager();
const themeName = themeManager.getCurrentThemeName();
const themePrefix = `theme-${themeName}`;
return [themePrefix, ...classes].join(" ");
}
/**
* 获取当前主题前缀
*/
export function getThemePrefix(): string {
const themeManager = getThemeManager()
const themeName = themeManager.getCurrentThemeName()
return `theme-${themeName}`
const themeManager = getThemeManager();
const themeName = themeManager.getCurrentThemeName();
return `theme-${themeName}`;
}
// utils/theme-variables.uts
// CSS 变量主题系统 - 动态设置 CSS 变量值
import { getThemeManager } from './theme-manager.uts'
import { getThemeManager } from "./theme-manager.uts";
/**
* CSS 变量名称映射
......@@ -10,85 +10,85 @@ import { getThemeManager } from './theme-manager.uts'
*/
const CSS_VARIABLES: Record<string, string> = {
// 间距 (Spacing)
'--p-page': 'base', // p-page 使用 base 间距
'--p-xs': 'xs',
'--p-sm': 'sm',
'--p-md': 'md',
'--p-base': 'base',
'--p-lg': 'lg',
'--p-xl': 'xl',
'--p-2xl': '2xl',
'--p-3xl': '3xl',
'--p-4xl': '4xl',
"--p-page": "base", // p-page 使用 base 间距
"--p-xs": "xs",
"--p-sm": "sm",
"--p-md": "md",
"--p-base": "base",
"--p-lg": "lg",
"--p-xl": "xl",
"--p-2xl": "2xl",
"--p-3xl": "3xl",
"--p-4xl": "4xl",
// 圆角 (Border Radius)
'--r-none': 'none',
'--r-sm': 'sm',
'--r-base': 'base',
'--r-md': 'md',
'--r-lg': 'lg',
'--r-xl': 'xl',
'--r-2xl': '2xl',
'--r-full': 'full',
"--r-none": "none",
"--r-sm": "sm",
"--r-base": "base",
"--r-md": "md",
"--r-lg": "lg",
"--r-xl": "xl",
"--r-2xl": "2xl",
"--r-full": "full",
// 字体大小 (Font Size)
'--t-xs': 'xs',
'--t-sm': 'sm',
'--t-base': 'base',
'--t-md': 'md',
'--t-lg': 'lg',
'--t-xl': 'xl',
'--t-2xl': '2xl',
'--t-3xl': '3xl',
'--t-4xl': '4xl',
"--t-xs": "xs",
"--t-sm": "sm",
"--t-base": "base",
"--t-md": "md",
"--t-lg": "lg",
"--t-xl": "xl",
"--t-2xl": "2xl",
"--t-3xl": "3xl",
"--t-4xl": "4xl",
// 尺寸 (Size)
'--s-xs': 'xs',
'--s-sm': 'sm',
'--s-md': 'md',
'--s-base': 'base',
'--s-lg': 'lg',
'--s-xl': 'xl'
}
"--s-xs": "xs",
"--s-sm": "sm",
"--s-md": "md",
"--s-base": "base",
"--s-lg": "lg",
"--s-xl": "xl"
};
/**
* 设置 CSS 变量到根元素
* 注意:uni-app x 中需要在根 view 上设置 style
*/
export function setThemeVariables(rootElement: any = null): void {
const themeManager = getThemeManager()
const theme = themeManager.getCurrentTheme()
const themeManager = getThemeManager();
const theme = themeManager.getCurrentTheme();
if (theme == null) {
console.warn('[theme-variables] Theme not loaded')
return
console.warn("[theme-variables] Theme not loaded");
return;
}
// 构建 CSS 变量对象
const cssVars: Record<string, string> = {}
const cssVars: Record<string, string> = {};
// 设置间距变量
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'
} else if (cssVar.startsWith('--r-')) {
cssVars[cssVar] = `${themeManager.getSpacing(varName) }px`;
} else if (cssVar.startsWith("--r-")) {
// 圆角变量
cssVars[cssVar] = themeManager.getBorderRadius(varName) + 'px'
} else if (cssVar.startsWith('--t-')) {
cssVars[cssVar] = `${themeManager.getBorderRadius(varName) }px`;
} else if (cssVar.startsWith("--t-")) {
// 字体大小变量
cssVars[cssVar] = themeManager.getFontSize(varName) + 'px'
} else if (cssVar.startsWith('--s-')) {
cssVars[cssVar] = `${themeManager.getFontSize(varName) }px`;
} else if (cssVar.startsWith("--s-")) {
// 尺寸变量
cssVars[cssVar] = themeManager.getSize(varName) + 'px'
cssVars[cssVar] = `${themeManager.getSize(varName) }px`;
}
})
});
// 在 uni-app x 中,需要通过 :style 绑定到根元素
// 这里返回样式对象,供组件使用
return cssVars
return cssVars;
}
/**
......@@ -96,7 +96,7 @@ export function setThemeVariables(rootElement: any = null): void {
* 用于绑定到根元素的 :style
*/
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 { cool } from "@cool-vue/vite-plugin";
import { proxy } from "./config/proxy";
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);
//为原代理路径添加带斜杠前缀的副本,兼容两种路径格式(如 /api/ 和 /api)
// 为原代理路径添加带斜杠前缀的副本,兼容两种路径格式(如 /api/ 和 /api)
for (const i in proxy) {
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!