Compare commits

..

No commits in common. "master" and "@r-utils/vue2@2.0.1" have entirely different histories.

90 changed files with 287 additions and 9890 deletions

1
.npmrc
View File

@ -1,3 +1,2 @@
registry=http://npm.nps.yunvip123.cn
engine-strict=true
shamefully-hoist=true

View File

@ -8,7 +8,7 @@
| ---- | ---- | ---- |
| `@r-utils/common` | `packages/common` | 通用 JS/TS 工具(权限、倒计时、打印、时间等) |
| `@r-utils/vue3` | `packages/vue3` | Vue3 工具class 处理、dispatch 等) |
| `@r-utils/uni-app` | `packages/uni-app` | uni-app 工具请求封装、蓝牙、NFC、打印、Vue3 Hooks 等) |
| `@r-utils/uni-app` | `packages/uni-app` | uni-app 工具请求封装、蓝牙、NFC、打印等 |
| `@r-utils/uview-plus` | `packages/uview-plus` | uview-plus 组合式 API HooksPicker、Calendar 等) |
| `@r-utils/vue2` | `packages/vue2` | Vue2 工具visibility 插件) |
@ -86,9 +86,6 @@ import { mergeClass, dispatch } from '@r-utils/vue3';
// uni-app 工具
import { Request } from '@r-utils/uni-app';
// uni-app Vue3 Hooks
import { useShare } from '@r-utils/uni-app/vue3';
// uview-plus Hooks
import { usePickerSingle, usePicker, useCalendar } from '@r-utils/uview-plus';

View File

@ -71,7 +71,6 @@ module.exports = {
{ value: "uni-app", name: "uni-app: @r-utils/uni-app 包" },
{ value: "deps", name: "deps: 依赖更新" },
{ value: "release", name: "release: 版本发布" },
{ value: "playground", name: "playground: 示例/调试项目" },
],
allowCustomScopes: true,
allowEmptyScopes: true,

View File

