Commit 2f29f6dc by liimin

refactor: 统一代码风格并优化签名函数逻辑

- 调整导入顺序,将 `import` 语句标准化
- 统一缩进为制表符(tabs),替换部分空格缩进
- 优化 `sign.uts` 中循环逻辑,使用 `for...of` 替代传统 `for` 循环
- 修复 `qs.uts` 中类型定义和递归序列化逻辑,增强健壮性
- 将登录页特定分辨率背景色从蓝色改为红色
1 parent d5e0c173
......@@ -3,107 +3,167 @@
* 仅支持简单对象序列化,不处理复杂嵌套
*/
interface StringifyOptions {
export type Encoder = (str: string) => string
export type Sorter = (a: any, b: any) => number
export type GenerateArrayPrefix = (prefix: string, key: string) => string
export type Formatter = (str: string) => string
export type SerializeDate = (date: Date) => string
export type Filter = (prefix: string, value: any) => any
export type StringifyOptions = {
allowDots?: boolean
encoder?: Encoder
encodeValuesOnly?: boolean
filter?: any // Function | Array<string>
formatter?: Formatter
generateArrayPrefix?: GenerateArrayPrefix
prefix?: string
encoder?: Function
filter?: Function | Array<string>
sort?: Function
strictNullHandling?: boolean
serializeDate?: SerializeDate
skipNulls?: boolean
encodeValuesOnly?: boolean
generateArrayPrefix?: Function
allowDots?: boolean
serializeDate?: Function
formatter?: Function
sort?: Sorter
strictNullHandling?: boolean
}
function defaultEncoder(str: string): string {
const res = encodeURIComponent(str);
return res ?? str;
}
function defaultGenerateArrayPrefix(p: string, k: string): string {
return `${p}[${k}]`;
}
function defaultFormatter(str: string): string {
return str;
}
function defaultSerializeDate(date: Date): string {
return date.toISOString();
}
function stringifyRecursive(
obj: any,
options: StringifyOptions = {}
obj: any | null,
options: StringifyOptions
): string {
const prefix = options.prefix ?? ''
const encoder = options.encoder || encodeURIComponent
const filter = options.filter
const sort = options.sort
const strictNullHandling = options.strictNullHandling ?? false
const skipNulls = options.skipNulls ?? false
const encodeValuesOnly = options.encodeValuesOnly ?? false
const generateArrayPrefix = options.generateArrayPrefix || ((p: string, k: string) => `${p}[${k}]`)
const allowDots = options.allowDots ?? false
const formatter = options.formatter || ((str: string) => str)
const serializeDate = options.serializeDate || ((date: Date) => date.toISOString())
let processedObj: any = obj
if (typeof filter === 'function') {
processedObj = filter(prefix, obj)
} else if (obj instanceof Date) {
processedObj = serializeDate(obj)
} else if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix) : prefix
}
processedObj = ''
}
if (typeof processedObj === 'string' ||
typeof processedObj === 'number' ||
typeof processedObj === 'boolean') {
if (encoder) {
const keyValue = encodeValuesOnly ? prefix : encoder(prefix)
return `${formatter(keyValue)}=${formatter(encoder(processedObj))}`
}
return `${formatter(prefix)}=${formatter(String(processedObj))}`
}
const values: Array<string> = []
if (typeof processedObj === 'undefined') {
return ''
}
let objKeys: Array<string> = []
if (Array.isArray(filter)) {
objKeys = filter as Array<string>
} else {
const keys = Object.keys(processedObj)
objKeys = sort ? keys.sort(sort) : keys
}
for (let i = 0; i < objKeys.length; i++) {
const key = objKeys[i]
if (skipNulls && processedObj[key] === null) {
continue
}
if (Array.isArray(processedObj)) {
const result = stringifyRecursive(
processedObj[key],
{
...options,
prefix: prefix ? generateArrayPrefix(prefix, key) : key
}
)
if (result) {
values.push(result)
}
} else {
const result = stringifyRecursive(
processedObj[key],
{
...options,
prefix: prefix ? prefix + (allowDots ? '.' + key : '[' + key + ']') : key
}
)
if (result) {
values.push(result)
}
}
}
return values.join('&')
const prefix = options.prefix ?? "";
const encoder = options.encoder != null ? options.encoder! : (str: string): string => defaultEncoder(str);
const filter = options.filter;
const sort = options.sort;
const strictNullHandling = options.strictNullHandling ?? false;
const skipNulls = options.skipNulls ?? false;
const encodeValuesOnly = options.encodeValuesOnly ?? false;
const generateArrayPrefix = options.generateArrayPrefix != null ? options.generateArrayPrefix! : (p: string, k: string): string => defaultGenerateArrayPrefix(p, k);
const allowDots = options.allowDots ?? false;
const formatter = options.formatter != null ? options.formatter! : (str: string): string => defaultFormatter(str);
const serializeDate = options.serializeDate != null ? options.serializeDate! : (date: Date): string => defaultSerializeDate(date);
let processedObj: any | null = obj;
if (typeof filter === "function") {
const filterFn = filter as Filter;
// UTS requires parameter types to match exactly, but 'obj' is 'any | null'
// and Filter expects 'any'. Casting 'obj' to 'any' is safe here.
processedObj = filterFn(prefix, obj as any);
} else if (obj instanceof Date) {
processedObj = serializeDate(obj);
} else if (obj === null) {
if (strictNullHandling) {
return encoder(prefix);
}
processedObj = "";
}
if (typeof processedObj === "string" ||
typeof processedObj === "number" ||
typeof processedObj === "boolean") {
const keyValue = encodeValuesOnly ? prefix : encoder(prefix);
const valueStr = typeof processedObj === "string" ? processedObj as string : `${processedObj}`;
return `${formatter(keyValue)}=${formatter(encoder(valueStr))}`;
}
const values: string[] = [];
if (processedObj == null) {
return "";
}
let objKeys: string[] = [];
let targetObj: any | null = processedObj;
if (Array.isArray(filter)) {
objKeys = filter as string[];
// If filter is array, we still need to know how to access processedObj
// If processedObj is not array/map, we might need to convert it to be accessible
if (!Array.isArray(processedObj) && !(processedObj instanceof UTSJSONObject)) {
targetObj = new UTSJSONObject(processedObj);
}
} else {
if (processedObj != null) {
if (Array.isArray(processedObj)) {
const arr = processedObj as any[];
for (let i = 0; i < arr.length; i++) {
objKeys.push(`${i}`);
}
} else if (processedObj instanceof UTSJSONObject) {
const objMap = (processedObj as UTSJSONObject).toMap();
objMap.forEach((_, key) => {
objKeys.push(key);
});
} else {
const json = new UTSJSONObject(processedObj);
targetObj = json;
const objMap = json.toMap();
objMap.forEach((_, key) => {
objKeys.push(key);
});
}
if (sort != null) {
objKeys = objKeys.sort(sort);
}
}
}
for (const key of objKeys) {
let value: any | null = null;
if (Array.isArray(targetObj)) {
const idx = Number.parseInt(key);
if (!isNaN(idx)) {
value = (targetObj as any[])[idx];
}
} else {
value = (targetObj as UTSJSONObject)[key];
}
if (skipNulls && value === null) {
continue;
}
const nextPrefix = Array.isArray(targetObj)
? (prefix != "" ? generateArrayPrefix(prefix, key) : key)
: (prefix != "" ? prefix + (allowDots ? `.${key}` : `[${key}]`) : key);
const newOptions: StringifyOptions = {
prefix: nextPrefix,
encoder,
filter,
sort,
strictNullHandling,
skipNulls,
encodeValuesOnly,
generateArrayPrefix,
allowDots,
serializeDate,
formatter
};
const result = stringifyRecursive(value, newOptions);
if (result != "") {
values.push(result);
}
}
return values.join("&");
}
/**
......@@ -113,8 +173,8 @@ function stringifyRecursive(
* @returns 序列化后的字符串,如 "key1=val1&key2=val2"
*/
export function stringify(
obj: UTSJSONObject,
options: StringifyOptions = {}
obj: UTSJSONObject,
options: StringifyOptions = {} as StringifyOptions
): string {
return stringifyRecursive(obj, options)
}
\ No newline at end of file
return stringifyRecursive(obj, options);
}
import { stringify as qsStringify, StringifyOptions } from "./qs.uts";
import { sha1 } from "./sha1.uts";
import { stringify as qsStringify } from "./qs.uts";
/**
* 参数签名方法(完全对齐 gl_tape/api/request/sign.js)
......@@ -16,25 +16,26 @@ import { stringify as qsStringify } from "./qs.uts";
export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] = []): UTSJSONObject {
// 1. 用 qs.stringify 序列化(encodeValuesOnly: true)
const objStr = qsStringify(params,{
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true
});
console.log(objStr,'===')
const options = {
// arrayFormat: 'indices', // UTS qs implementation doesn't support arrayFormat yet, default is indices-like
allowDots: true,
encodeValuesOnly: true
} as StringifyOptions;
const objStr = qsStringify(params, options);
console.log(objStr, "===");
// 2. split('&') 拆开
const objVal = objStr.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) {
for (const item of objVal) {
const idx = item.indexOf("=");
if (idx === -1) {
continue;
}
const key = item.substring(0, idx);
const val = decodeURIComponent(item.substring(idx + 1));
const key = item.slice(0, Math.max(0, idx));
const val = decodeURIComponent(item.slice(Math.max(0, idx + 1)));
realObj[key] = val;
}
......@@ -49,13 +50,12 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
sortedKeys.sort();
// 5. 归一化 value:null -> "",对象 -> JSON 字符串
for (let i = 0; i < sortedKeys.length; i++) {
const key = sortedKeys[i];
for (const key of sortedKeys) {
let obj: any | null = realObj[key];
if (obj == null) {
obj = "";
} else if (typeof obj == "object") {
} else if (typeof obj === "object") {
obj = JSON.stringify(obj);
}
......@@ -64,8 +64,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
// 6. 组装待签名字符串(排除 noSignAttr 指定的字段)
const segments: string[] = [];
for (let i = 0; i < sortedKeys.length; i++) {
const key = sortedKeys[i];
for (const key of sortedKeys) {
if (noSignAttr.indexOf(key) >= 0) {
continue;
}
......@@ -78,7 +77,7 @@ export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[]
const signVal = sha1(signSrc).toUpperCase();
// 8. 把 sign 挂到 realObj 上,返回全字符串的对象(和老项目保持一致)
realObj["sign"] = signVal;
realObj.sign = signVal;
return realObj;
}
......@@ -11,12 +11,12 @@ export function updateResolutionConfig() {
const info = uni.getWindowInfo();
console.log("🚀 ~ updateResolutionConfig ~ info:", info);
// 优先取 windowWidth,如果为 0 则取 screenWidth (物理屏幕宽)
let w = info.windowWidth;
let h = info.windowHeight;
const pr = info.pixelRatio;
// 兜底逻辑...
if (w === 0 && info.screenWidth > 0) {
w = info.screenWidth;
......@@ -28,7 +28,7 @@ export function updateResolutionConfig() {
console.error(`[ResolutionAdapt] Failed to get valid window size: ${w}x${h}`);
return;
}
const key = `${Math.round(w)}x${Math.round(h)}`;
console.log(`[ResolutionAdapt] Window: ${w}x${h} @${pr}x, Key: ${key}`);
......@@ -54,13 +54,13 @@ export function updateResolutionConfig() {
target = adapter.getFallback();
usedKey = `${adapter.getPrefix()}/common`;
}
if (target !== null) {
resolutionState.config = target;
resolutionState.currentKey = usedKey;
// 更新 CSS 类名
resolutionState.cssClass = adapter.getCssClass(key);
resolutionState.pixelRatio = pr;
resolutionState.windowWidth = w;
resolutionState.windowHeight = h;
......@@ -86,19 +86,19 @@ export function useResolutionConfig() : AppResolutionConfig {
*/
export function getResponsiveImage(img: ResponsiveImage): string {
const pr = resolutionState.pixelRatio;
// 3x 屏优先找 x3 -> x2 -> x1
if (pr >= 3) {
if (img.x3 !== null) return img.x3;
if (img.x2 !== null) return img.x2;
}
// 2x 屏优先找 x2 -> x3 -> x1
if (pr >= 2) {
if (img.x2 !== null) return img.x2;
if (img.x3 !== null) return img.x3;
}
// 默认返回 1倍图
return img.x1;
}
import { ResponsiveImage } from "./types/index.uts";
import { getResponsiveImage } from "./core.uts";
import { ResponsiveImage } from "./types/index.uts";
/**
* 获取响应式图片处理函数
* 在 setup 中调用此 hook,返回一个可以直接在 template 中使用的函数
*/
export function useResponsiveImage() {
// 返回一个符合模板调用要求的 wrapper 函数
const getResImg = (img: ResponsiveImage): string => {
return getResponsiveImage(img);
};
return getResImg;
// 返回一个符合模板调用要求的 wrapper 函数
const getResImg = (img: ResponsiveImage): string => {
return getResponsiveImage(img);
};
return getResImg;
}
......@@ -5,7 +5,7 @@ export { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
export { getResponsiveImage, updateResolutionConfig, useResolutionConfig } from "./core.uts";
// 导出 Hooks
export { useResponsiveImage } from './hooks.uts';
export { useResponsiveImage } from "./hooks.uts";
// 导出注册表
export { initRegistry, landscapeMap, portraitMap } from "./registry.uts";
......
......@@ -22,7 +22,7 @@
/* 针对 1174x768 的样式 */
&.layout-landscape-1174x768 {
.login {
background-color: blue;
background-color: red;
}
.title{
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!