diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 339e07d10..29f662fa8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -688,14 +688,11 @@ jobs: path: ${{ runner.temp }}/openless-android-emulator.log if-no-files-found: ignore - # HarmonyOS covers three layers, in three places: - # * the Rust host is compiled and tested by the Linux job - # (`cargo test --locked -p openless-harmony-host`); - # * ArkTS cannot be compiled without the Huawei SDK, so this job checks what - # is reproducible on a hosted runner: the committed IPC audit still matches - # the code, the ArkTS contract tests pass, and the ArkWeb bundle builds; - # * when `HARMONY_SDK_URL` is configured, the last step additionally builds a - # real HAP, which is what actually type-checks the ArkTS sources. + # HarmonyOS has one native ArkUI project in openless-all/harmony. This job + # verifies the shared IPC report and ArkTS behavior/structure contracts, then + # packages a real unsigned HAP with the checksum-pinned Huawei SDK so ArkTS + # sources and the Rust host are compiled. No React/ArkWeb bundle is embedded. + # Linux validation separately covers Rust host unit tests when explicitly enabled. harmony-check: needs: [changes] if: needs.changes.outputs.desktop-only != 'true' && (github.event_name != 'workflow_dispatch' || inputs.platform != 'macos') && needs.changes.outputs.harmony != 'false' @@ -721,20 +718,38 @@ jobs: # report hides commands that the Harmony host does not implement yet. run: | node ../harmony/scripts/audit-harmony-ipc.mjs --check + # Guards the gate itself: a stale report must fail the check and `--check` + # must stay read-only, so a later audit change cannot silently weaken it. + - name: Harmony IPC audit gate regression + run: | + node scripts/harmony-ipc-audit-check.test.mjs + - name: Harmony SDK setup regression + run: node scripts/harmony-sdk-prepare.test.mjs - name: Harmony ArkTS contracts run: | + set -euo pipefail node scripts/harmony-entry-startup.test.mjs node scripts/harmony-app-dictation.test.mjs node scripts/harmony-voice-configuration.test.mjs + node scripts/harmony-siwc.test.mjs node scripts/harmony-panel-layout.test.mjs node scripts/harmony-editor-compat.test.mjs node scripts/harmony-clipboard-history.test.mjs node scripts/harmony-symbol-gesture.test.mjs node scripts/harmony-rime-startup.test.mjs - # The ArkWeb bundle is not built here: `package-harmony-hap.sh` -> - # `build-harmony-frontend.sh` runs the same - # `npm run build -- --base=./ --outDir=…`, so building it twice only - # doubled the vite pass. + node scripts/harmony-native-ui.test.mjs + node scripts/harmony-responsive-ui.test.mjs + node scripts/harmony-system-speech.test.mjs + node scripts/harmony-ios-parity.test.mjs + node scripts/harmony-window-layout.test.mjs + node scripts/harmony-release-contract.test.mjs + node scripts/harmony-history-actions.test.mjs + node scripts/harmony-library-actions.test.mjs + node scripts/harmony-credential-actions.test.mjs + node scripts/harmony-core-contracts.test.mjs + node scripts/harmony-click-surfaces.test.mjs + # The HAP ships native ArkUI, so packaging builds the Rust host with the + # pinned SDK and skips the React bundle. - uses: dtolnay/rust-toolchain@stable with: # Tier-2 OHOS target; `rustup target list` above lists it for stable. @@ -744,7 +759,7 @@ jobs: workspaces: 'openless-all/app -> target' # The HAP embeds a release cdylib; keep its own key so the debug trees # of the other jobs do not evict it. - key: harmony-host + shared-key: harmony-host save-if: ${{ github.ref == 'refs/heads/beta' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }} # No toolchain cache. The download is 2.1 GB at ~100 MB/s plus ~70 s to diff --git a/.github/workflows/release-harmony.yml b/.github/workflows/release-harmony.yml index eab9ffad5..859a8b09b 100644 --- a/.github/workflows/release-harmony.yml +++ b/.github/workflows/release-harmony.yml @@ -1,7 +1,8 @@ name: Release HarmonyOS -# HarmonyOS ships its HAP in the same GitHub Release as the desktop, Android and -# Linux assets, and the same package is pushed to HUAWEI AppGallery Connect. +# HarmonyOS attaches its unsigned HAP to the shared desktop/Android draft. +# Store channels upload a separately signed App Pack to AppGallery Connect; +# published GitHub Release assets are immutable and Linux automation is paused. # # The build uses the official HarmonyOS command-line tools. Huawei's own download # page needs an account, but the same archive is mirrored publicly (the mirror @@ -12,8 +13,8 @@ name: Release HarmonyOS # Override `HARMONY_SDK_URL` / `HARMONY_SDK_SHA256` when a newer tools release is # needed, and `runner_labels` for a machine that already has the tools installed. # -# Dispatch it after the tag exists; it rebuilds that tag, signs it with material -# from Secrets, attaches the HAP to the Release and uploads it to AppGallery. +# An administrator may dispatch after the tag exists to repair its draft. +# The checked-out tag supplies the app; signing material comes only from Secrets. # `release-tauri.yml` calls this workflow in parallel with desktop and Android # after a short shared-draft preflight, using the same immutable tag commit. # Manual dispatch remains the repair path; automatic channel is @@ -136,6 +137,16 @@ jobs: ref: ${{ github.event_name == 'push' && github.sha || inputs.tag }} submodules: false + - name: Require a draft before publishing + if: inputs.publish + run: | + set -euo pipefail + draft=$(gh release view "$RELEASE_TAG" --json isDraft --jq .isDraft) + if [ "$draft" != true ]; then + echo "::error::Published Release assets are immutable; repair the draft before publication" + exit 1 + fi + - uses: actions/setup-java@v4 with: distribution: temurin @@ -145,13 +156,9 @@ jobs: with: node-version: '22' - # The HAP build shells out to `npm run build` for the ArkWeb bundle and to - # `cargo build --target aarch64-unknown-linux-ohos` for the Rust host, so it - # needs the app's `node_modules` and the Tier-2 OHOS target std. A hosted - # runner ships neither, and both gaps only surface minutes into the build - - # the first real dispatch of this workflow died with `can't find crate for - # `core`` (error[E0463]) after compiling the Rime/NDK tree. Install them up - # front, exactly like `ci.yml`'s `harmony-check` does. + # Current HAPs compile native ArkUI plus the Rust host, not the React bundle. + # Keep Node dependencies available for checked-out tag tooling, including + # guarded historical repairs, and install the Tier-2 OHOS target up front. - name: Cache npm from beta uses: ./.github/actions/cache-npm @@ -168,9 +175,9 @@ jobs: - uses: swatinem/rust-cache@v2 with: workspaces: 'openless-all/app -> target' - # Same key as `ci.yml`'s `harmony-check`: a tag build restores the tree - # that job already paid for, and a tag never writes to the cache. - key: harmony-host + # A job-independent shared key restores `ci.yml`'s `harmony-check` + # tree despite this job's different name. Tags never write the cache. + shared-key: harmony-host save-if: ${{ github.ref == 'refs/heads/beta' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }} # No toolchain cache here either: `prepare-harmony-sdk.sh` downloads the @@ -371,11 +378,11 @@ jobs: working-directory: openless-all/app run: | set -euo pipefail - # Automatic builds already have a shared draft: never wait for desktop. - # Direct manual dispatch still supports explicit published-tag repairs. + # Re-check immediately before writing: an admin may publish while the + # build runs. Manual repair has the same immutable-asset boundary. draft=$(gh release view "$RELEASE_TAG" --json isDraft --jq .isDraft) - if [ "${{ github.event_name }}" = push ] && [ "$draft" != true ]; then - echo "::error::Release was published while building; refusing automatic mutation" + if [ "$draft" != true ]; then + echo "::error::Published Release assets are immutable; refusing mutation" exit 1 fi output=target/harmony-packages diff --git a/.gitignore b/.gitignore index baec5839f..c83bcc3da 100644 --- a/.gitignore +++ b/.gitignore @@ -168,3 +168,6 @@ coverage/ /docs/test-captures/ /docs/test-results/ /openless-all/ios/docs/screenshots/ + +# Local iOS demo videos, extracted frames and UI reference captures. +/.refs/ diff --git a/openless-all/README.md b/openless-all/README.md index 008ced248..b1e70985a 100644 --- a/openless-all/README.md +++ b/openless-all/README.md @@ -11,12 +11,12 @@ This directory contains the cross-platform OpenLess source tree. Start with the | `app/crates/openless-core` | Framework-independent shared Rust core (dictation engine, ASR/LLM/Multimodal/DeepSeek-suite pipelines, style packs, dictionary, cloud sync, backend contract `2.0.0`). | | `app/crates/micyou-dsp`, `app/crates/micyou-infer` | Audio DSP preprocessing and inference crates. | | `app/crates/openless-capsule`, `app/native-capsule` | Native recording capsule state and platform UI support. | -| `app/src` | Shared React + TypeScript frontend for Tauri desktop/Android and HarmonyOS ArkWeb. | +| `app/src` | Shared React + TypeScript frontend for Tauri desktop and Android. | | `app/src-tauri` | macOS, Windows, and Android Tauri host, native adapters, and vendored crates (`src-tauri/vendor/`). | | `app/ask-window` | Standalone Ask Anything desktop window assets and bridge. | | `linux/egui` | Native Linux host and `egui`/`eframe` UI (no Tauri or WebKitGTK dependency). | | `android` | Android host packaging, manifest merges, and native glue. | -| `harmony` | HarmonyOS ArkTS + ArkWeb host and `harmony/rust` Node-API bridge. | +| `harmony` | Native HarmonyOS ArkUI host and `harmony/rust` Node-API bridge. | | `app/mobile-ime` | Shared native input-method core for Android and HarmonyOS. | | `windows/ime` | Windows TSF/IME integration scripts and helpers. | | `windows/nsis`, `windows/wix`, `windows/scripts` | Windows installer assets and build/acceptance tools. | @@ -138,17 +138,6 @@ powershell -ExecutionPolicy Bypass -File .\..\windows\scripts\windows-hotkey-inj See [`android/README.md`](android/README.md#build-and-ci) for Android SDK/NDK versions, generated Tauri Android scaffolding, APK builds across ABIs (`arm64-v8a`, `armeabi-v7a`, `x86_64`, `x86`), and device verification. -## HarmonyOS Build - -Requirements: HarmonyOS Command Line Tools (`../harmony/scripts/prepare-harmony-sdk.sh` fetches the pinned archive with SHA-256 verification), Python 3, Node.js 22+, and `rustup target add aarch64-unknown-linux-ohos`. - -```bash -cd openless-all/app -bash ../harmony/scripts/build-harmony-frontend.sh -``` - -Unsigned HAP output is placed under `${OPENLESS_CACHE_ROOT:-/data-win/openless-cache}/harmony/openless-project/entry/build/default/outputs/default/`. The packaging script stages deliverables in `app/target/harmony-packages/`. See [`RELEASING.md`](../RELEASING.md) for release signing and AppGallery uploads. - ## iOS Build iOS (`ios/`) is a native Swift + Rust project targeting iOS 16+ (Recording Widget requires iOS 18+) with independent versioning. See the [iOS build & signing guide](ios/README.md#build-from-source) for bootstrapping dependencies, building `CoreHost` and Rime, personal Xcode signing, simulator runs, and unsigned IPA packaging. diff --git a/openless-all/README.zh.md b/openless-all/README.zh.md index 2a604e34c..c4a0b72c8 100644 --- a/openless-all/README.zh.md +++ b/openless-all/README.zh.md @@ -11,12 +11,12 @@ | `app/crates/openless-core` | 框架无关的共享 Rust 核心(听写引擎、ASR / LLM / 多模态 / DeepSeek 大统一管线、风格包、词典、加密云同步与 `2.0.0` 后端契约)。 | | `app/crates/micyou-dsp`、`app/crates/micyou-infer` | 音频 DSP 前处理与推理支持库。 | | `app/crates/openless-capsule`、`app/native-capsule` | 原生语音胶囊状态与平台渲染支撑。 | -| `app/src` | Tauri 桌面/Android 与 HarmonyOS ArkWeb 共用的 React + TypeScript 前端界面。 | +| `app/src` | Tauri 桌面与 Android 共用的 React + TypeScript 前端界面。 | | `app/src-tauri` | macOS、Windows 与 Android 的 Tauri 宿主、原生适配层及内置 vendored 依赖(`src-tauri/vendor/`)。 | | `app/ask-window` | 桌面端独立「随便问」窗口界面与桥接代码。 | | `linux/egui` | Linux 原生宿主与 `egui` / `eframe` 界面(不依赖 Tauri 或 WebKitGTK)。 | | `android` | Android 宿主打包、清单合并与原生胶水代码。 | -| `harmony` | HarmonyOS ArkTS + ArkWeb 宿主及 `harmony/rust` Node-API 桥接。 | +| `harmony` | HarmonyOS 原生 ArkUI 宿主及 `harmony/rust` Node-API 桥接。 | | `app/mobile-ime` | Android 与 HarmonyOS 共享的移动端原生输入法核心。 | | `windows/ime` | Windows TSF / 输入法注册与测试脚本。 | | `windows/nsis`、`windows/wix`、`windows/scripts` | Windows 安装器资产与构建、验收工具。 | @@ -138,17 +138,6 @@ powershell -ExecutionPolicy Bypass -File .\..\windows\scripts\windows-hotkey-inj Android SDK/NDK 依赖、脚手架生成、多架构 APK(`arm64-v8a`、`armeabi-v7a`、`x86_64`、`x86`)构建与真机验证见 [Android 构建指南](android/README.zh.md#构建与-ci)。 -## HarmonyOS 构建 - -依赖环境:HarmonyOS Command Line Tools(可用 `../harmony/scripts/prepare-harmony-sdk.sh` 按固定 SHA-256 拉取)、Python 3、Node.js 22+ 以及 `rustup target add aarch64-unknown-linux-ohos`。 - -```bash -cd openless-all/app -bash ../harmony/scripts/build-harmony-frontend.sh -``` - -未签名 HAP 输出到 `${OPENLESS_CACHE_ROOT:-/data-win/openless-cache}/harmony/openless-project/entry/build/default/outputs/default/`;打包脚本将交付文件暂存到 `app/target/harmony-packages/`。正式签名与 AppGallery 上传流程见 [`RELEASING.zh.md`](../RELEASING.zh.md)。 - ## iOS 构建 iOS 端(`ios/`)为独立的原生 Swift + Rust 工程,应用与键盘面向 iOS 16+(录制小组件需 iOS 18+),采用独立版本号。完整依赖拉取、`CoreHost` 与 Rime 构建、个人证书签名、模拟器调试与未签名 IPA 打包步骤见 [iOS 构建指南](ios/README.zh.md#从源码构建)。 diff --git a/openless-all/app/scripts/ci-cache-sharing.test.mjs b/openless-all/app/scripts/ci-cache-sharing.test.mjs index 6aa352717..73995910a 100644 --- a/openless-all/app/scripts/ci-cache-sharing.test.mjs +++ b/openless-all/app/scripts/ci-cache-sharing.test.mjs @@ -65,6 +65,20 @@ for (const key of ['tauri-windows', 'tauri-macos']) { assert.ok(sharedKeys(release).includes(key), `release-tauri.yml must restore shared-key ${key}`); } +// Harmony CI and release have different job ids. An additive `key` alone keeps +// those ids in rust-cache's default key and cannot reuse the beta producer. +for (const [yaml, label] of [ + [ci.match(/\n harmony-check:[\s\S]*?(?=\n [a-z-]+:\n)/)?.[0] ?? '', 'ci.yml/harmony-check'], + [releaseHarmony, 'release-harmony.yml/build-harmony-hap'], +]) { + assert.match(yaml, /shared-key: harmony-host/, label + ' needs one job-independent key'); + assert.doesNotMatch(yaml, /^\s+key: harmony-host$/m); + assert.match( + yaml, + /save-if: \$\{\{ github\.ref == 'refs\/heads\/beta' && \(github\.event_name == 'push' \|\| github\.event_name == 'workflow_dispatch'\) \}\}/, + ); +} + // 2. The release workflow must not keep a private key: that is what made tag // builds cold (the baseline branch never wrote it). assert.doesNotMatch(release, /key:\s*macos-release/); diff --git a/openless-all/app/scripts/ci-changed-areas.test.mjs b/openless-all/app/scripts/ci-changed-areas.test.mjs index 124ce595c..36ba20436 100644 --- a/openless-all/app/scripts/ci-changed-areas.test.mjs +++ b/openless-all/app/scripts/ci-changed-areas.test.mjs @@ -137,6 +137,37 @@ try { }); reset(); + // Every native UI module and delivery script stays inside the Harmony gate; + // unknown host paths must not fall through to a desktop-only classification. + for (const path of [ + 'openless-all/harmony/entry/src/main/ets/components/ProductNavigation.ets', + 'openless-all/harmony/entry/src/main/ets/common/Breakpoint.ets', + 'openless-all/harmony/entry/src/main/resources/base/element/color.json', + 'openless-all/harmony/scripts/build-harmony-app.sh', + ]) { + commit({ [path]: '// native Harmony input\n' }, 'native Harmony input'); + expect(path, { ...every('false'), harmony: 'true' }); + reset(); + } + + // Mixed browser/native changes still run both gates; removing the ArkWeb edge + // must never turn a real ArkTS change into a skipped HAP type-check. + commit( + { + 'openless-all/app/src/features/style-packs/Style.tsx': 'export const x = 1;\n', + 'openless-all/harmony/entry/src/main/ets/pages/OverviewPage.ets': 'export {};\n', + }, + 'mixed browser and ArkUI changes', + ); + expect('mixed browser and ArkUI changes', { + tauri: 'true', + harmony: 'true', + frontend: 'true', + linux: 'false', + android: 'false', + }); + reset(); + // The Linux workflow owns Harmony Rust unit tests as well as the egui host. commit({ 'openless-all/harmony/rust/src/lib.rs': 'pub fn x() {}\n' }, 'harmony rust'); expect('harmony rust', { @@ -193,9 +224,8 @@ try { }); reset(); - // The rendered bundle is embedded by every shell that paints it; the Linux - // host draws a native egui UI and never reads `dist/`, and the Android job only - // compiles Rust, so neither is in scope. + // Browser-only changes do not reach native ArkUI/egui hosts. The Android + // compile gate builds Rust, so it is also outside a bundle-only change. commit( { 'openless-all/app/src/features/style-packs/Style.tsx': 'export const x = 1;\n' }, 'frontend only', @@ -204,7 +234,7 @@ try { tauri: 'true', msrv: 'false', linux: 'false', - harmony: 'true', + harmony: 'false', frontend: 'true', android: 'false', 'ios-device': 'false', @@ -252,7 +282,7 @@ try { tauri: 'true', msrv: 'false', frontend: 'true', - harmony: 'true', + harmony: 'false', android: 'false', linux: 'false', }); diff --git a/openless-all/app/scripts/ci-impact.mjs b/openless-all/app/scripts/ci-impact.mjs index 504479207..c9ab9317a 100644 --- a/openless-all/app/scripts/ci-impact.mjs +++ b/openless-all/app/scripts/ci-impact.mjs @@ -278,11 +278,11 @@ function classify(file, context) { const tags = new Set(); if (motionSurface(file)) { - // The bundle is embedded in every shell that renders it. The Linux host uses - // a native egui UI and does not consume `dist/` at all, and the Android job - // only compiles the Rust crate (`npm run build` there just satisfies - // `generate_context!`), so neither is in scope for a bundle-only change. - for (const tag of ['frontend', 'macos', 'windows', 'harmony']) tags.add(tag); + // Only browser-rendered shells consume the bundle. HarmonyOS builds native + // ArkUI and Linux uses egui; neither reads `dist/`. The Android job only + // compiles Rust (`npm run build` satisfies `generate_context!`), so it is + // outside a bundle-only change too. Shared manifests/resources stay fail-open. + for (const tag of ['frontend', 'macos', 'windows']) tags.add(tag); } const owner = ownerPackage(file, context); diff --git a/openless-all/app/scripts/ci-workflow-behavior.test.mjs b/openless-all/app/scripts/ci-workflow-behavior.test.mjs index d46e4fccb..bf23c0ce3 100644 --- a/openless-all/app/scripts/ci-workflow-behavior.test.mjs +++ b/openless-all/app/scripts/ci-workflow-behavior.test.mjs @@ -144,6 +144,9 @@ case "$name" in *'emu kill'*) kill -TERM "$(cat "$RUNNER_TEMP/emulator.pid")" 2>/dev/null || true ;; esac ;; + node) + [ "\${1:-}" != "\${FAKE_NODE_FAIL_ON:-}" ] || exit 19 + ;; cargo) [ "\${FAKE_CARGO_EXIT:-0}" = 0 ] || exit "$FAKE_CARGO_EXIT" if [ "\${FAKE_HOTKEY_MATCH:-1}" = 1 ]; then @@ -152,7 +155,13 @@ case "$name" in echo 'test result: ok. 0 passed; 1381 filtered out' fi ;; - gh) [ "$GH_REPO" = 'example/openless' ] ;; + gh) + [ "$GH_REPO" = 'example/openless' ] + if [ "\${1:-}" = release ] && [ "\${2:-}" = view ]; then + [ "\${FAKE_GH_VIEW_EXIT:-0}" = 0 ] || exit "$FAKE_GH_VIEW_EXIT" + printf '%s\\n' "\${FAKE_RELEASE_DRAFT-true}" + fi + ;; esac `; function fixture(name) { @@ -170,6 +179,7 @@ function fixture(name) { 'timeout', 'adb', 'cargo', + 'node', 'gh', 'sudo', ]) @@ -224,6 +234,60 @@ function fixture(name) { return { dir, sdk, run, trace, count, seed }; } try { + { + const job = ci.jobs['harmony-check']; + const steps = job.steps; + const contracts = steps.find((step) => step.name === 'Harmony ArkTS contracts'); + const build = steps.find( + (step) => step.name === 'Build the HAP (compiles ArkTS and the Rust host)', + ); + const expected = [ + 'entry-startup', + 'app-dictation', + 'voice-configuration', + 'siwc', + 'panel-layout', + 'editor-compat', + 'clipboard-history', + 'symbol-gesture', + 'rime-startup', + 'native-ui', + 'responsive-ui', + 'system-speech', + 'ios-parity', + 'window-layout', + 'release-contract', + 'history-actions', + 'library-actions', + 'credential-actions', + 'core-contracts', + 'click-surfaces', + ].map((name) => `scripts/harmony-${name}.test.mjs`); + const invoked = [...contracts.run.matchAll(/^\s*node (\S+)\s*$/gm)].map((match) => match[1]); + assert.deepEqual(invoked, expected, 'every native Harmony regression runs in CI'); + assert.ok( + steps.indexOf(contracts) < steps.indexOf(build), + 'fast contracts precede SDK compilation', + ); + assert.equal( + build.env.OPENLESS_HARMONY_CHANNEL, + 'none', + 'CI must not consume store signing material', + ); + assert.match(build.run, /bash \.\.\/harmony\/scripts\/package-harmony-hap\.sh/); + assert.match(build.run, /--allow-unsigned/); + assert.doesNotMatch(build.run, /npm run build|build-harmony-frontend/); + for (const [label, failed, count, status] of [ + ['all-pass', '', expected.length, 0], + ['ui-failure', expected[9], 10, 19], + ['rotation-failure', expected[13], 14, 19], + ]) { + const test = fixture('harmony-contracts-' + label); + const result = test.run(contracts.run, { FAKE_NODE_FAIL_ON: failed }); + assert.equal(result.status, status, label + ': ' + result.stderr); + assert.equal(test.count('node'), count, 'a failed contract stops the job: ' + label); + } + } { const test = fixture('emulator-disk-cleanup'); const cache = join(test.dir, 'openless-cache/mobile-rime'); @@ -311,6 +375,34 @@ try { /gradle .*:app:connectedX86_64DebugAndroidTest -x :app:rustBuildX86_64Debug --no-daemon/, ); } + // Execute the actual Harmony workflow guards with a fake GitHub CLI. Both + // early preflight and the final write must reject published or unreadable + // state, including manual repair runs; a tag build may only mutate a draft. + for (const stepName of [ + 'Require a draft before publishing', + 'Attach the HAP to the GitHub Release', + ]) { + const step = harmony.jobs['build-harmony-hap'].steps.find((item) => item.name === stepName); + assert.ok(step, stepName); + assert.equal(step.if, 'inputs.publish'); + for (const [name, env, expected] of [ + ['draft', { FAKE_RELEASE_DRAFT: 'true' }, 0], + ['published', { FAKE_RELEASE_DRAFT: 'false' }, 1], + ['empty', { FAKE_RELEASE_DRAFT: '' }, 1], + ['malformed', { FAKE_RELEASE_DRAFT: 'null' }, 1], + ['api-failure', { FAKE_GH_VIEW_EXIT: '7' }, 7], + ]) { + const test = fixture('harmony-draft-' + stepName.replaceAll(' ', '-') + '-' + name); + const result = test.run(step.run, env); + assert.equal(result.status, expected, stepName + '/' + name + ': ' + result.stderr); + assert.equal(test.count('gh'), expected === 0 && stepName.startsWith('Attach') ? 2 : 1); + assert.equal( + /gh release upload/.test(test.trace()), + expected === 0 && stepName.startsWith('Attach'), + 'a failed draft guard must never upload assets', + ); + } + } { const test = fixture('signing-passwords'); const signing = join(test.dir, 'signing'); diff --git a/openless-all/app/scripts/harmony-app-dictation.test.mjs b/openless-all/app/scripts/harmony-app-dictation.test.mjs index 3c092219d..ab96ae33c 100644 --- a/openless-all/app/scripts/harmony-app-dictation.test.mjs +++ b/openless-all/app/scripts/harmony-app-dictation.test.mjs @@ -13,7 +13,13 @@ const compiled = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, }).outputText; function host(granted = true) { - const events = []; + // The native UI has no DOM: the capability layer publishes dictation state into + // AppStorage, and pages observe it with @StorageLink. + const store = new Map(); + const AppStorage = { + setOrCreate: (key, value) => store.set(key, value), + get: (key) => store.get(key), + }; let starts = 0, cancels = 0, level, @@ -38,6 +44,7 @@ function host(granted = true) { vm.runInNewContext(compiled, { exports, console, + AppStorage, VoiceClient, abilityAccessCtrl: { GrantStatus: { PERMISSION_GRANTED: 0 }, @@ -48,24 +55,15 @@ function host(granted = true) { }, }); const api = new exports.HarmonyApi(); - api.configure( - { applicationInfo: { accessTokenId: 1 } }, - { - runJavaScript: async (code) => - vm.runInNewContext(code, { - window: { dispatchEvent: (event) => events.push(event) }, - CustomEvent: class { - constructor(type, options) { - this.type = type; - this.detail = options?.detail; - } - }, - }), - }, - ); + api.configure({ applicationInfo: { accessTokenId: 1 } }); return { api, - events, + realtime: () => ({ + phase: store.get('dictPhase'), + level: store.get('dictLevel'), + error: store.get('dictError'), + }), + backendChanges: () => store.get('backendRevision') ?? 0, starts: () => starts, cancels: () => cancels, level: (value) => level(value), @@ -77,8 +75,11 @@ function host(granted = true) { startup = reply; }, invoke: async (command) => JSON.parse(await api.invokeAsync(command, '{}')), - last: () => - events.filter((event) => event.type === 'openless:harmony-dictation').at(-1)?.detail, + last: () => ({ + phase: store.get('dictPhase'), + level: store.get('dictLevel'), + error: store.get('dictError'), + }), }; } const normal = host(); @@ -96,7 +97,7 @@ assert.equal( const completed = await normal.invoke('stop_dictation'); assert.deepEqual(completed.value, { rawText: '模拟识别', polishedText: '模拟润色' }); assert.equal(normal.last().phase, 'idle'); -assert(normal.events.some((event) => event.type === 'openless:harmony-backend-change')); +assert.equal(normal.backendChanges(), 1, 'a finished recording bumps the backend revision so the lists reload'); normal.fail('迟到的回调'); assert.equal(normal.last().error, '', 'finished sessions ignore late callbacks'); diff --git a/openless-all/app/scripts/harmony-click-surfaces.test.mjs b/openless-all/app/scripts/harmony-click-surfaces.test.mjs new file mode 100644 index 000000000..118fd91aa --- /dev/null +++ b/openless-all/app/scripts/harmony-click-surfaces.test.mjs @@ -0,0 +1,183 @@ +// Guard nested native Button clicks against enclosing card activation. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +import ts from 'typescript'; +const source = (path) => + readFileSync(new URL('../../harmony/entry/src/main/ets/' + path, import.meta.url), 'utf8'); +const kit = source('components/Kit.ets'); +const keys = { KEYCODE_ENTER: 1, KEYCODE_NUMPAD_ENTER: 2, KEYCODE_SPACE: 3, KEYCODE_A: 4 }; +const helper = kit.slice( + kit.indexOf('export function stopButtonKeyBubbling'), + kit.indexOf('/** Section heading'), +); +const exports = {}; +vm.runInNewContext( + ts.transpileModule(helper, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + }).outputText, + { exports, KeyCode: keys }, +); +for (const keyCode of Object.values(keys)) { + let stops = 0; + exports.stopButtonKeyBubbling({ keyCode, stopPropagation: () => stops++ }); + assert.equal(stops, keyCode === keys.KEYCODE_A ? 0 : 1); +} +function nativeClick(text, context) { + const match = text.match(/\.onClick\(\(event: ClickEvent\) => \{([\s\S]*?)\n\s*\}\)/); + assert.ok(match, 'a nested button must expose an isolated ClickEvent callback'); + const compiled = ts.transpileModule( + 'exports.click = function(event: ClickEvent) {' + match[1] + '\n};', + { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + }, + ).outputText; + const exports = {}; + vm.runInNewContext(compiled, { exports }); + let stopped = false; + const event = { + stopPropagation() { + stopped = true; + }, + }; + exports.click.call(context, event); + assert.equal(stopped, false, 'ArkUI ClickEvent has no DOM stopPropagation method'); + assert.doesNotMatch( + match[1], + /stopPropagation/, + 'click isolation must use native hit testing, not an unsupported ClickEvent API', + ); +} +for (const name of ['PrimaryButton', 'TonalButton', 'TextButton', 'IconButton']) { + const begin = kit.indexOf('export struct ' + name); + const end = kit.indexOf('\n@Component', begin + 1); + const component = kit.slice(begin, end < 0 ? undefined : end); + let actions = 0; + nativeClick(component, { usable: true, onTap: () => actions++ }); + assert.equal(actions, 1, name + ' activates exactly once'); + assert.match(component, /onKeyEvent\(\(event: KeyEvent\) => stopButtonKeyBubbling\(event\)\)/); +} +const card = source('components/library/LibraryPresentation.ets'); +const begin = card.indexOf(' capsule()'); +const capsule = card.slice(begin, card.indexOf(' build()', begin)); +let actions = 0; +nativeClick(capsule, { primaryEnabled: true, onPrimary: () => actions++ }); +assert.equal(actions, 1); +nativeClick(capsule, { primaryEnabled: false, onPrimary: () => actions++ }); +assert.equal(actions, 1, 'disabled native card actions remain inert'); +assert.match(capsule, /Row\(\)\s*\{[\s\S]*Button\(/); +assert.match( + capsule, + /\.hitTestBehavior\(HitTestMode\.Block\)/, + 'the disabled capsule wrapper must prevent the underlying card click (Huawei FAQ 243)', +); +assert.match(capsule, /onKeyEvent/); +const navigation = source('components/ProductNavigation.ets'); +assert.doesNotMatch( + navigation, + /item\([^)]*active:\s*boolean/, + 'ForEach items must not retain an initial computed selection Boolean', +); +assert.match(navigation, /accessibilitySelected\(this\.primaryActive\(id\)\)/); +assert.match(navigation, /backgroundColor\(this\.primaryActive\(id\)/); +assert.match(navigation, /uiMaterial\.isImmersiveMaterialSupported\(\)/); +const shell = source('components/AppShell.ets'); +assert.match(shell, /Tabs\(\{ barPosition: BarPosition\.End \}\)/); +assert.match(shell, /\.tabBar\(this\.floatingDock\)/); +assert.match( + shell, + /\.barOverlap\(true\)/, + 'native bottom TabBar must overlay content rather than reserve an opaque base', +); +const dockHead = + navigation + .slice(0, navigation.indexOf(' build()')) + .replace(/^import .*;\n/gm, '') + .replace(/^@Component\n/gm, '') + .replace(/@(Prop|StorageLink)\('[^']*'\)\s*/g, '') + .replace(/@Prop\s+/g, '') + .replace('export struct ProductDock', 'export class ProductDock') + '\n}\n'; +const dockExports = {}; +const deviceInfo = { sdkApiVersion: 23 }; +let supportChecks = 0; +let supported = false; +const uiMaterial = { + isImmersiveMaterialSupported() { + supportChecks++; + return supported; + }, + ImmersiveStyle: { THIN: 1 }, + ImmersiveMaterial: class { + constructor(options) { + this.options = options; + } + }, +}; +vm.runInNewContext( + ts.transpileModule(dockHead, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + }).outputText, + { + exports: dockExports, + deviceInfo, + uiMaterial, + console, + Palette: { dockTint: () => '#ffffff' }, + Nav: { + OVERVIEW: 'overview', + STYLE: 'style', + TRANSLATION: 'translation', + rootOf: (route) => (route === 'credentials' ? 'settings' : route), + }, + }, +); +const dock = new dockExports.ProductDock(); +for (const route of ['overview', 'history', 'vocab', 'settings', 'overview']) { + dock.route = route; + for (const id of ['overview', 'history', 'vocab', 'settings']) { + assert.equal(dock.primaryActive(id), id === route, 'selection follows live route: ' + route); + } +} +dock.route = 'style'; +assert.equal(dock.primaryActive('vocab'), false); +dock.route = 'translation'; +assert.equal(dock.primaryActive('vocab'), false); +console.log( + 'Harmony click surfaces: native activation, key/hit-test isolation and live dock selection passed', +); + +// HarmonyOS 6.1/API 23 is the minimum; API 26 capability queries and modifiers +// must be fully skipped, not invoked with an undefined material. +{ + assert.equal(dock.dockMaterial(), undefined); + assert.equal(supportChecks, 0, 'API 23 never queries the API 26 module'); + const unavailable = { + get systemMaterial() { + throw new Error('API 26 attribute accessed on API 23'); + }, + }; + new dockExports.DockMaterialModifier({ fixture: 'material' }).applyNormalAttribute(unavailable); + deviceInfo.sdkApiVersion = 26; + assert.equal(dock.dockMaterial(), undefined, 'unsupported hardware uses the blur fallback'); + new dockExports.DockMaterialModifier(undefined).applyNormalAttribute(unavailable); + supported = true; + const material = dock.dockMaterial(); + assert.ok(material); + const applied = []; + new dockExports.DockMaterialModifier(material).applyNormalAttribute({ + systemMaterial: (value) => applied.push(value), + }); + assert.deepEqual(applied, [material]); + assert.doesNotMatch( + navigation, + /\.systemMaterial\(this\.mat\)/, + 'new attributes cannot be unconditionally called by older devices', + ); + assert.equal( + (navigation.match(/\.attributeModifier\(this\.materialModifier\)/g) ?? []).length, + 2, + ); +} +console.log( + 'HarmonyOS 6.1/7 material compatibility: API 23 skip, API 26 hardware fallback and guarded application passed', +); diff --git a/openless-all/app/scripts/harmony-core-contracts.test.mjs b/openless-all/app/scripts/harmony-core-contracts.test.mjs new file mode 100644 index 000000000..bfa8391b2 --- /dev/null +++ b/openless-all/app/scripts/harmony-core-contracts.test.mjs @@ -0,0 +1,524 @@ +// Verify real HarmonyOS ArkTS API & page controllers against strict openless-core wire contracts. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +import ts from 'typescript'; + +const root = new URL('../../harmony/entry/src/main/ets/', import.meta.url); +const read = (file) => readFileSync(new URL(file, root), 'utf8'); +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +function compile(source, globals = {}) { + const exports = {}; + const clean = source + .replace(/^import[\s\S]*?from '[^']+';\n/gm, '') + .replace(/^@Component\n/gm, '') + .replace(/@(StorageLink|Watch)\('[^']*'\)\s*/g, '') + .replace(/@State\s+/g, ''); + const result = ts.transpileModule(clean, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + reportDiagnostics: true, + }); + assert.equal(result.diagnostics?.length ?? 0, 0, 'source must transpile cleanly'); + vm.runInNewContext(result.outputText, { exports, console, ...globals }); + return exports; +} + +// 1. Api.ets strict Core wire contracts: retranscribe sessionId, readRecording data URL, writePipelineMode. +{ + const calls = []; + class HarmonyApi { + async invokeAsync(command, argsJson) { + const args = JSON.parse(argsJson); + calls.push({ command, args }); + if (command === 'retranscribe_recording') { + assert.equal(typeof args.sessionId, 'string', 'retranscribe_recording requires sessionId'); + assert.equal('id' in args, false, 'retranscribe_recording must not send legacy id key'); + return JSON.stringify({ ok: true, value: { text: 'ok', updatedEntry: null } }); + } + if (command === 'read_audio_recording') { + assert.equal(typeof args.sessionId, 'string'); + return JSON.stringify({ ok: true, value: 'data:audio/wav;base64,UklGRg==' }); + } + if (command === 'create_channel') { + return JSON.stringify({ ok: true, value: 'created-channel-42' }); + } + if (command === 'list_channels') { + return JSON.stringify({ + ok: true, + value: [ + { + id: 'created-channel-42', + name: 'My Bailian', + providerType: 'bailian', + enabled: true, + order: 0, + }, + ], + }); + } + if (command === 'update_setting_fields') { + return JSON.stringify({ + ok: true, + value: { + preferences: { + pipelineMode: args.edits['/pipelineMode'], + multimodalPipelineEnabled: args.edits['/multimodalPipelineEnabled'], + }, + revision: 2, + }, + }); + } + return JSON.stringify({ ok: true, value: null }); + } + } + const { StyleEditing } = compile(read('data/StyleEditing.ets')); + const { Api } = compile(read('data/Api.ets'), { HarmonyApi, StyleEditing }); + + const retranscribed = await Api.retranscribe('session-123'); + assert.equal(retranscribed.text, 'ok'); + const recording = await Api.readRecording('session-123'); + assert.equal( + recording.base64, + 'UklGRg==', + 'readRecording must unwrap data:audio/wav;base64, strings', + ); + const created = await Api.createChannel('asr', 'bailian', 'My Bailian'); + assert.equal( + created.id, + 'created-channel-42', + 'createChannel must resolve Rust string channel IDs to Channel objects', + ); + assert.equal(created.providerType, 'bailian'); + const switched = await Api.writePipelineMode('multimodal'); + assert.equal(switched.preferences.pipelineMode, 'multimodal'); + assert.equal(switched.preferences.multimodalPipelineEnabled, true); + assert.deepEqual(calls.at(-1), { + command: 'update_setting_fields', + args: { edits: { '/pipelineMode': 'multimodal', '/multimodalPipelineEnabled': true } }, + }); +} + +// 2. AudioPlayback strips data URL prefix defensively before Base64 decoding. +{ + const decoded = []; + let fd = 0; + const fs = { + OpenMode: { CREATE: 1, READ_WRITE: 2, TRUNC: 4, READ_ONLY: 8 }, + openSync: (path) => ({ fd: ++fd, path }), + writeSync: () => {}, + closeSync: () => {}, + }; + const { AudioPlayback } = compile(read('common/AudioPlayback.ets'), { + fs, + util: { + Base64Helper: class { + decodeSync(value) { + decoded.push(value); + return new Uint8Array([1, 2, 3, 4]); + } + }, + }, + media: { + createAVPlayer: async () => ({ + on() {}, + async prepare() {}, + async play() {}, + async stop() {}, + async release() {}, + }), + }, + }); + const player = new AudioPlayback(); + await player.play('/cache', 's1', 'data:audio/wav;base64,AAAA', () => {}); + assert.deepEqual(decoded, ['AAAA']); + await player.stop(); +} + +// 3. StylePage GitHub device flow handles canonical Core expiresInSecs / intervalSecs fields. +{ + const library = read('pages/LibraryPages.ets'); + const start = library.indexOf('@Component\nexport struct StylePage'); + const source = + library + .slice(start, library.indexOf(' build()', start)) + .replace('export struct StylePage', 'export class StylePage') + '\n}\n'; + const timers = new Map(); + let nextTimer = 0; + const commands = []; + const Api = { + marketplaceAuthStatus: async () => ({ signedIn: true }), + marketplace: async () => [], + githubDeviceFlowStart: async () => ({ + flowId: 'flow-core', + userCode: 'ABCD-1234', + verificationUri: 'https://github.com/login/device', + expiresInSecs: 900, + intervalSecs: 5, + }), + githubDeviceFlowPoll: async () => { + commands.push('poll'); + return { kind: 'authorized', login: 'harmony-user' }; + }, + githubDeviceFlowCancel: async (id) => { + commands.push('cancel:' + id); + }, + copyText: async () => {}, + openExternalUrl: async () => {}, + }; + const { StyleEditing } = compile(read('data/StyleEditing.ets')); + const { StylePage } = compile(source, { + Api, + StyleEditing, + notify() {}, + SHEET_CREATE: 'create', + SHEET_EDIT: 'edit', + SHEET_DETAIL: 'detail', + SHEET_MARKET: 'market', + Layout: { LG: 'lg', XL: 'xl' }, + setTimeout: (cb, delay) => { + const id = ++nextTimer; + timers.set(id, { cb, delay }); + return id; + }, + clearTimeout: (id) => timers.delete(id), + }); + const page = new StylePage(); + page.viewActive = true; + const pending = page.startLogin(); + await tick(); + const [[id, entry]] = [...timers.entries()]; + assert.equal(entry.delay, 5000, 'intervalSecs=5 must schedule a 5000ms poll'); + timers.delete(id); + entry.cb(); + await pending; + assert.equal(page.signedIn, true); + assert.equal(page.loginState, '已登录 harmony-user'); + assert.deepEqual(commands, ['poll']); +} + +// 4. SettingsPage cloud sync uses marketplaceAuthStatus, real CloudSyncStatus fields, '{}' UI prefs and GitHub login. +{ + const settingsSource = read('pages/SettingsPage.ets'); + const start = settingsSource.indexOf('@Component\nexport struct SettingsPage'); + const controller = + settingsSource + .slice(start, settingsSource.indexOf(' // ── View', start)) + .replace('export struct SettingsPage', 'export class SettingsPage') + '\n}\n'; + const uploads = []; + const timers = new Map(); + let nextTimer = 0; + let signedIn = false; + const Api = { + settings: async () => ({ + preferences: { themeMode: 'system', translationTargetLanguage: 'English' }, + revision: 1, + }), + startupSnapshot: async () => ({ contractVersion: '2.0.0' }), + platformCapabilities: async () => ({ platform: 'harmony', supportsImeInput: true }), + network: async () => ({ online: true, latencyMs: 12 }), + microphoneDevices: async () => [], + history: async () => [], + raw: async () => JSON.stringify({ ok: true, value: 'granted' }), + marketplaceAuthStatus: async () => ({ signedIn }), + cloudSyncStatus: async () => ({ + schemaVersion: 1, + revision: 7, + updatedAt: '2026-11-28T08:00:00Z', + hasSnapshot: true, + counts: { dictionary: 12, corrections: 3, stylePacks: 4 }, + }), + cloudSyncUpload: async (baseRevision, uiPreferencesJson) => { + uploads.push({ baseRevision, uiPreferences: JSON.parse(uiPreferencesJson) }); + }, + getUpdateChannel: async () => 'stable', + setUpdateChannel: async (channel) => channel, + checkUpdate: async (currentVersion, channel) => ({ + currentVersion, + latestVersion: '2.1.0', + tagName: 'v2.1.0', + channel, + hasUpdate: true, + publishedAt: '2026-11-28T00:00:00Z', + releaseUrl: 'https://github.com/Open-Less/openless/releases/tag/v2.1.0', + }), + githubDeviceFlowStart: async () => ({ + flowId: 'settings-flow', + userCode: 'WXYZ-9999', + verificationUri: 'https://github.com/login/device', + expiresInSecs: 600, + intervalSecs: 3, + }), + githubDeviceFlowPoll: async () => { + signedIn = true; + return { kind: 'authorized', login: 'aeoform' }; + }, + githubDeviceFlowCancel: async () => {}, + marketplaceLogout: async () => { + signedIn = false; + }, + copyText: async () => {}, + openExternalUrl: async () => {}, + }; + const { SettingsPage } = compile(controller, { + Api, + AppStorage: { get: () => '2.0.2' }, + Appearance: { apply() {} }, + Layout: { isWide: () => false }, + THEME_IDS: ['system', 'light', 'dark'], + THEME_LABELS: ['跟随系统', '浅色', '深色'], + UPDATE_CHANNELS: ['stable', 'beta'], + UPDATE_CHANNEL_LABELS: ['正式版', 'Beta'], + LANG_IDS: ['', '简体中文', 'English', '日本語', '한국어'], + LANG_LABELS: ['关闭翻译', '简体中文', 'English', '日本語', '한국어'], + SECTION_ALL: 'all', + GROUP_SPECS: [], + notify() {}, + setTimeout: (cb, delay) => { + const id = ++nextTimer; + timers.set(id, { cb, delay }); + return id; + }, + clearTimeout: (id) => timers.delete(id), + }); + const page = new SettingsPage(); + page.getUIContext = () => ({ getHostContext: () => undefined }); + page.viewActive = true; + await page.loadSyncStatus(); + assert.equal(page.syncLoggedIn, false); + await page.syncUpload(); + assert.equal(uploads.length, 0, 'signed-out upload must be blocked'); + + const login = page.startLogin(); + await tick(); + const [[timerId, entry]] = [...timers.entries()]; + assert.equal(entry.delay, 3000); + timers.delete(timerId); + entry.cb(); + await login; + assert.equal(page.syncLoggedIn, true); + assert.equal(page.syncRevision, 7); + assert.equal(page.syncHasSnapshot, true); + assert.equal(page.syncLast, '2026-11-28T08:00:00Z'); + assert.match(page.syncCountsText, /词典 12.*纠错 3.*风格 4/); + + await page.syncUpload(); + assert.deepEqual(uploads, [{ baseRevision: 7, uiPreferences: {} }]); + + await page.switchUpdateChannel(1); + assert.equal(page.updateChannel, 'beta'); + await page.checkForUpdates(); + assert.equal(page.updateAvailable, true); + assert.match(page.updateNote, /v2\.1\.0/); + + await page.logoutAccount(); + assert.equal(page.syncLoggedIn, false); + assert.equal(page.syncHasSnapshot, false); + + // Settings must accurately describe HarmonyOS's shipped OpenLessInputMethod extension. + assert.doesNotMatch(settingsSource, /鸿蒙端没有第三方键盘扩展/); + assert.match(settingsSource, /OpenLess 鸿蒙输入法/); +} + +// 5. TranslationPage writes canonical native languages and PolishMode values, never /translationEnabled. +{ + const tools = read('pages/ToolPages.ets'); + assert.doesNotMatch( + tools, + /\/translationEnabled/, + 'UserPreferences has no /translationEnabled field', + ); + assert.doesNotMatch( + tools, + /'zh-CN'/, + 'translationTargetLanguage must use native names like 简体中文 / English', + ); + const start = tools.indexOf('@Component\nexport struct TranslationPage'); + const controller = + tools + .slice(start, tools.indexOf(' build()', start)) + .replace('export struct TranslationPage', 'export class TranslationPage') + '\n}\n'; + const writes = []; + const modeCalls = []; + let prefs = { defaultMode: 'light', translationTargetLanguage: 'English' }; + const Api = { + settings: async () => ({ preferences: { ...prefs }, revision: 1 }), + writeString: async (pointer, value) => { + writes.push([pointer, value]); + if (pointer === '/translationTargetLanguage') + prefs = { ...prefs, translationTargetLanguage: value }; + return { preferences: { ...prefs }, revision: 2 }; + }, + setDefaultPolishMode: async (mode) => { + modeCalls.push(mode); + prefs = { ...prefs, defaultMode: mode }; + return { preferences: { ...prefs }, revision: 3 }; + }, + }; + const { Labels } = compile(read('common/Labels.ets')); + const { TranslationPage } = compile(controller, { + Api, + Labels, + notify() {}, + LANGUAGES: ['简体中文', 'English', '日本語', '한국어'], + LANGUAGE_NAMES: ['简体中文', 'English', '日本語', '한국어'], + MODES: ['raw', 'light', 'structured', 'formal'], + Layout: { LG: 'lg', XL: 'xl' }, + }); + const page = new TranslationPage(); + await page.reload(); + assert.equal(page.translationOn(), true); + assert.equal(page.targetName(), 'English'); + await page.setTranslationEnabled(false); + assert.deepEqual(writes.at(-1), ['/translationTargetLanguage', '']); + assert.equal(page.translationOn(), false); + await page.setTranslationEnabled(true); + assert.deepEqual(writes.at(-1), ['/translationTargetLanguage', 'English']); + await page.writePolishMode('formal'); + assert.deepEqual(modeCalls, ['formal']); + assert.equal(Labels.polishMode('light'), '轻度润色'); + assert.equal(Labels.polishMode('formal'), '正式表达'); + assert.equal(Labels.provider('iflytek'), '讯飞 RTASR'); + assert.equal(Labels.provider('tencent-cloud'), '腾讯云'); +} + +// 6. CredentialsPage supports iflytek, tencent-cloud, volcengine, omni fields and pipeline switching. +{ + const credentials = read('pages/CredentialsPage.ets'); + const controller = + credentials + .slice( + credentials.indexOf('export struct CredentialsPage'), + credentials.indexOf(' // ── Page'), + ) + .replace('export struct CredentialsPage', 'export class CredentialsPage') + '\n}\n'; + const calls = []; + let pipelineMode = 'traditional'; + const Api = { + settings: async () => ({ + preferences: { pipelineMode, multimodalPipelineEnabled: pipelineMode === 'multimodal' }, + }), + credentialStatus: async () => ({ pipelineMode, omniConfigured: true }), + channels: async (kind) => { + assert.notEqual(kind, 'omni', 'ChannelKind only supports asr and llm'); + return []; + }, + providerDescriptors: async (kind) => + kind === 'omni' + ? [ + { + kind: 'omni', + providerType: 'gemini', + labelKey: 'omniGemini', + authRequirement: 'api_key', + }, + { + kind: 'omni', + providerType: 'not-added', + labelKey: 'notAdded', + authRequirement: 'api_key', + }, + ] + : [], + configuredOmniProviders: async () => [], + writePipelineMode: async (mode) => { + pipelineMode = mode; + calls.push(['pipeline', mode]); + return { + preferences: { pipelineMode: mode, multimodalPipelineEnabled: mode === 'multimodal' }, + revision: 2, + }; + }, + activateOmniProvider: async (id) => { + calls.push(['activateOmni', id]); + }, + validateChannel: async (kind, id) => { + calls.push(['validate', kind, id]); + return true; + }, + createChannel: async () => { + throw new Error('omni must not call createChannel'); + }, + renameChannel: async () => { + throw new Error('omni must not call renameChannel'); + }, + recordChannelTest: async () => { + throw new Error('omni must not call recordChannelTest'); + }, + deleteChannel: async () => { + throw new Error('omni must not call deleteChannel'); + }, + }; + const { CredentialsPage } = compile(controller, { + Api, + Store: { put() {} }, + AppStorage: { get: () => undefined }, + UNSUPPORTED_PROVIDERS: [], + Labels: { provider: (id) => id }, + notify() {}, + }); + const page = new CredentialsPage(); + page.pageActive = true; + await page.reload(); + assert.equal(page.omniChannels.length, 0, 'provider catalogue is not an added-channel list'); + Api.configuredOmniProviders = async () => ['gemini']; + await page.reload(); + assert.equal(page.omniChannels.length, 1); + assert.equal(page.omniChannels[0].id, 'gemini'); + assert.equal(page.omniDescriptors.length, 2, 'unconfigured providers remain in the add picker'); + assert.deepEqual( + Array.from(page.fieldSpecs('asr', 'iflytek'), (s) => s.account), + ['xfyun.app_id', 'xfyun.api_key', 'asr.endpoint', 'asr.model'], + ); + assert.deepEqual( + Array.from(page.fieldSpecs('asr', 'tencent-cloud'), (s) => s.account), + [ + 'tencent_cloud.app_id', + 'tencent_cloud.secret_id', + 'tencent_cloud.secret_key', + 'asr.endpoint', + 'asr.model', + ], + ); + assert.deepEqual( + Array.from(page.fieldSpecs('omni', 'gemini'), (s) => s.account), + ['omni.api_key', 'omni.endpoint', 'omni.model'], + ); + await page.switchPipeline(true); + assert.deepEqual(calls[0], ['pipeline', 'multimodal']); + assert.equal(page.isMultimodal(), true); + page.openCreate(); + page.selectKind(2); + assert.equal(page.editorKind, 'omni'); + await page.chooseProvider('gemini'); + await page.runTest(); + await page.activateEditorChannel(); + await page.deleteEditorChannel(); + assert.ok(calls.some((c) => c[0] === 'validate' && c[1] === 'omni' && c[2] === 'gemini')); + assert.ok(calls.some((c) => c[0] === 'activateOmni' && c[1] === 'gemini')); +} + +// 7. OverviewPage respects multimodal omniConfigured, ModelsPage avoids /localAsrEnabled, +// InputMethodPanel ships no dead '待接入' tiles, and LibraryPages wires vocab edit/reset/dismiss. +{ + const overview = read('pages/OverviewPage.ets'); + assert.match( + overview, + /credentials\.pipelineMode === 'multimodal'[\s\S]{0,80}credentials\.omniConfigured === true/, + ); + const models = read('pages/ModelsPage.ets'); + assert.doesNotMatch(models, /\/localAsrEnabled/); + const ime = read('pages/InputMethodPanel.ets'); + assert.doesNotMatch(ime, /待接入/, 'IME toolbar must not expose dead placeholder tiles'); + const library = read('pages/LibraryPages.ets'); + assert.match(library, /Api\.updateVocabulary\(/); + assert.match(library, /Api\.dismissSuggestions\(/); + assert.match(library, /Api\.resetBuiltinStylePack\(/); + const credentials = read('pages/CredentialsPage.ets'); + assert.match(credentials, /Api\.setChannelEnabled\(/); + assert.match(credentials, /Api\.listModels\(/); +} + +console.log( + 'Harmony Core wire contracts: retranscribe sessionId, audio data-URL, GitHub device flow, cloud sync, translation, multi-provider credentials and multimodal pipeline passed', +); diff --git a/openless-all/app/scripts/harmony-credential-actions.test.mjs b/openless-all/app/scripts/harmony-credential-actions.test.mjs new file mode 100644 index 000000000..f761cfa75 --- /dev/null +++ b/openless-all/app/scripts/harmony-credential-actions.test.mjs @@ -0,0 +1,490 @@ +// Execute real credential/navigation methods with deferred effects; no device or real keys. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +import ts from 'typescript'; + +const base = new URL('../../harmony/entry/src/main/ets/', import.meta.url); +const read = (name) => readFileSync(new URL(name, base), 'utf8'); +const credentials = read('pages/CredentialsPage.ets'); +const shell = read('components/AppShell.ets'); +const index = read('pages/Index.ets'); +const deferred = () => { + let resolve, reject; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +}; +const tick = async () => { + for (let i = 0; i < 20; i++) await Promise.resolve(); +}; +function compile(source, globals) { + const exports = {}; + const compiled = ts.transpileModule(source.replace(/^import .*;\n/gm, ''), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + reportDiagnostics: true, + }); + assert.equal(compiled.diagnostics.length, 0, 'source must transpile'); + vm.runInNewContext(compiled.outputText, { exports, console, ...globals }); + return exports; +} +function method(source, name) { + const match = new RegExp('(?:private )?' + name + '\\([^)]*\\)(?::[^\\{]+)?\\{').exec(source); + assert.ok(match, name); + let end = match.index + match[0].length, + depth = 1; + for (; depth > 0; end++) { + if (source[end] === '{') depth++; + if (source[end] === '}') depth--; + } + return source.slice(match.index, end).replace(/^private /, ''); +} +const controllerSource = + credentials + .slice( + credentials.indexOf('export struct CredentialsPage'), + credentials.indexOf(' // ── Page'), + ) + .replace('export struct CredentialsPage', 'export class CredentialsPage') + .replace(/@(StorageLink|Watch)\('[^']*'\)\s*/g, '') + .replace(/@State\s*/g, '') + '\n}\n'; +function harness() { + const storage = new Map([['route', 'style']]); + const calls = [], + pending = new Map(); + let page; + const Store = { + put(key, value) { + storage.set(key, value); + if (key === 'overlayBackRequest') { + page.overlayBackRequest = value; + page.onOverlayBack(); + } + }, + }; + const AppStorage = { get: (key) => storage.get(key) }; + const Nav = compile(read('components/Nav.ets'), { Store, AppStorage }).Nav; + const active = { llm: 'old-llm', asr: 'old-asr' }; + const Api = { + settings: async () => ({ + preferences: { activeLlmProvider: active.llm, activeAsrProvider: active.asr }, + }), + credentialStatus: async () => ({ llmConfigured: true }), + channels: async () => [], + providerDescriptors: async () => [], + configuredOmniProviders: async () => [], + }; + for (const name of [ + 'createChannel', + 'deleteChannel', + 'renameChannel', + 'setCredential', + 'activateLlmProvider', + 'activateAsrProvider', + 'validateChannel', + 'recordChannelTest', + 'listModels', + ]) { + Api[name] = async (...args) => { + calls.push([name, ...args]); + if (name.startsWith('activate')) + active[name === 'activateLlmProvider' ? 'llm' : 'asr'] = args[0]; + const wait = pending.get(name); + if (wait) return wait.promise; + if (name === 'createChannel') + return { id: 'draft-channel', providerType: args[1], name: args[2] }; + if (name === 'validateChannel') return true; + }; + } + const { CredentialsPage } = compile(controllerSource, { + Store, + AppStorage, + Api, + UNSUPPORTED_PROVIDERS: [], + Labels: { provider: (id) => id }, + notify() {}, + }); + page = new CredentialsPage(); + page.aboutToAppear(); + const { Index } = compile('export class Index {' + method(index, 'onBackPress') + '}', { Nav }); + const keys = { KEYCODE_1: 1, KEYCODE_2: 2, KEYCODE_3: 3, KEYCODE_4: 4, KEYCODE_5: 5 }; + const { AppShell } = compile('export class AppShell {' + method(shell, 'handleKey') + '}', { + Nav, + KeyCode: keys, + KeyType: { Down: 0 }, + }); + const event = { type: 0, keyCode: 1, metaKey: 1, stopPropagation() {} }; + return { + page, + Nav, + storage, + calls, + active, + pending, + back: () => new Index().onBackPress(), + shortcut: () => new AppShell().handleKey(event), + count: (name) => calls.filter((call) => call[0] === name).length, + openEdit: () => + page.openEdit('llm', { id: 'existing', name: 'Existing', providerType: 'openai' }), + wait(name) { + const wait = deferred(); + pending.set(name, wait); + return wait; + }, + }; +} + +// X/cancel/scrim all share closeEditor; a stale global flag must not swallow Back. +for (const close of ['close', 'back', 'disappear']) { + const h = harness(); + await tick(); + h.Nav.go(h.Nav.CREDENTIALS); + h.page.openCreate(); + assert.equal(h.storage.get('overlayOpen'), true); + if (close === 'close') h.page.closeEditor(); + else if (close === 'back') assert.equal(h.back(), true); + else h.page.aboutToDisappear(); + assert.equal(h.page.editorOpen, false, close); + assert.equal(h.storage.get('overlayOpen'), false, close); + if (close !== 'disappear') { + h.back(); + assert.equal(h.storage.get('route'), 'style'); + } +} + +// Double Back, dock/deep-link navigation and keyboard shortcuts cannot escape a busy editor. +{ + const h = harness(); + await tick(); + h.Nav.go(h.Nav.CREDENTIALS); + h.openEdit(); + h.page.drafts.set('ark.api_key', 'fixture-key'); + const saving = h.wait('setCredential'); + const work = h.page.saveEditor(); + await tick(); + assert.equal(h.count('setCredential'), 1); + assert.equal(h.back(), true); + assert.equal(h.back(), true); + h.Nav.openPrimary(h.Nav.HISTORY); + h.Nav.go(h.Nav.OVERVIEW); + h.shortcut(); + assert.equal(h.storage.get('route'), 'credentials'); + assert.equal(h.storage.get('overlayOpen'), true); + assert.equal(h.page.editorOpen, true); + await h.page.deleteEditorChannel(); + await h.page.activateEditorChannel(); + assert.equal(h.count('deleteChannel'), 0); + assert.equal(h.count('activateLlmProvider'), 0); + saving.resolve(); + await work; + assert.equal(h.storage.get('overlayOpen'), false); + h.back(); + assert.equal(h.storage.get('route'), 'style'); +} + +// Freeze provider identity, reject duplicate create/type changes, and never auto-activate drafts. +{ + const h = harness(); + await tick(); + h.page.openCreate(); + h.page.editorName = 'Draft'; + const creating = h.wait('createChannel'); + const work = h.page.chooseProvider('openai'); + h.page.selectKind(1); + assert.equal(h.page.editorKind, 'llm'); + await h.page.chooseProvider('another'); + assert.equal(h.count('createChannel'), 1); + h.page.editorKind = 'asr'; // Even an external mutation must not retarget the awaited result. + h.back(); + h.back(); + assert.equal(h.storage.get('overlayOpen'), true); + creating.resolve({ id: 'draft-channel', providerType: 'openai', name: 'Draft' }); + await work; + assert.equal(h.page.editorKind, 'llm'); + assert.equal(h.page.editorActive, false); + assert.equal(h.count('activateLlmProvider') + h.count('activateAsrProvider'), 0); + h.page.closeEditor(); + await tick(); + assert.deepEqual( + h.calls.filter((call) => call[0] === 'deleteChannel'), + [['deleteChannel', 'llm', 'draft-channel']], + ); + assert.equal(h.active.llm, 'old-llm'); + assert.equal(h.active.asr, 'old-asr'); + assert.equal(h.storage.get('overlayOpen'), false); +} + +// A create finishing after teardown cleans its uncommitted channel, never revives an overlay. +{ + const h = harness(); + await tick(); + h.page.openCreate(); + const creating = h.wait('createChannel'); + const work = h.page.chooseProvider('openai'); + h.page.aboutToDisappear(); + creating.resolve({ id: 'late-draft', providerType: 'openai', name: 'Late' }); + await work; + await tick(); + assert.equal(h.page.editorOpen, false); + assert.equal(h.storage.get('overlayOpen'), false); + assert.ok(h.calls.some((call) => call[0] === 'deleteChannel' && call[2] === 'late-draft')); + assert.equal(h.active.llm, 'old-llm'); +} + +// Testing blocks repeated test/save/activation; late results cannot alter a later editor. +{ + const h = harness(); + await tick(); + h.Nav.go(h.Nav.CREDENTIALS); + h.openEdit(); + const testing = h.wait('validateChannel'); + const work = h.page.runTest(); + await tick(); + await h.page.runTest(); + await h.page.saveEditor(); + h.back(); + h.back(); + assert.equal(h.count('validateChannel'), 1); + assert.equal(h.storage.get('overlayOpen'), true); + h.page.aboutToDisappear(); + h.page.aboutToAppear(); + h.page.openCreate(); + testing.resolve(true); + await work; + assert.equal(h.count('recordChannelTest'), 0); + assert.equal(h.page.editorStep, 'pick'); + assert.equal(h.page.editorTest, 'idle'); + assert.equal(h.storage.get('overlayOpen'), true); +} + +// Only explicit activation changes routing; cancellation after use must retain the channel. +{ + const h = harness(); + await tick(); + h.page.openCreate(); + await h.page.chooseProvider('openai'); + await h.page.activateEditorChannel(); + assert.equal(h.active.llm, 'draft-channel'); + h.page.closeEditor(); + await tick(); + assert.equal(h.count('deleteChannel'), 0); +} +{ + const h = harness(); + await tick(); + h.openEdit(); + const deleting = h.wait('deleteChannel'); + const work = h.page.deleteEditorChannel(); + await h.page.deleteEditorChannel(); + h.page.closeEditor(); + assert.equal(h.page.editorOpen, true); + deleting.resolve(); + await work; + assert.equal(h.count('deleteChannel'), 1); + assert.equal(h.storage.get('overlayOpen'), false); +} + +// Return origins are transient, while the styles family remembers Translation targets. +{ + const h = harness(); + await tick(); + h.Nav.go(h.Nav.CREDENTIALS); + h.Nav.back(); + assert.equal(h.storage.get('route'), 'style'); + h.Nav.go(h.Nav.SETTINGS); + h.Nav.go(h.Nav.CREDENTIALS); + h.Nav.go(h.Nav.HISTORY); + h.Nav.openPrimary(h.Nav.SETTINGS); + assert.equal(h.storage.get('route'), 'settings'); + h.Nav.go(h.Nav.TRANSLATION); + h.Nav.go(h.Nav.VOCAB); + h.Nav.openPrimary(h.Nav.STYLE); + assert.equal(h.storage.get('route'), 'translation'); + h.Nav.go(h.Nav.STYLE); + assert.equal(h.storage.get('route'), 'style', 'explicit expanded section still wins'); + h.Nav.go(h.Nav.VOCAB); + h.Nav.openPrimary(h.Nav.STYLE); + assert.equal(h.storage.get('route'), 'style'); +} +assert.match(shell, /\.enabled\(!this\.overlayOpen\)/, 'back affordance respects modal state'); +assert.match( + shell, + /\.enabled\(!this\.overlayOpen && !this\.keyboardVisible\)/, + 'dock cannot receive hits while a modal or keyboard is visible', +); +assert.match( + shell, + /\.visibility\(this\.overlayOpen \|\| this\.keyboardVisible \? Visibility\.Hidden : Visibility\.Visible\)/, +); +// Main-window keyboard subscription has stable identity, paired removal and late-event guards. +{ + const storage = new Map(); + const { Keyboard } = compile( + 'export class Keyboard { keyboardWindow; keyboardListener; ' + + method(index, 'watchKeyboard') + + method(index, 'stopKeyboardWatch') + + '}', + { Store: { put: (key, value) => storage.set(key, value) } }, + ); + const makeWindow = () => ({ + onCount: 0, + offCount: 0, + listener: undefined, + on(name, callback) { + assert.equal(name, 'keyboardHeightChange'); + this.onCount++; + this.listener = callback; + }, + off(name, callback) { + assert.equal(name, 'keyboardHeightChange'); + assert.equal(callback, this.listener); + this.offCount++; + }, + }); + const page = new Keyboard(), + first = makeWindow(), + second = makeWindow(); + page.watchKeyboard(first); + page.watchKeyboard(first); + assert.equal(first.onCount, 1); + first.listener(400); + assert.equal(storage.get('keyboardVisible'), true); + first.listener(0); + assert.equal(storage.get('keyboardVisible'), false); + const stale = first.listener; + page.watchKeyboard(second); + assert.equal(first.offCount, 1); + stale(500); + assert.equal(storage.get('keyboardVisible'), false); + second.listener(500); + assert.equal(storage.get('keyboardVisible'), true); + page.stopKeyboardWatch(); + assert.equal(second.offCount, 1); + assert.equal(storage.get('keyboardVisible'), false); + second.listener(500); + assert.equal(storage.get('keyboardVisible'), false); + page.stopKeyboardWatch(); + assert.equal(second.offCount, 1); +} +assert.match( + read('components/ProductNavigation.ets'), + /this\.animateDock\(\(\) => \{\s*Nav\.openPrimary\(Nav\.STYLE\)/, +); +console.log( + 'Harmony credential actions: modal/back, busy guards, deferred identities, draft cleanup, explicit activation, origin routing and style restoration passed', +); + +assert.match(shell, /barHeight\(this\.overlayOpen \|\| this\.keyboardVisible \? 0 : 78\)/); +assert.match(credentials, /credentials-editor-scrim/); +assert.match(credentials, /maxWidth: Layout\.contentMax\(this\.bp\)/); + +// The catalogue stays in a native dropdown: no chip wall, no silent 16-item truncation. +{ + const h = harness(); + await tick(); + h.openEdit(); + h.page.llmDescriptors = [ + { providerType: 'openai', staticModels: [' model-1 ', 'preset'], defaultModel: 'default' }, + ]; + h.page.editorModels = [' ', ...Array.from({ length: 64 }, (_, i) => `model-${i}`), 'model-1']; + const models = Array.from(h.page.availableModels()); + assert.equal(models.length, 66); + assert.equal(models.at(-1), 'default'); + assert.equal(models.filter((m) => m === 'model-1').length, 1); + assert.deepEqual( + Array.from(h.page.modelOptions(), (option) => option.value), + models, + ); + assert.equal(h.page.selectedModelIndex(), -1, 'no implicit first selection'); + h.page.selectModel(40); + assert.equal(h.page.editorModelSeed, 'model-40'); + assert.equal(h.page.drafts.get('ark.model_id'), 'model-40'); + assert.equal(h.page.selectedModelIndex(), 40); + h.page.updateDraft('ark.model_id', 'manual-model'); + assert.equal(h.page.editorModelSeed, 'manual-model'); + assert.equal(h.page.selectedModelIndex(), -1, 'manual ids remain supported'); + h.page.selectModel(-1); + h.page.selectModel(999); + assert.equal(h.page.drafts.get('ark.model_id'), 'manual-model'); + assert.equal(h.count('setCredential'), 0, 'selecting does not save or activate implicitly'); + assert.equal(h.count('activateLlmProvider'), 0); +} +// Fetch serializes writes, preserves a manual selection and ignores late editor results. +{ + const h = harness(); + await tick(); + h.openEdit(); + h.page.updateDraft('ark.model_id', 'manual-model'); + const fetching = h.wait('listModels'); + const work = h.page.fetchModels(); + await tick(); + assert.equal(h.count('listModels'), 1); + await h.page.fetchModels(); + await h.page.saveEditor(); + await h.page.runTest(); + await h.page.activateEditorChannel(); + await h.page.deleteEditorChannel(); + assert.equal(h.count('listModels'), 1); + assert.equal( + h.count('validateChannel') + h.count('activateLlmProvider') + h.count('deleteChannel'), + 0, + ); + fetching.resolve(['fetched-model']); + await work; + assert.deepEqual(Array.from(h.page.editorModels), ['fetched-model']); + assert.equal(h.page.editorModelSeed, 'manual-model', 'fetching does not select the first result'); + assert.equal(h.page.editorLoadingModels, false); + h.page.selectModel(0); + assert.equal(h.page.drafts.get('ark.model_id'), 'fetched-model'); +} +{ + const h = harness(); + await tick(); + h.openEdit(); + const fetching = h.wait('listModels'); + const work = h.page.fetchModels(); + await tick(); + h.page.closeEditor(); + h.page.openCreate(); + fetching.resolve(['late-result']); + await work; + assert.equal(h.page.editorStep, 'pick'); + assert.deepEqual(Array.from(h.page.editorModels), []); + assert.equal(h.page.editorLoadingModels, false); + assert.equal(h.page.editorModelSeed, ''); +} +{ + const h = harness(); + await tick(); + h.openEdit(); + const fetching = h.wait('listModels'); + const work = h.page.fetchModels(); + await tick(); + fetching.reject(new Error('fixture unavailable')); + await work; + assert.equal(h.page.editorLoadingModels, false); + assert.equal(h.page.editorError, 'fixture unavailable'); + h.page.updateDraft('ark.model_id', 'still-editable'); + assert.equal(h.page.drafts.get('ark.model_id'), 'still-editable'); +} +assert.match(credentials, /Select\(this\.modelOptions\(\)\)/); +assert.match(credentials, /credentials-model-fetch/); +assert.match(credentials, /credentials-model-select/); +assert.doesNotMatch(credentials, /可选模型(点按填入)|out\.length < 16/); +console.log( + 'Harmony model selector: full catalogue, dedup, manual ids, no implicit activation, busy guards and late fetch isolation passed', +); + +// Provider slots have no persisted Core channel-test history or custom names. +{ + const h = harness(); + await tick(); + const channel = { id: 'gemini', providerType: 'gemini', name: 'gemini' }; + assert.match(h.page.channelSubtitle(channel, 'omni'), /配置已保存/); + assert.doesNotMatch(h.page.channelSubtitle(channel, 'omni'), /还没测试过/); + assert.match(h.page.channelSubtitle(channel, 'llm'), /还没测试过/); +} +assert.match(credentials, /if \(this\.editorKind !== 'omni'\) \{\s*InputField\(\{\s*label: '名称'/); +assert.match(credentials, /拉取前会先保存已填写配置/); diff --git a/openless-all/app/scripts/harmony-entry-startup.test.mjs b/openless-all/app/scripts/harmony-entry-startup.test.mjs index e5fc6d3a0..5f204cf13 100644 --- a/openless-all/app/scripts/harmony-entry-startup.test.mjs +++ b/openless-all/app/scripts/harmony-entry-startup.test.mjs @@ -15,6 +15,18 @@ const requests = [], class UIAbility { context = { resourceManager: { getBooleanByName: () => clipboardAccess } }; } +// Launch hints are routes only; window geometry is owned by the stage. +const Boot = { + route: '', + mainWindow: undefined, + takeRoute() { + const value = this.route; + this.route = ''; + return value; + }, +}; +const stored = new Map(); +const Store = { put: (key, value) => stored.set(key, value) }; const exports = {}; vm.runInNewContext( ts.transpileModule(source, { @@ -23,6 +35,8 @@ vm.runInNewContext( { exports, UIAbility, + Boot, + Store, console, abilityAccessCtrl: { createAtManager: () => ({ @@ -34,8 +48,11 @@ vm.runInNewContext( }, }, ); +const mainWindow = { name: 'owning-main-window' }; const stage = { + getMainWindowSync: () => mainWindow, loadContent: (page, ready) => { + assert.equal(Boot.mainWindow, mainWindow, 'window is available before loading Index'); pages.push(page); ready(); }, @@ -43,6 +60,7 @@ const stage = { for (const want of [undefined, {}, { parameters: {} }]) { const ability = new exports.default(); ability.onCreate(want); + assert.equal(Boot.route, '', 'a plain launch must not carry a deep link'); ability.onForeground(); ability.onWindowStageCreate(stage); ability.onNewWant(); @@ -67,6 +85,20 @@ assert.deepEqual( [['ohos.permission.READ_PASTEBOARD']], 'authorized builds request only once per explicit action', ); +// Old QA layout arguments are deliberately ignored, including on a warm launch. +{ + const ability = new exports.default(); + ability.onCreate({ parameters: { route: 'settings', layout: 'sm' } }); + assert.equal(Boot.takeRoute(), 'settings'); + stored.delete('bpOverride'); + ability.onNewWant({ parameters: { route: 'history', layout: 'xl' } }); + assert.equal(stored.get('deepLinkRoute'), 'history'); + assert.equal(stored.has('bpOverride'), false, 'launch arguments cannot lock responsive layout'); + ability.onWindowStageCreate(stage); + assert.equal(Boot.mainWindow, mainWindow); + ability.onWindowStageDestroy(); + assert.equal(Boot.mainWindow, undefined, 'destroyed window references must be released'); +} console.log( - 'Harmony entry startup: absent launch arguments, page loading and clipboard capability gating passed', + 'Harmony entry startup: absent launch arguments, page loading, deep links and clipboard capability gating passed', ); diff --git a/openless-all/app/scripts/harmony-history-actions.test.mjs b/openless-all/app/scripts/harmony-history-actions.test.mjs new file mode 100644 index 000000000..4b18cf6b0 --- /dev/null +++ b/openless-all/app/scripts/harmony-history-actions.test.mjs @@ -0,0 +1,226 @@ +// Execute actual history action methods and player lifecycle with delayed ports. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +import ts from 'typescript'; +const ets = (name) => + readFileSync(new URL('../../harmony/entry/src/main/ets/' + name, import.meta.url), 'utf8'); +function load(source, globals) { + const exports = {}; + const clean = source + .replace(/^import[\s\S]*?from '[^']+';\n/gm, '') + .replace(/^@Component\n/gm, '') + .replace(/@(StorageLink|Watch)\('[^']*'\)\s*/g, '') + .replace(/@State\s+/g, '') + .replace('export struct HistoryPage', 'export class HistoryPage'); + const result = ts.transpileModule(clean, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + }); + vm.runInNewContext(result.outputText, { exports, console, ...globals }); + return exports; +} +const deferred = () => { + let resolve, reject; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +}; +const source = ets('pages/HistoryPage.ets'); +const methods = source.slice(0, source.indexOf(' // ── Build')) + '\n}\n'; +const A = { id: 'A', finalText: 'A final', rawTranscript: 'A raw' }; +const B = { id: 'B', finalText: 'B final', rawTranscript: 'B raw' }; +function history() { + const polish = [], + reads = [], + played = [], + notices = []; + const audio = { + stops: 0, + stop: async () => { + audio.stops++; + }, + play: async (...args) => { + played.push(args); + args.at(-1)(true); + }, + }; + const Api = { + repolish: (text, style) => { + const d = deferred(); + polish.push({ ...d, text, style }); + return d.promise; + }, + readRecording: (id) => { + const d = deferred(); + reads.push({ ...d, id }); + return d.promise; + }, + }; + const { HistoryPage } = load(methods, { + AudioPlayback: class { + constructor() { + return audio; + } + }, + Api, + notify: (text) => notices.push(text), + clearTimeout, + setTimeout, + }); + const page = new HistoryPage(); + page.pageActive = true; + page.entries = [A, B]; + page.detailId = 'A'; + page.getUIContext = () => ({ getHostContext: () => ({ cacheDir: '/cache' }) }); + page.flushDraft = () => {}; + page.cancelSearch = () => {}; + return { + page, + polish, + reads, + played, + notices, + audio, + select: (id) => { + page.detailId = id; + page.onDetailChange(); + }, + }; +} +{ + const h = history(); + const pending = h.page.repolish(A, { id: 'style-a', name: 'Style A' }); + h.select('B'); + const next = h.page.repolish(B, { id: 'style-b', name: 'Style B' }); + h.polish[0].resolve('late A output'); + await pending; + assert.equal(h.page.repolished, ''); + assert.equal(h.page.repolishedStyle, 'Style B'); + assert.equal(h.page.busy, true, 'old finally must not enable a newer action'); + h.polish[1].resolve('B output'); + await next; + assert.equal(h.page.repolished, 'B output'); + assert.equal(h.page.busy, false); +} +{ + const h = history(); + const pending = h.page.repolish(A, { id: 'style', name: 'Style' }); + h.select('B'); + h.polish[0].reject(new Error('late A failure')); + await pending; + assert.equal(h.page.detailError, ''); +} +for (const action of ['select', 'leave']) { + const h = history(); + const pending = h.page.togglePlayback(A); + if (action === 'select') h.select('B'); + else h.page.aboutToDisappear(); + h.reads[0].resolve({ base64: 'old audio' }); + await pending; + assert.equal(h.played.length, 0, action + ' must prevent delayed playback'); + assert.equal(h.page.playing, false); +} +{ + const h = history(); + const first = h.page.togglePlayback(A), + second = h.page.togglePlayback(A); + h.reads[0].resolve({ base64: 'first' }); + await first; + assert.equal(h.played.length, 0, 'only the latest pending playback owns audio'); + h.reads[1].resolve({ base64: 'second' }); + await second; + assert.equal(h.played.length, 1); + assert.equal(h.page.playing, true); + h.select('B'); + h.played[0].at(-1)(true); + assert.equal(h.page.playing, false, 'old player callback cannot follow the selection'); +} + +const playback = ets('common/AudioPlayback.ets'); +function playerHarness() { + const create = [], + closed = [], + writes = [], + events = []; + let fd = 0; + const fs = { + OpenMode: { CREATE: 1, READ_WRITE: 2, TRUNC: 4, READ_ONLY: 8 }, + openSync: (path) => ({ fd: ++fd, path }), + writeSync: (descriptor) => writes.push(descriptor), + closeSync: (file) => closed.push(file.fd), + }; + const { AudioPlayback } = load(playback, { + fs, + util: { + Base64Helper: class { + decodeSync() { + return new Uint8Array([1, 2, 3]); + } + }, + }, + media: { + createAVPlayer: () => { + const d = deferred(); + create.push(d); + return d.promise; + }, + }, + }); + return { controller: new AudioPlayback(), create, closed, writes, events }; +} +const tick = async () => { + for (let i = 0; i < 8; i++) await Promise.resolve(); +}; +function player({ prepare, stopThrows = false } = {}) { + return { + releases: 0, + starts: 0, + listeners: {}, + on(name, fn) { + this.listeners[name] = fn; + }, + prepare: () => (prepare ? prepare.promise : Promise.resolve()), + async play() { + this.starts++; + }, + async stop() { + if (stopThrows) throw new Error('not prepared'); + }, + async release() { + this.releases++; + }, + }; +} +{ + const h = playerHarness(); + const pending = h.controller.play('/cache', 'A', 'abc', (value) => h.events.push(value)); + await tick(); + await h.controller.stop(); + const late = player(); + h.create[0].resolve(late); + await pending; + assert.equal(late.starts, 0); + assert.equal(late.releases, 1); + assert.deepEqual(h.events, []); + assert.equal(h.controller.isPlaying(), false); +} +{ + const h = playerHarness(), + preparation = deferred(); + const pending = h.controller.play('/cache', 'A', 'abc', (value) => h.events.push(value)); + await tick(); + const p = player({ prepare: preparation, stopThrows: true }); + h.create[0].resolve(p); + await tick(); + await h.controller.stop(); + preparation.resolve(); + await pending; + assert.equal(p.starts, 0); + assert.equal(p.releases, 1, 'stop failure must not skip release'); + assert.equal(h.closed.length, 2, 'both write and player source descriptors close'); +} +console.log( + 'Harmony history actions: selection-bound async results, playback cancellation, obsolete callbacks and descriptor cleanup passed', +); diff --git a/openless-all/app/scripts/harmony-ios-parity.test.mjs b/openless-all/app/scripts/harmony-ios-parity.test.mjs new file mode 100644 index 000000000..22e480b12 --- /dev/null +++ b/openless-all/app/scripts/harmony-ios-parity.test.mjs @@ -0,0 +1,205 @@ +// Frame-by-frame parity contract with the iOS demo recording. +// +// Reference: /data/Video_1795451355907_396.mp4, analysed into .refs/ios-demo/ +// (147 frames at 10 fps + 15 per-second contact sheets). The assertions below pin +// the structural facts that were read off those frames AND confirmed in the iOS +// sources, so a later refactor cannot silently drift back to a "similar but not +// the same" layout: +// +// * home has no navigation bar (brand row scrolls with the content); +// * history / settings / style use the centred 17vp inline title; +// * dictionary draws its own 34vp large title inside the scroll body; +// * history cards use the iOS seven-state status mapping; +// * dictionary chips scroll horizontally and are driven by CapsuleTrack; +// * the two 52vp orbs own search and add; +// * section switching lives in the expanded dock, not in a page segmented. +// +// Text-based so it runs in the Linux contract job (no node_modules required). +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const ets = (path) => readFileSync(join(appRoot, '../harmony/entry/src/main/ets', path), 'utf8'); + +const overview = ets('pages/OverviewPage.ets'); +const history = ets('pages/HistoryPage.ets'); +const library = ets('pages/LibraryPages.ets'); +const settings = ets('pages/SettingsPage.ets'); +const kit = ets('components/Kit.ets'); +const nav = ets('components/ProductNavigation.ets'); +const shell = ets('components/AppShell.ets'); + +// 1. Home: `toolbar(.hidden)` + self-drawn brand row inside the scroll body. +assert.match(overview, /BrandBar\(/, 'home draws its own brand row'); +assert.doesNotMatch(overview, /PageScaffold\(/, 'home has no navigation bar'); +assert.match(overview, /Scroll\(\)/, 'home body scrolls'); + +// 2. Centred inline titles for history, settings and the style sections. +for (const [label, source, title] of [ + ['history', history, "title: this.detailOpen() ? '记录详情' : '历史'"], + ['settings', settings, "title: '设置'"], + ['style', library, "this.segment === 0 ? '我的风格' : '风格市场'"], +]) { + assert.ok(source.includes(title), `${label} uses its inline title`); + assert.match(source, /PageScaffold\(/, `${label} keeps the shared scaffold`); + assert.doesNotMatch(source, /largeTitle: true/, `${label} must not draw a large title`); +} + +// 3. Dictionary: 34vp large title drawn in the body, not by the scaffold. +assert.match( + library, + /Text\('词典'\)[\s\S]{0,160}fontSize\(Type\.pageTitle\)/, + 'dictionary draws its own large title', +); +assert.match( + library, + /fontWeight\(FontWeight\.Bold\)/, + 'the large title is bold like .largeTitle.bold()', +); + +// 4. History status mapping is the iOS seven-state switch. +for (const status of [ + '已完成', + '未完成录音', + '已取消', + '识别未完成', + '未识别到文字', + '润色未完成,原文已保留', + '文字已保留,输入未完成', +]) { + assert.ok(history.includes(status), `history status "${status}" must exist`); +} +assert.doesNotMatch( + history, + /Segmented\(\{\s*items: TAB_LABELS/, + 'the 记录/速记 segment lives in the menu, not on the page', +); +assert.match(history, /速记/, 'the scratchpad entry stays reachable'); +assert.match(history, /PinnedSearchBar\(/, 'history pins its search bar'); + +// 5. Dictionary chips + orbs. +assert.match(kit, /export struct CapsuleTrack/, 'the capsule track is shared, not page-local'); +assert.match( + kit, + /scrollable\(ScrollDirection\.Horizontal\)/, + 'the chip track scrolls horizontally', +); +assert.match(library, /CapsuleTrack\(\{/, 'dictionary uses the capsule track'); +assert.match(library, /bottomActions\(\)/, 'dictionary keeps the floating action area'); +assert.match(library, /\.width\(52\)/, 'orbs are 52vp like the video'); +assert.match(library, /searchOpen/, 'search expands from the orb'); + +// 6. Style sections come from the dock; no page-level section segmented. +assert.doesNotMatch(library, /STYLE_SEGMENTS/, 'style sections are not a page segmented'); +assert.match(library, /@StorageLink\('styleSection'\)/, 'style section is shared with the dock'); +assert.match(library, /设置文字模型/, 'the model entry row is present'); +assert.match( + nav, + /我的风格[\s\S]{0,200}风格市场[\s\S]{0,200}翻译目标/, + 'expanded dock lists all three sections', +); + +// 7. Settings uses the pinned search bar and the grouped section helper. +assert.match(settings, /PinnedSearchBar\(\{/, 'settings pins its search bar'); +assert.match(settings, /SettingsSection\(\{/, 'settings uses the inset-grouped helper'); + +// 8. Shared motion tokens and the native dock material remain, without an +// extra page-wide scrim that would flatten the immersive translucent surface. +assert.match(kit, /export struct PinnedSearchBar/, 'the pinned bar is a shared primitive'); +assert.match( + ets('common/Theme.ets'), + /static readonly dock: number = 280;/, + 'dock expansion uses the iOS 0.28s', +); +assert.doesNotMatch(shell, /DockScrim\(|ProductRail\(/, 'the shell mounts only the floating dock'); +assert.match(nav, /ImmersiveMaterial/, 'the dock paints the system immersive material'); +assert.match(nav, /pillGradient\(\)/, 'older devices keep the painted glass fallback'); + +// 9. The isolated dock platter is a fixed 62vp circle, not a tablet-width ratio. +assert.match(nav, /const DOCK_HEIGHT: number = 62;/); +assert.match(nav, /const DOCK_GAP: number = 10;/); +assert.match(nav, /\.width\(this\.expanded\(\) \? DOCK_HEIGHT : undefined\)/); +assert.match(nav, /\.width\(this\.expanded\(\) \? undefined : DOCK_HEIGHT\)/); +assert.doesNotMatch(nav, /layoutWeight\(this\.expanded\(\) \? (?:1 : 4|3 : 1)\)/); +const metrics = ets('components/overview/TodayMetricsCard.ets'); +assert.match( + metrics, + /\.id\(this\.metricId\)[\s\S]{0,40}\.width\('100%'\)/, + 'metric tile contents and their border must fill the allocated half-row', +); +for (const id of ['today-chars', 'today-duration', 'average-duration', 'total-records']) { + assert.ok(metrics.includes(`'metric-${id}'`)); +} +assert.match( + ets('components/overview/BrandBar.ets'), + /Image\(\$r\('app\.media\.openless_icon'\)\)/, +); +assert.doesNotMatch(ets('components/overview/BrandBar.ets'), /Text\('OL'\)/); + +// 10. Every sheet sends an SDK-typed radius, including orientation updates. +for (const [label, source] of [ + ['overview', overview], + ['history', history], + ['library', library], + ['settings', settings], +]) { + assert.equal( + (source.match(/radius: LengthMetrics\.vp\(Radius\.sheet\)/g) ?? []).length, + (source.match(/\.bindSheet\(/g) ?? []).length, + `${label} must type every sheet radius`, + ); + assert.doesNotMatch(source, /radius:\s*\{\s*topStart:/); +} + +// 11. Product silhouettes keep the iOS meanings: chart, closed dictionary, +// three-slider settings and sparkles instead of house/calendar/wand glyphs. +const icons = ets('components/Icons.ets'); +for (const name of ['dock_overview', 'dock_dictionary', 'dock_settings', 'dock_style']) { + const svg = readFileSync( + join(appRoot, '../harmony/entry/src/main/resources/base/media', name + '.svg'), + 'utf8', + ); + assert.match(svg, /viewBox="0 0 24 24"/); + assert.match(svg, / readFileSync(new URL(file, root), 'utf8'); +const clone = (value) => JSON.parse(JSON.stringify(value)); +function load(text, globals = {}) { + const exports = {}; + const clean = text.replace(/^import[\s\S]*?;\n/gm, ''); + const result = ts.transpileModule(clean, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + reportDiagnostics: true, + }); + assert.equal(result.diagnostics?.length ?? 0, 0); + vm.runInNewContext(result.outputText, { exports, console, ...globals }); + return exports; +} +const deferred = () => { + let resolve; + const promise = new Promise((yes) => { + resolve = yes; + }); + return { promise, resolve }; +}; +const tick = () => new Promise((resolve) => setImmediate(resolve)); +const { StyleEditing } = load(source('data/StyleEditing.ets')); +const original = { + id: 'imported.fixture', + name: 'Do not rename', + description: 'Do not erase', + author: 'Author', + version: '7.8.9', + kind: 'imported', + baseMode: 'formal', + prompt: 'speech original', + selectionPrompt: 'independent written rules', + voiceEditPrompt: 'independent EditPlan rules', + examples: [{ title: 'Example', input: 'a', output: 'b' }], + tags: ['retain'], + iconPath: '/fixture/icon.png', + createdAt: 'created', + updatedAt: 'updated', + enabled: false, + active: false, + recommendedModel: 'keep-model', + compatibleAppVersion: 'keep-version', + originPackId: 'remote-1', + originAuthorLogin: 'owner', + futureMetadata: { keep: 'unknown fields too' }, +}; +const edited = StyleEditing.withPrompt(original, 'new speech only'); +assert.deepEqual(clone(edited), { ...original, prompt: 'new speech only' }); +assert.equal(original.prompt, 'speech original', 'editor cannot mutate the loaded snapshot'); +assert.throws( + () => StyleEditing.withPrompt({ id: 'partial', name: 'x', prompt: 'x' }, 'unsafe'), + /不完整/, +); +for (const field of ['author', 'recommendedModel', 'compatibleAppVersion']) { + const partial = clone(original); + delete partial[field]; + assert.throws( + () => StyleEditing.withPrompt(partial, 'unsafe'), + /不完整/, + 'missing nullable metadata must fail closed, not silently default in Rust: ' + field, + ); +} +const created = StyleEditing.create(' New style ', ' literal prompt\n'); +assert.equal(created.name, 'New style'); +assert.equal(created.prompt, ' literal prompt\n', 'prompt whitespace is authored content'); +assert.equal(created.kind, 'imported'); +assert.equal(created.version, '1.0.0'); +assert.equal(created.selectionPrompt, ''); +assert.equal('systemPrompt' in created, false); +assert.throws(() => StyleEditing.create(' ', 'x'), /名称/); +const remote = { id: 'remote-1', authorLogin: 'owner', likeCount: 3, downloadCount: 8 }; +assert.equal(StyleEditing.installed(remote, [original]), true); +assert.equal( + StyleEditing.installed({ ...remote, authorLogin: 'different-owner' }, [original]), + false, +); + +const calls = []; +let listed = [clone(original)]; +class HarmonyApi { + async invokeAsync(command, argsJson) { + const args = JSON.parse(argsJson); + calls.push({ command, args }); + let value = null; + if (command === 'list_style_packs') value = listed; + if (command === 'save_style_pack') value = args.stylePack; + if (command === 'create_style_pack_from_template') value = { ...args.template, id: 'new-id' }; + if (command === 'marketplace_like') value = { alreadyLiked: false, likeCount: 2 }; + if (command === 'marketplace_auth_status') value = { signedIn: true }; + if (command === 'github_device_flow_poll') value = { kind: 'authorized', login: 'fixture' }; + return JSON.stringify({ ok: true, value }); + } +} +const { Api } = load(source('data/Api.ets'), { HarmonyApi, StyleEditing }); +await Api.createStylePack('New', 'speech'); +assert.equal(calls.at(-1).command, 'create_style_pack_from_template'); +assert.equal(calls.at(-1).args.template.prompt, 'speech'); +await Api.updateStylePrompt(original.id, 'edited from current Core snapshot'); +assert.equal(calls.at(-2).command, 'list_style_packs'); +assert.equal(calls.at(-1).command, 'save_style_pack'); +assert.deepEqual(calls.at(-1).args.stylePack, { + ...original, + prompt: 'edited from current Core snapshot', +}); +listed = []; +const beforeMissing = calls.length; +await assert.rejects(Api.updateStylePrompt(original.id, 'lost target'), /不存在/); +assert.equal(calls.length, beforeMissing + 1, 'missing targets never send save'); +assert.deepEqual(clone(await Api.likePack('remote-1')), { alreadyLiked: false, likeCount: 2 }); +assert.equal((await Api.marketplaceAuthStatus()).signedIn, true); +assert.equal((await Api.githubDeviceFlowPoll('flow')).kind, 'authorized'); +await Api.githubDeviceFlowCancel('flow'); +assert.deepEqual(calls.at(-1), { command: 'github_device_flow_cancel', args: { flowId: 'flow' } }); +await Api.openExternalUrl('https://github.com/login/device'); +assert.equal(calls.at(-1).command, 'open_external_url'); + +const library = source('pages/LibraryPages.ets'); +const start = library.indexOf('@Component\nexport struct StylePage'); +const controllerSource = + library + .slice(start, library.indexOf(' build()', start)) + .replace('@Component\n', '') + .replace('export struct StylePage', 'export class StylePage') + .replace(/@(StorageLink|Watch)\('[^']*'\)\s*/g, '') + .replace(/@State\s+/g, '') + '\n}\n'; +function harness() { + const messages = [], + commands = [], + timers = new Map(); + let nextTimer = 0; + const backend = { + packs: [clone(original)], + signedIn: false, + poll: { kind: 'authorized', login: 'fixture-user' }, + like: { alreadyLiked: true, likeCount: 4 }, + market: [clone(remote)], + }; + const mock = { + stylePacks: async () => clone(backend.packs), + settings: async () => ({ preferences: { activeStylePackId: 'other' } }), + createStylePack: async (name, prompt) => { + commands.push(['create', name, prompt]); + }, + updateStylePrompt: async (id, prompt) => { + commands.push(['edit', id, prompt]); + }, + marketplaceAuthStatus: async () => ({ signedIn: backend.signedIn }), + marketplace: async (query, sort) => { + commands.push(['search', query, sort]); + return clone(backend.market); + }, + githubDeviceFlowStart: async () => ({ + flowId: 'flow', + userCode: 'PUBLIC', + verificationUri: 'https://github.com/login/device', + interval: 2, + expiresIn: 600, + }), + githubDeviceFlowPoll: async () => { + commands.push(['poll']); + if (backend.poll.kind === 'authorized') backend.signedIn = true; + return clone(backend.poll); + }, + githubDeviceFlowCancel: async (id) => { + commands.push(['cancel', id]); + }, + copyText: async () => {}, + openExternalUrl: async (url) => { + commands.push(['browser', url]); + }, + likePack: async (id) => { + commands.push(['like', id]); + return clone(backend.like); + }, + installMarketplacePack: async (id) => { + commands.push(['install', id]); + }, + }; + const { StylePage } = load(controllerSource, { + Api: mock, + StyleEditing, + SHEET_CREATE: 'create', + SHEET_EDIT: 'edit', + SHEET_DETAIL: 'detail', + SHEET_MARKET: 'market', + Layout: { LG: 'lg', XL: 'xl' }, + notify: (message) => messages.push(message), + setTimeout: (callback, delay) => { + const id = ++nextTimer; + timers.set(id, { callback, delay }); + return id; + }, + clearTimeout: (id) => timers.delete(id), + }); + const page = new StylePage(); + page.viewActive = true; + page.packs = clone(backend.packs); + return { + page, + mock, + backend, + messages, + commands, + timers, + fire() { + const [id, timer] = timers.entries().next().value ?? []; + assert.ok(timer, 'a pending timer is required'); + timers.delete(id); + timer.callback(); + return timer.delay; + }, + }; +} +const create = harness(); +create.page.newName = 'New'; +create.page.newPrompt = 'literal'; +await create.page.createPack(); +assert.deepEqual( + create.commands.find((entry) => entry[0] === 'create'), + ['create', 'New', 'literal'], +); +const edit = harness(); +edit.page.selectedId = original.id; +edit.page.startEdit(); +assert.equal(edit.page.draftPrompt, original.prompt); +edit.page.draftPrompt = 'changed'; +edit.page.selectedId = 'some-other-selection'; // Frozen editor target, not mutable UI selection. +await edit.page.savePrompt(); +assert.deepEqual( + edit.commands.find((entry) => entry[0] === 'edit'), + ['edit', original.id, 'changed'], +); +const duplicate = harness(); +const gate = deferred(); +duplicate.mock.createStylePack = async () => { + duplicate.commands.push(['create']); + await gate.promise; +}; +duplicate.page.newName = 'New'; +const first = duplicate.page.createPack(); +await duplicate.page.createPack(); +assert.equal(duplicate.commands.filter((entry) => entry[0] === 'create').length, 1); +gate.resolve(); +await first; + +const login = harness(); +const authorization = login.page.startLogin(); +await tick(); +assert.deepEqual( + login.commands.find((entry) => entry[0] === 'browser'), + ['browser', 'https://github.com/login/device'], +); +assert.equal(login.fire(), 2000); +await authorization; +assert.equal(login.page.signedIn, true); +assert.equal(login.page.loginState, '已登录 fixture-user'); +assert.equal( + login.commands.filter((entry) => entry[0] === 'poll').length, + 1, + 'authorized kind must stop polling', +); +assert.equal(login.timers.size, 0); +const cancelled = harness(); +const pendingLogin = cancelled.page.startLogin(); +await tick(); +cancelled.page.aboutToDisappear(); +await pendingLogin; +assert.equal( + cancelled.commands.some((entry) => entry[0] === 'poll'), + false, +); +assert.ok(cancelled.commands.some((entry) => entry[0] === 'cancel')); +assert.equal(cancelled.timers.size, 0); +const slow = harness(); +slow.backend.poll = { kind: 'slowDown' }; +const slowLogin = slow.page.startLogin(); +await tick(); +slow.fire(); +await tick(); +assert.equal( + [...slow.timers.values()][0].delay, + 7000, + 'slowDown increases the next server poll interval', +); +slow.page.cancelLogin(); +await slowLogin; + +const search = harness(); +const searches = []; +search.mock.marketplace = (query) => { + const item = deferred(); + searches.push({ query, ...item }); + return item.promise; +}; +search.page.marketQuery = 'a'; +const a = search.page.reloadMarket(); +await tick(); +search.page.marketQuery = 'ab'; +const ab = search.page.reloadMarket(); +await tick(); +searches[1].resolve([{ ...remote, id: 'AB' }]); +await ab; +searches[0].resolve([{ ...remote, id: 'A' }]); +await a; +assert.equal(search.page.marketPacks[0].id, 'AB', 'older search cannot overwrite newer results'); +const likes = harness(); +likes.page.marketPacks = [clone(remote)]; +await likes.page.like(remote.id); +assert.equal(likes.page.marketPacks[0].likeCount, 4); +assert.equal(likes.page.marketLiked(remote.id), true); +likes.backend.like = { alreadyLiked: false, likeCount: 3 }; +await likes.page.like(remote.id); +assert.equal(likes.page.marketLiked(remote.id), false); +assert.equal(likes.messages.at(-1), '已取消点赞'); +const installed = harness(); +installed.page.marketPacks = [clone(remote)]; +await installed.page.install(remote.id); +assert.equal( + installed.commands.some((entry) => entry[0] === 'install'), + false, + 'installed origin-matched pack cannot be accidentally installed twice', +); +assert.match(library, /singleColumn|phoneLayout/); +assert.doesNotMatch( + library, + /StylePackPayload|\.builtIn|\.systemPrompt|poll\.state|auth\.loggedIn|pack\.installed/, +); +assert.match( + library, + /Layout\.dockClearance\(\) \+ 76/, + 'vocabulary floating actions keep existing layout clearance', +); +console.log( + 'Harmony library actions: Core creation, lossless prompt-only edits, missing-target refusal, duplicate guard, OAuth kind/cancellation/slowDown, last-query ownership, install origins and like toggles passed', +); diff --git a/openless-all/app/scripts/harmony-native-ui.test.mjs b/openless-all/app/scripts/harmony-native-ui.test.mjs new file mode 100644 index 000000000..c53e01dc4 --- /dev/null +++ b/openless-all/app/scripts/harmony-native-ui.test.mjs @@ -0,0 +1,336 @@ +// Contract test for the native HarmonyOS UI (v2 design system). +// +// v2 replaced the glass/glow "Common.ets + Tokens.ets" stack with a small, +// closed vocabulary: `common/Theme.ets` (semantic tokens) + `components/Kit.ets` +// (one way to draw a card, row, button, chip or input). This test guards the +// invariants that actually broke or drifted during the migration: +// +// * a WebView shell creeping back in (dead bundle + two UIs drifting apart); +// * destination ownership drifting between system back and navigation; +// * a route that exists in the dock/rail but has no page behind it; +// * pages drifting back to hard-coded hex colors or font sizes; +// * a light-mode token without a dark counterpart; +// * the v1 files resurrecting. +// +// Text-based so it runs in the Linux contract job (no node_modules required). +import assert from 'node:assert/strict'; +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const harmonyRoot = resolve(appRoot, '../harmony'); +const ets = (path) => readFileSync(join(harmonyRoot, 'entry/src/main/ets', path), 'utf8'); +const read = (path) => readFileSync(join(harmonyRoot, path), 'utf8'); +const has = (path) => existsSync(join(harmonyRoot, path)); + +const index = ets('pages/Index.ets'); +const shell = ets('components/AppShell.ets'); +const nav = ets('components/Nav.ets'); +const navigation = ets('components/ProductNavigation.ets'); +const theme = ets('common/Theme.ets'); +const kit = ets('components/Kit.ets'); +const moduleJson = read('entry/src/main/module.json5'); +const buildScript = read('scripts/build-harmony-app.sh'); +const packaging = read('scripts/package-harmony-hap.sh'); + +const PAGE_FILES = [ + 'pages/OverviewPage.ets', + 'pages/HistoryPage.ets', + 'pages/LibraryPages.ets', + 'pages/SettingsPage.ets', + 'pages/ToolPages.ets', + 'pages/ModelsPage.ets', + 'pages/CredentialsPage.ets', + 'pages/SelectionPage.ets', +]; +const pages = PAGE_FILES.map(ets).join('\n'); + +// 1. Native UI only: no ArkWeb shell, no web bundle. +for (const [label, source] of [ + ['pages/Index.ets', index], + ['components/AppShell.ets', shell], +]) { + assert.doesNotMatch( + source, + /@kit\.ArkWeb|webview\.|WebviewController/, + `${label} must not import ArkWeb`, + ); + assert.doesNotMatch(source, /rawfile\('web\/|Web\(\{/, `${label} must not host the web bundle`); +} +assert.ok( + !existsSync(join(harmonyRoot, 'entry/src/main/resources/rawfile/web')), + 'the web bundle must not be staged', +); +for (const file of [ + 'build-profile.json5', + 'entry/src/main/module.json5', + 'entry/src/main/ets/pages/Index.ets', +]) { + assert.ok( + !existsSync(join(appRoot, 'harmony', file)), + 'the retired app-local project must not return: ' + file, + ); +} +assert.ok( + !existsSync(join(appRoot, 'scripts/build-harmony-app.sh')), + 'the retired app-local builder must stay deleted', +); +assert.doesNotMatch( + buildScript, + /npm run build|web-dist|rawfile\/web'\)/, + 'the build must not produce a web bundle', +); +assert.match(packaging, /build-harmony-app\.sh/, 'packaging drives the native build script'); +assert.ok( + !has('scripts/build-harmony-frontend.sh'), + 'the old frontend-bundle script must stay gone', +); + +// 2. v1 design system is gone for good. +for (const stale of [ + 'entry/src/main/ets/components/Common.ets', + 'entry/src/main/ets/components/Material.ets', + 'entry/src/main/ets/common/Tokens.ets', +]) { + assert.ok(!has(stale), `${stale} must stay deleted`); +} + +// 3. Shared navigation model + five product destinations. +assert.match( + ets('common/Store.ets'), + /AppStorage\.setOrCreate\(key, value\)/, + 'Store.put uses the documented create-or-update operation', +); +const primary = nav.match(/static readonly PRIMARY: string\[\] = \[([\s\S]*?)\];/)?.[1] ?? ''; +const primaryIds = [...primary.matchAll(/Nav\.([A-Z]+)/g)].map((m) => m[1]); +assert.deepEqual( + primaryIds, + ['OVERVIEW', 'HISTORY', 'VOCAB', 'STYLE', 'SETTINGS'], + 'five product destinations stay available across layouts', +); +for (const id of ['SELECTION', 'TRANSLATION', 'CORRECTIONS', 'QA', 'CREDENTIALS', 'LOCALASR']) { + assert.match(nav, new RegExp(`id: Nav\\.${id}, label:`), `${id} must be listed in Nav.tools()`); +} +assert.ok( + !/Nav\.MARKETPLACE|Nav\.QUICKNOTE/.test(nav), + 'marketplace and quicknote routes are merged away', +); +assert.match( + nav, + /static rootOf\(id: string\): string/, + 'secondary pages need a top-level owner for the dock', +); +assert.match( + navigation, + /Nav\.rootOf\(this\.route\)/, + 'navigation must highlight the owning destination', +); +assert.match(navigation, /backgroundBlurStyle/, 'the dock uses native Harmony blur'); +assert.match( + navigation, + /Nav\.DOCK_MAIN/, + 'the compact dock groups primary items separately from styles', +); +assert.match(shell, /ProductDock\(/, 'shell delegates compact navigation'); +assert.doesNotMatch(shell, /ProductRail\(/, 'iOS keeps the tab bar on tablets, so no side rail'); +assert.doesNotMatch(shell + theme, /NO_RAIL/, 'wide navigation must not be forced off'); +assert.match(shell, /Layout\.bodyMax/, 'split pages must not be limited to single-column width'); +assert.match(index, /return Nav\.back\(\)/, 'system back follows the shared navigation model'); + +// 3b. iOS dock: fixed circular Dictionary platter + three-item Styles platter when expanded. +for (const label of ['我的风格', '风格市场', '翻译目标']) { + assert.ok(navigation.includes(`'${label}'`), `expanded dock must offer ${label}`); +} +assert.match( + navigation, + /this\.item\(Nav\.VOCAB, '词典'/, + 'expanded dock keeps 词典 as the way back', +); +assert.match(navigation, /Motion\.dock/, 'dock expansion uses the iOS 0.28s timing'); +assert.doesNotMatch(shell, /DockScrim\(/, 'the dock material must not get an extra opaque scrim'); +assert.doesNotMatch(navigation, /icon2\(\)\)\]/g, 'unselected dock glyphs use the primary ink'); + +// 4. Every page the shell routes to exists and is exported. +for (const struct of [ + 'OverviewPage', + 'HistoryPage', + 'StylePage', + 'VocabPage', + 'CorrectionsPage', + 'SettingsPage', + 'CredentialsPage', + 'SelectionPage', + 'TranslationPage', + 'QaPage', + 'LocalAsrPage', +]) { + assert.ok(pages.includes(`export struct ${struct}`), `missing native page ${struct}`); + assert.ok(shell.includes(`${struct}()`), `AppShell must render ${struct}`); +} +assert.match( + shell, + /else \{\s*\n\s*OverviewPage\(\)/, + 'unknown routes must fall back to the overview', +); + +// 5. Design tokens: one closed scale, resource-backed colors only. +assert.match(theme, /static readonly xxs: number = 4;/, 'spacing starts at 4vp'); +assert.match( + theme, + /static readonly xxl: number = 40;/, + 'spacing tops out at 40vp in the 4-step grid', +); +assert.match(theme, /static readonly body: number = 17;/, 'Body follows the iOS 17pt body style'); +assert.match( + theme, + /static readonly caption: number = 13;/, + 'captions follow the iOS 13pt footnote', +); +assert.match(theme, /static readonly caption2: number = 11;/, 'the 11pt caption2 tier exists'); +assert.match(theme, /static readonly card: number = 16;/, 'cards use the product 16vp radius'); +assert.match( + theme, + /static contentMax\(bp: string\): number \{[\s\S]{0,400}return 880;/, + 'XL content is capped', +); +assert.doesNotMatch( + theme, + /backgroundBlurStyle|linearGradient/, + 'tokens must not paint material themselves', +); +assert.match(kit, /export struct PageScaffold/, 'pages share one scaffold'); + +// 6. Pages only use tokens: no hex colors, no literal font sizes. +const hex = /#[0-9A-Fa-f]{6,8}\b/; +for (const file of PAGE_FILES) { + const source = ets(file); + assert.ok(!hex.test(source), `${file} must not hard-code a color`); + assert.ok(!/fontSize\(\s*\d/.test(source), `${file} must not hard-code a font size`); + assert.ok(!/backgroundBlurStyle\(/.test(source), `${file} must not paint its own material`); + assert.match(source, /from '\.\.\/components\/Kit'/, `${file} must use the shared kit`); +} +assert.ok(!hex.test(kit), 'the kit must not hard-code a color'); + +// 7. Light and dark palettes stay in step, and both carry the v2 roles. +const colors = (theme) => + JSON.parse(read(`entry/src/main/resources/${theme}/element/color.json`)).color.map((e) => e.name); +const light = colors('base'); +const dark = colors('dark'); +for (const name of light) assert.ok(dark.includes(name), `dark palette is missing ${name}`); +assert.ok( + light.filter((name) => name.startsWith('c_')).length >= 20, + 'the v2 palette defines the shared roles', +); +for (const role of ['c_bg', 'c_card', 'c_line', 'c_text_1', 'c_accent', 'c_danger']) { + assert.ok(light.includes(role), `missing color role ${role}`); +} + +// 8. Merged surfaces keep their behaviour. +assert.ok( + !/export struct MarketplacePage/.test(pages), + 'the marketplace is a section of StylePage', +); +assert.ok(!/export struct QuickNotePage/.test(pages), 'quick note lives inside the history page'); +assert.match( + ets('pages/LibraryPages.ets'), + /风格市场/, + 'StylePage must expose the marketplace section', +); +assert.match(ets('pages/HistoryPage.ets'), /速记/, 'HistoryPage must expose the notes section'); +assert.match( + ets('pages/OverviewPage.ets'), + /Dashboard/, + 'the overview composes user-selectable cards', +); +assert.match( + ets('common/Dashboard.ets'), + /static readonly CARDS/, + 'the dashboard keeps a card registry', +); + +// 9. Everything still goes through the one bridge to the shared Rust core. +for (const file of ['pages/OverviewPage.ets', 'pages/HistoryPage.ets', 'pages/SettingsPage.ets']) { + assert.match(ets(file), /from '\.\.\/data\/Api'/, `${file} must use the typed Api façade`); + assert.doesNotMatch( + ets(file), + /nativeHost\.invoke/, + `${file} must not call the native module directly`, + ); +} +for (const [label, file, api] of [ + ['history playback', 'pages/HistoryPage.ets', /Api\.readRecording/], + ['history re-polish', 'pages/HistoryPage.ets', /Api\.repolish/], + ['dictation', 'pages/OverviewPage.ets', /Api\.startDictation/], + ['settings writes', 'pages/SettingsPage.ets', /Api\.writeBool/], + ['cloud sync', 'pages/SettingsPage.ets', /Api\.cloudSyncUpload/], + ['credentials', 'pages/CredentialsPage.ets', /Api\.setCredential/], + ['channel test', 'pages/CredentialsPage.ets', /Api\.validateChannel/], + ['channel create', 'pages/CredentialsPage.ets', /Api\.createChannel/], + ['marketplace install', 'pages/LibraryPages.ets', /Api\.installMarketplacePack/], + ['marketplace like', 'pages/LibraryPages.ets', /Api\.likePack/], +]) { + assert.match(ets(file), api, `${label} must stay wired`); +} + +// 10. One UI for phone, tablet and 2-in-1 within the signing profile. +assert.match( + moduleJson, + /"deviceTypes":\s*\[\s*\n\s*"phone",\s*\n\s*"tablet"\s*\n\s*\]/, + 'deviceTypes must be phone + tablet', +); +assert.doesNotMatch( + moduleJson, + /"2in1"/, + 'a 2in1 device type needs a 2-in-1 signing profile first', +); +assert.match(moduleJson, /"orientation": "auto_rotation"/, 'the window must be free to rotate'); +assert.doesNotMatch( + ets('common/Breakpoint.ets'), + /mediaquery\.matchMediaSync/, + 'the size class must not depend on mediaquery', +); +assert.match( + ets('common/Breakpoint.ets'), + /getWindowProperties\(\)/, + 'the size class must use the window rectangle', +); + +// 11. Presentational modules must not duplicate backend or recording state. +for (const file of [ + 'VoiceSessionCard', + 'TranscriptCard', + 'TodayMetricsCard', + 'ActivityTrendCard', +]) { + const source = ets(`components/overview/${file}.ets`); + assert.doesNotMatch( + source, + /@State|@StorageLink|Api\./, + `${file} must receive props and callbacks`, + ); + assert.ok(!hex.test(source), `${file} uses semantic colors`); +} +assert.match( + ets('pages/OverviewPage.ets'), + /AdaptiveColumns/, + 'overview reuses the common reflow container', +); +assert.match( + ets('components/AdaptiveLayout.ets'), + /@BuilderParam primary/, + 'layout separates content slots', +); +assert.match( + ets('pages/ModelsPage.ets'), + /SystemSpeechCard/, + 'system offline trial is distinct from Core model support', +); +assert.match( + ets('pages/LibraryPages.ets'), + /@StorageLink\('styleSection'\)/, + 'style tabs and dock share selection', +); +console.log( + 'Harmony native UI: five destinations, modular pages, adaptive shell and native model trial passed', +); diff --git a/openless-all/app/scripts/harmony-release-contract.test.mjs b/openless-all/app/scripts/harmony-release-contract.test.mjs index 47ec273d1..0d88c4b9e 100644 --- a/openless-all/app/scripts/harmony-release-contract.test.mjs +++ b/openless-all/app/scripts/harmony-release-contract.test.mjs @@ -1,9 +1,8 @@ // Contract test for the HarmonyOS release path. // -// The HAP cannot be built on a hosted runner (the DevEco SDK is account-gated), -// so the risks this test guards are structural: the entry point must pin the tag, -// run on the SDK-bearing runner by default, keep every credential in Secrets, and -// hand the signed HAP to both the GitHub Release and AppGallery Connect. +// Hosted runners obtain checksum-pinned Harmony tools. This contract guards the +// native build entry, immutable tag source, draft-only asset writes, and signing +// separation: unsigned HAPs go to GitHub; signed App Packs go only to AppGallery. // Text-based so it also runs in the Linux contract job (no node_modules). import assert from 'node:assert/strict'; import { existsSync, readFileSync } from 'node:fs'; @@ -41,11 +40,29 @@ assert.match(workflow, /does not match package\.json version/); assert.match(workflow, /default: '\["ubuntu-latest"\]'/); assert.match(workflow, /prepare-harmony-sdk\.sh/); -// A hosted runner ships neither the app's `node_modules` (`build-harmony-frontend.sh` -// runs `npm run build`) nor the Tier-2 OHOS target std (`build-harmony-backend.sh` -// runs `cargo build --target aarch64-unknown-linux-ohos`). CI installs both; the -// first real dispatch of this workflow did not and died with `can't find crate for -// `core`` (error[E0463]) after the Rime/NDK compile. +// The product targets HarmonyOS 7 (API 26) while staying installable on 6.1 +// (API 23). Huawei maps 26.0.0 -> HarmonyOS 7.0 and 6.1.0 -> API 23, so the +// compiled HAP must keep that exact triple: a lower compile version drops the +// API 26 material APIs, a higher compatible one cuts off 6.1 devices. +{ + const profile = JSON.parse(readFileSync(join(appRoot, '../harmony/build-profile.json5'), 'utf8')); + const product = profile.app.products.find((entry) => entry.name === 'default'); + assert.ok(product, 'build-profile.json5 must keep the default product'); + assert.equal(product.runtimeOS, 'HarmonyOS'); + assert.equal(product.compatibleSdkVersion, '6.1.0(23)'); + assert.equal(product.compileSdkVersion, '26.0.0'); + assert.equal(product.targetSdkVersion, '26.0.0'); + // compileSdkVersion drives the API surface; targetSdkVersion must not exceed + // it or the HAP claims behaviour the compiler never checked. + const minor = (value) => Number(/^(\d+)\./.exec(value)?.[1] ?? -1); + assert.equal(minor(product.compileSdkVersion), 26); + assert.equal(minor(product.targetSdkVersion), 26); + assert.equal(/^(\d+)\.(\d+)\.(\d+)\((\d+)\)$/.exec(product.compatibleSdkVersion)?.[4], '23'); +} + +// Node dependencies support tag tooling/contract tests; the native HAP does not +// build a React bundle. Both CI and release must install the Tier-2 OHOS target +// before compiling the shared Rust host. assert.match(workflow, /dtolnay\/rust-toolchain@stable/); assert.match(workflow, /targets: aarch64-unknown-linux-ohos/); assert.match(workflow, /run: npm ci/); @@ -61,11 +78,60 @@ assert.match(workflow, /run: npm ci/); assert.deepEqual(ohosTargets(workflow), ohosTargets(ciWorkflow)); } const prepare = readFileSync(join(appRoot, '../harmony/scripts/prepare-harmony-sdk.sh'), 'utf8'); -assert.match(prepare, /DEFAULT_URL=https:\/\//); +// The toolchain default is the pinned API 26 (HarmonyOS 7) release, shipped as +// two ordered shards; the digest covers the concatenation. +assert.match(prepare, /DEFAULT_PARTS="https:\/\/[^"]*\.tar\.gz\.aa https:\/\/[^"]*\.tar\.gz\.ab"/); assert.match(prepare, /DEFAULT_SHA256=[0-9a-f]{64}/); +assert.match(prepare, /HARMONY_MIN_API:-26/); +assert.match(prepare, /below the required API \$min_api/); assert.match(prepare, /checksum mismatch/); +assert.doesNotMatch(prepare, /releases\/latest/); // No DevEco install: the standalone hvigor CLI must be usable. assert.match(packaging, /@ohos\/hvigor\/bin\/hvigor\.js/); +const nativeBuild = readFileSync(join(appRoot, '../harmony/scripts/build-harmony-app.sh'), 'utf8'); +assert.match(packaging, /bash "\$HARMONY_ROOT\/scripts\/build-harmony-app\.sh"/); +assert.match(nativeBuild, /bash "\$HARMONY_ROOT\/scripts\/build-harmony-backend\.sh"/); +// Source versions are placeholders; packaging injects and restores the release identity. +const sourceApp = JSON.parse( + readFileSync(join(appRoot, '../harmony/AppScope/app.json5'), 'utf8'), +).app; +assert.equal(sourceApp.versionCode, 1); +assert.equal(sourceApp.versionName, '0.1.0'); +assert.match(nativeBuild, /trap restore_app_json EXIT/); +assert.doesNotMatch(nativeBuild, /npm run build|web-dist|dist\/index\.html/); +assert.ok( + !existsSync(join(appRoot, 'scripts/build-harmony-app.sh')), + 'no retired app-local builder', +); +assert.ok( + !existsSync(join(appRoot, '../harmony/scripts/build-harmony-frontend.sh')), + 'no second frontend builder', +); +// Reused Hvigor staging must discard deleted modules and obsolete web assets. +assert.match(nativeBuild, /shutil\.rmtree\(staged_ets\)/); +assert.match(nativeBuild, /shutil\.rmtree\(stale_web\)/); +const verify = readFileSync(join(appRoot, '../harmony/scripts/verify-harmony-hap.sh'), 'utf8'); +assert.match(verify, /require_entry 'libs\/arm64-v8a\/libopenless_harmony_host\.so'/); +assert.match(verify, /HAP still carries the removed ArkWeb bundle/); + +// Both manual and automatic publication are draft-only. Check at the beginning +// and again immediately before writing, so publishing during a build is safe. +const preflightIndex = workflow.indexOf('- name: Require a draft before publishing'); +const buildIndex = workflow.indexOf('- name: Build, sign and stage the HAP'); +assert.ok(preflightIndex > 0 && preflightIndex < buildIndex); +const attachStep = workflow.slice( + workflow.indexOf('- name: Attach the HAP to the GitHub Release'), + workflow.indexOf('- name: Upload to HUAWEI AppGallery Connect'), +); +for (const guard of [ + workflow.slice(preflightIndex, workflow.indexOf('- uses: actions/setup-java@v4')), + attachStep, +]) { + assert.match(guard, /if: inputs\.publish/); + assert.match(guard, /if \[ "\$draft" != true \]; then/); + assert.doesNotMatch(guard, /github\.event_name/, 'manual dispatch cannot bypass the draft guard'); +} +assert.match(attachStep, /exit 1[\s\S]*gh release upload/); // Distribution policy: the repository only ever carries the unsigned package, // AppGallery gets the signed one, and the test channel signs with its own diff --git a/openless-all/app/scripts/harmony-responsive-ui.test.mjs b/openless-all/app/scripts/harmony-responsive-ui.test.mjs new file mode 100644 index 000000000..7dfcb0e44 --- /dev/null +++ b/openless-all/app/scripts/harmony-responsive-ui.test.mjs @@ -0,0 +1,156 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +import ts from 'typescript'; + +const stored = new Map(); +const storage = { + get: (key) => stored.get(key), + setOrCreate: (key, value) => stored.set(key, value), +}; +const Store = { put: (key, value) => stored.set(key, value) }; +function load(path) { + const source = readFileSync( + new URL(`../../harmony/entry/src/main/ets/${path}`, import.meta.url), + 'utf8', + ).replace(/^import .*;\n/gm, ''); + const exports = {}; + const result = ts.transpileModule(source, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + }); + vm.runInNewContext(result.outputText, { exports, AppStorage: storage, Store, console }); + return exports; +} + +const { Breakpoints, WindowWatcher } = load('common/Breakpoint.ets'); +const { Layout } = load('common/Theme.ets'); +const { Nav } = load('components/Nav.ets'); +assert.deepEqual([0, 319, 320, 599, 600, 839, 840, 1080, 1439, 1440, 1920].map(Breakpoints.of), [ + 'sm', + 'sm', + 'sm', + 'sm', + 'md', + 'md', + 'lg', + 'lg', + 'lg', + 'xl', + 'xl', +]); + +// Read real window dimensions, not device type or cached default-display density. +let density = 2; +let resize; +let detached = 0; +const window = { + getWindowProperties: () => ({ windowRect: { width: 780, height: 1688 } }), + getUIContext: () => ({ px2vp: (value) => value / density }), + on: (event, listener) => { + assert.equal(event, 'windowSizeChange'); + resize = listener; + }, + off: (event, listener) => { + assert.equal(event, 'windowSizeChange'); + assert.equal(listener, resize); + detached++; + }, +}; +const changes = []; +const watcher = new WindowWatcher(); +watcher.start(window, (bp, short) => changes.push([bp, short])); +assert.deepEqual(changes, [['sm', false]], 'initial compact dimensions must publish too'); +resize({ width: 800, height: 1700 }); +assert.equal(changes.length, 1, 'resize inside a class must not duplicate publications'); +resize({ width: 1688, height: 780 }); +assert.deepEqual(changes.at(-1), ['lg', true], 'landscape uses the wider body and short headers'); +resize({ width: 1688, height: 1600 }); +assert.deepEqual(changes.at(-1), ['lg', false], 'height changes also update chrome'); +density = 1.5; +resize({ width: 2250, height: 1500 }); +assert.deepEqual(changes.at(-1), ['xl', false], 'conversion follows the active UIContext'); +watcher.stop(); +assert.equal(detached, 1, 'remove exactly the registered listener'); +const count = changes.length; +resize({ width: 600, height: 800 }); +assert.equal(changes.length, count, 'late callbacks after detach must be inert'); + +// Orientation decides content presentation: a portrait tablet keeps one column, +// while a wide landscape/split window can spread into panes. Both keep the dock. +{ + let portraitCb; + const portraitWindow = { + getWindowProperties: () => ({ windowRect: { width: 1600, height: 2560 } }), + getUIContext: () => ({ px2vp: (value) => value / 2 }), + on: (_event, listener) => { + portraitCb = listener; + }, + off: () => {}, + }; + const seen = []; + const portraitWatcher = new WindowWatcher(); + portraitWatcher.start(portraitWindow, (bp, short, portrait) => seen.push([bp, short, portrait])); + assert.deepEqual(seen.at(-1), ['md', false, true], 'a portrait tablet reports the phone layout'); + portraitCb({ width: 2560, height: 1600 }); + assert.deepEqual(seen.at(-1), ['lg', false, false], 'landscape enables a multi-pane body'); + portraitWatcher.stop(); +} + +// A bottom dock does not consume horizontal space. Reading columns and wider +// workspaces retain separate budgets rather than reserving a retired side rail. +for (const width of [320, 390, 600, 839, 840, 1080, 1439, 1440, 1920]) { + const bp = Breakpoints.of(width); + const body = Math.min(width, Layout.bodyMax(bp, 'history')) - 2 * Layout.gutter(bp); + if (width >= 840) { + assert.ok( + body - 360 - Layout.columnGap(bp) >= 320, + `history detail needs at least 320vp after list/gutter at ${width}vp`, + ); + assert.ok(Layout.bodyMax(bp, 'overview') > Layout.contentMax(bp)); + } + assert.equal( + Layout.bodyMax(bp, 'credentials'), + Layout.contentMax(bp), + 'forms retain readable width', + ); +} +assert.deepEqual(Array.from(Nav.PRIMARY), ['overview', 'history', 'vocab', 'style', 'settings']); +assert.equal(Nav.ownerOf(Nav.CORRECTIONS), Nav.VOCAB); +assert.equal( + Nav.ownerOf(Nav.TRANSLATION), + Nav.TRANSLATION, + 'translation targets is a dock destination', +); +assert.equal(Nav.rootOf(Nav.LOCALASR), Nav.SETTINGS); +stored.set('route', Nav.HISTORY); +stored.set('detailId', 'history-42'); +Nav.go(Nav.HISTORY); +assert.equal( + stored.get('detailId'), + 'history-42', + 'reselecting a tab must not erase its selection', +); +Nav.go(Nav.VOCAB); +assert.equal(stored.get('detailId'), ''); +Nav.go(Nav.CORRECTIONS); +Nav.go(Nav.SETTINGS); +Nav.openPrimary(Nav.VOCAB); +assert.equal(stored.get('route'), Nav.CORRECTIONS, 'restore each destination navigation path'); +assert.equal(Nav.back(), true); +assert.equal(stored.get('route'), Nav.VOCAB, 'system back returns to owning primary, not home'); +Nav.openPrimary(Nav.HISTORY); +assert.equal( + stored.get('detailId'), + 'history-42', + 'restore the history selection across destinations', +); +assert.equal(Nav.back(), true); +assert.equal(stored.get('detailId'), ''); +Nav.go(Nav.TRANSLATION); +assert.equal(Nav.back(), true, 'translation is its own dock destination, so back leaves it'); +assert.equal(stored.get('route'), Nav.OVERVIEW); +Nav.go(Nav.OVERVIEW); +assert.equal(Nav.back(), false, 'root home delegates exit to the system'); +console.log( + 'Harmony responsive UI: window reflow, density, height, width budgets, navigation restoration and back passed', +); diff --git a/openless-all/app/scripts/harmony-sdk-prepare.test.mjs b/openless-all/app/scripts/harmony-sdk-prepare.test.mjs new file mode 100644 index 000000000..72d0fba71 --- /dev/null +++ b/openless-all/app/scripts/harmony-sdk-prepare.test.mjs @@ -0,0 +1,296 @@ +// Fixture test for `prepare-harmony-sdk.sh`: the CI toolchain must be an API 26 +// (HarmonyOS 7) tree and must be rejected from its own metadata rather than from +// a tools build number. Every case runs the real script against small synthetic +// archives; no 2.28 GB download, no network, no real toolchain touched. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// `prepare-harmony-sdk.sh` is a POSIX shell installer (bash/tar/grep). Windows +// has no bash in the hosted test image, so this fixture is skipped there; the +// Ubuntu Harmony job runs it unconditionally. +if (process.platform === 'win32') { + console.log('HarmonyOS SDK prepare: skipped on win32 (POSIX installer fixture)'); + process.exit(0); +} + +const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const script = resolve(appRoot, '../harmony/scripts/prepare-harmony-sdk.sh'); +const text = readFileSync(script, 'utf8'); + +// The pinned default is the API 26 tools archive; it must stay a fixed, +// sharded public asset with a complete digest - never `latest`. +assert.match( + text, + /DEFAULT_PARTS="https:\/\/[^"]*26\.0\.0\.821\/ohos-sdk-linux-amd64\.tar\.gz\.aa https:\/\/[^"]*26\.0\.0\.821\/ohos-sdk-linux-amd64\.tar\.gz\.ab"/, + 'default download must pin both API 26 shards by release tag', +); +assert.match(text, /DEFAULT_SHA256=[0-9a-f]{64}/, 'the complete archive digest must be pinned'); +assert.doesNotMatch( + text, + /releases\/latest|huggingface\.co/, + 'no floating or API 21 mirror default', +); +assert.match(text, /HARMONY_MIN_API:-26/, 'minimum API must default to 26'); +// The API level comes from sdk-pkg.json, never from the archive/tools name. +assert.match(text, /sdk_metadata "\$metadata" apiVersion/); +assert.match(text, /below the required API \$min_api/); + +const work = mkdtempSync(join(tmpdir(), 'openless-sdk-prepare-')); +const home = join(work, 'home'); +const temp = join(work, 'tmp'); +mkdirSync(home, { recursive: true }); +mkdirSync(temp, { recursive: true }); + +function makeTree(api, stage = 'Release') { + const dir = mkdtempSync(join(work, 'tree-')); + for (const part of [ + 'sdk/default/openharmony/ets', + 'sdk/default/openharmony/toolchains', + 'hvigor', + 'tool', + 'ohpm', + 'bin', + ]) { + mkdirSync(join(dir, part), { recursive: true }); + } + writeFileSync( + join(dir, 'sdk/default/sdk-pkg.json'), + JSON.stringify({ + meta: {}, + data: { + apiVersion: String(api), + displayName: `HarmonyOS ${api}.0.0`, + platformVersion: `${api}.0.0`, + stage, + }, + }), + ); + writeFileSync(join(dir, 'bin/hvigorw'), '#!/bin/sh\nexit 0\n'); + chmodSync(join(dir, 'bin/hvigorw'), 0o755); + writeFileSync(join(dir, 'LICENSE.txt'), 'fixture license'); + return dir; +} + +function pack(tree, name) { + const out = join(work, name); + execFileSync('tar', ['-czf', out, '-C', tree, '.']); + return out; +} + +function digest(file) { + return createHash('sha256').update(readFileSync(file)).digest('hex'); +} + +function run({ url, parts, sha256, minApi, replace, toolchain }) { + const env = { ...process.env }; + delete env.HARMONY_SDK_URL; + delete env.HARMONY_SDK_PARTS; + delete env.HARMONY_SDK_SHA256; + delete env.HARMONY_MIN_API; + delete env.HARMONY_SDK_REPLACE; + env.HOME = home; + env.TMPDIR = temp; + env.OPENLESS_HARMONY_TOOLCHAIN = toolchain; + if (url !== undefined) env.HARMONY_SDK_URL = url; + if (parts !== undefined) env.HARMONY_SDK_PARTS = parts; + if (sha256 !== undefined) env.HARMONY_SDK_SHA256 = sha256; + if (minApi !== undefined) env.HARMONY_MIN_API = minApi; + if (replace !== undefined) env.HARMONY_SDK_REPLACE = replace; + try { + const out = execFileSync('bash', [script], { + env, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + return { code: 0, output: out }; + } catch (error) { + return { code: error.status ?? 1, output: `${error.stdout ?? ''}${error.stderr ?? ''}` }; + } +} + +const fresh = () => mkdtempSync(join(work, 'toolchain-')); + +async function main() { + const api21 = pack(makeTree(21), 'api21.tar.gz'); + const api26 = pack(makeTree(26), 'api26.tar.gz'); + const api26Sha = digest(api26); + + // 1. An API 21 archive is the old CI toolchain; it must fail before ArkTS. + { + const result = run({ url: `file://${api21}`, sha256: digest(api21), toolchain: fresh() }); + assert.notEqual(result.code, 0, 'API 21 archive must be rejected'); + assert.match(result.output, /below the required API 26/); + } + + // 2. The same archive passes when a lower floor is requested explicitly, so the + // guard is metadata-driven and configurable, not a hard-coded path check. + { + const result = run({ + url: `file://${api21}`, + sha256: digest(api21), + minApi: '21', + toolchain: fresh(), + }); + assert.equal(result.code, 0, result.output); + assert.match(result.output, /SDK ready at .* \(API 21, Release\)/); + } + + // 3. API 26 installs and keeps the toolchain shape the build script drives. + { + const root = fresh(); + const result = run({ url: `file://${api26}`, sha256: api26Sha, toolchain: root }); + assert.equal(result.code, 0, result.output); + assert.match(result.output, /SDK ready at .* \(API 26, Release\)/); + assert.ok(existsSync(join(root, 'bin/hvigorw')), 'bundled hvigorw must survive install'); + const installed = JSON.parse(readFileSync(join(root, 'sdk/default/sdk-pkg.json'), 'utf8')); + assert.equal(String(installed.data.apiVersion), '26'); + + // 4. A second run reuses the compatible tree instead of re-downloading. + const reused = run({ url: `file://${api26}`, sha256: api26Sha, toolchain: root }); + assert.equal(reused.code, 0, reused.output); + assert.match(reused.output, /already present at .* \(API 26\)/); + } + + // 5. A checksum mismatch aborts before anything is extracted. + { + const root = fresh(); + const result = run({ url: `file://${api26}`, sha256: '0'.repeat(64), toolchain: root }); + assert.notEqual(result.code, 0); + assert.match(result.output, /checksum mismatch/); + assert.ok(!existsSync(join(root, 'sdk/default/sdk-pkg.json'))); + } + + // 6. Sharded archives are concatenated in order before the digest is checked. + { + const bytes = readFileSync(api26); + const cut = Math.floor(bytes.length / 2); + const head = join(work, 'api26-split.tar.gz.aa'); + const tail = join(work, 'api26-split.tar.gz.ab'); + writeFileSync(head, bytes.subarray(0, cut)); + writeFileSync(tail, bytes.subarray(cut)); + const root = fresh(); + const result = run({ + parts: `file://${head} file://${tail}`, + sha256: api26Sha, + toolchain: root, + }); + assert.equal(result.code, 0, result.output); + assert.match(result.output, /SDK ready at .* \(API 26, Release\)/); + assert.ok(existsSync(join(root, 'sdk/default/openharmony/ets'))); + } + + // 7. A stale API 21 tree on disk is refused unless replacement is explicit. + { + const root = fresh(); + const old = makeTree(21); + cpSync(old, root, { recursive: true }); + const refused = run({ url: `file://${api26}`, sha256: api26Sha, toolchain: root }); + assert.notEqual(refused.code, 0); + assert.match(refused.output, /below the required 26/); + assert.match(refused.output, /HARMONY_SDK_REPLACE=1/); + const replaced = run({ + url: `file://${api26}`, + sha256: api26Sha, + replace: '1', + toolchain: root, + }); + assert.equal(replaced.code, 0, replaced.output); + const api = JSON.parse(readFileSync(join(root, 'sdk/default/sdk-pkg.json'), 'utf8')); + assert.equal(String(api.data.apiVersion), '26'); + } + + // 8. Only a Release SDK may provide the pinned toolchain. + { + const beta = pack(makeTree(26, 'Beta1'), 'api26-beta.tar.gz'); + const root = fresh(); + const result = run({ url: `file://${beta}`, sha256: digest(beta), toolchain: root }); + assert.notEqual(result.code, 0); + assert.match(result.output, /not Release/); + assert.ok( + !existsSync(join(root, 'sdk/default/sdk-pkg.json')), + 'a rejected SDK installs nothing', + ); + } + + // 9. A rejected candidate never damages an existing compatible install, even + // when replacement was explicitly allowed: validation happens while staged. + { + const root = fresh(); + const installed = run({ url: `file://${api26}`, sha256: api26Sha, toolchain: root }); + assert.equal(installed.code, 0, installed.output); + const marker = join(root, 'keep-me.txt'); + writeFileSync(marker, 'previous toolchain'); + // Drop the bundled hvigorw so the reuse shortcut cannot mask the download + // path this case must exercise. + rmSync(join(root, 'bin/hvigorw'), { force: true }); + const beta = pack(makeTree(26, 'Canary'), 'api26-canary.tar.gz'); + const refused = run({ + url: `file://${beta}`, + sha256: digest(beta), + replace: '1', + toolchain: root, + }); + assert.notEqual(refused.code, 0, 'non-Release candidate must be rejected'); + assert.match(refused.output, /not Release/); + assert.ok(existsSync(marker), 'existing toolchain files must survive a failed install'); + const still = JSON.parse(readFileSync(join(root, 'sdk/default/sdk-pkg.json'), 'utf8')); + assert.equal(String(still.data.apiVersion), '26'); + assert.equal(still.data.stage, 'Release'); + } + + // 10. A non-numeric floor fails loudly instead of reaching `[ -lt ]`. + { + const result = run({ + url: `file://${api26}`, + sha256: api26Sha, + minApi: 'twenty-six', + toolchain: fresh(), + }); + assert.notEqual(result.code, 0); + assert.match(result.output, /HARMONY_MIN_API must be a positive integer/); + } + + // 11. Match the real 26.0.0.821 archive: a command-line-tools wrapper plus + // emulator/sdk-pkg.json. The emulator metadata is not an SDK API contract. + { + const wrapper = mkdtempSync(join(work, 'wrapped-')); + const tools = join(wrapper, 'command-line-tools'); + cpSync(makeTree(26), tools, { recursive: true }); + mkdirSync(join(tools, 'emulator'), { recursive: true }); + writeFileSync( + join(tools, 'emulator/sdk-pkg.json'), + JSON.stringify({ meta: {}, data: { path: 'emulator', version: '26.0.0.821' } }), + ); + const archive = pack(wrapper, 'wrapped-tools.tar.gz'); + const root = fresh(); + const result = run({ url: `file://${archive}`, sha256: digest(archive), toolchain: root }); + assert.equal(result.code, 0, result.output); + const installed = JSON.parse(readFileSync(join(root, 'sdk/default/sdk-pkg.json'), 'utf8')); + assert.equal(installed.data.apiVersion, '26'); + assert.ok(existsSync(join(root, 'bin/hvigorw'))); + } + + console.log( + 'HarmonyOS SDK prepare: API 26 install, API 21/checksum/non-Release rejection, shard concatenation, staged validation, reuse, explicit replacement and wrapped toolchain root discovery passed', + ); +} + +try { + await main(); +} finally { + rmSync(work, { recursive: true, force: true }); +} diff --git a/openless-all/app/scripts/harmony-system-speech.test.mjs b/openless-all/app/scripts/harmony-system-speech.test.mjs new file mode 100644 index 000000000..ba8f57f76 --- /dev/null +++ b/openless-all/app/scripts/harmony-system-speech.test.mjs @@ -0,0 +1,287 @@ +// Offline Speech Kit controller regression: real ArkTS source, deterministic SDK mocks. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +import ts from 'typescript'; + +const source = readFileSync( + new URL('../../harmony/entry/src/main/ets/common/SystemSpeech.ets', import.meta.url), + 'utf8', +); +const card = readFileSync( + new URL( + '../../harmony/entry/src/main/ets/components/models/SystemSpeechCard.ets', + import.meta.url, + ), + 'utf8', +); +const compiled = ts.transpileModule(source.replace(/^import .*;\n/gm, ''), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, +}).outputText; +const deferred = () => { + let resolve, reject; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +}; +function harness({ supported = true, granted = true, response = [0] } = {}) { + const storage = new Map([ + ['dictPhase', 'idle'], + ['appForeground', true], + ]); + const timers = new Map(); + const updates = []; + const engines = []; + const creates = []; + let permissions = 0, + timerId = 0, + pendingCreate, + pendingPermission; + function engine() { + const e = { + starts: [], + finishes: [], + cancels: [], + shutdowns: 0, + listener: undefined, + setListener(listener) { + this.listener = listener; + }, + startListening(params) { + assert.ok(this.listener, 'listener is installed before starting'); + this.starts.push(params); + }, + finish(id) { + this.finishes.push(id); + }, + cancel(id) { + this.cancels.push(id); + }, + shutdown() { + this.shutdowns++; + }, + }; + engines.push(e); + return e; + } + const exports = {}; + vm.runInNewContext(compiled, { + exports, + canIUse: (capability) => { + assert.equal(capability, 'SystemCapability.AI.SpeechRecognizer'); + return supported; + }, + Store: { put: (key, value) => storage.set(key, value) }, + AppStorage: { get: (key) => storage.get(key) }, + abilityAccessCtrl: { + GrantStatus: { PERMISSION_GRANTED: 0 }, + createAtManager: () => ({ + checkAccessTokenSync: () => (granted ? 0 : -1), + requestPermissionsFromUser: async (_ctx, names) => { + permissions++; + assert.deepEqual(Array.from(names), ['ohos.permission.MICROPHONE']); + return pendingPermission ? pendingPermission.promise : { authResults: response }; + }, + }), + }, + speechRecognizer: { + createEngine: async (params) => { + creates.push(params); + return pendingCreate ? pendingCreate.promise : engine(); + }, + }, + setTimeout: (callback, delay) => { + const id = ++timerId; + timers.set(id, { callback, delay }); + return id; + }, + clearTimeout: (id) => timers.delete(id), + }); + const controller = new exports.SystemSpeech((snapshot) => updates.push(snapshot)); + return { + controller, + storage, + updates, + engines, + creates, + timers, + engine, + start: () => controller.start({ applicationInfo: { accessTokenId: 1 } }), + permissions: () => permissions, + waitCreate: () => (pendingCreate = deferred()), + waitPermission: () => (pendingPermission = deferred()), + fire: (delay) => { + const entry = [...timers.entries()].find(([, timer]) => timer.delay === delay); + assert.ok(entry, 'deadline exists: ' + delay); + timers.delete(entry[0]); + entry[1].callback(); + }, + }; +} + +const unavailable = harness({ supported: false }); +assert.equal(unavailable.creates.length, 0, 'construction never starts speech'); +await unavailable.start(); +assert.equal(unavailable.permissions(), 0); +assert.equal(unavailable.creates.length, 0); +assert.match(unavailable.controller.snapshot().error, /不会切换到云端/); + +const denied = harness({ granted: false, response: [-1] }); +await denied.start(); +assert.equal(denied.permissions(), 1); +assert.equal(denied.creates.length, 0); +assert.equal(denied.storage.get('systemSpeechBusy'), false); +assert.equal(denied.timers.size, 0); +for (const phase of ['starting', 'recording', 'processing', 'cancelling']) { + const busy = harness(); + busy.storage.set('dictPhase', phase); + await busy.start(); + assert.equal(busy.creates.length, 0); +} +const monitor = harness({ granted: false }); +monitor.storage.set('microphoneMonitorBusy', true); +await monitor.start(); +assert.equal(monitor.creates.length, 0, 'microphone monitor excludes offline trial'); +assert.equal(monitor.permissions(), 0, 'monitor exclusion happens before permission preparation'); +const hidden = harness(); +hidden.storage.set('appForeground', false); +await hidden.start(); +assert.equal(hidden.creates.length, 0); + +const consent = harness({ granted: false }); +const permission = consent.waitPermission(); +const permissionStart = consent.start(); +consent.controller.cancel(); +permission.resolve({ authResults: [0] }); +await permissionStart; +assert.equal(consent.creates.length, 0, 'late permission cannot start recording'); + +const late = harness(); +const lateCreation = late.waitCreate(); +const lateStart = late.start(); +late.controller.cancel(); +const lateEngine = late.engine(); +lateCreation.resolve(lateEngine); +await lateStart; +assert.equal(lateEngine.shutdowns, 1, 'late engine is released'); +assert.equal(lateEngine.starts.length, 0, 'late engine never starts audio'); + +const normal = harness(); +await normal.start(); +await normal.start(); +assert.equal(normal.creates.length, 1, 'duplicate starts are ignored'); +assert.deepEqual(JSON.parse(JSON.stringify(normal.creates[0])), { + language: 'zh-CN', + online: 1, + extraParams: { locate: 'CN', recognizerMode: 'short' }, +}); +const e = normal.engines[0]; +const id = e.starts[0].sessionId; +assert.deepEqual(JSON.parse(JSON.stringify(e.starts[0].audioInfo)), { + audioType: 'pcm', + sampleRate: 16000, + soundChannel: 1, + sampleBit: 16, +}); +assert.equal(e.starts[0].extraParams.recognitionMode, 0, 'system captures audio'); +assert.equal(normal.controller.snapshot().phase, 'starting'); +e.listener.onStart(id, 'start'); +assert.equal(normal.controller.snapshot().phase, 'listening'); +e.listener.onResult('wrong_session', { result: 'wrong', isFinal: true, isLast: true }); +assert.equal(normal.controller.snapshot().text, ''); +e.listener.onResult(id, { result: '离线试用', isFinal: false, isLast: false }); +assert.equal(normal.controller.snapshot().text, '离线试用'); +normal.controller.finish(); +assert.deepEqual(e.finishes, [id]); +assert.equal(normal.controller.snapshot().phase, 'finishing'); +e.listener.onResult(id, { result: '离线试用结果', isFinal: true, isLast: true }); +e.listener.onComplete(id, 'done'); +assert.equal(normal.controller.snapshot().phase, 'done'); +assert.equal(e.shutdowns, 1); +assert.equal(normal.storage.get('systemSpeechBusy'), false); +assert.equal(normal.timers.size, 0); +e.listener.onError(id, 1002200011, 'late'); +assert.equal(normal.controller.snapshot().text, '离线试用结果'); +await normal.start(); +const fresh = normal.engines[1]; +const freshId = fresh.starts[0].sessionId; +e.listener.onResult(freshId, { result: 'old generation', isFinal: true, isLast: true }); +assert.equal( + normal.controller.snapshot().text, + '', + 'generation rejects old engine with current session id', +); +fresh.listener.onError(freshId, 1002200006, 'busy'); +assert.match(normal.controller.snapshot().error, /正忙/); +assert.equal(fresh.shutdowns, 1); + +for (const mode of ['create', 'start', 'finish', 'recording', 'permission']) { + const h = harness({ granted: mode !== 'permission' }); + let pending; + if (mode === 'create') pending = h.waitCreate(); + if (mode === 'permission') pending = h.waitPermission(); + const starting = h.start(); + if (pending) { + h.fire(mode === 'permission' ? 30000 : 10000); + if (mode === 'create') pending.resolve(h.engine()); + else pending.resolve({ authResults: [0] }); + await starting; + } else { + await starting; + const current = h.engines[0]; + if (mode !== 'start') current.listener.onStart(current.starts[0].sessionId, 'start'); + if (mode === 'finish') h.controller.finish(); + h.fire(mode === 'recording' ? 25000 : 10000); + } + assert.equal(h.controller.snapshot().phase, 'error', mode + ' timeout'); + assert.equal(h.storage.get('systemSpeechBusy'), false); + assert.equal(h.timers.size, 0); + for (const engine of h.engines) assert.equal(engine.shutdowns, 1); +} + +const disposed = harness(); +const disposedCreation = disposed.waitCreate(); +const disposedStart = disposed.start(); +disposed.controller.dispose(); +const count = disposed.updates.length; +const disposedEngine = disposed.engine(); +disposedCreation.resolve(disposedEngine); +await disposedStart; +assert.equal(disposed.updates.length, count, 'disposed components receive no callbacks'); +assert.equal(disposedEngine.shutdowns, 1); +await disposed.start(); +assert.equal(disposed.creates.length, 1); + +const switched = harness(); +const switchedCreate = switched.waitCreate(); +const switchedStart = switched.start(); +switched.storage.set('dictPhase', 'recording'); +const switchedEngine = switched.engine(); +switchedCreate.resolve(switchedEngine); +await switchedStart; +assert.equal(switchedEngine.starts.length, 0, 'main dictation rechecked after create'); +assert.equal(switchedEngine.shutdowns, 1); + +const cleanup = harness(); +await cleanup.start(); +const cleanupEngine = cleanup.engines[0]; +cleanupEngine.cancel = () => { + throw Error('cancel failed'); +}; +cleanup.controller.cancel(); +assert.equal(cleanupEngine.shutdowns, 1, 'shutdown runs even if cancel throws'); +assert.equal(cleanup.controller.snapshot().text, ''); +assert.doesNotMatch( + source, + /console\.|Api\.|writeAudio\(/, + 'no content logs, core calls or manually supplied audio', +); +assert.match(card, /@StorageLink\('appForeground'\) @Watch\('onForeground'\)/); +assert.match(card, /@StorageLink\('dictPhase'\) @Watch\('onDictation'\)/); +assert.match(card, /aboutToDisappear\(\): void \{[\s\S]*?\.dispose\(\)/); +assert.doesNotMatch(card, /@Prop\s+onCopy|\bApi\./); +console.log( + 'System offline speech: official parameters, permission denial, mutual exclusion, result/finish, cancellation, stale sessions, late creation, lifecycle cleanup and all deadlines passed', +); diff --git a/openless-all/app/scripts/harmony-window-layout.test.mjs b/openless-all/app/scripts/harmony-window-layout.test.mjs new file mode 100644 index 000000000..4ab1c21cd --- /dev/null +++ b/openless-all/app/scripts/harmony-window-layout.test.mjs @@ -0,0 +1,232 @@ +// Execute the real layout watcher and page lifecycle against deterministic windows. +// This verifies responsive state wiring, not device animation smoothness. +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +import ts from 'typescript'; + +const base = new URL('../../harmony/entry/src/main/ets/', import.meta.url); +const read = (path) => readFileSync(new URL(path, base), 'utf8'); +function load(source, globals = {}) { + const exports = {}; + const compiled = ts.transpileModule(source.replace(/^import .*;\n/gm, ''), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + reportDiagnostics: true, + }); + assert.equal(compiled.diagnostics?.length ?? 0, 0, 'test source must transpile'); + vm.runInNewContext(compiled.outputText, { exports, console, ...globals }); + return exports; +} +function fakeWindow(width, height, density = 2) { + const listeners = new Set(); + const keyboardListeners = new Set(); + return { + width, + height, + listeners, + keyboardListeners, + onCount: 0, + offCount: 0, + keyboardModes: [], + getWindowProperties() { + return { windowRect: { width: this.width, height: this.height } }; + }, + getUIContext() { + return { + px2vp: (px) => px / density, + setKeyboardAvoidMode: (mode) => this.keyboardModes.push(mode), + }; + }, + on(name, listener) { + assert.ok(['windowSizeChange', 'keyboardHeightChange'].includes(name)); + this.onCount++; + (name === 'keyboardHeightChange' ? keyboardListeners : listeners).add(listener); + }, + off(name, listener) { + assert.ok(['windowSizeChange', 'keyboardHeightChange'].includes(name)); + this.offCount++; + assert.ok( + (name === 'keyboardHeightChange' ? keyboardListeners : listeners).delete(listener), + 'off must use the exact subscribed callback', + ); + }, + resize(width, height) { + this.width = width; + this.height = height; + for (const listener of listeners) listener({ width, height }); + }, + }; +} +const { Breakpoints, WindowWatcher } = load(read('common/Breakpoint.ets')); +for (const [width, expected] of [ + [0, 'sm'], + [599, 'sm'], + [600, 'md'], + [839, 'md'], + [840, 'lg'], + [1439, 'lg'], + [1440, 'xl'], +]) { + assert.equal(Breakpoints.of(width), expected); +} +const changes = []; +const watcher = new WindowWatcher(); +const tablet = fakeWindow(1600, 2560); +watcher.start(tablet, (...state) => changes.push(state)); +assert.deepEqual(changes.at(-1), ['md', false, true]); +tablet.resize(2560, 1600); +assert.deepEqual(changes.at(-1), ['lg', false, false]); +tablet.resize(1600, 2560); +assert.deepEqual(changes.at(-1), ['md', false, true]); +const sameCount = changes.length; +tablet.resize(1600, 2560); +assert.equal(changes.length, sameCount, 'duplicate size state is ignored'); +// Orientation must update even when both widths remain in the same size class. +tablet.resize(1800, 2200); +assert.deepEqual(changes.at(-1), ['lg', false, true]); +tablet.resize(2200, 1800); +assert.deepEqual(changes.at(-1), ['lg', false, false]); +tablet.resize(2200, 800); +assert.deepEqual(changes.at(-1), ['lg', true, false]); +const validCount = changes.length; +tablet.resize(0, 0); +assert.equal(changes.length, validCount, 'transient zero bounds are ignored'); +const stale = [...tablet.listeners][0]; +const dense = fakeWindow(1800, 3000, 3); +watcher.start(dense, (...state) => changes.push(state)); +assert.equal(tablet.listeners.size, 0, 'rebinding detaches the old main window'); +assert.deepEqual(changes.at(-1), ['md', false, true], 'conversion uses this window density'); +const reboundCount = changes.length; +stale({ width: 4000, height: 1000 }); +assert.equal(changes.length, reboundCount, 'queued events from the previous window are rejected'); +watcher.stop(); +assert.equal(dense.listeners.size, 0); +watcher.stop(); // Idempotent teardown. + +// Execute Index before its backend and declarative builders; neither is replaced +// in production. Strip decorators only, retaining the actual lifecycle methods. +const index = read('pages/Index.ets'); +const pageSource = + index + .slice(0, index.indexOf(' private async boot()')) + .replace(/^@(Entry|Component)\n/gm, '') + .replace(/@(StorageLink|Watch)\('[^']*'\)\s*/g, '') + .replace(/@State\s+/g, '') + .replace('struct Index', 'export class Index') + ' private boot(): void {}\n}\n'; +const storage = new Map([['bpOverride', 'xl']]); // Obsolete QA state cannot pin the new UI. +const put = (key, value) => storage.set(key, value); +const main = fakeWindow(1600, 2560); +const Boot = { mainWindow: main, takeRoute: () => 'history' }; +let released = 0; +const Nav = { OVERVIEW: 'overview', known: () => true, go: () => {}, back: () => false }; +const { Index } = load(pageSource, { + Boot, + WindowWatcher, + Nav, + KeyboardAvoidMode: { RESIZE: 'resize' }, + Store: { put }, + AppStorage: { get: (key) => storage.get(key), setOrCreate: put }, + Api: { bridgeOf: () => ({ release: () => released++ }) }, +}); +const page = new Index(); +page.aboutToAppear(); +assert.equal(storage.get('bp'), 'md'); +assert.equal(storage.get('phoneLayout'), true); +assert.deepEqual( + main.keyboardModes, + ['resize'], + 'use native RESIZE, never manually pan floating inputs', +); +assert.equal(main.keyboardListeners.size, 1); +const keyboardListener = [...main.keyboardListeners][0]; +keyboardListener(500); +assert.equal(storage.get('keyboardVisible'), true); +keyboardListener(0); +assert.equal(storage.get('keyboardVisible'), false); +put('detailId', 'keep-history-detail'); +put('route', 'history'); +main.resize(2560, 1600); +assert.equal(storage.get('bp'), 'lg'); +assert.equal(storage.get('phoneLayout'), false); +assert.equal(storage.get('route'), 'history'); +assert.equal(storage.get('detailId'), 'keep-history-detail', 'rotation does not reset navigation'); +main.resize(1600, 2560); +assert.equal(storage.get('phoneLayout'), true); +main.resize(3000, 4000); +assert.equal(storage.get('bp'), 'xl'); +assert.equal(storage.get('phoneLayout'), true, 'portrait tablets remain single-column even at XL'); +page.onPageHide(); +assert.equal(storage.get('appForeground'), false); +// Simulate a background window resize for which no callback was delivered. +main.width = 2560; +main.height = 1600; +page.onPageShow(); +assert.equal(storage.get('bp'), 'lg'); +assert.equal(storage.get('phoneLayout'), false); +assert.equal(main.listeners.size, 1, 'foreground rebinding cannot accumulate listeners'); +page.aboutToDisappear(); +assert.equal(main.listeners.size, 0); +assert.equal(main.keyboardListeners.size, 0); +keyboardListener(500); +assert.equal(storage.get('keyboardVisible'), false, 'detached keyboard callback must stay inert'); +assert.equal(released, 1); + +const columns = read('components/AdaptiveLayout.ets'); +assert.equal((columns.match(/this\.primary\(\)/g) ?? []).length, 1); +assert.equal((columns.match(/this\.secondary\(\)/g) ?? []).length, 1); +assert.match(columns, /FlexDirection\.Row\s*:\s*FlexDirection\.Column/); +assert.doesNotMatch( + columns, + /animateTo\(|\.animation\(|\.transition\(/, + 'rotation must not queue a second full-page animation', +); +assert.doesNotMatch(index, /getLastWindow|bpOverride|takeLayout|onLayoutPin/); +const columnsHead = + columns + .slice(0, columns.indexOf(' build()')) + .replace(/^@Component\n/gm, '') + .replace(/@Prop\s+|@BuilderParam\s+/g, '') + .replace('export struct AdaptiveColumns', 'export class AdaptiveColumns') + '\n}\n'; +const { AdaptiveColumns } = load(columnsHead, { + Layout: { SM: 'sm', isWide: (bp) => bp === 'lg' || bp === 'xl' }, +}); +const adaptive = new AdaptiveColumns(); +adaptive.bp = 'xl'; +adaptive.singleColumn = true; +assert.equal(adaptive.wide(), false, 'portrait mode must reach the reusable column container'); +adaptive.singleColumn = false; +assert.equal(adaptive.wide(), true); +adaptive.bp = 'sm'; +assert.equal(adaptive.wide(), false, 'a narrow landscape window stays single-column'); +for (const file of ['pages/OverviewPage.ets', 'pages/ModelsPage.ets']) { + assert.match(read(file), /singleColumn:\s*this\.phoneLayout/); +} +const shell = read('components/AppShell.ets'); +assert.doesNotMatch( + shell, + /padding\(\{ bottom: DOCK_CLEARANCE/, + 'floating navigation must not shrink the entire content viewport', +); +assert.doesNotMatch( + shell, + /Layout\.columnMax/, + 'portrait tablets must not be squeezed into a phone reading column', +); +assert.match(shell, /shell-content-viewport/); +assert.match(shell, /shell-floating-dock/); +assert.match(read('pages/HistoryPage.ets'), /contentEndOffset\(Layout\.dockClearance\(\)\)/); +for (const file of [ + 'pages/OverviewPage.ets', + 'pages/SettingsPage.ets', + 'components/Kit.ets', + 'components/history/HistoryDetail.ets', +]) { + assert.match( + read(file), + /bottom: Layout\.dockClearance\(\)/, + `${file} must reserve space at the scroll tail, not around the viewport`, + ); +} +console.log( + 'Harmony window layout: live rotation, same-breakpoint orientation, density, lifecycle, stale events and state-preserving reflow passed', +); diff --git a/openless-all/app/scripts/platform-directory-layout.test.mjs b/openless-all/app/scripts/platform-directory-layout.test.mjs index faab4bb4d..154e18295 100644 --- a/openless-all/app/scripts/platform-directory-layout.test.mjs +++ b/openless-all/app/scripts/platform-directory-layout.test.mjs @@ -53,9 +53,29 @@ for (const member of ['linux/egui', 'harmony/rust']) { assert.ok(read('app/Cargo.toml').includes(`"../${member}"`)); } -const files = execFileSync('git', ['ls-files', '-z'], { cwd: repo, encoding: 'utf8' }) - .split('\0') - .filter(Boolean); +// Inspect the current candidate tree, including unstaged new tests and script +// moves. The index alone omits new files and resurrects intentional deletions +// until the integrator stages them. Keep the same strict path/content rules for +// every remaining file; ignored build outputs are never part of this tree. +const gitFiles = (flags) => + execFileSync('git', ['ls-files', '-z', ...flags], { + cwd: repo, + encoding: 'utf8', + }) + .split('\0') + .filter(Boolean); +const candidateFiles = (listed, deleted) => { + const removed = new Set(deleted); + return [...new Set(listed)].filter((path) => !removed.has(path)).sort(); +}; +assert.deepEqual(candidateFiles(['tracked', 'new', 'tracked', 'deleted'], ['deleted']), [ + 'new', + 'tracked', +]); +const files = candidateFiles( + gitFiles(['--cached', '--others', '--exclude-standard']), + gitFiles(['--deleted']), +); const movedScripts = files.filter((path) => /^openless-all\/(?:android|harmony|linux|windows|macos)\/scripts\//.test(path), ); @@ -82,6 +102,7 @@ const scriptNames = movedScripts.map((path) => path.split('/scripts/')[1]); const activeExtensions = /(?:\.(?:[cm]?[jt]sx?|sh|zsh|ps1|cmd|py|rs|toml|json|json5|ya?ml|md|txt|patch|sln|vcxproj|props|targets|nsh|wxs)|(?:^|\/)CMakeLists\.txt)$/; for (const path of files) { + assert.ok(!oldPlatform.test(path), `obsolete platform file: ${path}`); // AOCI indexes are maintained in a separate task and may describe old trees. if (!activeExtensions.test(path) || path.startsWith('.aoci/') || /^aoci[^/]*\.txt$/.test(path)) continue; @@ -260,9 +281,22 @@ const mirror = read('windows/scripts/windows-build-gnu.ps1'); assert.match(mirror, /git -c core\.quotePath=false ls-files --cached --others --exclude-standard/); assert.match(mirror, /Join-Path \$MirrorRoot "app"/); assert.match(mirror, /Copy-Item -LiteralPath \(Join-Path \$allRoot \$relative\)/); -const frontend = read('harmony/scripts/build-harmony-frontend.sh'); -assert.match(frontend, /"\$APP_ROOT\/mobile-ime"/); -assert.match(frontend, /shutil\.copytree\(mobile_ime, target \/ 'mobile-ime'/); +const harmonyBuild = read('harmony/scripts/build-harmony-app.sh'); +assert.match(harmonyBuild, /OPENLESS_HARMONY_MOBILE_IME:-\$APP_ROOT\/mobile-ime/); +assert.match(harmonyBuild, /shutil\.copytree\(mobile_ime, target \/ 'mobile-ime'/); +assert.doesNotMatch(harmonyBuild, /npm run build|web-dist|dist\/index\.html/); +assert.ok(!existsSync(resolve(all, 'harmony/scripts/build-harmony-frontend.sh'))); +assert.ok(!existsSync(resolve(app, 'scripts/build-harmony-app.sh'))); +for (const file of [ + 'build-profile.json5', + 'entry/src/main/module.json5', + 'entry/src/main/ets/pages/Index.ets', +]) { + assert.ok( + !existsSync(resolve(app, 'harmony', file)), + 'the retired app-local Harmony project must not return: ' + file, + ); +} assert.match(read('windows/wix/openless-ime.wxs'), /Source="\$\(env\.OPENLESS_IME_DLL_X64\)"/); assert.match(read('windows/wix/openless-ime.wxs'), /Source="\$\(env\.OPENLESS_IME_DLL_X86\)"/); console.log('Platform directory layout, source paths, and bundle assets passed'); diff --git a/openless-all/harmony/build-profile.json5 b/openless-all/harmony/build-profile.json5 index fbc256e72..e1752d5bc 100644 --- a/openless-all/harmony/build-profile.json5 +++ b/openless-all/harmony/build-profile.json5 @@ -3,8 +3,9 @@ "products": [ { "name": "default", - "compatibleSdkVersion": "5.0.0(12)", - "targetSdkVersion": "6.0.0(20)", + "compatibleSdkVersion": "6.1.0(23)", + "compileSdkVersion": "26.0.0", + "targetSdkVersion": "26.0.0", "runtimeOS": "HarmonyOS" } ], diff --git a/openless-all/harmony/entry/oh-package.json5 b/openless-all/harmony/entry/oh-package.json5 index 02e421dfe..b222fe0a2 100644 --- a/openless-all/harmony/entry/oh-package.json5 +++ b/openless-all/harmony/entry/oh-package.json5 @@ -1,7 +1,7 @@ { "name": "entry", - "version": "0.1.0", - "description": "ArkWeb host", + "version": "1.0.0", + "description": "OpenLess HarmonyOS native ArkUI host", "dependencies": { "libopenless_harmony.so": "file:./src/main/cpp/types/libopenless_harmony" }, diff --git a/openless-all/harmony/entry/src/main/cpp/CMakeLists.txt b/openless-all/harmony/entry/src/main/cpp/CMakeLists.txt index faed2db44..609f3c8b8 100644 --- a/openless-all/harmony/entry/src/main/cpp/CMakeLists.txt +++ b/openless-all/harmony/entry/src/main/cpp/CMakeLists.txt @@ -8,3 +8,15 @@ set_target_properties(openless_harmony_host PROPERTIES IMPORTED_NO_SONAME TRUE) add_library(openless_harmony SHARED bridge.cpp) target_link_libraries(openless_harmony PUBLIC openless_harmony_host openless_rime_engine libace_napi.z.so) + +# `bridge.cpp` links the Rust core as an imported shared library, so the HAP must +# ship `libopenless_harmony_host.so` next to `libopenless_harmony.so` or the NAPI +# module fails to load at runtime ("Error loading shared library +# libopenless_harmony_host.so ... load failed"). hvigor only packages what the +# native build emits, so stage the Rust library into the CMake output directory; +# `entry/src/main/libs` on its own is never packaged. +add_custom_command(TARGET openless_harmony POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_CURRENT_SOURCE_DIR}/../libs/arm64-v8a/libopenless_harmony_host.so" + "$/libopenless_harmony_host.so" + COMMENT "Staging libopenless_harmony_host.so for the HAP") diff --git a/openless-all/harmony/entry/src/main/ets/HarmonyApi.ets b/openless-all/harmony/entry/src/main/ets/HarmonyApi.ets index 223e3d693..8fba00b22 100644 --- a/openless-all/harmony/entry/src/main/ets/HarmonyApi.ets +++ b/openless-all/harmony/entry/src/main/ets/HarmonyApi.ets @@ -2,7 +2,6 @@ import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; import { common, abilityAccessCtrl } from '@kit.AbilityKit'; import { audio } from '@kit.AudioKit'; import { fileIo as fs, picker } from '@kit.CoreFileKit'; -import { webview } from '@kit.ArkWeb'; import { asset } from '@kit.AssetStoreKit'; import { util } from '@kit.ArkTS'; import { BusinessError, pasteboard } from '@kit.BasicServicesKit'; @@ -31,6 +30,16 @@ interface DeviceInfo { name: string; isDefault: boolean; } interface DictationEvent { phase: string; level: number; error: string; } interface VoiceCredentialStatus { pipelineMode: string; asrConfigured: boolean; omniConfigured: boolean; } interface VoiceCredentialReply { ok: boolean; value: VoiceCredentialStatus; } +/** + * The native UI has no WebView to dispatch DOM events into, so the capability + * layer publishes into `AppStorage`: pages observe `dictPhase` / `dictLevel` / + * `dictError` / `backendRevision` / `micLevel` with `@StorageLink`. + */ +function publishBackendChanged(): void { + const current: number = AppStorage.get('backendRevision') ?? 0; + AppStorage.setOrCreate('backendRevision', current + 1); +} + class CommandArgs { channelId: string = ''; action: string = ''; registrationId: string = ''; deviceName: string = ''; pane: string = ''; account: string = ''; provider?: string; value: string = ''; fileName: string = ''; message: string = ''; url: string = ''; id: string = ''; zipPath: string = ''; targetPath: string = ''; text: string = ''; } export class HarmonyApi { @@ -116,7 +125,7 @@ export class HarmonyApi { const snapshot: RevisionReply = JSON.parse(await nativeHost.invokeAsync('__revision_snapshot', '{}')); if (snapshot.ok) { if (this.revisions && JSON.stringify(this.revisions) !== JSON.stringify(snapshot.value)) { - this.controller?.runJavaScript("window.dispatchEvent(new CustomEvent('openless:harmony-backend-change'))").catch(() => {}); + publishBackendChanged(); } this.revisions = snapshot.value; } @@ -204,41 +213,26 @@ export class HarmonyApi { try { fs.writeSync(destination.fd, bytes.buffer); } finally { fs.closeSync(destination); } } - private sequence: number = 0; - private results: Map = new Map(); - - request(command: string, args: string): string { - const id = String(++this.sequence); - this.invokeAsync(command, args).then((result: string) => { this.results.set(id, result); }); - return id; - } - - takeResult(id: string): string { - const result = this.results.get(id); - if (result === undefined) return ''; - this.results.delete(id); - return result; - } - private context?: common.UIAbilityContext; - private controller?: webview.WebviewController; private capturer?: audio.AudioCapturer; private lastLevelEvent: number = 0; private voice: VoiceClient = new VoiceClient(); private voiceEpoch: number = 0; + private monitorEpoch: number = 0; private voicePhase: string = 'idle'; private voiceLevelAt: number = 0; private publishVoice(phase: string, level: number = 0, error: string = ''): void { this.voicePhase = phase; - const state: DictationEvent = { phase: phase, level: level, error: error }; - this.controller?.runJavaScript("window.dispatchEvent(new CustomEvent('openless:harmony-dictation',{detail:" + - JSON.stringify(state) + '}))').catch(() => {}); + AppStorage.setOrCreate('dictPhase', phase); + AppStorage.setOrCreate('dictLevel', level); + AppStorage.setOrCreate('dictError', error); } private async startDictation(): Promise { if (!this.context) throw new Error('应用上下文未就绪'); if (this.voicePhase !== 'idle') throw new Error('请先结束当前录音'); + if (AppStorage.get('systemSpeechBusy') === true) throw new Error('请先结束端侧语音试用'); const epoch = ++this.voiceEpoch; this.publishVoice('starting'); try { @@ -273,7 +267,7 @@ export class HarmonyApi { if (epoch !== this.voiceEpoch) throw new Error('录音已取消'); this.voiceEpoch++; this.publishVoice('idle'); - this.controller?.runJavaScript("window.dispatchEvent(new CustomEvent('openless:harmony-backend-change'))").catch(() => {}); + publishBackendChanged(); return result; } catch (error) { if (epoch === this.voiceEpoch) { this.voiceEpoch++; this.publishVoice('idle', 0, String(error)); } @@ -287,9 +281,8 @@ export class HarmonyApi { try { await this.voice.cancel(); } finally { if (epoch === this.voiceEpoch) this.publishVoice('idle'); } } - configure(context: common.UIAbilityContext, controller: webview.WebviewController): void { + configure(context: common.UIAbilityContext): void { this.context = context; - this.controller = controller; } private bytes(value: string): Uint8Array { return new util.TextEncoder().encodeInto(value); } @@ -353,6 +346,8 @@ export class HarmonyApi { } private async stopMonitor(): Promise { + this.monitorEpoch++; + AppStorage.setOrCreate('microphoneMonitorBusy', false); const capturer = this.capturer; this.capturer = undefined; if (capturer) { @@ -362,16 +357,27 @@ export class HarmonyApi { private async startMonitor(name: string): Promise { if (this.voicePhase !== 'idle') throw new Error('请先结束当前录音'); + if (AppStorage.get('systemSpeechBusy') === true) throw new Error('请先结束端侧语音试用'); await this.stopMonitor(); - if (this.microphoneStatus() !== 'granted' && await this.requestMicrophone() !== 'granted') { - throw new Error('未获得麦克风权限,请在权限页面授权'); + if (this.voicePhase !== 'idle' || AppStorage.get('systemSpeechBusy') === true) { + throw new Error('麦克风正在使用中'); } - const capturer = await audio.createAudioCapturer({ - streamInfo: { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_16000, channels: audio.AudioChannel.CHANNEL_1, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW }, - capturerInfo: { source: audio.SourceType.SOURCE_TYPE_MIC, capturerFlags: 0 } - }); - this.capturer = capturer; + const epoch: number = ++this.monitorEpoch; + AppStorage.setOrCreate('microphoneMonitorBusy', true); try { + if (this.microphoneStatus() !== 'granted' && await this.requestMicrophone() !== 'granted') { + throw new Error('未获得麦克风权限,请在权限页面授权'); + } + if (epoch !== this.monitorEpoch) throw new Error('麦克风测试已取消'); + const capturer = await audio.createAudioCapturer({ + streamInfo: { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_16000, channels: audio.AudioChannel.CHANNEL_1, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW }, + capturerInfo: { source: audio.SourceType.SOURCE_TYPE_MIC, capturerFlags: 0 } + }); + if (epoch !== this.monitorEpoch) { + await capturer.release(); + throw new Error('麦克风测试已取消'); + } + this.capturer = capturer; if (name) { const selected = this.devices().filter((device: audio.AudioDeviceDescriptor) => this.deviceName(device) === name); if (selected.length === 0) throw new Error('选中的麦克风已断开'); @@ -379,6 +385,7 @@ export class HarmonyApi { if (!preferred.some((device: audio.AudioDeviceDescriptor) => device.id === selected[0].id)) throw new Error('当前系统使用其他输入设备,请在系统中切换麦克风或选择系统默认'); } capturer.on('readData', (buffer: ArrayBuffer) => { + if (epoch !== this.monitorEpoch) return; const now = Date.now(); if (now - this.lastLevelEvent < 100) return; this.lastLevelEvent = now; @@ -386,12 +393,12 @@ export class HarmonyApi { let sum = 0; for (let i = 0; i < pcm.length; i++) sum += pcm[i] * pcm[i]; const level = pcm.length ? Math.min(1, Math.sqrt(sum / pcm.length) / 32768 * 4) : 0; - this.controller?.runJavaScript("window.dispatchEvent(new CustomEvent('openless:harmony-level',{detail:" + level + '}))').catch(() => {}); + AppStorage.setOrCreate('micLevel', level); }); await capturer.start(); console.info('[OpenLess Audio] microphone monitor started'); } catch (error) { - await this.stopMonitor(); + if (epoch === this.monitorEpoch) await this.stopMonitor(); throw new Error(String(error)); } } diff --git a/openless-all/harmony/entry/src/main/ets/common/Appearance.ets b/openless-all/harmony/entry/src/main/ets/common/Appearance.ets new file mode 100644 index 000000000..9efb213f9 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Appearance.ets @@ -0,0 +1,26 @@ +import { common, ConfigurationConstant } from '@kit.AbilityKit'; + +/** + * System appearance. + * + * The v1 settings page exposed a 跟随系统 / 浅色 / 深色 switch that wrote a + * preference nobody read: the app always followed the system. v2 applies the + * preference through `ApplicationContext.setColorMode`, so the switch actually + * works and both the main pages and the IME panel resources follow it. + */ +export class Appearance { + static apply(context: common.UIAbilityContext, theme: string): void { + try { + const app = context.getApplicationContext(); + if (theme === 'light') { + app.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT); + } else if (theme === 'dark') { + app.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); + } else { + app.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); + } + } catch (error) { + console.warn('[OpenLess Appearance] color mode not applied'); + } + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/AudioPlayback.ets b/openless-all/harmony/entry/src/main/ets/common/AudioPlayback.ets new file mode 100644 index 000000000..2f539f6a8 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/AudioPlayback.ets @@ -0,0 +1,90 @@ +import { media } from '@kit.MediaKit'; +import { fileIo as fs } from '@kit.CoreFileKit'; +import { util } from '@kit.ArkTS'; + +/** One cancellable archived recording. A late player must never outlive its page. */ +export class AudioPlayback { + private player?: media.AVPlayer; + private sourceFile?: fs.File; + private playing: boolean = false; + private generation: number = 0; + + isPlaying(): boolean { + return this.playing; + } + + async play(cacheDir: string, sessionId: string, base64: string, onState: (playing: boolean) => void): Promise { + const generation: number = ++this.generation; + await this.releaseCurrent(); + if (generation !== this.generation) return; + const path: string = cacheDir + '/rec-' + sessionId + '.wav'; + const marker: number = base64.indexOf(';base64,'); + const encoded: string = marker >= 0 ? base64.slice(marker + 8) : base64; + const bytes: Uint8Array = new util.Base64Helper().decodeSync(encoded); + const file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE | fs.OpenMode.TRUNC); + try { + fs.writeSync(file.fd, bytes.buffer); + } finally { + fs.closeSync(file); + } + const player = await media.createAVPlayer(); + if (generation !== this.generation) { + await player.release(); + return; + } + this.player = player; + const sourceFile = fs.openSync(path, fs.OpenMode.READ_ONLY); + this.sourceFile = sourceFile; + player.on('stateChange', (state: string) => { + if (generation !== this.generation) return; + if (state === 'completed' || state === 'error') { + this.playing = false; + onState(false); + } + }); + player.on('error', () => { + if (generation !== this.generation) return; + this.playing = false; + onState(false); + }); + try { + player.fdSrc = { fd: sourceFile.fd, offset: 0, length: bytes.byteLength }; + await player.prepare(); + if (generation !== this.generation) return; + await player.play(); + if (generation !== this.generation) return; + this.playing = true; + onState(true); + } catch (error) { + if (generation !== this.generation) return; + await this.stop(); + onState(false); + throw new Error((error as Error).message); + } + } + + async stop(): Promise { + this.generation++; + await this.releaseCurrent(); + } + + private async releaseCurrent(): Promise { + const player = this.player; + const sourceFile = this.sourceFile; + this.player = undefined; + this.sourceFile = undefined; + this.playing = false; + try { + if (player !== undefined) { + try { + await player.stop(); + } catch (error) { + // A created/preparing player cannot always stop, but must still release. + } + await player.release(); + } + } finally { + if (sourceFile !== undefined) fs.closeSync(sourceFile); + } + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/Boot.ets b/openless-all/harmony/entry/src/main/ets/common/Boot.ets new file mode 100644 index 000000000..0c283c1fe --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Boot.ets @@ -0,0 +1,17 @@ +import { window } from '@kit.ArkUI'; + +/** + * Launch handoff before the page exists. The ability owns the main window; + * pages must not select the last window, which may be a sheet or dialog. + * Route hints are consumed once. Layout always follows the real window. + */ +export class Boot { + static route: string = ''; + static mainWindow?: window.Window; + + static takeRoute(): string { + const value: string = Boot.route; + Boot.route = ''; + return value; + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/Breakpoint.ets b/openless-all/harmony/entry/src/main/ets/common/Breakpoint.ets new file mode 100644 index 000000000..da1eb4dcf --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Breakpoint.ets @@ -0,0 +1,100 @@ +import { window } from '@kit.ArkUI'; + +/** Huawei recommended window-width boundaries (xs folds into compact sm). + * https://developer.huawei.com/consumer/cn/doc/best-practices-V5/bpta-multi-device-bp-practice-V5 + * No device-type/orientation lock: split and floating windows share this path. + */ +export class Breakpoints { + static readonly SM: string = 'sm'; + static readonly MD: string = 'md'; + static readonly LG: string = 'lg'; + static readonly XL: string = 'xl'; + + static isCompact(bp: string): boolean { + return bp === Breakpoints.SM; + } + + static isWide(bp: string): boolean { + return bp === Breakpoints.LG || bp === Breakpoints.XL; + } + + static isExtraWide(bp: string): boolean { + return bp === Breakpoints.XL; + } + + static of(widthVp: number): string { + if (widthVp < 600) return Breakpoints.SM; + if (widthVp < 840) return Breakpoints.MD; + if (widthVp < 1440) return Breakpoints.LG; + return Breakpoints.XL; + } +} + +export class WindowWatcher { + private win?: window.Window; + private callback?: (bp: string, shortWindow: boolean, portrait: boolean) => void; + private current: string = Breakpoints.SM; + private shortWindow: boolean = false; + private portrait: boolean = true; + private initialized: boolean = false; + private generation: number = 0; + private sizeListener?: (size: window.Size) => void; + + value(): string { + return this.current; + } + + start(target: window.Window, onChange: (bp: string, shortWindow: boolean, portrait: boolean) => void): void { + this.stop(); + this.win = target; + this.callback = onChange; + const generation: number = this.generation; + this.sizeListener = (size: window.Size): void => { + // An already queued event from a destroyed/replaced window is obsolete. + if (generation !== this.generation || this.win !== target) return; + this.apply(size.width, size.height); + }; + try { + const properties = target.getWindowProperties(); + this.apply(properties.windowRect.width, properties.windowRect.height); + target.on('windowSizeChange', this.sizeListener); + } catch (error) { + console.error('[OpenLess Window] watcher failed: ' + JSON.stringify(error)); + } + } + + stop(): void { + this.generation++; + if (this.win !== undefined && this.sizeListener !== undefined) { + try { + this.win.off('windowSizeChange', this.sizeListener); + } catch (error) { + console.warn('[OpenLess Window] detach failed'); + } + } + this.win = undefined; + this.callback = undefined; + this.sizeListener = undefined; + this.initialized = false; + } + + private apply(widthPx: number, heightPx: number): void { + if (this.win === undefined || widthPx <= 0 || heightPx <= 0) return; + // Bind conversion to this window's UIContext, not the default display density. + // https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkui-753 + const context = this.win.getUIContext(); + const widthVp: number = context.px2vp(widthPx); + const heightVp: number = context.px2vp(heightPx); + const next: string = Breakpoints.of(widthVp); + const short: boolean = heightVp < 480; + // Portrait keeps the phone presentation on tablets (iOS demo layout). + const portrait: boolean = heightVp >= widthVp; + if (this.initialized && next === this.current && short === this.shortWindow && + portrait === this.portrait) return; + this.initialized = true; + this.current = next; + this.shortWindow = short; + this.portrait = portrait; + if (this.callback !== undefined) this.callback(next, short, portrait); + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/Dashboard.ets b/openless-all/harmony/entry/src/main/ets/common/Dashboard.ets new file mode 100644 index 000000000..301cca918 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Dashboard.ets @@ -0,0 +1,96 @@ +import { preferences } from '@kit.ArkData'; +import { common } from '@kit.AbilityKit'; + +export interface DashboardCard { + id: string; + title: string; + hint: string; +} + +/** + * Home dashboard composition. + * + * The overview is a card grid the user composes: every info card can be hidden or + * shown from 「自定义主页」. The choice lives in a local preferences file (not in + * the shared preference document) so the Rust core schema stays untouched. + */ +export class Dashboard { + static readonly TODAY: string = 'today'; + static readonly PERIOD: string = 'period'; + static readonly HEATMAP: string = 'heatmap'; + static readonly RECENT: string = 'recent'; + static readonly CONFIG: string = 'config'; + static readonly SHORTCUTS: string = 'shortcuts'; + + /** Registry, also the display order of the grid. */ + static readonly CARDS: DashboardCard[] = [ + { id: Dashboard.TODAY, title: '今日数据', hint: '字数、时长、段数与累计记录' }, + { id: Dashboard.PERIOD, title: '最近趋势', hint: '近 7 / 30 天的使用趋势' }, + { id: Dashboard.HEATMAP, title: '活动热力图', hint: '近 12 周每天的听写量' }, + { id: Dashboard.RECENT, title: '最近记录', hint: '最新三条听写,可跳转历史' }, + { id: Dashboard.CONFIG, title: '当前配置', hint: '引擎、模型、麦克风与网络状态' }, + { id: Dashboard.SHORTCUTS, title: '快捷入口', hint: '翻译、问答、速记与风格市场' } + ]; + + private static store?: preferences.Preferences; + + static defaults(): string[] { + const ids: string[] = []; + for (let index = 0; index < Dashboard.CARDS.length; index++) { + ids.push(Dashboard.CARDS[index].id); + } + return ids; + } + + static titleOf(id: string): string { + for (let index = 0; index < Dashboard.CARDS.length; index++) { + if (Dashboard.CARDS[index].id === id) return Dashboard.CARDS[index].title; + } + return id; + } + + static hintOf(id: string): string { + for (let index = 0; index < Dashboard.CARDS.length; index++) { + if (Dashboard.CARDS[index].id === id) return Dashboard.CARDS[index].hint; + } + return ''; + } + + /** Keeps the registry order and drops unknown / duplicated ids. */ + static normalize(ids: string[]): string[] { + const result: string[] = []; + for (let index = 0; index < Dashboard.CARDS.length; index++) { + const id: string = Dashboard.CARDS[index].id; + if (ids.indexOf(id) >= 0) result.push(id); + } + return result; + } + + static async load(context: common.UIAbilityContext): Promise { + try { + if (Dashboard.store === undefined) { + Dashboard.store = await preferences.getPreferences(context, { name: 'home_dashboard' }); + } + const raw: string = String(await Dashboard.store.get('cards', '')); + if (raw.length === 0) return Dashboard.defaults(); + const parsed: string[] = JSON.parse(raw) as string[]; + const normalized: string[] = Dashboard.normalize(parsed); + return normalized.length > 0 ? normalized : Dashboard.defaults(); + } catch (error) { + console.warn('[OpenLess Dashboard] preferences unavailable, using defaults'); + return Dashboard.defaults(); + } + } + + static async save(context: common.UIAbilityContext, ids: string[]): Promise { + try { + if (Dashboard.store === undefined) { + Dashboard.store = await preferences.getPreferences(context, { name: 'home_dashboard' }); + } + await Dashboard.store.put('cards', JSON.stringify(Dashboard.normalize(ids))); + await Dashboard.store.flush(); + } catch (error) { + console.warn('[OpenLess Dashboard] failed to save card selection'); + } + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/Draft.ets b/openless-all/harmony/entry/src/main/ets/common/Draft.ets new file mode 100644 index 000000000..9d7fac787 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Draft.ets @@ -0,0 +1,57 @@ +import { preferences } from '@kit.ArkData'; +import { common } from '@kit.AbilityKit'; + +/** + * 速记 draft (quick note) persistence. + * + * The scratchpad lives in its own local preferences file next to the dashboard + * selection instead of the shared preference document, so the Rust core schema + * stays untouched. One string under one key: 速记 is a scratchpad, not a document + * store, and the history page only needs to restore the last text it saw. + */ +export class Draft { + private static readonly STORE_NAME: string = 'home_draft'; + private static readonly KEY: string = 'text'; + + private static store?: preferences.Preferences; + + /** Opens the file once and reuses it for the lifetime of the process. */ + private static async open(context: common.UIAbilityContext): Promise { + const existing: preferences.Preferences | undefined = Draft.store; + if (existing !== undefined) return existing; + const opened: preferences.Preferences = await preferences.getPreferences(context, { name: Draft.STORE_NAME }); + Draft.store = opened; + return opened; + } + + static async load(context: common.UIAbilityContext): Promise { + try { + const store: preferences.Preferences = await Draft.open(context); + const raw: string = String(await store.get(Draft.KEY, '')); + return raw; + } catch (error) { + console.warn('[OpenLess Draft] preferences unavailable, starting empty'); + return ''; + } + } + + static async save(context: common.UIAbilityContext, text: string): Promise { + try { + const store: preferences.Preferences = await Draft.open(context); + await store.put(Draft.KEY, text); + await store.flush(); + } catch (error) { + console.warn('[OpenLess Draft] failed to save'); + } + } + + static async clear(context: common.UIAbilityContext): Promise { + try { + const store: preferences.Preferences = await Draft.open(context); + await store.delete(Draft.KEY); + await store.flush(); + } catch (error) { + console.warn('[OpenLess Draft] failed to clear'); + } + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/Format.ets b/openless-all/harmony/entry/src/main/ets/common/Format.ets new file mode 100644 index 000000000..2059935e5 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Format.ets @@ -0,0 +1,101 @@ +/** Locale-aware formatting for the native pages. */ + +const MONTHS_ZH: string[] = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']; + +function pad(value: number): string { + return value < 10 ? '0' + value.toString() : value.toString(); +} + +export class Fmt { + /** "刚刚" / "5 分钟前" / "昨天 14:32" / "10月21日 14:32" */ + static relative(iso: string): string { + if (!iso) return ''; + const then = new Date(iso); + const ms = then.getTime(); + if (Number.isNaN(ms)) return iso; + const now = Date.now(); + const diff = Math.max(0, now - ms); + const minute = 60 * 1000; + const hour = 60 * minute; + if (diff < minute) return '刚刚'; + if (diff < hour) return Math.floor(diff / minute).toString() + ' 分钟前'; + const clock = pad(then.getHours()) + ':' + pad(then.getMinutes()); + const today = new Date(now); + const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime(); + if (ms >= startOfToday) { + if (diff < 6 * hour) return Math.floor(diff / hour).toString() + ' 小时前'; + return '今天 ' + clock; + } + if (ms >= startOfToday - 24 * hour) return '昨天 ' + clock; + const sameYear = then.getFullYear() === today.getFullYear(); + const head = (then.getMonth() + 1).toString() + '月' + then.getDate().toString() + '日'; + return sameYear ? head + ' ' + clock : then.getFullYear().toString() + '年' + head; + } + + /** "0:42" / "1:05:09" */ + static duration(ms: number | null | undefined): string { + if (ms === null || ms === undefined || ms <= 0) return '—'; + const total = Math.round(ms / 1000); + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + const seconds = total % 60; + if (hours > 0) return hours.toString() + ':' + pad(minutes) + ':' + pad(seconds); + return minutes.toString() + ':' + pad(seconds); + } + + /** 1234 -> "1,234" */ + static count(value: number): string { + const text = Math.round(value).toString(); + let out = ''; + let digits = 0; + for (let index = text.length - 1; index >= 0; index--) { + out = text.charAt(index) + out; + digits++; + if (digits % 3 === 0 && index > 0) out = ',' + out; + } + return out; + } + + static bytes(value: number): string { + if (value < 1024) return value.toString() + ' B'; + if (value < 1024 * 1024) return (value / 1024).toFixed(1) + ' KB'; + return (value / (1024 * 1024)).toFixed(1) + ' MB'; + } + + static monthDay(isoDate: string): string { + const date = new Date(isoDate); + if (Number.isNaN(date.getTime())) return isoDate; + return (date.getMonth() + 1).toString() + '月' + date.getDate().toString() + '日'; + } + + static weekday(isoDate: string): string { + const date = new Date(isoDate); + if (Number.isNaN(date.getTime())) return ''; + const names: string[] = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; + return names[date.getDay()]; + } + + /** Trims a transcript down to one list row. */ + static preview(text: string, limit: number): string { + if (!text) return ''; + const flat = text.replace(/\s+/g, ' ').trim(); + if (flat.length <= limit) return flat; + return flat.substring(0, limit) + '…'; + } + + static clock(iso: string): string { + const date = new Date(iso); + if (Number.isNaN(date.getTime())) return ''; + return pad(date.getHours()) + ':' + pad(date.getMinutes()); + } + + static todayIso(): string { + const now = new Date(); + return now.getFullYear().toString() + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate()); + } + + static monthLabel(month: number): string { + const index = Math.min(Math.max(month - 1, 0), 11); + return MONTHS_ZH[index]; + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/Labels.ets b/openless-all/harmony/entry/src/main/ets/common/Labels.ets new file mode 100644 index 000000000..f59f92542 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Labels.ets @@ -0,0 +1,107 @@ +/** Human labels for provider ids, modes and channels shared by the native pages. */ + +interface LabelPair { + id: string; + label: string; +} + +const PROVIDERS: LabelPair[] = [ + { id: 'volcengine', label: '火山引擎' }, + { id: 'elevenlabs', label: 'ElevenLabs' }, + { id: 'bailian', label: '阿里百炼' }, + { id: 'bailian-qwen3-realtime', label: '百炼 Qwen3 实时' }, + { id: 'bailian-fun-asr-flash', label: '百炼 Fun-ASR Flash' }, + { id: 'siliconflow', label: '硅基流动' }, + { id: 'stepfun', label: '阶跃星辰' }, + { id: 'stepfun-realtime', label: '阶跃星辰实时' }, + { id: 'zhipu', label: '智谱 GLM' }, + { id: 'minimax', label: 'MiniMax' }, + { id: 'groq', label: 'Groq' }, + { id: 'whisper', label: 'OpenAI Whisper' }, + { id: 'openai-whisper', label: 'OpenAI Whisper' }, + { id: 'openrouter', label: 'OpenRouter' }, + { id: 'openrouterFree', label: 'OpenRouter 免费' }, + { id: 'orcarouter', label: 'OrcaRouter' }, + { id: 'zenmux', label: 'ZenMux' }, + { id: 'openai-compatible', label: 'OpenAI 兼容接口' }, + { id: 'xiaomi-mimo-asr', label: '小米 MiMo 语音' }, + { id: 'iflytek', label: '讯飞 RTASR' }, + { id: 'xfyun', label: '讯飞 RTASR' }, + { id: 'tencent-cloud', label: '腾讯云' }, + { id: 'tencent', label: '腾讯云' }, + { id: 'ark', label: '火山方舟' }, + { id: 'deepseek', label: 'DeepSeek' }, + { id: 'openai', label: 'OpenAI' }, + { id: 'gemini', label: 'Gemini' }, + { id: 'atlascloud', label: 'Atlas Cloud' }, + { id: 'mimo', label: '小米 MiMo' }, + { id: 'cometapi', label: 'CometAPI' }, + { id: 'requesty', label: 'Requesty' }, + { id: 'api-route', label: 'API Route' }, + { id: 'alibabaCoding', label: '阿里云百炼 Coding' }, + { id: 'codingPlanX', label: 'Coding Plan X' }, + { id: 'opencode', label: 'OpenCode' }, + { id: 'tencentTokenHub', label: '腾讯混元 TokenHub' }, + { id: 'lmstudio', label: 'LM Studio' }, + { id: 'dashscope-omni', label: '阿里百炼全模态' }, + { id: 'omni-volcengine', label: '火山全模态' }, + { id: 'omni-gemini', label: 'Gemini 全模态' }, + { id: 'custom', label: '自定义接口' }, + { id: 'custom_responses', label: '自定义 Responses' }, + { id: 'custom_messages', label: '自定义 Messages' }, + { id: 'apple-speech', label: 'Apple 语音' }, + { id: 'local-qwen3', label: '本地 Qwen3' }, + { id: 'micyou', label: 'MicYou' }, + { id: 'raw', label: '原文直出' } +]; + +const PIPELINES: LabelPair[] = [ + { id: 'traditional', label: '两段式(转写 + 润色)' }, + { id: 'multimodal', label: '全模态(一次调用)' }, + { id: 'deepseek', label: 'DeepSeek 大统一' } +]; + +const POLISH_MODES: LabelPair[] = [ + { id: 'raw', label: '原文' }, + { id: 'light', label: '轻度润色' }, + { id: 'structured', label: '清晰结构' }, + { id: 'formal', label: '正式表达' } +]; + +const CHANNELS: LabelPair[] = [ + { id: 'official', label: '正式版' }, + { id: 'beta', label: 'Beta' } +]; + +function lookup(list: LabelPair[], id: string): string { + for (let index = 0; index < list.length; index++) { + if (list[index].id === id) return list[index].label; + } + return ''; +} + +export class Labels { + static provider(id: string | undefined): string { + if (id === undefined || id.length === 0) return '未配置'; + const known: string = lookup(PROVIDERS, id); + return known.length > 0 ? known : id; + } + + static pipeline(id: string | undefined): string { + if (id === undefined || id.length === 0) return '默认'; + const known: string = lookup(PIPELINES, id); + return known.length > 0 ? known : id; + } + + static polishMode(id: string | undefined): string { + if (id === undefined || id.length === 0) return '润色'; + const known: string = lookup(POLISH_MODES, id); + return known.length > 0 ? known : id; + } + + static channel(id: string | undefined): string { + if (id === undefined || id.length === 0) return '正式版'; + const known: string = lookup(CHANNELS, id); + return known.length > 0 ? known : id; + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/Store.ets b/openless-all/harmony/entry/src/main/ets/common/Store.ets new file mode 100644 index 000000000..c80ec94ec --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Store.ets @@ -0,0 +1,9 @@ +/** Centralized application-state assignment. + * AppStorage.setOrCreate updates existing properties and creates missing ones. + * https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-state-management + */ +export class Store { + static put(key: string, value: T): void { + AppStorage.setOrCreate(key, value); + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/SystemSpeech.ets b/openless-all/harmony/entry/src/main/ets/common/SystemSpeech.ets new file mode 100644 index 000000000..7b481d5f2 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/SystemSpeech.ets @@ -0,0 +1,237 @@ +import { abilityAccessCtrl, common } from '@kit.AbilityKit'; +import { speechRecognizer } from '@kit.CoreSpeechKit'; +import { Store } from './Store'; + +export interface SystemSpeechSnapshot { + supported: boolean; + phase: string; + text: string; + error: string; +} + +/** Independent, offline-only trial, NOT the core dictation provider. + * Official contract (online: 1 means offline; recognitionMode: 0 captures audio): + * https://developer.huawei.com/consumer/cn/doc/doccenter-references/api/hms-ai-speechrecognizer + * No transcript is logged, uploaded, polished, inserted or persisted here. + */ +export class SystemSpeech { + private engine: speechRecognizer.SpeechRecognitionEngine | undefined = undefined; + private generation: number = 0; + private sessionId: string = ''; + private deadline: number = -1; + private disposed: boolean = false; + private ownsMicrophone: boolean = false; + private phase: string = 'idle'; + private text: string = ''; + private error: string = ''; + private supported: boolean = SystemSpeech.available(); + private onChange: (snapshot: SystemSpeechSnapshot) => void; + + constructor(onChange: (snapshot: SystemSpeechSnapshot) => void) { + this.onChange = onChange; + } + + static available(): boolean { + try { + return canIUse('SystemCapability.AI.SpeechRecognizer'); + } catch (error) { + return false; + } + } + + snapshot(): SystemSpeechSnapshot { + return { supported: this.supported, phase: this.phase, text: this.text, error: this.error }; + } + + private publish(): void { + if (!this.disposed) this.onChange(this.snapshot()); + } + + private current(generation: number, sessionId: string): boolean { + return !this.disposed && generation === this.generation && sessionId === this.sessionId; + } + + private mainBusy(): boolean { + const phase: string = AppStorage.get('dictPhase') ?? 'idle'; + return AppStorage.get('microphoneMonitorBusy') === true || + phase === 'starting' || phase === 'recording' || phase === 'processing' || phase === 'cancelling'; + } + + private foreground(): boolean { + return AppStorage.get('appForeground') !== false; + } + + private clearDeadline(): void { + if (this.deadline >= 0) { + clearTimeout(this.deadline); + this.deadline = -1; + } + } + + private arm(generation: number, sessionId: string, delay: number, message: string): void { + this.clearDeadline(); + this.deadline = setTimeout(() => { + if (this.current(generation, sessionId)) this.fail(message); + }, delay); + } + + /** Invalidate callbacks before cancel/shutdown, which may synchronously call listeners. */ + private release(cancel: boolean): void { + this.generation++; + const sessionId: string = this.sessionId; + this.sessionId = ''; + this.clearDeadline(); + const engine: speechRecognizer.SpeechRecognitionEngine | undefined = this.engine; + this.engine = undefined; + if (engine !== undefined) { + if (cancel && sessionId.length > 0) { + try { engine.cancel(sessionId); } catch (error) { /* shutdown still runs */ } + } + try { engine.shutdown(); } catch (error) { /* no sensitive diagnostic logging */ } + } + if (this.ownsMicrophone) { + this.ownsMicrophone = false; + Store.put('systemSpeechBusy', false); + } + } + + private fail(message: string): void { + this.release(true); + this.phase = 'error'; + this.text = ''; + this.error = message; + this.publish(); + } + + private errorText(code: number): string { + if (code === 1002200012 || code === 201) return '未获得麦克风权限,请在系统设置允许后重试。'; + if (code === 1002200006) return '系统语音服务正忙,请结束其他录音后重试。'; + if (code === 1002200001) return '无法准备离线中文识别,设备可能缺少系统语音资源。'; + return '系统离线识别暂时不可用,请稍后重试(' + code.toString() + ')。'; + } + + private listener(generation: number, sessionId: string): speechRecognizer.RecognitionListener { + const listener: speechRecognizer.RecognitionListener = { + onStart: (id: string, message: string): void => { + if (!this.current(generation, id) || id !== sessionId || this.phase !== 'starting') return; + this.phase = 'listening'; + this.arm(generation, id, 25000, '本次试用已超时,麦克风已释放,请重新开始。'); + this.publish(); + }, + onEvent: (id: string, code: number, message: string): void => { + if (!this.current(generation, id) || id !== sessionId) return; + if (code === 3 && this.phase === 'listening') { + this.phase = 'finishing'; + this.arm(generation, id, 10000, '等待离线识别结果超时,请重新开始。'); + this.publish(); + } + }, + onResult: (id: string, result: speechRecognizer.SpeechRecognitionResult): void => { + if (!this.current(generation, id) || id !== sessionId) return; + this.text = result.result; + this.publish(); + }, + onComplete: (id: string, message: string): void => { + if (!this.current(generation, id) || id !== sessionId) return; + this.release(false); + this.phase = 'done'; + this.error = this.text.length > 0 ? '' : '没有识别到文字,可重新试用。'; + this.publish(); + }, + onError: (id: string, code: number, message: string): void => { + if (this.current(generation, id) && id === sessionId) this.fail(this.errorText(code)); + } + }; + return listener; + } + + /** The only permission entry point: invoked explicitly by the trial start button. */ + async start(context: common.UIAbilityContext): Promise { + if (this.disposed || this.ownsMicrophone) return; + if (!this.supported) { + this.fail('这台设备未提供系统离线中文识别能力,不会切换到云端。'); + return; + } + if (!this.foreground() || this.mainBusy() || AppStorage.get('systemSpeechBusy') === true) { + this.fail('请先结束其他听写,并在前台打开本页后重试。'); + return; + } + const generation: number = ++this.generation; + const sessionId: string = 'offline_' + Date.now().toString() + '_' + generation.toString(); + this.sessionId = sessionId; + this.phase = 'starting'; + this.text = ''; + this.error = ''; + this.ownsMicrophone = true; + Store.put('systemSpeechBusy', true); + this.arm(generation, sessionId, 30000, '准备语音超时,请确认麦克风权限后重试。'); + this.publish(); + try { + const manager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); + const token: number = context.applicationInfo.accessTokenId; + let granted: boolean = manager.checkAccessTokenSync(token, 'ohos.permission.MICROPHONE') === + abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED; + if (!granted) { + const response = await manager.requestPermissionsFromUser(context, ['ohos.permission.MICROPHONE']); + granted = response.authResults.length > 0 && + response.authResults[0] === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED; + } + if (!this.current(generation, sessionId)) return; + if (!granted) { + this.fail('未获得麦克风权限,请在系统设置允许后重试。'); + return; + } + if (!this.foreground() || this.mainBusy()) { + this.fail('其他听写已启动或页面不在前台,本次试用已取消。'); + return; + } + this.arm(generation, sessionId, 10000, '准备离线识别超时,设备可能缺少系统语音资源。'); + const params: speechRecognizer.CreateEngineParams = { + language: 'zh-CN', online: 1, extraParams: { locate: 'CN', recognizerMode: 'short' } + }; + const engine: speechRecognizer.SpeechRecognitionEngine = await speechRecognizer.createEngine(params); + if (!this.current(generation, sessionId)) { + try { engine.shutdown(); } catch (error) { /* late creation must not acquire audio */ } + return; + } + this.engine = engine; + if (!this.foreground() || this.mainBusy()) { + this.fail('其他听写已启动或页面不在前台,本次试用已取消。'); + return; + } + engine.setListener(this.listener(generation, sessionId)); + const startParams: speechRecognizer.StartParams = { + sessionId: sessionId, + audioInfo: { audioType: 'pcm', sampleRate: 16000, soundChannel: 1, sampleBit: 16 }, + extraParams: { recognitionMode: 0, maxAudioDuration: 20000 } + }; + engine.startListening(startParams); + } catch (error) { + if (this.current(generation, sessionId)) { + this.fail('无法启动系统离线识别,请检查权限及设备语音资源后重试。'); + } + } + } + + finish(): void { + if (this.phase !== 'listening' || this.engine === undefined) return; + this.phase = 'finishing'; + this.arm(this.generation, this.sessionId, 10000, '等待离线识别结果超时,麦克风已释放。'); + this.publish(); + try { this.engine.finish(this.sessionId); } catch (error) { this.fail('结束识别失败,请重新试用。'); } + } + + cancel(): void { + this.release(true); + this.phase = 'idle'; + this.text = ''; + this.error = ''; + this.publish(); + } + + dispose(): void { + this.disposed = true; + this.release(true); + this.onChange = (snapshot: SystemSpeechSnapshot): void => {}; + } +} diff --git a/openless-all/harmony/entry/src/main/ets/common/Theme.ets b/openless-all/harmony/entry/src/main/ets/common/Theme.ets new file mode 100644 index 000000000..cf61333ee --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/common/Theme.ets @@ -0,0 +1,315 @@ +/** + * v2 design tokens for the native HarmonyOS UI. + * + * Rules: + * - Colors are semantic roles resolved through `app.color.c_*` resources, so + * light and dark stay in step and pages never hard-code a hex value. + * - Spacing is an 8vp grid with a 4vp step for tight pairs. + * - Type is a closed scale: pages may only use these sizes. + * - Elevation is nearly flat: cards use a hairline, only floating layers get a + * shadow. + */ + +/** Semantic color roles. Every getter resolves through the resource manager. */ +export class Palette { + /** Canvas behind the content (system gray). */ + static bg(): Resource { + return $r('app.color.c_bg'); + } + + /** Elevated canvas: sheets, dialogs, the window background on wide screens. */ + static bgElevated(): Resource { + return $r('app.color.c_bg_elev'); + } + + /** Card / list surface. */ + static card(): Resource { + return $r('app.color.c_card'); + } + + /** Recessed surface inside a card: sub-panels, inputs, chips. */ + static cardAlt(): Resource { + return $r('app.color.c_card_alt'); + } + + static cardPressed(): Resource { + return $r('app.color.c_card_pressed'); + } + + /** Hairline border and separators. */ + static line(): Resource { + return $r('app.color.c_line'); + } + + /** A border that must stay visible on dark (selected cards, focused inputs). */ + static lineStrong(): Resource { + return $r('app.color.c_line_strong'); + } + + /** Primary text. */ + static text1(): Resource { + return $r('app.color.c_text_1'); + } + + /** Secondary text: values, descriptions. */ + static text2(): Resource { + return $r('app.color.c_text_2'); + } + + /** Tertiary text: captions, hints, placeholders. */ + static text3(): Resource { + return $r('app.color.c_text_3'); + } + + static onAccent(): Resource { + return $r('app.color.c_text_on_accent'); + } + + static icon1(): Resource { + return $r('app.color.c_icon_1'); + } + + static icon2(): Resource { + return $r('app.color.c_icon_2'); + } + + static accent(): Resource { + return $r('app.color.c_accent'); + } + + static accentSoft(): Resource { + return $r('app.color.c_accent_soft'); + } + + static accentPressed(): Resource { + return $r('app.color.c_accent_pressed'); + } + + static success(): Resource { + return $r('app.color.c_success'); + } + + static successSoft(): Resource { + return $r('app.color.c_success_soft'); + } + + static warning(): Resource { + return $r('app.color.c_warning'); + } + + static warningSoft(): Resource { + return $r('app.color.c_warning_soft'); + } + + static danger(): Resource { + return $r('app.color.c_danger'); + } + + static dangerSoft(): Resource { + return $r('app.color.c_danger_soft'); + } + + /** Segmented-control track and its selected thumb. */ + static control(): Resource { + return $r('app.color.c_control'); + } + + static controlSelected(): Resource { + return $r('app.color.c_control_selected'); + } + + static scrim(): Resource { + return $r('app.color.c_scrim'); + } + + /** Immersive capsule glass: top/bottom gradient stops plus the highlight edge. */ + static glassHi(): Resource { + return $r('app.color.c_glass_hi'); + } + + static glassLo(): Resource { + return $r('app.color.c_glass_lo'); + } + + /** Soft tint layered on the dock's system material. */ + static dockTint(): Resource { + return $r('app.color.c_dock_tint'); + } + + static glassEdge(): Resource { + return $r('app.color.c_glass_edge'); + } + + /** Activity heat map ramp, 0 = no dictation that day. */ + static heat(level: number): Resource { + if (level <= 0) return $r('app.color.c_heat_0'); + if (level === 1) return $r('app.color.c_heat_1'); + if (level === 2) return $r('app.color.c_heat_2'); + if (level === 3) return $r('app.color.c_heat_3'); + return $r('app.color.c_heat_4'); + } +} + +/** Spacing scale (vp). */ +export class Space { + static readonly xxs: number = 4; + static readonly xs: number = 8; + static readonly sm: number = 12; + static readonly md: number = 16; + static readonly lg: number = 24; + static readonly xl: number = 32; + static readonly xxl: number = 40; +} + +/** Corner radii (vp). */ +export class Radius { + /** One product radius (React `--ol-radius: 16`) plus a tighter control step. */ + static readonly control: number = 12; + static readonly icon: number = 10; + static readonly card: number = 16; + static readonly sheet: number = 32; + static readonly pill: number = 999; +} + +/** + * Type scale copied 1:1 from the iOS AppDesign/SwiftUI text styles so the two + * apps read the same: body 17, subheadline 15, footnote 13, caption 12, + * caption2 11, title3 20, title2 22, largeTitle 34. + */ +export class Type { + /** Navigation bar title (iOS inline title, 17 semibold). */ + static readonly navTitle: number = 17; + static readonly pageTitle: number = 34; + static readonly section: number = 20; + static readonly cardTitle: number = 17; + static readonly body: number = 17; + /** subheadline: list values, hints, buttons. */ + static readonly label: number = 15; + /** footnote: captions, section headers, secondary lines. */ + static readonly caption: number = 13; + /** caption2: tile detail lines. */ + static readonly caption2: number = 11; + static readonly metric: number = 40; +} + +/** Line heights paired with `Type`. */ +export class Leading { + static readonly navTitle: number = 22; + static readonly pageTitle: number = 41; + static readonly section: number = 25; + static readonly cardTitle: number = 22; + static readonly body: number = 22; + static readonly label: number = 20; + static readonly caption: number = 18; + static readonly caption2: number = 14; + static readonly metric: number = 46; +} + +/** Common control sizes (vp). */ +export class Size { + static readonly touch: number = 44; + static readonly row: number = 56; + static readonly rowDouble: number = 72; + static readonly icon: number = 20; + static readonly iconSmall: number = 16; + static readonly iconLarge: number = 28; + static readonly tile: number = 40; +} + +/** Motion durations (ms). Curves stay on `Curve.EaseOut` / `Curve.Friction`. */ +/** + * Motion tokens copied from iOS `ProductMotion` / `PressFeedbackStyle`: + * quick 160ms easeOut, standard spring(0.34, 0.88), reduced 120ms. + * ArkUI has no spring(response:damping:) constructor, so `standard` maps to a + * friction curve with the same visible settling time; reduce-motion callers use + * `reduced`. + * https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-animatorproperty + */ +export class Motion { + /** iOS quick = easeOut 0.16. */ + static readonly quick: number = 160; + /** Button press feedback (iOS 0.14s, scale 0.98 / opacity 0.8). */ + static readonly press: number = 140; + /** iOS standard spring settles in roughly 340ms. */ + static readonly base: number = 340; + static readonly slow: number = 240; + /** iOS `reduced` = easeOut 0.12. */ + static readonly reduced: number = 120; + /** iOS Dock expand: UIViewPropertyAnimator(duration: 0.28, dampingRatio: 1). */ + static readonly dock: number = 280; + /** iOS Dock handoff: 0.12 easeOut. */ + static readonly dockHandoff: number = 120; +} + +/** Breakpoint-dependent layout metrics. */ +export class Layout { + static readonly SM: string = 'sm'; + static readonly MD: string = 'md'; + static readonly LG: string = 'lg'; + static readonly XL: string = 'xl'; + + /** + * Width of the centred column used while a device presents the phone-style UI + * (portrait tablet / folded phone). A phone keeps the full window; a tablet gets + * a wider but still bounded column so cards spread out instead of hugging a + * 393pt phone strip (Huawei Weather uses the same idea). + */ + static columnMax(bp: string): number { + if (bp === Layout.XL) return 880; + if (bp === Layout.LG) return 720; + if (bp === Layout.MD) return 640; + return 10000; + } + + /** iOS uses a 20pt page margin everywhere; wide windows get a little more. */ + static gutter(bp: string): number { + if (bp === Layout.XL) return 32; + if (bp === Layout.LG) return 24; + return 20; + } + + /** Max width of a single content column. */ + static contentMax(bp: string): number { + if (bp === Layout.SM) return 10000; + if (bp === Layout.MD) return 640; + if (bp === Layout.LG) return 760; + return 880; + } + + /** Floating dock + outer spacing; apply only to scrolling content tails. */ + static dockClearance(): number { + return 62 + Space.xs * 2 + Space.sm; + } + + /** Reading columns and multi-pane workspaces have separate width budgets. */ + static wideMax(bp: string): number { + return bp === Layout.XL ? 1320 : 1120; + } + + static isWide(bp: string): boolean { + return bp === Layout.LG || bp === Layout.XL; + } + + static bodyMax(bp: string, route: string): number { + // Product destinations fill a tablet's window. Only long-form setup and + // credential forms keep a reading-width limit, not the page background. + if (route === 'credentials' || route === 'selection' || route === 'qa') { + return Layout.contentMax(bp); + } + return 10000; + } + + static columnGap(bp: string): number { + return bp === Layout.SM ? 12 : 16; + } +} + +/** Level 2 elevation: floating layers only (sheets, dialogs, floating keys). */ +export function floatShadow(): ShadowOptions { + return { + radius: 24, + color: '#1F000000', + offsetX: 0, + offsetY: 8 + }; +} diff --git a/openless-all/harmony/entry/src/main/ets/components/AdaptiveLayout.ets b/openless-all/harmony/entry/src/main/ets/components/AdaptiveLayout.ets new file mode 100644 index 000000000..11b3a4bd8 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/AdaptiveLayout.ets @@ -0,0 +1,41 @@ +import { Layout, Space } from '../common/Theme'; + +/** + * Reflow the same slots rather than switching two page trees on rotation. + * Builders use arrow wrappers to preserve their owning page's `this`. + * https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-builderparam + * Rotation uses the platform's synchronized layout animation, not a second spring. + */ +@Component +export struct AdaptiveColumns { + @Prop bp: string = Layout.SM; + @Prop secondaryWidth: number = 320; + @Prop singleColumn: boolean = false; + @BuilderParam primary: () => void; + @BuilderParam secondary: () => void; + + private wide(): boolean { + return !this.singleColumn && Layout.isWide(this.bp); + } + + build() { + Flex({ direction: this.wide() ? FlexDirection.Row : FlexDirection.Column, + alignItems: ItemAlign.Start }) { + Column({ space: Space.lg }) { + this.primary() + } + .width(this.wide() ? undefined : '100%') + .layoutWeight(this.wide() ? 1 : 0) + .alignItems(HorizontalAlign.Start) + + Column({ space: Space.lg }) { + this.secondary() + } + .width(this.wide() ? this.secondaryWidth : '100%') + .margin({ left: this.wide() ? Layout.columnGap(this.bp) : 0, + top: this.wide() ? 0 : Space.lg }) + .alignItems(HorizontalAlign.Start) + } + .width('100%') + } +} diff --git a/openless-all/harmony/entry/src/main/ets/components/AppShell.ets b/openless-all/harmony/entry/src/main/ets/components/AppShell.ets new file mode 100644 index 000000000..46e589560 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/AppShell.ets @@ -0,0 +1,155 @@ +import { KeyCode } from '@kit.InputKit'; +import { Layout, Palette, Space } from '../common/Theme'; +import { PageBackBar } from './Kit'; +import { Nav } from './Nav'; +import { ProductDock } from './ProductNavigation'; +import { CredentialsPage } from '../pages/CredentialsPage'; +import { HistoryPage } from '../pages/HistoryPage'; +import { CorrectionsPage, StylePage, VocabPage } from '../pages/LibraryPages'; +import { OverviewPage } from '../pages/OverviewPage'; +import { SelectionPage } from '../pages/SelectionPage'; +import { SettingsPage } from '../pages/SettingsPage'; +import { QaPage, TranslationPage } from '../pages/ToolPages'; + +import { LocalAsrPage } from '../pages/ModelsPage'; + +/** + * Routing and window chrome only. ProductNavigation owns the persistent dock; + * pages own data; AdaptiveLayout owns reusable content reflow. Breakpoints refer + * to windows, not device names (Huawei multi-device breakpoint practice). + */ +@Component +export struct AppShell { + @StorageLink('bp') bp: string = 'sm'; + @StorageLink('route') route: string = 'overview'; + /** Portrait (phone-like) presentation: bottom dock, single column. */ + @StorageLink('phoneLayout') phoneLayout: boolean = true; + @StorageLink('overlayOpen') overlayOpen: boolean = false; + @StorageLink('keyboardVisible') keyboardVisible: boolean = false; + + private bodyMax(): number { + // The credential page owns a full-window scrim; only its form is bounded. + if (this.route === Nav.CREDENTIALS) return 10000; + return Layout.bodyMax(this.bp, this.route); + } + + build() { + // The system material is supported in an actual bottom TabBar, not a plain + // Stack content layer. One persistent host owns geometry; Nav owns the + // five destinations and their detail state without duplicating page trees. + // https://developer.huawei.com/consumer/cn/doc/doccenter-capabilities/arkts-immersive-light-sense-faq + Tabs({ barPosition: BarPosition.End }) { + TabContent() { + Column() { + if (Nav.isSecondary(this.route)) { + Row() { + PageBackBar({ + label: Nav.label(Nav.backTarget(this.route)), + onTap: () => Nav.back() + }) + } + .width('100%') + .constraintSize({ maxWidth: this.bodyMax() }) + .enabled(!this.overlayOpen) + .padding({ left: Layout.gutter(this.bp), right: Layout.gutter(this.bp) }) + } + Row() { + Column() { + this.content() + } + .width('100%') + .height('100%') + .constraintSize({ maxWidth: this.bodyMax() }) + } + .width('100%') + .layoutWeight(1) + .justifyContent(FlexAlign.Center) + } + .width('100%') + .height('100%') + // Keep the full viewport behind the dock. Individual scroll tails reserve + // its height; shrinking this Column creates an opaque empty bottom strip. + .id('shell-content-viewport') + + } + .tabBar(this.floatingDock) + } + .barOverlap(true) + .barHeight(this.overlayOpen || this.keyboardVisible ? 0 : 78) + .barWidth('100%') + .barMode(BarMode.Fixed) + .barBackgroundColor(Color.Transparent) + .barBackgroundBlurStyle(BlurStyle.NONE) + .scrollable(false) + .animationDuration(0) + .width('100%') + .height('100%') + .backgroundColor(Palette.bg()) + .focusable(true) + .onKeyEvent((event: KeyEvent) => this.handleKey(event)) + } + + @Builder + floatingDock() { + Row() { + ProductDock({ route: this.route }) + } + .width('100%') + .justifyContent(FlexAlign.Center) + .id('shell-floating-dock') + .visibility(this.overlayOpen || this.keyboardVisible ? Visibility.Hidden : Visibility.Visible) + .enabled(!this.overlayOpen && !this.keyboardVisible) + } + + /** Native focus bubbling: consume only handled Ctrl/Meta+1..5 shortcuts. */ + private handleKey(event: KeyEvent): void { + if (event.type !== KeyType.Down) return; + // getModifierKeyState accepts Ctrl/Alt/Shift only; Meta is a separate field. + // https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-universal-events-key + let withModifier: boolean = event.metaKey === 1; + if (!withModifier && event.getModifierKeyState !== undefined) { + try { + withModifier = event.getModifierKeyState(['Ctrl']); + } catch (error) { + return; + } + } + if (!withModifier) return; + const slots: number[] = [KeyCode.KEYCODE_1, KeyCode.KEYCODE_2, KeyCode.KEYCODE_3, + KeyCode.KEYCODE_4, KeyCode.KEYCODE_5]; + for (let index = 0; index < slots.length; index++) { + if (event.keyCode === slots[index]) { + Nav.openPrimary(Nav.PRIMARY[index]); + event.stopPropagation(); + return; + } + } + } + + @Builder + content() { + if (this.route === Nav.HISTORY) { + HistoryPage() + } else if (this.route === Nav.STYLE) { + StylePage() + } else if (this.route === Nav.SETTINGS) { + SettingsPage() + } else if (this.route === Nav.SELECTION) { + SelectionPage() + } else if (this.route === Nav.TRANSLATION) { + TranslationPage() + } else if (this.route === Nav.VOCAB) { + VocabPage() + } else if (this.route === Nav.CORRECTIONS) { + CorrectionsPage() + } else if (this.route === Nav.QA) { + QaPage() + } else if (this.route === Nav.CREDENTIALS) { + CredentialsPage() + } else if (this.route === Nav.LOCALASR) { + LocalAsrPage() + } else { + OverviewPage() + } + } +} diff --git a/openless-all/harmony/entry/src/main/ets/components/Icons.ets b/openless-all/harmony/entry/src/main/ets/components/Icons.ets new file mode 100644 index 000000000..f8aa4e4b7 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/Icons.ets @@ -0,0 +1,55 @@ +/** + * Iconography. + * + * HarmonyOS ships a system symbol library (`sys.symbol.*`) that follows the + * platform stroke weight and optical size. Most controls use those symbols; + * the product dock uses four original, monochrome SVGs where the system glyph + * changes the meaning or silhouette of the iOS reference. + */ +/** Original product navigation silhouettes, not extracted SF Symbols assets. + * Huawei Image.fillColor supports monochrome SVG resources. + * https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V13/ui-dark-light-color-adaptation-V13 + */ +export function hasDockImage(id: string): boolean { + return id === 'overview' || id === 'vocab' || id === 'settings' || id === 'style'; +} + +export function dockImageOf(id: string): Resource { + if (id === 'overview') return $r('app.media.dock_overview'); + if (id === 'vocab') return $r('app.media.dock_dictionary'); + if (id === 'settings') return $r('app.media.dock_settings'); + return $r('app.media.dock_style'); +} + +export function symbolOf(id: string): Resource { + if (id === 'overview') return $r('sys.symbol.house'); + if (id === 'history') return $r('sys.symbol.clock'); + if (id === 'vocab') return $r('sys.symbol.character_book'); + if (id === 'style') return $r('sys.symbol.wand_and_stars'); + if (id === 'marketplace') return $r('sys.symbol.square_grid_2x2'); + if (id === 'translation') return $r('sys.symbol.translate'); + if (id === 'qa') return $r('sys.symbol.message'); + if (id === 'quicknote') return $r('sys.symbol.doc_plaintext'); + if (id === 'corrections') return $r('sys.symbol.wand_and_stars'); + if (id === 'localasr') return $r('sys.symbol.waveform'); + if (id === 'settings') return $r('sys.symbol.slider_horizontal_2'); + if (id === 'keyboard') return $r('sys.symbol.keyboard_badge_gearshape'); + if (id === 'mic') return $r('sys.symbol.mic'); + if (id === 'search') return $r('sys.symbol.magnifyingglass'); + if (id === 'close') return $r('sys.symbol.xmark'); + if (id === 'check') return $r('sys.symbol.checkmark'); + if (id === 'chevron') return $r('sys.symbol.chevron_right'); + if (id === 'chevron_left') return $r('sys.symbol.chevron_left'); + if (id === 'chevron_down') return $r('sys.symbol.chevron_down'); + if (id === 'list') return $r('sys.symbol.list_bullet'); + if (id === 'trash') return $r('sys.symbol.trash'); + if (id === 'add') return $r('sys.symbol.plus'); + if (id === 'refresh') return $r('sys.symbol.arrow_clockwise'); + if (id === 'copy') return $r('sys.symbol.doc_plaintext'); + if (id === 'play') return $r('sys.symbol.play_fill'); + if (id === 'more') return $r('sys.symbol.ellipsis_message'); + if (id === 'stop') return $r('sys.symbol.square_fill'); + if (id === 'sparkles') return $r('sys.symbol.star'); + if (id === 'person') return $r('sys.symbol.person'); + return $r('sys.symbol.circle'); +} diff --git a/openless-all/harmony/entry/src/main/ets/components/Kit.ets b/openless-all/harmony/entry/src/main/ets/components/Kit.ets new file mode 100644 index 000000000..1ecb8f71c --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/Kit.ets @@ -0,0 +1,1124 @@ +import { KeyCode } from '@kit.InputKit'; +import { promptAction } from '@kit.ArkUI'; +import { Layout, Leading, Palette, Radius, Size, Space, Type } from '../common/Theme'; +import { symbolOf } from './Icons'; + +/** + * v2 component kit. + * + * Every visual primitive of the main app lives here: pages compose these and must + * not re-implement buttons, rows, chips or cards inline. Keeping the vocabulary + * small is what makes the pages look like one product. + */ + +/** + * Activate a custom clickable surface from a physical keyboard. Tablet and PC + * users navigate by focus, so every row/card answers Enter/Space. + * https://developer.huawei.com/consumer/cn/doc/best-practices-V14/bpta-multi-interaction-V14 + */ +export function activateOnKey(event: KeyEvent, action: () => void): void { + if (event.type !== KeyType.Down) return; + if (event.keyCode === KeyCode.KEYCODE_ENTER || event.keyCode === KeyCode.KEYCODE_NUMPAD_ENTER || + event.keyCode === KeyCode.KEYCODE_SPACE) { + event.stopPropagation(); + action(); + } +} + +/** A nested native Button must not also activate an enclosing clickable card. */ +export function stopButtonKeyBubbling(event: KeyEvent): void { + if (event.keyCode === KeyCode.KEYCODE_ENTER || event.keyCode === KeyCode.KEYCODE_NUMPAD_ENTER || + event.keyCode === KeyCode.KEYCODE_SPACE) event.stopPropagation(); +} + +/** Section heading inside a card. */ +@Component +export struct SectionTitle { + @Prop title: string; + @Prop hint: string = ''; + @Prop action: string = ''; + onAction: () => void = () => { + }; + + build() { + Row({ space: Space.sm }) { + Column({ space: Space.xxs }) { + Text(this.title) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.text1()) + if (this.hint.length > 0) { + Text(this.hint) + .fontSize(Type.caption) + .lineHeight(Leading.caption) + .fontColor(Palette.text2()) + } + } + .alignItems(HorizontalAlign.Start) + .layoutWeight(1) + + if (this.action.length > 0) { + TextButton({ label: this.action, onTap: () => this.onAction() }) + } + } + .width('100%') + } +} + +/** White card container. `tone`: card | alt | plain. */ +@Component +export struct Surface { + @Prop tone: string = 'card'; + @Prop inset: number = Space.md; + @BuilderParam content: () => void; + + private fill(): Resource { + if (this.tone === 'alt') return Palette.cardAlt(); + if (this.tone === 'plain') return Palette.bg(); + return Palette.card(); + } + + build() { + Column() { + this.content() + } + .width('100%') + .alignItems(HorizontalAlign.Start) + .padding(this.inset) + .backgroundColor(this.fill()) + .borderRadius(Radius.card) + .border({ width: 0.5, color: Palette.line() }) + } +} + +/** Grouped list container: rows inside keep their own padding and dividers. */ +@Component +export struct Group { + @Prop fill: string = 'card'; + /** iOS inset-grouped default is tighter than the 18vp product card. */ + @Prop radius: number = Radius.card; + @BuilderParam content: () => void; + + build() { + Column() { + this.content() + } + .width('100%') + .alignItems(HorizontalAlign.Start) + .backgroundColor(this.fill === 'alt' ? Palette.cardAlt() : Palette.card()) + .borderRadius(this.radius) + .border({ width: 0.5, color: Palette.line() }) + .clip(true) + } +} + +/** Standard list row: optional icon tile, title/subtitle, trailing value/chevron. */ +@Component +export struct RowItem { + @Prop symbol: string = ''; + @Prop accentSymbol: boolean = false; + @Prop title: string; + @Prop subtitle: string = ''; + @Prop value: string = ''; + @Prop showChevron: boolean = false; + @Prop showDivider: boolean = true; + @Prop muted: boolean = false; + /** iOS menu pickers render their current value in the accent colour. */ + @Prop valueAccent: boolean = false; + onTap: () => void = () => { + }; + + build() { + Column() { + Row({ space: Space.sm }) { + if (this.symbol.length > 0) { + Stack() { + SymbolGlyph(symbolOf(this.symbol)) + .fontSize(14) + .fontColor([Palette.accent()]) + } + .width(28) + .height(28) + .backgroundColor(Palette.accentSoft()) + .borderRadius(Radius.icon) + } + + Column({ space: Space.xxs }) { + Text(this.title) + .fontSize(Type.body) + .lineHeight(Leading.body) + .fontColor(Palette.text1()) + .maxLines(2) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + if (this.subtitle.length > 0) { + Text(this.subtitle) + .fontSize(Type.caption) + .lineHeight(Leading.caption) + .fontColor(Palette.text2()) + .maxLines(2) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + } + } + .alignItems(HorizontalAlign.Start) + .layoutWeight(1) + + if (this.value.length > 0) { + Text(this.value) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(this.valueAccent ? Palette.accent() : Palette.text2()) + .textAlign(TextAlign.End) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + .constraintSize({ maxWidth: 180 }) + } + if (this.showChevron) { + SymbolGlyph(symbolOf('chevron')) + .fontSize(Size.iconSmall) + .fontColor([Palette.text3()]) + } + } + .width('100%') + .constraintSize({ minHeight: this.subtitle.length > 0 ? 60 : Size.touch }) + .padding({ left: Space.md, right: Space.md, top: Space.xs, bottom: Space.xs }) + .opacity(this.muted ? 0.45 : 1) + .hoverEffect(HoverEffect.Highlight) + .focusable(true) + .onKeyEvent((event: KeyEvent) => activateOnKey(event, () => this.onTap())) + .onClick(() => this.onTap()) + + if (this.showDivider) { + Divider() + .color(Palette.line()) + .strokeWidth(0.5) + .margin({ left: this.symbol.length > 0 ? Space.md + 28 + Space.sm : Space.md }) + } + } + .width('100%') + } +} + +/** Filled action button. */ +@Component +export struct PrimaryButton { + @Prop label: string; + @Prop usable: boolean = true; + @Prop destructive: boolean = false; + onTap: () => void = () => { + }; + + build() { + Button(this.label, { type: ButtonType.Capsule }) + .constraintSize({ minHeight: Size.touch }) + .fontSize(Type.body) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.onAccent()) + .backgroundColor(this.destructive ? Palette.danger() : Palette.accent()) + .padding({ left: Space.lg, right: Space.lg }) + .opacity(this.usable ? 1 : 0.4) + .enabled(this.usable) + .stateStyles({ + normal: { .opacity(this.usable ? 1 : 0.4) }, + pressed: { .opacity(0.82) } + }) + .onKeyEvent((event: KeyEvent) => stopButtonKeyBubbling(event)) + .onClick((event: ClickEvent) => { + if (this.usable) this.onTap(); + }) + } +} + +/** Tonal action button (accent-soft background). */ +@Component +export struct TonalButton { + @Prop label: string; + @Prop symbol: string = ''; + @Prop usable: boolean = true; + onTap: () => void = () => { + }; + + build() { + Button({ type: ButtonType.Capsule }) { + Row({ space: Space.xs }) { + if (this.symbol.length > 0) { + SymbolGlyph(symbolOf(this.symbol)) + .fontSize(Size.iconSmall) + .fontColor([Palette.accent()]) + } + Text(this.label) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.accent()) + } + } + .constraintSize({ minHeight: Size.touch }) + .padding({ left: Space.md, right: Space.md }) + .backgroundColor(Palette.accentSoft()) + .borderRadius(Radius.pill) + .opacity(this.usable ? 1 : 0.4) + .enabled(this.usable) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(this.label) + .onKeyEvent((event: KeyEvent) => stopButtonKeyBubbling(event)) + .onClick((event: ClickEvent) => { + this.onTap(); + }) + } +} + +/** Borderless text action (headers, inline links). */ +@Component +export struct TextButton { + @Prop label: string; + @Prop symbol: string = ''; + @Prop tone: string = 'accent'; + @Prop usable: boolean = true; + onTap: () => void = () => { + }; + + private ink(): Resource { + if (this.tone === 'danger') return Palette.danger(); + if (this.tone === 'quiet') return Palette.text2(); + return Palette.accent(); + } + + build() { + Button({ type: ButtonType.Normal }) { + Row({ space: Space.xxs }) { + if (this.symbol.length > 0) { + SymbolGlyph(symbolOf(this.symbol)) + .fontSize(Size.iconSmall) + .fontColor([this.ink()]) + } + Text(this.label) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontWeight(FontWeight.Medium) + .fontColor(this.ink()) + } + } + .constraintSize({ minHeight: Size.touch }) + .padding({ left: Space.xs, right: Space.xs, top: Space.xxs, bottom: Space.xxs }) + .backgroundColor(Color.Transparent) + .borderRadius(Radius.control) + .opacity(this.usable ? 1 : 0.4) + .enabled(this.usable) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(this.label) + .onKeyEvent((event: KeyEvent) => stopButtonKeyBubbling(event)) + .onClick((event: ClickEvent) => { + this.onTap(); + }) + } +} + +/** Square icon-only action. */ +@Component +export struct IconButton { + @Prop symbol: string; + @Prop tint: string = 'neutral'; + onTap: () => void = () => { + }; + + build() { + Button({ type: ButtonType.Circle }) { + SymbolGlyph(symbolOf(this.symbol)) + .fontSize(Size.icon) + .fontColor([this.tint === 'accent' ? Palette.accent() : Palette.icon1()]) + } + .width(Size.touch) + .height(Size.touch) + .backgroundColor(Palette.cardAlt()) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(this.symbol) + .onKeyEvent((event: KeyEvent) => stopButtonKeyBubbling(event)) + .onClick((event: ClickEvent) => { + this.onTap(); + }) + } +} + +/** Single-select segmented control. Wraps on narrow screens instead of clipping. */ +@Component +export struct Segmented { + @Prop items: string[] = []; + @Prop selected: number = 0; + onSelect: (index: number) => void = (index: number) => { + }; + + build() { + Flex({ wrap: FlexWrap.Wrap, justifyContent: FlexAlign.Start }) { + ForEach(this.items, (item: string, index: number) => { + Button({ type: ButtonType.Normal }) { + Text(item) + .fontSize(Type.caption) + .lineHeight(Leading.caption) + .fontColor(index === this.selected ? Palette.text1() : Palette.text2()) + .fontWeight(index === this.selected ? FontWeight.Medium : FontWeight.Normal) + } + .constraintSize({ minHeight: 30 }) + .padding({ left: Space.sm, right: Space.sm }) + .margin(2) + .backgroundColor(index === this.selected ? Palette.controlSelected() : Color.Transparent) + .borderRadius(Radius.control) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(item) + .accessibilitySelected(index === this.selected) + .onClick(() => this.onSelect(index)) + }, (item: string) => item) + } + .width('100%') + .padding(Space.xxs) + .backgroundColor(Palette.control()) + .borderRadius(Radius.pill) + } +} + +/** Read-only status tag. */ +@Component +export struct Tag { + @Prop text: string; + @Prop tone: string = 'neutral'; + + private tint(): Resource { + if (this.tone === 'accent') return Palette.accentSoft(); + if (this.tone === 'success') return Palette.successSoft(); + if (this.tone === 'warning') return Palette.warningSoft(); + if (this.tone === 'danger') return Palette.dangerSoft(); + return Palette.cardAlt(); + } + + private ink(): Resource { + if (this.tone === 'accent') return Palette.accent(); + if (this.tone === 'success') return Palette.success(); + if (this.tone === 'warning') return Palette.warning(); + if (this.tone === 'danger') return Palette.danger(); + return Palette.text2(); + } + + build() { + Text(this.text) + .fontSize(Type.caption) + .lineHeight(Leading.caption) + .fontWeight(FontWeight.Medium) + .fontColor(this.ink()) + .padding({ left: Space.xs, right: Space.xs, top: 2, bottom: 2 }) + .backgroundColor(this.tint()) + .borderRadius(Radius.pill) + } +} + +/** Search / filter input. */ +@Component +export struct SearchField { + @Prop placeholder: string = '搜索'; + @Prop value: string = ''; + onInput: (value: string) => void = (value: string) => { + }; + + build() { + Row({ space: Space.xs }) { + SymbolGlyph(symbolOf('search')) + .fontSize(Size.iconSmall) + .fontColor([Palette.text3()]) + TextInput({ placeholder: this.placeholder, text: this.value }) + .fontSize(Type.body) + .fontColor(Palette.text1()) + .placeholderColor(Palette.text3()) + .backgroundColor(Color.Transparent) + .padding(0) + .layoutWeight(1) + .onChange((text: string) => this.onInput(text)) + if (this.value.length > 0) { + Button({ type: ButtonType.Circle }) { + SymbolGlyph(symbolOf('close')) + .fontSize(Size.iconSmall) + .fontColor([Palette.text3()]) + } + .width(32) + .height(32) + .backgroundColor(Color.Transparent) + .accessibilityText('清除搜索内容') + .onClick(() => this.onInput('')) + } + } + .width('100%') + .constraintSize({ minHeight: 40 }) + .padding({ left: Space.sm, right: Space.sm }) + .backgroundColor(Palette.cardAlt()) + .borderRadius(Radius.control) + } +} + +/** Empty state: symbol + one line + hint. */ +@Component +export struct EmptyHint { + @Prop symbol: string = 'sparkles'; + @Prop title: string; + @Prop hint: string = ''; + + build() { + Column({ space: Space.sm }) { + Stack() { + SymbolGlyph(symbolOf(this.symbol)) + .fontSize(24) + .fontColor([Palette.accent()]) + } + .width(56) + .height(56) + .backgroundColor(Palette.accentSoft()) + .borderRadius(14) + Text(this.title) + .fontSize(Type.cardTitle) + .lineHeight(Leading.cardTitle) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.text1()) + .textAlign(TextAlign.Center) + if (this.hint.length > 0) { + Text(this.hint) + .fontSize(Type.caption) + .lineHeight(Leading.caption) + .fontColor(Palette.text2()) + .textAlign(TextAlign.Center) + } + } + .width('100%') + .padding({ top: 48, bottom: 48, left: Space.lg, right: Space.lg }) + .justifyContent(FlexAlign.Center) + } +} + +/** Loading placeholder: a few neutral bars instead of a spinner over empty content. */ +@Component +export struct Skeleton { + @Prop rows: number = 3; + + build() { + Column({ space: Space.sm }) { + ForEach([0, 1, 2, 3, 4], (index: number) => { + if (index < this.rows) { + Row({ space: Space.sm }) { + Column() + .width(Size.tile) + .height(Size.tile) + .backgroundColor(Palette.cardAlt()) + .borderRadius(Radius.control) + Column({ space: Space.xs }) { + Column() + .width('60%') + .height(12) + .backgroundColor(Palette.cardAlt()) + .borderRadius(Radius.control) + Column() + .width('35%') + .height(10) + .backgroundColor(Palette.cardAlt()) + .borderRadius(Radius.control) + } + .alignItems(HorizontalAlign.Start) + .layoutWeight(1) + } + .width('100%') + .padding(Space.sm) + .backgroundColor(Palette.card()) + .borderRadius(Radius.card) + .border({ width: 0.5, color: Palette.line() }) + } + }, (index: number) => 'skeleton-' + index.toString()) + } + .width('100%') + } +} + +/** Inline error with a retry action. */ +@Component +export struct ErrorNote { + @Prop message: string; + onRetry: () => void = () => { + }; + + build() { + Row({ space: Space.sm }) { + SymbolGlyph(symbolOf('close')) + .fontSize(Size.iconSmall) + .fontColor([Palette.danger()]) + Text(this.message) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(Palette.text2()) + .layoutWeight(1) + TextButton({ label: '重试', tone: 'quiet', onTap: () => this.onRetry() }) + } + .width('100%') + .padding(Space.sm) + .backgroundColor(Palette.dangerSoft()) + .borderRadius(Radius.card) + } +} + +/** Soft note: onboarding, setup hints, warnings. */ +@Component +export struct Banner { + @Prop title: string; + @Prop text: string = ''; + @Prop tone: string = 'accent'; + @Prop action: string = ''; + @Prop actionSymbol: string = ''; + onAction: () => void = () => { + }; + + private surface(): Resource { + if (this.tone === 'warning') return Palette.warningSoft(); + if (this.tone === 'danger') return Palette.dangerSoft(); + return Palette.accentSoft(); + } + + private ink(): Resource { + if (this.tone === 'warning') return Palette.warning(); + if (this.tone === 'danger') return Palette.danger(); + return Palette.accent(); + } + + build() { + Column({ space: Space.xs }) { + Text(this.title) + .fontSize(Type.cardTitle) + .lineHeight(Leading.cardTitle) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.text1()) + if (this.text.length > 0) { + Text(this.text) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(Palette.text2()) + } + if (this.action.length > 0) { + Row() { + TonalButton({ label: this.action, symbol: this.actionSymbol, onTap: () => this.onAction() }) + } + .width('100%') + .padding({ top: Space.xxs }) + } + } + .width('100%') + .alignItems(HorizontalAlign.Start) + .padding(Space.md) + .backgroundColor(this.surface()) + .borderRadius(Radius.card) + } +} + +/** Big number with label. `size`: metric | section. */ +@Component +export struct MetricBlock { + @Prop value: string; + @Prop label: string; + @Prop unit: string = ''; + @Prop hero: boolean = false; + + build() { + Column({ space: Space.xxs }) { + Row({ space: Space.xxs }) { + Text(this.value) + .fontSize(this.hero ? Type.metric : Type.section) + .lineHeight(this.hero ? Leading.metric : Leading.section) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.text1()) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + if (this.unit.length > 0) { + Text(this.unit) + .fontSize(Type.caption) + .fontColor(Palette.text3()) + .margin({ bottom: 4 }) + } + } + .alignItems(VerticalAlign.Bottom) + + Text(this.label) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(Palette.text3()) + } + .alignItems(HorizontalAlign.Start) + .layoutWeight(1) + } +} + +/** Label + hint + switch. */ +@Component +export struct SettingSwitch { + @Prop label: string; + @Prop hint: string = ''; + @Prop checked: boolean = false; + @Prop showDivider: boolean = true; + onToggle: (value: boolean) => void = (value: boolean) => { + }; + + build() { + Column() { + Row({ space: Space.md }) { + Column({ space: Space.xxs }) { + Text(this.label) + .fontSize(Type.body) + .lineHeight(Leading.body) + .fontColor(Palette.text1()) + if (this.hint.length > 0) { + Text(this.hint) + .fontSize(Type.caption) + .lineHeight(Leading.caption) + .fontColor(Palette.text3()) + } + } + .alignItems(HorizontalAlign.Start) + .layoutWeight(1) + + Toggle({ type: ToggleType.Switch, isOn: this.checked }) + .selectedColor(Palette.accent()) + .onChange((value: boolean) => this.onToggle(value)) + } + .width('100%') + .padding({ left: Space.md, right: Space.md, top: Space.sm, bottom: Space.sm }) + + if (this.showDivider) { + Divider() + .color(Palette.line()) + .strokeWidth(0.5) + .margin({ left: Space.md }) + } + } + .width('100%') + } +} + +/** Back affordance for secondary pages. */ +@Component +export struct PageBackBar { + @Prop label: string; + onTap: () => void = () => { + }; + + build() { + Button({ type: ButtonType.Normal }) { + Row({ space: Space.xxs }) { + SymbolGlyph(symbolOf('chevron_left')) + .fontSize(Size.icon) + .fontColor([Palette.accent()]) + Text(this.label) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(Palette.accent()) + } + } + .constraintSize({ minHeight: Size.touch }) + .padding({ right: Space.sm }) + .backgroundColor(Color.Transparent) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText('返回' + this.label) + .onClick(() => this.onTap()) + } +} + +/** + * Page frame: large title + one header action + a body that either scrolls or + * fills. Every page starts with it so titles, gutters and bottom insets line up. + */ +@Component +export struct PageScaffold { + @Prop title: string; + @Prop subtitle: string = ''; + /** iOS largeTitle pages (Dictionary, Styles) keep a 34pt left title. */ + @Prop largeTitle: boolean = false; + @Prop actionLabel: string = ''; + @Prop actionSymbol: string = ''; + @Prop scrollable: boolean = true; + @Prop gap: number = Space.lg; + onAction: () => void = () => { + }; + @BuilderParam content: () => void; + @StorageLink('bp') bp: string = 'md'; + @StorageLink('shortWindow') shortWindow: boolean = false; + + build() { + Column() { + // iOS inline navigation bar: 44pt row, centred 17pt semibold title and a + // 44pt trailing toolbar button. An optional subtitle renders as a + // caption2 line rather than a second large title. + if (this.largeTitle) { + Row({ space: Space.sm }) { + Column({ space: Space.xxs }) { + Text(this.title) + .fontSize(Type.pageTitle) + .lineHeight(Leading.pageTitle) + .fontWeight(FontWeight.Bold) + .fontColor(Palette.text1()) + if (this.subtitle.length > 0) { + Text(this.subtitle) + .fontSize(Type.caption) + .lineHeight(Leading.caption) + .fontColor(Palette.text2()) + } + } + .alignItems(HorizontalAlign.Start) + .layoutWeight(1) + if (this.actionLabel.length > 0 || this.actionSymbol.length > 0) { + Button({ type: ButtonType.Circle }) { + SymbolGlyph(symbolOf(this.actionSymbol.length > 0 ? this.actionSymbol : 'add')) + .fontSize(Type.navTitle) + .fontColor([Palette.accent()]) + } + .width(Size.touch) + .height(Size.touch) + .backgroundColor(Palette.card()) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(this.actionLabel) + .onClick(() => this.onAction()) + } + } + .width('100%') + .padding({ top: Space.xs, bottom: Space.sm }) + } + Stack({ alignContent: Alignment.Center }) { + Column({ space: 2 }) { + Text(this.title) + .fontSize(Type.navTitle) + .lineHeight(Leading.navTitle) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.text1()) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + if (this.subtitle.length > 0 && !this.shortWindow) { + Text(this.subtitle) + .fontSize(Type.caption2) + .lineHeight(Leading.caption2) + .fontColor(Palette.text2()) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + } + } + .width('100%') + .alignItems(HorizontalAlign.Center) + + Row() { + Blank() + if (this.actionLabel.length > 0 || this.actionSymbol.length > 0) { + Button({ type: ButtonType.Circle }) { + if (this.actionSymbol.length > 0) { + SymbolGlyph(symbolOf(this.actionSymbol)) + .fontSize(Type.navTitle) + .fontColor([Palette.accent()]) + } else { + Text(this.actionLabel) + .fontSize(Type.caption) + .fontColor(Palette.accent()) + } + } + .width(Size.touch) + .height(Size.touch) + .backgroundColor(Palette.control()) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(this.actionLabel.length > 0 ? this.actionLabel : '操作') + .onClick(() => this.onAction()) + } + } + .width('100%') + } + .width('100%') + .visibility(this.largeTitle ? Visibility.None : Visibility.Visible) + .constraintSize({ minHeight: this.subtitle.length > 0 && !this.shortWindow ? 60 : Size.touch }) + + if (this.scrollable) { + Scroll() { + Column({ space: this.gap }) { + this.content() + } + .width('100%') + .padding({ top: Space.sm, bottom: Layout.dockClearance() }) + } + .layoutWeight(1) + .width('100%') + .align(Alignment.Top) + .scrollBar(BarState.Off) + .edgeEffect(EdgeEffect.Spring) + } else { + Column({ space: this.gap }) { + this.content() + } + .layoutWeight(1) + .width('100%') + .padding({ top: Space.xs, bottom: Space.xs }) + } + } + .width('100%') + .height('100%') + .padding({ left: Layout.gutter(this.bp), right: Layout.gutter(this.bp) }) + } +} + +/** + * iOS `PinnedSearchBar` (NativeSearchField.swift:71-79): a 48vp field pinned above + * the scrolling list, page gutter 20, 8vp vertical padding and a 0.5 hairline. + * Content scrolls underneath it, like the `.searchable` drawer in the video. + */ +@Component +export struct PinnedSearchBar { + @Prop placeholder: string = ''; + @Prop value: string = ''; + @Prop showHairline: boolean = true; + /** False when the parent page already applies the 20vp page gutter. */ + @Prop inset: boolean = true; + onInput: (text: string) => void = (text: string) => { + }; + @StorageLink('bp') bp: string = 'md'; + + build() { + Column() { + Row({ space: Space.xs }) { + SymbolGlyph(symbolOf('search')) + .fontSize(Size.iconSmall) + .fontColor([Palette.text3()]) + TextInput({ placeholder: this.placeholder, text: this.value }) + .fontSize(Type.body) + .fontColor(Palette.text1()) + .placeholderColor(Palette.text3()) + .backgroundColor(Color.Transparent) + .padding(0) + .layoutWeight(1) + .onChange((text: string) => this.onInput(text)) + if (this.value.length > 0) { + Button({ type: ButtonType.Circle }) { + SymbolGlyph(symbolOf('close')) + .fontSize(Size.iconSmall) + .fontColor([Palette.text3()]) + } + .width(32) + .height(32) + .backgroundColor(Color.Transparent) + .accessibilityText('清除搜索内容') + .onClick(() => this.onInput('')) + } + } + .width('100%') + .height(48) + .padding({ left: Space.sm, right: Space.sm }) + .backgroundColor(Palette.cardAlt()) + .borderRadius(Radius.control) + } + .width('100%') + .padding({ + left: this.inset ? Layout.gutter(this.bp) : 0, + right: this.inset ? Layout.gutter(this.bp) : 0, + top: Space.xs, + bottom: Space.xs + }) + .backgroundColor(Palette.bg()) + .border(this.showHairline + ? { width: { bottom: 0.5 }, color: Palette.line() } + : { width: 0, color: Color.Transparent }) + } +} + +/** + * iOS `sourceFilters` capsule track (VocabularyView.swift:133-153): a horizontally + * scrolling track (`secondarySystemBackground`) whose selected chip is a white + * capsule with a soft shadow. Chips carry an optional tinted glyph. + */ +export interface CapsuleChip { + label: string; + symbol: string; + tint: string; +} + +@Component +export struct CapsuleTrack { + @Prop chips: CapsuleChip[] = []; + @Prop selected: number = 0; + onSelect: (index: number) => void = (index: number) => { + }; + + private ink(tint: string): Resource { + if (tint === 'teal') return Palette.success(); + if (tint === 'accent') return Palette.accent(); + return Palette.text2(); + } + + build() { + Scroll() { + Row({ space: Space.xxs }) { + ForEach(this.chips, (chip: CapsuleChip, index: number) => { + Button({ type: ButtonType.Normal }) { + Row({ space: 6 }) { + if (chip.symbol.length > 0) { + SymbolGlyph(symbolOf(chip.symbol)) + .fontSize(Size.iconSmall) + .fontColor([this.ink(chip.tint)]) + } + Text(chip.label) + .fontSize(Type.body) + .lineHeight(Leading.body) + .fontWeight(index === this.selected ? FontWeight.Medium : FontWeight.Regular) + .fontColor(Palette.text1()) + .maxLines(1) + } + .padding({ left: Space.md, right: Space.md, top: Space.sm, bottom: Space.sm }) + .backgroundColor(index === this.selected ? Palette.card() : Color.Transparent) + .borderRadius(Radius.pill) + .shadow(index === this.selected + ? { radius: 4, color: Palette.line(), offsetY: 1 } + : undefined) + } + .padding(0) + .backgroundColor(Color.Transparent) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(chip.label) + .accessibilitySelected(index === this.selected) + .onClick(() => this.onSelect(index)) + }, (chip: CapsuleChip) => 'chip-' + chip.label) + } + .padding(5) + } + .scrollable(ScrollDirection.Horizontal) + .scrollBar(BarState.Off) + .align(Alignment.Start) + .width('100%') + .backgroundColor(Palette.control()) + .borderRadius(Radius.pill) + } +} + +/** iOS `.foregroundStyle(AppDesign.accent)` plain text action ("Filter by date"). */ +@Component +export struct AccentTextButton { + @Prop label: string; + @Prop usable: boolean = true; + onTap: () => void = () => { + }; + + build() { + Button({ type: ButtonType.Normal }) { + Text(this.label) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontWeight(FontWeight.Regular) + .fontColor(Palette.accent()) + } + .padding({ left: 0, right: 0, top: Space.xxs, bottom: Space.xxs }) + .backgroundColor(Color.Transparent) + .hoverEffect(HoverEffect.Highlight) + .enabled(this.usable) + .accessibilityText(this.label) + .onClick(() => this.onTap()) + } +} + +/** Single toast entry so every page reports success/failure the same way. */ +export function notify(message: string): void { + try { + promptAction.showToast({ message: message, duration: 2000 }); + } catch (error) { + console.warn('[OpenLess Toast] ' + message); + } +} + +/** Labelled text input; `multiline` switches to a text area. */ +@Component +export struct InputField { + @Prop label: string; + @Prop placeholder: string = ''; + @Prop value: string = ''; + @Prop hint: string = ''; + @Prop password: boolean = false; + @Prop multiline: boolean = false; + onInput: (value: string) => void = (value: string) => { + }; + + build() { + Column({ space: Space.xs }) { + Text(this.label) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.text1()) + + if (this.multiline) { + TextArea({ placeholder: this.placeholder, text: this.value }) + .fontSize(Type.body) + .fontColor(Palette.text1()) + .placeholderColor(Palette.text3()) + .backgroundColor(Palette.cardAlt()) + .borderRadius(Radius.control) + .constraintSize({ minHeight: 120 }) + .padding(Space.sm) + .width('100%') + .onChange((text: string) => this.onInput(text)) + } else { + TextInput({ placeholder: this.placeholder, text: this.value }) + .type(this.password ? InputType.Password : InputType.Normal) + .fontSize(Type.body) + .fontColor(Palette.text1()) + .placeholderColor(Palette.text3()) + .backgroundColor(Palette.cardAlt()) + .borderRadius(Radius.control) + .height(44) + .padding({ left: Space.sm, right: Space.sm }) + .width('100%') + .onChange((text: string) => this.onInput(text)) + } + + if (this.hint.length > 0) { + Text(this.hint) + .fontSize(Type.caption) + .lineHeight(Leading.caption) + .fontColor(Palette.text3()) + } + } + .width('100%') + .alignItems(HorizontalAlign.Start) + } +} + +/** Title block used inside `bindSheet` bodies. */ +@Component +export struct SheetTitle { + @Prop title: string; + @Prop hint: string = ''; + /** Trailing text action, e.g. the iOS sheet's 完成 / 保存. */ + @Prop actionLabel: string = ''; + onAction: () => void = () => { + }; + + build() { + Row({ space: Space.sm }) { + Column({ space: Space.xxs }) { + Text(this.title) + .fontSize(Type.section) + .lineHeight(Leading.section) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.text1()) + .width('100%') + if (this.hint.length > 0) { + Text(this.hint) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(Palette.text3()) + .width('100%') + } + } + .alignItems(HorizontalAlign.Start) + .layoutWeight(1) + + if (this.actionLabel.length > 0) { + TextButton({ + label: this.actionLabel, + usable: true, + onTap: () => this.onAction() + }) + } + } + .width('100%') + .alignItems(VerticalAlign.Top) + .padding({ bottom: Space.sm }) + } +} diff --git a/openless-all/harmony/entry/src/main/ets/components/Nav.ets b/openless-all/harmony/entry/src/main/ets/components/Nav.ets new file mode 100644 index 000000000..bb79e1e58 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/Nav.ets @@ -0,0 +1,156 @@ +import { Store } from '../common/Store'; + +export interface NavItem { + id: string; + label: string; + group: string; +} + +/** Product destinations mirror iOS; presentation (dock/rail) is window-driven. */ +export class Nav { + static readonly OVERVIEW: string = 'overview'; + static readonly HISTORY: string = 'history'; + static readonly VOCAB: string = 'vocab'; + static readonly STYLE: string = 'style'; + static readonly SETTINGS: string = 'settings'; + static readonly SELECTION: string = 'selection'; + static readonly TRANSLATION: string = 'translation'; + static readonly CORRECTIONS: string = 'corrections'; + static readonly QA: string = 'qa'; + static readonly CREDENTIALS: string = 'credentials'; + static readonly LOCALASR: string = 'localasr'; + + /** Stable keyboard order; the compact dock presents style as a separate group. */ + static readonly PRIMARY: string[] = [ + Nav.OVERVIEW, Nav.HISTORY, Nav.VOCAB, Nav.STYLE, Nav.SETTINGS + ]; + static readonly DOCK_MAIN: string[] = [Nav.OVERVIEW, Nav.HISTORY, Nav.VOCAB, Nav.SETTINGS]; + + static items(): NavItem[] { + return [ + { id: Nav.OVERVIEW, label: '概览', group: '主要' }, + { id: Nav.HISTORY, label: '历史', group: '主要' }, + { id: Nav.VOCAB, label: '词典', group: '主要' }, + { id: Nav.STYLE, label: '风格', group: '主要' }, + { id: Nav.SETTINGS, label: '设置', group: '主要' } + ]; + } + + static tools(): NavItem[] { + return [ + { id: Nav.SELECTION, label: '选取助手', group: '内容与工具' }, + { id: Nav.TRANSLATION, label: '翻译', group: '风格' }, + { id: Nav.CORRECTIONS, label: '纠错规则', group: '词典' }, + { id: Nav.QA, label: '问答', group: '内容与工具' }, + { id: Nav.CREDENTIALS, label: '大模型配置', group: '语音与模型' }, + { id: Nav.LOCALASR, label: '端侧模型', group: '语音与模型' } + ]; + } + + static label(id: string): string { + const items: NavItem[] = Nav.items().concat(Nav.tools()); + for (let index = 0; index < items.length; index++) { + if (items[index].id === id) return items[index].label; + } + return '概览'; + } + + static ownerOf(id: string): string { + if (id === Nav.CORRECTIONS) return Nav.VOCAB; + // 翻译目标 is the fourth item of the expanded styles dock, so it is a + // destination of its own (no back bar), exactly like the iOS section list. + if (id === Nav.TRANSLATION) return Nav.TRANSLATION; + if (id === Nav.SELECTION || id === Nav.CREDENTIALS || id === Nav.LOCALASR || id === Nav.QA) { + return Nav.SETTINGS; + } + return id; + } + + static rootOf(id: string): string { + let current: string = id; + for (let guard = 0; guard < 8; guard++) { + const owner: string = Nav.ownerOf(current); + if (owner === current) return current; + current = owner; + } + return Nav.OVERVIEW; + } + + static known(id: string): boolean { + const items: NavItem[] = Nav.items().concat(Nav.tools()); + for (let index = 0; index < items.length; index++) { + if (items[index].id === id) return true; + } + return false; + } + + static isSecondary(id: string): boolean { + return Nav.ownerOf(id) !== id; + } + + /** A custom modal blocks every navigation entry, including deep links. */ + static blocked(): boolean { + return AppStorage.get('overlayOpen') === true; + } + + /** Back asks the owner to dismiss; busy editors keep the modal flag intact. */ + static dismissOverlay(): boolean { + if (!Nav.blocked()) return false; + Store.put('overlayBackRequest', (AppStorage.get('overlayBackRequest') ?? 0) + 1); + return true; + } + + static backTarget(id: string): string { + if (id === Nav.CREDENTIALS) { + const origin: string = AppStorage.get('credentialsReturn') ?? Nav.SETTINGS; + return Nav.known(origin) && origin !== Nav.CREDENTIALS ? origin : Nav.SETTINGS; + } + return Nav.ownerOf(id); + } + + /** Preserve each destination's selected detail when changing tabs or layout. */ + static go(id: string): void { + if (Nav.blocked() || !Nav.known(id)) return; + const current: string = AppStorage.get('route') ?? Nav.OVERVIEW; + if (id === current) return; + if (id === Nav.CREDENTIALS) Store.put('credentialsReturn', current); + Store.put('navDetail-' + current, AppStorage.get('detailId') ?? ''); + // Credentials is a transient setup flow, not a sticky Settings tab path. + if (current !== Nav.CREDENTIALS) Store.put('navPath-' + Nav.rootOf(current), current); + Store.put('detailId', AppStorage.get('navDetail-' + id) ?? ''); + Store.put('route', id); + if (id !== Nav.CREDENTIALS) Store.put('navPath-' + Nav.rootOf(id), id); + if (id === Nav.STYLE || id === Nav.TRANSLATION) Store.put('navStyleDestination', id); + } + + static openPrimary(id: string): void { + if (Nav.blocked()) return; + if (id === Nav.STYLE) { + const style: string = AppStorage.get('navStyleDestination') ?? Nav.STYLE; + Nav.go(style === Nav.TRANSLATION ? Nav.TRANSLATION : Nav.STYLE); + return; + } + const saved: string = AppStorage.get('navPath-' + id) ?? id; + Nav.go(saved !== Nav.CREDENTIALS && Nav.rootOf(saved) === id ? saved : id); + } + + /** System back and the page back affordance agree on the owning destination. */ + static back(): boolean { + if (Nav.dismissOverlay()) return true; + const detail: string = AppStorage.get('detailId') ?? ''; + if (detail.length > 0) { + Store.put('detailId', ''); + return true; + } + const current: string = AppStorage.get('route') ?? Nav.OVERVIEW; + if (Nav.isSecondary(current)) { + Nav.go(Nav.backTarget(current)); + return true; + } + if (current !== Nav.OVERVIEW) { + Nav.openPrimary(Nav.OVERVIEW); + return true; + } + return false; + } +} diff --git a/openless-all/harmony/entry/src/main/ets/components/ProductNavigation.ets b/openless-all/harmony/entry/src/main/ets/components/ProductNavigation.ets new file mode 100644 index 000000000..a51088b8d --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/ProductNavigation.ets @@ -0,0 +1,263 @@ +import { deviceInfo } from '@kit.BasicServicesKit'; +import { uiMaterial } from '@kit.ArkUI'; +import { Leading, Motion, Palette, Radius, Size, Space, Type, floatShadow } from '../common/Theme'; +import { Store } from '../common/Store'; +import { dockImageOf, hasDockImage, symbolOf } from './Icons'; +import { Nav } from './Nav'; + +// ProductDock.swift:186-193 keeps the isolated platter circular at 62pt. +const DOCK_HEIGHT: number = 62; +const DOCK_GAP: number = 10; + +/** API 23 must never invoke an API 26 modifier, even with an undefined material. + * AttributeModifier supports guarded attribute calls without duplicating the dock tree. + * https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-user-defined-extension-attributemodifier + */ +export class DockMaterialModifier implements AttributeModifier { + private material: SystemUiMaterial | undefined; + + constructor(material: SystemUiMaterial | undefined) { + this.material = material; + } + + applyNormalAttribute(instance: CommonAttribute): void { + if (deviceInfo.sdkApiVersion >= 26 && this.material !== undefined) { + instance.systemMaterial(this.material); + } + } +} + +/** Native Button gives touch, keyboard activation and focus one shared action. + * Huawei multi-input guidance: + * https://developer.huawei.com/consumer/cn/doc/best-practices-V14/bpta-multi-interaction-V14 + */ +/** + * iOS `ProductDock` (ProductDock.swift), frame-verified against the demo video: + * + * collapsed one pill (概览/历史/词典/设置) + a separate Styles pill + * expanded a circular Dictionary platter + a three-item Styles platter: + * Dict… | My Style | Marketplace | Translation targets + * + * Selected item = accentSoft capsule with accent glyph+label; unselected glyphs + * use the primary text colour (black in light, white in dark), not grey. + * Expansion animates 0.28s with a 0.12s easeOut handoff (ProductDock.swift:149,159). + * https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-animatorproperty + */ +@Component +export struct ProductDock { + @Prop route: string = Nav.OVERVIEW; + @StorageLink('styleSection') section: number = 0; + @StorageLink('reduceMotion') reduceMotion: boolean = false; + private mat: SystemUiMaterial | undefined = undefined; + private materialModifier: DockMaterialModifier = new DockMaterialModifier(undefined); + + aboutToAppear(): void { + this.mat = this.dockMaterial(); + this.materialModifier = new DockMaterialModifier(this.mat); + } + + private hasMaterial(): boolean { + return this.mat !== undefined; + } + + private pillFill(): ResourceColor { + return this.hasMaterial() ? Color.Transparent : Palette.glassLo(); + } + + /** Deep glass gradient when we paint it ourselves; transparent under material. */ + private pillGradient(): LinearGradientOptions { + if (this.hasMaterial()) { + return { angle: 180, colors: [[Color.Transparent, 0], [Color.Transparent, 1]] }; + } + return { angle: 180, colors: [[Palette.glassHi(), 0], [Palette.glassLo(), 1]] }; + } + + private pillBlur(): BlurStyle { + return this.hasMaterial() ? BlurStyle.NONE : BlurStyle.COMPONENT_ULTRA_THICK; + } + + /** The styles pill stays expanded for its four sections, 翻译目标 included. */ + private expanded(): boolean { + return Nav.rootOf(this.route) === Nav.STYLE || this.route === Nav.TRANSLATION; + } + + /** + * System immersive material for the floating dock (the「沉浸光感」look used by + * Melotopia and HarmonyOS first-party apps). It is an API 26 surface, so older + * devices keep the blur + gradient fallback painted below. + * https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-uimaterial + */ + private dockMaterial(): SystemUiMaterial | undefined { + try { + if (deviceInfo.sdkApiVersion >= 26 && uiMaterial.isImmersiveMaterialSupported()) { + const material = new uiMaterial.ImmersiveMaterial({ + style: uiMaterial.ImmersiveStyle.THIN, + materialColor: Palette.dockTint(), + applyShadow: true, + interactive: false + }); + console.info('[OpenLess Dock] immersive material active, api=' + deviceInfo.sdkApiVersion.toString()); + return material; + } + console.info('[OpenLess Dock] immersive material needs API 26, api=' + deviceInfo.sdkApiVersion.toString()); + } catch (error) { + console.warn('[OpenLess Dock] immersive material unavailable'); + } + return undefined; + } + + private openStyle(section: number): void { + Store.put('styleSection', section); + Nav.go(Nav.STYLE); + } + + /** iOS swaps the whole dock with a spring, not a crossfade. */ + private animateDock(action: () => void): void { + if (this.reduceMotion) { + animateTo({ duration: Motion.reduced, curve: Curve.EaseOut }, () => { + action(); + }); + return; + } + animateTo({ duration: Motion.dock, curve: Curve.Friction }, () => { + action(); + }); + } + + /** ForEach retains each item; read the live route inside its reactive + * attributes instead of capturing a computed Boolean when the item is created. + */ + private primaryActive(id: string): boolean { + return !this.expanded() && Nav.rootOf(this.route) === id; + } + + build() { + // iOS renders two bars: the primary pill and the styles pill. Collapsed = + // 4 + 1; expanded = 词典 + the three style sections (ProductDock.swift:13-24). + Row({ space: DOCK_GAP }) { + Row() { + if (this.expanded()) { + this.item(Nav.VOCAB, '词典', 'dict') + } else { + ForEach(Nav.DOCK_MAIN, (id: string) => { + this.item(id, Nav.label(id), id) + }, (id: string) => 'dock-' + id) + } + } + .id('dock-primary-platter') + .layoutWeight(this.expanded() ? 0 : 1) + .width(this.expanded() ? DOCK_HEIGHT : undefined) + .constraintSize({ minHeight: DOCK_HEIGHT }) + .padding(Space.xxs) + .linearGradient(this.pillGradient()) + .backgroundColor(this.pillFill()) + .backgroundBlurStyle(this.pillBlur()) + .borderRadius(Radius.pill) + .border({ width: 0.5, color: Palette.glassEdge() }) + .shadow(floatShadow()) + .attributeModifier(this.materialModifier) + + Row() { + if (this.expanded()) { + this.styleItem('我的风格', 'style', 0) + this.styleItem('风格市场', 'marketplace', 1) + this.styleItem('翻译目标', 'translation', 2) + } else { + this.item(Nav.STYLE, '风格', 'style') + } + } + .id('dock-style-platter') + .layoutWeight(this.expanded() ? 1 : 0) + .width(this.expanded() ? undefined : DOCK_HEIGHT) + .constraintSize({ minHeight: DOCK_HEIGHT }) + .padding(Space.xxs) + .linearGradient(this.pillGradient()) + .backgroundColor(this.pillFill()) + .backgroundBlurStyle(this.pillBlur()) + .borderRadius(Radius.pill) + .border({ width: 0.5, color: Palette.glassEdge() }) + .shadow(floatShadow()) + .attributeModifier(this.materialModifier) + } + .width('100%') + .padding({ left: Space.md, right: Space.md, top: Space.xs, bottom: Space.xs }) + } + + @Builder + item(id: string, label: string, key: string) { + Button({ type: ButtonType.Normal }) { + Column({ space: 2 }) { + if (hasDockImage(id)) { + Image(dockImageOf(id)) + .width(Size.icon).height(Size.icon) + .objectFit(ImageFit.Contain) + .fillColor(this.primaryActive(id) ? Palette.accent() : Palette.text1()) + .accessibilityLevel('no') + } else { + SymbolGlyph(symbolOf(id)).fontSize(Size.icon) + .fontColor([this.primaryActive(id) ? Palette.accent() : Palette.text1()]) + } + Text(label).fontSize(Type.caption2).lineHeight(Leading.caption2) + .fontColor(this.primaryActive(id) ? Palette.accent() : Palette.text2()) + .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) + } + .width('100%') + } + .id('dock-' + key) + .layoutWeight(1) + .constraintSize({ minHeight: 54 }) + .borderRadius(Radius.pill) + .backgroundColor(this.primaryActive(id) ? Palette.accentSoft() : Color.Transparent) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(label) + .accessibilitySelected(this.primaryActive(id)) + .onClick(() => { + if (id === Nav.STYLE) { + this.animateDock(() => { + Nav.openPrimary(Nav.STYLE); + }); + } else { + Nav.openPrimary(id); + } + }) + } + + @Builder + styleItem(label: string, symbol: string, section: number) { + Button({ type: ButtonType.Normal }) { + Column({ space: 2 }) { + if (hasDockImage(symbol)) { + Image(dockImageOf(symbol)) + .width(Size.icon).height(Size.icon) + .objectFit(ImageFit.Contain) + .fillColor(this.styleActive(section) ? Palette.accent() : Palette.text1()) + .accessibilityLevel('no') + } else { + SymbolGlyph(symbolOf(symbol)).fontSize(Size.icon) + .fontColor([this.styleActive(section) ? Palette.accent() : Palette.text1()]) + } + Text(label).fontSize(Type.caption2).lineHeight(Leading.caption2) + .fontColor(this.styleActive(section) ? Palette.accent() : Palette.text2()) + .maxLines(1).textOverflow({ overflow: TextOverflow.Ellipsis }) + } + .width('100%') + } + .id('dock-style-' + section.toString()) + .layoutWeight(1) + .constraintSize({ minHeight: 54 }) + .borderRadius(Radius.pill) + .backgroundColor(this.styleActive(section) ? Palette.accentSoft() : Color.Transparent) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText(label) + .accessibilitySelected(this.styleActive(section)) + .onClick(() => { + if (section === 2) Nav.go(Nav.TRANSLATION); + else this.openStyle(section); + }) + } + + private styleActive(section: number): boolean { + if (section === 2) return this.route === Nav.TRANSLATION; + return this.route === Nav.STYLE && this.section === section; + } +} diff --git a/openless-all/harmony/entry/src/main/ets/components/VoiceControl.ets b/openless-all/harmony/entry/src/main/ets/components/VoiceControl.ets new file mode 100644 index 000000000..2dcb5711e --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/VoiceControl.ets @@ -0,0 +1,117 @@ +import { Motion, Palette, Radius, Type, Leading } from '../common/Theme'; +import { activateOnKey } from './Kit'; +import { symbolOf } from './Icons'; + +const BAR_PROFILE: number[] = [0.45, 0.7, 0.9, 1, 0.9, 0.7, 0.45]; + +/** + * Voice control modelled on the iOS main screen (ios/PlatformSupport SpeakButton): + * + * idle a wide capsule with a microphone and 「开始说话」 + * recording grows into a filled circle with a seven-bar waveform and a soft + * level ring behind it + * processing a compact capsule with an activity indicator and 「转写中…」 + * + * Tap toggles start/stop; the recorder itself lives in the core, this control only + * reflects `dictPhase` / `dictLevel` and reports intent. + */ +@Component +export struct VoiceControl { + @Prop phase: string = 'idle'; + @Prop level: number = 0; + @Prop usable: boolean = true; + onToggle: () => void = () => { + }; + + private recording(): boolean { + return this.phase === 'recording'; + } + + private busy(): boolean { + return this.phase === 'processing' || this.phase === 'starting' || this.phase === 'cancelling'; + } + + private amplitude(): number { + if (!this.recording()) return 0.1; + const value: number = this.level; + if (value < 0.05) return 0.05; + return value > 1 ? 1 : value; + } + + build() { + Stack() { + if (this.recording()) { + Column() + .width(150) + .height(150) + .borderRadius(Radius.pill) + .backgroundColor(Palette.dangerSoft()) + .scale({ x: 1 + this.amplitude() * 0.12, y: 1 + this.amplitude() * 0.12 }) + .opacity(0.9) + .animation({ duration: Motion.quick, curve: Curve.EaseOut }) + } + + Column() { + if (this.recording()) { + Row({ space: 4 }) { + ForEach(BAR_PROFILE, (profile: number, index: number) => { + Column() + .width(4) + .height(8 + this.amplitude() * 40 * profile) + .borderRadius(2) + .backgroundColor(Palette.onAccent()) + .animation({ duration: Motion.quick, curve: Curve.EaseOut }) + }, (profile: number, index: number) => 'bar-' + index.toString()) + } + .height(52) + } else if (this.busy()) { + Row({ space: 8 }) { + LoadingProgress() + .width(20) + .height(20) + .color(Palette.onAccent()) + Text(this.phase === 'starting' ? '准备中…' : '转写中…') + .fontSize(Type.label) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.bg()) + } + } else { + Row({ space: 8 }) { + SymbolGlyph(symbolOf('mic')) + .fontSize(22) + .fontColor([Palette.bg()]) + Text('开始说话') + .fontSize(Type.body) + .lineHeight(Leading.body) + .fontWeight(FontWeight.Medium) + .fontColor(Palette.bg()) + } + } + } + .width(this.recording() ? 112 : 152) + .height(this.recording() ? 112 : 60) + .justifyContent(FlexAlign.Center) + .backgroundColor(this.recording() ? Palette.danger() : Palette.text1()) + .borderRadius(Radius.pill) + .opacity(this.usable ? 1 : 0.5) + .animation({ duration: Motion.base, curve: Curve.EaseOut }) + .focusable(true) + .hoverEffect(HoverEffect.Highlight) + .onKeyEvent((event: KeyEvent) => activateOnKey(event, () => { + if (this.usable) this.onToggle(); + })) + .accessibilityText(this.recording() ? '结束并上屏' : '开始说话') + .accessibilitySelected(this.recording()) + .onClick(() => { + if (this.usable) this.onToggle(); + }) + .stateStyles({ + normal: { .scale({ x: 1, y: 1 }) }, + pressed: { .scale({ x: 0.96, y: 0.96 }) } + }) + } + .width('100%') + .height(176) + .alignContent(Alignment.Center) + } +} diff --git a/openless-all/harmony/entry/src/main/ets/components/history/HistoryDateFilter.ets b/openless-all/harmony/entry/src/main/ets/components/history/HistoryDateFilter.ets new file mode 100644 index 000000000..0d1635a6f --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/history/HistoryDateFilter.ets @@ -0,0 +1,135 @@ +import { Leading, Palette, Radius, Size, Space, Type } from '../../common/Theme'; +import { activateOnKey, Group, TextButton } from '../Kit'; +import { symbolOf } from '../Icons'; + +/** + * iOS `HistoryView.dateFilterRow` (HistoryView.swift lines 101-116), ported as the + * same single line: + * + * HStack [按日期筛选] (button style Toggle) ........ 重置 (only when on) + * (when on) DatePicker 开始 / DatePicker 结束, 8pt apart + * + * The page owns the dates; the pickers themselves are opened by the page so this + * component keeps no business state. + */ +const TOGGLE_HEIGHT: number = 36; +const DATE_ROW_HEIGHT: number = 44; + +@Component +struct HistoryDateRow { + @Prop label: string = ''; + @Prop value: string = ''; + onTap: () => void = () => { + }; + + build() { + Row({ space: Space.sm }) { + Text(this.label) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(Palette.text1()) + Blank() + Text(this.value) + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(Palette.text2()) + .maxLines(1) + SymbolGlyph(symbolOf('chevron')) + .fontSize(Size.iconSmall) + .fontColor([Palette.text3()]) + } + .width('100%') + .height(DATE_ROW_HEIGHT) + .padding({ left: Space.md, right: Space.md }) + .hoverEffect(HoverEffect.Highlight) + .focusable(true) + .onKeyEvent((event: KeyEvent) => activateOnKey(event, () => { + this.onTap(); + })) + .onClick(() => { + this.onTap(); + }) + .accessibilityText(this.label + ' ' + this.value) + } +} + +@Component +export struct HistoryDateFilter { + @Prop filterOn: boolean = false; + @Prop startLabel: string = ''; + @Prop endLabel: string = ''; + onToggle: () => void = () => { + }; + onReset: () => void = () => { + }; + onPickStart: () => void = () => { + }; + onPickEnd: () => void = () => { + }; + + build() { + Column({ space: Space.xs }) { + Row({ space: Space.xs }) { + Button({ type: ButtonType.Normal }) { + Text(this.filterOn ? '按日期筛选 · 已开启' : '按日期筛选') + .fontSize(Type.label) + .lineHeight(Leading.label) + .fontColor(Palette.accent()) + } + .padding({ left: 0, right: 0, top: Space.xxs, bottom: Space.xxs }) + .backgroundColor(Color.Transparent) + .hoverEffect(HoverEffect.Highlight) + .accessibilityText('按日期筛选') + .accessibilitySelected(this.filterOn) + .focusable(true) + .onKeyEvent((event: KeyEvent) => activateOnKey(event, () => { + this.onToggle(); + })) + .onClick(() => { + this.onToggle(); + }) + + Blank() + + if (this.filterOn) { + TextButton({ + label: '重置', + onTap: () => { + this.onReset(); + } + }) + } + } + .width('100%') + .alignItems(VerticalAlign.Center) + + if (this.filterOn) { + Group() { + Column() { + HistoryDateRow({ + label: '开始', + value: this.startLabel, + onTap: () => { + this.onPickStart(); + } + }) + Divider() + .color(Palette.line()) + .strokeWidth(0.5) + .margin({ left: Space.md }) + HistoryDateRow({ + label: '结束', + value: this.endLabel, + onTap: () => { + this.onPickEnd(); + } + }) + } + .width('100%') + } + } + } + .width('100%') + .alignItems(HorizontalAlign.Start) + } +} diff --git a/openless-all/harmony/entry/src/main/ets/components/history/HistoryDetail.ets b/openless-all/harmony/entry/src/main/ets/components/history/HistoryDetail.ets new file mode 100644 index 000000000..3ef92e928 --- /dev/null +++ b/openless-all/harmony/entry/src/main/ets/components/history/HistoryDetail.ets @@ -0,0 +1,249 @@ +import { Layout, Leading, Palette, Radius, Space, Type } from '../../common/Theme'; +import { SectionTitle, Surface, Tag, TextButton, TonalButton } from '../Kit'; +import { HistoryTextCard } from './HistoryTextCard'; + +/** + * The one detail surface used by both presentations, ported from + * `HistoryDetailView` (HistoryView.swift lines 138-244): + * + * status (subheadline semibold) / date (caption) / duration (caption) + * 处理结果 card → 识别原文 card (text cards with 复制) + * 录音 card (play / stop, plus the Harmony-only 重新转写) + * 重新润色 (style choice, hint when no text model is configured) + * 重新润色 ·