@ -4,14 +4,11 @@ import prettier from "eslint-config-prettier";
import prettierPlugin from "eslint-plugin-prettier";
import globals from "globals";
import importPlugin from "eslint-plugin-import-x";
import vuePlugin from "eslint-plugin-vue";
import vueParser from "vue-eslint-parser";
export default [
// 应用推荐规则
js.configs.recommended,
...ts.configs.recommended,
...vuePlugin.configs["flat/recommended"],
prettier,
// 基础配置
@ -40,22 +37,6 @@ export default [
"scripts/",
],
plugins: { prettier: prettierPlugin, "import-x": importPlugin },
languageOptions: {
globals: {
...globals.node,
...globals.browser,
},
ecmaVersion: "latest",
sourceType: "module",
parser: vueParser,
parserOptions: {
parser: ts.parser,
ecmaFeatures: {
impliedStrict: true,
},
extraFileExtensions: [".vue"],
},
},
settings: {
"import-x/resolver": {
typescript: {
@ -65,14 +46,24 @@ export default [
"packages/uview-plus/tsconfig.json",
"packages/vue2/tsconfig.json",
"packages/vue3/tsconfig.json",
"playground/vue3-app/tsconfig.json",
"playground/vue2-app/tsconfig.json",
"playground/uniapp-app/tsconfig.json",
],
},
node: true,
},
},
languageOptions: {
globals: {
...globals.node,
...globals.browser,
},
ecmaVersion: "latest",
sourceType: "module",
parserOptions: {
ecmaFeatures: {
impliedStrict: true,
},
},
},
rules: {
...importPlugin.flatConfigs.recommended.rules,
@ -129,9 +120,8 @@ export default [
// uni-app / App-Plus 运行时全局变量
{
files: [
"packages/uni-app/**/*.{js,ts,vue}",
"packages/uni-app/**/*.{js,ts}",
"packages/common/src/printer/**/*.{js,ts}",
"playground/uniapp-app/**/*.{js,ts,vue}",
],
languageOptions: {
globals: {
@ -142,13 +132,4 @@ export default [
},
},
},
// playground 项目放宽部分规则
{
files: ["playground/**/*.{js,ts,vue}"],
rules: {
"import-x/no-extraneous-dependencies": "off",
"vue/multi-word-component-names": "off",
},
},
];

View File

@ -38,16 +38,11 @@
"scripts": {
"preinstall": "npx only-allow pnpm",
"build": "turbo run build --filter=./packages/*",
"build:playground": "turbo run build --filter=./playground/*",
"build:watch": "turbo run watch --filter=./packages/* --parallel",
"typecheck": "turbo run typecheck --filter=./packages/* --concurrency=1",
"prepare": "husky install",
"lint": "turbo run lint --filter=./packages/*",
"lint:playground": "turbo run lint --filter=./playground/*",
"format": "turbo run format --filter=./packages/*",
"dev:vue3": "pnpm --filter @r-utils/playground-vue3 dev",
"dev:vue2": "pnpm --filter @r-utils/playground-vue2 dev",
"dev:uniapp": "pnpm --filter @r-utils/playground-uniapp dev:h5",
"changeset": "changeset",
"release": "changeset version",
"changeset:status": "changeset status --verbose",
@ -75,8 +70,6 @@
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import-x": "^4.16.2",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-vue": "^10.2.0",
"vue-eslint-parser": "^10.1.3",
"globals": "^17.4.0",
"husky": "^9.1.7",
"inquirer": "^9.3.8",

View File

@ -9,32 +9,19 @@
export type InputValue = string | number | null;
export interface InputOptions {
/** 最小值 */
min?: number;
/** 最大值 */
max?: number;
/** 初始值,当输入非法且 required 为 true 时回退到此值 */
init?: string | number;
/** 小数位数,设置后会对结果进行精度处理 */
digits?: number;
/** 匹配模式,文本模式下用于校验输入是否匹配该正则 */
pattern?: string | RegExp;
/** 是否必填,为 true 时非法输入将回退到 init 或 min */
required?: boolean;
/** 是否取整,为 true 时结果将取整 */
integer?: boolean;
/** 是否将结果转为数字类型 */
number?: boolean;
/** 是否使用文本模式,文本模式只做 pattern 校验和必填回退 */
text?: boolean;
/** 是否向下取整 */
floor?: boolean;
/** 是否向上取整 */
ceil?: boolean;
/** 是否保留小数位,为 true 时即使小数位为 0 也会保留指定位数(需配合 digits 使用) */
keepDecimal?: boolean;
/** 是否不允许输入正负号 */
noSign?: boolean;
min?: number; // 最小值
max?: number; // 最大值
init?: string | number; // 初始值
digits?: number; // 小数位数
pattern?: string | RegExp; // 匹配模式
required?: boolean; // 是否必填
integer?: boolean; // 是否整数
number?: boolean; // 是否转成数字
text?: boolean; // 是否使用文本模式
floor?: boolean; // 是否向下取数
ceil?: boolean; // 是否向上取数
keepDecimal?: boolean; // 是否保留小数即使是小数位是0
noSign?: boolean; // 不允许输入正负号
}
/**

View File

@ -1,80 +1,31 @@
/*
* @file \src\knock-test\KnockTest.ts
* @description
* @author tsl (randy1924@163.com)
* @date 2026-02-09 18:26:16
* @lastModified 2026-06-30 10:05:44
* @lastModifiedBy tsl (randy1924@163.com)
*/
import { debounce } from "lodash-es";
/** 操作项,定义一次敲击阶段的参数 */
export class Operation {
/** 敲击有效时长ms超过该时长未达到指定次数则重置 */
duration = 1000;
/** 当前操作完成后进入下一操作前的等待时长ms等待期间点击会重置 */
delay = 1000;
/** 当前操作需要敲击的次数 */
times = 1;
}
/** KnockTest 配置项 */
export class Config {
/** 最大等待时间ms从首次敲击开始计算超时未完成所有操作则自动重置 */
maxWaitTime = 5000;
/** 操作项列表,按顺序执行 */
operations: Operation[] = [];
}
/**
*
*
*
*
*
* - idle knocking
* - knocking wait
* - wait idle
*
* @example
* ```ts
* const kt = new KnockTest({
* maxWaitTime: 10000,
* operations: [
* { duration: 1000, delay: 500, times: 3 }, // 1秒内敲3次
* { duration: 1000, delay: 500, times: 2 }, // 然后等待0.5秒后1秒内敲2次
* ]
* })
* kt.addCallback(() => console.log('解锁成功'))
* kt.knock() // 在UI点击事件中调用
* ```
*/
export class KnockTest {
/** 配置项 */
config: Config;
/** 当前操作项索引 */
index = 0;
/** 当前阶段已敲击次数 */
times = 0;
/**
*
* - "idle" times从0开始计数duration期
* - "knocking" times达到Operation的指定次数后进入delay期
* - "wait"
* "idle"times从0开始计数duration期
* duration期间"knocking"times达到Operation的指定次数后进入delay期
* delay期间"wait"
*/
status: "idle" | "knocking" | "wait" = "idle";
/** duration 定时器 ID */
durationTimerId: number | null = null;
/** delay 定时器 ID */
delayTimerId: number | null = null;
/** 成功回调列表,所有操作完成后依次执行 */
callbackList: (() => void)[] = [];
/** 最大等待防抖函数,超时自动重置 */
maxWaitFun: () => void;
/**
* @param config 使
*/
constructor(config: Config) {
const c = new Config();
this.config = Object.assign(c, config);
@ -85,22 +36,10 @@ export class KnockTest {
}, this.config.maxWaitTime);
}
/**
*
* @param cb
*/
addCallback(cb: () => void) {
this.callbackList.push(cb);
}
/**
* UI
*
* 使 times + 1
* - idle
* - knocking
* - wait
*/
knock() {
console.log("knock");
this.maxWaitFun();
@ -121,7 +60,6 @@ export class KnockTest {
}
}
/** 重置所有状态,回到初始空闲状态并清除所有定时器 */
private reset() {
this.status = "idle";
this.times = 0;
@ -137,11 +75,6 @@ export class KnockTest {
}
}
/**
* duration
*
* @throws
*/
private handleIdle() {
if (this.config.operations.length === 0) {
throw new Error("至少添加一个操作项");
@ -159,17 +92,10 @@ export class KnockTest {
this.checkKnock();
}
/**
*
*/
private handleKnocking() {
this.checkKnock();
}
/**
*
*
*/
private checkKnock() {
const operation = this.config.operations[this.index];
@ -201,9 +127,6 @@ export class KnockTest {
}
}
/**
*
*/
private handleWait() {
if (this.delayTimerId != null) {
clearTimeout(this.delayTimerId);

View File

@ -1,54 +1,17 @@
/*
* @file \src\permission\Permission.ts
* @description
* @author tsl (randy1924@163.com)
* @date 2023-11-27 13:35:18
* @lastModified 2026-06-30 10:06:50
* @lastModifiedBy tsl (randy1924@163.com)
*/
/**
*
*
*
* "module:action:resource"使 ":" 3
*
* @example
* ```ts
* const permission = new Permission(['user:read:info', 'admin:write:config'], 3, ':')
* permission.isValid('user:read:info') // true
* permission.isValid('user:read') // false级数不足
* permission.isValid('user read info') // false分隔符不匹配
* ```
*/
export class Permission {
/** 权限字符串列表 */
/**
*
*/
list: string[];
/** 权限分隔符,默认为 ":" */
separator: string;
/** 权限级数,默认为 3如 "module:action:resource" */
level: number;
/**
* @param list
* @param level 3
* @param separator ":"
*/
constructor(list: string[], level = 3, separator = ":") {
this.list = list;
this.level = level;
this.separator = separator;
}
/**
*
*
*
* level=3separator=":" "module:action:resource" "module:action"
*
* @param str
* @returns
*/
isValid(str: string) {
const p = new Array(this.level).fill("\\w+?").join(this.separator);
// ^\w+?:\w+?:\w+?$

View File

@ -3,47 +3,20 @@ import { Duration } from "dayjs/plugin/duration";
type TimerCallback = (time: string) => void;
/**
*
*
* dayjs duration
* stepEventListener
* countdownEventListener
*
* @example
* ```ts
* const countdown = new Countdown(60000) // 60秒倒计时
* countdown.format = 'mm:ss'
* countdown.addStepEventListener((time) => console.log('剩余:', time))
* countdown.addCountdownEventListener((time) => console.log('倒计时结束:', time))
* countdown.start()
* ```
*/
export default class Countdown {
/** 定时器 ID-1 表示未运行 */
id = -1;
/** dayjs duration 对象,表示剩余时长 */
duration: Duration;
/** 输出时间格式,默认 "HH:mm:ss" */
format = "HH:mm:ss";
/**
*
*
*
*
*/
stepEventListenerList = <TimerCallback[]>[];
/**
*
*
*
*
*/
countdownEventListenerList = <TimerCallback[]>[];
/** 初始时间(毫秒),用于 restart 时重置 */
initialTime = 0;
/**
* @param time
*/
constructor(time: number) {
this.initialTime = time;
this.duration = dayjs.duration(time);
@ -51,11 +24,8 @@ export default class Countdown {
/**
*
*
*
*
* @param cb
* @returns cb TypeError
* @param cb
* @returns
*/
addStepEventListener(cb: TimerCallback) {
if (!(cb instanceof Function)) {
@ -65,12 +35,9 @@ export default class Countdown {
}
/**
*
*
*
*
* @param cb
* @returns cb TypeError
*
* @param cb
* @returns
*/
addCountdownEventListener(cb: TimerCallback) {
if (!(cb instanceof Function)) {
@ -80,7 +47,7 @@ export default class Countdown {
}
/**
*
*
*/
start() {
this.id = window.setInterval(() => {
@ -96,7 +63,7 @@ export default class Countdown {
}
/**
*
*
*/
stop() {
console.log("stop", this.id);
@ -108,7 +75,7 @@ export default class Countdown {
}
/**
*
*
*/
restart() {
clearInterval(this.id);

View File

@ -1,49 +1,19 @@
type TimerCallback = (time: number) => void;
/**
*
*
* startTime endTime
* interval endTime
*
* Countdown TimeoutTimer 使 dayjs duration
*
*
* @example
* ```ts
* // 实例方式
* const timer = new TimeoutTimer(10, 0, 1000)
* timer.addStepEventListener((time) => console.log('剩余:', time))
* timer.addCountdownEventListener((time) => console.log('结束:', time))
* timer.start()
*
* // 静态工厂方式
* const timer2 = TimeoutTimer.start(10, 0, 1000,
* (time) => console.log('剩余:', time),
* (time) => console.log('结束:', time),
* )
* ```
*/
export default class TimeoutTimer {
/** 起始时间(数值) */
startTime = 0;
/** 结束时间(数值),倒计时到此值停止 */
endTime = 0;
/** 递减间隔(毫秒) */
interval = 0;
/** 当前剩余时间 */
time = 0;
/** 定时器 ID-1 表示未运行 */
id = -1;
/** 步骤监听器列表,每次递减时触发,参数为当前剩余时间 */
stepEventListenerList = <TimerCallback[]>[];
/** 完成监听器列表,倒计时结束时触发,参数为结束时间 */
countdownEventListenerList = <TimerCallback[]>[];
/**
* @param startTime
* @param endTime 0
* @param interval 1000
*
* @param startTime
* @param endTime
* @param interval (ms)
*/
constructor(startTime = 5, endTime = 0, interval = 1000) {
this.startTime = startTime;
@ -52,12 +22,9 @@ export default class TimeoutTimer {
}
/**
*
*
*
*
* @param cb
* @returns cb TypeError
*
* @param cb
* @returns
*/
addStepEventListener(cb: TimerCallback) {
if (!(cb instanceof Function)) {
@ -67,12 +34,9 @@ export default class TimeoutTimer {
}
/**
*
*
* endTime
*
* @param cb
* @returns cb TypeError
*
* @param cb
* @returns
*/
addCountdownEventListener(cb: TimerCallback) {
if (!(cb instanceof Function)) {
@ -82,14 +46,13 @@ export default class TimeoutTimer {
}
/**
*
*
* @param startTime
* @param endTime 0
* @param interval 1000
* @param stepEventListener
* @param countdownEventListener
* @returns TimeoutTimer start
*
* @param startTime
* @param endTime
* @param interval
* @param stepEventListener
* @param countdownEventListener
* @returns
*/
static start(
startTime: number,
@ -110,7 +73,7 @@ export default class TimeoutTimer {
}
/**
* startTime endTime
*
*/
start() {
this.time = this.startTime;
@ -125,7 +88,7 @@ export default class TimeoutTimer {
}
/**
*
*
*/
stop() {
console.log("stop", this.id);

View File

@ -1,17 +1,5 @@
# @r-utils/uni-app
## 2.0.2
### Patch Changes
- 修复vue3未导出
## 2.0.1
### Patch Changes
- 修复类型问题
## 2.0.0
### Major Changes

View File

@ -1,11 +1,11 @@
# @r-utils/uni-app
仅用于 uni-app 项目的工具包封装请求、上传、NFC、蓝牙、打印、Vue3 Hooks 和常用 uni API 辅助方法。
仅用于 uni-app 项目的工具包封装请求、上传、NFC、蓝牙、打印和常用 uni API 辅助方法。
## 适用范围
- 适用于 uni-app 项目(含 uni 运行时能力)。
- 适用于需要复用请求、上传、蓝牙、NFC、打印、Vue3 Hooks 等能力的业务项目。
- 适用于需要复用请求、上传、蓝牙、NFC、打印等能力的业务项目。
## 不适用范围
@ -25,7 +25,7 @@ pnpm add @r-utils/uni-app
大多数场景推荐从根入口导入,路径简单,使用心智负担更低。
```ts
import { Request, showToast, toPromise, upload, Printer, useShare } from "@r-utils/uni-app";
import { Request, showToast, toPromise, upload, Printer } from "@r-utils/uni-app";
```
### 兼容:子路径导入
@ -39,7 +39,6 @@ import { upload } from "@r-utils/uni-app/upload";
import { Printer } from "@r-utils/uni-app/printer";
import { nfcScan } from "@r-utils/uni-app/nfc";
import { BluetoothUtils } from "@r-utils/uni-app/bluetooth-utils";
import { useShare, usePageTab, useTopSticky } from "@r-utils/uni-app/vue3";
```
## 导出模块
@ -52,7 +51,6 @@ import { useShare, usePageTab, useTopSticky } from "@r-utils/uni-app/vue3";
| `@r-utils/uni-app/printer` | 打印机相关工具 |
| `@r-utils/uni-app/nfc` | NFC 相关工具 |
| `@r-utils/uni-app/bluetooth-utils` | 蓝牙相关工具 |
| `@r-utils/uni-app/vue3` | uni-app Vue3 Hooks |
## 使用示例
@ -88,17 +86,6 @@ const request = new Request({
});
```
### 使用 Vue3 Hooks
```ts
import { useShare } from "@r-utils/uni-app/vue3";
const { getShareOptions } = useShare({
title: "页面标题",
query: { id: "1" },
});
```
## 注意事项
- 推荐优先使用根入口导入;如果需要更精确的模块边界,也可以使用子路径导入。

View File

@ -1,6 +1,6 @@
{
"name": "@r-utils/uni-app",
"version": "2.0.2",
"version": "2.0.0",
"private": false,
"description": "uni-app工具库",
"type": "module",
@ -46,11 +46,6 @@
"types": "./dist/upload/index.d.ts",
"import": "./dist/upload/index.mjs",
"require": "./dist/upload/index.cjs"
},
"./vue3": {
"types": "./dist/vue3/index.d.ts",
"import": "./dist/vue3/index.mjs",
"require": "./dist/vue3/index.cjs"
}
},
"keywords": [

View File

@ -4,4 +4,3 @@ export * from "./printer";
export * from "./request";
export * from "./uni-helper";
export * from "./upload";
export * from "./vue3";

View File

@ -1,56 +1,17 @@
/*
* @file \src\printer\index.ts
* @description
* @author tsl (randy1924@163.com)
* @date 2026-05-28 11:13:40
* @lastModified 2026-06-30 11:02:16
* @lastModifiedBy tsl (randy1924@163.com)
*/
import { wait } from "@r-utils/common";
import { BluetoothUtils, Device } from "@/bluetooth-utils";
/** 蓝牙设备完整数据,包含设备信息和所有必需的特征值 ID */
type DeviceData = Required<Device>;
/**
*
*
* BLE ESC/POS
* BLE
* size 30ms
*
* @example
* ```ts
* const printer = new Printer(device, { size: 80 })
* await printer.print(escData) // escData 为 ESC/POS 指令的 number 数组
* ```
*/
export class Printer {
/** 蓝牙设备信息,包含 deviceId、服务 ID 和特征值 ID 等 */
device: DeviceData;
/** 每次写入 BLE 的最大字节数,默认 80 */
size = 0;
/**
* @param device ID
* @param size 80
*/
constructor(device: DeviceData, { size = 80 } = {}) {
this.device = device;
this.size = size;
}
/**
*
*
*
* - App 使 BluetoothUtils.sendDataAndroid
* - BLE
*
* @param data ESC/POS
* @returns
*/
async print(data: number[]) {
console.log(
data.length,
@ -71,14 +32,6 @@ export class Printer {
return res;
}
/**
* BLE
*
* size ArrayBuffer BLE
* 30ms
*
* @param data
*/
async _print(data: number[]): Promise<void> {
const size = Math.min(data.length, this.size);
if (size === 0) {

View File

@ -1,12 +1,3 @@
/*
* @file \src\request\Request.ts
* @description uniapp请求类 alova[https://alova.js.org/zh-CN/]
* @author tsl (randy1924@163.com)
* @date 2026-05-28 11:13:40
* @lastModified 2026-06-30 10:14:09
* @lastModifiedBy tsl (randy1924@163.com)
*/
export type DataType = string | AnyObject | ArrayBuffer;
/** 请求配置 */

View File

@ -1,12 +1,3 @@
/*
* @file \src\upload\index.ts
* @description uniapp上传文件工具
* @author tsl (randy1924@163.com)
* @date 2026-05-28 11:13:40
* @lastModified 2026-06-30 10:54:55
* @lastModifiedBy tsl (randy1924@163.com)
*/
type UploadResponseData = {
originalFileName: string;
url: string;

View File

@ -1,9 +1,9 @@
/*
* @file /src/vue3/hooks/components.ts
* @description uniapp组件hook
* @description
* @author tsl (randy1924@163.com)
* @date 2026-03-19 11:11:11
* @lastModified 2026-06-30 10:55:21
* @lastModified 2026-03-26 09:16:44
* @lastModifiedBy tsl (randy1924@163.com)
*/

View File

@ -19,7 +19,6 @@ export default defineConfig({
"request/index": resolve(__dirname, "src/request/index.ts"),
"uni-helper/index": resolve(__dirname, "src/uni-helper/index.ts"),
"upload/index": resolve(__dirname, "src/upload/index.ts"),
"vue3/index": resolve(__dirname, "src/vue3/index.ts"),
},
formats: ["es", "cjs"],
fileName: (format, entryName) =>

View File

@ -1,11 +1,5 @@
# @r-utils/vue2
## 2.0.1
### Patch Changes
- 修复类型问题
## 2.0.0
### Major Changes

View File

@ -1,6 +1,6 @@
{
"name": "@r-utils/vue2",
"version": "2.0.1",
"version": "2.0.0",
"private": false,
"description": "Vue2工具库",
"type": "module",

View File

@ -1,9 +1,9 @@
/*
* @file /src/hooks/list.ts
* @description Hook
* @description
* @author tsl (randy1924@163.com)
* @date 2026-03-19 11:11:11
* @lastModified 2026-06-30 10:57:44
* @lastModified 2026-03-20 10:43:38
* @lastModifiedBy tsl (randy1924@163.com)
*/

View File

@ -1,116 +0,0 @@
/** Vue class 对象格式,键为类名,值为布尔值表示是否生效 */
type CustomClassObj = Record<string, boolean>;
/** Vue class 支持的类型:字符串、字符串数组或对象 */
type CustomClass = string | Array<string> | CustomClassObj;
/** 分解后的 Vue class 对象,所有类名值为 true */
type DistCustomClass = Record<string, true>;
/**
* Vue class
*
* `{ className: true }`
* Vue class
*
* @example
* ```ts
* createCustomClassObj('foo bar') // { foo: true, bar: true }
* createCustomClassObj(['foo', 'bar']) // { foo: true, bar: true }
* ```
*
* @param customClass
* @returns true
* @throws customClass TypeError
*/
export function createCustomClassObj(customClass: string): DistCustomClass;
export function createCustomClassObj(
customClass: Array<string>,
): DistCustomClass;
export function createCustomClassObj(
customClass: string | Array<string>,
): DistCustomClass {
let customClassObj = <DistCustomClass>{};
if (typeof customClass === "string") {
const customClassStr = customClass.trim().replace(" +", " ");
if (customClassStr.length > 0) {
const customClassEntries = customClassStr
.split(" ")
.map((name) => [name, true]);
customClassObj = Object.fromEntries(customClassEntries);
}
} else if (Array.isArray(customClass)) {
if (customClass.length > 0) {
const customClassEntries = customClass.map((name) => [name, true]);
customClassObj = Object.fromEntries(customClassEntries);
}
} else {
throw new TypeError(
`customClass只能是字符串或数组类型customClass: ${customClass}`,
);
}
return customClassObj;
}
/**
* Vue class Vue class
*
* Vue class
* `{ className: boolean }`
*
* @example
* ```ts
* convertCustomClass('foo bar') // { foo: true, bar: true }
* convertCustomClass(['foo', 'bar']) // { foo: true, bar: true }
* convertCustomClass({ foo: true, bar: false }) // { foo: true, bar: false }
* ```
*
* @param sourceClass Vue class
* @returns Vue class
* @throws sourceClass Vue class TypeError
*/
export function convertCustomClass(sourceClass: CustomClass): CustomClassObj {
let customClassObj = <CustomClassObj>{};
if (typeof sourceClass === "string") {
const customClassStr = sourceClass.trim().replace(" +", " ");
if (customClassStr.length > 0) {
const customClassEntries = customClassStr
.split(" ")
.map((name) => [name, true]);
customClassObj = Object.fromEntries(customClassEntries);
}
} else if (Array.isArray(sourceClass)) {
if (sourceClass.length > 0) {
const customClassEntries = sourceClass.map((name) => [name, true]);
customClassObj = Object.fromEntries(customClassEntries);
}
} else if (sourceClass instanceof Object) {
customClassObj = sourceClass;
} else {
throw new TypeError(
`sourceClass不是有效的vue classsourceClass: ${sourceClass}`,
);
}
return customClassObj;
}
/**
* Vue class
*
* Vue class
* class
*
* @example
* ```ts
* mergeClass('foo', ['bar'], { baz: true })
* // { foo: true, bar: true, baz: true }
* ```
*
* @param customClass Vue class
* @returns Vue class
*/
export function mergeClass(...customClass: CustomClass[]) {
return customClass
.map((cc) => convertCustomClass(cc))
.reduce((a, b) => Object.assign(a, b), {});
}

View File

@ -1,33 +1,88 @@
/*
* @file \src\vue-helper\index.ts
* @description vue3
* @author tsl (randy1924@163.com)
* @date 2026-05-28 11:13:40
* @lastModified 2026-06-30 11:00:29
* @lastModifiedBy tsl (randy1924@163.com)
*/
import { ComponentPublicInstance } from "vue";
export * from "./class-helper";
export * from "./style-helper";
type CustomClassObj = Record<string, boolean>;
type CustomClass = string | Array<string> | CustomClassObj;
type DistCustomClass = Record<string, true>;
export function createCustomClassObj(customClass: string): DistCustomClass;
export function createCustomClassObj(
customClass: Array<string>,
): DistCustomClass;
export function createCustomClassObj(
customClass: string | Array<string>,
): DistCustomClass {
let customClassObj = <DistCustomClass>{};
if (typeof customClass === "string") {
const customClassStr = customClass.trim().replace(" +", " ");
if (customClassStr.length > 0) {
const customClassEntries = customClassStr
.split(" ")
.map((name) => [name, true]);
customClassObj = Object.fromEntries(customClassEntries);
}
} else if (Array.isArray(customClass)) {
if (customClass.length > 0) {
const customClassEntries = customClass.map((name) => [name, true]);
customClassObj = Object.fromEntries(customClassEntries);
}
} else {
throw new TypeError(
`customClass只能是字符串或数组类型customClass: ${customClass}`,
);
}
return customClassObj;
}
/**
*
*
* Vue2 dispatch 沿
* componentName
*
* @example
* ```ts
* dispatch(this, 'FormComponent', 'validate', { field: 'name' })
* // 向上查找名为 FormComponent 的祖先组件,触发其 validate 事件
* ```
*
* @param thisArg
* @param componentName componentName
* @param eventName
* @param params
* vue class vue class
* @param sourceClass class
* @returns
*/
export function convertCustomClass(sourceClass: CustomClass): CustomClassObj {
let customClassObj = <CustomClassObj>{};
if (typeof sourceClass === "string") {
const customClassStr = sourceClass.trim().replace(" +", " ");
if (customClassStr.length > 0) {
const customClassEntries = customClassStr
.split(" ")
.map((name) => [name, true]);
customClassObj = Object.fromEntries(customClassEntries);
}
} else if (Array.isArray(sourceClass)) {
if (sourceClass.length > 0) {
const customClassEntries = sourceClass.map((name) => [name, true]);
customClassObj = Object.fromEntries(customClassEntries);
}
} else if (sourceClass instanceof Object) {
customClassObj = sourceClass;
} else {
throw new TypeError(
`sourceClass不是有效的vue classsourceClass: ${sourceClass}`,
);
}
return customClassObj;
}
/**
* class
* @param customClass vue class
* @returns
*/
export function mergeClass(...customClass: CustomClass[]) {
return customClass
.map((cc) => convertCustomClass(cc))
.reduce((a, b) => Object.assign(a, b), {});
}
/**
*
* @param thisArg
* @param componentName
* @param eventName
* @param params
* @returns
*/
export function dispatch(
thisArg: ComponentPublicInstance,

View File

@ -1,115 +0,0 @@
import type { CSSProperties, StyleValue } from "vue";
/**
* Vue style CSSProperties
*
*
* - value style string / CSSProperties / Array<StyleValue>
* - overrides style
*
*
* 1. style normalize overrides
* 2. overrides null / undefined / "" / false使 value
* 3.
*
* Vue normalizeStyle props customStyle
*/
export function normalizeStyle(
value: StyleValue,
overrides?: StyleValue,
): CSSProperties {
const base = toCSSProperties(value);
if (overrides == null) return base;
const over = toCSSProperties(overrides);
const result: Record<string, string | number> = {};
const allKeys = new Set([
...Object.keys(base as Record<string, unknown>),
...Object.keys(over),
]);
for (const key of allKeys) {
const overVal = (over as Record<string, unknown>)[key];
const baseVal = (base as Record<string, unknown>)[key];
if (!isEmptyStyleValue(overVal)) {
// overrides 有值,优先使用
result[key] = overVal as string | number;
} else if (!isEmptyStyleValue(baseVal)) {
// overrides 为空base 有值,使用 base
result[key] = baseVal as string | number;
}
// 两者都为空,跳过
}
return result as CSSProperties;
}
/**
* null / undefined / "" / false
*/
function isEmptyStyleValue(val: unknown): boolean {
return val == null || val === "" || val === false;
}
/**
* StyleValue CSSProperties
*/
function toCSSProperties(value: StyleValue): CSSProperties {
if (Array.isArray(value)) {
const res: CSSProperties = {};
for (let i = 0; i < value.length; i++) {
const item = value[i];
const normalized =
typeof item === "string"
? parseStringStyle(item)
: toCSSProperties(item as StyleValue);
if (normalized) {
const target = res as Record<string, string | number>;
const source = normalized as Record<string, string | number>;
for (const key in source) {
target[key] = source[key];
}
}
}
return res;
}
if (typeof value === "string") {
return parseStringStyle(value);
}
if (value != null && typeof value === "object") {
return value as CSSProperties;
}
return {};
}
/** 分号分隔正则,排除括号内的分号 */
const listDelimiterRE = /;(?![^(]*\))/;
/** 属性值分隔正则 */
const propertyDelimiterRE = /:([\s\S]+)/;
/** CSS 注释正则 */
const styleCommentRE = /\/\*[\s\S]*?\*\//g;
/**
* CSS CSSProperties
* Vue parseStringStyle
*/
function parseStringStyle(cssText: string): CSSProperties {
const ret: Record<string, string> = {};
cssText
.replace(styleCommentRE, "")
.split(listDelimiterRE)
.forEach((item) => {
if (item) {
const tmp = item.split(propertyDelimiterRE);
if (tmp.length > 1) {
ret[tmp[0].trim()] = tmp[1].trim();
}
}
});
return ret as CSSProperties;
}

View File

@ -1,134 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { dispatch } from "../src/vue-helper";
/**
* Vue ComponentPublicInstance
*/
function createMockInstance(
componentName?: string,
parent?: any,
root?: any,
) {
const instance = {
$parent: parent ?? null,
$root: root ?? null,
$options: { componentName: componentName ?? null },
$emit: vi.fn(),
};
return instance;
}
describe("dispatch", () => {
it("应在祖先组件中找到匹配的 componentName 并触发事件", () => {
const targetComponentName = "FormComponent";
const grandParent = createMockInstance(targetComponentName);
const parent = createMockInstance(undefined, grandParent, grandParent);
const thisArg = createMockInstance(undefined, parent, grandParent);
// thisArg.$parent → parent, parent.$parent → grandParent
parent.$parent = grandParent;
dispatch(thisArg, targetComponentName as any, "validate", { field: "name" });
expect(grandParent.$emit).toHaveBeenCalledWith("validate", { field: "name" });
});
it("应从直接父组件开始查找", () => {
const targetComponentName = "DirectParent";
const parent = createMockInstance(targetComponentName);
const thisArg = createMockInstance(undefined, parent, parent);
dispatch(thisArg, targetComponentName as any, "change", null);
expect(parent.$emit).toHaveBeenCalledWith("change", null);
});
it("当没有父组件且有根组件时,应从根组件开始查找", () => {
const targetComponentName = "RootComponent";
const root = createMockInstance(targetComponentName);
const thisArg = createMockInstance(undefined, null, root);
dispatch(thisArg, targetComponentName as any, "init", undefined);
expect(root.$emit).toHaveBeenCalledWith("init", undefined);
});
it("当 thisArg.$parent 和 thisArg.$root 都为 null 时,应直接返回", () => {
const thisArg = createMockInstance(undefined, null, null);
const targetComponentName = "FormComponent" as any;
// 不应抛出错误
expect(() => dispatch(thisArg, targetComponentName, "validate", {})).not.toThrow();
});
it("当找不到匹配的祖先组件时,不应触发任何事件", () => {
const grandParent = createMockInstance("OtherComponent");
const parent = createMockInstance("AnotherComponent", grandParent, grandParent);
const thisArg = createMockInstance(undefined, parent, grandParent);
dispatch(thisArg, "NonExistentComponent" as any, "validate", {});
expect(grandParent.$emit).not.toHaveBeenCalled();
expect(parent.$emit).not.toHaveBeenCalled();
});
it("应在多级父组件链中找到匹配的祖先", () => {
const targetComponentName = "GrandGrandParent";
const grandGrandParent = createMockInstance(targetComponentName);
const grandParent = createMockInstance("GrandParent", grandGrandParent, grandGrandParent);
const parent = createMockInstance("Parent", grandParent, grandGrandParent);
const thisArg = createMockInstance(undefined, parent, grandGrandParent);
dispatch(thisArg, targetComponentName as any, "submit", { data: "test" });
expect(grandGrandParent.$emit).toHaveBeenCalledWith("submit", { data: "test" });
expect(grandParent.$emit).not.toHaveBeenCalled();
expect(parent.$emit).not.toHaveBeenCalled();
});
it("找到的第一个匹配组件后,不应继续向上查找", () => {
const targetComponentName = "Parent";
const grandParent = createMockInstance(targetComponentName); // 更上层也有同名组件
const parent = createMockInstance(targetComponentName, grandParent, grandParent);
const thisArg = createMockInstance(undefined, parent, grandParent);
dispatch(thisArg, targetComponentName as any, "click", true);
// 应该触发 parent 的事件,而非 grandParent 的
expect(parent.$emit).toHaveBeenCalledWith("click", true);
expect(grandParent.$emit).not.toHaveBeenCalled();
});
it("应支持传递各种类型的参数", () => {
const parent = createMockInstance("Target");
const thisArg = createMockInstance(undefined, parent, parent);
// 字符串
dispatch(thisArg, "Target" as any, "event1", "hello");
expect(parent.$emit).toHaveBeenCalledWith("event1", "hello");
// 数字
dispatch(thisArg, "Target" as any, "event2", 42);
expect(parent.$emit).toHaveBeenCalledWith("event2", 42);
// 数组
dispatch(thisArg, "Target" as any, "event3", [1, 2, 3]);
expect(parent.$emit).toHaveBeenCalledWith("event3", [1, 2, 3]);
// undefined
dispatch(thisArg, "Target" as any, "event4", undefined);
expect(parent.$emit).toHaveBeenCalledWith("event4", undefined);
});
it("当祖先组件的 componentName 为 undefined 时,应跳过继续查找", () => {
const targetComponentName = "TargetComponent";
const grandParent = createMockInstance(targetComponentName);
// parent 没有 componentName
const parent = createMockInstance(undefined, grandParent, grandParent);
const thisArg = createMockInstance(undefined, parent, grandParent);
dispatch(thisArg, targetComponentName as any, "save", {});
expect(grandParent.$emit).toHaveBeenCalledWith("save", {});
});
});

View File

@ -1,284 +0,0 @@
import { describe, expect, it } from "vitest";
import { normalizeStyle } from "../src/vue-helper/style-helper";
describe("normalizeStyle", () => {
// ========== 单参数:纯转换 ==========
// ---------- 空值 / falsy ----------
it("应将 undefined 转为空对象", () => {
expect(normalizeStyle(undefined as any)).toEqual({});
});
it("应将 null 转为空对象", () => {
expect(normalizeStyle(null as any)).toEqual({});
});
it("应将 false 转为空对象", () => {
expect(normalizeStyle(false as any)).toEqual({});
});
// ---------- CSSProperties 对象 ----------
it("应直接返回 CSSProperties 对象", () => {
const style = { color: "red", fontSize: "14px" };
expect(normalizeStyle(style)).toEqual(style);
});
it("应保留 CSSProperties 中的数字值", () => {
const style = { zIndex: 10, opacity: 0.5 };
expect(normalizeStyle(style)).toEqual({ zIndex: 10, opacity: 0.5 });
});
it("应保留 CSS 变量", () => {
const style = { "--custom-color": "red" } as any;
expect(normalizeStyle(style)).toEqual({ "--custom-color": "red" });
});
it("空对象应返回空对象", () => {
expect(normalizeStyle({})).toEqual({});
});
// ---------- 字符串 ----------
it("应解析简单的 CSS 字符串", () => {
expect(normalizeStyle("color: red")).toEqual({ color: "red" });
});
it("应解析多条声明的 CSS 字符串", () => {
expect(normalizeStyle("color: red; font-size: 14px")).toEqual({
color: "red",
"font-size": "14px",
});
});
it("应解析带空格的 CSS 字符串", () => {
expect(normalizeStyle(" color : red ; font-size : 14px ")).toEqual({
color: "red",
"font-size": "14px",
});
});
it("应忽略空声明", () => {
expect(normalizeStyle("color: red;; font-size:14px;")).toEqual({
color: "red",
"font-size": "14px",
});
});
it("应忽略尾部分号后的空项", () => {
expect(normalizeStyle("color: red;")).toEqual({ color: "red" });
});
it("应去除 CSS 注释", () => {
expect(normalizeStyle("color: red; /* 注释 */ font-size: 14px")).toEqual({
color: "red",
"font-size": "14px",
});
});
it("应解析含 url() 的值(不拆分括号内的分号)", () => {
expect(normalizeStyle("background: url(data:image/png;base64,abc)")).toEqual({
background: "url(data:image/png;base64,abc)",
});
});
it("应解析含冒号的值(如 url 中的协议)", () => {
expect(normalizeStyle("background: url(http://example.com/img.png)")).toEqual({
background: "url(http://example.com/img.png)",
});
});
it("空字符串应返回空对象", () => {
expect(normalizeStyle("")).toEqual({});
});
// ---------- 数组 ----------
it("应合并对象数组", () => {
expect(normalizeStyle([{ color: "red" }, { fontSize: "14px" }])).toEqual({
color: "red",
fontSize: "14px",
});
});
it("应合并字符串数组", () => {
expect(normalizeStyle(["color: red", "font-size: 14px"])).toEqual({
color: "red",
"font-size": "14px",
});
});
it("应合并混合类型数组", () => {
expect(normalizeStyle(["color: red", { fontSize: "14px" }])).toEqual({
color: "red",
fontSize: "14px",
});
});
it("应处理嵌套数组", () => {
expect(normalizeStyle([["color: red", { fontSize: "14px" }], { fontWeight: "bold" }])).toEqual({
color: "red",
fontSize: "14px",
fontWeight: "bold",
});
});
it("应跳过数组中的 falsy 值", () => {
expect(normalizeStyle([null, false, undefined, { color: "red" }] as any)).toEqual({
color: "red",
});
});
it("数组中后面的属性应覆盖前面的", () => {
expect(normalizeStyle([{ color: "red" }, { color: "blue" }])).toEqual({
color: "blue",
});
});
it("空数组应返回空对象", () => {
expect(normalizeStyle([])).toEqual({});
});
// ---------- 实际使用场景 ----------
it("应处理 AppButton 典型的 customStyle 用法", () => {
// 字符串形式(旧用法兼容)
expect(normalizeStyle("color: red; font-size: 28rpx")).toEqual({
color: "red",
"font-size": "28rpx",
});
// 对象形式(推荐用法)
expect(normalizeStyle({ color: "red", fontSize: "28rpx" })).toEqual({
color: "red",
fontSize: "28rpx",
});
// 数组形式
expect(normalizeStyle([{ color: "red" }, { fontSize: "28rpx" }])).toEqual({
color: "red",
fontSize: "28rpx",
});
});
// ========== 双参数:合并覆盖 ==========
describe("合并覆盖(第二个参数)", () => {
it("不传第二个参数时,行为与单参数一致", () => {
expect(normalizeStyle({ color: "red" })).toEqual({ color: "red" });
});
it("第二个参数为 undefined 时,行为与单参数一致", () => {
expect(normalizeStyle({ color: "red" }, undefined)).toEqual({ color: "red" });
});
it("第二个参数为 null 时,行为与单参数一致", () => {
expect(normalizeStyle({ color: "red" }, null as any)).toEqual({ color: "red" });
});
it("overrides 有值的属性应覆盖 base", () => {
expect(normalizeStyle({ color: "red" }, { color: "blue" })).toEqual({ color: "blue" });
});
it("overrides 新增的属性应合并进来", () => {
expect(normalizeStyle({ color: "red" }, { fontSize: "14px" })).toEqual({
color: "red",
fontSize: "14px",
});
});
it("overrides 和 base 各有不同的属性时,应全部合并", () => {
expect(
normalizeStyle({ color: "red", padding: "8px" }, { fontSize: "14px", margin: "4px" }),
).toEqual({
color: "red",
padding: "8px",
fontSize: "14px",
margin: "4px",
});
});
// ---------- overrides 为空值时 fallback 到 base ----------
it("overrides 属性为 undefined 时应使用 base 的值", () => {
expect(normalizeStyle({ color: "red" }, { color: undefined } as any)).toEqual({
color: "red",
});
});
it("overrides 属性为 null 时应使用 base 的值", () => {
expect(normalizeStyle({ color: "red" }, { color: null } as any)).toEqual({ color: "red" });
});
it("overrides 属性为空字符串时应使用 base 的值", () => {
expect(normalizeStyle({ color: "red" }, { color: "" })).toEqual({ color: "red" });
});
it("overrides 属性为 false 时应使用 base 的值", () => {
expect(normalizeStyle({ color: "red" }, { color: false } as any)).toEqual({ color: "red" });
});
// ---------- 两者都为空时过滤属性 ----------
it("base 和 overrides 都为空时,应过滤掉该属性", () => {
expect(normalizeStyle({ color: "" }, { color: undefined } as any)).toEqual({});
});
it("base 和 overrides 都为 null 时,应过滤掉该属性", () => {
expect(normalizeStyle({ color: null } as any, { color: null } as any)).toEqual({});
});
it("base 有值但属性为空、overrides 未指定该属性时,应过滤掉", () => {
// base 有 color:"" (空值), overrides 没有 color → both empty → filtered
expect(normalizeStyle({ color: "" }, {})).toEqual({});
});
// ---------- 字符串形式的 overrides ----------
it("overrides 为字符串时应正常解析并合并", () => {
expect(normalizeStyle({ color: "red" }, "font-size: 14px")).toEqual({
color: "red",
"font-size": "14px",
});
});
it("base 为字符串、overrides 为对象时应正常合并", () => {
// 字符串解析出 kebab-case 键,对象用 camelCase 键,两者独立
expect(normalizeStyle("color: red", { fontSize: "14px" })).toEqual({
color: "red",
fontSize: "14px",
});
});
// ---------- 数组形式的 overrides ----------
it("overrides 为数组时应正常解析并合并", () => {
expect(normalizeStyle({ color: "red" }, [{ fontSize: "14px" }])).toEqual({
color: "red",
fontSize: "14px",
});
});
// ---------- 0 是有效值,不算空 ----------
it("数字 0 应视为有效值,不当作空值", () => {
expect(normalizeStyle({ opacity: 1 }, { opacity: 0 })).toEqual({ opacity: 0 });
});
it("overrides 为 0 时不应 fallback 到 base", () => {
expect(normalizeStyle({ zIndex: 10 }, { zIndex: 0 })).toEqual({ zIndex: 0 });
});
// ---------- 综合场景 ----------
it("应正确处理混合覆盖和 fallback", () => {
const base = { color: "red", fontSize: "14px", padding: "8px", margin: "" };
const overrides = { color: "blue", fontSize: undefined, padding: null, margin: "4px" } as any;
expect(normalizeStyle(base, overrides)).toEqual({
color: "blue", // overrides 有值,覆盖
fontSize: "14px", // overrides 为 undefinedfallback 到 base
padding: "8px", // overrides 为 nullfallback 到 base
margin: "4px", // base 为空overrides 有值,使用 overrides
});
});
it("appButton 场景customStyle 覆盖内部样式", () => {
// 模拟 AppButton 内部样式 + customStyle
const internal = { width: "200rpx", backgroundColor: "#3adceb", color: "#111" };
const custom = { width: "128rpx", backgroundColor: undefined, color: "" } as any;
expect(normalizeStyle(internal, custom)).toEqual({
width: "128rpx", // overrides 有值,覆盖
backgroundColor: "#3adceb", // overrides 为 undefinedfallback
color: "#111", // overrides 为空字符串fallback
});
});
});
});

View File

@ -1,187 +0,0 @@
import { describe, expect, it } from "vitest";
import {
createCustomClassObj,
convertCustomClass,
mergeClass,
} from "../src/vue-helper";
// ========== createCustomClassObj ==========
describe("createCustomClassObj", () => {
// ---------- 字符串输入 ----------
it("应将单个类名字符串转为对象", () => {
expect(createCustomClassObj("foo")).toEqual({ foo: true });
});
it("应将空格分隔的类名字符串转为对象", () => {
expect(createCustomClassObj("foo bar")).toEqual({ foo: true, bar: true });
});
it("应处理前后有空格的字符串", () => {
// trim 后 "foo bar"replace(" +"," ") 是字符串匹配不会替换连续空格
// split(" ") 产生 ["foo", "", "bar"],空字符串作为键
expect(createCustomClassObj(" foo bar ")).toEqual({ foo: true, "": true, bar: true });
});
it("应处理多个连续空格", () => {
// replace(" +", " ") 是字符串匹配而非正则,不会替换连续空格
// split(" ") 产生 ["foo", "", "", "", "bar"],重复的空字符串键只保留最后一个
expect(createCustomClassObj("foo bar")).toEqual({ foo: true, "": true, bar: true });
});
it("空字符串应返回空对象", () => {
expect(createCustomClassObj("")).toEqual({});
});
it("仅空格的字符串应返回空对象", () => {
expect(createCustomClassObj(" ")).toEqual({});
});
// ---------- 数组输入 ----------
it("应将类名数组转为对象", () => {
expect(createCustomClassObj(["foo", "bar"])).toEqual({ foo: true, bar: true });
});
it("应将单个元素的数组转为对象", () => {
expect(createCustomClassObj(["foo"])).toEqual({ foo: true });
});
it("空数组应返回空对象", () => {
expect(createCustomClassObj([])).toEqual({});
});
// ---------- 异常输入 ----------
it("传入对象应抛出 TypeError", () => {
expect(() => createCustomClassObj({} as any)).toThrow(TypeError);
});
it("传入数字应抛出 TypeError", () => {
expect(() => createCustomClassObj(123 as any)).toThrow(TypeError);
});
it("传入 null 应抛出 TypeError", () => {
expect(() => createCustomClassObj(null as any)).toThrow(TypeError);
});
it("传入 undefined 应抛出 TypeError", () => {
expect(() => createCustomClassObj(undefined as any)).toThrow(TypeError);
});
});
// ========== convertCustomClass ==========
describe("convertCustomClass", () => {
// ---------- 字符串输入 ----------
it("应将字符串转为类名对象", () => {
expect(convertCustomClass("foo bar")).toEqual({ foo: true, bar: true });
});
it("应将单个类名字符串转为对象", () => {
expect(convertCustomClass("foo")).toEqual({ foo: true });
});
it("空字符串应返回空对象", () => {
expect(convertCustomClass("")).toEqual({});
});
// ---------- 数组输入 ----------
it("应将类名数组转为对象", () => {
expect(convertCustomClass(["foo", "bar"])).toEqual({ foo: true, bar: true });
});
it("空数组应返回空对象", () => {
expect(convertCustomClass([])).toEqual({});
});
// ---------- 对象输入 ----------
it("应直接返回对象", () => {
const obj = { foo: true, bar: false };
expect(convertCustomClass(obj)).toEqual(obj);
});
it("应保留对象中值为 false 的属性", () => {
const obj = { foo: true, bar: false };
const result = convertCustomClass(obj);
expect(result).toHaveProperty("bar", false);
});
// ---------- 异常输入 ----------
it("传入数字应抛出 TypeError", () => {
expect(() => convertCustomClass(123 as any)).toThrow(TypeError);
});
it("传入 null 应抛出 TypeError", () => {
expect(() => convertCustomClass(null as any)).toThrow(TypeError);
});
it("传入 undefined 应抛出 TypeError", () => {
expect(() => convertCustomClass(undefined as any)).toThrow(TypeError);
});
it("传入布尔值应抛出 TypeError", () => {
expect(() => convertCustomClass(true as any)).toThrow(TypeError);
});
});
// ========== mergeClass ==========
describe("mergeClass", () => {
it("应合并多个字符串类名", () => {
expect(mergeClass("foo", "bar")).toEqual({ foo: true, bar: true });
});
it("应合并字符串和数组", () => {
expect(mergeClass("foo", ["bar"])).toEqual({ foo: true, bar: true });
});
it("应合并字符串、数组和对象", () => {
expect(mergeClass("foo", ["bar"], { baz: true })).toEqual({
foo: true,
bar: true,
baz: true,
});
});
it("后面的值应覆盖前面的同名属性", () => {
expect(mergeClass({ foo: true }, { foo: false })).toEqual({ foo: false });
});
it("字符串形式的类名应覆盖前面的", () => {
// "foo" → { foo: true },后者覆盖前者
expect(mergeClass("foo", "foo")).toEqual({ foo: true });
});
it("单个参数应正常工作", () => {
expect(mergeClass("foo")).toEqual({ foo: true });
});
it("应处理空字符串参数", () => {
expect(mergeClass("")).toEqual({});
});
it("应处理空数组参数", () => {
expect(mergeClass([])).toEqual({});
});
it("应处理空对象参数", () => {
expect(mergeClass({})).toEqual({});
});
it("应合并多个对象类名", () => {
expect(
mergeClass({ color: true }, { size: true }, { weight: true }),
).toEqual({ color: true, size: true, weight: true });
});
it("实际使用场景Vue 组件中合并 class", () => {
// 模拟组件内部 class + 传入 class
const internal = "btn primary";
const custom = { active: true, disabled: false };
expect(mergeClass(internal, custom)).toEqual({
btn: true,
primary: true,
active: true,
disabled: false,
});
});
});

View File

@ -1,21 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
*.local
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -1,2 +0,0 @@
public-hoist-pattern[]=*dcloudio*
shamefully-hoist=false

View File

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@ -1,78 +0,0 @@
{
"name": "@r-utils/playground-uniapp",
"private": true,
"version": "0.0.0",
"scripts": {
"dev:custom": "uni -p",
"dev:h5": "uni",
"dev:h5:ssr": "uni --ssr",
"dev:mp-alipay": "uni -p mp-alipay",
"dev:mp-baidu": "uni -p mp-baidu",
"dev:mp-jd": "uni -p mp-jd",
"dev:mp-kuaishou": "uni -p mp-kuaishou",
"dev:mp-lark": "uni -p mp-lark",
"dev:mp-qq": "uni -p mp-qq",
"dev:mp-toutiao": "uni -p mp-toutiao",
"dev:mp-harmony": "uni -p mp-harmony",
"dev:mp-weixin": "uni -p mp-weixin",
"dev:mp-xhs": "uni -p mp-xhs",
"dev:quickapp-webview": "uni -p quickapp-webview",
"dev:quickapp-webview-huawei": "uni -p quickapp-webview-huawei",
"dev:quickapp-webview-union": "uni -p quickapp-webview-union",
"build:custom": "uni build -p",
"build:h5": "uni build",
"build:h5:ssr": "uni build --ssr",
"build:mp-alipay": "uni build -p mp-alipay",
"build:mp-baidu": "uni build -p mp-baidu",
"build:mp-jd": "uni build -p mp-jd",
"build:mp-kuaishou": "uni build -p mp-kuaishou",
"build:mp-lark": "uni build -p mp-lark",
"build:mp-qq": "uni build -p mp-qq",
"build:mp-toutiao": "uni build -p mp-toutiao",
"build:mp-harmony": "uni build -p mp-harmony",
"build:mp-weixin": "uni build -p mp-weixin",
"build:mp-xhs": "uni build -p mp-xhs",
"build:quickapp-webview": "uni build -p quickapp-webview",
"build:quickapp-webview-huawei": "uni build -p quickapp-webview-huawei",
"build:quickapp-webview-union": "uni build -p quickapp-webview-union",
"type-check": "vue-tsc --noEmit",
"lint": "eslint . --fix",
"format": "prettier --write src"
},
"dependencies": {
"@dcloudio/uni-app": "3.0.0-4080420251103001",
"@dcloudio/uni-app-harmony": "3.0.0-4080420251103001",
"@dcloudio/uni-app-plus": "3.0.0-4080420251103001",
"@dcloudio/uni-components": "3.0.0-4080420251103001",
"@dcloudio/uni-h5": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-alipay": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-baidu": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-harmony": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-jd": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-kuaishou": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-lark": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-qq": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-toutiao": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-weixin": "3.0.0-4080420251103001",
"@dcloudio/uni-mp-xhs": "3.0.0-4080420251103001",
"@dcloudio/uni-quickapp-webview": "3.0.0-4080420251103001",
"@r-utils/uni-app": "workspace:^",
"@r-utils/uview-plus": "workspace:^",
"@r-utils/common": "workspace:^",
"vue": "^3.4.21",
"vue-i18n": "^9.1.9",
"vue-router": "^4.4.4"
},
"devDependencies": {
"@dcloudio/types": "^3.4.8",
"@dcloudio/uni-automator": "3.0.0-4080420251103001",
"@dcloudio/uni-cli-shared": "3.0.0-4080420251103001",
"@dcloudio/uni-stacktracey": "3.0.0-4080420251103001",
"@dcloudio/vite-plugin-uni": "3.0.0-4080420251103001",
"@vue/runtime-core": "^3.4.21",
"@vue/tsconfig": "^0.1.3",
"typescript": "^4.9.4",
"vite": "5.2.8",
"vue-tsc": "^1.0.24"
}
}

View File

@ -1,10 +0,0 @@
/// <reference types='@dcloudio/types' />
import 'vue'
declare module '@vue/runtime-core' {
type Hooks = App.AppInstance & Page.PageInstance;
interface ComponentCustomOptions extends Hooks {
}
}

View File

@ -1,13 +0,0 @@
<script setup lang="ts">
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
onLaunch(() => {
console.log("App Launch");
});
onShow(() => {
console.log("App Show");
});
onHide(() => {
console.log("App Hide");
});
</script>
<style></style>

View File

@ -1,8 +0,0 @@
/// <reference types="vite/client" />
declare module '*.vue' {
import { DefineComponent } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>
export default component
}

View File

@ -1,8 +0,0 @@
import { createSSRApp } from "vue";
import App from "./App.vue";
export function createApp() {
const app = createSSRApp(App);
return {
app,
};
}

View File

@ -1,72 +0,0 @@
{
"name" : "",
"appid" : "",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : "100",
"transformPx" : false,
/* 5+App */
"app-plus" : {
"usingComponents" : true,
"nvueStyleCompiler" : "uni-app",
"compilerVersion" : 3,
"splashscreen" : {
"alwaysShowBeforeRender" : true,
"waiting" : true,
"autoclose" : true,
"delay" : 0
},
/* */
"modules" : {},
/* */
"distribute" : {
/* android */
"android" : {
"permissions" : [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
/* ios */
"ios" : {},
/* SDK */
"sdkConfigs" : {}
}
},
/* */
"quickapp" : {},
/* */
"mp-weixin" : {
"appid" : "",
"setting" : {
"urlCheck" : false
},
"usingComponents" : true
},
"mp-alipay" : {
"usingComponents" : true
},
"mp-baidu" : {
"usingComponents" : true
},
"mp-toutiao" : {
"usingComponents" : true
},
"uniStatistics": {
"enable": false
},
"vueVersion" : "3"
}

View File

@ -1,70 +0,0 @@
{
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "@r-utils Playground"
}
},
{
"path": "pages/request/index",
"style": {
"navigationBarTitleText": "Request Demo"
}
},
{
"path": "pages/uni-helper/index",
"style": {
"navigationBarTitleText": "UniHelper Demo"
}
},
{
"path": "pages/bluetooth/index",
"style": {
"navigationBarTitleText": "Bluetooth Demo"
}
},
{
"path": "pages/nfc/index",
"style": {
"navigationBarTitleText": "NFC Demo"
}
},
{
"path": "pages/upload/index",
"style": {
"navigationBarTitleText": "Upload Demo"
}
},
{
"path": "pages/permission/index",
"style": {
"navigationBarTitleText": "Permission Demo"
}
},
{
"path": "pages/countdown/index",
"style": {
"navigationBarTitleText": "Countdown Demo"
}
},
{
"path": "pages/wait/index",
"style": {
"navigationBarTitleText": "Wait Demo"
}
},
{
"path": "pages/knock-test/index",
"style": {
"navigationBarTitleText": "KnockTest Demo"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
}
}

View File

@ -1,47 +0,0 @@
<template>
<view class="page">
<view class="section-title">BluetoothUtils 蓝牙工具 Demo</view>
<view class="demo-block">
<text class="label">蓝牙功能说明</text>
<text class="desc">BluetoothUtils 提供了蓝牙设备搜索连接数据传输等功能需要在真机上运行App 或小程序环境</text>
</view>
<view class="demo-block">
<text class="label">搜索设备</text>
<text class="code">BluetoothUtils.getDevices(cb, 3000)</text>
</view>
<view class="demo-block">
<text class="label">绑定设备</text>
<text class="code">BluetoothUtils.bindDevice(device, async () => { ... })</text>
</view>
<view class="demo-block">
<text class="label">发送数据</text>
<text class="code">BluetoothUtils.sendData(device, [0x1B, 0x40])</text>
</view>
<view class="demo-block">
<text class="label">获取 MTU</text>
<text class="code">BluetoothUtils.getBLEMTU(device)</text>
</view>
<view class="notice">
<text> 蓝牙功能需要在真机环境下测试H5 模拟器不支持</text>
</view>
</view>
</template>
<script setup lang="ts">
</script>
<style scoped>
.page { padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; color: #42b883; }
.demo-block { margin-bottom: 24rpx; padding: 20rpx; background: #f9f9f9; border-radius: 8rpx; }
.label { font-size: 28rpx; font-weight: bold; display: block; margin-bottom: 8rpx; }
.desc { font-size: 26rpx; color: #666; }
.code { font-size: 24rpx; color: #42b883; font-family: monospace; }
.notice { margin-top: 20rpx; padding: 16rpx; background: #fff3e0; border-radius: 8rpx; font-size: 24rpx; color: #e65100; }
</style>

View File

@ -1,51 +0,0 @@
<template>
<view class="page">
<view class="section-title">Countdown 倒计时 Demo</view>
<view class="demo-block">
<text class="label">倒计时: {{ timeDisplay }} ({{ status }})</text>
<view class="btn-group">
<button :disabled="status === 'running'" @click="start" size="mini">开始</button>
<button :disabled="status !== 'running'" @click="stop" size="mini">停止</button>
<button :disabled="status !== 'running'" @click="restart" size="mini">重新开始</button>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { Countdown } from '@r-utils/common'
const timeDisplay = ref('00:00:10')
const status = ref<'idle' | 'running' | 'stopped'>('idle')
let countdown: Countdown | null = null
function start() {
countdown = new Countdown(10)
countdown.addStepEventListener((t) => { timeDisplay.value = t })
countdown.addCountdownEventListener(() => { status.value = 'stopped' })
countdown.start()
status.value = 'running'
}
function stop() {
countdown?.stop()
status.value = 'stopped'
}
function restart() {
countdown?.restart()
status.value = 'running'
}
onUnmounted(() => { stop() })
</script>
<style scoped>
.page { padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; color: #42b883; }
.demo-block { margin-bottom: 24rpx; padding: 20rpx; background: #f9f9f9; border-radius: 8rpx; }
.label { font-size: 28rpx; font-weight: bold; display: block; margin-bottom: 12rpx; }
.btn-group { display: flex; gap: 16rpx; margin-top: 12rpx; }
</style>

View File

@ -1,107 +0,0 @@
<template>
<view class="content">
<view class="title">@r-utils/uni-app & @r-utils/common Playground</view>
<view class="desc">以下是各模块的使用示例点击进入独立页面</view>
<view class="section-title">@r-utils/uni-app</view>
<view class="nav-list">
<navigator url="/pages/request/index" class="nav-item">
<text class="nav-label">Request 请求封装</text>
<text class="nav-desc"> axios uni.request 封装支持拦截器</text>
</navigator>
<navigator url="/pages/uni-helper/index" class="nav-item">
<text class="nav-label">UniHelper 常用工具</text>
<text class="nav-desc">rpxToPxshowToastgetCurrentPage </text>
</navigator>
<navigator url="/pages/bluetooth/index" class="nav-item">
<text class="nav-label">BluetoothUtils 蓝牙工具</text>
<text class="nav-desc">蓝牙设备搜索连接数据传输</text>
</navigator>
<navigator url="/pages/nfc/index" class="nav-item">
<text class="nav-label">NFC NFC 功能</text>
<text class="nav-desc">NFC 标签读写</text>
</navigator>
<navigator url="/pages/upload/index" class="nav-item">
<text class="nav-label">Upload 文件上传</text>
<text class="nav-desc">uni.uploadFile 封装</text>
</navigator>
</view>
<view class="section-title" style="margin-top: 30rpx;">@r-utils/common</view>
<view class="nav-list">
<navigator url="/pages/permission/index" class="nav-item">
<text class="nav-label">Permission 权限校验</text>
<text class="nav-desc">权限字符串格式校验</text>
</navigator>
<navigator url="/pages/countdown/index" class="nav-item">
<text class="nav-label">Countdown 倒计时</text>
<text class="nav-desc">基于 dayjs 的倒计时类</text>
</navigator>
<navigator url="/pages/wait/index" class="nav-item">
<text class="nav-label">wait 等待函数</text>
<text class="nav-desc">异步等待指定时间</text>
</navigator>
<navigator url="/pages/knock-test/index" class="nav-item">
<text class="nav-label">KnockTest 敲击测试</text>
<text class="nav-desc">顺序敲击触发回调的状态机</text>
</navigator>
</view>
</view>
</template>
<script setup lang="ts">
</script>
<style>
.content {
padding: 30rpx;
}
.title {
font-size: 36rpx;
font-weight: bold;
margin-bottom: 12rpx;
}
.desc {
font-size: 26rpx;
color: #666;
margin-bottom: 40rpx;
}
.section-title {
font-size: 28rpx;
font-weight: bold;
color: #42b883;
margin-bottom: 20rpx;
padding-bottom: 8rpx;
border-bottom: 1px solid #eee;
}
.nav-list {
display: flex;
flex-direction: column;
gap: 16rpx;
margin-bottom: 20rpx;
}
.nav-item {
padding: 20rpx 24rpx;
background: #fff;
border-radius: 12rpx;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.nav-label {
display: block;
font-size: 28rpx;
font-weight: bold;
margin-bottom: 6rpx;
}
.nav-desc {
display: block;
font-size: 24rpx;
color: #888;
}
</style>

View File

@ -1,46 +0,0 @@
<template>
<view class="page">
<view class="section-title">KnockTest 敲击测试 Demo</view>
<view class="demo-block">
<text class="label">{{ message }}</text>
<text class="desc">成功次数: {{ successCount }}</text>
<button @click="knock" size="mini" style="margin-top: 12rpx">敲击 (Knock)</button>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { KnockTest } from '@r-utils/common'
const config = {
maxWaitTime: 5000,
operations: [
{ duration: 1000, delay: 500, times: 2 },
{ duration: 1000, delay: 500, times: 3 },
],
}
const knockTest = new KnockTest(config)
const message = ref('点击按钮按顺序触发敲击2次 → 等待 → 3次')
const successCount = ref(0)
knockTest.addCallback(() => {
successCount.value++
message.value = `🎉 敲击测试成功!(${successCount.value}次)`
})
function knock() {
message.value = '敲击中...'
knockTest.knock()
}
</script>
<style scoped>
.page { padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; color: #42b883; }
.demo-block { margin-bottom: 24rpx; padding: 20rpx; background: #f9f9f9; border-radius: 8rpx; }
.label { font-size: 28rpx; font-weight: bold; display: block; margin-bottom: 8rpx; }
.desc { font-size: 26rpx; color: #666; }
</style>

View File

@ -1,26 +0,0 @@
<template>
<view class="page">
<view class="section-title">NFC 功能 Demo</view>
<view class="demo-block">
<text class="label">NFC 功能说明</text>
<text class="desc">NFC 模块提供标签读写等功能需要在支持 NFC 的真机上运行</text>
</view>
<view class="notice">
<text> NFC 功能需要在真机环境下测试</text>
</view>
</view>
</template>
<script setup lang="ts">
</script>
<style scoped>
.page { padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; color: #42b883; }
.demo-block { margin-bottom: 24rpx; padding: 20rpx; background: #f9f9f9; border-radius: 8rpx; }
.label { font-size: 28rpx; font-weight: bold; display: block; margin-bottom: 8rpx; }
.desc { font-size: 26rpx; color: #666; }
.notice { margin-top: 20rpx; padding: 16rpx; background: #fff3e0; border-radius: 8rpx; font-size: 24rpx; color: #e65100; }
</style>

View File

@ -1,37 +0,0 @@
<template>
<view class="page">
<view class="section-title">Permission 权限校验 Demo</view>
<view class="demo-block">
<text class="label">格式: module:action:resource (三级冒号分隔)</text>
<input v-model="input" type="text" placeholder="输入权限字符串" class="input" @input="check" />
<text :style="{ color: isValid ? '#4caf50' : '#f44336' }" class="result">
{{ isValid ? '✓ 有效' : '✗ 无效' }}
</text>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { Permission } from '@r-utils/common'
const permissionList = ['user:read:profile', 'admin:write:config', 'invalid']
const permission = new Permission(permissionList)
const input = ref('user:read:profile')
const isValid = ref(permission.isValid(input.value))
function check() {
isValid.value = permission.isValid(input.value)
}
</script>
<style scoped>
.page { padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; color: #42b883; }
.demo-block { margin-bottom: 24rpx; padding: 20rpx; background: #f9f9f9; border-radius: 8rpx; }
.label { font-size: 28rpx; font-weight: bold; display: block; margin-bottom: 12rpx; }
.input { border: 1px solid #ddd; border-radius: 8rpx; padding: 12rpx; margin-bottom: 12rpx; font-size: 28rpx; }
.result { display: block; margin-top: 8rpx; font-size: 26rpx; }
</style>

View File

@ -1,124 +0,0 @@
<template>
<view class="page">
<view class="section-title">Request 请求封装 Demo</view>
<view class="demo-block">
<text class="label">创建 Request 实例</text>
<text class="code">const request = new Request({ baseURL: '/api' })</text>
</view>
<view class="demo-block">
<text class="label">添加请求拦截器</text>
<text class="code">request.interceptors.request.add(config => { config.header.token = 'xxx'; return config })</text>
</view>
<view class="demo-block">
<text class="label">添加响应拦截器</text>
<text class="code">request.interceptors.response.add(res => { return res.data })</text>
</view>
<view class="demo-block">
<text class="label">发送请求</text>
<text class="code">const res = await request.get('/users')</text>
</view>
<view class="demo-block">
<button @click="sendRequest" :disabled="loading">
{{ loading ? '请求中...' : '发送 GET 请求' }}
</button>
<view v-if="response" class="result">
<text>响应结果: {{ response }}</text>
</view>
<view v-if="error" class="error">
<text>请求失败: {{ error }}</text>
</view>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { Request } from '@r-utils/uni-app'
const loading = ref(false)
const response = ref('')
const error = ref('')
const request = new Request({
baseURL: 'https://jsonplaceholder.typicode.com',
})
request.interceptors.request.add((config) => {
console.log('请求拦截器:', config.url)
return config
})
request.interceptors.response.add((res) => {
console.log('响应拦截器:', res)
return res
})
async function sendRequest() {
loading.value = true
error.value = ''
response.value = ''
try {
const res = await request.get('/todos/1')
response.value = JSON.stringify(res)
} catch (e) {
error.value = String(e)
} finally {
loading.value = false
}
}
</script>
<style scoped>
.page {
padding: 30rpx;
}
.section-title {
font-size: 32rpx;
font-weight: bold;
margin-bottom: 30rpx;
color: #42b883;
}
.demo-block {
margin-bottom: 24rpx;
padding: 20rpx;
background: #f9f9f9;
border-radius: 8rpx;
}
.label {
font-size: 28rpx;
font-weight: bold;
display: block;
margin-bottom: 8rpx;
}
.code {
font-size: 24rpx;
color: #666;
font-family: monospace;
}
.result {
margin-top: 16rpx;
padding: 16rpx;
background: #e8f5e9;
border-radius: 8rpx;
font-size: 24rpx;
}
.error {
margin-top: 16rpx;
padding: 16rpx;
background: #ffebee;
border-radius: 8rpx;
font-size: 24rpx;
color: #c62828;
}
</style>

View File

@ -1,85 +0,0 @@
<template>
<view class="page">
<view class="section-title">UniHelper 工具 Demo</view>
<view class="demo-block">
<text class="label">rpxToPx rpx px</text>
<input v-model="rpxValue" type="number" placeholder="输入 rpx 值" class="input" />
<text class="result">{{ rpxValue }}rpx = {{ pxResult }}px</text>
</view>
<view class="demo-block">
<text class="label">pxToRpx px rpx</text>
<input v-model="pxValue" type="number" placeholder="输入 px 值" class="input" />
<text class="result">{{ pxValue }}px = {{ rpxResult }}rpx</text>
</view>
<view class="demo-block">
<text class="label">showToast 显示提示</text>
<view class="btn-group">
<button @click="showSuccessToast" size="mini">成功提示</button>
<button @click="showErrorToast" size="mini">错误提示</button>
<button @click="showNoneToast" size="mini">普通提示</button>
</view>
</view>
<view class="demo-block">
<text class="label">getCurrentPage 获取当前页面</text>
<text class="result">当前页面路由: {{ currentPageRoute }}</text>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { rpxToPx, pxToRpx, showToast, getCurrentPage } from '@r-utils/uni-app'
const rpxValue = ref('100')
const pxResult = computed(() => {
try {
return rpxToPx(Number(rpxValue.value))
} catch {
return '-'
}
})
const pxValue = ref('50')
const rpxResult = computed(() => {
try {
return pxToRpx(Number(pxValue.value))
} catch {
return '-'
}
})
const currentPageRoute = computed(() => {
try {
const page = getCurrentPage()
return (page as any)?.route ?? '未知'
} catch {
return 'H5 模式下可能无法获取'
}
})
function showSuccessToast() {
showToast('操作成功', 'success')
}
function showErrorToast() {
showToast('操作失败', 'error')
}
function showNoneToast() {
showToast('这是一条提示')
}
</script>
<style scoped>
.page { padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; color: #42b883; }
.demo-block { margin-bottom: 24rpx; padding: 20rpx; background: #f9f9f9; border-radius: 8rpx; }
.label { font-size: 28rpx; font-weight: bold; display: block; margin-bottom: 12rpx; }
.input { border: 1px solid #ddd; border-radius: 8rpx; padding: 12rpx; margin-bottom: 12rpx; font-size: 28rpx; }
.result { display: block; margin-top: 8rpx; font-size: 26rpx; color: #42b883; }
.btn-group { display: flex; gap: 16rpx; }
</style>

View File

@ -1,33 +0,0 @@
<template>
<view class="page">
<view class="section-title">Upload 文件上传 Demo</view>
<view class="demo-block">
<text class="label">上传功能说明</text>
<text class="desc">upload 函数封装了 uni.uploadFile支持自动解析响应数据</text>
</view>
<view class="demo-block">
<text class="label">示例代码</text>
<text class="code">import { upload } from '@r-utils/uni-app'</text>
<text class="code">const result = await upload({ url, filePath, name })</text>
</view>
<view class="notice">
<text> 文件上传需要在真机环境下测试且需要后端服务支持</text>
</view>
</view>
</template>
<script setup lang="ts">
</script>
<style scoped>
.page { padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; color: #42b883; }
.demo-block { margin-bottom: 24rpx; padding: 20rpx; background: #f9f9f9; border-radius: 8rpx; }
.label { font-size: 28rpx; font-weight: bold; display: block; margin-bottom: 8rpx; }
.desc { font-size: 26rpx; color: #666; }
.code { display: block; font-size: 24rpx; color: #42b883; font-family: monospace; margin-bottom: 4rpx; }
.notice { margin-top: 20rpx; padding: 16rpx; background: #fff3e0; border-radius: 8rpx; font-size: 24rpx; color: #e65100; }
</style>

View File

@ -1,40 +0,0 @@
<template>
<view class="page">
<view class="section-title">wait 等待函数 Demo</view>
<view class="demo-block">
<text class="label">等待时间: {{ waitTime }}ms</text>
<input v-model.number="waitTime" type="number" :min="100" :step="100" class="input" />
<button :disabled="waiting" @click="handleWait" size="mini">
{{ waiting ? '等待中...' : `等待 ${waitTime}ms` }}
</button>
<text v-if="waitDone" class="result"> 等待完成</text>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { wait } from '@r-utils/common'
const waiting = ref(false)
const waitDone = ref(false)
const waitTime = ref(2000)
async function handleWait() {
waiting.value = true
waitDone.value = false
await wait(waitTime.value)
waiting.value = false
waitDone.value = true
}
</script>
<style scoped>
.page { padding: 30rpx; }
.section-title { font-size: 32rpx; font-weight: bold; margin-bottom: 30rpx; color: #42b883; }
.demo-block { margin-bottom: 24rpx; padding: 20rpx; background: #f9f9f9; border-radius: 8rpx; }
.label { font-size: 28rpx; font-weight: bold; display: block; margin-bottom: 12rpx; }
.input { border: 1px solid #ddd; border-radius: 8rpx; padding: 12rpx; margin-bottom: 12rpx; font-size: 28rpx; }
.result { display: block; margin-top: 8rpx; font-size: 26rpx; color: #4caf50; }
</style>

View File

@ -1,6 +0,0 @@
export {}
declare module "vue" {
type Hooks = App.AppInstance & Page.PageInstance;
interface ComponentCustomOptions extends Hooks {}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

View File

@ -1,76 +0,0 @@
/**
* 这里是uni-app内置的常用样式变量
*
* uni-app 官方扩展插件及插件市场https://ext.dcloud.net.cn上很多三方插件均使用了这些样式变量
* 如果你是插件开发者建议你使用scss预处理并在插件代码中直接使用这些变量无需 import 这个文件方便用户通过搭积木的方式开发整体风格一致的App
*
*/
/**
* 如果你是App开发者插件使用者你可以通过修改这些变量来定制自己的插件主题实现自定义主题功能
*
* 如果你的项目同样使用了scss预处理你也可以直接在你的 scss 代码中使用如下变量同时无需 import 这个文件
*/
/* 颜色变量 */
/* 行为相关颜色 */
$uni-color-primary: #007aff;
$uni-color-success: #4cd964;
$uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d;
/* 文字基本颜色 */
$uni-text-color: #333; // 基本色
$uni-text-color-inverse: #fff; // 反色
$uni-text-color-grey: #999; // 辅助灰色如加载更多的提示信息
$uni-text-color-placeholder: #808080;
$uni-text-color-disable: #c0c0c0;
/* 背景颜色 */
$uni-bg-color: #fff;
$uni-bg-color-grey: #f8f8f8;
$uni-bg-color-hover: #f1f1f1; // 点击状态颜色
$uni-bg-color-mask: rgba(0, 0, 0, 0.4); // 遮罩颜色
/* 边框颜色 */
$uni-border-color: #c8c7cc;
/* 尺寸变量 */
/* 文字尺寸 */
$uni-font-size-sm: 12px;
$uni-font-size-base: 14px;
$uni-font-size-lg: 16;
/* 图片尺寸 */
$uni-img-size-sm: 20px;
$uni-img-size-base: 26px;
$uni-img-size-lg: 40px;
/* Border Radius */
$uni-border-radius-sm: 2px;
$uni-border-radius-base: 3px;
$uni-border-radius-lg: 6px;
$uni-border-radius-circle: 50%;
/* 水平间距 */
$uni-spacing-row-sm: 5px;
$uni-spacing-row-base: 10px;
$uni-spacing-row-lg: 15px;
/* 垂直间距 */
$uni-spacing-col-sm: 4px;
$uni-spacing-col-base: 8px;
$uni-spacing-col-lg: 12px;
/* 透明度 */
$uni-opacity-disabled: 0.3; // 组件禁用态的透明度
/* 文章场景相关 */
$uni-color-title: #2c405a; // 文章标题颜色
$uni-font-size-title: 20px;
$uni-color-subtitle: #555; // 二级标题颜色
$uni-font-size-subtitle: 18px;
$uni-color-paragraph: #3f536e; // 文章段落颜色
$uni-font-size-paragraph: 15px;

View File

@ -1,13 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"lib": ["esnext", "dom"],
"types": ["@dcloudio/types"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

View File

@ -1,7 +0,0 @@
import { defineConfig } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [uni()],
});

View File

@ -1,7 +0,0 @@
/// <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<object, object, unknown>;
export default component;
}

View File

@ -1,13 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@r-utils/vue2 Playground</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@ -1,24 +0,0 @@
{
"name": "@r-utils/playground-vue2",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint . --fix",
"format": "prettier --write src"
},
"dependencies": {
"@r-utils/vue2": "workspace:^",
"vue": "^2.7.16",
"vue-router": "^3.6.5"
},
"devDependencies": {
"@vitejs/plugin-vue2": "^2.0.1",
"typescript": "^5.9.3",
"vite": "^5.4.0",
"vue-tsc": "^2.2.8"
}
}

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFBD4F"></stop><stop offset="100%" stop-color="#FF9640"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -1,62 +0,0 @@
<template>
<div class="app">
<header class="header">
<router-link to="/" class="logo">@r-utils/vue2</router-link>
</header>
<main class="main">
<router-view />
</main>
</div>
</template>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, sans-serif;
background: #f5f5f5;
color: #333;
}
.app {
min-height: 100vh;
}
.header {
background: #fff;
border-bottom: 1px solid #eee;
padding: 12px 24px;
position: sticky;
top: 0;
z-index: 100;
}
.logo {
font-size: 16px;
font-weight: bold;
color: #42b883;
text-decoration: none;
}
.logo:hover {
text-decoration: underline;
}
.main {
max-width: 800px;
margin: 0 auto;
padding: 24px;
}
code {
background: #f0f0f0;
padding: 2px 6px;
border-radius: 3px;
font-size: 13px;
}
</style>

View File

@ -1,12 +0,0 @@
import Vue from "vue";
import { VisibilityPlugin } from "@r-utils/vue2";
import App from "./App.vue";
import router from "./router";
Vue.use(VisibilityPlugin);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new Vue({
router,
render: (h: any) => h(App),
} as any).$mount("#app");

View File

@ -1,24 +0,0 @@
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "index",
component: () => import("@/views/IndexPage.vue"),
},
{
path: "/visibility-plugin",
name: "visibilityPlugin",
component: () => import("@/views/VisibilityPluginDemo.vue"),
},
];
const router = new VueRouter({
mode: "history",
routes,
});
export default router;

View File

@ -1,74 +0,0 @@
<template>
<div>
<h1>Playground</h1>
<p class="desc">以下是 @r-utils/vue2 各模块的使用示例点击进入独立页面</p>
<section class="section">
<h2>@r-utils/vue2</h2>
<ul class="nav-list">
<li><router-link to="/visibility-plugin">VisibilityPlugin 页面可见性生命周期</router-link></li>
</ul>
</section>
</div>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({});
</script>
<style scoped>
h1 {
font-size: 24px;
margin-bottom: 8px;
color: #1a1a1a;
}
.desc {
color: #666;
margin-bottom: 24px;
}
.section {
margin-bottom: 24px;
}
.section h2 {
font-size: 16px;
margin-bottom: 12px;
color: #42b883;
border-bottom: 1px solid #eee;
padding-bottom: 8px;
}
.nav-list {
list-style: none;
padding: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.nav-list li {
background: #fff;
border-radius: 6px;
padding: 12px 16px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
transition: box-shadow 0.2s;
}
.nav-list li:hover {
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}
.nav-list a {
text-decoration: none;
color: #333;
font-size: 14px;
display: block;
}
.nav-list a:hover {
color: #42b883;
}
</style>

View File

@ -1,48 +0,0 @@
<template>
<div class="demo-page">
<h2 class="demo-title">VisibilityPlugin onShow / onHide</h2>
<p class="demo-desc"> Vue2 组件提供 onShow / onHide 生命周期钩子监听页面可见性变化</p>
<div class="demo-block">
<p>切换浏览器标签页可以触发 onShow / onHide 钩子</p>
<p>当前状态: <code :style="{ color: visible ? 'green' : 'red' }">{{ visible ? '✓ 可见' : '✗ 隐藏' }}</code></p>
<p>onShow 触发次数: <code>{{ showCount }}</code></p>
<p>onHide 触发次数: <code>{{ hideCount }}</code></p>
</div>
</div>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
name: "VisibilityPluginDemo",
data() {
return {
visible: true,
showCount: 0,
hideCount: 0,
};
},
// VisibilityPlugin
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onShow(this: any) {
this.visible = true;
this.showCount++;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onHide(this: any) {
this.visible = false;
this.hideCount++;
},
});
</script>
<style scoped>
.demo-block {
background: #fff;
border-radius: 8px;
padding: 20px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
</style>

View File

@ -1,11 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"types": ["vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.vue", "env.d.ts"]
}

View File

@ -1 +0,0 @@
{"root":["./src/main.ts","./src/router/index.ts","./src/app.vue","./src/views/indexpage.vue","./src/views/visibilityplugindemo.vue","./env.d.ts"],"version":"5.9.3"}

View File

@ -1,12 +0,0 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue2";
import { resolve } from "path";
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
},
});

View File

@ -1,7 +0,0 @@
/// <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<object, object, unknown>;
export default component;
}

View File

@ -1,13 +0,0 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@r-utils/vue3 Playground</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@ -1,25 +0,0 @@
{
"name": "@r-utils/playground-vue3",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint . --fix",
"format": "prettier --write src"
},
"dependencies": {
"@r-utils/common": "workspace:^",
"@r-utils/vue3": "workspace:^",
"vue": "^3.5.13",
"vue-router": "^4.5.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.0",
"typescript": "^5.9.3",
"vite": "catalog:",
"vue-tsc": "^2.2.8"
}
}

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFBD4F"></stop><stop offset="100%" stop-color="#FF9640"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -1,106 +0,0 @@
<script setup lang="ts">
</script>
<template>
<div class="app">
<header class="header">
<router-link to="/" class="logo">@r-utils/vue3 & @r-utils/common</router-link>
</header>
<main class="main">
<router-view />
</main>
</div>
</template>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, sans-serif;
background: #f5f5f5;
color: #333;
}
.app {
min-height: 100vh;
}
.header {
background: #fff;
border-bottom: 1px solid #eee;
padding: 12px 24px;
position: sticky;
top: 0;
z-index: 100;
}
.logo {
font-size: 16px;
font-weight: bold;
color: #42b883;
text-decoration: none;
}
.logo:hover {
text-decoration: underline;
}
.main {
max-width: 800px;
margin: 0 auto;
padding: 24px;
}
button {
padding: 6px 14px;
border: 1px solid #ddd;
border-radius: 4px;
background: #fff;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
}
button:hover {
background: #42b883;
color: #fff;
border-color: #42b883;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
input {
padding: 6px 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
outline: none;
}
input:focus {
border-color: #42b883;
}
code {
background: #f0f0f0;
padding: 2px 6px;
border-radius: 3px;
font-size: 13px;
}
.result {
margin-top: 8px;
padding: 8px 12px;
background: #f9f9f9;
border-radius: 4px;
font-size: 14px;
}
</style>

View File

@ -1,8 +0,0 @@
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import "./style.css";
const app = createApp(App);
app.use(router);
app.mount("#app");

View File

@ -1,71 +0,0 @@
import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/",
name: "index",
component: () => import("@/views/IndexPage.vue"),
},
// @r-utils/vue3
{
path: "/vue3/use-load-more",
name: "useLoadMore",
component: () => import("@/views/vue3/UseLoadMoreDemo.vue"),
},
{
path: "/vue3/use-timer",
name: "useTimer",
component: () => import("@/views/vue3/UseTimerDemo.vue"),
},
{
path: "/vue3/use-number-string",
name: "useNumberString",
component: () => import("@/views/vue3/UseNumberStringDemo.vue"),
},
{
path: "/vue3/use-value-of-rule",
name: "useValueOfRule",
component: () => import("@/views/vue3/UseValueOfRuleDemo.vue"),
},
{
path: "/vue3/merge-class",
name: "mergeClass",
component: () => import("@/views/vue3/MergeClassDemo.vue"),
},
// @r-utils/common
{
path: "/common/permission",
name: "permission",
component: () => import("@/views/common/PermissionDemo.vue"),
},
{
path: "/common/countdown",
name: "countdown",
component: () => import("@/views/common/CountdownDemo.vue"),
},
{
path: "/common/timeout-timer",
name: "timeoutTimer",
component: () => import("@/views/common/TimeoutTimerDemo.vue"),
},
{
path: "/common/knock-test",
name: "knockTest",
component: () => import("@/views/common/KnockTestDemo.vue"),
},
{
path: "/common/wait",
name: "wait",
component: () => import("@/views/common/WaitDemo.vue"),
},
{
path: "/common/slowly-scroll",
name: "slowlyScroll",
component: () => import("@/views/common/SlowlyScrollDemo.vue"),
},
],
});
export default router;

View File

@ -1,23 +0,0 @@
/* Demo 页面公共样式 */
.demo-page {
padding: 0;
}
.demo-title {
font-size: 20px;
margin-bottom: 8px;
color: #1a1a1a;
}
.demo-desc {
color: #666;
font-size: 14px;
margin-bottom: 16px;
}
.demo-block {
background: #fff;
border-radius: 8px;
padding: 20px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

View File

@ -1,85 +0,0 @@
<template>
<div>
<h1>Playground</h1>
<p class="desc">以下是 @r-utils/vue3 @r-utils/common 各模块的使用示例点击进入独立页面</p>
<section class="section">
<h2>@r-utils/vue3</h2>
<ul class="nav-list">
<li><router-link to="/vue3/use-load-more">useLoadMore 列表加载更多</router-link></li>
<li><router-link to="/vue3/use-timer">useTimer 倒计时</router-link></li>
<li><router-link to="/vue3/use-number-string">useNumber / useString 响应式类型转换</router-link></li>
<li><router-link to="/vue3/use-value-of-rule">useValueOfRule 按规则转换输入</router-link></li>
<li><router-link to="/vue3/merge-class">mergeClass / createCustomClassObj Vue Class 合并</router-link></li>
</ul>
</section>
<section class="section">
<h2>@r-utils/common</h2>
<ul class="nav-list">
<li><router-link to="/common/permission">Permission 权限字符串校验</router-link></li>
<li><router-link to="/common/countdown">Countdown 倒计时</router-link></li>
<li><router-link to="/common/timeout-timer">TimeoutTimer 超时计时器</router-link></li>
<li><router-link to="/common/knock-test">KnockTest 顺序敲击测试</router-link></li>
<li><router-link to="/common/wait">wait 等待函数</router-link></li>
<li><router-link to="/common/slowly-scroll">slowlyScroll 缓动滚动</router-link></li>
</ul>
</section>
</div>
</template>
<style scoped>
h1 {
font-size: 24px;
margin-bottom: 8px;
color: #1a1a1a;
}
.desc {
color: #666;
margin-bottom: 24px;
}
.section {
margin-bottom: 24px;
}
.section h2 {
font-size: 16px;
margin-bottom: 12px;
color: #42b883;
border-bottom: 1px solid #eee;
padding-bottom: 8px;
}
.nav-list {
list-style: none;
padding: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.nav-list li {
background: #fff;
border-radius: 6px;
padding: 12px 16px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
transition: box-shadow 0.2s;
}
.nav-list li:hover {
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}
.nav-list a {
text-decoration: none;
color: #333;
font-size: 14px;
display: block;
}
.nav-list a:hover {
color: #42b883;
}
</style>

View File

@ -1,50 +0,0 @@
<script setup lang="ts">
import { Countdown } from "@r-utils/common";
import { ref, onUnmounted } from "vue";
const timeDisplay = ref("00:00:10");
const status = ref<"idle" | "running" | "stopped">("idle");
let countdown: Countdown | null = null;
function start() {
countdown = new Countdown(10);
countdown.addStepEventListener((t) => {
timeDisplay.value = t;
});
countdown.addCountdownEventListener(() => {
status.value = "stopped";
});
countdown.start();
status.value = "running";
}
function stop() {
countdown?.stop();
status.value = "stopped";
}
function restart() {
countdown?.restart();
status.value = "running";
}
onUnmounted(() => {
stop();
});
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">Countdown 倒计时</h2>
<p class="demo-desc">基于 dayjs 的倒计时类支持步骤监听和完成监听</p>
<div class="demo-block">
<p>倒计时: <code>{{ timeDisplay }}</code> ({{ status }})</p>
<div style="margin-top: 8px; display: flex; gap: 8px">
<button :disabled="status === 'running'" @click="start">开始</button>
<button :disabled="status !== 'running'" @click="stop">停止</button>
<button :disabled="status !== 'running'" @click="restart">重新开始</button>
</div>
</div>
</div>
</template>

View File

@ -1,39 +0,0 @@
<script setup lang="ts">
import { KnockTest } from "@r-utils/common";
import { ref } from "vue";
const config = {
maxWaitTime: 5000,
operations: [
{ duration: 1000, delay: 500, times: 2 },
{ duration: 1000, delay: 500, times: 3 },
],
};
const knockTest = new KnockTest(config);
const message = ref("点击按钮按顺序触发敲击2次 → 等待 → 3次");
const successCount = ref(0);
knockTest.addCallback(() => {
successCount.value++;
message.value = `🎉 敲击测试成功!(${successCount.value}次)`;
});
function knock() {
message.value = "敲击中...";
knockTest.knock();
}
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">KnockTest 顺序敲击测试</h2>
<p class="demo-desc">按指定顺序敲击/点击触发回调的状态机可用于隐藏入口等场景</p>
<div class="demo-block">
<p>{{ message }}</p>
<p>成功次数: {{ successCount }}</p>
<button style="margin-top: 8px" @click="knock">敲击 (Knock)</button>
</div>
</div>
</template>

View File

@ -1,38 +0,0 @@
<script setup lang="ts">
import { Permission } from "@r-utils/common";
import { ref } from "vue";
const permissionList = ["user:read:profile", "admin:write:config", "invalid"];
const permission = new Permission(permissionList);
const input = ref("user:read:profile");
const isValid = ref(permission.isValid(input.value));
function check() {
isValid.value = permission.isValid(input.value);
}
check();
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">Permission 权限字符串校验</h2>
<p class="demo-desc">校验权限字符串是否符合指定格式 module:action:resource</p>
<div class="demo-block">
<p>格式: <code>module:action:resource</code> (三级冒号分隔)</p>
<p>
输入权限字符串:
<input v-model="input" type="text" @input="check" />
</p>
<div class="result">
<p>
校验结果:
<code :style="{ color: isValid ? 'green' : 'red' }">
{{ isValid ? "✓ 有效" : "✗ 无效" }}
</code>
</p>
</div>
</div>
</div>
</template>

View File

@ -1,49 +0,0 @@
<script setup lang="ts">
import { slowlyScroll } from "@r-utils/common";
import { ref } from "vue";
const currentValue = ref(0);
const isAnimating = ref(false);
async function animate() {
isAnimating.value = true;
await slowlyScroll(0, 500, 1000, (v) => {
currentValue.value = Math.round(v);
});
isAnimating.value = false;
}
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">slowlyScroll 缓动滚动</h2>
<p class="demo-desc">使用缓动函数(easeOutSine)从起始值缓动到结束值</p>
<div class="demo-block">
<p>当前值: <code>{{ currentValue }}</code></p>
<div class="progress-bar">
<div class="progress-fill" :style="{ width: (currentValue / 500) * 100 + '%' }"></div>
</div>
<button style="margin-top: 8px" :disabled="isAnimating" @click="animate">
{{ isAnimating ? '动画中...' : '开始缓动 (0 → 500)' }}
</button>
</div>
</div>
</template>
<style scoped>
.progress-bar {
height: 20px;
background: #f0f0f0;
border-radius: 10px;
overflow: hidden;
margin-top: 8px;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #42b883, #35495e);
border-radius: 10px;
transition: width 0.016s linear;
}
</style>

View File

@ -1,49 +0,0 @@
<script setup lang="ts">
import { TimeoutTimer } from "@r-utils/common";
import { ref, onUnmounted } from "vue";
const timeDisplay = ref("5");
const status = ref<"idle" | "running" | "stopped">("idle");
let timer: TimeoutTimer | null = null;
function start() {
timer = TimeoutTimer.start(
5,
0,
1000,
(t) => {
timeDisplay.value = String(t);
},
() => {
status.value = "stopped";
timeDisplay.value = "0";
},
);
timer.start();
status.value = "running";
}
function stop() {
timer?.stop();
status.value = "stopped";
}
onUnmounted(() => {
stop();
});
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">TimeoutTimer 超时计时器</h2>
<p class="demo-desc">可配置起始/结束时间和间隔的计时器支持静态创建</p>
<div class="demo-block">
<p>剩余: <code>{{ timeDisplay }}</code> ({{ status }})</p>
<div style="margin-top: 8px; display: flex; gap: 8px">
<button :disabled="status === 'running'" @click="start">开始 (5s)</button>
<button :disabled="status !== 'running'" @click="stop">停止</button>
</div>
</div>
</div>
</template>

View File

@ -1,34 +0,0 @@
<script setup lang="ts">
import { wait } from "@r-utils/common";
import { ref } from "vue";
const waiting = ref(false);
const waitDone = ref(false);
const waitTime = ref(2000);
async function handleWait() {
waiting.value = true;
waitDone.value = false;
await wait(waitTime.value);
waiting.value = false;
waitDone.value = true;
}
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">wait 等待函数</h2>
<p class="demo-desc">返回一个在指定时间后 resolve Promise用于异步等待</p>
<div class="demo-block">
<p>
等待时间(ms):
<input v-model.number="waitTime" type="number" :min="100" :step="100" />
</p>
<button style="margin-top: 8px" :disabled="waiting" @click="handleWait">
{{ waiting ? `等待 ${waitTime}ms 中...` : `等待 ${waitTime}ms` }}
</button>
<p v-if="waitDone" class="result"> 等待完成</p>
</div>
</div>
</template>

View File

@ -1,53 +0,0 @@
<script setup lang="ts">
import { mergeClass, createCustomClassObj } from "@r-utils/vue3";
import { ref } from "vue";
const classStr = ref("active primary");
const classArr = ref(["bold", "underline"]);
const merged = ref<Record<string, boolean>>({});
const customObj = ref<Record<string, true>>({});
function handleMerge() {
merged.value = mergeClass(classStr.value, classArr.value);
}
function handleCreate() {
customObj.value = createCustomClassObj(classStr.value);
}
handleMerge();
handleCreate();
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">mergeClass / createCustomClassObj Vue Class 合并</h2>
<p class="demo-desc">将字符串/数组形式的 Vue Class 合并为对象形式</p>
<div class="demo-block">
<p>
class 字符串:
<input v-model="classStr" type="text" />
</p>
<p>
class 数组 (逗号分隔):
<input
:value="classArr.join(',')"
type="text"
@input="
classArr = ($event.target as HTMLInputElement).value.split(',')
"
/>
</p>
<div style="margin-top: 8px; display: flex; gap: 8px">
<button @click="handleMerge">mergeClass</button>
<button @click="handleCreate">createCustomClassObj</button>
</div>
<div class="result">
<p>mergeClass: <code>{{ JSON.stringify(merged) }}</code></p>
<p>createCustomClassObj: <code>{{ JSON.stringify(customObj) }}</code></p>
</div>
</div>
</div>
</template>

View File

@ -1,58 +0,0 @@
<script setup lang="ts">
import { useLoadMore } from "@r-utils/vue3";
//
const mockFetch = (pageNum: number, pageSize: number) => {
return new Promise<{ total: number; list: string[] }>((resolve) => {
setTimeout(() => {
const total = 35;
const start = (pageNum - 1) * pageSize;
const end = Math.min(start + pageSize, total);
const list = Array.from({ length: end - start }, (_, i) =>
`Item ${start + i + 1}`,
);
resolve({ total, list });
}, 500);
});
};
const { list, total, status, isLoading, isFinished, loadMore, initList } =
useLoadMore(mockFetch, { pageSize: 10 });
//
initList();
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">useLoadMore 列表加载更多</h2>
<p class="demo-desc">分页加载列表数据的组合式 API支持加载更多重置加载状态管理</p>
<div class="demo-block">
<p>总数: {{ total }}当前: {{ list.length }} </p>
<p>状态: {{ status }}加载中: {{ isLoading }}已完成: {{ isFinished }}</p>
<ul class="list">
<li v-for="(item, index) in list" :key="index">{{ item }}</li>
</ul>
<div style="margin-top: 8px; display: flex; gap: 8px">
<button :disabled="isLoading" @click="loadMore">加载更多</button>
<button @click="initList">重置</button>
</div>
</div>
</div>
</template>
<style scoped>
.list {
list-style: none;
padding: 0;
}
.list li {
padding: 4px 0;
font-size: 14px;
border-bottom: 1px solid #f0f0f0;
}
</style>

View File

@ -1,28 +0,0 @@
<script setup lang="ts">
import { useNumber, useString } from "@r-utils/vue3";
import { ref } from "vue";
const rawValue = ref("42.5");
const { number, int, float } = useNumber(rawValue);
const { string } = useString(rawValue);
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">useNumber / useString 响应式类型转换</h2>
<p class="demo-desc">将响应式变量在 number string 之间双向转换</p>
<div class="demo-block">
<p>
原始值:
<input v-model="rawValue" type="text" />
</p>
<div class="result">
<p>useNumber number: <code>{{ number }}</code></p>
<p>useNumber int: <code>{{ int }}</code></p>
<p>useNumber float: <code>{{ float }}</code></p>
<p>useString string: <code>{{ string }}</code></p>
</div>
</div>
</div>
</template>

View File

@ -1,23 +0,0 @@
<script setup lang="ts">
import { useTimer } from "@r-utils/vue3";
import { ref } from "vue";
const initTime = ref(10);
const { time, start, restart, stop } = useTimer(initTime.value);
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">useTimer 倒计时</h2>
<p class="demo-desc">简单的倒计时 Hook支持开始重新开始停止</p>
<div class="demo-block">
<p>倒计时: <code>{{ time }}s</code></p>
<div style="margin-top: 8px; display: flex; gap: 8px">
<button @click="start">开始</button>
<button @click="restart">重新开始</button>
<button @click="stop">停止</button>
</div>
</div>
</div>
</template>

View File

@ -1,37 +0,0 @@
<script setup lang="ts">
import { useValueOfRule } from "@r-utils/vue3";
import { ref } from "vue";
const inputValue = ref("42.5");
const rule = ref({ min: 0, max: 99999.99, digits: 2, required: true });
const { value, rule: ruleRef, handleChange } = useValueOfRule({
value: inputValue,
rule: rule.value,
});
function apply() {
handleChange();
}
</script>
<template>
<div class="demo-page">
<h2 class="demo-title">useValueOfRule 按规则转换输入</h2>
<p class="demo-desc">根据自定义规则min/max/digits/integer 限制和转换输入值</p>
<div class="demo-block">
<p>
输入值:
<input v-model="inputValue" type="text" @blur="apply" />
</p>
<p style="margin-top: 8px; font-size: 13px; color: #666">
规则: min=0, max=99999.99, digits=2, required=true
</p>
<button style="margin-top: 8px" @click="apply">应用规则</button>
<div class="result">
<p>转换结果: <code>{{ value }}</code></p>
</div>
</div>
</div>
</template>

View File

@ -1,11 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"types": ["vite/client"]
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "env.d.ts"]
}

View File

@ -1 +0,0 @@
{"root":["./src/main.ts","./src/router/index.ts","./src/app.vue","./src/views/indexpage.vue","./src/views/common/countdowndemo.vue","./src/views/common/knocktestdemo.vue","./src/views/common/permissiondemo.vue","./src/views/common/slowlyscrolldemo.vue","./src/views/common/timeouttimerdemo.vue","./src/views/common/waitdemo.vue","./src/views/vue3/mergeclassdemo.vue","./src/views/vue3/useloadmoredemo.vue","./src/views/vue3/usenumberstringdemo.vue","./src/views/vue3/usetimerdemo.vue","./src/views/vue3/usevalueofruledemo.vue","./env.d.ts"],"version":"5.9.3"}

View File

@ -1,12 +0,0 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
},
});

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,5 @@
packages:
- packages/**
- playground/**
catalog:
"webpack": ^5.80.0