feat(all): 新增工具

This commit is contained in:
CodiceFabbrica 2026-05-28 11:30:35 +08:00
parent 5dbedcaf0f
commit 3a55edfafc
85 changed files with 2902 additions and 2591 deletions

8
.changeset/README.md Normal file
View File

@ -0,0 +1,8 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets).
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md).

11
.changeset/config.json Normal file
View File

@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.1.4/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"ignore": []
}

2
.gitignore vendored
View File

@ -1,4 +1,6 @@
node_modules
dist
coverage
.turbo
.changeset/pre.json
*.bak

View File

@ -1,7 +1,6 @@
# the name by which the project can be referenced within Serena
project_name: "r-util-js"
# list of languages for which language servers are started; choose from:
# al bash clojure cpp csharp
# csharp_omnisharp dart elixir elm erlang
@ -26,7 +25,7 @@ project_name: "r-util-js"
# The first language is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
languages:
- typescript
- typescript
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
@ -67,7 +66,7 @@ read_only: false
# This extends the existing exclusions (e.g. from the global configuration)
#
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project by name.

View File

@ -1,9 +0,0 @@
{
"bumpFiles": [
{ "filename": "package.json", "type": "json" },
{ "filename": "packages/common/package.json", "type": "json" },
{ "filename": "packages/vue3/package.json", "type": "json" },
{ "filename": "packages/uni-app/package.json", "type": "json" },
{ "filename": "packages/vue2/package.json", "type": "json" }
]
}

View File

@ -1,10 +1,10 @@
{
"recommendations": [
"psioniq.psi-header",
"aaron-bond.better-comments",
"streetsidesoftware.code-spell-checker",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"editorconfig.editorconfig"
]
"recommendations": [
"psioniq.psi-header",
"aaron-bond.better-comments",
"streetsidesoftware.code-spell-checker",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"editorconfig.editorconfig"
]
}

View File

@ -28,11 +28,6 @@
}
],
"workbench.editor.limit.value": 3,
"cSpell.words": [
"Codice",
"commitlint",
"dcloudio",
"Fabbrica"
],
"cSpell.words": ["Codice", "commitlint", "dcloudio", "Fabbrica"],
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
}

128
AGENTS.md Normal file
View File

@ -0,0 +1,128 @@
# AGENTS.md
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
## 项目概述
这是一个前端工具库 monorepo使用 **pnpm workspace + turbo** 管理,包含以下子包:
| 包名 | 路径 | 描述 |
|------|------|------|
| `@r-utils/common` | `packages/common` | 通用 JS/TS 工具库(不依赖框架) |
| `@r-utils/vue3` | `packages/vue3` | Vue3 专用工具 |
| `@r-utils/uni-app` | `packages/uni-app` | uni-app 专用工具 |
| `@r-utils/vue2` | `packages/vue2` | Vue2 专用工具 |
## 常用命令
### 构建
```bash
# 构建所有包
pnpm build
# 构建单个包Turbo filter
pnpm build -- --filter=@r-utils/common
# 构建单个包(在包目录内)
cd packages/common && pnpm build
```
> `@r-utils/common` 同时有 `webpack.config.js``rollup.config.js`,当前 `build` 脚本使用 webpackrollup 配置备用。
### 测试
```bash
# 在根目录运行所有测试
pnpm test
# 运行单个测试文件
pnpm vitest run packages/common/test/permission.test.ts
```
测试文件位于各包的 `test/` 目录下,使用 Vitest。
### 代码检查与格式化
```bash
# Lint从根目录仅检查 src 目录)
pnpm lint
# 格式化
pnpm format
```
ESLint 使用 v9 flat config`eslint.config.js`),已整合 TypeScript 和 Prettier 规则。
### Git 提交
```bash
# 使用 commitizen 提交(遵循 conventional commits 规范)
pnpm commit
```
**注意**:提交时 husky pre-commit 钩子会自动运行 lint-staged 和 `pnpm test`commit-msg 钩子会用 commitlint 校验提交信息格式。
### 发布
发布分四步:先记录 changeset再校验与构建、更新版本最后通过 `package.json` 命令发布。
```bash
# 1. 记录变更
pnpm changeset
# 2. 质量检查与构建
pnpm release:check
# 3. 版本管理(更新受影响包版本号 + 生成 CHANGELOG
pnpm release
# 4. 发布到 npm
pnpm release:publish
```
也可以使用一键命令:
```bash
pnpm release:all
```
changesets 配置见 `.changeset/config.json`,完整发布说明见 `docs/RELEASE.md`
## 架构说明
### Monorepo 结构
- 根 `package.json` 定义 devDependencies构建工具、ESLint、Vitest 等),各子包在自身 `package.json` 中声明运行时依赖
- `@r-utils/uni-app` 通过 `workspace:^` 依赖 `@r-utils/common`;其他包目前通过 `file:` 本地路径引用
- 每个包均输出 ES 模块格式,入口为 `dist/index.js`,类型声明在 `dist/index.d.ts`
### 构建工具
- 各包使用 **webpack 5** + **ts-loader** 进行构建,输出 ES module`experiments.outputModule: true`
- TypeScript 配置:`target: esnext`、`strict: true`、路径别名 `@` 指向 `src/`
### `@r-utils/common` 模块结构
```
src/
├── permission/ Permission 类:权限字符串格式校验(如 "module:action:resource"
├── timer/ Countdown倒计时、TimeoutTimer
├── printer/ ESC 打印工具PrintUtil 继承自 JpPrinteresc.js
├── knock-test/ KnockTest按顺序敲击/点击触发回调的状态机
└── time/ 时间工具函数
```
### `@r-utils/uni-app` 主要模块
- `request/Request.ts`:类 axios 的 uni.request 封装,支持请求/响应拦截器
- `uni-helper.ts`uni-app 常用工具scanCode、toPromise、rpxToPx、pathToBase64、Canvas 工具等)
- `bluetooth-utils/`、`nfc/`、`printer/`蓝牙、NFC、打印机功能
### `@r-utils/vue3`
- `vue-helper.ts`Vue class 处理工具(`mergeClass`、`createCustomClassObj`)、`dispatch` 祖先组件事件
### `@r-utils/vue2`
- `plugins/visibility.js`Vue2 mixin 插件,为组件提供 `onShow`/`onHide` 生命周期钩子

View File

@ -1,6 +1,6 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
All notable changes to this project will be documented in this file. Versioning is managed by `changesets`.
## [1.3.0](https://gitee.com/codice_fabbrica/r-util-js/compare/v1.2.1...v1.3.0) (2026-04-20)

View File

