Calculator v1.6: round-screen keypad with arithmetic

- 19-key layout fitted to round display, centered focus, scrollable list
- full arithmetic: +-*/ %, decimals, +/- , AC, divide-by-zero, chained ops
- scroll-to-center focus with top/bottom spacers, high-contrast keys
- tests: arithmetic + geometry/contrast
This commit is contained in:
2026-09-09 15:09:31 +01:00
commit 176de6bc1f
12 changed files with 10698 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
node_modules/
build/
dist/
sign/*.pem
+209
View File
@@ -0,0 +1,209 @@
# Xiaomi Vela Hello World for Watch S4
This is the smallest practical Xiaomi Vela JS watch application. It shows two centered lines on a round black screen:
```text
Hello World!
Xiaomi Watch S4
```
It compiles entirely from a Linux terminal. Xiaomi AIoT-IDE is not required.
## 1. What you need
- A 64-bit Linux system
- Node.js and npm
- OpenSSL, but only if you want a signed release package
- Internet access for the first `npm install`
Node.js 20 LTS is a conservative choice. The included project has also been build-tested with Node.js 24 and npm 11.
On Ubuntu or Debian, install the basic tools:
```bash
sudo apt update
sudo apt install -y curl openssl
```
Install Node.js using your preferred package manager or a version manager such as `nvm`. Confirm that it works:
```bash
node --version
npm --version
```
## 2. Understand the tiny project
```text
xiaomi-vela-s4-hello-world/
├── package.json
├── README.md
├── sign/
└── src/
├── app.ux
├── manifest.json
├── common/
│ ├── icon.png
│ └── icon.svg
└── pages/
└── index/
└── index.ux
```
- `package.json` installs Xiaomi's command-line build tool and defines the build commands.
- `src/manifest.json` defines the package, icon, watch target, design width, and start page.
- `src/app.ux` contains application lifecycle hooks.
- `src/pages/index/index.ux` contains the UI and its styles.
- `sign/` is where release certificate files go. Keep private keys private.
Vela `.ux` files resemble small single-file web components. A page may contain `template`, `style`, and `script` blocks. This Hello World page needs only `template` and `style`.
## 3. Compile a debug RPK without Xiaomi's IDE
Open a terminal in the project folder and run:
```bash
npm install
npm run build
```
The important output is created under `dist/` and ends in `.debug.rpk`:
```bash
find dist -maxdepth 1 -type f -name '*.rpk' -print
```
The `build/` directory contains intermediate generated files. You normally do not edit either `build/` or `dist/`.
To include a separate source map while debugging:
```bash
npm run build:source-map
```
To see every compiler option supported by your installed toolkit:
```bash
npm run help
```
## 4. Create a signed release RPK
The release builder expects these two files:
```text
sign/private.pem
sign/certificate.pem
```
Generate a local development certificate from the project root:
```bash
openssl req \
-newkey rsa:2048 \
-nodes \
-keyout sign/private.pem \
-x509 \
-days 3650 \
-out sign/certificate.pem \
-subj '/CN=Hello Vela Development/O=Example/C=US'
```
Then compile the release package:
```bash
npm run release
find dist -maxdepth 1 -type f -name '*.release.*.rpk' -print
```
Do not commit or share `sign/private.pem`. If a companion Android application communicates with the watch app, Xiaomi's wearable integration may require matching signing identity; changing certificates later can also prevent an update from being accepted as the same app.
## 5. Change the app
Edit `src/pages/index/index.ux`. For example, replace:
```xml
<text class="hello">Hello World!</text>
```
with:
```xml
<text class="hello">My first app</text>
```
Then rebuild:
```bash
npm run build
```
When publishing an update, increase `versionCode` in `src/manifest.json`. Also update `versionName` when you want the visible version string to change.
## 6. Important Vela rules
- A template must have exactly one root element.
- Visible text must be inside a `<text>` component.
- Vela uses flex layout, but its CSS support is smaller than a browser's CSS support.
- Package names should use reverse-domain form, such as `com.yourname.hello`.
- `designWidth: 480` lets Vela scale the 480-pixel design to the physical display.
- APIs such as sensors, storage, network, or vibration must usually be declared in the manifest's `features` array before use. This Hello World app requests no APIs.
## 7. Installing on a real Watch S4
Compilation and installation are separate. The terminal workflow above reliably creates the `.rpk`; transferring it to a physical watch depends on the exact Watch S4 model, firmware region, Mi Fitness version, and whether developer or debugging access is enabled for that firmware.
Do not treat the `.rpk` as an Android APK, and do not flash random firmware. Use Xiaomi's supported wearable deployment route for your device/account. Some retail or global firmware builds do not expose the same development or sideload controls as Chinese developer setups.
## 8. Troubleshooting
### `aiot: command not found`
Always run the local tool through npm:
```bash
npm install
npm run build
```
Do not rely on a global `aiot` installation.
### Dependency installation fails
Clear only this project's installed dependencies and retry:
```bash
rm -rf node_modules
npm install
```
If you use a company proxy, configure npm for that proxy instead of disabling TLS verification.
### No `.rpk` appears
Read the first compiler error, then verify:
```bash
npx aiot build -h
find src -maxdepth 4 -type f -print
```
The required files are `src/manifest.json`, `src/app.ux`, and the routed page component.
### Release build says signing files are missing
Run the OpenSSL command in section 4 and confirm:
```bash
test -s sign/private.pem && test -s sign/certificate.pem && echo 'Signing files exist'
```
## Official references
- Xiaomi Vela JS documentation: <https://iot.mi.com/vela/quickapp/en/>
- Project structure: <https://iot.mi.com/vela/quickapp/zh/guide/start/project-overview.html>
- Manifest configuration: <https://iot.mi.com/vela/quickapp/zh/guide/framework/manifest.html>
- Compiler parameters: <https://iot.mi.com/vela/quickapp/zh/guide/start/toolkit-params.html>
- UI introduction: <https://iot.mi.com/vela/quickapp/zh/guide/start/user-interface.html>
The project intentionally uses only the public `aiot-toolkit` command-line package. It does not require Xiaomi AIoT-IDE.
+1
View File
@@ -0,0 +1 @@
/tmp/hw/node_modules
+10223
View File
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
{
"name": "xiaomi-vela-s4-hello-world",
"version": "1.0.0",
"private": true,
"description": "Minimal Xiaomi Vela JS Hello World app for Xiaomi Watch S4",
"scripts": {
"build": "aiot build",
"release": "aiot release",
"build:source-map": "aiot build --devtool=source-map",
"help": "aiot build -h"
},
"devDependencies": {
"aiot-toolkit": "2.0.5"
}
}
+10
View File
@@ -0,0 +1,10 @@
<script>
export default {
onCreate() {
console.log('Hello Vela app created')
},
onDestroy() {
console.log('Hello Vela app destroyed')
}
}
</script>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="192" height="192" viewBox="0 0 192 192">
<rect width="192" height="192" rx="48" fill="#ff6900"/>
<text x="96" y="116" text-anchor="middle" font-family="DejaVu Sans, sans-serif" font-size="72" font-weight="700" fill="#ffffff">Hi</text>
</svg>

After

Width:  |  Height:  |  Size: 293 B

+27
View File
@@ -0,0 +1,27 @@
{
"package": "com.example.hellovela",
"name": "Calc",
"icon": "/common/icon.png",
"versionName": "1.6",
"versionCode": 7,
"minAPILevel": 1,
"deviceTypeList": [
"watch"
],
"config": {
"logLevel": "debug",
"designWidth": 480
},
"router": {
"entry": "pages/index",
"pages": {
"pages/index": {
"component": "index",
"path": "/"
}
}
},
"display": {
"backgroundColor": "#000000"
}
}
+108
View File
@@ -0,0 +1,108 @@
<template>
<div class="page">
<text class="display" style="font-size: {{displaySize}}px">{{ display }}</text>
<list class="keys" id="keys" onscroll="onScroll">
<list-item type="pad" class="pad top"></list-item>
<list-item type="key" class="item {{ $idx === focused ? 'focused' : '' }}" for="{{ keys }}" onclick="confirmKey">
<text class="keylabel" style="color: {{ $idx === focused ? '#000000' : '#ffffff' }}">{{ $item.label }}</text>
</list-item>
<list-item type="pad" class="pad bottom"></list-item>
</list>
</div>
</template>
<script>
export default {
private: {
display: '0',
focused: 0,
keys: []
},
computed: {
displaySize() {
return this.display.length > 9 ? 38 : this.display.length > 7 ? 46 : 52
}
},
onInit() {
const labels = ['AC','+/-','%','/','7','8','9','x','4','5','6','-','1','2','3','+','0','.','=']
this.keys = labels.map(l => ({ label: l }))
this.ITEM_H = 54
this.KEYS_H = 300
this.PAD = this.KEYS_H / 2 - this.ITEM_H / 2 // 123px spacers so first/last item can center
},
onScroll(e) {
// focused item = the one centered in the list's viewport (spacers included in offset)
const idx = Math.round((e.scrollY + this.KEYS_H / 2 - this.ITEM_H / 2 - this.PAD) / this.ITEM_H)
this.focused = Math.max(0, Math.min(this.keys.length - 1, idx))
},
confirmKey() {
if (!this.keys.length) return
this.press(this.keys[this.focused].label)
},
press(key) {
if (key === '+') { this.stored = Number(this.display); this.op = '+'; this.fresh = true }
else if (key === '-') { this.stored = Number(this.display); this.op = '-'; this.fresh = true }
else if (key === 'x') { this.stored = Number(this.display); this.op = 'x'; this.fresh = true }
else if (key === '/') { this.stored = Number(this.display); this.op = '/'; this.fresh = true }
else if (key === '=') {
const b = Number(this.display)
let r = 0
if (this.op === '+') r = this.stored + b
else if (this.op === '-') r = this.stored - b
else if (this.op === 'x') r = this.stored * b
else if (this.op === '/') r = b === 0 ? NaN : this.stored / b
this.display = Number.isFinite(r) ? String(Math.round(r * 1e9) / 1e9) : 'Error'
this.fresh = true
}
else if (key === 'AC') { this.display = '0'; this.stored = 0; this.op = ''; this.fresh = true }
else if (key === '+/-') { this.display = this.display.startsWith('-') ? this.display.slice(1) : '-' + this.display }
else if (key === '%') { this.display = String(Number(this.display) / 100) }
else if (key === '.') { if (this.fresh) { this.display = '0.'; this.fresh = false } else if (!this.display.includes('.')) this.display += '.' }
else {
if (this.fresh) { this.display = key; this.fresh = false }
else if (this.display.replace(/[-.]/g,'').length < 9) this.display += key
}
// keep the focused item visually centered after each press
const el = this.$element('keys')
el && el.scrollTo({
top: this.PAD + this.focused * this.ITEM_H - this.KEYS_H / 2 + this.ITEM_H / 2,
behavior: 'smooth'
})
},
onBackPress() {
this.confirmKey()
return true
}
}
</script>
<style>
.page {
width: 480px; height: 480px;
background-color: #000000;
flex-direction: column;
align-items: center;
justify-content: center;
}
.display {
width: 340px; height: 70px;
color: #ffffff;
text-align: center;
}
.keys {
width: 320px; height: 300px;
}
.item {
width: 300px; height: 54px;
justify-content: center; align-items: center;
border-radius: 27px;
background-color: #3a3a3e;
}
.focused {
background-color: #f3a633;
}
.pad {
height: 123px;
}
.keylabel {
font-size: 34px; text-align: center;
}
</style>
+42
View File
@@ -0,0 +1,42 @@
const fs = require('node:fs');
const vm = require('node:vm');
const assert = require('node:assert/strict');
const ux = fs.readFileSync('src/pages/index/index.ux', 'utf8');
const script = ux.match(/<script>([\s\S]*?)<\/script>/)[1];
function page() {
const spec = vm.runInNewContext(script.replace('export default', 'globalThis.spec =') + '\nspec');
return Object.assign({}, spec.private, spec);
}
const p = page();
assert.equal(typeof p.press, 'function', 'Keypress handler must exist');
['2','+','3','='].forEach(k => p.press(k));
assert.equal(p.display, '5');
console.log('PASS addition through page keypress handler');
const cases = [
['subtract',['9','-','4','='],'5'],
['multiply',['6','x','7','='],'42'],
['divide',['8','/','2','='],'4'],
['decimals',['0','.','1','+','0','.','2','='],'0.3'],
['duplicate dot',['1','.','.','2'],'1.2'],
['sign',['5','+/-','x','2','='],'-10'],
['percent',['5','0','%'],'0.5'],
['percent add',['2','0','0','+','1','0','%','='],'220'],
['percent multiply',['2','0','0','x','1','0','%','='],'20'],
['clear',['9','+','AC','2','='],'2'],
['zero division',['8','/','0','='],'Error'],
['recover',['8','/','0','=','3'],'3'],
['chain',['2','+','3','x','4','='],'20'],
['replace operator',['2','+','x','3','='],'6'],
['repeat equals',['2','+','3','=','=', '='],'11'],
['fresh entry',['2','+','3','=','7'],'7'],
['input cap',Array(20).fill('9'),'999999999'],
['leading zero',['0','0','2'],'2']
];
for(const [name,keys,expected] of cases) {
const c=page(); keys.forEach(k=>c.press(k)); assert.equal(c.display,expected,name);
}
assert.match(ux, /\{\{ display \}\}/);
const keys=[...ux.matchAll(/<text[^>]*onclick="press\('([^']+)'\)"/g)].map(m=>m[1]);
assert.equal(keys.length,19,'every button must have handler');
assert.equal(new Set(keys).size,19);
console.log('PASS',cases.length,'edge cases and all 19 button bindings');
+54
View File
@@ -0,0 +1,54 @@
// Visual layout test: circle-screen geometry + contrast, computed from the .ux source.
const fs = require('node:fs');
const assert = require('node:assert/strict');
const ux = fs.readFileSync('src/pages/index/index.ux', 'utf8');
const num = (re) => { const m = ux.match(re); assert.ok(m, 'style missing: ' + re); return Number(m[1]); };
const SCREEN = 480, R = SCREEN / 2;
const dispH = num(/\.display\s*{[^}]*height:\s*(\d+)px/);
const itemH = num(/\.item\s*{[^}]*height:\s*(\d+)px/);
const itemW = num(/\.item\s*{[^}]*width:\s*(\d+)px/);
const keysH = num(/\.keys\s*{[^}]*height:\s*(\d+)px/);
const keysW = num(/\.keys\s*{[^}]*width:\s*(\d+)px/);
const N = 19;
// page is justify-content:center → column total = dispH + keysH, centered vertically
const total = dispH + keysH;
const listTop = (SCREEN - total) / 2 + dispH;
// (1) geometry: check every POSSIBLE viewport position (item i centered → viewport spans [i*itemH, i*itemH+keysH] relative to list top incl pad)
// worst-case visible row = the centered one (at circle center) + rows at viewport top/bottom edges
for (let i = 0; i < N; i++) {
// item i centered: its top y = R - itemH/2 → rows at viewport edges: y = R ± keysH/2
for (const y of [R - keysH / 2, R + keysH / 2]) {
const halfW = Math.sqrt(Math.max(0, R * R - Math.abs(y - R) ** 2));
assert.ok(itemW / 2 <= halfW, `viewport edge row at y=${y} exceeds chord: needs ${itemW / 2}px, has ${halfW.toFixed(1)}px`);
}
}
console.log(`PASS circle containment: ${itemW}px items fit chord for all visible rows (listTop=${listTop})`);
// (2) focus = item centered in viewport, and pressing auto-centers it
assert.match(ux, /e\.scrollY \+ this\.KEYS_H \/ 2 - this\.ITEM_H \/ 2/, 'onScroll must center focus in viewport');
assert.match(ux, /scrollTo\(/, 'press() must auto-scroll to keep focus centered');
console.log('PASS focus = middle of viewport, auto-centered on press');
// (3) full reachability of first AND last item (spacers PAD = keysH/2 - itemH/2)
const pad = keysH / 2 - itemH / 2;
const scrollMax = Math.max(0, N * itemH + 2 * pad - keysH);
// item i is centered when scrollY = pad + i*itemH - (keysH/2 - itemH/2) = i*itemH (with pad = keysH/2-itemH/2)
assert.ok(scrollMax >= (N - 1) * itemH, `last item cannot center: scrollMax ${scrollMax} < ${(N - 1) * itemH}`);
assert.match(ux, /class="pad top"/, 'top spacer present');
assert.match(ux, /class="pad bottom"/, 'bottom spacer present');
console.log(`PASS reachability: with ${pad}px spacers, item 0..${N - 1} all centerable (scrollMax ${scrollMax}px)`);
// (4) contrast (large-text 4.5:1 target)
const lum = (hex) => {
const c = hex.match(/\w\w/g).map(x => parseInt(x, 16) / 255).map(v => v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4));
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
};
const ratio = (a, b) => (Math.max(lum(a), lum(b)) + 0.05) / (Math.min(lum(a), lum(b)) + 0.05);
assert.ok(ratio('#ffffff', '#3a3a3e') >= 4.5, 'normal key contrast');
assert.ok(ratio('#000000', '#f3a633') >= 4.5, 'focused key contrast');
assert.match(ux, /#3a3a3e/, 'key bg lighter than old #242426');
console.log('PASS contrast: keys ' + ratio('#ffffff', '#3a3a3e').toFixed(1) + ':1, focused ' + ratio('#000000', '#f3a633').toFixed(1) + ':1');
console.log('ALL VISUAL CHECKS PASS');