Commit ae74ab29 by cen

feat: 登录

1 parent dfaf5daf
Showing 83 changed files with 2441 additions and 973 deletions
<script lang="uts"> <script lang="uts">
let firstBackTime = 0; let firstBackTime = 0;
export default { export default {
onLaunch () { onLaunch: function () {
console.log("App Launch"); console.log("App Launch");
}, },
onShow () { onShow: function () {
console.log("App Show"); console.log("App Show");
}, },
onHide () { onHide: function () {
console.log("App Hide"); console.log("App Hide");
}, },
// #ifdef APP-ANDROID // #ifdef APP-ANDROID
onLastPageBackPress () { onLastPageBackPress: function () {
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 () { onExit: function () {
console.log("App Exit"); console.log("App Exit");
} }
}; };
...@@ -43,10 +43,23 @@ export default { ...@@ -43,10 +43,23 @@ export default {
/* @tailwind components; */ /* @tailwind components; */
/* @tailwind utilities; */ /* @tailwind utilities; */
/* 全局默认样式 */
uni-page-body {
font-size: 14px;
height: 100%;
min-height: 100%;
}
/* #ifdef H5 */ /* #ifdef H5 */
svg { svg {
display: initial; display: initial;
} }
/* H5 端统一 flex 默认行为,与 App 端保持一致 */
uni-app uni-page-body, uni-app uni-left-window .uni-left-window, uni-app uni-right-window .uni-right-window, uni-app uni-top-window .uni-top-window, uni-app uni-view, uni-app uni-match-media, uni-app uni-label, uni-app uni-swiper, uni-app uni-swiper-item, uni-app uni-movable-area, uni-app uni-movable-view, uni-app uni-cover-view, uni-app uni-list-item, uni-app uni-navigator, uni-app uni-radio-group, uni-app uni-checkbox-group, uni-app uni-scroll-view, uni-app uni-list-view, uni-app uni-unicloud-db, uni-app uni-sticky-section, uni-app uni-sticky-header {
display: flex ;
flex-direction: row ;
}
/* #endif */ /* #endif */
.safe-area-top { .safe-area-top {
......
...@@ -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";
/**
* 简化版 qs.stringify(从 gl_tape/lib/qs.js 核心逻辑提取)
* 仅支持简单对象序列化,不处理复杂嵌套
*/
function encodeValue(val: any): string {
if (val == null) {
return '';
}
const str = `${val}`;
const encoded = encodeURIComponent(str);
return encoded != null ? encoded : '';
}
/**
* 将对象序列化为 query string
* @param obj 要序列化的对象
* @param encodeValuesOnly 是否只编码值(key 不编码)
* @returns 序列化后的字符串,如 "key1=val1&key2=val2"
*/
export function stringify(obj: UTSJSONObject, encodeValuesOnly: boolean = true): string {
const pairs: string[] = [];
for (const key in obj) {
const val = obj[key];
if (val == null) {
continue;
}
const keyStr = encodeValuesOnly ? key : encodeURIComponent(key);
const valStr = encodeValue(val);
pairs.push(`${keyStr}=${valStr}`);
}
return pairs.join('&');
}
...@@ -6,22 +6,22 @@ function encodeUTF8(s: string): number[] { ...@@ -6,22 +6,22 @@ function encodeUTF8(s: string): number[] {
const r: number[] = []; const r: number[] = [];
let i = 0; let i = 0;
while (i < s.length) { while (i < s.length) {
const c = s.charCodeAt(i); const c = s.charCodeAt(i) as number;
if (c < 0x80) { if (c < 0x80) {
r.push(c); r.push(c);
} else if (c < 0x8_00) { } else if (c < 0x800) {
r.push(0xC0 + ((c >> 6) & 0x1F), 0x80 + (c & 0x3F)); r.push(0xc0 + ((c >> 6) & 0x1f), 0x80 + (c & 0x3f));
} else { } else {
const x = c ^ 0xD8_00; const x = c ^ 0xd800;
if (x >> 10 == 0) { if (x >> 10 == 0) {
const next = s.charCodeAt(i + 1) ^ 0xDC_00; const next = (s.charCodeAt(i + 1) as number) ^ 0xdc00;
const code = (x << 10) + next + 0x1_00_00; const code = (x << 10) + next + 0x10000;
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) & 0xf));
} }
r.push(0x80 + ((c >> 6) & 0x3F), 0x80 + (c & 0x3F)); r.push(0x80 + ((c >> 6) & 0x3f), 0x80 + (c & 0x3f));
} }
i++; i++;
} }
...@@ -38,19 +38,27 @@ export function sha1(s: string): string { ...@@ -38,19 +38,27 @@ export function sha1(s: string): string {
const t = new DataView(sBuf); const t = new DataView(sBuf);
let i = 0; let i = 0;
while (i < l) { while (i < l) {
s32[i] = t.getUint32(i << 2); s32[i] = t.getUint32(i << 2, false);
i++; i++;
} }
s32[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8); s32[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
s32[l - 1] = data.length << 3; s32[l - 1] = data.length << 3;
const w: number[] = []; const w: number[] = [];
const k = [1_518_500_249, 1_859_775_393, -1_894_007_588, -899_497_514]; // 预先初始化 w 数组为 80 个元素,避免 UTS 下标越界
let m0 = 1_732_584_193; let wInit = 0;
let m1 = -271_733_879; while (wInit < 80) {
let m2 = ~1_732_584_193; w.push(0);
let m3 = ~(-271_733_879); wInit++;
let m4 = -1_009_589_776; }
const k = [1518500249, 1859775393, -1894007588, -899497514];
let m0 = 1732584193;
let m1 = -271733879;
let m2 = 0;
let m3 = 0;
let m4 = -1009589776;
m2 = ~m0;
m3 = ~m1;
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 { stringify as qsStringify } from "./qs.uts";
/** /**
* 参数签名方法(从 gl_tape/api/request/sign.js 迁移) * 参数签名方法(完全对齐 gl_tape/api/request/sign.js)
* - 删除原始参数中的 sign 字段 * - 先用 qs.stringify 序列化参数
* - split('&') 拆开后 decodeURIComponent 解码
* - 按 key 字典序排序 * - 按 key 字典序排序
* - 将 null 转为空字符串,对对象使用 JSON.stringify
* - 拼接为 key + value 字符串,首尾加密钥后做 SHA1,再转大写 * - 拼接为 key + value 字符串,首尾加密钥后做 SHA1,再转大写
* - 最后把 sign 挂到原始参数对象上(保留原始类型)
* *
* @param params 原始参数对象(会被浅拷贝,不直接修改入参) * @param params 原始参数对象(会被修改,添加 sign 字段)
* @param secret 签名密钥 * @param secret 签名密钥
* @param noSignAttr 不参与签名的字段列表 * @param noSignAttr 不参与签名的字段列表
*/ */
export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] = []): UTSJSONObject { export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] = []): UTSJSONObject {
// 使用 UTSJSONObject 做一份浅拷贝,避免直接修改原始对象
const realObj = {} as UTSJSONObject;
// 先将入参拷贝到 realObj 中,并清理 sign 字段 // 1. 用 qs.stringify 序列化(encodeValuesOnly: true)
const rawKeys = keys(params); const objStr = qsStringify(params, true);
for (const key of rawKeys) {
if (key == "sign") { // 2. split('&') 拆开
const objVal = objStr.split('&');
// 3. 解码并重建对象(用于签名计算)
const realObj: UTSJSONObject = {};
for (let i = 0; i < objVal.length; i++) {
const item = objVal[i];
const idx = item.indexOf('=');
if (idx < 0) {
continue; continue;
} }
const value = get(params, key); const key = item.substring(0, idx);
set(realObj, key, value); const val = decodeURIComponent(item.substring(idx + 1));
realObj[key] = val;
} }
// 再次获取 key 列表并排序,确保签名字段顺序稳定 // 4. 获取 key 列表并排序
const sortedKeys = keys(realObj); const sortedKeys: string[] = [];
sortedKeys.sort((a, b) => a.localeCompare(b)); for (const key in realObj) {
if (key == "sign") {
continue;
}
sortedKeys.push(key);
}
sortedKeys.sort();
// 归一化 value:null -> "",对象 -> JSON 字符串 // 5. 归一化 value:null -> "",对象 -> JSON 字符串
for (const key of sortedKeys) { for (let i = 0; i < sortedKeys.length; i++) {
let obj: any | null = get(realObj, key); const key = sortedKeys[i];
let obj: any | null = 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);
} }
set(realObj, key, obj); realObj[key] = obj;
} }
// 组装待签名字符串(排除 noSignAttr 指定的字段) // 6. 组装待签名字符串(排除 noSignAttr 指定的字段)
const segments: string[] = []; const segments: string[] = [];
for (const key of sortedKeys) { for (let i = 0; i < sortedKeys.length; i++) {
const key = sortedKeys[i];
if (noSignAttr.indexOf(key) >= 0) { if (noSignAttr.indexOf(key) >= 0) {
continue; continue;
} }
const val = get(realObj, key, "") as string; const val = realObj[key];
segments.push(key + val); segments.push(key + val);
} }
// 计算签名:secret + 拼接字符串 + secret // 7. 计算签名:secret + 拼接字符串 + secret
const signSrc = secret + segments.join("") + secret; const signSrc = secret + segments.join("") + secret;
const signVal = sha1(signSrc).toUpperCase(); const signVal = sha1(signSrc).toUpperCase();
set(realObj, "sign", signVal);
// 8. 把 sign 挂到 realObj 上,返回全字符串的对象(和老项目保持一致)
realObj["sign"] = signVal;
return realObj; return realObj;
} }
import { storage } from "../../utils/storage.uts";
import { evaluationDomain, pathEnum, signSecretKey } from "../env.uts"; import { evaluationDomain, pathEnum, signSecretKey } from "../env.uts";
import { storage } from "../../utils/storage.uts";
type GscPostConfig = { type GscPostConfig = {
duplicatePrevention?: boolean;
returnAll?: boolean; returnAll?: boolean;
timeout?: number; timeout?: number;
duplicatePrevention?: boolean;
}; };
/** /**
...@@ -35,29 +35,30 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig ...@@ -35,29 +35,30 @@ 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 (const key of dataKeys) { for (let i = 0; i < dataKeys.length; i++) {
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 null | string; const sessionId = storage.get("sessionId") as string | null;
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 ?? 300_000; const timeout = finalConfig.timeout ?? 300000;
// 将 appId / appSecret 通过 header 传递给后端(近似旧项目 glsk-toolkit 行为) // 将 appId / appSecret 通过 header 传递给后端(近似旧项目 glsk-toolkit 行为)
const header = { const header = {
...@@ -113,7 +114,7 @@ export function gscPost(url: string, data: UTSJSONObject, config: GscPostConfig ...@@ -113,7 +114,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 null | string; const errMsg = (error as any).errMsg as string | null;
if (errMsg == "request:fail") { if (errMsg == "request:fail") {
title = "网络异常"; title = "网络异常";
} else if (errMsg != null && errMsg != "") { } else if (errMsg != null && errMsg != "") {
......
// 登录相关接口封装,对齐 gl_tape 中的 ROP 网关调用(http.fetch) // 登录相关接口封装,直接使用项目现成的 http.uts(已包含签名逻辑)
import { djDomain, djSecretKey, pathEnum } from "@/api/env.uts"; import http from '@/api/request/http.uts'
import { storage } from "@/utils/storage.uts";
const BOUTIQUE_PATH = pathEnum.boutique as string; // 获取短信验证码:dj.api.smartcarlife.sms.get.code
export async function apiGetSmsCode(params: UTSJSONObject): Promise<UTSJSONObject> {
// 简化版 SHA1,实现同 lib/sha1.js,用于生成 sign const data: UTSJSONObject = {
function encodeUTF8(input: string): number[] { projectName: 'boutique',
const result: number[] = []; ...params
let i = 0;
while (i < input.length) {
const cNum = input.charCodeAt(i) as number;
if (cNum < 0x80) {
result.push(cNum);
} else if (cNum < 0x8_00) {
result.push(0xC0 + ((cNum >> 6) & 0x1F), 0x80 + (cNum & 0x3F));
} else {
const x = cNum ^ 0xD8_00;
if (x >> 10 == 0) {
i++;
const c2 = input.charCodeAt(i) as number;
const uni = (x << 10) + (c2 ^ 0xDC_00) + 0x1_00_00;
result.push(
0xF0 + ((uni >> 18) & 0x7),
0x80 + ((uni >> 12) & 0x3F),
0x80 + ((uni >> 6) & 0x3F),
0x80 + (uni & 0x3F)
);
} else {
result.push(
0xE0 + ((cNum >> 12) & 0x0F),
0x80 + ((cNum >> 6) & 0x3F),
0x80 + (cNum & 0x3F)
);
}
}
i++;
}
return result;
}
function sha1Hex(input: string): string {
const dataArr = encodeUTF8(input);
const data = new Uint8Array(dataArr);
const l = (((data.length + 8) >>> 6) << 4) + 16;
const buffer = new Uint8Array(l << 2);
const dataBuf: ArrayBuffer = data.buffer as ArrayBuffer;
buffer.set(new Uint8Array(dataBuf));
const buf: ArrayBuffer = buffer.buffer as ArrayBuffer;
const s = new Uint32Array(buf);
const sBuf: ArrayBuffer = s.buffer as ArrayBuffer;
const dv = new DataView(sBuf);
let i = 0;
while (i < l) {
s[i] = dv.getUint32(i << 2);
i++;
}
const idx = data.length >> 2;
s[idx] = s[idx] | (0x80 << (24 - ((data.length & 3) * 8)));
s[l - 1] = data.length << 3;
const w: number[] = [];
const f = [
(m: number[]): number => (m[1] & m[2]) | (~m[1] & m[3]),
(m: number[]): number => m[1] ^ m[2] ^ m[3],
(m: number[]): number => (m[1] & m[2]) | (m[1] & m[3]) | (m[2] & m[3]),
(m: number[]): number => m[1] ^ m[2] ^ m[3]
];
const k = [1_518_500_249, 1_859_775_393, -1_894_007_588, -899_497_514];
const rol = (n: number, c: number): number => (n << c) | (n >>> (32 - c));
const m: number[] = [1_732_584_193, -271_733_879, 0, 0, -1_009_589_776];
m[2] = ~m[0];
m[3] = ~m[1];
let j = 0;
for (i = 0; i < s.length; i += 16) {
const o = [m[0], m[1], m[2], m[3], m[4]];
for (j = 0; j < 80; j++) {
if (j < 16) {
w[j] = s[i + j];
} else {
w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
}
const t = (rol(m[0], 5) + f[(j / 20) | 0](m) + m[4] + w[j] + k[(j / 20) | 0]) | 0;
m[4] = m[3];
m[3] = m[2];
m[2] = rol(m[1], 30);
m[1] = m[0];
m[0] = t;
}
for (j = 0; j < 5; j++) {
m[j] = (m[j] + o[j]) | 0;
}
}
const mArr = new Uint32Array(m);
const mBuf: ArrayBuffer = mArr.buffer as ArrayBuffer;
const out = new Uint8Array(mBuf);
let hex = "";
for (i = 0; i < out.length; i++) {
const v = out[i];
hex += (v < 16 ? "0" : "") + v.toString(16);
} }
return hex; return await http.fetch('dj.api.smartcarlife.sms.get.code', data, true, 'dj')
} }
// 按老项目 http.getData + sign.js 逻辑生成最终请求参数 // 手机验证码登录:dj.api.smartcarlife.sms.applogin
function buildSignedParams(method: string, payload: UTSJSONObject): UTSJSONObject { export async function apiSmsLogin(params: UTSJSONObject): Promise<UTSJSONObject> {
const params: UTSJSONObject = {}; const data: UTSJSONObject = {
projectName: 'boutique',
// 复制调用参数 source: 'MINIAPP',
for (const key in payload) { productCode: 'PC00c2',
params[key] = payload[key]; ...params
}
// 基础字段
params.method = method;
params.v = "1.0.0";
params.format = "json";
params.locale = "zh_CN";
params.source = "app";
// appKey / secret
const appKey = djSecretKey.appKey as string;
const secret = djSecretKey.secret as string;
params.appKey = appKey;
// sessionId(如果存在)
const sessionId = storage.get("sessionId") as null | string;
if (sessionId != null && sessionId != "") {
params.sessionId = sessionId;
}
// sign 计算:按照 key 排序、拼接 key+value
const realObj: UTSJSONObject = {};
for (const k in params) {
const v = params[k];
if (v == null) {
realObj[k] = "";
} else if (typeof v === "object") {
realObj[k] = JSON.stringify(v);
} else {
realObj[k] = v;
}
}
const keys: string[] = [];
for (const k in realObj) {
keys.push(k);
}
keys.sort();
const parts: string[] = [];
for (const k of keys) {
const vAny = realObj[k];
const vStr = `${vAny}`;
parts.push(k + vStr);
} }
return await http.fetch('dj.api.smartcarlife.sms.applogin', data, true, 'dj')
const signStr = secret + parts.join("") + secret;
// 目前关闭本地 SHA1 计算,直接透传待签名串,方便后端放宽或调试
console.log("rop signStr (sha disabled)", signStr);
params.sign = signStr;
return params;
} }
// 统一 ROP 请求封装:/router?method=xxx
async function postRop(method: string, payload: UTSJSONObject): Promise<UTSJSONObject> {
const url = `${djDomain}${BOUTIQUE_PATH}router?method=${method}`;
const data = buildSignedParams(method, payload);
console.log("rop request", url, data);
return await new Promise((resolve, reject) => { // 免登:dj.api.smartcarlife.sms.noSignIn.login
uni.request({ export async function apiAutoLogin(params: UTSJSONObject): Promise<UTSJSONObject> {
url, const data: UTSJSONObject = {
data, projectName: 'boutique',
method: "POST", ...params
header: {
"content-type": "application/x-www-form-urlencoded"
},
dataType: "json",
success: (res) => {
console.log("rop response", res.data);
resolve(res.data as UTSJSONObject);
},
fail: (err) => {
console.log("rop error", err);
reject(err);
} }
}); return await http.fetch('dj.api.smartcarlife.sms.noSignIn.login', data, true, 'dj')
});
} }
// 获取短信验证码:dj.api.smartcarlife.sms.get.code // 获取账号列表:dj.api.smartcarlife.workWechat.listSelectAccount
export async function apiGetSmsCode(params: UTSJSONObject): Promise<UTSJSONObject> { export async function apiGetListSelectAccount(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
projectName: 'boutique',
...params ...params
}; }
return await postRop("dj.api.smartcarlife.sms.get.code", data); return await http.fetch('dj.api.smartcarlife.workWechat.listSelectAccount', data, true, 'dj')
} }
// 手机验证码登录:dj.api.smartcarlife.sms.applogin // 选择账号登录:dj.api.smartcarlife.workWechat.selectAccountLogin
export async function apiSmsLogin(params: UTSJSONObject): Promise<UTSJSONObject> { export async function apiSelectAccountLogin(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
projectName: 'boutique',
method: 'dj.api.smartcarlife.workWechat.selectAccountLogin',
...params ...params
}; }
// 与旧项目保持一致的固定参数 return await http.post(data, true, 'dj', null)
data.source = "MINIAPP";
data.productCode = "PC00c2";
return await postRop("dj.api.smartcarlife.sms.applogin", data);
} }
// 免登:dj.api.smartcarlife.sms.noSignIn.login // 获取园区店下的4S店:dj.api.scenemerchantref.query4SRefByYqShopByLogin
export async function apiAutoLogin(params: UTSJSONObject): Promise<UTSJSONObject> { export async function apiGetSceneMerchantRefStoreList(params: UTSJSONObject): Promise<any[] | null> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
projectName: 'boutique',
method: 'dj.api.scenemerchantref.query4SRefByYqShopByLogin',
...params ...params
}; }
return await postRop("dj.api.smartcarlife.sms.noSignIn.login", data); return await http.post(data, true, 'dj', null)
} }
<template> <template>
<view v-if="isShow" <view v-if="isShow" class="publish-popup-mask" @click="closePopup">
class="publish-popup-mask"
@click="closePopup">
<view class="publish-popup-container" @click.stop> <view class="publish-popup-container" @click.stop>
<slot name="content"></slot> <slot name="content"></slot>
</view> </view>
...@@ -9,13 +7,13 @@ ...@@ -9,13 +7,13 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ref } from "vue"; import { ref } from 'vue';
// Props // Props
const props = defineProps<{ const props = defineProps<{
type?: string;
isShowFooter?: boolean; isShowFooter?: boolean;
showTitle?: boolean; showTitle?: boolean;
type?: string;
}>(); }>();
// 响应式数据 // 响应式数据
......
<template> <template>
<view class="type-tab"> <view class="type-tab">
<scroll-view class="type-box" <scroll-view class="type-box" scroll-x="true" :show-scrollbar="false" scroll-with-animation>
scroll-with-animation
scroll-x="true"
:show-scrollbar="false">
<view class="type-scroll-content"> <view class="type-scroll-content">
<view v-for="(i, index) in typeList" <view
:key="index"
class="tab-item" class="tab-item"
:class="[tabClass(index)]" :class="[tabClass(index)]"
@click.stop="tabClick(index, i)"> 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' : '']"> <view class="text flex justify-center align-center" :class="[tabIndex == index ? 'active' : '']">
<text class="tab-name">{{ getTabName(i) }}</text> <text class="tab-name">{{ getTabName(i) }}</text>
<text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text> <text v-if="isShowCount" class="count ml-8">{{ (getTabCount(i) > 99) ? '99+' : getTabCount(i).toString() }}</text>
...@@ -21,23 +20,23 @@ ...@@ -21,23 +20,23 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { ref, computed } from 'vue';
import { get } from "@/utils/common.uts"; import { get } from '@/utils/common.uts';
// Props 类型:使用 any[] 避免响应式对象类型转换问题 // Props 类型:使用 any[] 避免响应式对象类型转换问题
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
isShowCount?: boolean;
nameKey?: string;
tabIndex: number;
typeList: any[]; typeList: any[];
tabIndex: number;
nameKey?: string;
isShowCount?: boolean;
}>(), { }>(), {
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;
}>(); }>();
...@@ -45,7 +44,7 @@ const emit = defineEmits<{ ...@@ -45,7 +44,7 @@ const emit = defineEmits<{
// 响应式对象在 app 端无法通过 get() 访问,使用 JSON 序列化/反序列化解包 // 响应式对象在 app 端无法通过 get() 访问,使用 JSON 序列化/反序列化解包
const getTabName = (item: any): string => { const getTabName = (item: any): string => {
// 先尝试 get() // 先尝试 get()
const name = get(item, props.nameKey); let name = get(item, props.nameKey);
if (name != null) { if (name != null) {
return name as string; return name as string;
} }
...@@ -59,21 +58,21 @@ const getTabName = (item: any): string => { ...@@ -59,21 +58,21 @@ const getTabName = (item: any): string => {
if (name1 != null) { if (name1 != null) {
return name1 as string; return name1 as string;
} }
const name2 = get(parsed, "tabName"); const name2 = get(parsed, 'tabName');
if (name2 != null) { if (name2 != null) {
return name2 as string; return name2 as string;
} }
} }
} catch { } catch (e: any) {
// 静默失败 // 静默失败
} }
return "未知"; return '未知';
}; };
const getTabCount = (item: any): number => { const getTabCount = (item: any): number => {
// 先尝试 get() // 先尝试 get()
const count = get(item, "count"); let count = get(item, 'count');
if (count != null) { if (count != null) {
return count as number; return count as number;
} }
...@@ -83,12 +82,12 @@ const getTabCount = (item: any): number => { ...@@ -83,12 +82,12 @@ const getTabCount = (item: any): number => {
const jsonStr = JSON.stringify(item); const jsonStr = JSON.stringify(item);
const parsed = JSON.parse(jsonStr) as any; const parsed = JSON.parse(jsonStr) as any;
if (parsed != null) { if (parsed != null) {
const countValue = get(parsed, "count"); const countValue = get(parsed, 'count');
if (countValue != null) { if (countValue != null) {
return countValue as number; return countValue as number;
} }
} }
} catch { } catch (e: any) {
// 静默失败 // 静默失败
} }
...@@ -97,17 +96,17 @@ const getTabCount = (item: any): number => { ...@@ -97,17 +96,17 @@ const getTabCount = (item: any): number => {
// 方法 // 方法
const tabClass = (index: number): string => { const tabClass = (index: number): string => {
let className = ""; let className = '';
if (props.tabIndex == index) { if (props.tabIndex == index) {
className = "active "; className = 'active ';
if (index == 0) className += "first-nav"; if (index == 0) className += 'first-nav';
else className += "second-nav"; else className += 'second-nav';
} }
return className; return className;
}; };
const tabClick = (index: number, item: any) => { const tabClick = (index: number, item: any) => {
emit("tabClick", index, item); emit('tabClick', index, item);
}; };
</script> </script>
......
// composables/useTheme.uts // composables/useTheme.uts
// 主题 Composable - 提供响应式主题变量和切换接口 // 主题 Composable - 提供响应式主题变量和切换接口
import { computed, onMounted, ref } from "vue"; import { ref, computed, onMounted } from 'vue'
import { getThemeManager, ThemeName, ThemeVariables } from '@/utils/theme-manager.uts'
import { getThemeManager, ThemeName, ThemeVariables } from "@/utils/theme-manager.uts"; import { getScreenSize } from '@/utils/screen-adapt.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<null | ThemeVariables>(themeManager.getCurrentTheme()); const theme = ref<ThemeVariables | null>(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 { computed, onMounted, ref } from "vue"; import { ref, computed, onMounted } from 'vue'
import { getThemeVariablesStyle } from '@/utils/theme-variables.uts'
import { getThemeVariablesStyle } from "@/utils/theme-variables.uts"; import { useTheme } from './useTheme.uts'
import { useTheme } from "./useTheme.uts";
/** /**
* CSS 变量主题 Composable * CSS 变量主题 Composable
* 提供响应式的 CSS 变量样式对象 * 提供响应式的 CSS 变量样式对象
*/ */
export function useThemeVariables() { export function useThemeVariables() {
const { currentThemeName, autoSelectTheme } = useTheme(); const { currentThemeName, autoSelectTheme } = useTheme()
const themeVars = ref<Record<string, string>>({}); const themeVars = ref<Record<string, string>>({})
/** /**
* 更新 CSS 变量 * 更新 CSS 变量
*/ */
function updateThemeVariables(): void { function updateThemeVariables(): void {
themeVars.value = getThemeVariablesStyle(); themeVars.value = getThemeVariablesStyle()
} }
// 初始化时设置 CSS 变量 // 初始化时设置 CSS 变量
onMounted(() => { onMounted(() => {
updateThemeVariables(); updateThemeVariables()
}); })
// 监听主题变化,自动更新 CSS 变量 // 监听主题变化,自动更新 CSS 变量
const themeVarsComputed = computed(() => { const themeVarsComputed = computed(() => {
// 当主题名称变化时,重新计算 CSS 变量 // 当主题名称变化时,重新计算 CSS 变量
return getThemeVariablesStyle(); return getThemeVariablesStyle()
}); })
return { return {
// CSS 变量样式对象(用于 :style 绑定) // CSS 变量样式对象(用于 :style 绑定)
themeVars: themeVarsComputed, themeVars: themeVarsComputed,
// 手动更新 CSS 变量 // 手动更新 CSS 变量
updateThemeVariables updateThemeVariables
}; }
} }
// / <reference types="vite/client" /> /// <reference types="vite/client" />
declare module "*.uvue" {
import { DefineComponent } from "vue";
declare module '*.uvue' {
import { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<{}, {}, any>;
export default component; export default component;
} }
declare module "*.vue" { declare module '*.vue' {
import { DefineComponent } from "vue"; import { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>; const component: DefineComponent<{}, {}, any>;
export default component; export default component;
} }
......
import { createSSRApp } from "vue"; import { createSSRApp } from "vue";
import App from "./App.uvue";
import { appMixin } from "./utilsApi"; import { appMixin } from "./utilsApi";
import App from "./App.uvue";
export function createApp() { export function createApp() {
const app = createSSRApp(App); const app = createSSRApp(App);
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
"appid": "__UNI__B602BFA", "appid": "__UNI__B602BFA",
"description": "", "description": "",
"versionName": "1.0.0", "versionName": "1.0.0",
"versionCode": "108", "versionCode": "109",
"uni-app-x": { "uni-app-x": {
"flex-direction": "row" "flex-direction": "row"
}, },
......
{ {
"name": "uniapp-x-tape", "name": "uniappx-cli",
"version": "1.0.1", "version": "1.0.1",
"scripts": { "scripts": {
"postinstall": "weapp-tw patch" "postinstall": "weapp-tw patch"
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
"adm-zip": "^0.5.16", "adm-zip": "^0.5.16",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",
"postcss": "^8.5.6", "postcss": "^8.5.6",
"prettier": "^3.5.3",
"tailwindcss": "3", "tailwindcss": "3",
"tailwindcss-rem2px-preset": "^1.0.3", "tailwindcss-rem2px-preset": "^1.0.3",
"vite": "^6.3.5", "vite": "^6.3.5",
......
...@@ -4,7 +4,13 @@ ...@@ -4,7 +4,13 @@
{ {
"path": "pages/common/login/index", "path": "pages/common/login/index",
"style": { "style": {
"navigationBarTitleText": "登录" "navigationStyle": "custom"
}
},
{
"path": "pages/common/accountItems/index",
"style": {
"navigationStyle": "custom"
} }
}, },
{ {
...@@ -62,6 +68,14 @@ ...@@ -62,6 +68,14 @@
} }
} }
], ],
"easycom": {
"autoscan": true,
"custom": {
"^uni-(.*)": "@/uni_modules/uni-$1/components/uni-$1/uni-$1.uvue",
"^account-list$": "@/pages/common/components/AccountList.uvue",
"^no-data$": "@/pages/common/components/NoData.uvue"
}
},
"globalStyle": { "globalStyle": {
"navigationBarTextStyle": "black", "navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app x", "navigationBarTitleText": "uni-app x",
......
<template>
<view class="page-container">
<view class="bg">
<image class="bg-image" src="/static/images/login/account-bg.webp" mode="aspectFill"></image>
</view>
<view class="layout">
<view class="nav-bar">
<view class="back" @click="back">
<uni-icons type="left" :size="20" color="#000"></uni-icons>
</view>
</view>
<view class="step-box">
<view
v-for="(item, index) in stepList"
:key="index"
:class="['step-item', stepIndex >= index ? 'active-item' : '']"
@click="setStep(index)"
>
<view class="num">
<view class="text">
<text class="num-text">{{ index + 1 }}</text>
</view>
</view>
<text>{{ item }}</text>
</view>
</view>
<view class="content-box">
<view v-if="stepIndex != 2" class="search-box">
<view class="search-input">
<view v-if="!edit" :class="['input', searchValue != '' ? '' : 'placeholder']" @click="open">
<text v-if="searchValue != ''">{{ searchValue }}</text>
<text v-else>
请输入门店名称/商户号搜索
<view class="sprite-icon icon-search"></view>
</text>
</view>
<input
v-else
type="text"
class="input"
v-model="searchValue"
:focus="inputFocus"
confirm-type="search"
@blur="search"
@confirm="search"
/>
</view>
<view v-if="searchValue != ''" class="clear" @click="clear">
<uni-icons type="closeempty" :size="16" color="#1A1A1A"></uni-icons>
</view>
</view>
<!-- #ifdef APP -->
<scroll-view class="list" scroll-y :show-scrollbar="true">
<!-- #endif -->
<!-- #ifndef APP -->
<view class="list">
<!-- #endif -->
<account-list
v-show="stepIndex == 0"
ref="accountRef"
@chooseAccount="chooseAccount"
/>
<view v-show="stepIndex == 1">商户列表占位</view>
<view v-show="stepIndex == 2">场景选择占位</view>
<!-- #ifdef APP -->
</scroll-view>
<!-- #endif -->
<!-- #ifndef APP -->
</view>
<!-- #endif -->
</view>
</view>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
const stepList = ref<string[]>(['选择账号', '选择4S店', '选择场景'])
const stepIndex = ref<number>(0)
const searchValue = ref<string>('')
const edit = ref<boolean>(false)
const inputFocus = ref<boolean>(false)
let accountRef: any | null = null
onLoad((options: UTSJSONObject | null) => {
const stepIndexOpt = options != null ? (options['stepIndex'] as string | null) : null
if (stepIndexOpt == '1') {
stepIndex.value = 1
setTimeout(() => {
if (accountRef != null) {
const refObj = accountRef as UTSJSONObject
const method = refObj['getListSelectAccount']
if (method != null) {
(method as (autoLogin: boolean) => void)(true)
}
}
}, 100)
}
})
const search = (): void => {
edit.value = false
inputFocus.value = false
const step = stepIndex.value
if (step == 0 && accountRef != null) {
const refObj = accountRef as UTSJSONObject
const method = refObj['searchEvent']
if (method != null) {
(method as (searchValue: string) => void)(searchValue.value)
}
}
// TODO: 其他步骤的搜索
}
const open = (): void => {
edit.value = true
inputFocus.value = true
}
const back = (): void => {
uni.navigateBack()
}
const setStep = (index: number): void => {
if (index == 2) return
if (stepIndex.value > index) {
stepIndex.value = index
}
}
const clear = (): void => {
searchValue.value = ''
search()
}
const chooseAccount = (userInfo: any): void => {
console.log('chooseAccount:', userInfo)
stepIndex.value = 1
searchValue.value = ''
// TODO: 等待 MerchantList 组件迁移完成后,调用 merchantRef.init(userInfo)
}
const chooseMerchant = (userInfo: any): void => {
console.log('chooseMerchant:', userInfo)
stepIndex.value = 2
searchValue.value = ''
// TODO: 等待 Scene 组件迁移完成后,调用 sceneRef.init(userInfo)
}
</script>
<style scoped lang="scss">
.page-container {
width: 100%;
height: 100%;
position: relative;
.bg {
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
.bg-image {
width: 100%;
height: 100%;
display: block;
}
}
.layout {
width: 100%;
height: 100%;
padding-top: 72px;
font-size: 14px;
color: #333;
letter-spacing: 0;
box-sizing: border-box;
flex-direction: column;
align-items: center;
position: relative;
.nav-bar {
position: absolute;
width: 100%;
height: 48px;
left: 0;
top: 24px;
.back {
width: 48px;
height: 48px;
display: flex;
align-items: center;
justify-content: center;
}
}
.step-box {
position: relative;
display: flex;
align-items: center;
justify-content: center;
.step-item {
display: flex;
align-items: center;
font-weight: 500;
font-size: 36px;
color: #999999;
margin-right: 81.5px;
&:last-child {
margin-right: 0;
}
.num {
width: 28px;
height: 28px;
position: relative;
padding: 2px;
box-sizing: border-box;
margin-right: 5px;
&::after {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
border: 1px solid #b1b1b1;
content: '';
border-radius: 14px;
}
.text {
width: 100%;
height: 100%;
background: #b1b1b1;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.num-text {
font-weight: 700;
font-size: 16px;
color: #ffffff;
}
}
}
.active-item {
color: #4673ff;
.num {
&::after {
border-color: #4673ff;
}
.text {
background: #4673ff;
}
}
}
}
.content-box {
width: 81.84%;
flex: 1;
position: relative;
margin-top: 24px;
box-sizing: border-box;
padding-top: 24px;
box-shadow: inset 0 0 8px 0 #ffffff;
border-radius: 24px;
background: #ffffff59;
flex-direction: column;
&::after {
position: absolute;
content: '';
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #ffffff59;
box-shadow: inset 0 0 8px 0 #ffffff;
border-radius: 24px;
filter: blur(4px);
}
}
.search-box {
margin: 0 12px 24px;
position: relative;
.search-input {
width: 100%;
height: 40px;
background: #ffffff;
border: 1.5px solid #a8c1ff;
border-radius: 1px;
box-sizing: border-box;
color: #333;
padding: 0 6px;
font-size: 11px;
position: relative;
.input {
display: flex;
align-items: center;
height: 100%;
width: 100%;
justify-content: center;
text-align: center;
font-size: 11px;
}
.icon-search {
margin-left: 1px;
}
.placeholder {
font-size: 11px;
color: #999999;
}
}
.clear {
position: absolute;
top: 50%;
right: 0;
transform: translateY(-50%);
padding: 0 1px;
height: 100%;
display: flex;
align-items: center;
}
}
.list {
position: relative;
height: calc(100% - 88px);
flex-direction: column;
}
}
}
</style>
<template>
<view class="list-not">
<image src="/static/images/login/nothing.webp" class="list-not-img" />
<text>暂无内容</text>
</view>
</template>
<script setup lang="uts">
</script>
<style scoped lang="scss">
.list-not {
font-size: 11px;
color: #999999;
margin: auto;
text-align: center;
flex-direction: column;
&-img {
width: 338px;
height: 281px;
margin: 191px auto 6px;
display: block;
}
}
</style>
<template> <template>
<view style="flex: 1"> <view
<view id="chart-container-1" class="chart-container">
style="flex: 1"
>
<view class="chart-container" id="chart-container-1">
<!-- #ifdef APP --> <!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 --> <!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart ref="chartRef" <l-echart
:before-delay="0" ref="chartRef"
@finished="initChart"
class="chart" class="chart"
:enable-hover="false" :enable-hover="false"
:is-clickable="false" :is-clickable="false"
@finished="initChart"> :before-delay="0">
</l-echart> </l-echart>
<!-- #endif --> <!-- #endif -->
<!-- #ifndef APP --> <!-- #ifndef APP -->
<l-echart ref="chartRef" <l-echart ref="chartRef" @finished="initChart" class="chart"></l-echart>
class="chart"
@finished="initChart">
</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"
style="margin-top: 16px">
<!-- #ifdef APP --> <!-- #ifdef APP -->
<!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 --> <!-- APP 端:禁用悬停效果和点击交互,减少 web-view 通信开销 -->
<l-echart ref="lineChartRef" <l-echart
:before-delay="0" ref="lineChartRef"
@finished="initLineChart"
class="chart" class="chart"
:enable-hover="false" :enable-hover="false"
:is-clickable="false" :is-clickable="false"
@finished="initLineChart"> :before-delay="0">
</l-echart> </l-echart>
<!-- #endif --> <!-- #endif -->
<!-- #ifndef APP --> <!-- #ifndef APP -->
<l-echart ref="lineChartRef" <l-echart ref="lineChartRef" @finished="initLineChart" class="chart"></l-echart>
class="chart"
@finished="initLineChart">
</l-echart>
<!-- #endif --> <!-- #endif -->
</view> </view>
</view> </view>
......
<template> <template>
<!-- 和首页同样的写法:scroll-view 自己 flex:1,并且本身是纵向 flex 容器 --> <!-- 和首页同样的写法:scroll-view 自己 flex:1,并且本身是纵向 flex 容器 -->
<scroll-view class="flex flex-col bg-gray-50" <scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50">
scroll-y="true"
style="flex: 1">
<!-- 内层不再额外设 flex 布局,避免干扰 scroll-view 高度计算 --> <!-- 内层不再额外设 flex 布局,避免干扰 scroll-view 高度计算 -->
<!-- 顶部标题区域(渐变改为纯色,兼容 App) --> <!-- 顶部标题区域(渐变改为纯色,兼容 App) -->
<view class="bg-blue-500 px-6 py-8 flex-col"> <view class="bg-blue-500 px-6 py-8 flex-col">
...@@ -20,12 +18,8 @@ ...@@ -20,12 +18,8 @@
<text class="text-sm text-gray-600 block">新代码:getAppVersion()</text> <text class="text-sm text-gray-600 block">新代码:getAppVersion()</text>
</view> </view>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleGetVersion"> <button class="btn btn-primary mr-2 mb-2" @click="handleGetVersion">获取版本号</button>
获取版本号 <button class="btn btn-primary mr-2 mb-2" @click="handleOpenURL">打开URL</button>
</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleOpenURL">
打开URL
</button>
</view> </view>
<view v-if="runtimeResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="runtimeResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ runtimeResult }}</text> <text class="text-sm text-gray-800">{{ runtimeResult }}</text>
...@@ -40,15 +34,9 @@ ...@@ -40,15 +34,9 @@
<text class="text-sm text-gray-600 block">新代码:lockOrientation() + manifest.json配置</text> <text class="text-sm text-gray-600 block">新代码:lockOrientation() + manifest.json配置</text>
</view> </view>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-success mr-2 mb-2" @click="handleLockPortrait"> <button class="btn btn-success mr-2 mb-2" @click="handleLockPortrait">锁定竖屏</button>
锁定竖屏 <button class="btn btn-success mr-2 mb-2" @click="handleLockLandscape">锁定横屏</button>
</button> <button class="btn btn-success mr-2 mb-2" @click="handleKeepScreenOn">保持常亮</button>
<button class="btn btn-success mr-2 mb-2" @click="handleLockLandscape">
锁定横屏
</button>
<button class="btn btn-success mr-2 mb-2" @click="handleKeepScreenOn">
保持常亮
</button>
</view> </view>
<view v-if="screenResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="screenResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ screenResult }}</text> <text class="text-sm text-gray-800">{{ screenResult }}</text>
...@@ -63,15 +51,9 @@ ...@@ -63,15 +51,9 @@
<text class="text-sm text-gray-600 block">新代码:uni.getFileSystemManager()</text> <text class="text-sm text-gray-600 block">新代码:uni.getFileSystemManager()</text>
</view> </view>
<view class="flex flex-wrap"> <view class="flex flex-wrap">
<button class="btn btn-primary mr-2 mb-2" @click="handleGetFilePath"> <button class="btn btn-primary mr-2 mb-2" @click="handleGetFilePath">获取文件路径</button>
获取文件路径 <button class="btn btn-primary mr-2 mb-2" @click="handleWriteFile">写入文件</button>
</button> <button class="btn btn-primary mr-2 mb-2" @click="handleReadFile">读取文件</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleWriteFile">
写入文件
</button>
<button class="btn btn-primary mr-2 mb-2" @click="handleReadFile">
读取文件
</button>
</view> </view>
<view v-if="ioResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="ioResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800 break-words">{{ ioResult }}</text> <text class="text-sm text-gray-800 break-words">{{ ioResult }}</text>
...@@ -86,9 +68,7 @@ ...@@ -86,9 +68,7 @@
<text class="text-sm text-gray-600 block">新代码:isIOS() / isAndroid()</text> <text class="text-sm text-gray-600 block">新代码:isIOS() / isAndroid()</text>
</view> </view>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-warning mr-2 mb-2" @click="handleCheckOS"> <button class="btn btn-warning mr-2 mb-2" @click="handleCheckOS">检测系统</button>
检测系统
</button>
</view> </view>
<view v-if="osResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="osResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ osResult }}</text> <text class="text-sm text-gray-800">{{ osResult }}</text>
...@@ -103,9 +83,7 @@ ...@@ -103,9 +83,7 @@
<text class="text-sm text-gray-600 block">新代码:getStatusbarHeight()</text> <text class="text-sm text-gray-600 block">新代码:getStatusbarHeight()</text>
</view> </view>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-secondary mr-2 mb-2" @click="handleGetStatusbarHeight"> <button class="btn btn-secondary mr-2 mb-2" @click="handleGetStatusbarHeight">获取状态栏高度</button>
获取状态栏高度
</button>
</view> </view>
<view v-if="navigatorResult" class="mt-3 p-3 bg-gray-100 rounded"> <view v-if="navigatorResult" class="mt-3 p-3 bg-gray-100 rounded">
<text class="text-sm text-gray-800">{{ navigatorResult }}</text> <text class="text-sm text-gray-800">{{ navigatorResult }}</text>
...@@ -142,45 +120,45 @@ ...@@ -142,45 +120,45 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { getFilePath, readFile, writeFile } from "@/utils/plus-io"; import { getAppVersion, openURL, getAppInfo } from "@/utils/plus-runtime"
import { getStatusbarHeight } from "@/utils/plus-navigator"; import { lockOrientation, unlockOrientation, setKeepScreenOn } from "@/utils/plus-screen"
import { getOSName, isAndroid, isIOS } from "@/utils/plus-os"; import { getFilePath, writeFile, readFile } from "@/utils/plus-io"
import { getAppInfo, getAppVersion, openURL } from "@/utils/plus-runtime"; import { isIOS, isAndroid, getOSName } from "@/utils/plus-os"
import { lockOrientation, setKeepScreenOn } from "@/utils/plus-screen"; import { getStatusbarHeight } from "@/utils/plus-navigator"
const runtimeResult = ref<string>(""); const runtimeResult = ref<string>("")
const screenResult = ref<string>(""); const screenResult = ref<string>("")
const ioResult = ref<string>(""); const ioResult = ref<string>("")
const osResult = ref<string>(""); const osResult = ref<string>("")
const navigatorResult = ref<string>(""); const navigatorResult = ref<string>("")
// plus.runtime 示例 // plus.runtime 示例
const handleGetVersion = () => { const handleGetVersion = () => {
const version = getAppVersion(); const version = getAppVersion()
const appInfo = getAppInfo(); const appInfo = getAppInfo()
runtimeResult.value = `版本号: ${version}\nAppID: ${appInfo.appid}`; runtimeResult.value = `版本号: ${version}\nAppID: ${appInfo.appid}`
}; }
const handleOpenURL = () => { const handleOpenURL = () => {
openURL("https://uniapp.dcloud.net.cn/"); openURL("https://uniapp.dcloud.net.cn/")
runtimeResult.value = "已尝试打开 uni-app 官网"; runtimeResult.value = "已尝试打开 uni-app 官网"
}; }
// plus.screen 示例 // plus.screen 示例
const handleLockPortrait = () => { const handleLockPortrait = () => {
lockOrientation("portrait-primary"); lockOrientation("portrait-primary")
screenResult.value = "已锁定竖屏(实际需要在 manifest.json 中配置)"; screenResult.value = "已锁定竖屏(实际需要在 manifest.json 中配置)"
}; }
const handleLockLandscape = () => { const handleLockLandscape = () => {
lockOrientation("landscape-primary"); lockOrientation("landscape-primary")
screenResult.value = "已锁定横屏(实际需要在 manifest.json 中配置)"; screenResult.value = "已锁定横屏(实际需要在 manifest.json 中配置)"
}; }
const handleKeepScreenOn = () => { const handleKeepScreenOn = () => {
setKeepScreenOn(true); setKeepScreenOn(true)
screenResult.value = "已设置屏幕常亮"; screenResult.value = "已设置屏幕常亮"
}; }
// plus.io 示例 // plus.io 示例
const handleGetFilePath = async () => { const handleGetFilePath = async () => {
...@@ -195,12 +173,12 @@ const handleGetFilePath = async () => { ...@@ -195,12 +173,12 @@ const handleGetFilePath = async () => {
// #ifndef APP // #ifndef APP
path = await getFilePath(); path = await getFilePath();
// #endif // #endif
ioResult.value = `文件路径: ${path}`; ioResult.value = `文件路径: ${path}`
} catch (error: any) { } catch (error: any) {
// UTS 不支持 String() 构造函数,使用字符串模板或 toString() // UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `获取路径失败: ${error != null ? error.toString() : "未知错误"}`; ioResult.value = `获取路径失败: ${error != null ? error.toString() : "未知错误"}`
} }
}; }
const handleWriteFile = async () => { const handleWriteFile = async () => {
try { try {
...@@ -211,14 +189,14 @@ const handleWriteFile = async () => { ...@@ -211,14 +189,14 @@ const handleWriteFile = async () => {
// #ifndef APP // #ifndef APP
testPath = `${await getFilePath()}/hello.txt`; testPath = `${await getFilePath()}/hello.txt`;
// #endif // #endif
await writeFile(testPath, "Hello uni-app x!"); await writeFile(testPath, "Hello uni-app x!")
ioResult.value = `文件写入成功: ${testPath}`; ioResult.value = `文件写入成功: ${testPath}`
} catch (error: any) { } catch (error: any) {
console.error("writeFile fail:", error); console.error("writeFile fail: ", error);
// UTS 不支持 String() 构造函数,使用字符串模板或 toString() // UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `写入失败: ${error != null ? error.toString() : "未知错误"}`; ioResult.value = `写入失败: ${error != null ? error.toString() : "未知错误"}`
} }
}; }
const handleReadFile = async () => { const handleReadFile = async () => {
try { try {
...@@ -229,27 +207,27 @@ const handleReadFile = async () => { ...@@ -229,27 +207,27 @@ const handleReadFile = async () => {
// #ifndef APP // #ifndef APP
testPath = `${await getFilePath()}/hello.txt`; testPath = `${await getFilePath()}/hello.txt`;
// #endif // #endif
const content = await readFile(testPath); const content = await readFile(testPath)
ioResult.value = `文件内容: ${content}`; ioResult.value = `文件内容: ${content}`
} catch (error: any) { } catch (error: any) {
// UTS 不支持 String() 构造函数,使用字符串模板或 toString() // UTS 不支持 String() 构造函数,使用字符串模板或 toString()
ioResult.value = `读取失败: ${error != null ? error.toString() : "未知错误"}`; ioResult.value = `读取失败: ${error != null ? error.toString() : "未知错误"}`
} }
}; }
// plus.os 示例 // plus.os 示例
const handleCheckOS = () => { const handleCheckOS = () => {
const osName = getOSName(); const osName = getOSName()
const isIOSDevice = isIOS(); const isIOSDevice = isIOS()
const isAndroidDevice = isAndroid(); const isAndroidDevice = isAndroid()
osResult.value = `系统: ${osName}\n是否iOS: ${isIOSDevice}\n是否Android: ${isAndroidDevice}`; osResult.value = `系统: ${osName}\n是否iOS: ${isIOSDevice}\n是否Android: ${isAndroidDevice}`
}; }
// plus.navigator 示例 // plus.navigator 示例
const handleGetStatusbarHeight = () => { const handleGetStatusbarHeight = () => {
const height = getStatusbarHeight(); const height = getStatusbarHeight()
navigatorResult.value = `状态栏高度: ${height}px`; navigatorResult.value = `状态栏高度: ${height}px`
}; }
</script> </script>
<style> <style>
......
<template> <template>
<view> <view>
<image class="image" <image class="image" :fade-show="true" mode="widthFix" :src="imageSrc"></image>
:fade-show="true" <video
mode="widthFix"
:src="imageSrc">
</image>
<video autoplay
class="video" class="video"
controls
:src="src" :src="src"
style="width: 100%; height: 300px"> controls
</video> autoplay
style="width: 100%; height: 300px"
></video>
</view> </view>
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
const src =ref("https://qiniu-web-assets.dcloud.net.cn/video/sample/2minute-demo.mp4"); const src =ref('https://qiniu-web-assets.dcloud.net.cn/video/sample/2minute-demo.mp4')
const imageSrc =ref("https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/1762827440132_9hivo0xz.jpg"); const imageSrc =ref('https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/1762827440132_9hivo0xz.jpg')
</script> </script>
<template> <template>
<scroll-view class="flex flex-col bg-gray-50" <scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50">
scroll-y="true"
style="flex: 1">
<view class="flex flex-col px-5 py-5"> <view class="flex flex-col px-5 py-5">
<!-- 标题区域 --> <!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg"> <view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
...@@ -11,9 +9,11 @@ ...@@ -11,9 +9,11 @@
<!-- 权限列表 --> <!-- 权限列表 -->
<view class="flex flex-col"> <view class="flex flex-col">
<view v-for="permission in permissions" <view
v-for="permission in permissions"
:key="permission.name" :key="permission.name"
class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col"> class="bg-white rounded-lg p-4 shadow-sm mb-4 flex-col"
>
<!-- 权限名称和状态 --> <!-- 权限名称和状态 -->
<view class="flex flex-row items-center justify-between mb-3"> <view class="flex flex-row items-center justify-between mb-3">
<view class="flex flex-row items-center"> <view class="flex flex-row items-center">
...@@ -23,9 +23,11 @@ ...@@ -23,9 +23,11 @@
<text class="text-sm text-gray-500 block">{{ permission.desc }}</text> <text class="text-sm text-gray-500 block">{{ permission.desc }}</text>
</view> </view>
</view> </view>
<view class="px-3 py-1 rounded-full" <view
:class="`status-${ permission.status}`"> class="px-3 py-1 rounded-full"
<text class="text-xs font-medium" :class="`status-text-${ permission.status}`"> :class="'status-' + permission.status"
>
<text class="text-xs font-medium" :class="'status-text-' + permission.status">
{{ getStatusText(permission.status) }} {{ getStatusText(permission.status) }}
</text> </text>
</view> </view>
...@@ -33,13 +35,17 @@ ...@@ -33,13 +35,17 @@
<!-- 操作按钮 --> <!-- 操作按钮 -->
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2" <button
@click="checkPermission(permission)"> class="btn btn-primary mr-2 mb-2"
@click="checkPermission(permission)"
>
检查权限 检查权限
</button> </button>
<button class="btn btn-success mr-2 mb-2" <button
class="btn btn-success mr-2 mb-2"
@click="requestPermission(permission)"
:disabled="permission.status === 'granted'" :disabled="permission.status === 'granted'"
@click="requestPermission(permission)"> >
申请权限 申请权限
</button> </button>
</view> </view>
...@@ -49,17 +55,19 @@ ...@@ -49,17 +55,19 @@
<!-- 操作日志 --> <!-- 操作日志 -->
<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 class="flex flex-col" <scroll-view style="max-height: 300px" scroll-y="true" class="flex flex-col">
scroll-y="true" <view
style="max-height: 300px"> v-for="(log, index) in logs"
<view v-for="(log, index) in logs"
:key="index" :key="index"
class="mb-2 pb-2 border-b border-gray-200"> class="mb-2 pb-2 border-b border-gray-200"
>
<text class="text-sm text-gray-600 block">{{ log }}</text> <text class="text-sm text-gray-600 block">{{ log }}</text>
</view> </view>
</scroll-view> </scroll-view>
<button class="btn btn-secondary mt-3" <button
@click="clearLogs"> class="btn btn-secondary mt-3"
@click="clearLogs"
>
清空日志 清空日志
</button> </button>
</view> </view>
...@@ -70,15 +78,16 @@ ...@@ -70,15 +78,16 @@
<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 = "denied" | "granted" | "limited" | "permanentlyDenied" | "provisional" | "restricted" | "unknown"; type PermissionStatus = "unknown" | "granted" | "denied" | "restricted" | "limited" | "permanentlyDenied" | "provisional";
type Permission = { type Permission = {
desc: string; name: string;
displayName: string; displayName: string;
desc: string;
icon: string; icon: string;
name: string;
status: PermissionStatus; status: PermissionStatus;
}; };
...@@ -178,7 +187,7 @@ const checkPermission = (permission: Permission) => { ...@@ -178,7 +187,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 !== -1) { if (index >= 0) {
// 将插件返回的状态字符串转换为我们的状态类型 // 将插件返回的状态字符串转换为我们的状态类型
let status: PermissionStatus = "unknown"; let status: PermissionStatus = "unknown";
if (result == "granted") { if (result == "granted") {
...@@ -220,7 +229,7 @@ const requestPermission = (permission: Permission) => { ...@@ -220,7 +229,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 !== -1) { if (index >= 0) {
let status: PermissionStatus = "unknown"; let status: PermissionStatus = "unknown";
if (statusStr == "granted") { if (statusStr == "granted") {
status = "granted"; status = "granted";
......
<template> <template>
<scroll-view class="flex flex-col bg-gray-50" <scroll-view style="flex: 1" scroll-y="true" class="flex flex-col bg-gray-50">
scroll-y="true"
style="flex: 1">
<view class="flex flex-col px-5 py-5"> <view class="flex flex-col px-5 py-5">
<!-- 标题区域 --> <!-- 标题区域 -->
<view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg"> <view class="bg-blue-500 px-6 py-8 flex-col mb-5 rounded-lg">
...@@ -16,8 +14,10 @@ ...@@ -16,8 +14,10 @@
<text class="text-base font-semibold text-yellow-800 block">需要麦克风权限</text> <text class="text-base font-semibold text-yellow-800 block">需要麦克风权限</text>
</view> </view>
<text class="text-sm text-yellow-700 mb-3 block">录音功能需要访问您的麦克风,请先授予权限。</text> <text class="text-sm text-yellow-700 mb-3 block">录音功能需要访问您的麦克风,请先授予权限。</text>
<button class="btn btn-warning" <button
@click="requestRecordPermission"> class="btn btn-warning"
@click="requestRecordPermission"
>
申请麦克风权限 申请麦克风权限
</button> </button>
</view> </view>
...@@ -26,13 +26,17 @@ ...@@ -26,13 +26,17 @@
<view class="bg-white rounded-lg p-4 shadow-sm flex-col mb-4"> <view class="bg-white rounded-lg p-4 shadow-sm flex-col mb-4">
<text class="text-lg font-semibold text-gray-800 mb-3 block">录音控制</text> <text class="text-lg font-semibold text-gray-800 mb-3 block">录音控制</text>
<view class="flex flex-row flex-wrap"> <view class="flex flex-row flex-wrap">
<button class="btn btn-primary mr-2 mb-2" <button
class="btn btn-primary mr-2 mb-2"
@click="startRecord"
:disabled="!hasPermission" :disabled="!hasPermission"
@click="startRecord"> >
开始录音 开始录音
</button> </button>
<button class="btn btn-secondary mr-2 mb-2" <button
@click="stopRecord"> class="btn btn-secondary mr-2 mb-2"
@click="stopRecord"
>
停止录音 停止录音
</button> </button>
</view> </view>
...@@ -48,17 +52,21 @@ ...@@ -48,17 +52,21 @@
<text v-if="recordList.length > 0" class="text-sm text-gray-500">({{ recordList.length }} 条)</text> <text v-if="recordList.length > 0" class="text-sm text-gray-500">({{ recordList.length }} 条)</text>
</text> </text>
<view v-if="recordList.length === 0" class="flex flex-row items-center"> <view v-if="recordList.length == 0" class="flex flex-row items-center">
<text class="text-sm text-gray-500 block">暂无录音,先录一段试试吧~</text> <text class="text-sm text-gray-500 block">暂无录音,先录一段试试吧~</text>
</view> </view>
<scroll-view v-else <scroll-view
class="flex flex-col" v-else
style="max-height: 400px"
scroll-y="true" scroll-y="true"
style="max-height: 400px"> class="flex flex-col"
<view v-for="record in recordList" >
<view
v-for="record in recordList"
:key="record.id" :key="record.id"
class="flex flex-col mb-3 pb-3 border-b border-gray-200"> class="flex flex-col mb-3 pb-3 border-b border-gray-200"
>
<!-- 录音信息 --> <!-- 录音信息 -->
<view class="flex flex-row items-center justify-between mb-2"> <view class="flex flex-row items-center justify-between mb-2">
<view class="flex flex-col"> <view class="flex flex-col">
...@@ -67,18 +75,24 @@ ...@@ -67,18 +75,24 @@
<text class="text-xs text-gray-500 block">时间: {{ formatTime(record.createTime) }}</text> <text class="text-xs text-gray-500 block">时间: {{ formatTime(record.createTime) }}</text>
</view> </view>
<view class="flex flex-row"> <view class="flex flex-row">
<button v-if="!record.isPlaying" <button
v-if="!record.isPlaying"
class="btn btn-primary mr-2" class="btn btn-primary mr-2"
@click="playRecord(record)"> @click="playRecord(record)"
>
播放 播放
</button> </button>
<button v-else <button
v-else
class="btn btn-secondary mr-2" class="btn btn-secondary mr-2"
@click="stopPlay(record)"> @click="stopPlay(record)"
>
停止 停止
</button> </button>
<button class="btn btn-danger" <button
@click="deleteRecord(record)"> class="btn btn-danger"
@click="deleteRecord(record)"
>
删除 删除
</button> </button>
</view> </view>
...@@ -92,17 +106,19 @@ ...@@ -92,17 +106,19 @@
<!-- 操作日志 --> <!-- 操作日志 -->
<view class="bg-white rounded-lg p-4 shadow-sm flex-col"> <view class="bg-white rounded-lg p-4 shadow-sm flex-col">
<text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text> <text class="text-lg font-semibold text-gray-800 mb-3 block">操作日志</text>
<scroll-view class="flex flex-col" <scroll-view style="max-height: 300px" scroll-y="true" class="flex flex-col">
scroll-y="true" <view
style="max-height: 300px"> v-for="(log, index) in logs"
<view v-for="(log, index) in logs"
:key="index" :key="index"
class="mb-2 pb-2 border-b border-gray-200"> class="mb-2 pb-2 border-b border-gray-200"
>
<text class="text-sm text-gray-600 block">{{ log }}</text> <text class="text-sm text-gray-600 block">{{ log }}</text>
</view> </view>
</scroll-view> </scroll-view>
<button class="btn btn-secondary mt-3" <button
@click="clearLogs"> class="btn btn-secondary mt-3"
@click="clearLogs"
>
清空日志 清空日志
</button> </button>
</view> </view>
...@@ -111,19 +127,19 @@ ...@@ -111,19 +127,19 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { import {
startRecord as uniStartRecord, startRecord as uniStartRecord,
stopRecord as uniStopRecord stopRecord as uniStopRecord
} from "@/uni_modules/uts-recorder"; } from "@/uni_modules/uts-recorder";
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { get } from "@/utils/common.uts"; import { get } from "@/utils/common.uts";
// 录音文件信息类型 // 录音文件信息类型
type RecordFileInfo = { type RecordFileInfo = {
createTime: number;
duration: number;
filePath: string;
id: string; id: string;
filePath: string;
duration: number;
createTime: number;
isPlaying: boolean; isPlaying: boolean;
}; };
...@@ -155,7 +171,7 @@ const checkRecordPermission = () => { ...@@ -155,7 +171,7 @@ const checkRecordPermission = () => {
hasPermission.value = status == "granted"; hasPermission.value = status == "granted";
addLog(`当前麦克风权限状态: ${status}`); addLog(`当前麦克风权限状态: ${status}`);
}); });
}; }
// 申请录音权限 // 申请录音权限
const requestRecordPermission = () => { const requestRecordPermission = () => {
...@@ -168,7 +184,7 @@ const requestRecordPermission = () => { ...@@ -168,7 +184,7 @@ const requestRecordPermission = () => {
// result 是一个 Map<string, string> // result 是一个 Map<string, string>
// 使用 get() 辅助函数访问 Map // 使用 get() 辅助函数访问 Map
const micStatus = get(result, "Microphone") as null | string; const micStatus = get(result, "Microphone") as string | null;
if (micStatus != null) { if (micStatus != null) {
const granted = micStatus == "granted"; const granted = micStatus == "granted";
hasPermission.value = granted; hasPermission.value = granted;
...@@ -197,7 +213,7 @@ const requestRecordPermission = () => { ...@@ -197,7 +213,7 @@ const requestRecordPermission = () => {
}); });
} }
}); });
}; }
// 开始录音 - 使用标准 uni API 模式 // 开始录音 - 使用标准 uni API 模式
const startRecord = () => { const startRecord = () => {
...@@ -329,7 +345,7 @@ const stopPlay = (record: RecordFileInfo) => { ...@@ -329,7 +345,7 @@ const stopPlay = (record: RecordFileInfo) => {
const deleteRecord = (record: RecordFileInfo) => { const deleteRecord = (record: RecordFileInfo) => {
// 从列表中移除 // 从列表中移除
const index = recordList.value.findIndex(item => item.id == record.id); const index = recordList.value.findIndex(item => item.id == record.id);
if (index !== -1) { if (index > -1) {
recordList.value.splice(index, 1); recordList.value.splice(index, 1);
addLog(`已删除录音,剩余 ${recordList.value.length} 条`); addLog(`已删除录音,剩余 ${recordList.value.length} 条`);
} }
...@@ -340,15 +356,15 @@ const formatDuration = (ms: number): string => { ...@@ -340,15 +356,15 @@ const formatDuration = (ms: number): string => {
const seconds = Math.floor(ms / 1000); const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60); const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60; const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`; return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}; };
// 格式化时间 // 格式化时间
const formatTime = (timestamp: number): string => { const formatTime = (timestamp: number): string => {
const date = new Date(timestamp); const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, "0"); const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, "0"); const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, "0"); const seconds = date.getSeconds().toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`; return `${hours}:${minutes}:${seconds}`;
}; };
......
<template> <template>
<!-- #ifdef APP --> <!-- #ifdef APP -->
<scroll-view class="min-h-screen bg-gray-50" style="flex: 1"> <scroll-view style="flex: 1" class="min-h-screen bg-gray-50">
<!-- #endif --> <!-- #endif -->
<!-- #ifndef APP --> <!-- #ifndef APP -->
<view class="min-h-screen bg-gray-50"> <view class="min-h-screen bg-gray-50">
...@@ -128,32 +128,16 @@ ...@@ -128,32 +128,16 @@
<view class="bg-white rounded-lg p-4 shadow-sm"> <view class="bg-white rounded-lg p-4 shadow-sm">
<text class="text-lg font-semibold text-gray-800 mb-4 block">按钮样式</text> <text class="text-lg font-semibold text-gray-800 mb-4 block">按钮样式</text>
<view class="flex flex-wrap gap-3"> <view class="flex flex-wrap gap-3">
<button class="px-6 py-3 rounded-lg font-medium text-white bg-blue-500 active:bg-blue-600"> <button class="px-6 py-3 rounded-lg font-medium text-white bg-blue-500 active:bg-blue-600">Primary</button>
Primary <button class="px-6 py-3 rounded-lg font-medium text-white bg-gray-500 active:bg-gray-600">Secondary</button>
</button> <button class="px-6 py-3 rounded-lg font-medium text-white bg-green-500 active:bg-green-600">Success</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-gray-500 active:bg-gray-600"> <button class="px-6 py-3 rounded-lg font-medium text-white bg-red-500 active:bg-red-600">Danger</button>
Secondary <button class="px-6 py-3 rounded-lg font-medium text-white bg-yellow-500 active:bg-yellow-600">Warning</button>
</button> <button class="px-6 py-3 rounded-lg font-medium text-white bg-purple-500 active:bg-purple-600">Info</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-green-500 active:bg-green-600">
Success
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-red-500 active:bg-red-600">
Danger
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-yellow-500 active:bg-yellow-600">
Warning
</button>
<button class="px-6 py-3 rounded-lg font-medium text-white bg-purple-500 active:bg-purple-600">
Info
</button>
</view> </view>
<view class="mt-3 flex flex-wrap gap-3"> <view class="mt-3 flex flex-wrap gap-3">
<button class="px-4 py-2 rounded text-sm font-medium text-white bg-blue-500 active:bg-blue-600"> <button class="px-4 py-2 rounded text-sm font-medium text-white bg-blue-500 active:bg-blue-600">Small</button>
Small <button class="px-8 py-4 rounded-lg text-lg font-medium text-white bg-blue-500 active:bg-blue-600">Large</button>
</button>
<button class="px-8 py-4 rounded-lg text-lg font-medium text-white bg-blue-500 active:bg-blue-600">
Large
</button>
</view> </view>
</view> </view>
...@@ -166,9 +150,7 @@ ...@@ -166,9 +150,7 @@
<text class="text-gray-600 text-sm leading-relaxed block">这是一个使用 Tailwind CSS 构建的卡片组件,展示了阴影、圆角、间距等样式。weapp-tailwindcss 会自动将 Tailwind 类名转换为对应平台的样式。</text> <text class="text-gray-600 text-sm leading-relaxed block">这是一个使用 Tailwind CSS 构建的卡片组件,展示了阴影、圆角、间距等样式。weapp-tailwindcss 会自动将 Tailwind 类名转换为对应平台的样式。</text>
</view> </view>
<view class="px-4 py-3 bg-gray-50 border-t border-gray-200 flex justify-end"> <view class="px-4 py-3 bg-gray-50 border-t border-gray-200 flex justify-end">
<button class="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded active:bg-blue-600"> <button class="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded active:bg-blue-600">操作</button>
操作
</button>
</view> </view>
</view> </view>
...@@ -263,18 +245,10 @@ ...@@ -263,18 +245,10 @@
</view> </view>
</view> </view>
<view class="mt-4 flex flex-wrap gap-3"> <view class="mt-4 flex flex-wrap gap-3">
<view class="px-4 py-2 border-2 border-blue-500 rounded"> <view class="px-4 py-2 border-2 border-blue-500 rounded">border-2</view>
border-2 <view class="px-4 py-2 border-4 border-green-500 rounded">border-4</view>
</view> <view class="px-4 py-2 border-l-4 border-purple-500 rounded">border-l-4</view>
<view class="px-4 py-2 border-4 border-green-500 rounded"> <view class="px-4 py-2 border-t-4 border-red-500 rounded">border-t-4</view>
border-4
</view>
<view class="px-4 py-2 border-l-4 border-purple-500 rounded">
border-l-4
</view>
<view class="px-4 py-2 border-t-4 border-red-500 rounded">
border-t-4
</view>
</view> </view>
</view> </view>
...@@ -375,7 +349,6 @@ ...@@ -375,7 +349,6 @@
</view> </view>
</view> </view>
<!-- #ifdef APP --> <!-- #ifdef APP -->
</view>
</scroll-view> </scroll-view>
<!-- #endif --> <!-- #endif -->
<!-- #ifndef APP --> <!-- #ifndef APP -->
......
<template> <template>
<scroll-view class="flex flex-col bg-indigo-500" style="flex: 1"> <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"> <view class="flex flex-col">
<view class="flex flex-col px-8 pt-10 pb-8 items-center"> <view class="flex flex-col px-8 pt-10 pb-8 items-center">
...@@ -8,25 +8,31 @@ ...@@ -8,25 +8,31 @@
</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 v-for="item in data" <view
:key="item.label + item.path"
class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full" class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden w-full"
:class="{ 'card-pressed': isCardPressed(item.path) }" :class="{ 'card-pressed': isCardPressed(item.path) }"
@tap="toPath(item)" @touchstart="handleTouchStart(item.path)"
@touchend="pressedCard = ''" @touchend="pressedCard = ''"
@touchstart="handleTouchStart(item.path)"> @tap="toPath(item)"
v-for="item in data"
:key="item.label + item.path"
>
<!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 --> <!-- 使用 justify-between 而不是依赖 flex-1,兼容 App 端布局行为 -->
<view class="flex flex-row items-center p-5 w-full"> <view class="flex flex-row items-center p-5 w-full">
<view class="flex flex-row items-center"> <view class="flex flex-row items-center">
<view class="w-48 h-48 flex items-center justify-center bg-indigo-100 rounded-xl flex-shrink-0 mr-4"> <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> <text class="text-2xl">{{ getIcon(item.icon) }}</text>
</view> </view>
<text class="text-lg font-semibold text-gray-800"> <text class="text-lg font-semibold text-gray-800">
{{ item.label }} {{ item.label }}
</text> </text>
</view> </view>
<view class="w-32 h-32 flex items-center justify-center bg-indigo-500 rounded-lg flex-shrink-0" <view
style="margin-left: auto"> 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> <text class="text-lg text-white font-bold">→</text>
</view> </view>
</view> </view>
...@@ -42,12 +48,12 @@ import { get } from "@/utils/common.uts"; ...@@ -42,12 +48,12 @@ import { get } from "@/utils/common.uts";
// import { router } from "@/utils/router.uts"; // import { router } from "@/utils/router.uts";
type Item = { type Item = {
children?: Item[];
disabled?: boolean;
hidden?: boolean;
icon?: string;
label: string; label: string;
icon?: string;
path?: string; path?: string;
disabled?: boolean;
hidden?: boolean;
children?: Item[];
}; };
const data = computed<Item[]>(() => { const data = computed<Item[]>(() => {
...@@ -128,8 +134,8 @@ const toPath = (item: Item) => { ...@@ -128,8 +134,8 @@ const toPath = (item: Item) => {
// 使用索引访问属性,避免 error18 // 使用索引访问属性,避免 error18
// NavigateToFailImpl 类型特殊,需要先转换为 UTSJSONObject 或使用索引访问 // NavigateToFailImpl 类型特殊,需要先转换为 UTSJSONObject 或使用索引访问
let errMsg = "未知错误"; let errMsg = "未知错误";
let errCode: null | number = null; let errCode: number | null = null;
let errSubject: null | string = null; let errSubject: string | null = null;
// 尝试使用 UTSJSONObject 转换 // 尝试使用 UTSJSONObject 转换
try { try {
...@@ -148,7 +154,7 @@ const toPath = (item: Item) => { ...@@ -148,7 +154,7 @@ const toPath = (item: Item) => {
if (errSubjectTemp != null) { if (errSubjectTemp != null) {
errSubject = errSubjectTemp as string; errSubject = errSubjectTemp as string;
} }
} catch { } catch (e: any) {
// 如果转换失败,尝试使用 JSON 序列化/反序列化 // 如果转换失败,尝试使用 JSON 序列化/反序列化
try { try {
const jsonStr = JSON.stringify(err); const jsonStr = JSON.stringify(err);
...@@ -166,8 +172,8 @@ const toPath = (item: Item) => { ...@@ -166,8 +172,8 @@ const toPath = (item: Item) => {
if (errSubjectTemp != null) { if (errSubjectTemp != null) {
errSubject = errSubjectTemp as string; errSubject = errSubjectTemp as string;
} }
} catch (error: any) { } catch (e2: any) {
console.error("无法解析错误对象:", error); console.error("无法解析错误对象:", e2);
} }
} }
......
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",
"lib": ["esnext", "dom"], "verbatimModuleSyntax": true,
"experimentalDecorators": true, "experimentalDecorators": true,
"paths": { "sourceMap": true,
"@/*": ["./src/*"],
"$/*": ["./uni_modules/*"]
},
"resolveJsonModule": true, "resolveJsonModule": true,
"types": ["@dcloudio/types", "vue"], "esModuleInterop": true,
"noImplicitAny": false, "noImplicitAny": false,
"types": ["@dcloudio/types", "vue"],
"lib": ["esnext", "dom"],
"outDir": "esbuild", "outDir": "esbuild",
"sourceMap": true, "paths": {
"esModuleInterop": true, "@/*": ["./src/*"],
"verbatimModuleSyntax": true "$/*": ["./uni_modules/*"]
}
}, },
"vueCompilerOptions": { "vueCompilerOptions": {
"extensions": [".vue", ".uvue"] "extensions": [".vue", ".uvue"]
......
export type UserInfo = { export type UserInfo = {
avatarUrl?: string; // 头像 unionid: string; // 用户唯一id
birthday?: string; // 生日
city?: string; // 城市
createTime: string; // 创建时间
description?: string; // 描述
district?: string; // 区县
gender: number; // 性别
id: number; // 用户id id: number; // 用户id
loginType: number; // 登录类型
nickName: string; // 昵称 nickName: string; // 昵称
avatarUrl?: string; // 头像
phone: string; // 手机号 phone: string; // 手机号
province?: string; // 省份 gender: number; // 性别
status: number; // 状态 status: number; // 状态
unionid: string; // 用户唯一id description?: string; // 描述
loginType: number; // 登录类型
province?: string; // 省份
city?: string; // 城市
district?: string; // 区县
birthday?: string; // 生日
createTime: string; // 创建时间
updateTime: string; // 更新时间 updateTime: string; // 更新时间
}; };
export type PushAnimationType = export type PushAnimationType =
| "auto" | "auto"
| "fade-in"
| "none" | "none"
| "pop-in"
| "slide-in-bottom"
| "slide-in-left"
| "slide-in-right" | "slide-in-right"
| "slide-in-left"
| "slide-in-top" | "slide-in-top"
| "slide-in-bottom"
| "fade-in"
| "zoom-out"
| "zoom-fade-out" | "zoom-fade-out"
| "zoom-out"; | "pop-in";
export type BackAnimationType = export type BackAnimationType =
| "auto" | "auto"
| "fade-out"
| "none" | "none"
| "pop-out"
| "slide-out-bottom"
| "slide-out-left"
| "slide-out-right" | "slide-out-right"
| "slide-out-left"
| "slide-out-top" | "slide-out-top"
| "slide-out-bottom"
| "fade-out"
| "zoom-in"
| "zoom-fade-in" | "zoom-fade-in"
| "zoom-in"; | "pop-out";
export type PushMode = "navigateTo" | "redirectTo" | "reLaunch" | "switchTab"; export type PushMode = "navigateTo" | "redirectTo" | "reLaunch" | "switchTab";
export type BackOptions = { export type BackOptions = {
animationDuration?: number;
animationType?: BackAnimationType;
complete?: (result: any) => void;
delta?: number; delta?: number;
fail?: (result: any) => void; animationType?: BackAnimationType;
animationDuration?: number;
success?: (result: any) => void; success?: (result: any) => void;
fail?: (result: any) => void;
complete?: (result: any) => void;
}; };
export type PushOptions = { export type PushOptions = {
animationDuration?: number; path: string;
animationType?: PushAnimationType; mode?: PushMode;
complete?: (result: any) => void;
events?: any; events?: any;
fail?: (result: any) => void; query?: UTSJSONObject;
isAuth?: boolean; isAuth?: boolean;
mode?: PushMode;
params?: UTSJSONObject; params?: UTSJSONObject;
path: string; animationType?: PushAnimationType;
query?: UTSJSONObject; animationDuration?: number;
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 = "dark" | "light"; declare type Theme = "light" | "dark";
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): null | T; parseObject<T>(text: string): T | null;
} }
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;
getJSON?(key: string): null | UTSJSONObject; getNumber?(key: string): number | null;
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): null | string; getString?(key: string): string | null;
getString?(key: string, def: any): string; getString?(key: string, def: any): string;
parse?<T>(): null | T; getJSON?(key: string): UTSJSONObject | null;
set?(key: string, value: any | null): void; 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[];
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 =
| "CONNECT" | "OPTIONS"
| "DELETE"
| "GET" | "GET"
| "HEAD" | "HEAD"
| "OPTIONS"
| "POST" | "POST"
| "PUT" | "PUT"
| "TRACE"; | "DELETE"
| "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: {
fail?: (err: { errCode: number; errMsg: string }) => void;
success?: (res: { tempFilePath: string }) => void; success?: (res: { tempFilePath: string }) => void;
fail?: (err: { errCode: number; errMsg: 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?: "alternate" | "alternate-reverse" | "normal" | "reverse"; direction?: "normal" | "reverse" | "alternate" | "alternate-reverse";
duration?: number; duration?: number;
easing?: easing?:
| "cubic-bezier"
| "ease" | "ease"
| "ease-in" | "ease-in"
| "ease-in-out"
| "ease-out" | "ease-out"
| "linear"; | "ease-in-out"
fill?: "backwards" | "both" | "forwards" | "none"; | "linear"
| "cubic-bezier";
fill?: "backwards" | "forwards" | "both" | "none";
iterations?: number; iterations?: number;
} }
): null | { | number
): {
id: string; id: string;
playState: "finished" | "idle" | "paused" | "running"; playState: "running" | "paused" | "finished" | "idle";
}; } | null;
} }
declare interface CanvasContext extends HTMLCanvasElement { declare interface CanvasContext extends HTMLCanvasElement {
......
## 2.0.12(2025-08-26)
- 优化 uni-app x 下 size 类型问题
## 2.0.11(2025-08-18)
- 修复 图标点击事件返回
## 2.0.9(2024-01-12)
fix: 修复图标大小默认值错误的问题
## 2.0.8(2023-12-14)
- 修复 项目未使用 ts 情况下,打包报错的bug
## 2.0.7(2023-12-14)
- 修复 size 属性为 string 时,不加单位导致尺寸异常的bug
## 2.0.6(2023-12-11)
- 优化 兼容老版本icon类型,如 top ,bottom 等
## 2.0.5(2023-12-11)
- 优化 兼容老版本icon类型,如 top ,bottom 等
## 2.0.4(2023-12-06)
- 优化 uni-app x 下示例项目图标排序
## 2.0.3(2023-12-06)
- 修复 nvue下引入组件报错的bug
## 2.0.2(2023-12-05)
-优化 size 属性支持单位
## 2.0.1(2023-12-05)
- 新增 uni-app x 支持定义图标
## 1.3.5(2022-01-24)
- 优化 size 属性可以传入不带单位的字符串数值
## 1.3.4(2022-01-24)
- 优化 size 支持其他单位
## 1.3.3(2022-01-17)
- 修复 nvue 有些图标不显示的bug,兼容老版本图标
## 1.3.2(2021-12-01)
- 优化 示例可复制图标名称
## 1.3.1(2021-11-23)
- 优化 兼容旧组件 type 值
## 1.3.0(2021-11-19)
- 新增 更多图标
- 优化 自定义图标使用方式
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-icons](https://uniapp.dcloud.io/component/uniui/uni-icons)
## 1.1.7(2021-11-08)
## 1.2.0(2021-07-30)
- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 1.1.5(2021-05-12)
- 新增 组件示例地址
## 1.1.4(2021-02-05)
- 调整为uni_modules目录规范
<template>
<text class="uni-icons" :style="styleObj">
<slot>{{unicode}}</slot>
</text>
</template>
<script>
import { fontData, IconsDataItem } from './uniicons_file'
/**
* Icons 图标
* @description 用于展示 icon 图标
* @tutorial https://ext.dcloud.net.cn/plugin?id=28
* @property {Number} size 图标大小
* @property {String} type 图标图案,参考示例
* @property {String} color 图标颜色
* @property {String} customPrefix 自定义图标
* @event {Function} click 点击 Icon 触发事件
*/
export default {
name: "uni-icons",
props: {
type: {
type: String,
default: ''
},
color: {
type: String,
default: '#333333'
},
size: {
type: [Number, String],
default: 16
},
fontFamily: {
type: String,
default: ''
}
},
data() {
return {};
},
computed: {
unicode() : string {
let codes = fontData.find((item : IconsDataItem) : boolean => { return item.font_class == this.type })
if (codes !== null) {
return codes.unicode
}
return ''
},
iconSize() : string {
const size = this.size
if (typeof size == 'string') {
const reg = /^[0-9]*$/g
return reg.test(size as string) ? '' + size + 'px' : '' + size;
// return '' + this.size
}
return this.getFontSize(size as number)
},
styleObj() : UTSJSONObject {
if (this.fontFamily !== '') {
return { color: this.color, fontSize: this.iconSize, fontFamily: this.fontFamily }
}
return { color: this.color, fontSize: this.iconSize }
}
},
created() { },
methods: {
/**
* 字体大小
*/
getFontSize(size : number) : string {
return size + 'px';
},
},
}
</script>
<style scoped>
@font-face {
font-family: UniIconsFontFamily;
src: url('./uniicons.ttf');
}
.uni-icons {
font-family: UniIconsFontFamily;
font-size: 18px;
font-style: normal;
color: #333;
}
</style>
<template>
<!-- #ifdef APP-NVUE -->
<text :style="styleObj" class="uni-icons" @click="_onClick">{{unicode}}</text>
<!-- #endif -->
<!-- #ifndef APP-NVUE -->
<text :style="styleObj" class="uni-icons" :class="['uniui-'+type,customPrefix,customPrefix?type:'']" @click="_onClick">
<slot></slot>
</text>
<!-- #endif -->
</template>
<script>
import { fontData } from './uniicons_file_vue.js';
const getVal = (val) => {
const reg = /^[0-9]*$/g
return (typeof val === 'number' || reg.test(val)) ? val + 'px' : val;
}
// #ifdef APP-NVUE
var domModule = weex.requireModule('dom');
import iconUrl from './uniicons.ttf'
domModule.addRule('fontFace', {
'fontFamily': "uniicons",
'src': "url('" + iconUrl + "')"
});
// #endif
/**
* Icons 图标
* @description 用于展示 icons 图标
* @tutorial https://ext.dcloud.net.cn/plugin?id=28
* @property {Number} size 图标大小
* @property {String} type 图标图案,参考示例
* @property {String} color 图标颜色
* @property {String} customPrefix 自定义图标
* @event {Function} click 点击 Icon 触发事件
*/
export default {
name: 'UniIcons',
emits: ['click'],
props: {
type: {
type: String,
default: ''
},
color: {
type: String,
default: '#333333'
},
size: {
type: [Number, String],
default: 16
},
customPrefix: {
type: String,
default: ''
},
fontFamily: {
type: String,
default: ''
}
},
data() {
return {
icons: fontData
}
},
computed: {
unicode() {
let code = this.icons.find(v => v.font_class === this.type)
if (code) {
return code.unicode
}
return ''
},
iconSize() {
return getVal(this.size)
},
styleObj() {
if (this.fontFamily !== '') {
return `color: ${this.color}; font-size: ${this.iconSize}; font-family: ${this.fontFamily};`
}
return `color: ${this.color}; font-size: ${this.iconSize};`
}
},
methods: {
_onClick(e) {
this.$emit('click', e)
}
}
}
</script>
<style lang="scss">
/* #ifndef APP-NVUE */
@import './uniicons.css';
@font-face {
font-family: uniicons;
src: url('./uniicons.ttf');
}
/* #endif */
.uni-icons {
font-family: uniicons;
text-decoration: none;
text-align: center;
}
</style>
\ No newline at end of file \ No newline at end of file
.uniui-cart-filled:before {
content: "\e6d0";
}
.uniui-gift-filled:before {
content: "\e6c4";
}
.uniui-color:before {
content: "\e6cf";
}
.uniui-wallet:before {
content: "\e6b1";
}
.uniui-settings-filled:before {
content: "\e6ce";
}
.uniui-auth-filled:before {
content: "\e6cc";
}
.uniui-shop-filled:before {
content: "\e6cd";
}
.uniui-staff-filled:before {
content: "\e6cb";
}
.uniui-vip-filled:before {
content: "\e6c6";
}
.uniui-plus-filled:before {
content: "\e6c7";
}
.uniui-folder-add-filled:before {
content: "\e6c8";
}
.uniui-color-filled:before {
content: "\e6c9";
}
.uniui-tune-filled:before {
content: "\e6ca";
}
.uniui-calendar-filled:before {
content: "\e6c0";
}
.uniui-notification-filled:before {
content: "\e6c1";
}
.uniui-wallet-filled:before {
content: "\e6c2";
}
.uniui-medal-filled:before {
content: "\e6c3";
}
.uniui-fire-filled:before {
content: "\e6c5";
}
.uniui-refreshempty:before {
content: "\e6bf";
}
.uniui-location-filled:before {
content: "\e6af";
}
.uniui-person-filled:before {
content: "\e69d";
}
.uniui-personadd-filled:before {
content: "\e698";
}
.uniui-arrowthinleft:before {
content: "\e6d2";
}
.uniui-arrowthinup:before {
content: "\e6d3";
}
.uniui-arrowthindown:before {
content: "\e6d4";
}
.uniui-back:before {
content: "\e6b9";
}
.uniui-forward:before {
content: "\e6ba";
}
.uniui-arrow-right:before {
content: "\e6bb";
}
.uniui-arrow-left:before {
content: "\e6bc";
}
.uniui-arrow-up:before {
content: "\e6bd";
}
.uniui-arrow-down:before {
content: "\e6be";
}
.uniui-arrowthinright:before {
content: "\e6d1";
}
.uniui-down:before {
content: "\e6b8";
}
.uniui-bottom:before {
content: "\e6b8";
}
.uniui-arrowright:before {
content: "\e6d5";
}
.uniui-right:before {
content: "\e6b5";
}
.uniui-up:before {
content: "\e6b6";
}
.uniui-top:before {
content: "\e6b6";
}
.uniui-left:before {
content: "\e6b7";
}
.uniui-arrowup:before {
content: "\e6d6";
}
.uniui-eye:before {
content: "\e651";
}
.uniui-eye-filled:before {
content: "\e66a";
}
.uniui-eye-slash:before {
content: "\e6b3";
}
.uniui-eye-slash-filled:before {
content: "\e6b4";
}
.uniui-info-filled:before {
content: "\e649";
}
.uniui-reload:before {
content: "\e6b2";
}
.uniui-micoff-filled:before {
content: "\e6b0";
}
.uniui-map-pin-ellipse:before {
content: "\e6ac";
}
.uniui-map-pin:before {
content: "\e6ad";
}
.uniui-location:before {
content: "\e6ae";
}
.uniui-starhalf:before {
content: "\e683";
}
.uniui-star:before {
content: "\e688";
}
.uniui-star-filled:before {
content: "\e68f";
}
.uniui-calendar:before {
content: "\e6a0";
}
.uniui-fire:before {
content: "\e6a1";
}
.uniui-medal:before {
content: "\e6a2";
}
.uniui-font:before {
content: "\e6a3";
}
.uniui-gift:before {
content: "\e6a4";
}
.uniui-link:before {
content: "\e6a5";
}
.uniui-notification:before {
content: "\e6a6";
}
.uniui-staff:before {
content: "\e6a7";
}
.uniui-vip:before {
content: "\e6a8";
}
.uniui-folder-add:before {
content: "\e6a9";
}
.uniui-tune:before {
content: "\e6aa";
}
.uniui-auth:before {
content: "\e6ab";
}
.uniui-person:before {
content: "\e699";
}
.uniui-email-filled:before {
content: "\e69a";
}
.uniui-phone-filled:before {
content: "\e69b";
}
.uniui-phone:before {
content: "\e69c";
}
.uniui-email:before {
content: "\e69e";
}
.uniui-personadd:before {
content: "\e69f";
}
.uniui-chatboxes-filled:before {
content: "\e692";
}
.uniui-contact:before {
content: "\e693";
}
.uniui-chatbubble-filled:before {
content: "\e694";
}
.uniui-contact-filled:before {
content: "\e695";
}
.uniui-chatboxes:before {
content: "\e696";
}
.uniui-chatbubble:before {
content: "\e697";
}
.uniui-upload-filled:before {
content: "\e68e";
}
.uniui-upload:before {
content: "\e690";
}
.uniui-weixin:before {
content: "\e691";
}
.uniui-compose:before {
content: "\e67f";
}
.uniui-qq:before {
content: "\e680";
}
.uniui-download-filled:before {
content: "\e681";
}
.uniui-pyq:before {
content: "\e682";
}
.uniui-sound:before {
content: "\e684";
}
.uniui-trash-filled:before {
content: "\e685";
}
.uniui-sound-filled:before {
content: "\e686";
}
.uniui-trash:before {
content: "\e687";
}
.uniui-videocam-filled:before {
content: "\e689";
}
.uniui-spinner-cycle:before {
content: "\e68a";
}
.uniui-weibo:before {
content: "\e68b";
}
.uniui-videocam:before {
content: "\e68c";
}
.uniui-download:before {
content: "\e68d";
}
.uniui-help:before {
content: "\e679";
}
.uniui-navigate-filled:before {
content: "\e67a";
}
.uniui-plusempty:before {
content: "\e67b";
}
.uniui-smallcircle:before {
content: "\e67c";
}
.uniui-minus-filled:before {
content: "\e67d";
}
.uniui-micoff:before {
content: "\e67e";
}
.uniui-closeempty:before {
content: "\e66c";
}
.uniui-clear:before {
content: "\e66d";
}
.uniui-navigate:before {
content: "\e66e";
}
.uniui-minus:before {
content: "\e66f";
}
.uniui-image:before {
content: "\e670";
}
.uniui-mic:before {
content: "\e671";
}
.uniui-paperplane:before {
content: "\e672";
}
.uniui-close:before {
content: "\e673";
}
.uniui-help-filled:before {
content: "\e674";
}
.uniui-paperplane-filled:before {
content: "\e675";
}
.uniui-plus:before {
content: "\e676";
}
.uniui-mic-filled:before {
content: "\e677";
}
.uniui-image-filled:before {
content: "\e678";
}
.uniui-locked-filled:before {
content: "\e668";
}
.uniui-info:before {
content: "\e669";
}
.uniui-locked:before {
content: "\e66b";
}
.uniui-camera-filled:before {
content: "\e658";
}
.uniui-chat-filled:before {
content: "\e659";
}
.uniui-camera:before {
content: "\e65a";
}
.uniui-circle:before {
content: "\e65b";
}
.uniui-checkmarkempty:before {
content: "\e65c";
}
.uniui-chat:before {
content: "\e65d";
}
.uniui-circle-filled:before {
content: "\e65e";
}
.uniui-flag:before {
content: "\e65f";
}
.uniui-flag-filled:before {
content: "\e660";
}
.uniui-gear-filled:before {
content: "\e661";
}
.uniui-home:before {
content: "\e662";
}
.uniui-home-filled:before {
content: "\e663";
}
.uniui-gear:before {
content: "\e664";
}
.uniui-smallcircle-filled:before {
content: "\e665";
}
.uniui-map-filled:before {
content: "\e666";
}
.uniui-map:before {
content: "\e667";
}
.uniui-refresh-filled:before {
content: "\e656";
}
.uniui-refresh:before {
content: "\e657";
}
.uniui-cloud-upload:before {
content: "\e645";
}
.uniui-cloud-download-filled:before {
content: "\e646";
}
.uniui-cloud-download:before {
content: "\e647";
}
.uniui-cloud-upload-filled:before {
content: "\e648";
}
.uniui-redo:before {
content: "\e64a";
}
.uniui-images-filled:before {
content: "\e64b";
}
.uniui-undo-filled:before {
content: "\e64c";
}
.uniui-more:before {
content: "\e64d";
}
.uniui-more-filled:before {
content: "\e64e";
}
.uniui-undo:before {
content: "\e64f";
}
.uniui-images:before {
content: "\e650";
}
.uniui-paperclip:before {
content: "\e652";
}
.uniui-settings:before {
content: "\e653";
}
.uniui-search:before {
content: "\e654";
}
.uniui-redo-filled:before {
content: "\e655";
}
.uniui-list:before {
content: "\e644";
}
.uniui-mail-open-filled:before {
content: "\e63a";
}
.uniui-hand-down-filled:before {
content: "\e63c";
}
.uniui-hand-down:before {
content: "\e63d";
}
.uniui-hand-up-filled:before {
content: "\e63e";
}
.uniui-hand-up:before {
content: "\e63f";
}
.uniui-heart-filled:before {
content: "\e641";
}
.uniui-mail-open:before {
content: "\e643";
}
.uniui-heart:before {
content: "\e639";
}
.uniui-loop:before {
content: "\e633";
}
.uniui-pulldown:before {
content: "\e632";
}
.uniui-scan:before {
content: "\e62a";
}
.uniui-bars:before {
content: "\e627";
}
.uniui-checkbox:before {
content: "\e62b";
}
.uniui-checkbox-filled:before {
content: "\e62c";
}
.uniui-shop:before {
content: "\e62f";
}
.uniui-headphones:before {
content: "\e630";
}
.uniui-cart:before {
content: "\e631";
}
{
"id": "uni-icons",
"displayName": "uni-icons 图标",
"version": "2.0.12",
"description": "图标组件,用于展示移动端常见的图标,可自定义颜色、大小。",
"keywords": [
"uni-ui",
"uniui",
"icon",
"图标"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": "^3.2.14",
"uni-app": "^4.08",
"uni-app-x": "^4.61"
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue",
"darkmode": "x",
"i18n": "x",
"widescreen": "x"
},
"uni_modules": {
"dependencies": [
"uni-scss"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "x",
"aliyun": "x",
"alipay": "x"
},
"client": {
"uni-app": {
"vue": {
"vue2": "√",
"vue3": "√"
},
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"vue": "√",
"nvue": "-",
"android": {
"extVersion": "",
"minVersion": "29"
},
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√",
"alipay": "√",
"toutiao": "√",
"baidu": "√",
"kuaishou": "-",
"jd": "-",
"harmony": "-",
"qq": "√",
"lark": "-"
},
"quickapp": {
"huawei": "√",
"union": "√"
}
},
"uni-app-x": {
"web": {
"safari": "√",
"chrome": "√"
},
"app": {
"android": {
"extVersion": "",
"minVersion": "29"
},
"ios": "√",
"harmony": "√"
},
"mp": {
"weixin": "√"
}
}
}
}
}
}
\ No newline at end of file \ No newline at end of file
## Icons 图标
> **组件名:uni-icons**
> 代码块: `uIcons`
用于展示 icons 图标 。
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-icons)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
{"version":3,"sources":["pages/common/components/NoData.uvue"],"sourcesContent":["<template>\n <view class=\"list-not\">\n <image src=\"/static/images/login/nothing.webp\" class=\"list-not-img\" />\n <text>暂无内容</text>\n </view>\n</template>\n\n<script setup lang=\"uts\">\n</script>\n\n<style scoped lang=\"scss\">\n.list-not {\n font-size: 11px;\n color: #999999;\n margin: auto;\n text-align: center;\n flex-direction: column;\n \n &-img {\n width: 338px;\n height: 281px;\n margin: 191px auto 6px;\n display: block;\n }\n}\n</style>\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;eACE,IAGO,QAAA,IAHD,WAAM,aAAU;YACpB,IAAsE,SAAA,IAA/D,SAAI,qCAAoC,WAAM;YACrD,IAAiB,QAAA,IAAA,EAAX"}
\ No newline at end of file \ No newline at end of file
{"version":3,"sources":["uni_modules/uni-icons/components/uni-icons/uni-icons.uvue"],"sourcesContent":["<template>\r\n\t<text class=\"uni-icons\" :style=\"styleObj\">\r\n\t\t<slot>{{unicode}}</slot>\r\n\t</text>\r\n</template>\r\n\r\n<script>\r\n\timport { fontData, IconsDataItem } from './uniicons_file'\r\n\r\n\t/**\r\n\t * Icons 图标\r\n\t * @description 用于展示 icon 图标\r\n\t * @tutorial https://ext.dcloud.net.cn/plugin?id=28\r\n\t * @property {Number} size 图标大小\r\n\t * @property {String} type 图标图案,参考示例\r\n\t * @property {String} color 图标颜色\r\n\t * @property {String} customPrefix 自定义图标\r\n\t * @event {Function} click 点击 Icon 触发事件\r\n\t */\r\n\texport default {\r\n\t\tname: \"uni-icons\",\r\n\t\tprops: {\r\n\t\t\ttype: {\r\n\t\t\t\ttype: String,\r\n\t\t\t\tdefault: ''\r\n\t\t\t},\r\n\t\t\tcolor: {\r\n\t\t\t\ttype: String,\r\n\t\t\t\tdefault: '#333333'\r\n\t\t\t},\r\n\t\t\tsize: {\r\n type: [Number, String],\r\n default: 16\r\n\t\t\t},\r\n\t\t\tfontFamily: {\r\n\t\t\t\ttype: String,\r\n\t\t\t\tdefault: ''\r\n\t\t\t}\r\n\t\t},\r\n\t\tdata() {\r\n\t\t\treturn {};\r\n\t\t},\r\n\t\tcomputed: {\r\n\t\t\tunicode() : string {\r\n\t\t\t\tlet codes = fontData.find((item : IconsDataItem) : boolean => { return item.font_class == this.type })\r\n\t\t\t\tif (codes !== null) {\r\n\t\t\t\t\treturn codes.unicode\r\n\t\t\t\t}\r\n\t\t\t\treturn ''\r\n\t\t\t},\r\n\t\t\ticonSize() : string {\r\n\t\t\t\tconst size = this.size\n\t\t\t\tif (typeof size == 'string') {\n\t\t\t\t const reg = /^[0-9]*$/g\n\t\t\t\t return reg.test(size as string) ? '' + size + 'px' : '' + size;\n\t\t\t\t // return '' + this.size\n\t\t\t\t}\n\t\t\t\treturn this.getFontSize(size as number)\r\n\t\t\t},\r\n\t\t\tstyleObj() : UTSJSONObject {\r\n\t\t\t\tif (this.fontFamily !== '') {\r\n\t\t\t\t\treturn { color: this.color, fontSize: this.iconSize, fontFamily: this.fontFamily }\r\n\t\t\t\t}\r\n\t\t\t\treturn { color: this.color, fontSize: this.iconSize }\r\n\t\t\t}\r\n\t\t},\r\n\t\tcreated() { },\r\n\t\tmethods: {\r\n\t\t\t/**\r\n\t\t\t * 字体大小\r\n\t\t\t */\r\n\t\t\tgetFontSize(size : number) : string {\r\n\t\t\t\treturn size + 'px';\r\n\t\t\t},\r\n\t\t},\r\n\t}\r\n</script>\r\n\r\n<style scoped>\r\n\t@font-face {\r\n\t\tfont-family: UniIconsFontFamily;\r\n\t\tsrc: url('./uniicons.ttf');\r\n\t}\r\n\r\n\t.uni-icons {\r\n\t\tfont-family: UniIconsFontFamily;\r\n\t\tfont-size: 18px;\r\n\t\tfont-style: normal;\r\n\t\tcolor: #333;\r\n\t}\r\n</style>\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAmBM;;kBA+CJ,MAAO,CAAK;;;;;;eAjEb,IAEO,QAAA,IAFD,WAAM,aAAa,WAAK,IAAE,KAAA,QAAQ;YACvC,WAAwB,KAAA,QAAA,EAAA,WAAA,eAAA,EAAxB,gBAAwB,GAAA;uBAAA;oBAAA,IAAhB,KAAA,OAAO;iBAAA;;;;;IAoBd,SAAA,wBAGC;IACD,SAAA,yBAGC;IACD,SAAA,qBAGC;IACD,SAAA,8BAGA;sBAMY,MAAK;uBAOJ,MAAK;uBASL;;;yCAhBD,MAAK,EAAjB,OAAY,MAAK,CAAA;YAChB,IAAI,QAAQ,SAAS,IAAI,CAAC,IAAC,sBAAwB,OAAM,CAAG;gBAAI,OAAO,KAAK,UAAS,CAAA,EAAA,CAAK,IAAI,CAAC,IAAG;YAAE;;YACpG,IAAI,MAAI,EAAA,CAAM,IAAI,EAAE;gBACnB,OAAO,MAAM,OAAM;;YAEpB,OAAO;QACR;kCACa,MAAK,EAAlB,OAAa,MAAK,CAAA;YACjB,IAAM,OAAO,IAAI,CAAC,IAAG;YACrB,IAAI,oBAAO,MAAG,EAAA,CAAK,UAAU;gBAC3B,IAAM,MAAM;gBACZ,OAAO,IAAA,IAAI,IAAI,CAAC,KAAG,EAAA,CAAK,MAAM,GAAI;oBAAA,GAAC,CAAA,CAAA,CAAI,KAAG,EAAA,CAAA,MAAA,EAAA,CAAA,CAAI;gBAAA,EAAO,IAAS,CAAT;oBAAA,GAAC,CAAA,CAAA,CAAI,KAAI,EAAA,CAAA,MAAA;gBAAA;;YAGhE,OAAO,IAAI,CAAC,WAAW,CAAC,KAAG,EAAA,CAAK,MAAM;QACvC;kCACa,eAAb,OAAa,cAAY;YACxB,IAAI,IAAI,CAAC,UAAS,CAAA,GAAA,CAAM,IAAI;gBAC3B,OAAO,IAAE,WAAO,IAAI,CAAC,KAAK,EAAE,cAAU,IAAI,CAAC,QAAQ,EAAE,gBAAY,IAAI,CAAC,UAAS;;YAEhF,OAAO,IAAE,WAAO,IAAI,CAAC,KAAK,EAAE,cAAU,IAAI,CAAC,QAAO;QACnD;;;aAOA;aAAA,mBAAY,MAAO,MAAM,GAAI,MAAK,CAAA;QACjC,OAAO,KAAG,CAAA,CAAI;IACf;;mBArDK;;;;;;;;;;;;;4BAEL,UAAM,IACC,UAAA,UACG,aAAA,KAEV,WAAO,IACA,UAAA,UACG,aAAA,YAEV,UAAM;;;WAEQ,aAAA,EAAC,GAEf,gBAAY,IACL,UAAA,UACG,aAAA;;;;;;;;;AAuCZ"}
\ No newline at end of file \ No newline at end of file
...@@ -4,49 +4,65 @@ ...@@ -4,49 +4,65 @@
"compiler_version": "4.87" "compiler_version": "4.87"
}, },
"files": { "files": {
"components/evaluationForm/TypeTabComponent.kt": { "pages/index/index.kt": {
"md5": "0c65870c54770c8dfebb843dc83b547ef7d25a50", "class": "GenPagesIndexIndex",
"class": "GenComponentsEvaluationFormTypeTabComponent" "md5": "d8d028fdb9eab322150af58a90c2361ddfea3f18"
}, },
"uni_modules/z-paging-x/components/z-paging-x/z-paging-x.kt": { "index.kt": {
"md5": "4e08a9502eacce0a379370f55af65cc373be4d86", "md5": "58f0fea201e4278f6bc39c939656ca440a4b8d98",
"class": "GenUniModulesZPagingXComponentsZPagingXZPagingX" "class": ""
},
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-loading.kt": {
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoading",
"md5": "bc2c0931a10ad4eea405d60556ee5e702cc28f62"
},
"pages/common/login/index.kt": {
"md5": "165659590e28e0663c371d8606710e0c7fd36859",
"class": "GenPagesCommonLoginIndex"
},
"components/PublishPopup.kt": {
"md5": "b0c3be2d9836f013bc4b67bbf5fe08a456f6ce18",
"class": "GenComponentsPublishPopup"
}, },
"pages/demo/record/index.kt": { "pages/demo/record/index.kt": {
"class": "GenPagesDemoRecordIndex", "class": "GenPagesDemoRecordIndex",
"md5": "84e76df7ed975ac1925322c2e8a598c39e5c84af" "md5": "84e76df7ed975ac1925322c2e8a598c39e5c84af"
}, },
"pages/demo/echarts/index.kt": {
"md5": "e9c323efac81c50aa4eca12e75586263bacd95fb",
"class": "GenPagesDemoEchartsIndex"
},
"pages/demo/local-store/index.kt": {
"class": "GenPagesDemoLocalStoreIndex",
"md5": "6360b2df10619a70490f9f6f126d91728741e2c2"
},
"uni_modules/lime-echart/components/l-echart/l-echart.kt": { "uni_modules/lime-echart/components/l-echart/l-echart.kt": {
"class": "GenUniModulesLimeEchartComponentsLEchartLEchart", "md5": "23c5a52d57071d3771477b55f910fbe9ccac83fc",
"md5": "23c5a52d57071d3771477b55f910fbe9ccac83fc" "class": "GenUniModulesLimeEchartComponentsLEchartLEchart"
}, },
"pages/demo/media/index.kt": { "pages/demo/media/index.kt": {
"class": "GenPagesDemoMediaIndex", "class": "GenPagesDemoMediaIndex",
"md5": "d76917918ad2397c0cd8429328b52ab77a83ff4f" "md5": "d76917918ad2397c0cd8429328b52ab77a83ff4f"
}, },
"pages/demo/permission/index.kt": {
"class": "GenPagesDemoPermissionIndex",
"md5": "18cb329597e3254e8c67cefdc1f196e3a1260273"
},
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-refresher.kt": { "uni_modules/z-paging-x/components/z-paging-x/components/z-paging-refresher.kt": {
"md5": "16ff705042a40a87dd8d71d3fa16ad4a017d0301", "md5": "16ff705042a40a87dd8d71d3fa16ad4a017d0301",
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingRefresher" "class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingRefresher"
}, },
"pages/index/index.kt": { "pages/common/components/AccountList.kt": {
"md5": "d8d028fdb9eab322150af58a90c2361ddfea3f18", "class": "GenPagesCommonComponentsAccountList",
"class": "GenPagesIndexIndex" "md5": "d78e30a9fd29b1bd3fc6451b74a39845095f79ee"
}, },
"pages/common/login/index.kt": { "uni_modules/z-paging-x/components/z-paging-x/z-paging-x.kt": {
"class": "GenPagesCommonLoginIndex", "class": "GenUniModulesZPagingXComponentsZPagingXZPagingX",
"md5": "8275e3dccc8940758ddc7640b511dd5005c5f790" "md5": "4e08a9502eacce0a379370f55af65cc373be4d86"
}, },
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-load-more.kt": { "uni_modules/uni-icons/components/uni-icons/uni-icons.kt": {
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoadMore", "class": "GenUniModulesUniIconsComponentsUniIconsUniIcons",
"md5": "a09e63a3254f1a7fd1be3a47e1d27eccb876c289" "md5": "95aae1ef2b0e8906a602ca5d24eea964329fab31"
}, },
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-loading.kt": { "pages/common/accountItems/index.kt": {
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoading", "class": "GenPagesCommonAccountItemsIndex",
"md5": "bc2c0931a10ad4eea405d60556ee5e702cc28f62" "md5": "ce7b7aebc25c812bc76446384be7b4ae423373da"
}, },
"pages/demo/gl-tape-demo/index.kt": { "pages/demo/gl-tape-demo/index.kt": {
"class": "GenPagesDemoGlTapeDemoIndex", "class": "GenPagesDemoGlTapeDemoIndex",
...@@ -56,21 +72,17 @@ ...@@ -56,21 +72,17 @@
"class": "GenPagesDemoTailwindcssIndex", "class": "GenPagesDemoTailwindcssIndex",
"md5": "c427026081cb75ed3d462c5ebf8a3ac0750bfa34" "md5": "c427026081cb75ed3d462c5ebf8a3ac0750bfa34"
}, },
"components/PublishPopup.kt": { "pages/common/components/NoData.kt": {
"md5": "b0c3be2d9836f013bc4b67bbf5fe08a456f6ce18", "md5": "0608111022dbb7da0f7c3e452b7409d1ec7f5735",
"class": "GenComponentsPublishPopup" "class": "GenPagesCommonComponentsNoData"
},
"pages/demo/echarts/index.kt": {
"md5": "e9c323efac81c50aa4eca12e75586263bacd95fb",
"class": "GenPagesDemoEchartsIndex"
}, },
"pages/demo/local-store/index.kt": { "components/evaluationForm/TypeTabComponent.kt": {
"md5": "6360b2df10619a70490f9f6f126d91728741e2c2", "class": "GenComponentsEvaluationFormTypeTabComponent",
"class": "GenPagesDemoLocalStoreIndex" "md5": "0c65870c54770c8dfebb843dc83b547ef7d25a50"
}, },
"index.kt": { "uni_modules/z-paging-x/components/z-paging-x/components/z-paging-load-more.kt": {
"md5": "6e6ffa4e30e8732dd679c2a64e01a087e018ab0b", "class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoadMore",
"class": "" "md5": "a09e63a3254f1a7fd1be3a47e1d27eccb876c289"
}, },
"uni_modules/z-paging-x/components/z-paging-x-empty/z-paging-x-empty.kt": { "uni_modules/z-paging-x/components/z-paging-x-empty/z-paging-x-empty.kt": {
"class": "GenUniModulesZPagingXComponentsZPagingXEmptyZPagingXEmpty", "class": "GenUniModulesZPagingXComponentsZPagingXEmptyZPagingXEmpty",
...@@ -79,6 +91,10 @@ ...@@ -79,6 +91,10 @@
"pages/demo/old/index.kt": { "pages/demo/old/index.kt": {
"class": "GenPagesDemoOldIndex", "class": "GenPagesDemoOldIndex",
"md5": "8b8d4a1b49e2ef7592d4e2f958b222392cf46fe8" "md5": "8b8d4a1b49e2ef7592d4e2f958b222392cf46fe8"
},
"pages/demo/permission/index.kt": {
"md5": "18cb329597e3254e8c67cefdc1f196e3a1260273",
"class": "GenPagesDemoPermissionIndex"
} }
} }
} }
\ No newline at end of file \ No newline at end of file
@file:Suppress("UNCHECKED_CAST", "USELESS_CAST", "INAPPLICABLE_JVM_NAME", "UNUSED_ANONYMOUS_PARAMETER", "NAME_SHADOWING", "UNNECESSARY_NOT_NULL_ASSERTION")
package uni.UNIB602BFA
import io.dcloud.uniapp.*
import io.dcloud.uniapp.extapi.*
import io.dcloud.uniapp.framework.*
import io.dcloud.uniapp.runtime.*
import io.dcloud.uniapp.vue.*
import io.dcloud.uniapp.vue.shared.*
import io.dcloud.unicloud.*
import io.dcloud.uts.*
import io.dcloud.uts.Map
import io.dcloud.uts.Set
import io.dcloud.uts.UTSAndroid
import kotlin.properties.Delegates
open class GenPagesCommonComponentsNoData : VueComponent {
constructor(__ins: ComponentInternalInstance) : super(__ins) {}
@Suppress("UNUSED_PARAMETER", "UNUSED_VARIABLE")
override fun `$render`(): Any? {
val _cache = this.`$`.renderCache
return _cE("view", _uM("class" to "list-not"), _uA(
_cE("image", _uM("src" to "/static/images/login/nothing.webp", "class" to "list-not-img")),
_cE("text", null, "暂无内容")
))
}
companion object {
val styles: Map<String, Map<String, Map<String, Any>>> by lazy {
_nCS(_uA(
styles0
))
}
val styles0: Map<String, Map<String, Map<String, Any>>>
get() {
return _uM("text-hide" to _pS(_uM("whiteSpace" to "nowrap", "overflow" to "hidden", "textOverflow" to "ellipsis")), "text-two-line" to _pS(_uM("WebkitBoxOrient" to "vertical", "WebkitLineClamp" to 2, "overflow" to "hidden", "textOverflow" to "ellipsis")), "select-item" to _uM(".select-box " to _uM("display" to "flex", "justifyContent" to "center", "alignItems" to "center")), "common-title" to _pS(_uM("width" to "100%", "height" to "120rpx", "position" to "relative", "display" to "flex", "alignItems" to "center", "paddingLeft" to "48rpx", "color" to "#333333", "fontSize" to "34rpx", "content::after" to "\"\"", "position::after" to "absolute", "left::after" to 0, "top::after" to 0, "zIndex::after" to -2, "width::after" to "100%", "height::after" to "100%", "backgroundImage::after" to "linear-gradient(0deg, #94c2ff00 0%, #5294ff 100%)", "backgroundColor::after" to "rgba(0,0,0,0)", "opacity::after" to 0.15, "content::before" to "\"\"", "position::before" to "absolute", "zIndex::before" to -1, "width::before" to "136rpx", "height::before" to "136rpx", "opacity::before" to 0.6, "backgroundImage::before" to "linear-gradient(-44.4deg, #94c2ff00 0%, #5294ff 100%)", "backgroundColor::before" to "rgba(0,0,0,0)", "filter::before" to "blur(24rpx)")), "bg-title" to _pS(_uM("position" to "absolute", "top" to 0, "left" to 0, "width" to "100%", "height" to "120rpx", "display" to "flex", "alignItems" to "center", "paddingLeft" to "48rpx", "color" to "#333333", "fontSize" to "34rpx", "content::after" to "\"\"", "position::after" to "absolute", "left::after" to 0, "top::after" to 0, "zIndex::after" to -2, "width::after" to "100%", "height::after" to "100%", "backgroundImage::after" to "linear-gradient(0deg, #94c2ff00 0%, #5294ff 100%)", "backgroundColor::after" to "rgba(0,0,0,0)", "opacity::after" to 0.15, "content::before" to "\"\"", "position::before" to "absolute", "zIndex::before" to -1, "width::before" to "136rpx", "height::before" to "136rpx", "opacity::before" to 0.6, "backgroundImage::before" to "linear-gradient(-44.4deg, #94c2ff00 0%, #5294ff 100%)", "backgroundColor::before" to "rgba(0,0,0,0)", "filter::before" to "blur(24rpx)")), "list-not" to _pS(_uM("fontSize" to 11, "color" to "#999999", "marginTop" to "auto", "marginRight" to "auto", "marginBottom" to "auto", "marginLeft" to "auto", "textAlign" to "center", "flexDirection" to "column")), "list-not-img" to _pS(_uM("width" to 338, "height" to 281, "marginTop" to 191, "marginRight" to "auto", "marginBottom" to 6, "marginLeft" to "auto")))
}
var inheritAttrs = true
var inject: Map<String, Map<String, Any?>> = _uM()
var emits: Map<String, Any?> = _uM()
var props = _nP(_uM())
var propsNeedCastKeys: UTSArray<String> = _uA()
var components: Map<String, CreateVueComponent> = _uM()
}
}
@file:Suppress("UNCHECKED_CAST", "USELESS_CAST", "INAPPLICABLE_JVM_NAME", "UNUSED_ANONYMOUS_PARAMETER", "NAME_SHADOWING", "UNNECESSARY_NOT_NULL_ASSERTION")
package uni.UNIB602BFA
import io.dcloud.uniapp.*
import io.dcloud.uniapp.extapi.*
import io.dcloud.uniapp.framework.*
import io.dcloud.uniapp.runtime.*
import io.dcloud.uniapp.vue.*
import io.dcloud.uniapp.vue.shared.*
import io.dcloud.unicloud.*
import io.dcloud.uts.*
import io.dcloud.uts.Map
import io.dcloud.uts.Set
import io.dcloud.uts.UTSAndroid
import kotlin.properties.Delegates
open class GenUniModulesUniIconsComponentsUniIconsUniIcons : VueComponent {
constructor(__ins: ComponentInternalInstance) : super(__ins) {
onCreated(fun() {}, __ins)
}
@Suppress("UNUSED_PARAMETER", "UNUSED_VARIABLE")
override fun `$render`(): Any? {
val _ctx = this
val _cache = this.`$`.renderCache
return _cE("text", _uM("class" to "uni-icons", "style" to _nS(_ctx.styleObj)), _uA(
renderSlot(_ctx.`$slots`, "default", UTSJSONObject(), fun(): UTSArray<Any> {
return _uA(
_tD(_ctx.unicode)
)
}
)
), 4)
}
open var type: String by `$props`
open var color: String by `$props`
open var size: Any by `$props`
open var fontFamily: String by `$props`
open var unicode: String by `$data`
open var iconSize: String by `$data`
open var styleObj: UTSJSONObject by `$data`
@Suppress("USELESS_CAST")
override fun data(): Map<String, Any?> {
return _uM("unicode" to computed<String>(fun(): String {
var codes = fontData.find(fun(item: IconsDataItem): Boolean {
return item.font_class == this.type
}
)
if (codes != null) {
return codes.unicode
}
return ""
}
), "iconSize" to computed<String>(fun(): String {
val size = this.size
if (UTSAndroid.`typeof`(size) == "string") {
val reg = UTSRegExp("^[0-9]*\$", "g")
return if (reg.test(size as String)) {
"" + (size as String) + "px"
} else {
"" + (size as String)
}
}
return this.getFontSize(size as Number)
}
), "styleObj" to computed<UTSJSONObject>(fun(): UTSJSONObject {
if (this.fontFamily !== "") {
return _uO("color" to this.color, "fontSize" to this.iconSize, "fontFamily" to this.fontFamily)
}
return _uO("color" to this.color, "fontSize" to this.iconSize)
}
))
}
open var getFontSize = ::gen_getFontSize_fn
open fun gen_getFontSize_fn(size: Number): String {
return size + "px"
}
companion object {
var name = "uni-icons"
val styles: Map<String, Map<String, Map<String, Any>>> by lazy {
_nCS(_uA(
styles0
))
}
val styles0: Map<String, Map<String, Map<String, Any>>>
get() {
return _uM("uni-icons" to _pS(_uM("fontFamily" to "UniIconsFontFamily", "fontSize" to 18, "fontStyle" to "normal", "color" to "#333333")), "@FONT-FACE" to _uM("0" to _uM("fontFamily" to "UniIconsFontFamily", "src" to "url('/assets/uniicons.32e978a5.ttf')")))
}
var inheritAttrs = true
var inject: Map<String, Map<String, Any?>> = _uM()
var emits: Map<String, Any?> = _uM()
var props = _nP(_uM("type" to _uM("type" to "String", "default" to ""), "color" to _uM("type" to "String", "default" to "#333333"), "size" to _uM("type" to _uA(
"Number",
"String"
), "default" to 16), "fontFamily" to _uM("type" to "String", "default" to "")))
var propsNeedCastKeys = _uA(
"type",
"color",
"size",
"fontFamily"
)
var components: Map<String, CreateVueComponent> = _uM()
}
}
{"duts":["uni-actionSheet","uni-theme","uni-getSystemInfo","uni-base64ToArrayBuffer","uni-arrayBufferToBase64","uni-crash","uni-storage","uni-dialogPage","uni-event","uni-exit","uni-form","uni-getAccessibilityInfo","uni-getAppAuthorizeSetting","uni-getAppBaseInfo","uni-getDeviceInfo","uni-getElementById","uni-getSystemSetting","uni-modal","uni-openAppAuthorizeSetting","uni-privacy","uni-progress","uni-prompt","uni-rpx2px","uni-rich-text","uni-barcode-scanning","uni-camera","uni-media","permission-handler-plus","uni-location","uni-location-system","lime-sqlite","uts-recorder","uni-createInnerAudioContext","uni-clipboard","uni-previewImage","uni-network","uni-fileSystemManager","uni-video"]}
\ No newline at end of file \ No newline at end of file
{"duts":["uni-actionSheet","uni-theme","uni-getSystemInfo","uni-base64ToArrayBuffer","uni-arrayBufferToBase64","uni-crash","uni-storage","uni-dialogPage","uni-event","uni-exit","uni-form","uni-getAccessibilityInfo","uni-getAppAuthorizeSetting","uni-getAppBaseInfo","uni-getDeviceInfo","uni-getElementById","uni-getSystemSetting","uni-modal","uni-openAppAuthorizeSetting","uni-privacy","uni-progress","uni-prompt","uni-rpx2px","uni-rich-text","uni-barcode-scanning","uni-camera","uni-media","permission-handler-plus","uni-location","uni-location-system","lime-sqlite","uts-recorder","uni-createInnerAudioContext","uni-clipboard","uni-getNetworkType","uni-previewImage","uni-network","uni-fileSystemManager","uni-video"]}
\ No newline at end of file \ No newline at end of file
...@@ -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[]): null | T { export function first<T>(array: T[]): T | null {
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[]): null | T { ...@@ -112,7 +112,7 @@ export function first<T>(array: T[]): null | T {
* @example last([1, 2, 3]) // 3 * @example last([1, 2, 3]) // 3
* @example last([]) // null * @example last([]) // null
*/ */
export function last<T>(array: T[]): null | T { export function last<T>(array: T[]): T | null {
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 (const [i, element] of array.entries()) { for (let i = 0; i < array.length; i++) {
result.push(iteratee(element, i)); result.push(iteratee(array[i], 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 (const [i, element] of array.entries()) { for (let i = 0; i < array.length; i++) {
accumulator = iteratee(accumulator, element, i); accumulator = iteratee(accumulator, array[i], 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 (const [i, element] of array.entries()) { for (let i = 0; i < array.length; i++) {
if (!predicate(element, i)) { if (!predicate(array[i], 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 (const [i, element] of array.entries()) { for (let i = 0; i < array.length; i++) {
if (predicate(element, i)) { if (predicate(array[i], i)) {
return true; return true;
} }
} }
...@@ -247,7 +247,8 @@ export function uniq<T>(array: T[]): T[] { ...@@ -247,7 +247,8 @@ 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 (const item of array) { for (let i = 0; i < array.length; i++) {
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);
...@@ -267,7 +268,8 @@ export function flatten(array: any[]): any[] { ...@@ -267,7 +268,8 @@ export function flatten(array: any[]): any[] {
const result: any[] = []; const result: any[] = [];
for (const item of array) { for (let i = 0; i < array.length; i++) {
const item = array[i];
if (isArray(item)) { if (isArray(item)) {
result.push(...(item as any[])); result.push(...(item as any[]));
} else { } else {
...@@ -287,7 +289,8 @@ export function flattenDeep(array: any[]): any[] { ...@@ -287,7 +289,8 @@ export function flattenDeep(array: any[]): any[] {
const result: any[] = []; const result: any[] = [];
for (const item of array) { for (let i = 0; i < array.length; i++) {
const item = array[i];
if (isArray(item)) { if (isArray(item)) {
result.push(...flattenDeep(item as any[])); result.push(...flattenDeep(item as any[]));
} else { } else {
...@@ -307,11 +310,11 @@ export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] { ...@@ -307,11 +310,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);
} }
...@@ -351,14 +354,15 @@ export function groupBy<T>(array: T[], key: string) { ...@@ -351,14 +354,15 @@ export function groupBy<T>(array: T[], key: string) {
const result = {}; const result = {};
for (const item of array) { for (let i = 0; i < array.length; i++) {
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>();
} }
...@@ -384,7 +388,7 @@ export function assign(...items: any[]) { ...@@ -384,7 +388,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): null | T { export function nth<T>(array: T[], index: number): T | null {
if (index >= 0) { if (index >= 0) {
return array[index]; return array[index];
} }
...@@ -411,9 +415,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo ...@@ -411,9 +415,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo
const result: T[] = []; const result: T[] = [];
for (const [i, element] of array.entries()) { for (let i = 0; i < array.length; i++) {
if (!predicate(element, i)) { if (!predicate(array[i], i)) {
result.push(element); result.push(array[i]);
} }
} }
...@@ -428,9 +432,9 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi ...@@ -428,9 +432,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 (const [i, element] of array.entries()) { for (let i = 0; i < array.length; i++) {
if (element != null) { if (array[i] != null) {
iteratee(element, i); iteratee(array[i], i);
} }
} }
} }
...@@ -440,12 +444,12 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi ...@@ -440,12 +444,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): null | T { export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): T | null {
if (!isArray(array)) return null; if (!isArray(array)) return null;
for (const [i, element] of array.entries()) { for (let i = 0; i < array.length; i++) {
if (predicate(element, i)) { if (predicate(array[i], i)) {
return element; return array[i];
} }
} }
return null; return null;
...@@ -458,7 +462,8 @@ export function find<T>(array: T[], predicate: (value: T, index: number) => bool ...@@ -458,7 +462,8 @@ 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 (const key of objKeys) { for (let i = 0; i < objKeys.length; i++) {
const key = objKeys[i];
iteratee(get(data, key)!, key); iteratee(get(data, key)!, key);
} }
} }
...@@ -580,9 +585,9 @@ export function random(min: number, max: number): number { ...@@ -580,9 +585,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
const bytes = window.atob(data.split(",")[1]); let bytes = window.atob(data.split(",")[1]);
const ab = new ArrayBuffer(bytes.length); let ab = new ArrayBuffer(bytes.length);
const ia = new Uint8Array(ab); let 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 = {
pages: Page[];
root: string; root: string;
pages: Page[];
}; };
export type TabBarItem = { export type TabBarItem = {
iconPath?: string; text?: string;
pagePath: string; pagePath: string;
iconPath?: 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;
backgroundImage?: string;
backgroundRepeat?: "no-repeat" | "repeat" | "repeat-x" | "repeat-y";
blurEffect?: "dark" | "extralight" | "light" | "none";
borderStyle?: string; borderStyle?: string;
color?: string; blurEffect?: "dark" | "extralight" | "light" | "none";
custom?: boolean; list?: TabBarItem[];
position?: "top" | "bottom";
fontSize?: string; fontSize?: string;
height?: string;
iconWidth?: string; iconWidth?: string;
list?: TabBarItem[];
position?: "bottom" | "top";
redDotColor?: string;
selectedColor?: string;
spacing?: string; spacing?: string;
height?: string;
backgroundImage?: string;
backgroundRepeat?: "repeat" | "repeat-x" | "repeat-y" | "no-repeat";
redDotColor?: string;
}; };
export type Ctx = { export type Ctx = {
appid: string; appid: string;
color: UTSJSONObject;
globalStyle: UTSJSONObject; globalStyle: UTSJSONObject;
pages: Page[]; pages: Page[];
SAFE_CHAR_MAP_LOCALE: string[][];
subPackages: SubPackage[];
tabBar: TabBar;
theme: UTSJSONObject;
uniIdRouter: UTSJSONObject; uniIdRouter: UTSJSONObject;
theme: UTSJSONObject;
tabBar: TabBar;
subPackages: SubPackage[];
SAFE_CHAR_MAP_LOCALE: string[][];
color: 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 = {
createdAt: number;
itemId: string;
itemType: "article" | "product" | "video";
userId: string; userId: string;
itemId: string;
itemType: "article" | "video" | "product";
createdAt: number;
}; };
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 (const cartItem of cartItems) { for (let i = 0; i < cartItems.length; i++) {
totalPrice += cartItem.price * cartItem.quantity; totalPrice += cartItems[i].price * cartItems[i].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): null | T { export function parse<T>(data: any): T | null {
// #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): null | T { ...@@ -20,7 +20,7 @@ export function parse<T>(data: any): null | T {
* @param data 要解析的数据 * @param data 要解析的数据
* @returns 解析后的JSON对象 * @returns 解析后的JSON对象
*/ */
export function parseObject<T>(data: string): null | T { export function parseObject<T>(data: string): T | null {
// #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 ? Number.parseFloat(match[0] ?? "0") : 0; return match != null ? 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: number | string) => { export const getPx = (val: string | number) => {
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;
versionCode: number;
versionName: string; versionName: string;
versionCode: number;
appName: 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 { } catch (e: any) {
// 方法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 (error: any) { } catch (e2: any) {
console.error("readFile method2 failed:", error); console.error("readFile method2 failed: ", e2);
} }
} }
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 (error: any) { } catch (e: any) {
console.error("ArrayBuffer decode error:", error); console.error("ArrayBuffer decode error: ", e);
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 (Array.isArray(files)) { if (files instanceof Array) {
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 = {
appid: string;
version: string; version: string;
appid: string;
}; };
/** /**
...@@ -32,8 +32,8 @@ export function getAppVersion(): string { ...@@ -32,8 +32,8 @@ export function getAppVersion(): string {
} }
} }
// #endif // #endif
} catch (error: any) { } catch (e: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败:", error); console.error("[plus-runtime] 通过 getAppBaseInfo 获取版本号失败: ", e);
} }
// 其它平台或获取失败时返回空字符串,由上层决定是否展示 // 其它平台或获取失败时返回空字符串,由上层决定是否展示
...@@ -55,8 +55,8 @@ export function getAppId(): string { ...@@ -55,8 +55,8 @@ export function getAppId(): string {
} }
} }
// #endif // #endif
} catch (error: any) { } catch (e: any) {
console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败:", error); console.error("[plus-runtime] 通过 getAppBaseInfo 获取 appid 失败: ", e);
} }
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 (error: any) { } catch (e: any) {
console.error("[plus-runtime] 使用 openSchema 打开 URL 失败:", error, "url=", url); console.error("[plus-runtime] 使用 openSchema 打开 URL 失败: ", e, " 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 {
debounce, storage,
get, last,
isNull,
isEmpty, isEmpty,
get,
isFunction, isFunction,
isNull, toArray,
last,
map, map,
debounce,
nth, nth,
storage, assign,
toArray parse
} 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;
}; };
// 跳转前钩子类型 // 跳转前钩子类型
...@@ -29,81 +30,22 @@ type AfterLogin = () => void; ...@@ -29,81 +30,22 @@ type AfterLogin = () => void;
// 路由事件集合 // 路由事件集合
type Events = { type Events = {
afterLogin?: AfterLogin;
beforeEach?: BeforeEach; beforeEach?: BeforeEach;
afterLogin?: AfterLogin;
}; };
// 路由核心类 // 路由核心类
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 参数
afterLogin(cb: AfterLogin) { params() {
this.eventsMap.afterLogin = cb; return (storage.get("router-params") ?? {}) as UTSJSONObject;
}
// 返回上一页
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;
} }
// 执行当前页面暴露的方法 // 获取传递的 query 参数
callMethod(name: string, data?: any): any | null { query() {
const fn = get(this.route()!, `$vm.$.exposed.${name}`) as (d?: any) => any | null; return this.route()?.query ?? {};
if (isFunction(fn)) {
return fn(data);
}
return null;
} }
// 获取默认路径,支持 home 和 login // 获取默认路径,支持 home 和 login
...@@ -116,16 +58,6 @@ export class Router { ...@@ -116,16 +58,6 @@ 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) => {
...@@ -138,7 +70,7 @@ export class Router { ...@@ -138,7 +70,7 @@ export class Router {
// 补全路径前缀 // 补全路径前缀
if (!path.startsWith("/")) { if (!path.startsWith("/")) {
path = `/${ path}`; path = "/" + path;
} }
// 获取页面样式 // 获取页面样式
...@@ -172,76 +104,14 @@ export class Router { ...@@ -172,76 +104,14 @@ export class Router {
}); });
} }
// 回到首页 // 获取指定路径的页面实例
home() { getPage(path: string) {
this.push({ return this.getPages().find((e) => e.path == path);
path: this.defaultPath("home")
});
}
// 判断是否为当前页面
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() { route() {
return (storage.get("router-params") ?? {}) as UTSJSONObject; return last(this.getPages());
} }
// 获取当前页面路径 // 获取当前页面路径
...@@ -249,6 +119,13 @@ export class Router { ...@@ -249,6 +119,13 @@ 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 {
...@@ -270,7 +147,7 @@ export class Router { ...@@ -270,7 +147,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 临时存储
...@@ -286,7 +163,7 @@ export class Router { ...@@ -286,7 +163,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,
...@@ -297,8 +174,7 @@ export class Router { ...@@ -297,8 +174,7 @@ export class Router {
animationDuration animationDuration
}); });
break; break;
} case "redirectTo":
case "redirectTo": {
uni.redirectTo({ uni.redirectTo({
url: path, url: path,
success, success,
...@@ -306,8 +182,7 @@ export class Router { ...@@ -306,8 +182,7 @@ export class Router {
complete complete
}); });
break; break;
} case "reLaunch":
case "reLaunch": {
uni.reLaunch({ uni.reLaunch({
url: path, url: path,
success, success,
...@@ -315,8 +190,7 @@ export class Router { ...@@ -315,8 +190,7 @@ export class Router {
complete complete
}); });
break; break;
} case "switchTab":
case "switchTab": {
uni.switchTab({ uni.switchTab({
url: path, url: path,
success, success,
...@@ -325,7 +199,6 @@ export class Router { ...@@ -325,7 +199,6 @@ export class Router {
}); });
break; break;
} }
}
}; };
// 跳转前钩子处理 // 跳转前钩子处理
...@@ -343,22 +216,146 @@ export class Router { ...@@ -343,22 +216,146 @@ export class Router {
} }
} }
// 获取传递的 query 参数 // 回到首页
query() { home() {
return this.route()?.query ?? {}; this.push({
path: this.defaultPath("home")
});
} }
// 获取当前路由页面实例 // 返回上一页
route() { back(options: BackOptions | null = null) {
return last(this.getPages()); 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();
}
}
} }
// 简单跳转页面(默认 navigateTo) // 获取页面元数据
to(path: string) { 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({ this.push({
path 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) {
this.eventsMap.beforeEach = cb;
}
// 注册登录后回调
afterLogin(cb: AfterLogin) {
this.eventsMap.afterLogin = cb;
}
} }
// 单例导出 // 单例导出
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!