@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## 项目概述
这是一个前端工具库 monorepo使用 **pnpm workspace** 管理,包含以下子包:
这是一个前端工具库 monorepo使用 **pnpm workspace + turbo** 管理,包含以下子包:
| 包名 | 路径 | 描述 |
|------|------|------|
@ -21,6 +21,9 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
# 构建所有包
pnpm build
# 构建单个包Turbo filter
pnpm build -- --filter=@r-utils/common
# 构建单个包(在包目录内)
cd packages/common && pnpm build
```
@ -34,10 +37,10 @@ cd packages/common && pnpm build
pnpm test
# 运行单个测试文件
npx jest packages/common/test/permission.test.ts
pnpm vitest run packages/common/test/permission.test.ts
```
测试文件位于各包的 `test/` 目录下,使用 Jest + Babel
测试文件位于各包的 `test/` 目录下,使用 Vitest
### 代码检查与格式化
@ -58,29 +61,39 @@ ESLint 使用 v9 flat config`eslint.config.js`),已整合 TypeScript 和
pnpm commit
```
**注意**:提交时 husky pre-commit 钩子会自动运行 lint-staged 和 jest 测试commit-msg 钩子会用 commitlint 校验提交信息格式。
**注意**:提交时 husky pre-commit 钩子会自动运行 lint-staged 和 `pnpm test`commit-msg 钩子会用 commitlint 校验提交信息格式。
### 发布
发布分两步:先用 `standard-version` 管理版本,再用脚本构建和发布。
发布分四步:先记录 changeset再校验与构建、更新版本最后通过 `package.json` 命令发布。
```bash
# 1. 版本管理(更新版本号 + 生成 CHANGELOG + git commit/tag
pnpm release # 默认 patch
npx standard-version --release-as minor # 指定版本类型
# 1. 记录变更
pnpm changeset
# 2. 构建并发布到 npm
bash scripts/publish.sh # Linux/macOS
powershell scripts/publish.ps1 # Windows
# 2. 质量检查与构建
pnpm release:check
# 3. 版本管理(更新受影响包版本号 + 生成 CHANGELOG
pnpm release
# 4. 发布到 npm
pnpm release:publish
```
版本配置见 `.versionrc.json`,会同步更新根包和所有子包的版本号。
也可以使用一键命令:
```bash
pnpm release:all
```
changesets 配置见 `.changeset/config.json`,完整发布说明见 `docs/RELEASE.md`
## 架构说明
### Monorepo 结构
- 根 `package.json` 定义 devDependencies构建工具、ESLint、Jest 等),各子包在自身 `package.json` 中声明运行时依赖
- 根 `package.json` 定义 devDependencies构建工具、ESLint、Vitest 等),各子包在自身 `package.json` 中声明运行时依赖
- `@r-utils/uni-app` 通过 `workspace:^` 依赖 `@r-utils/common`;其他包目前通过 `file:` 本地路径引用
- 每个包均输出 ES 模块格式,入口为 `dist/index.js`,类型声明在 `dist/index.d.ts`

View File

@ -1,6 +1,6 @@
# r-utils
前端工具库 monorepo使用 pnpm workspace 管理Vite 构建。
前端工具库 monorepo使用 pnpm workspace + Turbo 管理任务Vite 构建。
## 包列表
@ -15,7 +15,7 @@
## 环境要求
- Node.js >= 18.12.0
- pnpm >= 8.15.6
- pnpm >= 10.0.0
## 安装依赖
@ -31,6 +31,14 @@ pnpm install
pnpm build
```
Turbo 会自动按依赖拓扑排序构建(例如 `@r-utils/common` 会先于依赖它的包构建),并复用缓存加速重复任务。
### 构建单个包Turbo 过滤)
```bash
pnpm build -- --filter=@r-utils/common
```
### 构建单个包
```bash
@ -52,8 +60,11 @@ dist/
### 监听模式
```bash
cd packages/common
pnpm watch
# 监听所有包
pnpm build:watch
# 仅监听单个包
pnpm build:watch -- --filter=@r-utils/common
```
## 使用方式
@ -114,7 +125,7 @@ const { Permission } = require('@r-utils/common');
pnpm test
# 运行单个测试文件
npx jest packages/common/test/permission.test.ts
pnpm vitest run packages/common/test/permission.test.ts
```
### 代码检查与格式化
@ -136,50 +147,27 @@ pnpm commit
提交时 husky 会自动运行:
- `lint-staged` - 代码检查和格式化
- `jest` - 单元测试
- `pnpm test`Vitest - 单元测试
- `commitlint` - 提交信息格式校验
详细说明请参考 [提交规范指南](./docs/COMMIT_GUIDE.md)。
## 发布
### 1. 版本管理standard-version
发布流程已提取到独立文档:[发布流程](./docs/RELEASE.md)。
使用 `standard-version` 更新版本号、生成 CHANGELOG、创建 Git commit 和 tag。版本配置见 `.versionrc.json`,会同步更新根包和所有子包的版本号。
常用命令:
```bash
# 默认 patch 版本
pnpm release
# 指定版本类型
npx standard-version --release-as minor # 1.0.0 -> 1.1.0
npx standard-version --release-as major # 1.0.0 -> 2.0.0
pnpm changeset # 记录变更
pnpm release:check # 测试 + 构建
pnpm release # 更新版本号与 CHANGELOG
pnpm release:publish # 发布到 npm 仓库
pnpm release:all # 一键执行检查 + 版本更新 + 发布
```
### 2. 构建并发布到私有 npm 仓库
项目已配置发布到私有 npm 仓库 `http://npm.nps.yunvip123.cn`
#### Windows (PowerShell)
```powershell
powershell scripts/publish.ps1
```
#### Linux/macOS (Bash)
```bash
bash scripts/publish.sh
```
发布脚本会自动执行以下步骤:
1. 检查 Git 工作区状态
2. 运行测试(确保代码质量)
3. 构建所有子包
4. 依次发布 `@r-utils/common`、`@r-utils/vue3`、`@r-utils/uni-app`、`@r-utils/vue2`
5. 询问是否推送到远程仓库
### 安装已发布的包
```bash

View File

@ -59,8 +59,10 @@ module.exports = {
prompt: {
useEmoji: true,
emojiAlign: "center",
allowCustomIssuePrefix: false,
allowEmptyIssuePrefix: false,
allowCustomIssuePrefix: true,
allowEmptyIssuePrefix: true,
emptyIssuePrefixAlias: "跳过",
customIssuePrefixAlias: "自定义",
// 定义 scope 选项
scopes: [
{ value: "common", name: "common: @r-utils/common 包" },
@ -75,39 +77,67 @@ module.exports = {
// 破坏性变更默认跳过;如需声明可手动在提交信息中添加 BREAKING CHANGE
allowBreakingChanges: [],
messages: {
type: '选择你要提交的类型:',
scope: '选择一个提交范围(可选):',
customScope: '请输入自定义范围:',
subject: '请简短描述这次改动:\n',
type: "选择你要提交的类型:",
scope: "选择一个提交范围(可选):",
customScope: "请输入自定义范围:",
subject: "请简短描述这次改动:\n",
body: '请详细描述这次改动(可选,用 "|" 换行):\n',
breaking: '是否有破坏性变更(可选,用 "|" 换行):\n',
footerPrefixesSelect: '选择关联的 ISSUE 类型(可选):',
customFooterPrefix: '输入 ISSUE 前缀:',
footer: '列出关联的 ISSUE如: #31, #34:\n',
generatingByAI: '正在通过 AI 生成提交信息...',
generatedSelectByAI: '选择一个 AI 生成的 subject:',
confirmCommit: '是否确认提交以上信息?',
footerPrefixesSelect: "选择关联的 ISSUE 类型(可选):",
customFooterPrefix: "输入 ISSUE 前缀:",
footer: "列出关联的 ISSUE如: #31, #34:\n",
generatingByAI: "正在通过 AI 生成提交信息...",
generatedSelectByAI: "选择一个 AI 生成的 subject:",
confirmCommit: "是否确认提交以上信息?",
},
// subject 最小长度提示(中文化 "[x more chars needed]"
minSubjectLength: 4,
defaultSubject: '',
defaultSubject: "",
types: [
{ value: 'feat', name: 'feat: 新增功能', emoji: ':sparkles:' },
{ value: 'fix', name: 'fix: 修复缺陷', emoji: ':bug:' },
{ value: 'docs', name: 'docs: 文档变更', emoji: ':memo:' },
{ value: 'style', name: 'style: 代码格式(不影响逻辑)', emoji: ':lipstick:' },
{ value: 'refactor', name: 'refactor: 重构(既非新功能,也不是修 bug', emoji: ':recycle:' },
{ value: 'perf', name: 'perf: 性能优化', emoji: ':zap:' },
{ value: 'test', name: 'test: 添加或修改测试', emoji: ':white_check_mark:' },
{ value: 'build', name: 'build: 构建系统或外部依赖变更', emoji: ':package:' },
{ value: 'ci', name: 'ci: CI 配置文件和脚本变更', emoji: ':ferris_wheel:' },
{ value: 'chore', name: 'chore: 其它不修改 src 或测试的改动', emoji: ':hammer:' },
{ value: 'revert', name: 'revert: 回退之前的 commit', emoji: ':rewind:' },
{ value: "feat", name: "feat: 新增功能", emoji: ":sparkles:" },
{ value: "fix", name: "fix: 修复缺陷", emoji: ":bug:" },
{ value: "docs", name: "docs: 文档变更", emoji: ":memo:" },
{
value: "style",
name: "style: 代码格式(不影响逻辑)",
emoji: ":lipstick:",
},
{
value: "refactor",
name: "refactor: 重构(既非新功能,也不是修 bug",
emoji: ":recycle:",
},
{ value: "perf", name: "perf: 性能优化", emoji: ":zap:" },
{
value: "test",
name: "test: 添加或修改测试",
emoji: ":white_check_mark:",
},
{
value: "build",
name: "build: 构建系统或外部依赖变更",
emoji: ":package:",
},
{
value: "ci",
name: "ci: CI 配置文件和脚本变更",
emoji: ":ferris_wheel:",
},
{
value: "chore",
name: "chore: 其它不修改 src 或测试的改动",
emoji: ":hammer:",
},
{
value: "revert",
name: "revert: 回退之前的 commit",
emoji: ":rewind:",
},
],
// issue 前缀也可以用中文说明
issuePrefixs: [
{ value: 'link', name: 'link: 关联 ISSUE' },
{ value: 'close', name: 'close: 关闭 ISSUE' },
{ value: "link", name: "link: 关联 ISSUE" },
{ value: "close", name: "close: 关闭 ISSUE" },
],
},
};

View File

@ -5,7 +5,7 @@
## 开发环境要求
- Node.js >= 18.12.0
- pnpm 8.15.6
- pnpm >= 10.0.0
## 快速开始
@ -40,7 +40,7 @@ git checkout -b fix/your-bug-fix
### 3. 开发与测试
```bash
# 构建所有包
# 构建所有包Turbo
pnpm build
# 运行测试
@ -162,7 +162,7 @@ git push origin feat/your-feature-name
### JavaScript/TypeScript
- 使用 ESLint + Prettier 进行代码检查和格式化
- 遵循项目的 `.eslintrc` 配置
- 遵循项目的 `eslint.config.js`ESLint Flat Config
- 提交前运行 `pnpm lint``pnpm format`
### 测试
@ -170,7 +170,7 @@ git push origin feat/your-feature-name
- 为新功能编写单元测试
- 确保所有测试通过: `pnpm test`
- 测试文件放在各包的 `test/` 目录下
- 使用 Jest 作为测试框架
- 使用 Vitest 作为测试框架
### 文档
@ -187,20 +187,20 @@ r-util-js/
│ ├── vue3/ # Vue3 工具
│ ├── vue2/ # Vue2 工具
│ └── uni-app/ # uni-app 工具
├── scripts/ # 构建和发布脚本
└── docs/ # 文档
```
## 发布流程
发布由维护者负责,使用 `standard-version` 自动生成版本号和 CHANGELOG:
发布由维护者负责,详细流程请查看 [发布流程文档](./RELEASE.md)。
常用命令:
```bash
# 生成版本和 CHANGELOG
pnpm changeset
pnpm release:check
pnpm release
# 发布到 npm
pnpm publish -r
pnpm release:publish
```
## 需要帮助?

65
docs/RELEASE.md Normal file
View File

@ -0,0 +1,65 @@
# 发布流程
本文档描述维护者发布 `@r-utils` monorepo 包的标准流程。
## 前置条件
- Node.js >= 18.12.0
- pnpm >= 10.0.0
- 已登录目标 npm 仓库(默认使用各包 `publishConfig.registry`
```bash
pnpm install
```
## 推荐发布流程(分步)
### 1. 记录变更changeset
```bash
pnpm changeset
pnpm changeset:status
```
### 2. 质量检查与构建
```bash
pnpm release:check
```
`release:check` 会依次执行:
- `pnpm test`
- `pnpm build`
### 3. 更新版本号与 CHANGELOG
```bash
pnpm release
```
该命令等价于 `changeset version`,会更新受影响包版本及 changelog。
### 4. 发布到 npm 仓库
```bash
pnpm release:publish
```
该命令等价于 `changeset publish`
## 一键发布(维护者)
```bash
pnpm release:all
```
`release:all` 会按顺序执行:
1. `pnpm release:check`
2. `pnpm release`
3. `pnpm release:publish`
## 发布后建议
发布完成后,手动提交并推送版本相关变更与 tag。

View File

@ -6,7 +6,7 @@ import globals from "globals";
import importPlugin from "eslint-plugin-import-x";
export default [
// 应用推荐规则
// 应用推荐规则
js.configs.recommended,
...ts.configs.recommended,
prettier,
@ -40,7 +40,13 @@ export default [
settings: {
"import-x/resolver": {
typescript: {
project: "tsconfig.eslint.json",
project: [
"packages/common/tsconfig.json",
"packages/uni-app/tsconfig.json",
"packages/uview-plus/tsconfig.json",
"packages/vue2/tsconfig.json",
"packages/vue3/tsconfig.json",
],
},
node: true,
},
@ -61,7 +67,7 @@ export default [
rules: {
...importPlugin.flatConfigs.recommended.rules,
// Prettier 规则
// Prettier 规则
"prettier/prettier": "warn",
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
@ -110,4 +116,20 @@ export default [
},
},
},
// uni-app / App-Plus 运行时全局变量
{
files: [
"packages/uni-app/**/*.{js,ts}",
"packages/common/src/printer/**/*.{js,ts}",
],
languageOptions: {
globals: {
uni: "readonly",
plus: "readonly",
wx: "readonly",
getCurrentPages: "readonly",
},
},
},
];

View File

@ -37,11 +37,18 @@
],
"scripts": {
"preinstall": "npx only-allow pnpm",
"build": "pnpm -r run build",
"build": "turbo run build --filter=./packages/*",
"build:watch": "turbo run watch --filter=./packages/* --parallel",
"typecheck": "turbo run typecheck --filter=./packages/* --concurrency=1",
"prepare": "husky install",
"lint": "eslint --fix packages/*/src",
"format": "prettier --write packages/*/src",
"release": "standard-version",
"lint": "turbo run lint --filter=./packages/*",
"format": "turbo run format --filter=./packages/*",
"changeset": "changeset",
"release": "changeset version",
"changeset:status": "changeset status --verbose",
"release:check": "pnpm test && pnpm build",
"release:publish": "changeset publish",
"release:all": "pnpm release:check && pnpm release && pnpm release:publish",
"commit": "cz",
"lint-staged": "lint-staged",
"test": "vitest run",
@ -49,6 +56,7 @@
"test:coverage": "vitest run --coverage"
},
"devDependencies": {
"@changesets/cli": "^2.31.0",
"@commitlint/config-conventional": "^20.5.0",
"@eslint/js": "^10.0.1",
"@typescript-eslint/eslint-plugin": "^8.57.1",
@ -66,14 +74,14 @@
"husky": "^9.1.7",
"inquirer": "^9.3.8",
"lint-staged": "^16.4.0",
"vitest": "catalog:",
"prettier": "^3.8.1",
"standard-version": "^9.5.0",
"tslib": "^2.8.1",
"turbo": "^2.9.6",
"typescript": "^5.9.3",
"typescript-eslint": "^8.57.1",
"vite": "^8.0.0",
"vite-plugin-dts": "^4.5.4"
"vite-plugin-dts": "^4.5.4",
"vitest": "catalog:"
},
"overrides": {
"@types/lodash": "4.17.16",

View File

@ -0,0 +1,7 @@
# @r-utils/common
## 1.4.0
### Minor Changes
- 添加工具

184
packages/common/README.md Normal file
View File

@ -0,0 +1,184 @@
# @r-utils/common
与框架无关的通用 JS/TS 工具库,适用于任意前端项目,也可在具备对应运行时 API 的环境中使用。
## 特性
- 不依赖 Vue、uni-app 或 uview-plus。
- 支持 ESM / CJS 双格式产物。
- 支持根入口导入和子路径按需导入。
- 标记 `sideEffects: false`,方便业务打包器进行 tree-shaking。
## 安装
```bash
pnpm add @r-utils/common
```
## 导入方式
### 推荐:根入口导入
大多数场景推荐从根入口导入,使用心智负担更低,现代打包器仍可结合 ESM 和 `sideEffects: false` 做 tree-shaking。
```ts
import {
Permission,
wait,
Countdown,
TimeoutTimer,
getValueOfRule,
} from "@r-utils/common";
```
### 兼容:子路径按需导入
如果你希望导入路径更精确,也可以使用子路径导入。两种方式都支持,按团队习惯选择即可。
```ts
import { Permission } from "@r-utils/common/permission";
import { wait } from "@r-utils/common/time";
import { Countdown, TimeoutTimer } from "@r-utils/common/timer";
import { getValueOfRule } from "@r-utils/common/input-rule";
```
## 导出模块
| 子路径 | 说明 |
| --- | --- |
| `@r-utils/common/permission` | 权限字符串格式校验 |
| `@r-utils/common/time` | 时间相关工具 |
| `@r-utils/common/timer` | 倒计时、超时计时器 |
| `@r-utils/common/input-rule` | 输入值规则处理 |
| `@r-utils/common/knock-test` | 连续敲击/点击触发器 |
| `@r-utils/common/ui` | 与框架无关的 UI 计算工具 |
| `@r-utils/common/printer` | ESC/TSC 打印相关工具 |
## 使用示例
### 权限字符串校验
```ts
import { Permission } from "@r-utils/common";
const permission = new Permission([], 3, ":");
permission.isValid("user:create:button"); // true
permission.isValid("user:create"); // false
```
### 等待指定时间
```ts
import { wait } from "@r-utils/common";
async function submit() {
await wait(300);
console.log("继续执行");
}
```
### 倒计时
```ts
import { Countdown } from "@r-utils/common";
const countdown = new Countdown(10 * 1000);
countdown.addStepEventListener((time) => {
console.log("剩余时间:", time);
});
countdown.addCountdownEventListener(() => {
console.log("倒计时结束");
});
countdown.start();
```
### 简单数值倒计时
```ts
import { TimeoutTimer } from "@r-utils/common";
const timer = new TimeoutTimer(5000, 0, 1000);
timer.addStepEventListener((time) => {
console.log("剩余毫秒:", time);
});
timer.addCountdownEventListener(() => {
console.log("完成");
});
timer.start();
```
### 输入值规则处理
```ts
import { getValueOfRule } from "@r-utils/common";
const value = getValueOfRule("12.345", {
min: 0,
max: 99999.99,
required: true,
digits: 2,
keepDecimal: true,
});
console.log(value); // "12.35"
```
### 禁止正负号并转成数字
```ts
import { getValueOfRule } from "@r-utils/common";
const value = getValueOfRule("-12", {
min: 0,
required: true,
noSign: true,
number: true,
});
console.log(value); // 0
```
### 连续敲击触发回调
```ts
import { KnockTest } from "@r-utils/common";
const knockTest = new KnockTest({
maxWaitTime: 5000,
operations: [
{ times: 3, duration: 1000, delay: 500 },
{ times: 2, duration: 1000, delay: 500 },
],
});
knockTest.addCallback(() => {
console.log("触发隐藏功能");
});
button.addEventListener("click", () => {
knockTest.knock();
});
```
### 缓动滚动计算
```ts
import { slowlyScroll } from "@r-utils/common";
await slowlyScroll(0, 300, 500, (value) => {
window.scrollTo(0, value);
});
```
## 注意事项
- `Countdown`、`TimeoutTimer` 和 `KnockTest` 内部使用 `window.setInterval` / `window.setTimeout`,更适合浏览器或类浏览器环境。
- 推荐优先使用根入口导入;如果需要更精确的模块边界,也可以使用子路径导入。
- 打印相关模块通常依赖具体设备和业务场景,建议在真实设备环境中验证。

View File

@ -1,6 +1,6 @@
{
"name": "@r-utils/common",
"version": "1.3.0",
"version": "1.4.0",
"private": false,
"description": "js通用工具库",
"type": "module",
@ -8,13 +8,50 @@
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"sideEffects": false,
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./*": "./*"
"./input-rule": {
"types": "./dist/input-rule/index.d.ts",
"import": "./dist/input-rule/index.mjs",
"require": "./dist/input-rule/index.cjs"
},
"./knock-test": {
"types": "./dist/knock-test/index.d.ts",
"import": "./dist/knock-test/index.mjs",
"require": "./dist/knock-test/index.cjs"
},
"./permission": {
"types": "./dist/permission/index.d.ts",
"import": "./dist/permission/index.mjs",
"require": "./dist/permission/index.cjs"
},
"./printer": {
"types": "./dist/printer/index.d.ts",
"import": "./dist/printer/index.mjs",
"require": "./dist/printer/index.cjs"
},
"./time": {
"types": "./dist/time/index.d.ts",
"import": "./dist/time/index.mjs",
"require": "./dist/time/index.cjs"
},
"./timer": {
"types": "./dist/timer/index.d.ts",
"import": "./dist/timer/index.mjs",
"require": "./dist/timer/index.cjs"
},
"./ui": {
"types": "./dist/ui/index.d.ts",
"import": "./dist/ui/index.mjs",
"require": "./dist/ui/index.cjs"
}
},
"keywords": [
"utils",
@ -44,9 +81,9 @@
"scripts": {
"build": "vite build",
"watch": "vite build --watch",
"typecheck": "tsc -p tsconfig.json --noEmit",
"lint": "eslint --ext .js,ts --fix src",
"format": "prettier --write src",
"release": "standard-version",
"commit": "cz",
"lint-staged": "lint-staged",
"test": "vitest run"

View File

@ -59,7 +59,10 @@ export function getValueOfRule(
/**
* -
*/
function getTextTargetValue(innerValue: InputValue, options: InputOptions): InputValue {
function getTextTargetValue(
innerValue: InputValue,
options: InputOptions,
): InputValue {
const { required, init, pattern, number } = options;
innerValue ??= "";
@ -143,7 +146,10 @@ function applyPrecision(num: number, options: InputOptions): number {
/**
* -
*/
function getNumberTargetValue(innerValue: InputValue, options: InputOptions): InputValue {
function getNumberTargetValue(
innerValue: InputValue,
options: InputOptions,
): InputValue {
const { number, keepDecimal, noSign, digits } = options;
const strValue = String(innerValue ?? "");

View File

@ -127,7 +127,7 @@ export class JpPrinter {
addText(content) {
content = String(content);
let code = [];
let code;
if (isAndroidApp) {
code = plus.android.invoke(content, "getBytes", "gbk");
} else {
@ -254,8 +254,8 @@ export class JpPrinter {
let code = new TextEncoder("gb18030", {
NONSTANDARD_allowLegacyEncoding: true,
}).encode(content);
const pL = parseInt((code.length + 3) % 256);
const pH = parseInt((code.length + 3) / 256);
// const pL = parseInt((code.length + 3) % 256);
// const pH = parseInt((code.length + 3) / 256);
this.data.push(29, 40, 107, 3, 0, 49, 69, ...code);
return this;
}
@ -740,6 +740,7 @@ export class JpPrinter {
let ch = 0;
text.split("").forEach((c) => {
// 是否是汉字,汉字两倍宽
// eslint-disable-next-line no-control-regex
const isChinese = /[^\x00-\xff]/.test(c);
if (isChinese) {
ch += 2;
@ -984,10 +985,12 @@ export class JpPrinter {
return this;
}
setBarcodeContent(t, content) {
setBarcodeContent(t) {
let ty = 73;
this.data.push(29);
this.data.push(107);
const bar = JpPrinter.bar;
switch (t) {
case bar[0]:
ty = 65;
@ -1031,12 +1034,16 @@ export class JpPrinter {
}
export class Query {
constructor() {
this.queryStatus = new Query();
}
/**
* 查询打印机实时状态
* @param {*} n
* @param {*} device
*/
getRealtimeStatusTransmission(n, device) {
getRealtimeStatusTransmission(n) {
/*
n = 1传送打印机状态
n = 2传送脱机状态
@ -1048,7 +1055,7 @@ export class Query {
dateView.setUint8(0, 16);
dateView.setUint8(1, 4);
dateView.setUint8(2, n);
queryStatus.query(buf);
this.queryStatus.query(buf);
}
addGeneratePlus(n, m, t, device) {
@ -1059,7 +1066,7 @@ export class Query {
dateView.setUint8(2, n);
dateView.setUint8(3, m);
dateView.setUint8(4, t);
queryStatus.query(buf, device);
this.queryStatus.query(buf, device);
}
query(buf, device) {

View File

@ -195,6 +195,7 @@ export class TSCPlus extends TSC {
let ch = 0;
text.split("").forEach((c) => {
// 是否是汉字,汉字两倍宽
// eslint-disable-next-line no-control-regex
const isChinese = /[^\x00-\xff]/.test(c);
if (isChinese) {
ch += 2;

View File

@ -417,7 +417,7 @@ export class TSC {
for (x = 0; x < w; x++) {
var color = bitmapData[(y * w + x) * 4 + 1];
if (color <= 128) {
bits[parseInt(y * pitch + x / 8)] |= 0x80 >> x % 8;
bits[parseInt(y * pitch + x / 8)] |= 0x80 >> (x % 8);
}
}
}

View File

@ -13,7 +13,9 @@ describe("getValueOfRule - 文本模式 (text: true)", () => {
});
test("required + init非数字文本回退到 init", () => {
expect(getValueOfRule("abc", { ...textOpts, required: true, init: "默认" })).toBe("默认");
expect(
getValueOfRule("abc", { ...textOpts, required: true, init: "默认" }),
).toBe("默认");
});
test("required 无 init非数字文本保持原值", () => {
@ -29,7 +31,9 @@ describe("getValueOfRule - 文本模式 (text: true)", () => {
});
test("pattern 匹配成功返回原值", () => {
expect(getValueOfRule("123", { ...textOpts, pattern: "^\\d+$" })).toBe("123");
expect(getValueOfRule("123", { ...textOpts, pattern: "^\\d+$" })).toBe(
"123",
);
});
});
@ -107,7 +111,9 @@ describe("getValueOfRule - digits 小数位数", () => {
});
test("keepDecimal + number 返回数字类型", () => {
expect(getValueOfRule("3.10", { digits: 2, keepDecimal: true, number: true })).toBe(3.1);
expect(
getValueOfRule("3.10", { digits: 2, keepDecimal: true, number: true }),
).toBe(3.1);
});
});
@ -127,11 +133,15 @@ describe("getValueOfRule - integer 整数模式", () => {
describe("getValueOfRule - noSign 不允许正负号", () => {
test("带正号的输入被视为非法", () => {
expect(getValueOfRule("+5", { noSign: true, required: true, init: 0 })).toBe("0");
expect(
getValueOfRule("+5", { noSign: true, required: true, init: 0 }),
).toBe("0");
});
test("带负号的输入被视为非法", () => {
expect(getValueOfRule("-5", { noSign: true, required: true, init: 0 })).toBe("0");
expect(
getValueOfRule("-5", { noSign: true, required: true, init: 0 }),
).toBe("0");
});
test("无符号数字正常通过", () => {
@ -142,25 +152,45 @@ describe("getValueOfRule - noSign 不允许正负号", () => {
describe("getValueOfRule - callback", () => {
test("callback 接收最终处理后的值", () => {
let received: unknown;
getValueOfRule("42", { number: true }, (v) => { received = v; });
getValueOfRule("42", { number: true }, (v) => {
received = v;
});
expect(received).toBe(42);
});
});
describe("getValueOfRule - 综合场景", () => {
test("限制输入 min:0, max:99999.99, required, digits:2", () => {
expect(getValueOfRule("100.456", { min: 0, max: 99999.99, required: true, digits: 2 })).toBe("100.46");
expect(
getValueOfRule("100.456", {
min: 0,
max: 99999.99,
required: true,
digits: 2,
}),
).toBe("100.46");
});
test("超出 max 时截断到 max", () => {
expect(getValueOfRule("100000", { min: 0, max: 99999.99, required: true, digits: 2 })).toBe("99999.99");
expect(
getValueOfRule("100000", {
min: 0,
max: 99999.99,
required: true,
digits: 2,
}),
).toBe("99999.99");
});
test("空输入 required 回退到 min", () => {
expect(getValueOfRule("", { min: 0, max: 99999.99, required: true, digits: 2 })).toBe("0");
expect(
getValueOfRule("", { min: 0, max: 99999.99, required: true, digits: 2 }),
).toBe("0");
});
test("负数输入限制到 min:0", () => {
expect(getValueOfRule("-5", { min: 0, max: 100, required: true })).toBe("0");
expect(getValueOfRule("-5", { min: 0, max: 100, required: true })).toBe(
"0",
);
});
});

View File

@ -1,11 +1,11 @@
{
"extends": "../../tsconfig.base.json",
"exclude": ["node_modules", "dist"],
"include": ["src/**/*.ts"],
"include": ["src/**/*.ts", "types/**/*.d.ts"],
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
},
}
}
}

338
packages/common/types/printer/esc.d.ts vendored Normal file
View File

@ -0,0 +1,338 @@
export function row2col(arr: any): any;
/**
* NOTE 3216
*
*/
export class JpPrinter {
static bar: string[];
/**
*
* @param {string} text
* @returns {number}
*/
static getTextDots(text: string): number;
/**
*
* @param {string} text
* @param {number} maxDots
* @return {string}
*/
static getMaxText(text?: string, maxDots?: number): string;
/**
*
* "123456789" => ["1234", "5678", "9"]
* @param {string} str
* @param {number} maxDots
* @return {string[]}
*/
static splitString(str: string, maxDots: number): string[];
static createDefaultPrinter(): JpPrinter;
static getQuery(): Query;
constructor(width?: number, dpi?: number);
name: string;
data: any[];
align: string;
bold: boolean;
lineSpacing: number;
fontSize: number;
/** 有效打印宽度 */
width: number;
dpi: number;
_layout: null;
storeLayout(): this;
restoreLayout(): this;
getXDots(): number;
/** 初始化打印机 */
init(): this;
/**
*
* @param {string} content
*/
addText(content: string): this;
/**
* GS !
* @param {number} n
* */
setFontSize(n?: number): this;
/**
* ESC E /
* @param {boolean} bold
* */
setBold(bold: boolean): this;
/**
* ESC /线
* n 线
* 线 HT
* 线 90°
* 线线线
* 线
* 线 ESC !
*
* @param {number} n
* 0, 48 线
* 1, 49 线1
* 2, 50 线2
* @returns
*/
setUnderline(n?: number): this;
/**
* FS - /线
* n 线
* 线 HT 线 90 线
* 线线线线线线 1
* 使线线
* FS !线
* @param {*} n
* 0, 48 线
* 1, 49 线1
* 2, 50 线2
* @returns
*/
setUnderlineChinese(n?: any): this;
/**
*
* @param {*} n
* @see {JpPrinter#setQRCodeSize}
*/
setSelectSizeOfModuleForQRCode(n: any): this;
/**
* QRCode n dot
* @param {number} n
* @returns
*/
setQRCodeSize(n: number): this;
/**
* QRCode
* @see {JpPrinter#setQRCodeErrorCorrectionLevel}
*/
setSelectErrorCorrectionLevelForQRCode(n: any): this;
/**
* QRCode
* n
* 48 L 7
* 49 M 15
* 50 Q 25
* 51 H 30
* @see
*/
setQRCodeErrorCorrectionLevel(n: any): this;
/** 设置二维码内容 */
setStoreQRCodeData(content: any): this;
/**
*
* @deprecated
* @see {JpPrinter#printQRCode}
* */
setPrintQRCode(): this;
/** 打印二维码 */
printQRCode(): this;
addQrCodeByUrl(url: any, width: any, height: any): this;
addImageByUrl(url: any, width: any, height: any): this;
addQrCodeByText(contents: any, width: any, height: any): this;
/**
* HT
*
* @deprecated
* @see {JpPrinter#addHorTab}
*/
setHorTab(): this;
/**
* HT
*
*/
addHorTab(): this;
/**
* ESC $
* @param {number} where
* @returns
*/
setAbsolutePrintPosition(where: number): this;
/**
* ESC \
* 127
*
* @param {number} where
* @returns
*/
setRelativePrintPosition(where: number): this;
/**
* ESC a
* @param {number} n
* 0, 48
* 1, 49
* 2, 50
*/
setSelectJustification(n: number): this;
/**
*
* @param {string} align
* "l"
* "m"
* "r"
* @returns
*/
setAlign(align: string): this;
/**
* ESC D
* @param {number} n
* @deprecated
* @see {}
*/
space(...nk: any[]): this;
/**
* ESC D
* @param {number} n
*/
addSpace(...nk: any[]): this;
/**
* GS L
* @param {number} n
* @returns
*/
setLeftMargin(n: number): this;
textMarginRight(n: any): this;
/**
* ESC 3
* @deprecated
* @see {JpPrinter#setLineSpacing}
* */
rowSpace(n: any): this;
/**
* ESC 3
* */
setLineSpacing(n: any): this;
/**
* GS W
* @param {number} width
* @returns
*/
setPrintingAreaWidth(width: number): this;
setSound(n: any, t: any): this;
setBitmap(res: any): this;
/**
* GS v 0
* */
addBitmap(m: any, xL: any, xH: any, yL: any, yH: any, ...data: any[]): this;
/**
*
* @param {Uint8ClampedArray} imgData
* @param {number} width
* @param {number} height
*/
addBitmapHelper(imgData: Uint8ClampedArray, width: number, height: number): this;
/**
*
* */
addLF(): this;
/**
* ESC J n
* @param {number} n
* @see {JpPrinter#addPrintAndFeed}
*/
setPrintAndFeed(n: number): this;
/**
* ESC J n
* @param {number} n
*/
addPrintAndFeed(n: number): this;
/**
* ESC d n
* @param {number} n
* @see {JpPrinter#addPrintAndFeedRow}
*/
setPrintAndFeedRow(n: number): this;
/**
* ESC d n
* @param {number} n
* @returns
*/
addPrintAndFeedRow(n: number): this;
/**
* n
* @param {number} n
* @see {JpPrinter#addPrintAndFeedRow}
*/
addRow(n: number): this;
/**
*
* @param {number[]} data
* @returns
*/
addData(...data: number[]): this;
/**
*
*/
getData(): any[];
/*********************** 自增 ***********************/
/**
*
* @param {*} value
* @param {*} width
* @deprecated
* @see {JpPrinter#getTextDots}
*/
siteText(value: any, width: any): number;
/**
*
* @param {*} value
* @param {*} width
* @deprecated
* @see {JpPrinter#getTextDots}
*/
siteNumber(value: any, width: any): number;
/**
*
* @deprecated
*/
alignLeft(name: any, text: any, arr: any): this;
/**
* @deprecated
* @see {JpPrinter.getTextDots}
*/
getTextDots(text: any): number;
/**
* @deprecated
* @see {JpPrinter.getMaxText}
*/
getMaxText(text?: string, maxDots?: number): string;
/**
*
*/
addTextJustifyAlign(text1: any, text2: any): this;
/**
* 线
*/
addDivider(): this;
/**
*
* @param {Object} table
* @param {Array} table.header
* @param {Array} table.data
* @param {number[]} [table.columns]
*/
addTable({ header, data, columns }: {
header: any[];
data: any[];
columns?: number[] | undefined;
}): this;
/**
*
* @deprecated
* @see {JpPrinter#addDivider}
*/
separator(width: any): this;
setBarcodeWidth(width: any): this;
setBarcodeHeight(height: any): this;
setBarcodeContent(t: any): this;
}
export class Query {
queryStatus: Query;
/**
*
* @param {*} n
* @param {*} device
*/
getRealtimeStatusTransmission(n: any): void;
addGeneratePlus(n: any, m: any, t: any, device: any): void;
query(buf: any, device: any): void;
}

View File

@ -0,0 +1,63 @@
export class TSCPlus extends TSC {
static MILLIMETERS_PER_INCH: number;
static getLetterWidthDot(font: any): number;
static getFontLineHeightDot(font: any, lineHeight: any): any;
/**
*
* @param {string} text
* @returns {number}
*/
static getTextDots(text: string, letterDots?: number): number;
/**
*
* @param {string} text
* @param {number} maxDots
* @return {string}
*/
static getMaxText(text?: string, maxDots?: number): string;
/**
*
* "123456789" => ["1234", "5678", "9"]
* @param {string} str
* @param {number} maxDots
* @return {string[]}
*/
static splitString(str: string, maxDots: number): string[];
font: string;
lineHeight: string;
dpi: number;
nextX: number;
nextY: number;
widthDot: number;
heightDot: number;
paddingTopDot: number;
paddingLeftDot: number;
paddingRightDot: number;
paddingBottomDot: number;
/**
*
* @param {number} paddingTopDot
* @param {number} paddingRightDot
* @param {number} paddingBottomDot
* @param {number} paddingLeftDot
*/
setPadding(paddingTopDot: number, paddingRightDot: number, paddingBottomDot: number, paddingLeftDot: number): void;
mmToDot(mm: any): number;
setDpi(dpi: any): void;
setSize(w: any, h: any): TSC;
setSizeMM(w: any, h: any): TSC;
setSizeDot(w: any, h: any): TSC;
/**
*
* @param {string} font
*/
setFont(font: string): void;
/**
*
* @param {string|number} lineHeight
*/
setLineHeight(lineHeight: string | number): void;
addTextLn(text: any, options?: {}): this;
addAddBarCode(content: any, options?: {}): this;
}
import { TSC } from "./tsc.js";

369
packages/common/types/printer/tsc.d.ts vendored Normal file
View File

@ -0,0 +1,369 @@
export class TSC {
static LINE_BREAK: string;
constructor(data?: any[]);
data: any[];
addData(...data: any[]): void;
addDataArray(dataArray: any): void;
addCode(code: any): this;
getData: () => any;
/**
*
* @param {number|string} w inch
* @param {number|string} h inch
* @returns {TSC}
*/
setSize(w: number | string, h: number | string): TSC;
/**
*
* @param {number|string} w mm
* @param {number|string} h mm
* @returns {TSC}
*/
setSizeMM(w: number | string, h: number | string): TSC;
/**
*
* @param {number|string} m inch
* @param {number|string} n inch
* @returns {TSC}
*/
setGap(m?: number | string, n?: number | string): TSC;
/**
*
* @param {number|string} m mm
* @param {number|string} n mm
* @returns {TSC}
*/
setGapMM(m?: number | string, n?: number | string): TSC;
/**
*
* @param {number|string} m inch
* @param {number|string} n inch
* @returns {TSC}
*/
setBLine(m?: number | string, n?: number | string): TSC;
/**
* peel-off mode
*
*
* @param {number|string} m inch
* @returns {TSC}
*/
setOffset(offset?: number): TSC;
/**
*
* @param {number|string} speed
* @returns {TSC}
*/
setSpeed(speed?: number | string): TSC;
/**
*
* @param {number|string} density
* @returns {TSC}
*/
setDensity(density?: number | string): TSC;
/**
*
* @param {number|string} direction
* @returns {TSC}
*/
setDirection(direction?: number | string): TSC;
/**
*
* @param {number|string} x ,dot
* @param {number|string} y ,dot
* @returns {TSC}
*/
setReference(x?: number | string, y?: number | string): TSC;
/**
*
* @param {number|string} n
* @returns {TSC}
*/
setShift(n?: number | string): TSC;
/**
*
* 001:USA
* 002:French
* 003:Latin America
* 034:Spanish
* 039:Italian
* 044:United Kingdom
* 046:Swedish
* 047:Norwegian
* 049:German
* @param {number|string} country
* @returns {TSC}
*/
setCountry(country?: number | string): TSC;
/**
*
* 8-bit codepage
* 437:United States
* 850:Multilingual
* 852:Slavic
* 860:Portuguese
* 863:Canadian/French
* 865:Nordic
*
* Windows code page
* 1250:Central Europe
* 1252:Latin I
* 1253:Greek
* 1254:Turkish
*
* 12×24 dot
* WestEurope:WestEurope
* Greek:Greek
* Hebrew:Hebrew
* EastEurope:EastEurope
* Iran:Iran
* IranII:IranII
* Latvian:Latvian
* Arabic:Arabic
* Vietnam:Vietnam
* Uygur:Uygur
* Thai:Thai
* 1252:Latin I
* 1257:WPC1257
* 1251:WPC1251
* 866:Cyrillic
* 858:PC858
* 747:PC747
* 864:PC864
* 1001:PC1001
* @param {number|string} n
* @returns {TSC}
*/
setCodepage(n?: number | string): TSC;
/**
* image buffer)
* SIZE
* @param {number|string} n
* @returns {TSC}
*/
setCls(): TSC;
/**
*
* 200 DPI:1 mm = 8 dots
* 300 DPI:1 mm = 12 dots
* @param {number|string} n 1n9999dot
* @returns {TSC}
*/
setFeed(n: number | string): TSC;
/**
*
* 200 DPI:1 mm = 8 dots
* 300 DPI:1 mm = 12 dots
* @param {number|string} n 1n9999dot
* @returns {TSC}
*/
setBackFeed(n: number | string): TSC;
/**
*
* 200 DPI:1 mm = 8 dots
* 300 DPI:1 mm = 12 dots
* @param {number|string} n 1n9999dot
* @returns {TSC}
*/
setBackUp(n: number | string): TSC;
/**
*
* @returns {TSC}
*/
setFromFeed(): TSC;
/**
* 使
*
*
*
* 使30 mm
* @returns {TSC}
*/
setHome(): TSC;
/**
*
* @param {number|string} m set
* @param {number|string} n
* @returns {TSC}
*/
setPrint(m?: number | string, n?: number | string): TSC;
/**
* 10
* 10
* @param {number|string} m set
* @param {number|string} n
* @returns {TSC}
*/
setSound(level?: number, interval?: number): TSC;
/**
*
*
* @param {number|string} limit inch
* @returns {TSC}
*/
setLimitFeed(limit?: number | string): TSC;
/**
*
* @returns {TSC}
*/
setSelfTest(): TSC;
/**
* 线
* @param {number|string} x 线X坐标dot
* @param {number|string} y 线Y坐标dot
* @param {number|string} width 线dot
* @param {number|string} height 线dot
* @returns {TSC}
*/
setBar(x: number | string, y: number | string, width: number | string, height: number | string): TSC;
/**
* 线
* @param {number|string} x 线X坐标dot
* @param {number|string} y 线Y坐标dot
* @param {number|string} codeType 线dot
* @param {number|string} height dot
* @param {number|string} readable 0 1
* @param {number|string} rotation
* @param {number|string} narrow bar宽度dot
* @param {number|string} wide bar宽度dot
* @param {number|string} content
* @returns {TSC}
*/
setBarCode(x: number | string, y: number | string, codeType: number | string | undefined, height: number | string | undefined, readable: number | string | undefined, rotation: number | string | undefined, narrow: number | string | undefined, wide: number | string | undefined, content: number | string): TSC;
/**
*
* @param {number|string} x1 线X坐标dot
* @param {number|string} y1 线Y坐标dot
* @param {number|string} x2 X坐标dot
* @param {number|string} y2 Y坐标dot
* @param {number|string} thickness 线dot
* @returns {TSC}
*/
setBox(x1: number | string, y1: number | string, x2: number | string, y2: number | string, thickness: number | string): TSC;
/**
* BMP格式图档
* @param {number|string} x 线X坐标dot
* @param {number|string} y 线Y坐标dot
* @param {number|string} width X坐标dot
* @param {number|string} height Y坐标dot
* @param {number|string} mode 线dot
* @param {number|string} bitmapData 线dot
* @returns {TSC}
*/
setBitmap(x: number | string, y: number | string, width: number | string, height: number | string, mode: number | string, bitmapData: number | string): TSC;
/**
*
* @param {number|string} x X座标dot
* @param {number|string} y Y座标dot
* @param {number|string} width dot
* @param {number|string} height dot
* @returns {TSC}
*/
setErase(x: number | string, y: number | string, width: number | string, height: number | string): TSC;
/**
*
* @param {number|string} x X座标dot
* @param {number|string} y Y座标dot
* @param {number|string} width dot
* @param {number|string} height dot
* @returns {TSC}
*/
setReverse(x: number | string, y: number | string, width: number | string, height: number | string): TSC;
/**
*
* @param {number|string} x X方向起始点坐标
* @param {number|string} y Y方向起始点坐标
* @param {number|string} font
* @param {number|string} sx X 1-10
* @param {number|string} sy Y 1-10
* @param {number|string} content
* @returns {TSC}
*/
setText(x: number | string, y: number | string, font: number | string, rotation: any, sx: number | string, sy: number | string, content: number | string): TSC;
/**
*
* @param {number|string} x
* @param {number|string} y Y座标dot
* @param {number|string} level QRCODE纠错等级
* @param {number|string} width 1-10
* @param {number|string} mode /
* @param {number|string} rotation
* @param {number|string} content
* @returns {TSC}
*/
setQrcode(x: number | string, y: number | string, level: number | string, width: number | string, mode: number | string, rotation: number | string, content: number | string): TSC;
/**
* Key1
*
* @param {"ON"|"OFF"} k /
* @returns {TSC}
*/
setKey1(k: "ON" | "OFF"): TSC;
/**
* Key2
*
* @param {"ON"|"OFF"} k /
* @returns {TSC}
*/
setKey2(k: "ON" | "OFF"): TSC;
/**
* /
* @param {"ON"|"OFF"} k /
* @returns {TSC}
*/
setPeel(k: "ON" | "OFF"): TSC;
/**
* /
* @param {"ON"|"OFF"} k /
* @returns {TSC}
*/
setTear(k: "ON" | "OFF"): TSC;
/**
* /
* @param {"ON"|"OFF"} k /
* @returns {TSC}
*/
setStripper(k: "ON" | "OFF"): TSC;
/**
* /
*
* @param {"ON"|"OFF"} k /
* @returns {TSC}
*/
setHead(k: "ON" | "OFF"): TSC;
/**
* /
*
* @param {"ON"|"OFF"|"AUTO"|string|number} k /
* @returns {TSC}
*/
setHead2(k: "ON" | "OFF" | "AUTO" | string | number): TSC;
/**
* /
*
* @param {"ON"|"OFF"} k /
* @returns {TSC}
*/
setReprint(k: "ON" | "OFF"): TSC;
/**
* //
* 使
*
* @param {"ON"|"OFF"} k /
* @returns {TSC}
*/
setRibbon(k: "ON" | "OFF"): TSC;
/**
*
* @param {"OFF"|"BATCH"|string|number} k /
* @returns {TSC}
*/
setCutter(k: "OFF" | "BATCH" | string | number): TSC;
/**
*
* @param {"ON"|"OFF"|"BATCH"} k /
* @param {string} content
* @returns {TSC}
*/
setResponse(k: "ON" | "OFF" | "BATCH", content: string): TSC;
}

View File

@ -5,15 +5,43 @@ import dts from "vite-plugin-dts";
const __dirname = fileURLToPath(new URL(".", import.meta.url));
const sharedOutput = {
preserveModules: true,
preserveModulesRoot: resolve(__dirname, "src"),
assetFileNames: "assets/[name]-[hash][extname]",
exports: "named",
} as const;
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, "src/index.ts"),
formats: ["es", "cjs"],
fileName: (format) => `index.${format === "es" ? "mjs" : "cjs"}`,
entry: {
index: resolve(__dirname, "src/index.ts"),
"input-rule/index": resolve(__dirname, "src/input-rule/index.ts"),
"knock-test/index": resolve(__dirname, "src/knock-test/index.ts"),
"permission/index": resolve(__dirname, "src/permission/index.ts"),
"printer/index": resolve(__dirname, "src/printer/index.ts"),
"time/index": resolve(__dirname, "src/time/index.ts"),
"timer/index": resolve(__dirname, "src/timer/index.ts"),
"ui/index": resolve(__dirname, "src/ui/index.ts"),
},
},
rollupOptions: {
rolldownOptions: {
external: ["dayjs", "lodash-es", "text-encoding", "tslib"],
output: [
{
...sharedOutput,
format: "es",
entryFileNames: "[name].mjs",
chunkFileNames: "chunks/[name]-[hash].mjs",
},
{
...sharedOutput,
format: "cjs",
entryFileNames: "[name].cjs",
chunkFileNames: "chunks/[name]-[hash].cjs",
},
],
},
sourcemap: true,
},
@ -24,7 +52,7 @@ export default defineConfig({
},
plugins: [
dts({
include: ["src"],
include: ["src", "types"],
outDir: "dist",
}),
],

View File

@ -0,0 +1,12 @@
# @r-utils/uni-app
## 1.4.0
### Minor Changes
- 添加工具
### Patch Changes
- Updated dependencies
- @r-utils/common@1.4.0

View File

@ -0,0 +1,93 @@
# @r-utils/uni-app
仅用于 uni-app 项目的工具包封装请求、上传、NFC、蓝牙、打印和常用 uni API 辅助方法。
## 适用范围
- 适用于 uni-app 项目(含 uni 运行时能力)。
- 适用于需要复用请求、上传、蓝牙、NFC、打印等能力的业务项目。
## 不适用范围
- 不适用于普通 Web Vue2/Vue3 项目。
- 不适用于没有 `uni` 运行时的纯 Node.js 环境。
## 安装
```bash
pnpm add @r-utils/uni-app
```
## 导入方式
### 推荐:根入口导入
大多数场景推荐从根入口导入,路径简单,使用心智负担更低。
```ts
import { Request, showToast, toPromise, upload, Printer } from "@r-utils/uni-app";
```
### 兼容:子路径导入
如果你希望模块边界更清晰,也可以使用子路径导入。两种方式都支持。
```ts
import { Request } from "@r-utils/uni-app/request";
import { showToast, toPromise } from "@r-utils/uni-app/uni-helper";
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";
```
## 导出模块
| 子路径 | 说明 |
| --- | --- |
| `@r-utils/uni-app/request` | 类 axios 的 `uni.request` 封装 |
| `@r-utils/uni-app/uni-helper` | 常用 uni API 辅助函数 |
| `@r-utils/uni-app/upload` | 上传相关工具 |
| `@r-utils/uni-app/printer` | 打印机相关工具 |
| `@r-utils/uni-app/nfc` | NFC 相关工具 |
| `@r-utils/uni-app/bluetooth-utils` | 蓝牙相关工具 |
## 使用示例
### 请求封装
```ts
import { Request } from "@r-utils/uni-app";
const request = new Request({
baseURL: "https://api.example.com",
});
const res = await request.get("/users", {
data: { pageNum: 1, pageSize: 10 },
});
```
### 使用 showToast
```ts
import { showToast } from "@r-utils/uni-app";
showToast("保存成功", "success");
```
### 子路径导入请求模块
```ts
import { Request } from "@r-utils/uni-app/request";
const request = new Request({
baseURL: "https://api.example.com",
});
```
## 注意事项
- 推荐优先使用根入口导入;如果需要更精确的模块边界,也可以使用子路径导入。
- 本包依赖 uni-app 运行时能力,需在真实 uni-app 环境中验证平台相关功能。
- NFC、蓝牙、打印功能通常依赖具体平台和设备能力建议按目标端单独测试。

View File

@ -1,6 +1,6 @@
{
"name": "@r-utils/uni-app",
"version": "1.3.0",
"version": "1.4.0",
"private": false,
"description": "uni-app工具库",
"type": "module",
@ -8,13 +8,45 @@
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"sideEffects": false,
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./*": "./*"
"./bluetooth-utils": {
"types": "./dist/bluetooth-utils/index.d.ts",
"import": "./dist/bluetooth-utils/index.mjs",
"require": "./dist/bluetooth-utils/index.cjs"
},
"./nfc": {
"types": "./dist/nfc/index.d.ts",
"import": "./dist/nfc/index.mjs",
"require": "./dist/nfc/index.cjs"
},
"./printer": {
"types": "./dist/printer/index.d.ts",
"import": "./dist/printer/index.mjs",
"require": "./dist/printer/index.cjs"
},
"./request": {
"types": "./dist/request/index.d.ts",
"import": "./dist/request/index.mjs",
"require": "./dist/request/index.cjs"
},
"./uni-helper": {
"types": "./dist/uni-helper/index.d.ts",
"import": "./dist/uni-helper/index.mjs",
"require": "./dist/uni-helper/index.cjs"
},
"./upload": {
"types": "./dist/upload/index.d.ts",
"import": "./dist/upload/index.mjs",
"require": "./dist/upload/index.cjs"
}
},
"keywords": [
"uni-app"
@ -43,8 +75,9 @@
"scripts": {
"build": "vite build",
"watch": "vite build --watch",
"typecheck": "tsc -p tsconfig.json --noEmit",
"lint": "eslint --ext .js,ts --fix src",
"release": "standard-version",
"format": "prettier --write src",
"commit": "cz",
"lint-staged": "lint-staged",
"test": "vitest run"

View File

@ -1,4 +1,5 @@
import { toPromise, showToast } from "@/uni-helper";
/* eslint-disable no-useless-assignment, @typescript-eslint/no-unused-vars */
import { showToast } from "@/uni-helper";
const systemInfo = uni.getSystemInfoSync();
const isAndroidApp =
@ -237,7 +238,7 @@ export class BluetoothUtils {
res = await cb();
} else {
// 失败重连5次
for (var i = 1; i <= 5; i++) {
for (let i = 1; i <= 5; i++) {
try {
await uni.createBLEConnection({
deviceId: device.deviceId,
@ -397,12 +398,12 @@ export class BluetoothUtils {
private static async _getBLEMTU(device: Device) {
console.log("_getBLEMTU", device);
// return new Promise<number>(async (resolve, reject) => {
return uni.getBLEMTU({
deviceId: device.deviceId,
// success: (res) => {
// resolve(res.mtu);
// },
});
return uni.getBLEMTU({
deviceId: device.deviceId,
// success: (res) => {
// resolve(res.mtu);
// },
});
// });
}

View File

@ -1,3 +1,4 @@
/* eslint-disable no-useless-assignment, @typescript-eslint/no-unused-vars */
const systemInfo = uni.getSystemInfoSync();
const isAndroid =
systemInfo.uniPlatform === "app" && systemInfo.osName === "android";
@ -195,12 +196,16 @@ export class AndroidNfcUtil {
static async scan() {
const androidNfcUtil = new AndroidNfcUtil();
return await new Promise(async (resolve, reject) => {
await androidNfcUtil.startNfcScan();
androidNfcUtil.addDiscoveredListener((res) => {
androidNfcUtil.stopNfcScan();
resolve(res);
});
return await new Promise((resolve, reject) => {
androidNfcUtil
.startNfcScan()
.then(() => {
androidNfcUtil.addDiscoveredListener((res) => {
androidNfcUtil.stopNfcScan();
resolve(res);
});
})
.catch(reject);
});
}
}

View File

@ -27,7 +27,7 @@ export async function isNfcEnabled() {
}
}
export function getNFCUtil(){
export function getNFCUtil() {
if (isAndroidApp) {
return new AndroidNfcUtil();
} else if (isAndroidWeixin) {

View File

@ -3,11 +3,15 @@ export async function startNfcScan() {
await nfcAdapter.startDiscovery();
return new Promise((resolve, reject) => {
nfcAdapter.onDiscovered((res) => {
console.log("onDiscovered", res);
const arr = Array.from(new Int8Array(res.id));
resolve(arr);
});
try {
nfcAdapter.onDiscovered((res) => {
console.log("onDiscovered", res);
const arr = Array.from(new Int8Array(res.id));
resolve(arr);
});
} catch (e) {
reject(e);
}
});
}
@ -67,12 +71,16 @@ export class WeixinNfcUtil {
static async scan() {
const weixinNfcUtil = new WeixinNfcUtil();
return await new Promise(async (resolve, reject) => {
await weixinNfcUtil.startNfcScan();
weixinNfcUtil.addDiscoveredListener((res) => {
weixinNfcUtil.stopNfcScan();
resolve(res);
});
return await new Promise((resolve, reject) => {
weixinNfcUtil
.startNfcScan()
.then(() => {
weixinNfcUtil.addDiscoveredListener((res) => {
weixinNfcUtil.stopNfcScan();
resolve(res);
});
})
.catch(reject);
});
}
}

View File

@ -1,6 +1,5 @@
import { BluetoothUtils, Device } from "@/bluetooth-utils";
import { wait } from "@r-utils/common";
import { BluetoothUtils, Device } from "@/bluetooth-utils";
type DeviceData = Required<Device>;
@ -17,9 +16,9 @@ export class Printer {
console.log(
data.length,
data.slice(0, 100),
data.slice(data.length - 100, data.length)
data.slice(data.length - 100, data.length),
);
let res = null;
let res;
const systemInfo = uni.getSystemInfoSync();
if (systemInfo.uniPlatform === "app" && systemInfo.osName === "android") {
res = await BluetoothUtils.sendDataAndroid(this.device, data);
@ -33,7 +32,7 @@ export class Printer {
return res;
}
async _print(data: number[]):Promise<any> {
async _print(data: number[]): Promise<void> {
const size = Math.min(data.length, this.size);
if (size === 0) {
return;

View File

@ -1,37 +1,57 @@
export type DataType = string | AnyObject | ArrayBuffer;
/** 请求配置 */
export interface Config<T extends DataType>
extends Partial<UniApp.RequestOptions> {
export interface Config<
T extends DataType,
> extends Partial<UniApp.RequestOptions> {
baseURL?: string;
data?: T;
[key: string]: any;
[key: string]: unknown;
}
/** 响应 */
export interface Response<
T extends DataType,
D extends DataType,
C extends Config<D> = Config<D>
> extends UniApp.RequestSuccessCallbackResult {
C extends Config<D> = Config<D>,
>
extends UniApp.RequestSuccessCallbackResult {
data: T;
errMsg?: string;
config: C;
}
/** 判断是否为绝对地址 */
const isAbsoluteUrl = (url: string): boolean =>
/^(?:[a-z][a-z\d+\-.]*:)?\/\//i.test(url);
/** 拼接基础地址 */
const joinBaseURL = (baseURL: string, url: string): string => {
if (!baseURL || isAbsoluteUrl(url)) {
return url;
}
const normalizedBaseURL = baseURL.endsWith("/")
? baseURL.slice(0, -1)
: baseURL;
const normalizedUrl = url.startsWith("/") ? url : `/${url}`;
return `${normalizedBaseURL}${normalizedUrl}`;
};
/** 成功拦截器 */
type FulfilledInterceptor<R, T> = (res: R) => T | Promise<T>;
/** 失败拦截器 */
type RejectedInterceptor = (error: any) => any;
type RejectedInterceptor = (error: unknown) => unknown | Promise<unknown>;
/** 拦截器管理 */
class InterceptorManager<R> {
/** 拦截器列表 */
handlers: [FulfilledInterceptor<R, any>?, RejectedInterceptor?][] = [];
handlers: [FulfilledInterceptor<R, unknown>?, RejectedInterceptor?][] = [];
/** 添加拦截器 */
add<T = R>(
onFulfilled?: FulfilledInterceptor<R, T>,
onRejected?: RejectedInterceptor
onRejected?: RejectedInterceptor,
): number {
this.handlers.push([onFulfilled, onRejected]);
return this.handlers.length - 1;
@ -44,9 +64,9 @@ class InterceptorManager<R> {
forEach(
fn: (
onFulfilled?: FulfilledInterceptor<R, any>,
onRejected?: RejectedInterceptor
) => void
onFulfilled?: FulfilledInterceptor<R, unknown>,
onRejected?: RejectedInterceptor,
) => void,
) {
this.handlers.forEach(([onFulfilled, onRejected]) => {
fn(onFulfilled, onRejected);
@ -59,16 +79,16 @@ class InterceptorManager<R> {
*/
export class Request {
/** 请求配置 */
config: Config<any>;
config: Config<DataType>;
/** 拦截器 */
interceptors: {
/** 请求拦截器 */
request: InterceptorManager<Config<any>>;
request: InterceptorManager<Config<DataType>>;
/** 响应拦截器 */
response: InterceptorManager<any>;
response: InterceptorManager<unknown>;
};
constructor(config: Config<any> = { url: "" }) {
constructor(config: Config<DataType> = { url: "" }) {
this.config = config;
this.interceptors = {
request: new InterceptorManager(),
@ -76,79 +96,86 @@ export class Request {
};
}
/** 依次执行请求拦截器 */
private async runRequestInterceptors<REQD extends DataType>(
config: Config<REQD>,
): Promise<Config<REQD>> {
let currentConfig = config;
for (const [onFulfilled, onRejected] of this.interceptors.request
.handlers) {
try {
if (onFulfilled) {
currentConfig = (await onFulfilled(currentConfig)) as Config<REQD>;
}
} catch (error) {
if (onRejected) {
currentConfig = (await onRejected(error)) as Config<REQD>;
} else {
throw error;
}
}
}
return currentConfig;
}
/** 依次执行响应拦截器 */
private async runResponseInterceptors<R>(response: R): Promise<R> {
let currentResponse = response;
for (const [onFulfilled, onRejected] of this.interceptors.response
.handlers) {
try {
if (onFulfilled) {
currentResponse = (await onFulfilled(currentResponse)) as R;
}
} catch (error) {
if (onRejected) {
currentResponse = (await onRejected(error)) as R;
} else {
throw error;
}
}
}
return currentResponse;
}
/**
*
*/
async request<
RESPD extends DataType,
REQD extends DataType,
R = Response<RESPD, REQD>
R = Response<RESPD, REQD>,
>(config: Config<REQD>): Promise<R> {
// 合并方法配置 与 实例配置
let newConfig = Object.assign({}, this.config, config);
let newConfig = Object.assign({}, this.config, config) as Config<REQD>;
// 赋值默认URL
newConfig.url = newConfig.url ?? "";
// 如果设置了 baseURL 并且 url 不是绝对路径,则拼接 baseURL
if (newConfig.baseURL && !/https?\/\//.test(newConfig.url)) {
newConfig.url = newConfig.baseURL + newConfig.url;
}
// 执行请求拦截器
this.interceptors.request.forEach((onFulfilled, onRejected) => {
try {
if (onFulfilled) {
newConfig = onFulfilled(newConfig);
}
} catch (error) {
if (onRejected) {
throw onRejected(error);
} else {
throw error;
}
}
});
newConfig = await this.runRequestInterceptors(newConfig);
// 如果设置了 baseURL 并且 url 不是绝对路径,则拼接 baseURL
newConfig.url = joinBaseURL(newConfig.baseURL ?? "", newConfig.url ?? "");
// 发送请求
// let responsePromise = await new Promise<Response<RESPD>>((resolve, reject) => {
// uni.request({
// ...newConfig,
// success(result) {
// resolve(result);
// },
// fail(result) {
// reject(result);
// },
// });
// });
let responsePromise = await (<Promise<R>>uni.request({
let responsePromise = (await (uni.request({
...newConfig,
url: newConfig.url,
}));
}) as Promise<R>)) as R;
// 替换新请求的配置
responsePromise = {
...responsePromise,
config: newConfig,
};
config: newConfig as Config<REQD>,
} as R;
// 执行响应拦截器
this.interceptors.response.forEach((onFulfilled, onRejected) => {
// this.interceptors?.response.handlers.forEach((handler) => {
// const [onFulfilled, onRejected] = handler;
// responsePromise = responsePromise.then(onFulfilled, onRejected);
try {
if (typeof onFulfilled !== "undefined") {
responsePromise = onFulfilled(responsePromise);
}
} catch (error) {
if (typeof onRejected !== "undefined") {
onRejected(error);
} else {
throw error;
}
}
});
responsePromise = await this.runResponseInterceptors(responsePromise);
return responsePromise;
}
@ -156,7 +183,7 @@ export class Request {
/** GET 请求 */
get<RESPD extends DataType, REQD extends DataType, R = Response<RESPD, REQD>>(
url: string,
config?: Config<REQD>
config?: Config<REQD>,
): Promise<R> {
return this.request({ ...config, url, method: "GET" });
}
@ -165,17 +192,17 @@ export class Request {
post<
RESPD extends DataType,
REQD extends DataType,
R = Response<RESPD, REQD>
R = Response<RESPD, REQD>,
>(url: string, data?: REQD, config?: Config<REQD>): Promise<R> {
return this.request({ ...config, url, method: "POST", data });
}
/** PUT 请求 */
put<
RESPD extends DataType,
REQD extends DataType,
R = Response<RESPD, REQD>
>(url: string, data?: REQD, config?: Config<REQD>): Promise<R> {
put<RESPD extends DataType, REQD extends DataType, R = Response<RESPD, REQD>>(
url: string,
data?: REQD,
config?: Config<REQD>,
): Promise<R> {
return this.request({ ...config, url, method: "PUT", data });
}
}

View File

@ -1,4 +1,3 @@
type UploadResponseData = {
originalFileName: string;
url: string;

View File

@ -7,6 +7,6 @@
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
},
}
}
}

File diff suppressed because it is too large Load Diff

45
packages/uni-app/types/nfc/android.d.ts vendored Normal file
View File

@ -0,0 +1,45 @@
export class AndroidNfcUtil {
/**
* NFC
* @returns
*/
static isNfcSupported(): boolean;
/**
* NFC
* @returns {boolean} true
*/
static isNfcEnabled(): Promise<boolean>;
static scan(): Promise<number[]>;
main: PlusAndroidInstanceObject | null;
nfcAdapter: PlusAndroidInstanceObject | null;
pendingIntent: PlusAndroidInstanceObject | null;
intentFiltersArray: PlusAndroidInstanceObject[] | null;
techListsArray: string[][] | null;
discoveredListenerList: Array<(id: number[]) => void>;
/**
*
*/
_discoveredHandler: (() => void) | null;
/**
*
*/
_resumeHandler: (() => void) | null;
/**
* NFC发现监听器
* @param cb NFC ID
*/
addDiscoveredListener(cb: (id: number[]) => void): void;
/**
* NFC扫描
* @returns {Promise<number[]>}
*/
startNfcScan(): Promise<number[]>;
stopNfcScan(): Promise<void>;
/**
* NFC并开启监听
*/
init(): Promise<void>;
resumeHandler(): void;
discoveredHandler(): void;
readId(): number[];
}

6
packages/uni-app/types/nfc/index.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import { AndroidNfcUtil } from "./android";
import { WeixinNfcUtil } from "./weixin";
export function nfcScan(): Promise<number[] | undefined>;
export function isNfcEnabled(): Promise<boolean | undefined>;
export function getNFCUtil(): AndroidNfcUtil | WeixinNfcUtil | undefined;

27
packages/uni-app/types/nfc/weixin.d.ts vendored Normal file
View File

@ -0,0 +1,27 @@
export function startNfcScan(): Promise<number[]>;
export class WeixinNfcUtil {
/**
* NFC
* NOTE
* @returns {boolean} true
*/
static isNfcEnabled(): Promise<boolean>;
static scan(): Promise<number[]>;
nfcAdapter: WechatMiniprogram.NFCAdapter | null;
discoveredListenerList: Array<(id: number[]) => void>;
/**
*
*/
_discoveredHandler:
| ((res: WechatMiniprogram.OnDiscoveredCallbackResult) => void)
| null;
discoveredHandler(res: WechatMiniprogram.OnDiscoveredCallbackResult): void;
/**
* NFC发现监听器
* @param cb NFC ID
*/
addDiscoveredListener(cb: (id: number[]) => void): void;
startNfcScan(): Promise<WechatMiniprogram.NFCError>;
stopNfcScan(): Promise<WechatMiniprogram.NFCError>;
}

View File

@ -1,4 +1,5 @@
import * as QQMapWX from "@jonny1994/qqmap-wx-jssdk";
export * from "@jonny1994/qqmap-wx-jssdk";
/**
*

View File

@ -1,7 +1,7 @@
/// <reference types="@dcloudio/types" />
declare namespace UniNamespace {
type LocaldataItem<T=string> = {
type LocaldataItem<T = string> = {
text: string;
value: T;
children?: LocaldataItem<T>[];
@ -111,7 +111,7 @@ interface PlusIo {
resolveLocalFileSystemURL(
url?: string,
succesCB?: (result: PlusIoFileEntry) => void,
errorCB?: (result: any) => void,
errorCB?: (result: PlusIoDirectoryEntry) => void,
): void;
}

View File

@ -1,32 +1,47 @@
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from "vite";
import dts from "vite-plugin-dts";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const __dirname = fileURLToPath(new URL(".", import.meta.url));
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
formats: ['es', 'cjs'],
fileName: (format) => `index.${format === 'es' ? 'mjs' : 'cjs'}`,
entry: {
index: resolve(__dirname, "src/index.ts"),
"bluetooth-utils/index": resolve(
__dirname,
"src/bluetooth-utils/index.ts",
),
"nfc/index": resolve(__dirname, "src/nfc/index.js"),
"printer/index": resolve(__dirname, "src/printer/index.ts"),
"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"),
},
formats: ["es", "cjs"],
fileName: (format, entryName) =>
`${entryName}.${format === "es" ? "mjs" : "cjs"}`,
},
rollupOptions: {
// uni / plus / wx 是 uni-app 运行时注入的全局变量,无需 external
external: ['vue', 'lodash', /^@r-utils\/.*/],
external: ["vue", "lodash", /^@r-utils\/.*/],
output: {
chunkFileNames: "chunks/[name]-[hash].js",
assetFileNames: "assets/[name]-[hash][extname]",
},
},
sourcemap: true,
},
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
"@": resolve(__dirname, "src"),
},
},
plugins: [
dts({
include: ['src', 'types'],
outDir: 'dist',
include: ["src", "types"],
outDir: "dist",
}),
],
});

View File

@ -0,0 +1,7 @@
# @r-utils/uview-plus
## 1.3.0
### Minor Changes
- 添加工具

View File

@ -1,6 +1,16 @@
# @r-utils/uview-plus
基于 [uview-plus](https://uview-plus.jiangruyi.com/) 的 Vue3 组合式 API 工具 Hooks适用于 uni-app 项目。
在项目已使用 [uview-plus](https://uview-plus.jiangruyi.com/) 的前提下,提供适用于 uview-plus 组件的组合式 API Hooks。
## 适用范围
- 适用于已接入 `uview-plus` 的项目。
- 典型场景是 uni-app + Vue3 + uview-plus。
## 不适用范围
- 未使用 `uview-plus` 的项目不建议使用。
- 不适用于 Vue2 项目。
## 安装
@ -8,102 +18,69 @@
pnpm add @r-utils/uview-plus
```
## 使用
## 导入方式
### 推荐:根入口导入
大多数场景推荐从根入口导入,路径简单,使用心智负担更低。
```ts
import { usePickerSingle, usePicker, useCalendar } from '@r-utils/uview-plus'
import {
usePickerSingle,
usePicker,
useDateTimePicker,
useCalendar,
} from "@r-utils/uview-plus";
```
## API
### 兼容:子路径导入
### `usePickerSingle(options)`
单列 Picker 封装。
| 参数 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `value` | `unknown \| Ref<unknown>` | `null` | 选中的值 |
| `show` | `boolean \| Ref<boolean>` | `false` | 是否显示 |
| `indexes` | `Array<number \| null> \| Ref<...>` | `[null]` | 选中的索引 |
| `list` | `PickerColumns[0] \| Ref<...>` | `[]` | 列数据 |
| `textName` | `string` | `'text'` | 显示字段名 |
| `valueName` | `string` | `'value'` | 值字段名 |
| `placeholder` | `string` | `'请选择'` | 占位文本 |
**返回值:**
如果你希望模块边界更清晰,也可以使用子路径导入。两种方式都支持。
```ts
{
value, show, indexes, columns, text, defaultIndex,
showPicker, hidePicker, handleConfirm, handleClose
}
import { usePickerSingle } from "@r-utils/uview-plus/picker-single";
import { usePicker } from "@r-utils/uview-plus/picker";
import { useDateTimePicker } from "@r-utils/uview-plus/datetime-picker";
import { useCalendar } from "@r-utils/uview-plus/calendar";
```
---
## 导出模块
### `usePicker(options)`
| 子路径 | 说明 |
| --- | --- |
| `@r-utils/uview-plus/picker-single` | 单列 picker Hook |
| `@r-utils/uview-plus/picker` | 多列 picker Hook |
| `@r-utils/uview-plus/datetime-picker` | 时间选择器 Hook |
| `@r-utils/uview-plus/calendar` | 日历选择器 Hook |
多列 Picker 封装。
## 使用示例
| 参数 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `value` | `unknown[] \| Ref<unknown[]>` | `[]` | 选中的值数组 |
| `show` | `boolean \| Ref<boolean>` | `false` | 是否显示 |
| `indexes` | `Array<number \| null> \| Ref<...>` | `[]` | 选中的索引数组 |
| `columns` | `PickerColumns \| Ref<PickerColumns>` | `[]` | 列数据 |
| `textName` | `string` | `'text'` | 显示字段名 |
| `valueName` | `string` | `'value'` | 值字段名 |
| `placeholder` | `string` | `'请选择'` | 占位文本 |
| `separator` | `string` | `' '` | 多列值拼接分隔符 |
**返回值:**
### 单列选择器
```ts
{
value, show, indexes, columns, text, defaultIndex,
showPicker, hidePicker, handleConfirm, handleClose
}
import { usePickerSingle } from "@r-utils/uview-plus";
const picker = usePickerSingle({
list: [
{ text: "启用", value: 1 },
{ text: "禁用", value: 0 },
],
});
picker.showPicker();
```
---
### `useCalendar(options)`
日历选择封装。
| 参数 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `value` | `string \| string[] \| Ref<...>` | `null` | 选中的日期 |
| `show` | `boolean \| Ref<boolean>` | `false` | 是否显示 |
| `mode` | `'single' \| 'multiple' \| 'range' \| Ref<...>` | `'single'` | 日历模式 |
| `placeholder` | `string` | `'请选择'` | 占位文本 |
**返回值:**
### 子路径导入
```ts
{
value, show, text,
showCalendar, hideCalendar, handleConfirm, handleClose
}
import { usePicker } from "@r-utils/uview-plus/picker";
const picker = usePicker({
columns: [[{ text: "浙江", value: "zhejiang" }]],
});
```
## 类型声明
## 注意事项
包内置了 `UViewPlus` namespace 类型声明,无需额外引入。
```ts
declare namespace UViewPlus {
type PickerColumns = any[][];
type PickerValue<T extends PickerColumns = PickerColumns> = T[number][number][];
type PickerConfirmEvent<T extends PickerColumns = PickerColumns> = {
indexs: number[];
value: PickerValue<T>;
values: T;
};
type CalendarConfirmEvent = string[];
}
```
## 许可证
ISC
- 推荐优先使用根入口导入;如果需要更精确的模块边界,也可以使用子路径导入。
- 本包依赖 Vue3 和 uview-plus请确保业务项目已安装并正确配置。

