Files
harmony-client/docs/conventions.md

71 lines
3.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Conventions(编码规范)
ArkTS(TypeScript 的超集,HarmonyOS 严格类型方言)+ ArkUI 声明式 UI。
## 命名 Naming
| 元素 Element | 规则 Rule | 示例 Example |
|-------------|----------|-------------|
| 组件 / Ability | `PascalCase` | `LoginPage`, `EntryAbility` |
| 文件 | 与组件同名 `.ets` | `LoginPage.ets` |
| 变量 / 函数 / 属性 | `camelCase` | `userName`, `fetchData()` |
| 常量 | `UPPER_SNAKE_CASE` | `MAX_RETRY_COUNT` |
| 布尔变量 | `is`/`has`/`can` 前缀 | `isLoading`, `hasError` |
## 严格类型 Strict Typing
- **禁止** `any`、`@ts-ignore`、`@ts-expect-error`。
- 类型搞不定 = 设计有问题,重构类型而不是绕过它。
- 优先 `interface` / `enum`,复杂类型放 `model/`。
## 声明式 UI 与状态 Declarative UI & State
- UI 由状态驱动:改状态 → 自动重渲染,禁止命令式直接改 UI。
- 状态管理**全量使用 StateManagement V2**(禁用 V1 装饰器):
- 组件/页面 `@ComponentV2`
- 局部状态 `@Local`
- 父子传递 `@Param`(单向输入)/ `@Event`(子→父回调,**不用 `@Link`**)
- 类可观察 `@ObservedV2` + `@Trace`(字段级精准刷新)
- 跨层共享 `@Provider` / `@Consumer`;变化监听 `@Monitor`
- 全局/持久化 `AppStorageV2` / `PersistenceV2`
- 避免不必要的重渲染:`@Trace` 字段粒度要细,不要一个大对象整体刷新。
## 资源 Resources
- 颜色 / 间距 / 字号统一走 `uikit/theme/Theme.ets` 的 token(`AppColor` / `AppSpacing` / `AppFontSize`),禁止在组件里散落颜色/尺寸魔法值。
- 用户可见文案:优先 `$r('app.string.xxx')`(便于国际化);临时/演示文案可内联,正式功能应收口到资源。
- 图片/图标等媒体:`$r('app.media.xxx')`。
## 组件化 Components
- 页面:`@Entry @ComponentV2`,放 `pages/`,仅编排(组合 view + viewmodel,不含业务逻辑)。
- 业务复用组件:`@ComponentV2`,放 `view/`,通过 `@Param`(输入)/ `@Event`(回调)与外界通信,不直接依赖业务层。
- 跨模块通用组件:下沉到 `uikit/`(`uikit/src/main/ets/components/`)。
- 长列表复用用 `@Reusable`。
## 分层与依赖方向 Layering
`pages → viewmodel → data(repository/api) → model`。禁止反向依赖(如 `model` import `repository`)。
- `viewmodel` 只依赖 `data/repository` 的抽象契约;`repository` 实现依赖 `data/api` + `common` 网络层。
- 跨模块依赖:`entry → common / uikit`;`common`、`uikit` 相互独立,禁止反向/循环依赖。
架构越界由约定 + 人工审查把关(ArkTS 侧暂无现成的依赖方向 linter)。
## 安全 Security
`code-linter.json5` 已启用 `@security/*` 规则,**改动不得引入不安全算法**:
- 禁用不安全哈希(MD5/SHA1)、不安全 AES 模式、3DES、弱 RSA/DH 密钥等。
- 需要加密时优先系统安全 API(如 `@ohos.security.cryptoFramework` 的安全模式)。
## 性能 Performance
`code-linter.json5` 已启用 `@performance/recommended`:
- 长列表用 `LazyForEach` + `@Reusable`,不要 `ForEach` 渲染大量节点。
- 避免在 `build()` 里做重计算/创建新对象。
- 大图/列表项懒加载,图片用合适的缓存策略。
## 改动后验证 Verify After Change
- 跑 lint:DevEco 里 Code Linter,或 hvigor 对应任务。
- 跑相关测试:见 `docs/testing.md`。
- 提交前确认 `code-linter.json5` 无新增 error。