Merged
KVT-integratie: ci-lichter, Ponos-tegel, vensterknoppen, emoji, Asclepius-tegel/-formulier/-venster, minimale CI
iris bot
wants to merge
25 commits
from
kvt/integratie
into
master
Overview Commits 25 Pipelines 2 Changes 63
Eén integratiebranch (t2283u): alle openstaande KVT-branches in één keer naar master.
Samengevoegd, in volgorde: lichtere CI (ci-lichter), Ponos-tegel (het merge-commit van !12 is op de server verloren gegaan: master staat nog op c0b35d9c, daarom zit de tegel hier opnieuw bij), eigen vensterknoppen, custom emoji in reactiepillen, organisatie-emoji, Asclepius-tegel, nieuw-ticketformulier en ticketvenster.
Conflicten opgelost in crates/app/src/kvt/mod.rs, crates/app-base/locales/kvt.yml en KVT-FORK.md (beide kanten bewaard). Extra fix: de lege custom-emoji-placeholder gebruikt een zachte vulling in plaats van een harde rand (layout_guard).
Lokaal getest (profile ci, 2 jobs): kvt-sleutels 51, app-state 696, app 452 (incl. layout_guard), packaging/kvt/tests.sh ok. Alleen demomodus; nog niet tegen de echte sleutels.kvt.nl.
Activity
- iris Pipeline #533 is Failed 29 November 2026
- iris opened this merge request 29 November 2026
- iris Pipeline #534 is Warning 29 November 2026
-
iris
pushed
29 November 2026
ci(kvt): minimale pijplijn: lichte controle, zware tests handmatig, tag-pipeline alleen release
-
iris
changed the title
29 November 2026
KVT-integratie: ci-lichter, Ponos-tegel, vensterknoppen, emoji, Asclepius-tegel/-formulier/-venster, minimale CI
- iris marked this merge request as ready for review 29 November 2026
- iris merged this merge request 29 November 2026
Commits
- ci(kvt): minimale pijplijn: lichte controle, zware tests handmatig, tag-pipeline alleen release
9cbef4a51ehephaestus - fix(kvt): lege custom-emoji-placeholder met zachte vulling in plaats van harde rand (layout_guard)
be026c8217hephaestus - Merge commit '5763e9ae' into kvt/integratie
4bd63b3cefhephaestus - Merge commit 'd711d5ef' into kvt/integratie
8b0b99ca0chephaestus - Merge commit 'f88aaeed' into kvt/integratie
b81a5e2680hephaestus - Merge commit '373157c1' into kvt/integratie
4a09ee1f22hephaestus - Merge commit 'd19d4dfb' into kvt/integratie
898ff63bd1hephaestus - Merge commit 'c2a02c24' into kvt/integratie
24eb8c6e21hephaestus - Merge commit '9cb48ea6' into kvt/integratie
b168c815e3hephaestus - Merge commit '307baf14' into kvt/integratie
c3b0c7c8adhephaestus - ci(kvt): lichtere BlueGit-builds tegen piekgeheugen
307baf14fahephaestus - feat(kvt): ticketlinks openen in een ticketvenster als je toegang hebt, anders in de browser
5763e9ae70hephaestus - feat(kvt): nieuw-ticketformulier in de app, ook vanuit een bericht, met vermeldingen naar Asclepius
d711d5ef6bhephaestus - fix(kvt): demo-organisatie-emoji laden en inline tonen
373157c133hephaestus - feat(kvt): Asclepius-tegel met ticketlijst, gesprek en ghost-berichten zoals op het web
f88aaeed45hephaestus - fix(kvt): compileer organisatie-emoji-kiezers
f5f9bd9fe5hephaestus - feat(kvt): organisatie-emoji-documentatie en afronding (WIP, lokale back-up)
4116a7aba8hephaestus - feat(kvt): organisatie-emoji in composer en bijlagenbalk (WIP, lokale back-up)
d183cb8cd9hephaestus - feat(kvt): organisatie-emoji in de emoji-kiezer (WIP, lokale back-up)
bb4c02d6cahephaestus - feat(kvt): organisatie-emoji-metadata en afbeeldingen (WIP, lokale back-up)
43b862e01ahephaestus - feat(kvt): organisatie-emoji in berichten en uitgaande tekst (WIP, lokale back-up)
4dda6e1565hephaestus - feat(kvt): ophalen van organisatie-emoji-metadata (WIP, lokale back-up)
eba7c672cbhephaestus - fix: toon custom emoji in reactiepillen in plaats van 'custo'
d19d4dfbb4hephaestus - feat(kvt): eigen vensterknoppen in de titelbalk
c2a02c247ehephaestus - feat(kvt): Ponos-tegel in de navigatierail met volledig bord
9cb48ea6f3hephaestus
Pipelines
Changes
@@ -59,6 +59,12 @@ debug = "line-tables-only"
[profile.dev.package."*"]
debug = false
# BlueGit-CI: minder geheugen bij compileren en linken (blue-ci-cd.yml).
[profile.ci]
inherits = "dev"
incremental = false
debug = 0
[profile.release]
incremental = true
codegen-units = 256
@@ -59,6 +59,12 @@ debug = "line-tables-only"[profile.dev.package."*"][profile.dev.package."*"]debug = falsedebug = false# BlueGit-CI: minder geheugen bij compileren en linken (blue-ci-cd.yml).[profile.ci]inherits = "dev"incremental = falsedebug = 0[profile.release][profile.release]incremental = trueincremental = truecodegen-units = 256codegen-units = 256@@ -80,6 +80,39 @@ Merge-tip: `release_feed.rs` is het meest gevoelige upstream-bestand. Houd de ho
| Upstream aangeraakt | — |
| Commits / MR's | [!5](https://git.kvt.nl/ict/rusty-teams/-/merge-requests/5) `ed0382d` |
### Lichtere BlueGit-CI — branch `kvt/ci-lichter`
De Rust-test- en releasebuilds trokken de gedeelde git.kvt.nl-runner onderuit
(503). De jobs blijven hetzelfde, maar gebruiken minder piekgeheugen en niet
twee zware compiles tegelijk.
| | |
|---|---|
| Wat | `CARGO_BUILD_JOBS=2`, `RUST_TEST_THREADS=2`, `CARGO_INCREMENTAL=0`, `profile.ci` (`debug = 0`). `app_test` (nu handmatig) compileert één keer met `cargo test --no-run` en draait daarna dezelfde tests (kvt-update, updatertests, kvt-sleutels, `cargo check -p app`). `windows_release` wacht op `linux_release`. Tussen runs een Cargo/rustup-tarball: BlueGit cache't geen mappen, en `target/` is te groot voor de jobcache. |
| Eigen bestanden | `blue-ci-cd.yml`, `packaging/kvt/ci-cache.sh`, `packaging/kvt/ci-setup.sh` (Cargo/rustup in de werkmap onder `CI`) |
| Upstream aangeraakt | `Cargo.toml` (alleen `[profile.ci]`) |
| Commits / MR's | branch `kvt/ci-lichter` (MR volgt als de runners conservatief staan) |
Daarbovenop (Tim, t2294u: «alleen wat technisch minimaal vereist is voor een release build»):
- **Branch-push en merge request:** alleen `kvt_test`, nu zonder apt-installs en zonder cargo
(`bash -n` op `packaging/kvt/*.sh` en `packaging/kvt/tests.sh`).
- **`aur_check` en `app_test`** staan op `when: manual` (`allow_failure`): ze starten niet
vanzelf en blokkeren de pipeline niet. De volledige tests (`cargo test -p app`, `-p app-state`,
`-p kvt-sleutels`, `packaging/kvt/tests.sh`) draai je lokaal, met `CARGO_BUILD_JOBS=2` en
`--profile ci`, of je speelt de job bewust.
- **Tag-pipeline:** alleen `linux_release` → `checksums` → `release` → `publish_aur`, zonder
testjobs; `linux_release` wacht niet meer op `kvt_test`/`aur_check`.
- **`windows_release`** is handmatig (`allow_failure`) en geen voorwaarde meer voor `checksums` en
`release`. Een release zonder Windows-exe biedt Windows-installaties die versie niet aan;
speel je `windows_release` later alsnog, draai dan `checksums` en `release` opnieuw.
- **`ci-setup.sh`:** installeert `clang-21` via het apt.llvm.org-repo zelf en niet via `llvm.sh`
(dat ook lldb, lld en clangd bijzet), en laat `software-properties-common` weg.
Merge-tip: conflict in `blue-ci-cd.yml` of `Cargo.toml` alleen de KVT-jobs en
`[profile.ci]` terugzetten; de release-, AUR- en checksum-scripts zelf zijn
ongewijzigd.
### Thema "Koninklijke van Twist" — MR !4, accenten en typografie in MR !6
Een derde kleurenschema naast Rusty Teams en Teams, en het standaardthema voor nieuwe
@@ -199,17 +232,16 @@ chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0024.
Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0024.
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het nieuw-ticketformulier
van Asclepius in de browser met `new_title` (eerste regel, max. 150 tekens) en `new_description`
(het bericht als Markdown-citaat, afzender, tijd `15 jan 2026 13:39` en de Teams-link). Geen token
of API: de gebruiker kiest zelf de categorie en slaat op in Asclepius.
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het formulier
«Nieuw ticket maken» in de app (zie «Asclepius-tegel»), vooraf ingevuld: titel = eerste regel (max.
150 tekens), beschrijving = het bericht als Markdown-citaat met afzender, tijd `15 jan 2026 13:39`
en de Teams-link. Vermeldingen in het bericht worden `@naam:domein` (adres via het Teams-profiel,
best effort), zodat Asclepius ze herkent en die collega's deelnemer worden.
- **Taak maken in Ponos** (berichtmenu, «Create Ponos task»): dialoog met groepkeuze (groepen waar
je taken mag maken, laatst gekozen groep onthouden als id in de lokale opslag), titel en
omschrijving vooraf ingevuld zoals hierboven. Maakt de taak via `ponos_api.php` met de app-token.
- **Mijn taken** («…» rechtsboven > «My tasks in Ponos»): open taken die aan jou zijn toegewezen,
met groep, status en deadline (`15 jan 2026`, rood als die voorbij is). Vinkje = afronden, klik =
taak openen in Ponos. Ponos staat een app-token alleen taakacties toe (geen API-sleutels of
groepsbeheer).
- **Ponos-tegel** (navigatierail, direct onder Agents): zie «Ponos-bord» hieronder. Vervangt het
oude paneel «Mijn taken» in het «…»-menu.
- **Daedalus-planning in de agenda** (Instellingen > Algemeen > KVT, standaard aan): je eigen
werkorders uit `/daedalus/api/planning.php` als read-only afspraken (bron ICS, agenda «Daedalus»):
geen RSVP, geen verwijderen. Daedalus had geen ICS-abonnement; het endpoint geeft JSON (en ook
@@ -221,12 +253,51 @@ Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inl
| | |
|---|---|
| Eigen bestanden | `crates/kvt-sleutels/src/{asclepius,ponos,planning,format}.rs`.<br>`crates/app/src/kvt/{message,tasks,calendar}.rs`.<br>`crates/app-state/src/kvt_calendar.rs` |
| Upstream aangeraakt | `crates/app/src/views/message_actions.rs` (veld `kvt` in `MessageMenu`/`MenuActions`, regels na «Share to Outlook»).<br>`crates/app/src/views/conversation.rs` (`kvt: crate::kvt::menu_entries(...)` in `message_menu`).<br>`crates/app/src/views/status_menu.rs` (`crate::kvt::extend_settings_menu`).<br>`crates/app-state/src/call/week.rs` (demo-regel en het blok na de ICS-abonnementen).<br>`crates/app-state/src/lib.rs` (`mod kvt_calendar`) |
| Upstream aangeraakt | `crates/app/src/views/message_actions.rs` (veld `kvt` in `MessageMenu`/`MenuActions`, regels na «Share to Outlook»).<br>`crates/app/src/views/conversation.rs` (`kvt: crate::kvt::menu_entries(...)` in `message_menu`).<br>`crates/app-state/src/call/week.rs` (demo-regel en het blok na de ICS-abonnementen).<br>`crates/app-state/src/lib.rs` (`mod kvt_calendar`) |
Serverkant (geen deel van deze repo): `ict/ponos` (`ponos_app_token.php`: app-tokens met scope
`ponos` voor een vaste lijst taakacties) en `ict/daedalus` (`/daedalus/api/planning.php`, README
«Planning for native apps»).
### Ponos-bord (tegel in de navigatierail)
Op verzoek van Tim een eigen tegel «Ponos» in de navigatierail, direct onder Agents (altijd de laatste
tegel). Een klik opent het bord in het hoofdpaneel, net als Agenda en Gesprekken (de chatlijst gaat
dicht). Links alle groepen die `navigation` geeft, in de volgorde van Ponos, eerst «Mijn Taken» (de
persoonlijke groep: alles wat aan jou is toegewezen), met het aantal open taken. Rechts de kolommen
met de statusnamen van Ponos (todo / in_progress / done: «Nog te doen», «Onderhanden», «Afgerond»;
`kvt.board_status.*` alleen als terugval).
- Kaartje: titel, categorie, deadline (`15 jan 2026`, rood als die voorbij is), checklist (`1/4`),
toegewezen persoon (naam uit het adres, «Ik» voor jezelf); in «Mijn Taken» ook de groep.
- **Slepen** tussen en binnen kolommen: op een kaartje = erboven, op de kolom = onderaan. Lokaal
meteen, daarna `reorder_task` (kolom + plek) en opnieuw laden. In «Mijn Taken» verandert alleen de
status (`update_status`); die weergave heeft in Ponos geen eigen volgorde.
- **Nieuwe taak**: knop «Nieuwe taak» of «+» in een kolomkop (die status). Niet in «Mijn Taken» en
alleen in groepen met `can_create_tasks` en taaktoegang.
- **Bewerken** (klik op een kaartje): titel, omschrijving, status, deadline (`15 jan 2026`,
`15-01-2026`, `2026-01-15`; leeg = geen), toegewezen aan Niemand/Ik (een ander blijft staan) en
verplaatsen naar een andere groep. «Afronden», «Ponos openen». Alleen-lezen groepen: geen slepen
of opslaan.
- **Verwijderen** bestaat niet in Ponos (afgeronde taken gaan na een tijd vanzelf naar het archief);
het bord biedt daarom alleen «Afronden».
- De laatst gekozen groep staat als id in de lokale opslag (`kvt.ponos.board_group`).
- `--demo`: drie verzonnen groepen plus «Mijn Taken» met verzonnen taken (adressen op `example.com`);
wijzigingen blijven in het geheugen.
| | |
|---|---|
| Eigen bestanden | `crates/app/src/kvt/board.rs` (bord, slepen, bewerkvenster, demo).<br>`crates/kvt-sleutels/src/ponos.rs` (`ponos_navigation`, `ponos_tasks`, `ponos_create`, `ponos_update_task`, `ponos_reorder_task`, `ponos_set_status`, `drop_position`, `apply_move`, `name_from_email`, `group_url`), `format.rs` (`parse_date_input`).<br>`crates/app/src/kvt/demo.rs` (demobord), `crates/app-base/locales/kvt.yml` (`kvt.rail.*`, `kvt.board*`) |
| Upstream aangeraakt | `crates/app/src/views/rail.rs` (één `crate::kvt::with_rail_tiles` na `rail_items`, ook voor Asclepius).<br>`crates/app/src/views/sidebar.rs` (variant `SidebarTab::Ponos`, titel, `kvt::board_opened` in `open_tab`, drie match-armen).<br>`crates/app/src/views/shell.rs` (`ponos_open`, geen zijbalk, parameter `ponos` van `islands` als eerste arm van het hoofdpaneel).<br>`crates/app/src/views/status_menu.rs`: de KVT-regel «Mijn taken» is weer weg (bestand weer gelijk aan upstream). |
Serverkant: `ict/ponos` !8 — nieuwe actie `reorder_task` en het app-token mag nu ook
`update_task`, `move_task` en `reorder_task`.
Merge-tip: voegt upstream een `SidebarTab` toe, dan vraagt de compiler om de Ponos-arm in de
matches van `sidebar.rs`. Herschrijft upstream het hoofdpaneel in `shell.rs` (`islands`), zet dan de
`ponos`-arm weer als eerste. Komt er upstream een tegel bij, dan blijft Ponos de laatste
(`with_rail_tiles` hangt Ponos en Asclepius achteraan).
Merge-tip: herschrijft upstream `fill_rest` in `message_actions.rs` of het laadblok in `week.rs`, zet
dan de lus over `self.kvt` en het `kvt_calendar::source()`-blok terug; de rest staat in eigen bestanden.
@@ -239,6 +310,48 @@ terug. `browser/kvt.rs` gebruikt `cdp_call`, `CDP_TIMEOUT` en `OPEN_TAB_TIMEOUT`
hernoemt upstream die, pas dan alleen `kvt.rs` aan. De loopback-pagina en de PROBE-selector in
`kvt-sleutels/src/session.rs` volgen de markup van `app_connect.php` in `ict/login`.
### Asclepius-tegel (tickets in de navigatierail)
Op verzoek van Tim een tegel «Asclepius» direct onder Ponos (dus de laatste). De tegel laat zien
wat je op het web onder «Mijn tickets» ziet, met dezelfde zichtbaarheid: je eigen tickets, die waar
je deelnemer bent en die aan jou zijn toegewezen. Beheer (status, toewijzen, de ICT-lijst) blijft
in Asclepius (fase 2).
- **Lijst** links: standaard open tickets, filter «Open» / «Afgehandeld». Per ticket titel, nummer,
status en laatste wijziging (`15 jan 2026 13:39`).
- **Ongelezen** is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at` nieuwer is dan toen
je het opende, is vet met een stip; de tegel toont het aantal. De eerste keer telt alles als gelezen.
- **Gesprek** rechts: kop met nummer, status, categorie › subcategorie en aanmaakdatum; berichten
met afzender, «ICT» en tijd; bijlagen openen na downloaden met de token (tijdelijke map).
**Ghost-berichten** (alleen zichtbaar voor ICT) hebben de kleuren van het web (paars #5b21b6,
roze rand #f9a8d4), los van het thema.
- **@vermeldingen**: Asclepius schrijft `@jan:examplecom` voor `jan@example.com` (domein zonder punten); de tegel
toont `@Jan`, vet. Onder het antwoordveld staan knoppen «@naam» voor deelnemers en de behandelaar;
die zetten het token in de tekst, zodat Asclepius de vermelding herkent.
- **Antwoorden** via `add_ticket_message`. Heropenen (op het web een vinkje) blijft in Asclepius;
bij een afgehandeld ticket staat dat onder het antwoordveld.
- **Nieuw ticket maken** (knop in de kop, en vanuit het berichtmenu): de velden van het
webformulier: Titel, Categorie (zonder de ICT-categorieën Indiensttreding/Uitdiensttreding),
Subcategorie (alleen als de categorie die heeft, optioneel), Beschrijving, de twee vinkjes
«Mijn werkzaamheden worden belemmerd» / «Ik kan niet verder werken tot dit opgelost is» (het
tweede alleen met het eerste; prioriteit 0–2 zoals `getPriorityFromFlags`), Extra gebruikers
(optioneel, adressen gescheiden door komma's) en «Screenshots of documenten» (hooguit 10, elk
hooguit 10 MB, als base64 in de JSON). Na indienen opent het nieuwe ticket in de tegel.
- Elke minuut `ticket_updates` (`updated_since`); bij een wijziging laden lijst en gesprek opnieuw.
- **Ticketlinks** (`https://sleutels.kvt.nl/asclepius/index.php?open=…`, ook `admin.php`) in berichten
en kaartjes: de app haalt het ticket op met de token. Lukt dat (je hebt toegang), dan opent het in een
ticketvenster in de app (hetzelfde gesprek als in de tegel, met antwoordveld); zo niet (geen
toegang, niet gekoppeld of Asclepius onbereikbaar), dan gewoon in de browser.
- `--demo`: verzonnen tickets op `example.com`, met een ghost-bericht, een vermelding een bijlage en een ticketlink in de chat met Jonas Ortega (`app-state/src/kvt_demo.rs`).
| | |
|---|---|
| Eigen bestanden | `crates/kvt-sleutels/src/tickets.rs` (API, vermeldingen, ongelezen).<br>`crates/app/src/kvt/tickets.rs` (tegel, gesprek, demo).<br>`crates/app/src/kvt/ticket_form.rs` (nieuw-ticketformulier).<br>`crates/app/src/kvt/message.rs` (berichtmenu, vermelde personen).<br>`crates/kvt-sleutels/src/asclepius.rs` (`MessageSource` met `mentions`).<br>`crates/app-base/locales/kvt.yml` (`kvt.rail.asclepius`, `kvt.tickets.*`).<br>`crates/app/assets/symbols/confirmation_number.svg` (Material Symbols, Apache 2.0) |
| Upstream aangeraakt | `crates/app/src/views/rail.rs` (tegel in `with_rail_tiles`).<br>`crates/app/src/views/sidebar.rs` (variant `SidebarTab::Asclepius` in dezelfde armen als Ponos).<br>`crates/app/src/views/shell.rs` (`kvt_tab`: Ponos of Asclepius in het hoofdpaneel; eerste regel van `open_link`: `crate::kvt::open_ticket_link`).<br>`crates/app-base/src/assets.rs` (symbool `confirmation_number` en `icons/ticket.svg`).<br>`crates/app/src/layout_guard.rs` (uitzondering voor de roze ghost-rand) |
Serverkant: `ict/asclepius` — app-tokens (`sat_…`, `asclepius_app_token.php`), gefilterde lijst,
`ticket_updates` en bijlagen bij aanmaken.
### Nederlandse UI
De KVT-build heeft naast Engels en Duits ook Nederlands, en Nederlands is de standaard (besluit Tim,
@@ -256,19 +369,83 @@ tot er een `nl:`-regel bij staat; de test `every_key_resolves_in_english_and_ger
ontbreken. Bij een conflict in `app.yml` de upstream-versie nemen en de `nl:`-regels opnieuw
invoegen. Termen: «chat», «vergadering», «kanaal», «oproep», «agenda»; datums als «15 jan 2026».
### Eigen vensterknoppen
Op verzoek van Tim (t2263u): minimaliseren, maximaliseren/herstellen en sluiten als kleine
knoppen helemaal rechts in de titelbalk (na «…» en de avatar), in dezelfde stijl als de
andere titelbalkknoppen: chevron omlaag, chevron omhoog (herstellen: het bestaande
herstel-icoon) en een kruisje. Daarmee kunnen de vensterranden van het systeem weg, zonder
die functies te verliezen.
- Linux (KWin Wayland en X11) en Windows: bij een nieuwe installatie staan de eigen knoppen
aan en vraagt het hoofdvenster client-side decorations. Verslepen gaat via de lege
titelbalk, dubbelklikken maximaliseert, de randen en hoeken wijzigen de grootte
(bestaande GPUI-`WindowBorder` in `Root`).
- Instellingen › Weergave › «Eigen vensterknoppen» (standaard aan) zet het uit en brengt de
systeemranden terug. Een wijziging geldt meteen.
- Sluiten volgt dezelfde route als de systeemknop, inclusief «sluiten naar de tray».
- macOS houdt de verkeerslichten van het systeem; de instelling en de eigen knoppen blijven
daar weg.
- De ingebouwde vensterknoppen van de upstream-`TitleBar` (Windows-11-stijl) worden
verborgen zolang de KVT-knoppen aan staan, zodat ze niet verdubbelen.
| | |
|---|---|
| Wat | Eigen vensterknoppen in de titelbalk, client-side decorations, instelling |
| Eigen bestanden | `crates/app-base/src/kvt_window.rs` (opslag, standaard aan).<br>`crates/app/src/kvt/window_controls.rs` (knoppen, decorations, sluiten).<br>`crates/app-base/locales/kvt.yml` (`kvt.window.*`) |
| Upstream aangeraakt | `vendor/gpui-component/src/title_bar.rs` (`system_window_controls`, dubbelklik ook op Windows).<br>`crates/app/src/views/title_bar.rs` (die vlag).<br>`crates/app/src/views/shell.rs` (knoppen na avatar).<br>`crates/app/src/settings/appearance.rs` (schakelaar).<br>`crates/app/src/main.rs` (`window_decorations` van het hoofdvenster, `install`).<br>`crates/app-base/src/lib.rs` (`mod kvt_window`). |
Merge-tip: de haak in `title_bar.rs` van gpui-component is de nieuwe methode en de
Windows-tak van `on_double_click`. Blijft die bij een upstream-update weg, zet hem terug
en houd `system_window_controls(false)` in onze titelbalk.
### Custom emoji in reactiepillen — upstream-kandidaat
Graph levert een custom reactie als `reactionType: "custom"` met `displayName` en `reactionContentUrl`.
De fork bewaarde alleen het type, waardoor de pil de afgekorte tekst "custo" toonde in plaats van het plaatje.
Dit is geen KVT-specifiek gedrag: dezelfde Graph-payload geldt voor elke tenant. Geschikt om naar upstream te sturen.
| | |
|---|---|
| Wat | Custom emoji-reacties herkennen (Graph-velden en chatsvc-sleutel `naam;objectid`) en als plaatje tonen; nooit de ruwe sleutel in de pil |
| Eigen bestanden | — |
| Upstream aangeraakt | `crates/graph/src/models.rs`, `crates/core/src/mapping.rs`, `crates/chatsvc/src/reactions.rs`, `crates/chatsvc/src/links.rs`, `crates/app-state/src/rows.rs`, `crates/app-state/src/reaction_model.rs`, `crates/app/src/views/reaction_pills.rs`, `crates/app-base/locales/app.yml` |
### Organisatie-emoji in kiezer en berichten — upstream-kandidaat
De officiële webclient haalt de tenantlijst op via CSA
`GET /api/csa/{region}/api/v1/customemoji/metadata` met het bestaande CSA-token
(`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`). In een bericht
gaat een custom emoji als `<img itemtype="http://schema.skype.com/CustomEmoji" itemid="naam;objectId" …>`.
Een reactie gebruikt dezelfde sleutel `naam;objectId`. We cachen de lijst 30 minuten
in de store, met optionele delta via `x-ms-continuation`.
Aannames die nog live getest moeten worden: host (`teams.cloud.microsoft`, het CSA-host
van de andere calls hier), regio (`emea`), en of het CSA-token zonder extra scope volstaat.
De optionele Graph-beta-route `teamwork/messaging/customEmojis` is niet gebruikt.
| | |
|---|---|
| Wat | Organisatie-emoji ophalen en cachen, tab in emoji- en reactiekiezer, zoeken op naam, invoegen en verzenden in het officiële HTML-formaat, plus demomodus |
| Eigen bestanden | — |
| Upstream aangeraakt | `crates/chatsvc/src/custom_emojis.rs`, `crates/core/src/org_emojis.rs`, `crates/core/src/remote.rs`, `crates/core/src/spans.rs`, `crates/app-state/src/org_emojis.rs`, `crates/app-state/src/demo.rs`, `crates/app-state/src/stored_outgoing.rs`, `crates/app-base/src/remote_image.rs`, `crates/app/src/views/fun_picker.rs`, `crates/app/src/views/reaction_picker.rs`, `crates/app/src/views/attachment_tray.rs`, `crates/app/src/views/composer.rs`, `crates/app-base/locales/app.yml` |
## Eigen modules in het kort
| Pad | Rol |
|---|---|
| `crates/app-base/src/theme/kvt.rs` | Palet, WCAG-tests, DINPro-detectie |
| `crates/app-base/src/kvt_brand.rs` | Titelbalk-woordmerk (licht/donker) |
| `crates/app-base/src/kvt_feed.rs` | Releasefeed van git.kvt.nl |
| `crates/kvt-update/` | Vertaling van BlueGit-releases naar het updater-formaat, pakketvlag |
| `packaging/kvt/` | CI-setup, Windows-cross-build, AUR, release-assets |
| `packaging/kvt/` | CI-setup, CI-cache-tarball, Windows-cross-build, AUR, release-assets |
| `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren |
| `crates/app/assets/brand/` | Officieel woordmerk |
| `crates/kvt-sleutels/` | sleutels.kvt.nl: BC-links, Mímir-kaarten, Ponos, Daedalus-planning, Asclepius-link, koppelen (PKCE, loopback, sessietabblad), keyring |
| `crates/app/src/kvt/`, `settings/kvt.rs`, `composer/kvt.rs` | BC-kaarten, detailvenster, picker, berichtmenu (Asclepius, Ponos), Mijn taken, Daedalus-agenda, instellingen |
| `crates/kvt-sleutels/` | sleutels.kvt.nl: BC-links, Mímir-kaarten, Ponos (ook bord en slepen), Daedalus-planning, Asclepius-link en -tickets, koppelen (PKCE, loopback, sessietabblad), keyring |
| `crates/app/src/kvt/`, `settings/kvt.rs`, `composer/kvt.rs` | BC-kaarten, detailvenster, picker, berichtmenu (Asclepius, Ponos), Ponos-bord (tegel), Asclepius-tickets (tegel), Daedalus-agenda, instellingen |
| `crates/app-state/src/kvt_calendar.rs` | Haak voor de Daedalus-planning in de weekweergave |
| `crates/browser/src/browser/kvt.rs` | Los tabblad in de sessiebrowser voor het koppelen |
| `blue-ci-cd.yml` | Sync, test (ook `cargo test -p kvt-sleutels` in `app_test`), release, AUR (KVT-gedeelte) |
| `crates/app-base/src/kvt_window.rs`, `crates/app/src/kvt/window_controls.rs` | Eigen vensterknoppen en client-side decorations |
| `blue-ci-cd.yml` | Sync, lichte controle (`kvt_test`), zware tests alleen handmatig, minimale tag-pipeline (Linux-release, checksums, release, AUR; Windows handmatig) |
@@ -80,6 +80,39 @@ Merge-tip: `release_feed.rs` is het meest gevoelige upstream-bestand. Houd de ho| Upstream aangeraakt | — || Upstream aangeraakt | — || Commits / MR's | [!5](https://git.kvt.nl/ict/rusty-teams/-/merge-requests/5) `ed0382d` || Commits / MR's | [!5](https://git.kvt.nl/ict/rusty-teams/-/merge-requests/5) `ed0382d` |### Lichtere BlueGit-CI — branch `kvt/ci-lichter`De Rust-test- en releasebuilds trokken de gedeelde git.kvt.nl-runner onderuit(503). De jobs blijven hetzelfde, maar gebruiken minder piekgeheugen en niettwee zware compiles tegelijk.| | ||---|---|| Wat | `CARGO_BUILD_JOBS=2`, `RUST_TEST_THREADS=2`, `CARGO_INCREMENTAL=0`, `profile.ci` (`debug = 0`). `app_test` (nu handmatig) compileert één keer met `cargo test --no-run` en draait daarna dezelfde tests (kvt-update, updatertests, kvt-sleutels, `cargo check -p app`). `windows_release` wacht op `linux_release`. Tussen runs een Cargo/rustup-tarball: BlueGit cache't geen mappen, en `target/` is te groot voor de jobcache. || Eigen bestanden | `blue-ci-cd.yml`, `packaging/kvt/ci-cache.sh`, `packaging/kvt/ci-setup.sh` (Cargo/rustup in de werkmap onder `CI`) || Upstream aangeraakt | `Cargo.toml` (alleen `[profile.ci]`) || Commits / MR's | branch `kvt/ci-lichter` (MR volgt als de runners conservatief staan) |Daarbovenop (Tim, t2294u: «alleen wat technisch minimaal vereist is voor een release build»):- **Branch-push en merge request:** alleen `kvt_test`, nu zonder apt-installs en zonder cargo (`bash -n` op `packaging/kvt/*.sh` en `packaging/kvt/tests.sh`).- **`aur_check` en `app_test`** staan op `when: manual` (`allow_failure`): ze starten niet vanzelf en blokkeren de pipeline niet. De volledige tests (`cargo test -p app`, `-p app-state`, `-p kvt-sleutels`, `packaging/kvt/tests.sh`) draai je lokaal, met `CARGO_BUILD_JOBS=2` en `--profile ci`, of je speelt de job bewust.- **Tag-pipeline:** alleen `linux_release` → `checksums` → `release` → `publish_aur`, zonder testjobs; `linux_release` wacht niet meer op `kvt_test`/`aur_check`.- **`windows_release`** is handmatig (`allow_failure`) en geen voorwaarde meer voor `checksums` en `release`. Een release zonder Windows-exe biedt Windows-installaties die versie niet aan; speel je `windows_release` later alsnog, draai dan `checksums` en `release` opnieuw.- **`ci-setup.sh`:** installeert `clang-21` via het apt.llvm.org-repo zelf en niet via `llvm.sh` (dat ook lldb, lld en clangd bijzet), en laat `software-properties-common` weg.Merge-tip: conflict in `blue-ci-cd.yml` of `Cargo.toml` alleen de KVT-jobs en`[profile.ci]` terugzetten; de release-, AUR- en checksum-scripts zelf zijnongewijzigd.### Thema "Koninklijke van Twist" — MR !4, accenten en typografie in MR !6### Thema "Koninklijke van Twist" — MR !4, accenten en typografie in MR !6Een derde kleurenschema naast Rusty Teams en Teams, en het standaardthema voor nieuweEen derde kleurenschema naast Rusty Teams en Teams, en het standaardthema voor nieuwe@@ -199,17 +232,16 @@ chat met Jonas Ortega en verzonnen kaarten. Besluit: ADR 0024.Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0024.Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0024.- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het nieuw-ticketformulier- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het formulier van Asclepius in de browser met `new_title` (eerste regel, max. 150 tekens) en `new_description` «Nieuw ticket maken» in de app (zie «Asclepius-tegel»), vooraf ingevuld: titel = eerste regel (max. (het bericht als Markdown-citaat, afzender, tijd `15 jan 2026 13:39` en de Teams-link). Geen token 150 tekens), beschrijving = het bericht als Markdown-citaat met afzender, tijd `15 jan 2026 13:39` of API: de gebruiker kiest zelf de categorie en slaat op in Asclepius. en de Teams-link. Vermeldingen in het bericht worden `@naam:domein` (adres via het Teams-profiel, best effort), zodat Asclepius ze herkent en die collega's deelnemer worden.- **Taak maken in Ponos** (berichtmenu, «Create Ponos task»): dialoog met groepkeuze (groepen waar- **Taak maken in Ponos** (berichtmenu, «Create Ponos task»): dialoog met groepkeuze (groepen waar je taken mag maken, laatst gekozen groep onthouden als id in de lokale opslag), titel en je taken mag maken, laatst gekozen groep onthouden als id in de lokale opslag), titel en omschrijving vooraf ingevuld zoals hierboven. Maakt de taak via `ponos_api.php` met de app-token. omschrijving vooraf ingevuld zoals hierboven. Maakt de taak via `ponos_api.php` met de app-token.- **Mijn taken** («…» rechtsboven > «My tasks in Ponos»): open taken die aan jou zijn toegewezen,- **Ponos-tegel** (navigatierail, direct onder Agents): zie «Ponos-bord» hieronder. Vervangt het met groep, status en deadline (`15 jan 2026`, rood als die voorbij is). Vinkje = afronden, klik = oude paneel «Mijn taken» in het «…»-menu. taak openen in Ponos. Ponos staat een app-token alleen taakacties toe (geen API-sleutels of groepsbeheer).- **Daedalus-planning in de agenda** (Instellingen > Algemeen > KVT, standaard aan): je eigen- **Daedalus-planning in de agenda** (Instellingen > Algemeen > KVT, standaard aan): je eigen werkorders uit `/daedalus/api/planning.php` als read-only afspraken (bron ICS, agenda «Daedalus»): werkorders uit `/daedalus/api/planning.php` als read-only afspraken (bron ICS, agenda «Daedalus»): geen RSVP, geen verwijderen. Daedalus had geen ICS-abonnement; het endpoint geeft JSON (en ook geen RSVP, geen verwijderen. Daedalus had geen ICS-abonnement; het endpoint geeft JSON (en ook@@ -221,12 +253,51 @@ Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inl| | || | ||---|---||---|---|| Eigen bestanden | `crates/kvt-sleutels/src/{asclepius,ponos,planning,format}.rs`.<br>`crates/app/src/kvt/{message,tasks,calendar}.rs`.<br>`crates/app-state/src/kvt_calendar.rs` || Eigen bestanden | `crates/kvt-sleutels/src/{asclepius,ponos,planning,format}.rs`.<br>`crates/app/src/kvt/{message,tasks,calendar}.rs`.<br>`crates/app-state/src/kvt_calendar.rs` || Upstream aangeraakt | `crates/app/src/views/message_actions.rs` (veld `kvt` in `MessageMenu`/`MenuActions`, regels na «Share to Outlook»).<br>`crates/app/src/views/conversation.rs` (`kvt: crate::kvt::menu_entries(...)` in `message_menu`).<br>`crates/app/src/views/status_menu.rs` (`crate::kvt::extend_settings_menu`).<br>`crates/app-state/src/call/week.rs` (demo-regel en het blok na de ICS-abonnementen).<br>`crates/app-state/src/lib.rs` (`mod kvt_calendar`) || Upstream aangeraakt | `crates/app/src/views/message_actions.rs` (veld `kvt` in `MessageMenu`/`MenuActions`, regels na «Share to Outlook»).<br>`crates/app/src/views/conversation.rs` (`kvt: crate::kvt::menu_entries(...)` in `message_menu`).<br>`crates/app-state/src/call/week.rs` (demo-regel en het blok na de ICS-abonnementen).<br>`crates/app-state/src/lib.rs` (`mod kvt_calendar`) |Serverkant (geen deel van deze repo): `ict/ponos` (`ponos_app_token.php`: app-tokens met scopeServerkant (geen deel van deze repo): `ict/ponos` (`ponos_app_token.php`: app-tokens met scope`ponos` voor een vaste lijst taakacties) en `ict/daedalus` (`/daedalus/api/planning.php`, README`ponos` voor een vaste lijst taakacties) en `ict/daedalus` (`/daedalus/api/planning.php`, README«Planning for native apps»).«Planning for native apps»).### Ponos-bord (tegel in de navigatierail)Op verzoek van Tim een eigen tegel «Ponos» in de navigatierail, direct onder Agents (altijd de laatstetegel). Een klik opent het bord in het hoofdpaneel, net als Agenda en Gesprekken (de chatlijst gaatdicht). Links alle groepen die `navigation` geeft, in de volgorde van Ponos, eerst «Mijn Taken» (depersoonlijke groep: alles wat aan jou is toegewezen), met het aantal open taken. Rechts de kolommenmet de statusnamen van Ponos (todo / in_progress / done: «Nog te doen», «Onderhanden», «Afgerond»;`kvt.board_status.*` alleen als terugval).- Kaartje: titel, categorie, deadline (`15 jan 2026`, rood als die voorbij is), checklist (`1/4`), toegewezen persoon (naam uit het adres, «Ik» voor jezelf); in «Mijn Taken» ook de groep.- **Slepen** tussen en binnen kolommen: op een kaartje = erboven, op de kolom = onderaan. Lokaal meteen, daarna `reorder_task` (kolom + plek) en opnieuw laden. In «Mijn Taken» verandert alleen de status (`update_status`); die weergave heeft in Ponos geen eigen volgorde.- **Nieuwe taak**: knop «Nieuwe taak» of «+» in een kolomkop (die status). Niet in «Mijn Taken» en alleen in groepen met `can_create_tasks` en taaktoegang.- **Bewerken** (klik op een kaartje): titel, omschrijving, status, deadline (`15 jan 2026`, `15-01-2026`, `2026-01-15`; leeg = geen), toegewezen aan Niemand/Ik (een ander blijft staan) en verplaatsen naar een andere groep. «Afronden», «Ponos openen». Alleen-lezen groepen: geen slepen of opslaan.- **Verwijderen** bestaat niet in Ponos (afgeronde taken gaan na een tijd vanzelf naar het archief); het bord biedt daarom alleen «Afronden».- De laatst gekozen groep staat als id in de lokale opslag (`kvt.ponos.board_group`).- `--demo`: drie verzonnen groepen plus «Mijn Taken» met verzonnen taken (adressen op `example.com`); wijzigingen blijven in het geheugen.| | ||---|---|| Eigen bestanden | `crates/app/src/kvt/board.rs` (bord, slepen, bewerkvenster, demo).<br>`crates/kvt-sleutels/src/ponos.rs` (`ponos_navigation`, `ponos_tasks`, `ponos_create`, `ponos_update_task`, `ponos_reorder_task`, `ponos_set_status`, `drop_position`, `apply_move`, `name_from_email`, `group_url`), `format.rs` (`parse_date_input`).<br>`crates/app/src/kvt/demo.rs` (demobord), `crates/app-base/locales/kvt.yml` (`kvt.rail.*`, `kvt.board*`) || Upstream aangeraakt | `crates/app/src/views/rail.rs` (één `crate::kvt::with_rail_tiles` na `rail_items`, ook voor Asclepius).<br>`crates/app/src/views/sidebar.rs` (variant `SidebarTab::Ponos`, titel, `kvt::board_opened` in `open_tab`, drie match-armen).<br>`crates/app/src/views/shell.rs` (`ponos_open`, geen zijbalk, parameter `ponos` van `islands` als eerste arm van het hoofdpaneel).<br>`crates/app/src/views/status_menu.rs`: de KVT-regel «Mijn taken» is weer weg (bestand weer gelijk aan upstream). |Serverkant: `ict/ponos` !8 — nieuwe actie `reorder_task` en het app-token mag nu ook`update_task`, `move_task` en `reorder_task`.Merge-tip: voegt upstream een `SidebarTab` toe, dan vraagt de compiler om de Ponos-arm in dematches van `sidebar.rs`. Herschrijft upstream het hoofdpaneel in `shell.rs` (`islands`), zet dan de`ponos`-arm weer als eerste. Komt er upstream een tegel bij, dan blijft Ponos de laatste(`with_rail_tiles` hangt Ponos en Asclepius achteraan).Merge-tip: herschrijft upstream `fill_rest` in `message_actions.rs` of het laadblok in `week.rs`, zetMerge-tip: herschrijft upstream `fill_rest` in `message_actions.rs` of het laadblok in `week.rs`, zetdan de lus over `self.kvt` en het `kvt_calendar::source()`-blok terug; de rest staat in eigen bestanden.dan de lus over `self.kvt` en het `kvt_calendar::source()`-blok terug; de rest staat in eigen bestanden.@@ -239,6 +310,48 @@ terug. `browser/kvt.rs` gebruikt `cdp_call`, `CDP_TIMEOUT` en `OPEN_TAB_TIMEOUT`hernoemt upstream die, pas dan alleen `kvt.rs` aan. De loopback-pagina en de PROBE-selector inhernoemt upstream die, pas dan alleen `kvt.rs` aan. De loopback-pagina en de PROBE-selector in`kvt-sleutels/src/session.rs` volgen de markup van `app_connect.php` in `ict/login`.`kvt-sleutels/src/session.rs` volgen de markup van `app_connect.php` in `ict/login`.### Asclepius-tegel (tickets in de navigatierail)Op verzoek van Tim een tegel «Asclepius» direct onder Ponos (dus de laatste). De tegel laat zienwat je op het web onder «Mijn tickets» ziet, met dezelfde zichtbaarheid: je eigen tickets, die waarje deelnemer bent en die aan jou zijn toegewezen. Beheer (status, toewijzen, de ICT-lijst) blijftin Asclepius (fase 2).- **Lijst** links: standaard open tickets, filter «Open» / «Afgehandeld». Per ticket titel, nummer, status en laatste wijziging (`15 jan 2026 13:39`).- **Ongelezen** is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at` nieuwer is dan toen je het opende, is vet met een stip; de tegel toont het aantal. De eerste keer telt alles als gelezen.- **Gesprek** rechts: kop met nummer, status, categorie › subcategorie en aanmaakdatum; berichten met afzender, «ICT» en tijd; bijlagen openen na downloaden met de token (tijdelijke map). **Ghost-berichten** (alleen zichtbaar voor ICT) hebben de kleuren van het web (paars #5b21b6, roze rand #f9a8d4), los van het thema.- **@vermeldingen**: Asclepius schrijft `@jan:examplecom` voor `jan@example.com` (domein zonder punten); de tegel toont `@Jan`, vet. Onder het antwoordveld staan knoppen «@naam» voor deelnemers en de behandelaar; die zetten het token in de tekst, zodat Asclepius de vermelding herkent.- **Antwoorden** via `add_ticket_message`. Heropenen (op het web een vinkje) blijft in Asclepius; bij een afgehandeld ticket staat dat onder het antwoordveld.- **Nieuw ticket maken** (knop in de kop, en vanuit het berichtmenu): de velden van het webformulier: Titel, Categorie (zonder de ICT-categorieën Indiensttreding/Uitdiensttreding), Subcategorie (alleen als de categorie die heeft, optioneel), Beschrijving, de twee vinkjes «Mijn werkzaamheden worden belemmerd» / «Ik kan niet verder werken tot dit opgelost is» (het tweede alleen met het eerste; prioriteit 0–2 zoals `getPriorityFromFlags`), Extra gebruikers (optioneel, adressen gescheiden door komma's) en «Screenshots of documenten» (hooguit 10, elk hooguit 10 MB, als base64 in de JSON). Na indienen opent het nieuwe ticket in de tegel.- Elke minuut `ticket_updates` (`updated_since`); bij een wijziging laden lijst en gesprek opnieuw.- **Ticketlinks** (`https://sleutels.kvt.nl/asclepius/index.php?open=…`, ook `admin.php`) in berichten en kaartjes: de app haalt het ticket op met de token. Lukt dat (je hebt toegang), dan opent het in een ticketvenster in de app (hetzelfde gesprek als in de tegel, met antwoordveld); zo niet (geen toegang, niet gekoppeld of Asclepius onbereikbaar), dan gewoon in de browser.- `--demo`: verzonnen tickets op `example.com`, met een ghost-bericht, een vermelding een bijlage en een ticketlink in de chat met Jonas Ortega (`app-state/src/kvt_demo.rs`).| | ||---|---|| Eigen bestanden | `crates/kvt-sleutels/src/tickets.rs` (API, vermeldingen, ongelezen).<br>`crates/app/src/kvt/tickets.rs` (tegel, gesprek, demo).<br>`crates/app/src/kvt/ticket_form.rs` (nieuw-ticketformulier).<br>`crates/app/src/kvt/message.rs` (berichtmenu, vermelde personen).<br>`crates/kvt-sleutels/src/asclepius.rs` (`MessageSource` met `mentions`).<br>`crates/app-base/locales/kvt.yml` (`kvt.rail.asclepius`, `kvt.tickets.*`).<br>`crates/app/assets/symbols/confirmation_number.svg` (Material Symbols, Apache 2.0) || Upstream aangeraakt | `crates/app/src/views/rail.rs` (tegel in `with_rail_tiles`).<br>`crates/app/src/views/sidebar.rs` (variant `SidebarTab::Asclepius` in dezelfde armen als Ponos).<br>`crates/app/src/views/shell.rs` (`kvt_tab`: Ponos of Asclepius in het hoofdpaneel; eerste regel van `open_link`: `crate::kvt::open_ticket_link`).<br>`crates/app-base/src/assets.rs` (symbool `confirmation_number` en `icons/ticket.svg`).<br>`crates/app/src/layout_guard.rs` (uitzondering voor de roze ghost-rand) |Serverkant: `ict/asclepius` — app-tokens (`sat_…`, `asclepius_app_token.php`), gefilterde lijst,`ticket_updates` en bijlagen bij aanmaken.### Nederlandse UI### Nederlandse UIDe KVT-build heeft naast Engels en Duits ook Nederlands, en Nederlands is de standaard (besluit Tim,De KVT-build heeft naast Engels en Duits ook Nederlands, en Nederlands is de standaard (besluit Tim,@@ -256,19 +369,83 @@ tot er een `nl:`-regel bij staat; de test `every_key_resolves_in_english_and_gerontbreken. Bij een conflict in `app.yml` de upstream-versie nemen en de `nl:`-regels opnieuwontbreken. Bij een conflict in `app.yml` de upstream-versie nemen en de `nl:`-regels opnieuwinvoegen. Termen: «chat», «vergadering», «kanaal», «oproep», «agenda»; datums als «15 jan 2026».invoegen. Termen: «chat», «vergadering», «kanaal», «oproep», «agenda»; datums als «15 jan 2026».### Eigen vensterknoppenOp verzoek van Tim (t2263u): minimaliseren, maximaliseren/herstellen en sluiten als kleineknoppen helemaal rechts in de titelbalk (na «…» en de avatar), in dezelfde stijl als deandere titelbalkknoppen: chevron omlaag, chevron omhoog (herstellen: het bestaandeherstel-icoon) en een kruisje. Daarmee kunnen de vensterranden van het systeem weg, zonderdie functies te verliezen.- Linux (KWin Wayland en X11) en Windows: bij een nieuwe installatie staan de eigen knoppen aan en vraagt het hoofdvenster client-side decorations. Verslepen gaat via de lege titelbalk, dubbelklikken maximaliseert, de randen en hoeken wijzigen de grootte (bestaande GPUI-`WindowBorder` in `Root`).- Instellingen › Weergave › «Eigen vensterknoppen» (standaard aan) zet het uit en brengt de systeemranden terug. Een wijziging geldt meteen.- Sluiten volgt dezelfde route als de systeemknop, inclusief «sluiten naar de tray».- macOS houdt de verkeerslichten van het systeem; de instelling en de eigen knoppen blijven daar weg.- De ingebouwde vensterknoppen van de upstream-`TitleBar` (Windows-11-stijl) worden verborgen zolang de KVT-knoppen aan staan, zodat ze niet verdubbelen.| | ||---|---|| Wat | Eigen vensterknoppen in de titelbalk, client-side decorations, instelling || Eigen bestanden | `crates/app-base/src/kvt_window.rs` (opslag, standaard aan).<br>`crates/app/src/kvt/window_controls.rs` (knoppen, decorations, sluiten).<br>`crates/app-base/locales/kvt.yml` (`kvt.window.*`) || Upstream aangeraakt | `vendor/gpui-component/src/title_bar.rs` (`system_window_controls`, dubbelklik ook op Windows).<br>`crates/app/src/views/title_bar.rs` (die vlag).<br>`crates/app/src/views/shell.rs` (knoppen na avatar).<br>`crates/app/src/settings/appearance.rs` (schakelaar).<br>`crates/app/src/main.rs` (`window_decorations` van het hoofdvenster, `install`).<br>`crates/app-base/src/lib.rs` (`mod kvt_window`). |Merge-tip: de haak in `title_bar.rs` van gpui-component is de nieuwe methode en deWindows-tak van `on_double_click`. Blijft die bij een upstream-update weg, zet hem terugen houd `system_window_controls(false)` in onze titelbalk.### Custom emoji in reactiepillen — upstream-kandidaatGraph levert een custom reactie als `reactionType: "custom"` met `displayName` en `reactionContentUrl`.De fork bewaarde alleen het type, waardoor de pil de afgekorte tekst "custo" toonde in plaats van het plaatje.Dit is geen KVT-specifiek gedrag: dezelfde Graph-payload geldt voor elke tenant. Geschikt om naar upstream te sturen.| | ||---|---|| Wat | Custom emoji-reacties herkennen (Graph-velden en chatsvc-sleutel `naam;objectid`) en als plaatje tonen; nooit de ruwe sleutel in de pil || Eigen bestanden | — || Upstream aangeraakt | `crates/graph/src/models.rs`, `crates/core/src/mapping.rs`, `crates/chatsvc/src/reactions.rs`, `crates/chatsvc/src/links.rs`, `crates/app-state/src/rows.rs`, `crates/app-state/src/reaction_model.rs`, `crates/app/src/views/reaction_pills.rs`, `crates/app-base/locales/app.yml` |### Organisatie-emoji in kiezer en berichten — upstream-kandidaatDe officiële webclient haalt de tenantlijst op via CSA`GET /api/csa/{region}/api/v1/customemoji/metadata` met het bestaande CSA-token(`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`). In een berichtgaat een custom emoji als `<img itemtype="http://schema.skype.com/CustomEmoji" itemid="naam;objectId" …>`.Een reactie gebruikt dezelfde sleutel `naam;objectId`. We cachen de lijst 30 minutenin de store, met optionele delta via `x-ms-continuation`.Aannames die nog live getest moeten worden: host (`teams.cloud.microsoft`, het CSA-hostvan de andere calls hier), regio (`emea`), en of het CSA-token zonder extra scope volstaat.De optionele Graph-beta-route `teamwork/messaging/customEmojis` is niet gebruikt.| | ||---|---|| Wat | Organisatie-emoji ophalen en cachen, tab in emoji- en reactiekiezer, zoeken op naam, invoegen en verzenden in het officiële HTML-formaat, plus demomodus || Eigen bestanden | — || Upstream aangeraakt | `crates/chatsvc/src/custom_emojis.rs`, `crates/core/src/org_emojis.rs`, `crates/core/src/remote.rs`, `crates/core/src/spans.rs`, `crates/app-state/src/org_emojis.rs`, `crates/app-state/src/demo.rs`, `crates/app-state/src/stored_outgoing.rs`, `crates/app-base/src/remote_image.rs`, `crates/app/src/views/fun_picker.rs`, `crates/app/src/views/reaction_picker.rs`, `crates/app/src/views/attachment_tray.rs`, `crates/app/src/views/composer.rs`, `crates/app-base/locales/app.yml` |## Eigen modules in het kort## Eigen modules in het kort| Pad | Rol || Pad | Rol ||---|---||---|---|| `crates/app-base/src/theme/kvt.rs` | Palet, WCAG-tests, DINPro-detectie || `crates/app-base/src/theme/kvt.rs` | Palet, WCAG-tests, DINPro-detectie || `crates/app-base/src/kvt_brand.rs` | Titelbalk-woordmerk (licht/donker) || `crates/app-base/src/kvt_brand.rs` | Titelbalk-woordmerk (licht/donker) || `crates/app-base/src/kvt_feed.rs` | Releasefeed van git.kvt.nl || `crates/app-base/src/kvt_feed.rs` | Releasefeed van git.kvt.nl || `crates/kvt-update/` | Vertaling van BlueGit-releases naar het updater-formaat, pakketvlag || `crates/kvt-update/` | Vertaling van BlueGit-releases naar het updater-formaat, pakketvlag || `packaging/kvt/` | CI-setup, Windows-cross-build, AUR, release-assets || `packaging/kvt/` | CI-setup, CI-cache-tarball, Windows-cross-build, AUR, release-assets || `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren || `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren || `crates/app/assets/brand/` | Officieel woordmerk || `crates/app/assets/brand/` | Officieel woordmerk || `crates/kvt-sleutels/` | sleutels.kvt.nl: BC-links, Mímir-kaarten, Ponos, Daedalus-planning, Asclepius-link, koppelen (PKCE, loopback, sessietabblad), keyring || `crates/kvt-sleutels/` | sleutels.kvt.nl: BC-links, Mímir-kaarten, Ponos (ook bord en slepen), Daedalus-planning, Asclepius-link en -tickets, koppelen (PKCE, loopback, sessietabblad), keyring || `crates/app/src/kvt/`, `settings/kvt.rs`, `composer/kvt.rs` | BC-kaarten, detailvenster, picker, berichtmenu (Asclepius, Ponos), Mijn taken, Daedalus-agenda, instellingen || `crates/app/src/kvt/`, `settings/kvt.rs`, `composer/kvt.rs` | BC-kaarten, detailvenster, picker, berichtmenu (Asclepius, Ponos), Ponos-bord (tegel), Asclepius-tickets (tegel), Daedalus-agenda, instellingen || `crates/app-state/src/kvt_calendar.rs` | Haak voor de Daedalus-planning in de weekweergave || `crates/app-state/src/kvt_calendar.rs` | Haak voor de Daedalus-planning in de weekweergave || `crates/browser/src/browser/kvt.rs` | Los tabblad in de sessiebrowser voor het koppelen || `crates/browser/src/browser/kvt.rs` | Los tabblad in de sessiebrowser voor het koppelen || `blue-ci-cd.yml` | Sync, test (ook `cargo test -p kvt-sleutels` in `app_test`), release, AUR (KVT-gedeelte) || `crates/app-base/src/kvt_window.rs`, `crates/app/src/kvt/window_controls.rs` | Eigen vensterknoppen en client-side decorations || `blue-ci-cd.yml` | Sync, lichte controle (`kvt_test`), zware tests alleen handmatig, minimale tag-pipeline (Linux-release, checksums, release, AUR; Windows handmatig) |@@ -7,14 +7,24 @@
# (knop "Run pipeline" op master, of
# POST /api/v1/projects/ict/rusty-teams/pipelines {"ref": "master"}),
# nooit bij een push, tag of merge request.
# 2. Controle bij een merge request of push: kvt_test (de KVT-crate en
# -scripts, snel), aur_check (PKGBUILD en .SRCINFO in Arch) en app_test
# (bouwt app-base en app, draait de updatertests en de kvt-sleutels-tests;
# alleen als Rust-code of Cargo-bestanden veranderen).
# 3. Release bij een tag v* (schema v<versie>-kvt.<n>, bijvoorbeeld v0.6.1-kvt.1):
# 2. Controle bij een merge request of branch-push: alleen kvt_test (shell-
# syntaxis en packaging/kvt/tests.sh, zonder compileren of installs).
# De zware jobs aur_check en app_test (één keer compileren met
# `cargo test --no-run`, daarna kvt-update, updatertests, kvt-sleutels en
# `cargo check -p app`) staan op `when: manual` en starten niet vanzelf: ze
# hebben de gedeelde BlueGit-runner herhaaldelijk onderuit gehaald. Draai de
# volledige tests lokaal (cargo test -p app / -p app-state / -p kvt-sleutels)
# of start de jobs bewust met "play".
# Rust-jobs gebruiken CARGO_BUILD_JOBS=2, RUST_TEST_THREADS=2,
# CARGO_INCREMENTAL=0 en profile.ci (debug=0). Tussen runs bewaren ze
# een Cargo/rustup-tarball: BlueGit cache't geen mappen, en target/
# is te groot voor de jobcache.
# 3. Release bij een tag v* (schema v<versie>-kvt.<n>, bijvoorbeeld v0.6.1-kvt.1).
# Een tag-pipeline bevat alleen wat voor de release nodig is, zonder tests:
# linux_release Linux-binary + FHS-tarball (packaging/linux/package.sh)
# windows_release teams.exe, cross-build met cargo-xwin en fxc onder wine
# (allow_failure: zonder exe gaat de release door)
# windows_release handmatig (when: manual, allow_failure): teams.exe,
# cross-build met cargo-xwin en fxc onder wine. Zwaar, dus
# niet automatisch; de release gaat zonder exe door
# checksums SHA256SUMS van alle assets
# release maakt de release op git.kvt.nl met de assets
# publish_aur AUR-pakket kvt-rusty-teams-bin (allow_failure; slaat
@@ -98,35 +108,52 @@ sync-upstream:
# KVT: controle, release, AUR. Alles hieronder staat los van sync-upstream.
# ---------------------------------------------------------------------------
# Lichte controle: bij een merge request en een branch-push, niet in een tag-pipeline.
.kvt_check:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/
# Zware controle: alleen op verzoek (play), nooit automatisch.
.kvt_manual_check:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
allow_failure: true
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null
when: manual
allow_failure: true
.kvt_tag:
rules:
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/
# De KVT-crate (BlueGit-releasefeed, versies, assetnamen, pakketbeheer-vlag) en
# de scripts in packaging/kvt. Klein en snel.
# Minder piekgeheugen op de gedeelde BlueGit-runner.
.kvt_rust:
variables:
CARGO_INCREMENTAL: "0"
CARGO_BUILD_JOBS: "2"
RUST_TEST_THREADS: "2"
# De scripts in packaging/kvt (shell-syntaxis en tests.sh). Geen apt-installs en
# geen cargo: de kvt-update-tests draaien in app_test (handmatig) en lokaal.
kvt_test:
stage: test
image: rust:1-bookworm
extends: .kvt_check
needs: []
timeout: 30m
timeout: 10m
script:
- apt-get update -qq && apt-get install -y -qq --no-install-recommends clang mold >/dev/null
- cargo test -p kvt-update --locked
- for f in packaging/kvt/*.sh; do bash -n "$f"; done
- packaging/kvt/tests.sh
# PKGBUILD renderen en .SRCINFO maken op Arch, zoals publish_aur dat doet.
# Handmatig: de Arch-image is zwaar, en publish_aur doet dezelfde render bij een release.
aur_check:
stage: test
image: archlinux/archlinux:base-devel
extends: .kvt_check
extends: .kvt_manual_check
allow_failure: true
needs: []
timeout: 20m
script:
@@ -143,29 +170,36 @@ aur_check:
grep -q 'source = rusty-teams-0.0.1-kvt.1-linux-x86_64.tar.gz::https://git.kvt.nl/' "$out/.SRCINFO"
grep -qP '^\tpkgver = 0\.0\.1\.kvt\.1$' "$out/.SRCINFO"
# Bouwt app-base en app en draait de updatertests (release_feed, kvt_feed) en
# de tests van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen).
# Alleen als Rust-code of Cargo-bestanden veranderen; zwaar (volledige build).
# Bouwt één keer (cargo test --no-run) en draait daarna dezelfde tests als
# voorheen: kvt-update, de updatertests (release_feed, kvt_feed) en de tests
# van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen), plus
# cargo check -p app. Handmatig (play): zwaar, start niet vanzelf.
app_test:
stage: test
image: ubuntu:22.04
extends: [.kvt_manual_check, .kvt_rust]
allow_failure: true
needs: []
timeout: 120m
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]
variables:
CC: clang-21
CXX: clang++-21
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21
cache:
key: rusty-teams-cargo-linux
paths: [.ci-cache/cargo-linux.tar.gz]
script:
- packaging/kvt/ci-cache.sh restore linux
- packaging/kvt/ci-setup.sh linux
- . "$HOME/.cargo/env"
- cargo test --locked -p app-base --lib -- release_feed kvt_feed updater
- cargo test --locked -p kvt-sleutels
- cargo check --locked -p app
- . "${CARGO_HOME:-$HOME/.cargo}/env"
- cargo test --locked --profile ci -j2 --no-run -p kvt-update
- cargo test --locked --profile ci -j2 --no-run -p kvt-sleutels
- cargo test --locked --profile ci -j2 --no-run -p app-base --lib
- cargo check --locked --profile ci -j2 -p app
- cargo test --locked --profile ci -j2 -p kvt-update
- cargo test --locked --profile ci -j2 -p kvt-sleutels
- cargo test --locked --profile ci -j2 -p app-base --lib -- release_feed kvt_feed updater
- packaging/kvt/ci-cache.sh save linux
# Linux: release-build met de tag als versie (TEAMS_RELEASE_TAG via build.rs),
# daarna de FHS-tarball van packaging/linux/package.sh. Vaste artifactnamen;
@@ -173,16 +207,20 @@ app_test:
linux_release:
stage: build
image: ubuntu:22.04
extends: .kvt_tag
needs: [kvt_test, aur_check]
extends: [.kvt_tag, .kvt_rust]
needs: []
timeout: 150m
variables:
CC: clang-21
CXX: clang++-21
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21
cache:
key: rusty-teams-cargo-linux
paths: [.ci-cache/cargo-linux.tar.gz]
script:
- packaging/kvt/ci-cache.sh restore linux
- packaging/kvt/ci-setup.sh linux
- . "$HOME/.cargo/env"
- . "${CARGO_HOME:-$HOME/.cargo}/env"
- export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag RUSTY_TEAMS_VERSION="$CI_COMMIT_TAG"
- export RUSTY_TEAMS_MAINTAINER="KVT ICT <hephaestus@noreply.kvt.nl>"
- cargo build -p app --release --locked
@@ -193,6 +231,7 @@ linux_release:
- strip dist/kvt/teams-linux-amd64
- grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-linux-amd64
- ls -la dist/kvt
- packaging/kvt/ci-cache.sh save linux
artifacts:
paths:
- dist/kvt/teams-linux-amd64
@@ -200,23 +239,33 @@ linux_release:
expire_in: 7d
# Windows x86_64: cross-build vanuit Linux (packaging/kvt/build-windows.sh).
# allow_failure: mislukt hij, dan krijgt de release geen exe en biedt een
# Windows-installatie die versie niet aan; Linux en AUR gaan door.
# Handmatig (play) en allow_failure: de release wacht er niet op en krijgt dan
# geen exe, dus een Windows-installatie krijgt die versie niet aangeboden; Linux
# en AUR gaan door. Wil je de exe er alsnog bij: speel windows_release, daarna
# checksums en release opnieuw.
windows_release:
stage: build
image: ubuntu:24.04
extends: .kvt_tag
needs: [kvt_test]
extends: .kvt_rust
needs: [linux_release]
allow_failure: true
rules:
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/
when: manual
allow_failure: true
timeout: 180m
variables:
CC: clang-21
CXX: clang++-21
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21
XWIN_ACCEPT_LICENSE: "1"
cache:
key: rusty-teams-cargo-windows
paths: [.ci-cache/cargo-windows.tar.gz]
script:
- packaging/kvt/ci-cache.sh restore windows
- packaging/kvt/ci-setup.sh windows
- . "$HOME/.cargo/env"
- . "${CARGO_HOME:-$HOME/.cargo}/env"
- export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag
- packaging/kvt/build-windows.sh
- mkdir -p dist/kvt
@@ -224,6 +273,7 @@ windows_release:
- head -c 2 dist/kvt/teams-windows-amd64.exe | grep -q MZ
- grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-windows-amd64.exe
- ls -la dist/kvt
- packaging/kvt/ci-cache.sh save windows
artifacts:
paths:
- dist/kvt/teams-windows-amd64.exe
@@ -233,7 +283,7 @@ checksums:
stage: package
image: bluegit/base
extends: .kvt_tag
needs: [linux_release, windows_release]
needs: [linux_release]
script:
- packaging/kvt/release-assets.sh sums "$CI_COMMIT_TAG"
artifacts:
@@ -247,7 +297,7 @@ release:
stage: release
image: bluegit/base
extends: .kvt_tag
needs: [checksums, linux_release, windows_release]
needs: [checksums, linux_release]
script:
- packaging/kvt/release-assets.sh json "$CI_COMMIT_TAG" "$CI_COMMIT_SHA" > release.json
- cat release.json
@@ -7,14 +7,24 @@# (knop "Run pipeline" op master, of# (knop "Run pipeline" op master, of# POST /api/v1/projects/ict/rusty-teams/pipelines {"ref": "master"}),# POST /api/v1/projects/ict/rusty-teams/pipelines {"ref": "master"}),# nooit bij een push, tag of merge request.# nooit bij een push, tag of merge request.# 2. Controle bij een merge request of push: kvt_test (de KVT-crate en# 2. Controle bij een merge request of branch-push: alleen kvt_test (shell-# -scripts, snel), aur_check (PKGBUILD en .SRCINFO in Arch) en app_test# syntaxis en packaging/kvt/tests.sh, zonder compileren of installs).# (bouwt app-base en app, draait de updatertests en de kvt-sleutels-tests;# De zware jobs aur_check en app_test (één keer compileren met# alleen als Rust-code of Cargo-bestanden veranderen).# `cargo test --no-run`, daarna kvt-update, updatertests, kvt-sleutels en# 3. Release bij een tag v* (schema v<versie>-kvt.<n>, bijvoorbeeld v0.6.1-kvt.1):# `cargo check -p app`) staan op `when: manual` en starten niet vanzelf: ze# hebben de gedeelde BlueGit-runner herhaaldelijk onderuit gehaald. Draai de# volledige tests lokaal (cargo test -p app / -p app-state / -p kvt-sleutels)# of start de jobs bewust met "play".# Rust-jobs gebruiken CARGO_BUILD_JOBS=2, RUST_TEST_THREADS=2,# CARGO_INCREMENTAL=0 en profile.ci (debug=0). Tussen runs bewaren ze# een Cargo/rustup-tarball: BlueGit cache't geen mappen, en target/# is te groot voor de jobcache.# 3. Release bij een tag v* (schema v<versie>-kvt.<n>, bijvoorbeeld v0.6.1-kvt.1).# Een tag-pipeline bevat alleen wat voor de release nodig is, zonder tests:# linux_release Linux-binary + FHS-tarball (packaging/linux/package.sh)# linux_release Linux-binary + FHS-tarball (packaging/linux/package.sh)# windows_release teams.exe, cross-build met cargo-xwin en fxc onder wine# windows_release handmatig (when: manual, allow_failure): teams.exe,# (allow_failure: zonder exe gaat de release door)# cross-build met cargo-xwin en fxc onder wine. Zwaar, dus# niet automatisch; de release gaat zonder exe door# checksums SHA256SUMS van alle assets# checksums SHA256SUMS van alle assets# release maakt de release op git.kvt.nl met de assets# release maakt de release op git.kvt.nl met de assets# publish_aur AUR-pakket kvt-rusty-teams-bin (allow_failure; slaat# publish_aur AUR-pakket kvt-rusty-teams-bin (allow_failure; slaat@@ -98,35 +108,52 @@ sync-upstream:# KVT: controle, release, AUR. Alles hieronder staat los van sync-upstream.# KVT: controle, release, AUR. Alles hieronder staat los van sync-upstream.# ---------------------------------------------------------------------------# ---------------------------------------------------------------------------# Lichte controle: bij een merge request en een branch-push, niet in een tag-pipeline..kvt_check:.kvt_check: rules: rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/# Zware controle: alleen op verzoek (play), nooit automatisch..kvt_manual_check: rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" when: manual allow_failure: true - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null when: manual allow_failure: true.kvt_tag:.kvt_tag: rules: rules: - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/ - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/# De KVT-crate (BlueGit-releasefeed, versies, assetnamen, pakketbeheer-vlag) en# Minder piekgeheugen op de gedeelde BlueGit-runner.# de scripts in packaging/kvt. Klein en snel..kvt_rust: variables: CARGO_INCREMENTAL: "0" CARGO_BUILD_JOBS: "2" RUST_TEST_THREADS: "2"# De scripts in packaging/kvt (shell-syntaxis en tests.sh). Geen apt-installs en# geen cargo: de kvt-update-tests draaien in app_test (handmatig) en lokaal.kvt_test:kvt_test: stage: test stage: test image: rust:1-bookworm image: rust:1-bookworm extends: .kvt_check extends: .kvt_check needs: [] needs: [] timeout: 30m timeout: 10m script: script: - apt-get update -qq && apt-get install -y -qq --no-install-recommends clang mold >/dev/null - cargo test -p kvt-update --locked - for f in packaging/kvt/*.sh; do bash -n "$f"; done - for f in packaging/kvt/*.sh; do bash -n "$f"; done - packaging/kvt/tests.sh - packaging/kvt/tests.sh# PKGBUILD renderen en .SRCINFO maken op Arch, zoals publish_aur dat doet.# PKGBUILD renderen en .SRCINFO maken op Arch, zoals publish_aur dat doet.# Handmatig: de Arch-image is zwaar, en publish_aur doet dezelfde render bij een release.aur_check:aur_check: stage: test stage: test image: archlinux/archlinux:base-devel image: archlinux/archlinux:base-devel extends: .kvt_check extends: .kvt_manual_check allow_failure: true needs: [] needs: [] timeout: 20m timeout: 20m script: script:@@ -143,29 +170,36 @@ aur_check: grep -q 'source = rusty-teams-0.0.1-kvt.1-linux-x86_64.tar.gz::https://git.kvt.nl/' "$out/.SRCINFO" grep -q 'source = rusty-teams-0.0.1-kvt.1-linux-x86_64.tar.gz::https://git.kvt.nl/' "$out/.SRCINFO" grep -qP '^\tpkgver = 0\.0\.1\.kvt\.1$' "$out/.SRCINFO" grep -qP '^\tpkgver = 0\.0\.1\.kvt\.1$' "$out/.SRCINFO"# Bouwt app-base en app en draait de updatertests (release_feed, kvt_feed) en# Bouwt één keer (cargo test --no-run) en draait daarna dezelfde tests als# de tests van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen).# voorheen: kvt-update, de updatertests (release_feed, kvt_feed) en de tests# Alleen als Rust-code of Cargo-bestanden veranderen; zwaar (volledige build).# van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen), plus# cargo check -p app. Handmatig (play): zwaar, start niet vanzelf.app_test:app_test: stage: test stage: test image: ubuntu:22.04 image: ubuntu:22.04 extends: [.kvt_manual_check, .kvt_rust] allow_failure: true needs: [] needs: [] timeout: 120m timeout: 120m rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml] - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml] variables: variables: CC: clang-21 CC: clang-21 CXX: clang++-21 CXX: clang++-21 CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21 CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21 cache: key: rusty-teams-cargo-linux paths: [.ci-cache/cargo-linux.tar.gz] script: script: - packaging/kvt/ci-cache.sh restore linux - packaging/kvt/ci-setup.sh linux - packaging/kvt/ci-setup.sh linux - . "$HOME/.cargo/env" - . "${CARGO_HOME:-$HOME/.cargo}/env" - cargo test --locked -p app-base --lib -- release_feed kvt_feed updater - cargo test --locked --profile ci -j2 --no-run -p kvt-update - cargo test --locked -p kvt-sleutels - cargo test --locked --profile ci -j2 --no-run -p kvt-sleutels - cargo check --locked -p app - cargo test --locked --profile ci -j2 --no-run -p app-base --lib - cargo check --locked --profile ci -j2 -p app - cargo test --locked --profile ci -j2 -p kvt-update - cargo test --locked --profile ci -j2 -p kvt-sleutels - cargo test --locked --profile ci -j2 -p app-base --lib -- release_feed kvt_feed updater - packaging/kvt/ci-cache.sh save linux# Linux: release-build met de tag als versie (TEAMS_RELEASE_TAG via build.rs),# Linux: release-build met de tag als versie (TEAMS_RELEASE_TAG via build.rs),# daarna de FHS-tarball van packaging/linux/package.sh. Vaste artifactnamen;# daarna de FHS-tarball van packaging/linux/package.sh. Vaste artifactnamen;@@ -173,16 +207,20 @@ app_test:linux_release:linux_release: stage: build stage: build image: ubuntu:22.04 image: ubuntu:22.04 extends: .kvt_tag extends: [.kvt_tag, .kvt_rust] needs: [kvt_test, aur_check] needs: [] timeout: 150m timeout: 150m variables: variables: CC: clang-21 CC: clang-21 CXX: clang++-21 CXX: clang++-21 CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21 CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21 cache: key: rusty-teams-cargo-linux paths: [.ci-cache/cargo-linux.tar.gz] script: script: - packaging/kvt/ci-cache.sh restore linux - packaging/kvt/ci-setup.sh linux - packaging/kvt/ci-setup.sh linux - . "$HOME/.cargo/env" - . "${CARGO_HOME:-$HOME/.cargo}/env" - export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag RUSTY_TEAMS_VERSION="$CI_COMMIT_TAG" - export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag RUSTY_TEAMS_VERSION="$CI_COMMIT_TAG" - export RUSTY_TEAMS_MAINTAINER="KVT ICT <hephaestus@noreply.kvt.nl>" - export RUSTY_TEAMS_MAINTAINER="KVT ICT <hephaestus@noreply.kvt.nl>" - cargo build -p app --release --locked - cargo build -p app --release --locked@@ -193,6 +231,7 @@ linux_release: - strip dist/kvt/teams-linux-amd64 - strip dist/kvt/teams-linux-amd64 - grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-linux-amd64 - grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-linux-amd64 - ls -la dist/kvt - ls -la dist/kvt - packaging/kvt/ci-cache.sh save linux artifacts: artifacts: paths: paths: - dist/kvt/teams-linux-amd64 - dist/kvt/teams-linux-amd64@@ -200,23 +239,33 @@ linux_release: expire_in: 7d expire_in: 7d# Windows x86_64: cross-build vanuit Linux (packaging/kvt/build-windows.sh).# Windows x86_64: cross-build vanuit Linux (packaging/kvt/build-windows.sh).# allow_failure: mislukt hij, dan krijgt de release geen exe en biedt een# Handmatig (play) en allow_failure: de release wacht er niet op en krijgt dan# Windows-installatie die versie niet aan; Linux en AUR gaan door.# geen exe, dus een Windows-installatie krijgt die versie niet aangeboden; Linux# en AUR gaan door. Wil je de exe er alsnog bij: speel windows_release, daarna# checksums en release opnieuw.windows_release:windows_release: stage: build stage: build image: ubuntu:24.04 image: ubuntu:24.04 extends: .kvt_tag extends: .kvt_rust needs: [kvt_test] needs: [linux_release] allow_failure: true allow_failure: true rules: - if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/ when: manual allow_failure: true timeout: 180m timeout: 180m variables: variables: CC: clang-21 CC: clang-21 CXX: clang++-21 CXX: clang++-21 CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21 CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21 XWIN_ACCEPT_LICENSE: "1" XWIN_ACCEPT_LICENSE: "1" cache: key: rusty-teams-cargo-windows paths: [.ci-cache/cargo-windows.tar.gz] script: script: - packaging/kvt/ci-cache.sh restore windows - packaging/kvt/ci-setup.sh windows - packaging/kvt/ci-setup.sh windows - . "$HOME/.cargo/env" - . "${CARGO_HOME:-$HOME/.cargo}/env" - export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag - export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag - packaging/kvt/build-windows.sh - packaging/kvt/build-windows.sh - mkdir -p dist/kvt - mkdir -p dist/kvt@@ -224,6 +273,7 @@ windows_release: - head -c 2 dist/kvt/teams-windows-amd64.exe | grep -q MZ - head -c 2 dist/kvt/teams-windows-amd64.exe | grep -q MZ - grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-windows-amd64.exe - grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-windows-amd64.exe - ls -la dist/kvt - ls -la dist/kvt - packaging/kvt/ci-cache.sh save windows artifacts: artifacts: paths: paths: - dist/kvt/teams-windows-amd64.exe - dist/kvt/teams-windows-amd64.exe@@ -233,7 +283,7 @@ checksums: stage: package stage: package image: bluegit/base image: bluegit/base extends: .kvt_tag extends: .kvt_tag needs: [linux_release, windows_release] needs: [linux_release] script: script: - packaging/kvt/release-assets.sh sums "$CI_COMMIT_TAG" - packaging/kvt/release-assets.sh sums "$CI_COMMIT_TAG" artifacts: artifacts:@@ -247,7 +297,7 @@ release: stage: release stage: release image: bluegit/base image: bluegit/base extends: .kvt_tag extends: .kvt_tag needs: [checksums, linux_release, windows_release] needs: [checksums, linux_release] script: script: - packaging/kvt/release-assets.sh json "$CI_COMMIT_TAG" "$CI_COMMIT_SHA" > release.json - packaging/kvt/release-assets.sh json "$CI_COMMIT_TAG" "$CI_COMMIT_SHA" > release.json - cat release.json - cat release.json@@ -109,6 +109,90 @@ notice:
en: "Something went wrong: %{detail}"
de: "Etwas ist schiefgelaufen: %{detail}"
nl: "Er ging iets mis: %{detail}"
reaction:
custom_emoji:
en: Custom emoji
de: Organisations-Emoji
nl: Organisatie-emoji
fun_picker:
tab:
emoji:
en: Emoji
de: Emoji
nl: Emoji
gif:
en: GIF
de: GIF
nl: GIF
sticker:
en: Sticker
de: Sticker
nl: Sticker
org:
en: Organization
de: Organisation
nl: Organisatie
search:
emoji:
en: Search emoji
de: Emoji suchen
nl: Emoji zoeken
gif:
en: Search GIFs
de: GIFs suchen
nl: GIFs zoeken
sticker:
en: Search stickers
de: Sticker suchen
nl: Stickers zoeken
org:
en: Search organization emoji
de: Organisations-Emoji suchen
nl: Organisatie-emoji zoeken
org:
empty:
en: No organization emoji
de: Keine Organisations-Emojis
nl: Geen organisatie-emoji
empty_query:
en: "No organization emoji for \"%{query}\""
de: "Keine Organisations-Emojis zu \"%{query}\""
nl: "Geen organisatie-emoji voor \"%{query}\""
failed:
en: Organization emoji could not be loaded.
de: Organisations-Emojis konnten nicht geladen werden.
nl: Organisatie-emoji konden niet worden geladen.
retry:
en: Try again
de: Erneut versuchen
nl: Opnieuw proberen
reaction_picker:
tab:
emoji:
en: Emoji
de: Emoji
nl: Emoji
org:
en: Organization
de: Organisation
nl: Organisatie
search:
org:
en: Search organization emoji
de: Organisations-Emoji suchen
nl: Organisatie-emoji zoeken
org:
empty:
en: No organization emoji
de: Keine Organisations-Emojis
nl: Geen organisatie-emoji
empty_query:
en: "No organization emoji for \"%{query}\""
de: "Keine Organisations-Emojis zu \"%{query}\""
nl: "Geen organisatie-emoji voor \"%{query}\""
settings:
search:
no_results:
@@ -109,6 +109,90 @@ notice: en: "Something went wrong: %{detail}" en: "Something went wrong: %{detail}" de: "Etwas ist schiefgelaufen: %{detail}" de: "Etwas ist schiefgelaufen: %{detail}" nl: "Er ging iets mis: %{detail}" nl: "Er ging iets mis: %{detail}"reaction: custom_emoji: en: Custom emoji de: Organisations-Emoji nl: Organisatie-emojifun_picker: tab: emoji: en: Emoji de: Emoji nl: Emoji gif: en: GIF de: GIF nl: GIF sticker: en: Sticker de: Sticker nl: Sticker org: en: Organization de: Organisation nl: Organisatie search: emoji: en: Search emoji de: Emoji suchen nl: Emoji zoeken gif: en: Search GIFs de: GIFs suchen nl: GIFs zoeken sticker: en: Search stickers de: Sticker suchen nl: Stickers zoeken org: en: Search organization emoji de: Organisations-Emoji suchen nl: Organisatie-emoji zoeken org: empty: en: No organization emoji de: Keine Organisations-Emojis nl: Geen organisatie-emoji empty_query: en: "No organization emoji for \"%{query}\"" de: "Keine Organisations-Emojis zu \"%{query}\"" nl: "Geen organisatie-emoji voor \"%{query}\"" failed: en: Organization emoji could not be loaded. de: Organisations-Emojis konnten nicht geladen werden. nl: Organisatie-emoji konden niet worden geladen. retry: en: Try again de: Erneut versuchen nl: Opnieuw proberenreaction_picker: tab: emoji: en: Emoji de: Emoji nl: Emoji org: en: Organization de: Organisation nl: Organisatie search: org: en: Search organization emoji de: Organisations-Emoji suchen nl: Organisatie-emoji zoeken org: empty: en: No organization emoji de: Keine Organisations-Emojis nl: Geen organisatie-emoji empty_query: en: "No organization emoji for \"%{query}\"" de: "Keine Organisations-Emojis zu \"%{query}\"" nl: "Geen organisatie-emoji voor \"%{query}\""settings:settings: search: search: no_results: no_results:@@ -202,22 +202,6 @@ kvt:
de: Ponos konnte das nicht speichern
nl: Ponos kon dit niet opslaan
tasks:
menu:
en: My tasks in Ponos
de: Meine Aufgaben in Ponos
nl: Mijn taken in Ponos
title:
en: My tasks
de: Meine Aufgaben
nl: Mijn taken
empty:
en: No open tasks
de: Keine offenen Aufgaben
nl: Geen open taken
in_progress:
en: In progress
de: In Bearbeitung
nl: Mee bezig
completed:
en: Task done
de: Aufgabe erledigt
@@ -226,6 +210,85 @@ kvt:
en: Open Ponos
de: Ponos öffnen
nl: Ponos openen
rail:
ponos:
en: Ponos
de: Ponos
nl: Ponos
asclepius:
en: Asclepius
de: Asclepius
nl: Asclepius
board:
title:
en: Ponos
de: Ponos
nl: Ponos
new_task:
en: New task
de: Neue Aufgabe
nl: Nieuwe taak
edit_task:
en: Task in Ponos
de: Aufgabe in Ponos
nl: Taak in Ponos
empty_column:
en: No tasks
de: Keine Aufgaben
nl: Geen taken
status:
en: Status
de: Status
nl: Status
due:
en: Due date
de: Fällig am
nl: Deadline
due_placeholder:
en: e.g. 15 jan 2026 (empty = none)
de: z. B. 15 jan 2026 (leer = keins)
nl: bijv. 15 jan 2026 (leeg = geen)
bad_date:
en: Enter the due date like 15 jan 2026 or 15-01-2026
de: Datum wie 15 jan 2026 oder 15-01-2026 eingeben
nl: Vul de deadline in als 15 jan 2026 of 15-01-2026
assignee:
en: Assigned to
de: Zugewiesen an
nl: Toegewezen aan
assignee_none:
en: Nobody
de: Niemand
nl: Niemand
assignee_me:
en: Me
de: Ich
nl: Ik
save:
en: Save
de: Speichern
nl: Opslaan
saved:
en: Saved in Ponos
de: In Ponos gespeichert
nl: Opgeslagen in Ponos
complete:
en: Done
de: Erledigt
nl: Afronden
board_status:
todo:
en: To do
de: Zu erledigen
nl: Nog te doen
in_progress:
en: In progress
de: In Bearbeitung
nl: Onderhanden
done:
en: Done
de: Erledigt
nl: Afgerond
planning:
title:
en: Daedalus planning in calendar
@@ -243,3 +306,209 @@ kvt:
en: Connect to sleutels.kvt.nl again to see the Daedalus planning
de: Erneut mit sleutels.kvt.nl verbinden, um die Daedalus-Planung zu sehen
nl: Koppel opnieuw met sleutels.kvt.nl om de Daedalus-planning te zien
window:
title:
en: Custom window buttons
de: Eigene Fensterschaltflächen
nl: Eigen vensterknoppen
detail:
en: Place minimize, maximize and close in the title bar and hide the system window borders.
de: Minimieren, Maximieren und Schließen in der Titelleiste, ohne die Systemfensterrahmen.
nl: Minimaliseren, maximaliseren en sluiten in de titelbalk, zonder de vensterranden van het systeem.
minimize:
en: Minimize
de: Minimieren
nl: Minimaliseren
maximize:
en: Maximize
de: Maximieren
nl: Maximaliseren
restore:
en: Restore
de: Wiederherstellen
nl: Herstellen
close:
en: Close
de: Schließen
nl: Sluiten
tickets:
title:
en: My tickets
de: Meine Tickets
nl: Mijn tickets
filter_open:
en: Open
de: Offen
nl: Open
filter_closed:
en: Closed
de: Erledigt
nl: Afgehandeld
empty_open:
en: You have no open tickets
de: Du hast keine offenen Tickets
nl: Je hebt geen open tickets
empty_closed:
en: No closed tickets
de: Keine erledigten Tickets
nl: Geen afgehandelde tickets
pick:
en: Choose a ticket on the left
de: Wähle links ein Ticket
nl: Kies links een ticket
not_found:
en: This ticket does not exist or you have no access
de: Dieses Ticket gibt es nicht oder du hast keinen Zugriff
nl: Dit ticket bestaat niet of je hebt er geen toegang toe
failed:
en: Asclepius could not process this
de: Asclepius konnte das nicht verarbeiten
nl: Asclepius kon dit niet verwerken
reply_placeholder:
en: Write a reply…
de: Antwort schreiben…
nl: Schrijf een reactie…
send:
en: Send
de: Senden
nl: Versturen
sending:
en: Sending…
de: Wird gesendet…
nl: Bezig…
mention:
en: "Mention:"
de: "Erwähnen:"
nl: "Vermeld:"
ict:
en: ICT
de: ICT
nl: ICT
ghost:
en: internal note
de: interne Notiz
nl: interne notitie
closed_hint:
en: "This ticket is closed; reopening is done in Asclepius"
de: "Dieses Ticket ist erledigt; wieder öffnen geht in Asclepius"
nl: "Dit ticket is afgehandeld; heropenen kan in Asclepius"
demo_attachment:
en: Attachments are not available in the demo
de: Anhänge sind in der Demo nicht verfügbar
nl: Bijlagen zijn niet beschikbaar in de demo
new:
en: "New ticket"
de: "Neues Ticket"
nl: "Nieuw ticket"
form:
heading:
en: "Create new ticket"
de: "Neues Ticket erstellen"
nl: "Nieuw ticket maken"
title:
en: "Title"
de: "Titel"
nl: "Titel"
title_placeholder:
en: "For example: New scanner needed"
de: "Zum Beispiel: Neuer Scanner benötigt"
nl: "Bijvoorbeeld: Nieuwe scanner nodig"
category:
en: "Category"
de: "Kategorie"
nl: "Categorie"
subcategory:
en: "Subcategory"
de: "Unterkategorie"
nl: "Subcategorie"
description:
en: "Description"
de: "Beschreibung"
nl: "Beschrijving"
description_placeholder:
en: "Describe the problem or request as clearly as possible."
de: "Beschreibe das Problem oder die Anfrage so genau wie möglich."
nl: "Beschrijf het probleem of de aanvraag zo duidelijk mogelijk."
blocked:
en: "My work is being impeded"
de: "Meine Arbeit wird behindert"
nl: "Mijn werkzaamheden worden belemmerd"
fully_blocked:
en: "I cannot continue working until this is resolved"
de: "Ich kann nicht weiterarbeiten, bis das gelöst ist"
nl: "Ik kan niet verder werken tot dit opgelost is"
participants:
en: "Additional users"
de: "Weitere Benutzer"
nl: "Extra gebruikers"
participants_placeholder:
en: "name1@kvt.nl, name2@kvt.nl"
de: "name1@kvt.nl, name2@kvt.nl"
nl: "naam1@kvt.nl, naam2@kvt.nl"
participants_hint:
en: "Add colleagues who should also see this ticket under My tickets."
de: "Füge Kollegen hinzu, die dieses Ticket auch unter Meine Tickets sehen sollen."
nl: "Voeg collega's toe die dit ticket ook onder Mijn tickets moeten zien."
attachments:
en: "Screenshots or documents"
de: "Screenshots oder Dokumente"
nl: "Screenshots of documenten"
add_files:
en: "Add files"
de: "Dateien hinzufügen"
nl: "Bestanden toevoegen"
submit:
en: "Submit ticket"
de: "Ticket einreichen"
nl: "Ticket indienen"
pick_category:
en: "Choose a category"
de: "Kategorie wählen"
nl: "Kies een categorie"
fill_in:
en: "Fill in a title and a description"
de: "Titel und Beschreibung ausfüllen"
nl: "Vul een titel en een beschrijving in"
bad_email:
en: "Not a valid e-mail address: %{email}"
de: "Keine gültige E-Mail-Adresse: %{email}"
nl: "Geen geldig e-mailadres: %{email}"
too_many_files:
en: "At most %{max} files"
de: "Höchstens %{max} Dateien"
nl: "Hooguit %{max} bestanden"
file_too_large:
en: "%{name} is larger than 10 MB"
de: "%{name} ist größer als 10 MB"
nl: "%{name} is groter dan 10 MB"
created:
en: "Ticket #%{id} created in Asclepius"
de: "Ticket #%{id} in Asclepius erstellt"
nl: "Ticket #%{id} aangemaakt in Asclepius"
status:
ingediend:
en: Submitted
de: Eingereicht
nl: Ingediend
in_behandeling:
en: In progress
de: In Bearbeitung
nl: In behandeling
afwachtende_op_gebruiker:
en: Waiting for user
de: Wartet auf Benutzer
nl: Afwachtende op gebruiker
afwachtende_op_bestelling:
en: Waiting for order
de: Wartet auf Bestellung
nl: Afwachtende op bestelling
afwachtende_op_derde_partij:
en: Waiting for third party
de: Wartet auf Dritte
nl: Afwachtende op derde partij
afgehandeld:
en: Closed
de: Erledigt
nl: Afgehandeld
@@ -202,22 +202,6 @@ kvt: de: Ponos konnte das nicht speichern de: Ponos konnte das nicht speichern nl: Ponos kon dit niet opslaan nl: Ponos kon dit niet opslaan tasks: tasks: menu: en: My tasks in Ponos de: Meine Aufgaben in Ponos nl: Mijn taken in Ponos title: en: My tasks de: Meine Aufgaben nl: Mijn taken empty: en: No open tasks de: Keine offenen Aufgaben nl: Geen open taken in_progress: en: In progress de: In Bearbeitung nl: Mee bezig completed: completed: en: Task done en: Task done de: Aufgabe erledigt de: Aufgabe erledigt@@ -226,6 +210,85 @@ kvt: en: Open Ponos en: Open Ponos de: Ponos öffnen de: Ponos öffnen nl: Ponos openen nl: Ponos openen rail: ponos: en: Ponos de: Ponos nl: Ponos asclepius: en: Asclepius de: Asclepius nl: Asclepius board: title: en: Ponos de: Ponos nl: Ponos new_task: en: New task de: Neue Aufgabe nl: Nieuwe taak edit_task: en: Task in Ponos de: Aufgabe in Ponos nl: Taak in Ponos empty_column: en: No tasks de: Keine Aufgaben nl: Geen taken status: en: Status de: Status nl: Status due: en: Due date de: Fällig am nl: Deadline due_placeholder: en: e.g. 15 jan 2026 (empty = none) de: z. B. 15 jan 2026 (leer = keins) nl: bijv. 15 jan 2026 (leeg = geen) bad_date: en: Enter the due date like 15 jan 2026 or 15-01-2026 de: Datum wie 15 jan 2026 oder 15-01-2026 eingeben nl: Vul de deadline in als 15 jan 2026 of 15-01-2026 assignee: en: Assigned to de: Zugewiesen an nl: Toegewezen aan assignee_none: en: Nobody de: Niemand nl: Niemand assignee_me: en: Me de: Ich nl: Ik save: en: Save de: Speichern nl: Opslaan saved: en: Saved in Ponos de: In Ponos gespeichert nl: Opgeslagen in Ponos complete: en: Done de: Erledigt nl: Afronden board_status: todo: en: To do de: Zu erledigen nl: Nog te doen in_progress: en: In progress de: In Bearbeitung nl: Onderhanden done: en: Done de: Erledigt nl: Afgerond planning: planning: title: title: en: Daedalus planning in calendar en: Daedalus planning in calendar@@ -243,3 +306,209 @@ kvt: en: Connect to sleutels.kvt.nl again to see the Daedalus planning en: Connect to sleutels.kvt.nl again to see the Daedalus planning de: Erneut mit sleutels.kvt.nl verbinden, um die Daedalus-Planung zu sehen de: Erneut mit sleutels.kvt.nl verbinden, um die Daedalus-Planung zu sehen nl: Koppel opnieuw met sleutels.kvt.nl om de Daedalus-planning te zien nl: Koppel opnieuw met sleutels.kvt.nl om de Daedalus-planning te zien window: title: en: Custom window buttons de: Eigene Fensterschaltflächen nl: Eigen vensterknoppen detail: en: Place minimize, maximize and close in the title bar and hide the system window borders. de: Minimieren, Maximieren und Schließen in der Titelleiste, ohne die Systemfensterrahmen. nl: Minimaliseren, maximaliseren en sluiten in de titelbalk, zonder de vensterranden van het systeem. minimize: en: Minimize de: Minimieren nl: Minimaliseren maximize: en: Maximize de: Maximieren nl: Maximaliseren restore: en: Restore de: Wiederherstellen nl: Herstellen close: en: Close de: Schließen nl: Sluiten tickets: title: en: My tickets de: Meine Tickets nl: Mijn tickets filter_open: en: Open de: Offen nl: Open filter_closed: en: Closed de: Erledigt nl: Afgehandeld empty_open: en: You have no open tickets de: Du hast keine offenen Tickets nl: Je hebt geen open tickets empty_closed: en: No closed tickets de: Keine erledigten Tickets nl: Geen afgehandelde tickets pick: en: Choose a ticket on the left de: Wähle links ein Ticket nl: Kies links een ticket not_found: en: This ticket does not exist or you have no access de: Dieses Ticket gibt es nicht oder du hast keinen Zugriff nl: Dit ticket bestaat niet of je hebt er geen toegang toe failed: en: Asclepius could not process this de: Asclepius konnte das nicht verarbeiten nl: Asclepius kon dit niet verwerken reply_placeholder: en: Write a reply… de: Antwort schreiben… nl: Schrijf een reactie… send: en: Send de: Senden nl: Versturen sending: en: Sending… de: Wird gesendet… nl: Bezig… mention: en: "Mention:" de: "Erwähnen:" nl: "Vermeld:" ict: en: ICT de: ICT nl: ICT ghost: en: internal note de: interne Notiz nl: interne notitie closed_hint: en: "This ticket is closed; reopening is done in Asclepius" de: "Dieses Ticket ist erledigt; wieder öffnen geht in Asclepius" nl: "Dit ticket is afgehandeld; heropenen kan in Asclepius" demo_attachment: en: Attachments are not available in the demo de: Anhänge sind in der Demo nicht verfügbar nl: Bijlagen zijn niet beschikbaar in de demo new: en: "New ticket" de: "Neues Ticket" nl: "Nieuw ticket" form: heading: en: "Create new ticket" de: "Neues Ticket erstellen" nl: "Nieuw ticket maken" title: en: "Title" de: "Titel" nl: "Titel" title_placeholder: en: "For example: New scanner needed" de: "Zum Beispiel: Neuer Scanner benötigt" nl: "Bijvoorbeeld: Nieuwe scanner nodig" category: en: "Category" de: "Kategorie" nl: "Categorie" subcategory: en: "Subcategory" de: "Unterkategorie" nl: "Subcategorie" description: en: "Description" de: "Beschreibung" nl: "Beschrijving" description_placeholder: en: "Describe the problem or request as clearly as possible." de: "Beschreibe das Problem oder die Anfrage so genau wie möglich." nl: "Beschrijf het probleem of de aanvraag zo duidelijk mogelijk." blocked: en: "My work is being impeded" de: "Meine Arbeit wird behindert" nl: "Mijn werkzaamheden worden belemmerd" fully_blocked: en: "I cannot continue working until this is resolved" de: "Ich kann nicht weiterarbeiten, bis das gelöst ist" nl: "Ik kan niet verder werken tot dit opgelost is" participants: en: "Additional users" de: "Weitere Benutzer" nl: "Extra gebruikers" participants_placeholder: en: "name1@kvt.nl, name2@kvt.nl" de: "name1@kvt.nl, name2@kvt.nl" nl: "naam1@kvt.nl, naam2@kvt.nl" participants_hint: en: "Add colleagues who should also see this ticket under My tickets." de: "Füge Kollegen hinzu, die dieses Ticket auch unter Meine Tickets sehen sollen." nl: "Voeg collega's toe die dit ticket ook onder Mijn tickets moeten zien." attachments: en: "Screenshots or documents" de: "Screenshots oder Dokumente" nl: "Screenshots of documenten" add_files: en: "Add files" de: "Dateien hinzufügen" nl: "Bestanden toevoegen" submit: en: "Submit ticket" de: "Ticket einreichen" nl: "Ticket indienen" pick_category: en: "Choose a category" de: "Kategorie wählen" nl: "Kies een categorie" fill_in: en: "Fill in a title and a description" de: "Titel und Beschreibung ausfüllen" nl: "Vul een titel en een beschrijving in" bad_email: en: "Not a valid e-mail address: %{email}" de: "Keine gültige E-Mail-Adresse: %{email}" nl: "Geen geldig e-mailadres: %{email}" too_many_files: en: "At most %{max} files" de: "Höchstens %{max} Dateien" nl: "Hooguit %{max} bestanden" file_too_large: en: "%{name} is larger than 10 MB" de: "%{name} ist größer als 10 MB" nl: "%{name} is groter dan 10 MB" created: en: "Ticket #%{id} created in Asclepius" de: "Ticket #%{id} in Asclepius erstellt" nl: "Ticket #%{id} aangemaakt in Asclepius" status: ingediend: en: Submitted de: Eingereicht nl: Ingediend in_behandeling: en: In progress de: In Bearbeitung nl: In behandeling afwachtende_op_gebruiker: en: Waiting for user de: Wartet auf Benutzer nl: Afwachtende op gebruiker afwachtende_op_bestelling: en: Waiting for order de: Wartet auf Bestellung nl: Afwachtende op bestelling afwachtende_op_derde_partij: en: Waiting for third party de: Wartet auf Dritte nl: Afwachtende op derde partij afgehandeld: en: Closed de: Erledigt nl: Afgehandeld@@ -8,7 +8,7 @@ macro_rules! symbols {
};
}
const SYMBOLS: [(&str, &[u8]); 208] = symbols![
const SYMBOLS: [(&str, &[u8]); 209] = symbols![
"account_circle",
"add",
"alarm",
@@ -57,6 +57,7 @@ const SYMBOLS: [(&str, &[u8]); 208] = symbols![
"cloud",
"cloud_upload",
"code",
"confirmation_number", // KVT-fork: Asclepius-tegel
"code_blocks",
"content_copy",
"content_paste",
@@ -219,7 +220,7 @@ const SYMBOLS: [(&str, &[u8]); 208] = symbols![
"zoom_out",
];
const LUCIDE_AS_MATERIAL: [(&str, &str); 159] = [
const LUCIDE_AS_MATERIAL: [(&str, &str); 160] = [
("icons/alarm-clock.svg", "symbols/alarm.svg"),
("icons/app-window.svg", "symbols/web_asset.svg"),
("icons/arrow-down.svg", "symbols/arrow_downward.svg"),
@@ -384,6 +385,7 @@ const LUCIDE_AS_MATERIAL: [(&str, &str); 159] = [
("icons/target.svg", "symbols/target.svg"),
("icons/thumbs-down.svg", "symbols/thumb_down.svg"),
("icons/thumbs-up.svg", "symbols/thumb_up.svg"),
("icons/ticket.svg", "symbols/confirmation_number.svg"), // KVT-fork
("icons/timer.svg", "symbols/timer.svg"),
("icons/trash.svg", "symbols/delete.svg"),
("icons/triangle-alert.svg", "symbols/warning.svg"),
@@ -8,7 +8,7 @@ macro_rules! symbols { }; };}}const SYMBOLS: [(&str, &[u8]); 208] = symbols![const SYMBOLS: [(&str, &[u8]); 209] = symbols![ "account_circle", "account_circle", "add", "add", "alarm", "alarm",@@ -57,6 +57,7 @@ const SYMBOLS: [(&str, &[u8]); 208] = symbols![ "cloud", "cloud", "cloud_upload", "cloud_upload", "code", "code", "confirmation_number", // KVT-fork: Asclepius-tegel "code_blocks", "code_blocks", "content_copy", "content_copy", "content_paste", "content_paste",@@ -219,7 +220,7 @@ const SYMBOLS: [(&str, &[u8]); 208] = symbols![ "zoom_out", "zoom_out",];];const LUCIDE_AS_MATERIAL: [(&str, &str); 159] = [const LUCIDE_AS_MATERIAL: [(&str, &str); 160] = [ ("icons/alarm-clock.svg", "symbols/alarm.svg"), ("icons/alarm-clock.svg", "symbols/alarm.svg"), ("icons/app-window.svg", "symbols/web_asset.svg"), ("icons/app-window.svg", "symbols/web_asset.svg"), ("icons/arrow-down.svg", "symbols/arrow_downward.svg"), ("icons/arrow-down.svg", "symbols/arrow_downward.svg"),@@ -384,6 +385,7 @@ const LUCIDE_AS_MATERIAL: [(&str, &str); 159] = [ ("icons/target.svg", "symbols/target.svg"), ("icons/target.svg", "symbols/target.svg"), ("icons/thumbs-down.svg", "symbols/thumb_down.svg"), ("icons/thumbs-down.svg", "symbols/thumb_down.svg"), ("icons/thumbs-up.svg", "symbols/thumb_up.svg"), ("icons/thumbs-up.svg", "symbols/thumb_up.svg"), ("icons/ticket.svg", "symbols/confirmation_number.svg"), // KVT-fork ("icons/timer.svg", "symbols/timer.svg"), ("icons/timer.svg", "symbols/timer.svg"), ("icons/trash.svg", "symbols/delete.svg"), ("icons/trash.svg", "symbols/delete.svg"), ("icons/triangle-alert.svg", "symbols/warning.svg"), ("icons/triangle-alert.svg", "symbols/warning.svg"),@@ -0,0 +1,66 @@
//! KVT-fork: instelling voor eigen vensterknoppen (client-side decorations).
//!
//! Standaard aan in de KVT-build. Uit schakelen brengt de vensterranden van het
//! systeem terug. Zie KVT-FORK.md.
use store::Store;
const META_KEY: &str = "kvt.window.client_decorations";
/// Standaard in de KVT-build: eigen knoppen in de titelbalk, geen systeemranden.
pub const DEFAULT_ENABLED: bool = true;
/// Of de gebruiker eigen vensterknoppen wil (en dus client-side decorations).
///
/// Een ontbrekende sleutel betekent de KVT-standaard (aan). Alleen een
/// opgeslagen `false` zet het uit.
pub fn load(store: &Store) -> bool {
match store.meta(META_KEY).ok().flatten().as_deref() {
Some("false") | Some("0") => false,
Some("true") | Some("1") => true,
Some(other) if other.trim().eq_ignore_ascii_case("false") => false,
Some(_) | None => DEFAULT_ENABLED,
}
}
pub fn save(store: &Store, enabled: bool) {
let _ = store.set_meta(META_KEY, if enabled { "true" } else { "false" });
}
/// Of deze bouw de instelling en de eigen knoppen toont.
///
/// Op macOS blijven de verkeerslichten van het systeem; daar is de instelling
/// verborgen en staan de eigen knoppen uit.
pub fn available() -> bool {
!cfg!(target_os = "macos")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_key_defaults_to_on() {
let store = Store::open_in_memory().unwrap();
assert!(load(&store));
assert!(DEFAULT_ENABLED);
}
#[test]
fn round_trips_off_and_on() {
let store = Store::open_in_memory().unwrap();
save(&store, false);
assert!(!load(&store));
save(&store, true);
assert!(load(&store));
}
#[test]
fn only_an_explicit_false_turns_it_off() {
let store = Store::open_in_memory().unwrap();
let _ = store.set_meta(META_KEY, "false");
assert!(!load(&store));
let _ = store.set_meta(META_KEY, "unexpected");
assert!(load(&store));
}
}
@@ -0,0 +1,66 @@//! KVT-fork: instelling voor eigen vensterknoppen (client-side decorations).//!//! Standaard aan in de KVT-build. Uit schakelen brengt de vensterranden van het//! systeem terug. Zie KVT-FORK.md.use store::Store;const META_KEY: &str = "kvt.window.client_decorations";/// Standaard in de KVT-build: eigen knoppen in de titelbalk, geen systeemranden.pub const DEFAULT_ENABLED: bool = true;/// Of de gebruiker eigen vensterknoppen wil (en dus client-side decorations).////// Een ontbrekende sleutel betekent de KVT-standaard (aan). Alleen een/// opgeslagen `false` zet het uit.pub fn load(store: &Store) -> bool { match store.meta(META_KEY).ok().flatten().as_deref() { Some("false") | Some("0") => false, Some("true") | Some("1") => true, Some(other) if other.trim().eq_ignore_ascii_case("false") => false, Some(_) | None => DEFAULT_ENABLED, }}pub fn save(store: &Store, enabled: bool) { let _ = store.set_meta(META_KEY, if enabled { "true" } else { "false" });}/// Of deze bouw de instelling en de eigen knoppen toont.////// Op macOS blijven de verkeerslichten van het systeem; daar is de instelling/// verborgen en staan de eigen knoppen uit.pub fn available() -> bool { !cfg!(target_os = "macos")}#[cfg(test)]mod tests { use super::*; #[test] fn missing_key_defaults_to_on() { let store = Store::open_in_memory().unwrap(); assert!(load(&store)); assert!(DEFAULT_ENABLED); } #[test] fn round_trips_off_and_on() { let store = Store::open_in_memory().unwrap(); save(&store, false); assert!(!load(&store)); save(&store, true); assert!(load(&store)); } #[test] fn only_an_explicit_false_turns_it_off() { let store = Store::open_in_memory().unwrap(); let _ = store.set_meta(META_KEY, "false"); assert!(!load(&store)); let _ = store.set_meta(META_KEY, "unexpected"); assert!(load(&store)); }}@@ -24,6 +24,7 @@ pub mod image_view_math;
pub mod inline_image;
pub mod kvt_brand;
pub mod kvt_feed;
pub mod kvt_window;
#[cfg(target_os = "linux")]
pub mod linux_desktop;
#[cfg(target_os = "linux")]
@@ -24,6 +24,7 @@ pub mod image_view_math;pub mod inline_image;pub mod inline_image;pub mod kvt_brand;pub mod kvt_brand;pub mod kvt_feed;pub mod kvt_feed;pub mod kvt_window;#[cfg(target_os = "linux")]#[cfg(target_os = "linux")]pub mod linux_desktop;pub mod linux_desktop;#[cfg(target_os = "linux")]#[cfg(target_os = "linux")]@@ -1,5 +1,5 @@
use gpui_kit::{ImageSource, SharedString};
use teams_core::{Gif, ImageRef};
use teams_core::{Gif, ImageRef, OrgEmoji, custom_emoji_html};
use crate::stickers::Sticker;
@@ -8,10 +8,11 @@ const STICKER_SIZE: u32 = 250;
const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";
const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RemoteKind {
Gif,
Sticker,
CustomEmoji { object_id: String },
}
/// A GIF or sticker the message points at by URL; nothing is uploaded.
@@ -46,18 +47,42 @@ impl RemoteImage {
}
}
pub fn custom_emoji(emoji: &OrgEmoji) -> Self {
RemoteImage {
kind: RemoteKind::CustomEmoji {
object_id: emoji.document_id.clone(),
},
url: emoji.image_url(),
title: emoji.name.clone(),
width: 20,
height: 20,
}
}
pub fn is_custom_emoji(&self) -> bool {
matches!(self.kind, RemoteKind::CustomEmoji { .. })
}
pub fn html(&self) -> String {
let itemtype = match self.kind {
RemoteKind::Gif => GIF_ITEMTYPE,
RemoteKind::Sticker => STICKER_ITEMTYPE,
};
format!(
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{itemtype}\">",
teams_core::escape_html(&self.url),
self.width,
self.height,
teams_core::escape_html(&self.title),
)
match &self.kind {
RemoteKind::CustomEmoji { object_id } => {
custom_emoji_html(&self.title, object_id, &self.url)
}
RemoteKind::Gif => format!(
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{GIF_ITEMTYPE}\">",
teams_core::escape_html(&self.url),
self.width,
self.height,
teams_core::escape_html(&self.title),
),
RemoteKind::Sticker => format!(
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{STICKER_ITEMTYPE}\">",
teams_core::escape_html(&self.url),
self.width,
self.height,
teams_core::escape_html(&self.title),
),
}
}
pub fn image_ref(&self) -> ImageRef {
@@ -131,4 +156,20 @@ mod tests {
assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));
assert!(html.contains("clippy-250x250"));
}
#[test]
fn custom_emoji_html_uses_the_official_itemtype_and_itemid() {
let emoji = OrgEmoji {
id: "em-1".into(),
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
name: "absolute-cinema".into(),
keywords: vec![],
source: None,
};
let html = RemoteImage::custom_emoji(&emoji).html();
assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));
assert!(html.contains("itemid=\"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));
assert!(html.contains("width=\"20\" height=\"20\""));
assert!(html.contains("/views/imgt2_anim"));
}
}
@@ -1,5 +1,5 @@use gpui_kit::{ImageSource, SharedString};use gpui_kit::{ImageSource, SharedString};use teams_core::{Gif, ImageRef};use teams_core::{Gif, ImageRef, OrgEmoji, custom_emoji_html};use crate::stickers::Sticker;use crate::stickers::Sticker;@@ -8,10 +8,11 @@ const STICKER_SIZE: u32 = 250;const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";#[derive(Debug, Clone, Copy, PartialEq, Eq)]#[derive(Debug, Clone, PartialEq, Eq)]pub enum RemoteKind {pub enum RemoteKind { Gif, Gif, Sticker, Sticker, CustomEmoji { object_id: String },}}/// A GIF or sticker the message points at by URL; nothing is uploaded./// A GIF or sticker the message points at by URL; nothing is uploaded.@@ -46,18 +47,42 @@ impl RemoteImage { } } } } pub fn custom_emoji(emoji: &OrgEmoji) -> Self { RemoteImage { kind: RemoteKind::CustomEmoji { object_id: emoji.document_id.clone(), }, url: emoji.image_url(), title: emoji.name.clone(), width: 20, height: 20, } } pub fn is_custom_emoji(&self) -> bool { matches!(self.kind, RemoteKind::CustomEmoji { .. }) } pub fn html(&self) -> String { pub fn html(&self) -> String { let itemtype = match self.kind { match &self.kind { RemoteKind::Gif => GIF_ITEMTYPE, RemoteKind::CustomEmoji { object_id } => { RemoteKind::Sticker => STICKER_ITEMTYPE, custom_emoji_html(&self.title, object_id, &self.url) }; } format!( RemoteKind::Gif => format!( "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{itemtype}\">", "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{GIF_ITEMTYPE}\">", teams_core::escape_html(&self.url), teams_core::escape_html(&self.url), self.width, self.width, self.height, self.height, teams_core::escape_html(&self.title), teams_core::escape_html(&self.title), ) ), RemoteKind::Sticker => format!( "<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{STICKER_ITEMTYPE}\">", teams_core::escape_html(&self.url), self.width, self.height, teams_core::escape_html(&self.title), ), } } } pub fn image_ref(&self) -> ImageRef { pub fn image_ref(&self) -> ImageRef {@@ -131,4 +156,20 @@ mod tests { assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">")); assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">")); assert!(html.contains("clippy-250x250")); assert!(html.contains("clippy-250x250")); } } #[test] fn custom_emoji_html_uses_the_official_itemtype_and_itemid() { let emoji = OrgEmoji { id: "em-1".into(), document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(), name: "absolute-cinema".into(), keywords: vec![], source: None, }; let html = RemoteImage::custom_emoji(&emoji).html(); assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\"")); assert!(html.contains("itemid=\"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\"")); assert!(html.contains("width=\"20\" height=\"20\"")); assert!(html.contains("/views/imgt2_anim")); }}}@@ -13,7 +13,8 @@ use store::{
use teams_core::{
ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,
CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage,
LinkPreview, MentionCandidate, NOTES_CHAT_ID, OrgEmoji, PersonCandidate, PersonSource, PinnedMessage,
custom_emoji_html,
SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
};
@@ -24,6 +25,7 @@ use crate::demo_gifs;
use crate::message_actions::ForwardSource;
static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
static DEMO_ORG_EMOJIS: OnceLock<Vec<OrgEmoji>> = OnceLock::new();
pub const DEMO_USER_ID: &str = "demo-me";
const DEMO_USER_NAME: &str = "Dana Demo";
@@ -595,6 +597,101 @@ fn image_directory() -> PathBuf {
std::env::temp_dir().join("rusty-teams-demo")
}
pub const DEMO_ORG_KOFIE_ID: &str = "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
pub const DEMO_ORG_SHIPIT_ID: &str = "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
pub const DEMO_ORG_HIGHFIVE_ID: &str = "0-weu-d1-cccccccccccccccccccccccccccccccc";
pub const DEMO_ORG_FEEST_ID: &str = "0-weu-d1-dddddddddddddddddddddddddddddddd";
pub fn org_emoji_demo_url(name: &str) -> String {
format!("demo://org-emoji-{name}")
}
pub fn org_emoji_source(object_id: &str) -> Option<String> {
DEMO_ORG_EMOJIS
.get()
.into_iter()
.flatten()
.find(|emoji| emoji.document_id == object_id)
.and_then(|emoji| emoji.source.clone())
}
pub fn org_emoji_image_url(object_id: &str) -> Option<String> {
DEMO_ORG_EMOJIS
.get()
.into_iter()
.flatten()
.find(|emoji| emoji.document_id == object_id)
.map(|emoji| org_emoji_demo_url(&emoji.name))
}
pub fn ensure_org_emojis() -> Vec<OrgEmoji> {
if let Some(emojis) = DEMO_ORG_EMOJIS.get() {
return emojis.clone();
}
let emojis = generate_org_emojis(&image_directory());
let _ = DEMO_ORG_EMOJIS.set(emojis.clone());
emojis
}
fn demo_org_emoji_html(name: &str, document_id: &str) -> String {
custom_emoji_html(name, document_id, &org_emoji_demo_url(name))
}
pub fn org_emojis() -> Vec<OrgEmoji> {
ensure_org_emojis()
}
pub fn search_org_emojis(query: &str) -> Vec<OrgEmoji> {
org_emojis()
.into_iter()
.filter(|emoji| emoji.matches(query))
.collect()
}
fn generate_org_emojis(directory: &std::path::Path) -> Vec<OrgEmoji> {
const FACES: [(&str, &str, &str, [u8; 3], &[&str]); 4] = [
("demo-koffie", "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "koffie", [166, 92, 46], &["koffie", "coffee"]),
("demo-shipit", "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "ship-it", [47, 133, 90], &["ship", "lancering"]),
("demo-highfive", "0-weu-d1-cccccccccccccccccccccccccccccccc", "high-five", [196, 92, 58], &["highfive", "team"]),
("demo-feest", "0-weu-d1-dddddddddddddddddddddddddddddddd", "feest", [126, 68, 173], &["feest", "party"]),
];
let mut emojis = Vec::new();
let _ = std::fs::create_dir_all(directory);
for (id, document_id, name, color, keywords) in FACES {
let path = directory.join(format!("org-emoji-{name}.png"));
let png = encode_rgb(32, 32, |column, row| {
let dx = column as i32 - 16;
let dy = row as i32 - 16;
if dx * dx + dy * dy <= 13 * 13 {
if (dx + dy) < -6 {
[
color[0].saturating_add(40).min(255),
color[1].saturating_add(40).min(255),
color[2].saturating_add(40).min(255),
]
} else {
color
}
} else {
[255, 255, 255]
}
});
let source = if std::fs::write(&path, png).is_ok() {
Some(path.to_string_lossy().into_owned())
} else {
None
};
emojis.push(OrgEmoji {
id: id.to_owned(),
document_id: document_id.to_owned(),
name: name.to_owned(),
keywords: keywords.iter().map(|keyword| (*keyword).to_owned()).collect(),
source,
});
}
emojis
}
pub fn search_gifs(query: &str) -> Vec<Gif> {
let query = query.trim().to_lowercase();
SEARCHABLE_GIFS
@@ -847,6 +944,7 @@ pub fn activity_snapshot() -> ActivitySnapshot {
}
pub fn seed(store: &Store) {
let _ = ensure_org_emojis();
let chats: Vec<ChatRecord> = demo_chats()
.into_iter()
.map(|demo| ChatRecord {
@@ -1092,6 +1190,14 @@ pub fn seed_directory(state: &mut AppState) {
state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);
}
let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
let org_emojis = ensure_org_emojis();
for emoji in &org_emojis {
if let Some(path) = emoji.source.as_deref() {
state
.directory
.set_image(&org_emoji_demo_url(&emoji.name), std::path::Path::new(path));
}
}
state.directory.set_image(
demo_gifs::RECEIVED_GIF_KEY,
&directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
@@ -2033,6 +2139,35 @@ fn release_messages() -> Vec<MessageRecord> {
"[]",
false,
),
{
let org = reactions_json(vec![
reaction(
&format!("koffie;{DEMO_ORG_KOFIE_ID}"),
&[
(MARA_ID, mara_name, at(0, 13, 58)),
(JONAS_ID, jonas_name, at(0, 13, 59)),
],
),
reaction(
&format!("feest;{DEMO_ORG_FEEST_ID}"),
&[(PRIYA_ID, priya_name, at(0, 14, 0))],
),
]);
message(
chat,
"m13",
None,
me,
at(0, 13, 56),
&format!(
"<p>De organisatie-emoji staan erin, bijvoorbeeld {} bij de koffie en {} als we live gaan.</p>",
demo_org_emoji_html("koffie", DEMO_ORG_KOFIE_ID),
demo_org_emoji_html("ship-it", DEMO_ORG_SHIPIT_ID),
),
&org,
false,
)
},
]
}
@@ -13,7 +13,8 @@ use store::{use teams_core::{use teams_core::{ ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot, ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings, LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage, LinkPreview, MentionCandidate, NOTES_CHAT_ID, OrgEmoji, PersonCandidate, PersonSource, PinnedMessage, custom_emoji_html, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,};};@@ -24,6 +25,7 @@ use crate::demo_gifs;use crate::message_actions::ForwardSource;use crate::message_actions::ForwardSource;static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();static DEMO_ORG_EMOJIS: OnceLock<Vec<OrgEmoji>> = OnceLock::new();pub const DEMO_USER_ID: &str = "demo-me";pub const DEMO_USER_ID: &str = "demo-me";const DEMO_USER_NAME: &str = "Dana Demo";const DEMO_USER_NAME: &str = "Dana Demo";@@ -595,6 +597,101 @@ fn image_directory() -> PathBuf { std::env::temp_dir().join("rusty-teams-demo") std::env::temp_dir().join("rusty-teams-demo")}}pub const DEMO_ORG_KOFIE_ID: &str = "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";pub const DEMO_ORG_SHIPIT_ID: &str = "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";pub const DEMO_ORG_HIGHFIVE_ID: &str = "0-weu-d1-cccccccccccccccccccccccccccccccc";pub const DEMO_ORG_FEEST_ID: &str = "0-weu-d1-dddddddddddddddddddddddddddddddd";pub fn org_emoji_demo_url(name: &str) -> String { format!("demo://org-emoji-{name}")}pub fn org_emoji_source(object_id: &str) -> Option<String> { DEMO_ORG_EMOJIS .get() .into_iter() .flatten() .find(|emoji| emoji.document_id == object_id) .and_then(|emoji| emoji.source.clone())}pub fn org_emoji_image_url(object_id: &str) -> Option<String> { DEMO_ORG_EMOJIS .get() .into_iter() .flatten() .find(|emoji| emoji.document_id == object_id) .map(|emoji| org_emoji_demo_url(&emoji.name))}pub fn ensure_org_emojis() -> Vec<OrgEmoji> { if let Some(emojis) = DEMO_ORG_EMOJIS.get() { return emojis.clone(); } let emojis = generate_org_emojis(&image_directory()); let _ = DEMO_ORG_EMOJIS.set(emojis.clone()); emojis}fn demo_org_emoji_html(name: &str, document_id: &str) -> String { custom_emoji_html(name, document_id, &org_emoji_demo_url(name))}pub fn org_emojis() -> Vec<OrgEmoji> { ensure_org_emojis()}pub fn search_org_emojis(query: &str) -> Vec<OrgEmoji> { org_emojis() .into_iter() .filter(|emoji| emoji.matches(query)) .collect()}fn generate_org_emojis(directory: &std::path::Path) -> Vec<OrgEmoji> { const FACES: [(&str, &str, &str, [u8; 3], &[&str]); 4] = [ ("demo-koffie", "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "koffie", [166, 92, 46], &["koffie", "coffee"]), ("demo-shipit", "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "ship-it", [47, 133, 90], &["ship", "lancering"]), ("demo-highfive", "0-weu-d1-cccccccccccccccccccccccccccccccc", "high-five", [196, 92, 58], &["highfive", "team"]), ("demo-feest", "0-weu-d1-dddddddddddddddddddddddddddddddd", "feest", [126, 68, 173], &["feest", "party"]), ]; let mut emojis = Vec::new(); let _ = std::fs::create_dir_all(directory); for (id, document_id, name, color, keywords) in FACES { let path = directory.join(format!("org-emoji-{name}.png")); let png = encode_rgb(32, 32, |column, row| { let dx = column as i32 - 16; let dy = row as i32 - 16; if dx * dx + dy * dy <= 13 * 13 { if (dx + dy) < -6 { [ color[0].saturating_add(40).min(255), color[1].saturating_add(40).min(255), color[2].saturating_add(40).min(255), ] } else { color } } else { [255, 255, 255] } }); let source = if std::fs::write(&path, png).is_ok() { Some(path.to_string_lossy().into_owned()) } else { None }; emojis.push(OrgEmoji { id: id.to_owned(), document_id: document_id.to_owned(), name: name.to_owned(), keywords: keywords.iter().map(|keyword| (*keyword).to_owned()).collect(), source, }); } emojis}pub fn search_gifs(query: &str) -> Vec<Gif> {pub fn search_gifs(query: &str) -> Vec<Gif> { let query = query.trim().to_lowercase(); let query = query.trim().to_lowercase(); SEARCHABLE_GIFS SEARCHABLE_GIFS@@ -847,6 +944,7 @@ pub fn activity_snapshot() -> ActivitySnapshot {}}pub fn seed(store: &Store) {pub fn seed(store: &Store) { let _ = ensure_org_emojis(); let chats: Vec<ChatRecord> = demo_chats() let chats: Vec<ChatRecord> = demo_chats() .into_iter() .into_iter() .map(|demo| ChatRecord { .map(|demo| ChatRecord {@@ -1092,6 +1190,14 @@ pub fn seed_directory(state: &mut AppState) { state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path); state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path); } } let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path)); let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path)); let org_emojis = ensure_org_emojis(); for emoji in &org_emojis { if let Some(path) = emoji.source.as_deref() { state .directory .set_image(&org_emoji_demo_url(&emoji.name), std::path::Path::new(path)); } } state.directory.set_image( state.directory.set_image( demo_gifs::RECEIVED_GIF_KEY, demo_gifs::RECEIVED_GIF_KEY, &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)), &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),@@ -2033,6 +2139,35 @@ fn release_messages() -> Vec<MessageRecord> { "[]", "[]", false, false, ), ), { let org = reactions_json(vec![ reaction( &format!("koffie;{DEMO_ORG_KOFIE_ID}"), &[ (MARA_ID, mara_name, at(0, 13, 58)), (JONAS_ID, jonas_name, at(0, 13, 59)), ], ), reaction( &format!("feest;{DEMO_ORG_FEEST_ID}"), &[(PRIYA_ID, priya_name, at(0, 14, 0))], ), ]); message( chat, "m13", None, me, at(0, 13, 56), &format!( "<p>De organisatie-emoji staan erin, bijvoorbeeld {} bij de koffie en {} als we live gaan.</p>", demo_org_emoji_html("koffie", DEMO_ORG_KOFIE_ID), demo_org_emoji_html("ship-it", DEMO_ORG_SHIPIT_ID), ), &org, false, ) }, ] ]}}@@ -1,5 +1,5 @@
//! KVT-fork: een demobericht met Business Central-links, zodat `--demo` de
//! kaartjes van `crate::kvt` (app) laat zien. Verzonnen nummers, geen echte data.
//! kaartjes van `crate::kvt` (app) laat zien, plus een Asclepius-ticketlink. Verzonnen nummers, geen echte data.
use store::MessageRecord;
@@ -10,6 +10,7 @@ const COMPONENT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninkli
const PROJECT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=88&filter=%27No.%27%20IS%20%27PRJ2699001%27";
const CUSTOMER: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=21&filter=%27No.%27%20IS%20%27269901%27";
const ITEM: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=30&filter=%27No.%27%20IS%20%272699001%27";
const TICKET: &str = "https://sleutels.kvt.nl/asclepius/index.php?open=4102";
const CONTRACT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333015&filter=%27Contract%20No.%27%20IS%20%27CT2699001%27";
pub fn messages() -> Vec<MessageRecord> {
@@ -28,6 +29,14 @@ pub fn messages() -> Vec<MessageRecord> {
"<p>Zelfde klant, project en artikel erbij:</p><p><a href=\"{CUSTOMER}\">Klant 269901 - Rederij Voorbeeld</a></p><p><a href=\"{PROJECT}\">Project PRJ2699001 - Nieuwbouw aandrijving</a></p><p><a href=\"{ITEM}\">Artikel 2699001 - Brandstoffilter 12 µm</a></p>"
),
),
// Asclepius-ticketlink: opent het ticketvenster (demoticket #4102).
message(
"kvt4",
at(0, 11, 3),
format!(
"<p>Ik heb er een ticket van gemaakt: <a href=\"{TICKET}\">#4102 Laptop start niet meer op</a></p>"
),
),
// Alleen de link: de app laat dan alleen het kaartje zien.
message(
"kvt3",
@@ -1,5 +1,5 @@//! KVT-fork: een demobericht met Business Central-links, zodat `--demo` de//! KVT-fork: een demobericht met Business Central-links, zodat `--demo` de//! kaartjes van `crate::kvt` (app) laat zien. Verzonnen nummers, geen echte data.//! kaartjes van `crate::kvt` (app) laat zien, plus een Asclepius-ticketlink. Verzonnen nummers, geen echte data.use store::MessageRecord;use store::MessageRecord;@@ -10,6 +10,7 @@ const COMPONENT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninkliconst PROJECT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=88&filter=%27No.%27%20IS%20%27PRJ2699001%27";const PROJECT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=88&filter=%27No.%27%20IS%20%27PRJ2699001%27";const CUSTOMER: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=21&filter=%27No.%27%20IS%20%27269901%27";const CUSTOMER: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=21&filter=%27No.%27%20IS%20%27269901%27";const ITEM: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=30&filter=%27No.%27%20IS%20%272699001%27";const ITEM: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=30&filter=%27No.%27%20IS%20%272699001%27";const TICKET: &str = "https://sleutels.kvt.nl/asclepius/index.php?open=4102";const CONTRACT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333015&filter=%27Contract%20No.%27%20IS%20%27CT2699001%27";const CONTRACT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333015&filter=%27Contract%20No.%27%20IS%20%27CT2699001%27";pub fn messages() -> Vec<MessageRecord> {pub fn messages() -> Vec<MessageRecord> {@@ -28,6 +29,14 @@ pub fn messages() -> Vec<MessageRecord> { "<p>Zelfde klant, project en artikel erbij:</p><p><a href=\"{CUSTOMER}\">Klant 269901 - Rederij Voorbeeld</a></p><p><a href=\"{PROJECT}\">Project PRJ2699001 - Nieuwbouw aandrijving</a></p><p><a href=\"{ITEM}\">Artikel 2699001 - Brandstoffilter 12 µm</a></p>" "<p>Zelfde klant, project en artikel erbij:</p><p><a href=\"{CUSTOMER}\">Klant 269901 - Rederij Voorbeeld</a></p><p><a href=\"{PROJECT}\">Project PRJ2699001 - Nieuwbouw aandrijving</a></p><p><a href=\"{ITEM}\">Artikel 2699001 - Brandstoffilter 12 µm</a></p>" ), ), ), ), // Asclepius-ticketlink: opent het ticketvenster (demoticket #4102). message( "kvt4", at(0, 11, 3), format!( "<p>Ik heb er een ticket van gemaakt: <a href=\"{TICKET}\">#4102 Laptop start niet meer op</a></p>" ), ), // Alleen de link: de app laat dan alleen het kaartje zien. // Alleen de link: de app laat dan alleen het kaartje zien. message( message( "kvt3", "kvt3",@@ -45,6 +45,7 @@ pub mod message_actions;
pub mod notice;
pub mod notify;
mod org_actions;
pub mod org_emojis;
pub mod org_watch;
pub mod outbox;
pub mod outgoing;
@@ -45,6 +45,7 @@ pub mod message_actions;pub mod notice;pub mod notice;pub mod notify;pub mod notify;mod org_actions;mod org_actions;pub mod org_emojis;pub mod org_watch;pub mod org_watch;pub mod outbox;pub mod outbox;pub mod outgoing;pub mod outgoing;@@ -0,0 +1,67 @@
use std::sync::Arc;
use teams_core::OrgEmoji;
use tokio::sync::oneshot;
use crate::backend::Engine;
use crate::{demo, runtime};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrgEmojiError {
Failed,
}
pub type OrgEmojiList = oneshot::Receiver<Result<Vec<OrgEmoji>, OrgEmojiError>>;
/// Demo mode answers with fabricated organisation emojis. A live session
/// uses the cached CSA catalogue, refreshing when it is older than 30 minutes.
pub fn list(engine: Option<Arc<Engine>>, demo_mode: bool, force: bool) -> OrgEmojiList {
if demo_mode {
return runtime::spawn(async move { Ok(demo::org_emojis()) });
}
let Some(engine) = engine else {
let (sender, receiver) = oneshot::channel();
let _ = sender.send(Err(OrgEmojiError::Failed));
return receiver;
};
runtime::spawn(async move {
engine
.list_org_emojis(force)
.await
.map_err(|_| OrgEmojiError::Failed)
})
}
pub fn filter<'a>(emojis: &'a [OrgEmoji], query: &str) -> Vec<&'a OrgEmoji> {
emojis
.iter()
.filter(|emoji| emoji.matches(query))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn demo_catalogue_is_searchable_by_name_and_keyword() {
let emojis = crate::demo::org_emojis();
assert!(emojis.len() >= 4);
assert!(emojis.iter().any(|emoji| emoji.name == "koffie"));
assert!(filter(&emojis, "ship").iter().any(|emoji| emoji.name == "ship-it"));
assert!(filter(&emojis, "lancering").iter().any(|emoji| emoji.name == "ship-it"));
assert!(filter(&emojis, "zzz").is_empty());
for emoji in &emojis {
assert!(emoji.document_id.starts_with("0-"));
let source = emoji.source.as_deref().expect("demo writes a local png");
assert!(std::path::Path::new(source).is_file());
}
let key = format!("koffie;{}", crate::demo::DEMO_ORG_KOFIE_ID);
let image = crate::rows::custom_emoji_image(&key).expect("demo koffie");
assert_eq!(image.url, crate::demo::org_emoji_demo_url("koffie"));
assert!(!image.url.contains("custo"), "{}", image.url);
assert_eq!(image.alt.as_deref(), Some("koffie"));
let source = crate::demo::org_emoji_source(crate::demo::DEMO_ORG_KOFIE_ID).expect("source");
assert!(std::path::Path::new(&source).is_file());
}
}
@@ -0,0 +1,67 @@use std::sync::Arc;use teams_core::OrgEmoji;use tokio::sync::oneshot;use crate::backend::Engine;use crate::{demo, runtime};#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum OrgEmojiError { Failed,}pub type OrgEmojiList = oneshot::Receiver<Result<Vec<OrgEmoji>, OrgEmojiError>>;/// Demo mode answers with fabricated organisation emojis. A live session/// uses the cached CSA catalogue, refreshing when it is older than 30 minutes.pub fn list(engine: Option<Arc<Engine>>, demo_mode: bool, force: bool) -> OrgEmojiList { if demo_mode { return runtime::spawn(async move { Ok(demo::org_emojis()) }); } let Some(engine) = engine else { let (sender, receiver) = oneshot::channel(); let _ = sender.send(Err(OrgEmojiError::Failed)); return receiver; }; runtime::spawn(async move { engine .list_org_emojis(force) .await .map_err(|_| OrgEmojiError::Failed) })}pub fn filter<'a>(emojis: &'a [OrgEmoji], query: &str) -> Vec<&'a OrgEmoji> { emojis .iter() .filter(|emoji| emoji.matches(query)) .collect()}#[cfg(test)]mod tests { use super::*; #[test] fn demo_catalogue_is_searchable_by_name_and_keyword() { let emojis = crate::demo::org_emojis(); assert!(emojis.len() >= 4); assert!(emojis.iter().any(|emoji| emoji.name == "koffie")); assert!(filter(&emojis, "ship").iter().any(|emoji| emoji.name == "ship-it")); assert!(filter(&emojis, "lancering").iter().any(|emoji| emoji.name == "ship-it")); assert!(filter(&emojis, "zzz").is_empty()); for emoji in &emojis { assert!(emoji.document_id.starts_with("0-")); let source = emoji.source.as_deref().expect("demo writes a local png"); assert!(std::path::Path::new(source).is_file()); } let key = format!("koffie;{}", crate::demo::DEMO_ORG_KOFIE_ID); let image = crate::rows::custom_emoji_image(&key).expect("demo koffie"); assert_eq!(image.url, crate::demo::org_emoji_demo_url("koffie")); assert!(!image.url.contains("custo"), "{}", image.url); assert_eq!(image.alt.as_deref(), Some("koffie")); let source = crate::demo::org_emoji_source(crate::demo::DEMO_ORG_KOFIE_ID).expect("source"); assert!(std::path::Path::new(&source).is_file()); }}@@ -1,6 +1,6 @@
use std::fmt::Display;
use app_base::ui_locale::tr_with;
use app_base::ui_locale::{tr, tr_with};
use chrono::{DateTime, Datelike, TimeZone, Utc};
use crate::rows::ReactionChip;
@@ -57,7 +57,21 @@ pub fn chip_tooltip(chip: &ReactionChip) -> String {
.iter()
.map(|reactor| reactor.name.as_str())
.collect();
tooltip_text(&names)
let people = tooltip_text(&names);
match emoji_tooltip_name(chip) {
Some(name) if people.is_empty() => name,
Some(name) => format!("{name}\n{people}"),
None => people,
}
}
fn emoji_tooltip_name(chip: &ReactionChip) -> Option<String> {
chatsvc::custom_emoji_display_name(&chip.reaction_type)
.or_else(|| chatsvc::custom_emoji_display_name(&chip.glyph()))
.or_else(|| {
chatsvc::hides_raw_reaction_key(&chip.reaction_type)
.then(|| tr("reaction.custom_emoji"))
})
}
pub fn reaction_time_label<Zone>(time: DateTime<Utc>, now: &DateTime<Zone>) -> String
@@ -1,6 +1,6 @@use std::fmt::Display;use std::fmt::Display;use app_base::ui_locale::tr_with;use app_base::ui_locale::{tr, tr_with};use chrono::{DateTime, Datelike, TimeZone, Utc};use chrono::{DateTime, Datelike, TimeZone, Utc};use crate::rows::ReactionChip;use crate::rows::ReactionChip;@@ -57,7 +57,21 @@ pub fn chip_tooltip(chip: &ReactionChip) -> String { .iter() .iter() .map(|reactor| reactor.name.as_str()) .map(|reactor| reactor.name.as_str()) .collect(); .collect(); tooltip_text(&names) let people = tooltip_text(&names); match emoji_tooltip_name(chip) { Some(name) if people.is_empty() => name, Some(name) => format!("{name}\n{people}"), None => people, }}fn emoji_tooltip_name(chip: &ReactionChip) -> Option<String> { chatsvc::custom_emoji_display_name(&chip.reaction_type) .or_else(|| chatsvc::custom_emoji_display_name(&chip.glyph())) .or_else(|| { chatsvc::hides_raw_reaction_key(&chip.reaction_type) .then(|| tr("reaction.custom_emoji")) })}}pub fn reaction_time_label<Zone>(time: DateTime<Utc>, now: &DateTime<Zone>) -> Stringpub fn reaction_time_label<Zone>(time: DateTime<Utc>, now: &DateTime<Zone>) -> String@@ -60,10 +60,13 @@ impl ReactionChip {
/// Text for places without images: the org emoji's name instead of its raw key.
pub fn reaction_text(reaction_type: &str) -> String {
match chatsvc::custom_emoji(reaction_type) {
Some(emoji) => format!(":{}:", emoji.name),
None => reaction_glyph(reaction_type),
if let Some(name) = chatsvc::custom_emoji_display_name(reaction_type) {
return format!(":{name}:");
}
if chatsvc::hides_raw_reaction_key(reaction_type) {
return app_base::ui_locale::tr("reaction.custom_emoji");
}
reaction_glyph(reaction_type)
}
pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {
@@ -72,7 +75,7 @@ pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {
};
Some(ImageRef {
id: emoji.object_id.to_owned(),
url: emoji.image_url(),
url: crate::demo::org_emoji_image_url(&emoji.object_id).unwrap_or_else(|| emoji.image_url()),
width: None,
height: None,
alt: Some(emoji.name.to_owned()),
@@ -514,6 +517,16 @@ pub fn apply_pending_reactions(
}
}
fn visible_reaction_label(reaction_type: &str, shown: &str) -> String {
if let Some(name) = chatsvc::custom_emoji_display_name(reaction_type) {
return format!(":{name}:");
}
if chatsvc::hides_raw_reaction_key(reaction_type) || chatsvc::hides_raw_reaction_key(shown) {
return String::new();
}
shown.to_owned()
}
pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
let my_user_id = context.my_user_id.as_deref();
let mut chips: Vec<ReactionChip> = Vec::new();
@@ -553,7 +566,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<R
});
}
for (chip, shown) in chips.iter_mut().zip(variants) {
chip.label = shown.concat();
chip.label = visible_reaction_label(&chip.reaction_type, &shown.concat());
}
chips
}
@@ -1411,6 +1424,23 @@ mod tests {
.ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim")
);
assert_eq!(custom_emoji_image("like"), None);
assert_eq!(reaction_text("custom:tsignal"), ":tsignal:");
assert_ne!(reaction_text("custom"), "custom");
let hosted = concat!(
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/",
"aWQ9MC13dWstZDItZjM4MjU3YzBmYmEyZDI5ODFlYzJhMzY4YzVjZjE4NTMsdHlwZT0xLHVybD0=/",
"$value",
);
let from_graph =
chatsvc::custom_reaction_key("custom", Some("tsignal"), Some(hosted), None)
.expect("key");
assert_eq!(reaction_text(&from_graph), ":tsignal:");
let image = custom_emoji_image(&from_graph).expect("graph image");
assert!(
image
.url
.ends_with("/0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853/views/imgt2_anim")
);
}
#[test]
@@ -60,10 +60,13 @@ impl ReactionChip {/// Text for places without images: the org emoji's name instead of its raw key./// Text for places without images: the org emoji's name instead of its raw key.pub fn reaction_text(reaction_type: &str) -> String {pub fn reaction_text(reaction_type: &str) -> String { match chatsvc::custom_emoji(reaction_type) { if let Some(name) = chatsvc::custom_emoji_display_name(reaction_type) { Some(emoji) => format!(":{}:", emoji.name), return format!(":{name}:"); None => reaction_glyph(reaction_type), } } if chatsvc::hides_raw_reaction_key(reaction_type) { return app_base::ui_locale::tr("reaction.custom_emoji"); } reaction_glyph(reaction_type)}}pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {@@ -72,7 +75,7 @@ pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> { }; }; Some(ImageRef { Some(ImageRef { id: emoji.object_id.to_owned(), id: emoji.object_id.to_owned(), url: emoji.image_url(), url: crate::demo::org_emoji_image_url(&emoji.object_id).unwrap_or_else(|| emoji.image_url()), width: None, width: None, height: None, height: None, alt: Some(emoji.name.to_owned()), alt: Some(emoji.name.to_owned()),@@ -514,6 +517,16 @@ pub fn apply_pending_reactions( } }}}fn visible_reaction_label(reaction_type: &str, shown: &str) -> String { if let Some(name) = chatsvc::custom_emoji_display_name(reaction_type) { return format!(":{name}:"); } if chatsvc::hides_raw_reaction_key(reaction_type) || chatsvc::hides_raw_reaction_key(shown) { return String::new(); } shown.to_owned()}pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> { let my_user_id = context.my_user_id.as_deref(); let my_user_id = context.my_user_id.as_deref(); let mut chips: Vec<ReactionChip> = Vec::new(); let mut chips: Vec<ReactionChip> = Vec::new();@@ -553,7 +566,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<R }); }); } } for (chip, shown) in chips.iter_mut().zip(variants) { for (chip, shown) in chips.iter_mut().zip(variants) { chip.label = shown.concat(); chip.label = visible_reaction_label(&chip.reaction_type, &shown.concat()); } } chips chips}}@@ -1411,6 +1424,23 @@ mod tests { .ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim") .ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim") ); ); assert_eq!(custom_emoji_image("like"), None); assert_eq!(custom_emoji_image("like"), None); assert_eq!(reaction_text("custom:tsignal"), ":tsignal:"); assert_ne!(reaction_text("custom"), "custom"); let hosted = concat!( "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/", "aWQ9MC13dWstZDItZjM4MjU3YzBmYmEyZDI5ODFlYzJhMzY4YzVjZjE4NTMsdHlwZT0xLHVybD0=/", "$value", ); let from_graph = chatsvc::custom_reaction_key("custom", Some("tsignal"), Some(hosted), None) .expect("key"); assert_eq!(reaction_text(&from_graph), ":tsignal:"); let image = custom_emoji_image(&from_graph).expect("graph image"); assert!( image .url .ends_with("/0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853/views/imgt2_anim") ); } } #[test] #[test]@@ -25,6 +25,7 @@ enum StoredObject {
Inline,
Gif(StoredRemote),
Sticker(StoredRemote),
CustomEmoji(StoredRemote),
}
#[derive(Serialize, Deserialize)]
@@ -33,6 +34,8 @@ struct StoredRemote {
title: String,
width: u32,
height: u32,
#[serde(default)]
object_id: Option<String>,
}
#[derive(Serialize, Deserialize)]
@@ -87,10 +90,15 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
title: remote.title.clone(),
width: remote.width,
height: remote.height,
object_id: match &remote.kind {
RemoteKind::CustomEmoji { object_id } => Some(object_id.clone()),
_ => None,
},
};
objects.push(match remote.kind {
objects.push(match &remote.kind {
RemoteKind::Gif => StoredObject::Gif(stored),
RemoteKind::Sticker => StoredObject::Sticker(stored),
RemoteKind::CustomEmoji { .. } => StoredObject::CustomEmoji(stored),
});
}
}
@@ -129,6 +137,12 @@ fn inline_image(stored: &AttachmentImage) -> Option<OutgoingImage> {
}
fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
let kind = match kind {
RemoteKind::CustomEmoji { .. } => RemoteKind::CustomEmoji {
object_id: stored.object_id.unwrap_or_default(),
},
other => other,
};
OutgoingImage::Remote(RemoteImage {
kind,
url: stored.url,
@@ -157,6 +171,10 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
StoredObject::Inline => inline.next().and_then(inline_image),
StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),
StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),
StoredObject::CustomEmoji(stored) => {
let object_id = stored.object_id.clone().unwrap_or_default();
Some(remote_image(RemoteKind::CustomEmoji { object_id }, stored))
}
})
.collect();
Some(Outgoing {
@@ -25,6 +25,7 @@ enum StoredObject { Inline, Inline, Gif(StoredRemote), Gif(StoredRemote), Sticker(StoredRemote), Sticker(StoredRemote), CustomEmoji(StoredRemote),}}#[derive(Serialize, Deserialize)]#[derive(Serialize, Deserialize)]@@ -33,6 +34,8 @@ struct StoredRemote { title: String, title: String, width: u32, width: u32, height: u32, height: u32, #[serde(default)] object_id: Option<String>,}}#[derive(Serialize, Deserialize)]#[derive(Serialize, Deserialize)]@@ -87,10 +90,15 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> { title: remote.title.clone(), title: remote.title.clone(), width: remote.width, width: remote.width, height: remote.height, height: remote.height, object_id: match &remote.kind { RemoteKind::CustomEmoji { object_id } => Some(object_id.clone()), _ => None, }, }; }; objects.push(match remote.kind { objects.push(match &remote.kind { RemoteKind::Gif => StoredObject::Gif(stored), RemoteKind::Gif => StoredObject::Gif(stored), RemoteKind::Sticker => StoredObject::Sticker(stored), RemoteKind::Sticker => StoredObject::Sticker(stored), RemoteKind::CustomEmoji { .. } => StoredObject::CustomEmoji(stored), }); }); } } } }@@ -129,6 +137,12 @@ fn inline_image(stored: &AttachmentImage) -> Option<OutgoingImage> {}}fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage { let kind = match kind { RemoteKind::CustomEmoji { .. } => RemoteKind::CustomEmoji { object_id: stored.object_id.unwrap_or_default(), }, other => other, }; OutgoingImage::Remote(RemoteImage { OutgoingImage::Remote(RemoteImage { kind, kind, url: stored.url, url: stored.url,@@ -157,6 +171,10 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> { StoredObject::Inline => inline.next().and_then(inline_image), StoredObject::Inline => inline.next().and_then(inline_image), StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)), StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)), StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)), StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)), StoredObject::CustomEmoji(stored) => { let object_id = stored.object_id.clone().unwrap_or_default(); Some(remote_image(RemoteKind::CustomEmoji { object_id }, stored)) } }) }) .collect(); .collect(); Some(Outgoing { Some(Outgoing {@@ -4,7 +4,9 @@ use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};
pub const IMAGE_PLACEHOLDER: &str = "[image]";
pub const CODE_PADDING: &str = "\u{2004}";
pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";
// Invisible width reservation. Black squares stay visible as dark bars
// beside the overlaid image when a color font or missed highlight paints them.
pub const EMOJI_PLACEHOLDER: &str = "\u{2003}\u{2003}";
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
const BASE_FONT_PIXELS: f32 = 14.;
@@ -4,7 +4,9 @@ use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};pub const IMAGE_PLACEHOLDER: &str = "[image]";pub const IMAGE_PLACEHOLDER: &str = "[image]";pub const CODE_PADDING: &str = "\u{2004}";pub const CODE_PADDING: &str = "\u{2004}";pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";// Invisible width reservation. Black squares stay visible as dark bars// beside the overlaid image when a color font or missed highlight paints them.pub const EMOJI_PLACEHOLDER: &str = "\u{2003}\u{2003}";const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";const BASE_FONT_PIXELS: f32 = 14.;const BASE_FONT_PIXELS: f32 = 14.;@@ -452,13 +452,6 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
.into_iter()
.map(|range| (range, emoji_family.clone())),
)
.chain(
inline
.segments
.iter()
.filter(|segment| segment.emoji.is_some())
.map(|segment| (segment.range.clone(), emoji_family.clone())),
)
.collect();
font_overrides.sort_by_key(|(range, _)| range.start);
let keycaps = keycap_ranges(&inline.text);
@@ -501,11 +494,11 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
},
None => highlight_for(segment.style, own),
},
family: if segment.emoji.is_some() {
Some(SharedString::from(theme::EMOJI_FONT_FAMILY))
} else {
segment.style.code.then(|| mono.clone())
},
family: segment
.style
.code
.then(|| mono.clone())
.filter(|_| segment.emoji.is_none()),
scale: segment.style.font_scale(),
raise: segment.style.baseline_raise(),
})
@@ -452,13 +452,6 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement .into_iter() .into_iter() .map(|range| (range, emoji_family.clone())), .map(|range| (range, emoji_family.clone())), ) ) .chain( inline .segments .iter() .filter(|segment| segment.emoji.is_some()) .map(|segment| (segment.range.clone(), emoji_family.clone())), ) .collect(); .collect(); font_overrides.sort_by_key(|(range, _)| range.start); font_overrides.sort_by_key(|(range, _)| range.start); let keycaps = keycap_ranges(&inline.text); let keycaps = keycap_ranges(&inline.text);@@ -501,11 +494,11 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement }, }, None => highlight_for(segment.style, own), None => highlight_for(segment.style, own), }, }, family: if segment.emoji.is_some() { family: segment Some(SharedString::from(theme::EMOJI_FONT_FAMILY)) .style } else { .code segment.style.code.then(|| mono.clone()) .then(|| mono.clone()) }, .filter(|_| segment.emoji.is_none()), scale: segment.style.font_scale(), scale: segment.style.font_scale(), raise: segment.style.baseline_raise(), raise: segment.style.baseline_raise(), }) })@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="M480-280q17 0 28.5-11.5T520-320q0-17-11.5-28.5T480-360q-17 0-28.5 11.5T440-320q0 17 11.5 28.5T480-280Zm0-160q17 0 28.5-11.5T520-480q0-17-11.5-28.5T480-520q-17 0-28.5 11.5T440-480q0 17 11.5 28.5T480-440Zm0-160q17 0 28.5-11.5T520-640q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640q0 17 11.5 28.5T480-600Zm320 440H160q-33 0-56.5-23.5T80-240v-160q33 0 56.5-23.5T160-480q0-33-23.5-56.5T80-560v-160q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v160q-33 0-56.5 23.5T800-480q0 33 23.5 56.5T880-400v160q0 33-23.5 56.5T800-160Zm0-80v-102q-37-22-58.5-58.5T720-480q0-43 21.5-79.5T800-618v-102H160v102q37 22 58.5 58.5T240-480q0 43-21.5 79.5T160-342v102h640ZM480-480Z"/></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="M480-280q17 0 28.5-11.5T520-320q0-17-11.5-28.5T480-360q-17 0-28.5 11.5T440-320q0 17 11.5 28.5T480-280Zm0-160q17 0 28.5-11.5T520-480q0-17-11.5-28.5T480-520q-17 0-28.5 11.5T440-480q0 17 11.5 28.5T480-440Zm0-160q17 0 28.5-11.5T520-640q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640q0 17 11.5 28.5T480-600Zm320 440H160q-33 0-56.5-23.5T80-240v-160q33 0 56.5-23.5T160-480q0-33-23.5-56.5T80-560v-160q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v160q-33 0-56.5 23.5T800-480q0 33 23.5 56.5T880-400v160q0 33-23.5 56.5T800-160Zm0-80v-102q-37-22-58.5-58.5T720-480q0-43 21.5-79.5T800-618v-102H160v102q37 22 58.5 58.5T240-480q0 43-21.5 79.5T160-342v102h640ZM480-480Z"/></svg>@@ -0,0 +1,1395 @@
//! Ponos-bord in het hoofdpaneel: de tegel «Ponos» in de navigatierail, direct
//! onder Agents (Tim). Links alle groepen die je in Ponos ziet (eerst
//! «Mijn Taken», je persoonlijke groep), rechts het bord met de kolommen van
//! Ponos. Taken maken, bewerken, afronden en slepen tussen en binnen kolommen.
//!
//! Upstream-haken: `views/rail.rs` (tegel), `views/sidebar.rs` (`SidebarTab::Ponos`),
//! `views/shell.rs` (hoofdpaneel). Zie KVT-FORK.md.
use std::collections::HashMap;
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::scroll::ScrollableElement as _;
use gpui_kit::component::{h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use kvt_sleutels::format::{iso_date_nl, parse_date_input};
use kvt_sleutels::ponos::{
MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask, STATUS_DONE, STATUSES, TaskInput,
apply_move, column, drop_position, group_url, name_from_email,
};
use kvt_sleutels::{CardsClient, ClientError};
use super::modal::{primary_button, secondary_button};
use super::tasks::{chip, field, label, muted, not_linked, ponos_error};
use super::{Link, base_url, forget_token, is_demo, link, notice, open_external, token_and_client};
use crate::app_state::AppHandle;
use crate::i18n::tr;
use crate::runtime;
use crate::theme::{self, ElevatedSurface as _};
use crate::views::widgets::symbol;
pub const KVT_BOARD_TAG: &str = "kvt-ponos-board";
/// Laatst gekozen groep op het bord (alleen een id, in de lokale opslag).
const BOARD_GROUP_META_KEY: &str = "kvt.ponos.board_group";
const TITLE_MAX: usize = 200;
const HEADER_HEIGHT: f32 = 60.;
const PAGE_PADDING: f32 = 20.;
const GROUPS_WIDTH: f32 = 240.;
const GROUP_ROW_HEIGHT: f32 = 36.;
const COLUMN_MIN_WIDTH: f32 = 220.;
const COLUMN_GAP: f32 = 12.;
const CARD_GAP: f32 = 8.;
const RADIUS: f32 = 10.;
const EDITOR_WIDTH: f32 = 560.;
const BACKDROP_OPACITY: f32 = 0.55;
#[derive(Clone)]
enum Nav {
NotLinked,
Loading,
Loaded(PonosNavigation),
Failed(ClientError),
}
#[derive(Clone)]
enum Tasks {
Loading,
Loaded(Vec<PonosTask>),
Failed(ClientError),
}
#[derive(Clone)]
struct DraggedTask {
id: String,
title: String,
from_status: String,
}
struct TaskGhost {
title: String,
}
impl Render for TaskGhost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.w(px(COLUMN_MIN_WIDTH))
.px(px(12.))
.py(px(10.))
.rounded(px(8.))
.flyout_surface()
.text_size(px(13.))
.text_color(theme::text())
.truncate()
.child(self.title.clone())
}
}
struct Editor {
/// `None`: nieuwe taak.
task: Option<PonosTask>,
status: String,
assignee: String,
target_group: Option<String>,
title: Entity<InputState>,
description: Entity<TextareaState>,
due: Entity<InputState>,
saving: bool,
error: Option<String>,
}
pub struct PonosBoard {
nav: Nav,
group: Option<String>,
tasks: Tasks,
generation: u64,
editor: Option<Editor>,
/// Alleen `--demo`: verzonnen taken per groep.
demo: HashMap<String, Vec<PonosTask>>,
}
/// Het bord als element van het hoofdpaneel (eenmalig aangemaakt).
pub fn board_view(cx: &mut App) -> AnyElement {
let existing = super::read(cx, |kvt| kvt.board.clone()).flatten();
let board = match existing {
Some(board) => board,
None => {
let board = cx.new(PonosBoard::new);
if cx.has_global::<super::Kvt>() {
cx.global_mut::<super::Kvt>().board = Some(board.clone());
}
board
}
};
div()
.flex_1()
.min_w_0()
.h_full()
.child(board)
.into_any_element()
}
/// De tegel is geopend: vers ophalen (bij de eerste keer laadt `new`).
pub fn board_opened(cx: &mut App) {
if let Some(board) = super::read(cx, |kvt| kvt.board.clone()).flatten() {
board.update(cx, |board, cx| board.reload(cx));
}
}
/// Na «Taak maken in Ponos» vanuit een bericht.
pub(super) fn refresh_board_if_open(cx: &mut App) {
board_opened(cx);
}
fn remembered_group(cx: &App) -> Option<String> {
let handle = cx.try_global::<AppHandle>()?;
handle
.0
.read(cx)
.store
.meta(BOARD_GROUP_META_KEY)
.ok()
.flatten()
}
fn remember_group(group: &str, cx: &App) {
if let Some(handle) = cx.try_global::<AppHandle>() {
let _ = handle
.0
.read(cx)
.store
.set_meta(BOARD_GROUP_META_KEY, group);
}
}
/// Gekozen groep als die nog bestaat, anders de eerste (Mijn Taken).
fn pick_group(wanted: Option<&str>, navigation: &PonosNavigation) -> Option<String> {
wanted
.filter(|wanted| navigation.groups.iter().any(|group| group.id == *wanted))
.map(str::to_owned)
.or_else(|| navigation.groups.first().map(|group| group.id.clone()))
}
fn status_fallback(status: &str) -> String {
tr(match status {
"in_progress" => "kvt.board_status.in_progress",
STATUS_DONE => "kvt.board_status.done",
_ => "kvt.board_status.todo",
})
}
impl PonosBoard {
fn new(cx: &mut Context<Self>) -> Self {
let demo = if is_demo(cx) {
super::demo::board_tasks()
} else {
HashMap::new()
};
let mut board = PonosBoard {
nav: Nav::Loading,
group: remembered_group(cx),
tasks: Tasks::Loading,
generation: 0,
editor: None,
demo,
};
board.reload(cx);
board
}
fn navigation(&self) -> Option<&PonosNavigation> {
match &self.nav {
Nav::Loaded(navigation) => Some(navigation),
_ => None,
}
}
fn current_group(&self) -> Option<&PonosGroup> {
let group = self.group.as_deref()?;
self.navigation()?
.groups
.iter()
.find(|candidate| candidate.id == group)
}
fn user_email(&self) -> String {
self.navigation()
.map(|navigation| navigation.user_email.clone())
.unwrap_or_default()
}
fn status_label(&self, status: &str) -> String {
match self.navigation() {
Some(navigation) => navigation.status_label(status, || status_fallback(status)),
None => status_fallback(status),
}
}
// --- laden ------------------------------------------------------------
fn reload(&mut self, cx: &mut Context<Self>) {
self.generation += 1;
if is_demo(cx) {
let navigation = super::demo::board_navigation(&self.demo);
self.group = pick_group(self.group.as_deref(), &navigation);
self.tasks = Tasks::Loaded(self.demo_tasks());
self.nav = Nav::Loaded(navigation);
cx.notify();
return;
}
let Some((token, client)) = token_and_client(cx) else {
self.nav = Nav::NotLinked;
cx.notify();
return;
};
if !matches!(self.nav, Nav::Loaded(_)) {
self.nav = Nav::Loading;
}
let generation = self.generation;
let wanted = self.group.clone();
let loading = runtime::spawn(async move {
let navigation = client.ponos_navigation(&token).await?;
let group = pick_group(wanted.as_deref(), &navigation);
let tasks = match &group {
Some(group) => client.ponos_tasks(&token, group).await,
None => Ok(Vec::new()),
};
Ok::<_, ClientError>((navigation, group, tasks))
});
cx.spawn(async move |this, cx| {
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| {
let unauthorized = matches!(&result, Err(ClientError::Unauthorized))
|| matches!(&result, Ok((_, _, Err(ClientError::Unauthorized))));
if unauthorized {
forget_token(cx);
}
this.update(cx, |this, cx| {
if this.generation != generation {
return;
}
match result {
Ok((navigation, group, tasks)) => {
this.group = group;
this.tasks = match tasks {
Ok(tasks) => Tasks::Loaded(tasks),
Err(error) => Tasks::Failed(error),
};
this.nav = Nav::Loaded(navigation);
}
Err(ClientError::Unauthorized) => this.nav = Nav::NotLinked,
Err(error) => this.nav = Nav::Failed(error),
}
cx.notify();
})
.ok();
});
})
.detach();
}
fn select_group(&mut self, group: String, cx: &mut Context<Self>) {
if self.group.as_deref() == Some(group.as_str()) {
return;
}
remember_group(&group, cx);
self.group = Some(group);
self.tasks = Tasks::Loading;
self.editor = None;
self.reload(cx);
}
// --- demo -------------------------------------------------------------
fn demo_tasks(&self) -> Vec<PonosTask> {
let Some(group) = self.group.as_deref() else {
return Vec::new();
};
if group == MY_TASKS_GROUP {
let mut mine: Vec<PonosTask> = self
.demo
.values()
.flatten()
.filter(|task| task.assignee_email == super::demo::BOARD_USER)
.cloned()
.collect();
mine.sort_by(|a, b| a.id.cmp(&b.id));
return mine;
}
self.demo.get(group).cloned().unwrap_or_default()
}
fn demo_task_mut(&mut self, id: &str) -> Option<&mut PonosTask> {
self.demo.values_mut().flatten().find(|task| task.id == id)
}
// --- acties -----------------------------------------------------------
/// Een schrijfactie bij Ponos; daarna altijd opnieuw laden.
fn submit<Fut>(
&mut self,
cx: &mut Context<Self>,
done: Option<String>,
job: impl FnOnce(String, CardsClient) -> Fut,
) where
Fut: std::future::Future<Output = Result<(), ClientError>> + Send + 'static,
{
let Some((token, client)) = token_and_client(cx) else {
self.reload(cx);
return;
};
let running = runtime::spawn(job(token, client));
cx.spawn(async move |this, cx| {
let result = running.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| {
match &result {
Ok(()) => {
if let Some(done) = done {
notice(done, cx);
}
}
Err(error) => {
if *error == ClientError::Unauthorized {
forget_token(cx);
}
notice(ponos_error(error), cx);
}
}
this.update(cx, |this, cx| {
if result.is_ok() {
this.editor = None;
} else if let Some(editor) = this.editor.as_mut() {
editor.saving = false;
}
this.reload(cx);
})
.ok();
});
})
.detach();
}
fn drop_task(
&mut self,
dragged: &DraggedTask,
status: &'static str,
before: Option<usize>,
cx: &mut Context<Self>,
) {
let Some(group) = self.group.clone() else {
return;
};
let Tasks::Loaded(tasks) = &mut self.tasks else {
return;
};
let position = drop_position(tasks, &dragged.id, status, before);
let unchanged = dragged.from_status == status
&& column(tasks, status).position(|task| task.id == dragged.id) == Some(position);
if unchanged || !apply_move(tasks, &dragged.id, status, position) {
return;
}
cx.notify();
let id = dragged.id.clone();
if is_demo(cx) {
if let Some(task) = self.demo_task_mut(&id) {
task.status = status.to_owned();
}
if group != MY_TASKS_GROUP
&& let Some(list) = self.demo.get_mut(&group)
{
apply_move(list, &id, status, position);
}
return;
}
let virtual_group = group == MY_TASKS_GROUP;
let status_changed = dragged.from_status != status;
if virtual_group && !status_changed {
// «Mijn Taken» heeft geen eigen volgorde in Ponos.
return;
}
self.submit(cx, None, move |token, client| async move {
if virtual_group {
client.ponos_set_status(&token, &group, &id, status).await?;
} else {
client
.ponos_reorder_task(&token, &group, &id, status, position)
.await?;
}
Ok(())
});
}
fn open_editor(
&mut self,
task: Option<PonosTask>,
status: &str,
window: &mut Window,
cx: &mut Context<Self>,
) {
let (title_text, description_text, due_text) = match &task {
Some(task) => (
task.title.clone(),
task.description.clone(),
iso_date_nl(&task.due_date).unwrap_or_default(),
),
None => Default::default(),
};
let title = cx.new(|cx| {
InputState::new(window, cx)
.placeholder(tr("kvt.ponos.title"))
.default_value(title_text)
});
let description = cx.new(|cx| {
TextareaState::new(window, cx)
.auto_grow(4, 10)
.placeholder(tr("kvt.ponos.description"))
.default_value(description_text)
});
let due = cx.new(|cx| {
InputState::new(window, cx)
.placeholder(tr("kvt.board.due_placeholder"))
.default_value(due_text)
});
title.update(cx, |input, cx| input.focus(window, cx));
let assignee = match &task {
Some(task) => task.assignee_email.clone(),
// Nieuw in «Mijn Taken» kan niet; elders standaard niemand.
None => String::new(),
};
self.editor = Some(Editor {
status: task
.as_ref()
.map_or_else(|| status.to_owned(), |task| task.status.clone()),
assignee,
target_group: None,
task,
title,
description,
due,
saving: false,
error: None,
});
cx.notify();
}
fn save_editor(&mut self, cx: &mut Context<Self>) {
let Some(group) = self.group.clone() else {
return;
};
let Some(editor) = self.editor.as_mut() else {
return;
};
if editor.saving {
return;
}
let title: String = editor
.title
.read(cx)
.value()
.trim()
.chars()
.take(TITLE_MAX)
.collect();
let description = editor.description.read(cx).value().trim().to_owned();
if title.is_empty() || description.is_empty() {
editor.error = Some(tr("kvt.ponos.fill_in"));
cx.notify();
return;
}
let Some(due_date) = parse_date_input(&editor.due.read(cx).value()) else {
editor.error = Some(tr("kvt.board.bad_date"));
cx.notify();
return;
};
let input = TaskInput {
title,
description,
due_date,
assignee_email: editor.assignee.clone(),
target_group: editor.target_group.clone(),
};
let status = editor.status.clone();
let existing = editor.task.clone();
editor.saving = true;
editor.error = None;
cx.notify();
if is_demo(cx) {
self.save_demo(&group, existing, input, status);
self.editor = None;
notice(tr("kvt.board.saved"), cx);
self.reload(cx);
return;
}
let done = tr(if existing.is_some() {
"kvt.board.saved"
} else {
"kvt.ponos.created"
});
self.submit(cx, Some(done), move |token, client| async move {
match existing {
Some(task) => {
let saved = client
.ponos_update_task(&token, &group, &task.id, &input)
.await?;
if saved.status != status {
let home = input.target_group.as_deref().unwrap_or(&group);
client
.ponos_set_status(&token, home, &saved.id, &status)
.await?;
}
}
None => {
let created = client.ponos_create(&token, &group, &input).await?;
if created.status != status {
client
.ponos_set_status(&token, &group, &created.id, &status)
.await?;
}
}
}
Ok(())
});
}
fn save_demo(
&mut self,
group: &str,
existing: Option<PonosTask>,
input: TaskInput,
status: String,
) {
match existing {
Some(task) => {
let home = task.group().to_owned();
let Some(list) = self.demo.get_mut(&home) else {
return;
};
let Some(index) = list.iter().position(|other| other.id == task.id) else {
return;
};
let mut updated = list.remove(index);
updated.title = input.title;
updated.description = input.description;
updated.due_date = input.due_date;
updated.assignee_email = input.assignee_email;
let target = input.target_group.unwrap_or(home.clone());
if target == home && updated.status == status {
list.insert(index, updated);
return;
}
updated.status = status;
updated.group_id = target.clone();
updated.home_group_id = target.clone();
self.demo.entry(target).or_default().push(updated);
}
None => {
let id = format!(
"demo-board-{}",
self.demo.values().map(Vec::len).sum::<usize>() + 1
);
let task = PonosTask {
id,
group_id: group.to_owned(),
home_group_id: group.to_owned(),
title: input.title,
status,
due_date: input.due_date,
description: input.description,
assignee_email: input.assignee_email,
..super::demo::empty_task()
};
self.demo.entry(group.to_owned()).or_default().push(task);
}
}
}
fn complete_from_editor(&mut self, cx: &mut Context<Self>) {
let Some(group) = self.group.clone() else {
return;
};
let Some(task) = self.editor.as_ref().and_then(|editor| editor.task.clone()) else {
return;
};
if is_demo(cx) {
if let Some(demo) = self.demo_task_mut(&task.id) {
demo.status = STATUS_DONE.to_owned();
}
self.editor = None;
notice(tr("kvt.tasks.completed"), cx);
self.reload(cx);
return;
}
if let Some(editor) = self.editor.as_mut() {
editor.saving = true;
}
self.submit(
cx,
Some(tr("kvt.tasks.completed")),
move |token, client| async move {
client.ponos_complete_task(&token, &group, &task.id).await
},
);
}
// --- weergave ---------------------------------------------------------
fn groups_list(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(navigation) = self.navigation() else {
return div().into_any_element();
};
v_flex()
.id("kvt-board-groups")
.w(px(GROUPS_WIDTH))
.h_full()
.flex_none()
.p(px(8.))
.gap(px(2.))
.border_r_1()
.border_color(theme::border())
.overflow_y_scrollbar()
.children(navigation.groups.iter().enumerate().map(|(index, group)| {
let selected = self.group.as_deref() == Some(group.id.as_str());
let id = group.id.clone();
h_flex()
.id(ElementId::Name(format!("kvt-board-group-{index}").into()))
.w_full()
.h(px(GROUP_ROW_HEIGHT))
.flex_none()
.px(px(10.))
.gap(px(8.))
.items_center()
.rounded(px(6.))
.cursor_pointer()
.text_size(px(13.))
.map(|row| {
if selected {
row.bg(theme::selection())
.text_color(theme::text_strong())
.font_weight(FontWeight::SEMIBOLD)
} else {
row.text_color(theme::text())
.hover(|row| row.bg(theme::row_hover()))
}
})
.on_click(cx.listener(move |this, _, _, cx| this.select_group(id.clone(), cx)))
.child(symbol(
if group.is_virtual { "person" } else { "group" },
16.,
if selected {
theme::accent_text()
} else {
theme::text_muted()
},
))
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.child(group.name.clone()),
)
.when(group.task_count > 0, |row| {
row.child(
div()
.flex_none()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(group.task_count.to_string()),
)
})
}))
.into_any_element()
}
fn header(&self, cx: &mut Context<Self>) -> Div {
let group = self.current_group();
let title = group.map_or_else(|| tr("kvt.board.title"), |group| group.name.clone());
let can_create = group.is_some_and(PonosGroup::accepts_new_tasks)
&& matches!(self.tasks, Tasks::Loaded(_));
let url = match self.group.as_deref() {
Some(group) => group_url(&base_url(), group),
None => format!("{}/ponos/", base_url()),
};
h_flex()
.h(px(HEADER_HEIGHT))
.flex_none()
.px(px(PAGE_PADDING))
.gap(px(8.))
.items_center()
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(16.))
.font_weight(FontWeight::BOLD)
.text_color(theme::text())
.child(title),
)
.when(can_create, |row| {
row.child(
primary_button("kvt-board-new", tr("kvt.board.new_task")).on_click(
cx.listener(|this, _, window, cx| {
this.open_editor(None, STATUSES[0], window, cx)
}),
),
)
})
.child(
secondary_button("kvt-board-refresh", "refresh", tr("kvt.card.refresh"))
.on_click(cx.listener(|this, _, _, cx| this.reload(cx))),
)
.child(
secondary_button("kvt-board-open", "open_in_new", tr("kvt.tasks.open_ponos"))
.on_click(move |_, _, cx| open_external(&url, cx)),
)
}
fn columns(&self, cx: &mut Context<Self>) -> AnyElement {
let tasks = match &self.tasks {
Tasks::Loading => {
return muted(tr("kvt.card.loading"))
.px(px(PAGE_PADDING))
.into_any_element();
}
Tasks::Failed(error) => {
return muted(ponos_error(error))
.px(px(PAGE_PADDING))
.into_any_element();
}
Tasks::Loaded(tasks) => tasks,
};
let group = self.current_group();
let editable = group.is_some_and(PonosGroup::editable);
let can_create = group.is_some_and(PonosGroup::accepts_new_tasks);
let me = self.user_email();
h_flex()
.id("kvt-board-columns")
.flex_1()
.min_h_0()
.w_full()
.px(px(PAGE_PADDING))
.pb(px(PAGE_PADDING))
.gap(px(COLUMN_GAP))
.items_start()
.overflow_x_scrollbar()
.children(
STATUSES
.iter()
.map(|&status| self.column(tasks, status, editable, can_create, &me, cx)),
)
.into_any_element()
}
fn column(
&self,
tasks: &[PonosTask],
status: &'static str,
editable: bool,
can_create: bool,
me: &str,
cx: &mut Context<Self>,
) -> AnyElement {
let cards: Vec<&PonosTask> = column(tasks, status).collect();
let today = chrono::Local::now().format("%Y-%m-%d").to_string();
let dot = match status {
"in_progress" => theme::accent(),
STATUS_DONE => theme::green(),
_ => theme::text_faint(),
};
v_flex()
.id(ElementId::Name(format!("kvt-board-column-{status}").into()))
.debug_selector(move || format!("kvt-board/column/{status}"))
.flex_1()
.min_w(px(COLUMN_MIN_WIDTH))
.h_full()
.p(px(10.))
.gap(px(CARD_GAP))
.rounded(px(RADIUS))
.bg(theme::surface())
.drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background()))
.on_drop(cx.listener(move |this, dragged: &DraggedTask, _, cx| {
this.drop_task(dragged, status, None, cx)
}))
.child(
h_flex()
.w_full()
.h(px(28.))
.flex_none()
.gap(px(8.))
.items_center()
.child(div().size(px(8.)).flex_none().rounded_full().bg(dot))
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(13.))
.font_weight(FontWeight::SEMIBOLD)
.text_color(theme::text())
.child(self.status_label(status)),
)
.child(
div()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(cards.len().to_string()),
)
.when(can_create, |row| {
row.child(
div()
.id(ElementId::Name(format!("kvt-board-add-{status}").into()))
.size(px(24.))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.hover(|button| button.bg(theme::row_hover()))
.on_click(cx.listener(move |this, _, window, cx| {
this.open_editor(None, status, window, cx)
}))
.child(symbol("add", 16., theme::text_muted())),
)
}),
)
.child(
v_flex()
.id(ElementId::Name(format!("kvt-board-cards-{status}").into()))
.w_full()
.flex_1()
.min_h(px(80.))
.gap(px(CARD_GAP))
.overflow_y_scrollbar()
.when(cards.is_empty(), |list| {
list.child(
div()
.w_full()
.py(px(16.))
.text_center()
.text_size(px(12.))
.text_color(theme::text_faint())
.child(tr("kvt.board.empty_column")),
)
})
.children(cards.iter().enumerate().map(|(index, task)| {
self.card(task, status, index, editable, me, &today, cx)
})),
)
.into_any_element()
}
#[allow(clippy::too_many_arguments)]
fn card(
&self,
task: &PonosTask,
status: &'static str,
index: usize,
editable: bool,
me: &str,
today: &str,
cx: &mut Context<Self>,
) -> AnyElement {
let movable = editable && task.can_edit;
let overdue =
status != STATUS_DONE && !task.due_date.is_empty() && task.due_date.as_str() < today;
let due = iso_date_nl(&task.due_date);
let assignee = if task.assignee_email.is_empty() {
None
} else if task.assignee_email.eq_ignore_ascii_case(me) {
Some(tr("kvt.board.assignee_me"))
} else {
Some(name_from_email(&task.assignee_email))
};
let in_my_tasks = self.group.as_deref() == Some(MY_TASKS_GROUP);
let open = task.clone();
let dragged = DraggedTask {
id: task.id.clone(),
title: task.title.clone(),
from_status: task.status.clone(),
};
v_flex()
.id(ElementId::Name(
format!("kvt-board-card-{}", task.id).into(),
))
.w_full()
.flex_none()
.px(px(12.))
.py(px(10.))
.gap(px(6.))
.rounded(px(8.))
.bg(theme::surface_raised())
.cursor_pointer()
.hover(|card| card.bg(theme::popup_hover()))
.on_click(cx.listener(move |this, _, window, cx| {
this.open_editor(Some(open.clone()), &open.status, window, cx)
}))
.when(movable, |card| {
card.on_drag(dragged, |dragged, _, _, cx| {
let title = dragged.title.clone();
cx.new(|_| TaskGhost { title })
})
.drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background()))
.on_drop(cx.listener(
move |this, dragged: &DraggedTask, _, cx| {
cx.stop_propagation();
this.drop_task(dragged, status, Some(index), cx)
},
))
})
.when(in_my_tasks && !task.home_group_name.is_empty(), |card| {
card.child(
div()
.truncate()
.text_size(px(11.))
.text_color(theme::text_muted())
.child(task.home_group_name.clone()),
)
})
.child(
div()
.text_size(px(13.))
.line_height(px(18.))
.text_color(if status == STATUS_DONE {
theme::text_muted()
} else {
theme::text()
})
.when(status == STATUS_DONE, |text| text.line_through())
.child(task.title.clone()),
)
.child(
h_flex()
.w_full()
.flex_wrap()
.gap(px(8.))
.items_center()
.text_size(px(11.))
.text_color(theme::text_muted())
.when(!task.category_label.is_empty(), |row| {
row.child(
div()
.px(px(6.))
.py(px(1.))
.rounded(px(4.))
.bg(theme::selection())
.text_color(theme::text_strong())
.child(task.category_label.clone()),
)
})
.children(due.map(|due| {
h_flex()
.gap(px(3.))
.items_center()
.text_color(if overdue {
theme::red_soft()
} else {
theme::text_muted()
})
.child(symbol(
"event",
12.,
if overdue {
theme::red_soft()
} else {
theme::text_muted()
},
))
.child(due)
}))
.when(task.checklist_total > 0, |row| {
row.child(
h_flex()
.gap(px(3.))
.items_center()
.child(symbol("check", 12., theme::text_muted()))
.child(format!("{}/{}", task.checklist_done, task.checklist_total)),
)
})
.children(assignee.map(|assignee| {
h_flex()
.gap(px(3.))
.items_center()
.child(symbol("person", 12., theme::text_muted()))
.child(assignee)
})),
)
.into_any_element()
}
fn editor_layer(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
let editor = self.editor.as_ref()?;
let navigation = self.navigation()?;
let me = navigation.user_email.clone();
let existing = editor.task.clone();
let editable = existing.as_ref().is_none_or(|task| task.can_edit);
let home = existing
.as_ref()
.map(|task| task.group().to_owned())
.or_else(|| self.group.clone())
.unwrap_or_default();
let target = editor.target_group.clone().unwrap_or_else(|| home.clone());
let title = tr(if existing.is_some() {
"kvt.board.edit_task"
} else {
"kvt.ponos.dialog_title"
});
let detail = existing
.as_ref()
.filter(|task| !task.home_group_name.is_empty())
.map(|task| task.home_group_name.clone())
.unwrap_or_default();
let url = existing.as_ref().map(|task| task.url(&base_url()));
let move_groups: Vec<PonosGroup> = navigation
.groups
.iter()
.filter(|group| !group.is_virtual && group.has_task_access)
.cloned()
.collect();
let other_assignee = (!editor.assignee.is_empty()
&& !editor.assignee.eq_ignore_ascii_case(&me))
.then(|| name_from_email(&editor.assignee));
let assignee_is_me = !me.is_empty() && editor.assignee.eq_ignore_ascii_case(&me);
let status_chips =
h_flex()
.w_full()
.flex_wrap()
.gap(px(6.))
.children(STATUSES.iter().enumerate().map(|(index, &status)| {
chip(
format!("kvt-board-status-{index}").into(),
self.status_label(status),
editor.status == status,
)
.on_click(cx.listener(move |this, _, _, cx| {
if let Some(editor) = this.editor.as_mut() {
editor.status = status.to_owned();
cx.notify();
}
}))
}));
let assignee_chips = h_flex()
.w_full()
.flex_wrap()
.gap(px(6.))
.child(
chip(
"kvt-board-assignee-none".into(),
tr("kvt.board.assignee_none"),
editor.assignee.is_empty(),
)
.on_click(cx.listener(|this, _, _, cx| {
if let Some(editor) = this.editor.as_mut() {
editor.assignee.clear();
cx.notify();
}
})),
)
.when(!me.is_empty(), |row| {
let me = me.clone();
row.child(
chip(
"kvt-board-assignee-me".into(),
tr("kvt.board.assignee_me"),
assignee_is_me,
)
.on_click(cx.listener(move |this, _, _, cx| {
if let Some(editor) = this.editor.as_mut() {
editor.assignee = me.clone();
cx.notify();
}
})),
)
})
.children(
other_assignee.map(|name| chip("kvt-board-assignee-other".into(), name, true)),
);
let group_chips =
(existing.is_some() && move_groups.len() > 1).then(|| {
h_flex().w_full().flex_wrap().gap(px(6.)).children(
move_groups.iter().enumerate().map(|(index, group)| {
let id = group.id.clone();
let home = home.clone();
chip(
format!("kvt-board-move-{index}").into(),
group.name.clone(),
group.id == target,
)
.on_click(cx.listener(move |this, _, _, cx| {
if let Some(editor) = this.editor.as_mut() {
editor.target_group = (id != home).then(|| id.clone());
cx.notify();
}
}))
}),
)
});
let can_complete = existing
.as_ref()
.is_some_and(|task| task.status != STATUS_DONE && task.can_edit);
let panel = v_flex()
.debug_selector(|| "kvt-board-editor".into())
.w(px(EDITOR_WIDTH))
.max_w(relative(1.))
.max_h(relative(0.92))
.m(px(32.))
.p(px(16.))
.gap(px(10.))
.rounded(px(RADIUS))
.dialog_surface()
.text_color(theme::text())
.occlude()
.child(
h_flex()
.w_full()
.items_center()
.gap(px(12.))
.child(
v_flex()
.flex_1()
.min_w_0()
.child(
div()
.text_size(px(15.))
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.when(!detail.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(detail),
)
}),
)
.child(
div()
.id("kvt-board-editor-close")
.size(px(28.))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.hover(|button| button.bg(theme::popup_hover()))
.on_click(cx.listener(|this, _, _, cx| {
this.editor = None;
cx.notify();
}))
.child(symbol("close", 16., theme::text_muted())),
),
)
.child(label(tr("kvt.ponos.title")))
.child(
field().child(
div()
.flex_1()
.child(Input::new(&editor.title).appearance(false).bordered(false)),
),
)
.child(label(tr("kvt.ponos.description")))
.child(Textarea::new(&editor.description))
.child(label(tr("kvt.board.status")))
.child(status_chips)
.child(label(tr("kvt.board.due")))
.child(
field().child(
div()
.flex_1()
.child(Input::new(&editor.due).appearance(false).bordered(false)),
),
)
.child(label(tr("kvt.board.assignee")))
.child(assignee_chips)
.when_some(group_chips, |panel, chips| {
panel.child(label(tr("kvt.ponos.group"))).child(chips)
})
.children(editor.error.clone().map(|error| {
div()
.text_size(px(13.))
.text_color(theme::red_soft())
.child(error)
}))
.child(
h_flex()
.w_full()
.gap(px(8.))
.items_center()
.children(url.map(|url| {
secondary_button(
"kvt-board-editor-open",
"open_in_new",
tr("kvt.tasks.open_ponos"),
)
.on_click(move |_, _, cx| open_external(&url, cx))
}))
.child(div().flex_1())
.when(can_complete, |row| {
row.child(
secondary_button(
"kvt-board-complete",
"check_circle",
tr("kvt.board.complete"),
)
.on_click(cx.listener(|this, _, _, cx| this.complete_from_editor(cx))),
)
})
.child(
secondary_button("kvt-board-cancel", "close", tr("common.cancel"))
.on_click(cx.listener(|this, _, _, cx| {
this.editor = None;
cx.notify();
})),
)
.when(editable, |row| {
row.child(
primary_button(
"kvt-board-save",
tr(if editor.saving {
"kvt.ponos.saving"
} else {
"kvt.board.save"
}),
)
.on_click(cx.listener(|this, _, _, cx| this.save_editor(cx))),
)
}),
);
Some(
div()
.id("kvt-board-editor-layer")
.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
if event.keystroke.key == "escape" {
cx.stop_propagation();
this.editor = None;
cx.notify();
}
}))
.absolute()
.top_0()
.left_0()
.size_full()
.flex()
.items_center()
.justify_center()
.child(
div()
.id("kvt-board-editor-backdrop")
.absolute()
.top_0()
.left_0()
.size_full()
.bg(black().opacity(BACKDROP_OPACITY))
.occlude()
.on_click(cx.listener(|this, _, _, cx| {
this.editor = None;
cx.notify();
})),
)
.child(panel)
.into_any_element(),
)
}
}
impl Render for PonosBoard {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let linked = matches!(link(cx), Link::Linked(_));
if !linked && !is_demo(cx) {
// Ontkoppeld: na opnieuw koppelen vers laden, niets van de oude token tonen.
self.nav = Nav::NotLinked;
self.editor = None;
} else if matches!(self.nav, Nav::NotLinked) {
self.reload(cx);
}
let body = match (&self.nav, linked) {
(_, false) => v_flex()
.p(px(PAGE_PADDING))
.max_w(px(EDITOR_WIDTH))
.child(not_linked())
.into_any_element(),
(Nav::NotLinked | Nav::Loading, _) => muted(tr("kvt.card.loading"))
.px(px(PAGE_PADDING))
.into_any_element(),
(Nav::Failed(error), _) => muted(ponos_error(error))
.px(px(PAGE_PADDING))
.into_any_element(),
(Nav::Loaded(_), _) => h_flex()
.flex_1()
.min_h_0()
.w_full()
.child(self.groups_list(cx))
.child(
v_flex()
.flex_1()
.min_w_0()
.h_full()
.child(self.header(cx))
.child(self.columns(cx)),
)
.into_any_element(),
};
let page_title = (!matches!(self.nav, Nav::Loaded(_)) || !linked).then(|| {
h_flex()
.h(px(HEADER_HEIGHT))
.flex_none()
.px(px(PAGE_PADDING))
.items_center()
.child(
div()
.text_size(px(16.))
.font_weight(FontWeight::BOLD)
.text_color(theme::text())
.child(tr("kvt.board.title")),
)
});
v_flex()
.debug_selector(|| KVT_BOARD_TAG.into())
.relative()
.size_full()
.rounded(px(RADIUS))
.bg(theme::surface())
.overflow_hidden()
.children(page_title)
.child(body)
.children(self.editor_layer(cx))
}
}
#[cfg(test)]
mod tests {
use super::pick_group;
use kvt_sleutels::ponos::{PonosGroup, PonosNavigation};
fn group(id: &str) -> PonosGroup {
PonosGroup {
id: id.to_owned(),
name: id.to_owned(),
is_virtual: false,
can_create_tasks: true,
has_task_access: true,
task_count: 0,
}
}
#[test]
fn remembered_group_wins_when_it_still_exists() {
let navigation = PonosNavigation {
groups: vec![group("__my_tasks__"), group("g1")],
..Default::default()
};
assert_eq!(pick_group(Some("g1"), &navigation).as_deref(), Some("g1"));
assert_eq!(
pick_group(Some("weg"), &navigation).as_deref(),
Some("__my_tasks__")
);
assert_eq!(pick_group(None, &PonosNavigation::default()), None);
}
}
@@ -0,0 +1,1395 @@//! Ponos-bord in het hoofdpaneel: de tegel «Ponos» in de navigatierail, direct//! onder Agents (Tim). Links alle groepen die je in Ponos ziet (eerst//! «Mijn Taken», je persoonlijke groep), rechts het bord met de kolommen van//! Ponos. Taken maken, bewerken, afronden en slepen tussen en binnen kolommen.//!//! Upstream-haken: `views/rail.rs` (tegel), `views/sidebar.rs` (`SidebarTab::Ponos`),//! `views/shell.rs` (hoofdpaneel). Zie KVT-FORK.md.use std::collections::HashMap;use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};use gpui_kit::component::scroll::ScrollableElement as _;use gpui_kit::component::{h_flex, v_flex};use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::*;use kvt_sleutels::format::{iso_date_nl, parse_date_input};use kvt_sleutels::ponos::{ MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask, STATUS_DONE, STATUSES, TaskInput, apply_move, column, drop_position, group_url, name_from_email,};use kvt_sleutels::{CardsClient, ClientError};use super::modal::{primary_button, secondary_button};use super::tasks::{chip, field, label, muted, not_linked, ponos_error};use super::{Link, base_url, forget_token, is_demo, link, notice, open_external, token_and_client};use crate::app_state::AppHandle;use crate::i18n::tr;use crate::runtime;use crate::theme::{self, ElevatedSurface as _};use crate::views::widgets::symbol;pub const KVT_BOARD_TAG: &str = "kvt-ponos-board";/// Laatst gekozen groep op het bord (alleen een id, in de lokale opslag).const BOARD_GROUP_META_KEY: &str = "kvt.ponos.board_group";const TITLE_MAX: usize = 200;const HEADER_HEIGHT: f32 = 60.;const PAGE_PADDING: f32 = 20.;const GROUPS_WIDTH: f32 = 240.;const GROUP_ROW_HEIGHT: f32 = 36.;const COLUMN_MIN_WIDTH: f32 = 220.;const COLUMN_GAP: f32 = 12.;const CARD_GAP: f32 = 8.;const RADIUS: f32 = 10.;const EDITOR_WIDTH: f32 = 560.;const BACKDROP_OPACITY: f32 = 0.55;#[derive(Clone)]enum Nav { NotLinked, Loading, Loaded(PonosNavigation), Failed(ClientError),}#[derive(Clone)]enum Tasks { Loading, Loaded(Vec<PonosTask>), Failed(ClientError),}#[derive(Clone)]struct DraggedTask { id: String, title: String, from_status: String,}struct TaskGhost { title: String,}impl Render for TaskGhost { fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { div() .w(px(COLUMN_MIN_WIDTH)) .px(px(12.)) .py(px(10.)) .rounded(px(8.)) .flyout_surface() .text_size(px(13.)) .text_color(theme::text()) .truncate() .child(self.title.clone()) }}struct Editor { /// `None`: nieuwe taak. task: Option<PonosTask>, status: String, assignee: String, target_group: Option<String>, title: Entity<InputState>, description: Entity<TextareaState>, due: Entity<InputState>, saving: bool, error: Option<String>,}pub struct PonosBoard { nav: Nav, group: Option<String>, tasks: Tasks, generation: u64, editor: Option<Editor>, /// Alleen `--demo`: verzonnen taken per groep. demo: HashMap<String, Vec<PonosTask>>,}/// Het bord als element van het hoofdpaneel (eenmalig aangemaakt).pub fn board_view(cx: &mut App) -> AnyElement { let existing = super::read(cx, |kvt| kvt.board.clone()).flatten(); let board = match existing { Some(board) => board, None => { let board = cx.new(PonosBoard::new); if cx.has_global::<super::Kvt>() { cx.global_mut::<super::Kvt>().board = Some(board.clone()); } board } }; div() .flex_1() .min_w_0() .h_full() .child(board) .into_any_element()}/// De tegel is geopend: vers ophalen (bij de eerste keer laadt `new`).pub fn board_opened(cx: &mut App) { if let Some(board) = super::read(cx, |kvt| kvt.board.clone()).flatten() { board.update(cx, |board, cx| board.reload(cx)); }}/// Na «Taak maken in Ponos» vanuit een bericht.pub(super) fn refresh_board_if_open(cx: &mut App) { board_opened(cx);}fn remembered_group(cx: &App) -> Option<String> { let handle = cx.try_global::<AppHandle>()?; handle .0 .read(cx) .store .meta(BOARD_GROUP_META_KEY) .ok() .flatten()}fn remember_group(group: &str, cx: &App) { if let Some(handle) = cx.try_global::<AppHandle>() { let _ = handle .0 .read(cx) .store .set_meta(BOARD_GROUP_META_KEY, group); }}/// Gekozen groep als die nog bestaat, anders de eerste (Mijn Taken).fn pick_group(wanted: Option<&str>, navigation: &PonosNavigation) -> Option<String> { wanted .filter(|wanted| navigation.groups.iter().any(|group| group.id == *wanted)) .map(str::to_owned) .or_else(|| navigation.groups.first().map(|group| group.id.clone()))}fn status_fallback(status: &str) -> String { tr(match status { "in_progress" => "kvt.board_status.in_progress", STATUS_DONE => "kvt.board_status.done", _ => "kvt.board_status.todo", })}impl PonosBoard { fn new(cx: &mut Context<Self>) -> Self { let demo = if is_demo(cx) { super::demo::board_tasks() } else { HashMap::new() }; let mut board = PonosBoard { nav: Nav::Loading, group: remembered_group(cx), tasks: Tasks::Loading, generation: 0, editor: None, demo, }; board.reload(cx); board } fn navigation(&self) -> Option<&PonosNavigation> { match &self.nav { Nav::Loaded(navigation) => Some(navigation), _ => None, } } fn current_group(&self) -> Option<&PonosGroup> { let group = self.group.as_deref()?; self.navigation()? .groups .iter() .find(|candidate| candidate.id == group) } fn user_email(&self) -> String { self.navigation() .map(|navigation| navigation.user_email.clone()) .unwrap_or_default() } fn status_label(&self, status: &str) -> String { match self.navigation() { Some(navigation) => navigation.status_label(status, || status_fallback(status)), None => status_fallback(status), } } // --- laden ------------------------------------------------------------ fn reload(&mut self, cx: &mut Context<Self>) { self.generation += 1; if is_demo(cx) { let navigation = super::demo::board_navigation(&self.demo); self.group = pick_group(self.group.as_deref(), &navigation); self.tasks = Tasks::Loaded(self.demo_tasks()); self.nav = Nav::Loaded(navigation); cx.notify(); return; } let Some((token, client)) = token_and_client(cx) else { self.nav = Nav::NotLinked; cx.notify(); return; }; if !matches!(self.nav, Nav::Loaded(_)) { self.nav = Nav::Loading; } let generation = self.generation; let wanted = self.group.clone(); let loading = runtime::spawn(async move { let navigation = client.ponos_navigation(&token).await?; let group = pick_group(wanted.as_deref(), &navigation); let tasks = match &group { Some(group) => client.ponos_tasks(&token, group).await, None => Ok(Vec::new()), }; Ok::<_, ClientError>((navigation, group, tasks)) }); cx.spawn(async move |this, cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { let unauthorized = matches!(&result, Err(ClientError::Unauthorized)) || matches!(&result, Ok((_, _, Err(ClientError::Unauthorized)))); if unauthorized { forget_token(cx); } this.update(cx, |this, cx| { if this.generation != generation { return; } match result { Ok((navigation, group, tasks)) => { this.group = group; this.tasks = match tasks { Ok(tasks) => Tasks::Loaded(tasks), Err(error) => Tasks::Failed(error), }; this.nav = Nav::Loaded(navigation); } Err(ClientError::Unauthorized) => this.nav = Nav::NotLinked, Err(error) => this.nav = Nav::Failed(error), } cx.notify(); }) .ok(); }); }) .detach(); } fn select_group(&mut self, group: String, cx: &mut Context<Self>) { if self.group.as_deref() == Some(group.as_str()) { return; } remember_group(&group, cx); self.group = Some(group); self.tasks = Tasks::Loading; self.editor = None; self.reload(cx); } // --- demo ------------------------------------------------------------- fn demo_tasks(&self) -> Vec<PonosTask> { let Some(group) = self.group.as_deref() else { return Vec::new(); }; if group == MY_TASKS_GROUP { let mut mine: Vec<PonosTask> = self .demo .values() .flatten() .filter(|task| task.assignee_email == super::demo::BOARD_USER) .cloned() .collect(); mine.sort_by(|a, b| a.id.cmp(&b.id)); return mine; } self.demo.get(group).cloned().unwrap_or_default() } fn demo_task_mut(&mut self, id: &str) -> Option<&mut PonosTask> { self.demo.values_mut().flatten().find(|task| task.id == id) } // --- acties ----------------------------------------------------------- /// Een schrijfactie bij Ponos; daarna altijd opnieuw laden. fn submit<Fut>( &mut self, cx: &mut Context<Self>, done: Option<String>, job: impl FnOnce(String, CardsClient) -> Fut, ) where Fut: std::future::Future<Output = Result<(), ClientError>> + Send + 'static, { let Some((token, client)) = token_and_client(cx) else { self.reload(cx); return; }; let running = runtime::spawn(job(token, client)); cx.spawn(async move |this, cx| { let result = running.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { match &result { Ok(()) => { if let Some(done) = done { notice(done, cx); } } Err(error) => { if *error == ClientError::Unauthorized { forget_token(cx); } notice(ponos_error(error), cx); } } this.update(cx, |this, cx| { if result.is_ok() { this.editor = None; } else if let Some(editor) = this.editor.as_mut() { editor.saving = false; } this.reload(cx); }) .ok(); }); }) .detach(); } fn drop_task( &mut self, dragged: &DraggedTask, status: &'static str, before: Option<usize>, cx: &mut Context<Self>, ) { let Some(group) = self.group.clone() else { return; }; let Tasks::Loaded(tasks) = &mut self.tasks else { return; }; let position = drop_position(tasks, &dragged.id, status, before); let unchanged = dragged.from_status == status && column(tasks, status).position(|task| task.id == dragged.id) == Some(position); if unchanged || !apply_move(tasks, &dragged.id, status, position) { return; } cx.notify(); let id = dragged.id.clone(); if is_demo(cx) { if let Some(task) = self.demo_task_mut(&id) { task.status = status.to_owned(); } if group != MY_TASKS_GROUP && let Some(list) = self.demo.get_mut(&group) { apply_move(list, &id, status, position); } return; } let virtual_group = group == MY_TASKS_GROUP; let status_changed = dragged.from_status != status; if virtual_group && !status_changed { // «Mijn Taken» heeft geen eigen volgorde in Ponos. return; } self.submit(cx, None, move |token, client| async move { if virtual_group { client.ponos_set_status(&token, &group, &id, status).await?; } else { client .ponos_reorder_task(&token, &group, &id, status, position) .await?; } Ok(()) }); } fn open_editor( &mut self, task: Option<PonosTask>, status: &str, window: &mut Window, cx: &mut Context<Self>, ) { let (title_text, description_text, due_text) = match &task { Some(task) => ( task.title.clone(), task.description.clone(), iso_date_nl(&task.due_date).unwrap_or_default(), ), None => Default::default(), }; let title = cx.new(|cx| { InputState::new(window, cx) .placeholder(tr("kvt.ponos.title")) .default_value(title_text) }); let description = cx.new(|cx| { TextareaState::new(window, cx) .auto_grow(4, 10) .placeholder(tr("kvt.ponos.description")) .default_value(description_text) }); let due = cx.new(|cx| { InputState::new(window, cx) .placeholder(tr("kvt.board.due_placeholder")) .default_value(due_text) }); title.update(cx, |input, cx| input.focus(window, cx)); let assignee = match &task { Some(task) => task.assignee_email.clone(), // Nieuw in «Mijn Taken» kan niet; elders standaard niemand. None => String::new(), }; self.editor = Some(Editor { status: task .as_ref() .map_or_else(|| status.to_owned(), |task| task.status.clone()), assignee, target_group: None, task, title, description, due, saving: false, error: None, }); cx.notify(); } fn save_editor(&mut self, cx: &mut Context<Self>) { let Some(group) = self.group.clone() else { return; }; let Some(editor) = self.editor.as_mut() else { return; }; if editor.saving { return; } let title: String = editor .title .read(cx) .value() .trim() .chars() .take(TITLE_MAX) .collect(); let description = editor.description.read(cx).value().trim().to_owned(); if title.is_empty() || description.is_empty() { editor.error = Some(tr("kvt.ponos.fill_in")); cx.notify(); return; } let Some(due_date) = parse_date_input(&editor.due.read(cx).value()) else { editor.error = Some(tr("kvt.board.bad_date")); cx.notify(); return; }; let input = TaskInput { title, description, due_date, assignee_email: editor.assignee.clone(), target_group: editor.target_group.clone(), }; let status = editor.status.clone(); let existing = editor.task.clone(); editor.saving = true; editor.error = None; cx.notify(); if is_demo(cx) { self.save_demo(&group, existing, input, status); self.editor = None; notice(tr("kvt.board.saved"), cx); self.reload(cx); return; } let done = tr(if existing.is_some() { "kvt.board.saved" } else { "kvt.ponos.created" }); self.submit(cx, Some(done), move |token, client| async move { match existing { Some(task) => { let saved = client .ponos_update_task(&token, &group, &task.id, &input) .await?; if saved.status != status { let home = input.target_group.as_deref().unwrap_or(&group); client .ponos_set_status(&token, home, &saved.id, &status) .await?; } } None => { let created = client.ponos_create(&token, &group, &input).await?; if created.status != status { client .ponos_set_status(&token, &group, &created.id, &status) .await?; } } } Ok(()) }); } fn save_demo( &mut self, group: &str, existing: Option<PonosTask>, input: TaskInput, status: String, ) { match existing { Some(task) => { let home = task.group().to_owned(); let Some(list) = self.demo.get_mut(&home) else { return; }; let Some(index) = list.iter().position(|other| other.id == task.id) else { return; }; let mut updated = list.remove(index); updated.title = input.title; updated.description = input.description; updated.due_date = input.due_date; updated.assignee_email = input.assignee_email; let target = input.target_group.unwrap_or(home.clone()); if target == home && updated.status == status { list.insert(index, updated); return; } updated.status = status; updated.group_id = target.clone(); updated.home_group_id = target.clone(); self.demo.entry(target).or_default().push(updated); } None => { let id = format!( "demo-board-{}", self.demo.values().map(Vec::len).sum::<usize>() + 1 ); let task = PonosTask { id, group_id: group.to_owned(), home_group_id: group.to_owned(), title: input.title, status, due_date: input.due_date, description: input.description, assignee_email: input.assignee_email, ..super::demo::empty_task() }; self.demo.entry(group.to_owned()).or_default().push(task); } } } fn complete_from_editor(&mut self, cx: &mut Context<Self>) { let Some(group) = self.group.clone() else { return; }; let Some(task) = self.editor.as_ref().and_then(|editor| editor.task.clone()) else { return; }; if is_demo(cx) { if let Some(demo) = self.demo_task_mut(&task.id) { demo.status = STATUS_DONE.to_owned(); } self.editor = None; notice(tr("kvt.tasks.completed"), cx); self.reload(cx); return; } if let Some(editor) = self.editor.as_mut() { editor.saving = true; } self.submit( cx, Some(tr("kvt.tasks.completed")), move |token, client| async move { client.ponos_complete_task(&token, &group, &task.id).await }, ); } // --- weergave --------------------------------------------------------- fn groups_list(&self, cx: &mut Context<Self>) -> AnyElement { let Some(navigation) = self.navigation() else { return div().into_any_element(); }; v_flex() .id("kvt-board-groups") .w(px(GROUPS_WIDTH)) .h_full() .flex_none() .p(px(8.)) .gap(px(2.)) .border_r_1() .border_color(theme::border()) .overflow_y_scrollbar() .children(navigation.groups.iter().enumerate().map(|(index, group)| { let selected = self.group.as_deref() == Some(group.id.as_str()); let id = group.id.clone(); h_flex() .id(ElementId::Name(format!("kvt-board-group-{index}").into())) .w_full() .h(px(GROUP_ROW_HEIGHT)) .flex_none() .px(px(10.)) .gap(px(8.)) .items_center() .rounded(px(6.)) .cursor_pointer() .text_size(px(13.)) .map(|row| { if selected { row.bg(theme::selection()) .text_color(theme::text_strong()) .font_weight(FontWeight::SEMIBOLD) } else { row.text_color(theme::text()) .hover(|row| row.bg(theme::row_hover())) } }) .on_click(cx.listener(move |this, _, _, cx| this.select_group(id.clone(), cx))) .child(symbol( if group.is_virtual { "person" } else { "group" }, 16., if selected { theme::accent_text() } else { theme::text_muted() }, )) .child( div() .flex_1() .min_w_0() .truncate() .child(group.name.clone()), ) .when(group.task_count > 0, |row| { row.child( div() .flex_none() .text_size(px(12.)) .text_color(theme::text_muted()) .child(group.task_count.to_string()), ) }) })) .into_any_element() } fn header(&self, cx: &mut Context<Self>) -> Div { let group = self.current_group(); let title = group.map_or_else(|| tr("kvt.board.title"), |group| group.name.clone()); let can_create = group.is_some_and(PonosGroup::accepts_new_tasks) && matches!(self.tasks, Tasks::Loaded(_)); let url = match self.group.as_deref() { Some(group) => group_url(&base_url(), group), None => format!("{}/ponos/", base_url()), }; h_flex() .h(px(HEADER_HEIGHT)) .flex_none() .px(px(PAGE_PADDING)) .gap(px(8.)) .items_center() .child( div() .flex_1() .min_w_0() .truncate() .text_size(px(16.)) .font_weight(FontWeight::BOLD) .text_color(theme::text()) .child(title), ) .when(can_create, |row| { row.child( primary_button("kvt-board-new", tr("kvt.board.new_task")).on_click( cx.listener(|this, _, window, cx| { this.open_editor(None, STATUSES[0], window, cx) }), ), ) }) .child( secondary_button("kvt-board-refresh", "refresh", tr("kvt.card.refresh")) .on_click(cx.listener(|this, _, _, cx| this.reload(cx))), ) .child( secondary_button("kvt-board-open", "open_in_new", tr("kvt.tasks.open_ponos")) .on_click(move |_, _, cx| open_external(&url, cx)), ) } fn columns(&self, cx: &mut Context<Self>) -> AnyElement { let tasks = match &self.tasks { Tasks::Loading => { return muted(tr("kvt.card.loading")) .px(px(PAGE_PADDING)) .into_any_element(); } Tasks::Failed(error) => { return muted(ponos_error(error)) .px(px(PAGE_PADDING)) .into_any_element(); } Tasks::Loaded(tasks) => tasks, }; let group = self.current_group(); let editable = group.is_some_and(PonosGroup::editable); let can_create = group.is_some_and(PonosGroup::accepts_new_tasks); let me = self.user_email(); h_flex() .id("kvt-board-columns") .flex_1() .min_h_0() .w_full() .px(px(PAGE_PADDING)) .pb(px(PAGE_PADDING)) .gap(px(COLUMN_GAP)) .items_start() .overflow_x_scrollbar() .children( STATUSES .iter() .map(|&status| self.column(tasks, status, editable, can_create, &me, cx)), ) .into_any_element() } fn column( &self, tasks: &[PonosTask], status: &'static str, editable: bool, can_create: bool, me: &str, cx: &mut Context<Self>, ) -> AnyElement { let cards: Vec<&PonosTask> = column(tasks, status).collect(); let today = chrono::Local::now().format("%Y-%m-%d").to_string(); let dot = match status { "in_progress" => theme::accent(), STATUS_DONE => theme::green(), _ => theme::text_faint(), }; v_flex() .id(ElementId::Name(format!("kvt-board-column-{status}").into())) .debug_selector(move || format!("kvt-board/column/{status}")) .flex_1() .min_w(px(COLUMN_MIN_WIDTH)) .h_full() .p(px(10.)) .gap(px(CARD_GAP)) .rounded(px(RADIUS)) .bg(theme::surface()) .drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background())) .on_drop(cx.listener(move |this, dragged: &DraggedTask, _, cx| { this.drop_task(dragged, status, None, cx) })) .child( h_flex() .w_full() .h(px(28.)) .flex_none() .gap(px(8.)) .items_center() .child(div().size(px(8.)).flex_none().rounded_full().bg(dot)) .child( div() .flex_1() .min_w_0() .truncate() .text_size(px(13.)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme::text()) .child(self.status_label(status)), ) .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(cards.len().to_string()), ) .when(can_create, |row| { row.child( div() .id(ElementId::Name(format!("kvt-board-add-{status}").into())) .size(px(24.)) .flex_none() .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::row_hover())) .on_click(cx.listener(move |this, _, window, cx| { this.open_editor(None, status, window, cx) })) .child(symbol("add", 16., theme::text_muted())), ) }), ) .child( v_flex() .id(ElementId::Name(format!("kvt-board-cards-{status}").into())) .w_full() .flex_1() .min_h(px(80.)) .gap(px(CARD_GAP)) .overflow_y_scrollbar() .when(cards.is_empty(), |list| { list.child( div() .w_full() .py(px(16.)) .text_center() .text_size(px(12.)) .text_color(theme::text_faint()) .child(tr("kvt.board.empty_column")), ) }) .children(cards.iter().enumerate().map(|(index, task)| { self.card(task, status, index, editable, me, &today, cx) })), ) .into_any_element() } #[allow(clippy::too_many_arguments)] fn card( &self, task: &PonosTask, status: &'static str, index: usize, editable: bool, me: &str, today: &str, cx: &mut Context<Self>, ) -> AnyElement { let movable = editable && task.can_edit; let overdue = status != STATUS_DONE && !task.due_date.is_empty() && task.due_date.as_str() < today; let due = iso_date_nl(&task.due_date); let assignee = if task.assignee_email.is_empty() { None } else if task.assignee_email.eq_ignore_ascii_case(me) { Some(tr("kvt.board.assignee_me")) } else { Some(name_from_email(&task.assignee_email)) }; let in_my_tasks = self.group.as_deref() == Some(MY_TASKS_GROUP); let open = task.clone(); let dragged = DraggedTask { id: task.id.clone(), title: task.title.clone(), from_status: task.status.clone(), }; v_flex() .id(ElementId::Name( format!("kvt-board-card-{}", task.id).into(), )) .w_full() .flex_none() .px(px(12.)) .py(px(10.)) .gap(px(6.)) .rounded(px(8.)) .bg(theme::surface_raised()) .cursor_pointer() .hover(|card| card.bg(theme::popup_hover())) .on_click(cx.listener(move |this, _, window, cx| { this.open_editor(Some(open.clone()), &open.status, window, cx) })) .when(movable, |card| { card.on_drag(dragged, |dragged, _, _, cx| { let title = dragged.title.clone(); cx.new(|_| TaskGhost { title }) }) .drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background())) .on_drop(cx.listener( move |this, dragged: &DraggedTask, _, cx| { cx.stop_propagation(); this.drop_task(dragged, status, Some(index), cx) }, )) }) .when(in_my_tasks && !task.home_group_name.is_empty(), |card| { card.child( div() .truncate() .text_size(px(11.)) .text_color(theme::text_muted()) .child(task.home_group_name.clone()), ) }) .child( div() .text_size(px(13.)) .line_height(px(18.)) .text_color(if status == STATUS_DONE { theme::text_muted() } else { theme::text() }) .when(status == STATUS_DONE, |text| text.line_through()) .child(task.title.clone()), ) .child( h_flex() .w_full() .flex_wrap() .gap(px(8.)) .items_center() .text_size(px(11.)) .text_color(theme::text_muted()) .when(!task.category_label.is_empty(), |row| { row.child( div() .px(px(6.)) .py(px(1.)) .rounded(px(4.)) .bg(theme::selection()) .text_color(theme::text_strong()) .child(task.category_label.clone()), ) }) .children(due.map(|due| { h_flex() .gap(px(3.)) .items_center() .text_color(if overdue { theme::red_soft() } else { theme::text_muted() }) .child(symbol( "event", 12., if overdue { theme::red_soft() } else { theme::text_muted() }, )) .child(due) })) .when(task.checklist_total > 0, |row| { row.child( h_flex() .gap(px(3.)) .items_center() .child(symbol("check", 12., theme::text_muted())) .child(format!("{}/{}", task.checklist_done, task.checklist_total)), ) }) .children(assignee.map(|assignee| { h_flex() .gap(px(3.)) .items_center() .child(symbol("person", 12., theme::text_muted())) .child(assignee) })), ) .into_any_element() } fn editor_layer(&self, cx: &mut Context<Self>) -> Option<AnyElement> { let editor = self.editor.as_ref()?; let navigation = self.navigation()?; let me = navigation.user_email.clone(); let existing = editor.task.clone(); let editable = existing.as_ref().is_none_or(|task| task.can_edit); let home = existing .as_ref() .map(|task| task.group().to_owned()) .or_else(|| self.group.clone()) .unwrap_or_default(); let target = editor.target_group.clone().unwrap_or_else(|| home.clone()); let title = tr(if existing.is_some() { "kvt.board.edit_task" } else { "kvt.ponos.dialog_title" }); let detail = existing .as_ref() .filter(|task| !task.home_group_name.is_empty()) .map(|task| task.home_group_name.clone()) .unwrap_or_default(); let url = existing.as_ref().map(|task| task.url(&base_url())); let move_groups: Vec<PonosGroup> = navigation .groups .iter() .filter(|group| !group.is_virtual && group.has_task_access) .cloned() .collect(); let other_assignee = (!editor.assignee.is_empty() && !editor.assignee.eq_ignore_ascii_case(&me)) .then(|| name_from_email(&editor.assignee)); let assignee_is_me = !me.is_empty() && editor.assignee.eq_ignore_ascii_case(&me); let status_chips = h_flex() .w_full() .flex_wrap() .gap(px(6.)) .children(STATUSES.iter().enumerate().map(|(index, &status)| { chip( format!("kvt-board-status-{index}").into(), self.status_label(status), editor.status == status, ) .on_click(cx.listener(move |this, _, _, cx| { if let Some(editor) = this.editor.as_mut() { editor.status = status.to_owned(); cx.notify(); } })) })); let assignee_chips = h_flex() .w_full() .flex_wrap() .gap(px(6.)) .child( chip( "kvt-board-assignee-none".into(), tr("kvt.board.assignee_none"), editor.assignee.is_empty(), ) .on_click(cx.listener(|this, _, _, cx| { if let Some(editor) = this.editor.as_mut() { editor.assignee.clear(); cx.notify(); } })), ) .when(!me.is_empty(), |row| { let me = me.clone(); row.child( chip( "kvt-board-assignee-me".into(), tr("kvt.board.assignee_me"), assignee_is_me, ) .on_click(cx.listener(move |this, _, _, cx| { if let Some(editor) = this.editor.as_mut() { editor.assignee = me.clone(); cx.notify(); } })), ) }) .children( other_assignee.map(|name| chip("kvt-board-assignee-other".into(), name, true)), ); let group_chips = (existing.is_some() && move_groups.len() > 1).then(|| { h_flex().w_full().flex_wrap().gap(px(6.)).children( move_groups.iter().enumerate().map(|(index, group)| { let id = group.id.clone(); let home = home.clone(); chip( format!("kvt-board-move-{index}").into(), group.name.clone(), group.id == target, ) .on_click(cx.listener(move |this, _, _, cx| { if let Some(editor) = this.editor.as_mut() { editor.target_group = (id != home).then(|| id.clone()); cx.notify(); } })) }), ) }); let can_complete = existing .as_ref() .is_some_and(|task| task.status != STATUS_DONE && task.can_edit); let panel = v_flex() .debug_selector(|| "kvt-board-editor".into()) .w(px(EDITOR_WIDTH)) .max_w(relative(1.)) .max_h(relative(0.92)) .m(px(32.)) .p(px(16.)) .gap(px(10.)) .rounded(px(RADIUS)) .dialog_surface() .text_color(theme::text()) .occlude() .child( h_flex() .w_full() .items_center() .gap(px(12.)) .child( v_flex() .flex_1() .min_w_0() .child( div() .text_size(px(15.)) .font_weight(FontWeight::SEMIBOLD) .child(title), ) .when(!detail.is_empty(), |column| { column.child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(detail), ) }), ) .child( div() .id("kvt-board-editor-close") .size(px(28.)) .flex_none() .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::popup_hover())) .on_click(cx.listener(|this, _, _, cx| { this.editor = None; cx.notify(); })) .child(symbol("close", 16., theme::text_muted())), ), ) .child(label(tr("kvt.ponos.title"))) .child( field().child( div() .flex_1() .child(Input::new(&editor.title).appearance(false).bordered(false)), ), ) .child(label(tr("kvt.ponos.description"))) .child(Textarea::new(&editor.description)) .child(label(tr("kvt.board.status"))) .child(status_chips) .child(label(tr("kvt.board.due"))) .child( field().child( div() .flex_1() .child(Input::new(&editor.due).appearance(false).bordered(false)), ), ) .child(label(tr("kvt.board.assignee"))) .child(assignee_chips) .when_some(group_chips, |panel, chips| { panel.child(label(tr("kvt.ponos.group"))).child(chips) }) .children(editor.error.clone().map(|error| { div() .text_size(px(13.)) .text_color(theme::red_soft()) .child(error) })) .child( h_flex() .w_full() .gap(px(8.)) .items_center() .children(url.map(|url| { secondary_button( "kvt-board-editor-open", "open_in_new", tr("kvt.tasks.open_ponos"), ) .on_click(move |_, _, cx| open_external(&url, cx)) })) .child(div().flex_1()) .when(can_complete, |row| { row.child( secondary_button( "kvt-board-complete", "check_circle", tr("kvt.board.complete"), ) .on_click(cx.listener(|this, _, _, cx| this.complete_from_editor(cx))), ) }) .child( secondary_button("kvt-board-cancel", "close", tr("common.cancel")) .on_click(cx.listener(|this, _, _, cx| { this.editor = None; cx.notify(); })), ) .when(editable, |row| { row.child( primary_button( "kvt-board-save", tr(if editor.saving { "kvt.ponos.saving" } else { "kvt.board.save" }), ) .on_click(cx.listener(|this, _, _, cx| this.save_editor(cx))), ) }), ); Some( div() .id("kvt-board-editor-layer") .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { if event.keystroke.key == "escape" { cx.stop_propagation(); this.editor = None; cx.notify(); } })) .absolute() .top_0() .left_0() .size_full() .flex() .items_center() .justify_center() .child( div() .id("kvt-board-editor-backdrop") .absolute() .top_0() .left_0() .size_full() .bg(black().opacity(BACKDROP_OPACITY)) .occlude() .on_click(cx.listener(|this, _, _, cx| { this.editor = None; cx.notify(); })), ) .child(panel) .into_any_element(), ) }}impl Render for PonosBoard { fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let linked = matches!(link(cx), Link::Linked(_)); if !linked && !is_demo(cx) { // Ontkoppeld: na opnieuw koppelen vers laden, niets van de oude token tonen. self.nav = Nav::NotLinked; self.editor = None; } else if matches!(self.nav, Nav::NotLinked) { self.reload(cx); } let body = match (&self.nav, linked) { (_, false) => v_flex() .p(px(PAGE_PADDING)) .max_w(px(EDITOR_WIDTH)) .child(not_linked()) .into_any_element(), (Nav::NotLinked | Nav::Loading, _) => muted(tr("kvt.card.loading")) .px(px(PAGE_PADDING)) .into_any_element(), (Nav::Failed(error), _) => muted(ponos_error(error)) .px(px(PAGE_PADDING)) .into_any_element(), (Nav::Loaded(_), _) => h_flex() .flex_1() .min_h_0() .w_full() .child(self.groups_list(cx)) .child( v_flex() .flex_1() .min_w_0() .h_full() .child(self.header(cx)) .child(self.columns(cx)), ) .into_any_element(), }; let page_title = (!matches!(self.nav, Nav::Loaded(_)) || !linked).then(|| { h_flex() .h(px(HEADER_HEIGHT)) .flex_none() .px(px(PAGE_PADDING)) .items_center() .child( div() .text_size(px(16.)) .font_weight(FontWeight::BOLD) .text_color(theme::text()) .child(tr("kvt.board.title")), ) }); v_flex() .debug_selector(|| KVT_BOARD_TAG.into()) .relative() .size_full() .rounded(px(RADIUS)) .bg(theme::surface()) .overflow_hidden() .children(page_title) .child(body) .children(self.editor_layer(cx)) }}#[cfg(test)]mod tests { use super::pick_group; use kvt_sleutels::ponos::{PonosGroup, PonosNavigation}; fn group(id: &str) -> PonosGroup { PonosGroup { id: id.to_owned(), name: id.to_owned(), is_virtual: false, can_create_tasks: true, has_task_access: true, task_count: 0, } } #[test] fn remembered_group_wins_when_it_still_exists() { let navigation = PonosNavigation { groups: vec![group("__my_tasks__"), group("g1")], ..Default::default() }; assert_eq!(pick_group(Some("g1"), &navigation).as_deref(), Some("g1")); assert_eq!( pick_group(Some("weg"), &navigation).as_deref(), Some("__my_tasks__") ); assert_eq!(pick_group(None, &PonosNavigation::default()), None); }}@@ -5,6 +5,10 @@ use kvt_sleutels::{
Card, CardField, CardKind, CardLinks, CardRef, FieldRef, SearchResult, StoredToken,
};
use std::collections::HashMap;
use kvt_sleutels::ponos::{MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask};
use super::DEFAULT_COMPANY as COMPANY;
pub(super) fn token() -> StoredToken {
@@ -241,59 +245,204 @@ pub(super) fn ponos_groups() -> Vec<kvt_sleutels::ponos::PonosGroup> {
is_virtual: false,
can_create_tasks: true,
has_task_access: true,
task_count: 0,
})
.collect()
}
pub(super) fn my_tasks() -> Vec<kvt_sleutels::ponos::PonosTask> {
/// Verzonnen gebruiker van het demobord (geen echt adres).
pub(super) const BOARD_USER: &str = "dana.demo@example.com";
pub(super) fn empty_task() -> PonosTask {
PonosTask {
id: String::new(),
group_id: String::new(),
home_group_id: String::new(),
home_group_name: String::new(),
title: String::new(),
status: "todo".to_owned(),
due_date: String::new(),
description: String::new(),
assignee_email: String::new(),
category_label: String::new(),
checklist_total: 0,
checklist_done: 0,
can_edit: true,
}
}
/// Verzonnen taken per groep voor het Ponos-bord in `--demo`.
pub(super) fn board_tasks() -> HashMap<String, Vec<PonosTask>> {
let today = chrono::Local::now().date_naive();
let task = |id: &str, group: &str, title: &str, status: &str, due: Option<i64>| {
kvt_sleutels::ponos::PonosTask {
id: id.to_owned(),
group_id: "demo-group-0".to_owned(),
home_group_id: "demo-group-0".to_owned(),
home_group_name: group.to_owned(),
title: title.to_owned(),
status: status.to_owned(),
due_date: due
.map(|days| {
(today + chrono::Duration::days(days))
.format("%Y-%m-%d")
.to_string()
})
.unwrap_or_default(),
}
};
kvt_sleutels::ponos::sort_open(vec![
task(
"demo-task-1",
"ICT",
let groups = ponos_groups();
let mut board: HashMap<String, Vec<PonosTask>> = HashMap::new();
#[allow(clippy::type_complexity)]
let rows: [(usize, &str, &str, Option<i64>, &str, &str, (u32, u32)); 13] = [
(
0,
"Laptop klaarzetten voor nieuwe collega",
"todo",
Some(-1),
BOARD_USER,
"Hardware",
(1, 4),
),
(
0,
"Printer receptie controleren",
"todo",
None,
BOARD_USER,
"",
(0, 0),
),
(
0,
"Wifi in hal 3 meten",
"todo",
Some(6),
"",
"Netwerk",
(0, 0),
),
(
0,
"Teams-koppeling testen",
"in_progress",
Some(1),
BOARD_USER,
"",
(2, 3),
),
(
0,
"Back-up NAS nakijken",
"in_progress",
None,
"jonas.ortega@example.com",
"",
(0, 0),
),
(
0,
"Licenties verlengd",
"done",
None,
BOARD_USER,
"",
(0, 0),
),
task(
"demo-task-2",
"Service Noord",
(
1,
"Rapport WO2699001 nakijken",
"in_progress",
Some(2),
BOARD_USER,
"Rapport",
(0, 0),
),
task(
"demo-task-3",
"Werkplaats",
(
1,
"Onderdelen bestellen voor PRJ2600140",
"todo",
Some(4),
"mila.van.der.berg@example.com",
"",
(0, 0),
),
(
1,
"Klant terugbellen over storing",
"todo",
Some(0),
BOARD_USER,
"",
(0, 0),
),
(1, "Servicebus ingepland", "done", None, "", "", (0, 0)),
(
2,
"Brandstoffilters bestellen",
"todo",
Some(9),
BOARD_USER,
"Inkoop",
(0, 0),
),
task(
"demo-task-4",
"ICT",
"Printer receptie controleren",
"todo",
(2, "Hefbrug keuren", "in_progress", Some(12), "", "", (0, 0)),
(
2,
"Gereedschapskist aangevuld",
"done",
None,
"",
"",
(0, 0),
),
];
for (index, (group, title, status, due, assignee, category, (done, total))) in
rows.into_iter().enumerate()
{
let group = &groups[group];
board.entry(group.id.clone()).or_default().push(PonosTask {
id: format!("demo-board-task-{index}"),
group_id: group.id.clone(),
home_group_id: group.id.clone(),
home_group_name: group.name.clone(),
title: title.to_owned(),
status: status.to_owned(),
due_date: due
.map(|days| {
(today + chrono::Duration::days(days))
.format("%Y-%m-%d")
.to_string()
})
.unwrap_or_default(),
description: "Verzonnen taak voor de demo.".to_owned(),
assignee_email: assignee.to_owned(),
category_label: category.to_owned(),
checklist_total: total,
checklist_done: done,
..empty_task()
});
}
board
}
/// Groepen zoals Ponos ze geeft: eerst «Mijn Taken», met open taken geteld.
pub(super) fn board_navigation(board: &HashMap<String, Vec<PonosTask>>) -> PonosNavigation {
let open = |tasks: &mut dyn Iterator<Item = &PonosTask>| {
tasks.filter(|task| task.status != "done").count() as u32
};
let mut groups = vec![PonosGroup {
id: MY_TASKS_GROUP.to_owned(),
name: "Mijn Taken".to_owned(),
is_virtual: true,
can_create_tasks: false,
has_task_access: true,
task_count: open(
&mut board
.values()
.flatten()
.filter(|task| task.assignee_email == BOARD_USER),
),
])
}];
groups.extend(ponos_groups().into_iter().map(|mut group| {
group.task_count = open(&mut board.get(&group.id).into_iter().flatten());
group
}));
PonosNavigation {
groups,
status_labels: [
("todo", "Nog te doen"),
("in_progress", "Onderhanden"),
("done", "Afgerond"),
]
.into_iter()
.map(|(status, label)| (status.to_owned(), label.to_owned()))
.collect(),
user_email: BOARD_USER.to_owned(),
}
}
/// Twee verzonnen werkorders in de zichtbare periode.
@@ -5,6 +5,10 @@ use kvt_sleutels::{ Card, CardField, CardKind, CardLinks, CardRef, FieldRef, SearchResult, StoredToken, Card, CardField, CardKind, CardLinks, CardRef, FieldRef, SearchResult, StoredToken,};};use std::collections::HashMap;use kvt_sleutels::ponos::{MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask};use super::DEFAULT_COMPANY as COMPANY;use super::DEFAULT_COMPANY as COMPANY;pub(super) fn token() -> StoredToken {pub(super) fn token() -> StoredToken {@@ -241,59 +245,204 @@ pub(super) fn ponos_groups() -> Vec<kvt_sleutels::ponos::PonosGroup> { is_virtual: false, is_virtual: false, can_create_tasks: true, can_create_tasks: true, has_task_access: true, has_task_access: true, task_count: 0, }) }) .collect() .collect()}}pub(super) fn my_tasks() -> Vec<kvt_sleutels::ponos::PonosTask> {/// Verzonnen gebruiker van het demobord (geen echt adres).pub(super) const BOARD_USER: &str = "dana.demo@example.com";pub(super) fn empty_task() -> PonosTask { PonosTask { id: String::new(), group_id: String::new(), home_group_id: String::new(), home_group_name: String::new(), title: String::new(), status: "todo".to_owned(), due_date: String::new(), description: String::new(), assignee_email: String::new(), category_label: String::new(), checklist_total: 0, checklist_done: 0, can_edit: true, }}/// Verzonnen taken per groep voor het Ponos-bord in `--demo`.pub(super) fn board_tasks() -> HashMap<String, Vec<PonosTask>> { let today = chrono::Local::now().date_naive(); let today = chrono::Local::now().date_naive(); let task = |id: &str, group: &str, title: &str, status: &str, due: Option<i64>| { let groups = ponos_groups(); kvt_sleutels::ponos::PonosTask { let mut board: HashMap<String, Vec<PonosTask>> = HashMap::new(); id: id.to_owned(), #[allow(clippy::type_complexity)] group_id: "demo-group-0".to_owned(), let rows: [(usize, &str, &str, Option<i64>, &str, &str, (u32, u32)); 13] = [ home_group_id: "demo-group-0".to_owned(), ( home_group_name: group.to_owned(), 0, title: title.to_owned(), status: status.to_owned(), due_date: due .map(|days| { (today + chrono::Duration::days(days)) .format("%Y-%m-%d") .to_string() }) .unwrap_or_default(), } }; kvt_sleutels::ponos::sort_open(vec![ task( "demo-task-1", "ICT", "Laptop klaarzetten voor nieuwe collega", "Laptop klaarzetten voor nieuwe collega", "todo", "todo", Some(-1), Some(-1), BOARD_USER, "Hardware", (1, 4), ), ( 0, "Printer receptie controleren", "todo", None, BOARD_USER, "", (0, 0), ), ( 0, "Wifi in hal 3 meten", "todo", Some(6), "", "Netwerk", (0, 0), ), ( 0, "Teams-koppeling testen", "in_progress", Some(1), BOARD_USER, "", (2, 3), ), ( 0, "Back-up NAS nakijken", "in_progress", None, "jonas.ortega@example.com", "", (0, 0), ), ( 0, "Licenties verlengd", "done", None, BOARD_USER, "", (0, 0), ), ), task( ( "demo-task-2", 1, "Service Noord", "Rapport WO2699001 nakijken", "Rapport WO2699001 nakijken", "in_progress", "in_progress", Some(2), Some(2), BOARD_USER, "Rapport", (0, 0), ), ), task( ( "demo-task-3", 1, "Werkplaats", "Onderdelen bestellen voor PRJ2600140", "todo", Some(4), "mila.van.der.berg@example.com", "", (0, 0), ), ( 1, "Klant terugbellen over storing", "todo", Some(0), BOARD_USER, "", (0, 0), ), (1, "Servicebus ingepland", "done", None, "", "", (0, 0)), ( 2, "Brandstoffilters bestellen", "Brandstoffilters bestellen", "todo", "todo", Some(9), Some(9), BOARD_USER, "Inkoop", (0, 0), ), ), task( (2, "Hefbrug keuren", "in_progress", Some(12), "", "", (0, 0)), "demo-task-4", ( "ICT", 2, "Printer receptie controleren", "Gereedschapskist aangevuld", "todo", "done", None, None, "", "", (0, 0), ), ]; for (index, (group, title, status, due, assignee, category, (done, total))) in rows.into_iter().enumerate() { let group = &groups[group]; board.entry(group.id.clone()).or_default().push(PonosTask { id: format!("demo-board-task-{index}"), group_id: group.id.clone(), home_group_id: group.id.clone(), home_group_name: group.name.clone(), title: title.to_owned(), status: status.to_owned(), due_date: due .map(|days| { (today + chrono::Duration::days(days)) .format("%Y-%m-%d") .to_string() }) .unwrap_or_default(), description: "Verzonnen taak voor de demo.".to_owned(), assignee_email: assignee.to_owned(), category_label: category.to_owned(), checklist_total: total, checklist_done: done, ..empty_task() }); } board}/// Groepen zoals Ponos ze geeft: eerst «Mijn Taken», met open taken geteld.pub(super) fn board_navigation(board: &HashMap<String, Vec<PonosTask>>) -> PonosNavigation { let open = |tasks: &mut dyn Iterator<Item = &PonosTask>| { tasks.filter(|task| task.status != "done").count() as u32 }; let mut groups = vec![PonosGroup { id: MY_TASKS_GROUP.to_owned(), name: "Mijn Taken".to_owned(), is_virtual: true, can_create_tasks: false, has_task_access: true, task_count: open( &mut board .values() .flatten() .filter(|task| task.assignee_email == BOARD_USER), ), ), ]) }]; groups.extend(ponos_groups().into_iter().map(|mut group| { group.task_count = open(&mut board.get(&group.id).into_iter().flatten()); group })); PonosNavigation { groups, status_labels: [ ("todo", "Nog te doen"), ("in_progress", "Onderhanden"), ("done", "Afgerond"), ] .into_iter() .map(|(status, label)| (status.to_owned(), label.to_owned())) .collect(), user_email: BOARD_USER.to_owned(), }}}/// Twee verzonnen werkorders in de zichtbare periode./// Twee verzonnen werkorders in de zichtbare periode.@@ -1,4 +1,5 @@
//! Berichtmenu: «Ticket maken in Asclepius» en «Taak maken in Ponos».
//! Berichtmenu: «Ticket maken in Asclepius» en «Taak maken in Ponos» (beide een
//! dialoog in de app, vooraf ingevuld met het bericht).
//!
//! Upstream-haak: `views/message_actions.rs` (veld `kvt` in `MessageMenu`) en
//! `views/conversation.rs` (`message_menu`).
@@ -8,10 +9,10 @@ use std::rc::Rc;
use chrono::Local;
use gpui_kit::assets::IconName;
use gpui_kit::*;
use kvt_sleutels::asclepius::{MessageSource, new_ticket_url};
use kvt_sleutels::asclepius::MessageSource;
use kvt_sleutels::format::date_time_nl;
use super::{base_url, installed, open_external};
use super::installed;
use crate::app_state::AppHandle;
use crate::i18n::tr;
use crate::runtime;
@@ -52,7 +53,7 @@ pub fn menu_entries(conversation_id: Option<String>, message_id: &str, cx: &App)
entry(
"kvt.message.asclepius",
IconName::Ticket,
|source, _, cx| open_external(&new_ticket_url(&base_url(), &source), cx),
|source, window, cx| super::ticket_form::open_new(Some(source), window, cx),
),
entry(
"kvt.message.ponos",
@@ -82,7 +83,9 @@ fn with_source(
sender: record.sender_name.clone().unwrap_or_default(),
sent_at: date_time_nl(record.created_at.with_timezone(&Local).naive_local()),
link: None,
mentions: Vec::new(),
};
let mentioned = mentioned_users(&record.mentions_json);
let Some(engine) = state.engine.clone() else {
let link = state
.mode
@@ -92,11 +95,79 @@ fn with_source(
return;
};
let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned());
let linking =
runtime::spawn(async move { engine.message_link(&conversation_id, &message_id).await });
let linking = runtime::spawn(async move {
let link = engine
.message_link(&conversation_id, &message_id)
.await
.ok();
// Vermeldingen: het adres via het profiel (best effort), voor `@naam:domein` in Asclepius.
let mut mentions = Vec::new();
for (name, user_id) in mentioned {
if let Ok(profile) = engine.person_profile(&user_id).await
&& let Some(email) = profile.email.filter(|email| email.contains('@'))
{
mentions.push((name, email));
}
}
(link, mentions)
});
cx.spawn(async move |cx| {
let link = linking.await.ok().and_then(Result::ok);
cx.update(|cx| then(MessageSource { link, ..source }, cx));
let (link, mentions) = linking.await.unwrap_or_default();
cx.update(|cx| {
then(
MessageSource {
link,
mentions,
..source
},
cx,
)
});
})
.detach();
}
/// Vermelde personen (naam, Teams-id) uit het bericht; groepen en dubbelen niet.
fn mentioned_users(mentions_json: &str) -> Vec<(String, String)> {
let infos: Vec<teams_core::MentionInfo> =
serde_json::from_str(mentions_json).unwrap_or_default();
let mut users: Vec<(String, String)> = Vec::new();
for info in infos.into_iter().filter(|info| !info.group) {
let Some(user_id) = info.user_id.filter(|id| !id.is_empty()) else {
continue;
};
let name = info.name.trim().to_owned();
if name.is_empty() || users.iter().any(|(_, known)| *known == user_id) {
continue;
}
users.push((name, user_id));
}
users.truncate(MENTIONS_MAX);
users
}
/// Zoveel profielen halen we hooguit op voor één bericht.
const MENTIONS_MAX: usize = 10;
#[cfg(test)]
mod tests {
use super::mentioned_users;
#[test]
fn mentioned_users_skips_groups_and_duplicates() {
let json = r#"[
{"user_id":"8:orgid:a","name":"Jonas Ortega","id":0},
{"user_id":"8:orgid:a","name":"Jonas","id":1},
{"user_id":null,"name":"Iedereen","id":2,"group":true},
{"user_id":"8:orgid:b","name":"Mara","id":3}
]"#;
assert_eq!(
mentioned_users(json),
[
("Jonas Ortega".to_owned(), "8:orgid:a".to_owned()),
("Mara".to_owned(), "8:orgid:b".to_owned())
]
);
assert!(mentioned_users("geen json").is_empty());
}
}
@@ -1,4 +1,5 @@//! Berichtmenu: «Ticket maken in Asclepius» en «Taak maken in Ponos».//! Berichtmenu: «Ticket maken in Asclepius» en «Taak maken in Ponos» (beide een//! dialoog in de app, vooraf ingevuld met het bericht).//!//!//! Upstream-haak: `views/message_actions.rs` (veld `kvt` in `MessageMenu`) en//! Upstream-haak: `views/message_actions.rs` (veld `kvt` in `MessageMenu`) en//! `views/conversation.rs` (`message_menu`).//! `views/conversation.rs` (`message_menu`).@@ -8,10 +9,10 @@ use std::rc::Rc;use chrono::Local;use chrono::Local;use gpui_kit::assets::IconName;use gpui_kit::assets::IconName;use gpui_kit::*;use gpui_kit::*;use kvt_sleutels::asclepius::{MessageSource, new_ticket_url};use kvt_sleutels::asclepius::MessageSource;use kvt_sleutels::format::date_time_nl;use kvt_sleutels::format::date_time_nl;use super::{base_url, installed, open_external};use super::installed;use crate::app_state::AppHandle;use crate::app_state::AppHandle;use crate::i18n::tr;use crate::i18n::tr;use crate::runtime;use crate::runtime;@@ -52,7 +53,7 @@ pub fn menu_entries(conversation_id: Option<String>, message_id: &str, cx: &App) entry( entry( "kvt.message.asclepius", "kvt.message.asclepius", IconName::Ticket, IconName::Ticket, |source, _, cx| open_external(&new_ticket_url(&base_url(), &source), cx), |source, window, cx| super::ticket_form::open_new(Some(source), window, cx), ), ), entry( entry( "kvt.message.ponos", "kvt.message.ponos",@@ -82,7 +83,9 @@ fn with_source( sender: record.sender_name.clone().unwrap_or_default(), sender: record.sender_name.clone().unwrap_or_default(), sent_at: date_time_nl(record.created_at.with_timezone(&Local).naive_local()), sent_at: date_time_nl(record.created_at.with_timezone(&Local).naive_local()), link: None, link: None, mentions: Vec::new(), }; }; let mentioned = mentioned_users(&record.mentions_json); let Some(engine) = state.engine.clone() else { let Some(engine) = state.engine.clone() else { let link = state let link = state .mode .mode@@ -92,11 +95,79 @@ fn with_source( return; return; }; }; let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned()); let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned()); let linking = let linking = runtime::spawn(async move { runtime::spawn(async move { engine.message_link(&conversation_id, &message_id).await }); let link = engine .message_link(&conversation_id, &message_id) .await .ok(); // Vermeldingen: het adres via het profiel (best effort), voor `@naam:domein` in Asclepius. let mut mentions = Vec::new(); for (name, user_id) in mentioned { if let Ok(profile) = engine.person_profile(&user_id).await && let Some(email) = profile.email.filter(|email| email.contains('@')) { mentions.push((name, email)); } } (link, mentions) }); cx.spawn(async move |cx| { cx.spawn(async move |cx| { let link = linking.await.ok().and_then(Result::ok); let (link, mentions) = linking.await.unwrap_or_default(); cx.update(|cx| then(MessageSource { link, ..source }, cx)); cx.update(|cx| { then( MessageSource { link, mentions, ..source }, cx, ) }); }) }) .detach(); .detach();}}/// Vermelde personen (naam, Teams-id) uit het bericht; groepen en dubbelen niet.fn mentioned_users(mentions_json: &str) -> Vec<(String, String)> { let infos: Vec<teams_core::MentionInfo> = serde_json::from_str(mentions_json).unwrap_or_default(); let mut users: Vec<(String, String)> = Vec::new(); for info in infos.into_iter().filter(|info| !info.group) { let Some(user_id) = info.user_id.filter(|id| !id.is_empty()) else { continue; }; let name = info.name.trim().to_owned(); if name.is_empty() || users.iter().any(|(_, known)| *known == user_id) { continue; } users.push((name, user_id)); } users.truncate(MENTIONS_MAX); users}/// Zoveel profielen halen we hooguit op voor één bericht.const MENTIONS_MAX: usize = 10;#[cfg(test)]mod tests { use super::mentioned_users; #[test] fn mentioned_users_skips_groups_and_duplicates() { let json = r#"[ {"user_id":"8:orgid:a","name":"Jonas Ortega","id":0}, {"user_id":"8:orgid:a","name":"Jonas","id":1}, {"user_id":null,"name":"Iedereen","id":2,"group":true}, {"user_id":"8:orgid:b","name":"Mara","id":3} ]"#; assert_eq!( mentioned_users(json), [ ("Jonas Ortega".to_owned(), "8:orgid:a".to_owned()), ("Mara".to_owned(), "8:orgid:b".to_owned()) ] ); assert!(mentioned_users("geen json").is_empty()); }}@@ -6,15 +6,19 @@
//! geen eigen berichtformaten). Zie KVT-FORK.md en ADR 0024.
//!
//! Daarnaast: «Ticket maken in Asclepius» en «Taak maken in Ponos» in het
//! berichtmenu (`message`), het paneel «Mijn taken» (`tasks`) en de eigen
//! Daedalus-planning als read-only agenda (`calendar`).
//! berichtmenu (`message`, `tasks`), het Ponos-bord achter de tegel in de
//! navigatierail (`board`), de Asclepius-tegel eronder (`tickets`), de eigen
//! Daedalus-planning als read-only agenda (`calendar`) en eigen vensterknoppen
//! in de titelbalk (`window_controls`).
//!
//! Upstream-haken: `views/shell.rs` (install, overlay, dialog-telling),
//! `views/message_row.rs` en `views/post_card.rs` (kaartjes), `settings/general.rs`
//! (instellingen, via `settings/kvt.rs`), `views/composer/plus_menu.rs` (picker), `views/composer.rs`
//! (`mod kvt`), `views/message_actions.rs` en `views/conversation.rs` (berichtmenu),
//! `views/status_menu.rs` (Mijn taken), `app-state/src/call/week.rs` (agenda).
//! `views/rail.rs`, `views/sidebar.rs` en `views/shell.rs` (Ponos-tegel en -bord),
//! `app-state/src/call/week.rs` (agenda).
mod board;
pub mod calendar;
mod card;
mod demo;
@@ -23,6 +27,9 @@ mod modal;
mod picker;
mod session;
mod tasks;
mod ticket_form;
mod tickets;
pub mod window_controls;
use std::collections::HashMap;
@@ -34,11 +41,13 @@ use crate::app_state::AppHandle;
use crate::i18n::tr;
use crate::runtime;
pub use board::{board_opened, board_view};
pub use card::{blocks_without_card_links, message_cards};
pub use message::{MenuEntry, menu_entries};
pub use modal::render_modal;
pub use picker::{open_picker, plus_item};
pub use tasks::extend_settings_menu;
pub use tickets::{open_ticket_link, tickets_opened, tickets_unread, tickets_view};
pub use window_controls::{title_bar_system_window_controls, title_buttons};
/// Alleen voor testen tegen een andere Login/Mímir (bijv. .test); altijd https.
const BASE_URL_ENV: &str = "KVT_SLEUTELS_URL";
@@ -83,9 +92,14 @@ pub(crate) struct Kvt {
connecting: Option<tokio::task::AbortHandle>,
connect_generation: u64,
ponos_dialog: Option<Entity<tasks::PonosDialog>>,
tasks: Option<tasks::TasksLoad>,
/// Alleen `--demo`: «Mijn taken» zonder Ponos.
demo_tasks: Vec<kvt_sleutels::ponos::PonosTask>,
/// Ponos-bord in het hoofdpaneel (aangemaakt bij de eerste keer openen).
board: Option<Entity<board::PonosBoard>>,
/// Asclepius-tickets in het hoofdpaneel (ook voor de badge op de tegel).
tickets: Option<Entity<tickets::TicketsPage>>,
/// «Nieuw ticket maken» (ook vanuit een bericht).
ticket_form: Option<Entity<ticket_form::TicketForm>>,
/// Ticketvenster na een klik op een ticketlink (alleen met toegang).
ticket_window: Option<Entity<tickets::TicketThread>>,
/// Daedalus-planning in de agenda (instelling).
planning: bool,
/// Token waarmee de agendabron nu staat (zie `calendar::sync`).
@@ -118,8 +132,10 @@ pub fn install(demo: bool, cx: &mut App) {
connecting: None,
connect_generation: 0,
ponos_dialog: None,
tasks: None,
demo_tasks: if demo { demo::my_tasks() } else { Vec::new() },
board: None,
tickets: None,
ticket_form: None,
ticket_window: None,
planning: true,
calendar_source: None,
});
@@ -505,13 +521,28 @@ pub fn disconnect(cx: &mut App) {
notice(tr("kvt.notice.disconnected"), cx);
}
/// KVT-tegels in de navigatierail.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RailTile {
Ponos,
Asclepius,
}
/// Navigatierail: Ponos direct onder Agents, Asclepius daaronder (laatste tegels).
pub fn with_rail_tiles<T>(mut items: Vec<T>, tile: impl Fn(RailTile, String) -> T) -> Vec<T> {
items.push(tile(RailTile::Ponos, tr("kvt.rail.ponos")));
items.push(tile(RailTile::Asclepius, tr("kvt.rail.asclepius")));
items
}
/// Telt mee voor de modale lagen van de shell.
pub fn dialog_open(cx: &App) -> bool {
read(cx, |kvt| {
kvt.modal.is_some()
|| kvt.picker.is_some()
|| kvt.ponos_dialog.is_some()
|| kvt.tasks.is_some()
|| kvt.ticket_form.is_some()
|| kvt.ticket_window.is_some()
})
.unwrap_or(false)
}
@@ -525,18 +556,31 @@ pub fn overlay(cx: &App) -> Vec<AnyElement> {
if let Some(picker) = read(cx, |kvt| kvt.picker.clone()).flatten() {
layers.push(picker.into_any_element());
}
if let Some(tasks) = tasks::render_tasks(cx) {
layers.push(tasks);
}
if let Some(dialog) = read(cx, |kvt| kvt.ponos_dialog.clone()).flatten() {
layers.push(dialog.into_any_element());
}
if let Some(thread) = read(cx, |kvt| kvt.ticket_window.clone()).flatten() {
layers.push(tickets::window_overlay(thread));
}
if let Some(form) = read(cx, |kvt| kvt.ticket_form.clone()).flatten() {
layers.push(form.into_any_element());
}
layers
}
#[cfg(test)]
mod tests {
use super::{device_name, host_of};
use super::{device_name, host_of, with_rail_tiles};
#[test]
fn ponos_then_asclepius_come_last_below_agents() {
app_base::ui_locale::apply_locale("nl");
let items = with_rail_tiles(
vec!["Activiteit".to_owned(), "Agents".to_owned()],
|_, label| label,
);
assert_eq!(items, ["Activiteit", "Agents", "Ponos", "Asclepius"]);
}
#[test]
fn host_of_base_url() {
@@ -6,15 +6,19 @@//! geen eigen berichtformaten). Zie KVT-FORK.md en ADR 0024.//! geen eigen berichtformaten). Zie KVT-FORK.md en ADR 0024.//!//!//! Daarnaast: «Ticket maken in Asclepius» en «Taak maken in Ponos» in het//! Daarnaast: «Ticket maken in Asclepius» en «Taak maken in Ponos» in het//! berichtmenu (`message`), het paneel «Mijn taken» (`tasks`) en de eigen//! berichtmenu (`message`, `tasks`), het Ponos-bord achter de tegel in de//! Daedalus-planning als read-only agenda (`calendar`).//! navigatierail (`board`), de Asclepius-tegel eronder (`tickets`), de eigen//! Daedalus-planning als read-only agenda (`calendar`) en eigen vensterknoppen//! in de titelbalk (`window_controls`).//!//!//! Upstream-haken: `views/shell.rs` (install, overlay, dialog-telling),//! Upstream-haken: `views/shell.rs` (install, overlay, dialog-telling),//! `views/message_row.rs` en `views/post_card.rs` (kaartjes), `settings/general.rs`//! `views/message_row.rs` en `views/post_card.rs` (kaartjes), `settings/general.rs`//! (instellingen, via `settings/kvt.rs`), `views/composer/plus_menu.rs` (picker), `views/composer.rs`//! (instellingen, via `settings/kvt.rs`), `views/composer/plus_menu.rs` (picker), `views/composer.rs`//! (`mod kvt`), `views/message_actions.rs` en `views/conversation.rs` (berichtmenu),//! (`mod kvt`), `views/message_actions.rs` en `views/conversation.rs` (berichtmenu),//! `views/status_menu.rs` (Mijn taken), `app-state/src/call/week.rs` (agenda).//! `views/rail.rs`, `views/sidebar.rs` en `views/shell.rs` (Ponos-tegel en -bord),//! `app-state/src/call/week.rs` (agenda).mod board;pub mod calendar;pub mod calendar;mod card;mod card;mod demo;mod demo;@@ -23,6 +27,9 @@ mod modal;mod picker;mod picker;mod session;mod session;mod tasks;mod tasks;mod ticket_form;mod tickets;pub mod window_controls;use std::collections::HashMap;use std::collections::HashMap;@@ -34,11 +41,13 @@ use crate::app_state::AppHandle;use crate::i18n::tr;use crate::i18n::tr;use crate::runtime;use crate::runtime;pub use board::{board_opened, board_view};pub use card::{blocks_without_card_links, message_cards};pub use card::{blocks_without_card_links, message_cards};pub use message::{MenuEntry, menu_entries};pub use message::{MenuEntry, menu_entries};pub use modal::render_modal;pub use modal::render_modal;pub use picker::{open_picker, plus_item};pub use picker::{open_picker, plus_item};pub use tasks::extend_settings_menu;pub use tickets::{open_ticket_link, tickets_opened, tickets_unread, tickets_view};pub use window_controls::{title_bar_system_window_controls, title_buttons};/// Alleen voor testen tegen een andere Login/Mímir (bijv. .test); altijd https./// Alleen voor testen tegen een andere Login/Mímir (bijv. .test); altijd https.const BASE_URL_ENV: &str = "KVT_SLEUTELS_URL";const BASE_URL_ENV: &str = "KVT_SLEUTELS_URL";@@ -83,9 +92,14 @@ pub(crate) struct Kvt { connecting: Option<tokio::task::AbortHandle>, connecting: Option<tokio::task::AbortHandle>, connect_generation: u64, connect_generation: u64, ponos_dialog: Option<Entity<tasks::PonosDialog>>, ponos_dialog: Option<Entity<tasks::PonosDialog>>, tasks: Option<tasks::TasksLoad>, /// Ponos-bord in het hoofdpaneel (aangemaakt bij de eerste keer openen). /// Alleen `--demo`: «Mijn taken» zonder Ponos. board: Option<Entity<board::PonosBoard>>, demo_tasks: Vec<kvt_sleutels::ponos::PonosTask>, /// Asclepius-tickets in het hoofdpaneel (ook voor de badge op de tegel). tickets: Option<Entity<tickets::TicketsPage>>, /// «Nieuw ticket maken» (ook vanuit een bericht). ticket_form: Option<Entity<ticket_form::TicketForm>>, /// Ticketvenster na een klik op een ticketlink (alleen met toegang). ticket_window: Option<Entity<tickets::TicketThread>>, /// Daedalus-planning in de agenda (instelling). /// Daedalus-planning in de agenda (instelling). planning: bool, planning: bool, /// Token waarmee de agendabron nu staat (zie `calendar::sync`). /// Token waarmee de agendabron nu staat (zie `calendar::sync`).@@ -118,8 +132,10 @@ pub fn install(demo: bool, cx: &mut App) { connecting: None, connecting: None, connect_generation: 0, connect_generation: 0, ponos_dialog: None, ponos_dialog: None, tasks: None, board: None, demo_tasks: if demo { demo::my_tasks() } else { Vec::new() }, tickets: None, ticket_form: None, ticket_window: None, planning: true, planning: true, calendar_source: None, calendar_source: None, }); });@@ -505,13 +521,28 @@ pub fn disconnect(cx: &mut App) { notice(tr("kvt.notice.disconnected"), cx); notice(tr("kvt.notice.disconnected"), cx);}}/// KVT-tegels in de navigatierail.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum RailTile { Ponos, Asclepius,}/// Navigatierail: Ponos direct onder Agents, Asclepius daaronder (laatste tegels).pub fn with_rail_tiles<T>(mut items: Vec<T>, tile: impl Fn(RailTile, String) -> T) -> Vec<T> { items.push(tile(RailTile::Ponos, tr("kvt.rail.ponos"))); items.push(tile(RailTile::Asclepius, tr("kvt.rail.asclepius"))); items}/// Telt mee voor de modale lagen van de shell./// Telt mee voor de modale lagen van de shell.pub fn dialog_open(cx: &App) -> bool {pub fn dialog_open(cx: &App) -> bool { read(cx, |kvt| { read(cx, |kvt| { kvt.modal.is_some() kvt.modal.is_some() || kvt.picker.is_some() || kvt.picker.is_some() || kvt.ponos_dialog.is_some() || kvt.ponos_dialog.is_some() || kvt.tasks.is_some() || kvt.ticket_form.is_some() || kvt.ticket_window.is_some() }) }) .unwrap_or(false) .unwrap_or(false)}}@@ -525,18 +556,31 @@ pub fn overlay(cx: &App) -> Vec<AnyElement> { if let Some(picker) = read(cx, |kvt| kvt.picker.clone()).flatten() { if let Some(picker) = read(cx, |kvt| kvt.picker.clone()).flatten() { layers.push(picker.into_any_element()); layers.push(picker.into_any_element()); } } if let Some(tasks) = tasks::render_tasks(cx) { layers.push(tasks); } if let Some(dialog) = read(cx, |kvt| kvt.ponos_dialog.clone()).flatten() { if let Some(dialog) = read(cx, |kvt| kvt.ponos_dialog.clone()).flatten() { layers.push(dialog.into_any_element()); layers.push(dialog.into_any_element()); } } if let Some(thread) = read(cx, |kvt| kvt.ticket_window.clone()).flatten() { layers.push(tickets::window_overlay(thread)); } if let Some(form) = read(cx, |kvt| kvt.ticket_form.clone()).flatten() { layers.push(form.into_any_element()); } layers layers}}#[cfg(test)]#[cfg(test)]mod tests {mod tests { use super::{device_name, host_of}; use super::{device_name, host_of, with_rail_tiles}; #[test] fn ponos_then_asclepius_come_last_below_agents() { app_base::ui_locale::apply_locale("nl"); let items = with_rail_tiles( vec!["Activiteit".to_owned(), "Agents".to_owned()], |_, label| label, ); assert_eq!(items, ["Activiteit", "Agents", "Ponos", "Asclepius"]); } #[test] #[test] fn host_of_base_url() { fn host_of_base_url() {@@ -1,23 +1,19 @@
//! Ponos: «Taak maken van bericht» (dialoog) en het paneel «Mijn taken».
//!
//! Upstream-haak voor het paneel: `views/status_menu.rs` (instellingenmenu).
//! Ponos: «Taak maken van bericht» (dialoog) en gedeelde bouwstenen voor het
//! bord (`board.rs`). Het oude paneel «Mijn taken» (…-menu) is vervangen door
//! de tegel Ponos in de navigatierail.
use gpui_kit::assets::IconName;
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
use gpui_kit::component::scroll::ScrollableElement as _;
use gpui_kit::component::{h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use kvt_sleutels::ClientError;
use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource};
use kvt_sleutels::format::iso_date_nl;
use kvt_sleutels::ponos::{PonosGroup, PonosTask};
use kvt_sleutels::ponos::PonosGroup;
use super::modal::{primary_button, secondary_button};
use super::{
Link, base_url, connect, error_text, forget_token, installed, is_demo, link, notice,
open_external, read, token_and_client, update,
Link, connect, error_text, forget_token, installed, is_demo, link, notice, token_and_client,
update,
};
use crate::app_state::AppHandle;
use crate::i18n::tr;
@@ -26,7 +22,6 @@ use crate::theme::{self, ElevatedSurface as _};
use crate::views::widgets::symbol;
pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog";
pub const KVT_TASKS_PANEL_TAG: &str = "kvt-tasks-panel";
/// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag).
const GROUP_META_KEY: &str = "kvt.ponos.group";
/// Ponos staat 200 tekens toe in de titel.
@@ -40,15 +35,6 @@ const SECTION_GAP: f32 = 12.;
const CLOSE_SIZE: f32 = 28.;
const CHIP_HEIGHT: f32 = 28.;
const FIELD_HEIGHT: f32 = 36.;
const ROW_HEIGHT: f32 = 48.;
const LIST_MAX_HEIGHT: f32 = 420.;
#[derive(Clone)]
pub(crate) enum TasksLoad {
Loading,
Loaded(Vec<PonosTask>),
Failed(ClientError),
}
#[derive(Clone)]
enum Groups {
@@ -195,7 +181,7 @@ impl PonosDialog {
Ok(_) => {
close_create(cx);
notice(tr("kvt.ponos.created"), cx);
refresh_tasks_if_open(cx);
super::board::refresh_board_if_open(cx);
}
Err(error) => {
if error == ClientError::Unauthorized {
@@ -303,245 +289,9 @@ impl Render for PonosDialog {
}
}
// --- Mijn taken -------------------------------------------------------------
/// Regel «Mijn taken in Ponos» in het instellingenmenu (`…` rechtsboven).
pub fn extend_settings_menu(popup: PopupMenu, cx: &App) -> PopupMenu {
if !installed(cx) {
return popup;
}
popup.separator().item(
PopupMenuItem::new(tr("kvt.tasks.menu"))
.icon(IconName::ClipboardCheck)
.on_click(|_, _, cx| open_tasks(cx)),
)
}
pub(crate) fn open_tasks(cx: &mut App) {
update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loading));
load_tasks(cx);
}
fn close_tasks(cx: &mut App) {
update(cx, |kvt| kvt.tasks = None);
}
fn refresh_tasks_if_open(cx: &mut App) {
if read(cx, |kvt| kvt.tasks.is_some()).unwrap_or(false) {
load_tasks(cx);
}
}
fn load_tasks(cx: &mut App) {
if is_demo(cx) {
let tasks = read(cx, |kvt| kvt.demo_tasks.clone()).unwrap_or_default();
update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loaded(tasks)));
return;
}
let Some((token, client)) = token_and_client(cx) else {
return;
};
let loading = runtime::spawn(async move { client.ponos_my_tasks(&token).await });
cx.spawn(async move |cx| {
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| {
if result == Err(ClientError::Unauthorized) {
forget_token(cx);
}
let load = match result {
Ok(tasks) => TasksLoad::Loaded(tasks),
Err(error) => TasksLoad::Failed(error),
};
update(cx, |kvt| {
if kvt.tasks.is_some() {
kvt.tasks = Some(load);
}
});
});
})
.detach();
}
fn complete(task: PonosTask, cx: &mut App) {
let remove = |kvt: &mut super::Kvt, id: &str| {
if let Some(TasksLoad::Loaded(tasks)) = kvt.tasks.as_mut() {
tasks.retain(|task| task.id != id);
}
kvt.demo_tasks.retain(|task| task.id != id);
};
if is_demo(cx) {
update(cx, |kvt| remove(kvt, &task.id));
notice(tr("kvt.tasks.completed"), cx);
return;
}
let Some((token, client)) = token_and_client(cx) else {
return;
};
let (group, id) = (task.group().to_owned(), task.id.clone());
let completing = runtime::spawn({
let id = id.clone();
async move { client.ponos_complete_task(&token, &group, &id).await }
});
cx.spawn(async move |cx| {
let result = completing.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| match result {
Ok(()) => {
update(cx, |kvt| remove(kvt, &id));
notice(tr("kvt.tasks.completed"), cx);
}
Err(error) => {
if error == ClientError::Unauthorized {
forget_token(cx);
}
notice(ponos_error(&error), cx);
}
});
})
.detach();
}
pub fn render_tasks(cx: &App) -> Option<AnyElement> {
let load = read(cx, |kvt| kvt.tasks.clone()).flatten()?;
let body = if !matches!(link(cx), Link::Linked(_)) {
not_linked().into_any_element()
} else {
match load {
TasksLoad::Loading => muted(tr("kvt.card.loading")).into_any_element(),
TasksLoad::Failed(error) => muted(ponos_error(&error)).into_any_element(),
TasksLoad::Loaded(tasks) if tasks.is_empty() => {
muted(tr("kvt.tasks.empty")).into_any_element()
}
TasksLoad::Loaded(tasks) => v_flex()
.id("kvt-tasks-list")
.w_full()
.max_h(px(LIST_MAX_HEIGHT))
.overflow_y_scrollbar()
.children(
tasks
.into_iter()
.enumerate()
.map(|(index, task)| task_row(index, task)),
)
.into_any_element(),
}
};
let ponos = format!("{}/ponos/", base_url());
Some(
layer("kvt-tasks", |cx| close_tasks(cx))
.child(
panel(KVT_TASKS_PANEL_TAG)
.child(header(tr("kvt.tasks.title"), String::new(), |cx| {
close_tasks(cx)
}))
.child(body)
.child(
h_flex()
.w_full()
.gap(px(8.))
.child(
secondary_button(
"kvt-tasks-open",
"open_in_new",
tr("kvt.tasks.open_ponos"),
)
.on_click(move |_, _, cx| open_external(&ponos, cx)),
)
.child(
secondary_button(
"kvt-tasks-refresh",
"refresh",
tr("kvt.card.refresh"),
)
.on_click(|_, _, cx| open_tasks(cx)),
),
),
)
.into_any_element(),
)
}
fn task_row(index: usize, task: PonosTask) -> AnyElement {
let today = chrono::Local::now()
.date_naive()
.format("%Y-%m-%d")
.to_string();
let overdue = !task.due_date.is_empty() && task.due_date.as_str() < today.as_str();
let mut detail = Vec::new();
if !task.home_group_name.is_empty() {
detail.push(task.home_group_name.clone());
}
if task.status == "in_progress" {
detail.push(tr("kvt.tasks.in_progress"));
}
let due = iso_date_nl(&task.due_date);
let url = task.url(&base_url());
let done = task.clone();
h_flex()
.id(ElementId::Name(format!("kvt-task-{index}").into()))
.w_full()
.h(px(ROW_HEIGHT))
.flex_none()
.px(px(8.))
.gap(px(10.))
.items_center()
.rounded(px(6.))
.cursor_pointer()
.hover(|row| row.bg(theme::popup_hover()))
.on_click(move |_, _, cx| open_external(&url, cx))
.child(
div()
.id(ElementId::Name(format!("kvt-task-done-{index}").into()))
.size(px(CLOSE_SIZE))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded_full()
.hover(|button| button.bg(theme::row_hover()))
.on_click(move |_, _, cx| {
cx.stop_propagation();
complete(done.clone(), cx);
})
.child(symbol("check_circle", 18., theme::text_muted())),
)
.child(
v_flex()
.flex_1()
.min_w_0()
.child(
div()
.truncate()
.text_size(px(13.))
.text_color(theme::text())
.child(task.title.clone()),
)
.when(!detail.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(detail.join(" · ")),
)
}),
)
.children(due.map(|due| {
div()
.flex_none()
.text_size(px(12.))
.text_color(if overdue {
theme::red_soft()
} else {
theme::text_muted()
})
.child(due)
}))
.into_any_element()
}
// --- gedeelde bouwstenen ----------------------------------------------------
fn ponos_error(error: &ClientError) -> String {
pub(super) fn ponos_error(error: &ClientError) -> String {
match error {
ClientError::Forbidden => tr("kvt.ponos.forbidden"),
ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"),
@@ -628,7 +378,7 @@ fn header(title: String, detail: String, close: fn(&mut App)) -> Div {
)
}
fn label(text: String) -> Div {
pub(super) fn label(text: String) -> Div {
div()
.text_size(px(12.))
.font_weight(FontWeight::SEMIBOLD)
@@ -636,7 +386,7 @@ fn label(text: String) -> Div {
.child(text)
}
fn muted(text: String) -> Div {
pub(super) fn muted(text: String) -> Div {
div()
.w_full()
.py(px(8.))
@@ -645,7 +395,7 @@ fn muted(text: String) -> Div {
.child(text)
}
fn field() -> Div {
pub(super) fn field() -> Div {
h_flex()
.w_full()
.h(px(FIELD_HEIGHT))
@@ -656,7 +406,7 @@ fn field() -> Div {
.bg(theme::popup_hover())
}
fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
pub(super) fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
h_flex()
.id(id)
.h(px(CHIP_HEIGHT))
@@ -680,7 +430,7 @@ fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
.child(label)
}
fn not_linked() -> Div {
pub(super) fn not_linked() -> Div {
v_flex()
.w_full()
.gap(px(8.))
@@ -1,23 +1,19 @@//! Ponos: «Taak maken van bericht» (dialoog) en het paneel «Mijn taken».//! Ponos: «Taak maken van bericht» (dialoog) en gedeelde bouwstenen voor het//!//! bord (`board.rs`). Het oude paneel «Mijn taken» (…-menu) is vervangen door//! Upstream-haak voor het paneel: `views/status_menu.rs` (instellingenmenu).//! de tegel Ponos in de navigatierail.use gpui_kit::assets::IconName;use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};use gpui_kit::component::scroll::ScrollableElement as _;use gpui_kit::component::{h_flex, v_flex};use gpui_kit::component::{h_flex, v_flex};use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::*;use gpui_kit::*;use kvt_sleutels::ClientError;use kvt_sleutels::ClientError;use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource};use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource};use kvt_sleutels::format::iso_date_nl;use kvt_sleutels::ponos::PonosGroup;use kvt_sleutels::ponos::{PonosGroup, PonosTask};use super::modal::{primary_button, secondary_button};use super::modal::{primary_button, secondary_button};use super::{use super::{ Link, base_url, connect, error_text, forget_token, installed, is_demo, link, notice, Link, connect, error_text, forget_token, installed, is_demo, link, notice, token_and_client, open_external, read, token_and_client, update, update,};};use crate::app_state::AppHandle;use crate::app_state::AppHandle;use crate::i18n::tr;use crate::i18n::tr;@@ -26,7 +22,6 @@ use crate::theme::{self, ElevatedSurface as _};use crate::views::widgets::symbol;use crate::views::widgets::symbol;pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog";pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog";pub const KVT_TASKS_PANEL_TAG: &str = "kvt-tasks-panel";/// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag)./// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag).const GROUP_META_KEY: &str = "kvt.ponos.group";const GROUP_META_KEY: &str = "kvt.ponos.group";/// Ponos staat 200 tekens toe in de titel./// Ponos staat 200 tekens toe in de titel.@@ -40,15 +35,6 @@ const SECTION_GAP: f32 = 12.;const CLOSE_SIZE: f32 = 28.;const CLOSE_SIZE: f32 = 28.;const CHIP_HEIGHT: f32 = 28.;const CHIP_HEIGHT: f32 = 28.;const FIELD_HEIGHT: f32 = 36.;const FIELD_HEIGHT: f32 = 36.;const ROW_HEIGHT: f32 = 48.;const LIST_MAX_HEIGHT: f32 = 420.;#[derive(Clone)]pub(crate) enum TasksLoad { Loading, Loaded(Vec<PonosTask>), Failed(ClientError),}#[derive(Clone)]#[derive(Clone)]enum Groups {enum Groups {@@ -195,7 +181,7 @@ impl PonosDialog { Ok(_) => { Ok(_) => { close_create(cx); close_create(cx); notice(tr("kvt.ponos.created"), cx); notice(tr("kvt.ponos.created"), cx); refresh_tasks_if_open(cx); super::board::refresh_board_if_open(cx); } } Err(error) => { Err(error) => { if error == ClientError::Unauthorized { if error == ClientError::Unauthorized {@@ -303,245 +289,9 @@ impl Render for PonosDialog { } }}}// --- Mijn taken -------------------------------------------------------------/// Regel «Mijn taken in Ponos» in het instellingenmenu (`…` rechtsboven).pub fn extend_settings_menu(popup: PopupMenu, cx: &App) -> PopupMenu { if !installed(cx) { return popup; } popup.separator().item( PopupMenuItem::new(tr("kvt.tasks.menu")) .icon(IconName::ClipboardCheck) .on_click(|_, _, cx| open_tasks(cx)), )}pub(crate) fn open_tasks(cx: &mut App) { update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loading)); load_tasks(cx);}fn close_tasks(cx: &mut App) { update(cx, |kvt| kvt.tasks = None);}fn refresh_tasks_if_open(cx: &mut App) { if read(cx, |kvt| kvt.tasks.is_some()).unwrap_or(false) { load_tasks(cx); }}fn load_tasks(cx: &mut App) { if is_demo(cx) { let tasks = read(cx, |kvt| kvt.demo_tasks.clone()).unwrap_or_default(); update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loaded(tasks))); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let loading = runtime::spawn(async move { client.ponos_my_tasks(&token).await }); cx.spawn(async move |cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if result == Err(ClientError::Unauthorized) { forget_token(cx); } let load = match result { Ok(tasks) => TasksLoad::Loaded(tasks), Err(error) => TasksLoad::Failed(error), }; update(cx, |kvt| { if kvt.tasks.is_some() { kvt.tasks = Some(load); } }); }); }) .detach();}fn complete(task: PonosTask, cx: &mut App) { let remove = |kvt: &mut super::Kvt, id: &str| { if let Some(TasksLoad::Loaded(tasks)) = kvt.tasks.as_mut() { tasks.retain(|task| task.id != id); } kvt.demo_tasks.retain(|task| task.id != id); }; if is_demo(cx) { update(cx, |kvt| remove(kvt, &task.id)); notice(tr("kvt.tasks.completed"), cx); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let (group, id) = (task.group().to_owned(), task.id.clone()); let completing = runtime::spawn({ let id = id.clone(); async move { client.ponos_complete_task(&token, &group, &id).await } }); cx.spawn(async move |cx| { let result = completing.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(()) => { update(cx, |kvt| remove(kvt, &id)); notice(tr("kvt.tasks.completed"), cx); } Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } notice(ponos_error(&error), cx); } }); }) .detach();}pub fn render_tasks(cx: &App) -> Option<AnyElement> { let load = read(cx, |kvt| kvt.tasks.clone()).flatten()?; let body = if !matches!(link(cx), Link::Linked(_)) { not_linked().into_any_element() } else { match load { TasksLoad::Loading => muted(tr("kvt.card.loading")).into_any_element(), TasksLoad::Failed(error) => muted(ponos_error(&error)).into_any_element(), TasksLoad::Loaded(tasks) if tasks.is_empty() => { muted(tr("kvt.tasks.empty")).into_any_element() } TasksLoad::Loaded(tasks) => v_flex() .id("kvt-tasks-list") .w_full() .max_h(px(LIST_MAX_HEIGHT)) .overflow_y_scrollbar() .children( tasks .into_iter() .enumerate() .map(|(index, task)| task_row(index, task)), ) .into_any_element(), } }; let ponos = format!("{}/ponos/", base_url()); Some( layer("kvt-tasks", |cx| close_tasks(cx)) .child( panel(KVT_TASKS_PANEL_TAG) .child(header(tr("kvt.tasks.title"), String::new(), |cx| { close_tasks(cx) })) .child(body) .child( h_flex() .w_full() .gap(px(8.)) .child( secondary_button( "kvt-tasks-open", "open_in_new", tr("kvt.tasks.open_ponos"), ) .on_click(move |_, _, cx| open_external(&ponos, cx)), ) .child( secondary_button( "kvt-tasks-refresh", "refresh", tr("kvt.card.refresh"), ) .on_click(|_, _, cx| open_tasks(cx)), ), ), ) .into_any_element(), )}fn task_row(index: usize, task: PonosTask) -> AnyElement { let today = chrono::Local::now() .date_naive() .format("%Y-%m-%d") .to_string(); let overdue = !task.due_date.is_empty() && task.due_date.as_str() < today.as_str(); let mut detail = Vec::new(); if !task.home_group_name.is_empty() { detail.push(task.home_group_name.clone()); } if task.status == "in_progress" { detail.push(tr("kvt.tasks.in_progress")); } let due = iso_date_nl(&task.due_date); let url = task.url(&base_url()); let done = task.clone(); h_flex() .id(ElementId::Name(format!("kvt-task-{index}").into())) .w_full() .h(px(ROW_HEIGHT)) .flex_none() .px(px(8.)) .gap(px(10.)) .items_center() .rounded(px(6.)) .cursor_pointer() .hover(|row| row.bg(theme::popup_hover())) .on_click(move |_, _, cx| open_external(&url, cx)) .child( div() .id(ElementId::Name(format!("kvt-task-done-{index}").into())) .size(px(CLOSE_SIZE)) .flex_none() .flex() .items_center() .justify_center() .rounded_full() .hover(|button| button.bg(theme::row_hover())) .on_click(move |_, _, cx| { cx.stop_propagation(); complete(done.clone(), cx); }) .child(symbol("check_circle", 18., theme::text_muted())), ) .child( v_flex() .flex_1() .min_w_0() .child( div() .truncate() .text_size(px(13.)) .text_color(theme::text()) .child(task.title.clone()), ) .when(!detail.is_empty(), |column| { column.child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(detail.join(" · ")), ) }), ) .children(due.map(|due| { div() .flex_none() .text_size(px(12.)) .text_color(if overdue { theme::red_soft() } else { theme::text_muted() }) .child(due) })) .into_any_element()}// --- gedeelde bouwstenen ----------------------------------------------------// --- gedeelde bouwstenen ----------------------------------------------------fn ponos_error(error: &ClientError) -> String {pub(super) fn ponos_error(error: &ClientError) -> String { match error { match error { ClientError::Forbidden => tr("kvt.ponos.forbidden"), ClientError::Forbidden => tr("kvt.ponos.forbidden"), ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"), ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"),@@ -628,7 +378,7 @@ fn header(title: String, detail: String, close: fn(&mut App)) -> Div { ) )}}fn label(text: String) -> Div {pub(super) fn label(text: String) -> Div { div() div() .text_size(px(12.)) .text_size(px(12.)) .font_weight(FontWeight::SEMIBOLD) .font_weight(FontWeight::SEMIBOLD)@@ -636,7 +386,7 @@ fn label(text: String) -> Div { .child(text) .child(text)}}fn muted(text: String) -> Div {pub(super) fn muted(text: String) -> Div { div() div() .w_full() .w_full() .py(px(8.)) .py(px(8.))@@ -645,7 +395,7 @@ fn muted(text: String) -> Div { .child(text) .child(text)}}fn field() -> Div {pub(super) fn field() -> Div { h_flex() h_flex() .w_full() .w_full() .h(px(FIELD_HEIGHT)) .h(px(FIELD_HEIGHT))@@ -656,7 +406,7 @@ fn field() -> Div { .bg(theme::popup_hover()) .bg(theme::popup_hover())}}fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {pub(super) fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> { h_flex() h_flex() .id(id) .id(id) .h(px(CHIP_HEIGHT)) .h(px(CHIP_HEIGHT))@@ -680,7 +430,7 @@ fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> { .child(label) .child(label)}}fn not_linked() -> Div {pub(super) fn not_linked() -> Div { v_flex() v_flex() .w_full() .w_full() .gap(px(8.)) .gap(px(8.))@@ -0,0 +1,680 @@
//! Asclepius: «Nieuw ticket maken» in de app, met de velden van het webformulier.
//! Ook voor «Ticket maken in Asclepius» in het berichtmenu, dan vooraf ingevuld
//! met het bericht; vermeldingen worden `@naam:domein` zoals Asclepius ze kent.
use std::path::PathBuf;
use gpui_kit::component::checkbox::Checkbox;
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::{Disableable as _, h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use kvt_sleutels::ClientError;
use kvt_sleutels::asclepius::MessageSource;
use kvt_sleutels::tickets::{
ATTACHMENT_MAX_BYTES, ATTACHMENTS_MAX, DESCRIPTION_MAX, Lookups, NewAttachment, NewTicket,
TITLE_MAX, mentions_to_asclepius, mime_for, parse_participants, priority_from_flags,
};
use super::modal::{primary_button, secondary_button};
use super::tasks::{chip, field, label, muted, not_linked};
use super::tickets::ticket_error;
use super::{Link, forget_token, installed, is_demo, link, notice, token_and_client, update};
use crate::i18n::{tr, tr_args};
use crate::runtime;
use crate::theme::{self, ElevatedSurface as _};
use crate::views::widgets::symbol;
pub const KVT_TICKET_FORM_TAG: &str = "kvt-asclepius-form";
const BACKDROP_OPACITY: f32 = 0.55;
const PANEL_WIDTH: f32 = 560.;
const PANEL_MARGIN: f32 = 32.;
const PANEL_RADIUS: f32 = 10.;
const PANEL_PADDING: f32 = 16.;
const SECTION_GAP: f32 = 10.;
const CLOSE_SIZE: f32 = 28.;
#[derive(Clone)]
enum LookupState {
Loading,
Loaded(Lookups),
Failed(ClientError),
}
struct PickedFile {
name: String,
size: usize,
attachment: NewAttachment,
}
pub struct TicketForm {
source: Option<MessageSource>,
lookups: LookupState,
category: Option<String>,
subcategory: Option<String>,
title: Entity<InputState>,
description: Entity<TextareaState>,
participants: Entity<InputState>,
blocked: bool,
fully_blocked: bool,
files: Vec<PickedFile>,
saving: bool,
error: Option<String>,
}
/// Opent het formulier; `source` is het bericht bij «Ticket maken in Asclepius».
pub(super) fn open_new(source: Option<MessageSource>, window: &mut Window, cx: &mut App) {
if !installed(cx) {
return;
}
let form = cx.new(|cx| TicketForm::new(source, window, cx));
update(cx, |kvt| kvt.ticket_form = Some(form.clone()));
if is_demo(cx) {
form.update(cx, |form, cx| form.set_lookups(Ok(demo_lookups()), cx));
return;
}
let Some((token, client)) = token_and_client(cx) else {
return;
};
let loading = runtime::spawn(async move { client.asclepius_lookups(&token).await });
let weak = form.downgrade();
cx.spawn(async move |cx| {
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| {
if result == Err(ClientError::Unauthorized) {
forget_token(cx);
}
weak.update(cx, |form, cx| form.set_lookups(result, cx))
.ok();
});
})
.detach();
}
fn tr_with(key: &str, name: &str, value: String) -> String {
tr_args(
key,
&std::collections::HashMap::from([(name.to_owned(), value)]),
)
}
fn close(cx: &mut App) {
update(cx, |kvt| kvt.ticket_form = None);
}
/// Knop «Nieuw ticket» in de kop van de tegel.
pub(super) fn new_ticket_button<T: 'static>(cx: &mut Context<T>) -> Option<Stateful<Div>> {
matches!(link(cx), Link::Linked(_)).then(|| {
primary_button("kvt-tickets-new", tr("kvt.tickets.new"))
.on_click(|_, window, cx| open_new(None, window, cx))
})
}
/// Beschrijving uit het bericht, met de vermeldingen als Asclepius-token.
fn prefilled_description(source: &MessageSource) -> String {
mentions_to_asclepius(&source.description(DESCRIPTION_MAX), &source.mentions)
}
impl TicketForm {
fn new(source: Option<MessageSource>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let title_text = source
.as_ref()
.map(|source| source.title(TITLE_MAX))
.unwrap_or_default();
let description_text = source
.as_ref()
.map(prefilled_description)
.unwrap_or_default();
let title = cx.new(|cx| {
InputState::new(window, cx)
.placeholder(tr("kvt.tickets.form.title_placeholder"))
.default_value(title_text)
});
let description = cx.new(|cx| {
TextareaState::new(window, cx)
.auto_grow(4, 10)
.placeholder(tr("kvt.tickets.form.description_placeholder"))
.default_value(description_text)
});
let participants = cx.new(|cx| {
InputState::new(window, cx).placeholder(tr("kvt.tickets.form.participants_placeholder"))
});
title.update(cx, |input, cx| input.focus(window, cx));
TicketForm {
source,
lookups: LookupState::Loading,
category: None,
subcategory: None,
title,
description,
participants,
blocked: false,
fully_blocked: false,
files: Vec::new(),
saving: false,
error: None,
}
}
fn set_lookups(&mut self, result: Result<Lookups, ClientError>, cx: &mut Context<Self>) {
self.lookups = match result {
Ok(lookups) => LookupState::Loaded(lookups),
Err(error) => LookupState::Failed(error),
};
cx.notify();
}
fn pick_files(&mut self, cx: &mut Context<Self>) {
let receiver = cx.prompt_for_paths(PathPromptOptions {
files: true,
directories: false,
multiple: true,
prompt: None,
});
cx.spawn(async move |this, cx| {
let Ok(Ok(Some(paths))) = receiver.await else {
return;
};
let reading = runtime::spawn(async move { read_files(paths) });
let read = reading.await.unwrap_or_default();
this.update(cx, |this, cx| {
for file in read {
match file {
Ok(file) if this.files.len() < ATTACHMENTS_MAX => this.files.push(file),
Ok(_) => {
this.error = Some(tr_with(
"kvt.tickets.form.too_many_files",
"max",
ATTACHMENTS_MAX.to_string(),
))
}
Err(name) => {
this.error =
Some(tr_with("kvt.tickets.form.file_too_large", "name", name))
}
}
}
cx.notify();
})
.ok();
})
.detach();
}
fn save(&mut self, cx: &mut Context<Self>) {
if self.saving {
return;
}
let title = self.title.read(cx).value().trim().to_owned();
let description = self.description.read(cx).value().trim().to_owned();
let participants_text = self.participants.read(cx).value().to_string();
let Some(category) = self.category.clone() else {
self.error = Some(tr("kvt.tickets.form.pick_category"));
cx.notify();
return;
};
if title.is_empty() || description.is_empty() {
self.error = Some(tr("kvt.tickets.form.fill_in"));
cx.notify();
return;
}
let participant_emails = match parse_participants(&participants_text) {
Ok(emails) => emails,
Err(bad) => {
self.error = Some(tr_with("kvt.tickets.form.bad_email", "email", bad));
cx.notify();
return;
}
};
let ticket = NewTicket {
title,
category,
subcategory: self.subcategory.clone(),
description,
priority: priority_from_flags(self.blocked, self.fully_blocked),
participant_emails,
attachments: self
.files
.iter()
.map(|file| file.attachment.clone())
.collect(),
};
if is_demo(cx) {
close(cx);
notice(
tr_with("kvt.tickets.form.created", "id", "4103".to_owned()),
cx,
);
return;
}
let Some((token, client)) = token_and_client(cx) else {
return;
};
self.saving = true;
self.error = None;
cx.notify();
let creating =
runtime::spawn(async move { client.asclepius_create(&token, &ticket).await });
cx.spawn(async move |this, cx| {
let result = creating.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| match result {
Ok(id) => {
close(cx);
notice(
tr_with("kvt.tickets.form.created", "id", id.to_string()),
cx,
);
super::tickets::created(id, cx);
}
Err(error) => {
if error == ClientError::Unauthorized {
forget_token(cx);
}
this.update(cx, |this, cx| {
this.saving = false;
this.error = Some(ticket_error(&error));
cx.notify();
})
.ok();
}
});
})
.detach();
}
fn categories(&self, cx: &mut Context<Self>) -> AnyElement {
let lookups = match &self.lookups {
LookupState::Loading => return muted(tr("kvt.card.loading")).into_any_element(),
LookupState::Failed(error) => return muted(ticket_error(error)).into_any_element(),
LookupState::Loaded(lookups) => lookups,
};
let categories = h_flex().w_full().flex_wrap().gap(px(6.)).children(
lookups
.form_categories()
.into_iter()
.enumerate()
.map(|(index, category)| {
let selected = self.category.as_deref() == Some(category.as_str());
chip(
format!("kvt-ticket-category-{index}").into(),
category.clone(),
selected,
)
.on_click(cx.listener(move |this, _, _, cx| {
if this.category.as_deref() != Some(category.as_str()) {
this.category = Some(category.clone());
this.subcategory = None;
}
this.error = None;
cx.notify();
}))
}),
);
let subcategories = self
.category
.as_deref()
.map(|category| lookups.subcategories_of(category).to_vec())
.unwrap_or_default();
v_flex()
.w_full()
.gap(px(SECTION_GAP))
.child(categories)
.when(!subcategories.is_empty(), |column| {
column
.child(label(tr("kvt.tickets.form.subcategory")))
.child(
h_flex().w_full().flex_wrap().gap(px(6.)).children(
subcategories
.into_iter()
.enumerate()
.map(|(index, subcategory)| {
let selected =
self.subcategory.as_deref() == Some(subcategory.as_str());
chip(
format!("kvt-ticket-subcategory-{index}").into(),
subcategory.clone(),
selected,
)
.on_click(cx.listener(
move |this, _, _, cx| {
// Nogmaals klikken haalt de keuze weg (subcategorie is optioneel).
this.subcategory =
(!selected).then(|| subcategory.clone());
cx.notify();
},
))
}),
),
)
})
.into_any_element()
}
fn files(&self, cx: &mut Context<Self>) -> Div {
h_flex()
.w_full()
.flex_wrap()
.gap(px(6.))
.items_center()
.children(self.files.iter().enumerate().map(|(index, file)| {
h_flex()
.id(ElementId::Name(format!("kvt-ticket-file-{index}").into()))
.h(px(28.))
.pl(px(10.))
.pr(px(4.))
.gap(px(6.))
.items_center()
.rounded(px(6.))
.bg(theme::popup_hover())
.text_size(px(12.))
.child(symbol("attach_file", 14., theme::text_muted()))
.child(format!("{} ({})", file.name, size_label(file.size)))
.child(
div()
.id(ElementId::Name(
format!("kvt-ticket-file-remove-{index}").into(),
))
.size(px(20.))
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.hover(|button| button.bg(theme::row_hover()))
.on_click(cx.listener(move |this, _, _, cx| {
if index < this.files.len() {
this.files.remove(index);
}
cx.notify();
}))
.child(symbol("close", 12., theme::text_muted())),
)
}))
.when(self.files.len() < ATTACHMENTS_MAX, |row| {
row.child(
secondary_button(
"kvt-ticket-add-file",
"attach_file",
tr("kvt.tickets.form.add_files"),
)
.on_click(cx.listener(|this, _, _, cx| this.pick_files(cx))),
)
})
}
}
fn read_files(paths: Vec<PathBuf>) -> Vec<Result<PickedFile, String>> {
paths
.into_iter()
.filter_map(|path| {
let name = path.file_name()?.to_string_lossy().into_owned();
let size = std::fs::metadata(&path).ok()?.len() as usize;
if size > ATTACHMENT_MAX_BYTES {
return Some(Err(name));
}
let data = std::fs::read(&path).ok()?;
Some(Ok(PickedFile {
size: data.len(),
attachment: NewAttachment {
mime: mime_for(&name).to_owned(),
filename: name.clone(),
data,
},
name,
}))
})
.collect()
}
fn size_label(bytes: usize) -> String {
if bytes >= 1024 * 1024 {
format!("{:.1} MB", bytes as f64 / (1024. * 1024.)).replace('.', ",")
} else {
format!("{} kB", bytes.div_ceil(1024).max(1))
}
}
impl Render for TicketForm {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let linked = matches!(link(cx), Link::Linked(_));
let ready = linked && matches!(self.lookups, LookupState::Loaded(_));
let detail = self
.source
.as_ref()
.filter(|source| !source.sender.is_empty())
.map(|source| format!("{} · {}", source.sender, source.sent_at))
.unwrap_or_default();
let blocked = self.blocked;
let body = if !linked {
v_flex().w_full().child(not_linked())
} else {
v_flex()
.w_full()
.gap(px(SECTION_GAP))
.child(label(tr("kvt.tickets.form.title")))
.child(
field().child(
div()
.flex_1()
.child(Input::new(&self.title).appearance(false).bordered(false)),
),
)
.child(label(tr("kvt.tickets.form.category")))
.child(self.categories(cx))
.child(label(tr("kvt.tickets.form.description")))
.child(Textarea::new(&self.description))
.child(
Checkbox::new("kvt-ticket-blocked")
.label(tr("kvt.tickets.form.blocked"))
.checked(self.blocked)
.on_click(cx.listener(|this, checked: &bool, _, cx| {
this.blocked = *checked;
if !*checked {
this.fully_blocked = false;
}
cx.notify();
})),
)
.child(
Checkbox::new("kvt-ticket-fully-blocked")
.label(tr("kvt.tickets.form.fully_blocked"))
.checked(self.fully_blocked)
.disabled(!blocked)
.on_click(cx.listener(|this, checked: &bool, _, cx| {
this.fully_blocked = *checked && this.blocked;
cx.notify();
})),
)
.child(label(tr("kvt.tickets.form.participants")))
.child(
field().child(
div().flex_1().child(
Input::new(&self.participants)
.appearance(false)
.bordered(false),
),
),
)
.child(
div()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(tr("kvt.tickets.form.participants_hint")),
)
.child(label(tr("kvt.tickets.form.attachments")))
.child(self.files(cx))
};
div()
.id("kvt-ticket-form-layer")
.absolute()
.top_0()
.left_0()
.size_full()
.flex()
.items_center()
.justify_center()
.child(
div()
.id("kvt-ticket-form-backdrop")
.absolute()
.top_0()
.left_0()
.size_full()
.bg(black().opacity(BACKDROP_OPACITY))
.occlude()
.on_click(|_, _, cx| close(cx)),
)
.child(
v_flex()
.id("kvt-ticket-form-panel")
.debug_selector(|| KVT_TICKET_FORM_TAG.into())
.w(px(PANEL_WIDTH))
.max_w(relative(1.))
.max_h(relative(0.92))
.m(px(PANEL_MARGIN))
.p(px(PANEL_PADDING))
.gap(px(SECTION_GAP))
.rounded(px(PANEL_RADIUS))
.dialog_surface()
.text_color(theme::text())
.overflow_y_scroll()
.occlude()
.on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| {
if event.keystroke.key == "escape" {
close(cx);
}
}))
.child(
h_flex()
.w_full()
.items_center()
.gap(px(SECTION_GAP))
.child(
v_flex()
.flex_1()
.min_w_0()
.child(
div()
.text_size(px(15.))
.font_weight(FontWeight::SEMIBOLD)
.child(tr("kvt.tickets.form.heading")),
)
.when(!detail.is_empty(), |column| {
column.child(
div()
.truncate()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(detail),
)
}),
)
.child(
div()
.id("kvt-ticket-form-close")
.size(px(CLOSE_SIZE))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.hover(|button| button.bg(theme::popup_hover()))
.on_click(|_, _, cx| close(cx))
.child(symbol("close", 16., theme::text_muted())),
),
)
.child(body)
.children(self.error.clone().map(|error| {
div()
.text_size(px(13.))
.text_color(theme::red_soft())
.child(error)
}))
.child(
h_flex()
.w_full()
.gap(px(8.))
.justify_end()
.child(
secondary_button(
"kvt-ticket-form-cancel",
"close",
tr("common.cancel"),
)
.on_click(|_, _, cx| close(cx)),
)
.when(ready, |row| {
row.child(
primary_button(
"kvt-ticket-form-submit",
tr(if self.saving {
"kvt.tickets.sending"
} else {
"kvt.tickets.form.submit"
}),
)
.on_click(cx.listener(|this, _, _, cx| this.save(cx))),
)
}),
),
)
}
}
pub(super) fn demo_lookups() -> Lookups {
let mut lookups = Lookups {
categories: [
"Hardware",
"Hardware bestellen",
"Software",
"Rechten en toegang",
"Indiensttreding",
]
.map(str::to_owned)
.to_vec(),
..Lookups::default()
};
lookups.subcategories.insert(
"Hardware".to_owned(),
["Laptop", "Monitor", "Printer"].map(str::to_owned).to_vec(),
);
lookups
}
#[cfg(test)]
mod tests {
use super::{demo_lookups, prefilled_description, size_label};
use kvt_sleutels::asclepius::MessageSource;
#[test]
fn message_mentions_become_asclepius_tokens() {
let source = MessageSource {
text: "@Jonas Ortega kun jij hiernaar kijken?".to_owned(),
sender: "Dana Demo".to_owned(),
sent_at: "15 jan 2026 13:39".to_owned(),
link: None,
mentions: vec![(
"Jonas Ortega".to_owned(),
"jonas.ortega@example.com".to_owned(),
)],
};
let description = prefilled_description(&source);
assert!(description.starts_with("> @jonas.ortega:examplecom kun jij"));
}
#[test]
fn ict_only_categories_are_not_offered() {
assert!(
!demo_lookups()
.form_categories()
.contains(&"Indiensttreding".to_owned())
);
}
#[test]
fn sizes_are_short_and_dutch() {
assert_eq!(size_label(500), "1 kB");
assert_eq!(size_label(3 * 1024 * 1024 + 512 * 1024), "3,5 MB");
}
}
@@ -0,0 +1,680 @@//! Asclepius: «Nieuw ticket maken» in de app, met de velden van het webformulier.//! Ook voor «Ticket maken in Asclepius» in het berichtmenu, dan vooraf ingevuld//! met het bericht; vermeldingen worden `@naam:domein` zoals Asclepius ze kent.use std::path::PathBuf;use gpui_kit::component::checkbox::Checkbox;use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};use gpui_kit::component::{Disableable as _, h_flex, v_flex};use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::*;use kvt_sleutels::ClientError;use kvt_sleutels::asclepius::MessageSource;use kvt_sleutels::tickets::{ ATTACHMENT_MAX_BYTES, ATTACHMENTS_MAX, DESCRIPTION_MAX, Lookups, NewAttachment, NewTicket, TITLE_MAX, mentions_to_asclepius, mime_for, parse_participants, priority_from_flags,};use super::modal::{primary_button, secondary_button};use super::tasks::{chip, field, label, muted, not_linked};use super::tickets::ticket_error;use super::{Link, forget_token, installed, is_demo, link, notice, token_and_client, update};use crate::i18n::{tr, tr_args};use crate::runtime;use crate::theme::{self, ElevatedSurface as _};use crate::views::widgets::symbol;pub const KVT_TICKET_FORM_TAG: &str = "kvt-asclepius-form";const BACKDROP_OPACITY: f32 = 0.55;const PANEL_WIDTH: f32 = 560.;const PANEL_MARGIN: f32 = 32.;const PANEL_RADIUS: f32 = 10.;const PANEL_PADDING: f32 = 16.;const SECTION_GAP: f32 = 10.;const CLOSE_SIZE: f32 = 28.;#[derive(Clone)]enum LookupState { Loading, Loaded(Lookups), Failed(ClientError),}struct PickedFile { name: String, size: usize, attachment: NewAttachment,}pub struct TicketForm { source: Option<MessageSource>, lookups: LookupState, category: Option<String>, subcategory: Option<String>, title: Entity<InputState>, description: Entity<TextareaState>, participants: Entity<InputState>, blocked: bool, fully_blocked: bool, files: Vec<PickedFile>, saving: bool, error: Option<String>,}/// Opent het formulier; `source` is het bericht bij «Ticket maken in Asclepius».pub(super) fn open_new(source: Option<MessageSource>, window: &mut Window, cx: &mut App) { if !installed(cx) { return; } let form = cx.new(|cx| TicketForm::new(source, window, cx)); update(cx, |kvt| kvt.ticket_form = Some(form.clone())); if is_demo(cx) { form.update(cx, |form, cx| form.set_lookups(Ok(demo_lookups()), cx)); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let loading = runtime::spawn(async move { client.asclepius_lookups(&token).await }); let weak = form.downgrade(); cx.spawn(async move |cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if result == Err(ClientError::Unauthorized) { forget_token(cx); } weak.update(cx, |form, cx| form.set_lookups(result, cx)) .ok(); }); }) .detach();}fn tr_with(key: &str, name: &str, value: String) -> String { tr_args( key, &std::collections::HashMap::from([(name.to_owned(), value)]), )}fn close(cx: &mut App) { update(cx, |kvt| kvt.ticket_form = None);}/// Knop «Nieuw ticket» in de kop van de tegel.pub(super) fn new_ticket_button<T: 'static>(cx: &mut Context<T>) -> Option<Stateful<Div>> { matches!(link(cx), Link::Linked(_)).then(|| { primary_button("kvt-tickets-new", tr("kvt.tickets.new")) .on_click(|_, window, cx| open_new(None, window, cx)) })}/// Beschrijving uit het bericht, met de vermeldingen als Asclepius-token.fn prefilled_description(source: &MessageSource) -> String { mentions_to_asclepius(&source.description(DESCRIPTION_MAX), &source.mentions)}impl TicketForm { fn new(source: Option<MessageSource>, window: &mut Window, cx: &mut Context<Self>) -> Self { let title_text = source .as_ref() .map(|source| source.title(TITLE_MAX)) .unwrap_or_default(); let description_text = source .as_ref() .map(prefilled_description) .unwrap_or_default(); let title = cx.new(|cx| { InputState::new(window, cx) .placeholder(tr("kvt.tickets.form.title_placeholder")) .default_value(title_text) }); let description = cx.new(|cx| { TextareaState::new(window, cx) .auto_grow(4, 10) .placeholder(tr("kvt.tickets.form.description_placeholder")) .default_value(description_text) }); let participants = cx.new(|cx| { InputState::new(window, cx).placeholder(tr("kvt.tickets.form.participants_placeholder")) }); title.update(cx, |input, cx| input.focus(window, cx)); TicketForm { source, lookups: LookupState::Loading, category: None, subcategory: None, title, description, participants, blocked: false, fully_blocked: false, files: Vec::new(), saving: false, error: None, } } fn set_lookups(&mut self, result: Result<Lookups, ClientError>, cx: &mut Context<Self>) { self.lookups = match result { Ok(lookups) => LookupState::Loaded(lookups), Err(error) => LookupState::Failed(error), }; cx.notify(); } fn pick_files(&mut self, cx: &mut Context<Self>) { let receiver = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: true, prompt: None, }); cx.spawn(async move |this, cx| { let Ok(Ok(Some(paths))) = receiver.await else { return; }; let reading = runtime::spawn(async move { read_files(paths) }); let read = reading.await.unwrap_or_default(); this.update(cx, |this, cx| { for file in read { match file { Ok(file) if this.files.len() < ATTACHMENTS_MAX => this.files.push(file), Ok(_) => { this.error = Some(tr_with( "kvt.tickets.form.too_many_files", "max", ATTACHMENTS_MAX.to_string(), )) } Err(name) => { this.error = Some(tr_with("kvt.tickets.form.file_too_large", "name", name)) } } } cx.notify(); }) .ok(); }) .detach(); } fn save(&mut self, cx: &mut Context<Self>) { if self.saving { return; } let title = self.title.read(cx).value().trim().to_owned(); let description = self.description.read(cx).value().trim().to_owned(); let participants_text = self.participants.read(cx).value().to_string(); let Some(category) = self.category.clone() else { self.error = Some(tr("kvt.tickets.form.pick_category")); cx.notify(); return; }; if title.is_empty() || description.is_empty() { self.error = Some(tr("kvt.tickets.form.fill_in")); cx.notify(); return; } let participant_emails = match parse_participants(&participants_text) { Ok(emails) => emails, Err(bad) => { self.error = Some(tr_with("kvt.tickets.form.bad_email", "email", bad)); cx.notify(); return; } }; let ticket = NewTicket { title, category, subcategory: self.subcategory.clone(), description, priority: priority_from_flags(self.blocked, self.fully_blocked), participant_emails, attachments: self .files .iter() .map(|file| file.attachment.clone()) .collect(), }; if is_demo(cx) { close(cx); notice( tr_with("kvt.tickets.form.created", "id", "4103".to_owned()), cx, ); return; } let Some((token, client)) = token_and_client(cx) else { return; }; self.saving = true; self.error = None; cx.notify(); let creating = runtime::spawn(async move { client.asclepius_create(&token, &ticket).await }); cx.spawn(async move |this, cx| { let result = creating.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(id) => { close(cx); notice( tr_with("kvt.tickets.form.created", "id", id.to_string()), cx, ); super::tickets::created(id, cx); } Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } this.update(cx, |this, cx| { this.saving = false; this.error = Some(ticket_error(&error)); cx.notify(); }) .ok(); } }); }) .detach(); } fn categories(&self, cx: &mut Context<Self>) -> AnyElement { let lookups = match &self.lookups { LookupState::Loading => return muted(tr("kvt.card.loading")).into_any_element(), LookupState::Failed(error) => return muted(ticket_error(error)).into_any_element(), LookupState::Loaded(lookups) => lookups, }; let categories = h_flex().w_full().flex_wrap().gap(px(6.)).children( lookups .form_categories() .into_iter() .enumerate() .map(|(index, category)| { let selected = self.category.as_deref() == Some(category.as_str()); chip( format!("kvt-ticket-category-{index}").into(), category.clone(), selected, ) .on_click(cx.listener(move |this, _, _, cx| { if this.category.as_deref() != Some(category.as_str()) { this.category = Some(category.clone()); this.subcategory = None; } this.error = None; cx.notify(); })) }), ); let subcategories = self .category .as_deref() .map(|category| lookups.subcategories_of(category).to_vec()) .unwrap_or_default(); v_flex() .w_full() .gap(px(SECTION_GAP)) .child(categories) .when(!subcategories.is_empty(), |column| { column .child(label(tr("kvt.tickets.form.subcategory"))) .child( h_flex().w_full().flex_wrap().gap(px(6.)).children( subcategories .into_iter() .enumerate() .map(|(index, subcategory)| { let selected = self.subcategory.as_deref() == Some(subcategory.as_str()); chip( format!("kvt-ticket-subcategory-{index}").into(), subcategory.clone(), selected, ) .on_click(cx.listener( move |this, _, _, cx| { // Nogmaals klikken haalt de keuze weg (subcategorie is optioneel). this.subcategory = (!selected).then(|| subcategory.clone()); cx.notify(); }, )) }), ), ) }) .into_any_element() } fn files(&self, cx: &mut Context<Self>) -> Div { h_flex() .w_full() .flex_wrap() .gap(px(6.)) .items_center() .children(self.files.iter().enumerate().map(|(index, file)| { h_flex() .id(ElementId::Name(format!("kvt-ticket-file-{index}").into())) .h(px(28.)) .pl(px(10.)) .pr(px(4.)) .gap(px(6.)) .items_center() .rounded(px(6.)) .bg(theme::popup_hover()) .text_size(px(12.)) .child(symbol("attach_file", 14., theme::text_muted())) .child(format!("{} ({})", file.name, size_label(file.size))) .child( div() .id(ElementId::Name( format!("kvt-ticket-file-remove-{index}").into(), )) .size(px(20.)) .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::row_hover())) .on_click(cx.listener(move |this, _, _, cx| { if index < this.files.len() { this.files.remove(index); } cx.notify(); })) .child(symbol("close", 12., theme::text_muted())), ) })) .when(self.files.len() < ATTACHMENTS_MAX, |row| { row.child( secondary_button( "kvt-ticket-add-file", "attach_file", tr("kvt.tickets.form.add_files"), ) .on_click(cx.listener(|this, _, _, cx| this.pick_files(cx))), ) }) }}fn read_files(paths: Vec<PathBuf>) -> Vec<Result<PickedFile, String>> { paths .into_iter() .filter_map(|path| { let name = path.file_name()?.to_string_lossy().into_owned(); let size = std::fs::metadata(&path).ok()?.len() as usize; if size > ATTACHMENT_MAX_BYTES { return Some(Err(name)); } let data = std::fs::read(&path).ok()?; Some(Ok(PickedFile { size: data.len(), attachment: NewAttachment { mime: mime_for(&name).to_owned(), filename: name.clone(), data, }, name, })) }) .collect()}fn size_label(bytes: usize) -> String { if bytes >= 1024 * 1024 { format!("{:.1} MB", bytes as f64 / (1024. * 1024.)).replace('.', ",") } else { format!("{} kB", bytes.div_ceil(1024).max(1)) }}impl Render for TicketForm { fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let linked = matches!(link(cx), Link::Linked(_)); let ready = linked && matches!(self.lookups, LookupState::Loaded(_)); let detail = self .source .as_ref() .filter(|source| !source.sender.is_empty()) .map(|source| format!("{} · {}", source.sender, source.sent_at)) .unwrap_or_default(); let blocked = self.blocked; let body = if !linked { v_flex().w_full().child(not_linked()) } else { v_flex() .w_full() .gap(px(SECTION_GAP)) .child(label(tr("kvt.tickets.form.title"))) .child( field().child( div() .flex_1() .child(Input::new(&self.title).appearance(false).bordered(false)), ), ) .child(label(tr("kvt.tickets.form.category"))) .child(self.categories(cx)) .child(label(tr("kvt.tickets.form.description"))) .child(Textarea::new(&self.description)) .child( Checkbox::new("kvt-ticket-blocked") .label(tr("kvt.tickets.form.blocked")) .checked(self.blocked) .on_click(cx.listener(|this, checked: &bool, _, cx| { this.blocked = *checked; if !*checked { this.fully_blocked = false; } cx.notify(); })), ) .child( Checkbox::new("kvt-ticket-fully-blocked") .label(tr("kvt.tickets.form.fully_blocked")) .checked(self.fully_blocked) .disabled(!blocked) .on_click(cx.listener(|this, checked: &bool, _, cx| { this.fully_blocked = *checked && this.blocked; cx.notify(); })), ) .child(label(tr("kvt.tickets.form.participants"))) .child( field().child( div().flex_1().child( Input::new(&self.participants) .appearance(false) .bordered(false), ), ), ) .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(tr("kvt.tickets.form.participants_hint")), ) .child(label(tr("kvt.tickets.form.attachments"))) .child(self.files(cx)) }; div() .id("kvt-ticket-form-layer") .absolute() .top_0() .left_0() .size_full() .flex() .items_center() .justify_center() .child( div() .id("kvt-ticket-form-backdrop") .absolute() .top_0() .left_0() .size_full() .bg(black().opacity(BACKDROP_OPACITY)) .occlude() .on_click(|_, _, cx| close(cx)), ) .child( v_flex() .id("kvt-ticket-form-panel") .debug_selector(|| KVT_TICKET_FORM_TAG.into()) .w(px(PANEL_WIDTH)) .max_w(relative(1.)) .max_h(relative(0.92)) .m(px(PANEL_MARGIN)) .p(px(PANEL_PADDING)) .gap(px(SECTION_GAP)) .rounded(px(PANEL_RADIUS)) .dialog_surface() .text_color(theme::text()) .overflow_y_scroll() .occlude() .on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| { if event.keystroke.key == "escape" { close(cx); } })) .child( h_flex() .w_full() .items_center() .gap(px(SECTION_GAP)) .child( v_flex() .flex_1() .min_w_0() .child( div() .text_size(px(15.)) .font_weight(FontWeight::SEMIBOLD) .child(tr("kvt.tickets.form.heading")), ) .when(!detail.is_empty(), |column| { column.child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(detail), ) }), ) .child( div() .id("kvt-ticket-form-close") .size(px(CLOSE_SIZE)) .flex_none() .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::popup_hover())) .on_click(|_, _, cx| close(cx)) .child(symbol("close", 16., theme::text_muted())), ), ) .child(body) .children(self.error.clone().map(|error| { div() .text_size(px(13.)) .text_color(theme::red_soft()) .child(error) })) .child( h_flex() .w_full() .gap(px(8.)) .justify_end() .child( secondary_button( "kvt-ticket-form-cancel", "close", tr("common.cancel"), ) .on_click(|_, _, cx| close(cx)), ) .when(ready, |row| { row.child( primary_button( "kvt-ticket-form-submit", tr(if self.saving { "kvt.tickets.sending" } else { "kvt.tickets.form.submit" }), ) .on_click(cx.listener(|this, _, _, cx| this.save(cx))), ) }), ), ) }}pub(super) fn demo_lookups() -> Lookups { let mut lookups = Lookups { categories: [ "Hardware", "Hardware bestellen", "Software", "Rechten en toegang", "Indiensttreding", ] .map(str::to_owned) .to_vec(), ..Lookups::default() }; lookups.subcategories.insert( "Hardware".to_owned(), ["Laptop", "Monitor", "Printer"].map(str::to_owned).to_vec(), ); lookups}#[cfg(test)]mod tests { use super::{demo_lookups, prefilled_description, size_label}; use kvt_sleutels::asclepius::MessageSource; #[test] fn message_mentions_become_asclepius_tokens() { let source = MessageSource { text: "@Jonas Ortega kun jij hiernaar kijken?".to_owned(), sender: "Dana Demo".to_owned(), sent_at: "15 jan 2026 13:39".to_owned(), link: None, mentions: vec![( "Jonas Ortega".to_owned(), "jonas.ortega@example.com".to_owned(), )], }; let description = prefilled_description(&source); assert!(description.starts_with("> @jonas.ortega:examplecom kun jij")); } #[test] fn ict_only_categories_are_not_offered() { assert!( !demo_lookups() .form_categories() .contains(&"Indiensttreding".to_owned()) ); } #[test] fn sizes_are_short_and_dutch() { assert_eq!(size_label(500), "1 kB"); assert_eq!(size_label(3 * 1024 * 1024 + 512 * 1024), "3,5 MB"); }}@@ -0,0 +1,1448 @@
//! Asclepius-tegel: je tickets (zoals «Mijn tickets» op het web, plus aan jou
//! toegewezen) links, het gesprek van het gekozen ticket rechts. Antwoorden kan
//! hier; behandelen (status, toewijzing) blijft in Asclepius (fase 2).
//!
//! Ongelezen is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at`
//! nieuwer is dan toen je het opende. Elke minuut `ticket_updates`.
use std::collections::HashMap;
use std::time::Duration;
use chrono::{DateTime, Local};
use gpui_kit::component::input::{Textarea, TextareaState};
use gpui_kit::component::scroll::ScrollableElement as _;
use gpui_kit::component::{h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use kvt_sleutels::format::date_time_nl;
use kvt_sleutels::tickets::{
SeenTickets, TextPart, Ticket, TicketAttachment, TicketDetail, TicketFilter, TicketMessage,
mention_label, mention_token, split_mentions, ticket_id_from_url,
};
use kvt_sleutels::{CardsClient, ClientError};
use super::modal::{primary_button, secondary_button};
use super::tasks::{chip, muted, not_linked};
use super::{
Link, base_url, error_text, forget_token, installed, is_demo, link, notice, token_and_client,
update,
};
use crate::app_state::AppHandle;
use crate::i18n::tr;
use crate::runtime;
use crate::theme::{self, ElevatedSurface as _};
use crate::views::widgets::symbol;
pub const KVT_TICKETS_TAG: &str = "kvt-asclepius-tickets";
const SEEN_META_KEY: &str = "kvt.asclepius.seen";
const POLL_INTERVAL: Duration = Duration::from_secs(60);
const HEADER_HEIGHT: f32 = 60.;
const PAGE_PADDING: f32 = 20.;
const LIST_WIDTH: f32 = 320.;
const RADIUS: f32 = 10.;
const BUBBLE_RADIUS: f32 = 14.;
// Ghost-berichten zoals op het web (`.message.is-ghost`), ongeacht het thema.
const GHOST_BG: u32 = 0x5b21b6;
const GHOST_BORDER: u32 = 0xf9a8d4;
const GHOST_TEXT: u32 = 0xfce7f3;
#[derive(Clone)]
enum List {
NotLinked,
Loading,
Loaded(Vec<Ticket>),
Failed(ClientError),
}
#[derive(Clone)]
enum Detail {
Loading,
Loaded(TicketDetail),
Failed(ClientError),
}
pub(super) fn ticket_error(error: &ClientError) -> String {
match error {
ClientError::Forbidden | ClientError::NotFound => tr("kvt.tickets.not_found"),
ClientError::BadRequest => tr("kvt.tickets.failed"),
other => error_text(other),
}
}
/// `2026-01-15T13:39:00+01:00` → `15 jan 2026 13:39` (lokale tijd).
pub(super) fn when(value: &str) -> String {
DateTime::parse_from_rfc3339(value.trim())
.map(|moment| date_time_nl(moment.with_timezone(&Local).naive_local()))
.unwrap_or_else(|_| value.get(..16).unwrap_or(value).replace('T', " "))
}
pub(super) fn status_label(status: &str) -> String {
let key = format!("kvt.tickets.status.{}", status.trim().replace(' ', "_"));
let label = tr(&key);
if label == key || label.is_empty() {
status.to_owned()
} else {
label
}
}
fn me(cx: &App) -> String {
match link(cx) {
Link::Linked(stored) => stored.email.to_lowercase(),
_ => String::new(),
}
}
// --- lokaal ongelezen ----------------------------------------------------------
fn load_seen(cx: &App) -> SeenTickets {
cx.try_global::<AppHandle>()
.and_then(|handle| handle.0.read(cx).store.meta(SEEN_META_KEY).ok().flatten())
.map(|json| SeenTickets::from_json(&json))
.unwrap_or_default()
}
fn save_seen(seen: &SeenTickets, cx: &App) {
if let Some(handle) = cx.try_global::<AppHandle>() {
let _ = handle
.0
.read(cx)
.store
.set_meta(SEEN_META_KEY, &seen.to_json());
}
}
// --- gesprek van één ticket (tegel en ticketvenster) ----------------------------
pub struct TicketThread {
id: u64,
detail: Detail,
reply: Entity<TextareaState>,
sending: bool,
error: Option<String>,
generation: u64,
scroll: ScrollHandle,
}
impl TicketThread {
pub(super) fn new(id: u64, window: &mut Window, cx: &mut Context<Self>) -> Self {
let mut thread = Self::with_detail(id, None, window, cx);
thread.reload(cx);
thread
}
/// Met een al opgehaald ticket (ticketvenster: eerst kijken of je toegang hebt).
fn with_detail(
id: u64,
detail: Option<TicketDetail>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let reply = cx.new(|cx| {
TextareaState::new(window, cx)
.auto_grow(2, 8)
.placeholder(tr("kvt.tickets.reply_placeholder"))
});
let scroll = ScrollHandle::new();
if detail.is_some() {
scroll.scroll_to_bottom();
}
TicketThread {
id,
detail: detail.map_or(Detail::Loading, Detail::Loaded),
reply,
sending: false,
error: None,
generation: 0,
scroll,
}
}
pub(super) fn id(&self) -> u64 {
self.id
}
pub(super) fn reload(&mut self, cx: &mut Context<Self>) {
self.generation += 1;
let generation = self.generation;
let id = self.id;
if is_demo(cx) {
self.detail = match demo_detail(id) {
Some(detail) => Detail::Loaded(detail),
None => Detail::Failed(ClientError::NotFound),
};
self.scroll.scroll_to_bottom();
cx.notify();
return;
}
let Some((token, client)) = token_and_client(cx) else {
return;
};
let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await });
cx.spawn(async move |this, cx| {
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| {
if result == Err(ClientError::Unauthorized) {
forget_token(cx);
}
let opened = result.as_ref().ok().map(|detail| detail.ticket.clone());
this.update(cx, |this, cx| {
if this.generation != generation {
return;
}
let first = !matches!(this.detail, Detail::Loaded(_));
this.detail = match result {
Ok(detail) => Detail::Loaded(detail),
Err(error) => Detail::Failed(error),
};
if first {
this.scroll.scroll_to_bottom();
}
cx.notify();
})
.ok();
if let Some(ticket) = opened {
ticket_seen(&ticket, cx);
}
});
})
.detach();
}
fn mention(&mut self, email: &str, window: &mut Window, cx: &mut Context<Self>) {
let Some(token) = mention_token(email) else {
return;
};
let current = self.reply.read(cx).value().to_string();
let joined = if current.is_empty() || current.ends_with([' ', '\n']) {
format!("{current}{token} ")
} else {
format!("{current} {token} ")
};
self.reply.update(cx, |reply, cx| {
reply.set_value(joined, window, cx);
reply.focus(window, cx);
});
}
fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.sending {
return;
}
let text = self.reply.read(cx).value().trim().to_owned();
if text.is_empty() {
return;
}
self.sending = true;
self.error = None;
cx.notify();
if is_demo(cx) {
demo_reply(self.id, &text, &me(cx));
self.sending = false;
self.reply
.update(cx, |reply, cx| reply.set_value("", window, cx));
self.scroll.scroll_to_bottom();
self.reload(cx);
refresh_list(cx);
return;
}
let Some((token, client)) = token_and_client(cx) else {
self.sending = false;
return;
};
let id = self.id;
let sending =
runtime::spawn(async move { client.asclepius_reply(&token, id, &text).await });
let reply = self.reply.clone();
cx.spawn_in(window, async move |this, cx| {
let result = sending.await.unwrap_or(Err(ClientError::Unavailable));
this.update_in(cx, |this, window, cx| {
this.sending = false;
match &result {
Ok(()) => {
reply.update(cx, |reply, cx| reply.set_value("", window, cx));
this.scroll.scroll_to_bottom();
this.reload(cx);
refresh_list(cx);
}
Err(error) => {
if *error == ClientError::Unauthorized {
forget_token(cx);
}
this.error = Some(ticket_error(error));
}
}
cx.notify();
})
.ok();
})
.detach();
}
fn header(&self, detail: &TicketDetail) -> Div {
let ticket = &detail.ticket;
let mut meta = vec![format!("#{}", ticket.id), status_label(&ticket.status)];
if !ticket.category.is_empty() {
meta.push(if ticket.subcategory.is_empty() {
ticket.category.clone()
} else {
format!("{} › {}", ticket.category, ticket.subcategory)
});
}
if !ticket.created_at.is_empty() {
meta.push(when(&ticket.created_at));
}
v_flex()
.w_full()
.flex_none()
.px(px(PAGE_PADDING))
.py(px(12.))
.gap(px(2.))
.border_b_1()
.border_color(theme::border())
.child(
div()
.text_size(px(16.))
.font_weight(FontWeight::BOLD)
.text_color(theme::text())
.child(ticket.title.clone()),
)
.child(
div()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(meta.join(" · ")),
)
}
fn message(
&self,
index: usize,
message: &TicketMessage,
known: &[String],
cx: &mut Context<Self>,
) -> AnyElement {
let ghost = message.is_ghost;
let from_ict = message.sender_role == "admin";
let text_color = if ghost {
rgb(GHOST_TEXT).into()
} else {
theme::text()
};
let muted_color = if ghost {
rgb(GHOST_TEXT).into()
} else {
theme::text_muted()
};
let mention_color: Hsla = if ghost {
rgb(GHOST_BORDER).into()
} else {
theme::accent_text()
};
let mut role = Vec::new();
if from_ict {
role.push(tr("kvt.tickets.ict"));
}
if ghost {
role.push(tr("kvt.tickets.ghost"));
}
let head = h_flex()
.w_full()
.gap(px(8.))
.items_center()
.child(
div()
.text_size(px(13.))
.font_weight(FontWeight::SEMIBOLD)
.text_color(text_color)
.child(message.sender_name()),
)
.when(!role.is_empty(), |row| {
row.child(
div()
.text_size(px(11.))
.text_color(muted_color)
.child(role.join(" · ")),
)
})
.child(div().flex_1())
.child(
div()
.text_size(px(11.))
.text_color(muted_color)
.child(when(&message.created_at)),
);
let body = message_text(&message.message_text, known, mention_color);
let attachments: Vec<AnyElement> = message
.attachments
.iter()
.enumerate()
.map(|(position, attachment)| {
attachment_chip(index, position, attachment, ghost, cx).into_any_element()
})
.collect();
v_flex()
.id(ElementId::Name(
format!("kvt-ticket-message-{index}").into(),
))
.w_full()
.p(px(12.))
.gap(px(6.))
.rounded(px(BUBBLE_RADIUS))
.map(|bubble| {
if ghost {
bubble
.bg(rgb(GHOST_BG))
.border_2()
.border_color(rgb(GHOST_BORDER))
} else if from_ict {
bubble.bg(theme::popup_hover())
} else {
bubble.bg(theme::surface_raised())
}
})
.child(head)
.child(div().text_size(px(13.)).text_color(text_color).child(body))
.when(!attachments.is_empty(), |bubble| {
bubble.child(h_flex().flex_wrap().gap(px(6.)).children(attachments))
})
.into_any_element()
}
fn composer(&self, detail: &TicketDetail, cx: &mut Context<Self>) -> Div {
let me = me(cx);
let mut people: Vec<String> = detail
.participant_emails
.iter()
.chain(std::iter::once(&detail.ticket.assigned_email))
.map(|email| email.to_lowercase())
.filter(|email| !email.is_empty() && *email != me)
.collect();
people.sort();
people.dedup();
let names = sender_names(detail);
v_flex()
.w_full()
.flex_none()
.px(px(PAGE_PADDING))
.py(px(12.))
.gap(px(8.))
.border_t_1()
.border_color(theme::border())
.when(!people.is_empty(), |column| {
column.child(
h_flex()
.w_full()
.flex_wrap()
.gap(px(6.))
.items_center()
.child(
div()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(tr("kvt.tickets.mention")),
)
.children(people.into_iter().enumerate().map(|(index, email)| {
let label = names
.get(&email)
.cloned()
.unwrap_or_else(|| kvt_sleutels::ponos::name_from_email(&email));
chip(
format!("kvt-ticket-mention-{index}").into(),
format!("@{label}"),
false,
)
.on_click(cx.listener(
move |this, _, window, cx| this.mention(&email, window, cx),
))
})),
)
})
.child(Textarea::new(&self.reply))
.children(self.error.clone().map(|error| {
div()
.text_size(px(13.))
.text_color(theme::red_soft())
.child(error)
}))
.child(
h_flex()
.w_full()
.gap(px(8.))
.items_center()
.when(detail.ticket.is_closed(), |row| {
row.child(
div()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(tr("kvt.tickets.closed_hint")),
)
})
.child(div().flex_1())
.child(
primary_button(
"kvt-ticket-send",
tr(if self.sending {
"kvt.tickets.sending"
} else {
"kvt.tickets.send"
}),
)
.on_click(cx.listener(|this, _, window, cx| this.send(window, cx))),
),
)
}
}
fn sender_names(detail: &TicketDetail) -> HashMap<String, String> {
detail
.messages
.iter()
.filter(|message| !message.sender_display_name.trim().is_empty())
.map(|message| {
(
message.sender_email.to_lowercase(),
message.sender_display_name.trim().to_owned(),
)
})
.collect()
}
/// Tekst met Asclepius-vermeldingen als `@Voornaam` (vet, accentkleur), zoals op het web.
fn message_text(text: &str, known: &[String], mention: Hsla) -> StyledText {
let (shown, ranges) = mention_display(text, known);
let style = HighlightStyle {
color: Some(mention),
font_weight: Some(FontWeight::BOLD),
..HighlightStyle::default()
};
StyledText::new(shown).with_highlights(ranges.into_iter().map(|range| (range, style)))
}
/// Getoonde tekst en de plekken van de vermeldingen daarin.
fn mention_display(text: &str, known: &[String]) -> (String, Vec<std::ops::Range<usize>>) {
let mut shown = String::new();
let mut ranges = Vec::new();
for part in split_mentions(text.trim_end(), known) {
match part {
TextPart::Text(text) => shown.push_str(&text),
TextPart::Mention { key, email } => {
let start = shown.len();
shown.push_str(&mention_label(&key, email.as_deref()));
ranges.push(start..shown.len());
}
}
}
(shown, ranges)
}
fn attachment_chip(
message: usize,
position: usize,
attachment: &TicketAttachment,
ghost: bool,
cx: &mut Context<TicketThread>,
) -> Stateful<Div> {
let attachment = attachment.clone();
let name = attachment.original_name.clone();
h_flex()
.id(ElementId::Name(
format!("kvt-ticket-attachment-{message}-{position}").into(),
))
.h(px(28.))
.px(px(10.))
.gap(px(6.))
.items_center()
.rounded(px(6.))
.cursor_pointer()
.text_size(px(12.))
.map(|chip| {
if ghost {
chip.border_1()
.border_color(rgb(GHOST_BORDER))
.text_color(rgb(GHOST_TEXT))
} else {
chip.bg(theme::popup_hover())
.text_color(theme::text())
.hover(|chip| chip.bg(theme::row_hover()))
}
})
.on_click(cx.listener(move |_, _, _, cx| open_attachment(attachment.clone(), cx)))
.child(symbol(
"attach_file",
14.,
if ghost {
rgb(GHOST_TEXT).into()
} else {
theme::text_muted()
},
))
.child(name)
}
/// Bijlagen gaan alleen met de token: ophalen, in de tijdelijke map zetten en openen.
fn open_attachment(attachment: TicketAttachment, cx: &mut App) {
if is_demo(cx) {
notice(tr("kvt.tickets.demo_attachment"), cx);
return;
}
let Some((token, client)) = token_and_client(cx) else {
return;
};
let id = attachment.id;
let name: String = attachment
.original_name
.chars()
.filter(|c| c.is_alphanumeric() || "-_. ".contains(*c))
.collect();
let name = if name.trim().is_empty() {
"bijlage".to_owned()
} else {
name
};
let downloading = runtime::spawn(async move {
let bytes = client.asclepius_attachment(&token, id).await?;
let directory = std::env::temp_dir().join("rusty-teams-asclepius");
std::fs::create_dir_all(&directory).map_err(|_| ClientError::Unavailable)?;
let path = directory.join(format!("{id}-{name}"));
std::fs::write(&path, bytes).map_err(|_| ClientError::Unavailable)?;
Ok::<_, ClientError>(path)
});
cx.spawn(async move |cx| {
let result = downloading.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| match result {
Ok(path) => cx.open_with_system(&path),
Err(error) => {
if error == ClientError::Unauthorized {
forget_token(cx);
}
notice(ticket_error(&error), cx);
}
});
})
.detach();
}
impl Render for TicketThread {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let detail = match &self.detail {
Detail::Loading => {
return v_flex()
.size_full()
.child(muted(tr("kvt.card.loading")).px(px(PAGE_PADDING)))
.into_any_element();
}
Detail::Failed(error) => {
return v_flex()
.size_full()
.child(muted(ticket_error(error)).px(px(PAGE_PADDING)))
.into_any_element();
}
Detail::Loaded(detail) => detail.clone(),
};
let mut known = detail.participant_emails.clone();
known.push(detail.ticket.assigned_email.clone());
known.push(detail.ticket.user_email.clone());
known.extend(
detail
.messages
.iter()
.map(|message| message.sender_email.clone()),
);
let messages: Vec<AnyElement> = detail
.messages
.iter()
.enumerate()
.map(|(index, message)| self.message(index, message, &known, cx))
.collect();
v_flex()
.debug_selector(|| "kvt-ticket-thread".into())
.size_full()
.min_h_0()
.child(self.header(&detail))
.child(
div()
.id("kvt-ticket-messages")
.flex_1()
.min_h_0()
.overflow_y_scroll()
.track_scroll(&self.scroll)
.child(
v_flex()
.w_full()
.px(px(PAGE_PADDING))
.py(px(12.))
.gap(px(10.))
.children(messages),
),
)
.child(self.composer(&detail, cx))
.into_any_element()
}
}
// --- tegelpagina -------------------------------------------------------------
pub struct TicketsPage {
filter: TicketFilter,
list: List,
/// Open tickets, ook als het filter op Afgehandeld staat (badge in de rail).
open: Vec<Ticket>,
selected: Option<Entity<TicketThread>>,
seen: SeenTickets,
generation: u64,
since: Option<String>,
polling: bool,
}
/// De pagina (eenmalig aangemaakt; ook voor de badge als de tegel dicht is).
fn page(cx: &mut App) -> Option<Entity<TicketsPage>> {
if !super::installed(cx) {
return None;
}
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
return Some(page);
}
let page = cx.new(TicketsPage::new);
cx.global_mut::<super::Kvt>().tickets = Some(page.clone());
Some(page)
}
/// De tegel als element van het hoofdpaneel.
pub fn tickets_view(cx: &mut App) -> AnyElement {
match page(cx) {
Some(page) => div()
.flex_1()
.min_w_0()
.h_full()
.child(page)
.into_any_element(),
None => div().into_any_element(),
}
}
/// De tegel is geopend: vers ophalen.
pub fn tickets_opened(cx: &mut App) {
if let Some(page) = page(cx) {
page.update(cx, |page, cx| page.reload(cx));
}
}
/// Aantal ongelezen open tickets, voor de badge op de tegel.
pub fn tickets_unread(cx: &mut App) -> usize {
if !matches!(link(cx), Link::Linked(_)) {
return 0;
}
page(cx).map_or(0, |page| {
let page = page.read(cx);
page.seen.unread_count(&page.open)
})
}
fn refresh_list(cx: &mut App) {
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
page.update(cx, |page, cx| page.reload(cx));
}
}
/// Net aangemaakt: lijst opnieuw en het nieuwe ticket openen (als de tegel bestaat).
pub(super) fn created(id: u64, cx: &mut App) {
let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() else {
return;
};
let Some(window) = cx.active_window() else {
page.update(cx, |page, cx| page.reload(cx));
return;
};
window
.update(cx, |_, window, cx| {
page.update(cx, |page, cx| {
page.filter = TicketFilter::Open;
page.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));
page.reload(cx);
})
})
.ok();
}
/// Een ticket is bekeken (tegel of ticketvenster): niet meer ongelezen.
pub(super) fn ticket_seen(ticket: &Ticket, cx: &mut App) {
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
page.update(cx, |page, cx| {
if page.seen.mark(ticket) {
save_seen(&page.seen, cx);
cx.notify();
}
});
}
}
impl TicketsPage {
fn new(cx: &mut Context<Self>) -> Self {
let mut page = TicketsPage {
filter: TicketFilter::Open,
list: List::Loading,
open: Vec::new(),
selected: None,
seen: load_seen(cx),
generation: 0,
since: None,
polling: false,
};
page.reload(cx);
page.start_polling(cx);
page
}
fn reload(&mut self, cx: &mut Context<Self>) {
self.generation += 1;
let generation = self.generation;
let filter = self.filter;
if is_demo(cx) {
let all = demo_tickets();
self.open = all.iter().filter(|t| !t.is_closed()).cloned().collect();
if self.seen.initialize(&self.open) {
// Demo: één ticket ongelezen, om de stip te tonen.
self.seen.seen.insert(DEMO_UNREAD, String::new());
}
self.list = List::Loaded(
all.into_iter()
.filter(|t| t.is_closed() == (filter == TicketFilter::Closed))
.collect(),
);
cx.notify();
return;
}
let Some((token, client)) = token_and_client(cx) else {
self.list = List::NotLinked;
cx.notify();
return;
};
if !matches!(self.list, List::Loaded(_)) {
self.list = List::Loading;
}
let loading = runtime::spawn(async move {
let open = client.asclepius_tickets(&token, TicketFilter::Open).await?;
let shown = match filter {
TicketFilter::Open => open.clone(),
TicketFilter::Closed => {
client
.asclepius_tickets(&token, TicketFilter::Closed)
.await?
}
};
Ok::<_, ClientError>((open, shown))
});
cx.spawn(async move |this, cx| {
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| {
if matches!(result, Err(ClientError::Unauthorized)) {
forget_token(cx);
}
this.update(cx, |this, cx| {
if this.generation != generation {
return;
}
match result {
Ok((open, shown)) => {
if this.seen.initialize(&open) {
save_seen(&this.seen, cx);
}
this.since = Some(chrono::Utc::now().to_rfc3339());
this.open = open;
this.list = List::Loaded(shown);
}
Err(ClientError::Unauthorized) => this.list = List::NotLinked,
Err(error) => this.list = List::Failed(error),
}
cx.notify();
cx.refresh_windows();
})
.ok();
});
})
.detach();
}
/// Elke minuut `ticket_updates`; bij wijzigingen de lijst en het open ticket opnieuw.
fn start_polling(&mut self, cx: &mut Context<Self>) {
if self.polling || is_demo(cx) {
return;
}
self.polling = true;
cx.spawn(async move |this, cx| {
loop {
cx.background_executor().timer(POLL_INTERVAL).await;
let Ok(Some((since, token))) = this.update(cx, |this, cx| {
let since = this.since.clone()?;
let (token, client) = token_and_client(cx)?;
Some((since, (token, client)))
}) else {
if this.upgrade().is_none() {
return;
}
continue;
};
let (token, client): (String, CardsClient) = token;
let polling =
runtime::spawn(async move { client.asclepius_updates(&token, &since).await });
let result = polling.await.unwrap_or(Err(ClientError::Unavailable));
let alive = this.update(cx, |this, cx| {
if let Ok((changed, server_time)) = result {
if !server_time.is_empty() {
this.since = Some(server_time);
}
if !changed.is_empty() {
let open_id = this.selected.as_ref().map(|thread| thread.read(cx).id());
if let Some(thread) = this.selected.clone()
&& changed.iter().any(|t| Some(t.id) == open_id)
{
thread.update(cx, |thread, cx| thread.reload(cx));
}
this.reload(cx);
}
}
});
if alive.is_err() {
return;
}
}
})
.detach();
}
fn set_filter(&mut self, filter: TicketFilter, cx: &mut Context<Self>) {
if self.filter == filter {
return;
}
self.filter = filter;
self.list = List::Loading;
self.reload(cx);
}
fn select(&mut self, ticket: &Ticket, window: &mut Window, cx: &mut Context<Self>) {
if self
.selected
.as_ref()
.is_some_and(|thread| thread.read(cx).id() == ticket.id)
{
return;
}
let id = ticket.id;
self.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));
if self.seen.mark(ticket) {
save_seen(&self.seen, cx);
}
cx.notify();
cx.refresh_windows();
}
fn header(&self, cx: &mut Context<Self>) -> Div {
h_flex()
.h(px(HEADER_HEIGHT))
.flex_none()
.px(px(PAGE_PADDING))
.gap(px(8.))
.items_center()
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(16.))
.font_weight(FontWeight::BOLD)
.text_color(theme::text())
.child(tr("kvt.tickets.title")),
)
.children(super::ticket_form::new_ticket_button(cx))
.child(
secondary_button("kvt-tickets-refresh", "refresh", tr("kvt.card.refresh"))
.on_click(cx.listener(|this, _, _, cx| this.reload(cx))),
)
}
fn list(&self, cx: &mut Context<Self>) -> AnyElement {
let filters = h_flex()
.w_full()
.flex_none()
.px(px(12.))
.pb(px(8.))
.gap(px(6.))
.child(
chip(
"kvt-tickets-filter-open".into(),
tr("kvt.tickets.filter_open"),
self.filter == TicketFilter::Open,
)
.on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Open, cx))),
)
.child(
chip(
"kvt-tickets-filter-closed".into(),
tr("kvt.tickets.filter_closed"),
self.filter == TicketFilter::Closed,
)
.on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Closed, cx))),
);
let selected = self.selected.as_ref().map(|thread| thread.read(cx).id());
let rows: AnyElement = match &self.list {
List::Loading | List::NotLinked => {
muted(tr("kvt.card.loading")).px(px(12.)).into_any_element()
}
List::Failed(error) => muted(ticket_error(error)).px(px(12.)).into_any_element(),
List::Loaded(tickets) if tickets.is_empty() => muted(tr(match self.filter {
TicketFilter::Open => "kvt.tickets.empty_open",
TicketFilter::Closed => "kvt.tickets.empty_closed",
}))
.px(px(12.))
.into_any_element(),
List::Loaded(tickets) => v_flex()
.w_full()
.px(px(8.))
.gap(px(2.))
.children(tickets.iter().enumerate().map(|(index, ticket)| {
let unread = self.seen.is_unread(ticket);
let active = selected == Some(ticket.id);
let row_ticket = ticket.clone();
v_flex()
.id(ElementId::Name(format!("kvt-tickets-row-{index}").into()))
.debug_selector(move || format!("kvt-tickets/row/{index}"))
.w_full()
.px(px(10.))
.py(px(8.))
.gap(px(2.))
.rounded(px(6.))
.cursor_pointer()
.map(|row| {
if active {
row.bg(theme::selection())
} else {
row.hover(|row| row.bg(theme::row_hover()))
}
})
.on_click(cx.listener(move |this, _, window, cx| {
this.select(&row_ticket, window, cx)
}))
.child(
h_flex()
.w_full()
.gap(px(6.))
.items_center()
.child(
div()
.flex_1()
.min_w_0()
.truncate()
.text_size(px(13.))
.text_color(theme::text_strong())
.when(unread, |title| title.font_weight(FontWeight::BOLD))
.child(ticket.title.clone()),
)
.when(unread, |row| {
row.child(
div()
.size(px(8.))
.flex_none()
.rounded_full()
.bg(theme::accent()),
)
}),
)
.child(
div()
.truncate()
.text_size(px(12.))
.text_color(theme::text_muted())
.child(format!(
"#{} · {} · {}",
ticket.id,
status_label(&ticket.status),
when(&ticket.updated_at)
)),
)
}))
.into_any_element(),
};
v_flex()
.id("kvt-tickets-list")
.w(px(LIST_WIDTH))
.h_full()
.flex_none()
.border_r_1()
.border_color(theme::border())
.child(filters)
.child(
div()
.id("kvt-tickets-rows")
.flex_1()
.min_h_0()
.overflow_y_scrollbar()
.child(rows),
)
.into_any_element()
}
}
impl Render for TicketsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let linked = matches!(link(cx), Link::Linked(_));
if !linked && !is_demo(cx) {
self.list = List::NotLinked;
self.selected = None;
self.open.clear();
} else if matches!(self.list, List::NotLinked) {
self.reload(cx);
}
let body = if !linked {
v_flex()
.p(px(PAGE_PADDING))
.max_w(px(560.))
.child(not_linked())
.into_any_element()
} else {
h_flex()
.flex_1()
.min_h_0()
.w_full()
.child(self.list(cx))
.child(
div()
.flex_1()
.min_w_0()
.h_full()
.child(match &self.selected {
Some(thread) => thread.clone().into_any_element(),
None => muted(tr("kvt.tickets.pick"))
.px(px(PAGE_PADDING))
.into_any_element(),
}),
)
.into_any_element()
};
v_flex()
.debug_selector(|| KVT_TICKETS_TAG.into())
.relative()
.size_full()
.rounded(px(RADIUS))
.bg(theme::surface())
.overflow_hidden()
.child(self.header(cx))
.child(body)
}
}
// --- ticketvenster (links naar een ticket) ----------------------------------------
const WINDOW_WIDTH: f32 = 720.;
const WINDOW_MARGIN: f32 = 32.;
const WINDOW_BACKDROP: f32 = 0.55;
pub const KVT_TICKET_WINDOW_TAG: &str = "kvt-asclepius-window";
/// Een link naar een Asclepius-ticket (`…/asclepius/index.php?open=…`): heb je toegang, dan
/// opent het ticket in een venster in de app; anders gewoon in de browser. `false` als het
/// geen ticketlink is of je niet gekoppeld bent (dan opent de shell de link zelf).
pub fn open_ticket_link(url: &str, cx: &mut App) -> bool {
if !installed(cx) || !matches!(link(cx), Link::Linked(_)) {
return false;
}
let Some(id) = ticket_id_from_url(&base_url(), url) else {
return false;
};
let url = url.to_owned();
if is_demo(cx) {
match demo_detail(id) {
Some(detail) => cx.defer(move |cx| show_window(detail, cx)),
None => cx.open_url(&url),
}
return true;
}
let Some((token, client)) = token_and_client(cx) else {
return false;
};
let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await });
cx.spawn(async move |cx| {
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
cx.update(|cx| match result {
Ok(detail) => show_window(detail, cx),
Err(error) => {
if error == ClientError::Unauthorized {
forget_token(cx);
}
// Geen toegang of Asclepius niet bereikbaar: een gewone link.
cx.open_url(&url);
}
});
})
.detach();
true
}
fn show_window(detail: TicketDetail, cx: &mut App) {
let Some(window) = cx
.active_window()
.or_else(|| cx.windows().into_iter().next())
else {
return;
};
let ticket = detail.ticket.clone();
window
.update(cx, |_, window, cx| {
let thread =
cx.new(|cx| TicketThread::with_detail(ticket.id, Some(detail), window, cx));
update(cx, |kvt| kvt.ticket_window = Some(thread));
cx.refresh_windows();
})
.ok();
ticket_seen(&ticket, cx);
}
fn close_window(cx: &mut App) {
update(cx, |kvt| kvt.ticket_window = None);
cx.refresh_windows();
}
/// Laag voor `kvt::overlay`.
pub(super) fn window_overlay(thread: Entity<TicketThread>) -> AnyElement {
div()
.id("kvt-ticket-window-layer")
.absolute()
.top_0()
.left_0()
.size_full()
.flex()
.items_center()
.justify_center()
.child(
div()
.id("kvt-ticket-window-backdrop")
.absolute()
.top_0()
.left_0()
.size_full()
.bg(black().opacity(WINDOW_BACKDROP))
.occlude()
.on_click(|_, _, cx| close_window(cx)),
)
.child(
div()
.id("kvt-ticket-window")
.debug_selector(|| KVT_TICKET_WINDOW_TAG.into())
.relative()
.w(px(WINDOW_WIDTH))
.max_w(relative(1.))
.h(relative(0.85))
.m(px(WINDOW_MARGIN))
.rounded(px(RADIUS))
.dialog_surface()
.overflow_hidden()
.occlude()
.child(thread)
.child(
div()
.id("kvt-ticket-window-close")
.absolute()
.top(px(10.))
.right(px(10.))
.size(px(28.))
.flex()
.items_center()
.justify_center()
.rounded_full()
.cursor_pointer()
.hover(|button| button.bg(theme::popup_hover()))
.on_click(|_, _, cx| close_window(cx))
.child(symbol("close", 16., theme::text_muted())),
),
)
.into_any_element()
}
// --- demo ------------------------------------------------------------------------
const DEMO_UNREAD: u64 = 4102;
thread_local! {
static DEMO_REPLIES: std::cell::RefCell<HashMap<u64, Vec<TicketMessage>>> =
std::cell::RefCell::new(HashMap::new());
}
fn demo_ticket(id: u64, title: &str, status: &str, category: &str, updated: &str) -> Ticket {
Ticket {
id,
title: title.to_owned(),
category: category.to_owned(),
user_email: super::demo::token().email,
assigned_email: "ict.medewerker@example.com".to_owned(),
status: status.to_owned(),
created_at: "2026-01-12T09:15:00+01:00".to_owned(),
updated_at: updated.to_owned(),
message_count: 3,
..Ticket::default()
}
}
pub(super) fn demo_tickets() -> Vec<Ticket> {
vec![
Ticket {
subcategory: "Laptop".to_owned(),
..demo_ticket(
DEMO_UNREAD,
"Laptop start niet meer op",
"in behandeling",
"Hardware",
"2026-01-15T13:39:00+01:00",
)
},
demo_ticket(
4098,
"Toegang tot gedeelde map Projecten",
"afwachtende op gebruiker",
"Rechten en toegang",
"2026-01-14T16:02:00+01:00",
),
demo_ticket(
4090,
"Nieuwe headset",
"ingediend",
"Hardware bestellen",
"2026-01-13T10:20:00+01:00",
),
demo_ticket(
4012,
"Printer op kantoor geeft een fout",
"afgehandeld",
"Hardware",
"2026-01-08T11:00:00+01:00",
),
]
}
fn demo_message(
id: u64,
email: &str,
name: &str,
role: &str,
text: &str,
at: &str,
) -> TicketMessage {
TicketMessage {
id,
sender_email: email.to_owned(),
sender_role: role.to_owned(),
sender_display_name: name.to_owned(),
message_text: text.to_owned(),
created_at: at.to_owned(),
..TicketMessage::default()
}
}
pub(super) fn demo_detail(id: u64) -> Option<TicketDetail> {
let ticket = demo_tickets().into_iter().find(|ticket| ticket.id == id)?;
let me = super::demo::token();
let ict = "ict.medewerker@example.com";
let mut messages = vec![
demo_message(
1,
&me.email,
&me.name,
"user",
"Mijn laptop gaat niet meer aan sinds vanochtend. Het lampje knippert oranje.",
"2026-01-15T09:15:00+01:00",
),
demo_message(
2,
ict,
"Sam Ict",
"admin",
"Dank je. Kun je de lader een minuut loskoppelen en het opnieuw proberen? @dana.demo:examplecom",
"2026-01-15T10:02:00+01:00",
),
TicketMessage {
is_ghost: true,
..demo_message(
3,
ict,
"Sam Ict",
"admin",
"Intern: garantie loopt nog tot maart, eventueel omruilen via de leverancier.",
"2026-01-15T10:05:00+01:00",
)
},
TicketMessage {
attachments: vec![TicketAttachment {
id: 77,
original_name: "foto-lampje.jpg".to_owned(),
mime_type: "image/jpeg".to_owned(),
file_size: 120_000,
}],
..demo_message(
4,
&me.email,
&me.name,
"user",
"Gedaan, hij knippert nog steeds. Foto erbij.",
"2026-01-15T13:39:00+01:00",
)
},
];
if id != DEMO_UNREAD {
messages.truncate(1);
messages[0].message_text = format!("{}.", ticket.title);
}
DEMO_REPLIES.with(|replies| {
messages.extend(replies.borrow().get(&id).cloned().unwrap_or_default());
});
Some(TicketDetail {
description: messages[0].message_text.clone(),
participant_emails: vec![me.email.clone(), "jonas.ortega@example.com".to_owned()],
messages,
ticket,
})
}
fn demo_reply(id: u64, text: &str, email: &str) {
let me = super::demo::token();
DEMO_REPLIES.with(|replies| {
let mut replies = replies.borrow_mut();
let list = replies.entry(id).or_default();
list.push(demo_message(
100 + list.len() as u64,
if email.is_empty() { &me.email } else { email },
&me.name,
"user",
text,
&chrono::Local::now().to_rfc3339(),
));
});
}
#[cfg(test)]
mod tests {
use super::{DEMO_UNREAD, demo_detail, demo_tickets, mention_display, when};
use kvt_sleutels::tickets::Ticket;
#[test]
fn dates_are_dutch_and_local() {
let shown = when("2026-01-15T13:39:00+01:00");
assert!(shown.starts_with("15 jan 2026") || shown.starts_with("16 jan 2026"));
assert_eq!(when("geen datum"), "geen datum");
}
#[test]
fn demo_has_a_ghost_and_a_closed_ticket() {
let detail = demo_detail(DEMO_UNREAD).unwrap();
assert!(detail.messages.iter().any(|message| message.is_ghost));
assert!(demo_tickets().iter().any(Ticket::is_closed));
}
#[test]
fn mentions_render_as_first_names() {
let (shown, ranges) = mention_display(
"Graag @dana.demo:examplecom",
&["dana.demo@example.com".to_owned()],
);
assert_eq!(shown, "Graag @Dana");
assert_eq!(ranges, [6..11]);
}
}
@@ -0,0 +1,1448 @@//! Asclepius-tegel: je tickets (zoals «Mijn tickets» op het web, plus aan jou//! toegewezen) links, het gesprek van het gekozen ticket rechts. Antwoorden kan//! hier; behandelen (status, toewijzing) blijft in Asclepius (fase 2).//!//! Ongelezen is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at`//! nieuwer is dan toen je het opende. Elke minuut `ticket_updates`.use std::collections::HashMap;use std::time::Duration;use chrono::{DateTime, Local};use gpui_kit::component::input::{Textarea, TextareaState};use gpui_kit::component::scroll::ScrollableElement as _;use gpui_kit::component::{h_flex, v_flex};use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::*;use kvt_sleutels::format::date_time_nl;use kvt_sleutels::tickets::{ SeenTickets, TextPart, Ticket, TicketAttachment, TicketDetail, TicketFilter, TicketMessage, mention_label, mention_token, split_mentions, ticket_id_from_url,};use kvt_sleutels::{CardsClient, ClientError};use super::modal::{primary_button, secondary_button};use super::tasks::{chip, muted, not_linked};use super::{ Link, base_url, error_text, forget_token, installed, is_demo, link, notice, token_and_client, update,};use crate::app_state::AppHandle;use crate::i18n::tr;use crate::runtime;use crate::theme::{self, ElevatedSurface as _};use crate::views::widgets::symbol;pub const KVT_TICKETS_TAG: &str = "kvt-asclepius-tickets";const SEEN_META_KEY: &str = "kvt.asclepius.seen";const POLL_INTERVAL: Duration = Duration::from_secs(60);const HEADER_HEIGHT: f32 = 60.;const PAGE_PADDING: f32 = 20.;const LIST_WIDTH: f32 = 320.;const RADIUS: f32 = 10.;const BUBBLE_RADIUS: f32 = 14.;// Ghost-berichten zoals op het web (`.message.is-ghost`), ongeacht het thema.const GHOST_BG: u32 = 0x5b21b6;const GHOST_BORDER: u32 = 0xf9a8d4;const GHOST_TEXT: u32 = 0xfce7f3;#[derive(Clone)]enum List { NotLinked, Loading, Loaded(Vec<Ticket>), Failed(ClientError),}#[derive(Clone)]enum Detail { Loading, Loaded(TicketDetail), Failed(ClientError),}pub(super) fn ticket_error(error: &ClientError) -> String { match error { ClientError::Forbidden | ClientError::NotFound => tr("kvt.tickets.not_found"), ClientError::BadRequest => tr("kvt.tickets.failed"), other => error_text(other), }}/// `2026-01-15T13:39:00+01:00` → `15 jan 2026 13:39` (lokale tijd).pub(super) fn when(value: &str) -> String { DateTime::parse_from_rfc3339(value.trim()) .map(|moment| date_time_nl(moment.with_timezone(&Local).naive_local())) .unwrap_or_else(|_| value.get(..16).unwrap_or(value).replace('T', " "))}pub(super) fn status_label(status: &str) -> String { let key = format!("kvt.tickets.status.{}", status.trim().replace(' ', "_")); let label = tr(&key); if label == key || label.is_empty() { status.to_owned() } else { label }}fn me(cx: &App) -> String { match link(cx) { Link::Linked(stored) => stored.email.to_lowercase(), _ => String::new(), }}// --- lokaal ongelezen ----------------------------------------------------------fn load_seen(cx: &App) -> SeenTickets { cx.try_global::<AppHandle>() .and_then(|handle| handle.0.read(cx).store.meta(SEEN_META_KEY).ok().flatten()) .map(|json| SeenTickets::from_json(&json)) .unwrap_or_default()}fn save_seen(seen: &SeenTickets, cx: &App) { if let Some(handle) = cx.try_global::<AppHandle>() { let _ = handle .0 .read(cx) .store .set_meta(SEEN_META_KEY, &seen.to_json()); }}// --- gesprek van één ticket (tegel en ticketvenster) ----------------------------pub struct TicketThread { id: u64, detail: Detail, reply: Entity<TextareaState>, sending: bool, error: Option<String>, generation: u64, scroll: ScrollHandle,}impl TicketThread { pub(super) fn new(id: u64, window: &mut Window, cx: &mut Context<Self>) -> Self { let mut thread = Self::with_detail(id, None, window, cx); thread.reload(cx); thread } /// Met een al opgehaald ticket (ticketvenster: eerst kijken of je toegang hebt). fn with_detail( id: u64, detail: Option<TicketDetail>, window: &mut Window, cx: &mut Context<Self>, ) -> Self { let reply = cx.new(|cx| { TextareaState::new(window, cx) .auto_grow(2, 8) .placeholder(tr("kvt.tickets.reply_placeholder")) }); let scroll = ScrollHandle::new(); if detail.is_some() { scroll.scroll_to_bottom(); } TicketThread { id, detail: detail.map_or(Detail::Loading, Detail::Loaded), reply, sending: false, error: None, generation: 0, scroll, } } pub(super) fn id(&self) -> u64 { self.id } pub(super) fn reload(&mut self, cx: &mut Context<Self>) { self.generation += 1; let generation = self.generation; let id = self.id; if is_demo(cx) { self.detail = match demo_detail(id) { Some(detail) => Detail::Loaded(detail), None => Detail::Failed(ClientError::NotFound), }; self.scroll.scroll_to_bottom(); cx.notify(); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await }); cx.spawn(async move |this, cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if result == Err(ClientError::Unauthorized) { forget_token(cx); } let opened = result.as_ref().ok().map(|detail| detail.ticket.clone()); this.update(cx, |this, cx| { if this.generation != generation { return; } let first = !matches!(this.detail, Detail::Loaded(_)); this.detail = match result { Ok(detail) => Detail::Loaded(detail), Err(error) => Detail::Failed(error), }; if first { this.scroll.scroll_to_bottom(); } cx.notify(); }) .ok(); if let Some(ticket) = opened { ticket_seen(&ticket, cx); } }); }) .detach(); } fn mention(&mut self, email: &str, window: &mut Window, cx: &mut Context<Self>) { let Some(token) = mention_token(email) else { return; }; let current = self.reply.read(cx).value().to_string(); let joined = if current.is_empty() || current.ends_with([' ', '\n']) { format!("{current}{token} ") } else { format!("{current} {token} ") }; self.reply.update(cx, |reply, cx| { reply.set_value(joined, window, cx); reply.focus(window, cx); }); } fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) { if self.sending { return; } let text = self.reply.read(cx).value().trim().to_owned(); if text.is_empty() { return; } self.sending = true; self.error = None; cx.notify(); if is_demo(cx) { demo_reply(self.id, &text, &me(cx)); self.sending = false; self.reply .update(cx, |reply, cx| reply.set_value("", window, cx)); self.scroll.scroll_to_bottom(); self.reload(cx); refresh_list(cx); return; } let Some((token, client)) = token_and_client(cx) else { self.sending = false; return; }; let id = self.id; let sending = runtime::spawn(async move { client.asclepius_reply(&token, id, &text).await }); let reply = self.reply.clone(); cx.spawn_in(window, async move |this, cx| { let result = sending.await.unwrap_or(Err(ClientError::Unavailable)); this.update_in(cx, |this, window, cx| { this.sending = false; match &result { Ok(()) => { reply.update(cx, |reply, cx| reply.set_value("", window, cx)); this.scroll.scroll_to_bottom(); this.reload(cx); refresh_list(cx); } Err(error) => { if *error == ClientError::Unauthorized { forget_token(cx); } this.error = Some(ticket_error(error)); } } cx.notify(); }) .ok(); }) .detach(); } fn header(&self, detail: &TicketDetail) -> Div { let ticket = &detail.ticket; let mut meta = vec![format!("#{}", ticket.id), status_label(&ticket.status)]; if !ticket.category.is_empty() { meta.push(if ticket.subcategory.is_empty() { ticket.category.clone() } else { format!("{} › {}", ticket.category, ticket.subcategory) }); } if !ticket.created_at.is_empty() { meta.push(when(&ticket.created_at)); } v_flex() .w_full() .flex_none() .px(px(PAGE_PADDING)) .py(px(12.)) .gap(px(2.)) .border_b_1() .border_color(theme::border()) .child( div() .text_size(px(16.)) .font_weight(FontWeight::BOLD) .text_color(theme::text()) .child(ticket.title.clone()), ) .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(meta.join(" · ")), ) } fn message( &self, index: usize, message: &TicketMessage, known: &[String], cx: &mut Context<Self>, ) -> AnyElement { let ghost = message.is_ghost; let from_ict = message.sender_role == "admin"; let text_color = if ghost { rgb(GHOST_TEXT).into() } else { theme::text() }; let muted_color = if ghost { rgb(GHOST_TEXT).into() } else { theme::text_muted() }; let mention_color: Hsla = if ghost { rgb(GHOST_BORDER).into() } else { theme::accent_text() }; let mut role = Vec::new(); if from_ict { role.push(tr("kvt.tickets.ict")); } if ghost { role.push(tr("kvt.tickets.ghost")); } let head = h_flex() .w_full() .gap(px(8.)) .items_center() .child( div() .text_size(px(13.)) .font_weight(FontWeight::SEMIBOLD) .text_color(text_color) .child(message.sender_name()), ) .when(!role.is_empty(), |row| { row.child( div() .text_size(px(11.)) .text_color(muted_color) .child(role.join(" · ")), ) }) .child(div().flex_1()) .child( div() .text_size(px(11.)) .text_color(muted_color) .child(when(&message.created_at)), ); let body = message_text(&message.message_text, known, mention_color); let attachments: Vec<AnyElement> = message .attachments .iter() .enumerate() .map(|(position, attachment)| { attachment_chip(index, position, attachment, ghost, cx).into_any_element() }) .collect(); v_flex() .id(ElementId::Name( format!("kvt-ticket-message-{index}").into(), )) .w_full() .p(px(12.)) .gap(px(6.)) .rounded(px(BUBBLE_RADIUS)) .map(|bubble| { if ghost { bubble .bg(rgb(GHOST_BG)) .border_2() .border_color(rgb(GHOST_BORDER)) } else if from_ict { bubble.bg(theme::popup_hover()) } else { bubble.bg(theme::surface_raised()) } }) .child(head) .child(div().text_size(px(13.)).text_color(text_color).child(body)) .when(!attachments.is_empty(), |bubble| { bubble.child(h_flex().flex_wrap().gap(px(6.)).children(attachments)) }) .into_any_element() } fn composer(&self, detail: &TicketDetail, cx: &mut Context<Self>) -> Div { let me = me(cx); let mut people: Vec<String> = detail .participant_emails .iter() .chain(std::iter::once(&detail.ticket.assigned_email)) .map(|email| email.to_lowercase()) .filter(|email| !email.is_empty() && *email != me) .collect(); people.sort(); people.dedup(); let names = sender_names(detail); v_flex() .w_full() .flex_none() .px(px(PAGE_PADDING)) .py(px(12.)) .gap(px(8.)) .border_t_1() .border_color(theme::border()) .when(!people.is_empty(), |column| { column.child( h_flex() .w_full() .flex_wrap() .gap(px(6.)) .items_center() .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(tr("kvt.tickets.mention")), ) .children(people.into_iter().enumerate().map(|(index, email)| { let label = names .get(&email) .cloned() .unwrap_or_else(|| kvt_sleutels::ponos::name_from_email(&email)); chip( format!("kvt-ticket-mention-{index}").into(), format!("@{label}"), false, ) .on_click(cx.listener( move |this, _, window, cx| this.mention(&email, window, cx), )) })), ) }) .child(Textarea::new(&self.reply)) .children(self.error.clone().map(|error| { div() .text_size(px(13.)) .text_color(theme::red_soft()) .child(error) })) .child( h_flex() .w_full() .gap(px(8.)) .items_center() .when(detail.ticket.is_closed(), |row| { row.child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(tr("kvt.tickets.closed_hint")), ) }) .child(div().flex_1()) .child( primary_button( "kvt-ticket-send", tr(if self.sending { "kvt.tickets.sending" } else { "kvt.tickets.send" }), ) .on_click(cx.listener(|this, _, window, cx| this.send(window, cx))), ), ) }}fn sender_names(detail: &TicketDetail) -> HashMap<String, String> { detail .messages .iter() .filter(|message| !message.sender_display_name.trim().is_empty()) .map(|message| { ( message.sender_email.to_lowercase(), message.sender_display_name.trim().to_owned(), ) }) .collect()}/// Tekst met Asclepius-vermeldingen als `@Voornaam` (vet, accentkleur), zoals op het web.fn message_text(text: &str, known: &[String], mention: Hsla) -> StyledText { let (shown, ranges) = mention_display(text, known); let style = HighlightStyle { color: Some(mention), font_weight: Some(FontWeight::BOLD), ..HighlightStyle::default() }; StyledText::new(shown).with_highlights(ranges.into_iter().map(|range| (range, style)))}/// Getoonde tekst en de plekken van de vermeldingen daarin.fn mention_display(text: &str, known: &[String]) -> (String, Vec<std::ops::Range<usize>>) { let mut shown = String::new(); let mut ranges = Vec::new(); for part in split_mentions(text.trim_end(), known) { match part { TextPart::Text(text) => shown.push_str(&text), TextPart::Mention { key, email } => { let start = shown.len(); shown.push_str(&mention_label(&key, email.as_deref())); ranges.push(start..shown.len()); } } } (shown, ranges)}fn attachment_chip( message: usize, position: usize, attachment: &TicketAttachment, ghost: bool, cx: &mut Context<TicketThread>,) -> Stateful<Div> { let attachment = attachment.clone(); let name = attachment.original_name.clone(); h_flex() .id(ElementId::Name( format!("kvt-ticket-attachment-{message}-{position}").into(), )) .h(px(28.)) .px(px(10.)) .gap(px(6.)) .items_center() .rounded(px(6.)) .cursor_pointer() .text_size(px(12.)) .map(|chip| { if ghost { chip.border_1() .border_color(rgb(GHOST_BORDER)) .text_color(rgb(GHOST_TEXT)) } else { chip.bg(theme::popup_hover()) .text_color(theme::text()) .hover(|chip| chip.bg(theme::row_hover())) } }) .on_click(cx.listener(move |_, _, _, cx| open_attachment(attachment.clone(), cx))) .child(symbol( "attach_file", 14., if ghost { rgb(GHOST_TEXT).into() } else { theme::text_muted() }, )) .child(name)}/// Bijlagen gaan alleen met de token: ophalen, in de tijdelijke map zetten en openen.fn open_attachment(attachment: TicketAttachment, cx: &mut App) { if is_demo(cx) { notice(tr("kvt.tickets.demo_attachment"), cx); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let id = attachment.id; let name: String = attachment .original_name .chars() .filter(|c| c.is_alphanumeric() || "-_. ".contains(*c)) .collect(); let name = if name.trim().is_empty() { "bijlage".to_owned() } else { name }; let downloading = runtime::spawn(async move { let bytes = client.asclepius_attachment(&token, id).await?; let directory = std::env::temp_dir().join("rusty-teams-asclepius"); std::fs::create_dir_all(&directory).map_err(|_| ClientError::Unavailable)?; let path = directory.join(format!("{id}-{name}")); std::fs::write(&path, bytes).map_err(|_| ClientError::Unavailable)?; Ok::<_, ClientError>(path) }); cx.spawn(async move |cx| { let result = downloading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(path) => cx.open_with_system(&path), Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } notice(ticket_error(&error), cx); } }); }) .detach();}impl Render for TicketThread { fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let detail = match &self.detail { Detail::Loading => { return v_flex() .size_full() .child(muted(tr("kvt.card.loading")).px(px(PAGE_PADDING))) .into_any_element(); } Detail::Failed(error) => { return v_flex() .size_full() .child(muted(ticket_error(error)).px(px(PAGE_PADDING))) .into_any_element(); } Detail::Loaded(detail) => detail.clone(), }; let mut known = detail.participant_emails.clone(); known.push(detail.ticket.assigned_email.clone()); known.push(detail.ticket.user_email.clone()); known.extend( detail .messages .iter() .map(|message| message.sender_email.clone()), ); let messages: Vec<AnyElement> = detail .messages .iter() .enumerate() .map(|(index, message)| self.message(index, message, &known, cx)) .collect(); v_flex() .debug_selector(|| "kvt-ticket-thread".into()) .size_full() .min_h_0() .child(self.header(&detail)) .child( div() .id("kvt-ticket-messages") .flex_1() .min_h_0() .overflow_y_scroll() .track_scroll(&self.scroll) .child( v_flex() .w_full() .px(px(PAGE_PADDING)) .py(px(12.)) .gap(px(10.)) .children(messages), ), ) .child(self.composer(&detail, cx)) .into_any_element() }}// --- tegelpagina -------------------------------------------------------------pub struct TicketsPage { filter: TicketFilter, list: List, /// Open tickets, ook als het filter op Afgehandeld staat (badge in de rail). open: Vec<Ticket>, selected: Option<Entity<TicketThread>>, seen: SeenTickets, generation: u64, since: Option<String>, polling: bool,}/// De pagina (eenmalig aangemaakt; ook voor de badge als de tegel dicht is).fn page(cx: &mut App) -> Option<Entity<TicketsPage>> { if !super::installed(cx) { return None; } if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() { return Some(page); } let page = cx.new(TicketsPage::new); cx.global_mut::<super::Kvt>().tickets = Some(page.clone()); Some(page)}/// De tegel als element van het hoofdpaneel.pub fn tickets_view(cx: &mut App) -> AnyElement { match page(cx) { Some(page) => div() .flex_1() .min_w_0() .h_full() .child(page) .into_any_element(), None => div().into_any_element(), }}/// De tegel is geopend: vers ophalen.pub fn tickets_opened(cx: &mut App) { if let Some(page) = page(cx) { page.update(cx, |page, cx| page.reload(cx)); }}/// Aantal ongelezen open tickets, voor de badge op de tegel.pub fn tickets_unread(cx: &mut App) -> usize { if !matches!(link(cx), Link::Linked(_)) { return 0; } page(cx).map_or(0, |page| { let page = page.read(cx); page.seen.unread_count(&page.open) })}fn refresh_list(cx: &mut App) { if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() { page.update(cx, |page, cx| page.reload(cx)); }}/// Net aangemaakt: lijst opnieuw en het nieuwe ticket openen (als de tegel bestaat).pub(super) fn created(id: u64, cx: &mut App) { let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() else { return; }; let Some(window) = cx.active_window() else { page.update(cx, |page, cx| page.reload(cx)); return; }; window .update(cx, |_, window, cx| { page.update(cx, |page, cx| { page.filter = TicketFilter::Open; page.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx))); page.reload(cx); }) }) .ok();}/// Een ticket is bekeken (tegel of ticketvenster): niet meer ongelezen.pub(super) fn ticket_seen(ticket: &Ticket, cx: &mut App) { if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() { page.update(cx, |page, cx| { if page.seen.mark(ticket) { save_seen(&page.seen, cx); cx.notify(); } }); }}impl TicketsPage { fn new(cx: &mut Context<Self>) -> Self { let mut page = TicketsPage { filter: TicketFilter::Open, list: List::Loading, open: Vec::new(), selected: None, seen: load_seen(cx), generation: 0, since: None, polling: false, }; page.reload(cx); page.start_polling(cx); page } fn reload(&mut self, cx: &mut Context<Self>) { self.generation += 1; let generation = self.generation; let filter = self.filter; if is_demo(cx) { let all = demo_tickets(); self.open = all.iter().filter(|t| !t.is_closed()).cloned().collect(); if self.seen.initialize(&self.open) { // Demo: één ticket ongelezen, om de stip te tonen. self.seen.seen.insert(DEMO_UNREAD, String::new()); } self.list = List::Loaded( all.into_iter() .filter(|t| t.is_closed() == (filter == TicketFilter::Closed)) .collect(), ); cx.notify(); return; } let Some((token, client)) = token_and_client(cx) else { self.list = List::NotLinked; cx.notify(); return; }; if !matches!(self.list, List::Loaded(_)) { self.list = List::Loading; } let loading = runtime::spawn(async move { let open = client.asclepius_tickets(&token, TicketFilter::Open).await?; let shown = match filter { TicketFilter::Open => open.clone(), TicketFilter::Closed => { client .asclepius_tickets(&token, TicketFilter::Closed) .await? } }; Ok::<_, ClientError>((open, shown)) }); cx.spawn(async move |this, cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if matches!(result, Err(ClientError::Unauthorized)) { forget_token(cx); } this.update(cx, |this, cx| { if this.generation != generation { return; } match result { Ok((open, shown)) => { if this.seen.initialize(&open) { save_seen(&this.seen, cx); } this.since = Some(chrono::Utc::now().to_rfc3339()); this.open = open; this.list = List::Loaded(shown); } Err(ClientError::Unauthorized) => this.list = List::NotLinked, Err(error) => this.list = List::Failed(error), } cx.notify(); cx.refresh_windows(); }) .ok(); }); }) .detach(); } /// Elke minuut `ticket_updates`; bij wijzigingen de lijst en het open ticket opnieuw. fn start_polling(&mut self, cx: &mut Context<Self>) { if self.polling || is_demo(cx) { return; } self.polling = true; cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(POLL_INTERVAL).await; let Ok(Some((since, token))) = this.update(cx, |this, cx| { let since = this.since.clone()?; let (token, client) = token_and_client(cx)?; Some((since, (token, client))) }) else { if this.upgrade().is_none() { return; } continue; }; let (token, client): (String, CardsClient) = token; let polling = runtime::spawn(async move { client.asclepius_updates(&token, &since).await }); let result = polling.await.unwrap_or(Err(ClientError::Unavailable)); let alive = this.update(cx, |this, cx| { if let Ok((changed, server_time)) = result { if !server_time.is_empty() { this.since = Some(server_time); } if !changed.is_empty() { let open_id = this.selected.as_ref().map(|thread| thread.read(cx).id()); if let Some(thread) = this.selected.clone() && changed.iter().any(|t| Some(t.id) == open_id) { thread.update(cx, |thread, cx| thread.reload(cx)); } this.reload(cx); } } }); if alive.is_err() { return; } } }) .detach(); } fn set_filter(&mut self, filter: TicketFilter, cx: &mut Context<Self>) { if self.filter == filter { return; } self.filter = filter; self.list = List::Loading; self.reload(cx); } fn select(&mut self, ticket: &Ticket, window: &mut Window, cx: &mut Context<Self>) { if self .selected .as_ref() .is_some_and(|thread| thread.read(cx).id() == ticket.id) { return; } let id = ticket.id; self.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx))); if self.seen.mark(ticket) { save_seen(&self.seen, cx); } cx.notify(); cx.refresh_windows(); } fn header(&self, cx: &mut Context<Self>) -> Div { h_flex() .h(px(HEADER_HEIGHT)) .flex_none() .px(px(PAGE_PADDING)) .gap(px(8.)) .items_center() .child( div() .flex_1() .min_w_0() .truncate() .text_size(px(16.)) .font_weight(FontWeight::BOLD) .text_color(theme::text()) .child(tr("kvt.tickets.title")), ) .children(super::ticket_form::new_ticket_button(cx)) .child( secondary_button("kvt-tickets-refresh", "refresh", tr("kvt.card.refresh")) .on_click(cx.listener(|this, _, _, cx| this.reload(cx))), ) } fn list(&self, cx: &mut Context<Self>) -> AnyElement { let filters = h_flex() .w_full() .flex_none() .px(px(12.)) .pb(px(8.)) .gap(px(6.)) .child( chip( "kvt-tickets-filter-open".into(), tr("kvt.tickets.filter_open"), self.filter == TicketFilter::Open, ) .on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Open, cx))), ) .child( chip( "kvt-tickets-filter-closed".into(), tr("kvt.tickets.filter_closed"), self.filter == TicketFilter::Closed, ) .on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Closed, cx))), ); let selected = self.selected.as_ref().map(|thread| thread.read(cx).id()); let rows: AnyElement = match &self.list { List::Loading | List::NotLinked => { muted(tr("kvt.card.loading")).px(px(12.)).into_any_element() } List::Failed(error) => muted(ticket_error(error)).px(px(12.)).into_any_element(), List::Loaded(tickets) if tickets.is_empty() => muted(tr(match self.filter { TicketFilter::Open => "kvt.tickets.empty_open", TicketFilter::Closed => "kvt.tickets.empty_closed", })) .px(px(12.)) .into_any_element(), List::Loaded(tickets) => v_flex() .w_full() .px(px(8.)) .gap(px(2.)) .children(tickets.iter().enumerate().map(|(index, ticket)| { let unread = self.seen.is_unread(ticket); let active = selected == Some(ticket.id); let row_ticket = ticket.clone(); v_flex() .id(ElementId::Name(format!("kvt-tickets-row-{index}").into())) .debug_selector(move || format!("kvt-tickets/row/{index}")) .w_full() .px(px(10.)) .py(px(8.)) .gap(px(2.)) .rounded(px(6.)) .cursor_pointer() .map(|row| { if active { row.bg(theme::selection()) } else { row.hover(|row| row.bg(theme::row_hover())) } }) .on_click(cx.listener(move |this, _, window, cx| { this.select(&row_ticket, window, cx) })) .child( h_flex() .w_full() .gap(px(6.)) .items_center() .child( div() .flex_1() .min_w_0() .truncate() .text_size(px(13.)) .text_color(theme::text_strong()) .when(unread, |title| title.font_weight(FontWeight::BOLD)) .child(ticket.title.clone()), ) .when(unread, |row| { row.child( div() .size(px(8.)) .flex_none() .rounded_full() .bg(theme::accent()), ) }), ) .child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(format!( "#{} · {} · {}", ticket.id, status_label(&ticket.status), when(&ticket.updated_at) )), ) })) .into_any_element(), }; v_flex() .id("kvt-tickets-list") .w(px(LIST_WIDTH)) .h_full() .flex_none() .border_r_1() .border_color(theme::border()) .child(filters) .child( div() .id("kvt-tickets-rows") .flex_1() .min_h_0() .overflow_y_scrollbar() .child(rows), ) .into_any_element() }}impl Render for TicketsPage { fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { let linked = matches!(link(cx), Link::Linked(_)); if !linked && !is_demo(cx) { self.list = List::NotLinked; self.selected = None; self.open.clear(); } else if matches!(self.list, List::NotLinked) { self.reload(cx); } let body = if !linked { v_flex() .p(px(PAGE_PADDING)) .max_w(px(560.)) .child(not_linked()) .into_any_element() } else { h_flex() .flex_1() .min_h_0() .w_full() .child(self.list(cx)) .child( div() .flex_1() .min_w_0() .h_full() .child(match &self.selected { Some(thread) => thread.clone().into_any_element(), None => muted(tr("kvt.tickets.pick")) .px(px(PAGE_PADDING)) .into_any_element(), }), ) .into_any_element() }; v_flex() .debug_selector(|| KVT_TICKETS_TAG.into()) .relative() .size_full() .rounded(px(RADIUS)) .bg(theme::surface()) .overflow_hidden() .child(self.header(cx)) .child(body) }}// --- ticketvenster (links naar een ticket) ----------------------------------------const WINDOW_WIDTH: f32 = 720.;const WINDOW_MARGIN: f32 = 32.;const WINDOW_BACKDROP: f32 = 0.55;pub const KVT_TICKET_WINDOW_TAG: &str = "kvt-asclepius-window";/// Een link naar een Asclepius-ticket (`…/asclepius/index.php?open=…`): heb je toegang, dan/// opent het ticket in een venster in de app; anders gewoon in de browser. `false` als het/// geen ticketlink is of je niet gekoppeld bent (dan opent de shell de link zelf).pub fn open_ticket_link(url: &str, cx: &mut App) -> bool { if !installed(cx) || !matches!(link(cx), Link::Linked(_)) { return false; } let Some(id) = ticket_id_from_url(&base_url(), url) else { return false; }; let url = url.to_owned(); if is_demo(cx) { match demo_detail(id) { Some(detail) => cx.defer(move |cx| show_window(detail, cx)), None => cx.open_url(&url), } return true; } let Some((token, client)) = token_and_client(cx) else { return false; }; let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await }); cx.spawn(async move |cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(detail) => show_window(detail, cx), Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } // Geen toegang of Asclepius niet bereikbaar: een gewone link. cx.open_url(&url); } }); }) .detach(); true}fn show_window(detail: TicketDetail, cx: &mut App) { let Some(window) = cx .active_window() .or_else(|| cx.windows().into_iter().next()) else { return; }; let ticket = detail.ticket.clone(); window .update(cx, |_, window, cx| { let thread = cx.new(|cx| TicketThread::with_detail(ticket.id, Some(detail), window, cx)); update(cx, |kvt| kvt.ticket_window = Some(thread)); cx.refresh_windows(); }) .ok(); ticket_seen(&ticket, cx);}fn close_window(cx: &mut App) { update(cx, |kvt| kvt.ticket_window = None); cx.refresh_windows();}/// Laag voor `kvt::overlay`.pub(super) fn window_overlay(thread: Entity<TicketThread>) -> AnyElement { div() .id("kvt-ticket-window-layer") .absolute() .top_0() .left_0() .size_full() .flex() .items_center() .justify_center() .child( div() .id("kvt-ticket-window-backdrop") .absolute() .top_0() .left_0() .size_full() .bg(black().opacity(WINDOW_BACKDROP)) .occlude() .on_click(|_, _, cx| close_window(cx)), ) .child( div() .id("kvt-ticket-window") .debug_selector(|| KVT_TICKET_WINDOW_TAG.into()) .relative() .w(px(WINDOW_WIDTH)) .max_w(relative(1.)) .h(relative(0.85)) .m(px(WINDOW_MARGIN)) .rounded(px(RADIUS)) .dialog_surface() .overflow_hidden() .occlude() .child(thread) .child( div() .id("kvt-ticket-window-close") .absolute() .top(px(10.)) .right(px(10.)) .size(px(28.)) .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::popup_hover())) .on_click(|_, _, cx| close_window(cx)) .child(symbol("close", 16., theme::text_muted())), ), ) .into_any_element()}// --- demo ------------------------------------------------------------------------const DEMO_UNREAD: u64 = 4102;thread_local! { static DEMO_REPLIES: std::cell::RefCell<HashMap<u64, Vec<TicketMessage>>> = std::cell::RefCell::new(HashMap::new());}fn demo_ticket(id: u64, title: &str, status: &str, category: &str, updated: &str) -> Ticket { Ticket { id, title: title.to_owned(), category: category.to_owned(), user_email: super::demo::token().email, assigned_email: "ict.medewerker@example.com".to_owned(), status: status.to_owned(), created_at: "2026-01-12T09:15:00+01:00".to_owned(), updated_at: updated.to_owned(), message_count: 3, ..Ticket::default() }}pub(super) fn demo_tickets() -> Vec<Ticket> { vec![ Ticket { subcategory: "Laptop".to_owned(), ..demo_ticket( DEMO_UNREAD, "Laptop start niet meer op", "in behandeling", "Hardware", "2026-01-15T13:39:00+01:00", ) }, demo_ticket( 4098, "Toegang tot gedeelde map Projecten", "afwachtende op gebruiker", "Rechten en toegang", "2026-01-14T16:02:00+01:00", ), demo_ticket( 4090, "Nieuwe headset", "ingediend", "Hardware bestellen", "2026-01-13T10:20:00+01:00", ), demo_ticket( 4012, "Printer op kantoor geeft een fout", "afgehandeld", "Hardware", "2026-01-08T11:00:00+01:00", ), ]}fn demo_message( id: u64, email: &str, name: &str, role: &str, text: &str, at: &str,) -> TicketMessage { TicketMessage { id, sender_email: email.to_owned(), sender_role: role.to_owned(), sender_display_name: name.to_owned(), message_text: text.to_owned(), created_at: at.to_owned(), ..TicketMessage::default() }}pub(super) fn demo_detail(id: u64) -> Option<TicketDetail> { let ticket = demo_tickets().into_iter().find(|ticket| ticket.id == id)?; let me = super::demo::token(); let ict = "ict.medewerker@example.com"; let mut messages = vec![ demo_message( 1, &me.email, &me.name, "user", "Mijn laptop gaat niet meer aan sinds vanochtend. Het lampje knippert oranje.", "2026-01-15T09:15:00+01:00", ), demo_message( 2, ict, "Sam Ict", "admin", "Dank je. Kun je de lader een minuut loskoppelen en het opnieuw proberen? @dana.demo:examplecom", "2026-01-15T10:02:00+01:00", ), TicketMessage { is_ghost: true, ..demo_message( 3, ict, "Sam Ict", "admin", "Intern: garantie loopt nog tot maart, eventueel omruilen via de leverancier.", "2026-01-15T10:05:00+01:00", ) }, TicketMessage { attachments: vec![TicketAttachment { id: 77, original_name: "foto-lampje.jpg".to_owned(), mime_type: "image/jpeg".to_owned(), file_size: 120_000, }], ..demo_message( 4, &me.email, &me.name, "user", "Gedaan, hij knippert nog steeds. Foto erbij.", "2026-01-15T13:39:00+01:00", ) }, ]; if id != DEMO_UNREAD { messages.truncate(1); messages[0].message_text = format!("{}.", ticket.title); } DEMO_REPLIES.with(|replies| { messages.extend(replies.borrow().get(&id).cloned().unwrap_or_default()); }); Some(TicketDetail { description: messages[0].message_text.clone(), participant_emails: vec![me.email.clone(), "jonas.ortega@example.com".to_owned()], messages, ticket, })}fn demo_reply(id: u64, text: &str, email: &str) { let me = super::demo::token(); DEMO_REPLIES.with(|replies| { let mut replies = replies.borrow_mut(); let list = replies.entry(id).or_default(); list.push(demo_message( 100 + list.len() as u64, if email.is_empty() { &me.email } else { email }, &me.name, "user", text, &chrono::Local::now().to_rfc3339(), )); });}#[cfg(test)]mod tests { use super::{DEMO_UNREAD, demo_detail, demo_tickets, mention_display, when}; use kvt_sleutels::tickets::Ticket; #[test] fn dates_are_dutch_and_local() { let shown = when("2026-01-15T13:39:00+01:00"); assert!(shown.starts_with("15 jan 2026") || shown.starts_with("16 jan 2026")); assert_eq!(when("geen datum"), "geen datum"); } #[test] fn demo_has_a_ghost_and_a_closed_ticket() { let detail = demo_detail(DEMO_UNREAD).unwrap(); assert!(detail.messages.iter().any(|message| message.is_ghost)); assert!(demo_tickets().iter().any(Ticket::is_closed)); } #[test] fn mentions_render_as_first_names() { let (shown, ranges) = mention_display( "Graag @dana.demo:examplecom", &["dana.demo@example.com".to_owned()], ); assert_eq!(shown, "Graag @Dana"); assert_eq!(ranges, [6..11]); }}@@ -0,0 +1,224 @@
//! KVT-fork: minimaliseren, maximaliseren/herstellen en sluiten in de titelbalk.
//!
//! Alleen op Linux en Windows, en alleen als de instelling aan staat. Op macOS
//! blijven de verkeerslichten van het systeem. Sluiten volgt dezelfde route als
//! de systeemknop (inclusief sluiten naar de tray). Zie KVT-FORK.md.
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::h_flex;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use store::Store;
use crate::i18n::tr;
use crate::notify::NotificationCenter;
/// Kleine titelbalk-iconen, strak gegroepeerd zodat de zoekbalk ruimte houdt.
const CONTROL_SIZE: f32 = 20.;
const CONTROL_GAP: f32 = 0.;
/// Of de eigen knoppen en client-side decorations gewenst zijn.
pub fn enabled(cx: &App) -> bool {
app_base::kvt_window::available()
&& cx
.try_global::<Active>()
.map(|active| active.enabled)
.unwrap_or(app_base::kvt_window::DEFAULT_ENABLED)
}
pub fn install(store: &Store, cx: &mut App) {
cx.set_global(Active {
enabled: app_base::kvt_window::load(store),
});
}
/// Zet de instelling, vraagt de passende decorations aan en ververst de vensters.
pub fn set_enabled(enabled: bool, store: &Store, window: &Window, cx: &mut App) {
app_base::kvt_window::save(store, enabled);
cx.set_global(Active { enabled });
apply_decorations(window, enabled);
cx.refresh_windows();
}
/// Decorations voor het hoofdvenster bij het openen.
pub fn window_decorations(enabled: bool) -> WindowDecorations {
if enabled && app_base::kvt_window::available() {
WindowDecorations::Client
} else {
WindowDecorations::Server
}
}
pub fn apply_decorations(window: &Window, enabled: bool) {
if app_base::kvt_window::available() {
window.request_decorations(window_decorations(enabled));
}
}
pub fn title_bar_system_window_controls(cx: &App) -> bool {
!enabled(cx)
}
/// Knoppen rechts in de titelbalk, na «…» en de avatar, als één groep zodat
/// de zoekbalk bij een smal venster ruimte houdt. Leeg als ze niet getoond
/// moeten worden.
pub fn title_buttons(
notifications: &Entity<NotificationCenter>,
window: &Window,
cx: &App,
) -> Vec<AnyElement> {
if !enabled(cx) {
return Vec::new();
}
let supported = window.window_controls();
let maximized = window.is_maximized();
let mut buttons = Vec::new();
if supported.minimize {
buttons.push(control_button(
"title-window-minimize",
"shell/title-bar/minimize",
IconName::ChevronDown,
tr("kvt.window.minimize"),
Action::Minimize,
notifications.clone(),
));
}
if supported.maximize {
if maximized {
buttons.push(control_button(
"title-window-restore",
"shell/title-bar/restore",
IconName::WindowRestore,
tr("kvt.window.restore"),
Action::Restore,
notifications.clone(),
));
} else {
buttons.push(control_button(
"title-window-maximize",
"shell/title-bar/maximize",
IconName::ChevronUp,
tr("kvt.window.maximize"),
Action::Maximize,
notifications.clone(),
));
}
}
buttons.push(control_button(
"title-window-close",
"shell/title-bar/close",
IconName::Close,
tr("kvt.window.close"),
Action::Close,
notifications.clone(),
));
if buttons.is_empty() {
return Vec::new();
}
vec![
h_flex()
.debug_selector(|| "shell/title-bar/window-controls".into())
.flex_none()
.h_full()
.items_center()
.gap(px(CONTROL_GAP))
.children(buttons)
.into_any_element(),
]
}
#[derive(Clone, Copy)]
enum Action {
Minimize,
Maximize,
Restore,
Close,
}
impl Action {
fn window_control_area(self) -> WindowControlArea {
match self {
Self::Minimize => WindowControlArea::Min,
Self::Maximize | Self::Restore => WindowControlArea::Max,
Self::Close => WindowControlArea::Close,
}
}
}
fn control_button(
id: &'static str,
selector: &'static str,
icon: IconName,
tooltip: String,
action: Action,
notifications: Entity<NotificationCenter>,
) -> AnyElement {
let is_windows = cfg!(target_os = "windows");
let is_linux = cfg!(target_os = "linux");
Button::new(id)
.ghost()
.compact()
.p_0()
.size(px(CONTROL_SIZE))
.icon(icon)
.tooltip(tooltip)
.debug_selector(|| selector.into())
.when(is_windows, |button| {
button.window_control_area(action.window_control_area())
})
.when(is_linux || cfg!(not(any(target_os = "windows", target_os = "macos"))), |button| {
button
.on_mouse_down(MouseButton::Left, |_, window, cx| {
window.prevent_default();
cx.stop_propagation();
})
.on_click(move |_, window, cx| {
cx.stop_propagation();
match action {
Action::Minimize => window.minimize_window(),
Action::Maximize | Action::Restore => window.zoom_window(),
Action::Close => close_main_window(¬ifications, window, cx),
}
})
})
.into_any_element()
}
/// Zelfde pad als de systeem-sluitknop: `on_window_should_close` in de shell
/// (tray verbergen of echt sluiten).
fn close_main_window(
notifications: &Entity<NotificationCenter>,
window: &mut Window,
cx: &mut App,
) {
let keep_open = notifications.update(cx, |notifications, cx| notifications.intercept_close(cx));
if !keep_open {
window.remove_window();
}
}
struct Active {
enabled: bool,
}
impl Global for Active {}
#[cfg(test)]
mod tests {
use super::window_decorations;
use gpui_kit::WindowDecorations;
#[test]
fn client_decorations_follow_the_setting() {
assert_eq!(
window_decorations(true),
if cfg!(target_os = "macos") {
WindowDecorations::Server
} else {
WindowDecorations::Client
}
);
assert_eq!(window_decorations(false), WindowDecorations::Server);
}
}
@@ -0,0 +1,224 @@//! KVT-fork: minimaliseren, maximaliseren/herstellen en sluiten in de titelbalk.//!//! Alleen op Linux en Windows, en alleen als de instelling aan staat. Op macOS//! blijven de verkeerslichten van het systeem. Sluiten volgt dezelfde route als//! de systeemknop (inclusief sluiten naar de tray). Zie KVT-FORK.md.use gpui_kit::assets::IconName;use gpui_kit::component::button::{Button, ButtonVariants as _};use gpui_kit::component::h_flex;use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::*;use store::Store;use crate::i18n::tr;use crate::notify::NotificationCenter;/// Kleine titelbalk-iconen, strak gegroepeerd zodat de zoekbalk ruimte houdt.const CONTROL_SIZE: f32 = 20.;const CONTROL_GAP: f32 = 0.;/// Of de eigen knoppen en client-side decorations gewenst zijn.pub fn enabled(cx: &App) -> bool { app_base::kvt_window::available() && cx .try_global::<Active>() .map(|active| active.enabled) .unwrap_or(app_base::kvt_window::DEFAULT_ENABLED)}pub fn install(store: &Store, cx: &mut App) { cx.set_global(Active { enabled: app_base::kvt_window::load(store), });}/// Zet de instelling, vraagt de passende decorations aan en ververst de vensters.pub fn set_enabled(enabled: bool, store: &Store, window: &Window, cx: &mut App) { app_base::kvt_window::save(store, enabled); cx.set_global(Active { enabled }); apply_decorations(window, enabled); cx.refresh_windows();}/// Decorations voor het hoofdvenster bij het openen.pub fn window_decorations(enabled: bool) -> WindowDecorations { if enabled && app_base::kvt_window::available() { WindowDecorations::Client } else { WindowDecorations::Server }}pub fn apply_decorations(window: &Window, enabled: bool) { if app_base::kvt_window::available() { window.request_decorations(window_decorations(enabled)); }}pub fn title_bar_system_window_controls(cx: &App) -> bool { !enabled(cx)}/// Knoppen rechts in de titelbalk, na «…» en de avatar, als één groep zodat/// de zoekbalk bij een smal venster ruimte houdt. Leeg als ze niet getoond/// moeten worden.pub fn title_buttons( notifications: &Entity<NotificationCenter>, window: &Window, cx: &App,) -> Vec<AnyElement> { if !enabled(cx) { return Vec::new(); } let supported = window.window_controls(); let maximized = window.is_maximized(); let mut buttons = Vec::new(); if supported.minimize { buttons.push(control_button( "title-window-minimize", "shell/title-bar/minimize", IconName::ChevronDown, tr("kvt.window.minimize"), Action::Minimize, notifications.clone(), )); } if supported.maximize { if maximized { buttons.push(control_button( "title-window-restore", "shell/title-bar/restore", IconName::WindowRestore, tr("kvt.window.restore"), Action::Restore, notifications.clone(), )); } else { buttons.push(control_button( "title-window-maximize", "shell/title-bar/maximize", IconName::ChevronUp, tr("kvt.window.maximize"), Action::Maximize, notifications.clone(), )); } } buttons.push(control_button( "title-window-close", "shell/title-bar/close", IconName::Close, tr("kvt.window.close"), Action::Close, notifications.clone(), )); if buttons.is_empty() { return Vec::new(); } vec![ h_flex() .debug_selector(|| "shell/title-bar/window-controls".into()) .flex_none() .h_full() .items_center() .gap(px(CONTROL_GAP)) .children(buttons) .into_any_element(), ]}#[derive(Clone, Copy)]enum Action { Minimize, Maximize, Restore, Close,}impl Action { fn window_control_area(self) -> WindowControlArea { match self { Self::Minimize => WindowControlArea::Min, Self::Maximize | Self::Restore => WindowControlArea::Max, Self::Close => WindowControlArea::Close, } }}fn control_button( id: &'static str, selector: &'static str, icon: IconName, tooltip: String, action: Action, notifications: Entity<NotificationCenter>,) -> AnyElement { let is_windows = cfg!(target_os = "windows"); let is_linux = cfg!(target_os = "linux"); Button::new(id) .ghost() .compact() .p_0() .size(px(CONTROL_SIZE)) .icon(icon) .tooltip(tooltip) .debug_selector(|| selector.into()) .when(is_windows, |button| { button.window_control_area(action.window_control_area()) }) .when(is_linux || cfg!(not(any(target_os = "windows", target_os = "macos"))), |button| { button .on_mouse_down(MouseButton::Left, |_, window, cx| { window.prevent_default(); cx.stop_propagation(); }) .on_click(move |_, window, cx| { cx.stop_propagation(); match action { Action::Minimize => window.minimize_window(), Action::Maximize | Action::Restore => window.zoom_window(), Action::Close => close_main_window(¬ifications, window, cx), } }) }) .into_any_element()}/// Zelfde pad als de systeem-sluitknop: `on_window_should_close` in de shell/// (tray verbergen of echt sluiten).fn close_main_window( notifications: &Entity<NotificationCenter>, window: &mut Window, cx: &mut App,) { let keep_open = notifications.update(cx, |notifications, cx| notifications.intercept_close(cx)); if !keep_open { window.remove_window(); }}struct Active { enabled: bool,}impl Global for Active {}#[cfg(test)]mod tests { use super::window_decorations; use gpui_kit::WindowDecorations; #[test] fn client_decorations_follow_the_setting() { assert_eq!( window_decorations(true), if cfg!(target_os = "macos") { WindowDecorations::Server } else { WindowDecorations::Client } ); assert_eq!(window_decorations(false), WindowDecorations::Server); }}@@ -3124,6 +3124,11 @@ const STATE_RING_COLORS: &[&str] = &[
"if state.failed",
];
const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
(
"kvt/tickets.rs",
"rgb(GHOST_BORDER)",
"KVT-fork: ghost-berichten van Asclepius houden de roze rand van het web",
),
(
"notify/ring_view.rs",
"theme::green()",
@@ -3124,6 +3124,11 @@ const STATE_RING_COLORS: &[&str] = &[ "if state.failed", "if state.failed",];];const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[ ( "kvt/tickets.rs", "rgb(GHOST_BORDER)", "KVT-fork: ghost-berichten van Asclepius houden de roze rand van het web", ), ( ( "notify/ring_view.rs", "notify/ring_view.rs", "theme::green()", "theme::green()",@@ -168,6 +168,9 @@ fn main_window_options(cx: &App) -> WindowOptions {
options.window_bounds = Some(WindowBounds::Windowed(bounds));
options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
options.app_id = Some(LINUX_APP_ID.to_owned());
options.window_decorations = Some(crate::kvt::window_controls::window_decorations(
crate::kvt::window_controls::enabled(cx),
));
if let Some(titlebar) = options.titlebar.as_mut() {
titlebar.title = Some(APP_NAME.into());
}
@@ -326,6 +329,7 @@ fn main() {
.detach();
theme::load_fonts(cx);
active_appearance::install(&store, cx);
crate::kvt::window_controls::install(&store, cx);
active_locale::install(&store, cx);
theme::apply(cx);
bind_keys(cx);
@@ -168,6 +168,9 @@ fn main_window_options(cx: &App) -> WindowOptions { options.window_bounds = Some(WindowBounds::Windowed(bounds)); options.window_bounds = Some(WindowBounds::Windowed(bounds)); options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT))); options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT))); options.app_id = Some(LINUX_APP_ID.to_owned()); options.app_id = Some(LINUX_APP_ID.to_owned()); options.window_decorations = Some(crate::kvt::window_controls::window_decorations( crate::kvt::window_controls::enabled(cx), )); if let Some(titlebar) = options.titlebar.as_mut() { if let Some(titlebar) = options.titlebar.as_mut() { titlebar.title = Some(APP_NAME.into()); titlebar.title = Some(APP_NAME.into()); } }@@ -326,6 +329,7 @@ fn main() { .detach(); .detach(); theme::load_fonts(cx); theme::load_fonts(cx); active_appearance::install(&store, cx); active_appearance::install(&store, cx); crate::kvt::window_controls::install(&store, cx); active_locale::install(&store, cx); active_locale::install(&store, cx); theme::apply(cx); theme::apply(cx); bind_keys(cx); bind_keys(cx);@@ -2,7 +2,7 @@ use gpui_kit::component::{h_flex, v_flex};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};
use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled, toggle_row};
use crate::active_appearance;
use crate::active_locale;
use crate::app_state::AppState;
@@ -120,6 +120,21 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
theme_choices,
),
))
.when(app_base::kvt_window::available(), |view| {
let store = app.clone();
let on = crate::kvt::window_controls::enabled(cx);
view.child(toggle_row(
"settings-window-controls",
tr("kvt.window.title"),
tr("kvt.window.detail"),
theme::text_muted(),
on,
)
.on_click(move |_, window, cx| {
let store = store.read(cx).store.clone();
crate::kvt::window_controls::set_enabled(!on, &store, window, cx);
}))
})
.child(choice_group(
tr("settings.appearance.color_scheme"),
tr("settings.appearance.color_scheme_detail"),
@@ -2,7 +2,7 @@ use gpui_kit::component::{h_flex, v_flex};use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::*;use gpui_kit::*;use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled, toggle_row};use crate::active_appearance;use crate::active_appearance;use crate::active_locale;use crate::active_locale;use crate::app_state::AppState;use crate::app_state::AppState;@@ -120,6 +120,21 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div { theme_choices, theme_choices, ), ), )) )) .when(app_base::kvt_window::available(), |view| { let store = app.clone(); let on = crate::kvt::window_controls::enabled(cx); view.child(toggle_row( "settings-window-controls", tr("kvt.window.title"), tr("kvt.window.detail"), theme::text_muted(), on, ) .on_click(move |_, window, cx| { let store = store.read(cx).store.clone(); crate::kvt::window_controls::set_enabled(!on, &store, window, cx); })) }) .child(choice_group( .child(choice_group( tr("settings.appearance.color_scheme"), tr("settings.appearance.color_scheme"), tr("settings.appearance.color_scheme_detail"), tr("settings.appearance.color_scheme_detail"),@@ -174,6 +174,19 @@ impl ItemKind {
fn is_object(&self) -> bool {
matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
}
fn is_custom_emoji(&self) -> bool {
matches!(self, ItemKind::Remote(remote) if remote.is_custom_emoji())
}
}
impl AttachmentTray {
pub fn attachment_count(&self) -> usize {
self.items
.iter()
.filter(|item| !item.kind.is_custom_emoji())
.count()
}
}
impl TrayItem {
@@ -269,7 +282,7 @@ impl AttachmentTray {
/// `None` when the tray is full.
pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
self.notice = None;
if self.items.len() >= MAX_ATTACHMENTS {
if !remote.is_custom_emoji() && self.attachment_count() >= MAX_ATTACHMENTS {
self.notice = Some(limit_notice(1));
return None;
}
@@ -303,7 +316,7 @@ impl AttachmentTray {
reference: FileReference,
) -> Option<u64> {
self.notice = None;
if self.items.len() >= MAX_ATTACHMENTS {
if self.attachment_count() >= MAX_ATTACHMENTS {
self.notice = Some(limit_notice(1));
return None;
}
@@ -327,7 +340,7 @@ impl AttachmentTray {
self.notice = None;
let accepted = names
.len()
.min(MAX_ATTACHMENTS.saturating_sub(self.items.len()));
.min(MAX_ATTACHMENTS.saturating_sub(self.attachment_count()));
let ids = names[..accepted]
.iter()
.map(|name| self.push(name.clone(), 0, ItemKind::Reading))
@@ -1476,6 +1489,26 @@ mod tests {
assert!(tray.notice().is_some());
}
fn org_emoji() -> RemoteImage {
RemoteImage::custom_emoji(&teams_core::OrgEmoji {
id: "em-1".into(),
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
name: "ship-it".into(),
keywords: vec![],
source: None,
})
}
#[test]
fn a_full_tray_still_accepts_a_custom_emoji() {
let mut tray = AttachmentTray::default();
for _ in 0..MAX_ATTACHMENTS {
assert!(tray.add_remote(gif("Wave")).is_some());
}
assert!(tray.add_remote(org_emoji()).is_some());
assert!(tray.add_remote(gif("Wave")).is_none());
}
#[test]
fn images_come_back_in_the_order_asked_for_and_only_when_known() {
let mut tray = AttachmentTray::default();
@@ -174,6 +174,19 @@ impl ItemKind { fn is_object(&self) -> bool { fn is_object(&self) -> bool { matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_)) matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_)) } } fn is_custom_emoji(&self) -> bool { matches!(self, ItemKind::Remote(remote) if remote.is_custom_emoji()) }}impl AttachmentTray { pub fn attachment_count(&self) -> usize { self.items .iter() .filter(|item| !item.kind.is_custom_emoji()) .count() }}}impl TrayItem {impl TrayItem {@@ -269,7 +282,7 @@ impl AttachmentTray { /// `None` when the tray is full. /// `None` when the tray is full. pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> { pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> { self.notice = None; self.notice = None; if self.items.len() >= MAX_ATTACHMENTS { if !remote.is_custom_emoji() && self.attachment_count() >= MAX_ATTACHMENTS { self.notice = Some(limit_notice(1)); self.notice = Some(limit_notice(1)); return None; return None; } }@@ -303,7 +316,7 @@ impl AttachmentTray { reference: FileReference, reference: FileReference, ) -> Option<u64> { ) -> Option<u64> { self.notice = None; self.notice = None; if self.items.len() >= MAX_ATTACHMENTS { if self.attachment_count() >= MAX_ATTACHMENTS { self.notice = Some(limit_notice(1)); self.notice = Some(limit_notice(1)); return None; return None; } }@@ -327,7 +340,7 @@ impl AttachmentTray { self.notice = None; self.notice = None; let accepted = names let accepted = names .len() .len() .min(MAX_ATTACHMENTS.saturating_sub(self.items.len())); .min(MAX_ATTACHMENTS.saturating_sub(self.attachment_count())); let ids = names[..accepted] let ids = names[..accepted] .iter() .iter() .map(|name| self.push(name.clone(), 0, ItemKind::Reading)) .map(|name| self.push(name.clone(), 0, ItemKind::Reading))@@ -1476,6 +1489,26 @@ mod tests { assert!(tray.notice().is_some()); assert!(tray.notice().is_some()); } } fn org_emoji() -> RemoteImage { RemoteImage::custom_emoji(&teams_core::OrgEmoji { id: "em-1".into(), document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(), name: "ship-it".into(), keywords: vec![], source: None, }) } #[test] fn a_full_tray_still_accepts_a_custom_emoji() { let mut tray = AttachmentTray::default(); for _ in 0..MAX_ATTACHMENTS { assert!(tray.add_remote(gif("Wave")).is_some()); } assert!(tray.add_remote(org_emoji()).is_some()); assert!(tray.add_remote(gif("Wave")).is_none()); } #[test] #[test] fn images_come_back_in_the_order_asked_for_and_only_when_known() { fn images_come_back_in_the_order_asked_for_and_only_when_known() { let mut tray = AttachmentTray::default(); let mut tray = AttachmentTray::default();@@ -2120,7 +2120,7 @@ impl Composer {
/// Images that no longer sit in the text give way to new attachments.
fn make_room(&mut self, needed: usize, cx: &App) {
if self.tray.items().len() + needed > MAX_ATTACHMENTS {
if self.tray.attachment_count() + needed > MAX_ATTACHMENTS {
let referenced: Vec<u64> = self
.input
.read(cx)
@@ -2187,7 +2187,9 @@ impl Composer {
window: &mut Window,
cx: &mut Context<Self>,
) {
self.make_room(1, cx);
if !image.is_custom_emoji() {
self.make_room(1, cx);
}
if let Some(id) = self.tray.add_remote(image) {
self.insert_image_token(id, window, cx);
}
@@ -2120,7 +2120,7 @@ impl Composer { /// Images that no longer sit in the text give way to new attachments. /// Images that no longer sit in the text give way to new attachments. fn make_room(&mut self, needed: usize, cx: &App) { fn make_room(&mut self, needed: usize, cx: &App) { if self.tray.items().len() + needed > MAX_ATTACHMENTS { if self.tray.attachment_count() + needed > MAX_ATTACHMENTS { let referenced: Vec<u64> = self let referenced: Vec<u64> = self .input .input .read(cx) .read(cx)@@ -2187,7 +2187,9 @@ impl Composer { window: &mut Window, window: &mut Window, cx: &mut Context<Self>, cx: &mut Context<Self>, ) { ) { self.make_room(1, cx); if !image.is_custom_emoji() { self.make_room(1, cx); } if let Some(id) = self.tray.add_remote(image) { if let Some(id) = self.tray.add_remote(image) { self.insert_image_token(id, window, cx); self.insert_image_token(id, window, cx); } }@@ -11,13 +11,17 @@ use gpui_kit::component::{
};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use teams_core::Gif;
use gpui_kit::component::tooltip::Tooltip;
use std::collections::HashMap;
use teams_core::{Gif, OrgEmoji};
use super::skin_tone_choices::{tone_badge, tone_choices};
use crate::app_state::AppState;
use crate::emoji;
use crate::emoticons;
use crate::gifs::{self, GifError};
use crate::i18n::{tr, tr_args};
use crate::org_emojis::{self, OrgEmojiError};
use crate::remote_image::{RemoteImage, image_source};
use crate::stickers::{self, Sticker};
use crate::theme;
@@ -39,6 +43,10 @@ const GIF_MIN_HEIGHT: f32 = 48.;
const GIF_MAX_HEIGHT: f32 = 200.;
const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];
const STICKER_COLUMNS: usize = 4;
const ORG_COLUMNS: usize = 8;
const ORG_GAP: f32 = 4.;
const ORG_CELL: f32 =
(CONTENT_WIDTH - ORG_GAP * (ORG_COLUMNS - 1) as f32) / ORG_COLUMNS as f32;
const STICKER_GAP: f32 = 6.;
const POPULAR_LABEL: &str = "Beliebt";
const TILE_RADIUS: f32 = 6.;
@@ -48,16 +56,18 @@ enum Tab {
Emoji,
Gif,
Sticker,
Org,
}
impl Tab {
const ALL: [Tab; 3] = [Tab::Emoji, Tab::Gif, Tab::Sticker];
const ALL: [Tab; 4] = [Tab::Emoji, Tab::Gif, Tab::Sticker, Tab::Org];
fn key(self) -> &'static str {
match self {
Tab::Emoji => "emoji",
Tab::Gif => "gif",
Tab::Sticker => "sticker",
Tab::Org => "org",
}
}
@@ -65,20 +75,38 @@ impl Tab {
Tab::ALL.into_iter().find(|tab| tab.key() == key)
}
fn label(self) -> &'static str {
match self {
Tab::Emoji => "Emoji",
Tab::Gif => "GIF",
Tab::Sticker => "Sticker",
}
fn label(self) -> String {
tr(match self {
Tab::Emoji => "fun_picker.tab.emoji",
Tab::Gif => "fun_picker.tab.gif",
Tab::Sticker => "fun_picker.tab.sticker",
Tab::Org => "fun_picker.tab.org",
})
}
fn placeholder(self) -> &'static str {
match self {
Tab::Emoji => "Emoji suchen",
Tab::Gif => "GIFs suchen",
Tab::Sticker => "Sticker suchen",
}
fn placeholder(self) -> String {
tr(match self {
Tab::Emoji => "fun_picker.search.emoji",
Tab::Gif => "fun_picker.search.gif",
Tab::Sticker => "fun_picker.search.sticker",
Tab::Org => "fun_picker.search.org",
})
}
}
enum OrgState {
Loading,
Ready(Vec<OrgEmoji>),
Failed,
}
fn org_empty_message(query: &str) -> String {
if query.is_empty() {
tr("fun_picker.org.empty")
} else {
let mut args = HashMap::new();
args.insert("query".into(), query.to_owned());
tr_args("fun_picker.org.empty_query", &args)
}
}
@@ -122,6 +150,10 @@ pub struct FunPicker {
chip: StickerChip,
sticker_rows: Vec<Vec<&'static Sticker>>,
sticker_scroll: UniformListScrollHandle,
org: OrgState,
org_generation: u64,
org_task: Option<Task<()>>,
org_scroll: UniformListScrollHandle,
_subscription: Subscription,
}
@@ -218,6 +250,10 @@ impl FunPicker {
chip: StickerChip::Popular,
sticker_rows: sticker_rows("", StickerChip::Popular),
sticker_scroll: UniformListScrollHandle::new(),
org: OrgState::Loading,
org_generation: 0,
org_task: None,
org_scroll: UniformListScrollHandle::new(),
_subscription: subscription,
}
}
@@ -271,6 +307,7 @@ impl FunPicker {
self.sticker_rows = sticker_rows(&self.query, self.chip);
self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);
}
Tab::Org => self.load_org_emojis(cx),
}
cx.notify();
}
@@ -279,7 +316,7 @@ impl FunPicker {
&mut self,
input: &Entity<InputState>,
event: &InputEvent,
_: &mut Window,
window: &mut Window,
cx: &mut Context<Self>,
) {
match event {
@@ -299,6 +336,12 @@ impl FunPicker {
self.pick_emoji(&glyph, cx);
}
}
InputEvent::PressEnter { .. } if self.tab == Tab::Org => {
if let Some(emoji) = self.visible_org_emojis().first().cloned() {
let image = RemoteImage::custom_emoji(&emoji);
self.pick_image(image, window, cx);
}
}
_ => {}
}
}
@@ -391,11 +434,11 @@ impl FunPicker {
div()
.id(("fun-picker-tab", tab as usize))
.h(px(32.))
.px(px(14.))
.px(px(8.))
.flex()
.items_center()
.cursor_pointer()
.text_size(px(13.))
.text_size(px(12.))
.font_weight(FontWeight::SEMIBOLD)
.border_b_2()
.border_color(if selected {
@@ -729,6 +772,156 @@ impl FunPicker {
.child(div().flex_1().min_h_0().child(grid))
.into_any_element()
}
fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
match &self.org {
OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
.into_iter()
.cloned()
.collect(),
_ => Vec::new(),
}
}
fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
if matches!(self.org, OrgState::Ready(_)) {
self.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
return;
}
self.org_generation += 1;
let generation = self.org_generation;
self.org = OrgState::Loading;
let (demo, engine) = {
let state = self.app.read(cx);
(state.mode.demo, state.engine.clone())
};
self.org_task = Some(cx.spawn(async move |this, cx| {
let outcome = org_emojis::list(engine, demo, false)
.await
.unwrap_or(Err(OrgEmojiError::Failed));
this.update(cx, |this, cx| {
if this.org_generation != generation {
return;
}
this.org = match outcome {
Ok(emojis) => OrgState::Ready(emojis),
Err(_) => OrgState::Failed,
};
this.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
cx.notify();
})
.ok();
}));
}
fn reload_org_emojis(&mut self, cx: &mut Context<Self>) {
self.org = OrgState::Loading;
self.load_org_emojis(cx);
}
fn org_tile(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
let picked = RemoteImage::custom_emoji(emoji);
let name = emoji.name.clone();
let label = name.clone();
v_flex()
.id(("fun-picker-org", index))
.w(px(ORG_CELL))
.flex_none()
.items_center()
.gap(px(2.))
.p(px(2.))
.rounded(px(TILE_RADIUS))
.cursor_pointer()
.hover(|tile| tile.bg(theme::popup_hover()))
.child(
img(bounded(image_source(&emoji.image_url())))
.size(px(ORG_CELL - 8.))
.object_fit(ObjectFit::Contain),
)
.child(
div()
.w(px(ORG_CELL))
.overflow_hidden()
.text_ellipsis()
.text_center()
.text_size(px(9.))
.text_color(theme::text_muted())
.child(label),
)
.tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
.on_click(cx.listener(move |this, _, window, cx| {
this.pick_image(picked.clone(), window, cx)
}))
.into_any_element()
}
fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
match &self.org {
OrgState::Loading => Self::message(String::new())
.child(
div()
.size_full()
.flex()
.items_center()
.justify_center()
.text_color(theme::text_muted())
.child("…"),
)
.into_any_element(),
OrgState::Failed => Self::message(tr("fun_picker.org.failed"))
.child(
div()
.id("fun-picker-org-retry")
.h(px(28.))
.px(px(12.))
.flex()
.items_center()
.rounded(px(6.))
.bg(theme::popup_hover())
.text_color(theme::text())
.cursor_pointer()
.hover(|button| button.bg(theme::border_strong()))
.child(tr("fun_picker.org.retry"))
.on_click(cx.listener(|this, _, _, cx| this.reload_org_emojis(cx))),
)
.into_any_element(),
OrgState::Ready(emojis) => {
let visible = org_emojis::filter(emojis.as_slice(), &self.query);
if visible.is_empty() {
return Self::message(org_empty_message(&self.query)).into_any_element();
}
let rows: Vec<Vec<OrgEmoji>> = visible
.into_iter()
.cloned()
.collect::<Vec<_>>()
.chunks(ORG_COLUMNS)
.map(|chunk| chunk.to_vec())
.collect();
uniform_list(
"fun-picker-org-list",
rows.len(),
cx.processor(move |this, range: std::ops::Range<usize>, _, cx| {
range
.map(|index| {
let tiles = rows[index].iter().enumerate().map(|(column, emoji)| {
this.org_tile(emoji, index * ORG_COLUMNS + column, cx)
});
h_flex()
.h(px(ORG_CELL + 16. + ORG_GAP))
.gap(px(ORG_GAP))
.children(tiles)
.into_any_element()
})
.collect::<Vec<_>>()
}),
)
.track_scroll(&self.org_scroll)
.size_full()
.into_any_element()
}
}
}
}
impl Render for FunPicker {
@@ -738,6 +931,7 @@ impl Render for FunPicker {
Tab::Emoji => self.render_emoji(cx),
Tab::Gif => self.render_gifs(cx),
Tab::Sticker => self.render_stickers(cx),
Tab::Org => self.render_org(cx),
};
v_flex()
.w(px(WIDTH))
@@ -11,13 +11,17 @@ use gpui_kit::component::{};};use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::prelude::FluentBuilder as _;use gpui_kit::*;use gpui_kit::*;use teams_core::Gif;use gpui_kit::component::tooltip::Tooltip;use std::collections::HashMap;use teams_core::{Gif, OrgEmoji};use super::skin_tone_choices::{tone_badge, tone_choices};use super::skin_tone_choices::{tone_badge, tone_choices};use crate::app_state::AppState;use crate::app_state::AppState;use crate::emoji;use crate::emoji;use crate::emoticons;use crate::emoticons;use crate::gifs::{self, GifError};use crate::gifs::{self, GifError};use crate::i18n::{tr, tr_args};use crate::org_emojis::{self, OrgEmojiError};use crate::remote_image::{RemoteImage, image_source};use crate::remote_image::{RemoteImage, image_source};use crate::stickers::{self, Sticker};use crate::stickers::{self, Sticker};use crate::theme;use crate::theme;@@ -39,6 +43,10 @@ const GIF_MIN_HEIGHT: f32 = 48.;const GIF_MAX_HEIGHT: f32 = 200.;const GIF_MAX_HEIGHT: f32 = 200.;const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];const STICKER_COLUMNS: usize = 4;const STICKER_COLUMNS: usize = 4;const ORG_COLUMNS: usize = 8;const ORG_GAP: f32 = 4.;const ORG_CELL: f32 = (CONTENT_WIDTH - ORG_GAP * (ORG_COLUMNS - 1) as f32) / ORG_COLUMNS as f32;const STICKER_GAP: f32 = 6.;const STICKER_GAP: f32 = 6.;const POPULAR_LABEL: &str = "Beliebt";const POPULAR_LABEL: &str = "Beliebt";const TILE_RADIUS: f32 = 6.;const TILE_RADIUS: f32 = 6.;@@ -48,16 +56,18 @@ enum Tab { Emoji, Emoji, Gif, Gif, Sticker, Sticker, Org,}}impl Tab {impl Tab { const ALL: [Tab; 3] = [Tab::Emoji, Tab::Gif, Tab::Sticker]; const ALL: [Tab; 4] = [Tab::Emoji, Tab::Gif, Tab::Sticker, Tab::Org]; fn key(self) -> &'static str { fn key(self) -> &'static str { match self { match self { Tab::Emoji => "emoji", Tab::Emoji => "emoji", Tab::Gif => "gif", Tab::Gif => "gif", Tab::Sticker => "sticker", Tab::Sticker => "sticker", Tab::Org => "org", } } } }@@ -65,20 +75,38 @@ impl Tab { Tab::ALL.into_iter().find(|tab| tab.key() == key) Tab::ALL.into_iter().find(|tab| tab.key() == key) } } fn label(self) -> &'static str { fn label(self) -> String { match self { tr(match self { Tab::Emoji => "Emoji", Tab::Emoji => "fun_picker.tab.emoji", Tab::Gif => "GIF", Tab::Gif => "fun_picker.tab.gif", Tab::Sticker => "Sticker", Tab::Sticker => "fun_picker.tab.sticker", } Tab::Org => "fun_picker.tab.org", }) } } fn placeholder(self) -> &'static str { fn placeholder(self) -> String { match self { tr(match self { Tab::Emoji => "Emoji suchen", Tab::Emoji => "fun_picker.search.emoji", Tab::Gif => "GIFs suchen", Tab::Gif => "fun_picker.search.gif", Tab::Sticker => "Sticker suchen", Tab::Sticker => "fun_picker.search.sticker", } Tab::Org => "fun_picker.search.org", }) }}enum OrgState { Loading, Ready(Vec<OrgEmoji>), Failed,}fn org_empty_message(query: &str) -> String { if query.is_empty() { tr("fun_picker.org.empty") } else { let mut args = HashMap::new(); args.insert("query".into(), query.to_owned()); tr_args("fun_picker.org.empty_query", &args) } }}}@@ -122,6 +150,10 @@ pub struct FunPicker { chip: StickerChip, chip: StickerChip, sticker_rows: Vec<Vec<&'static Sticker>>, sticker_rows: Vec<Vec<&'static Sticker>>, sticker_scroll: UniformListScrollHandle, sticker_scroll: UniformListScrollHandle, org: OrgState, org_generation: u64, org_task: Option<Task<()>>, org_scroll: UniformListScrollHandle, _subscription: Subscription, _subscription: Subscription,}}@@ -218,6 +250,10 @@ impl FunPicker { chip: StickerChip::Popular, chip: StickerChip::Popular, sticker_rows: sticker_rows("", StickerChip::Popular), sticker_rows: sticker_rows("", StickerChip::Popular), sticker_scroll: UniformListScrollHandle::new(), sticker_scroll: UniformListScrollHandle::new(), org: OrgState::Loading, org_generation: 0, org_task: None, org_scroll: UniformListScrollHandle::new(), _subscription: subscription, _subscription: subscription, } } } }@@ -271,6 +307,7 @@ impl FunPicker { self.sticker_rows = sticker_rows(&self.query, self.chip); self.sticker_rows = sticker_rows(&self.query, self.chip); self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top); self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top); } } Tab::Org => self.load_org_emojis(cx), } } cx.notify(); cx.notify(); } }@@ -279,7 +316,7 @@ impl FunPicker { &mut self, &mut self, input: &Entity<InputState>, input: &Entity<InputState>, event: &InputEvent, event: &InputEvent, _: &mut Window, window: &mut Window, cx: &mut Context<Self>, cx: &mut Context<Self>, ) { ) { match event { match event {@@ -299,6 +336,12 @@ impl FunPicker { self.pick_emoji(&glyph, cx); self.pick_emoji(&glyph, cx); } } } } InputEvent::PressEnter { .. } if self.tab == Tab::Org => { if let Some(emoji) = self.visible_org_emojis().first().cloned() { let image = RemoteImage::custom_emoji(&emoji); self.pick_image(image, window, cx); } } _ => {} _ => {} } } } }@@ -391,11 +434,11 @@ impl FunPicker { div() div() .id(("fun-picker-tab", tab as usize)) .id(("fun-picker-tab", tab as usize)) .h(px(32.)) .h(px(32.)) .px(px(14.)) .px(px(8.)) .flex() .flex() .items_center() .items_center() .cursor_pointer() .cursor_pointer() .text_size(px(13.)) .text_size(px(12.)) .font_weight(FontWeight::SEMIBOLD) .font_weight(FontWeight::SEMIBOLD) .border_b_2() .border_b_2() .border_color(if selected { .border_color(if selected {@@ -729,6 +772,156 @@ impl FunPicker { .child(div().flex_1().min_h_0().child(grid)) .child(div().flex_1().min_h_0().child(grid)) .into_any_element() .into_any_element() } } fn visible_org_emojis(&self) -> Vec<OrgEmoji> { match &self.org { OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query) .into_iter() .cloned() .collect(), _ => Vec::new(), } } fn load_org_emojis(&mut self, cx: &mut Context<Self>) { if matches!(self.org, OrgState::Ready(_)) { self.org_scroll.scroll_to_item(0, ScrollStrategy::Top); return; } self.org_generation += 1; let generation = self.org_generation; self.org = OrgState::Loading; let (demo, engine) = { let state = self.app.read(cx); (state.mode.demo, state.engine.clone()) }; self.org_task = Some(cx.spawn(async move |this, cx| { let outcome = org_emojis::list(engine, demo, false) .await .unwrap_or(Err(OrgEmojiError::Failed)); this.update(cx, |this, cx| { if this.org_generation != generation { return; } this.org = match outcome { Ok(emojis) => OrgState::Ready(emojis), Err(_) => OrgState::Failed, }; this.org_scroll.scroll_to_item(0, ScrollStrategy::Top); cx.notify(); }) .ok(); })); } fn reload_org_emojis(&mut self, cx: &mut Context<Self>) { self.org = OrgState::Loading; self.load_org_emojis(cx); } fn org_tile(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement { let picked = RemoteImage::custom_emoji(emoji); let name = emoji.name.clone(); let label = name.clone(); v_flex() .id(("fun-picker-org", index)) .w(px(ORG_CELL)) .flex_none() .items_center() .gap(px(2.)) .p(px(2.)) .rounded(px(TILE_RADIUS)) .cursor_pointer() .hover(|tile| tile.bg(theme::popup_hover())) .child( img(bounded(image_source(&emoji.image_url()))) .size(px(ORG_CELL - 8.)) .object_fit(ObjectFit::Contain), ) .child( div() .w(px(ORG_CELL)) .overflow_hidden() .text_ellipsis() .text_center() .text_size(px(9.)) .text_color(theme::text_muted()) .child(label), ) .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx)) .on_click(cx.listener(move |this, _, window, cx| { this.pick_image(picked.clone(), window, cx) })) .into_any_element() } fn render_org(&self, cx: &mut Context<Self>) -> AnyElement { match &self.org { OrgState::Loading => Self::message(String::new()) .child( div() .size_full() .flex() .items_center() .justify_center() .text_color(theme::text_muted()) .child("…"), ) .into_any_element(), OrgState::Failed => Self::message(tr("fun_picker.org.failed")) .child( div() .id("fun-picker-org-retry") .h(px(28.)) .px(px(12.)) .flex() .items_center() .rounded(px(6.)) .bg(theme::popup_hover()) .text_color(theme::text()) .cursor_pointer() .hover(|button| button.bg(theme::border_strong())) .child(tr("fun_picker.org.retry")) .on_click(cx.listener(|this, _, _, cx| this.reload_org_emojis(cx))), ) .into_any_element(), OrgState::Ready(emojis) => { let visible = org_emojis::filter(emojis.as_slice(), &self.query); if visible.is_empty() { return Self::message(org_empty_message(&self.query)).into_any_element(); } let rows: Vec<Vec<OrgEmoji>> = visible .into_iter() .cloned() .collect::<Vec<_>>() .chunks(ORG_COLUMNS) .map(|chunk| chunk.to_vec()) .collect(); uniform_list( "fun-picker-org-list", rows.len(), cx.processor(move |this, range: std::ops::Range<usize>, _, cx| { range .map(|index| { let tiles = rows[index].iter().enumerate().map(|(column, emoji)| { this.org_tile(emoji, index * ORG_COLUMNS + column, cx) }); h_flex() .h(px(ORG_CELL + 16. + ORG_GAP)) .gap(px(ORG_GAP)) .children(tiles) .into_any_element() }) .collect::<Vec<_>>() }), ) .track_scroll(&self.org_scroll) .size_full() .into_any_element() } } }}}impl Render for FunPicker {impl Render for FunPicker {@@ -738,6 +931,7 @@ impl Render for FunPicker { Tab::Emoji => self.render_emoji(cx), Tab::Emoji => self.render_emoji(cx), Tab::Gif => self.render_gifs(cx), Tab::Gif => self.render_gifs(cx), Tab::Sticker => self.render_stickers(cx), Tab::Sticker => self.render_stickers(cx), Tab::Org => self.render_org(cx), }; }; v_flex() v_flex() .w(px(WIDTH)) .w(px(WIDTH))@@ -245,6 +245,24 @@ impl Render for RailView {
calendar,
self.agents_running(cx),
);
// KVT-fork: tegels Ponos en Asclepius direct onder Agents.
let tickets_unread = crate::kvt::tickets_unread(cx);
let items = crate::kvt::with_rail_tiles(items, |tile, label| match tile {
crate::kvt::RailTile::Ponos => RailItem {
tab: SidebarTab::Ponos,
label,
shortcut_label: "Open Ponos",
icon: IconName::ClipboardCheck,
badge: RailBadge::None,
},
crate::kvt::RailTile::Asclepius => RailItem {
tab: SidebarTab::Asclepius,
label,
shortcut_label: "Open Asclepius",
icon: IconName::Ticket,
badge: count_badge_for(tickets_unread),
},
});
v_flex()
.debug_selector(|| "shell/islands/rail".into())
.w(px(RAIL_WIDTH))
@@ -245,6 +245,24 @@ impl Render for RailView { calendar, calendar, self.agents_running(cx), self.agents_running(cx), ); ); // KVT-fork: tegels Ponos en Asclepius direct onder Agents. let tickets_unread = crate::kvt::tickets_unread(cx); let items = crate::kvt::with_rail_tiles(items, |tile, label| match tile { crate::kvt::RailTile::Ponos => RailItem { tab: SidebarTab::Ponos, label, shortcut_label: "Open Ponos", icon: IconName::ClipboardCheck, badge: RailBadge::None, }, crate::kvt::RailTile::Asclepius => RailItem { tab: SidebarTab::Asclepius, label, shortcut_label: "Open Asclepius", icon: IconName::Ticket, badge: count_badge_for(tickets_unread), }, }); v_flex() v_flex() .debug_selector(|| "shell/islands/rail".into()) .debug_selector(|| "shell/islands/rail".into()) .w(px(RAIL_WIDTH)) .w(px(RAIL_WIDTH))@@ -1,4 +1,4 @@
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use gpui_kit::base::PopoverState;
@@ -21,6 +21,11 @@ use crate::emoji;
use crate::emoticons;
use crate::rows::reaction_glyph;
use crate::theme;
use crate::i18n::{tr, tr_args};
use crate::org_emojis::{self, OrgEmojiError};
use crate::remote_image::image_source;
use crate::views::image_memory::bounded;
use teams_core::OrgEmoji;
const PICKER_QUICK: [&str; 6] = [
"\u{1F44D}",
@@ -52,6 +57,30 @@ const PICKER_WIDTH: f32 = 296.;
const CELL_SIZE: f32 = 32.;
const GRID_COLUMNS: usize = 8;
const GRID_LIMIT: usize = 32;
const ORG_COLUMNS: usize = 8;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tab {
Emoji,
Org,
}
enum OrgState {
Loading,
Ready(Vec<OrgEmoji>),
Failed,
}
fn org_empty_message(query: &str) -> String {
if query.is_empty() {
tr("reaction_picker.org.empty")
} else {
let mut args = HashMap::new();
args.insert("query".into(), query.to_owned());
tr_args("reaction_picker.org.empty_query", &args)
}
}
pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;
@@ -73,6 +102,10 @@ pub struct ReactionPicker {
skin_tone: u8,
tone_menu: Option<(String, Point<Pixels>)>,
customizing: bool,
tab: Tab,
org: OrgState,
org_generation: u64,
org_task: Option<Task<()>>,
_subscription: Subscription,
}
@@ -95,6 +128,10 @@ impl ReactionPicker {
skin_tone: 0,
tone_menu: None,
customizing: false,
tab: Tab::Emoji,
org: OrgState::Loading,
org_generation: 0,
org_task: None,
_subscription: subscription,
}
}
@@ -131,10 +168,15 @@ impl ReactionPicker {
cx.notify();
});
self.query.clear();
self.tab = Tab::Emoji;
self.input.update(cx, |state, cx| {
state.set_value("", window, cx);
state.set_placeholder("Search emoji", window, cx);
state.focus(window, cx);
});
if !self.customizing {
self.load_org_emojis(cx);
}
cx.notify();
}
@@ -151,7 +193,12 @@ impl ReactionPicker {
cx.notify();
}
InputEvent::PressEnter { .. } => {
if let Some(first) = self.results(cx).first().cloned() {
let first = if self.tab == Tab::Org {
self.visible_org_emojis().first().map(|emoji| emoji.key())
} else {
self.results(cx).first().cloned()
};
if let Some(first) = first {
self.pick(&first, false, window, cx);
}
}
@@ -315,6 +362,154 @@ impl ReactionPicker {
this.pick(&picked, event.modifiers().shift, window, cx)
}))
}
fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
match &self.org {
OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
.into_iter()
.cloned()
.collect(),
_ => Vec::new(),
}
}
fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
if tab == self.tab {
return;
}
self.tab = tab;
let placeholder = if tab == Tab::Org {
tr("reaction_picker.search.org")
} else {
"Search emoji".to_owned()
};
self.input.update(cx, |state, cx| {
state.set_placeholder(placeholder, window, cx);
state.focus(window, cx);
});
if tab == Tab::Org {
self.load_org_emojis(cx);
}
cx.notify();
}
fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
if matches!(self.org, OrgState::Ready(_)) {
return;
}
self.org_generation += 1;
let generation = self.org_generation;
self.org = OrgState::Loading;
let (demo, engine) = {
let state = self.app.read(cx);
(state.mode.demo, state.engine.clone())
};
self.org_task = Some(cx.spawn(async move |this, cx| {
let outcome = org_emojis::list(engine, demo, false)
.await
.unwrap_or(Err(OrgEmojiError::Failed));
this.update(cx, |this, cx| {
if this.org_generation != generation {
return;
}
this.org = match outcome {
Ok(emojis) => OrgState::Ready(emojis),
Err(_) => OrgState::Failed,
};
cx.notify();
})
.ok();
}));
}
fn tab_button(&self, tab: Tab, label_key: &str, cx: &mut Context<Self>) -> Stateful<Div> {
let selected = tab == self.tab;
div()
.id(("reaction-picker-tab", tab as usize))
.h(px(26.))
.px(px(8.))
.flex()
.items_center()
.cursor_pointer()
.text_size(px(12.))
.font_weight(FontWeight::SEMIBOLD)
.border_b_2()
.border_color(if selected {
theme::accent()
} else {
transparent_black()
})
.text_color(if selected {
theme::accent_text()
} else {
theme::text_muted()
})
.hover(|button| button.text_color(theme::text_strong()))
.child(tr(label_key))
.on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
}
fn org_cell(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
let key = emoji.key();
let name = emoji.name.clone();
let selected = self.selected.contains(&key);
div()
.id(("reaction-picker-org", index))
.size(px(CELL_SIZE))
.flex_none()
.p(px(3.))
.rounded(px(6.))
.cursor_pointer()
.when(selected, |cell| cell.bg(theme::reaction_on_own()))
.hover(|cell| cell.bg(theme::popup_hover()))
.child(
img(bounded(image_source(&emoji.image_url())))
.size_full()
.object_fit(ObjectFit::Contain),
)
.tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
.on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
this.pick(&key, event.modifiers().shift, window, cx)
}))
.into_any_element()
}
fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
match &self.org {
OrgState::Loading => div()
.text_size(px(11.))
.text_color(theme::text_muted())
.child("…")
.into_any_element(),
OrgState::Failed => div()
.text_size(px(11.))
.text_color(theme::text_muted())
.child(tr("fun_picker.org.failed"))
.into_any_element(),
OrgState::Ready(_) => {
let visible = self.visible_org_emojis();
if visible.is_empty() {
return div()
.text_size(px(11.))
.text_color(theme::text_muted())
.child(org_empty_message(&self.query))
.into_any_element();
}
let mut rows = Vec::new();
let mut row = Vec::new();
for (index, emoji) in visible.iter().enumerate() {
row.push(self.org_cell(emoji, index, cx));
if row.len() == ORG_COLUMNS {
rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
}
}
if !row.is_empty() {
rows.push(h_flex().gap(px(2.)).children(row));
}
v_flex().gap(px(2.)).children(rows).into_any_element()
}
}
}
}
impl Render for ReactionPicker {
@@ -343,11 +538,35 @@ impl Render for ReactionPicker {
if !row.is_empty() {
rows.push(h_flex().gap(px(2.)).children(row));
}
let tabs = (!self.customizing).then(|| {
h_flex()
.flex_none()
.gap(px(2.))
.child(self.tab_button(Tab::Emoji, "reaction_picker.tab.emoji", cx))
.child(self.tab_button(Tab::Org, "reaction_picker.tab.org", cx))
});
let body = if self.tab == Tab::Org && !self.customizing {
self.render_org(cx)
} else {
v_flex()
.gap(px(2.))
.child(
div()
.text_size(px(11.))
.text_color(theme::text_muted())
.child(label),
)
.child(v_flex().gap(px(2.)).children(rows))
.into_any_element()
};
v_flex()
.w(px(PICKER_WIDTH))
.gap(px(8.))
.p(px(8.))
.child(h_flex().gap(px(2.)).children(quick))
.children(tabs)
.when(self.tab != Tab::Org || self.customizing, |picker| {
picker.child(h_flex().gap(px(2.)).children(quick))
})
.child(
h_flex()
.gap(px(4.))
@@ -365,13 +584,7 @@ impl Render for ReactionPicker {
)
.children(self.customize_button(cx)),
)
.child(
div()
.text_size(px(11.))
.text_color(theme::text_muted())
.child(label),
)
.child(v_flex().gap(px(2.)).children(rows))
.child(body)
.children(self.tone_menu(cx))
}
}
@@ -1,4 +1,4 @@use std::collections::HashSet;use std::collections::{HashMap, HashSet};use std::rc::Rc;use std::rc::Rc;use gpui_kit::base::PopoverState;use gpui_kit::base::PopoverState;@@ -21,6 +21,11 @@ use crate::emoji;use crate::emoticons;use crate::emoticons;use crate::rows::reaction_glyph;use crate::rows::reaction_glyph;use crate::theme;use crate::theme;use crate::i18n::{tr, tr_args};use crate::org_emojis::{self, OrgEmojiError};use crate::remote_image::image_source;use crate::views::image_memory::bounded;use teams_core::OrgEmoji;const PICKER_QUICK: [&str; 6] = [const PICKER_QUICK: [&str; 6] = [ "\u{1F44D}", "\u{1F44D}",@@ -52,6 +57,30 @@ const PICKER_WIDTH: f32 = 296.;const CELL_SIZE: f32 = 32.;const CELL_SIZE: f32 = 32.;const GRID_COLUMNS: usize = 8;const GRID_COLUMNS: usize = 8;const GRID_LIMIT: usize = 32;const GRID_LIMIT: usize = 32;const ORG_COLUMNS: usize = 8;#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Tab { Emoji, Org,}enum OrgState { Loading, Ready(Vec<OrgEmoji>), Failed,}fn org_empty_message(query: &str) -> String { if query.is_empty() { tr("reaction_picker.org.empty") } else { let mut args = HashMap::new(); args.insert("query".into(), query.to_owned()); tr_args("reaction_picker.org.empty_query", &args) }}pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;@@ -73,6 +102,10 @@ pub struct ReactionPicker { skin_tone: u8, skin_tone: u8, tone_menu: Option<(String, Point<Pixels>)>, tone_menu: Option<(String, Point<Pixels>)>, customizing: bool, customizing: bool, tab: Tab, org: OrgState, org_generation: u64, org_task: Option<Task<()>>, _subscription: Subscription, _subscription: Subscription,}}@@ -95,6 +128,10 @@ impl ReactionPicker { skin_tone: 0, skin_tone: 0, tone_menu: None, tone_menu: None, customizing: false, customizing: false, tab: Tab::Emoji, org: OrgState::Loading, org_generation: 0, org_task: None, _subscription: subscription, _subscription: subscription, } } } }@@ -131,10 +168,15 @@ impl ReactionPicker { cx.notify(); cx.notify(); }); }); self.query.clear(); self.query.clear(); self.tab = Tab::Emoji; self.input.update(cx, |state, cx| { self.input.update(cx, |state, cx| { state.set_value("", window, cx); state.set_value("", window, cx); state.set_placeholder("Search emoji", window, cx); state.focus(window, cx); state.focus(window, cx); }); }); if !self.customizing { self.load_org_emojis(cx); } cx.notify(); cx.notify(); } }@@ -151,7 +193,12 @@ impl ReactionPicker { cx.notify(); cx.notify(); } } InputEvent::PressEnter { .. } => { InputEvent::PressEnter { .. } => { if let Some(first) = self.results(cx).first().cloned() { let first = if self.tab == Tab::Org { self.visible_org_emojis().first().map(|emoji| emoji.key()) } else { self.results(cx).first().cloned() }; if let Some(first) = first { self.pick(&first, false, window, cx); self.pick(&first, false, window, cx); } } } }@@ -315,6 +362,154 @@ impl ReactionPicker { this.pick(&picked, event.modifiers().shift, window, cx) this.pick(&picked, event.modifiers().shift, window, cx) })) })) } } fn visible_org_emojis(&self) -> Vec<OrgEmoji> { match &self.org { OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query) .into_iter() .cloned() .collect(), _ => Vec::new(), } } fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) { if tab == self.tab { return; } self.tab = tab; let placeholder = if tab == Tab::Org { tr("reaction_picker.search.org") } else { "Search emoji".to_owned() }; self.input.update(cx, |state, cx| { state.set_placeholder(placeholder, window, cx); state.focus(window, cx); }); if tab == Tab::Org { self.load_org_emojis(cx); } cx.notify(); } fn load_org_emojis(&mut self, cx: &mut Context<Self>) { if matches!(self.org, OrgState::Ready(_)) { return; } self.org_generation += 1; let generation = self.org_generation; self.org = OrgState::Loading; let (demo, engine) = { let state = self.app.read(cx); (state.mode.demo, state.engine.clone()) }; self.org_task = Some(cx.spawn(async move |this, cx| { let outcome = org_emojis::list(engine, demo, false) .await .unwrap_or(Err(OrgEmojiError::Failed)); this.update(cx, |this, cx| { if this.org_generation != generation { return; } this.org = match outcome { Ok(emojis) => OrgState::Ready(emojis), Err(_) => OrgState::Failed, }; cx.notify(); }) .ok(); })); } fn tab_button(&self, tab: Tab, label_key: &str, cx: &mut Context<Self>) -> Stateful<Div> { let selected = tab == self.tab; div() .id(("reaction-picker-tab", tab as usize)) .h(px(26.)) .px(px(8.)) .flex() .items_center() .cursor_pointer() .text_size(px(12.)) .font_weight(FontWeight::SEMIBOLD) .border_b_2() .border_color(if selected { theme::accent() } else { transparent_black() }) .text_color(if selected { theme::accent_text() } else { theme::text_muted() }) .hover(|button| button.text_color(theme::text_strong())) .child(tr(label_key)) .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx))) } fn org_cell(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement { let key = emoji.key(); let name = emoji.name.clone(); let selected = self.selected.contains(&key); div() .id(("reaction-picker-org", index)) .size(px(CELL_SIZE)) .flex_none() .p(px(3.)) .rounded(px(6.)) .cursor_pointer() .when(selected, |cell| cell.bg(theme::reaction_on_own())) .hover(|cell| cell.bg(theme::popup_hover())) .child( img(bounded(image_source(&emoji.image_url()))) .size_full() .object_fit(ObjectFit::Contain), ) .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx)) .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| { this.pick(&key, event.modifiers().shift, window, cx) })) .into_any_element() } fn render_org(&self, cx: &mut Context<Self>) -> AnyElement { match &self.org { OrgState::Loading => div() .text_size(px(11.)) .text_color(theme::text_muted()) .child("…") .into_any_element(), OrgState::Failed => div() .text_size(px(11.)) .text_color(theme::text_muted()) .child(tr("fun_picker.org.failed")) .into_any_element(), OrgState::Ready(_) => { let visible = self.visible_org_emojis(); if visible.is_empty() { return div() .text_size(px(11.)) .text_color(theme::text_muted()) .child(org_empty_message(&self.query)) .into_any_element(); } let mut rows = Vec::new(); let mut row = Vec::new(); for (index, emoji) in visible.iter().enumerate() { row.push(self.org_cell(emoji, index, cx)); if row.len() == ORG_COLUMNS { rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row))); } } if !row.is_empty() { rows.push(h_flex().gap(px(2.)).children(row)); } v_flex().gap(px(2.)).children(rows).into_any_element() } } }}}impl Render for ReactionPicker {impl Render for ReactionPicker {@@ -343,11 +538,35 @@ impl Render for ReactionPicker { if !row.is_empty() { if !row.is_empty() { rows.push(h_flex().gap(px(2.)).children(row)); rows.push(h_flex().gap(px(2.)).children(row)); } } let tabs = (!self.customizing).then(|| { h_flex() .flex_none() .gap(px(2.)) .child(self.tab_button(Tab::Emoji, "reaction_picker.tab.emoji", cx)) .child(self.tab_button(Tab::Org, "reaction_picker.tab.org", cx)) }); let body = if self.tab == Tab::Org && !self.customizing { self.render_org(cx) } else { v_flex() .gap(px(2.)) .child( div() .text_size(px(11.)) .text_color(theme::text_muted()) .child(label), ) .child(v_flex().gap(px(2.)).children(rows)) .into_any_element() }; v_flex() v_flex() .w(px(PICKER_WIDTH)) .w(px(PICKER_WIDTH)) .gap(px(8.)) .gap(px(8.)) .p(px(8.)) .p(px(8.)) .child(h_flex().gap(px(2.)).children(quick)) .children(tabs) .when(self.tab != Tab::Org || self.customizing, |picker| { picker.child(h_flex().gap(px(2.)).children(quick)) }) .child( .child( h_flex() h_flex() .gap(px(4.)) .gap(px(4.))@@ -365,13 +584,7 @@ impl Render for ReactionPicker { ) ) .children(self.customize_button(cx)), .children(self.customize_button(cx)), ) ) .child( .child(body) div() .text_size(px(11.)) .text_color(theme::text_muted()) .child(label), ) .child(v_flex().gap(px(2.)).children(rows)) .children(self.tone_menu(cx)) .children(self.tone_menu(cx)) } }}}@@ -78,8 +78,31 @@ fn faces_width(count: usize) -> f32 {
diameter + count.saturating_sub(1) as f32 * (diameter - FACE_OVERLAP)
}
fn generic_custom_emoji(size: f32) -> AnyElement {
let glyph = (size * 0.7).round().max(8.);
div()
.size(px(size))
.flex_none()
.rounded(px((size * 0.25).round().max(2.)))
.bg(theme::popup_hover())
.flex()
.items_center()
.justify_center()
.text_size(px(glyph))
.line_height(px(size))
.text_color(theme::text_muted())
.child("☺")
.into_any_element()
}
fn reaction_emoji(glyph: &str, label: &str, size: f32, directory: &Directory) -> AnyElement {
let Some(image) = custom_emoji_image(glyph) else {
if chatsvc::hides_raw_reaction_key(glyph)
|| chatsvc::hides_raw_reaction_key(label)
|| label.is_empty() && chatsvc::is_custom_reaction_type(glyph)
{
return generic_custom_emoji(size);
}
return div()
.flex_none()
.h(px(size))
@@ -78,8 +78,31 @@ fn faces_width(count: usize) -> f32 { diameter + count.saturating_sub(1) as f32 * (diameter - FACE_OVERLAP) diameter + count.saturating_sub(1) as f32 * (diameter - FACE_OVERLAP)}}fn generic_custom_emoji(size: f32) -> AnyElement { let glyph = (size * 0.7).round().max(8.); div() .size(px(size)) .flex_none() .rounded(px((size * 0.25).round().max(2.))) .bg(theme::popup_hover()) .flex() .items_center() .justify_center() .text_size(px(glyph)) .line_height(px(size)) .text_color(theme::text_muted()) .child("☺") .into_any_element()}fn reaction_emoji(glyph: &str, label: &str, size: f32, directory: &Directory) -> AnyElement {fn reaction_emoji(glyph: &str, label: &str, size: f32, directory: &Directory) -> AnyElement { let Some(image) = custom_emoji_image(glyph) else { let Some(image) = custom_emoji_image(glyph) else { if chatsvc::hides_raw_reaction_key(glyph) || chatsvc::hides_raw_reaction_key(label) || label.is_empty() && chatsvc::is_custom_reaction_type(glyph) { return generic_custom_emoji(size); } return div() return div() .flex_none() .flex_none() .h(px(size)) .h(px(size))@@ -102,6 +102,9 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:
}
fn open_link(url: &str, cx: &mut App) {
if crate::kvt::open_ticket_link(url, cx) {
return; // KVT-fork: Asclepius-ticket in de app (met toegang)
}
if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() {
let text = opening_link_text(url);
handle
@@ -1007,6 +1010,7 @@ impl AppShell {
quick_view_open: bool,
calls_open: bool,
manage_team_open: bool,
mut ponos: Option<AnyElement>, // KVT-fork: Ponos-bord
) -> Div {
h_flex()
.debug_selector(|| "shell/islands".into())
@@ -1030,6 +1034,7 @@ impl AppShell {
},
))
.child(match () {
_ if ponos.is_some() => ponos.take().unwrap_or_else(|| div().into_any_element()),
_ if calls_open => self
.calls_page
.clone()
@@ -1108,13 +1113,22 @@ impl Render for AppShell {
let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar;
let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats;
let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls;
let kvt_tab = self.sidebar.read(cx).tab(); // KVT-fork: Ponos/Asclepius-tegel
let ponos_open = matches!(kvt_tab, SidebarTab::Ponos | SidebarTab::Asclepius); // KVT-fork
let ponos_board = match kvt_tab {
// KVT-fork
SidebarTab::Ponos => Some(crate::kvt::board_view(cx)),
SidebarTab::Asclepius => Some(crate::kvt::tickets_view(cx)),
_ => None,
};
let splash = self.render_splash(cx);
let state = self.state.read(cx);
let calendar_open = calendar_tab;
let quick_view_open = chats_tab && state.quick_view.is_some();
let manage_team_open = !calendar_tab && !calls_tab && state.manage_team.is_some();
let manage_team_open =
!calendar_tab && !calls_tab && !ponos_open && state.manage_team.is_some();
let calls_open = calls_tab;
let show_sidebar = !calendar_open && !calls_open;
let show_sidebar = !calendar_open && !calls_open && !ponos_open;
let banner = state
.connection_banner_text()
.filter(|_| !self.splash.is_up())
@@ -1154,7 +1168,8 @@ impl Render for AppShell {
own_status_button(&self.state, state),
]
.into_iter()
.flatten(),
.flatten()
.chain(crate::kvt::title_buttons(&self.notifications, window, cx)),
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),
);
let shell = div()
@@ -1370,6 +1385,7 @@ impl Render for AppShell {
quick_view_open,
calls_open,
manage_team_open,
ponos_board,
),
&self.splash,
cx,
@@ -102,6 +102,9 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:}}fn open_link(url: &str, cx: &mut App) {fn open_link(url: &str, cx: &mut App) { if crate::kvt::open_ticket_link(url, cx) { return; // KVT-fork: Asclepius-ticket in de app (met toegang) } if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() { if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() { let text = opening_link_text(url); let text = opening_link_text(url); handle handle@@ -1007,6 +1010,7 @@ impl AppShell { quick_view_open: bool, quick_view_open: bool, calls_open: bool, calls_open: bool, manage_team_open: bool, manage_team_open: bool, mut ponos: Option<AnyElement>, // KVT-fork: Ponos-bord ) -> Div { ) -> Div { h_flex() h_flex() .debug_selector(|| "shell/islands".into()) .debug_selector(|| "shell/islands".into())@@ -1030,6 +1034,7 @@ impl AppShell { }, }, )) )) .child(match () { .child(match () { _ if ponos.is_some() => ponos.take().unwrap_or_else(|| div().into_any_element()), _ if calls_open => self _ if calls_open => self .calls_page .calls_page .clone() .clone()@@ -1108,13 +1113,22 @@ impl Render for AppShell { let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar; let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar; let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats; let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats; let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls; let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls; let kvt_tab = self.sidebar.read(cx).tab(); // KVT-fork: Ponos/Asclepius-tegel let ponos_open = matches!(kvt_tab, SidebarTab::Ponos | SidebarTab::Asclepius); // KVT-fork let ponos_board = match kvt_tab { // KVT-fork SidebarTab::Ponos => Some(crate::kvt::board_view(cx)), SidebarTab::Asclepius => Some(crate::kvt::tickets_view(cx)), _ => None, }; let splash = self.render_splash(cx); let splash = self.render_splash(cx); let state = self.state.read(cx); let state = self.state.read(cx); let calendar_open = calendar_tab; let calendar_open = calendar_tab; let quick_view_open = chats_tab && state.quick_view.is_some(); let quick_view_open = chats_tab && state.quick_view.is_some(); let manage_team_open = !calendar_tab && !calls_tab && state.manage_team.is_some(); let manage_team_open = !calendar_tab && !calls_tab && !ponos_open && state.manage_team.is_some(); let calls_open = calls_tab; let calls_open = calls_tab; let show_sidebar = !calendar_open && !calls_open; let show_sidebar = !calendar_open && !calls_open && !ponos_open; let banner = state let banner = state .connection_banner_text() .connection_banner_text() .filter(|_| !self.splash.is_up()) .filter(|_| !self.splash.is_up())@@ -1154,7 +1168,8 @@ impl Render for AppShell { own_status_button(&self.state, state), own_status_button(&self.state, state), ] ] .into_iter() .into_iter() .flatten(), .flatten() .chain(crate::kvt::title_buttons(&self.notifications, window, cx)), cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)), cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)), ); ); let shell = div() let shell = div()@@ -1370,6 +1385,7 @@ impl Render for AppShell { quick_view_open, quick_view_open, calls_open, calls_open, manage_team_open, manage_team_open, ponos_board, ), ), &self.splash, &self.splash, cx, cx,@@ -96,6 +96,10 @@ pub enum SidebarTab {
Calendar,
Calls,
Agents,
/// KVT-fork: Ponos-bord in het hoofdpaneel (`crate::kvt::board_view`).
Ponos,
/// KVT-fork: Asclepius-tickets in het hoofdpaneel (`crate::kvt::tickets_view`).
Asclepius,
}
impl SidebarTab {
@@ -107,6 +111,8 @@ impl SidebarTab {
SidebarTab::Calendar => tr("rail.calendar"),
SidebarTab::Calls => tr("rail.calls"),
SidebarTab::Agents => tr("rail.agents"),
SidebarTab::Ponos => tr("kvt.rail.ponos"),
SidebarTab::Asclepius => tr("kvt.rail.asclepius"),
}
}
}
@@ -549,6 +555,8 @@ impl SidebarView {
let activity = self.activity_panel.read(cx).activity();
activity.update(cx, |activity, cx| activity.mark_seen(cx));
}
SidebarTab::Ponos => crate::kvt::board_opened(cx),
SidebarTab::Asclepius => crate::kvt::tickets_opened(cx),
_ => {}
}
cx.notify();
@@ -583,7 +591,9 @@ impl SidebarView {
SidebarTab::Activity
| SidebarTab::Calendar
| SidebarTab::Calls
| SidebarTab::Agents => None,
| SidebarTab::Agents
| SidebarTab::Ponos
| SidebarTab::Asclepius => None,
};
if let Some(selection) = selection {
self.state
@@ -2146,7 +2156,10 @@ impl Render for SidebarView {
Some(panel) => panel.clone().into_any_element(),
None => div().into_any_element(),
},
SidebarTab::Calls | SidebarTab::Calendar => div().into_any_element(),
SidebarTab::Calls
| SidebarTab::Calendar
| SidebarTab::Ponos
| SidebarTab::Asclepius => div().into_any_element(),
};
let header = match self.tab {
SidebarTab::Chats => Some(
@@ -2172,7 +2185,11 @@ impl Render for SidebarView {
.child(self.channel_filter_bar(cx)),
),
SidebarTab::Agents => Some(page_header(&self.tab.title())),
SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Calendar => None,
SidebarTab::Activity
| SidebarTab::Calls
| SidebarTab::Calendar
| SidebarTab::Ponos
| SidebarTab::Asclepius => None,
};
v_flex()
.debug_selector(|| "shell/islands/sidebar".into())
@@ -96,6 +96,10 @@ pub enum SidebarTab { Calendar, Calendar, Calls, Calls, Agents, Agents, /// KVT-fork: Ponos-bord in het hoofdpaneel (`crate::kvt::board_view`). Ponos, /// KVT-fork: Asclepius-tickets in het hoofdpaneel (`crate::kvt::tickets_view`). Asclepius,}}impl SidebarTab {impl SidebarTab {@@ -107,6 +111,8 @@ impl SidebarTab { SidebarTab::Calendar => tr("rail.calendar"), SidebarTab::Calendar => tr("rail.calendar"), SidebarTab::Calls => tr("rail.calls"), SidebarTab::Calls => tr("rail.calls"), SidebarTab::Agents => tr("rail.agents"), SidebarTab::Agents => tr("rail.agents"), SidebarTab::Ponos => tr("kvt.rail.ponos"), SidebarTab::Asclepius => tr("kvt.rail.asclepius"), } } } }}}@@ -549,6 +555,8 @@ impl SidebarView { let activity = self.activity_panel.read(cx).activity(); let activity = self.activity_panel.read(cx).activity(); activity.update(cx, |activity, cx| activity.mark_seen(cx)); activity.update(cx, |activity, cx| activity.mark_seen(cx)); } } SidebarTab::Ponos => crate::kvt::board_opened(cx), SidebarTab::Asclepius => crate::kvt::tickets_opened(cx), _ => {} _ => {} } } cx.notify(); cx.notify();@@ -583,7 +591,9 @@ impl SidebarView { SidebarTab::Activity SidebarTab::Activity | SidebarTab::Calendar | SidebarTab::Calendar | SidebarTab::Calls | SidebarTab::Calls | SidebarTab::Agents => None, | SidebarTab::Agents | SidebarTab::Ponos | SidebarTab::Asclepius => None, }; }; if let Some(selection) = selection { if let Some(selection) = selection { self.state self.state@@ -2146,7 +2156,10 @@ impl Render for SidebarView { Some(panel) => panel.clone().into_any_element(), Some(panel) => panel.clone().into_any_element(), None => div().into_any_element(), None => div().into_any_element(), }, }, SidebarTab::Calls | SidebarTab::Calendar => div().into_any_element(), SidebarTab::Calls | SidebarTab::Calendar | SidebarTab::Ponos | SidebarTab::Asclepius => div().into_any_element(), }; }; let header = match self.tab { let header = match self.tab { SidebarTab::Chats => Some( SidebarTab::Chats => Some(@@ -2172,7 +2185,11 @@ impl Render for SidebarView { .child(self.channel_filter_bar(cx)), .child(self.channel_filter_bar(cx)), ), ), SidebarTab::Agents => Some(page_header(&self.tab.title())), SidebarTab::Agents => Some(page_header(&self.tab.title())), SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Calendar => None, SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Calendar | SidebarTab::Ponos | SidebarTab::Asclepius => None, }; }; v_flex() v_flex() .debug_selector(|| "shell/islands/sidebar".into()) .debug_selector(|| "shell/islands/sidebar".into())@@ -307,6 +307,7 @@ impl RenderOnce for TitleBarRow {
.h(px(TITLE_BAR_HEIGHT))
.border_b_0()
.bg(theme::background())
.system_window_controls(crate::kvt::title_bar_system_window_controls(cx))
.child(row);
let on_search = self.on_search;
div()
@@ -307,6 +307,7 @@ impl RenderOnce for TitleBarRow { .h(px(TITLE_BAR_HEIGHT)) .h(px(TITLE_BAR_HEIGHT)) .border_b_0() .border_b_0() .bg(theme::background()) .bg(theme::background()) .system_window_controls(crate::kvt::title_bar_system_window_controls(cx)) .child(row); .child(row); let on_search = self.on_search; let on_search = self.on_search; div() div()@@ -0,0 +1,387 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use session::{Request, Session};
use crate::error::Result;
use crate::messages::ensure_success;
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
use crate::reactions::CustomEmoji;
/// Official web client (2024): `GET /api/csa/{region}/api/v1/customemoji/metadata`
/// with the CSA bearer (`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`).
/// Optional `x-ms-continuation` asks for changes since the previous `continuationToken`.
/// We use the same path on `teams.cloud.microsoft` (the host of every other CSA call here)
/// and `DEFAULT_REGION` (`emea`). Live check: the host, the region, and the token audience.
const METADATA_PATH: &str = "customemoji/metadata";
const CONTINUATION_HEADER: &str = "x-ms-continuation";
const CUSTOM_CATEGORY: &str = "customEmoji";
const ITEMTYPE: &str = "http://schema.skype.com/CustomEmoji";
const DISPLAY_SIZE: u32 = 20;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OrgEmoji {
pub id: String,
pub document_id: String,
pub name: String,
pub keywords: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
}
impl OrgEmoji {
pub fn key(&self) -> String {
format!("{};{}", self.name, self.document_id)
}
pub fn image_url(&self) -> String {
if let Some(source) = &self.source {
return source.clone();
}
CustomEmoji {
name: self.name.clone(),
object_id: self.document_id.clone(),
}
.image_url()
}
pub fn html(&self) -> String {
custom_emoji_html(&self.name, &self.document_id, &self.image_url())
}
pub fn matches(&self, query: &str) -> bool {
let query = query.trim();
if query.is_empty() {
return true;
}
let query = query.to_ascii_lowercase();
self.name.to_ascii_lowercase().contains(&query)
|| self
.keywords
.iter()
.any(|keyword| keyword.to_ascii_lowercase().contains(&query))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct OrgEmojiCatalog {
pub emojis: Vec<OrgEmoji>,
pub deleted_ids: Vec<String>,
pub continuation: Option<String>,
}
pub struct CustomEmojis<T: CsaTransport = SessionTransport> {
transport: T,
url: String,
}
impl CustomEmojis<SessionTransport> {
pub fn new(session: &Session) -> Self {
CustomEmojis::with_transport(SessionTransport::new(session), DEFAULT_REGION)
}
}
impl<T: CsaTransport> CustomEmojis<T> {
pub fn with_transport(transport: T, region: &str) -> Self {
CustomEmojis {
transport,
url: format!("https://teams.cloud.microsoft/api/csa/{region}/api/v1/{METADATA_PATH}"),
}
}
/// A request without `x-ms-continuation` returns the full catalogue.
pub async fn list(&self) -> Result<OrgEmojiCatalog> {
self.fetch(None).await
}
pub async fn list_since(&self, continuation: &str) -> Result<OrgEmojiCatalog> {
self.fetch(Some(continuation)).await
}
async fn fetch(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
let mut request = Request::get(&self.url);
if let Some(token) = continuation.map(str::trim).filter(|token| !token.is_empty()) {
request
.headers
.push((CONTINUATION_HEADER.to_owned(), token.to_owned()));
}
let answer = self.transport.send(request).await?;
ensure_success(&answer)?;
Ok(parse_metadata(&answer.body))
}
}
/// The HTML the official client accepts when a custom emoji is sent in a message.
pub fn custom_emoji_html(name: &str, object_id: &str, source: &str) -> String {
format!(
"<img alt=\"{alt}\" itemid=\"{itemid}\" itemtype=\"{ITEMTYPE}\" src=\"{src}\" width=\"{DISPLAY_SIZE}\" height=\"{DISPLAY_SIZE}\" style=\"width:{DISPLAY_SIZE}px;height:{DISPLAY_SIZE}px;\">",
alt = escape_attr(name),
itemid = escape_attr(&format!("{name};{object_id}")),
src = escape_attr(source),
)
}
pub fn parse_metadata(body: &Value) -> OrgEmojiCatalog {
let continuation = continuation_token(body.get("continuationToken"));
let mut emojis = Vec::new();
let mut deleted_ids = Vec::new();
let entries = body
.get("categories")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|category| category.get("id").and_then(Value::as_str) == Some(CUSTOM_CATEGORY))
.flat_map(|category| {
category
.get("emoticons")
.and_then(Value::as_array)
.into_iter()
.flatten()
});
for entry in entries {
match parse_emoticon(entry) {
ParsedEmoticon::Live(emoji) => emojis.push(emoji),
ParsedEmoticon::Deleted(id) => deleted_ids.push(id),
ParsedEmoticon::Skip => {}
}
}
OrgEmojiCatalog {
emojis,
deleted_ids,
continuation,
}
}
/// Apply a delta (or a full list) to a previously cached catalogue.
pub fn merge_catalog(previous: &[OrgEmoji], incoming: OrgEmojiCatalog, full: bool) -> OrgEmojiCatalog {
if full {
return incoming;
}
let mut by_id: std::collections::HashMap<String, OrgEmoji> = previous
.iter()
.cloned()
.map(|emoji| (emoji.id.clone(), emoji))
.collect();
for id in &incoming.deleted_ids {
by_id.remove(id);
}
for emoji in incoming.emojis {
by_id.insert(emoji.id.clone(), emoji);
}
let mut emojis: Vec<OrgEmoji> = by_id.into_values().collect();
emojis.sort_by(|left, right| left.name.cmp(&right.name).then(left.id.cmp(&right.id)));
OrgEmojiCatalog {
emojis,
deleted_ids: Vec::new(),
continuation: incoming.continuation,
}
}
enum ParsedEmoticon {
Live(OrgEmoji),
Deleted(String),
Skip,
}
fn parse_emoticon(entry: &Value) -> ParsedEmoticon {
let id = entry
.get("id")
.and_then(Value::as_str)
.map(str::trim)
.filter(|id| !id.is_empty())
.map(str::to_owned);
if entry.get("isDeleted").and_then(Value::as_bool) == Some(true) {
return id.map(ParsedEmoticon::Deleted).unwrap_or(ParsedEmoticon::Skip);
}
let Some(document_id) = entry
.get("documentId")
.and_then(Value::as_str)
.map(str::trim)
.filter(|id| crate::links::is_ams_object_id(id))
else {
return ParsedEmoticon::Skip;
};
let Some(name) = entry
.get("shortcuts")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::trim)
.find(|name| !name.is_empty())
.or_else(|| {
entry
.get("description")
.and_then(Value::as_str)
.map(str::trim)
.filter(|name| !name.is_empty())
})
.map(str::to_owned)
else {
return ParsedEmoticon::Skip;
};
let keywords = entry
.get("keywords")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::trim)
.filter(|keyword| !keyword.is_empty())
.map(str::to_owned)
.collect();
ParsedEmoticon::Live(OrgEmoji {
id: id.unwrap_or_else(|| document_id.to_owned()),
document_id: document_id.to_owned(),
name,
keywords,
source: None,
})
}
fn continuation_token(value: Option<&Value>) -> Option<String> {
match value {
Some(Value::String(text)) => Some(text.clone()).filter(|text| !text.is_empty()),
Some(Value::Number(number)) => Some(number.to_string()),
_ => None,
}
}
fn escape_attr(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use serde_json::Value;
use session::{ApiResponse, Method};
use super::*;
struct Canned {
body: Value,
requests: Mutex<Vec<Request>>,
}
impl CsaTransport for &Canned {
async fn send(&self, request: Request) -> Result<ApiResponse> {
self.requests.lock().unwrap().push(request);
Ok(ApiResponse {
status: 200,
body: self.body.clone(),
retry_after: None,
})
}
}
fn fixture() -> Value {
serde_json::from_str(include_str!("../tests/fixtures/custom_emoji_metadata.json")).unwrap()
}
#[test]
fn metadata_keeps_live_emoticons_and_skips_deleted_or_unsafe_ids() {
let catalog = parse_metadata(&fixture());
assert_eq!(catalog.continuation.as_deref(), Some("42"));
let names: Vec<&str> = catalog.emojis.iter().map(|emoji| emoji.name.as_str()).collect();
assert_eq!(names, ["absolute-cinema", "tsignal"]);
assert!(catalog.emojis.iter().all(|emoji| crate::links::is_ams_object_id(&emoji.document_id)));
assert!(catalog.emojis[0].matches("cinema"));
assert!(catalog.emojis[0].matches("movie"));
assert!(!catalog.emojis[0].matches("tsignal"));
assert_eq!(catalog.deleted_ids, ["em-gone"]);
}
#[test]
fn merge_catalog_removes_deleted_ids_and_keeps_the_rest() {
let previous = vec![
OrgEmoji {
id: "em-1".into(),
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
name: "absolute-cinema".into(),
keywords: vec!["cinema".into()],
source: None,
},
OrgEmoji {
id: "em-gone".into(),
document_id: "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef".into(),
name: "old-one".into(),
keywords: vec![],
source: None,
},
];
let incoming = OrgEmojiCatalog {
emojis: vec![OrgEmoji {
id: "em-2".into(),
document_id: "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853".into(),
name: "tsignal".into(),
keywords: vec!["tsignal".into()],
source: None,
}],
deleted_ids: vec!["em-gone".into()],
continuation: Some("43".into()),
};
let merged = merge_catalog(&previous, incoming, false);
let names: Vec<&str> = merged.emojis.iter().map(|emoji| emoji.name.as_str()).collect();
assert_eq!(names, ["absolute-cinema", "tsignal"]);
assert!(merged.deleted_ids.is_empty());
assert_eq!(merged.continuation.as_deref(), Some("43"));
}
#[test]
fn html_names_the_custom_emoji_itemtype_and_itemid() {
let html = custom_emoji_html(
"say \"hi\" & <wave>",
"0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim",
);
assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));
assert!(html.contains("itemid=\"say "hi" & <wave>;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));
assert!(html.contains("alt=\"say "hi" & <wave>\""));
assert!(html.contains("width=\"20\" height=\"20\""));
assert!(html.contains("style=\"width:20px;height:20px;\""));
assert!(html.contains("/views/imgt2_anim"));
}
#[tokio::test]
async fn list_uses_the_csa_metadata_path_and_omits_continuation_for_a_full_fetch() {
let transport = Canned {
body: fixture(),
requests: Mutex::new(Vec::new()),
};
let client = CustomEmojis::with_transport(&transport, "emea");
let catalog = client.list().await.unwrap();
assert_eq!(catalog.emojis.len(), 2);
let sent = transport.requests.lock().unwrap();
assert_eq!(
sent[0].url,
"https://teams.cloud.microsoft/api/csa/emea/api/v1/customemoji/metadata"
);
assert_eq!(sent[0].method, Method::Get);
assert!(
sent[0]
.headers
.iter()
.all(|(name, _)| name != CONTINUATION_HEADER)
);
}
#[tokio::test]
async fn list_since_sends_the_continuation_header() {
let transport = Canned {
body: fixture(),
requests: Mutex::new(Vec::new()),
};
let client = CustomEmojis::with_transport(&transport, "emea");
client.list_since("42").await.unwrap();
let sent = transport.requests.lock().unwrap();
assert_eq!(
sent[0].headers,
vec![(CONTINUATION_HEADER.to_owned(), "42".to_owned())]
);
}
}
@@ -0,0 +1,387 @@use serde::{Deserialize, Serialize};use serde_json::Value;use session::{Request, Session};use crate::error::Result;use crate::messages::ensure_success;use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};use crate::reactions::CustomEmoji;/// Official web client (2024): `GET /api/csa/{region}/api/v1/customemoji/metadata`/// with the CSA bearer (`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`)./// Optional `x-ms-continuation` asks for changes since the previous `continuationToken`./// We use the same path on `teams.cloud.microsoft` (the host of every other CSA call here)/// and `DEFAULT_REGION` (`emea`). Live check: the host, the region, and the token audience.const METADATA_PATH: &str = "customemoji/metadata";const CONTINUATION_HEADER: &str = "x-ms-continuation";const CUSTOM_CATEGORY: &str = "customEmoji";const ITEMTYPE: &str = "http://schema.skype.com/CustomEmoji";const DISPLAY_SIZE: u32 = 20;#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct OrgEmoji { pub id: String, pub document_id: String, pub name: String, pub keywords: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<String>,}impl OrgEmoji { pub fn key(&self) -> String { format!("{};{}", self.name, self.document_id) } pub fn image_url(&self) -> String { if let Some(source) = &self.source { return source.clone(); } CustomEmoji { name: self.name.clone(), object_id: self.document_id.clone(), } .image_url() } pub fn html(&self) -> String { custom_emoji_html(&self.name, &self.document_id, &self.image_url()) } pub fn matches(&self, query: &str) -> bool { let query = query.trim(); if query.is_empty() { return true; } let query = query.to_ascii_lowercase(); self.name.to_ascii_lowercase().contains(&query) || self .keywords .iter() .any(|keyword| keyword.to_ascii_lowercase().contains(&query)) }}#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct OrgEmojiCatalog { pub emojis: Vec<OrgEmoji>, pub deleted_ids: Vec<String>, pub continuation: Option<String>,}pub struct CustomEmojis<T: CsaTransport = SessionTransport> { transport: T, url: String,}impl CustomEmojis<SessionTransport> { pub fn new(session: &Session) -> Self { CustomEmojis::with_transport(SessionTransport::new(session), DEFAULT_REGION) }}impl<T: CsaTransport> CustomEmojis<T> { pub fn with_transport(transport: T, region: &str) -> Self { CustomEmojis { transport, url: format!("https://teams.cloud.microsoft/api/csa/{region}/api/v1/{METADATA_PATH}"), } } /// A request without `x-ms-continuation` returns the full catalogue. pub async fn list(&self) -> Result<OrgEmojiCatalog> { self.fetch(None).await } pub async fn list_since(&self, continuation: &str) -> Result<OrgEmojiCatalog> { self.fetch(Some(continuation)).await } async fn fetch(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> { let mut request = Request::get(&self.url); if let Some(token) = continuation.map(str::trim).filter(|token| !token.is_empty()) { request .headers .push((CONTINUATION_HEADER.to_owned(), token.to_owned())); } let answer = self.transport.send(request).await?; ensure_success(&answer)?; Ok(parse_metadata(&answer.body)) }}/// The HTML the official client accepts when a custom emoji is sent in a message.pub fn custom_emoji_html(name: &str, object_id: &str, source: &str) -> String { format!( "<img alt=\"{alt}\" itemid=\"{itemid}\" itemtype=\"{ITEMTYPE}\" src=\"{src}\" width=\"{DISPLAY_SIZE}\" height=\"{DISPLAY_SIZE}\" style=\"width:{DISPLAY_SIZE}px;height:{DISPLAY_SIZE}px;\">", alt = escape_attr(name), itemid = escape_attr(&format!("{name};{object_id}")), src = escape_attr(source), )}pub fn parse_metadata(body: &Value) -> OrgEmojiCatalog { let continuation = continuation_token(body.get("continuationToken")); let mut emojis = Vec::new(); let mut deleted_ids = Vec::new(); let entries = body .get("categories") .and_then(Value::as_array) .into_iter() .flatten() .filter(|category| category.get("id").and_then(Value::as_str) == Some(CUSTOM_CATEGORY)) .flat_map(|category| { category .get("emoticons") .and_then(Value::as_array) .into_iter() .flatten() }); for entry in entries { match parse_emoticon(entry) { ParsedEmoticon::Live(emoji) => emojis.push(emoji), ParsedEmoticon::Deleted(id) => deleted_ids.push(id), ParsedEmoticon::Skip => {} } } OrgEmojiCatalog { emojis, deleted_ids, continuation, }}/// Apply a delta (or a full list) to a previously cached catalogue.pub fn merge_catalog(previous: &[OrgEmoji], incoming: OrgEmojiCatalog, full: bool) -> OrgEmojiCatalog { if full { return incoming; } let mut by_id: std::collections::HashMap<String, OrgEmoji> = previous .iter() .cloned() .map(|emoji| (emoji.id.clone(), emoji)) .collect(); for id in &incoming.deleted_ids { by_id.remove(id); } for emoji in incoming.emojis { by_id.insert(emoji.id.clone(), emoji); } let mut emojis: Vec<OrgEmoji> = by_id.into_values().collect(); emojis.sort_by(|left, right| left.name.cmp(&right.name).then(left.id.cmp(&right.id))); OrgEmojiCatalog { emojis, deleted_ids: Vec::new(), continuation: incoming.continuation, }}enum ParsedEmoticon { Live(OrgEmoji), Deleted(String), Skip,}fn parse_emoticon(entry: &Value) -> ParsedEmoticon { let id = entry .get("id") .and_then(Value::as_str) .map(str::trim) .filter(|id| !id.is_empty()) .map(str::to_owned); if entry.get("isDeleted").and_then(Value::as_bool) == Some(true) { return id.map(ParsedEmoticon::Deleted).unwrap_or(ParsedEmoticon::Skip); } let Some(document_id) = entry .get("documentId") .and_then(Value::as_str) .map(str::trim) .filter(|id| crate::links::is_ams_object_id(id)) else { return ParsedEmoticon::Skip; }; let Some(name) = entry .get("shortcuts") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(Value::as_str) .map(str::trim) .find(|name| !name.is_empty()) .or_else(|| { entry .get("description") .and_then(Value::as_str) .map(str::trim) .filter(|name| !name.is_empty()) }) .map(str::to_owned) else { return ParsedEmoticon::Skip; }; let keywords = entry .get("keywords") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(Value::as_str) .map(str::trim) .filter(|keyword| !keyword.is_empty()) .map(str::to_owned) .collect(); ParsedEmoticon::Live(OrgEmoji { id: id.unwrap_or_else(|| document_id.to_owned()), document_id: document_id.to_owned(), name, keywords, source: None, })}fn continuation_token(value: Option<&Value>) -> Option<String> { match value { Some(Value::String(text)) => Some(text.clone()).filter(|text| !text.is_empty()), Some(Value::Number(number)) => Some(number.to_string()), _ => None, }}fn escape_attr(value: &str) -> String { value .replace('&', "&") .replace('<', "<") .replace('>', ">") .replace('"', """)}#[cfg(test)]mod tests { use std::sync::Mutex; use serde_json::Value; use session::{ApiResponse, Method}; use super::*; struct Canned { body: Value, requests: Mutex<Vec<Request>>, } impl CsaTransport for &Canned { async fn send(&self, request: Request) -> Result<ApiResponse> { self.requests.lock().unwrap().push(request); Ok(ApiResponse { status: 200, body: self.body.clone(), retry_after: None, }) } } fn fixture() -> Value { serde_json::from_str(include_str!("../tests/fixtures/custom_emoji_metadata.json")).unwrap() } #[test] fn metadata_keeps_live_emoticons_and_skips_deleted_or_unsafe_ids() { let catalog = parse_metadata(&fixture()); assert_eq!(catalog.continuation.as_deref(), Some("42")); let names: Vec<&str> = catalog.emojis.iter().map(|emoji| emoji.name.as_str()).collect(); assert_eq!(names, ["absolute-cinema", "tsignal"]); assert!(catalog.emojis.iter().all(|emoji| crate::links::is_ams_object_id(&emoji.document_id))); assert!(catalog.emojis[0].matches("cinema")); assert!(catalog.emojis[0].matches("movie")); assert!(!catalog.emojis[0].matches("tsignal")); assert_eq!(catalog.deleted_ids, ["em-gone"]); } #[test] fn merge_catalog_removes_deleted_ids_and_keeps_the_rest() { let previous = vec![ OrgEmoji { id: "em-1".into(), document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(), name: "absolute-cinema".into(), keywords: vec!["cinema".into()], source: None, }, OrgEmoji { id: "em-gone".into(), document_id: "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef".into(), name: "old-one".into(), keywords: vec![], source: None, }, ]; let incoming = OrgEmojiCatalog { emojis: vec![OrgEmoji { id: "em-2".into(), document_id: "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853".into(), name: "tsignal".into(), keywords: vec!["tsignal".into()], source: None, }], deleted_ids: vec!["em-gone".into()], continuation: Some("43".into()), }; let merged = merge_catalog(&previous, incoming, false); let names: Vec<&str> = merged.emojis.iter().map(|emoji| emoji.name.as_str()).collect(); assert_eq!(names, ["absolute-cinema", "tsignal"]); assert!(merged.deleted_ids.is_empty()); assert_eq!(merged.continuation.as_deref(), Some("43")); } #[test] fn html_names_the_custom_emoji_itemtype_and_itemid() { let html = custom_emoji_html( "say \"hi\" & <wave>", "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8", "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim", ); assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\"")); assert!(html.contains("itemid=\"say "hi" & <wave>;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\"")); assert!(html.contains("alt=\"say "hi" & <wave>\"")); assert!(html.contains("width=\"20\" height=\"20\"")); assert!(html.contains("style=\"width:20px;height:20px;\"")); assert!(html.contains("/views/imgt2_anim")); } #[tokio::test] async fn list_uses_the_csa_metadata_path_and_omits_continuation_for_a_full_fetch() { let transport = Canned { body: fixture(), requests: Mutex::new(Vec::new()), }; let client = CustomEmojis::with_transport(&transport, "emea"); let catalog = client.list().await.unwrap(); assert_eq!(catalog.emojis.len(), 2); let sent = transport.requests.lock().unwrap(); assert_eq!( sent[0].url, "https://teams.cloud.microsoft/api/csa/emea/api/v1/customemoji/metadata" ); assert_eq!(sent[0].method, Method::Get); assert!( sent[0] .headers .iter() .all(|(name, _)| name != CONTINUATION_HEADER) ); } #[tokio::test] async fn list_since_sends_the_continuation_header() { let transport = Canned { body: fixture(), requests: Mutex::new(Vec::new()), }; let client = CustomEmojis::with_transport(&transport, "emea"); client.list_since("42").await.unwrap(); let sent = transport.requests.lock().unwrap(); assert_eq!( sent[0].headers, vec![(CONTINUATION_HEADER.to_owned(), "42".to_owned())] ); }}@@ -14,6 +14,7 @@ pub mod chat_settings;
pub mod compose_copilot;
pub mod conversations;
pub mod copilot;
pub mod custom_emojis;
pub mod drafts;
pub mod emotions;
mod error;
@@ -87,6 +88,7 @@ pub use drafts::{ScheduledDraft, ScheduledDrafts};
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
pub use error::{Error, Result};
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
pub use custom_emojis::{CustomEmojis, OrgEmoji, OrgEmojiCatalog, custom_emoji_html, merge_catalog, parse_metadata};
pub use gifs::{Gif, Gifs};
pub use google_calendar::{
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
@@ -104,7 +106,7 @@ pub use language_settings::{
};
pub use links::{
LinkImage, LinkInfo, MessageLinks, ams_full_size_url, hosted_content_image_url,
is_ams_image_url, is_link_image_url,
hosted_content_object_id, is_ams_image_url, is_link_image_url,
};
pub use mask::mask_conversation_id;
pub use members::{
@@ -123,7 +125,8 @@ pub use presence::{
error_status, is_endpoint_missing,
};
pub use reactions::{
CustomEmoji, custom_emoji, emotion_glyph, emotion_key, emotion_keys, insert_skin_tone,
CustomEmoji, custom_emoji, custom_emoji_display_name, custom_reaction_key, emotion_glyph,
emotion_key, emotion_keys, hides_raw_reaction_key, insert_skin_tone, is_custom_reaction_type,
reaction_glyph_for_key, reaction_key, reaction_keys,
};
pub use read_horizon::ReadHorizon;
@@ -14,6 +14,7 @@ pub mod chat_settings;pub mod compose_copilot;pub mod compose_copilot;pub mod conversations;pub mod conversations;pub mod copilot;pub mod copilot;pub mod custom_emojis;pub mod drafts;pub mod drafts;pub mod emotions;pub mod emotions;mod error;mod error;@@ -87,6 +88,7 @@ pub use drafts::{ScheduledDraft, ScheduledDrafts};pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};pub use error::{Error, Result};pub use error::{Error, Result};pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};pub use custom_emojis::{CustomEmojis, OrgEmoji, OrgEmojiCatalog, custom_emoji_html, merge_catalog, parse_metadata};pub use gifs::{Gif, Gifs};pub use gifs::{Gif, Gifs};pub use google_calendar::{pub use google_calendar::{ AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri, AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,@@ -104,7 +106,7 @@ pub use language_settings::{};};pub use links::{pub use links::{ LinkImage, LinkInfo, MessageLinks, ams_full_size_url, hosted_content_image_url, LinkImage, LinkInfo, MessageLinks, ams_full_size_url, hosted_content_image_url, is_ams_image_url, is_link_image_url, hosted_content_object_id, is_ams_image_url, is_link_image_url,};};pub use mask::mask_conversation_id;pub use mask::mask_conversation_id;pub use members::{pub use members::{@@ -123,7 +125,8 @@ pub use presence::{ error_status, is_endpoint_missing, error_status, is_endpoint_missing,};};pub use reactions::{pub use reactions::{ CustomEmoji, custom_emoji, emotion_glyph, emotion_key, emotion_keys, insert_skin_tone, CustomEmoji, custom_emoji, custom_emoji_display_name, custom_reaction_key, emotion_glyph, emotion_key, emotion_keys, hides_raw_reaction_key, insert_skin_tone, is_custom_reaction_type, reaction_glyph_for_key, reaction_key, reaction_keys, reaction_glyph_for_key, reaction_key, reaction_keys,};};pub use read_horizon::ReadHorizon;pub use read_horizon::ReadHorizon;@@ -48,6 +48,21 @@ pub fn is_link_image_url(url: &str) -> bool {
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.
pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
let (_, url) = hosted_content_fields(graph_url)?;
(is_link_image_url(&url) || is_ams_image_url(&url)).then_some(url)
}
/// The `id=` value from a Graph `hostedContents` link, used when `url=` is empty
/// (custom emoji reactions).
pub fn hosted_content_object_id(graph_url: &str) -> Option<String> {
let (id, url) = hosted_content_fields(graph_url)?;
if is_ams_object_id(&id) {
return Some(id);
}
object_id_from_ams_path(&url).map(str::to_owned)
}
fn hosted_content_fields(graph_url: &str) -> Option<(String, String)> {
let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?;
let encoded = after.split('/').next()?;
let bytes = STANDARD
@@ -55,8 +70,31 @@ pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
.or_else(|_| URL_SAFE_NO_PAD.decode(encoded))
.ok()?;
let decoded = String::from_utf8(bytes).ok()?;
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;
(is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned())
let id = decoded
.strip_prefix("id=")?
.split(',')
.next()
.filter(|id| !id.is_empty())?
.to_owned();
let url = decoded
.split_once(HOSTED_URL_KEY)
.map(|(_, url)| url.to_owned())
.unwrap_or_default();
Some((id, url))
}
pub(crate) fn is_ams_object_id(object_id: &str) -> bool {
!object_id.is_empty()
&& object_id.contains('-')
&& object_id
.chars()
.all(|character| character.is_ascii_alphanumeric() || character == '-')
}
pub(crate) fn object_id_from_ams_path(url: &str) -> Option<&str> {
let path = url.split_once("/v1/objects/")?.1;
let id = path.split(['/', '?', '#']).next()?;
is_ams_object_id(id).then_some(id)
}
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.
@@ -229,6 +267,21 @@ mod tests {
);
}
#[test]
fn custom_emoji_hosted_content_ids_carry_the_object_id_when_url_is_empty() {
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";
let id = STANDARD.encode(format!("id={object_id},type=1,url="));
let graph = format!(
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value"
);
assert_eq!(hosted_content_image_url(&graph), None);
assert_eq!(hosted_content_object_id(&graph).as_deref(), Some(object_id));
assert_eq!(
hosted_content_object_id("https://example.com/not-hosted"),
None
);
}
#[test]
fn ams_object_views_are_recognized_inside_hosted_content_ids() {
let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo";
@@ -48,6 +48,21 @@ pub fn is_link_image_url(url: &str) -> bool {/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`./// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {pub fn hosted_content_image_url(graph_url: &str) -> Option<String> { let (_, url) = hosted_content_fields(graph_url)?; (is_link_image_url(&url) || is_ams_image_url(&url)).then_some(url)}/// The `id=` value from a Graph `hostedContents` link, used when `url=` is empty/// (custom emoji reactions).pub fn hosted_content_object_id(graph_url: &str) -> Option<String> { let (id, url) = hosted_content_fields(graph_url)?; if is_ams_object_id(&id) { return Some(id); } object_id_from_ams_path(&url).map(str::to_owned)}fn hosted_content_fields(graph_url: &str) -> Option<(String, String)> { let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?; let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?; let encoded = after.split('/').next()?; let encoded = after.split('/').next()?; let bytes = STANDARD let bytes = STANDARD@@ -55,8 +70,31 @@ pub fn hosted_content_image_url(graph_url: &str) -> Option<String> { .or_else(|_| URL_SAFE_NO_PAD.decode(encoded)) .or_else(|_| URL_SAFE_NO_PAD.decode(encoded)) .ok()?; .ok()?; let decoded = String::from_utf8(bytes).ok()?; let decoded = String::from_utf8(bytes).ok()?; let (_, url) = decoded.split_once(HOSTED_URL_KEY)?; let id = decoded (is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned()) .strip_prefix("id=")? .split(',') .next() .filter(|id| !id.is_empty())? .to_owned(); let url = decoded .split_once(HOSTED_URL_KEY) .map(|(_, url)| url.to_owned()) .unwrap_or_default(); Some((id, url))}pub(crate) fn is_ams_object_id(object_id: &str) -> bool { !object_id.is_empty() && object_id.contains('-') && object_id .chars() .all(|character| character.is_ascii_alphanumeric() || character == '-')}pub(crate) fn object_id_from_ams_path(url: &str) -> Option<&str> { let path = url.split_once("/v1/objects/")?.1; let id = path.split(['/', '?', '#']).next()?; is_ams_object_id(id).then_some(id)}}/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages./// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.@@ -229,6 +267,21 @@ mod tests { ); ); } } #[test] fn custom_emoji_hosted_content_ids_carry_the_object_id_when_url_is_empty() { let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"; let id = STANDARD.encode(format!("id={object_id},type=1,url=")); let graph = format!( "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value" ); assert_eq!(hosted_content_image_url(&graph), None); assert_eq!(hosted_content_object_id(&graph).as_deref(), Some(object_id)); assert_eq!( hosted_content_object_id("https://example.com/not-hosted"), None ); } #[test] #[test] fn ams_object_views_are_recognized_inside_hosted_content_ids() { fn ams_object_views_are_recognized_inside_hosted_content_ids() { let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo"; let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo";@@ -145,26 +145,185 @@ pub fn emotion_key(glyph: &str) -> Option<&'static str> {
emotion_keys(glyph).first().copied()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CustomEmoji<'a> {
pub name: &'a str,
pub object_id: &'a str,
const CUSTOM_TYPE: &str = "custom";
const CUSTOM_UNDERSCORE: &str = "custom_";
const CUSTOM_COLON: &str = "custom:";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CustomEmoji {
pub name: String,
pub object_id: String,
}
impl CustomEmoji<'_> {
impl CustomEmoji {
pub fn key(&self) -> String {
format!("{}{CUSTOM_EMOJI_SEPARATOR}{}", self.name, self.object_id)
}
pub fn image_url(&self) -> String {
format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id)
}
/// The name to show in a tooltip or as `:name:`. `None` when we only have a placeholder.
pub fn display_name(&self) -> Option<&str> {
let name = self.name.trim();
(!name.is_empty() && !name.eq_ignore_ascii_case(CUSTOM_TYPE)).then_some(name)
}
}
/// `absolute-cinema;0-wcde-d3-5f5e...`: an org emoji, name and AMS object of its image.
pub fn custom_emoji(key: &str) -> Option<CustomEmoji<'_>> {
let (name, object_id) = key.split_once(CUSTOM_EMOJI_SEPARATOR)?;
let valid_object = !object_id.is_empty()
&& object_id
.chars()
.all(|character| character.is_ascii_alphanumeric() || character == '-');
(!name.is_empty() && valid_object).then_some(CustomEmoji { name, object_id })
/// An org custom emoji hidden in a reaction key.
///
/// Known shapes:
/// - `name;objectId` (chat service emotions)
/// - a Graph `hostedContents/...` URL whose id is `id={objectId},type=1,url=`
/// - an AMS object URL
/// - `custom_{objectId}` or a bare object id
pub fn custom_emoji(key: &str) -> Option<CustomEmoji> {
let key = key.trim();
if let Some((name, object_id)) = key.split_once(CUSTOM_EMOJI_SEPARATOR) {
let object_id = object_id
.split([CUSTOM_EMOJI_SEPARATOR, '|'])
.next()
.unwrap_or(object_id)
.trim();
let name = name
.strip_prefix(CUSTOM_UNDERSCORE)
.or_else(|| name.strip_prefix(CUSTOM_COLON))
.unwrap_or(name)
.trim();
if !name.is_empty() && crate::links::is_ams_object_id(object_id) {
return Some(CustomEmoji {
name: name.to_owned(),
object_id: object_id.to_owned(),
});
}
}
if let Some(object_id) = crate::links::hosted_content_object_id(key) {
return Some(CustomEmoji {
name: CUSTOM_TYPE.to_owned(),
object_id,
});
}
if let Some(object_id) = crate::links::object_id_from_ams_path(key) {
return Some(CustomEmoji {
name: CUSTOM_TYPE.to_owned(),
object_id: object_id.to_owned(),
});
}
if let Some(object_id) = key
.strip_prefix(CUSTOM_UNDERSCORE)
.or_else(|| key.strip_prefix(CUSTOM_COLON))
.map(str::trim)
.filter(|id| crate::links::is_ams_object_id(id))
{
return Some(CustomEmoji {
name: CUSTOM_TYPE.to_owned(),
object_id: object_id.to_owned(),
});
}
crate::links::is_ams_object_id(key).then(|| CustomEmoji {
name: CUSTOM_TYPE.to_owned(),
object_id: key.to_owned(),
})
}
/// Canonical `name;objectId` key from a Graph (or mixed) custom reaction payload.
///
/// Graph stores `reactionType: "custom"` with the name and image in `displayName`
/// and `reactionContentUrl`. Returns `None` when this is not a custom reaction.
pub fn custom_reaction_key(
reaction_type: &str,
display_name: Option<&str>,
content_url: Option<&str>,
reaction_id: Option<&str>,
) -> Option<String> {
let display_name = display_name.map(str::trim).filter(|name| !name.is_empty());
if let Some(emoji) = custom_emoji(reaction_type) {
let name = display_name
.or_else(|| emoji.display_name())
.unwrap_or(&emoji.name);
return Some(
CustomEmoji {
name: name.to_owned(),
object_id: emoji.object_id,
}
.key(),
);
}
let object_id = content_url
.and_then(crate::links::hosted_content_object_id)
.or_else(|| {
content_url
.and_then(crate::links::object_id_from_ams_path)
.map(str::to_owned)
})
.or_else(|| {
reaction_id
.map(str::trim)
.filter(|id| crate::links::is_ams_object_id(id))
.map(str::to_owned)
});
match (display_name, object_id) {
(Some(name), Some(object_id)) => Some(
CustomEmoji {
name: name.to_owned(),
object_id,
}
.key(),
),
(None, Some(object_id)) if is_custom_reaction_type(reaction_type) => Some(
CustomEmoji {
name: CUSTOM_TYPE.to_owned(),
object_id,
}
.key(),
),
(Some(name), None) if is_custom_reaction_type(reaction_type) => {
Some(format!("{CUSTOM_COLON}{name}"))
}
_ if is_custom_reaction_type(reaction_type) => Some(CUSTOM_TYPE.to_owned()),
_ => None,
}
}
pub fn is_custom_reaction_type(reaction_type: &str) -> bool {
let key = reaction_type.trim();
key.eq_ignore_ascii_case(CUSTOM_TYPE)
|| key.starts_with(CUSTOM_UNDERSCORE)
|| key.starts_with(CUSTOM_COLON)
|| custom_emoji(key).is_some()
}
/// A reaction key that must not be drawn as text in a pill (`custom`, `name;id`, ...).
pub fn hides_raw_reaction_key(key: &str) -> bool {
if ["like", "heart", "laugh", "surprised", "sad", "angry"].contains(&key) {
return false;
}
if reaction_glyph_for_key(key).is_some() {
return false;
}
if key.chars().any(|character| !character.is_ascii()) {
return false;
}
is_custom_reaction_type(key)
|| custom_emoji_display_name(key).is_some()
|| crate::links::is_ams_object_id(key)
|| key.contains(CUSTOM_EMOJI_SEPARATOR)
}
pub fn custom_emoji_display_name(key: &str) -> Option<String> {
if let Some(name) = custom_emoji(key)
.as_ref()
.and_then(CustomEmoji::display_name)
{
return Some(name.to_owned());
}
let key = key.trim();
key.strip_prefix(CUSTOM_COLON)
.or_else(|| key.strip_prefix(CUSTOM_UNDERSCORE))
.map(str::trim)
.filter(|name| !name.is_empty() && !crate::links::is_ams_object_id(name))
.map(str::to_owned)
}
#[cfg(test)]
@@ -183,6 +342,95 @@ mod tests {
assert_eq!(custom_emoji("like"), None);
assert_eq!(custom_emoji("x;../evil"), None);
assert_eq!(custom_emoji(";0-wcde-d3-1"), None);
assert_eq!(custom_emoji("custom"), None);
}
#[test]
fn custom_emoji_keys_accept_graph_and_prefixed_variants() {
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";
let hosted = format!(
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value",
base64_id(object_id)
);
let from_url = custom_emoji(&hosted).expect("hosted content");
assert_eq!(from_url.object_id, object_id);
assert_eq!(
from_url.image_url(),
format!(
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim"
)
);
let from_prefix = custom_emoji(&format!("custom_{object_id}")).expect("prefixed");
assert_eq!(from_prefix.object_id, object_id);
let from_bare = custom_emoji(object_id).expect("bare object id");
assert_eq!(from_bare.object_id, object_id);
let from_ams = custom_emoji(&format!(
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim"
))
.expect("ams url");
assert_eq!(from_ams.object_id, object_id);
}
#[test]
fn graph_custom_reaction_payloads_become_a_name_and_object_key() {
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";
let hosted = format!(
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value",
base64_id(object_id)
);
assert_eq!(
custom_reaction_key("custom", Some("tsignal"), Some(&hosted), None).as_deref(),
Some("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")
);
assert_eq!(
custom_reaction_key("custom", Some("party-parrot"), None, Some(object_id)).as_deref(),
Some("party-parrot;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")
);
assert_eq!(
custom_reaction_key("custom", Some("tsignal"), None, None).as_deref(),
Some("custom:tsignal")
);
assert_eq!(
custom_reaction_key("custom", None, None, None).as_deref(),
Some("custom")
);
assert_eq!(custom_reaction_key("like", None, None, None), None);
assert_eq!(
custom_reaction_key(
"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",
None,
None,
None
)
.as_deref(),
Some("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8")
);
assert!(hides_raw_reaction_key("custom"));
assert!(hides_raw_reaction_key("custom:tsignal"));
assert!(hides_raw_reaction_key(
"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8"
));
assert!(!hides_raw_reaction_key("like"));
assert!(!hides_raw_reaction_key("\u{1F44D}"));
assert_eq!(
custom_emoji_display_name("custom:tsignal").as_deref(),
Some("tsignal")
);
assert_eq!(
custom_emoji_display_name("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")
.as_deref(),
Some("tsignal")
);
}
fn base64_id(object_id: &str) -> String {
base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
format!("id={object_id},type=1,url="),
)
}
#[test]
@@ -145,26 +145,185 @@ pub fn emotion_key(glyph: &str) -> Option<&'static str> { emotion_keys(glyph).first().copied() emotion_keys(glyph).first().copied()}}#[derive(Debug, Clone, Copy, PartialEq, Eq)]const CUSTOM_TYPE: &str = "custom";pub struct CustomEmoji<'a> {const CUSTOM_UNDERSCORE: &str = "custom_"; pub name: &'a str,const CUSTOM_COLON: &str = "custom:"; pub object_id: &'a str,#[derive(Debug, Clone, PartialEq, Eq)]pub struct CustomEmoji { pub name: String, pub object_id: String,}}impl CustomEmoji<'_> {impl CustomEmoji { pub fn key(&self) -> String { format!("{}{CUSTOM_EMOJI_SEPARATOR}{}", self.name, self.object_id) } pub fn image_url(&self) -> String { pub fn image_url(&self) -> String { format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id) format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id) } } /// The name to show in a tooltip or as `:name:`. `None` when we only have a placeholder. pub fn display_name(&self) -> Option<&str> { let name = self.name.trim(); (!name.is_empty() && !name.eq_ignore_ascii_case(CUSTOM_TYPE)).then_some(name) }}}/// `absolute-cinema;0-wcde-d3-5f5e...`: an org emoji, name and AMS object of its image./// An org custom emoji hidden in a reaction key.pub fn custom_emoji(key: &str) -> Option<CustomEmoji<'_>> {/// let (name, object_id) = key.split_once(CUSTOM_EMOJI_SEPARATOR)?;/// Known shapes: let valid_object = !object_id.is_empty()/// - `name;objectId` (chat service emotions) && object_id/// - a Graph `hostedContents/...` URL whose id is `id={objectId},type=1,url=` .chars()/// - an AMS object URL .all(|character| character.is_ascii_alphanumeric() || character == '-');/// - `custom_{objectId}` or a bare object id (!name.is_empty() && valid_object).then_some(CustomEmoji { name, object_id })pub fn custom_emoji(key: &str) -> Option<CustomEmoji> { let key = key.trim(); if let Some((name, object_id)) = key.split_once(CUSTOM_EMOJI_SEPARATOR) { let object_id = object_id .split([CUSTOM_EMOJI_SEPARATOR, '|']) .next() .unwrap_or(object_id) .trim(); let name = name .strip_prefix(CUSTOM_UNDERSCORE) .or_else(|| name.strip_prefix(CUSTOM_COLON)) .unwrap_or(name) .trim(); if !name.is_empty() && crate::links::is_ams_object_id(object_id) { return Some(CustomEmoji { name: name.to_owned(), object_id: object_id.to_owned(), }); } } if let Some(object_id) = crate::links::hosted_content_object_id(key) { return Some(CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id, }); } if let Some(object_id) = crate::links::object_id_from_ams_path(key) { return Some(CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id: object_id.to_owned(), }); } if let Some(object_id) = key .strip_prefix(CUSTOM_UNDERSCORE) .or_else(|| key.strip_prefix(CUSTOM_COLON)) .map(str::trim) .filter(|id| crate::links::is_ams_object_id(id)) { return Some(CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id: object_id.to_owned(), }); } crate::links::is_ams_object_id(key).then(|| CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id: key.to_owned(), })}/// Canonical `name;objectId` key from a Graph (or mixed) custom reaction payload.////// Graph stores `reactionType: "custom"` with the name and image in `displayName`/// and `reactionContentUrl`. Returns `None` when this is not a custom reaction.pub fn custom_reaction_key( reaction_type: &str, display_name: Option<&str>, content_url: Option<&str>, reaction_id: Option<&str>,) -> Option<String> { let display_name = display_name.map(str::trim).filter(|name| !name.is_empty()); if let Some(emoji) = custom_emoji(reaction_type) { let name = display_name .or_else(|| emoji.display_name()) .unwrap_or(&emoji.name); return Some( CustomEmoji { name: name.to_owned(), object_id: emoji.object_id, } .key(), ); } let object_id = content_url .and_then(crate::links::hosted_content_object_id) .or_else(|| { content_url .and_then(crate::links::object_id_from_ams_path) .map(str::to_owned) }) .or_else(|| { reaction_id .map(str::trim) .filter(|id| crate::links::is_ams_object_id(id)) .map(str::to_owned) }); match (display_name, object_id) { (Some(name), Some(object_id)) => Some( CustomEmoji { name: name.to_owned(), object_id, } .key(), ), (None, Some(object_id)) if is_custom_reaction_type(reaction_type) => Some( CustomEmoji { name: CUSTOM_TYPE.to_owned(), object_id, } .key(), ), (Some(name), None) if is_custom_reaction_type(reaction_type) => { Some(format!("{CUSTOM_COLON}{name}")) } _ if is_custom_reaction_type(reaction_type) => Some(CUSTOM_TYPE.to_owned()), _ => None, }}pub fn is_custom_reaction_type(reaction_type: &str) -> bool { let key = reaction_type.trim(); key.eq_ignore_ascii_case(CUSTOM_TYPE) || key.starts_with(CUSTOM_UNDERSCORE) || key.starts_with(CUSTOM_COLON) || custom_emoji(key).is_some()}/// A reaction key that must not be drawn as text in a pill (`custom`, `name;id`, ...).pub fn hides_raw_reaction_key(key: &str) -> bool { if ["like", "heart", "laugh", "surprised", "sad", "angry"].contains(&key) { return false; } if reaction_glyph_for_key(key).is_some() { return false; } if key.chars().any(|character| !character.is_ascii()) { return false; } is_custom_reaction_type(key) || custom_emoji_display_name(key).is_some() || crate::links::is_ams_object_id(key) || key.contains(CUSTOM_EMOJI_SEPARATOR)}pub fn custom_emoji_display_name(key: &str) -> Option<String> { if let Some(name) = custom_emoji(key) .as_ref() .and_then(CustomEmoji::display_name) { return Some(name.to_owned()); } let key = key.trim(); key.strip_prefix(CUSTOM_COLON) .or_else(|| key.strip_prefix(CUSTOM_UNDERSCORE)) .map(str::trim) .filter(|name| !name.is_empty() && !crate::links::is_ams_object_id(name)) .map(str::to_owned)}}#[cfg(test)]#[cfg(test)]@@ -183,6 +342,95 @@ mod tests { assert_eq!(custom_emoji("like"), None); assert_eq!(custom_emoji("like"), None); assert_eq!(custom_emoji("x;../evil"), None); assert_eq!(custom_emoji("x;../evil"), None); assert_eq!(custom_emoji(";0-wcde-d3-1"), None); assert_eq!(custom_emoji(";0-wcde-d3-1"), None); assert_eq!(custom_emoji("custom"), None); } #[test] fn custom_emoji_keys_accept_graph_and_prefixed_variants() { let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"; let hosted = format!( "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value", base64_id(object_id) ); let from_url = custom_emoji(&hosted).expect("hosted content"); assert_eq!(from_url.object_id, object_id); assert_eq!( from_url.image_url(), format!( "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim" ) ); let from_prefix = custom_emoji(&format!("custom_{object_id}")).expect("prefixed"); assert_eq!(from_prefix.object_id, object_id); let from_bare = custom_emoji(object_id).expect("bare object id"); assert_eq!(from_bare.object_id, object_id); let from_ams = custom_emoji(&format!( "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim" )) .expect("ams url"); assert_eq!(from_ams.object_id, object_id); } #[test] fn graph_custom_reaction_payloads_become_a_name_and_object_key() { let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"; let hosted = format!( "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value", base64_id(object_id) ); assert_eq!( custom_reaction_key("custom", Some("tsignal"), Some(&hosted), None).as_deref(), Some("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") ); assert_eq!( custom_reaction_key("custom", Some("party-parrot"), None, Some(object_id)).as_deref(), Some("party-parrot;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") ); assert_eq!( custom_reaction_key("custom", Some("tsignal"), None, None).as_deref(), Some("custom:tsignal") ); assert_eq!( custom_reaction_key("custom", None, None, None).as_deref(), Some("custom") ); assert_eq!(custom_reaction_key("like", None, None, None), None); assert_eq!( custom_reaction_key( "absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8", None, None, None ) .as_deref(), Some("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8") ); assert!(hides_raw_reaction_key("custom")); assert!(hides_raw_reaction_key("custom:tsignal")); assert!(hides_raw_reaction_key( "absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8" )); assert!(!hides_raw_reaction_key("like")); assert!(!hides_raw_reaction_key("\u{1F44D}")); assert_eq!( custom_emoji_display_name("custom:tsignal").as_deref(), Some("tsignal") ); assert_eq!( custom_emoji_display_name("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853") .as_deref(), Some("tsignal") ); } fn base64_id(object_id: &str) -> String { base64::Engine::encode( &base64::engine::general_purpose::STANDARD, format!("id={object_id},type=1,url="), ) } } #[test] #[test]@@ -0,0 +1,46 @@
{
"continuationToken": "42",
"categories": [
{
"id": "customEmoji",
"title": "Custom Emoji",
"description": "Custom Emoji",
"emoticons": [
{
"id": "em-1",
"documentId": "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",
"shortcuts": ["absolute-cinema"],
"description": "absolute-cinema",
"createdOn": 1710000000000,
"isDeleted": false,
"unicode": null,
"diverse": false,
"keywords": ["cinema", "movie"],
"creator": "user-1",
"etag": "\"1\""
},
{
"id": "em-2",
"documentId": "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853",
"shortcuts": ["tsignal"],
"description": "tsignal",
"isDeleted": false,
"keywords": ["tsignal"]
},
{
"id": "em-gone",
"documentId": "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef",
"shortcuts": ["old-one"],
"isDeleted": true,
"keywords": []
},
{
"id": "em-bad",
"documentId": "../evil",
"shortcuts": ["bad"],
"isDeleted": false
}
]
}
]
}
@@ -0,0 +1,46 @@{ "continuationToken": "42", "categories": [ { "id": "customEmoji", "title": "Custom Emoji", "description": "Custom Emoji", "emoticons": [ { "id": "em-1", "documentId": "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8", "shortcuts": ["absolute-cinema"], "description": "absolute-cinema", "createdOn": 1710000000000, "isDeleted": false, "unicode": null, "diverse": false, "keywords": ["cinema", "movie"], "creator": "user-1", "etag": "\"1\"" }, { "id": "em-2", "documentId": "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853", "shortcuts": ["tsignal"], "description": "tsignal", "isDeleted": false, "keywords": ["tsignal"] }, { "id": "em-gone", "documentId": "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef", "shortcuts": ["old-one"], "isDeleted": true, "keywords": [] }, { "id": "em-bad", "documentId": "../evil", "shortcuts": ["bad"], "isDeleted": false } ] } ]}@@ -36,6 +36,7 @@ mod folders;
mod forward_sync;
mod forwarded;
mod gifs;
mod org_emojis;
mod hidden_chats;
mod image_size;
mod images;
@@ -127,7 +128,7 @@ pub use chatsvc::{
pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};
pub use chatsvc::{
CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage,
ForwardResult, Gif, OrgEmoji, OrgEmojiCatalog, PinnedMessage, custom_emoji_html, PostFollowState, PresenceStatus, SavedMessage,
ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind,
WorkLocationSource,
};
@@ -36,6 +36,7 @@ mod folders;mod forward_sync;mod forward_sync;mod forwarded;mod forwarded;mod gifs;mod gifs;mod org_emojis;mod hidden_chats;mod hidden_chats;mod image_size;mod image_size;mod images;mod images;@@ -127,7 +128,7 @@ pub use chatsvc::{pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};pub use chatsvc::{pub use chatsvc::{ CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind, CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage, ForwardResult, Gif, OrgEmoji, OrgEmojiCatalog, PinnedMessage, custom_emoji_html, PostFollowState, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind, ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource, WorkLocationSource,};};@@ -280,7 +280,13 @@ fn quote_info(content: &str) -> Option<QuoteInfo> {
fn reaction_info(reaction: &Reaction) -> ReactionInfo {
ReactionInfo {
reaction_type: reaction.reaction_type.clone(),
reaction_type: chatsvc::custom_reaction_key(
&reaction.reaction_type,
reaction.display_name.as_deref(),
reaction.reaction_content_url.as_deref(),
reaction.reaction_id.as_deref(),
)
.unwrap_or_else(|| reaction.reaction_type.clone()),
user_id: reaction
.user
.as_ref()
@@ -671,4 +677,35 @@ mod tests {
assert!(!mentions_of(mentioned)[0].group);
}
}
#[test]
fn graph_custom_emoji_reactions_keep_their_name_and_object() {
let hosted = concat!(
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/",
"aWQ9MC13dWstZDItZjM4MjU3YzBmYmEyZDI5ODFlYzJhMzY4YzVjZjE4NTMsdHlwZT0xLHVybD0=/",
"$value",
);
let message: Message = serde_json::from_value(json!({
"id": "m1",
"messageType": "message",
"createdDateTime": "2026-05-03T14:30:00Z",
"from": {"user": {"id": "u1", "displayName": "Ann"}},
"body": {"contentType": "html", "content": "<p>hi</p>"},
"reactions": [{
"reactionType": "custom",
"displayName": "tsignal",
"reactionContentUrl": hosted,
"createdDateTime": "2026-05-03T14:37:23.278Z",
"user": {"user": {"id": "u2", "displayName": "Bo"}},
}],
}))
.unwrap();
let record = message_record("c", &message).expect("record");
let reactions = crate::stored::reactions(&record);
assert_eq!(
reactions[0].reaction_type,
"tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"
);
assert_eq!(reactions[0].user_id.as_deref(), Some("u2"));
}
}
@@ -280,7 +280,13 @@ fn quote_info(content: &str) -> Option<QuoteInfo> {fn reaction_info(reaction: &Reaction) -> ReactionInfo {fn reaction_info(reaction: &Reaction) -> ReactionInfo { ReactionInfo { ReactionInfo { reaction_type: reaction.reaction_type.clone(), reaction_type: chatsvc::custom_reaction_key( &reaction.reaction_type, reaction.display_name.as_deref(), reaction.reaction_content_url.as_deref(), reaction.reaction_id.as_deref(), ) .unwrap_or_else(|| reaction.reaction_type.clone()), user_id: reaction user_id: reaction .user .user .as_ref() .as_ref()@@ -671,4 +677,35 @@ mod tests { assert!(!mentions_of(mentioned)[0].group); assert!(!mentions_of(mentioned)[0].group); } } } } #[test] fn graph_custom_emoji_reactions_keep_their_name_and_object() { let hosted = concat!( "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/", "aWQ9MC13dWstZDItZjM4MjU3YzBmYmEyZDI5ODFlYzJhMzY4YzVjZjE4NTMsdHlwZT0xLHVybD0=/", "$value", ); let message: Message = serde_json::from_value(json!({ "id": "m1", "messageType": "message", "createdDateTime": "2026-05-03T14:30:00Z", "from": {"user": {"id": "u1", "displayName": "Ann"}}, "body": {"contentType": "html", "content": "<p>hi</p>"}, "reactions": [{ "reactionType": "custom", "displayName": "tsignal", "reactionContentUrl": hosted, "createdDateTime": "2026-05-03T14:37:23.278Z", "user": {"user": {"id": "u2", "displayName": "Bo"}}, }], })) .unwrap(); let record = message_record("c", &message).expect("record"); let reactions = crate::stored::reactions(&record); assert_eq!( reactions[0].reaction_type, "tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853" ); assert_eq!(reactions[0].user_id.as_deref(), Some("u2")); }}}@@ -0,0 +1,124 @@
use chrono::{Duration, Utc};
use store::Store;
use chatsvc::{OrgEmoji, OrgEmojiCatalog, merge_catalog};
use crate::engine::SyncEngine;
use crate::error::Result;
use crate::remote::Remote;
pub const META_ORG_EMOJIS: &str = "org_emojis";
pub const META_ORG_EMOJIS_AT: &str = "org_emojis_at";
const CACHE_TTL: Duration = Duration::minutes(30);
impl<R: Remote> SyncEngine<R> {
/// Fresh catalogue from the store when it is younger than 30 minutes.
/// Otherwise a CSA refresh (delta when a continuation token is cached),
/// falling back to the stale cache if the network call fails.
pub async fn list_org_emojis(&self, force: bool) -> Result<Vec<OrgEmoji>> {
let now = Utc::now();
if !force {
if let Some(fresh) = cached_if_fresh(&self.store, now)? {
return Ok(fresh.emojis);
}
}
let previous = load_catalog(&self.store)?.unwrap_or_default();
let use_delta = !force
&& previous
.continuation
.as_deref()
.is_some_and(|token| !token.is_empty());
let incoming = if use_delta {
match self
.remote
.list_org_emojis(previous.continuation.as_deref())
.await
{
Ok(page) => page,
Err(_) => match self.remote.list_org_emojis(None).await {
Ok(page) => page,
Err(error) => return stale_or_err(previous, error),
},
}
} else {
match self.remote.list_org_emojis(None).await {
Ok(page) => page,
Err(error) => return stale_or_err(previous, error),
}
};
let merged = merge_catalog(&previous.emojis, incoming, !use_delta);
save_catalog(&self.store, &merged, now)?;
Ok(merged.emojis)
}
}
fn stale_or_err(previous: OrgEmojiCatalog, error: crate::error::Error) -> Result<Vec<OrgEmoji>> {
if previous.emojis.is_empty() {
Err(error)
} else {
Ok(previous.emojis)
}
}
pub fn cached_if_fresh(store: &Store, now: chrono::DateTime<Utc>) -> Result<Option<OrgEmojiCatalog>> {
let Some(cached_at) = store.meta_time(META_ORG_EMOJIS_AT)? else {
return Ok(None);
};
if now.signed_duration_since(cached_at) >= CACHE_TTL {
return Ok(None);
}
load_catalog(store)
}
pub fn load_catalog(store: &Store) -> Result<Option<OrgEmojiCatalog>> {
let Some(json) = store.meta(META_ORG_EMOJIS)? else {
return Ok(None);
};
Ok(serde_json::from_str(&json).ok())
}
pub fn save_catalog(
store: &Store,
catalog: &OrgEmojiCatalog,
now: chrono::DateTime<Utc>,
) -> Result<()> {
let json = serde_json::to_string(catalog).map_err(|error| crate::error::Error::Folders(error.to_string()))?;
store.set_meta(META_ORG_EMOJIS, &json)?;
store.set_meta_time(META_ORG_EMOJIS_AT, now)?;
Ok(())
}
#[cfg(test)]
mod tests {
use chatsvc::OrgEmoji;
use chrono::TimeZone;
use store::Store;
use super::*;
fn emoji(id: &str, name: &str) -> OrgEmoji {
OrgEmoji {
id: id.to_owned(),
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".to_owned(),
name: name.to_owned(),
keywords: vec![],
source: None,
}
}
#[test]
fn store_returns_a_fresh_catalogue_and_hides_a_stale_one() {
let store = Store::open_in_memory().unwrap();
let t0 = Utc.with_ymd_and_hms(2026, 5, 3, 12, 0, 0).unwrap();
let catalog = OrgEmojiCatalog {
emojis: vec![emoji("em-1", "ship-it")],
deleted_ids: vec![],
continuation: Some("42".into()),
};
save_catalog(&store, &catalog, t0).unwrap();
let fresh = cached_if_fresh(&store, t0 + Duration::minutes(29)).unwrap().unwrap();
assert_eq!(fresh.emojis[0].name, "ship-it");
assert!(cached_if_fresh(&store, t0 + Duration::minutes(31)).unwrap().is_none());
assert_eq!(load_catalog(&store).unwrap().unwrap().continuation.as_deref(), Some("42"));
}
}
@@ -0,0 +1,124 @@use chrono::{Duration, Utc};use store::Store;use chatsvc::{OrgEmoji, OrgEmojiCatalog, merge_catalog};use crate::engine::SyncEngine;use crate::error::Result;use crate::remote::Remote;pub const META_ORG_EMOJIS: &str = "org_emojis";pub const META_ORG_EMOJIS_AT: &str = "org_emojis_at";const CACHE_TTL: Duration = Duration::minutes(30);impl<R: Remote> SyncEngine<R> { /// Fresh catalogue from the store when it is younger than 30 minutes. /// Otherwise a CSA refresh (delta when a continuation token is cached), /// falling back to the stale cache if the network call fails. pub async fn list_org_emojis(&self, force: bool) -> Result<Vec<OrgEmoji>> { let now = Utc::now(); if !force { if let Some(fresh) = cached_if_fresh(&self.store, now)? { return Ok(fresh.emojis); } } let previous = load_catalog(&self.store)?.unwrap_or_default(); let use_delta = !force && previous .continuation .as_deref() .is_some_and(|token| !token.is_empty()); let incoming = if use_delta { match self .remote .list_org_emojis(previous.continuation.as_deref()) .await { Ok(page) => page, Err(_) => match self.remote.list_org_emojis(None).await { Ok(page) => page, Err(error) => return stale_or_err(previous, error), }, } } else { match self.remote.list_org_emojis(None).await { Ok(page) => page, Err(error) => return stale_or_err(previous, error), } }; let merged = merge_catalog(&previous.emojis, incoming, !use_delta); save_catalog(&self.store, &merged, now)?; Ok(merged.emojis) }}fn stale_or_err(previous: OrgEmojiCatalog, error: crate::error::Error) -> Result<Vec<OrgEmoji>> { if previous.emojis.is_empty() { Err(error) } else { Ok(previous.emojis) }}pub fn cached_if_fresh(store: &Store, now: chrono::DateTime<Utc>) -> Result<Option<OrgEmojiCatalog>> { let Some(cached_at) = store.meta_time(META_ORG_EMOJIS_AT)? else { return Ok(None); }; if now.signed_duration_since(cached_at) >= CACHE_TTL { return Ok(None); } load_catalog(store)}pub fn load_catalog(store: &Store) -> Result<Option<OrgEmojiCatalog>> { let Some(json) = store.meta(META_ORG_EMOJIS)? else { return Ok(None); }; Ok(serde_json::from_str(&json).ok())}pub fn save_catalog( store: &Store, catalog: &OrgEmojiCatalog, now: chrono::DateTime<Utc>,) -> Result<()> { let json = serde_json::to_string(catalog).map_err(|error| crate::error::Error::Folders(error.to_string()))?; store.set_meta(META_ORG_EMOJIS, &json)?; store.set_meta_time(META_ORG_EMOJIS_AT, now)?; Ok(())}#[cfg(test)]mod tests { use chatsvc::OrgEmoji; use chrono::TimeZone; use store::Store; use super::*; fn emoji(id: &str, name: &str) -> OrgEmoji { OrgEmoji { id: id.to_owned(), document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".to_owned(), name: name.to_owned(), keywords: vec![], source: None, } } #[test] fn store_returns_a_fresh_catalogue_and_hides_a_stale_one() { let store = Store::open_in_memory().unwrap(); let t0 = Utc.with_ymd_and_hms(2026, 5, 3, 12, 0, 0).unwrap(); let catalog = OrgEmojiCatalog { emojis: vec![emoji("em-1", "ship-it")], deleted_ids: vec![], continuation: Some("42".into()), }; save_catalog(&store, &catalog, t0).unwrap(); let fresh = cached_if_fresh(&store, t0 + Duration::minutes(29)).unwrap().unwrap(); assert_eq!(fresh.emojis[0].name, "ship-it"); assert!(cached_if_fresh(&store, t0 + Duration::minutes(31)).unwrap().is_none()); assert_eq!(load_catalog(&store).unwrap().unwrap().continuation.as_deref(), Some("42")); }}@@ -14,7 +14,7 @@ use chatsvc::{
use chatsvc::{
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, CustomEmojis, OrgEmojiCatalog,
MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus,
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote,
@@ -615,6 +615,10 @@ pub trait Remote {
Err(Error::Unsupported("GIF search"))
}
async fn list_org_emojis(&self, _continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
Err(Error::Unsupported("custom emoji catalogue"))
}
async fn server_search_init(
&self,
_identity: &SearchIdentity,
@@ -1635,6 +1639,14 @@ impl Remote for Graph {
Ok(Gifs::new(self.session()).search(query).await?)
}
async fn list_org_emojis(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
let client = CustomEmojis::new(self.session());
match continuation.map(str::trim).filter(|token| !token.is_empty()) {
Some(token) => Ok(client.list_since(token).await?),
None => Ok(client.list().await?),
}
}
async fn server_search_init(
&self,
identity: &SearchIdentity,
@@ -14,7 +14,7 @@ use chatsvc::{use chatsvc::{use chatsvc::{ BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef, BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare, ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare, InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, CustomEmojis, OrgEmojiCatalog, MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus, PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus, Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote,@@ -615,6 +615,10 @@ pub trait Remote { Err(Error::Unsupported("GIF search")) Err(Error::Unsupported("GIF search")) } } async fn list_org_emojis(&self, _continuation: Option<&str>) -> Result<OrgEmojiCatalog> { Err(Error::Unsupported("custom emoji catalogue")) } async fn server_search_init( async fn server_search_init( &self, &self, _identity: &SearchIdentity, _identity: &SearchIdentity,@@ -1635,6 +1639,14 @@ impl Remote for Graph { Ok(Gifs::new(self.session()).search(query).await?) Ok(Gifs::new(self.session()).search(query).await?) } } async fn list_org_emojis(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> { let client = CustomEmojis::new(self.session()); match continuation.map(str::trim).filter(|token| !token.is_empty()) { Some(token) => Ok(client.list_since(token).await?), None => Ok(client.list().await?), } } async fn server_search_init( async fn server_search_init( &self, &self, identity: &SearchIdentity, identity: &SearchIdentity,@@ -79,6 +79,7 @@ const BLOCK_ELEMENTS: [&str; 12] = [
const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
const LANGUAGE_PREFIX: &str = "language-";
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
const MAX_HEADING_LEVEL: u8 = 3;
const MARK_BACKGROUND: u32 = 0xffff00;
@@ -448,9 +449,28 @@ fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {
fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {
let value = element.value();
let is_emoji = value
.attr("itemtype")
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
let itemtype = value.attr("itemtype").unwrap_or("");
if itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) {
let name = value
.attr("alt")
.or_else(|| {
value
.attr("itemid")
.and_then(|itemid| itemid.split_once(';').map(|(name, _)| name))
})
.unwrap_or_default()
.to_owned();
if let Some(source) = value.attr("src").filter(|source| !source.is_empty()) {
spans.push(Span::CustomEmoji {
name,
url: source.to_owned(),
});
} else if !name.is_empty() {
push_text(spans, &format!(":{name}:"));
}
return;
}
let is_emoji = itemtype.contains(EMOJI_ITEMTYPE);
if is_emoji {
if let Some(alt) = value.attr("alt") {
push_text(spans, &without_repeated_skin_tone(alt));
@@ -79,6 +79,7 @@ const BLOCK_ELEMENTS: [&str; 12] = [const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];const LANGUAGE_PREFIX: &str = "language-";const LANGUAGE_PREFIX: &str = "language-";const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";const MAX_HEADING_LEVEL: u8 = 3;const MAX_HEADING_LEVEL: u8 = 3;const MARK_BACKGROUND: u32 = 0xffff00;const MARK_BACKGROUND: u32 = 0xffff00;@@ -448,9 +449,28 @@ fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) { let value = element.value(); let value = element.value(); let is_emoji = value let itemtype = value.attr("itemtype").unwrap_or(""); .attr("itemtype") if itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) { .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE)); let name = value .attr("alt") .or_else(|| { value .attr("itemid") .and_then(|itemid| itemid.split_once(';').map(|(name, _)| name)) }) .unwrap_or_default() .to_owned(); if let Some(source) = value.attr("src").filter(|source| !source.is_empty()) { spans.push(Span::CustomEmoji { name, url: source.to_owned(), }); } else if !name.is_empty() { push_text(spans, &format!(":{name}:")); } return; } let is_emoji = itemtype.contains(EMOJI_ITEMTYPE); if is_emoji { if is_emoji { if let Some(alt) = value.attr("alt") { if let Some(alt) = value.attr("alt") { push_text(spans, &without_repeated_skin_tone(alt)); push_text(spans, &without_repeated_skin_tone(alt));@@ -16,6 +16,7 @@ use crate::mentions::MentionInput;
use crate::spans::{Span, html_to_spans};
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";
const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";
@@ -318,6 +319,10 @@ fn inline_reply_quote(record: &MessageRecord) -> Option<QuoteInfo> {
})
}
fn is_emoji_itemtype(itemtype: &str) -> bool {
itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) || itemtype.contains(EMOJI_ITEMTYPE)
}
pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
if record.deleted {
return Vec::new();
@@ -336,7 +341,7 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
let value = element.value();
let is_emoji = value
.attr("itemtype")
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
.is_some_and(is_emoji_itemtype);
let src = value.attr("src").filter(|src| !src.is_empty());
let Some(url) = (match value.name() {
"img" if !is_emoji => src.map(str::to_owned),
@@ -384,7 +389,7 @@ pub fn edit_preserved(record: &MessageRecord) -> EditPreserved {
let value = element.value();
let is_emoji = value
.attr("itemtype")
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
.is_some_and(is_emoji_itemtype);
match value.name() {
"img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {
preserved
@@ -991,6 +996,7 @@ mod tests {
r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#,
r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
r#"<img itemtype="http://schema.skype.com/CustomEmoji" itemid="koffie;0-weu-d1-aaa" src="demo://org-emoji-koffie" alt="koffie" width="20" height="20">"#,
r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
);
let found = images(&record(html, "[]"));
@@ -16,6 +16,7 @@ use crate::mentions::MentionInput;use crate::spans::{Span, html_to_spans};use crate::spans::{Span, html_to_spans};const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";@@ -318,6 +319,10 @@ fn inline_reply_quote(record: &MessageRecord) -> Option<QuoteInfo> { }) })}}fn is_emoji_itemtype(itemtype: &str) -> bool { itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) || itemtype.contains(EMOJI_ITEMTYPE)}pub fn images(record: &MessageRecord) -> Vec<ImageRef> {pub fn images(record: &MessageRecord) -> Vec<ImageRef> { if record.deleted { if record.deleted { return Vec::new(); return Vec::new();@@ -336,7 +341,7 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> { let value = element.value(); let value = element.value(); let is_emoji = value let is_emoji = value .attr("itemtype") .attr("itemtype") .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE)); .is_some_and(is_emoji_itemtype); let src = value.attr("src").filter(|src| !src.is_empty()); let src = value.attr("src").filter(|src| !src.is_empty()); let Some(url) = (match value.name() { let Some(url) = (match value.name() { "img" if !is_emoji => src.map(str::to_owned), "img" if !is_emoji => src.map(str::to_owned),@@ -384,7 +389,7 @@ pub fn edit_preserved(record: &MessageRecord) -> EditPreserved { let value = element.value(); let value = element.value(); let is_emoji = value let is_emoji = value .attr("itemtype") .attr("itemtype") .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE)); .is_some_and(is_emoji_itemtype); match value.name() { match value.name() { "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => { "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => { preserved preserved@@ -991,6 +996,7 @@ mod tests { r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#, r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#, r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#, r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#, r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#, r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#, r#"<img itemtype="http://schema.skype.com/CustomEmoji" itemid="koffie;0-weu-d1-aaa" src="demo://org-emoji-koffie" alt="koffie" width="20" height="20">"#, r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#, r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#, ); ); let found = images(&record(html, "[]")); let found = images(&record(html, "[]"));@@ -539,4 +539,14 @@ fn org_emoji_keep_their_image_and_name() {
html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),
vec![text(":crying_cat:")]
);
let official = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim";
assert_eq!(
html_to_spans(&format!(
r#"<p><img alt="absolute-cinema" itemid="absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8" itemtype="http://schema.skype.com/CustomEmoji" src="{official}" width="20" height="20"></p>"#
)),
vec![Span::CustomEmoji {
name: "absolute-cinema".to_owned(),
url: official.to_owned(),
}]
);
}
@@ -539,4 +539,14 @@ fn org_emoji_keep_their_image_and_name() { html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"), html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"), vec![text(":crying_cat:")] vec![text(":crying_cat:")] ); ); let official = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim"; assert_eq!( html_to_spans(&format!( r#"<p><img alt="absolute-cinema" itemid="absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8" itemtype="http://schema.skype.com/CustomEmoji" src="{official}" width="20" height="20"></p>"# )), vec![Span::CustomEmoji { name: "absolute-cinema".to_owned(), url: official.to_owned(), }] );}}@@ -112,6 +112,12 @@ pub struct Attachment {
#[serde(rename_all = "camelCase")]
pub struct Reaction {
pub reaction_type: String,
#[serde(default)]
pub display_name: Option<String>,
#[serde(default)]
pub reaction_content_url: Option<String>,
#[serde(default)]
pub reaction_id: Option<String>,
pub created_date_time: Option<DateTime<Utc>>,
pub user: Option<Sender>,
}
@@ -112,6 +112,12 @@ pub struct Attachment {#[serde(rename_all = "camelCase")]#[serde(rename_all = "camelCase")]pub struct Reaction {pub struct Reaction { pub reaction_type: String, pub reaction_type: String, #[serde(default)] pub display_name: Option<String>, #[serde(default)] pub reaction_content_url: Option<String>, #[serde(default)] pub reaction_id: Option<String>, pub created_date_time: Option<DateTime<Utc>>, pub created_date_time: Option<DateTime<Utc>>, pub user: Option<Sender>, pub user: Option<Sender>,}}@@ -19,6 +19,8 @@ pub struct MessageSource {
pub sent_at: String,
/// Link naar het bericht in Teams, als die er is.
pub link: Option<String>,
/// Vermelde personen in het bericht (naam zoals in de tekst, e-mailadres), als bekend.
pub mentions: Vec<(String, String)>,
}
impl MessageSource {
@@ -90,6 +92,7 @@ mod tests {
sender: "Mara Lindqvist".into(),
sent_at: "15 jan 2026 13:39".into(),
link: Some("https://teams.microsoft.com/l/message/19:x/1".into()),
mentions: Vec::new(),
}
}
@@ -19,6 +19,8 @@ pub struct MessageSource { pub sent_at: String, pub sent_at: String, /// Link naar het bericht in Teams, als die er is. /// Link naar het bericht in Teams, als die er is. pub link: Option<String>, pub link: Option<String>, /// Vermelde personen in het bericht (naam zoals in de tekst, e-mailadres), als bekend. pub mentions: Vec<(String, String)>,}}impl MessageSource {impl MessageSource {@@ -90,6 +92,7 @@ mod tests { sender: "Mara Lindqvist".into(), sender: "Mara Lindqvist".into(), sent_at: "15 jan 2026 13:39".into(), sent_at: "15 jan 2026 13:39".into(), link: Some("https://teams.microsoft.com/l/message/19:x/1".into()), link: Some("https://teams.microsoft.com/l/message/19:x/1".into()), mentions: Vec::new(), } } } }@@ -26,6 +26,38 @@ pub fn iso_date_nl(value: &str) -> Option<String> {
.map(date_nl)
}
/// Invoer van een datum: `15 jan 2026`, `15-01-2026`, `15-1-26`, `15/01/2026`
/// of `2026-01-15`, als `YYYY-MM-DD`. Leeg → `Some("")` (geen datum),
/// onleesbaar → `None`.
pub fn parse_date_input(value: &str) -> Option<String> {
let value = value.trim().to_lowercase();
if value.is_empty() {
return Some(String::new());
}
let parts: Vec<&str> = value
.split([' ', '-', '/', '.'])
.filter(|part| !part.is_empty())
.collect();
let [first, second, third] = parts.as_slice() else {
return None;
};
let number = |part: &str| part.parse::<u32>().ok();
let (year, month, day) = if first.len() == 4 {
(number(first)? as i32, number(second)?, number(third)?)
} else {
let month = number(second).or_else(|| {
MONTHS
.iter()
.position(|name| second.starts_with(name))
.map(|index| index as u32 + 1)
})?;
let year = number(third)? as i32;
let year = if third.len() == 2 { 2000 + year } else { year };
(year, month, number(first)?)
};
NaiveDate::from_ymd_opt(year, month, day).map(|date| date.format("%Y-%m-%d").to_string())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -41,4 +73,29 @@ mod tests {
assert_eq!(iso_date_nl("2026-03-02").as_deref(), Some("2 mrt 2026"));
assert_eq!(iso_date_nl(""), None);
}
#[test]
fn reads_dates_as_people_type_them() {
for input in [
"15 jan 2026",
"15-01-2026",
"15-1-26",
"15/01/2026",
"2026-01-15",
" 15 Januari 2026 ",
] {
assert_eq!(
parse_date_input(input).as_deref(),
Some("2026-01-15"),
"{input}"
);
}
assert_eq!(
parse_date_input("2 mrt 2026").as_deref(),
Some("2026-03-02")
);
assert_eq!(parse_date_input("").as_deref(), Some(""));
assert_eq!(parse_date_input("31-02-2026"), None);
assert_eq!(parse_date_input("morgen"), None);
}
}
@@ -26,6 +26,38 @@ pub fn iso_date_nl(value: &str) -> Option<String> { .map(date_nl) .map(date_nl)}}/// Invoer van een datum: `15 jan 2026`, `15-01-2026`, `15-1-26`, `15/01/2026`/// of `2026-01-15`, als `YYYY-MM-DD`. Leeg → `Some("")` (geen datum),/// onleesbaar → `None`.pub fn parse_date_input(value: &str) -> Option<String> { let value = value.trim().to_lowercase(); if value.is_empty() { return Some(String::new()); } let parts: Vec<&str> = value .split([' ', '-', '/', '.']) .filter(|part| !part.is_empty()) .collect(); let [first, second, third] = parts.as_slice() else { return None; }; let number = |part: &str| part.parse::<u32>().ok(); let (year, month, day) = if first.len() == 4 { (number(first)? as i32, number(second)?, number(third)?) } else { let month = number(second).or_else(|| { MONTHS .iter() .position(|name| second.starts_with(name)) .map(|index| index as u32 + 1) })?; let year = number(third)? as i32; let year = if third.len() == 2 { 2000 + year } else { year }; (year, month, number(first)?) }; NaiveDate::from_ymd_opt(year, month, day).map(|date| date.format("%Y-%m-%d").to_string())}#[cfg(test)]#[cfg(test)]mod tests {mod tests { use super::*; use super::*;@@ -41,4 +73,29 @@ mod tests { assert_eq!(iso_date_nl("2026-03-02").as_deref(), Some("2 mrt 2026")); assert_eq!(iso_date_nl("2026-03-02").as_deref(), Some("2 mrt 2026")); assert_eq!(iso_date_nl(""), None); assert_eq!(iso_date_nl(""), None); } } #[test] fn reads_dates_as_people_type_them() { for input in [ "15 jan 2026", "15-01-2026", "15-1-26", "15/01/2026", "2026-01-15", " 15 Januari 2026 ", ] { assert_eq!( parse_date_input(input).as_deref(), Some("2026-01-15"), "{input}" ); } assert_eq!( parse_date_input("2 mrt 2026").as_deref(), Some("2026-03-02") ); assert_eq!(parse_date_input("").as_deref(), Some("")); assert_eq!(parse_date_input("31-02-2026"), None); assert_eq!(parse_date_input("morgen"), None); }}}@@ -20,6 +20,7 @@ pub mod model;
pub mod planning;
pub mod ponos;
pub mod session;
pub mod tickets;
pub mod token;
pub use client::{CardsClient, ClientError};
@@ -20,6 +20,7 @@ pub mod model;pub mod planning;pub mod planning;pub mod ponos;pub mod ponos;pub mod session;pub mod session;pub mod tickets;pub mod token;pub mod token;pub use client::{CardsClient, ClientError};pub use client::{CardsClient, ClientError};@@ -1,6 +1,9 @@
//! Ponos (`/ponos/ponos_api.php`) met het app-token (scope `ponos`): groepen,
//! «Mijn taken», een taak maken en afronden. Ponos staat een app-token alleen
//! deze taakacties toe.
//! «Mijn taken», het bord per groep (lezen, maken, bewerken, slepen) en
//! afronden. Ponos staat een app-token alleen taakacties toe (ict/ponos
//! `ponos_app_token_actions()`), geen groepen, leden of sleutels.
use std::collections::HashMap;
use serde::Deserialize;
use url::Url;
@@ -10,6 +13,10 @@ use crate::client::{CardsClient, ClientError, json_or_error};
/// Virtuele groep met de taken die aan de gebruiker zijn toegewezen.
pub const MY_TASKS_GROUP: &str = "__my_tasks__";
/// De kolommen van een Ponos-bord, in deze volgorde (`PONOS_STATUS_*`).
pub const STATUSES: [&str; 3] = ["todo", "in_progress", "done"];
pub const STATUS_DONE: &str = "done";
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct PonosGroup {
pub id: String,
@@ -20,6 +27,9 @@ pub struct PonosGroup {
pub can_create_tasks: bool,
#[serde(default = "yes")]
pub has_task_access: bool,
/// Open taken (todo + in progress).
#[serde(default)]
pub task_count: u32,
}
fn yes() -> bool {
@@ -31,6 +41,11 @@ impl PonosGroup {
pub fn accepts_new_tasks(&self) -> bool {
!self.is_virtual && self.can_create_tasks && self.has_task_access
}
/// Taken in deze groep mogen worden bewerkt en versleept.
pub fn editable(&self) -> bool {
self.is_virtual || self.has_task_access
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
@@ -49,6 +64,18 @@ pub struct PonosTask {
/// `YYYY-MM-DD` of leeg.
#[serde(default)]
pub due_date: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub assignee_email: String,
#[serde(default)]
pub category_label: String,
#[serde(default)]
pub checklist_total: u32,
#[serde(default)]
pub checklist_done: u32,
#[serde(default = "yes")]
pub can_edit: bool,
}
impl PonosTask {
@@ -69,6 +96,64 @@ impl PonosTask {
}
}
/// Velden van een nieuwe of bewerkte taak. Bij bewerken gaan alle velden mee
/// (leeg = wissen); `target_group` verplaatst de taak naar een andere groep.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TaskInput {
pub title: String,
pub description: String,
/// `YYYY-MM-DD` of leeg.
pub due_date: String,
pub assignee_email: String,
pub target_group: Option<String>,
}
impl TaskInput {
fn form(&self) -> Vec<(&'static str, &str)> {
let mut form = vec![
("title", self.title.as_str()),
("description", self.description.as_str()),
("due_date", self.due_date.as_str()),
("assignee_email", self.assignee_email.as_str()),
];
if let Some(group) = self.target_group.as_deref() {
form.push(("target_group", group));
}
form
}
}
/// `navigation`: alle groepen die de gebruiker ziet (eerst «Mijn taken»),
/// de namen van de statussen en wie er is ingelogd.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PonosNavigation {
pub groups: Vec<PonosGroup>,
pub status_labels: HashMap<String, String>,
pub user_email: String,
}
impl PonosNavigation {
/// Naam van een status zoals Ponos die toont, anders `fallback`.
pub fn status_label(&self, status: &str, fallback: impl FnOnce() -> String) -> String {
self.status_labels
.get(status)
.filter(|label| !label.trim().is_empty())
.cloned()
.unwrap_or_else(fallback)
}
}
/// Ponos-webpagina van een groep.
pub fn group_url(base_url: &str, group: &str) -> String {
let mut url = Url::parse(&format!(
"{}/ponos/index.php",
base_url.trim_end_matches('/')
))
.unwrap_or_else(|_| Url::parse("https://sleutels.kvt.nl/ponos/index.php").expect("vaste url"));
url.query_pairs_mut().append_pair("group", group);
url.to_string()
}
pub fn task_url(base_url: &str, group: &str, task: &str) -> String {
let mut url = Url::parse(&format!(
"{}/ponos/index.php",
@@ -85,6 +170,20 @@ pub fn task_url(base_url: &str, group: &str, task: &str) -> String {
struct NavigationEnvelope {
#[serde(default)]
groups: Vec<PonosGroup>,
#[serde(default)]
statuses: HashMap<String, String>,
#[serde(default)]
user_email: String,
}
impl From<NavigationEnvelope> for PonosNavigation {
fn from(envelope: NavigationEnvelope) -> Self {
PonosNavigation {
groups: envelope.groups,
status_labels: envelope.statuses,
user_email: envelope.user_email,
}
}
}
#[derive(Deserialize)]
@@ -152,6 +251,104 @@ impl CardsClient {
.collect())
}
/// Alle groepen (ook «Mijn taken») met de statusnamen, voor het bord.
pub async fn ponos_navigation(&self, token: &str) -> Result<PonosNavigation, ClientError> {
let envelope: NavigationEnvelope =
self.ponos_get(token, &[("action", "navigation")]).await?;
Ok(envelope.into())
}
/// Alle taken op het bord van een groep (ook afgerond, niet gearchiveerd),
/// in de volgorde van Ponos.
pub async fn ponos_tasks(
&self,
token: &str,
group: &str,
) -> Result<Vec<PonosTask>, ClientError> {
let envelope: TasksEnvelope = self
.ponos_get(token, &[("action", "list_tasks"), ("group", group)])
.await?;
Ok(envelope.tasks)
}
/// Nieuwe taak met alle velden uit `input` (`target_group` telt niet).
pub async fn ponos_create(
&self,
token: &str,
group: &str,
input: &TaskInput,
) -> Result<PonosTask, ClientError> {
let input = TaskInput {
target_group: None,
..input.clone()
};
let mut form = vec![("action", "create_task"), ("group", group)];
form.extend(input.form());
let envelope: TaskEnvelope = self.ponos_post(token, &form).await?;
Ok(envelope.task)
}
/// Taak bewerken; met `target_group` ook naar een andere groep.
pub async fn ponos_update_task(
&self,
token: &str,
group: &str,
task: &str,
input: &TaskInput,
) -> Result<PonosTask, ClientError> {
let mut form = vec![("action", "update_task"), ("group", group), ("task", task)];
form.extend(input.form());
let envelope: TaskEnvelope = self.ponos_post(token, &form).await?;
Ok(envelope.task)
}
/// Slepen: taak naar kolom `status` op plek `position` (0 = boven) in zijn groep.
pub async fn ponos_reorder_task(
&self,
token: &str,
group: &str,
task: &str,
status: &str,
position: usize,
) -> Result<PonosTask, ClientError> {
let position = position.to_string();
let envelope: TaskEnvelope = self
.ponos_post(
token,
&[
("action", "reorder_task"),
("group", group),
("task", task),
("status", status),
("position", &position),
],
)
.await?;
Ok(envelope.task)
}
/// Alleen de status (behoudt de plek niet; Ponos zet hem onderaan).
pub async fn ponos_set_status(
&self,
token: &str,
group: &str,
task: &str,
status: &str,
) -> Result<PonosTask, ClientError> {
let envelope: TaskEnvelope = self
.ponos_post(
token,
&[
("action", "update_status"),
("group", group),
("task", task),
("status", status),
],
)
.await?;
Ok(envelope.task)
}
/// Open taken die aan de gebruiker zijn toegewezen, eerst die met de vroegste deadline.
pub async fn ponos_my_tasks(&self, token: &str) -> Result<Vec<PonosTask>, ClientError> {
let envelope: TasksEnvelope = self
@@ -208,6 +405,89 @@ impl CardsClient {
}
}
/// Taken van één kolom, in de volgorde van Ponos.
pub fn column<'a>(tasks: &'a [PonosTask], status: &'a str) -> impl Iterator<Item = &'a PonosTask> {
tasks.iter().filter(move |task| task.status == status)
}
/// Plek die Ponos verwacht (`reorder_task`, zonder de gesleepte taak zelf) als
/// `dragged` boven taak nummer `before` van kolom `status` valt; `None` = onderaan.
pub fn drop_position(
tasks: &[PonosTask],
dragged: &str,
status: &str,
before: Option<usize>,
) -> usize {
let others: Vec<&PonosTask> = column(tasks, status)
.filter(|task| task.id != dragged)
.collect();
match before {
None => others.len(),
Some(index) => {
let target = column(tasks, status)
.nth(index)
.map(|task| task.id.as_str());
match target {
Some(id) if id != dragged => others
.iter()
.position(|task| task.id == id)
.unwrap_or(others.len()),
// Op zichzelf: plek blijft gelijk.
Some(_) => column(tasks, status)
.position(|task| task.id == dragged)
.unwrap_or(0),
None => others.len(),
}
}
}
}
/// Lokaal hetzelfde doen als `reorder_task` (meteen tonen, daarna verversen).
/// Geeft `false` als de taak er niet is.
pub fn apply_move(tasks: &mut Vec<PonosTask>, id: &str, status: &str, position: usize) -> bool {
let Some(from) = tasks.iter().position(|task| task.id == id) else {
return false;
};
let mut task = tasks.remove(from);
task.status = status.to_owned();
let slots: Vec<usize> = tasks
.iter()
.enumerate()
.filter(|(_, other)| other.status == status)
.map(|(index, _)| index)
.collect();
let insert_at = match slots.get(position) {
Some(&index) => index,
None => slots.last().map_or(tasks.len(), |&last| last + 1),
};
tasks.insert(insert_at, task);
true
}
/// Naam uit een e-mailadres: `jan.de.vries@example.com` → `Jan de Vries`.
pub fn name_from_email(email: &str) -> String {
const LOWER: [&str; 6] = ["de", "van", "der", "den", "het", "ter"];
let local = email.split('@').next().unwrap_or_default();
local
.split(['.', '_', '-'])
.filter(|part| !part.is_empty())
.enumerate()
.map(|(index, part)| {
let lower = part.to_lowercase();
if index > 0 && LOWER.contains(&lower.as_str()) {
lower
} else {
let mut chars = lower.chars();
chars
.next()
.map(|first| first.to_uppercase().chain(chars).collect())
.unwrap_or_default()
}
})
.collect::<Vec<String>>()
.join(" ")
}
/// Alleen open taken; met deadline eerst (vroegste bovenaan), daarna zonder.
pub fn sort_open(tasks: Vec<PonosTask>) -> Vec<PonosTask> {
let mut open: Vec<PonosTask> = tasks.into_iter().filter(PonosTask::is_open).collect();
@@ -266,4 +546,124 @@ mod tests {
"https://sleutels.kvt.nl/ponos/index.php?group=g1&task=t1"
);
}
fn board() -> Vec<PonosTask> {
let json = r#"{"ok":true,"tasks":[
{"id":"a","group_id":"g","title":"A","status":"todo"},
{"id":"b","group_id":"g","title":"B","status":"todo"},
{"id":"p","group_id":"g","title":"P","status":"in_progress"},
{"id":"c","group_id":"g","title":"C","status":"todo"},
{"id":"d","group_id":"g","title":"D","status":"done","description":"x","assignee_email":"jan.de.vries@example.com","checklist_total":3,"checklist_done":1,"can_edit":false}]}"#;
serde_json::from_str::<TasksEnvelope>(json).unwrap().tasks
}
fn ids<'a>(tasks: &'a [PonosTask], status: &'a str) -> Vec<&'a str> {
column(tasks, status).map(|task| task.id.as_str()).collect()
}
#[test]
fn navigation_keeps_all_groups_and_status_names() {
let json = r#"{"ok":true,"groups":[
{"id":"__my_tasks__","name":"Mijn Taken","virtual":true,"can_create_tasks":false,"task_count":2},
{"id":"g1","name":"ICT","can_create_tasks":true,"has_task_access":true},
{"id":"g2","name":"Alleen lezen","can_create_tasks":true,"has_task_access":false}],
"statuses":{"todo":"Nog te doen","in_progress":"Onderhanden","done":"Afgerond"},
"user_email":"tester@example.com"}"#;
let navigation: PonosNavigation = serde_json::from_str::<NavigationEnvelope>(json)
.unwrap()
.into();
assert_eq!(navigation.groups.len(), 3);
assert_eq!(navigation.groups[0].task_count, 2);
assert!(navigation.groups[0].editable() && !navigation.groups[0].accepts_new_tasks());
assert!(navigation.groups[1].editable() && navigation.groups[1].accepts_new_tasks());
assert!(!navigation.groups[2].editable());
assert_eq!(
navigation.status_label("in_progress", || "x".into()),
"Onderhanden"
);
assert_eq!(
navigation.status_label("onbekend", || "Terugval".into()),
"Terugval"
);
assert_eq!(navigation.user_email, "tester@example.com");
}
#[test]
fn board_tasks_read_the_extra_fields() {
let tasks = board();
assert_eq!(ids(&tasks, "todo"), ["a", "b", "c"]);
let done = &tasks[4];
assert_eq!(done.assignee_email, "jan.de.vries@example.com");
assert_eq!((done.checklist_done, done.checklist_total), (1, 3));
assert!(!done.can_edit);
assert!(tasks[0].can_edit, "zonder veld: bewerken mag");
}
#[test]
fn drop_position_matches_ponos_reorder() {
let tasks = board();
// c boven a: plek 0.
assert_eq!(drop_position(&tasks, "c", "todo", Some(0)), 0);
// a boven c (index 2): zonder a is c plek 1.
assert_eq!(drop_position(&tasks, "a", "todo", Some(2)), 1);
// a op zichzelf blijft 0; onderaan = aantal anderen.
assert_eq!(drop_position(&tasks, "a", "todo", Some(0)), 0);
assert_eq!(drop_position(&tasks, "a", "todo", None), 2);
// Naar een andere kolom.
assert_eq!(drop_position(&tasks, "a", "in_progress", Some(0)), 0);
assert_eq!(drop_position(&tasks, "a", "in_progress", None), 1);
assert_eq!(drop_position(&tasks, "a", "done", Some(9)), 1);
}
#[test]
fn apply_move_reorders_and_changes_status() {
let mut tasks = board();
assert!(apply_move(&mut tasks, "c", "todo", 0));
assert_eq!(ids(&tasks, "todo"), ["c", "a", "b"]);
assert!(apply_move(&mut tasks, "c", "todo", 99));
assert_eq!(ids(&tasks, "todo"), ["a", "b", "c"]);
assert!(apply_move(&mut tasks, "b", "in_progress", 0));
assert_eq!(ids(&tasks, "in_progress"), ["b", "p"]);
assert_eq!(ids(&tasks, "todo"), ["a", "c"]);
assert!(apply_move(&mut tasks, "a", "done", 5));
assert_eq!(ids(&tasks, "done"), ["d", "a"]);
let mut only = vec![tasks[0].clone()];
assert!(apply_move(&mut only, &tasks[0].id.clone(), "todo", 0));
assert!(!apply_move(&mut tasks, "bestaat-niet", "todo", 0));
assert_eq!(tasks.len(), 5);
}
#[test]
fn task_input_sends_every_field_and_optional_group() {
let input = TaskInput {
title: "T".into(),
description: "O".into(),
due_date: "2026-12-03".into(),
assignee_email: String::new(),
target_group: Some("g2".into()),
};
let form = input.form();
assert!(
form.contains(&("assignee_email", "")),
"leeg = toewijzing wissen"
);
assert!(form.contains(&("target_group", "g2")));
let rest = TaskInput {
target_group: None,
..input
};
let without = rest.form();
assert!(!without.iter().any(|(key, _)| *key == "target_group"));
}
#[test]
fn names_from_kvt_addresses() {
assert_eq!(name_from_email("jan.de.vries@example.com"), "Jan de Vries");
assert_eq!(name_from_email("PIET_JANSEN@example.com"), "Piet Jansen");
assert_eq!(name_from_email(""), "");
assert_eq!(
group_url("https://sleutels.kvt.nl/", "__my_tasks__"),
"https://sleutels.kvt.nl/ponos/index.php?group=__my_tasks__"
);
}
}
@@ -1,6 +1,9 @@//! Ponos (`/ponos/ponos_api.php`) met het app-token (scope `ponos`): groepen,//! Ponos (`/ponos/ponos_api.php`) met het app-token (scope `ponos`): groepen,//! «Mijn taken», een taak maken en afronden. Ponos staat een app-token alleen//! «Mijn taken», het bord per groep (lezen, maken, bewerken, slepen) en//! deze taakacties toe.//! afronden. Ponos staat een app-token alleen taakacties toe (ict/ponos//! `ponos_app_token_actions()`), geen groepen, leden of sleutels.use std::collections::HashMap;use serde::Deserialize;use serde::Deserialize;use url::Url;use url::Url;@@ -10,6 +13,10 @@ use crate::client::{CardsClient, ClientError, json_or_error};/// Virtuele groep met de taken die aan de gebruiker zijn toegewezen./// Virtuele groep met de taken die aan de gebruiker zijn toegewezen.pub const MY_TASKS_GROUP: &str = "__my_tasks__";pub const MY_TASKS_GROUP: &str = "__my_tasks__";/// De kolommen van een Ponos-bord, in deze volgorde (`PONOS_STATUS_*`).pub const STATUSES: [&str; 3] = ["todo", "in_progress", "done"];pub const STATUS_DONE: &str = "done";#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]pub struct PonosGroup {pub struct PonosGroup { pub id: String, pub id: String,@@ -20,6 +27,9 @@ pub struct PonosGroup { pub can_create_tasks: bool, pub can_create_tasks: bool, #[serde(default = "yes")] #[serde(default = "yes")] pub has_task_access: bool, pub has_task_access: bool, /// Open taken (todo + in progress). #[serde(default)] pub task_count: u32,}}fn yes() -> bool {fn yes() -> bool {@@ -31,6 +41,11 @@ impl PonosGroup { pub fn accepts_new_tasks(&self) -> bool { pub fn accepts_new_tasks(&self) -> bool { !self.is_virtual && self.can_create_tasks && self.has_task_access !self.is_virtual && self.can_create_tasks && self.has_task_access } } /// Taken in deze groep mogen worden bewerkt en versleept. pub fn editable(&self) -> bool { self.is_virtual || self.has_task_access }}}#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]@@ -49,6 +64,18 @@ pub struct PonosTask { /// `YYYY-MM-DD` of leeg. /// `YYYY-MM-DD` of leeg. #[serde(default)] #[serde(default)] pub due_date: String, pub due_date: String, #[serde(default)] pub description: String, #[serde(default)] pub assignee_email: String, #[serde(default)] pub category_label: String, #[serde(default)] pub checklist_total: u32, #[serde(default)] pub checklist_done: u32, #[serde(default = "yes")] pub can_edit: bool,}}impl PonosTask {impl PonosTask {@@ -69,6 +96,64 @@ impl PonosTask { } }}}/// Velden van een nieuwe of bewerkte taak. Bij bewerken gaan alle velden mee/// (leeg = wissen); `target_group` verplaatst de taak naar een andere groep.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct TaskInput { pub title: String, pub description: String, /// `YYYY-MM-DD` of leeg. pub due_date: String, pub assignee_email: String, pub target_group: Option<String>,}impl TaskInput { fn form(&self) -> Vec<(&'static str, &str)> { let mut form = vec![ ("title", self.title.as_str()), ("description", self.description.as_str()), ("due_date", self.due_date.as_str()), ("assignee_email", self.assignee_email.as_str()), ]; if let Some(group) = self.target_group.as_deref() { form.push(("target_group", group)); } form }}/// `navigation`: alle groepen die de gebruiker ziet (eerst «Mijn taken»),/// de namen van de statussen en wie er is ingelogd.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct PonosNavigation { pub groups: Vec<PonosGroup>, pub status_labels: HashMap<String, String>, pub user_email: String,}impl PonosNavigation { /// Naam van een status zoals Ponos die toont, anders `fallback`. pub fn status_label(&self, status: &str, fallback: impl FnOnce() -> String) -> String { self.status_labels .get(status) .filter(|label| !label.trim().is_empty()) .cloned() .unwrap_or_else(fallback) }}/// Ponos-webpagina van een groep.pub fn group_url(base_url: &str, group: &str) -> String { let mut url = Url::parse(&format!( "{}/ponos/index.php", base_url.trim_end_matches('/') )) .unwrap_or_else(|_| Url::parse("https://sleutels.kvt.nl/ponos/index.php").expect("vaste url")); url.query_pairs_mut().append_pair("group", group); url.to_string()}pub fn task_url(base_url: &str, group: &str, task: &str) -> String {pub fn task_url(base_url: &str, group: &str, task: &str) -> String { let mut url = Url::parse(&format!( let mut url = Url::parse(&format!( "{}/ponos/index.php", "{}/ponos/index.php",@@ -85,6 +170,20 @@ pub fn task_url(base_url: &str, group: &str, task: &str) -> String {struct NavigationEnvelope {struct NavigationEnvelope { #[serde(default)] #[serde(default)] groups: Vec<PonosGroup>, groups: Vec<PonosGroup>, #[serde(default)] statuses: HashMap<String, String>, #[serde(default)] user_email: String,}impl From<NavigationEnvelope> for PonosNavigation { fn from(envelope: NavigationEnvelope) -> Self { PonosNavigation { groups: envelope.groups, status_labels: envelope.statuses, user_email: envelope.user_email, } }}}#[derive(Deserialize)]#[derive(Deserialize)]@@ -152,6 +251,104 @@ impl CardsClient { .collect()) .collect()) } } /// Alle groepen (ook «Mijn taken») met de statusnamen, voor het bord. pub async fn ponos_navigation(&self, token: &str) -> Result<PonosNavigation, ClientError> { let envelope: NavigationEnvelope = self.ponos_get(token, &[("action", "navigation")]).await?; Ok(envelope.into()) } /// Alle taken op het bord van een groep (ook afgerond, niet gearchiveerd), /// in de volgorde van Ponos. pub async fn ponos_tasks( &self, token: &str, group: &str, ) -> Result<Vec<PonosTask>, ClientError> { let envelope: TasksEnvelope = self .ponos_get(token, &[("action", "list_tasks"), ("group", group)]) .await?; Ok(envelope.tasks) } /// Nieuwe taak met alle velden uit `input` (`target_group` telt niet). pub async fn ponos_create( &self, token: &str, group: &str, input: &TaskInput, ) -> Result<PonosTask, ClientError> { let input = TaskInput { target_group: None, ..input.clone() }; let mut form = vec![("action", "create_task"), ("group", group)]; form.extend(input.form()); let envelope: TaskEnvelope = self.ponos_post(token, &form).await?; Ok(envelope.task) } /// Taak bewerken; met `target_group` ook naar een andere groep. pub async fn ponos_update_task( &self, token: &str, group: &str, task: &str, input: &TaskInput, ) -> Result<PonosTask, ClientError> { let mut form = vec![("action", "update_task"), ("group", group), ("task", task)]; form.extend(input.form()); let envelope: TaskEnvelope = self.ponos_post(token, &form).await?; Ok(envelope.task) } /// Slepen: taak naar kolom `status` op plek `position` (0 = boven) in zijn groep. pub async fn ponos_reorder_task( &self, token: &str, group: &str, task: &str, status: &str, position: usize, ) -> Result<PonosTask, ClientError> { let position = position.to_string(); let envelope: TaskEnvelope = self .ponos_post( token, &[ ("action", "reorder_task"), ("group", group), ("task", task), ("status", status), ("position", &position), ], ) .await?; Ok(envelope.task) } /// Alleen de status (behoudt de plek niet; Ponos zet hem onderaan). pub async fn ponos_set_status( &self, token: &str, group: &str, task: &str, status: &str, ) -> Result<PonosTask, ClientError> { let envelope: TaskEnvelope = self .ponos_post( token, &[ ("action", "update_status"), ("group", group), ("task", task), ("status", status), ], ) .await?; Ok(envelope.task) } /// Open taken die aan de gebruiker zijn toegewezen, eerst die met de vroegste deadline. /// Open taken die aan de gebruiker zijn toegewezen, eerst die met de vroegste deadline. pub async fn ponos_my_tasks(&self, token: &str) -> Result<Vec<PonosTask>, ClientError> { pub async fn ponos_my_tasks(&self, token: &str) -> Result<Vec<PonosTask>, ClientError> { let envelope: TasksEnvelope = self let envelope: TasksEnvelope = self@@ -208,6 +405,89 @@ impl CardsClient { } }}}/// Taken van één kolom, in de volgorde van Ponos.pub fn column<'a>(tasks: &'a [PonosTask], status: &'a str) -> impl Iterator<Item = &'a PonosTask> { tasks.iter().filter(move |task| task.status == status)}/// Plek die Ponos verwacht (`reorder_task`, zonder de gesleepte taak zelf) als/// `dragged` boven taak nummer `before` van kolom `status` valt; `None` = onderaan.pub fn drop_position( tasks: &[PonosTask], dragged: &str, status: &str, before: Option<usize>,) -> usize { let others: Vec<&PonosTask> = column(tasks, status) .filter(|task| task.id != dragged) .collect(); match before { None => others.len(), Some(index) => { let target = column(tasks, status) .nth(index) .map(|task| task.id.as_str()); match target { Some(id) if id != dragged => others .iter() .position(|task| task.id == id) .unwrap_or(others.len()), // Op zichzelf: plek blijft gelijk. Some(_) => column(tasks, status) .position(|task| task.id == dragged) .unwrap_or(0), None => others.len(), } } }}/// Lokaal hetzelfde doen als `reorder_task` (meteen tonen, daarna verversen)./// Geeft `false` als de taak er niet is.pub fn apply_move(tasks: &mut Vec<PonosTask>, id: &str, status: &str, position: usize) -> bool { let Some(from) = tasks.iter().position(|task| task.id == id) else { return false; }; let mut task = tasks.remove(from); task.status = status.to_owned(); let slots: Vec<usize> = tasks .iter() .enumerate() .filter(|(_, other)| other.status == status) .map(|(index, _)| index) .collect(); let insert_at = match slots.get(position) { Some(&index) => index, None => slots.last().map_or(tasks.len(), |&last| last + 1), }; tasks.insert(insert_at, task); true}/// Naam uit een e-mailadres: `jan.de.vries@example.com` → `Jan de Vries`.pub fn name_from_email(email: &str) -> String { const LOWER: [&str; 6] = ["de", "van", "der", "den", "het", "ter"]; let local = email.split('@').next().unwrap_or_default(); local .split(['.', '_', '-']) .filter(|part| !part.is_empty()) .enumerate() .map(|(index, part)| { let lower = part.to_lowercase(); if index > 0 && LOWER.contains(&lower.as_str()) { lower } else { let mut chars = lower.chars(); chars .next() .map(|first| first.to_uppercase().chain(chars).collect()) .unwrap_or_default() } }) .collect::<Vec<String>>() .join(" ")}/// Alleen open taken; met deadline eerst (vroegste bovenaan), daarna zonder./// Alleen open taken; met deadline eerst (vroegste bovenaan), daarna zonder.pub fn sort_open(tasks: Vec<PonosTask>) -> Vec<PonosTask> {pub fn sort_open(tasks: Vec<PonosTask>) -> Vec<PonosTask> { let mut open: Vec<PonosTask> = tasks.into_iter().filter(PonosTask::is_open).collect(); let mut open: Vec<PonosTask> = tasks.into_iter().filter(PonosTask::is_open).collect();@@ -266,4 +546,124 @@ mod tests { "https://sleutels.kvt.nl/ponos/index.php?group=g1&task=t1" "https://sleutels.kvt.nl/ponos/index.php?group=g1&task=t1" ); ); } } fn board() -> Vec<PonosTask> { let json = r#"{"ok":true,"tasks":[ {"id":"a","group_id":"g","title":"A","status":"todo"}, {"id":"b","group_id":"g","title":"B","status":"todo"}, {"id":"p","group_id":"g","title":"P","status":"in_progress"}, {"id":"c","group_id":"g","title":"C","status":"todo"}, {"id":"d","group_id":"g","title":"D","status":"done","description":"x","assignee_email":"jan.de.vries@example.com","checklist_total":3,"checklist_done":1,"can_edit":false}]}"#; serde_json::from_str::<TasksEnvelope>(json).unwrap().tasks } fn ids<'a>(tasks: &'a [PonosTask], status: &'a str) -> Vec<&'a str> { column(tasks, status).map(|task| task.id.as_str()).collect() } #[test] fn navigation_keeps_all_groups_and_status_names() { let json = r#"{"ok":true,"groups":[ {"id":"__my_tasks__","name":"Mijn Taken","virtual":true,"can_create_tasks":false,"task_count":2}, {"id":"g1","name":"ICT","can_create_tasks":true,"has_task_access":true}, {"id":"g2","name":"Alleen lezen","can_create_tasks":true,"has_task_access":false}], "statuses":{"todo":"Nog te doen","in_progress":"Onderhanden","done":"Afgerond"}, "user_email":"tester@example.com"}"#; let navigation: PonosNavigation = serde_json::from_str::<NavigationEnvelope>(json) .unwrap() .into(); assert_eq!(navigation.groups.len(), 3); assert_eq!(navigation.groups[0].task_count, 2); assert!(navigation.groups[0].editable() && !navigation.groups[0].accepts_new_tasks()); assert!(navigation.groups[1].editable() && navigation.groups[1].accepts_new_tasks()); assert!(!navigation.groups[2].editable()); assert_eq!( navigation.status_label("in_progress", || "x".into()), "Onderhanden" ); assert_eq!( navigation.status_label("onbekend", || "Terugval".into()), "Terugval" ); assert_eq!(navigation.user_email, "tester@example.com"); } #[test] fn board_tasks_read_the_extra_fields() { let tasks = board(); assert_eq!(ids(&tasks, "todo"), ["a", "b", "c"]); let done = &tasks[4]; assert_eq!(done.assignee_email, "jan.de.vries@example.com"); assert_eq!((done.checklist_done, done.checklist_total), (1, 3)); assert!(!done.can_edit); assert!(tasks[0].can_edit, "zonder veld: bewerken mag"); } #[test] fn drop_position_matches_ponos_reorder() { let tasks = board(); // c boven a: plek 0. assert_eq!(drop_position(&tasks, "c", "todo", Some(0)), 0); // a boven c (index 2): zonder a is c plek 1. assert_eq!(drop_position(&tasks, "a", "todo", Some(2)), 1); // a op zichzelf blijft 0; onderaan = aantal anderen. assert_eq!(drop_position(&tasks, "a", "todo", Some(0)), 0); assert_eq!(drop_position(&tasks, "a", "todo", None), 2); // Naar een andere kolom. assert_eq!(drop_position(&tasks, "a", "in_progress", Some(0)), 0); assert_eq!(drop_position(&tasks, "a", "in_progress", None), 1); assert_eq!(drop_position(&tasks, "a", "done", Some(9)), 1); } #[test] fn apply_move_reorders_and_changes_status() { let mut tasks = board(); assert!(apply_move(&mut tasks, "c", "todo", 0)); assert_eq!(ids(&tasks, "todo"), ["c", "a", "b"]); assert!(apply_move(&mut tasks, "c", "todo", 99)); assert_eq!(ids(&tasks, "todo"), ["a", "b", "c"]); assert!(apply_move(&mut tasks, "b", "in_progress", 0)); assert_eq!(ids(&tasks, "in_progress"), ["b", "p"]); assert_eq!(ids(&tasks, "todo"), ["a", "c"]); assert!(apply_move(&mut tasks, "a", "done", 5)); assert_eq!(ids(&tasks, "done"), ["d", "a"]); let mut only = vec![tasks[0].clone()]; assert!(apply_move(&mut only, &tasks[0].id.clone(), "todo", 0)); assert!(!apply_move(&mut tasks, "bestaat-niet", "todo", 0)); assert_eq!(tasks.len(), 5); } #[test] fn task_input_sends_every_field_and_optional_group() { let input = TaskInput { title: "T".into(), description: "O".into(), due_date: "2026-12-03".into(), assignee_email: String::new(), target_group: Some("g2".into()), }; let form = input.form(); assert!( form.contains(&("assignee_email", "")), "leeg = toewijzing wissen" ); assert!(form.contains(&("target_group", "g2"))); let rest = TaskInput { target_group: None, ..input }; let without = rest.form(); assert!(!without.iter().any(|(key, _)| *key == "target_group")); } #[test] fn names_from_kvt_addresses() { assert_eq!(name_from_email("jan.de.vries@example.com"), "Jan de Vries"); assert_eq!(name_from_email("PIET_JANSEN@example.com"), "Piet Jansen"); assert_eq!(name_from_email(""), ""); assert_eq!( group_url("https://sleutels.kvt.nl/", "__my_tasks__"), "https://sleutels.kvt.nl/ponos/index.php?group=__my_tasks__" ); }}}@@ -0,0 +1,1024 @@
//! Asclepius-tickets via `/asclepius/api.php` met de app-token (scope `asclepius`).
//!
//! Wat de token mag, bepaalt Asclepius (`asclepius_app_token.php`): je eigen tickets
//! (ingediend, deelnemer, gemachtigde of aan jou toegewezen), lezen, aanmaken en een
//! gewoon bericht plaatsen. Geen status, toewijzing of ghost-berichten plaatsen.
//! Ghosts komen alleen mee voor ICT, binnen de regels van de webinterface.
use std::collections::{HashMap, HashSet};
use base64::Engine as _;
use serde::de::{self, Deserializer};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::client::{CardsClient, ClientError, json_or_error};
/// Status van een gesloten ticket.
pub const STATUS_CLOSED: &str = "afgehandeld";
/// Categorieën die op het web alleen ICT kiest; het formulier toont ze niet.
pub const ICT_ONLY_CATEGORIES: [&str; 2] = ["Uitdiensttreding", "Indiensttreding"];
/// Asclepius: titel max. 150 tekens, beschrijving max. 20 000 in het formulier.
pub const TITLE_MAX: usize = 150;
pub const DESCRIPTION_MAX: usize = 20_000;
/// Zelfde grenzen als `add_ticket_message`.
pub const ATTACHMENTS_MAX: usize = 10;
pub const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TicketFilter {
#[default]
Open,
Closed,
}
impl TicketFilter {
pub fn as_str(self) -> &'static str {
match self {
TicketFilter::Open => "open",
TicketFilter::Closed => "closed",
}
}
}
// --- lenient velden (SQLite via PDO geeft soms "12" in plaats van 12) ---------
fn de_u64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
match serde_json::Value::deserialize(deserializer)? {
serde_json::Value::Number(number) => number
.as_u64()
.or_else(|| number.as_f64().map(|value| value as u64))
.ok_or_else(|| de::Error::custom("geen getal")),
serde_json::Value::String(text) => text.trim().parse().map_err(de::Error::custom),
serde_json::Value::Null => Ok(0),
_ => Err(de::Error::custom("geen getal")),
}
}
fn de_i64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
match serde_json::Value::deserialize(deserializer)? {
serde_json::Value::Number(number) => Ok(number
.as_i64()
.or_else(|| number.as_f64().map(|value| value as i64))
.unwrap_or(0)),
serde_json::Value::String(text) => Ok(text.trim().parse().unwrap_or(0)),
serde_json::Value::Bool(value) => Ok(i64::from(value)),
_ => Ok(0),
}
}
fn de_bool<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
Ok(match serde_json::Value::deserialize(deserializer)? {
serde_json::Value::Bool(value) => value,
serde_json::Value::Number(number) => number.as_i64().unwrap_or(0) != 0,
serde_json::Value::String(text) => matches!(text.trim(), "1" | "true"),
_ => false,
})
}
fn de_string<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
Ok(match serde_json::Value::deserialize(deserializer)? {
serde_json::Value::String(text) => text,
serde_json::Value::Number(number) => number.to_string(),
_ => String::new(),
})
}
// --- model ------------------------------------------------------------------
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct Ticket {
#[serde(deserialize_with = "de_u64")]
pub id: u64,
#[serde(default, deserialize_with = "de_string")]
pub title: String,
#[serde(default, deserialize_with = "de_string")]
pub category: String,
#[serde(default, deserialize_with = "de_string")]
pub subcategory: String,
#[serde(default, deserialize_with = "de_string")]
pub user_email: String,
#[serde(default, deserialize_with = "de_string")]
pub requester_display_name: String,
#[serde(default, deserialize_with = "de_string")]
pub assigned_email: String,
#[serde(default, deserialize_with = "de_string")]
pub status: String,
#[serde(default, deserialize_with = "de_i64")]
pub priority: i64,
#[serde(default, deserialize_with = "de_string")]
pub created_at: String,
#[serde(default, deserialize_with = "de_string")]
pub updated_at: String,
#[serde(default, deserialize_with = "de_i64")]
pub message_count: i64,
}
impl Ticket {
pub fn is_closed(&self) -> bool {
is_closed(&self.status)
}
pub fn url(&self, base_url: &str) -> String {
ticket_url(base_url, self.id)
}
}
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct TicketAttachment {
#[serde(deserialize_with = "de_u64")]
pub id: u64,
#[serde(default, deserialize_with = "de_string")]
pub original_name: String,
#[serde(default, deserialize_with = "de_string")]
pub mime_type: String,
#[serde(default, deserialize_with = "de_i64")]
pub file_size: i64,
}
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct TicketMessage {
#[serde(deserialize_with = "de_u64")]
pub id: u64,
#[serde(default, deserialize_with = "de_string")]
pub sender_email: String,
/// `admin` (ICT) of `user`.
#[serde(default, deserialize_with = "de_string")]
pub sender_role: String,
#[serde(default, deserialize_with = "de_string")]
pub sender_display_name: String,
#[serde(default, deserialize_with = "de_string")]
pub message_text: String,
#[serde(default, deserialize_with = "de_string")]
pub created_at: String,
#[serde(default, deserialize_with = "de_bool")]
pub is_ghost: bool,
#[serde(default)]
pub attachments: Vec<TicketAttachment>,
}
impl TicketMessage {
pub fn sender_name(&self) -> String {
if self.sender_display_name.trim().is_empty() {
crate::ponos::name_from_email(&self.sender_email)
} else {
self.sender_display_name.trim().to_owned()
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
pub struct TicketDetail {
#[serde(flatten)]
pub ticket: Ticket,
#[serde(default, deserialize_with = "de_string")]
pub description: String,
#[serde(default)]
pub participant_emails: Vec<String>,
#[serde(default)]
pub messages: Vec<TicketMessage>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Lookups {
pub categories: Vec<String>,
/// Categorie → subcategorieën, in de volgorde van Asclepius.
pub subcategories: HashMap<String, Vec<String>>,
}
impl Lookups {
/// Categorieën voor het formulier, zonder de ICT-only categorieën (zoals op het web).
pub fn form_categories(&self) -> Vec<String> {
self.categories
.iter()
.filter(|category| !ICT_ONLY_CATEGORIES.contains(&category.as_str()))
.cloned()
.collect()
}
pub fn subcategories_of(&self, category: &str) -> &[String] {
self.subcategories
.get(category)
.map(Vec::as_slice)
.unwrap_or_default()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewAttachment {
pub filename: String,
pub mime: String,
pub data: Vec<u8>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NewTicket {
pub title: String,
pub category: String,
pub subcategory: Option<String>,
pub description: String,
/// 0–2, uit de twee vinkjes van het webformulier (`priority_from_flags`).
pub priority: u8,
pub participant_emails: Vec<String>,
pub attachments: Vec<NewAttachment>,
}
#[derive(Serialize)]
struct AttachmentBody<'a> {
filename: &'a str,
mime: &'a str,
data_base64: String,
}
#[derive(Serialize)]
struct CreateBody<'a> {
title: &'a str,
category: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
subcategory: Option<&'a str>,
description: &'a str,
priority: u8,
participant_emails: &'a [String],
#[serde(skip_serializing_if = "Vec::is_empty")]
attachments: Vec<AttachmentBody<'a>>,
}
impl NewTicket {
fn body(&self) -> CreateBody<'_> {
CreateBody {
title: &self.title,
category: &self.category,
subcategory: self
.subcategory
.as_deref()
.filter(|value| !value.is_empty()),
description: &self.description,
priority: self.priority.min(2),
participant_emails: &self.participant_emails,
attachments: self
.attachments
.iter()
.map(|attachment| AttachmentBody {
filename: &attachment.filename,
mime: &attachment.mime,
data_base64: base64::engine::general_purpose::STANDARD.encode(&attachment.data),
})
.collect(),
}
}
}
// --- regels -----------------------------------------------------------------
pub fn is_closed(status: &str) -> bool {
status.trim().eq_ignore_ascii_case(STATUS_CLOSED)
}
/// Zelfde als `getPriorityFromFlags` op het web: het tweede vinkje telt alleen met het eerste.
/// MIME-type uit de extensie (Asclepius controleert de inhoud zelf ook).
pub fn mime_for(filename: &str) -> &'static str {
let extension = filename
.rsplit_once('.')
.map(|(_, extension)| extension.to_ascii_lowercase())
.unwrap_or_default();
match extension.as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"pdf" => "application/pdf",
"txt" | "log" => "text/plain",
"csv" => "text/csv",
"doc" => "application/msword",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xls" => "application/vnd.ms-excel",
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ppt" => "application/vnd.ms-powerpoint",
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"zip" => "application/zip",
"eml" => "message/rfc822",
_ => "application/octet-stream",
}
}
pub fn priority_from_flags(blocked: bool, fully_blocked: bool) -> u8 {
match (blocked, fully_blocked) {
(true, true) => 2,
(true, false) => 1,
_ => 0,
}
}
/// `https://sleutels.kvt.nl/asclepius/index.php?open=123`.
pub fn ticket_url(base_url: &str, id: u64) -> String {
format!(
"{}/asclepius/index.php?open={id}",
base_url.trim_end_matches('/')
)
}
/// Ticketnummer uit een Asclepius-link op dezelfde host als `base_url`
/// (`/asclepius/`, `index.php` of `admin.php`, met `?open=`). Anders `None`.
pub fn ticket_id_from_url(base_url: &str, url: &str) -> Option<u64> {
let base = Url::parse(base_url).ok()?;
let url = Url::parse(url.trim()).ok()?;
if url.scheme() != "https" || !url.host_str()?.eq_ignore_ascii_case(base.host_str()?) {
return None;
}
let path = url.path().trim_end_matches('/');
if !matches!(
path,
"/asclepius" | "/asclepius/index.php" | "/asclepius/admin.php"
) {
return None;
}
url.query_pairs()
.find(|(key, _)| key == "open")
.and_then(|(_, value)| value.trim().parse::<u64>().ok())
.filter(|id| *id > 0)
}
/// Komen de opgegeven deelnemers als lijst van geldige adressen, zonder dubbele.
pub fn parse_participants(text: &str) -> Result<Vec<String>, String> {
let mut seen = HashSet::new();
let mut emails = Vec::new();
for part in text.split([',', ';', '\n', ' ']) {
let email = part.trim().trim_matches(['<', '>']).to_lowercase();
if email.is_empty() {
continue;
}
let valid = email.split_once('@').is_some_and(|(local, domain)| {
!local.is_empty() && domain.contains('.') && !domain.starts_with('.')
});
if !valid {
return Err(email);
}
if seen.insert(email.clone()) {
emails.push(email);
}
}
Ok(emails)
}
// --- @-vermeldingen ----------------------------------------------------------
/// `jan@example.com` → `@jan:examplecom` (zoals Asclepius vermeldingen opslaat).
pub fn mention_token(email: &str) -> Option<String> {
let email = email.trim().to_lowercase();
let (local, domain) = email.rsplit_once('@')?;
let domain = domain.replace('.', "");
let domain_ok = !domain.is_empty()
&& domain
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-');
(!local.is_empty() && domain_ok).then(|| format!("@{local}:{domain}"))
}
/// Teams-vermeldingen (`@Naam` in de tekst) naar Asclepius-tokens, als het adres bekend is.
/// Elke naam één keer, de langste eerst (zodat `@Jan de Vries` niet als `@Jan` telt).
pub fn mentions_to_asclepius(text: &str, mentions: &[(String, String)]) -> String {
let mut ordered: Vec<&(String, String)> = mentions.iter().collect();
ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count()));
let mut out = text.to_owned();
for (name, email) in ordered {
let name = name.trim().trim_start_matches('@');
let Some(token) = mention_token(email) else {
continue;
};
if name.is_empty() {
continue;
}
let needle = format!("@{name}");
let mut result = String::with_capacity(out.len());
let mut rest = out.as_str();
while let Some(index) = rest.find(&needle) {
result.push_str(&rest[..index]);
result.push_str(&token);
rest = &rest[index + needle.len()..];
}
result.push_str(rest);
out = result;
}
out
}
/// Een stuk berichttekst: gewone tekst of een Asclepius-vermelding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TextPart {
Text(String),
/// `key` zonder `@` (`jan:examplecom`); `email` als die bekend is.
Mention {
key: String,
email: Option<String>,
},
}
fn mention_key_char(c: char) -> bool {
c.is_ascii_alphanumeric() || "._%+-".contains(c)
}
/// Asclepius-tokens (`@jan:examplecom`) in de tekst, met het adres uit `known` als dat erbij hoort.
/// Niet in code (```…``` of `…`), niet midden in een woord of adres.
pub fn split_mentions(text: &str, known: &[String]) -> Vec<TextPart> {
let by_key: HashMap<String, String> = known
.iter()
.filter_map(|email| {
mention_token(email).map(|token| (token[1..].to_owned(), email.to_lowercase()))
})
.collect();
let mut parts = Vec::new();
let mut plain = String::new();
let chars: Vec<(usize, char)> = text.char_indices().collect();
let mut index = 0;
let mut in_fence = false;
let mut in_code = false;
while index < chars.len() {
let (byte, c) = chars[index];
if text[byte..].starts_with("```") {
in_fence = !in_fence;
plain.push_str("```");
index += 3;
continue;
}
if c == '`' && !in_fence {
in_code = !in_code;
}
let before = index.checked_sub(1).map(|i| chars[i].1);
let opens = before.is_none_or(|b| !(b.is_alphanumeric() || "@./-_".contains(b)));
if c == '@' && opens && !in_fence && !in_code {
// local
let mut end = index + 1;
while end < chars.len() && mention_key_char(chars[end].1) {
end += 1;
}
let local_end = end;
if local_end > index + 1 && end < chars.len() && chars[end].1 == ':' {
let mut domain_end = end + 1;
while domain_end < chars.len()
&& (chars[domain_end].1.is_ascii_alphanumeric() || chars[domain_end].1 == '-')
{
domain_end += 1;
}
let next = chars.get(domain_end).map(|(_, c)| *c);
let next_ok = next.is_none_or(|n| n != ':' && !n.is_alphanumeric());
if domain_end > end + 1 && next_ok {
let start = chars[index + 1].0;
let stop = chars.get(domain_end).map_or(text.len(), |(b, _)| *b);
let key = text[start..stop].to_lowercase();
let local = &text[start..chars[local_end].0];
if !local.ends_with('.') {
if !plain.is_empty() {
parts.push(TextPart::Text(std::mem::take(&mut plain)));
}
parts.push(TextPart::Mention {
email: by_key.get(&key).cloned(),
key,
});
index = domain_end;
continue;
}
}
}
}
plain.push(c);
index += 1;
}
if !plain.is_empty() {
parts.push(TextPart::Text(plain));
}
parts
}
/// Naam voor een vermelding: uit het adres als dat bekend is, anders het deel voor de `:`.
pub fn mention_label(key: &str, email: Option<&str>) -> String {
let name = match email {
Some(email) => crate::ponos::name_from_email(email),
None => crate::ponos::name_from_email(key.split(':').next().unwrap_or(key)),
};
let first = name.split(' ').next().unwrap_or_default();
format!("@{}", if first.is_empty() { key } else { first })
}
// --- lokaal ongelezen ----------------------------------------------------------
/// Laatst gezien per ticket (`updated_at`), alleen in de lokale opslag.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeenTickets {
/// Na de eerste lijst: oude tickets tellen dan niet als ongelezen.
#[serde(default)]
pub initialized: bool,
#[serde(default)]
pub seen: HashMap<u64, String>,
}
impl SeenTickets {
pub fn from_json(text: &str) -> Self {
serde_json::from_str(text).unwrap_or_default()
}
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
/// Eerste keer: alles wat er nu is telt als gelezen.
pub fn initialize(&mut self, tickets: &[Ticket]) -> bool {
if self.initialized {
return false;
}
for ticket in tickets {
self.seen.insert(ticket.id, ticket.updated_at.clone());
}
self.initialized = true;
true
}
pub fn is_unread(&self, ticket: &Ticket) -> bool {
if !self.initialized {
return false;
}
match self.seen.get(&ticket.id) {
Some(seen) => ticket.updated_at.as_str() > seen.as_str(),
None => true,
}
}
pub fn mark(&mut self, ticket: &Ticket) -> bool {
let changed = self.seen.get(&ticket.id) != Some(&ticket.updated_at);
self.seen.insert(ticket.id, ticket.updated_at.clone());
changed
}
pub fn unread_count(&self, tickets: &[Ticket]) -> usize {
tickets
.iter()
.filter(|ticket| self.is_unread(ticket))
.count()
}
}
// --- client -------------------------------------------------------------------
#[derive(Deserialize)]
struct ListEnvelope {
#[serde(default)]
tickets: Vec<Ticket>,
}
#[derive(Deserialize)]
struct UpdatesEnvelope {
#[serde(default)]
tickets: Vec<Ticket>,
#[serde(default)]
server_time: String,
}
#[derive(Deserialize)]
struct DetailEnvelope {
ticket: TicketDetail,
}
#[derive(Deserialize)]
struct LookupsEnvelope {
#[serde(default)]
categories: Vec<String>,
#[serde(default)]
subcategories: serde_json::Value,
}
#[derive(Deserialize)]
struct CreatedEnvelope {
#[serde(deserialize_with = "de_u64")]
ticket_id: u64,
}
#[derive(Deserialize)]
struct SuccessEnvelope {
#[serde(default, deserialize_with = "de_bool")]
success: bool,
}
async fn api_json<T: serde::de::DeserializeOwned>(
response: reqwest::Response,
) -> Result<T, ClientError> {
match response.status().as_u16() {
// Ongeldige invoer of te grote bijlage: de app toont «niet gelukt».
413 | 422 => Err(ClientError::BadRequest),
_ => json_or_error(response).await,
}
}
impl CardsClient {
fn asclepius_url(&self) -> String {
format!("{}/asclepius/api.php", self.base_url())
}
async fn asclepius_get<T: serde::de::DeserializeOwned>(
&self,
token: &str,
query: &[(&str, &str)],
) -> Result<T, ClientError> {
let response = self
.http()
.get(self.asclepius_url())
.query(query)
.bearer_auth(token)
.send()
.await
.map_err(|_| ClientError::Unavailable)?;
api_json(response).await
}
async fn asclepius_post<T: serde::de::DeserializeOwned>(
&self,
token: &str,
body: &impl Serialize,
) -> Result<T, ClientError> {
let body = serde_json::to_vec(body).map_err(|_| ClientError::BadRequest)?;
let response = self
.http()
.post(self.asclepius_url())
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(body)
.bearer_auth(token)
.send()
.await
.map_err(|_| ClientError::Unavailable)?;
api_json(response).await
}
/// Je tickets (zoals «Mijn tickets» op het web, plus aan jou toegewezen).
pub async fn asclepius_tickets(
&self,
token: &str,
filter: TicketFilter,
) -> Result<Vec<Ticket>, ClientError> {
let envelope: ListEnvelope = self
.asclepius_get(token, &[("filter", filter.as_str())])
.await?;
Ok(envelope.tickets)
}
/// Eén ticket met berichten; ghosts alleen als Asclepius ze voor jou toont (ICT).
pub async fn asclepius_ticket(
&self,
token: &str,
id: u64,
) -> Result<TicketDetail, ClientError> {
let id = id.to_string();
let envelope: DetailEnvelope = self
.asclepius_get(token, &[("id", id.as_str()), ("include_ghosts", "1")])
.await?;
Ok(envelope.ticket)
}
/// Tickets die sinds `since` (ISO of `server_time` van de vorige keer) veranderd zijn.
pub async fn asclepius_updates(
&self,
token: &str,
since: &str,
) -> Result<(Vec<Ticket>, String), ClientError> {
let envelope: UpdatesEnvelope = self
.asclepius_get(
token,
&[("action", "ticket_updates"), ("updated_since", since)],
)
.await?;
Ok((envelope.tickets, envelope.server_time))
}
pub async fn asclepius_lookups(&self, token: &str) -> Result<Lookups, ClientError> {
let envelope: LookupsEnvelope = self
.asclepius_get(token, &[("action", "ticket_lookups")])
.await?;
let mut subcategories = HashMap::new();
if let serde_json::Value::Object(map) = envelope.subcategories {
for (category, values) in map {
let list: Vec<String> = values
.as_array()
.map(|values| {
values
.iter()
.filter_map(|value| value.as_str().map(str::to_owned))
.collect()
})
.unwrap_or_default();
if !list.is_empty() {
subcategories.insert(category, list);
}
}
}
Ok(Lookups {
categories: envelope.categories,
subcategories,
})
}
/// Maakt het ticket op jouw naam; geeft het ticketnummer.
pub async fn asclepius_create(
&self,
token: &str,
ticket: &NewTicket,
) -> Result<u64, ClientError> {
let created: CreatedEnvelope = self.asclepius_post(token, &ticket.body()).await?;
Ok(created.ticket_id)
}
/// Een gewoon bericht (geen ghost, geen status).
pub async fn asclepius_reply(
&self,
token: &str,
id: u64,
text: &str,
) -> Result<(), ClientError> {
let envelope: SuccessEnvelope = self
.asclepius_post(
token,
&serde_json::json!({
"action": "add_ticket_message",
"ticket_id": id,
"message": text,
}),
)
.await?;
if envelope.success {
Ok(())
} else {
Err(ClientError::BadRequest)
}
}
/// De inhoud van een bijlage (alleen met de token, dus niet via de browser).
pub async fn asclepius_attachment(&self, token: &str, id: u64) -> Result<Vec<u8>, ClientError> {
let id = id.to_string();
let response = self
.http()
.get(self.asclepius_url())
.query(&[("action", "get_attachment"), ("id", id.as_str())])
.bearer_auth(token)
.send()
.await
.map_err(|_| ClientError::Unavailable)?;
match response.status().as_u16() {
200 => response
.bytes()
.await
.map(|bytes| bytes.to_vec())
.map_err(|_| ClientError::Unavailable),
401 => Err(ClientError::Unauthorized),
403 => Err(ClientError::Forbidden),
404 => Err(ClientError::NotFound),
_ => Err(ClientError::Unavailable),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn list_tolerates_string_numbers_and_nulls() {
let json = r#"{"success":true,"filter":"open","tickets":[
{"id":"12","title":"Printer","category":"Hardware bestellen","subcategory":null,
"user_email":"jan@example.com","assigned_email":null,"status":"ingediend","priority":"1",
"created_at":"2026-01-15T10:00:00+01:00","updated_at":"2026-01-15T11:00:00+01:00",
"message_count":"3","is_private":0}]}"#;
let envelope: ListEnvelope = serde_json::from_str(json).unwrap();
let ticket = &envelope.tickets[0];
assert_eq!(ticket.id, 12);
assert_eq!(ticket.priority, 1);
assert_eq!(ticket.subcategory, "");
assert_eq!(ticket.assigned_email, "");
assert_eq!(ticket.message_count, 3);
assert!(!ticket.is_closed());
}
#[test]
fn detail_reads_messages_ghosts_and_attachments() {
let json = r#"{"success":true,"ticket":{"id":7,"title":"VPN","status":"afgehandeld",
"description":"Werkt niet","participant_emails":["jan@example.com"],
"messages":[
{"id":1,"sender_email":"jan@example.com","sender_role":"user","message_text":"Hoi","created_at":"x","is_ghost":0,"attachments":[]},
{"id":"2","sender_email":"ict@example.com","sender_role":"admin","sender_display_name":"ICT Bot","message_text":"Intern","is_ghost":"1",
"attachments":[{"id":"9","original_name":"log.txt","mime_type":"text/plain","file_size":"12","download_url":"https://x"}]}
]}}"#;
let envelope: DetailEnvelope = serde_json::from_str(json).unwrap();
let detail = envelope.ticket;
assert_eq!(detail.ticket.id, 7);
assert!(detail.ticket.is_closed());
assert_eq!(detail.participant_emails, ["jan@example.com"]);
assert!(!detail.messages[0].is_ghost);
assert!(detail.messages[1].is_ghost);
assert_eq!(detail.messages[1].attachments[0].id, 9);
assert_eq!(detail.messages[0].sender_name(), "Jan");
assert_eq!(detail.messages[1].sender_name(), "ICT Bot");
}
#[test]
fn create_body_matches_the_api() {
let ticket = NewTicket {
title: "Scanner".into(),
category: "Hardware bestellen".into(),
subcategory: Some(String::new()),
description: "Graag".into(),
priority: priority_from_flags(true, true),
participant_emails: vec!["piet@example.com".into()],
attachments: vec![NewAttachment {
filename: "a.png".into(),
mime: "image/png".into(),
data: vec![1, 2, 3],
}],
};
let value = serde_json::to_value(ticket.body()).unwrap();
assert_eq!(value["priority"], 2);
assert!(value.get("subcategory").is_none());
assert_eq!(value["participant_emails"][0], "piet@example.com");
assert_eq!(value["attachments"][0]["data_base64"], "AQID");
assert!(value.get("action").is_none());
}
#[test]
fn priority_follows_the_web_checkboxes() {
assert_eq!(priority_from_flags(false, false), 0);
assert_eq!(priority_from_flags(true, false), 1);
assert_eq!(priority_from_flags(true, true), 2);
assert_eq!(priority_from_flags(false, true), 0);
}
#[test]
fn form_hides_ict_only_categories() {
let lookups = Lookups {
categories: vec![
"Hardware bestellen".into(),
"Uitdiensttreding".into(),
"Indiensttreding".into(),
],
subcategories: HashMap::from([("Hardware bestellen".into(), vec!["Laptop".into()])]),
};
assert_eq!(lookups.form_categories(), ["Hardware bestellen"]);
assert_eq!(lookups.subcategories_of("Hardware bestellen"), ["Laptop"]);
assert!(lookups.subcategories_of("Anders").is_empty());
}
#[test]
fn ticket_links_on_the_same_host_only() {
let base = "https://sleutels.kvt.nl";
assert_eq!(
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=776"),
Some(776)
);
assert_eq!(
ticket_id_from_url(base, "https://Sleutels.kvt.nl/asclepius/?open=5#mention-1"),
Some(5)
);
assert_eq!(
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/admin.php?open=9"),
Some(9)
);
assert_eq!(
ticket_id_from_url(base, "https://evil.example/asclepius/index.php?open=1"),
None
);
assert_eq!(
ticket_id_from_url(base, "http://sleutels.kvt.nl/asclepius/index.php?open=1"),
None
);
assert_eq!(
ticket_id_from_url(base, "https://sleutels.kvt.nl/ponos/?open=1"),
None
);
assert_eq!(
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php"),
None
);
assert_eq!(
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=0"),
None
);
assert_eq!(
ticket_url(base, 12),
"https://sleutels.kvt.nl/asclepius/index.php?open=12"
);
}
#[test]
fn participants_are_validated_and_deduplicated() {
assert_eq!(
parse_participants("Piet@example.com, jan@example.com; piet@example.com").unwrap(),
["piet@example.com", "jan@example.com"]
);
assert_eq!(parse_participants(" ").unwrap(), Vec::<String>::new());
assert_eq!(
parse_participants("jan, piet@example.com"),
Err("jan".into())
);
}
#[test]
fn mention_tokens_match_asclepius() {
assert_eq!(
mention_token("jan@example.com").as_deref(),
Some("@jan:examplecom")
);
assert_eq!(
mention_token("J.DeVries@example.be").as_deref(),
Some("@j.devries:examplebe")
);
assert_eq!(mention_token("geen-adres"), None);
}
#[test]
fn teams_mentions_become_asclepius_tokens() {
let mentions = vec![
("Jan".to_owned(), "jan.peters@example.com".to_owned()),
(
"Jan de Vries".to_owned(),
"j.devries@example.com".to_owned(),
),
];
assert_eq!(
mentions_to_asclepius("@Jan de Vries en @Jan, kijk even", &mentions),
"@j.devries:examplecom en @jan.peters:examplecom, kijk even"
);
assert_eq!(
mentions_to_asclepius("geen vermelding", &mentions),
"geen vermelding"
);
}
#[test]
fn asclepius_tokens_are_split_out_for_display() {
let known = vec!["jan.peters@example.com".to_owned()];
let parts = split_mentions("Hoi @jan.peters:examplecom en @piet:examplecom!", &known);
assert_eq!(
parts,
vec![
TextPart::Text("Hoi ".into()),
TextPart::Mention {
key: "jan.peters:examplecom".into(),
email: Some("jan.peters@example.com".into())
},
TextPart::Text(" en ".into()),
TextPart::Mention {
key: "piet:examplecom".into(),
email: None
},
TextPart::Text("!".into()),
]
);
assert_eq!(
mention_label("jan.peters:examplecom", Some("jan.peters@example.com")),
"@Jan"
);
assert_eq!(mention_label("piet:examplecom", None), "@Piet");
}
#[test]
fn no_mentions_in_code_addresses_or_times() {
let none = |text: &str| {
split_mentions(text, &[])
.iter()
.all(|part| matches!(part, TextPart::Text(_)))
};
assert!(none("mail jan@example.com:examplecom"));
assert!(none("`@jan:examplecom`"));
assert!(none("```\n@jan:examplecom\n```"));
assert!(none("@jan:examplecom:extra"));
assert!(none("om 10:30 @ kantoor"));
}
#[test]
fn unread_is_local_and_starts_clean() {
let mut seen = SeenTickets::default();
let ticket = Ticket {
id: 1,
updated_at: "2026-01-15T10:00:00+01:00".into(),
..Default::default()
};
assert!(!seen.is_unread(&ticket));
assert!(seen.initialize(std::slice::from_ref(&ticket)));
assert!(!seen.initialize(&[]));
assert!(!seen.is_unread(&ticket));
let newer = Ticket {
updated_at: "2026-01-15T12:00:00+01:00".into(),
..ticket.clone()
};
assert!(seen.is_unread(&newer));
let fresh = Ticket {
id: 2,
..ticket.clone()
};
assert_eq!(seen.unread_count(&[newer.clone(), fresh]), 2);
assert!(seen.mark(&newer));
assert!(!seen.is_unread(&newer));
let restored = SeenTickets::from_json(&seen.to_json());
assert_eq!(restored, seen);
}
#[test]
fn mime_comes_from_the_extension() {
assert_eq!(mime_for("Scherm.PNG"), "image/png");
assert_eq!(mime_for("rapport.pdf"), "application/pdf");
assert_eq!(mime_for("geen-extensie"), "application/octet-stream");
}
}
@@ -0,0 +1,1024 @@//! Asclepius-tickets via `/asclepius/api.php` met de app-token (scope `asclepius`).//!//! Wat de token mag, bepaalt Asclepius (`asclepius_app_token.php`): je eigen tickets//! (ingediend, deelnemer, gemachtigde of aan jou toegewezen), lezen, aanmaken en een//! gewoon bericht plaatsen. Geen status, toewijzing of ghost-berichten plaatsen.//! Ghosts komen alleen mee voor ICT, binnen de regels van de webinterface.use std::collections::{HashMap, HashSet};use base64::Engine as _;use serde::de::{self, Deserializer};use serde::{Deserialize, Serialize};use url::Url;use crate::client::{CardsClient, ClientError, json_or_error};/// Status van een gesloten ticket.pub const STATUS_CLOSED: &str = "afgehandeld";/// Categorieën die op het web alleen ICT kiest; het formulier toont ze niet.pub const ICT_ONLY_CATEGORIES: [&str; 2] = ["Uitdiensttreding", "Indiensttreding"];/// Asclepius: titel max. 150 tekens, beschrijving max. 20 000 in het formulier.pub const TITLE_MAX: usize = 150;pub const DESCRIPTION_MAX: usize = 20_000;/// Zelfde grenzen als `add_ticket_message`.pub const ATTACHMENTS_MAX: usize = 10;pub const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub enum TicketFilter { #[default] Open, Closed,}impl TicketFilter { pub fn as_str(self) -> &'static str { match self { TicketFilter::Open => "open", TicketFilter::Closed => "closed", } }}// --- lenient velden (SQLite via PDO geeft soms "12" in plaats van 12) ---------fn de_u64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> { match serde_json::Value::deserialize(deserializer)? { serde_json::Value::Number(number) => number .as_u64() .or_else(|| number.as_f64().map(|value| value as u64)) .ok_or_else(|| de::Error::custom("geen getal")), serde_json::Value::String(text) => text.trim().parse().map_err(de::Error::custom), serde_json::Value::Null => Ok(0), _ => Err(de::Error::custom("geen getal")), }}fn de_i64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> { match serde_json::Value::deserialize(deserializer)? { serde_json::Value::Number(number) => Ok(number .as_i64() .or_else(|| number.as_f64().map(|value| value as i64)) .unwrap_or(0)), serde_json::Value::String(text) => Ok(text.trim().parse().unwrap_or(0)), serde_json::Value::Bool(value) => Ok(i64::from(value)), _ => Ok(0), }}fn de_bool<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> { Ok(match serde_json::Value::deserialize(deserializer)? { serde_json::Value::Bool(value) => value, serde_json::Value::Number(number) => number.as_i64().unwrap_or(0) != 0, serde_json::Value::String(text) => matches!(text.trim(), "1" | "true"), _ => false, })}fn de_string<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> { Ok(match serde_json::Value::deserialize(deserializer)? { serde_json::Value::String(text) => text, serde_json::Value::Number(number) => number.to_string(), _ => String::new(), })}// --- model ------------------------------------------------------------------#[derive(Debug, Clone, Default, PartialEq, Deserialize)]pub struct Ticket { #[serde(deserialize_with = "de_u64")] pub id: u64, #[serde(default, deserialize_with = "de_string")] pub title: String, #[serde(default, deserialize_with = "de_string")] pub category: String, #[serde(default, deserialize_with = "de_string")] pub subcategory: String, #[serde(default, deserialize_with = "de_string")] pub user_email: String, #[serde(default, deserialize_with = "de_string")] pub requester_display_name: String, #[serde(default, deserialize_with = "de_string")] pub assigned_email: String, #[serde(default, deserialize_with = "de_string")] pub status: String, #[serde(default, deserialize_with = "de_i64")] pub priority: i64, #[serde(default, deserialize_with = "de_string")] pub created_at: String, #[serde(default, deserialize_with = "de_string")] pub updated_at: String, #[serde(default, deserialize_with = "de_i64")] pub message_count: i64,}impl Ticket { pub fn is_closed(&self) -> bool { is_closed(&self.status) } pub fn url(&self, base_url: &str) -> String { ticket_url(base_url, self.id) }}#[derive(Debug, Clone, Default, PartialEq, Deserialize)]pub struct TicketAttachment { #[serde(deserialize_with = "de_u64")] pub id: u64, #[serde(default, deserialize_with = "de_string")] pub original_name: String, #[serde(default, deserialize_with = "de_string")] pub mime_type: String, #[serde(default, deserialize_with = "de_i64")] pub file_size: i64,}#[derive(Debug, Clone, Default, PartialEq, Deserialize)]pub struct TicketMessage { #[serde(deserialize_with = "de_u64")] pub id: u64, #[serde(default, deserialize_with = "de_string")] pub sender_email: String, /// `admin` (ICT) of `user`. #[serde(default, deserialize_with = "de_string")] pub sender_role: String, #[serde(default, deserialize_with = "de_string")] pub sender_display_name: String, #[serde(default, deserialize_with = "de_string")] pub message_text: String, #[serde(default, deserialize_with = "de_string")] pub created_at: String, #[serde(default, deserialize_with = "de_bool")] pub is_ghost: bool, #[serde(default)] pub attachments: Vec<TicketAttachment>,}impl TicketMessage { pub fn sender_name(&self) -> String { if self.sender_display_name.trim().is_empty() { crate::ponos::name_from_email(&self.sender_email) } else { self.sender_display_name.trim().to_owned() } }}#[derive(Debug, Clone, Default, PartialEq, Deserialize)]pub struct TicketDetail { #[serde(flatten)] pub ticket: Ticket, #[serde(default, deserialize_with = "de_string")] pub description: String, #[serde(default)] pub participant_emails: Vec<String>, #[serde(default)] pub messages: Vec<TicketMessage>,}#[derive(Debug, Clone, Default, PartialEq)]pub struct Lookups { pub categories: Vec<String>, /// Categorie → subcategorieën, in de volgorde van Asclepius. pub subcategories: HashMap<String, Vec<String>>,}impl Lookups { /// Categorieën voor het formulier, zonder de ICT-only categorieën (zoals op het web). pub fn form_categories(&self) -> Vec<String> { self.categories .iter() .filter(|category| !ICT_ONLY_CATEGORIES.contains(&category.as_str())) .cloned() .collect() } pub fn subcategories_of(&self, category: &str) -> &[String] { self.subcategories .get(category) .map(Vec::as_slice) .unwrap_or_default() }}#[derive(Debug, Clone, PartialEq, Eq)]pub struct NewAttachment { pub filename: String, pub mime: String, pub data: Vec<u8>,}#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct NewTicket { pub title: String, pub category: String, pub subcategory: Option<String>, pub description: String, /// 0–2, uit de twee vinkjes van het webformulier (`priority_from_flags`). pub priority: u8, pub participant_emails: Vec<String>, pub attachments: Vec<NewAttachment>,}#[derive(Serialize)]struct AttachmentBody<'a> { filename: &'a str, mime: &'a str, data_base64: String,}#[derive(Serialize)]struct CreateBody<'a> { title: &'a str, category: &'a str, #[serde(skip_serializing_if = "Option::is_none")] subcategory: Option<&'a str>, description: &'a str, priority: u8, participant_emails: &'a [String], #[serde(skip_serializing_if = "Vec::is_empty")] attachments: Vec<AttachmentBody<'a>>,}impl NewTicket { fn body(&self) -> CreateBody<'_> { CreateBody { title: &self.title, category: &self.category, subcategory: self .subcategory .as_deref() .filter(|value| !value.is_empty()), description: &self.description, priority: self.priority.min(2), participant_emails: &self.participant_emails, attachments: self .attachments .iter() .map(|attachment| AttachmentBody { filename: &attachment.filename, mime: &attachment.mime, data_base64: base64::engine::general_purpose::STANDARD.encode(&attachment.data), }) .collect(), } }}// --- regels -----------------------------------------------------------------pub fn is_closed(status: &str) -> bool { status.trim().eq_ignore_ascii_case(STATUS_CLOSED)}/// Zelfde als `getPriorityFromFlags` op het web: het tweede vinkje telt alleen met het eerste./// MIME-type uit de extensie (Asclepius controleert de inhoud zelf ook).pub fn mime_for(filename: &str) -> &'static str { let extension = filename .rsplit_once('.') .map(|(_, extension)| extension.to_ascii_lowercase()) .unwrap_or_default(); match extension.as_str() { "png" => "image/png", "jpg" | "jpeg" => "image/jpeg", "gif" => "image/gif", "webp" => "image/webp", "pdf" => "application/pdf", "txt" | "log" => "text/plain", "csv" => "text/csv", "doc" => "application/msword", "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "xls" => "application/vnd.ms-excel", "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "ppt" => "application/vnd.ms-powerpoint", "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation", "zip" => "application/zip", "eml" => "message/rfc822", _ => "application/octet-stream", }}pub fn priority_from_flags(blocked: bool, fully_blocked: bool) -> u8 { match (blocked, fully_blocked) { (true, true) => 2, (true, false) => 1, _ => 0, }}/// `https://sleutels.kvt.nl/asclepius/index.php?open=123`.pub fn ticket_url(base_url: &str, id: u64) -> String { format!( "{}/asclepius/index.php?open={id}", base_url.trim_end_matches('/') )}/// Ticketnummer uit een Asclepius-link op dezelfde host als `base_url`/// (`/asclepius/`, `index.php` of `admin.php`, met `?open=`). Anders `None`.pub fn ticket_id_from_url(base_url: &str, url: &str) -> Option<u64> { let base = Url::parse(base_url).ok()?; let url = Url::parse(url.trim()).ok()?; if url.scheme() != "https" || !url.host_str()?.eq_ignore_ascii_case(base.host_str()?) { return None; } let path = url.path().trim_end_matches('/'); if !matches!( path, "/asclepius" | "/asclepius/index.php" | "/asclepius/admin.php" ) { return None; } url.query_pairs() .find(|(key, _)| key == "open") .and_then(|(_, value)| value.trim().parse::<u64>().ok()) .filter(|id| *id > 0)}/// Komen de opgegeven deelnemers als lijst van geldige adressen, zonder dubbele.pub fn parse_participants(text: &str) -> Result<Vec<String>, String> { let mut seen = HashSet::new(); let mut emails = Vec::new(); for part in text.split([',', ';', '\n', ' ']) { let email = part.trim().trim_matches(['<', '>']).to_lowercase(); if email.is_empty() { continue; } let valid = email.split_once('@').is_some_and(|(local, domain)| { !local.is_empty() && domain.contains('.') && !domain.starts_with('.') }); if !valid { return Err(email); } if seen.insert(email.clone()) { emails.push(email); } } Ok(emails)}// --- @-vermeldingen ----------------------------------------------------------/// `jan@example.com` → `@jan:examplecom` (zoals Asclepius vermeldingen opslaat).pub fn mention_token(email: &str) -> Option<String> { let email = email.trim().to_lowercase(); let (local, domain) = email.rsplit_once('@')?; let domain = domain.replace('.', ""); let domain_ok = !domain.is_empty() && domain .chars() .all(|c| c.is_ascii_alphanumeric() || c == '-'); (!local.is_empty() && domain_ok).then(|| format!("@{local}:{domain}"))}/// Teams-vermeldingen (`@Naam` in de tekst) naar Asclepius-tokens, als het adres bekend is./// Elke naam één keer, de langste eerst (zodat `@Jan de Vries` niet als `@Jan` telt).pub fn mentions_to_asclepius(text: &str, mentions: &[(String, String)]) -> String { let mut ordered: Vec<&(String, String)> = mentions.iter().collect(); ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count())); let mut out = text.to_owned(); for (name, email) in ordered { let name = name.trim().trim_start_matches('@'); let Some(token) = mention_token(email) else { continue; }; if name.is_empty() { continue; } let needle = format!("@{name}"); let mut result = String::with_capacity(out.len()); let mut rest = out.as_str(); while let Some(index) = rest.find(&needle) { result.push_str(&rest[..index]); result.push_str(&token); rest = &rest[index + needle.len()..]; } result.push_str(rest); out = result; } out}/// Een stuk berichttekst: gewone tekst of een Asclepius-vermelding.#[derive(Debug, Clone, PartialEq, Eq)]pub enum TextPart { Text(String), /// `key` zonder `@` (`jan:examplecom`); `email` als die bekend is. Mention { key: String, email: Option<String>, },}fn mention_key_char(c: char) -> bool { c.is_ascii_alphanumeric() || "._%+-".contains(c)}/// Asclepius-tokens (`@jan:examplecom`) in de tekst, met het adres uit `known` als dat erbij hoort./// Niet in code (```…``` of `…`), niet midden in een woord of adres.pub fn split_mentions(text: &str, known: &[String]) -> Vec<TextPart> { let by_key: HashMap<String, String> = known .iter() .filter_map(|email| { mention_token(email).map(|token| (token[1..].to_owned(), email.to_lowercase())) }) .collect(); let mut parts = Vec::new(); let mut plain = String::new(); let chars: Vec<(usize, char)> = text.char_indices().collect(); let mut index = 0; let mut in_fence = false; let mut in_code = false; while index < chars.len() { let (byte, c) = chars[index]; if text[byte..].starts_with("```") { in_fence = !in_fence; plain.push_str("```"); index += 3; continue; } if c == '`' && !in_fence { in_code = !in_code; } let before = index.checked_sub(1).map(|i| chars[i].1); let opens = before.is_none_or(|b| !(b.is_alphanumeric() || "@./-_".contains(b))); if c == '@' && opens && !in_fence && !in_code { // local let mut end = index + 1; while end < chars.len() && mention_key_char(chars[end].1) { end += 1; } let local_end = end; if local_end > index + 1 && end < chars.len() && chars[end].1 == ':' { let mut domain_end = end + 1; while domain_end < chars.len() && (chars[domain_end].1.is_ascii_alphanumeric() || chars[domain_end].1 == '-') { domain_end += 1; } let next = chars.get(domain_end).map(|(_, c)| *c); let next_ok = next.is_none_or(|n| n != ':' && !n.is_alphanumeric()); if domain_end > end + 1 && next_ok { let start = chars[index + 1].0; let stop = chars.get(domain_end).map_or(text.len(), |(b, _)| *b); let key = text[start..stop].to_lowercase(); let local = &text[start..chars[local_end].0]; if !local.ends_with('.') { if !plain.is_empty() { parts.push(TextPart::Text(std::mem::take(&mut plain))); } parts.push(TextPart::Mention { email: by_key.get(&key).cloned(), key, }); index = domain_end; continue; } } } } plain.push(c); index += 1; } if !plain.is_empty() { parts.push(TextPart::Text(plain)); } parts}/// Naam voor een vermelding: uit het adres als dat bekend is, anders het deel voor de `:`.pub fn mention_label(key: &str, email: Option<&str>) -> String { let name = match email { Some(email) => crate::ponos::name_from_email(email), None => crate::ponos::name_from_email(key.split(':').next().unwrap_or(key)), }; let first = name.split(' ').next().unwrap_or_default(); format!("@{}", if first.is_empty() { key } else { first })}// --- lokaal ongelezen ----------------------------------------------------------/// Laatst gezien per ticket (`updated_at`), alleen in de lokale opslag.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct SeenTickets { /// Na de eerste lijst: oude tickets tellen dan niet als ongelezen. #[serde(default)] pub initialized: bool, #[serde(default)] pub seen: HashMap<u64, String>,}impl SeenTickets { pub fn from_json(text: &str) -> Self { serde_json::from_str(text).unwrap_or_default() } pub fn to_json(&self) -> String { serde_json::to_string(self).unwrap_or_default() } /// Eerste keer: alles wat er nu is telt als gelezen. pub fn initialize(&mut self, tickets: &[Ticket]) -> bool { if self.initialized { return false; } for ticket in tickets { self.seen.insert(ticket.id, ticket.updated_at.clone()); } self.initialized = true; true } pub fn is_unread(&self, ticket: &Ticket) -> bool { if !self.initialized { return false; } match self.seen.get(&ticket.id) { Some(seen) => ticket.updated_at.as_str() > seen.as_str(), None => true, } } pub fn mark(&mut self, ticket: &Ticket) -> bool { let changed = self.seen.get(&ticket.id) != Some(&ticket.updated_at); self.seen.insert(ticket.id, ticket.updated_at.clone()); changed } pub fn unread_count(&self, tickets: &[Ticket]) -> usize { tickets .iter() .filter(|ticket| self.is_unread(ticket)) .count() }}// --- client -------------------------------------------------------------------#[derive(Deserialize)]struct ListEnvelope { #[serde(default)] tickets: Vec<Ticket>,}#[derive(Deserialize)]struct UpdatesEnvelope { #[serde(default)] tickets: Vec<Ticket>, #[serde(default)] server_time: String,}#[derive(Deserialize)]struct DetailEnvelope { ticket: TicketDetail,}#[derive(Deserialize)]struct LookupsEnvelope { #[serde(default)] categories: Vec<String>, #[serde(default)] subcategories: serde_json::Value,}#[derive(Deserialize)]struct CreatedEnvelope { #[serde(deserialize_with = "de_u64")] ticket_id: u64,}#[derive(Deserialize)]struct SuccessEnvelope { #[serde(default, deserialize_with = "de_bool")] success: bool,}async fn api_json<T: serde::de::DeserializeOwned>( response: reqwest::Response,) -> Result<T, ClientError> { match response.status().as_u16() { // Ongeldige invoer of te grote bijlage: de app toont «niet gelukt». 413 | 422 => Err(ClientError::BadRequest), _ => json_or_error(response).await, }}impl CardsClient { fn asclepius_url(&self) -> String { format!("{}/asclepius/api.php", self.base_url()) } async fn asclepius_get<T: serde::de::DeserializeOwned>( &self, token: &str, query: &[(&str, &str)], ) -> Result<T, ClientError> { let response = self .http() .get(self.asclepius_url()) .query(query) .bearer_auth(token) .send() .await .map_err(|_| ClientError::Unavailable)?; api_json(response).await } async fn asclepius_post<T: serde::de::DeserializeOwned>( &self, token: &str, body: &impl Serialize, ) -> Result<T, ClientError> { let body = serde_json::to_vec(body).map_err(|_| ClientError::BadRequest)?; let response = self .http() .post(self.asclepius_url()) .header(reqwest::header::CONTENT_TYPE, "application/json") .body(body) .bearer_auth(token) .send() .await .map_err(|_| ClientError::Unavailable)?; api_json(response).await } /// Je tickets (zoals «Mijn tickets» op het web, plus aan jou toegewezen). pub async fn asclepius_tickets( &self, token: &str, filter: TicketFilter, ) -> Result<Vec<Ticket>, ClientError> { let envelope: ListEnvelope = self .asclepius_get(token, &[("filter", filter.as_str())]) .await?; Ok(envelope.tickets) } /// Eén ticket met berichten; ghosts alleen als Asclepius ze voor jou toont (ICT). pub async fn asclepius_ticket( &self, token: &str, id: u64, ) -> Result<TicketDetail, ClientError> { let id = id.to_string(); let envelope: DetailEnvelope = self .asclepius_get(token, &[("id", id.as_str()), ("include_ghosts", "1")]) .await?; Ok(envelope.ticket) } /// Tickets die sinds `since` (ISO of `server_time` van de vorige keer) veranderd zijn. pub async fn asclepius_updates( &self, token: &str, since: &str, ) -> Result<(Vec<Ticket>, String), ClientError> { let envelope: UpdatesEnvelope = self .asclepius_get( token, &[("action", "ticket_updates"), ("updated_since", since)], ) .await?; Ok((envelope.tickets, envelope.server_time)) } pub async fn asclepius_lookups(&self, token: &str) -> Result<Lookups, ClientError> { let envelope: LookupsEnvelope = self .asclepius_get(token, &[("action", "ticket_lookups")]) .await?; let mut subcategories = HashMap::new(); if let serde_json::Value::Object(map) = envelope.subcategories { for (category, values) in map { let list: Vec<String> = values .as_array() .map(|values| { values .iter() .filter_map(|value| value.as_str().map(str::to_owned)) .collect() }) .unwrap_or_default(); if !list.is_empty() { subcategories.insert(category, list); } } } Ok(Lookups { categories: envelope.categories, subcategories, }) } /// Maakt het ticket op jouw naam; geeft het ticketnummer. pub async fn asclepius_create( &self, token: &str, ticket: &NewTicket, ) -> Result<u64, ClientError> { let created: CreatedEnvelope = self.asclepius_post(token, &ticket.body()).await?; Ok(created.ticket_id) } /// Een gewoon bericht (geen ghost, geen status). pub async fn asclepius_reply( &self, token: &str, id: u64, text: &str, ) -> Result<(), ClientError> { let envelope: SuccessEnvelope = self .asclepius_post( token, &serde_json::json!({ "action": "add_ticket_message", "ticket_id": id, "message": text, }), ) .await?; if envelope.success { Ok(()) } else { Err(ClientError::BadRequest) } } /// De inhoud van een bijlage (alleen met de token, dus niet via de browser). pub async fn asclepius_attachment(&self, token: &str, id: u64) -> Result<Vec<u8>, ClientError> { let id = id.to_string(); let response = self .http() .get(self.asclepius_url()) .query(&[("action", "get_attachment"), ("id", id.as_str())]) .bearer_auth(token) .send() .await .map_err(|_| ClientError::Unavailable)?; match response.status().as_u16() { 200 => response .bytes() .await .map(|bytes| bytes.to_vec()) .map_err(|_| ClientError::Unavailable), 401 => Err(ClientError::Unauthorized), 403 => Err(ClientError::Forbidden), 404 => Err(ClientError::NotFound), _ => Err(ClientError::Unavailable), } }}#[cfg(test)]mod tests { use super::*; #[test] fn list_tolerates_string_numbers_and_nulls() { let json = r#"{"success":true,"filter":"open","tickets":[ {"id":"12","title":"Printer","category":"Hardware bestellen","subcategory":null, "user_email":"jan@example.com","assigned_email":null,"status":"ingediend","priority":"1", "created_at":"2026-01-15T10:00:00+01:00","updated_at":"2026-01-15T11:00:00+01:00", "message_count":"3","is_private":0}]}"#; let envelope: ListEnvelope = serde_json::from_str(json).unwrap(); let ticket = &envelope.tickets[0]; assert_eq!(ticket.id, 12); assert_eq!(ticket.priority, 1); assert_eq!(ticket.subcategory, ""); assert_eq!(ticket.assigned_email, ""); assert_eq!(ticket.message_count, 3); assert!(!ticket.is_closed()); } #[test] fn detail_reads_messages_ghosts_and_attachments() { let json = r#"{"success":true,"ticket":{"id":7,"title":"VPN","status":"afgehandeld", "description":"Werkt niet","participant_emails":["jan@example.com"], "messages":[ {"id":1,"sender_email":"jan@example.com","sender_role":"user","message_text":"Hoi","created_at":"x","is_ghost":0,"attachments":[]}, {"id":"2","sender_email":"ict@example.com","sender_role":"admin","sender_display_name":"ICT Bot","message_text":"Intern","is_ghost":"1", "attachments":[{"id":"9","original_name":"log.txt","mime_type":"text/plain","file_size":"12","download_url":"https://x"}]} ]}}"#; let envelope: DetailEnvelope = serde_json::from_str(json).unwrap(); let detail = envelope.ticket; assert_eq!(detail.ticket.id, 7); assert!(detail.ticket.is_closed()); assert_eq!(detail.participant_emails, ["jan@example.com"]); assert!(!detail.messages[0].is_ghost); assert!(detail.messages[1].is_ghost); assert_eq!(detail.messages[1].attachments[0].id, 9); assert_eq!(detail.messages[0].sender_name(), "Jan"); assert_eq!(detail.messages[1].sender_name(), "ICT Bot"); } #[test] fn create_body_matches_the_api() { let ticket = NewTicket { title: "Scanner".into(), category: "Hardware bestellen".into(), subcategory: Some(String::new()), description: "Graag".into(), priority: priority_from_flags(true, true), participant_emails: vec!["piet@example.com".into()], attachments: vec![NewAttachment { filename: "a.png".into(), mime: "image/png".into(), data: vec![1, 2, 3], }], }; let value = serde_json::to_value(ticket.body()).unwrap(); assert_eq!(value["priority"], 2); assert!(value.get("subcategory").is_none()); assert_eq!(value["participant_emails"][0], "piet@example.com"); assert_eq!(value["attachments"][0]["data_base64"], "AQID"); assert!(value.get("action").is_none()); } #[test] fn priority_follows_the_web_checkboxes() { assert_eq!(priority_from_flags(false, false), 0); assert_eq!(priority_from_flags(true, false), 1); assert_eq!(priority_from_flags(true, true), 2); assert_eq!(priority_from_flags(false, true), 0); } #[test] fn form_hides_ict_only_categories() { let lookups = Lookups { categories: vec![ "Hardware bestellen".into(), "Uitdiensttreding".into(), "Indiensttreding".into(), ], subcategories: HashMap::from([("Hardware bestellen".into(), vec!["Laptop".into()])]), }; assert_eq!(lookups.form_categories(), ["Hardware bestellen"]); assert_eq!(lookups.subcategories_of("Hardware bestellen"), ["Laptop"]); assert!(lookups.subcategories_of("Anders").is_empty()); } #[test] fn ticket_links_on_the_same_host_only() { let base = "https://sleutels.kvt.nl"; assert_eq!( ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=776"), Some(776) ); assert_eq!( ticket_id_from_url(base, "https://Sleutels.kvt.nl/asclepius/?open=5#mention-1"), Some(5) ); assert_eq!( ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/admin.php?open=9"), Some(9) ); assert_eq!( ticket_id_from_url(base, "https://evil.example/asclepius/index.php?open=1"), None ); assert_eq!( ticket_id_from_url(base, "http://sleutels.kvt.nl/asclepius/index.php?open=1"), None ); assert_eq!( ticket_id_from_url(base, "https://sleutels.kvt.nl/ponos/?open=1"), None ); assert_eq!( ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php"), None ); assert_eq!( ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=0"), None ); assert_eq!( ticket_url(base, 12), "https://sleutels.kvt.nl/asclepius/index.php?open=12" ); } #[test] fn participants_are_validated_and_deduplicated() { assert_eq!( parse_participants("Piet@example.com, jan@example.com; piet@example.com").unwrap(), ["piet@example.com", "jan@example.com"] ); assert_eq!(parse_participants(" ").unwrap(), Vec::<String>::new()); assert_eq!( parse_participants("jan, piet@example.com"), Err("jan".into()) ); } #[test] fn mention_tokens_match_asclepius() { assert_eq!( mention_token("jan@example.com").as_deref(), Some("@jan:examplecom") ); assert_eq!( mention_token("J.DeVries@example.be").as_deref(), Some("@j.devries:examplebe") ); assert_eq!(mention_token("geen-adres"), None); } #[test] fn teams_mentions_become_asclepius_tokens() { let mentions = vec![ ("Jan".to_owned(), "jan.peters@example.com".to_owned()), ( "Jan de Vries".to_owned(), "j.devries@example.com".to_owned(), ), ]; assert_eq!( mentions_to_asclepius("@Jan de Vries en @Jan, kijk even", &mentions), "@j.devries:examplecom en @jan.peters:examplecom, kijk even" ); assert_eq!( mentions_to_asclepius("geen vermelding", &mentions), "geen vermelding" ); } #[test] fn asclepius_tokens_are_split_out_for_display() { let known = vec!["jan.peters@example.com".to_owned()]; let parts = split_mentions("Hoi @jan.peters:examplecom en @piet:examplecom!", &known); assert_eq!( parts, vec![ TextPart::Text("Hoi ".into()), TextPart::Mention { key: "jan.peters:examplecom".into(), email: Some("jan.peters@example.com".into()) }, TextPart::Text(" en ".into()), TextPart::Mention { key: "piet:examplecom".into(), email: None }, TextPart::Text("!".into()), ] ); assert_eq!( mention_label("jan.peters:examplecom", Some("jan.peters@example.com")), "@Jan" ); assert_eq!(mention_label("piet:examplecom", None), "@Piet"); } #[test] fn no_mentions_in_code_addresses_or_times() { let none = |text: &str| { split_mentions(text, &[]) .iter() .all(|part| matches!(part, TextPart::Text(_))) }; assert!(none("mail jan@example.com:examplecom")); assert!(none("`@jan:examplecom`")); assert!(none("```\n@jan:examplecom\n```")); assert!(none("@jan:examplecom:extra")); assert!(none("om 10:30 @ kantoor")); } #[test] fn unread_is_local_and_starts_clean() { let mut seen = SeenTickets::default(); let ticket = Ticket { id: 1, updated_at: "2026-01-15T10:00:00+01:00".into(), ..Default::default() }; assert!(!seen.is_unread(&ticket)); assert!(seen.initialize(std::slice::from_ref(&ticket))); assert!(!seen.initialize(&[])); assert!(!seen.is_unread(&ticket)); let newer = Ticket { updated_at: "2026-01-15T12:00:00+01:00".into(), ..ticket.clone() }; assert!(seen.is_unread(&newer)); let fresh = Ticket { id: 2, ..ticket.clone() }; assert_eq!(seen.unread_count(&[newer.clone(), fresh]), 2); assert!(seen.mark(&newer)); assert!(!seen.is_unread(&newer)); let restored = SeenTickets::from_json(&seen.to_json()); assert_eq!(restored, seen); } #[test] fn mime_comes_from_the_extension() { assert_eq!(mime_for("Scherm.PNG"), "image/png"); assert_eq!(mime_for("rapport.pdf"), "application/pdf"); assert_eq!(mime_for("geen-extensie"), "application/octet-stream"); }}@@ -38,3 +38,11 @@ Options for the message format were: an own card format, or a plain link with re
- «Create Ponos task» and «My tasks» call Ponos directly; the dialog lists only groups where the user may create tasks.
- The Daedalus planning is a read-only calendar source (`CalendarSource::Ics`, calendar «Daedalus»), so the calendar offers no RSVP or delete for it. Daedalus had no ICS subscription to reuse, so a small JSON endpoint was added; its `format=ics` output also needs the bearer header, which plain calendar apps cannot send. The endpoint shows only the user's own work orders, without memos or materials. When BC fails, the planning is empty rather than an error. It is on by default and can be turned off in Settings.
- The Asclepius embed view and a virtual Asclepius team are not part of this release.
## Addendum: Ponos tile and board (next release)
- Tim asked for Ponos in the navigation rail, right below Agents, with all his groups including his personal group, the columns todo / in progress / done, and creating and dragging tasks. It is a rail tile (`SidebarTab::Ponos`) that opens a full board in the main panel, like Calendar and Calls: the chat list is hidden while the board is open.
- The personal group is Ponos' own virtual «Mijn Taken» (`__my_tasks__`, all tasks assigned to you). The board lists every group `navigation` returns, in Ponos' order, and uses Ponos' own status names («Nog te doen», «Onderhanden», «Afgerond»).
- Ponos gained one action for this, `reorder_task` (column + place), and the app-token list now also allows `update_task` and `move_task` (ict/ponos !8). Still no API keys, groups, members, settings or reminders through an app token. Dragging inside «Mijn Taken» only changes the status: that view has no order of its own in Ponos.
- Ponos has no delete action (done tasks are archived automatically), so the board offers «Afronden» but no delete. The old «My tasks in Ponos» panel in the «…» menu is gone; the tile replaces it.
- Planned, not built: the Asclepius integration (virtual team / embed view) becomes the next tile, directly below Ponos.
@@ -38,3 +38,11 @@ Options for the message format were: an own card format, or a plain link with re- «Create Ponos task» and «My tasks» call Ponos directly; the dialog lists only groups where the user may create tasks.- «Create Ponos task» and «My tasks» call Ponos directly; the dialog lists only groups where the user may create tasks.- The Daedalus planning is a read-only calendar source (`CalendarSource::Ics`, calendar «Daedalus»), so the calendar offers no RSVP or delete for it. Daedalus had no ICS subscription to reuse, so a small JSON endpoint was added; its `format=ics` output also needs the bearer header, which plain calendar apps cannot send. The endpoint shows only the user's own work orders, without memos or materials. When BC fails, the planning is empty rather than an error. It is on by default and can be turned off in Settings.- The Daedalus planning is a read-only calendar source (`CalendarSource::Ics`, calendar «Daedalus»), so the calendar offers no RSVP or delete for it. Daedalus had no ICS subscription to reuse, so a small JSON endpoint was added; its `format=ics` output also needs the bearer header, which plain calendar apps cannot send. The endpoint shows only the user's own work orders, without memos or materials. When BC fails, the planning is empty rather than an error. It is on by default and can be turned off in Settings.- The Asclepius embed view and a virtual Asclepius team are not part of this release.- The Asclepius embed view and a virtual Asclepius team are not part of this release.## Addendum: Ponos tile and board (next release)- Tim asked for Ponos in the navigation rail, right below Agents, with all his groups including his personal group, the columns todo / in progress / done, and creating and dragging tasks. It is a rail tile (`SidebarTab::Ponos`) that opens a full board in the main panel, like Calendar and Calls: the chat list is hidden while the board is open.- The personal group is Ponos' own virtual «Mijn Taken» (`__my_tasks__`, all tasks assigned to you). The board lists every group `navigation` returns, in Ponos' order, and uses Ponos' own status names («Nog te doen», «Onderhanden», «Afgerond»).- Ponos gained one action for this, `reorder_task` (column + place), and the app-token list now also allows `update_task` and `move_task` (ict/ponos !8). Still no API keys, groups, members, settings or reminders through an app token. Dragging inside «Mijn Taken» only changes the status: that view has no order of its own in Ponos.- Ponos has no delete action (done tasks are archived automatically), so the board offers «Afronden» but no delete. The old «My tasks in Ponos» panel in the «…» menu is gone; the tile replaces it.- Planned, not built: the Asclepius integration (virtual team / embed view) becomes the next tile, directly below Ponos.@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# Pack or unpack a Cargo/rustup (and optional cargo-xwin) cache as one tarball.
# BlueGit `cache.paths` copies only files, not directories, so a directory
# such as cargo-home/ would otherwise be skipped (see bluegit runner saveCache).
# Does not cache target/: too large for the runner's job-cache budget.
set -euo pipefail
usage() {
echo "usage: $0 restore|save linux|windows" >&2
exit 2
}
cmd="${1:-}"
kind="${2:-}"
[[ "$cmd" == restore || "$cmd" == save ]] || usage
[[ "$kind" == linux || "$kind" == windows ]] || usage
archive=".ci-cache/cargo-${kind}.tar.gz"
# Locations in the job workspace (set by the CI job / ci-setup.sh).
cargo_home="${CARGO_HOME:-$PWD/cargo-home}"
rustup_home="${RUSTUP_HOME:-$PWD/rustup-home}"
xwin_cache="${XWIN_CACHE_DIR:-$PWD/xwin-cache}"
relpath() {
local abs="$1"
case "$abs" in
"$PWD"/*) printf '%s\n' "${abs#"$PWD"/}" ;;
/*) printf '%s\n' "$abs" ;;
*) printf '%s\n' "$abs" ;;
esac
}
if [[ "$cmd" == restore ]]; then
if [[ -f "$archive" ]]; then
tar -xzf "$archive"
echo "CI-cache hersteld ($archive)."
else
echo "Geen CI-cache ($archive)."
fi
exit 0
fi
mkdir -p .ci-cache
parts=()
add_if_dir() {
local p="$1"
[[ -d "$p" ]] || return 0
parts+=("$(relpath "$p")")
}
# Registry and git checkouts, not registry/src (that is rebuilt from .crate files).
add_if_dir "$cargo_home/bin"
add_if_dir "$cargo_home/registry/index"
add_if_dir "$cargo_home/registry/cache"
add_if_dir "$cargo_home/git/db"
add_if_dir "$rustup_home"
if [[ "$kind" == windows ]]; then
add_if_dir "$xwin_cache"
fi
if [[ ${#parts[@]} -eq 0 ]]; then
echo "Niets te cachen."
exit 0
fi
# gzip -1: kleiner bestand voor de 10 GB-jobcache, weinig CPU.
tar -c --use-compress-program='gzip -1' -f "$archive" "${parts[@]}"
echo "CI-cache opgeslagen ($archive): ${parts[*]}"
ls -lh "$archive"
@@ -0,0 +1,70 @@#!/usr/bin/env bash# Pack or unpack a Cargo/rustup (and optional cargo-xwin) cache as one tarball.# BlueGit `cache.paths` copies only files, not directories, so a directory# such as cargo-home/ would otherwise be skipped (see bluegit runner saveCache).# Does not cache target/: too large for the runner's job-cache budget.set -euo pipefailusage() { echo "usage: $0 restore|save linux|windows" >&2 exit 2}cmd="${1:-}"kind="${2:-}"[[ "$cmd" == restore || "$cmd" == save ]] || usage[[ "$kind" == linux || "$kind" == windows ]] || usagearchive=".ci-cache/cargo-${kind}.tar.gz"# Locations in the job workspace (set by the CI job / ci-setup.sh).cargo_home="${CARGO_HOME:-$PWD/cargo-home}"rustup_home="${RUSTUP_HOME:-$PWD/rustup-home}"xwin_cache="${XWIN_CACHE_DIR:-$PWD/xwin-cache}"relpath() { local abs="$1" case "$abs" in "$PWD"/*) printf '%s\n' "${abs#"$PWD"/}" ;; /*) printf '%s\n' "$abs" ;; *) printf '%s\n' "$abs" ;; esac}if [[ "$cmd" == restore ]]; then if [[ -f "$archive" ]]; then tar -xzf "$archive" echo "CI-cache hersteld ($archive)." else echo "Geen CI-cache ($archive)." fi exit 0fimkdir -p .ci-cacheparts=()add_if_dir() { local p="$1" [[ -d "$p" ]] || return 0 parts+=("$(relpath "$p")")}# Registry and git checkouts, not registry/src (that is rebuilt from .crate files).add_if_dir "$cargo_home/bin"add_if_dir "$cargo_home/registry/index"add_if_dir "$cargo_home/registry/cache"add_if_dir "$cargo_home/git/db"add_if_dir "$rustup_home"if [[ "$kind" == windows ]]; then add_if_dir "$xwin_cache"fiif [[ ${#parts[@]} -eq 0 ]]; then echo "Niets te cachen." exit 0fi# gzip -1: kleiner bestand voor de 10 GB-jobcache, weinig CPU.tar -c --use-compress-program='gzip -1' -f "$archive" "${parts[@]}"echo "CI-cache opgeslagen ($archive): ${parts[*]}"ls -lh "$archive"@@ -1,14 +1,24 @@
#!/usr/bin/env bash
# KVT fork: tools for the BlueGit CI jobs in blue-ci-cd.yml, on an Ubuntu image.
# ci-setup.sh linux Linux build (as .github/actions/setup-linux): headers, clang 21, mold
# ci-setup.sh linux Linux build (as .github/actions/setup-linux): headers, clang 21, mold (clang-21 zonder lldb/lld/clangd)
# ci-setup.sh windows the above plus the cross-build bits: lld/llvm 21, wine, cargo-xwin
# Rust comes from rustup (stable) into $CARGO_HOME, which the jobs cache.
set -euo pipefail
mode="${1:-linux}"
export DEBIAN_FRONTEND=noninteractive
# Keep Cargo and rustup in the workspace so ci-cache.sh can pack them.
# BlueGit cache only copies files, not directories; the job stores a tarball.
if [[ -n "${CI:-}" ]]; then
export CARGO_HOME="${CARGO_HOME:-$PWD/cargo-home}"
export RUSTUP_HOME="${RUSTUP_HOME:-$PWD/rustup-home}"
export PATH="$CARGO_HOME/bin:$PATH"
if [[ "$mode" == windows ]]; then
export XWIN_CACHE_DIR="${XWIN_CACHE_DIR:-$PWD/xwin-cache}"
fi
fi
apt-get update -qq
apt-get install -y -qq --no-install-recommends \
ca-certificates curl git gnupg lsb-release wget software-properties-common \
ca-certificates curl git gnupg lsb-release wget \
build-essential binutils file python3 unzip xz-utils patch jq \
clang mold pkg-config libclang-dev \
libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \
@@ -17,8 +27,12 @@ apt-get install -y -qq --no-install-recommends \
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \
desktop-file-utils >/dev/null
# webrtc-sys needs clang 21 (check_clang_version in vendor/webrtc-sys/build.rs).
curl -fsSL https://apt.llvm.org/llvm.sh -o /tmp/llvm.sh
bash /tmp/llvm.sh 21 >/dev/null
# Alleen het apt.llvm.org-repo toevoegen en clang-21 installeren: llvm.sh zelf zet er
# ook lldb, lld en clangd bij (honderden MB extra uitpakken op de gedeelde runner).
codename="$(lsb_release -cs)"
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key -o /etc/apt/trusted.gpg.d/apt.llvm.org.asc
echo "deb https://apt.llvm.org/$codename/ llvm-toolchain-$codename-21 main" > /etc/apt/sources.list.d/llvm-21.list
apt-get update -qq
apt-get install -y -qq --no-install-recommends clang-21 >/dev/null
if [[ "$mode" == windows ]]; then
# cargo-xwin (ureq/native-tls) needs OpenSSL headers to build on the Linux host.
@@ -1,14 +1,24 @@#!/usr/bin/env bash#!/usr/bin/env bash# KVT fork: tools for the BlueGit CI jobs in blue-ci-cd.yml, on an Ubuntu image.# KVT fork: tools for the BlueGit CI jobs in blue-ci-cd.yml, on an Ubuntu image.# ci-setup.sh linux Linux build (as .github/actions/setup-linux): headers, clang 21, mold# ci-setup.sh linux Linux build (as .github/actions/setup-linux): headers, clang 21, mold (clang-21 zonder lldb/lld/clangd)# ci-setup.sh windows the above plus the cross-build bits: lld/llvm 21, wine, cargo-xwin# ci-setup.sh windows the above plus the cross-build bits: lld/llvm 21, wine, cargo-xwin# Rust comes from rustup (stable) into $CARGO_HOME, which the jobs cache.# Rust comes from rustup (stable) into $CARGO_HOME, which the jobs cache.set -euo pipefailset -euo pipefailmode="${1:-linux}"mode="${1:-linux}"export DEBIAN_FRONTEND=noninteractiveexport DEBIAN_FRONTEND=noninteractive# Keep Cargo and rustup in the workspace so ci-cache.sh can pack them.# BlueGit cache only copies files, not directories; the job stores a tarball.if [[ -n "${CI:-}" ]]; then export CARGO_HOME="${CARGO_HOME:-$PWD/cargo-home}" export RUSTUP_HOME="${RUSTUP_HOME:-$PWD/rustup-home}" export PATH="$CARGO_HOME/bin:$PATH" if [[ "$mode" == windows ]]; then export XWIN_CACHE_DIR="${XWIN_CACHE_DIR:-$PWD/xwin-cache}" fifiapt-get update -qqapt-get update -qqapt-get install -y -qq --no-install-recommends \apt-get install -y -qq --no-install-recommends \ ca-certificates curl git gnupg lsb-release wget software-properties-common \ ca-certificates curl git gnupg lsb-release wget \ build-essential binutils file python3 unzip xz-utils patch jq \ build-essential binutils file python3 unzip xz-utils patch jq \ clang mold pkg-config libclang-dev \ clang mold pkg-config libclang-dev \ libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \ libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \@@ -17,8 +27,12 @@ apt-get install -y -qq --no-install-recommends \ libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \ libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \ desktop-file-utils >/dev/null desktop-file-utils >/dev/null# webrtc-sys needs clang 21 (check_clang_version in vendor/webrtc-sys/build.rs).# webrtc-sys needs clang 21 (check_clang_version in vendor/webrtc-sys/build.rs).curl -fsSL https://apt.llvm.org/llvm.sh -o /tmp/llvm.sh# Alleen het apt.llvm.org-repo toevoegen en clang-21 installeren: llvm.sh zelf zet erbash /tmp/llvm.sh 21 >/dev/null# ook lldb, lld en clangd bij (honderden MB extra uitpakken op de gedeelde runner).codename="$(lsb_release -cs)"curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key -o /etc/apt/trusted.gpg.d/apt.llvm.org.ascecho "deb https://apt.llvm.org/$codename/ llvm-toolchain-$codename-21 main" > /etc/apt/sources.list.d/llvm-21.listapt-get update -qqapt-get install -y -qq --no-install-recommends clang-21 >/dev/nullapt-get install -y -qq --no-install-recommends clang-21 >/dev/nullif [[ "$mode" == windows ]]; thenif [[ "$mode" == windows ]]; then # cargo-xwin (ureq/native-tls) needs OpenSSL headers to build on the Linux host. # cargo-xwin (ureq/native-tls) needs OpenSSL headers to build on the Linux host.@@ -55,4 +55,19 @@ PY
rm dist/kvt/teams-linux-amd64
! "$HERE/release-assets.sh" sums v0.6.1-kvt.2 2>/dev/null || fail "missing linux binary accepted"
# CI cache helper: tarball round-trip (BlueGit caches files, not directories).
cachework="$(mktemp -d)"
mkdir -p "$cachework/cargo-home/registry/cache/demo" "$cachework/rustup-home/toolchains"
echo crate > "$cachework/cargo-home/registry/cache/demo/foo.crate"
echo rustc > "$cachework/rustup-home/toolchains/marker"
(cd "$cachework" && CARGO_HOME="$cachework/cargo-home" RUSTUP_HOME="$cachework/rustup-home" "$HERE/ci-cache.sh" save linux)
[[ -f "$cachework/.ci-cache/cargo-linux.tar.gz" ]] || fail "cache archive missing"
rm -rf "$cachework/cargo-home" "$cachework/rustup-home"
(cd "$cachework" && CARGO_HOME="$cachework/cargo-home" RUSTUP_HOME="$cachework/rustup-home" "$HERE/ci-cache.sh" restore linux)
[[ -f "$cachework/cargo-home/registry/cache/demo/foo.crate" ]] || fail "cache restore cargo"
[[ -f "$cachework/rustup-home/toolchains/marker" ]] || fail "cache restore rustup"
out="$(cd "$cachework" && "$HERE/ci-cache.sh" restore windows)"
grep -q 'Geen CI-cache' <<<"$out" || fail "missing windows cache message"
rm -rf "$cachework"
echo "packaging/kvt tests: ok"
@@ -55,4 +55,19 @@ PYrm dist/kvt/teams-linux-amd64rm dist/kvt/teams-linux-amd64! "$HERE/release-assets.sh" sums v0.6.1-kvt.2 2>/dev/null || fail "missing linux binary accepted"! "$HERE/release-assets.sh" sums v0.6.1-kvt.2 2>/dev/null || fail "missing linux binary accepted"# CI cache helper: tarball round-trip (BlueGit caches files, not directories).cachework="$(mktemp -d)"mkdir -p "$cachework/cargo-home/registry/cache/demo" "$cachework/rustup-home/toolchains"echo crate > "$cachework/cargo-home/registry/cache/demo/foo.crate"echo rustc > "$cachework/rustup-home/toolchains/marker"(cd "$cachework" && CARGO_HOME="$cachework/cargo-home" RUSTUP_HOME="$cachework/rustup-home" "$HERE/ci-cache.sh" save linux)[[ -f "$cachework/.ci-cache/cargo-linux.tar.gz" ]] || fail "cache archive missing"rm -rf "$cachework/cargo-home" "$cachework/rustup-home"(cd "$cachework" && CARGO_HOME="$cachework/cargo-home" RUSTUP_HOME="$cachework/rustup-home" "$HERE/ci-cache.sh" restore linux)[[ -f "$cachework/cargo-home/registry/cache/demo/foo.crate" ]] || fail "cache restore cargo"[[ -f "$cachework/rustup-home/toolchains/marker" ]] || fail "cache restore rustup"out="$(cd "$cachework" && "$HERE/ci-cache.sh" restore windows)"grep -q 'Geen CI-cache' <<<"$out" || fail "missing windows cache message"rm -rf "$cachework"echo "packaging/kvt tests: ok"echo "packaging/kvt tests: ok"@@ -47,6 +47,7 @@ pub struct TitleBar {
style: StyleRefinement,
children: SmallVec<[AnyElement; 1]>,
on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
system_window_controls: bool,
}
impl TitleBar {
@@ -56,6 +57,7 @@ impl TitleBar {
style: StyleRefinement::default(),
children: SmallVec::new(),
on_close_window: None,
system_window_controls: true,
}
}
@@ -105,6 +107,15 @@ impl TitleBar {
}
self
}
/// Whether this title bar draws the built-in minimize/maximize/close buttons.
///
/// Defaults to `true`. Set to `false` when the window draws its own buttons,
/// so the two sets are not stacked.
pub fn system_window_controls(mut self, show: bool) -> Self {
self.system_window_controls = show;
self
}
}
// We don't need implementation the click event for the control buttons.
@@ -346,7 +357,7 @@ impl RenderOnce for TitleBar {
cx.theme().background,
))
.refine_style(&self.style)
.when(is_linux, |this| {
.when(is_linux || cfg!(target_os = "windows"), |this| {
this.on_double_click(|_, window, _| window.zoom_window())
})
.when(is_macos, |this| {
@@ -402,8 +413,10 @@ impl RenderOnce for TitleBar {
})
.children(self.children),
)
.child(WindowControls {
on_close_window: self.on_close_window,
.when(self.system_window_controls, |this| {
this.child(WindowControls {
on_close_window: self.on_close_window,
})
}),
)
}
@@ -47,6 +47,7 @@ pub struct TitleBar { style: StyleRefinement, style: StyleRefinement, children: SmallVec<[AnyElement; 1]>, children: SmallVec<[AnyElement; 1]>, on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>, on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>, system_window_controls: bool,}}impl TitleBar {impl TitleBar {@@ -56,6 +57,7 @@ impl TitleBar { style: StyleRefinement::default(), style: StyleRefinement::default(), children: SmallVec::new(), children: SmallVec::new(), on_close_window: None, on_close_window: None, system_window_controls: true, } } } }@@ -105,6 +107,15 @@ impl TitleBar { } } self self } } /// Whether this title bar draws the built-in minimize/maximize/close buttons. /// /// Defaults to `true`. Set to `false` when the window draws its own buttons, /// so the two sets are not stacked. pub fn system_window_controls(mut self, show: bool) -> Self { self.system_window_controls = show; self }}}// We don't need implementation the click event for the control buttons.// We don't need implementation the click event for the control buttons.@@ -346,7 +357,7 @@ impl RenderOnce for TitleBar { cx.theme().background, cx.theme().background, )) )) .refine_style(&self.style) .refine_style(&self.style) .when(is_linux, |this| { .when(is_linux || cfg!(target_os = "windows"), |this| { this.on_double_click(|_, window, _| window.zoom_window()) this.on_double_click(|_, window, _| window.zoom_window()) }) }) .when(is_macos, |this| { .when(is_macos, |this| {@@ -402,8 +413,10 @@ impl RenderOnce for TitleBar { }) }) .children(self.children), .children(self.children), ) ) .child(WindowControls { .when(self.system_window_controls, |this| { on_close_window: self.on_close_window, this.child(WindowControls { on_close_window: self.on_close_window, }) }), }), ) ) } }