View File

@ -1,6 +1,6 @@
{
"name": "@r-utils/uview-plus",
"version": "1.2.1",
"version": "1.3.0",
"private": false,
"description": "uview-plus 组合式 API Hooks",
"type": "module",
@ -8,13 +8,35 @@
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"sideEffects": false,
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./*": "./*"
"./calendar": {
"types": "./dist/calendar/index.d.ts",
"import": "./dist/calendar/index.mjs",
"require": "./dist/calendar/index.cjs"
},
"./datetime-picker": {
"types": "./dist/datetime-picker/index.d.ts",
"import": "./dist/datetime-picker/index.mjs",
"require": "./dist/datetime-picker/index.cjs"
},
"./picker-single": {
"types": "./dist/picker-single/index.d.ts",
"import": "./dist/picker-single/index.mjs",
"require": "./dist/picker-single/index.cjs"
},
"./picker": {
"types": "./dist/picker/index.d.ts",
"import": "./dist/picker/index.mjs",
"require": "./dist/picker/index.cjs"
}
},
"keywords": [
"vue3",
@ -46,11 +68,12 @@
"scripts": {
"build": "vite build",
"watch": "vite build --watch",
"typecheck": "tsc -p tsconfig.json --noEmit",
"lint": "eslint --ext .js,ts --fix src",
"release": "standard-version",
"format": "prettier --write src",
"commit": "cz",
"lint-staged": "lint-staged",
"test": "jest"
"test": "vitest run"
},
"peerDependencies": {
"uview-plus": ">=3.0.0",
@ -62,9 +85,11 @@
}
},
"dependencies": {
"@jonny1994/qqmap-wx-jssdk": "^1.4.0",
"lodash-es": "catalog:"
},
"devDependencies": {
"@dcloudio/types": "^3.4.14",
"@types/lodash-es": "catalog:",
"vite": "catalog:",
"vite-plugin-dts": "catalog:",

View File

@ -17,7 +17,10 @@ describe("useCalendar", () => {
test("单选模式text 显示 value无值时显示 placeholder", () => {
const scope = effectScope();
scope.run(() => {
const { value, text } = useCalendar({ mode: "single", placeholder: "请选日期" });
const { value, text } = useCalendar({
mode: "single",
placeholder: "请选日期",
});
expect(text.value).toBe("请选日期");
value.value = "2024-01-15";
expect(text.value).toBe("2024-01-15");

View File

@ -50,7 +50,9 @@ describe("useDateTimePicker", () => {
test("handleConfirm 关闭弹窗(不更新 value", () => {
const scope = effectScope();
scope.run(() => {
const { value, show, handleConfirm } = useDateTimePicker({ value: "2024-01-01" });
const { value, show, handleConfirm } = useDateTimePicker({
value: "2024-01-01",
});
show.value = true;
const event = { indexs: [], value: [], values: [] } as any;
handleConfirm(event);

View File

@ -60,7 +60,11 @@ describe("usePicker", () => {
test("indexes 含 null 时 text 显示 placeholder", async () => {
const scope = effectScope();
await scope.run(async () => {
const { text } = usePicker({ indexes: [null, 1], columns, placeholder: "请选择地区" });
const { text } = usePicker({
indexes: [null, 1],
columns,
placeholder: "请选择地区",
});
await nextTick();
expect(text.value).toBe("请选择地区");
});
@ -71,7 +75,11 @@ describe("usePicker", () => {
const scope = effectScope();
await scope.run(async () => {
const { indexes, value, handleConfirm } = usePicker({ columns });
handleConfirm({ indexs: [1, 0], value: ["pb", "ca"], values: columns } as any);
handleConfirm({
indexs: [1, 0],
value: ["pb", "ca"],
values: columns,
} as any);
expect(indexes.value).toEqual([1, 0]);
await nextTick();
expect(value.value).toEqual(["pb", "ca"]);

View File

@ -6,6 +6,6 @@
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
},
}
}
}

View File

@ -0,0 +1,50 @@
import * as QQMapWX from "@jonny1994/qqmap-wx-jssdk";
export * from "@jonny1994/qqmap-wx-jssdk";
/**
*
* @example
* cidx: [103, 118]
* fullname: "张家口市"
* id: "130700"
* location: {lat: 40.82444, lng: 114.88755}
* name: "张家口"
* pinyin: ["zhang", "jia", "kou"]
*/
export interface GetCityListSuccessResultResult {
/**
*
* @example "110000"
*/
id: number;
/**
*
*/
name?: string;
/**
*
* @example "北京市"
*/
fullname: string;
/**
*
* @example {lat: 39.90469, lng: 116.40717}
*/
location: QQMapWX.ResultLocation;
/**
* [nei,meng,gu]
*/
pinyin: string[];
/**
*
* @example [0, 15]
*/
cidx?: number[];
}
export interface GetCityListSuccessResult extends QQMapWX.CommonResult {
/**
* 01使getchildren接口时
*/
result: GetCityListSuccessResultResult[];
}

View File

@ -1,10 +1,9 @@
/// <reference types="uview-plus/types" />
declare namespace UViewPlus {
type PickerColumns = never[][];
type PickerValue<T extends PickerColumns = PickerColumns> = T[number][number][];
type PickerValue<T extends PickerColumns = PickerColumns> =
T[number][number][];
type PickerConfirmEvent<T extends PickerColumns = PickerColumns> = {
indexs: number[];

View File

@ -1,31 +1,48 @@
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from "vite";
import dts from "vite-plugin-dts";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const __dirname = fileURLToPath(new URL(".", import.meta.url));
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
formats: ['es', 'cjs'],
fileName: (format) => `index.${format === 'es' ? 'mjs' : 'cjs'}`,
entry: {
index: resolve(__dirname, "src/index.ts"),
"calendar/index": resolve(__dirname, "src/calendar/index.ts"),
"datetime-picker/index": resolve(
__dirname,
"src/datetime-picker/index.ts",
),
"picker-single/index": resolve(
__dirname,
"src/picker-single/index.ts",
),
"picker/index": resolve(__dirname, "src/picker/index.ts"),
},
formats: ["es", "cjs"],
fileName: (format, entryName) =>
`${entryName}.${format === "es" ? "mjs" : "cjs"}`,
},
rollupOptions: {
external: ['vue', 'lodash-es'],
external: ["vue", "lodash-es"],
output: {
chunkFileNames: "chunks/[name]-[hash].js",
assetFileNames: "assets/[name]-[hash][extname]",
},
},
sourcemap: true,
},
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
"@": resolve(__dirname, "src"),
},
},
plugins: [
dts({
include: ['src', 'types'],
outDir: 'dist',
include: ["src", "types"],
outDir: "dist",
}),
],
});

