Clean browser integration and verify complete Ukuvota workflows

This commit is contained in:
waozi committed 2026-10-07 02:18:08 -03:00
1 parent b68ebc9027
commit ca0be3ca43
51 files changed
+1157 -562

No files matched your search

+2
View File
@@ -9,3 +9,5 @@ zlib1g-dev
curl
xvfb
xauth
tesseract-ocr
python3-pil
+5 -2
View File
@@ -97,10 +97,13 @@ jobs:
with:
node-version: '22'
- name: Test browser persistence
- name: Test complete browser workflows and website
env:
CHROMIUM: google-chrome
run: node tests/web_test.mjs
run: |
sh site/build.sh
node tests/web_test.mjs
node tests/web_test.mjs --site
build-android-debug:
name: Build Android Debug
-10
View File
@@ -1,10 +0,0 @@
# FreeBSD make entrypoint. The canonical build is the GNU Makefile.
GMAKE ?= gmake
.MAIN: all
all:
${GMAKE} all
.DEFAULT:
${GMAKE} ${.TARGET}
+4
View File
@@ -4,10 +4,14 @@
- Use the same Ukuvota interface on Linux, Android and the web.
- Save browser decisions between visits and download a local backup.
- Use native browser text editing for touch keyboards, international typing, selection and paste.
- Follow the browser's light or dark appearance preference.
- Collect separate ballots from people sharing a device and return to edit a saved ballot.
- Show ties clearly, ignore abstentions and reject empty ballots or duplicate voter names.
- Include Status quo and Repeat process in every new decision.
- Improve narrow-screen voting and translate the updated manual into all supported languages.
- Follow phase changes automatically and keep the current voting or results heading visible.
- Retry browser saves after storage failures and keep backup controls clear of the ballot.
- Preserve existing decisions when an unsupported database cannot be opened.
- Make local storage explicit; online sharing is not connected in this version.
-1
View File
@@ -1 +0,0 @@
include Makefile
+2
View File
@@ -59,4 +59,6 @@ appimage: build
sh scripts/package-linux.sh appimage
web-test: web
sh site/build.sh
node tests/web_test.mjs
node tests/web_test.mjs --site
+10 -1
View File
@@ -61,12 +61,21 @@ The browser build needs Emscripten (tested with 6.0.6), Tcl and CMake:
make web # HTML, JavaScript, Wasm and both distribution ZIPs
make serve # http://127.0.0.1:8080
make site # static site and embedded app in build/site
make web-test # complete browser flow in both packaged versions
```
`EMCC` and `EMCMAKE` can select Emscripten tools; the default is
`~/emsdk/upstream/emscripten`. Browser data lives in IndexedDB under the app's
origin. Use Download backup before clearing browser data. If saving fails,
keep the page open and download the backup.
keep the page open and download the backup, then use Retry saving. Browser
text fields use native editing, including selection, paste, IME and touch
keyboards. System appearance follows the browser's color preference.
The browser tests need Node 22, Chromium, Xvfb, xauth, Tesseract OCR and Pillow. They
use a disposable profile and private display, recognize rendered controls,
and verify proposals, distinct voters, ballot editing, ties, quorum, mobile
touch input, reload persistence and downloaded SQLite backups. Both the web
distribution and the website's app path run through the same tests.
Android needs JDK 17 or newer, Android SDK 36, NDK 28.2.13676358 and CMake 3.22.1:
+11 -5
View File
@@ -5,7 +5,9 @@ Ukuvota has one maintained Ziran application. `app.zi` supplies `Frame`,
`collect_view.zi` collects proposals, ballots and results. UI code imports the
current `kryon/Widgets` surface. The desktop host uses SDL/Cairo, the browser
host uses Kryon's Canvas backend, and Android uses Kryon's Raylib host with a
small keyboard/data-directory bridge.
small keyboard/data-directory bridge. Browser fields use native DOM editing
through Ziran's public Web API, so touch keyboards, selection, paste and IME
input use the browser's normal controls. Kryon draws the shared field UI.
`storage.zi` owns SQLite transactions, process history and local participant
identities. Existing database upgrades preserve records and key material;
@@ -28,8 +30,12 @@ proposals cannot become a winner, and equal scored leaders have no selected
winner. Status quo and Repeat process have stable stored keys.
The browser mounts SQLite storage on IndexedDB before starting the app,
flushes committed changes, reports failures and offers a SQLite download.
Tests and screenshots use private displays and disposable databases.
flushes committed changes, reports failures, allows retrying a failed save
and offers a SQLite download. System appearance follows the browser's color
preference. The integration suite checks actual proposals and ballots, edits
and retained identities, results, quorum, touch input and backup integrity in
both the distribution and the website build. Tests and screenshots use private
displays and disposable databases.
Online multi-device participation remains a separate feature. Before exposing
it, the server needs process/proposal/ballot routes, proof of identity,
@@ -39,5 +45,5 @@ controls. Do not restore old compatibility clients to provide them.
Android builds still need device testing for keyboard, lifecycle, insets and
accessibility. Signed distribution and hosted website publication are separate
from passing local build checks. Visual assets should be refreshed from the
maintained interface when preparing a public release.
from passing local build checks. Website screenshots come from the maintained
browser interface.
@@ -1,6 +1,3 @@
<resources>
<string name="app_name">Ukuvota</string>
<string name="share_chooser_title">Share Ukuvota link</string>
<string name="qr_share_failed">Could not share QR code.</string>
<string name="qr_scan_unavailable">No QR scanner app is installed. Paste the link instead.</string>
</resources>
+6 -3
View File
@@ -91,9 +91,6 @@ Minuty
[create_process_button]
Vytvořit proces
---
[collect_title]
Sbírat návrhy
---
[proposal_phase_label]
Fáze návrhů
---
@@ -364,3 +361,9 @@ Rozhodnutí jsou uložena v tomto zařízení. Online sdílení zatím není př
[next_participant]
Další účastník
---
[backup_button]
Stáhnout zálohu
---
[retry_save_button]
Zkusit uložit znovu
---
+6 -3
View File
@@ -91,9 +91,6 @@ Minuten
[create_process_button]
Prozess erstellen
---
[collect_title]
Vorschläge sammeln
---
[proposal_phase_label]
Vorschlagsphase
---
@@ -367,3 +364,9 @@ Entscheidungen werden auf diesem Gerät gespeichert. Online-Teilen ist noch nich
[next_participant]
Nächste teilnehmende Person
---
[backup_button]
Sicherung herunterladen
---
[retry_save_button]
Erneut speichern
---
+6 -3
View File
@@ -91,9 +91,6 @@ Minutes
[create_process_button]
Create Process
---
[collect_title]
Collect Proposals
---
[proposal_phase_label]
Proposal phase
---
@@ -208,3 +205,9 @@ Decisions are stored on this device. Online sharing is not connected yet.
[next_participant]
Next participant
---
[backup_button]
Download backup
---
[retry_save_button]
Retry saving
---
+6 -3
View File
@@ -91,9 +91,6 @@ Minutos
[create_process_button]
Crear proceso
---
[collect_title]
Recoger propuestas
---
[proposal_phase_label]
Fase de propuestas
---
@@ -367,3 +364,9 @@ Las decisiones se guardan en este dispositivo. Compartir en línea aún no está
[next_participant]
Siguiente participante
---
[backup_button]
Descargar copia de seguridad
---
[retry_save_button]
Reintentar guardar
---
+6 -3
View File
@@ -91,9 +91,6 @@ Minutes
[create_process_button]
Créer le processus
---
[collect_title]
Collecter les propositions
---
[proposal_phase_label]
Phase de propositions
---
@@ -367,3 +364,9 @@ Les décisions sont conservées sur cet appareil. Le partage en ligne ne fonctio
[next_participant]
Participant suivant
---
[backup_button]
Télécharger la sauvegarde
---
[retry_save_button]
Réessayer l’enregistrement
---
+6 -3
View File
@@ -91,9 +91,6 @@ Menit
[create_process_button]
Buat Proses
---
[collect_title]
Kumpulkan Proposal
---
[proposal_phase_label]
Fase proposal
---
@@ -364,3 +361,9 @@ Keputusan disimpan di perangkat ini. Berbagi daring belum terhubung.
[next_participant]
Peserta berikutnya
---
[backup_button]
Unduh cadangan
---
[retry_save_button]
Coba simpan lagi
---
+6 -3
View File
@@ -91,9 +91,6 @@ Minuti
[create_process_button]
Crea processo
---
[collect_title]
Raccogli proposte
---
[proposal_phase_label]
Fase proposte
---
@@ -364,3 +361,9 @@ Le decisioni sono salvate su questo dispositivo. La condivisione online non è a
[next_participant]
Partecipante successivo
---
[backup_button]
Scarica backup
---
[retry_save_button]
Riprova a salvare
---
+6 -3
View File
@@ -91,9 +91,6 @@
[create_process_button]
プロセスを作成
---
[collect_title]
提案を集める
---
[proposal_phase_label]
提案フェーズ
---
@@ -364,3 +361,9 @@ Status quo が維持されます
[next_participant]
次の参加者
---
[backup_button]
バックアップをダウンロード
---
[retry_save_button]
保存を再試行
---
+6 -3
View File
@@ -91,9 +91,6 @@
[create_process_button]
프로세스 만들기
---
[collect_title]
제안 모으기
---
[proposal_phase_label]
제안 단계
---
@@ -364,3 +361,9 @@ Status quo가 유지됩니다
[next_participant]
다음 참여자
---
[backup_button]
백업 다운로드
---
[retry_save_button]
저장 다시 시도
---
+6 -3
View File
@@ -91,9 +91,6 @@ Minutos
[create_process_button]
Criar processo
---
[collect_title]
Coletar propostas
---
[proposal_phase_label]
Fase de propostas
---
@@ -364,3 +361,9 @@ As decisões ficam neste dispositivo. O compartilhamento on-line ainda não est
[next_participant]
Próximo participante
---
[backup_button]
Baixar cópia de segurança
---
[retry_save_button]
Tentar salvar novamente
---
+6 -3
View File
@@ -91,9 +91,6 @@
[create_process_button]
Создать процесс
---
[collect_title]
Собрать предложения
---
[proposal_phase_label]
Фаза предложений
---
@@ -364,3 +361,9 @@ Status quo и «Повторить процесс» всегда есть сре
[next_participant]
Следующий участник
---
[backup_button]
Скачать резервную копию
---
[retry_save_button]
Повторить сохранение
---
+6 -3
View File
@@ -91,9 +91,6 @@
[create_process_button]
创建流程
---
[collect_title]
收集提案
---
[proposal_phase_label]
提案阶段
---
@@ -364,3 +361,9 @@ Status quo 和“重复流程”始终是可选项。
[next_participant]
下一位参与者
---
[backup_button]
下载备份
---
[retry_save_button]
重试保存
---
-10
View File
@@ -1,10 +0,0 @@
# Native make shim. The canonical build is the GNU Makefile.
GMAKE ?= gmake
.MAIN: all
all:
$(GMAKE) -f Makefile $@
.DEFAULT:
$(GMAKE) -f Makefile $@
+10
View File
@@ -2,10 +2,15 @@
"""Reject the retired C/Kryon UI and ambiguous dependency imports."""
from pathlib import Path
import re
import subprocess
root = Path(__file__).resolve().parents[1]
local_modules = {p.stem for p in (root / "src").glob("*.zi")}
errors = []
tracked = subprocess.check_output(['git', 'ls-files'], cwd=root, text=True).splitlines()
for name in tracked:
if name == '.gitmodules' or name.startswith('vendor/'):
errors.append(f'{name}: dependencies must use the package lock')
for base in ("src", "tests"):
for path in (root / base).rglob("*"):
if not path.is_file():
@@ -14,9 +19,14 @@ for base in ("src", "tests"):
errors.append(f"{path.relative_to(root)}: maintained app code must be Ziran")
if path.suffix != ".zi":
continue
if re.search(r'\b(?:ParseProcessDetail|BallotReplaceId|StorageMarkSynced|StoragePendingVotes|StoragePendingProposals|BrowserScriptInt|BrowserScript)\s*::', path.read_text()):
errors.append(f"{path.relative_to(root)}: retired server or eval helper")
for module in re.findall(r'#import\s+"([^"]+)"', path.read_text()):
if "/" not in module and module not in local_modules:
errors.append(f"{path.relative_to(root)}: qualify dependency {module}")
for name in ('SyncNetwork.java', 'ShareProvider.java', 'android_bridge.h'):
if any((root / 'droid/app/src/main').rglob(name)):
errors.append(f'{name}: retired Android bridge')
if errors:
raise SystemExit("\n".join(errors))
print("Maintained source uses Ziran and explicit package imports")
+2 -1
View File
@@ -5,7 +5,8 @@ import zipfile
root = Path(__file__).resolve().parents[1]
web = root / 'build/dist/web'
if not all((web / name).is_file() for name in ('index.html', 'index.js', 'index.wasm')):
required = ('index.html', 'index.js', 'index.wasm', 'uku-logo.svg', 'browser-input.js')
if not all((web / name).is_file() for name in required):
raise SystemExit('Build the web profile first: make web')
for name in ('uku-web.zip', 'uku-itch-html5.zip'):
with zipfile.ZipFile(root / 'build/dist' / name, 'w', zipfile.ZIP_DEFLATED) as archive:
+1
View File
@@ -36,4 +36,5 @@ mkdir -p build/web/c
-sENVIRONMENT=web --shell-file src/web_shell.html \
-o build/dist/web/index.html
cp web-assets/uku-logo.svg build/dist/web/
cp web-assets/browser-input.js build/dist/web/
python3 scripts/package-web.py
+1 -1
View File
@@ -94,7 +94,7 @@ write_web_app_csp_html() {
src=$1
dst=$2
cache_version=$(date +%s)
csp="default-src 'self' data: blob:; connect-src 'self' https: wss:; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; worker-src 'self' 'unsafe-eval' 'unsafe-inline' data: blob:; img-src 'self' data: blob:; media-src 'self' data: blob:; object-src 'none'"
csp="default-src 'self' data: blob:; connect-src 'self'; script-src 'self' 'wasm-unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; object-src 'none'"
meta="<meta http-equiv=\"Content-Security-Policy\" content=\"$csp\">"
python3 - "$src" "$dst" "$meta" "$cache_version" <<'PYTHON'
Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 49 KiB

+9
View File
@@ -13,6 +13,9 @@ using UI :: #import "kryon/Widgets";
#import "ui_kit"
#import "kryon/ScrollDevice"
#import "std/date_time_linux"
#if #defined(PLATFORM_WEB) {
#import "browser_input"
}
initialized: bool;
storage_ready: bool;
@@ -59,6 +62,9 @@ Frame :: (session: Session, viewport: Rectangle) -> s32 {
viewport.height -= height
}
now := UnixNow()
#if #defined(PLATFORM_WEB) {
BrowserInputsBegin(viewport)
}
if screen == ScreenId.ScreenHome {
HomeView(session, viewport, now)
} else if screen == ScreenId.ScreenCreate {
@@ -70,5 +76,8 @@ Frame :: (session: Session, viewport: Rectangle) -> s32 {
} else {
ManualView(session, viewport)
}
#if #defined(PLATFORM_WEB) {
BrowserInputsEnd()
}
return 0
}
-42
View File
@@ -144,45 +144,3 @@ BallotAppend :: (output: []u8, length: s64, id: string, score: s32) -> s64 {
length = TextAppend(output, length, "=")
return BallotAppendScore(output, length, score)
}
// The ballot with every entry for `old_id` renamed to `new_id`, as when a
// locally drafted proposal receives its server id.
BallotReplaceId :: (text: string, old_id: string, new_id: string, output: []u8) -> s64 {
if output.count == 0 {
return -1
}
output[0] = cast(u8)0
length: s64 = 0
at: s64 = 0
while at < text.count && length >= 0 {
entry := BallotEntryAt(text, at)
if !entry.valid {
break
}
if BallotIdIs(text, entry.id_start, entry.id_end, old_id) {
length = BallotAppend(output, length, new_id, entry.score)
} else {
length = BallotAppendRange(output, length, text, entry.id_start, entry.id_end, entry.score)
}
at = entry.next
}
return length
}
BallotAppendRange :: (output: []u8, length: s64, text: string, start: s64, end: s64, score: s32) -> s64 {
if length > 0 {
length = TextAppend(output, length, ";")
}
if length < 0 || length + (end - start) + 1 > output.count {
return -1
}
index := start
while index < end {
output[length] = text[index]
length += 1
index += 1
}
output[length] = cast(u8)0
length = TextAppend(output, length, "=")
return BallotAppendScore(output, length, score)
}
+57
View File
@@ -0,0 +1,57 @@
// App host glue using Ziran's public browser API. Kryon still draws fields;
// the DOM supplies native text editing and reports byte-based selections.
#import "std/web"
#import "std/text_buffer"
#import "locale"
using UI :: #import "kryon/Widgets";
BrowserFieldState :: struct {
cursor: s32
anchor: s32
focused: bool
committed: bool
}
BrowserInputsBegin :: (viewport: Rectangle) {
scope := WebScope()
args: [4]WebValue
args[0] = WebNumber(cast(float64)viewport.y + 56.0)
args[1] = WebNumber(cast(float64)viewport.height - 56.0)
args[2] = WebText(Tr("backup_button"))
args[3] = WebText(Tr("retry_save_button"))
unused WebCall(WebModule, WebName("beginFields"), *args[0], 4)
WebEnd(scope)
}
BrowserInputsEnd :: () {
scope := WebScope()
unused WebCall0(WebModule, WebName("endFields"))
WebEnd(scope)
}
BrowserFieldRead :: (id: s32, label: string, placeholder: string, buffer: []u8, bounds: Rectangle) -> BrowserFieldState {
scope := WebScope()
args: [9]WebValue
args[0] = WebNumber(cast(float64)id)
args[1] = WebText(label)
args[2] = WebText(placeholder)
args[3] = WebText(TextUntilNul(buffer))
args[4] = WebNumber(cast(float64)buffer.count - 1.0)
args[5] = WebNumber(cast(float64)bounds.x)
args[6] = WebNumber(cast(float64)bounds.y)
args[7] = WebNumber(cast(float64)bounds.width)
args[8] = WebNumber(cast(float64)bounds.height)
result := WebAsObject(WebCall(WebModule, WebName("inputField"), *args[0], 9))
state: BrowserFieldState
if result != 0 {
text := WebGetObject(result, WebName("value"))
// End the model's borrow before copying the browser edit into it.
unused WebCopyString(text, buffer)
state.cursor = cast(s32)WebGetNumber(result, WebName("cursor"))
state.anchor = cast(s32)WebGetNumber(result, WebName("anchor"))
state.focused = WebAsBool(WebGet(result, WebName("focused")))
state.committed = WebAsBool(WebGet(result, WebName("committed")))
}
WebEnd(scope)
return state
}
+36 -18
View File
@@ -32,6 +32,8 @@ new_proposal_description: [420]u8;
collect_status: [160]u8;
collect_scroll: s32;
collect_content_height: s32 = 900;
collect_phase: Phase;
collect_phase_known: bool;
ClearBallot :: () {
index: s32 = 0
@@ -58,6 +60,7 @@ CollectOpened :: () {
voter_name = .{}
collect_status[0] = cast(u8)0
collect_scroll = 0
collect_phase_known = false
}
}
@@ -367,11 +370,6 @@ VerdictText :: (verdict: VerdictResult, quorum: s32, output: []u8) -> string {
ResultRow :: (session: Session, rank: s32, leading: bool, proposal_index: s32, tally: ProposalTally, weight: s32, x: float32, y: float32, width: float32) -> float32 {
proposal := process.proposals[proposal_index]
resisted := tally.vote_count > 0 && tally.negative_total < 0 && -tally.negative_total >= tally.positive_total
height: float32 = 76.0
if resisted {
height = 96.0
}
UiPanel(session, cast(u64)(7600 + rank), Rectangle.{x, y, width, height})
title: [256]u8
digits: [24]u8
length := TextAppend(title[:], 0, FormatInteger(cast(s64)rank, digits[:]))
@@ -383,7 +381,6 @@ ResultRow :: (session: Session, rank: s32, leading: bool, proposal_index: s32, t
if NegativeWeightIsInfinite(weight) && tally.negative_total <= -cast(s64)NEGATIVE_WEIGHT_INFINITY {
length = TextAppend(title[:], length, Tr(" - vetoed"))
}
UiText(session, TextUntilNul(title[:]), Rectangle.{x + 14.0, y + 12.0, width - 90.0, 22.0}, 16)
meta: [256]u8
average: [24]u8
length = TextAppend(meta[:], 0, Tr("total"))
@@ -405,9 +402,23 @@ ResultRow :: (session: Session, rank: s32, leading: bool, proposal_index: s32, t
length = TextAppend(meta[:], length, Tr("avg"))
length = TextAppend(meta[:], length, " ")
length = TextAppend(meta[:], length, FormatAverage(tally.total, tally.vote_count, average[:]))
UiText(session, TextUntilNul(meta[:]), Rectangle.{x + 14.0, y + 42.0, width - 90.0, 18.0}, 13)
inner := width - 90.0
title_height := UiTextHeight(TextUntilNul(title[:]), inner, 16)
meta_height := UiTextHeight(TextUntilNul(meta[:]), inner, 13)
warning_height: float32 = 0.0
if resisted {
UiText(session, Tr("resistance at least equals support"), Rectangle.{x + 14.0, y + 64.0, width - 90.0, 18.0}, 13)
warning_height = UiTextHeight(Tr("resistance at least equals support"), inner, 13) + 8.0
}
height := 12.0 + title_height + 8.0 + meta_height + warning_height + 12.0
if height < 76.0 {
height = 76.0
}
UiPanel(session, cast(u64)(7600 + rank), Rectangle.{x, y, width, height})
text_y := y + 12.0
text_y += UiParagraph(session, TextUntilNul(title[:]), x + 14.0, text_y, inner, 16) + 8.0
text_y += UiParagraph(session, TextUntilNul(meta[:]), x + 14.0, text_y, inner, 13)
if resisted {
unused UiParagraph(session, Tr("resistance at least equals support"), x + 14.0, text_y + 8.0, inner, 13)
}
// The average score, rounded, in a badge at the end of the row.
badge: [16]u8
@@ -535,7 +546,8 @@ ProposalList :: (session: Session, x: float32, y: float32, width: float32) -> fl
author := TextUntilNul(proposal.display_name[:])
description := TextUntilNul(proposal.description[:])
inner := width - 28.0
height: float32 = 44.0
title_height := UiTextHeight(TextUntilNul(proposal.title[:]), inner, 16)
height := title_height + 22.0
if author.count > 0 {
height += 22.0
}
@@ -546,8 +558,7 @@ ProposalList :: (session: Session, x: float32, y: float32, width: float32) -> fl
}
UiPanel(session, cast(u64)(8000 + index), Rectangle.{x, y, width, height})
line_y := y + 12.0
UiText(session, TextUntilNul(proposal.title[:]), Rectangle.{x + 14.0, line_y, inner, 22.0}, 16)
line_y += 26.0
line_y += UiParagraph(session, TextUntilNul(proposal.title[:]), x + 14.0, line_y, inner, 16) + 8.0
if author.count > 0 {
UiText(session, author, Rectangle.{x + 14.0, line_y, inner, 18.0}, 13)
line_y += 22.0
@@ -562,18 +573,26 @@ ProposalList :: (session: Session, x: float32, y: float32, width: float32) -> fl
}
CollectView :: (session: Session, viewport: Rectangle, now: s64) {
if UiSubPageBar(session, viewport, Tr("collect_title")) {
screen = ScreenId.ScreenHome
unused StorageLoadProcesses()
loaded_row = -1
return
}
if open_row < 0 || open_row >= process_row_count {
screen = ScreenId.ScreenHome
return
}
CollectOpened()
row := process_rows[open_row]
phase := ProcessPhaseAt(row.created_at, row.proposal_minutes, row.voting_minutes, now).phase
if !collect_phase_known || phase != collect_phase {
collect_phase = phase
collect_phase_known = true
collect_scroll = 0
focused_field = -1
collect_status = .{}
}
if UiSubPageBar(session, viewport, PhaseLabel(phase)) {
screen = ScreenId.ScreenHome
unused StorageLoadProcesses()
loaded_row = -1
return
}
props: ScrollProps
props.key = cast(u64)7000
props.bounds = Rectangle.{viewport.x, viewport.y + SUB_PAGE_BAR_HEIGHT, viewport.width, viewport.height - SUB_PAGE_BAR_HEIGHT}
@@ -591,7 +610,6 @@ CollectView :: (session: Session, viewport: Rectangle, now: s64) {
top := scroll.content.y + 20.0
y := top
y += Header(session, row, now, x, y, width)
phase := ProcessPhaseAt(row.created_at, row.proposal_minutes, row.voting_minutes, now).phase
if phase == Phase.PhaseProposal {
y += ProposalSection(session, row, now, x, y, width)
} else if phase == Phase.PhaseVoting {
+11 -10
View File
@@ -264,14 +264,20 @@ ProposalsStep :: (session: Session, x: float32, y: float32, width: float32) -> f
while index < draft.proposal_count {
proposal := draft.proposals[index]
has_description := proposal.description[0] != cast(u8)0
height: float32 = 52.0
inner := width - 140.0
title_height := UiTextHeight(TextUntilNul(proposal.title[:]), inner, 16)
description_height: float32 = 0.0
if has_description {
height = 76.0
description_height = UiTextHeight(TextUntilNul(proposal.description[:]), inner, 13) + 8.0
}
height := 28.0 + title_height + description_height
if height < 52.0 {
height = 52.0
}
UiPanel(session, cast(u64)(2600 + index), Rectangle.{x, y, width, height})
UiText(session, TextUntilNul(proposal.title[:]), Rectangle.{x + 14.0, y + 14.0, width - 140.0, 22.0}, 16)
unused UiParagraph(session, TextUntilNul(proposal.title[:]), x + 14.0, y + 14.0, inner, 16)
if has_description {
UiText(session, TextUntilNul(proposal.description[:]), Rectangle.{x + 14.0, y + 42.0, width - 140.0, 18.0}, 13)
unused UiParagraph(session, TextUntilNul(proposal.description[:]), x + 14.0, y + 22.0 + title_height, inner, 13)
}
if UiButton(session, 2700 + index, Tr("Delete"), Rectangle.{x + width - 110.0, y + 8.0, 100.0, 36.0}, false) {
RemoveDraftProposal(index)
@@ -350,10 +356,6 @@ SaveDraft :: (now: s64) -> bool {
row.voting_minutes = DurationMinutes(draft.voting_days, draft.voting_hours, draft.voting_minutes)
row.negative_weight = draft.negative_weight
row.quorum_votes = draft.quorum_votes
SetText(row.visibility[:], "private")
SetText(row.proposal_visibility[:], "participants")
SetText(row.proposal_access[:], "participants")
SetText(row.voting_access[:], "participants")
row.created_at = now
ProcessClear()
if draft.voting_only {
@@ -384,8 +386,7 @@ ReviewLine :: (session: Session, label: string, value: string, x: float32, y: fl
length := TextAppend(line[:], 0, label)
length = TextAppend(line[:], length, ": ")
length = TextAppend(line[:], length, value)
UiText(session, TextUntilNul(line[:]), Rectangle.{x, y, width, 20.0}, 15)
return 30.0
return UiParagraph(session, TextUntilNul(line[:]), x, y, width, 15) + 10.0
}
ReviewStep :: (session: Session, x: float32, y: float32, width: float32, now: s64) -> float32 {
+24 -12
View File
@@ -35,7 +35,6 @@ LocaleFill_en :: () {
LocaleAdd("hours_label", "Hours")
LocaleAdd("minutes_label", "Minutes")
LocaleAdd("create_process_button", "Create Process")
LocaleAdd("collect_title", "Collect Proposals")
LocaleAdd("proposal_phase_label", "Proposal phase")
LocaleAdd("voting_phase_label", "Voting phase")
LocaleAdd("results_phase_label", "Results ready")
@@ -74,6 +73,8 @@ LocaleFill_en :: () {
LocaleAdd("persistence_error", "Could not save browser data. Keep this page open and export a backup.")
LocaleAdd("local_mode_hint", "Decisions are stored on this device. Online sharing is not connected yet.")
LocaleAdd("next_participant", "Next participant")
LocaleAdd("backup_button", "Download backup")
LocaleAdd("retry_save_button", "Retry saving")
}
LocaleFill_es :: () {
@@ -106,7 +107,6 @@ LocaleFill_es :: () {
LocaleAdd("hours_label", "Horas")
LocaleAdd("minutes_label", "Minutos")
LocaleAdd("create_process_button", "Crear proceso")
LocaleAdd("collect_title", "Recoger propuestas")
LocaleAdd("proposal_phase_label", "Fase de propuestas")
LocaleAdd("voting_phase_label", "Fase de votación")
LocaleAdd("results_phase_label", "Resultados listos")
@@ -198,6 +198,8 @@ LocaleFill_es :: () {
LocaleAdd("persistence_error", "No se pudieron guardar los datos del navegador. Mantén esta página abierta y exporta una copia de seguridad.")
LocaleAdd("local_mode_hint", "Las decisiones se guardan en este dispositivo. Compartir en línea aún no está conectado.")
LocaleAdd("next_participant", "Siguiente participante")
LocaleAdd("backup_button", "Descargar copia de seguridad")
LocaleAdd("retry_save_button", "Reintentar guardar")
}
LocaleFill_cs :: () {
@@ -230,7 +232,6 @@ LocaleFill_cs :: () {
LocaleAdd("hours_label", "Hodiny")
LocaleAdd("minutes_label", "Minuty")
LocaleAdd("create_process_button", "Vytvořit proces")
LocaleAdd("collect_title", "Sbírat návrhy")
LocaleAdd("proposal_phase_label", "Fáze návrhů")
LocaleAdd("voting_phase_label", "Fáze hlasování")
LocaleAdd("results_phase_label", "Výsledky připraveny")
@@ -321,6 +322,8 @@ LocaleFill_cs :: () {
LocaleAdd("persistence_error", "Data prohlížeče se nepodařilo uložit. Nechte stránku otevřenou a exportujte zálohu.")
LocaleAdd("local_mode_hint", "Rozhodnutí jsou uložena v tomto zařízení. Online sdílení zatím není připojeno.")
LocaleAdd("next_participant", "Další účastník")
LocaleAdd("backup_button", "Stáhnout zálohu")
LocaleAdd("retry_save_button", "Zkusit uložit znovu")
}
LocaleFill_de :: () {
@@ -353,7 +356,6 @@ LocaleFill_de :: () {
LocaleAdd("hours_label", "Stunden")
LocaleAdd("minutes_label", "Minuten")
LocaleAdd("create_process_button", "Prozess erstellen")
LocaleAdd("collect_title", "Vorschläge sammeln")
LocaleAdd("proposal_phase_label", "Vorschlagsphase")
LocaleAdd("voting_phase_label", "Abstimmungsphase")
LocaleAdd("results_phase_label", "Ergebnisse bereit")
@@ -445,6 +447,8 @@ LocaleFill_de :: () {
LocaleAdd("persistence_error", "Browserdaten konnten nicht gespeichert werden. Lass diese Seite geöffnet und exportiere eine Sicherung.")
LocaleAdd("local_mode_hint", "Entscheidungen werden auf diesem Gerät gespeichert. Online-Teilen ist noch nicht verbunden.")
LocaleAdd("next_participant", "Nächste teilnehmende Person")
LocaleAdd("backup_button", "Sicherung herunterladen")
LocaleAdd("retry_save_button", "Erneut speichern")
}
LocaleFill_fr :: () {
@@ -477,7 +481,6 @@ LocaleFill_fr :: () {
LocaleAdd("hours_label", "Heures")
LocaleAdd("minutes_label", "Minutes")
LocaleAdd("create_process_button", "Créer le processus")
LocaleAdd("collect_title", "Collecter les propositions")
LocaleAdd("proposal_phase_label", "Phase de propositions")
LocaleAdd("voting_phase_label", "Phase de vote")
LocaleAdd("results_phase_label", "Résultats prêts")
@@ -569,6 +572,8 @@ LocaleFill_fr :: () {
LocaleAdd("persistence_error", "Impossible de sauvegarder les données du navigateur. Gardez cette page ouverte et exportez une sauvegarde.")
LocaleAdd("local_mode_hint", "Les décisions sont conservées sur cet appareil. Le partage en ligne ne fonctionne pas encore.")
LocaleAdd("next_participant", "Participant suivant")
LocaleAdd("backup_button", "Télécharger la sauvegarde")
LocaleAdd("retry_save_button", "Réessayer l’enregistrement")
}
LocaleFill_id :: () {
@@ -601,7 +606,6 @@ LocaleFill_id :: () {
LocaleAdd("hours_label", "Jam")
LocaleAdd("minutes_label", "Menit")
LocaleAdd("create_process_button", "Buat Proses")
LocaleAdd("collect_title", "Kumpulkan Proposal")
LocaleAdd("proposal_phase_label", "Fase proposal")
LocaleAdd("voting_phase_label", "Fase pemungutan suara")
LocaleAdd("results_phase_label", "Hasil siap")
@@ -692,6 +696,8 @@ LocaleFill_id :: () {
LocaleAdd("persistence_error", "Data peramban tidak dapat disimpan. Biarkan halaman ini terbuka dan ekspor cadangan.")
LocaleAdd("local_mode_hint", "Keputusan disimpan di perangkat ini. Berbagi daring belum terhubung.")
LocaleAdd("next_participant", "Peserta berikutnya")
LocaleAdd("backup_button", "Unduh cadangan")
LocaleAdd("retry_save_button", "Coba simpan lagi")
}
LocaleFill_it :: () {
@@ -724,7 +730,6 @@ LocaleFill_it :: () {
LocaleAdd("hours_label", "Ore")
LocaleAdd("minutes_label", "Minuti")
LocaleAdd("create_process_button", "Crea processo")
LocaleAdd("collect_title", "Raccogli proposte")
LocaleAdd("proposal_phase_label", "Fase proposte")
LocaleAdd("voting_phase_label", "Fase voto")
LocaleAdd("results_phase_label", "Risultati pronti")
@@ -815,6 +820,8 @@ LocaleFill_it :: () {
LocaleAdd("persistence_error", "Impossibile salvare i dati del browser. Tieni aperta questa pagina ed esporta una copia di sicurezza.")
LocaleAdd("local_mode_hint", "Le decisioni sono salvate su questo dispositivo. La condivisione online non è ancora collegata.")
LocaleAdd("next_participant", "Partecipante successivo")
LocaleAdd("backup_button", "Scarica backup")
LocaleAdd("retry_save_button", "Riprova a salvare")
}
LocaleFill_pt :: () {
@@ -847,7 +854,6 @@ LocaleFill_pt :: () {
LocaleAdd("hours_label", "Horas")
LocaleAdd("minutes_label", "Minutos")
LocaleAdd("create_process_button", "Criar processo")
LocaleAdd("collect_title", "Coletar propostas")
LocaleAdd("proposal_phase_label", "Fase de propostas")
LocaleAdd("voting_phase_label", "Fase de votação")
LocaleAdd("results_phase_label", "Resultados prontos")
@@ -938,6 +944,8 @@ LocaleFill_pt :: () {
LocaleAdd("persistence_error", "Não foi possível salvar os dados do navegador. Mantenha esta página aberta e exporte uma cópia de segurança.")
LocaleAdd("local_mode_hint", "As decisões ficam neste dispositivo. O compartilhamento on-line ainda não está conectado.")
LocaleAdd("next_participant", "Próximo participante")
LocaleAdd("backup_button", "Baixar cópia de segurança")
LocaleAdd("retry_save_button", "Tentar salvar novamente")
}
LocaleFill_ru :: () {
@@ -970,7 +978,6 @@ LocaleFill_ru :: () {
LocaleAdd("hours_label", "Часы")
LocaleAdd("minutes_label", "Минуты")
LocaleAdd("create_process_button", "Создать процесс")
LocaleAdd("collect_title", "Собрать предложения")
LocaleAdd("proposal_phase_label", "Фаза предложений")
LocaleAdd("voting_phase_label", "Фаза голосования")
LocaleAdd("results_phase_label", "Результаты готовы")
@@ -1061,6 +1068,8 @@ LocaleFill_ru :: () {
LocaleAdd("persistence_error", "Не удалось сохранить данные браузера. Оставьте страницу открытой и экспортируйте резервную копию.")
LocaleAdd("local_mode_hint", "Решения хранятся на этом устройстве. Обмен через интернет пока не подключён.")
LocaleAdd("next_participant", "Следующий участник")
LocaleAdd("backup_button", "Скачать резервную копию")
LocaleAdd("retry_save_button", "Повторить сохранение")
}
LocaleFill_ja :: () {
@@ -1093,7 +1102,6 @@ LocaleFill_ja :: () {
LocaleAdd("hours_label", "時間")
LocaleAdd("minutes_label", "分")
LocaleAdd("create_process_button", "プロセスを作成")
LocaleAdd("collect_title", "提案を集める")
LocaleAdd("proposal_phase_label", "提案フェーズ")
LocaleAdd("voting_phase_label", "投票フェーズ")
LocaleAdd("results_phase_label", "結果の準備完了")
@@ -1184,6 +1192,8 @@ LocaleFill_ja :: () {
LocaleAdd("persistence_error", "ブラウザーのデータを保存できませんでした。このページを開いたままバックアップを書き出してください。")
LocaleAdd("local_mode_hint", "決定はこの端末に保存されます。オンライン共有はまだ接続されていません。")
LocaleAdd("next_participant", "次の参加者")
LocaleAdd("backup_button", "バックアップをダウンロード")
LocaleAdd("retry_save_button", "保存を再試行")
}
LocaleFill_ko :: () {
@@ -1216,7 +1226,6 @@ LocaleFill_ko :: () {
LocaleAdd("hours_label", "시간")
LocaleAdd("minutes_label", "분")
LocaleAdd("create_process_button", "프로세스 만들기")
LocaleAdd("collect_title", "제안 모으기")
LocaleAdd("proposal_phase_label", "제안 단계")
LocaleAdd("voting_phase_label", "투표 단계")
LocaleAdd("results_phase_label", "결과 준비됨")
@@ -1307,6 +1316,8 @@ LocaleFill_ko :: () {
LocaleAdd("persistence_error", "브라우저 데이터를 저장하지 못했습니다. 이 페이지를 열어 두고 백업을 내보내세요.")
LocaleAdd("local_mode_hint", "결정은 이 기기에 저장됩니다. 온라인 공유는 아직 연결되지 않았습니다.")
LocaleAdd("next_participant", "다음 참여자")
LocaleAdd("backup_button", "백업 다운로드")
LocaleAdd("retry_save_button", "저장 다시 시도")
}
LocaleFill_zh :: () {
@@ -1339,7 +1350,6 @@ LocaleFill_zh :: () {
LocaleAdd("hours_label", "小时")
LocaleAdd("minutes_label", "分钟")
LocaleAdd("create_process_button", "创建流程")
LocaleAdd("collect_title", "收集提案")
LocaleAdd("proposal_phase_label", "提案阶段")
LocaleAdd("voting_phase_label", "投票阶段")
LocaleAdd("results_phase_label", "结果已准备好")
@@ -1430,6 +1440,8 @@ LocaleFill_zh :: () {
LocaleAdd("persistence_error", "无法保存浏览器数据。请保持此页面打开并导出备份。")
LocaleAdd("local_mode_hint", "决策保存在此设备上。在线分享尚未连接。")
LocaleAdd("next_participant", "下一位参与者")
LocaleAdd("backup_button", "下载备份")
LocaleAdd("retry_save_button", "重试保存")
}
// Fills locale_filling for a language code; false for an unknown code.
+18 -11
View File
@@ -12,9 +12,7 @@ libc :: #system_library "libc";
EnvironmentRaw :: (name: *u8) -> *u8 #foreign libc "getenv";
#if #defined(PLATFORM_WEB) {
emscripten :: #system_library "emscripten";
BrowserScript :: (script: *u8) #foreign emscripten "emscripten_run_script";
BrowserScriptInt :: (script: *u8) -> s32 #foreign emscripten "emscripten_run_script_int";
#import "std/web"
}
#if #defined(ANDROID_BUILD) {
platform_api :: #system_library "platform_api";
@@ -106,23 +104,32 @@ DataPath :: () -> string {
PersistChanges :: () {
#if #defined(PLATFORM_WEB) {
script: [64]u8
if CopyCString("Module.saveUkuData();", script[:]) {
BrowserScript(*script[0])
}
scope := WebScope()
unused WebCall0(WebModule, WebName("saveUkuData"))
WebEnd(scope)
}
}
PersistenceFailed :: () -> bool {
#if #defined(PLATFORM_WEB) {
script: [64]u8
if CopyCString("Module.ukuSaveFailed ? 1 : 0", script[:]) {
return BrowserScriptInt(*script[0]) != 0
}
scope := WebScope()
failed := WebAsBool(WebGet(WebModule, WebName("ukuSaveFailed")))
WebEnd(scope)
return failed
}
return false
}
#if #defined(PLATFORM_WEB) {
BrowserPrefersDark :: () -> bool {
scope := WebScope()
query := WebAsObject(WebCall1(WebGlobal, WebName("matchMedia"), WebText("(prefers-color-scheme: dark)")))
dark := WebAsBool(WebGet(query, WebName("matches")))
WebEnd(scope)
return dark
}
}
ShowKeyboard :: (visible: bool) {
#if #defined(ANDROID_BUILD) {
AndroidKeyboard(ifx visible then 1 else 0)
+2 -203
View File
@@ -1,11 +1,9 @@
#import "std/json_scan"
#import "ballot"
#import "tally"
#import "std/text_buffer"
// A decision process as the Ukuvota server returns it: its settings, the
// proposals (consent and collection processes) or options (ranked
// processes), and each participant's scores.
// A stored decision, its proposals and each participant's scores.
// Existing ranked decisions retain their saved options.
MAX_PROPOSALS :: 64
MAX_OPTIONS :: 5
@@ -19,21 +17,12 @@ ProcessType :: enum {
ProcessSettings :: struct {
id: [40]u8
owner: [65]u8
type: ProcessType
topic: [180]u8
description: [420]u8
visibility: [16]u8
proposal_visibility: [16]u8
proposal_access: [16]u8
voting_access: [16]u8
outcome: [120]u8
review_at: [64]u8
created_at: [64]u8
proposal_minutes: s32
voting_minutes: s32
negative_weight: s32
quorum_percent: s32
quorum_votes: s32
}
@@ -122,33 +111,6 @@ SetText :: (output: []u8, value: string) {
output[length] = cast(u8)0
}
// Reads the string member `name` of the object at `object_at` into output.
// Returns false, with output empty, when it is missing or not a string.
ReadTextField :: (json: string, object_at: s32, name: string, output: []u8) -> bool {
if output.count == 0 {
return false
}
output[0] = cast(u8)0
at := FieldAt(json, object_at, name)
if at < 0 {
return false
}
return ReadStringText(json, at, output) > 0
}
// Reads the whole-number member `name`, or returns fallback.
ReadNumberField :: (json: string, object_at: s32, name: string, fallback: s32) -> s32 {
at := FieldAt(json, object_at, name)
if at < 0 {
return fallback
}
number := ReadNumber(json, at)
if !number.valid {
return fallback
}
return cast(s32)number.value
}
ProcessClear :: () {
process = ProcessDetail.{}
}
@@ -222,169 +184,6 @@ ProcessOptionFind :: (id: string) -> s32 {
return -1
}
ParseSettings :: (json: string) {
settings: ProcessSettings
unused ReadTextField(json, 0, "id", settings.id[:])
unused ReadTextField(json, 0, "owner_user_id_hash", settings.owner[:])
type_key: [40]u8
if ReadTextField(json, 0, "type", type_key[:]) {
settings.type = ProcessTypeFromKey(TextUntilNul(type_key[:]))
}
unused ReadTextField(json, 0, "title", settings.topic[:])
unused ReadTextField(json, 0, "description", settings.description[:])
unused ReadTextField(json, 0, "outcome", settings.outcome[:])
unused ReadTextField(json, 0, "review_at", settings.review_at[:])
unused ReadTextField(json, 0, "created_at", settings.created_at[:])
// Every permission defaults to public.
if !ReadTextField(json, 0, "visibility", settings.visibility[:]) {
SetText(settings.visibility[:], "public")
}
if !ReadTextField(json, 0, "proposal_visibility", settings.proposal_visibility[:]) {
SetText(settings.proposal_visibility[:], "public")
}
if !ReadTextField(json, 0, "proposal_access", settings.proposal_access[:]) {
SetText(settings.proposal_access[:], "public")
}
if !ReadTextField(json, 0, "voting_access", settings.voting_access[:]) {
SetText(settings.voting_access[:], "public")
}
settings.proposal_minutes = ReadNumberField(json, 0, "proposal_minutes", 0)
settings.voting_minutes = ReadNumberField(json, 0, "voting_minutes", 0)
settings.quorum_percent = ReadNumberField(json, 0, "quorum_percent", 0)
settings.quorum_votes = ReadNumberField(json, 0, "quorum_votes", 0)
settings.negative_weight = ReadNumberField(json, 0, "negative_weight", 0)
if ProcessUsesNegativeWeight(settings.type) {
settings.negative_weight = NegativeWeightNormalize(settings.negative_weight)
}
process.settings = settings
}
ParseProposals :: (json: string) {
array := FieldAt(json, 0, "proposals")
count := ArrayCount(json, array)
element: s32 = 0
while element < count && process.proposal_count < MAX_PROPOSALS {
at := ElementAt(json, array, element)
proposal: Proposal
if ReadTextField(json, at, "id", proposal.id[:]) &&
ReadTextField(json, at, "title", proposal.title[:]) {
unused ReadTextField(json, at, "description", proposal.description[:])
unused ReadTextField(json, at, "author_user_id_hash", proposal.author[:])
if !ReadTextField(json, at, "display_name", proposal.display_name[:]) {
unused ReadTextField(json, at, "author_display_name", proposal.display_name[:])
}
process.proposals[process.proposal_count] = proposal
process.proposal_count += 1
}
element += 1
}
}
ParseOptions :: (json: string) {
array := FieldAt(json, 0, "options")
count := ArrayCount(json, array)
element: s32 = 0
while element < count && process.option_count < MAX_OPTIONS {
at := ElementAt(json, array, element)
option: Option
if ReadTextField(json, at, "id", option.id[:]) &&
ReadTextField(json, at, "label", option.label[:]) {
unused ReadTextField(json, at, "description", option.description[:])
process.options[process.option_count] = option
process.option_count += 1
}
element += 1
}
}
// Reads the "scores" object of the vote at `vote_at` into the participant's
// row, by proposal (or option) id. Unknown ids are ignored.
ParseVoteScores :: (json: string, vote_at: s32, participant: s32) {
scores_at := FieldAt(json, vote_at, "scores")
cursor := Space(json, scores_at)
if cursor < 0 || cursor >= cast(s32)json.count || json[cursor] != cast(u8)123 {
return
}
cursor = Space(json, cursor + 1)
options := ProcessHasOptions(process.settings.type)
id: [40]u8
while cursor < cast(s32)json.count && json[cursor] != cast(u8)125 {
key := ReadString(json, cursor)
if !key.valid {
return
}
unused ReadStringText(json, cursor, id[:])
cursor = Space(json, key.after)
if cursor >= cast(s32)json.count || json[cursor] != cast(u8)58 {
return
}
cursor = Space(json, cursor + 1)
number := ReadNumber(json, cursor)
if number.valid && ScoreIsValid(cast(s32)number.value) {
score := cast(s8)cast(s32)number.value
if options {
index := ProcessOptionFind(TextUntilNul(id[:]))
if index >= 0 {
process.option_scores[participant][index] = score
}
} else {
index := ProcessProposalFind(TextUntilNul(id[:]))
if index >= 0 {
process.proposal_scores[participant][index] = score
}
}
}
cursor = ValueEnd(json, cursor, 0)
if cursor < 0 {
return
}
cursor = Space(json, cursor)
if cursor < cast(s32)json.count && json[cursor] == cast(u8)44 {
cursor = Space(json, cursor + 1)
}
}
}
ParseVotes :: (json: string) {
array := FieldAt(json, 0, "votes")
count := ArrayCount(json, array)
element: s32 = 0
while element < count {
at := ElementAt(json, array, element)
voter: [65]u8
display_name: [80]u8
unused ReadTextField(json, at, "voter_user_id_hash", voter[:])
unused ReadTextField(json, at, "display_name", display_name[:])
participant := ProcessParticipantAdd(TextUntilNul(voter[:]), TextUntilNul(display_name[:]), true)
if participant >= 0 {
unused ReadTextField(json, at, "updated_at", process.participants[participant].updated_at[:])
ParseVoteScores(json, at, participant)
}
element += 1
}
}
// Replaces the current process with the one in `json`. Options come before
// proposals and proposals before votes, since votes refer to them by id.
// Proposal authors take part even before they vote.
ParseProcessDetail :: (json: string) -> bool {
ProcessClear()
if FieldAt(json, 0, "id") < 0 {
return false
}
ParseSettings(json)
ParseOptions(json)
ParseProposals(json)
ParseVotes(json)
index: s32 = 0
while index < process.proposal_count {
unused ProcessParticipantAdd(TextUntilNul(process.proposals[index].author[:]),
TextUntilNul(process.proposals[index].display_name[:]), false)
index += 1
}
return true
}
ProcessBallotCounts :: (index: s32) -> bool {
return process.participants[index].has_ballot && !process.participants[index].excluded
}
+22 -46
View File
@@ -10,8 +10,10 @@
#import "text_append"
#import "platform"
// Local decisions, ballots, account keys and preferences. Schema upgrades
// Local decisions, ballots, participant keys and preferences. Schema upgrades
// preserve data; unsupported schemas are refused without modifying them.
// Historical columns remain for stored-data preservation only. The active
// app uses local participant identities and stable proposal keys.
STORAGE_SCHEMA :: "create table if not exists processes (id text primary key, type text not null, phase text not null, topic text not null, description text not null, proposal_minutes integer not null, voting_minutes integer not null, negative_weight integer not null, quorum_votes integer not null default 0, visibility text not null default 'public', proposal_visibility text not null default 'public', proposal_access text not null default 'public', voting_access text not null default 'public', local_address text not null, created_at integer not null, synced integer not null default 0); create table if not exists options (id text primary key, process_id text not null, label text not null, description text not null, position integer not null, foreign key(process_id) references processes(id)); create table if not exists proposals (id integer primary key autoincrement, process_id text not null, author_user_id text not null default '', remote_id text not null default '', display_name text not null default '', title text not null, description text not null, created_at integer not null, synced integer not null default 0, foreign key(process_id) references processes(id)); create table if not exists votes (process_id text not null, voter_user_id text not null, display_name text not null, reason text not null, scores text not null, updated_at integer not null, synced integer not null default 0, primary key(process_id, voter_user_id), foreign key(process_id) references processes(id)); create table if not exists results (process_id text primary key, result_json text not null, computed_at integer not null, foreign key(process_id) references processes(id)); create table if not exists account (id integer primary key check(id = 1), public_id text not null, public_key text not null, private_key text not null); create table if not exists settings (key text primary key, value text not null); create table if not exists participants (process_id text not null, public_id text not null, public_key text not null, private_key text not null, primary key(process_id, public_id));"
@@ -23,10 +25,6 @@ StorageColumn :: struct {
database: *void;
StorageOpened :: () -> bool {
return database != null
}
StorageClose :: () {
if database != null {
unused SqliteClose(database)
@@ -120,6 +118,8 @@ StorageOpen :: (path: string) -> bool {
return false
}
ready := SqliteExecText(database, STORAGE_SCHEMA) == SQLITE_OK && StorageAddMissingColumns()
// Preserve identifiers written by earlier versions in the current key column.
ready = ready && SqliteExecText(database, "update proposals set proposal_key=remote_id where proposal_key='' and remote_id<>''") == SQLITE_OK
ready = ready && SqliteExecText(database, "commit") == SQLITE_OK
if !ready {
unused SqliteExecText(database, "rollback")
@@ -214,7 +214,6 @@ MAX_PROCESSES :: 128
// A process as the dashboard lists it.
ProcessRow :: struct {
id: [40]u8
local_address: [512]u8
owner: [65]u8
topic: [180]u8
description: [420]u8
@@ -223,10 +222,6 @@ ProcessRow :: struct {
voting_minutes: s32
negative_weight: s32
quorum_votes: s32
visibility: [16]u8
proposal_visibility: [16]u8
proposal_access: [16]u8
voting_access: [16]u8
created_at: s64
}
@@ -250,7 +245,7 @@ StorageLoadProcesses :: () -> s32 {
return 0
}
statement: *void = null
if SqlitePrepareText(database, "select id, type, topic, description, proposal_minutes, voting_minutes, negative_weight, visibility, local_address, created_at, quorum_votes, owner_user_id, proposal_visibility, proposal_access, voting_access from processes order by created_at desc limit ?", -1, *statement, null) != SQLITE_OK {
if SqlitePrepareText(database, "select id, type, topic, description, proposal_minutes, voting_minutes, negative_weight, created_at, quorum_votes, owner_user_id from processes order by created_at desc limit ?", -1, *statement, null) != SQLITE_OK {
return 0
}
unused SqliteBindInt(statement, 1, MAX_PROCESSES)
@@ -268,14 +263,9 @@ StorageLoadProcesses :: () -> s32 {
if ProcessUsesNegativeWeight(row.type) {
row.negative_weight = NegativeWeightNormalize(row.negative_weight)
}
StorageColumnText(statement, 7, "public", row.visibility[:])
StorageColumnText(statement, 8, "", row.local_address[:])
row.created_at = SqliteColumnInt64(statement, 9)
row.quorum_votes = SqliteColumnInt(statement, 10)
StorageColumnText(statement, 11, "", row.owner[:])
StorageColumnText(statement, 12, "public", row.proposal_visibility[:])
StorageColumnText(statement, 13, "public", row.proposal_access[:])
StorageColumnText(statement, 14, "public", row.voting_access[:])
row.created_at = SqliteColumnInt64(statement, 7)
row.quorum_votes = SqliteColumnInt(statement, 8)
StorageColumnText(statement, 9, "", row.owner[:])
process_rows[process_row_count] = row
process_row_count += 1
}
@@ -284,9 +274,9 @@ StorageLoadProcesses :: () -> s32 {
}
// Inserts a proposal and returns its local rowid, or -1.
StorageInsertProposal :: (process_id: string, author: string, display_name: string, title: string, description: string, created_at: s64, synced: bool) -> s64 {
StorageInsertProposal :: (process_id: string, author: string, display_name: string, title: string, description: string, created_at: s64) -> s64 {
statement: *void = null
if SqlitePrepareText(database, "insert into proposals(process_id, author_user_id, display_name, title, description, created_at, synced) values(?, ?, ?, ?, ?, ?, ?)", -1, *statement, null) != SQLITE_OK {
if SqlitePrepareText(database, "insert into proposals(process_id, author_user_id, display_name, title, description, created_at) values(?, ?, ?, ?, ?, ?)", -1, *statement, null) != SQLITE_OK {
return -1
}
unused SqliteBindTextString(statement, 1, process_id, -1)
@@ -295,7 +285,6 @@ StorageInsertProposal :: (process_id: string, author: string, display_name: stri
unused SqliteBindTextString(statement, 4, title, -1)
unused SqliteBindTextString(statement, 5, description, -1)
unused SqliteBindInt64(statement, 6, created_at)
unused SqliteBindInt(statement, 7, ifx synced then 1 else 0)
inserted := SqliteStep(statement) == SQLITE_DONE
unused SqliteFinalize(statement)
if !inserted {
@@ -337,7 +326,7 @@ StorageInsertOption :: (process_id: string, option: Option, position: s32) -> bo
}
StorageInsertStanding :: (process_id: string, owner: string, key: string, title: string, description: string, now: s64) -> bool {
rowid := StorageInsertProposal(process_id, owner, "", title, description, now, true)
rowid := StorageInsertProposal(process_id, owner, "", title, description, now)
if rowid < 0 {
return false
}
@@ -352,7 +341,7 @@ StorageInsertStanding :: (process_id: string, owner: string, key: string, title:
return saved
}
// The standing proposals of a new consent process that has none of its own.
// Standing proposals included in every new consent decision.
StandingProposals :: struct {
status_quo_title: string
status_quo_description: string
@@ -362,7 +351,7 @@ StandingProposals :: struct {
StorageInsertProcessRow :: (row: ProcessRow) -> bool {
statement: *void = null
if SqlitePrepareText(database, "insert into processes(id, type, phase, topic, description, proposal_minutes, voting_minutes, negative_weight, quorum_votes, visibility, proposal_visibility, proposal_access, voting_access, local_address, created_at, synced, owner_user_id) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)", -1, *statement, null) != SQLITE_OK {
if SqlitePrepareText(database, "insert into processes(id, type, phase, topic, description, proposal_minutes, voting_minutes, negative_weight, quorum_votes, visibility, proposal_visibility, proposal_access, voting_access, local_address, created_at, synced, owner_user_id) values(?, ?, ?, ?, ?, ?, ?, ?, ?, 'private', 'participants', 'participants', 'participants', '', ?, 0, ?)", -1, *statement, null) != SQLITE_OK {
return false
}
unused SqliteBindTextString(statement, 1, TextUntilNul(row.id[:]), -1)
@@ -374,13 +363,8 @@ StorageInsertProcessRow :: (row: ProcessRow) -> bool {
unused SqliteBindInt(statement, 7, row.voting_minutes)
unused SqliteBindInt(statement, 8, row.negative_weight)
unused SqliteBindInt(statement, 9, row.quorum_votes)
unused SqliteBindTextString(statement, 10, TextUntilNul(row.visibility[:]), -1)
unused SqliteBindTextString(statement, 11, TextUntilNul(row.proposal_visibility[:]), -1)
unused SqliteBindTextString(statement, 12, TextUntilNul(row.proposal_access[:]), -1)
unused SqliteBindTextString(statement, 13, TextUntilNul(row.voting_access[:]), -1)
unused SqliteBindTextString(statement, 14, TextUntilNul(row.local_address[:]), -1)
unused SqliteBindInt64(statement, 15, row.created_at)
unused SqliteBindTextString(statement, 16, TextUntilNul(row.owner[:]), -1)
unused SqliteBindInt64(statement, 10, row.created_at)
unused SqliteBindTextString(statement, 11, TextUntilNul(row.owner[:]), -1)
inserted := SqliteStep(statement) == SQLITE_DONE
unused SqliteFinalize(statement)
return inserted
@@ -388,7 +372,7 @@ StorageInsertProcessRow :: (row: ProcessRow) -> bool {
// Saves a newly created process in one transaction: the process, then its
// options (ranked) or proposals (consent), all as the owner's. A consent
// process without proposals starts with the two standing ones.
// process also includes the two standing proposals.
StorageSaveNewProcess :: (row: ProcessRow, owner_name: string, standing: StandingProposals) -> bool {
if database == null || SqliteExecText(database, "begin immediate") != SQLITE_OK {
return false
@@ -408,7 +392,7 @@ StorageSaveNewProcess :: (row: ProcessRow, owner_name: string, standing: Standin
index: s32 = 0
while saved && index < process.proposal_count {
proposal := process.proposals[index]
saved = StorageInsertProposal(process_id, owner, owner_name, TextUntilNul(proposal.title[:]), TextUntilNul(proposal.description[:]), row.created_at, true) >= 0
saved = StorageInsertProposal(process_id, owner, owner_name, TextUntilNul(proposal.title[:]), TextUntilNul(proposal.description[:]), row.created_at) >= 0
index += 1
}
}
@@ -435,14 +419,9 @@ StorageSaveNewProcess :: (row: ProcessRow, owner_name: string, standing: Standin
ProcessSettingsFromRow :: (row: ProcessRow) -> ProcessSettings {
settings: ProcessSettings
settings.id = row.id
settings.owner = row.owner
settings.type = row.type
settings.topic = row.topic
settings.description = row.description
settings.visibility = row.visibility
settings.proposal_visibility = row.proposal_visibility
settings.proposal_access = row.proposal_access
settings.voting_access = row.voting_access
settings.proposal_minutes = row.proposal_minutes
settings.voting_minutes = row.voting_minutes
settings.negative_weight = row.negative_weight
@@ -483,7 +462,7 @@ StorageLoadOptions :: (process_id: string) {
// Preserve stored proposal keys; otherwise use a stable local row identifier.
StorageLoadProposals :: (process_id: string) {
statement: *void = null
if SqlitePrepareText(database, "select id, author_user_id, coalesce(nullif(proposal_key,''), remote_id), title, description, display_name from proposals where process_id=? order by created_at, id", -1, *statement, null) != SQLITE_OK {
if SqlitePrepareText(database, "select id, author_user_id, proposal_key, title, description, display_name from proposals where process_id=? order by created_at, id", -1, *statement, null) != SQLITE_OK {
return
}
unused SqliteBindTextString(statement, 1, process_id, -1)
@@ -492,10 +471,7 @@ StorageLoadProposals :: (process_id: string) {
StorageColumnText(statement, 2, "", proposal.id[:])
if proposal.id[0] == cast(u8)0 {
local: [24]u8
number: [24]u8
length := TextAppend(local[:], 0, "local-")
unused TextAppend(local[:], length, FormatInteger(SqliteColumnInt64(statement, 0), number[:]))
unused CopyCString(TextUntilNul(local[:]), proposal.id[:])
unused CopyCString(StorageLocalProposalId(SqliteColumnInt64(statement, 0), local[:]), proposal.id[:])
}
StorageColumnText(statement, 1, "", proposal.author[:])
StorageColumnText(statement, 3, "", proposal.title[:])
@@ -569,7 +545,7 @@ StorageSaveLocalProposal :: (process_id: string, author: string, display_name: s
if database == null || !StorageHasText(title) {
return -1
}
return StorageInsertProposal(process_id, author, display_name, title, description, now, false)
return StorageInsertProposal(process_id, author, display_name, title, description, now)
}
// Saves this participant's ballot, replacing only their own earlier ballot.
@@ -578,7 +554,7 @@ StorageSaveLocalVote :: (process_id: string, voter: string, display_name: string
return false
}
statement: *void = null
if SqlitePrepareText(database, "insert into votes(process_id, voter_user_id, display_name, reason, scores, updated_at, synced) values(?, ?, ?, ?, ?, ?, 0) on conflict(process_id, voter_user_id) do update set display_name=excluded.display_name, reason=excluded.reason, scores=excluded.scores, updated_at=excluded.updated_at, synced=0", -1, *statement, null) != SQLITE_OK {
if SqlitePrepareText(database, "insert into votes(process_id, voter_user_id, display_name, reason, scores, updated_at) values(?, ?, ?, ?, ?, ?) on conflict(process_id, voter_user_id) do update set display_name=excluded.display_name, reason=excluded.reason, scores=excluded.scores, updated_at=excluded.updated_at", -1, *statement, null) != SQLITE_OK {
return false
}
unused SqliteBindTextString(statement, 1, process_id, -1)
+8 -5
View File
@@ -7,6 +7,7 @@ SystemThemeLinux :: #import "kryon/SystemThemeLinux";
#import "kryon/system_theme"
#import "text_append"
#import "std/text_buffer"
#import "platform"
theme_palette: SystemPalette;
// ThemePolicy: 0 follows the desktop, 1 is light, 2 is dark.
@@ -44,7 +45,13 @@ ThemeUpdate :: () {
}
theme_frames = 0
}
#if #defined(PLATFORM_WEB) || #defined(ANDROID_BUILD) {
#if #defined(PLATFORM_WEB) {
theme_palette = SystemPaletteFallback(BrowserPrefersDark())
unused SystemStyle.StyleInstallSystem(theme_palette)
theme_installed = true
return
}
#if #defined(ANDROID_BUILD) {
theme_palette = SystemPaletteFallback(false)
unused SystemStyle.StyleInstallSystem(theme_palette)
theme_installed = true
@@ -73,7 +80,3 @@ ThemeSurface :: () -> Color {
ThemeBorder :: () -> Color {
return ColorFromPacked(CssMix(theme_palette.background, theme_palette.text, 0.16))
}
ThemeAccent :: () -> Color {
return ColorFromPacked(theme_palette.selected)
}
+21 -3
View File
@@ -6,6 +6,9 @@ using UI :: #import "kryon/Widgets";
#import "std/text_buffer"
#import "std/number_text"
#import "std/c_string"
#if #defined(PLATFORM_WEB) {
#import "browser_input"
}
FIELD_LIMIT :: 32
@@ -163,6 +166,17 @@ UiField :: (session: Session, index: s32, label: string, placeholder: string, bu
edit: TextFieldEdit
replacement_storage: [1024]u8
committed: bool
#if #defined(PLATFORM_WEB) {
native := BrowserFieldRead(index, label, placeholder, buffer, bounds)
state.cursor = native.cursor
state.anchor = native.anchor
if native.focused {
focused_field = index
} else if focused_field == index {
focused_field = -1
}
committed = native.committed
}
{
props: TextFieldProps
props.key = cast(u64)(1000 + index)
@@ -177,8 +191,10 @@ UiField :: (session: Session, index: s32, label: string, placeholder: string, bu
props.focused = focused_field == index
props.max_bytes = cast(s32)buffer.count - 1
props.max_codepoints = props.max_bytes
if props.focused {
props.input = TextFieldInputFor(frame_key, frame_modifiers, TextView(typed_storage[0:frame_typed_count]))
#if !#defined(PLATFORM_WEB) {
if props.focused {
props.input = TextFieldInputFor(frame_key, frame_modifiers, TextView(typed_storage[0:frame_typed_count]))
}
}
result := TextField(session, props)
state.cursor = result.cursor
@@ -199,7 +215,9 @@ UiField :: (session: Session, index: s32, label: string, placeholder: string, bu
if !CopyCString(result.edit.replacement, replacement_storage[:]) {
return false
}
committed = result.committed
#if !#defined(PLATFORM_WEB) {
committed = result.committed
}
}
edit.replacement = TextUntilNul(replacement_storage[:])
unused UiApplyEdit(buffer, edit)
+38 -8
View File
@@ -7,31 +7,56 @@
<link rel="icon" href="uku-logo.svg" type="image/svg+xml">
<style>
html, body { margin: 0; height: 100%; background: #f5f5f5; }
canvas { display: block; width: 100%; height: 100dvh; }
canvas { display: block; width: 100%; height: calc(100dvh - 54px); }
#status { position: fixed; top: 0; padding: 12px; background: white; font: 14px system-ui; }
#status:empty { display: none; }
#backup { position: fixed; right: 12px; bottom: 12px; padding: 10px; }
#tools { position: fixed; bottom: 0; left: 0; right: 0; height: 54px; display: flex; justify-content: flex-end; align-items: center; gap: 8px; padding: 0 12px; background: #f5f5f5; box-sizing: border-box; }
#tools button { padding: 10px; }
#fields { position: fixed; left: 0; right: 0; overflow: hidden; pointer-events: none; }
#fields input { position: absolute; box-sizing: border-box; padding: 0 8px; margin: 0; border: 0; outline: 0; background: transparent; color: transparent; caret-color: transparent; font: 16px sans-serif; pointer-events: auto; }
#fields input::selection { background: transparent; }
#fields input::placeholder { color: transparent; }
</style>
</head>
<body>
<p id="status" role="status">Loading Ukuvota…</p>
<canvas id="canvas" tabindex="0" aria-label="Ukuvota decision workspace"></canvas>
<button id="backup" hidden>Download backup</button>
<div id="fields"></div>
<div id="tools">
<button id="retry" hidden>Retry saving</button>
<button id="backup" hidden>Download backup</button>
</div>
<script src="browser-input.js"></script>
<script>
var fields = new InputFields(document.getElementById('fields'));
var Module = {
canvas: document.getElementById('canvas'),
ukuSaveFailed: false,
beginFields: function (top, height, backupLabel, retryLabel) {
fields.begin(top, height);
var backup = document.getElementById('backup');
var retry = document.getElementById('retry');
if (backup.textContent !== backupLabel) backup.textContent = backupLabel;
if (retry.textContent !== retryLabel) retry.textContent = retryLabel;
},
inputField: function (...args) { return fields.field(...args); },
endFields: function () { fields.end(); },
saveUkuData: function () {
Module.ukuSaveQueued = true;
if (Module.ukuSaving) return;
function save() {
Module.ukuSaveQueued = false;
Module.ukuSaving = true;
FS.syncfs(false, function (error) {
var completed = false;
function saved(error) {
if (completed) return;
completed = true;
Module.ukuSaveFailed = Boolean(error);
document.getElementById('retry').hidden = !error;
Module.ukuSaving = false;
if (Module.ukuSaveQueued && !error) save();
});
}
try { FS.syncfs(false, saved); } catch (error) { saved(error); }
}
save();
},
@@ -39,16 +64,18 @@
FS.mkdir('/data');
FS.mount(IDBFS, {}, '/data');
addRunDependency('uku-data');
FS.syncfs(true, function (error) {
function restored(error) {
if (error) {
Module.ukuStartupFailed = true;
document.getElementById('status').textContent = 'Could not open saved data. Enable browser storage and reload.';
return;
}
removeRunDependency('uku-data');
});
}
try { FS.syncfs(true, restored); } catch (error) { restored(error); }
}],
setStatus: function (text) {
document.getElementById('status').textContent = text;
if (!Module.ukuStartupFailed) document.getElementById('status').textContent = text;
},
onRuntimeInitialized: function () {
document.getElementById('status').textContent = '';
@@ -59,6 +86,9 @@
document.getElementById('status').textContent = 'Ukuvota could not start. Reload to try again.';
}
};
document.getElementById('retry').addEventListener('click', function () {
Module.saveUkuData();
});
document.getElementById('backup').addEventListener('click', function () {
try {
var bytes = FS.readFile('/data/uku.sqlite3');
-6
View File
@@ -55,12 +55,6 @@ BallotAnswer :: () -> s32 {
return 9
}
renamed: [64]u8
length = BallotReplaceId("draft-1=2;p1=-1;draft-10=3", "draft-1", "srv-9", renamed[:])
// Only the whole id is renamed, never a longer id that starts with it.
if !Same(renamed[:], length, "srv-9=2;p1=-1;draft-10=3") {
return 10
}
return 42
}
+43
View File
@@ -0,0 +1,43 @@
"""Prepare high-contrast captions for rendered canvas integration checks."""
import json
from pathlib import Path
import sys
from PIL import Image, ImageChops, ImageDraw, ImageOps
source = Path(sys.argv[1])
image = Image.open(source).convert('RGB')
red, _, blue = image.split()
mask = ImageChops.subtract(blue, red).point(lambda value: 255 if value > 40 else 0)
output = source.parent / 'ocr'
output.mkdir(exist_ok=True)
regions = []
while mask.getbbox():
_, top, _, _ = mask.getbbox()
left = mask.crop((0, top, mask.width, top + 1)).tobytes().index(255)
previous = mask.copy()
ImageDraw.floodfill(mask, (left, top), 0)
bounds = ImageChops.difference(previous, mask).getbbox()
x, y, right, bottom = bounds
if right - x < 48 or bottom - y < 24:
continue
# Borders confuse full-page OCR, so recognize the caption separately.
inset = max(2, round(image.width / 500))
x, y, right, bottom = x + inset, y + inset, right - inset, bottom - inset
# Accent buttons have light captions on blue; a red-channel threshold
# removes their fill and focus borders without erasing antialiased text.
crop = image.crop((x, y, right, bottom)).getchannel('R').point(
lambda value: 0 if value > 190 else 255)
file = output / f'{len(regions)}.png'
crop.save(file)
regions.append({'file': str(file), 'x': x, 'y': y})
# Tesseract misses small light text on the dark canvas unless its polarity is
# normalized. Keep the original pixel dimensions for reliable click positions.
page = image.convert('L')
if page.getpixel((10, min(70, page.height - 1))) < 128:
page = ImageOps.invert(page)
page = ImageOps.autocontrast(page)
file = output / 'page.png'
page.save(file)
regions.extend({'file': str(file), 'x': 0, 'y': 0, 'mode': mode} for mode in (6, 11))
print(json.dumps(regions))
+1 -1
View File
@@ -79,7 +79,7 @@ def main():
click(650, 392) # Rules: weight, quorum and local storage notice
click(650, 395) # Timing: proposal and voting phases
subprocess.run(['import', '-window', window, str(ROOT / 'build/smoke/review.png')], check=True)
click(650, 375) # Review: create the decision
click(650, 350) # Review: create the decision
def created():
with sqlite3.connect(database) as connection:
return connection.execute("select count(*) from processes where topic='Choose dinner'").fetchone()[0] == 1
+27 -45
View File
@@ -2,70 +2,52 @@
#import "tally"
#import "std/text_buffer"
// Proposals and votes come before the process's own title, and the ids of
// nested objects repeat field names, so reading by field path matters.
SAMPLE :: "{\"proposals\":[{\"id\":\"p1\",\"title\":\"Caf\\u00e9 \\\"night\\\"\",\"author_user_id_hash\":\"alice\",\"author_display_name\":\"Alice\"},{\"id\":\"p2\",\"title\":\"Picnic\",\"description\":\"Line 1\\nLine 2\"},{\"title\":\"no id\"}],\"votes\":[{\"voter_user_id_hash\":\"bob\",\"display_name\":\"Bob\",\"updated_at\":\"2026-09-29\",\"scores\":{\"p1\":3,\"p2\":-2,\"gone\":1,\"p1x\":9}},{\"voter_user_id_hash\":\"alice\",\"scores\":{\"p2\":0}}],\"id\":\"proc-7\",\"type\":\"consent\",\"title\":\"Team outing\",\"negative_weight\":0,\"quorum_votes\":2,\"proposal_minutes\":1500,\"voting_access\":\"members\"}"
#program_export
ProcessAnswer :: () -> s32 {
if !ParseProcessDetail(SAMPLE) {
ProcessClear()
process.settings.negative_weight = 3
process.proposal_count = 2
SetText(process.proposals[0].id[:], "p1")
SetText(process.proposals[1].id[:], "p2")
alice := ProcessParticipantAdd("alice", "Alice", false)
bob := ProcessParticipantAdd("bob", "Bob", true)
if alice < 0 || bob < 0 || ProcessParticipantAdd("alice", "", true) != alice || process.participant_count != 2 {
return 1
}
if TextUntilNul(process.settings.id[:]) != "proc-7" || TextUntilNul(process.settings.topic[:]) != "Team outing" {
ProcessApplyBallot(alice, "p1=3;p2=-2;gone=1")
ProcessApplyBallot(bob, "p2=0;p1x=9")
if process.proposal_scores[alice][0] != cast(s8)3 || process.proposal_scores[alice][1] != cast(s8)-2 {
return 2
}
if process.settings.type != ProcessType.ProcessConsent || process.settings.quorum_votes != 2 || process.settings.proposal_minutes != 1500 {
if process.proposal_scores[bob][0] != cast(s8)SCORE_UNSET || process.proposal_scores[bob][1] != cast(s8)0 {
return 3
}
// Consent processes read a stored weight of 0 as Infinity.
if process.settings.negative_weight != NEGATIVE_WEIGHT_INFINITY {
tally := ProcessProposalTally(1)
if ProcessIncludedBallots() != 2 || tally.vote_count != 2 || tally.total != -6 {
return 4
}
if TextUntilNul(process.settings.visibility[:]) != "public" || TextUntilNul(process.settings.voting_access[:]) != "members" {
process.participants[alice].excluded = true
tally = ProcessProposalTally(1)
if !ProcessSubsetActive() || ProcessIncludedBallots() != 1 || tally.vote_count != 1 || tally.total != 0 {
return 5
}
// A proposal without an id is skipped; escapes are decoded.
if process.proposal_count != 2 {
// Stored ranked decisions retain canonical type keys and option scores.
if ProcessTypeFromKey("ranked_choice") != ProcessType.ProcessRanked || ProcessTypeKey(ProcessType.ProcessRanked) != "ranked_choice" {
return 6
}
if TextUntilNul(process.proposals[0].title[:]) != "Café \"night\"" || TextUntilNul(process.proposals[0].display_name[:]) != "Alice" {
ProcessClear()
process.settings.type = ProcessType.ProcessRanked
process.option_count = 1
SetText(process.options[0].id[:], "o1")
voter := ProcessParticipantAdd("voter", "Voter", true)
ProcessApplyBallot(voter, "o1=2")
if process.option_scores[voter][0] != cast(s8)2 || ProcessOptionTally(0).total != 2 {
return 7
}
if TextUntilNul(process.proposals[1].description[:]) != "Line 1\nLine 2" {
return 8
}
// Bob and Alice voted; Alice is also p1's author and appears once.
if process.participant_count != 2 {
return 9
}
bob := ProcessParticipantFind("bob")
alice := ProcessParticipantFind("alice")
if bob < 0 || alice < 0 || !process.participants[alice].has_ballot {
return 10
}
if TextUntilNul(process.participants[bob].updated_at[:]) != "2026-09-29" {
return 11
}
// Unknown ids and out-of-range scores are ignored.
if process.proposal_scores[bob][0] != cast(s8)3 || process.proposal_scores[bob][1] != cast(s8)-2 {
return 12
}
if process.proposal_scores[alice][0] != cast(s8)SCORE_UNSET || process.proposal_scores[alice][1] != cast(s8)0 {
return 13
}
if ProcessTypeFromKey("ranked_choice") != ProcessType.ProcessRanked || ProcessTypeKey(ProcessType.ProcessRanked) != "ranked_choice" {
return 14
}
if ParseProcessDetail("{\"title\":\"no id\"}") {
return 15
}
return 42
}
#program_export
main :: () -> s32 {
if ProcessAnswer() == 42 {
return 0
}
return 1
return ifx ProcessAnswer() == 42 then 0 else 1
}
+20 -3
View File
@@ -104,12 +104,12 @@ main :: () -> s32 {
if TextUntilNul(newest.id[:]) != "ranked-1" || newest.type != ProcessType.ProcessRanked || newest.created_at != 200 {
return 14
}
if TextUntilNul(oldest.topic[:]) != "Café night" || oldest.negative_weight != NEGATIVE_WEIGHT_INFINITY || TextUntilNul(oldest.voting_access[:]) != "public" {
if TextUntilNul(oldest.topic[:]) != "Café night" || oldest.negative_weight != NEGATIVE_WEIGHT_INFINITY {
return 15
}
// The consent process got the two standing proposals; the ranked one
// kept its labelled option and skipped the blank one.
if Count("select count(*) from proposals where process_id = 'consent-1' and author_user_id = 'owner' and synced = 1") != 2 {
if Count("select count(*) from proposals where process_id = 'consent-1' and author_user_id = 'owner'") != 2 {
return 16
}
if Count("select count(*) from options where process_id = 'ranked-1'") != 1 {
@@ -129,6 +129,9 @@ main :: () -> s32 {
if SaveConsent("consent-1", 300) || Count("select count(*) from processes") != 2 || Count("select count(*) from proposals") != proposals {
return 18
}
if !CheckProposalKeyUpgrade() {
return 26
}
StorageClose()
if SettingSaveText("closed", "x") {
return 11
@@ -136,6 +139,21 @@ main :: () -> s32 {
return 0
}
// Earlier proposal identifiers migrate without replacing current keys or votes.
CheckProposalKeyUpgrade :: () -> bool {
votes := Count("select count(*) from votes")
if SqliteExecText(database, "update proposals set remote_id=proposal_key, proposal_key='' where process_id='consent-1' and proposal_key='status-quo'; update proposals set remote_id='obsolete' where process_id='consent-1' and proposal_key='repeat-process'") != SQLITE_OK {
return false
}
StorageClose()
if !StorageOpen(STORAGE_TEST_PATH) {
return false
}
return Count("select count(*) from votes") == votes &&
Count("select count(*) from proposals where process_id='consent-1' and proposal_key='status-quo'") == 1 &&
Count("select count(*) from proposals where process_id='consent-1' and proposal_key='repeat-process' and remote_id='obsolete'") == 1
}
Standing :: () -> StandingProposals {
standing: StandingProposals
standing.status_quo_title = "Status quo"
@@ -151,7 +169,6 @@ SaveConsent :: (id: string, created_at: s64) -> bool {
SetText(row.id[:], id)
SetText(row.owner[:], "owner")
SetText(row.topic[:], "Café night")
SetText(row.visibility[:], "public")
row.type = ProcessType.ProcessConsent
row.negative_weight = 0
row.created_at = created_at
+601 -79
View File
@@ -1,140 +1,662 @@
// Standalone browser integration test. No owner profile or desktop is used.
import assert from 'node:assert/strict';
import {spawn, spawnSync} from 'node:child_process';
import {createServer} from 'node:http';
import {readFile, writeFile, mkdtemp, mkdir, stat, rm} from 'node:fs/promises';
import { spawn, spawnSync } from 'node:child_process';
import { createServer } from 'node:http';
import { readFile, writeFile, mkdtemp, mkdir, stat, rm } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import {fileURLToPath} from 'node:url';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
if (!process.argv.includes('--private-display')) {
const env = {...process.env};
for (const key of ['DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS']) delete env[key];
const result = spawnSync('xvfb-run', ['-a', process.execPath, fileURLToPath(import.meta.url), '--private-display'], {cwd: root, env, stdio: 'inherit'});
const env = { ...process.env };
for (const key of ['DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'DBUS_SESSION_BUS_ADDRESS'])
delete env[key];
const result = spawnSync(
'xvfb-run',
[
'-a',
process.execPath,
fileURLToPath(import.meta.url),
'--private-display',
...process.argv.slice(2),
],
{ cwd: root, env, stdio: 'inherit' },
);
process.exit(result.status ?? 1);
}
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function until(check, message) {
for (let i = 0; i < 300; i++) {
try { if (await check()) return; } catch {}
const deadline = performance.now() + 30000;
while (performance.now() < deadline) {
try {
if (await check()) return;
} catch {}
await delay(100);
}
throw new Error(message);
}
const webRoot = path.join(root, 'build/dist/web');
const site = process.argv.includes('--site');
const webRoot = path.join(root, site ? 'build/site' : 'build/dist/web');
const scratch = await mkdtemp(path.join(os.tmpdir(), 'uku-browser-'));
const artifacts = path.join(root, 'build/smoke');
await mkdir(artifacts, {recursive: true});
await mkdir(artifacts, { recursive: true });
const server = createServer(async (req, res) => {
const requested = new URL(req.url, 'http://localhost').pathname;
const file = path.resolve(webRoot, '.' + (requested === '/' ? '/index.html' : requested));
if (!file.startsWith(webRoot + path.sep)) { res.writeHead(403).end(); return; }
if (!file.startsWith(webRoot + path.sep)) {
res.writeHead(403).end();
return;
}
try {
const mime = {'.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.svg': 'image/svg+xml'}[path.extname(file)] || 'application/octet-stream';
res.writeHead(200, {'Content-Type': mime}).end(await readFile(file));
} catch { res.writeHead(404).end(); }
const mime =
{
'.html': 'text/html',
'.js': 'text/javascript',
'.wasm': 'application/wasm',
'.svg': 'image/svg+xml',
}[path.extname(file)] || 'application/octet-stream';
res
.writeHead(200, { 'Content-Type': mime, 'X-Content-Type-Options': 'nosniff' })
.end(await readFile(file));
} catch {
res.writeHead(404).end();
}
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${server.address().port}/`;
const browser = spawn(process.env.CHROMIUM || 'chromium', ['--headless=new', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage', '--disable-background-networking', '--no-first-run', '--remote-debugging-port=0', `--user-data-dir=${scratch}`, url], {stdio: ['ignore', 'ignore', 'pipe']});
const browser = spawn(
process.env.CHROMIUM || 'chromium',
[
'--headless=new',
'--no-sandbox',
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-background-networking',
'--no-first-run',
'--remote-debugging-port=0',
`--user-data-dir=${scratch}`,
url,
],
{ stdio: ['ignore', 'ignore', 'pipe'] },
);
let browserLog = '';
browser.stderr.on('data', data => { browserLog = (browserLog + data).slice(-8000); });
browser.stderr.on('data', (data) => {
browserLog = (browserLog + data).slice(-8000);
});
let socket;
try {
const portFile = path.join(scratch, 'DevToolsActivePort');
await until(async () => (await stat(portFile)).size > 0, 'Chromium did not start: ' + browserLog);
const port = (await readFile(portFile, 'utf8')).split('\n')[0];
const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
socket = new WebSocket(targets.find(target => target.type === 'page').webSocketDebuggerUrl);
await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; });
socket = new WebSocket(targets.find((target) => target.type === 'page').webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
socket.onopen = resolve;
socket.onerror = reject;
});
let nextId = 0;
const pending = new Map();
const exceptions = [];
socket.onmessage = event => {
const consoleMessages = [];
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') exceptions.push(message.params.exceptionDetails);
if (message.method === 'Runtime.exceptionThrown')
exceptions.push(message.params.exceptionDetails);
if (message.method === 'Runtime.consoleAPICalled')
consoleMessages.push(
message.params.args.map((arg) => arg.value ?? arg.description).join(' '),
);
if (message.id && pending.has(message.id)) {
const {resolve, reject} = pending.get(message.id);
const { resolve, reject } = pending.get(message.id);
pending.delete(message.id);
message.error ? reject(new Error(JSON.stringify(message.error))) : resolve(message.result);
}
};
const command = (method, params = {}) => new Promise((resolve, reject) => {
const id = ++nextId;
pending.set(id, {resolve, reject});
socket.send(JSON.stringify({id, method, params}));
});
const evaluate = async expression => {
const result = await command('Runtime.evaluate', {expression, returnByValue: true});
const command = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++nextId;
const timeout = setTimeout(() => {
pending.delete(id);
reject(new Error('Timed out: ' + method));
}, 30000);
pending.set(id, {
resolve: (result) => {
clearTimeout(timeout);
resolve(result);
},
reject: (error) => {
clearTimeout(timeout);
reject(error);
},
});
socket.send(JSON.stringify({ id, method, params }));
});
const evaluate = async (expression) => {
const result = await command('Runtime.evaluate', { expression, returnByValue: true });
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
return result.result.value;
};
await command('Runtime.enable');
await command('Page.enable');
await command('Emulation.setDeviceMetricsOverride', {width: 1000, height: 760, deviceScaleFactor: 1, mobile: false});
const ready = () => evaluate("typeof FS !== 'undefined' && typeof Module !== 'undefined' && FS.analyzePath('/data/uku.sqlite3').exists && document.getElementById('status').textContent === ''");
await until(ready, 'Browser app did not initialize: ' + browserLog);
await command('Network.enable');
const networkFailures = [];
const oldMessage = socket.onmessage;
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Network.loadingFailed' && !message.params.canceled)
networkFailures.push(message.params.errorText);
if (message.method === 'Network.responseReceived' && message.params.response.status >= 400)
networkFailures.push(message.params.response.url);
oldMessage(event);
};
await command('Page.addScriptToEvaluateOnNewDocument', {
source: `
const now = Date.now.bind(Date);
Date.now = () => now() + Number(sessionStorage.testClock || 0);
`,
});
let mobile = false;
await command('Emulation.setDeviceMetricsOverride', {
width: 1000,
height: 760,
deviceScaleFactor: 1,
mobile,
});
if (site) {
await until(
() => evaluate('Boolean(document.querySelector(\'a[href="/build/web/index.html"]\'))'),
'Website did not offer the web app',
);
await until(
() =>
evaluate(
'Array.from(document.images).every(image => image.complete && image.naturalWidth > 0)',
),
'Website screenshots or logos did not load',
);
await evaluate('document.querySelector(\'a[href="/build/web/index.html"]\').click()');
await until(
() =>
evaluate("location.pathname === '/build/web/index.html' && typeof Module !== 'undefined'"),
'Website Run web app link did not open Ukuvota',
);
}
await command('Page.reload');
const ready = () =>
evaluate(
"typeof FS !== 'undefined' && typeof Module !== 'undefined' && FS.analyzePath('/data/uku.sqlite3').exists && document.getElementById('status').textContent === '' && document.title === 'Ukuvota'",
);
try {
await until(ready, 'Browser app did not initialize');
} catch (error) {
console.error(
await evaluate(
"JSON.stringify({title:document.title,status:document.getElementById('status').textContent,filesystem:typeof FS,fields:typeof fields,bridgeError:typeof __ziranWeb!=='undefined'?__ziranWeb.perm[__ziranWeb.error]?.stack:null,fieldsCount:document.querySelectorAll('#fields input').length})",
),
);
console.error(JSON.stringify({ exceptions, consoleMessages, networkFailures }));
throw error;
}
await delay(600);
async function click(x, y) {
await command('Input.dispatchMouseEvent', {type: 'mouseMoved', x, y});
await command('Input.dispatchMouseEvent', {type: 'mousePressed', x, y, button: 'left', clickCount: 1});
await delay(100);
await command('Input.dispatchMouseEvent', {type: 'mouseReleased', x, y, button: 'left', clickCount: 1});
if (mobile) {
await command('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
await delay(100);
await command('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
} else {
await command('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y });
await command('Input.dispatchMouseEvent', {
type: 'mousePressed',
x,
y,
button: 'left',
clickCount: 1,
});
await delay(100);
await command('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x,
y,
button: 'left',
clickCount: 1,
});
}
await delay(200);
}
await click(920, 30); // Settings
await click(660, 220); // Dark appearance
const settingsShot = await command('Page.captureScreenshot', {format: 'png'});
await writeFile(path.join(artifacts, 'browser-settings.png'), Buffer.from(settingsShot.data, 'base64'));
await until(() => evaluate('!Module.ukuSaving && !Module.ukuSaveFailed'), 'Browser saving failed');
async function checkStoredTheme() {
const bytes = await evaluate("Array.from(FS.readFile('/data/uku.sqlite3'))");
const database = path.join(artifacts, 'browser.sqlite3');
await writeFile(database, Buffer.from(bytes));
const check = spawnSync('python3', ['-c', 'import sqlite3,sys; c=sqlite3.connect(sys.argv[1]); assert c.execute("select value from settings where key=\'theme_mode\'").fetchone() == (\'2\',)', database], {encoding: 'utf8'});
assert.equal(check.status, 0, check.stderr);
async function scroll(amount) {
await command('Input.dispatchMouseEvent', {
type: 'mouseMoved',
x: mobile ? 200 : 700,
y: 400,
});
await command('Input.dispatchMouseEvent', {
type: 'mouseWheel',
x: mobile ? 200 : 700,
y: 400,
deltaX: 0,
deltaY: amount,
});
await delay(200);
}
await checkStoredTheme();
async function swipe(startY, endY) {
const x = 375;
await command('Input.dispatchTouchEvent', {
type: 'touchStart',
touchPoints: [{ x, y: startY }],
});
await delay(100);
for (let step = 1; step <= 8; step++) {
const y = startY + ((endY - startY) * step) / 8;
await command('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y }] });
await delay(30);
}
await command('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
await delay(200);
}
async function text() {
const screenshot = await command('Page.captureScreenshot', { format: 'png' });
const file = path.join(artifacts, 'browser-current.png');
await writeFile(file, Buffer.from(screenshot.data, 'base64'));
const scale = await evaluate('devicePixelRatio');
const rows = [];
const prepared = spawnSync('python3', [path.join(root, 'tests/browser_ocr.py'), file], {
encoding: 'utf8',
});
assert.equal(prepared.status, 0, prepared.stderr);
const sources = JSON.parse(prepared.stdout).map((region) => ({
...region,
mode: region.mode ?? 7,
}));
for (const source of sources) {
const result = spawnSync(
process.env.TESSERACT || 'tesseract',
[source.file, 'stdout', '--psm', String(source.mode), '-c', 'tessedit_create_tsv=1'],
{ encoding: 'utf8', env: { ...process.env, OMP_THREAD_LIMIT: '1' } },
);
assert.equal(result.status, 0, 'OCR failed: ' + result.stderr);
const lines = new Map();
for (const line of result.stdout.trim().split('\n').slice(1)) {
const cols = line.split('\t');
if (cols[0] !== '5' || !cols[11]?.trim()) continue;
const word = {
text: cols[11].trim(),
x: (Number(cols[6]) + source.x) / scale,
y: (Number(cols[7]) + Number(cols[9]) + source.y) / scale,
width: Number(cols[8]) / scale,
};
rows.push(word);
const key = cols.slice(1, 5).join(':');
const words = lines.get(key) || [];
words.push(word);
lines.set(key, words);
}
for (const words of lines.values()) {
for (let start = 0; start < words.length; start++)
for (let count = 2; count <= 8 && start + count <= words.length; count++) {
const group = words.slice(start, start + count);
rows.push({
text: group.map((w) => w.text).join(' '),
x: group[0].x,
y: Math.max(...group.map((w) => w.y)),
width: group.at(-1).x + group.at(-1).width - group[0].x,
});
}
}
}
return rows;
}
const normalize = (value) =>
value
.toLowerCase()
.replace(/[^\p{L}\p{N}+\-]+/gu, ' ')
.trim();
const matches = (value, label) =>
normalize(value) === normalize(label) ||
(label.startsWith('Choose café') && normalize(value).startsWith('choose café dinner'));
async function visible(label) {
const rows = await text();
return rows.filter(
(row) => matches(row.text, label) && row.y > 0 && row.y < (mobile ? 810 : 725),
);
}
async function clickText(label, { scrollTo = true, occurrence = 0 } = {}) {
for (let i = 0; i < 24; i++) {
const found = (await visible(label))[occurrence];
if (found) {
await click(found.x + found.width / 2, found.y - 5);
return;
}
if (!scrollTo) break;
const rows = (await text()).filter((row) => matches(row.text, label));
await scroll(rows.length && rows[occurrence]?.y < 64 ? -250 : 250);
}
throw new Error(
'Cannot find visible control: ' +
label +
'\n' +
JSON.stringify((await text()).filter((row) => row.text.length > 5).slice(0, 30)),
);
}
async function see(part) {
await until(
async () => (await text()).some((row) => row.text.toLowerCase().includes(part.toLowerCase())),
'Expected rendered text: ' + part,
);
}
async function input(id, value) {
const box = await evaluate(
`(() => { const field = document.getElementById('field-${id}'); if (!field) return null; const r=field.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`,
);
assert.ok(box, 'Missing native field ' + id);
await click(box.x, box.y);
assert.equal(await evaluate('document.activeElement.id'), `field-${id}`);
await command('Input.dispatchKeyEvent', {
type: 'keyDown',
key: 'a',
code: 'KeyA',
windowsVirtualKeyCode: 65,
modifiers: 2,
});
await command('Input.dispatchKeyEvent', {
type: 'keyUp',
key: 'a',
code: 'KeyA',
windowsVirtualKeyCode: 65,
modifiers: 2,
});
await command('Input.insertText', { text: value });
await delay(200);
assert.equal(await evaluate('document.activeElement.value'), value);
}
async function stored() {
await until(
() => evaluate('!Module.ukuSaving && !Module.ukuSaveQueued && !Module.ukuSaveFailed'),
'Browser saving failed',
);
const database = path.join(artifacts, 'browser.sqlite3');
await writeFile(
database,
Buffer.from(await evaluate("Array.from(FS.readFile('/data/uku.sqlite3'))")),
);
const result = spawnSync(
'python3',
[
'-c',
'import sqlite3,json,sys; c=sqlite3.connect(sys.argv[1]); c.row_factory=sqlite3.Row; print(json.dumps({t:[dict(r) for r in c.execute("select * from "+t)] for t in ["processes","proposals","votes","participants","settings"]},ensure_ascii=False))',
database,
],
{ encoding: 'utf8' },
);
assert.equal(result.status, 0, result.stderr);
return JSON.parse(result.stdout);
}
async function shot(name) {
const screenshot = await command('Page.captureScreenshot', { format: 'png' });
await writeFile(
path.join(artifacts, `browser-${name}.png`),
Buffer.from(screenshot.data, 'base64'),
);
}
async function score(title, value) {
await scroll(-10000);
for (let i = 0; i < 24; i++) {
const proposal = (await text()).find((row) => matches(row.text, title));
const field = await evaluate(
"(() => {const r=document.getElementById('field-10').getBoundingClientRect();return {x:r.x,width:r.width};})()",
);
const count = field.width - 28 < 352 ? 4 : 8;
const index = value === '—' ? 7 : Number(value) + 3;
const y = proposal && proposal.y + 50 + Math.floor(index / count) * 52;
if (
proposal &&
proposal.y > 64 &&
y < (await evaluate('Module.canvas.getBoundingClientRect().height-10'))
) {
await click(field.x + 14 + (((index % count) + 0.5) * (field.width - 28)) / count, y);
return;
}
await scroll(150);
}
throw new Error('Cannot score ' + title + ' with ' + value);
}
await shot('dashboard-empty');
await clickText('Settings', { scrollTo: false });
await command('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
});
await click(327, 216); // System appearance
await until(
() => evaluate("Module.canvas.getContext('2d').getImageData(10,70,1,1).data[0]<100"),
'System appearance did not follow dark preference',
);
await command('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value: 'light' }],
});
await until(
() => evaluate("Module.canvas.getContext('2d').getImageData(10,70,1,1).data[0]>200"),
'System appearance did not follow light preference',
);
await clickText('Dark');
assert.ok((await stored()).settings.some((row) => row.key === 'theme_mode' && row.value === '2'));
await command('Page.reload');
await delay(300);
await until(ready, 'Saved browser data did not reopen');
await checkStoredTheme();
await click(650, 30);
await click(500, 248);
for (const key of 'Choose dinner') {
await command('Input.dispatchKeyEvent', {type: 'keyDown', key, text: key});
await command('Input.dispatchKeyEvent', {type: 'keyUp', key});
await delay(30);
}
await click(650, 390);
await click(650, 375);
await click(650, 395);
await click(650, 375);
assert.ok((await stored()).settings.some((row) => row.key === 'theme_mode' && row.value === '2'));
await clickText('Make New Process', { scrollTo: false });
console.log('Settings persisted; testing native editing and decision creation');
await shot('setup-process');
await input(0, 'Choose café dinner 🍲');
await command('Input.insertText', { text: '🍲'.repeat(100) });
await delay(200);
const boundedTopic = await evaluate("document.getElementById('field-0').value");
assert.ok(
Buffer.byteLength(boundedTopic, 'utf8') <= 179,
'Native input exceeded the topic byte capacity',
);
assert.ok(!boundedTopic.includes('\ufffd'), 'Native input split a Unicode character');
await input(0, 'Choose café dinner 🍲');
await input(1, 'A shared decision with international text.');
await clickText('Continue');
await click(381, 255);
await click(381, 255);
await clickText('Continue');
await shot('schedule');
await clickText('Continue');
await shot('review');
await clickText('Create Process');
await see('Add proposal');
const initial = await stored();
assert.equal(initial.processes.length, 1);
assert.equal(initial.processes[0].topic, 'Choose café dinner 🍲');
assert.equal(initial.processes[0].quorum_votes, 2);
assert.equal(initial.proposals.length, 2);
await input(10, 'Alice');
await input(11, 'Pasta');
await input(12, 'Vegetarian pasta for everyone.');
await clickText('Submit proposal');
assert.equal((await stored()).proposals.length, 3);
await shot('proposals');
await evaluate('sessionStorage.testClock=3601000');
await see('Your ballot');
console.log('Proposal saved; testing ballots and participants');
await clickText('Submit vote');
assert.equal((await stored()).votes.length, 0, 'An entirely abstained ballot must not save');
await score('Status quo', '+3');
await score('Repeat process', '-1');
await score('Pasta', '+3');
await clickText('Submit vote');
const first = await stored();
assert.equal(first.votes.length, 1);
assert.equal(first.votes[0].display_name, 'Alice');
assert.equal(first.votes[0].scores, 'status-quo=3;repeat-process=-1;local-3=3');
await clickText('Next participant');
await input(10, 'Alice');
await score('Status quo', '-1');
await score('Repeat process', '-1');
await score('Pasta', '-1');
await clickText('Submit vote');
assert.equal(
(await stored()).votes.length,
1,
'Duplicate name must not overwrite another ballot',
);
await scroll(-3000);
await input(10, 'Bob');
await clickText('Submit vote');
const two = await stored();
assert.equal(two.votes.length, 2);
assert.notEqual(two.votes[0].voter_user_id, two.votes[1].voter_user_id);
const bob = two.votes.find((row) => row.display_name === 'Bob');
await clickText('Alice');
await input(10, 'Alice 🍀');
await clickText('Update vote');
const edited = await stored();
assert.equal(edited.votes.length, 2);
assert.deepEqual(
edited.votes.find((row) => row.display_name === 'Bob'),
bob,
);
assert.equal(
edited.votes.find((row) => row.voter_user_id === first.votes[0].voter_user_id).display_name,
'Alice 🍀',
);
await scroll(-10000);
await shot('voting');
await command('Page.reload');
await delay(300);
await until(() => evaluate('!Module.ukuSaving && !Module.ukuSaveFailed'), 'Created process did not persist');
const createdBytes = await evaluate("Array.from(FS.readFile('/data/uku.sqlite3'))");
const createdFile = path.join(artifacts, 'browser.sqlite3');
await writeFile(createdFile, Buffer.from(createdBytes));
const processCheck = spawnSync('python3', ['-c', 'import sqlite3,sys; c=sqlite3.connect(sys.argv[1]); assert c.execute("select topic from processes").fetchall() == [("Choose dinner",)]; assert c.execute("select count(*) from proposals").fetchone() == (2,)', createdFile], {encoding: 'utf8'});
assert.equal(processCheck.status, 0, processCheck.stderr);
await command('Browser.setDownloadBehavior', {behavior: 'allow', downloadPath: scratch});
await until(ready, 'Ballots failed to reopen');
assert.deepEqual((await stored()).votes, edited.votes);
await shot('dashboard-active');
await clickText('Choose café dinner 🍲');
await see('Your ballot');
await evaluate('sessionStorage.testClock=7201000');
await see('Results');
await see('no unique winner');
console.log('Distinct ballots persisted and edit isolation passed; testing tie and quorum');
await shot('results');
await clickText('Bob');
await see('No quorum');
await clickText('Bob');
await see('no unique winner');
mobile = true;
await command('Emulation.setDeviceMetricsOverride', {
width: 390,
height: 844,
deviceScaleFactor: 2,
mobile,
});
await command('Emulation.setTouchEmulationEnabled', { enabled: true });
await delay(500);
await shot('mobile-results');
assert.equal(
await evaluate('document.documentElement.scrollWidth<=innerWidth'),
true,
'Mobile page overflows horizontally',
);
await click(65, 30); // Back in the mobile toolbar.
await clickText('Make New Process', { scrollTo: false });
await input(0, 'Choose tea 茶');
await input(1, 'Touch input and browser-native editing.');
await clickText('Voting Phase only');
await clickText('Continue');
await clickText('Continue');
await input(2, 'Green tea');
await input(3, 'Fresh tea.');
await clickText('Add Proposal');
await clickText('Continue');
await clickText('Continue');
await clickText('Create Process');
await see('Your ballot');
await input(10, 'Chloé');
const nameFieldY = () =>
evaluate("document.getElementById('field-10').getBoundingClientRect().y");
const beforeSwipe = await nameFieldY();
await swipe(660, 340);
assert.ok(
(await nameFieldY()) < beforeSwipe - 100,
'Mobile touch drag did not scroll the ballot',
);
await score('Green tea', '+2');
await clickText('Submit vote');
assert.equal((await stored()).votes.length, 3);
console.log('Mobile touch entry and voting passed; testing backups and storage failures');
await shot('mobile-voting');
await command('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: scratch });
await evaluate("document.getElementById('backup').click()");
const backup = path.join(scratch, 'ukuvota-backup.sqlite3');
await until(async () => (await stat(backup)).size > 0, 'Backup download failed');
assert.equal((await readFile(backup)).subarray(0, 15).toString(), 'SQLite format 3');
const screenshot = await command('Page.captureScreenshot', {format: 'png'});
await writeFile(path.join(artifacts, 'browser.png'), Buffer.from(screenshot.data, 'base64'));
await evaluate("Module.originalSync = FS.syncfs; FS.syncfs = (populate, callback) => callback(new Error('test')); Module.saveUkuData()");
const backupCheck = spawnSync(
'python3',
[
'-c',
'import sqlite3,sys; c=sqlite3.connect(sys.argv[1]); assert c.execute("pragma integrity_check").fetchone()==("ok",); assert c.execute("select count(*) from votes").fetchone()==(3,)',
backup,
],
{ encoding: 'utf8' },
);
assert.equal(backupCheck.status, 0, backupCheck.stderr);
await evaluate(
"Module.originalSync=FS.syncfs; FS.syncfs=(populate,callback)=>callback(new Error('test')); Module.saveUkuData()",
);
assert.equal(await evaluate('Module.ukuSaveFailed'), true);
await evaluate('FS.syncfs = Module.originalSync; Module.saveUkuData()');
await until(() => evaluate('!Module.ukuSaving && !Module.ukuSaveFailed'), 'Saving did not recover');
await see('Could not save browser data');
await evaluate('FS.syncfs=Module.originalSync');
await evaluate("document.getElementById('retry').click()");
await until(
() => evaluate('!Module.ukuSaving && !Module.ukuSaveFailed'),
'Saving did not recover',
);
assert.equal(await evaluate("document.getElementById('retry').hidden"), true);
// A synchronous storage failure must also clear the saving flag and allow retry.
await evaluate(
"FS.syncfs=()=>{throw new Error('test synchronous failure')}; Module.saveUkuData()",
);
assert.equal(await evaluate('Module.ukuSaving'), false);
assert.equal(await evaluate('Module.ukuSaveFailed'), true);
await evaluate('FS.syncfs=Module.originalSync');
await evaluate("document.getElementById('retry').click()");
await until(
() => evaluate('!Module.ukuSaving && !Module.ukuSaveFailed'),
'Synchronous save failure did not recover',
);
const blocked = await command('Page.addScriptToEvaluateOnNewDocument', {
source: "indexedDB.open=()=>{throw new DOMException('test storage denied','SecurityError')}",
});
await command('Page.reload');
await until(
() =>
evaluate(
"document.getElementById('status').textContent.includes('Could not open saved data')",
),
'Denied browser storage did not show a recovery message',
);
assert.equal(
await evaluate("document.getElementById('backup').hidden"),
true,
'Unavailable data must not offer an empty backup',
);
await command('Page.removeScriptToEvaluateOnNewDocument', { identifier: blocked.identifier });
await command('Page.reload');
await until(ready, 'Saved data did not reopen after storage access returned');
assert.equal((await stored()).votes.length, 3, 'Storage startup failure changed saved ballots');
assert.equal(
await evaluate("typeof __ziranWeb==='undefined'||!__ziranWeb.error"),
true,
'The public browser bridge recorded an error',
);
assert.deepEqual(exceptions, [], 'Unexpected browser runtime exceptions');
console.log('Browser startup, reload persistence, process creation, backup download and save recovery: pass');
assert.deepEqual(networkFailures, [], 'Failed browser resource requests');
console.log(
`Browser ${site ? 'website' : 'distribution'}: native international editing, proposal/voting/results, separate participants, editing, tie/quorum, reload persistence, mobile touch, backup and save recovery: pass`,
);
} finally {
socket?.close();
browser.kill('SIGTERM');
await new Promise(resolve => { if (browser.exitCode !== null) resolve(); else browser.once('exit', resolve); });
await new Promise(resolve => server.close(resolve));
await rm(scratch, {recursive: true, force: true});
await new Promise((resolve) => {
if (browser.exitCode !== null) resolve();
else browser.once('exit', resolve);
});
await new Promise((resolve) => server.close(resolve));
await rm(scratch, { recursive: true, force: true });
}
+99
View File
@@ -0,0 +1,99 @@
// Native browser editing for the shared canvas fields: IME, touch keyboards,
// selection and clipboard stay under the browser's normal input policy.
class InputFields {
constructor(container) {
this.container = container;
this.fields = new Map();
this.encoder = new TextEncoder();
}
begin(top, height) {
this.top = top;
this.container.style.top = `${top}px`;
this.container.style.height = `${Math.max(0, height)}px`;
for (const field of this.fields.values()) field.seen = false;
if (document.title !== 'Ukuvota') document.title = 'Ukuvota';
}
field(id, label, placeholder, value, capacity, x, y, width, height) {
let field = this.fields.get(id);
if (!field) {
const input = document.createElement('input');
input.id = `field-${id}`;
input.type = 'text';
input.autocomplete = 'off';
input.spellcheck = false;
field = { input, model: value, seen: true, committed: false };
input.value = value;
for (const event of [
'keydown',
'keyup',
'keypress',
'paste',
'mousedown',
'mouseup',
'touchstart',
'touchmove',
'touchend',
]) {
input.addEventListener(event, (event) => event.stopPropagation());
}
input.addEventListener('keydown', (event) => {
if (event.key === 'Enter' && !event.isComposing) {
event.preventDefault();
field.committed = true;
}
if (event.key === 'Escape') input.blur();
});
input.addEventListener('input', () => {
if (this.encoder.encode(input.value).length > field.capacity) {
let length = 0;
let limited = '';
for (const character of input.value) {
length += this.encoder.encode(character).length;
if (length > field.capacity) break;
limited += character;
}
input.value = limited;
}
});
this.container.append(input);
this.fields.set(id, field);
}
const { input } = field;
field.seen = true;
field.capacity = capacity;
if (value !== field.model) input.value = value;
input.setAttribute('aria-label', label);
input.placeholder = placeholder;
input.maxLength = capacity;
Object.assign(input.style, {
left: `${x}px`,
top: `${y - this.top}px`,
width: `${width}px`,
height: `${height}px`,
});
const start = input.selectionStart ?? input.value.length;
const end = input.selectionEnd ?? start;
const backwards = input.selectionDirection === 'backward';
const result = {
value: input.value,
cursor: this.encoder.encode(input.value.slice(0, backwards ? start : end)).length,
anchor: this.encoder.encode(input.value.slice(0, backwards ? end : start)).length,
focused: document.activeElement === input,
committed: field.committed,
};
field.committed = false;
field.model = input.value;
return result;
}
end() {
for (const [id, field] of this.fields) {
if (!field.seen) {
field.input.remove();
this.fields.delete(id);
}
}
}
}