View File

@ -0,0 +1,7 @@
# @r-utils/vue2
## 1.4.0
### Minor Changes
- 添加工具

76
packages/vue2/README.md Normal file
View File

@ -0,0 +1,76 @@
# @r-utils/vue2
仅用于 Vue2 项目的工具包。
## 适用范围
- 适用于 Vue2 项目。
- 适用于需要根据页面可见性触发组件 `onShow` / `onHide` 的场景。
## 不适用范围
- 不适用于 Vue3 项目。
- 如果是 uni-app 专用能力,建议优先使用 `@r-utils/uni-app`
## 安装
```bash
pnpm add @r-utils/vue2
```
## 导入方式
### 推荐:根入口导入
大多数场景推荐从根入口导入,路径简单,使用心智负担更低。
```ts
import Vue from "vue";
import { VisibilityPlugin } from "@r-utils/vue2";
Vue.use(VisibilityPlugin);
```
也可以使用默认导出:
```ts
import Vue from "vue";
import VisibilityPlugin from "@r-utils/vue2";
Vue.use(VisibilityPlugin);
```
### 兼容:子路径导入
如果你希望模块边界更清晰,也可以使用子路径导入。两种方式都支持。
```ts
import Vue from "vue";
import VisibilityPlugin from "@r-utils/vue2/plugins/visibility";
Vue.use(VisibilityPlugin);
```
## 当前能力
| 子路径 | 说明 |
| --- | --- |
| `@r-utils/vue2/plugins/visibility` | 基于页面可见性变更触发 `onShow` / `onHide` |
## 使用示例
```ts
export default {
onShow() {
console.log("页面显示");
},
onHide() {
console.log("页面隐藏");
},
};
```
## 注意事项
- 推荐优先使用根入口导入;如果需要更精确的模块边界,也可以使用子路径导入。
- 本包依赖 Vue2请确保业务项目已安装兼容版本的 `vue`

View File

@ -1,6 +1,6 @@
{
"name": "@r-utils/vue2",
"version": "1.3.0",
"version": "1.4.0",
"private": false,
"description": "Vue2工具库",
"type": "module",
@ -8,13 +8,20 @@
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"sideEffects": false,
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./*": "./*"
"./plugins/visibility": {
"types": "./dist/plugins/visibility/index.d.ts",
"import": "./dist/plugins/visibility/index.mjs",
"require": "./dist/plugins/visibility/index.cjs"
}
},
"keywords": [
"vue2"
@ -43,8 +50,9 @@
"scripts": {
"build": "vite build",
"watch": "vite build --watch",
"typecheck": "tsc -p tsconfig.json --noEmit",
"lint": "eslint --ext .js,ts --fix src",
"release": "standard-version",
"format": "prettier --write src",
"commit": "cz",
"lint-staged": "lint-staged",
"test": "vitest run"

View File

@ -0,0 +1,22 @@
import type Vue from "vue";
import type { PluginObject, VueConstructor } from "vue";
declare module "vue/types/options" {
interface ComponentOptions<V extends Vue> {
/** 页面变为可见时触发的生命周期钩子 */
onShow?: (this: V) => void;
/** 页面变为隐藏时触发的生命周期钩子 */
onHide?: (this: V) => void;
}
}
/** 安装页面可见性生命周期插件 */
export declare function install(Vue: VueConstructor): void;
/** 页面可见性生命周期插件 */
declare const VisibilityPlugin: PluginObject<never> & {
/** 安装页面可见性生命周期插件 */
install: typeof install;
};
export default VisibilityPlugin;

View File

@ -1,3 +1,7 @@
/**
* 安装页面可见性生命周期插件
* @param {import("vue").VueConstructor} Vue Vue2 构造器
*/
function install(Vue) {
Vue.mixin({
created() {
@ -8,14 +12,14 @@ function install(Vue) {
this.visibilitychangeCallback();
document.addEventListener(
"visibilitychange",
this.visibilitychangeCallback
this.visibilitychangeCallback,
);
}
},
destroyed() {
document.removeEventListener(
"visibilitychange",
this.visibilitychangeCallback
this.visibilitychangeCallback,
);
},
methods: {

View File

@ -6,6 +6,6 @@
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
},
}
}
}

View File

@ -1,31 +1,43 @@
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from "vite";
import dts from "vite-plugin-dts";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const __dirname = fileURLToPath(new URL(".", import.meta.url));
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
formats: ['es', 'cjs'],
fileName: (format) => `index.${format === 'es' ? 'mjs' : 'cjs'}`,
entry: {
index: resolve(__dirname, "src/index.ts"),
"plugins/visibility/index": resolve(
__dirname,
"src/plugins/visibility/index.js",
),
},
formats: ["es", "cjs"],
fileName: (format, entryName) =>
`${entryName}.${format === "es" ? "mjs" : "cjs"}`,
},
rollupOptions: {
external: ['vue', 'lodash'],
external: ["vue", "lodash"],
output: {
chunkFileNames: "chunks/[name]-[hash].js",
assetFileNames: "assets/[name]-[hash][extname]",
exports: "named",
},
},
sourcemap: true,
},
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
"@": resolve(__dirname, "src"),
},
},
plugins: [
dts({
include: ['src'],
outDir: 'dist',
include: ["src"],
outDir: "dist",
}),
],
});

View File

@ -0,0 +1,12 @@
# @r-utils/vue3
## 1.4.0
### Minor Changes
- 添加工具
### Patch Changes
- Updated dependencies
- @r-utils/common@1.4.0

92
packages/vue3/README.md Normal file
View File

@ -0,0 +1,92 @@
# @r-utils/vue3
仅用于 Vue3 项目的工具包,提供 class 处理、组件事件派发和常用组合式 Hooks。
## 适用范围
- 适用于 Vue3 项目。
- 适用于需要复用 Vue3 class 处理、列表加载、表单输入值处理等能力的项目。
## 不适用范围
- 不适用于 Vue2 项目。
- 如果是 uni-app 专用能力,建议优先使用 `@r-utils/uni-app`
## 安装
```bash
pnpm add @r-utils/vue3
```
## 导入方式
### 推荐:根入口导入
大多数场景推荐从根入口导入,路径简单,使用心智负担更低。
```ts
import {
mergeClass,
dispatch,
useLoadMore,
useTimer,
useValueOfRule,
} from "@r-utils/vue3";
```
### 兼容:子路径导入
如果你希望模块边界更清晰,也可以使用子路径导入。两种方式都支持。
```ts
import { mergeClass } from "@r-utils/vue3/vue-helper";
import { useLoadMore } from "@r-utils/vue3/hooks/list";
import { useTimer, useValueOfRule } from "@r-utils/vue3/hooks/utils";
```
## 导出模块
| 子路径 | 说明 |
| --- | --- |
| `@r-utils/vue3/vue-helper` | Vue class 合并、转换和祖先组件事件派发 |
| `@r-utils/vue3/hooks/list` | 列表分页加载 Hook |
| `@r-utils/vue3/hooks/utils` | 常用组合式工具 Hook |
## 使用示例
### 合并 class
```ts
import { mergeClass } from "@r-utils/vue3";
const cls = mergeClass("btn", ["btn-primary"], { active: true });
```
### 列表加载
```ts
import { useLoadMore } from "@r-utils/vue3";
const listState = useLoadMore(async (pageNum, pageSize) => {
return {
total: 100,
list: await fetchList(pageNum, pageSize),
};
});
await listState.loadMore();
```
### 子路径导入 Hook
```ts
import { useTimer } from "@r-utils/vue3/hooks/utils";
const timer = useTimer(60);
timer.start();
```
## 注意事项
- 推荐优先使用根入口导入;如果需要更精确的模块边界,也可以使用子路径导入。
- 本包依赖 Vue3请确保业务项目已安装兼容版本的 `vue`

View File

@ -1,6 +1,6 @@
{
"name": "@r-utils/vue3",
"version": "1.3.0",
"version": "1.4.0",
"private": false,
"description": "Vue3 工具",
"type": "module",
@ -8,13 +8,30 @@
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"sideEffects": false,
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./*": "./*"
"./hooks/list": {
"types": "./dist/hooks/list/index.d.ts",
"import": "./dist/hooks/list/index.mjs",
"require": "./dist/hooks/list/index.cjs"
},
"./hooks/utils": {
"types": "./dist/hooks/utils/index.d.ts",
"import": "./dist/hooks/utils/index.mjs",
"require": "./dist/hooks/utils/index.cjs"
},
"./vue-helper": {
"types": "./dist/vue-helper/index.d.ts",
"import": "./dist/vue-helper/index.mjs",
"require": "./dist/vue-helper/index.cjs"
}
},
"keywords": [
"vue3"
@ -42,8 +59,9 @@
"scripts": {
"build": "vite build",
"watch": "vite build --watch",
"typecheck": "tsc -p tsconfig.json --noEmit",
"lint": "eslint --ext .js,ts --fix src",
"release": "standard-version",
"format": "prettier --write src",
"commit": "cz",
"lint-staged": "lint-staged",
"test": "vitest run"

View File

@ -9,7 +9,7 @@ import type { Ref } from "vue";
*/
export function useTimer(initTime = 0) {
const time = ref(initTime);
const timeInterval = ref();
const timeInterval = ref<ReturnType<typeof setInterval>>();
const start = () => {
timeInterval.value = setInterval(() => {

View File

@ -1 +1,3 @@
export * from "./vue-helper"
export * from "./vue-helper";
export * from "./hooks/list";
export * from "./hooks/utils";

View File

@ -5,10 +5,10 @@ type CustomClass = string | Array<string> | CustomClassObj;
type DistCustomClass = Record<string, true>;
export function createCustomClassObj(customClass: string): DistCustomClass;
export function createCustomClassObj(
customClass: Array<string>
customClass: Array<string>,
): DistCustomClass;
export function createCustomClassObj(
customClass: string | Array<string>
customClass: string | Array<string>,
): DistCustomClass {
let customClassObj = <DistCustomClass>{};
if (typeof customClass === "string") {
@ -26,7 +26,7 @@ export function createCustomClassObj(
}
} else {
throw new TypeError(
`customClass只能是字符串或数组类型customClass: ${customClass}`
`customClass只能是字符串或数组类型customClass: ${customClass}`,
);
}
@ -57,7 +57,7 @@ export function convertCustomClass(sourceClass: CustomClass): CustomClassObj {
customClassObj = sourceClass;
} else {
throw new TypeError(
`sourceClass不是有效的vue classsourceClass: ${sourceClass}`
`sourceClass不是有效的vue classsourceClass: ${sourceClass}`,
);
}
@ -72,7 +72,7 @@ export function convertCustomClass(sourceClass: CustomClass): CustomClassObj {
export function mergeClass(...customClass: CustomClass[]) {
return customClass
.map((cc) => convertCustomClass(cc))
.reduce((a, b) => Object.assign(a, b),{});
.reduce((a, b) => Object.assign(a, b), {});
}
/**
@ -87,7 +87,7 @@ export function dispatch(
thisArg: ComponentPublicInstance,
componentName: ComponentPublicInstance,
eventName: string,
params: unknown
params: unknown,
): void {
let parent = thisArg.$parent || thisArg.$root;
if (parent == null) {

View File

@ -6,6 +6,6 @@
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
},
}
}
}

View File

@ -8,6 +8,7 @@
*/
import * as QQMapWX from "@jonny1994/qqmap-wx-jssdk";
export * from "@jonny1994/qqmap-wx-jssdk";
/**

View File

@ -1,31 +1,41 @@
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from "vite";
import dts from "vite-plugin-dts";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const __dirname = fileURLToPath(new URL(".", import.meta.url));
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
formats: ['es', 'cjs'],
fileName: (format) => `index.${format === 'es' ? 'mjs' : 'cjs'}`,
entry: {
index: resolve(__dirname, "src/index.ts"),
"hooks/list/index": resolve(__dirname, "src/hooks/list/index.ts"),
"hooks/utils/index": resolve(__dirname, "src/hooks/utils/index.ts"),
"vue-helper/index": resolve(__dirname, "src/vue-helper/index.ts"),
},
formats: ["es", "cjs"],
fileName: (format, entryName) =>
`${entryName}.${format === "es" ? "mjs" : "cjs"}`,
},
rollupOptions: {
external: ['vue', 'lodash'],
external: ["vue", "lodash"],
output: {
chunkFileNames: "chunks/[name]-[hash].js",
assetFileNames: "assets/[name]-[hash][extname]",
},
},
sourcemap: true,
},
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
"@": resolve(__dirname, "src"),
},
},
plugins: [
dts({
include: ['src'],
outDir: 'dist',
include: ["src"],
outDir: "dist",
}),
],
});

File diff suppressed because it is too large Load Diff

View File

@ -1,80 +0,0 @@
# 发布所有子包到私有 npm 仓库
# 使用方法: powershell scripts/publish.ps1
# 注意: 发布仓库地址使用各子包 package.json 中的 publishConfig.registry 配置
# 版本管理请先通过 pnpm release (standard-version) 完成,本脚本仅负责构建和发布
$ErrorActionPreference = "Stop"
Write-Host "🚀 开始发布流程" -ForegroundColor Green
Write-Host ""
# 子包列表
$PACKAGES = @(
"packages/common",
"packages/vue3",
"packages/uni-app",
"packages/uview-plus",
"packages/vue2"
)
# 1. 检查工作区是否干净
Write-Host "🔍 检查 Git 工作区状态..." -ForegroundColor Cyan
$gitStatus = git status -s
if ($gitStatus) {
Write-Host "⚠️ 工作区有未提交的更改,请先提交或暂存" -ForegroundColor Yellow
git status -s
$continue = Read-Host "是否继续? (y/N)"
if ($continue -ne "y" -and $continue -ne "Y") {
exit 1
}
}
Write-Host ""
# 2. 运行测试
Write-Host "🧪 运行测试..." -ForegroundColor Cyan
pnpm test
if ($LASTEXITCODE -ne 0) {
Write-Host "❌ 测试失败,停止发布" -ForegroundColor Red
exit 1
}
Write-Host ""
# 3. 构建所有包
Write-Host "📦 构建所有包..." -ForegroundColor Cyan
pnpm build
if ($LASTEXITCODE -ne 0) {
Write-Host "❌ 构建失败,停止发布" -ForegroundColor Red
exit 1
}
Write-Host ""
# 获取当前版本号
$CURRENT_VERSION = node -p "require('./package.json').version"
Write-Host " 当前版本: v$CURRENT_VERSION" -ForegroundColor Gray
Write-Host ""
# 4. 发布每个包
Write-Host "📤 开始发布包到 npm..." -ForegroundColor Cyan
foreach ($package in $PACKAGES) {
if (Test-Path $package) {
Push-Location $package
$PACKAGE_NAME = node -p "require('./package.json').name"
$PACKAGE_VERSION = node -p "require('./package.json').version"
Write-Host "📤 发布 $PACKAGE_NAME@$PACKAGE_VERSION ..." -ForegroundColor Cyan
pnpm publish --no-git-checks
if ($LASTEXITCODE -ne 0) {
Pop-Location
Write-Host "$package 发布失败,停止后续发布" -ForegroundColor Red
exit 1
}
Pop-Location
Write-Host "$PACKAGE_NAME@$PACKAGE_VERSION 发布成功" -ForegroundColor Green
Write-Host ""
} else {
Write-Host "⚠️ 跳过不存在的包: $package" -ForegroundColor Yellow
}
}
Write-Host "🎉 所有包发布完成!版本: v$CURRENT_VERSION" -ForegroundColor Green

View File

@ -1,90 +0,0 @@
#!/bin/bash
# 发布所有子包到私有 npm 仓库
# 使用方法: bash scripts/publish.sh
# 注意: 发布仓库地址使用各子包 package.json 中的 publishConfig.registry 配置
# 版本管理请先通过 pnpm release (standard-version) 完成,本脚本仅负责构建和发布
set -e
echo "🚀 开始发布流程"
echo ""
# 子包列表
PACKAGES=(
"packages/common"
"packages/vue3"
"packages/uni-app"
"packages/vue2"
)
# 1. 检查工作区是否干净
echo "🔍 检查 Git 工作区状态..."
if [[ -n $(git status -s) ]]; then
echo "⚠️ 工作区有未提交的更改,请先提交或暂存"
git status -s
read -p "是否继续? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
exit 1
fi
fi
echo ""
# 2. 运行测试
echo "🧪 运行测试..."
if ! pnpm test; then
echo "❌ 测试失败,停止发布"
exit 1
fi
echo ""
# 3. 构建所有包
echo "📦 构建所有包..."
if ! pnpm build; then
echo "❌ 构建失败,停止发布"
exit 1
fi
echo ""
# 获取当前版本号
CURRENT_VERSION=$(node -p "require('./package.json').version")
echo " 当前版本: v$CURRENT_VERSION"
echo ""
# 4. 发布每个包
echo "📤 开始发布包到 npm..."
for package in "${PACKAGES[@]}"; do
if [ -d "$package" ]; then
PACKAGE_NAME=$(node -p "require('./$package/package.json').name")
PACKAGE_VERSION=$(node -p "require('./$package/package.json').version")
echo "📤 发布 $PACKAGE_NAME@$PACKAGE_VERSION ..."
cd "$package"
if ! pnpm publish --no-git-checks; then
echo "$package 发布失败,停止后续发布"
exit 1
fi
cd - > /dev/null
echo "$PACKAGE_NAME@$PACKAGE_VERSION 发布成功"
echo ""
else
echo "⚠️ 跳过不存在的包: $package"
fi
done
# 5. 推送到远程仓库
echo "🔼 推送到远程仓库..."
read -p "是否推送到远程仓库? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
git push origin master
git push origin --tags
echo "✅ 已推送到远程仓库"
else
echo "⚠️ 跳过推送,请手动执行:"
echo " git push origin master"
echo " git push origin --tags"
fi
echo ""
echo "🎉 所有包发布完成!版本: v$CURRENT_VERSION"

View File

@ -11,7 +11,7 @@
"esModuleInterop": true,
"lib": ["dom", "esnext"],
"allowJs": true,
"declaration": true,
"noEmit": true,
"skipLibCheck": true
}
}

View File

@ -1,11 +1,6 @@
{
"extends": "./tsconfig.base.json",
"include": [
"vitest.config.ts",
"packages/*/src/**/*.ts",
"packages/*/src/**/*.js",
"packages/*/types/**/*.d.ts"
],
"include": ["vitest.config.ts", "packages/*/src/**/*.ts", "packages/*/src/**/*.js", "packages/*/types/**/*.d.ts"],
"exclude": ["**/node_modules/**", "**/dist/**"],
"compilerOptions": {
"noEmit": true

26
turbo.json Normal file
View File

@ -0,0 +1,26 @@
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"watch": {
"cache": false,
"persistent": true
},
"lint": {
"outputs": []
},
"format": {
"outputs": []
},
"typecheck": {
"outputs": []
},
"test": {
"dependsOn": ["^build"],
"outputs": []
}
}
}