Merge branch 'kvt/integratie' into 'master'
@@ -59,6 +59,12 @@ debug = "line-tables-only"
59
59
[profile.dev.package."*"]
60
60
debug = false
61
61
62
# BlueGit-CI: minder geheugen bij compileren en linken (blue-ci-cd.yml).
63
[profile.ci]
64
inherits = "dev"
65
incremental = false
66
debug = 0
67
62
68
[profile.release]
63
69
incremental = true
64
70
codegen-units = 256
@@ -59,6 +59,12 @@ debug = "line-tables-only"59
[profile.dev.package."*"]59
[profile.dev.package."*"]60
debug = false60
debug = false61
61
62
# BlueGit-CI: minder geheugen bij compileren en linken (blue-ci-cd.yml).63
[profile.ci]64
inherits = "dev"65
incremental = false66
debug = 067
62
[profile.release]68
[profile.release]63
incremental = true69
incremental = true64
codegen-units = 25670
codegen-units = 256@@ -80,6 +80,39 @@ Merge-tip: `release_feed.rs` is het meest gevoelige upstream-bestand. Houd de ho
80
80
| Upstream aangeraakt | — |
81
81
| Commits / MR's | [!5](https://git.kvt.nl/ict/rusty-teams/-/merge-requests/5) `ed0382d` |
82
82
83
### Lichtere BlueGit-CI — branch `kvt/ci-lichter`
84
85
De Rust-test- en releasebuilds trokken de gedeelde git.kvt.nl-runner onderuit
86
(503). De jobs blijven hetzelfde, maar gebruiken minder piekgeheugen en niet
87
twee zware compiles tegelijk.
88
89
| | |
90
|---|---|
91
| 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. |
92
| Eigen bestanden | `blue-ci-cd.yml`, `packaging/kvt/ci-cache.sh`, `packaging/kvt/ci-setup.sh` (Cargo/rustup in de werkmap onder `CI`) |
93
| Upstream aangeraakt | `Cargo.toml` (alleen `[profile.ci]`) |
94
| Commits / MR's | branch `kvt/ci-lichter` (MR volgt als de runners conservatief staan) |
95
96
Daarbovenop (Tim, t2294u: «alleen wat technisch minimaal vereist is voor een release build»):
97
98
- **Branch-push en merge request:** alleen `kvt_test`, nu zonder apt-installs en zonder cargo
99
(`bash -n` op `packaging/kvt/*.sh` en `packaging/kvt/tests.sh`).
100
- **`aur_check` en `app_test`** staan op `when: manual` (`allow_failure`): ze starten niet
101
vanzelf en blokkeren de pipeline niet. De volledige tests (`cargo test -p app`, `-p app-state`,
102
`-p kvt-sleutels`, `packaging/kvt/tests.sh`) draai je lokaal, met `CARGO_BUILD_JOBS=2` en
103
`--profile ci`, of je speelt de job bewust.
104
- **Tag-pipeline:** alleen `linux_release` → `checksums` → `release` → `publish_aur`, zonder
105
testjobs; `linux_release` wacht niet meer op `kvt_test`/`aur_check`.
106
- **`windows_release`** is handmatig (`allow_failure`) en geen voorwaarde meer voor `checksums` en
107
`release`. Een release zonder Windows-exe biedt Windows-installaties die versie niet aan;
108
speel je `windows_release` later alsnog, draai dan `checksums` en `release` opnieuw.
109
- **`ci-setup.sh`:** installeert `clang-21` via het apt.llvm.org-repo zelf en niet via `llvm.sh`
110
(dat ook lldb, lld en clangd bijzet), en laat `software-properties-common` weg.
111
112
Merge-tip: conflict in `blue-ci-cd.yml` of `Cargo.toml` alleen de KVT-jobs en
113
`[profile.ci]` terugzetten; de release-, AUR- en checksum-scripts zelf zijn
114
ongewijzigd.
115
83
116
### Thema "Koninklijke van Twist" — MR !4, accenten en typografie in MR !6
84
117
85
118
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.
199
232
200
233
Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0024.
201
234
202
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het nieuw-ticketformulier
203
van Asclepius in de browser met `new_title` (eerste regel, max. 150 tekens) en `new_description`
204
(het bericht als Markdown-citaat, afzender, tijd `15 jan 2026 13:39` en de Teams-link). Geen token
205
of API: de gebruiker kiest zelf de categorie en slaat op in Asclepius.
235
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het formulier
236
«Nieuw ticket maken» in de app (zie «Asclepius-tegel»), vooraf ingevuld: titel = eerste regel (max.
237
150 tekens), beschrijving = het bericht als Markdown-citaat met afzender, tijd `15 jan 2026 13:39`
238
en de Teams-link. Vermeldingen in het bericht worden `@naam:domein` (adres via het Teams-profiel,
239
best effort), zodat Asclepius ze herkent en die collega's deelnemer worden.
206
240
- **Taak maken in Ponos** (berichtmenu, «Create Ponos task»): dialoog met groepkeuze (groepen waar
207
241
je taken mag maken, laatst gekozen groep onthouden als id in de lokale opslag), titel en
208
242
omschrijving vooraf ingevuld zoals hierboven. Maakt de taak via `ponos_api.php` met de app-token.
209
- **Mijn taken** («…» rechtsboven > «My tasks in Ponos»): open taken die aan jou zijn toegewezen,
210
met groep, status en deadline (`15 jan 2026`, rood als die voorbij is). Vinkje = afronden, klik =
211
taak openen in Ponos. Ponos staat een app-token alleen taakacties toe (geen API-sleutels of
212
groepsbeheer).
243
- **Ponos-tegel** (navigatierail, direct onder Agents): zie «Ponos-bord» hieronder. Vervangt het
244
oude paneel «Mijn taken» in het «…»-menu.
213
245
- **Daedalus-planning in de agenda** (Instellingen > Algemeen > KVT, standaard aan): je eigen
214
246
werkorders uit `/daedalus/api/planning.php` als read-only afspraken (bron ICS, agenda «Daedalus»):
215
247
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
221
253
| | |
222
254
|---|---|
223
255
| 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` |
224
| 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`) |
256
| 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`) |
225
257
226
258
Serverkant (geen deel van deze repo): `ict/ponos` (`ponos_app_token.php`: app-tokens met scope
227
259
`ponos` voor een vaste lijst taakacties) en `ict/daedalus` (`/daedalus/api/planning.php`, README
228
260
«Planning for native apps»).
229
261
262
### Ponos-bord (tegel in de navigatierail)
263
264
Op verzoek van Tim een eigen tegel «Ponos» in de navigatierail, direct onder Agents (altijd de laatste
265
tegel). Een klik opent het bord in het hoofdpaneel, net als Agenda en Gesprekken (de chatlijst gaat
266
dicht). Links alle groepen die `navigation` geeft, in de volgorde van Ponos, eerst «Mijn Taken» (de
267
persoonlijke groep: alles wat aan jou is toegewezen), met het aantal open taken. Rechts de kolommen
268
met de statusnamen van Ponos (todo / in_progress / done: «Nog te doen», «Onderhanden», «Afgerond»;
269
`kvt.board_status.*` alleen als terugval).
270
271
- Kaartje: titel, categorie, deadline (`15 jan 2026`, rood als die voorbij is), checklist (`1/4`),
272
toegewezen persoon (naam uit het adres, «Ik» voor jezelf); in «Mijn Taken» ook de groep.
273
- **Slepen** tussen en binnen kolommen: op een kaartje = erboven, op de kolom = onderaan. Lokaal
274
meteen, daarna `reorder_task` (kolom + plek) en opnieuw laden. In «Mijn Taken» verandert alleen de
275
status (`update_status`); die weergave heeft in Ponos geen eigen volgorde.
276
- **Nieuwe taak**: knop «Nieuwe taak» of «+» in een kolomkop (die status). Niet in «Mijn Taken» en
277
alleen in groepen met `can_create_tasks` en taaktoegang.
278
- **Bewerken** (klik op een kaartje): titel, omschrijving, status, deadline (`15 jan 2026`,
279
`15-01-2026`, `2026-01-15`; leeg = geen), toegewezen aan Niemand/Ik (een ander blijft staan) en
280
verplaatsen naar een andere groep. «Afronden», «Ponos openen». Alleen-lezen groepen: geen slepen
281
of opslaan.
282
- **Verwijderen** bestaat niet in Ponos (afgeronde taken gaan na een tijd vanzelf naar het archief);
283
het bord biedt daarom alleen «Afronden».
284
- De laatst gekozen groep staat als id in de lokale opslag (`kvt.ponos.board_group`).
285
- `--demo`: drie verzonnen groepen plus «Mijn Taken» met verzonnen taken (adressen op `example.com`);
286
wijzigingen blijven in het geheugen.
287
288
| | |
289
|---|---|
290
| 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*`) |
291
| 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). |
292
293
Serverkant: `ict/ponos` !8 — nieuwe actie `reorder_task` en het app-token mag nu ook
294
`update_task`, `move_task` en `reorder_task`.
295
296
Merge-tip: voegt upstream een `SidebarTab` toe, dan vraagt de compiler om de Ponos-arm in de
297
matches van `sidebar.rs`. Herschrijft upstream het hoofdpaneel in `shell.rs` (`islands`), zet dan de
298
`ponos`-arm weer als eerste. Komt er upstream een tegel bij, dan blijft Ponos de laatste
299
(`with_rail_tiles` hangt Ponos en Asclepius achteraan).
300
230
301
Merge-tip: herschrijft upstream `fill_rest` in `message_actions.rs` of het laadblok in `week.rs`, zet
231
302
dan de lus over `self.kvt` en het `kvt_calendar::source()`-blok terug; de rest staat in eigen bestanden.
232
303
@@ -239,6 +310,48 @@ terug. `browser/kvt.rs` gebruikt `cdp_call`, `CDP_TIMEOUT` en `OPEN_TAB_TIMEOUT`
239
310
hernoemt upstream die, pas dan alleen `kvt.rs` aan. De loopback-pagina en de PROBE-selector in
240
311
`kvt-sleutels/src/session.rs` volgen de markup van `app_connect.php` in `ict/login`.
241
312
313
### Asclepius-tegel (tickets in de navigatierail)
314
315
Op verzoek van Tim een tegel «Asclepius» direct onder Ponos (dus de laatste). De tegel laat zien
316
wat je op het web onder «Mijn tickets» ziet, met dezelfde zichtbaarheid: je eigen tickets, die waar
317
je deelnemer bent en die aan jou zijn toegewezen. Beheer (status, toewijzen, de ICT-lijst) blijft
318
in Asclepius (fase 2).
319
320
- **Lijst** links: standaard open tickets, filter «Open» / «Afgehandeld». Per ticket titel, nummer,
321
status en laatste wijziging (`15 jan 2026 13:39`).
322
- **Ongelezen** is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at` nieuwer is dan toen
323
je het opende, is vet met een stip; de tegel toont het aantal. De eerste keer telt alles als gelezen.
324
- **Gesprek** rechts: kop met nummer, status, categorie › subcategorie en aanmaakdatum; berichten
325
met afzender, «ICT» en tijd; bijlagen openen na downloaden met de token (tijdelijke map).
326
**Ghost-berichten** (alleen zichtbaar voor ICT) hebben de kleuren van het web (paars #5b21b6,
327
roze rand #f9a8d4), los van het thema.
328
- **@vermeldingen**: Asclepius schrijft `@jan:examplecom` voor `jan@example.com` (domein zonder punten); de tegel
329
toont `@Jan`, vet. Onder het antwoordveld staan knoppen «@naam» voor deelnemers en de behandelaar;
330
die zetten het token in de tekst, zodat Asclepius de vermelding herkent.
331
- **Antwoorden** via `add_ticket_message`. Heropenen (op het web een vinkje) blijft in Asclepius;
332
bij een afgehandeld ticket staat dat onder het antwoordveld.
333
- **Nieuw ticket maken** (knop in de kop, en vanuit het berichtmenu): de velden van het
334
webformulier: Titel, Categorie (zonder de ICT-categorieën Indiensttreding/Uitdiensttreding),
335
Subcategorie (alleen als de categorie die heeft, optioneel), Beschrijving, de twee vinkjes
336
«Mijn werkzaamheden worden belemmerd» / «Ik kan niet verder werken tot dit opgelost is» (het
337
tweede alleen met het eerste; prioriteit 0–2 zoals `getPriorityFromFlags`), Extra gebruikers
338
(optioneel, adressen gescheiden door komma's) en «Screenshots of documenten» (hooguit 10, elk
339
hooguit 10 MB, als base64 in de JSON). Na indienen opent het nieuwe ticket in de tegel.
340
- Elke minuut `ticket_updates` (`updated_since`); bij een wijziging laden lijst en gesprek opnieuw.
341
- **Ticketlinks** (`https://sleutels.kvt.nl/asclepius/index.php?open=…`, ook `admin.php`) in berichten
342
en kaartjes: de app haalt het ticket op met de token. Lukt dat (je hebt toegang), dan opent het in een
343
ticketvenster in de app (hetzelfde gesprek als in de tegel, met antwoordveld); zo niet (geen
344
toegang, niet gekoppeld of Asclepius onbereikbaar), dan gewoon in de browser.
345
- `--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`).
346
347
| | |
348
|---|---|
349
| 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) |
350
| 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) |
351
352
Serverkant: `ict/asclepius` — app-tokens (`sat_…`, `asclepius_app_token.php`), gefilterde lijst,
353
`ticket_updates` en bijlagen bij aanmaken.
354
242
355
### Nederlandse UI
243
356
244
357
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
256
369
ontbreken. Bij een conflict in `app.yml` de upstream-versie nemen en de `nl:`-regels opnieuw
257
370
invoegen. Termen: «chat», «vergadering», «kanaal», «oproep», «agenda»; datums als «15 jan 2026».
258
371
372
### Eigen vensterknoppen
373
374
Op verzoek van Tim (t2263u): minimaliseren, maximaliseren/herstellen en sluiten als kleine
375
knoppen helemaal rechts in de titelbalk (na «…» en de avatar), in dezelfde stijl als de
376
andere titelbalkknoppen: chevron omlaag, chevron omhoog (herstellen: het bestaande
377
herstel-icoon) en een kruisje. Daarmee kunnen de vensterranden van het systeem weg, zonder
378
die functies te verliezen.
379
380
- Linux (KWin Wayland en X11) en Windows: bij een nieuwe installatie staan de eigen knoppen
381
aan en vraagt het hoofdvenster client-side decorations. Verslepen gaat via de lege
382
titelbalk, dubbelklikken maximaliseert, de randen en hoeken wijzigen de grootte
383
(bestaande GPUI-`WindowBorder` in `Root`).
384
- Instellingen › Weergave › «Eigen vensterknoppen» (standaard aan) zet het uit en brengt de
385
systeemranden terug. Een wijziging geldt meteen.
386
- Sluiten volgt dezelfde route als de systeemknop, inclusief «sluiten naar de tray».
387
- macOS houdt de verkeerslichten van het systeem; de instelling en de eigen knoppen blijven
388
daar weg.
389
- De ingebouwde vensterknoppen van de upstream-`TitleBar` (Windows-11-stijl) worden
390
verborgen zolang de KVT-knoppen aan staan, zodat ze niet verdubbelen.
391
392
| | |
393
|---|---|
394
| Wat | Eigen vensterknoppen in de titelbalk, client-side decorations, instelling |
395
| 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.*`) |
396
| 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`). |
397
398
Merge-tip: de haak in `title_bar.rs` van gpui-component is de nieuwe methode en de
399
Windows-tak van `on_double_click`. Blijft die bij een upstream-update weg, zet hem terug
400
en houd `system_window_controls(false)` in onze titelbalk.
401
402
### Custom emoji in reactiepillen — upstream-kandidaat
403
404
Graph levert een custom reactie als `reactionType: "custom"` met `displayName` en `reactionContentUrl`.
405
De fork bewaarde alleen het type, waardoor de pil de afgekorte tekst "custo" toonde in plaats van het plaatje.
406
Dit is geen KVT-specifiek gedrag: dezelfde Graph-payload geldt voor elke tenant. Geschikt om naar upstream te sturen.
407
408
| | |
409
|---|---|
410
| Wat | Custom emoji-reacties herkennen (Graph-velden en chatsvc-sleutel `naam;objectid`) en als plaatje tonen; nooit de ruwe sleutel in de pil |
411
| Eigen bestanden | — |
412
| 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` |
413
414
415
### Organisatie-emoji in kiezer en berichten — upstream-kandidaat
416
417
De officiële webclient haalt de tenantlijst op via CSA
418
`GET /api/csa/{region}/api/v1/customemoji/metadata` met het bestaande CSA-token
419
(`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`). In een bericht
420
gaat een custom emoji als `<img itemtype="http://schema.skype.com/CustomEmoji" itemid="naam;objectId" …>`.
421
Een reactie gebruikt dezelfde sleutel `naam;objectId`. We cachen de lijst 30 minuten
422
in de store, met optionele delta via `x-ms-continuation`.
423
424
Aannames die nog live getest moeten worden: host (`teams.cloud.microsoft`, het CSA-host
425
van de andere calls hier), regio (`emea`), en of het CSA-token zonder extra scope volstaat.
426
De optionele Graph-beta-route `teamwork/messaging/customEmojis` is niet gebruikt.
427
428
| | |
429
|---|---|
430
| 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 |
431
| Eigen bestanden | — |
432
| 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` |
433
259
434
## Eigen modules in het kort
260
435
436
261
437
| Pad | Rol |
262
438
|---|---|
263
439
| `crates/app-base/src/theme/kvt.rs` | Palet, WCAG-tests, DINPro-detectie |
264
440
| `crates/app-base/src/kvt_brand.rs` | Titelbalk-woordmerk (licht/donker) |
265
441
| `crates/app-base/src/kvt_feed.rs` | Releasefeed van git.kvt.nl |
266
442
| `crates/kvt-update/` | Vertaling van BlueGit-releases naar het updater-formaat, pakketvlag |
267
| `packaging/kvt/` | CI-setup, Windows-cross-build, AUR, release-assets |
443
| `packaging/kvt/` | CI-setup, CI-cache-tarball, Windows-cross-build, AUR, release-assets |
268
444
| `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren |
269
445
| `crates/app/assets/brand/` | Officieel woordmerk |
270
| `crates/kvt-sleutels/` | sleutels.kvt.nl: BC-links, Mímir-kaarten, Ponos, Daedalus-planning, Asclepius-link, koppelen (PKCE, loopback, sessietabblad), keyring |
271
| `crates/app/src/kvt/`, `settings/kvt.rs`, `composer/kvt.rs` | BC-kaarten, detailvenster, picker, berichtmenu (Asclepius, Ponos), Mijn taken, Daedalus-agenda, instellingen |
446
| `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 |
447
| `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 |
272
448
| `crates/app-state/src/kvt_calendar.rs` | Haak voor de Daedalus-planning in de weekweergave |
273
449
| `crates/browser/src/browser/kvt.rs` | Los tabblad in de sessiebrowser voor het koppelen |
274
| `blue-ci-cd.yml` | Sync, test (ook `cargo test -p kvt-sleutels` in `app_test`), release, AUR (KVT-gedeelte) |
450
| `crates/app-base/src/kvt_window.rs`, `crates/app/src/kvt/window_controls.rs` | Eigen vensterknoppen en client-side decorations |
451
| `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 ho80
| Upstream aangeraakt | — |80
| Upstream aangeraakt | — |81
| Commits / MR's | [!5](https://git.kvt.nl/ict/rusty-teams/-/merge-requests/5) `ed0382d` |81
| Commits / MR's | [!5](https://git.kvt.nl/ict/rusty-teams/-/merge-requests/5) `ed0382d` |82
82
83
### Lichtere BlueGit-CI — branch `kvt/ci-lichter`84
85
De Rust-test- en releasebuilds trokken de gedeelde git.kvt.nl-runner onderuit86
(503). De jobs blijven hetzelfde, maar gebruiken minder piekgeheugen en niet87
twee zware compiles tegelijk.88
89
| | |90
|---|---|91
| 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. |92
| Eigen bestanden | `blue-ci-cd.yml`, `packaging/kvt/ci-cache.sh`, `packaging/kvt/ci-setup.sh` (Cargo/rustup in de werkmap onder `CI`) |93
| Upstream aangeraakt | `Cargo.toml` (alleen `[profile.ci]`) |94
| Commits / MR's | branch `kvt/ci-lichter` (MR volgt als de runners conservatief staan) |95
96
Daarbovenop (Tim, t2294u: «alleen wat technisch minimaal vereist is voor een release build»):97
98
- **Branch-push en merge request:** alleen `kvt_test`, nu zonder apt-installs en zonder cargo99
(`bash -n` op `packaging/kvt/*.sh` en `packaging/kvt/tests.sh`).100
- **`aur_check` en `app_test`** staan op `when: manual` (`allow_failure`): ze starten niet101
vanzelf en blokkeren de pipeline niet. De volledige tests (`cargo test -p app`, `-p app-state`,102
`-p kvt-sleutels`, `packaging/kvt/tests.sh`) draai je lokaal, met `CARGO_BUILD_JOBS=2` en103
`--profile ci`, of je speelt de job bewust.104
- **Tag-pipeline:** alleen `linux_release` → `checksums` → `release` → `publish_aur`, zonder105
testjobs; `linux_release` wacht niet meer op `kvt_test`/`aur_check`.106
- **`windows_release`** is handmatig (`allow_failure`) en geen voorwaarde meer voor `checksums` en107
`release`. Een release zonder Windows-exe biedt Windows-installaties die versie niet aan;108
speel je `windows_release` later alsnog, draai dan `checksums` en `release` opnieuw.109
- **`ci-setup.sh`:** installeert `clang-21` via het apt.llvm.org-repo zelf en niet via `llvm.sh`110
(dat ook lldb, lld en clangd bijzet), en laat `software-properties-common` weg.111
112
Merge-tip: conflict in `blue-ci-cd.yml` of `Cargo.toml` alleen de KVT-jobs en113
`[profile.ci]` terugzetten; de release-, AUR- en checksum-scripts zelf zijn114
ongewijzigd.115
83
### Thema "Koninklijke van Twist" — MR !4, accenten en typografie in MR !6116
### Thema "Koninklijke van Twist" — MR !4, accenten en typografie in MR !684
117
85
Een derde kleurenschema naast Rusty Teams en Teams, en het standaardthema voor nieuwe118
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.199
232
200
Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0024.233
Zelfde koppeling (app-token, scopes `asclepius ponos daedalus`), geen nieuwe inlog. Besluit: ADR 0024.201
234
202
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het nieuw-ticketformulier235
- **Ticket maken in Asclepius** (berichtmenu, «Create Asclepius ticket»): opent het formulier203
van Asclepius in de browser met `new_title` (eerste regel, max. 150 tekens) en `new_description`236
«Nieuw ticket maken» in de app (zie «Asclepius-tegel»), vooraf ingevuld: titel = eerste regel (max.204
(het bericht als Markdown-citaat, afzender, tijd `15 jan 2026 13:39` en de Teams-link). Geen token237
150 tekens), beschrijving = het bericht als Markdown-citaat met afzender, tijd `15 jan 2026 13:39`205
of API: de gebruiker kiest zelf de categorie en slaat op in Asclepius.238
en de Teams-link. Vermeldingen in het bericht worden `@naam:domein` (adres via het Teams-profiel,239
best effort), zodat Asclepius ze herkent en die collega's deelnemer worden.206
- **Taak maken in Ponos** (berichtmenu, «Create Ponos task»): dialoog met groepkeuze (groepen waar240
- **Taak maken in Ponos** (berichtmenu, «Create Ponos task»): dialoog met groepkeuze (groepen waar207
je taken mag maken, laatst gekozen groep onthouden als id in de lokale opslag), titel en241
je taken mag maken, laatst gekozen groep onthouden als id in de lokale opslag), titel en208
omschrijving vooraf ingevuld zoals hierboven. Maakt de taak via `ponos_api.php` met de app-token.242
omschrijving vooraf ingevuld zoals hierboven. Maakt de taak via `ponos_api.php` met de app-token.209
- **Mijn taken** («…» rechtsboven > «My tasks in Ponos»): open taken die aan jou zijn toegewezen,243
- **Ponos-tegel** (navigatierail, direct onder Agents): zie «Ponos-bord» hieronder. Vervangt het210
met groep, status en deadline (`15 jan 2026`, rood als die voorbij is). Vinkje = afronden, klik =244
oude paneel «Mijn taken» in het «…»-menu.211
taak openen in Ponos. Ponos staat een app-token alleen taakacties toe (geen API-sleutels of212
groepsbeheer).213
- **Daedalus-planning in de agenda** (Instellingen > Algemeen > KVT, standaard aan): je eigen245
- **Daedalus-planning in de agenda** (Instellingen > Algemeen > KVT, standaard aan): je eigen214
werkorders uit `/daedalus/api/planning.php` als read-only afspraken (bron ICS, agenda «Daedalus»):246
werkorders uit `/daedalus/api/planning.php` als read-only afspraken (bron ICS, agenda «Daedalus»):215
geen RSVP, geen verwijderen. Daedalus had geen ICS-abonnement; het endpoint geeft JSON (en ook247
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 inl221
| | |253
| | |222
|---|---|254
|---|---|223
| 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` |255
| 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` |224
| 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`) |256
| 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`) |225
257
226
Serverkant (geen deel van deze repo): `ict/ponos` (`ponos_app_token.php`: app-tokens met scope258
Serverkant (geen deel van deze repo): `ict/ponos` (`ponos_app_token.php`: app-tokens met scope227
`ponos` voor een vaste lijst taakacties) en `ict/daedalus` (`/daedalus/api/planning.php`, README259
`ponos` voor een vaste lijst taakacties) en `ict/daedalus` (`/daedalus/api/planning.php`, README228
«Planning for native apps»).260
«Planning for native apps»).229
261
262
### Ponos-bord (tegel in de navigatierail)263
264
Op verzoek van Tim een eigen tegel «Ponos» in de navigatierail, direct onder Agents (altijd de laatste265
tegel). Een klik opent het bord in het hoofdpaneel, net als Agenda en Gesprekken (de chatlijst gaat266
dicht). Links alle groepen die `navigation` geeft, in de volgorde van Ponos, eerst «Mijn Taken» (de267
persoonlijke groep: alles wat aan jou is toegewezen), met het aantal open taken. Rechts de kolommen268
met de statusnamen van Ponos (todo / in_progress / done: «Nog te doen», «Onderhanden», «Afgerond»;269
`kvt.board_status.*` alleen als terugval).270
271
- Kaartje: titel, categorie, deadline (`15 jan 2026`, rood als die voorbij is), checklist (`1/4`),272
toegewezen persoon (naam uit het adres, «Ik» voor jezelf); in «Mijn Taken» ook de groep.273
- **Slepen** tussen en binnen kolommen: op een kaartje = erboven, op de kolom = onderaan. Lokaal274
meteen, daarna `reorder_task` (kolom + plek) en opnieuw laden. In «Mijn Taken» verandert alleen de275
status (`update_status`); die weergave heeft in Ponos geen eigen volgorde.276
- **Nieuwe taak**: knop «Nieuwe taak» of «+» in een kolomkop (die status). Niet in «Mijn Taken» en277
alleen in groepen met `can_create_tasks` en taaktoegang.278
- **Bewerken** (klik op een kaartje): titel, omschrijving, status, deadline (`15 jan 2026`,279
`15-01-2026`, `2026-01-15`; leeg = geen), toegewezen aan Niemand/Ik (een ander blijft staan) en280
verplaatsen naar een andere groep. «Afronden», «Ponos openen». Alleen-lezen groepen: geen slepen281
of opslaan.282
- **Verwijderen** bestaat niet in Ponos (afgeronde taken gaan na een tijd vanzelf naar het archief);283
het bord biedt daarom alleen «Afronden».284
- De laatst gekozen groep staat als id in de lokale opslag (`kvt.ponos.board_group`).285
- `--demo`: drie verzonnen groepen plus «Mijn Taken» met verzonnen taken (adressen op `example.com`);286
wijzigingen blijven in het geheugen.287
288
| | |289
|---|---|290
| 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*`) |291
| 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). |292
293
Serverkant: `ict/ponos` !8 — nieuwe actie `reorder_task` en het app-token mag nu ook294
`update_task`, `move_task` en `reorder_task`.295
296
Merge-tip: voegt upstream een `SidebarTab` toe, dan vraagt de compiler om de Ponos-arm in de297
matches van `sidebar.rs`. Herschrijft upstream het hoofdpaneel in `shell.rs` (`islands`), zet dan de298
`ponos`-arm weer als eerste. Komt er upstream een tegel bij, dan blijft Ponos de laatste299
(`with_rail_tiles` hangt Ponos en Asclepius achteraan).300
230
Merge-tip: herschrijft upstream `fill_rest` in `message_actions.rs` of het laadblok in `week.rs`, zet301
Merge-tip: herschrijft upstream `fill_rest` in `message_actions.rs` of het laadblok in `week.rs`, zet231
dan de lus over `self.kvt` en het `kvt_calendar::source()`-blok terug; de rest staat in eigen bestanden.302
dan de lus over `self.kvt` en het `kvt_calendar::source()`-blok terug; de rest staat in eigen bestanden.232
303
@@ -239,6 +310,48 @@ terug. `browser/kvt.rs` gebruikt `cdp_call`, `CDP_TIMEOUT` en `OPEN_TAB_TIMEOUT`239
hernoemt upstream die, pas dan alleen `kvt.rs` aan. De loopback-pagina en de PROBE-selector in310
hernoemt upstream die, pas dan alleen `kvt.rs` aan. De loopback-pagina en de PROBE-selector in240
`kvt-sleutels/src/session.rs` volgen de markup van `app_connect.php` in `ict/login`.311
`kvt-sleutels/src/session.rs` volgen de markup van `app_connect.php` in `ict/login`.241
312
313
### Asclepius-tegel (tickets in de navigatierail)314
315
Op verzoek van Tim een tegel «Asclepius» direct onder Ponos (dus de laatste). De tegel laat zien316
wat je op het web onder «Mijn tickets» ziet, met dezelfde zichtbaarheid: je eigen tickets, die waar317
je deelnemer bent en die aan jou zijn toegewezen. Beheer (status, toewijzen, de ICT-lijst) blijft318
in Asclepius (fase 2).319
320
- **Lijst** links: standaard open tickets, filter «Open» / «Afgehandeld». Per ticket titel, nummer,321
status en laatste wijziging (`15 jan 2026 13:39`).322
- **Ongelezen** is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at` nieuwer is dan toen323
je het opende, is vet met een stip; de tegel toont het aantal. De eerste keer telt alles als gelezen.324
- **Gesprek** rechts: kop met nummer, status, categorie › subcategorie en aanmaakdatum; berichten325
met afzender, «ICT» en tijd; bijlagen openen na downloaden met de token (tijdelijke map).326
**Ghost-berichten** (alleen zichtbaar voor ICT) hebben de kleuren van het web (paars #5b21b6,327
roze rand #f9a8d4), los van het thema.328
- **@vermeldingen**: Asclepius schrijft `@jan:examplecom` voor `jan@example.com` (domein zonder punten); de tegel329
toont `@Jan`, vet. Onder het antwoordveld staan knoppen «@naam» voor deelnemers en de behandelaar;330
die zetten het token in de tekst, zodat Asclepius de vermelding herkent.331
- **Antwoorden** via `add_ticket_message`. Heropenen (op het web een vinkje) blijft in Asclepius;332
bij een afgehandeld ticket staat dat onder het antwoordveld.333
- **Nieuw ticket maken** (knop in de kop, en vanuit het berichtmenu): de velden van het334
webformulier: Titel, Categorie (zonder de ICT-categorieën Indiensttreding/Uitdiensttreding),335
Subcategorie (alleen als de categorie die heeft, optioneel), Beschrijving, de twee vinkjes336
«Mijn werkzaamheden worden belemmerd» / «Ik kan niet verder werken tot dit opgelost is» (het337
tweede alleen met het eerste; prioriteit 0–2 zoals `getPriorityFromFlags`), Extra gebruikers338
(optioneel, adressen gescheiden door komma's) en «Screenshots of documenten» (hooguit 10, elk339
hooguit 10 MB, als base64 in de JSON). Na indienen opent het nieuwe ticket in de tegel.340
- Elke minuut `ticket_updates` (`updated_since`); bij een wijziging laden lijst en gesprek opnieuw.341
- **Ticketlinks** (`https://sleutels.kvt.nl/asclepius/index.php?open=…`, ook `admin.php`) in berichten342
en kaartjes: de app haalt het ticket op met de token. Lukt dat (je hebt toegang), dan opent het in een343
ticketvenster in de app (hetzelfde gesprek als in de tegel, met antwoordveld); zo niet (geen344
toegang, niet gekoppeld of Asclepius onbereikbaar), dan gewoon in de browser.345
- `--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`).346
347
| | |348
|---|---|349
| 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) |350
| 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) |351
352
Serverkant: `ict/asclepius` — app-tokens (`sat_…`, `asclepius_app_token.php`), gefilterde lijst,353
`ticket_updates` en bijlagen bij aanmaken.354
242
### Nederlandse UI355
### Nederlandse UI243
356
244
De KVT-build heeft naast Engels en Duits ook Nederlands, en Nederlands is de standaard (besluit Tim,357
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_ger256
ontbreken. Bij een conflict in `app.yml` de upstream-versie nemen en de `nl:`-regels opnieuw369
ontbreken. Bij een conflict in `app.yml` de upstream-versie nemen en de `nl:`-regels opnieuw257
invoegen. Termen: «chat», «vergadering», «kanaal», «oproep», «agenda»; datums als «15 jan 2026».370
invoegen. Termen: «chat», «vergadering», «kanaal», «oproep», «agenda»; datums als «15 jan 2026».258
371
372
### Eigen vensterknoppen373
374
Op verzoek van Tim (t2263u): minimaliseren, maximaliseren/herstellen en sluiten als kleine375
knoppen helemaal rechts in de titelbalk (na «…» en de avatar), in dezelfde stijl als de376
andere titelbalkknoppen: chevron omlaag, chevron omhoog (herstellen: het bestaande377
herstel-icoon) en een kruisje. Daarmee kunnen de vensterranden van het systeem weg, zonder378
die functies te verliezen.379
380
- Linux (KWin Wayland en X11) en Windows: bij een nieuwe installatie staan de eigen knoppen381
aan en vraagt het hoofdvenster client-side decorations. Verslepen gaat via de lege382
titelbalk, dubbelklikken maximaliseert, de randen en hoeken wijzigen de grootte383
(bestaande GPUI-`WindowBorder` in `Root`).384
- Instellingen › Weergave › «Eigen vensterknoppen» (standaard aan) zet het uit en brengt de385
systeemranden terug. Een wijziging geldt meteen.386
- Sluiten volgt dezelfde route als de systeemknop, inclusief «sluiten naar de tray».387
- macOS houdt de verkeerslichten van het systeem; de instelling en de eigen knoppen blijven388
daar weg.389
- De ingebouwde vensterknoppen van de upstream-`TitleBar` (Windows-11-stijl) worden390
verborgen zolang de KVT-knoppen aan staan, zodat ze niet verdubbelen.391
392
| | |393
|---|---|394
| Wat | Eigen vensterknoppen in de titelbalk, client-side decorations, instelling |395
| 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.*`) |396
| 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`). |397
398
Merge-tip: de haak in `title_bar.rs` van gpui-component is de nieuwe methode en de399
Windows-tak van `on_double_click`. Blijft die bij een upstream-update weg, zet hem terug400
en houd `system_window_controls(false)` in onze titelbalk.401
402
### Custom emoji in reactiepillen — upstream-kandidaat403
404
Graph levert een custom reactie als `reactionType: "custom"` met `displayName` en `reactionContentUrl`.405
De fork bewaarde alleen het type, waardoor de pil de afgekorte tekst "custo" toonde in plaats van het plaatje.406
Dit is geen KVT-specifiek gedrag: dezelfde Graph-payload geldt voor elke tenant. Geschikt om naar upstream te sturen.407
408
| | |409
|---|---|410
| Wat | Custom emoji-reacties herkennen (Graph-velden en chatsvc-sleutel `naam;objectid`) en als plaatje tonen; nooit de ruwe sleutel in de pil |411
| Eigen bestanden | — |412
| 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` |413
414
415
### Organisatie-emoji in kiezer en berichten — upstream-kandidaat416
417
De officiële webclient haalt de tenantlijst op via CSA418
`GET /api/csa/{region}/api/v1/customemoji/metadata` met het bestaande CSA-token419
(`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`). In een bericht420
gaat een custom emoji als `<img itemtype="http://schema.skype.com/CustomEmoji" itemid="naam;objectId" …>`.421
Een reactie gebruikt dezelfde sleutel `naam;objectId`. We cachen de lijst 30 minuten422
in de store, met optionele delta via `x-ms-continuation`.423
424
Aannames die nog live getest moeten worden: host (`teams.cloud.microsoft`, het CSA-host425
van de andere calls hier), regio (`emea`), en of het CSA-token zonder extra scope volstaat.426
De optionele Graph-beta-route `teamwork/messaging/customEmojis` is niet gebruikt.427
428
| | |429
|---|---|430
| 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 |431
| Eigen bestanden | — |432
| 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` |433
259
## Eigen modules in het kort434
## Eigen modules in het kort260
435
436
261
| Pad | Rol |437
| Pad | Rol |262
|---|---|438
|---|---|263
| `crates/app-base/src/theme/kvt.rs` | Palet, WCAG-tests, DINPro-detectie |439
| `crates/app-base/src/theme/kvt.rs` | Palet, WCAG-tests, DINPro-detectie |264
| `crates/app-base/src/kvt_brand.rs` | Titelbalk-woordmerk (licht/donker) |440
| `crates/app-base/src/kvt_brand.rs` | Titelbalk-woordmerk (licht/donker) |265
| `crates/app-base/src/kvt_feed.rs` | Releasefeed van git.kvt.nl |441
| `crates/app-base/src/kvt_feed.rs` | Releasefeed van git.kvt.nl |266
| `crates/kvt-update/` | Vertaling van BlueGit-releases naar het updater-formaat, pakketvlag |442
| `crates/kvt-update/` | Vertaling van BlueGit-releases naar het updater-formaat, pakketvlag |267
| `packaging/kvt/` | CI-setup, Windows-cross-build, AUR, release-assets |443
| `packaging/kvt/` | CI-setup, CI-cache-tarball, Windows-cross-build, AUR, release-assets |268
| `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren |444
| `crates/app/assets/icon/kvt-teams.*`, `kvt-app.rc` | App-icoon in KVT-kleuren |269
| `crates/app/assets/brand/` | Officieel woordmerk |445
| `crates/app/assets/brand/` | Officieel woordmerk |270
| `crates/kvt-sleutels/` | sleutels.kvt.nl: BC-links, Mímir-kaarten, Ponos, Daedalus-planning, Asclepius-link, koppelen (PKCE, loopback, sessietabblad), keyring |446
| `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 |271
| `crates/app/src/kvt/`, `settings/kvt.rs`, `composer/kvt.rs` | BC-kaarten, detailvenster, picker, berichtmenu (Asclepius, Ponos), Mijn taken, Daedalus-agenda, instellingen |447
| `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 |272
| `crates/app-state/src/kvt_calendar.rs` | Haak voor de Daedalus-planning in de weekweergave |448
| `crates/app-state/src/kvt_calendar.rs` | Haak voor de Daedalus-planning in de weekweergave |273
| `crates/browser/src/browser/kvt.rs` | Los tabblad in de sessiebrowser voor het koppelen |449
| `crates/browser/src/browser/kvt.rs` | Los tabblad in de sessiebrowser voor het koppelen |274
| `blue-ci-cd.yml` | Sync, test (ook `cargo test -p kvt-sleutels` in `app_test`), release, AUR (KVT-gedeelte) |450
| `crates/app-base/src/kvt_window.rs`, `crates/app/src/kvt/window_controls.rs` | Eigen vensterknoppen en client-side decorations |451
| `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 @@
7
7
# (knop "Run pipeline" op master, of
8
8
# POST /api/v1/projects/ict/rusty-teams/pipelines {"ref": "master"}),
9
9
# nooit bij een push, tag of merge request.
10
# 2. Controle bij een merge request of push: kvt_test (de KVT-crate en
11
# -scripts, snel), aur_check (PKGBUILD en .SRCINFO in Arch) en app_test
12
# (bouwt app-base en app, draait de updatertests en de kvt-sleutels-tests;
13
# alleen als Rust-code of Cargo-bestanden veranderen).
14
# 3. Release bij een tag v* (schema v<versie>-kvt.<n>, bijvoorbeeld v0.6.1-kvt.1):
10
# 2. Controle bij een merge request of branch-push: alleen kvt_test (shell-
11
# syntaxis en packaging/kvt/tests.sh, zonder compileren of installs).
12
# De zware jobs aur_check en app_test (één keer compileren met
13
# `cargo test --no-run`, daarna kvt-update, updatertests, kvt-sleutels en
14
# `cargo check -p app`) staan op `when: manual` en starten niet vanzelf: ze
15
# hebben de gedeelde BlueGit-runner herhaaldelijk onderuit gehaald. Draai de
16
# volledige tests lokaal (cargo test -p app / -p app-state / -p kvt-sleutels)
17
# of start de jobs bewust met "play".
18
# Rust-jobs gebruiken CARGO_BUILD_JOBS=2, RUST_TEST_THREADS=2,
19
# CARGO_INCREMENTAL=0 en profile.ci (debug=0). Tussen runs bewaren ze
20
# een Cargo/rustup-tarball: BlueGit cache't geen mappen, en target/
21
# is te groot voor de jobcache.
22
# 3. Release bij een tag v* (schema v<versie>-kvt.<n>, bijvoorbeeld v0.6.1-kvt.1).
23
# Een tag-pipeline bevat alleen wat voor de release nodig is, zonder tests:
15
24
# linux_release Linux-binary + FHS-tarball (packaging/linux/package.sh)
16
# windows_release teams.exe, cross-build met cargo-xwin en fxc onder wine
17
# (allow_failure: zonder exe gaat de release door)
25
# windows_release handmatig (when: manual, allow_failure): teams.exe,
26
# cross-build met cargo-xwin en fxc onder wine. Zwaar, dus
27
# niet automatisch; de release gaat zonder exe door
18
28
# checksums SHA256SUMS van alle assets
19
29
# release maakt de release op git.kvt.nl met de assets
20
30
# publish_aur AUR-pakket kvt-rusty-teams-bin (allow_failure; slaat
@@ -98,35 +108,52 @@ sync-upstream:
98
108
# KVT: controle, release, AUR. Alles hieronder staat los van sync-upstream.
99
109
# ---------------------------------------------------------------------------
100
110
111
# Lichte controle: bij een merge request en een branch-push, niet in een tag-pipeline.
101
112
.kvt_check:
102
113
rules:
103
114
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
104
115
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null
105
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/
116
117
# Zware controle: alleen op verzoek (play), nooit automatisch.
118
.kvt_manual_check:
119
rules:
120
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
121
when: manual
122
allow_failure: true
123
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null
124
when: manual
125
allow_failure: true
106
126
107
127
.kvt_tag:
108
128
rules:
109
129
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/
110
130
111
# De KVT-crate (BlueGit-releasefeed, versies, assetnamen, pakketbeheer-vlag) en
112
# de scripts in packaging/kvt. Klein en snel.
131
# Minder piekgeheugen op de gedeelde BlueGit-runner.
132
.kvt_rust:
133
variables:
134
CARGO_INCREMENTAL: "0"
135
CARGO_BUILD_JOBS: "2"
136
RUST_TEST_THREADS: "2"
137
138
# De scripts in packaging/kvt (shell-syntaxis en tests.sh). Geen apt-installs en
139
# geen cargo: de kvt-update-tests draaien in app_test (handmatig) en lokaal.
113
140
kvt_test:
114
141
stage: test
115
142
image: rust:1-bookworm
116
143
extends: .kvt_check
117
144
needs: []
118
timeout: 30m
145
timeout: 10m
119
146
script:
120
- apt-get update -qq && apt-get install -y -qq --no-install-recommends clang mold >/dev/null
121
- cargo test -p kvt-update --locked
122
147
- for f in packaging/kvt/*.sh; do bash -n "$f"; done
123
148
- packaging/kvt/tests.sh
124
149
125
150
# PKGBUILD renderen en .SRCINFO maken op Arch, zoals publish_aur dat doet.
151
# Handmatig: de Arch-image is zwaar, en publish_aur doet dezelfde render bij een release.
126
152
aur_check:
127
153
stage: test
128
154
image: archlinux/archlinux:base-devel
129
extends: .kvt_check
155
extends: .kvt_manual_check
156
allow_failure: true
130
157
needs: []
131
158
timeout: 20m
132
159
script:
@@ -143,29 +170,36 @@ aur_check:
143
170
grep -q 'source = rusty-teams-0.0.1-kvt.1-linux-x86_64.tar.gz::https://git.kvt.nl/' "$out/.SRCINFO"
144
171
grep -qP '^\tpkgver = 0\.0\.1\.kvt\.1$' "$out/.SRCINFO"
145
172
146
# Bouwt app-base en app en draait de updatertests (release_feed, kvt_feed) en
147
# de tests van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen).
148
# Alleen als Rust-code of Cargo-bestanden veranderen; zwaar (volledige build).
173
# Bouwt één keer (cargo test --no-run) en draait daarna dezelfde tests als
174
# voorheen: kvt-update, de updatertests (release_feed, kvt_feed) en de tests
175
# van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen), plus
176
# cargo check -p app. Handmatig (play): zwaar, start niet vanzelf.
149
177
app_test:
150
178
stage: test
151
179
image: ubuntu:22.04
180
extends: [.kvt_manual_check, .kvt_rust]
181
allow_failure: true
152
182
needs: []
153
183
timeout: 120m
154
rules:
155
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
156
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]
157
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null
158
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]
159
184
variables:
160
185
CC: clang-21
161
186
CXX: clang++-21
162
187
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21
188
cache:
189
key: rusty-teams-cargo-linux
190
paths: [.ci-cache/cargo-linux.tar.gz]
163
191
script:
192
- packaging/kvt/ci-cache.sh restore linux
164
193
- packaging/kvt/ci-setup.sh linux
165
- . "$HOME/.cargo/env"
166
- cargo test --locked -p app-base --lib -- release_feed kvt_feed updater
167
- cargo test --locked -p kvt-sleutels
168
- cargo check --locked -p app
194
- . "${CARGO_HOME:-$HOME/.cargo}/env"
195
- cargo test --locked --profile ci -j2 --no-run -p kvt-update
196
- cargo test --locked --profile ci -j2 --no-run -p kvt-sleutels
197
- cargo test --locked --profile ci -j2 --no-run -p app-base --lib
198
- cargo check --locked --profile ci -j2 -p app
199
- cargo test --locked --profile ci -j2 -p kvt-update
200
- cargo test --locked --profile ci -j2 -p kvt-sleutels
201
- cargo test --locked --profile ci -j2 -p app-base --lib -- release_feed kvt_feed updater
202
- packaging/kvt/ci-cache.sh save linux
169
203
170
204
# Linux: release-build met de tag als versie (TEAMS_RELEASE_TAG via build.rs),
171
205
# daarna de FHS-tarball van packaging/linux/package.sh. Vaste artifactnamen;
@@ -173,16 +207,20 @@ app_test:
173
207
linux_release:
174
208
stage: build
175
209
image: ubuntu:22.04
176
extends: .kvt_tag
177
needs: [kvt_test, aur_check]
210
extends: [.kvt_tag, .kvt_rust]
211
needs: []
178
212
timeout: 150m
179
213
variables:
180
214
CC: clang-21
181
215
CXX: clang++-21
182
216
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21
217
cache:
218
key: rusty-teams-cargo-linux
219
paths: [.ci-cache/cargo-linux.tar.gz]
183
220
script:
221
- packaging/kvt/ci-cache.sh restore linux
184
222
- packaging/kvt/ci-setup.sh linux
185
- . "$HOME/.cargo/env"
223
- . "${CARGO_HOME:-$HOME/.cargo}/env"
186
224
- export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag RUSTY_TEAMS_VERSION="$CI_COMMIT_TAG"
187
225
- export RUSTY_TEAMS_MAINTAINER="KVT ICT <hephaestus@noreply.kvt.nl>"
188
226
- cargo build -p app --release --locked
@@ -193,6 +231,7 @@ linux_release:
193
231
- strip dist/kvt/teams-linux-amd64
194
232
- grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-linux-amd64
195
233
- ls -la dist/kvt
234
- packaging/kvt/ci-cache.sh save linux
196
235
artifacts:
197
236
paths:
198
237
- dist/kvt/teams-linux-amd64
@@ -200,23 +239,33 @@ linux_release:
200
239
expire_in: 7d
201
240
202
241
# Windows x86_64: cross-build vanuit Linux (packaging/kvt/build-windows.sh).
203
# allow_failure: mislukt hij, dan krijgt de release geen exe en biedt een
204
# Windows-installatie die versie niet aan; Linux en AUR gaan door.
242
# Handmatig (play) en allow_failure: de release wacht er niet op en krijgt dan
243
# geen exe, dus een Windows-installatie krijgt die versie niet aangeboden; Linux
244
# en AUR gaan door. Wil je de exe er alsnog bij: speel windows_release, daarna
245
# checksums en release opnieuw.
205
246
windows_release:
206
247
stage: build
207
248
image: ubuntu:24.04
208
extends: .kvt_tag
209
needs: [kvt_test]
249
extends: .kvt_rust
250
needs: [linux_release]
210
251
allow_failure: true
252
rules:
253
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/
254
when: manual
255
allow_failure: true
211
256
timeout: 180m
212
257
variables:
213
258
CC: clang-21
214
259
CXX: clang++-21
215
260
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21
216
261
XWIN_ACCEPT_LICENSE: "1"
262
cache:
263
key: rusty-teams-cargo-windows
264
paths: [.ci-cache/cargo-windows.tar.gz]
217
265
script:
266
- packaging/kvt/ci-cache.sh restore windows
218
267
- packaging/kvt/ci-setup.sh windows
219
- . "$HOME/.cargo/env"
268
- . "${CARGO_HOME:-$HOME/.cargo}/env"
220
269
- export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag
221
270
- packaging/kvt/build-windows.sh
222
271
- mkdir -p dist/kvt
@@ -224,6 +273,7 @@ windows_release:
224
273
- head -c 2 dist/kvt/teams-windows-amd64.exe | grep -q MZ
225
274
- grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-windows-amd64.exe
226
275
- ls -la dist/kvt
276
- packaging/kvt/ci-cache.sh save windows
227
277
artifacts:
228
278
paths:
229
279
- dist/kvt/teams-windows-amd64.exe
@@ -233,7 +283,7 @@ checksums:
233
283
stage: package
234
284
image: bluegit/base
235
285
extends: .kvt_tag
236
needs: [linux_release, windows_release]
286
needs: [linux_release]
237
287
script:
238
288
- packaging/kvt/release-assets.sh sums "$CI_COMMIT_TAG"
239
289
artifacts:
@@ -247,7 +297,7 @@ release:
247
297
stage: release
248
298
image: bluegit/base
249
299
extends: .kvt_tag
250
needs: [checksums, linux_release, windows_release]
300
needs: [checksums, linux_release]
251
301
script:
252
302
- packaging/kvt/release-assets.sh json "$CI_COMMIT_TAG" "$CI_COMMIT_SHA" > release.json
253
303
- cat release.json
@@ -7,14 +7,24 @@7
# (knop "Run pipeline" op master, of7
# (knop "Run pipeline" op master, of8
# POST /api/v1/projects/ict/rusty-teams/pipelines {"ref": "master"}),8
# POST /api/v1/projects/ict/rusty-teams/pipelines {"ref": "master"}),9
# nooit bij een push, tag of merge request.9
# nooit bij een push, tag of merge request.10
# 2. Controle bij een merge request of push: kvt_test (de KVT-crate en10
# 2. Controle bij een merge request of branch-push: alleen kvt_test (shell-11
# -scripts, snel), aur_check (PKGBUILD en .SRCINFO in Arch) en app_test11
# syntaxis en packaging/kvt/tests.sh, zonder compileren of installs).12
# (bouwt app-base en app, draait de updatertests en de kvt-sleutels-tests;12
# De zware jobs aur_check en app_test (één keer compileren met13
# alleen als Rust-code of Cargo-bestanden veranderen).13
# `cargo test --no-run`, daarna kvt-update, updatertests, kvt-sleutels en14
# 3. Release bij een tag v* (schema v<versie>-kvt.<n>, bijvoorbeeld v0.6.1-kvt.1):14
# `cargo check -p app`) staan op `when: manual` en starten niet vanzelf: ze15
# hebben de gedeelde BlueGit-runner herhaaldelijk onderuit gehaald. Draai de16
# volledige tests lokaal (cargo test -p app / -p app-state / -p kvt-sleutels)17
# of start de jobs bewust met "play".18
# Rust-jobs gebruiken CARGO_BUILD_JOBS=2, RUST_TEST_THREADS=2,19
# CARGO_INCREMENTAL=0 en profile.ci (debug=0). Tussen runs bewaren ze20
# een Cargo/rustup-tarball: BlueGit cache't geen mappen, en target/21
# is te groot voor de jobcache.22
# 3. Release bij een tag v* (schema v<versie>-kvt.<n>, bijvoorbeeld v0.6.1-kvt.1).23
# Een tag-pipeline bevat alleen wat voor de release nodig is, zonder tests:15
# linux_release Linux-binary + FHS-tarball (packaging/linux/package.sh)24
# linux_release Linux-binary + FHS-tarball (packaging/linux/package.sh)16
# windows_release teams.exe, cross-build met cargo-xwin en fxc onder wine25
# windows_release handmatig (when: manual, allow_failure): teams.exe,17
# (allow_failure: zonder exe gaat de release door)26
# cross-build met cargo-xwin en fxc onder wine. Zwaar, dus27
# niet automatisch; de release gaat zonder exe door18
# checksums SHA256SUMS van alle assets28
# checksums SHA256SUMS van alle assets19
# release maakt de release op git.kvt.nl met de assets29
# release maakt de release op git.kvt.nl met de assets20
# publish_aur AUR-pakket kvt-rusty-teams-bin (allow_failure; slaat30
# publish_aur AUR-pakket kvt-rusty-teams-bin (allow_failure; slaat@@ -98,35 +108,52 @@ sync-upstream:98
# KVT: controle, release, AUR. Alles hieronder staat los van sync-upstream.108
# KVT: controle, release, AUR. Alles hieronder staat los van sync-upstream.99
# ---------------------------------------------------------------------------109
# ---------------------------------------------------------------------------100
110
111
# Lichte controle: bij een merge request en een branch-push, niet in een tag-pipeline.101
.kvt_check:112
.kvt_check:102
rules:113
rules:103
- if: $CI_PIPELINE_SOURCE == "merge_request_event"114
- if: $CI_PIPELINE_SOURCE == "merge_request_event"104
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null115
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null105
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/116
117
# Zware controle: alleen op verzoek (play), nooit automatisch.118
.kvt_manual_check:119
rules:120
- if: $CI_PIPELINE_SOURCE == "merge_request_event"121
when: manual122
allow_failure: true123
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null124
when: manual125
allow_failure: true106
126
107
.kvt_tag:127
.kvt_tag:108
rules:128
rules:109
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/129
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/110
130
111
# De KVT-crate (BlueGit-releasefeed, versies, assetnamen, pakketbeheer-vlag) en131
# Minder piekgeheugen op de gedeelde BlueGit-runner.112
# de scripts in packaging/kvt. Klein en snel.132
.kvt_rust:133
variables:134
CARGO_INCREMENTAL: "0"135
CARGO_BUILD_JOBS: "2"136
RUST_TEST_THREADS: "2"137
138
# De scripts in packaging/kvt (shell-syntaxis en tests.sh). Geen apt-installs en139
# geen cargo: de kvt-update-tests draaien in app_test (handmatig) en lokaal.113
kvt_test:140
kvt_test:114
stage: test141
stage: test115
image: rust:1-bookworm142
image: rust:1-bookworm116
extends: .kvt_check143
extends: .kvt_check117
needs: []144
needs: []118
timeout: 30m145
timeout: 10m119
script:146
script:120
- apt-get update -qq && apt-get install -y -qq --no-install-recommends clang mold >/dev/null121
- cargo test -p kvt-update --locked122
- for f in packaging/kvt/*.sh; do bash -n "$f"; done147
- for f in packaging/kvt/*.sh; do bash -n "$f"; done123
- packaging/kvt/tests.sh148
- packaging/kvt/tests.sh124
149
125
# PKGBUILD renderen en .SRCINFO maken op Arch, zoals publish_aur dat doet.150
# PKGBUILD renderen en .SRCINFO maken op Arch, zoals publish_aur dat doet.151
# Handmatig: de Arch-image is zwaar, en publish_aur doet dezelfde render bij een release.126
aur_check:152
aur_check:127
stage: test153
stage: test128
image: archlinux/archlinux:base-devel154
image: archlinux/archlinux:base-devel129
extends: .kvt_check155
extends: .kvt_manual_check156
allow_failure: true130
needs: []157
needs: []131
timeout: 20m158
timeout: 20m132
script:159
script:@@ -143,29 +170,36 @@ aur_check:143
grep -q 'source = rusty-teams-0.0.1-kvt.1-linux-x86_64.tar.gz::https://git.kvt.nl/' "$out/.SRCINFO"170
grep -q 'source = rusty-teams-0.0.1-kvt.1-linux-x86_64.tar.gz::https://git.kvt.nl/' "$out/.SRCINFO"144
grep -qP '^\tpkgver = 0\.0\.1\.kvt\.1$' "$out/.SRCINFO"171
grep -qP '^\tpkgver = 0\.0\.1\.kvt\.1$' "$out/.SRCINFO"145
172
146
# Bouwt app-base en app en draait de updatertests (release_feed, kvt_feed) en173
# Bouwt één keer (cargo test --no-run) en draait daarna dezelfde tests als147
# de tests van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen).174
# voorheen: kvt-update, de updatertests (release_feed, kvt_feed) en de tests148
# Alleen als Rust-code of Cargo-bestanden veranderen; zwaar (volledige build).175
# van crates/kvt-sleutels (BC-links, kaarten, Ponos, planning, koppelen), plus176
# cargo check -p app. Handmatig (play): zwaar, start niet vanzelf.149
app_test:177
app_test:150
stage: test178
stage: test151
image: ubuntu:22.04179
image: ubuntu:22.04180
extends: [.kvt_manual_check, .kvt_rust]181
allow_failure: true152
needs: []182
needs: []153
timeout: 120m183
timeout: 120m154
rules:155
- if: $CI_PIPELINE_SOURCE == "merge_request_event"156
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]157
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != null158
changes: [crates/**/*, vendor/**/*, Cargo.toml, Cargo.lock, .cargo/**/*, blue-ci-cd.yml]159
variables:184
variables:160
CC: clang-21185
CC: clang-21161
CXX: clang++-21186
CXX: clang++-21162
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21187
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21188
cache:189
key: rusty-teams-cargo-linux190
paths: [.ci-cache/cargo-linux.tar.gz]163
script:191
script:192
- packaging/kvt/ci-cache.sh restore linux164
- packaging/kvt/ci-setup.sh linux193
- packaging/kvt/ci-setup.sh linux165
- . "$HOME/.cargo/env"194
- . "${CARGO_HOME:-$HOME/.cargo}/env"166
- cargo test --locked -p app-base --lib -- release_feed kvt_feed updater195
- cargo test --locked --profile ci -j2 --no-run -p kvt-update167
- cargo test --locked -p kvt-sleutels196
- cargo test --locked --profile ci -j2 --no-run -p kvt-sleutels168
- cargo check --locked -p app197
- cargo test --locked --profile ci -j2 --no-run -p app-base --lib198
- cargo check --locked --profile ci -j2 -p app199
- cargo test --locked --profile ci -j2 -p kvt-update200
- cargo test --locked --profile ci -j2 -p kvt-sleutels201
- cargo test --locked --profile ci -j2 -p app-base --lib -- release_feed kvt_feed updater202
- packaging/kvt/ci-cache.sh save linux169
203
170
# Linux: release-build met de tag als versie (TEAMS_RELEASE_TAG via build.rs),204
# Linux: release-build met de tag als versie (TEAMS_RELEASE_TAG via build.rs),171
# daarna de FHS-tarball van packaging/linux/package.sh. Vaste artifactnamen;205
# daarna de FHS-tarball van packaging/linux/package.sh. Vaste artifactnamen;@@ -173,16 +207,20 @@ app_test:173
linux_release:207
linux_release:174
stage: build208
stage: build175
image: ubuntu:22.04209
image: ubuntu:22.04176
extends: .kvt_tag210
extends: [.kvt_tag, .kvt_rust]177
needs: [kvt_test, aur_check]211
needs: []178
timeout: 150m212
timeout: 150m179
variables:213
variables:180
CC: clang-21214
CC: clang-21181
CXX: clang++-21215
CXX: clang++-21182
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21216
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21217
cache:218
key: rusty-teams-cargo-linux219
paths: [.ci-cache/cargo-linux.tar.gz]183
script:220
script:221
- packaging/kvt/ci-cache.sh restore linux184
- packaging/kvt/ci-setup.sh linux222
- packaging/kvt/ci-setup.sh linux185
- . "$HOME/.cargo/env"223
- . "${CARGO_HOME:-$HOME/.cargo}/env"186
- export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag RUSTY_TEAMS_VERSION="$CI_COMMIT_TAG"224
- export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag RUSTY_TEAMS_VERSION="$CI_COMMIT_TAG"187
- export RUSTY_TEAMS_MAINTAINER="KVT ICT <hephaestus@noreply.kvt.nl>"225
- export RUSTY_TEAMS_MAINTAINER="KVT ICT <hephaestus@noreply.kvt.nl>"188
- cargo build -p app --release --locked226
- cargo build -p app --release --locked@@ -193,6 +231,7 @@ linux_release:193
- strip dist/kvt/teams-linux-amd64231
- strip dist/kvt/teams-linux-amd64194
- grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-linux-amd64232
- grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-linux-amd64195
- ls -la dist/kvt233
- ls -la dist/kvt234
- packaging/kvt/ci-cache.sh save linux196
artifacts:235
artifacts:197
paths:236
paths:198
- dist/kvt/teams-linux-amd64237
- dist/kvt/teams-linux-amd64@@ -200,23 +239,33 @@ linux_release:200
expire_in: 7d239
expire_in: 7d201
240
202
# Windows x86_64: cross-build vanuit Linux (packaging/kvt/build-windows.sh).241
# Windows x86_64: cross-build vanuit Linux (packaging/kvt/build-windows.sh).203
# allow_failure: mislukt hij, dan krijgt de release geen exe en biedt een242
# Handmatig (play) en allow_failure: de release wacht er niet op en krijgt dan204
# Windows-installatie die versie niet aan; Linux en AUR gaan door.243
# geen exe, dus een Windows-installatie krijgt die versie niet aangeboden; Linux244
# en AUR gaan door. Wil je de exe er alsnog bij: speel windows_release, daarna245
# checksums en release opnieuw.205
windows_release:246
windows_release:206
stage: build247
stage: build207
image: ubuntu:24.04248
image: ubuntu:24.04208
extends: .kvt_tag249
extends: .kvt_rust209
needs: [kvt_test]250
needs: [linux_release]210
allow_failure: true251
allow_failure: true252
rules:253
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG =~ /^v[0-9]/254
when: manual255
allow_failure: true211
timeout: 180m256
timeout: 180m212
variables:257
variables:213
CC: clang-21258
CC: clang-21214
CXX: clang++-21259
CXX: clang++-21215
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21260
CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER: clang-21216
XWIN_ACCEPT_LICENSE: "1"261
XWIN_ACCEPT_LICENSE: "1"262
cache:263
key: rusty-teams-cargo-windows264
paths: [.ci-cache/cargo-windows.tar.gz]217
script:265
script:266
- packaging/kvt/ci-cache.sh restore windows218
- packaging/kvt/ci-setup.sh windows267
- packaging/kvt/ci-setup.sh windows219
- . "$HOME/.cargo/env"268
- . "${CARGO_HOME:-$HOME/.cargo}/env"220
- export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag269
- export GITHUB_REF_NAME="$CI_COMMIT_TAG" GITHUB_REF_TYPE=tag221
- packaging/kvt/build-windows.sh270
- packaging/kvt/build-windows.sh222
- mkdir -p dist/kvt271
- mkdir -p dist/kvt@@ -224,6 +273,7 @@ windows_release:224
- head -c 2 dist/kvt/teams-windows-amd64.exe | grep -q MZ273
- head -c 2 dist/kvt/teams-windows-amd64.exe | grep -q MZ225
- grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-windows-amd64.exe274
- grep -aq "$CI_COMMIT_TAG" dist/kvt/teams-windows-amd64.exe226
- ls -la dist/kvt275
- ls -la dist/kvt276
- packaging/kvt/ci-cache.sh save windows227
artifacts:277
artifacts:228
paths:278
paths:229
- dist/kvt/teams-windows-amd64.exe279
- dist/kvt/teams-windows-amd64.exe@@ -233,7 +283,7 @@ checksums:233
stage: package283
stage: package234
image: bluegit/base284
image: bluegit/base235
extends: .kvt_tag285
extends: .kvt_tag236
needs: [linux_release, windows_release]286
needs: [linux_release]237
script:287
script:238
- packaging/kvt/release-assets.sh sums "$CI_COMMIT_TAG"288
- packaging/kvt/release-assets.sh sums "$CI_COMMIT_TAG"239
artifacts:289
artifacts:@@ -247,7 +297,7 @@ release:247
stage: release297
stage: release248
image: bluegit/base298
image: bluegit/base249
extends: .kvt_tag299
extends: .kvt_tag250
needs: [checksums, linux_release, windows_release]300
needs: [checksums, linux_release]251
script:301
script:252
- packaging/kvt/release-assets.sh json "$CI_COMMIT_TAG" "$CI_COMMIT_SHA" > release.json302
- packaging/kvt/release-assets.sh json "$CI_COMMIT_TAG" "$CI_COMMIT_SHA" > release.json253
- cat release.json303
- cat release.json@@ -109,6 +109,90 @@ notice:
109
109
en: "Something went wrong: %{detail}"
110
110
de: "Etwas ist schiefgelaufen: %{detail}"
111
111
nl: "Er ging iets mis: %{detail}"
112
reaction:
113
custom_emoji:
114
en: Custom emoji
115
de: Organisations-Emoji
116
nl: Organisatie-emoji
117
118
fun_picker:
119
tab:
120
emoji:
121
en: Emoji
122
de: Emoji
123
nl: Emoji
124
gif:
125
en: GIF
126
de: GIF
127
nl: GIF
128
sticker:
129
en: Sticker
130
de: Sticker
131
nl: Sticker
132
org:
133
en: Organization
134
de: Organisation
135
nl: Organisatie
136
search:
137
emoji:
138
en: Search emoji
139
de: Emoji suchen
140
nl: Emoji zoeken
141
gif:
142
en: Search GIFs
143
de: GIFs suchen
144
nl: GIFs zoeken
145
sticker:
146
en: Search stickers
147
de: Sticker suchen
148
nl: Stickers zoeken
149
org:
150
en: Search organization emoji
151
de: Organisations-Emoji suchen
152
nl: Organisatie-emoji zoeken
153
org:
154
empty:
155
en: No organization emoji
156
de: Keine Organisations-Emojis
157
nl: Geen organisatie-emoji
158
empty_query:
159
en: "No organization emoji for \"%{query}\""
160
de: "Keine Organisations-Emojis zu \"%{query}\""
161
nl: "Geen organisatie-emoji voor \"%{query}\""
162
failed:
163
en: Organization emoji could not be loaded.
164
de: Organisations-Emojis konnten nicht geladen werden.
165
nl: Organisatie-emoji konden niet worden geladen.
166
retry:
167
en: Try again
168
de: Erneut versuchen
169
nl: Opnieuw proberen
170
reaction_picker:
171
tab:
172
emoji:
173
en: Emoji
174
de: Emoji
175
nl: Emoji
176
org:
177
en: Organization
178
de: Organisation
179
nl: Organisatie
180
search:
181
org:
182
en: Search organization emoji
183
de: Organisations-Emoji suchen
184
nl: Organisatie-emoji zoeken
185
org:
186
empty:
187
en: No organization emoji
188
de: Keine Organisations-Emojis
189
nl: Geen organisatie-emoji
190
empty_query:
191
en: "No organization emoji for \"%{query}\""
192
de: "Keine Organisations-Emojis zu \"%{query}\""
193
nl: "Geen organisatie-emoji voor \"%{query}\""
194
195
112
196
settings:
113
197
search:
114
198
no_results:
@@ -109,6 +109,90 @@ notice:109
en: "Something went wrong: %{detail}"109
en: "Something went wrong: %{detail}"110
de: "Etwas ist schiefgelaufen: %{detail}"110
de: "Etwas ist schiefgelaufen: %{detail}"111
nl: "Er ging iets mis: %{detail}"111
nl: "Er ging iets mis: %{detail}"112
reaction:113
custom_emoji:114
en: Custom emoji115
de: Organisations-Emoji116
nl: Organisatie-emoji117
118
fun_picker:119
tab:120
emoji:121
en: Emoji122
de: Emoji123
nl: Emoji124
gif:125
en: GIF126
de: GIF127
nl: GIF128
sticker:129
en: Sticker130
de: Sticker131
nl: Sticker132
org:133
en: Organization134
de: Organisation135
nl: Organisatie136
search:137
emoji:138
en: Search emoji139
de: Emoji suchen140
nl: Emoji zoeken141
gif:142
en: Search GIFs143
de: GIFs suchen144
nl: GIFs zoeken145
sticker:146
en: Search stickers147
de: Sticker suchen148
nl: Stickers zoeken149
org:150
en: Search organization emoji151
de: Organisations-Emoji suchen152
nl: Organisatie-emoji zoeken153
org:154
empty:155
en: No organization emoji156
de: Keine Organisations-Emojis157
nl: Geen organisatie-emoji158
empty_query:159
en: "No organization emoji for \"%{query}\""160
de: "Keine Organisations-Emojis zu \"%{query}\""161
nl: "Geen organisatie-emoji voor \"%{query}\""162
failed:163
en: Organization emoji could not be loaded.164
de: Organisations-Emojis konnten nicht geladen werden.165
nl: Organisatie-emoji konden niet worden geladen.166
retry:167
en: Try again168
de: Erneut versuchen169
nl: Opnieuw proberen170
reaction_picker:171
tab:172
emoji:173
en: Emoji174
de: Emoji175
nl: Emoji176
org:177
en: Organization178
de: Organisation179
nl: Organisatie180
search:181
org:182
en: Search organization emoji183
de: Organisations-Emoji suchen184
nl: Organisatie-emoji zoeken185
org:186
empty:187
en: No organization emoji188
de: Keine Organisations-Emojis189
nl: Geen organisatie-emoji190
empty_query:191
en: "No organization emoji for \"%{query}\""192
de: "Keine Organisations-Emojis zu \"%{query}\""193
nl: "Geen organisatie-emoji voor \"%{query}\""194
195
112
settings:196
settings:113
search:197
search:114
no_results:198
no_results:@@ -202,22 +202,6 @@ kvt:
202
202
de: Ponos konnte das nicht speichern
203
203
nl: Ponos kon dit niet opslaan
204
204
tasks:
205
menu:
206
en: My tasks in Ponos
207
de: Meine Aufgaben in Ponos
208
nl: Mijn taken in Ponos
209
title:
210
en: My tasks
211
de: Meine Aufgaben
212
nl: Mijn taken
213
empty:
214
en: No open tasks
215
de: Keine offenen Aufgaben
216
nl: Geen open taken
217
in_progress:
218
en: In progress
219
de: In Bearbeitung
220
nl: Mee bezig
221
205
completed:
222
206
en: Task done
223
207
de: Aufgabe erledigt
@@ -226,6 +210,85 @@ kvt:
226
210
en: Open Ponos
227
211
de: Ponos öffnen
228
212
nl: Ponos openen
213
rail:
214
ponos:
215
en: Ponos
216
de: Ponos
217
nl: Ponos
218
asclepius:
219
en: Asclepius
220
de: Asclepius
221
nl: Asclepius
222
board:
223
title:
224
en: Ponos
225
de: Ponos
226
nl: Ponos
227
new_task:
228
en: New task
229
de: Neue Aufgabe
230
nl: Nieuwe taak
231
edit_task:
232
en: Task in Ponos
233
de: Aufgabe in Ponos
234
nl: Taak in Ponos
235
empty_column:
236
en: No tasks
237
de: Keine Aufgaben
238
nl: Geen taken
239
status:
240
en: Status
241
de: Status
242
nl: Status
243
due:
244
en: Due date
245
de: Fällig am
246
nl: Deadline
247
due_placeholder:
248
en: e.g. 15 jan 2026 (empty = none)
249
de: z. B. 15 jan 2026 (leer = keins)
250
nl: bijv. 15 jan 2026 (leeg = geen)
251
bad_date:
252
en: Enter the due date like 15 jan 2026 or 15-01-2026
253
de: Datum wie 15 jan 2026 oder 15-01-2026 eingeben
254
nl: Vul de deadline in als 15 jan 2026 of 15-01-2026
255
assignee:
256
en: Assigned to
257
de: Zugewiesen an
258
nl: Toegewezen aan
259
assignee_none:
260
en: Nobody
261
de: Niemand
262
nl: Niemand
263
assignee_me:
264
en: Me
265
de: Ich
266
nl: Ik
267
save:
268
en: Save
269
de: Speichern
270
nl: Opslaan
271
saved:
272
en: Saved in Ponos
273
de: In Ponos gespeichert
274
nl: Opgeslagen in Ponos
275
complete:
276
en: Done
277
de: Erledigt
278
nl: Afronden
279
board_status:
280
todo:
281
en: To do
282
de: Zu erledigen
283
nl: Nog te doen
284
in_progress:
285
en: In progress
286
de: In Bearbeitung
287
nl: Onderhanden
288
done:
289
en: Done
290
de: Erledigt
291
nl: Afgerond
229
292
planning:
230
293
title:
231
294
en: Daedalus planning in calendar
@@ -243,3 +306,209 @@ kvt:
243
306
en: Connect to sleutels.kvt.nl again to see the Daedalus planning
244
307
de: Erneut mit sleutels.kvt.nl verbinden, um die Daedalus-Planung zu sehen
245
308
nl: Koppel opnieuw met sleutels.kvt.nl om de Daedalus-planning te zien
309
310
window:
311
title:
312
en: Custom window buttons
313
de: Eigene Fensterschaltflächen
314
nl: Eigen vensterknoppen
315
detail:
316
en: Place minimize, maximize and close in the title bar and hide the system window borders.
317
de: Minimieren, Maximieren und Schließen in der Titelleiste, ohne die Systemfensterrahmen.
318
nl: Minimaliseren, maximaliseren en sluiten in de titelbalk, zonder de vensterranden van het systeem.
319
minimize:
320
en: Minimize
321
de: Minimieren
322
nl: Minimaliseren
323
maximize:
324
en: Maximize
325
de: Maximieren
326
nl: Maximaliseren
327
restore:
328
en: Restore
329
de: Wiederherstellen
330
nl: Herstellen
331
close:
332
en: Close
333
de: Schließen
334
nl: Sluiten
335
336
tickets:
337
title:
338
en: My tickets
339
de: Meine Tickets
340
nl: Mijn tickets
341
filter_open:
342
en: Open
343
de: Offen
344
nl: Open
345
filter_closed:
346
en: Closed
347
de: Erledigt
348
nl: Afgehandeld
349
empty_open:
350
en: You have no open tickets
351
de: Du hast keine offenen Tickets
352
nl: Je hebt geen open tickets
353
empty_closed:
354
en: No closed tickets
355
de: Keine erledigten Tickets
356
nl: Geen afgehandelde tickets
357
pick:
358
en: Choose a ticket on the left
359
de: Wähle links ein Ticket
360
nl: Kies links een ticket
361
not_found:
362
en: This ticket does not exist or you have no access
363
de: Dieses Ticket gibt es nicht oder du hast keinen Zugriff
364
nl: Dit ticket bestaat niet of je hebt er geen toegang toe
365
failed:
366
en: Asclepius could not process this
367
de: Asclepius konnte das nicht verarbeiten
368
nl: Asclepius kon dit niet verwerken
369
reply_placeholder:
370
en: Write a reply…
371
de: Antwort schreiben…
372
nl: Schrijf een reactie…
373
send:
374
en: Send
375
de: Senden
376
nl: Versturen
377
sending:
378
en: Sending…
379
de: Wird gesendet…
380
nl: Bezig…
381
mention:
382
en: "Mention:"
383
de: "Erwähnen:"
384
nl: "Vermeld:"
385
ict:
386
en: ICT
387
de: ICT
388
nl: ICT
389
ghost:
390
en: internal note
391
de: interne Notiz
392
nl: interne notitie
393
closed_hint:
394
en: "This ticket is closed; reopening is done in Asclepius"
395
de: "Dieses Ticket ist erledigt; wieder öffnen geht in Asclepius"
396
nl: "Dit ticket is afgehandeld; heropenen kan in Asclepius"
397
demo_attachment:
398
en: Attachments are not available in the demo
399
de: Anhänge sind in der Demo nicht verfügbar
400
nl: Bijlagen zijn niet beschikbaar in de demo
401
new:
402
en: "New ticket"
403
de: "Neues Ticket"
404
nl: "Nieuw ticket"
405
form:
406
heading:
407
en: "Create new ticket"
408
de: "Neues Ticket erstellen"
409
nl: "Nieuw ticket maken"
410
title:
411
en: "Title"
412
de: "Titel"
413
nl: "Titel"
414
title_placeholder:
415
en: "For example: New scanner needed"
416
de: "Zum Beispiel: Neuer Scanner benötigt"
417
nl: "Bijvoorbeeld: Nieuwe scanner nodig"
418
category:
419
en: "Category"
420
de: "Kategorie"
421
nl: "Categorie"
422
subcategory:
423
en: "Subcategory"
424
de: "Unterkategorie"
425
nl: "Subcategorie"
426
description:
427
en: "Description"
428
de: "Beschreibung"
429
nl: "Beschrijving"
430
description_placeholder:
431
en: "Describe the problem or request as clearly as possible."
432
de: "Beschreibe das Problem oder die Anfrage so genau wie möglich."
433
nl: "Beschrijf het probleem of de aanvraag zo duidelijk mogelijk."
434
blocked:
435
en: "My work is being impeded"
436
de: "Meine Arbeit wird behindert"
437
nl: "Mijn werkzaamheden worden belemmerd"
438
fully_blocked:
439
en: "I cannot continue working until this is resolved"
440
de: "Ich kann nicht weiterarbeiten, bis das gelöst ist"
441
nl: "Ik kan niet verder werken tot dit opgelost is"
442
participants:
443
en: "Additional users"
444
de: "Weitere Benutzer"
445
nl: "Extra gebruikers"
446
participants_placeholder:
447
en: "name1@kvt.nl, name2@kvt.nl"
448
de: "name1@kvt.nl, name2@kvt.nl"
449
nl: "naam1@kvt.nl, naam2@kvt.nl"
450
participants_hint:
451
en: "Add colleagues who should also see this ticket under My tickets."
452
de: "Füge Kollegen hinzu, die dieses Ticket auch unter Meine Tickets sehen sollen."
453
nl: "Voeg collega's toe die dit ticket ook onder Mijn tickets moeten zien."
454
attachments:
455
en: "Screenshots or documents"
456
de: "Screenshots oder Dokumente"
457
nl: "Screenshots of documenten"
458
add_files:
459
en: "Add files"
460
de: "Dateien hinzufügen"
461
nl: "Bestanden toevoegen"
462
submit:
463
en: "Submit ticket"
464
de: "Ticket einreichen"
465
nl: "Ticket indienen"
466
pick_category:
467
en: "Choose a category"
468
de: "Kategorie wählen"
469
nl: "Kies een categorie"
470
fill_in:
471
en: "Fill in a title and a description"
472
de: "Titel und Beschreibung ausfüllen"
473
nl: "Vul een titel en een beschrijving in"
474
bad_email:
475
en: "Not a valid e-mail address: %{email}"
476
de: "Keine gültige E-Mail-Adresse: %{email}"
477
nl: "Geen geldig e-mailadres: %{email}"
478
too_many_files:
479
en: "At most %{max} files"
480
de: "Höchstens %{max} Dateien"
481
nl: "Hooguit %{max} bestanden"
482
file_too_large:
483
en: "%{name} is larger than 10 MB"
484
de: "%{name} ist größer als 10 MB"
485
nl: "%{name} is groter dan 10 MB"
486
created:
487
en: "Ticket #%{id} created in Asclepius"
488
de: "Ticket #%{id} in Asclepius erstellt"
489
nl: "Ticket #%{id} aangemaakt in Asclepius"
490
status:
491
ingediend:
492
en: Submitted
493
de: Eingereicht
494
nl: Ingediend
495
in_behandeling:
496
en: In progress
497
de: In Bearbeitung
498
nl: In behandeling
499
afwachtende_op_gebruiker:
500
en: Waiting for user
501
de: Wartet auf Benutzer
502
nl: Afwachtende op gebruiker
503
afwachtende_op_bestelling:
504
en: Waiting for order
505
de: Wartet auf Bestellung
506
nl: Afwachtende op bestelling
507
afwachtende_op_derde_partij:
508
en: Waiting for third party
509
de: Wartet auf Dritte
510
nl: Afwachtende op derde partij
511
afgehandeld:
512
en: Closed
513
de: Erledigt
514
nl: Afgehandeld
@@ -202,22 +202,6 @@ kvt:202
de: Ponos konnte das nicht speichern202
de: Ponos konnte das nicht speichern203
nl: Ponos kon dit niet opslaan203
nl: Ponos kon dit niet opslaan204
tasks:204
tasks:205
menu:206
en: My tasks in Ponos207
de: Meine Aufgaben in Ponos208
nl: Mijn taken in Ponos209
title:210
en: My tasks211
de: Meine Aufgaben212
nl: Mijn taken213
empty:214
en: No open tasks215
de: Keine offenen Aufgaben216
nl: Geen open taken217
in_progress:218
en: In progress219
de: In Bearbeitung220
nl: Mee bezig221
completed:205
completed:222
en: Task done206
en: Task done223
de: Aufgabe erledigt207
de: Aufgabe erledigt@@ -226,6 +210,85 @@ kvt:226
en: Open Ponos210
en: Open Ponos227
de: Ponos öffnen211
de: Ponos öffnen228
nl: Ponos openen212
nl: Ponos openen213
rail:214
ponos:215
en: Ponos216
de: Ponos217
nl: Ponos218
asclepius:219
en: Asclepius220
de: Asclepius221
nl: Asclepius222
board:223
title:224
en: Ponos225
de: Ponos226
nl: Ponos227
new_task:228
en: New task229
de: Neue Aufgabe230
nl: Nieuwe taak231
edit_task:232
en: Task in Ponos233
de: Aufgabe in Ponos234
nl: Taak in Ponos235
empty_column:236
en: No tasks237
de: Keine Aufgaben238
nl: Geen taken239
status:240
en: Status241
de: Status242
nl: Status243
due:244
en: Due date245
de: Fällig am246
nl: Deadline247
due_placeholder:248
en: e.g. 15 jan 2026 (empty = none)249
de: z. B. 15 jan 2026 (leer = keins)250
nl: bijv. 15 jan 2026 (leeg = geen)251
bad_date:252
en: Enter the due date like 15 jan 2026 or 15-01-2026253
de: Datum wie 15 jan 2026 oder 15-01-2026 eingeben254
nl: Vul de deadline in als 15 jan 2026 of 15-01-2026255
assignee:256
en: Assigned to257
de: Zugewiesen an258
nl: Toegewezen aan259
assignee_none:260
en: Nobody261
de: Niemand262
nl: Niemand263
assignee_me:264
en: Me265
de: Ich266
nl: Ik267
save:268
en: Save269
de: Speichern270
nl: Opslaan271
saved:272
en: Saved in Ponos273
de: In Ponos gespeichert274
nl: Opgeslagen in Ponos275
complete:276
en: Done277
de: Erledigt278
nl: Afronden279
board_status:280
todo:281
en: To do282
de: Zu erledigen283
nl: Nog te doen284
in_progress:285
en: In progress286
de: In Bearbeitung287
nl: Onderhanden288
done:289
en: Done290
de: Erledigt291
nl: Afgerond229
planning:292
planning:230
title:293
title:231
en: Daedalus planning in calendar294
en: Daedalus planning in calendar@@ -243,3 +306,209 @@ kvt:243
en: Connect to sleutels.kvt.nl again to see the Daedalus planning306
en: Connect to sleutels.kvt.nl again to see the Daedalus planning244
de: Erneut mit sleutels.kvt.nl verbinden, um die Daedalus-Planung zu sehen307
de: Erneut mit sleutels.kvt.nl verbinden, um die Daedalus-Planung zu sehen245
nl: Koppel opnieuw met sleutels.kvt.nl om de Daedalus-planning te zien308
nl: Koppel opnieuw met sleutels.kvt.nl om de Daedalus-planning te zien309
310
window:311
title:312
en: Custom window buttons313
de: Eigene Fensterschaltflächen314
nl: Eigen vensterknoppen315
detail:316
en: Place minimize, maximize and close in the title bar and hide the system window borders.317
de: Minimieren, Maximieren und Schließen in der Titelleiste, ohne die Systemfensterrahmen.318
nl: Minimaliseren, maximaliseren en sluiten in de titelbalk, zonder de vensterranden van het systeem.319
minimize:320
en: Minimize321
de: Minimieren322
nl: Minimaliseren323
maximize:324
en: Maximize325
de: Maximieren326
nl: Maximaliseren327
restore:328
en: Restore329
de: Wiederherstellen330
nl: Herstellen331
close:332
en: Close333
de: Schließen334
nl: Sluiten335
336
tickets:337
title:338
en: My tickets339
de: Meine Tickets340
nl: Mijn tickets341
filter_open:342
en: Open343
de: Offen344
nl: Open345
filter_closed:346
en: Closed347
de: Erledigt348
nl: Afgehandeld349
empty_open:350
en: You have no open tickets351
de: Du hast keine offenen Tickets352
nl: Je hebt geen open tickets353
empty_closed:354
en: No closed tickets355
de: Keine erledigten Tickets356
nl: Geen afgehandelde tickets357
pick:358
en: Choose a ticket on the left359
de: Wähle links ein Ticket360
nl: Kies links een ticket361
not_found:362
en: This ticket does not exist or you have no access363
de: Dieses Ticket gibt es nicht oder du hast keinen Zugriff364
nl: Dit ticket bestaat niet of je hebt er geen toegang toe365
failed:366
en: Asclepius could not process this367
de: Asclepius konnte das nicht verarbeiten368
nl: Asclepius kon dit niet verwerken369
reply_placeholder:370
en: Write a reply…371
de: Antwort schreiben…372
nl: Schrijf een reactie…373
send:374
en: Send375
de: Senden376
nl: Versturen377
sending:378
en: Sending…379
de: Wird gesendet…380
nl: Bezig…381
mention:382
en: "Mention:"383
de: "Erwähnen:"384
nl: "Vermeld:"385
ict:386
en: ICT387
de: ICT388
nl: ICT389
ghost:390
en: internal note391
de: interne Notiz392
nl: interne notitie393
closed_hint:394
en: "This ticket is closed; reopening is done in Asclepius"395
de: "Dieses Ticket ist erledigt; wieder öffnen geht in Asclepius"396
nl: "Dit ticket is afgehandeld; heropenen kan in Asclepius"397
demo_attachment:398
en: Attachments are not available in the demo399
de: Anhänge sind in der Demo nicht verfügbar400
nl: Bijlagen zijn niet beschikbaar in de demo401
new:402
en: "New ticket"403
de: "Neues Ticket"404
nl: "Nieuw ticket"405
form:406
heading:407
en: "Create new ticket"408
de: "Neues Ticket erstellen"409
nl: "Nieuw ticket maken"410
title:411
en: "Title"412
de: "Titel"413
nl: "Titel"414
title_placeholder:415
en: "For example: New scanner needed"416
de: "Zum Beispiel: Neuer Scanner benötigt"417
nl: "Bijvoorbeeld: Nieuwe scanner nodig"418
category:419
en: "Category"420
de: "Kategorie"421
nl: "Categorie"422
subcategory:423
en: "Subcategory"424
de: "Unterkategorie"425
nl: "Subcategorie"426
description:427
en: "Description"428
de: "Beschreibung"429
nl: "Beschrijving"430
description_placeholder:431
en: "Describe the problem or request as clearly as possible."432
de: "Beschreibe das Problem oder die Anfrage so genau wie möglich."433
nl: "Beschrijf het probleem of de aanvraag zo duidelijk mogelijk."434
blocked:435
en: "My work is being impeded"436
de: "Meine Arbeit wird behindert"437
nl: "Mijn werkzaamheden worden belemmerd"438
fully_blocked:439
en: "I cannot continue working until this is resolved"440
de: "Ich kann nicht weiterarbeiten, bis das gelöst ist"441
nl: "Ik kan niet verder werken tot dit opgelost is"442
participants:443
en: "Additional users"444
de: "Weitere Benutzer"445
nl: "Extra gebruikers"446
participants_placeholder:447
en: "name1@kvt.nl, name2@kvt.nl"448
de: "name1@kvt.nl, name2@kvt.nl"449
nl: "naam1@kvt.nl, naam2@kvt.nl"450
participants_hint:451
en: "Add colleagues who should also see this ticket under My tickets."452
de: "Füge Kollegen hinzu, die dieses Ticket auch unter Meine Tickets sehen sollen."453
nl: "Voeg collega's toe die dit ticket ook onder Mijn tickets moeten zien."454
attachments:455
en: "Screenshots or documents"456
de: "Screenshots oder Dokumente"457
nl: "Screenshots of documenten"458
add_files:459
en: "Add files"460
de: "Dateien hinzufügen"461
nl: "Bestanden toevoegen"462
submit:463
en: "Submit ticket"464
de: "Ticket einreichen"465
nl: "Ticket indienen"466
pick_category:467
en: "Choose a category"468
de: "Kategorie wählen"469
nl: "Kies een categorie"470
fill_in:471
en: "Fill in a title and a description"472
de: "Titel und Beschreibung ausfüllen"473
nl: "Vul een titel en een beschrijving in"474
bad_email:475
en: "Not a valid e-mail address: %{email}"476
de: "Keine gültige E-Mail-Adresse: %{email}"477
nl: "Geen geldig e-mailadres: %{email}"478
too_many_files:479
en: "At most %{max} files"480
de: "Höchstens %{max} Dateien"481
nl: "Hooguit %{max} bestanden"482
file_too_large:483
en: "%{name} is larger than 10 MB"484
de: "%{name} ist größer als 10 MB"485
nl: "%{name} is groter dan 10 MB"486
created:487
en: "Ticket #%{id} created in Asclepius"488
de: "Ticket #%{id} in Asclepius erstellt"489
nl: "Ticket #%{id} aangemaakt in Asclepius"490
status:491
ingediend:492
en: Submitted493
de: Eingereicht494
nl: Ingediend495
in_behandeling:496
en: In progress497
de: In Bearbeitung498
nl: In behandeling499
afwachtende_op_gebruiker:500
en: Waiting for user501
de: Wartet auf Benutzer502
nl: Afwachtende op gebruiker503
afwachtende_op_bestelling:504
en: Waiting for order505
de: Wartet auf Bestellung506
nl: Afwachtende op bestelling507
afwachtende_op_derde_partij:508
en: Waiting for third party509
de: Wartet auf Dritte510
nl: Afwachtende op derde partij511
afgehandeld:512
en: Closed513
de: Erledigt514
nl: Afgehandeld@@ -8,7 +8,7 @@ macro_rules! symbols {
8
8
};
9
9
}
10
10
11
const SYMBOLS: [(&str, &[u8]); 208] = symbols![
11
const SYMBOLS: [(&str, &[u8]); 209] = symbols![
12
12
"account_circle",
13
13
"add",
14
14
"alarm",
@@ -57,6 +57,7 @@ const SYMBOLS: [(&str, &[u8]); 208] = symbols![
57
57
"cloud",
58
58
"cloud_upload",
59
59
"code",
60
"confirmation_number", // KVT-fork: Asclepius-tegel
60
61
"code_blocks",
61
62
"content_copy",
62
63
"content_paste",
@@ -219,7 +220,7 @@ const SYMBOLS: [(&str, &[u8]); 208] = symbols![
219
220
"zoom_out",
220
221
];
221
222
222
const LUCIDE_AS_MATERIAL: [(&str, &str); 159] = [
223
const LUCIDE_AS_MATERIAL: [(&str, &str); 160] = [
223
224
("icons/alarm-clock.svg", "symbols/alarm.svg"),
224
225
("icons/app-window.svg", "symbols/web_asset.svg"),
225
226
("icons/arrow-down.svg", "symbols/arrow_downward.svg"),
@@ -384,6 +385,7 @@ const LUCIDE_AS_MATERIAL: [(&str, &str); 159] = [
384
385
("icons/target.svg", "symbols/target.svg"),
385
386
("icons/thumbs-down.svg", "symbols/thumb_down.svg"),
386
387
("icons/thumbs-up.svg", "symbols/thumb_up.svg"),
388
("icons/ticket.svg", "symbols/confirmation_number.svg"), // KVT-fork
387
389
("icons/timer.svg", "symbols/timer.svg"),
388
390
("icons/trash.svg", "symbols/delete.svg"),
389
391
("icons/triangle-alert.svg", "symbols/warning.svg"),
@@ -8,7 +8,7 @@ macro_rules! symbols {8
};8
};9
}9
}10
10
11
const SYMBOLS: [(&str, &[u8]); 208] = symbols![11
const SYMBOLS: [(&str, &[u8]); 209] = symbols![12
"account_circle",12
"account_circle",13
"add",13
"add",14
"alarm",14
"alarm",@@ -57,6 +57,7 @@ const SYMBOLS: [(&str, &[u8]); 208] = symbols![57
"cloud",57
"cloud",58
"cloud_upload",58
"cloud_upload",59
"code",59
"code",60
"confirmation_number", // KVT-fork: Asclepius-tegel60
"code_blocks",61
"code_blocks",61
"content_copy",62
"content_copy",62
"content_paste",63
"content_paste",@@ -219,7 +220,7 @@ const SYMBOLS: [(&str, &[u8]); 208] = symbols![219
"zoom_out",220
"zoom_out",220
];221
];221
222
222
const LUCIDE_AS_MATERIAL: [(&str, &str); 159] = [223
const LUCIDE_AS_MATERIAL: [(&str, &str); 160] = [223
("icons/alarm-clock.svg", "symbols/alarm.svg"),224
("icons/alarm-clock.svg", "symbols/alarm.svg"),224
("icons/app-window.svg", "symbols/web_asset.svg"),225
("icons/app-window.svg", "symbols/web_asset.svg"),225
("icons/arrow-down.svg", "symbols/arrow_downward.svg"),226
("icons/arrow-down.svg", "symbols/arrow_downward.svg"),@@ -384,6 +385,7 @@ const LUCIDE_AS_MATERIAL: [(&str, &str); 159] = [384
("icons/target.svg", "symbols/target.svg"),385
("icons/target.svg", "symbols/target.svg"),385
("icons/thumbs-down.svg", "symbols/thumb_down.svg"),386
("icons/thumbs-down.svg", "symbols/thumb_down.svg"),386
("icons/thumbs-up.svg", "symbols/thumb_up.svg"),387
("icons/thumbs-up.svg", "symbols/thumb_up.svg"),388
("icons/ticket.svg", "symbols/confirmation_number.svg"), // KVT-fork387
("icons/timer.svg", "symbols/timer.svg"),389
("icons/timer.svg", "symbols/timer.svg"),388
("icons/trash.svg", "symbols/delete.svg"),390
("icons/trash.svg", "symbols/delete.svg"),389
("icons/triangle-alert.svg", "symbols/warning.svg"),391
("icons/triangle-alert.svg", "symbols/warning.svg"),@@ -0,0 +1,66 @@
1
//! KVT-fork: instelling voor eigen vensterknoppen (client-side decorations).
2
//!
3
//! Standaard aan in de KVT-build. Uit schakelen brengt de vensterranden van het
4
//! systeem terug. Zie KVT-FORK.md.
5
6
use store::Store;
7
8
const META_KEY: &str = "kvt.window.client_decorations";
9
10
/// Standaard in de KVT-build: eigen knoppen in de titelbalk, geen systeemranden.
11
pub const DEFAULT_ENABLED: bool = true;
12
13
/// Of de gebruiker eigen vensterknoppen wil (en dus client-side decorations).
14
///
15
/// Een ontbrekende sleutel betekent de KVT-standaard (aan). Alleen een
16
/// opgeslagen `false` zet het uit.
17
pub fn load(store: &Store) -> bool {
18
match store.meta(META_KEY).ok().flatten().as_deref() {
19
Some("false") | Some("0") => false,
20
Some("true") | Some("1") => true,
21
Some(other) if other.trim().eq_ignore_ascii_case("false") => false,
22
Some(_) | None => DEFAULT_ENABLED,
23
}
24
}
25
26
pub fn save(store: &Store, enabled: bool) {
27
let _ = store.set_meta(META_KEY, if enabled { "true" } else { "false" });
28
}
29
30
/// Of deze bouw de instelling en de eigen knoppen toont.
31
///
32
/// Op macOS blijven de verkeerslichten van het systeem; daar is de instelling
33
/// verborgen en staan de eigen knoppen uit.
34
pub fn available() -> bool {
35
!cfg!(target_os = "macos")
36
}
37
38
#[cfg(test)]
39
mod tests {
40
use super::*;
41
42
#[test]
43
fn missing_key_defaults_to_on() {
44
let store = Store::open_in_memory().unwrap();
45
assert!(load(&store));
46
assert!(DEFAULT_ENABLED);
47
}
48
49
#[test]
50
fn round_trips_off_and_on() {
51
let store = Store::open_in_memory().unwrap();
52
save(&store, false);
53
assert!(!load(&store));
54
save(&store, true);
55
assert!(load(&store));
56
}
57
58
#[test]
59
fn only_an_explicit_false_turns_it_off() {
60
let store = Store::open_in_memory().unwrap();
61
let _ = store.set_meta(META_KEY, "false");
62
assert!(!load(&store));
63
let _ = store.set_meta(META_KEY, "unexpected");
64
assert!(load(&store));
65
}
66
}
@@ -0,0 +1,66 @@1
//! KVT-fork: instelling voor eigen vensterknoppen (client-side decorations).2
//!3
//! Standaard aan in de KVT-build. Uit schakelen brengt de vensterranden van het4
//! systeem terug. Zie KVT-FORK.md.5
6
use store::Store;7
8
const META_KEY: &str = "kvt.window.client_decorations";9
10
/// Standaard in de KVT-build: eigen knoppen in de titelbalk, geen systeemranden.11
pub const DEFAULT_ENABLED: bool = true;12
13
/// Of de gebruiker eigen vensterknoppen wil (en dus client-side decorations).14
///15
/// Een ontbrekende sleutel betekent de KVT-standaard (aan). Alleen een16
/// opgeslagen `false` zet het uit.17
pub fn load(store: &Store) -> bool {18
match store.meta(META_KEY).ok().flatten().as_deref() {19
Some("false") | Some("0") => false,20
Some("true") | Some("1") => true,21
Some(other) if other.trim().eq_ignore_ascii_case("false") => false,22
Some(_) | None => DEFAULT_ENABLED,23
}24
}25
26
pub fn save(store: &Store, enabled: bool) {27
let _ = store.set_meta(META_KEY, if enabled { "true" } else { "false" });28
}29
30
/// Of deze bouw de instelling en de eigen knoppen toont.31
///32
/// Op macOS blijven de verkeerslichten van het systeem; daar is de instelling33
/// verborgen en staan de eigen knoppen uit.34
pub fn available() -> bool {35
!cfg!(target_os = "macos")36
}37
38
#[cfg(test)]39
mod tests {40
use super::*;41
42
#[test]43
fn missing_key_defaults_to_on() {44
let store = Store::open_in_memory().unwrap();45
assert!(load(&store));46
assert!(DEFAULT_ENABLED);47
}48
49
#[test]50
fn round_trips_off_and_on() {51
let store = Store::open_in_memory().unwrap();52
save(&store, false);53
assert!(!load(&store));54
save(&store, true);55
assert!(load(&store));56
}57
58
#[test]59
fn only_an_explicit_false_turns_it_off() {60
let store = Store::open_in_memory().unwrap();61
let _ = store.set_meta(META_KEY, "false");62
assert!(!load(&store));63
let _ = store.set_meta(META_KEY, "unexpected");64
assert!(load(&store));65
}66
}@@ -24,6 +24,7 @@ pub mod image_view_math;
24
24
pub mod inline_image;
25
25
pub mod kvt_brand;
26
26
pub mod kvt_feed;
27
pub mod kvt_window;
27
28
#[cfg(target_os = "linux")]
28
29
pub mod linux_desktop;
29
30
#[cfg(target_os = "linux")]
@@ -24,6 +24,7 @@ pub mod image_view_math;24
pub mod inline_image;24
pub mod inline_image;25
pub mod kvt_brand;25
pub mod kvt_brand;26
pub mod kvt_feed;26
pub mod kvt_feed;27
pub mod kvt_window;27
#[cfg(target_os = "linux")]28
#[cfg(target_os = "linux")]28
pub mod linux_desktop;29
pub mod linux_desktop;29
#[cfg(target_os = "linux")]30
#[cfg(target_os = "linux")]@@ -1,5 +1,5 @@
1
1
use gpui_kit::{ImageSource, SharedString};
2
use teams_core::{Gif, ImageRef};
2
use teams_core::{Gif, ImageRef, OrgEmoji, custom_emoji_html};
3
3
4
4
use crate::stickers::Sticker;
5
5
@@ -8,10 +8,11 @@ const STICKER_SIZE: u32 = 250;
8
8
const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";
9
9
const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";
10
10
11
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11
#[derive(Debug, Clone, PartialEq, Eq)]
12
12
pub enum RemoteKind {
13
13
Gif,
14
14
Sticker,
15
CustomEmoji { object_id: String },
15
16
}
16
17
17
18
/// A GIF or sticker the message points at by URL; nothing is uploaded.
@@ -46,18 +47,42 @@ impl RemoteImage {
46
47
}
47
48
}
48
49
50
pub fn custom_emoji(emoji: &OrgEmoji) -> Self {
51
RemoteImage {
52
kind: RemoteKind::CustomEmoji {
53
object_id: emoji.document_id.clone(),
54
},
55
url: emoji.image_url(),
56
title: emoji.name.clone(),
57
width: 20,
58
height: 20,
59
}
60
}
61
62
pub fn is_custom_emoji(&self) -> bool {
63
matches!(self.kind, RemoteKind::CustomEmoji { .. })
64
}
65
49
66
pub fn html(&self) -> String {
50
let itemtype = match self.kind {
51
RemoteKind::Gif => GIF_ITEMTYPE,
52
RemoteKind::Sticker => STICKER_ITEMTYPE,
53
};
54
format!(
55
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{itemtype}\">",
56
teams_core::escape_html(&self.url),
57
self.width,
58
self.height,
59
teams_core::escape_html(&self.title),
60
)
67
match &self.kind {
68
RemoteKind::CustomEmoji { object_id } => {
69
custom_emoji_html(&self.title, object_id, &self.url)
70
}
71
RemoteKind::Gif => format!(
72
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{GIF_ITEMTYPE}\">",
73
teams_core::escape_html(&self.url),
74
self.width,
75
self.height,
76
teams_core::escape_html(&self.title),
77
),
78
RemoteKind::Sticker => format!(
79
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{STICKER_ITEMTYPE}\">",
80
teams_core::escape_html(&self.url),
81
self.width,
82
self.height,
83
teams_core::escape_html(&self.title),
84
),
85
}
61
86
}
62
87
63
88
pub fn image_ref(&self) -> ImageRef {
@@ -131,4 +156,20 @@ mod tests {
131
156
assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));
132
157
assert!(html.contains("clippy-250x250"));
133
158
}
159
160
#[test]
161
fn custom_emoji_html_uses_the_official_itemtype_and_itemid() {
162
let emoji = OrgEmoji {
163
id: "em-1".into(),
164
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
165
name: "absolute-cinema".into(),
166
keywords: vec![],
167
source: None,
168
};
169
let html = RemoteImage::custom_emoji(&emoji).html();
170
assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));
171
assert!(html.contains("itemid=\"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));
172
assert!(html.contains("width=\"20\" height=\"20\""));
173
assert!(html.contains("/views/imgt2_anim"));
174
}
134
175
}
@@ -1,5 +1,5 @@1
use gpui_kit::{ImageSource, SharedString};1
use gpui_kit::{ImageSource, SharedString};2
use teams_core::{Gif, ImageRef};2
use teams_core::{Gif, ImageRef, OrgEmoji, custom_emoji_html};3
3
4
use crate::stickers::Sticker;4
use crate::stickers::Sticker;5
5
@@ -8,10 +8,11 @@ const STICKER_SIZE: u32 = 250;8
const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";8
const GIF_ITEMTYPE: &str = "http://schema.skype.com/Giphy";9
const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";9
const STICKER_ITEMTYPE: &str = "http://schema.skype.com/Sticker";10
10
11
#[derive(Debug, Clone, Copy, PartialEq, Eq)]11
#[derive(Debug, Clone, PartialEq, Eq)]12
pub enum RemoteKind {12
pub enum RemoteKind {13
Gif,13
Gif,14
Sticker,14
Sticker,15
CustomEmoji { object_id: String },15
}16
}16
17
17
/// A GIF or sticker the message points at by URL; nothing is uploaded.18
/// A GIF or sticker the message points at by URL; nothing is uploaded.@@ -46,18 +47,42 @@ impl RemoteImage {46
}47
}47
}48
}48
49
50
pub fn custom_emoji(emoji: &OrgEmoji) -> Self {51
RemoteImage {52
kind: RemoteKind::CustomEmoji {53
object_id: emoji.document_id.clone(),54
},55
url: emoji.image_url(),56
title: emoji.name.clone(),57
width: 20,58
height: 20,59
}60
}61
62
pub fn is_custom_emoji(&self) -> bool {63
matches!(self.kind, RemoteKind::CustomEmoji { .. })64
}65
49
pub fn html(&self) -> String {66
pub fn html(&self) -> String {50
let itemtype = match self.kind {67
match &self.kind {51
RemoteKind::Gif => GIF_ITEMTYPE,68
RemoteKind::CustomEmoji { object_id } => {52
RemoteKind::Sticker => STICKER_ITEMTYPE,69
custom_emoji_html(&self.title, object_id, &self.url)53
};70
}54
format!(71
RemoteKind::Gif => format!(55
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{itemtype}\">",72
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{GIF_ITEMTYPE}\">",56
teams_core::escape_html(&self.url),73
teams_core::escape_html(&self.url),57
self.width,74
self.width,58
self.height,75
self.height,59
teams_core::escape_html(&self.title),76
teams_core::escape_html(&self.title),60
)77
),78
RemoteKind::Sticker => format!(79
"<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{}\" itemtype=\"{STICKER_ITEMTYPE}\">",80
teams_core::escape_html(&self.url),81
self.width,82
self.height,83
teams_core::escape_html(&self.title),84
),85
}61
}86
}62
87
63
pub fn image_ref(&self) -> ImageRef {88
pub fn image_ref(&self) -> ImageRef {@@ -131,4 +156,20 @@ mod tests {131
assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));156
assert!(html.ends_with("itemtype=\"http://schema.skype.com/Sticker\">"));132
assert!(html.contains("clippy-250x250"));157
assert!(html.contains("clippy-250x250"));133
}158
}159
160
#[test]161
fn custom_emoji_html_uses_the_official_itemtype_and_itemid() {162
let emoji = OrgEmoji {163
id: "em-1".into(),164
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),165
name: "absolute-cinema".into(),166
keywords: vec![],167
source: None,168
};169
let html = RemoteImage::custom_emoji(&emoji).html();170
assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));171
assert!(html.contains("itemid=\"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));172
assert!(html.contains("width=\"20\" height=\"20\""));173
assert!(html.contains("/views/imgt2_anim"));174
}134
}175
}@@ -13,7 +13,8 @@ use store::{
13
13
use teams_core::{
14
14
ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,
15
15
CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
16
LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage,
16
LinkPreview, MentionCandidate, NOTES_CHAT_ID, OrgEmoji, PersonCandidate, PersonSource, PinnedMessage,
17
custom_emoji_html,
17
18
SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
18
19
};
19
20
@@ -24,6 +25,7 @@ use crate::demo_gifs;
24
25
use crate::message_actions::ForwardSource;
25
26
26
27
static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
28
static DEMO_ORG_EMOJIS: OnceLock<Vec<OrgEmoji>> = OnceLock::new();
27
29
28
30
pub const DEMO_USER_ID: &str = "demo-me";
29
31
const DEMO_USER_NAME: &str = "Dana Demo";
@@ -595,6 +597,101 @@ fn image_directory() -> PathBuf {
595
597
std::env::temp_dir().join("rusty-teams-demo")
596
598
}
597
599
600
pub const DEMO_ORG_KOFIE_ID: &str = "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
601
pub const DEMO_ORG_SHIPIT_ID: &str = "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
602
pub const DEMO_ORG_HIGHFIVE_ID: &str = "0-weu-d1-cccccccccccccccccccccccccccccccc";
603
pub const DEMO_ORG_FEEST_ID: &str = "0-weu-d1-dddddddddddddddddddddddddddddddd";
604
605
pub fn org_emoji_demo_url(name: &str) -> String {
606
format!("demo://org-emoji-{name}")
607
}
608
609
pub fn org_emoji_source(object_id: &str) -> Option<String> {
610
DEMO_ORG_EMOJIS
611
.get()
612
.into_iter()
613
.flatten()
614
.find(|emoji| emoji.document_id == object_id)
615
.and_then(|emoji| emoji.source.clone())
616
}
617
618
pub fn org_emoji_image_url(object_id: &str) -> Option<String> {
619
DEMO_ORG_EMOJIS
620
.get()
621
.into_iter()
622
.flatten()
623
.find(|emoji| emoji.document_id == object_id)
624
.map(|emoji| org_emoji_demo_url(&emoji.name))
625
}
626
627
pub fn ensure_org_emojis() -> Vec<OrgEmoji> {
628
if let Some(emojis) = DEMO_ORG_EMOJIS.get() {
629
return emojis.clone();
630
}
631
let emojis = generate_org_emojis(&image_directory());
632
let _ = DEMO_ORG_EMOJIS.set(emojis.clone());
633
emojis
634
}
635
636
fn demo_org_emoji_html(name: &str, document_id: &str) -> String {
637
custom_emoji_html(name, document_id, &org_emoji_demo_url(name))
638
}
639
640
pub fn org_emojis() -> Vec<OrgEmoji> {
641
ensure_org_emojis()
642
}
643
644
pub fn search_org_emojis(query: &str) -> Vec<OrgEmoji> {
645
org_emojis()
646
.into_iter()
647
.filter(|emoji| emoji.matches(query))
648
.collect()
649
}
650
651
fn generate_org_emojis(directory: &std::path::Path) -> Vec<OrgEmoji> {
652
const FACES: [(&str, &str, &str, [u8; 3], &[&str]); 4] = [
653
("demo-koffie", "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "koffie", [166, 92, 46], &["koffie", "coffee"]),
654
("demo-shipit", "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "ship-it", [47, 133, 90], &["ship", "lancering"]),
655
("demo-highfive", "0-weu-d1-cccccccccccccccccccccccccccccccc", "high-five", [196, 92, 58], &["highfive", "team"]),
656
("demo-feest", "0-weu-d1-dddddddddddddddddddddddddddddddd", "feest", [126, 68, 173], &["feest", "party"]),
657
];
658
let mut emojis = Vec::new();
659
let _ = std::fs::create_dir_all(directory);
660
for (id, document_id, name, color, keywords) in FACES {
661
let path = directory.join(format!("org-emoji-{name}.png"));
662
let png = encode_rgb(32, 32, |column, row| {
663
let dx = column as i32 - 16;
664
let dy = row as i32 - 16;
665
if dx * dx + dy * dy <= 13 * 13 {
666
if (dx + dy) < -6 {
667
[
668
color[0].saturating_add(40).min(255),
669
color[1].saturating_add(40).min(255),
670
color[2].saturating_add(40).min(255),
671
]
672
} else {
673
color
674
}
675
} else {
676
[255, 255, 255]
677
}
678
});
679
let source = if std::fs::write(&path, png).is_ok() {
680
Some(path.to_string_lossy().into_owned())
681
} else {
682
None
683
};
684
emojis.push(OrgEmoji {
685
id: id.to_owned(),
686
document_id: document_id.to_owned(),
687
name: name.to_owned(),
688
keywords: keywords.iter().map(|keyword| (*keyword).to_owned()).collect(),
689
source,
690
});
691
}
692
emojis
693
}
694
598
695
pub fn search_gifs(query: &str) -> Vec<Gif> {
599
696
let query = query.trim().to_lowercase();
600
697
SEARCHABLE_GIFS
@@ -847,6 +944,7 @@ pub fn activity_snapshot() -> ActivitySnapshot {
847
944
}
848
945
849
946
pub fn seed(store: &Store) {
947
let _ = ensure_org_emojis();
850
948
let chats: Vec<ChatRecord> = demo_chats()
851
949
.into_iter()
852
950
.map(|demo| ChatRecord {
@@ -1092,6 +1190,14 @@ pub fn seed_directory(state: &mut AppState) {
1092
1190
state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);
1093
1191
}
1094
1192
let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
1193
let org_emojis = ensure_org_emojis();
1194
for emoji in &org_emojis {
1195
if let Some(path) = emoji.source.as_deref() {
1196
state
1197
.directory
1198
.set_image(&org_emoji_demo_url(&emoji.name), std::path::Path::new(path));
1199
}
1200
}
1095
1201
state.directory.set_image(
1096
1202
demo_gifs::RECEIVED_GIF_KEY,
1097
1203
&directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
@@ -2033,6 +2139,35 @@ fn release_messages() -> Vec<MessageRecord> {
2033
2139
"[]",
2034
2140
false,
2035
2141
),
2142
{
2143
let org = reactions_json(vec![
2144
reaction(
2145
&format!("koffie;{DEMO_ORG_KOFIE_ID}"),
2146
&[
2147
(MARA_ID, mara_name, at(0, 13, 58)),
2148
(JONAS_ID, jonas_name, at(0, 13, 59)),
2149
],
2150
),
2151
reaction(
2152
&format!("feest;{DEMO_ORG_FEEST_ID}"),
2153
&[(PRIYA_ID, priya_name, at(0, 14, 0))],
2154
),
2155
]);
2156
message(
2157
chat,
2158
"m13",
2159
None,
2160
me,
2161
at(0, 13, 56),
2162
&format!(
2163
"<p>De organisatie-emoji staan erin, bijvoorbeeld {} bij de koffie en {} als we live gaan.</p>",
2164
demo_org_emoji_html("koffie", DEMO_ORG_KOFIE_ID),
2165
demo_org_emoji_html("ship-it", DEMO_ORG_SHIPIT_ID),
2166
),
2167
&org,
2168
false,
2169
)
2170
},
2036
2171
]
2037
2172
}
2038
2173
@@ -13,7 +13,8 @@ use store::{13
use teams_core::{13
use teams_core::{14
ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,14
ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,15
CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,15
CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,16
LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage,16
LinkPreview, MentionCandidate, NOTES_CHAT_ID, OrgEmoji, PersonCandidate, PersonSource, PinnedMessage,17
custom_emoji_html,17
SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,18
SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,18
};19
};19
20
@@ -24,6 +25,7 @@ use crate::demo_gifs;24
use crate::message_actions::ForwardSource;25
use crate::message_actions::ForwardSource;25
26
26
static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();27
static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();28
static DEMO_ORG_EMOJIS: OnceLock<Vec<OrgEmoji>> = OnceLock::new();27
29
28
pub const DEMO_USER_ID: &str = "demo-me";30
pub const DEMO_USER_ID: &str = "demo-me";29
const DEMO_USER_NAME: &str = "Dana Demo";31
const DEMO_USER_NAME: &str = "Dana Demo";@@ -595,6 +597,101 @@ fn image_directory() -> PathBuf {595
std::env::temp_dir().join("rusty-teams-demo")597
std::env::temp_dir().join("rusty-teams-demo")596
}598
}597
599
600
pub const DEMO_ORG_KOFIE_ID: &str = "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";601
pub const DEMO_ORG_SHIPIT_ID: &str = "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";602
pub const DEMO_ORG_HIGHFIVE_ID: &str = "0-weu-d1-cccccccccccccccccccccccccccccccc";603
pub const DEMO_ORG_FEEST_ID: &str = "0-weu-d1-dddddddddddddddddddddddddddddddd";604
605
pub fn org_emoji_demo_url(name: &str) -> String {606
format!("demo://org-emoji-{name}")607
}608
609
pub fn org_emoji_source(object_id: &str) -> Option<String> {610
DEMO_ORG_EMOJIS611
.get()612
.into_iter()613
.flatten()614
.find(|emoji| emoji.document_id == object_id)615
.and_then(|emoji| emoji.source.clone())616
}617
618
pub fn org_emoji_image_url(object_id: &str) -> Option<String> {619
DEMO_ORG_EMOJIS620
.get()621
.into_iter()622
.flatten()623
.find(|emoji| emoji.document_id == object_id)624
.map(|emoji| org_emoji_demo_url(&emoji.name))625
}626
627
pub fn ensure_org_emojis() -> Vec<OrgEmoji> {628
if let Some(emojis) = DEMO_ORG_EMOJIS.get() {629
return emojis.clone();630
}631
let emojis = generate_org_emojis(&image_directory());632
let _ = DEMO_ORG_EMOJIS.set(emojis.clone());633
emojis634
}635
636
fn demo_org_emoji_html(name: &str, document_id: &str) -> String {637
custom_emoji_html(name, document_id, &org_emoji_demo_url(name))638
}639
640
pub fn org_emojis() -> Vec<OrgEmoji> {641
ensure_org_emojis()642
}643
644
pub fn search_org_emojis(query: &str) -> Vec<OrgEmoji> {645
org_emojis()646
.into_iter()647
.filter(|emoji| emoji.matches(query))648
.collect()649
}650
651
fn generate_org_emojis(directory: &std::path::Path) -> Vec<OrgEmoji> {652
const FACES: [(&str, &str, &str, [u8; 3], &[&str]); 4] = [653
("demo-koffie", "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "koffie", [166, 92, 46], &["koffie", "coffee"]),654
("demo-shipit", "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "ship-it", [47, 133, 90], &["ship", "lancering"]),655
("demo-highfive", "0-weu-d1-cccccccccccccccccccccccccccccccc", "high-five", [196, 92, 58], &["highfive", "team"]),656
("demo-feest", "0-weu-d1-dddddddddddddddddddddddddddddddd", "feest", [126, 68, 173], &["feest", "party"]),657
];658
let mut emojis = Vec::new();659
let _ = std::fs::create_dir_all(directory);660
for (id, document_id, name, color, keywords) in FACES {661
let path = directory.join(format!("org-emoji-{name}.png"));662
let png = encode_rgb(32, 32, |column, row| {663
let dx = column as i32 - 16;664
let dy = row as i32 - 16;665
if dx * dx + dy * dy <= 13 * 13 {666
if (dx + dy) < -6 {667
[668
color[0].saturating_add(40).min(255),669
color[1].saturating_add(40).min(255),670
color[2].saturating_add(40).min(255),671
]672
} else {673
color674
}675
} else {676
[255, 255, 255]677
}678
});679
let source = if std::fs::write(&path, png).is_ok() {680
Some(path.to_string_lossy().into_owned())681
} else {682
None683
};684
emojis.push(OrgEmoji {685
id: id.to_owned(),686
document_id: document_id.to_owned(),687
name: name.to_owned(),688
keywords: keywords.iter().map(|keyword| (*keyword).to_owned()).collect(),689
source,690
});691
}692
emojis693
}694
598
pub fn search_gifs(query: &str) -> Vec<Gif> {695
pub fn search_gifs(query: &str) -> Vec<Gif> {599
let query = query.trim().to_lowercase();696
let query = query.trim().to_lowercase();600
SEARCHABLE_GIFS697
SEARCHABLE_GIFS@@ -847,6 +944,7 @@ pub fn activity_snapshot() -> ActivitySnapshot {847
}944
}848
945
849
pub fn seed(store: &Store) {946
pub fn seed(store: &Store) {947
let _ = ensure_org_emojis();850
let chats: Vec<ChatRecord> = demo_chats()948
let chats: Vec<ChatRecord> = demo_chats()851
.into_iter()949
.into_iter()852
.map(|demo| ChatRecord {950
.map(|demo| ChatRecord {@@ -1092,6 +1190,14 @@ pub fn seed_directory(state: &mut AppState) {1092
state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);1190
state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);1093
}1191
}1094
let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));1192
let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));1193
let org_emojis = ensure_org_emojis();1194
for emoji in &org_emojis {1195
if let Some(path) = emoji.source.as_deref() {1196
state1197
.directory1198
.set_image(&org_emoji_demo_url(&emoji.name), std::path::Path::new(path));1199
}1200
}1095
state.directory.set_image(1201
state.directory.set_image(1096
demo_gifs::RECEIVED_GIF_KEY,1202
demo_gifs::RECEIVED_GIF_KEY,1097
&directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),1203
&directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),@@ -2033,6 +2139,35 @@ fn release_messages() -> Vec<MessageRecord> {2033
"[]",2139
"[]",2034
false,2140
false,2035
),2141
),2142
{2143
let org = reactions_json(vec![2144
reaction(2145
&format!("koffie;{DEMO_ORG_KOFIE_ID}"),2146
&[2147
(MARA_ID, mara_name, at(0, 13, 58)),2148
(JONAS_ID, jonas_name, at(0, 13, 59)),2149
],2150
),2151
reaction(2152
&format!("feest;{DEMO_ORG_FEEST_ID}"),2153
&[(PRIYA_ID, priya_name, at(0, 14, 0))],2154
),2155
]);2156
message(2157
chat,2158
"m13",2159
None,2160
me,2161
at(0, 13, 56),2162
&format!(2163
"<p>De organisatie-emoji staan erin, bijvoorbeeld {} bij de koffie en {} als we live gaan.</p>",2164
demo_org_emoji_html("koffie", DEMO_ORG_KOFIE_ID),2165
demo_org_emoji_html("ship-it", DEMO_ORG_SHIPIT_ID),2166
),2167
&org,2168
false,2169
)2170
},2036
]2171
]2037
}2172
}2038
2173
@@ -1,5 +1,5 @@
1
1
//! KVT-fork: een demobericht met Business Central-links, zodat `--demo` de
2
//! kaartjes van `crate::kvt` (app) laat zien. Verzonnen nummers, geen echte data.
2
//! kaartjes van `crate::kvt` (app) laat zien, plus een Asclepius-ticketlink. Verzonnen nummers, geen echte data.
3
3
4
4
use store::MessageRecord;
5
5
@@ -10,6 +10,7 @@ const COMPONENT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninkli
10
10
const PROJECT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=88&filter=%27No.%27%20IS%20%27PRJ2699001%27";
11
11
const CUSTOMER: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=21&filter=%27No.%27%20IS%20%27269901%27";
12
12
const ITEM: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=30&filter=%27No.%27%20IS%20%272699001%27";
13
const TICKET: &str = "https://sleutels.kvt.nl/asclepius/index.php?open=4102";
13
14
const CONTRACT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333015&filter=%27Contract%20No.%27%20IS%20%27CT2699001%27";
14
15
15
16
pub fn messages() -> Vec<MessageRecord> {
@@ -28,6 +29,14 @@ pub fn messages() -> Vec<MessageRecord> {
28
29
"<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>"
29
30
),
30
31
),
32
// Asclepius-ticketlink: opent het ticketvenster (demoticket #4102).
33
message(
34
"kvt4",
35
at(0, 11, 3),
36
format!(
37
"<p>Ik heb er een ticket van gemaakt: <a href=\"{TICKET}\">#4102 Laptop start niet meer op</a></p>"
38
),
39
),
31
40
// Alleen de link: de app laat dan alleen het kaartje zien.
32
41
message(
33
42
"kvt3",
@@ -1,5 +1,5 @@1
//! KVT-fork: een demobericht met Business Central-links, zodat `--demo` de1
//! KVT-fork: een demobericht met Business Central-links, zodat `--demo` de2
//! kaartjes van `crate::kvt` (app) laat zien. Verzonnen nummers, geen echte data.2
//! kaartjes van `crate::kvt` (app) laat zien, plus een Asclepius-ticketlink. Verzonnen nummers, geen echte data.3
3
4
use store::MessageRecord;4
use store::MessageRecord;5
5
@@ -10,6 +10,7 @@ const COMPONENT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninkli10
const PROJECT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=88&filter=%27No.%27%20IS%20%27PRJ2699001%27";10
const PROJECT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=88&filter=%27No.%27%20IS%20%27PRJ2699001%27";11
const CUSTOMER: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=21&filter=%27No.%27%20IS%20%27269901%27";11
const CUSTOMER: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=21&filter=%27No.%27%20IS%20%27269901%27";12
const ITEM: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=30&filter=%27No.%27%20IS%20%272699001%27";12
const ITEM: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=30&filter=%27No.%27%20IS%20%272699001%27";13
const TICKET: &str = "https://sleutels.kvt.nl/asclepius/index.php?open=4102";13
const CONTRACT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333015&filter=%27Contract%20No.%27%20IS%20%27CT2699001%27";14
const CONTRACT: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333015&filter=%27Contract%20No.%27%20IS%20%27CT2699001%27";14
15
15
pub fn messages() -> Vec<MessageRecord> {16
pub fn messages() -> Vec<MessageRecord> {@@ -28,6 +29,14 @@ pub fn messages() -> Vec<MessageRecord> {28
"<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>"29
"<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>"29
),30
),30
),31
),32
// Asclepius-ticketlink: opent het ticketvenster (demoticket #4102).33
message(34
"kvt4",35
at(0, 11, 3),36
format!(37
"<p>Ik heb er een ticket van gemaakt: <a href=\"{TICKET}\">#4102 Laptop start niet meer op</a></p>"38
),39
),31
// Alleen de link: de app laat dan alleen het kaartje zien.40
// Alleen de link: de app laat dan alleen het kaartje zien.32
message(41
message(33
"kvt3",42
"kvt3",@@ -45,6 +45,7 @@ pub mod message_actions;
45
45
pub mod notice;
46
46
pub mod notify;
47
47
mod org_actions;
48
pub mod org_emojis;
48
49
pub mod org_watch;
49
50
pub mod outbox;
50
51
pub mod outgoing;
@@ -45,6 +45,7 @@ pub mod message_actions;45
pub mod notice;45
pub mod notice;46
pub mod notify;46
pub mod notify;47
mod org_actions;47
mod org_actions;48
pub mod org_emojis;48
pub mod org_watch;49
pub mod org_watch;49
pub mod outbox;50
pub mod outbox;50
pub mod outgoing;51
pub mod outgoing;@@ -0,0 +1,67 @@
1
use std::sync::Arc;
2
3
use teams_core::OrgEmoji;
4
use tokio::sync::oneshot;
5
6
use crate::backend::Engine;
7
use crate::{demo, runtime};
8
9
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10
pub enum OrgEmojiError {
11
Failed,
12
}
13
14
pub type OrgEmojiList = oneshot::Receiver<Result<Vec<OrgEmoji>, OrgEmojiError>>;
15
16
/// Demo mode answers with fabricated organisation emojis. A live session
17
/// uses the cached CSA catalogue, refreshing when it is older than 30 minutes.
18
pub fn list(engine: Option<Arc<Engine>>, demo_mode: bool, force: bool) -> OrgEmojiList {
19
if demo_mode {
20
return runtime::spawn(async move { Ok(demo::org_emojis()) });
21
}
22
let Some(engine) = engine else {
23
let (sender, receiver) = oneshot::channel();
24
let _ = sender.send(Err(OrgEmojiError::Failed));
25
return receiver;
26
};
27
runtime::spawn(async move {
28
engine
29
.list_org_emojis(force)
30
.await
31
.map_err(|_| OrgEmojiError::Failed)
32
})
33
}
34
35
pub fn filter<'a>(emojis: &'a [OrgEmoji], query: &str) -> Vec<&'a OrgEmoji> {
36
emojis
37
.iter()
38
.filter(|emoji| emoji.matches(query))
39
.collect()
40
}
41
42
#[cfg(test)]
43
mod tests {
44
use super::*;
45
46
#[test]
47
fn demo_catalogue_is_searchable_by_name_and_keyword() {
48
let emojis = crate::demo::org_emojis();
49
assert!(emojis.len() >= 4);
50
assert!(emojis.iter().any(|emoji| emoji.name == "koffie"));
51
assert!(filter(&emojis, "ship").iter().any(|emoji| emoji.name == "ship-it"));
52
assert!(filter(&emojis, "lancering").iter().any(|emoji| emoji.name == "ship-it"));
53
assert!(filter(&emojis, "zzz").is_empty());
54
for emoji in &emojis {
55
assert!(emoji.document_id.starts_with("0-"));
56
let source = emoji.source.as_deref().expect("demo writes a local png");
57
assert!(std::path::Path::new(source).is_file());
58
}
59
let key = format!("koffie;{}", crate::demo::DEMO_ORG_KOFIE_ID);
60
let image = crate::rows::custom_emoji_image(&key).expect("demo koffie");
61
assert_eq!(image.url, crate::demo::org_emoji_demo_url("koffie"));
62
assert!(!image.url.contains("custo"), "{}", image.url);
63
assert_eq!(image.alt.as_deref(), Some("koffie"));
64
let source = crate::demo::org_emoji_source(crate::demo::DEMO_ORG_KOFIE_ID).expect("source");
65
assert!(std::path::Path::new(&source).is_file());
66
}
67
}
@@ -0,0 +1,67 @@1
use std::sync::Arc;2
3
use teams_core::OrgEmoji;4
use tokio::sync::oneshot;5
6
use crate::backend::Engine;7
use crate::{demo, runtime};8
9
#[derive(Debug, Clone, Copy, PartialEq, Eq)]10
pub enum OrgEmojiError {11
Failed,12
}13
14
pub type OrgEmojiList = oneshot::Receiver<Result<Vec<OrgEmoji>, OrgEmojiError>>;15
16
/// Demo mode answers with fabricated organisation emojis. A live session17
/// uses the cached CSA catalogue, refreshing when it is older than 30 minutes.18
pub fn list(engine: Option<Arc<Engine>>, demo_mode: bool, force: bool) -> OrgEmojiList {19
if demo_mode {20
return runtime::spawn(async move { Ok(demo::org_emojis()) });21
}22
let Some(engine) = engine else {23
let (sender, receiver) = oneshot::channel();24
let _ = sender.send(Err(OrgEmojiError::Failed));25
return receiver;26
};27
runtime::spawn(async move {28
engine29
.list_org_emojis(force)30
.await31
.map_err(|_| OrgEmojiError::Failed)32
})33
}34
35
pub fn filter<'a>(emojis: &'a [OrgEmoji], query: &str) -> Vec<&'a OrgEmoji> {36
emojis37
.iter()38
.filter(|emoji| emoji.matches(query))39
.collect()40
}41
42
#[cfg(test)]43
mod tests {44
use super::*;45
46
#[test]47
fn demo_catalogue_is_searchable_by_name_and_keyword() {48
let emojis = crate::demo::org_emojis();49
assert!(emojis.len() >= 4);50
assert!(emojis.iter().any(|emoji| emoji.name == "koffie"));51
assert!(filter(&emojis, "ship").iter().any(|emoji| emoji.name == "ship-it"));52
assert!(filter(&emojis, "lancering").iter().any(|emoji| emoji.name == "ship-it"));53
assert!(filter(&emojis, "zzz").is_empty());54
for emoji in &emojis {55
assert!(emoji.document_id.starts_with("0-"));56
let source = emoji.source.as_deref().expect("demo writes a local png");57
assert!(std::path::Path::new(source).is_file());58
}59
let key = format!("koffie;{}", crate::demo::DEMO_ORG_KOFIE_ID);60
let image = crate::rows::custom_emoji_image(&key).expect("demo koffie");61
assert_eq!(image.url, crate::demo::org_emoji_demo_url("koffie"));62
assert!(!image.url.contains("custo"), "{}", image.url);63
assert_eq!(image.alt.as_deref(), Some("koffie"));64
let source = crate::demo::org_emoji_source(crate::demo::DEMO_ORG_KOFIE_ID).expect("source");65
assert!(std::path::Path::new(&source).is_file());66
}67
}@@ -1,6 +1,6 @@
1
1
use std::fmt::Display;
2
2
3
use app_base::ui_locale::tr_with;
3
use app_base::ui_locale::{tr, tr_with};
4
4
use chrono::{DateTime, Datelike, TimeZone, Utc};
5
5
6
6
use crate::rows::ReactionChip;
@@ -57,7 +57,21 @@ pub fn chip_tooltip(chip: &ReactionChip) -> String {
57
57
.iter()
58
58
.map(|reactor| reactor.name.as_str())
59
59
.collect();
60
tooltip_text(&names)
60
let people = tooltip_text(&names);
61
match emoji_tooltip_name(chip) {
62
Some(name) if people.is_empty() => name,
63
Some(name) => format!("{name}\n{people}"),
64
None => people,
65
}
66
}
67
68
fn emoji_tooltip_name(chip: &ReactionChip) -> Option<String> {
69
chatsvc::custom_emoji_display_name(&chip.reaction_type)
70
.or_else(|| chatsvc::custom_emoji_display_name(&chip.glyph()))
71
.or_else(|| {
72
chatsvc::hides_raw_reaction_key(&chip.reaction_type)
73
.then(|| tr("reaction.custom_emoji"))
74
})
61
75
}
62
76
63
77
pub fn reaction_time_label<Zone>(time: DateTime<Utc>, now: &DateTime<Zone>) -> String
@@ -1,6 +1,6 @@1
use std::fmt::Display;1
use std::fmt::Display;2
2
3
use app_base::ui_locale::tr_with;3
use app_base::ui_locale::{tr, tr_with};4
use chrono::{DateTime, Datelike, TimeZone, Utc};4
use chrono::{DateTime, Datelike, TimeZone, Utc};5
5
6
use crate::rows::ReactionChip;6
use crate::rows::ReactionChip;@@ -57,7 +57,21 @@ pub fn chip_tooltip(chip: &ReactionChip) -> String {57
.iter()57
.iter()58
.map(|reactor| reactor.name.as_str())58
.map(|reactor| reactor.name.as_str())59
.collect();59
.collect();60
tooltip_text(&names)60
let people = tooltip_text(&names);61
match emoji_tooltip_name(chip) {62
Some(name) if people.is_empty() => name,63
Some(name) => format!("{name}\n{people}"),64
None => people,65
}66
}67
68
fn emoji_tooltip_name(chip: &ReactionChip) -> Option<String> {69
chatsvc::custom_emoji_display_name(&chip.reaction_type)70
.or_else(|| chatsvc::custom_emoji_display_name(&chip.glyph()))71
.or_else(|| {72
chatsvc::hides_raw_reaction_key(&chip.reaction_type)73
.then(|| tr("reaction.custom_emoji"))74
})61
}75
}62
76
63
pub fn reaction_time_label<Zone>(time: DateTime<Utc>, now: &DateTime<Zone>) -> String77
pub fn reaction_time_label<Zone>(time: DateTime<Utc>, now: &DateTime<Zone>) -> String@@ -60,10 +60,13 @@ impl ReactionChip {
60
60
61
61
/// Text for places without images: the org emoji's name instead of its raw key.
62
62
pub fn reaction_text(reaction_type: &str) -> String {
63
match chatsvc::custom_emoji(reaction_type) {
64
Some(emoji) => format!(":{}:", emoji.name),
65
None => reaction_glyph(reaction_type),
63
if let Some(name) = chatsvc::custom_emoji_display_name(reaction_type) {
64
return format!(":{name}:");
66
65
}
66
if chatsvc::hides_raw_reaction_key(reaction_type) {
67
return app_base::ui_locale::tr("reaction.custom_emoji");
68
}
69
reaction_glyph(reaction_type)
67
70
}
68
71
69
72
pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {
@@ -72,7 +75,7 @@ pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {
72
75
};
73
76
Some(ImageRef {
74
77
id: emoji.object_id.to_owned(),
75
url: emoji.image_url(),
78
url: crate::demo::org_emoji_image_url(&emoji.object_id).unwrap_or_else(|| emoji.image_url()),
76
79
width: None,
77
80
height: None,
78
81
alt: Some(emoji.name.to_owned()),
@@ -514,6 +517,16 @@ pub fn apply_pending_reactions(
514
517
}
515
518
}
516
519
520
fn visible_reaction_label(reaction_type: &str, shown: &str) -> String {
521
if let Some(name) = chatsvc::custom_emoji_display_name(reaction_type) {
522
return format!(":{name}:");
523
}
524
if chatsvc::hides_raw_reaction_key(reaction_type) || chatsvc::hides_raw_reaction_key(shown) {
525
return String::new();
526
}
527
shown.to_owned()
528
}
529
517
530
pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
518
531
let my_user_id = context.my_user_id.as_deref();
519
532
let mut chips: Vec<ReactionChip> = Vec::new();
@@ -553,7 +566,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<R
553
566
});
554
567
}
555
568
for (chip, shown) in chips.iter_mut().zip(variants) {
556
chip.label = shown.concat();
569
chip.label = visible_reaction_label(&chip.reaction_type, &shown.concat());
557
570
}
558
571
chips
559
572
}
@@ -1411,6 +1424,23 @@ mod tests {
1411
1424
.ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim")
1412
1425
);
1413
1426
assert_eq!(custom_emoji_image("like"), None);
1427
assert_eq!(reaction_text("custom:tsignal"), ":tsignal:");
1428
assert_ne!(reaction_text("custom"), "custom");
1429
let hosted = concat!(
1430
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/",
1431
"aWQ9MC13dWstZDItZjM4MjU3YzBmYmEyZDI5ODFlYzJhMzY4YzVjZjE4NTMsdHlwZT0xLHVybD0=/",
1432
"$value",
1433
);
1434
let from_graph =
1435
chatsvc::custom_reaction_key("custom", Some("tsignal"), Some(hosted), None)
1436
.expect("key");
1437
assert_eq!(reaction_text(&from_graph), ":tsignal:");
1438
let image = custom_emoji_image(&from_graph).expect("graph image");
1439
assert!(
1440
image
1441
.url
1442
.ends_with("/0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853/views/imgt2_anim")
1443
);
1414
1444
}
1415
1445
1416
1446
#[test]
@@ -60,10 +60,13 @@ impl ReactionChip {60
60
61
/// Text for places without images: the org emoji's name instead of its raw key.61
/// Text for places without images: the org emoji's name instead of its raw key.62
pub fn reaction_text(reaction_type: &str) -> String {62
pub fn reaction_text(reaction_type: &str) -> String {63
match chatsvc::custom_emoji(reaction_type) {63
if let Some(name) = chatsvc::custom_emoji_display_name(reaction_type) {64
Some(emoji) => format!(":{}:", emoji.name),64
return format!(":{name}:");65
None => reaction_glyph(reaction_type),66
}65
}66
if chatsvc::hides_raw_reaction_key(reaction_type) {67
return app_base::ui_locale::tr("reaction.custom_emoji");68
}69
reaction_glyph(reaction_type)67
}70
}68
71
69
pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {72
pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {@@ -72,7 +75,7 @@ pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {72
};75
};73
Some(ImageRef {76
Some(ImageRef {74
id: emoji.object_id.to_owned(),77
id: emoji.object_id.to_owned(),75
url: emoji.image_url(),78
url: crate::demo::org_emoji_image_url(&emoji.object_id).unwrap_or_else(|| emoji.image_url()),76
width: None,79
width: None,77
height: None,80
height: None,78
alt: Some(emoji.name.to_owned()),81
alt: Some(emoji.name.to_owned()),@@ -514,6 +517,16 @@ pub fn apply_pending_reactions(514
}517
}515
}518
}516
519
520
fn visible_reaction_label(reaction_type: &str, shown: &str) -> String {521
if let Some(name) = chatsvc::custom_emoji_display_name(reaction_type) {522
return format!(":{name}:");523
}524
if chatsvc::hides_raw_reaction_key(reaction_type) || chatsvc::hides_raw_reaction_key(shown) {525
return String::new();526
}527
shown.to_owned()528
}529
517
pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {530
pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {518
let my_user_id = context.my_user_id.as_deref();531
let my_user_id = context.my_user_id.as_deref();519
let mut chips: Vec<ReactionChip> = Vec::new();532
let mut chips: Vec<ReactionChip> = Vec::new();@@ -553,7 +566,7 @@ pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<R553
});566
});554
}567
}555
for (chip, shown) in chips.iter_mut().zip(variants) {568
for (chip, shown) in chips.iter_mut().zip(variants) {556
chip.label = shown.concat();569
chip.label = visible_reaction_label(&chip.reaction_type, &shown.concat());557
}570
}558
chips571
chips559
}572
}@@ -1411,6 +1424,23 @@ mod tests {1411
.ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim")1424
.ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim")1412
);1425
);1413
assert_eq!(custom_emoji_image("like"), None);1426
assert_eq!(custom_emoji_image("like"), None);1427
assert_eq!(reaction_text("custom:tsignal"), ":tsignal:");1428
assert_ne!(reaction_text("custom"), "custom");1429
let hosted = concat!(1430
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/",1431
"aWQ9MC13dWstZDItZjM4MjU3YzBmYmEyZDI5ODFlYzJhMzY4YzVjZjE4NTMsdHlwZT0xLHVybD0=/",1432
"$value",1433
);1434
let from_graph =1435
chatsvc::custom_reaction_key("custom", Some("tsignal"), Some(hosted), None)1436
.expect("key");1437
assert_eq!(reaction_text(&from_graph), ":tsignal:");1438
let image = custom_emoji_image(&from_graph).expect("graph image");1439
assert!(1440
image1441
.url1442
.ends_with("/0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853/views/imgt2_anim")1443
);1414
}1444
}1415
1445
1416
#[test]1446
#[test]@@ -25,6 +25,7 @@ enum StoredObject {
25
25
Inline,
26
26
Gif(StoredRemote),
27
27
Sticker(StoredRemote),
28
CustomEmoji(StoredRemote),
28
29
}
29
30
30
31
#[derive(Serialize, Deserialize)]
@@ -33,6 +34,8 @@ struct StoredRemote {
33
34
title: String,
34
35
width: u32,
35
36
height: u32,
37
#[serde(default)]
38
object_id: Option<String>,
36
39
}
37
40
38
41
#[derive(Serialize, Deserialize)]
@@ -87,10 +90,15 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
87
90
title: remote.title.clone(),
88
91
width: remote.width,
89
92
height: remote.height,
93
object_id: match &remote.kind {
94
RemoteKind::CustomEmoji { object_id } => Some(object_id.clone()),
95
_ => None,
96
},
90
97
};
91
objects.push(match remote.kind {
98
objects.push(match &remote.kind {
92
99
RemoteKind::Gif => StoredObject::Gif(stored),
93
100
RemoteKind::Sticker => StoredObject::Sticker(stored),
101
RemoteKind::CustomEmoji { .. } => StoredObject::CustomEmoji(stored),
94
102
});
95
103
}
96
104
}
@@ -129,6 +137,12 @@ fn inline_image(stored: &AttachmentImage) -> Option<OutgoingImage> {
129
137
}
130
138
131
139
fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
140
let kind = match kind {
141
RemoteKind::CustomEmoji { .. } => RemoteKind::CustomEmoji {
142
object_id: stored.object_id.unwrap_or_default(),
143
},
144
other => other,
145
};
132
146
OutgoingImage::Remote(RemoteImage {
133
147
kind,
134
148
url: stored.url,
@@ -157,6 +171,10 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
157
171
StoredObject::Inline => inline.next().and_then(inline_image),
158
172
StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),
159
173
StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),
174
StoredObject::CustomEmoji(stored) => {
175
let object_id = stored.object_id.clone().unwrap_or_default();
176
Some(remote_image(RemoteKind::CustomEmoji { object_id }, stored))
177
}
160
178
})
161
179
.collect();
162
180
Some(Outgoing {
@@ -25,6 +25,7 @@ enum StoredObject {25
Inline,25
Inline,26
Gif(StoredRemote),26
Gif(StoredRemote),27
Sticker(StoredRemote),27
Sticker(StoredRemote),28
CustomEmoji(StoredRemote),28
}29
}29
30
30
#[derive(Serialize, Deserialize)]31
#[derive(Serialize, Deserialize)]@@ -33,6 +34,8 @@ struct StoredRemote {33
title: String,34
title: String,34
width: u32,35
width: u32,35
height: u32,36
height: u32,37
#[serde(default)]38
object_id: Option<String>,36
}39
}37
40
38
#[derive(Serialize, Deserialize)]41
#[derive(Serialize, Deserialize)]@@ -87,10 +90,15 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {87
title: remote.title.clone(),90
title: remote.title.clone(),88
width: remote.width,91
width: remote.width,89
height: remote.height,92
height: remote.height,93
object_id: match &remote.kind {94
RemoteKind::CustomEmoji { object_id } => Some(object_id.clone()),95
_ => None,96
},90
};97
};91
objects.push(match remote.kind {98
objects.push(match &remote.kind {92
RemoteKind::Gif => StoredObject::Gif(stored),99
RemoteKind::Gif => StoredObject::Gif(stored),93
RemoteKind::Sticker => StoredObject::Sticker(stored),100
RemoteKind::Sticker => StoredObject::Sticker(stored),101
RemoteKind::CustomEmoji { .. } => StoredObject::CustomEmoji(stored),94
});102
});95
}103
}96
}104
}@@ -129,6 +137,12 @@ fn inline_image(stored: &AttachmentImage) -> Option<OutgoingImage> {129
}137
}130
138
131
fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {139
fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {140
let kind = match kind {141
RemoteKind::CustomEmoji { .. } => RemoteKind::CustomEmoji {142
object_id: stored.object_id.unwrap_or_default(),143
},144
other => other,145
};132
OutgoingImage::Remote(RemoteImage {146
OutgoingImage::Remote(RemoteImage {133
kind,147
kind,134
url: stored.url,148
url: stored.url,@@ -157,6 +171,10 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {157
StoredObject::Inline => inline.next().and_then(inline_image),171
StoredObject::Inline => inline.next().and_then(inline_image),158
StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),172
StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),159
StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),173
StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),174
StoredObject::CustomEmoji(stored) => {175
let object_id = stored.object_id.clone().unwrap_or_default();176
Some(remote_image(RemoteKind::CustomEmoji { object_id }, stored))177
}160
})178
})161
.collect();179
.collect();162
Some(Outgoing {180
Some(Outgoing {@@ -4,7 +4,9 @@ use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};
4
4
5
5
pub const IMAGE_PLACEHOLDER: &str = "[image]";
6
6
pub const CODE_PADDING: &str = "\u{2004}";
7
pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";
7
// Invisible width reservation. Black squares stay visible as dark bars
8
// beside the overlaid image when a color font or missed highlight paints them.
9
pub const EMOJI_PLACEHOLDER: &str = "\u{2003}\u{2003}";
8
10
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];
9
11
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";
10
12
const BASE_FONT_PIXELS: f32 = 14.;
@@ -4,7 +4,9 @@ use teams_core::{FontSize, PROFILE_LINK_PREFIX, Span};4
4
5
pub const IMAGE_PLACEHOLDER: &str = "[image]";5
pub const IMAGE_PLACEHOLDER: &str = "[image]";6
pub const CODE_PADDING: &str = "\u{2004}";6
pub const CODE_PADDING: &str = "\u{2004}";7
pub const EMOJI_PLACEHOLDER: &str = "\u{25a0}\u{25a0}";7
// Invisible width reservation. Black squares stay visible as dark bars8
// beside the overlaid image when a color font or missed highlight paints them.9
pub const EMOJI_PLACEHOLDER: &str = "\u{2003}\u{2003}";8
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];10
const URL_PREFIXES: [&str; 3] = ["https://", "http://", "www."];9
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";11
const TRAILING_PUNCTUATION: &str = ".,;:!?'\"";10
const BASE_FONT_PIXELS: f32 = 14.;12
const BASE_FONT_PIXELS: f32 = 14.;@@ -452,13 +452,6 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
452
452
.into_iter()
453
453
.map(|range| (range, emoji_family.clone())),
454
454
)
455
.chain(
456
inline
457
.segments
458
.iter()
459
.filter(|segment| segment.emoji.is_some())
460
.map(|segment| (segment.range.clone(), emoji_family.clone())),
461
)
462
455
.collect();
463
456
font_overrides.sort_by_key(|(range, _)| range.start);
464
457
let keycaps = keycap_ranges(&inline.text);
@@ -501,11 +494,11 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement
501
494
},
502
495
None => highlight_for(segment.style, own),
503
496
},
504
family: if segment.emoji.is_some() {
505
Some(SharedString::from(theme::EMOJI_FONT_FAMILY))
506
} else {
507
segment.style.code.then(|| mono.clone())
508
},
497
family: segment
498
.style
499
.code
500
.then(|| mono.clone())
501
.filter(|_| segment.emoji.is_none()),
509
502
scale: segment.style.font_scale(),
510
503
raise: segment.style.baseline_raise(),
511
504
})
@@ -452,13 +452,6 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement452
.into_iter()452
.into_iter()453
.map(|range| (range, emoji_family.clone())),453
.map(|range| (range, emoji_family.clone())),454
)454
)455
.chain(456
inline457
.segments458
.iter()459
.filter(|segment| segment.emoji.is_some())460
.map(|segment| (segment.range.clone(), emoji_family.clone())),461
)462
.collect();455
.collect();463
font_overrides.sort_by_key(|(range, _)| range.start);456
font_overrides.sort_by_key(|(range, _)| range.start);464
let keycaps = keycap_ranges(&inline.text);457
let keycaps = keycap_ranges(&inline.text);@@ -501,11 +494,11 @@ fn render_inline(inline: &Inline, id: String, own: bool, cx: &App) -> AnyElement501
},494
},502
None => highlight_for(segment.style, own),495
None => highlight_for(segment.style, own),503
},496
},504
family: if segment.emoji.is_some() {497
family: segment505
Some(SharedString::from(theme::EMOJI_FONT_FAMILY))498
.style506
} else {499
.code507
segment.style.code.then(|| mono.clone())500
.then(|| mono.clone())508
},501
.filter(|_| segment.emoji.is_none()),509
scale: segment.style.font_scale(),502
scale: segment.style.font_scale(),510
raise: segment.style.baseline_raise(),503
raise: segment.style.baseline_raise(),511
})504
})@@ -0,0 +1 @@
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 @@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 @@
1
//! Ponos-bord in het hoofdpaneel: de tegel «Ponos» in de navigatierail, direct
2
//! onder Agents (Tim). Links alle groepen die je in Ponos ziet (eerst
3
//! «Mijn Taken», je persoonlijke groep), rechts het bord met de kolommen van
4
//! Ponos. Taken maken, bewerken, afronden en slepen tussen en binnen kolommen.
5
//!
6
//! Upstream-haken: `views/rail.rs` (tegel), `views/sidebar.rs` (`SidebarTab::Ponos`),
7
//! `views/shell.rs` (hoofdpaneel). Zie KVT-FORK.md.
8
9
use std::collections::HashMap;
10
11
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
12
use gpui_kit::component::scroll::ScrollableElement as _;
13
use gpui_kit::component::{h_flex, v_flex};
14
use gpui_kit::prelude::FluentBuilder as _;
15
use gpui_kit::*;
16
use kvt_sleutels::format::{iso_date_nl, parse_date_input};
17
use kvt_sleutels::ponos::{
18
MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask, STATUS_DONE, STATUSES, TaskInput,
19
apply_move, column, drop_position, group_url, name_from_email,
20
};
21
use kvt_sleutels::{CardsClient, ClientError};
22
23
use super::modal::{primary_button, secondary_button};
24
use super::tasks::{chip, field, label, muted, not_linked, ponos_error};
25
use super::{Link, base_url, forget_token, is_demo, link, notice, open_external, token_and_client};
26
use crate::app_state::AppHandle;
27
use crate::i18n::tr;
28
use crate::runtime;
29
use crate::theme::{self, ElevatedSurface as _};
30
use crate::views::widgets::symbol;
31
32
pub const KVT_BOARD_TAG: &str = "kvt-ponos-board";
33
/// Laatst gekozen groep op het bord (alleen een id, in de lokale opslag).
34
const BOARD_GROUP_META_KEY: &str = "kvt.ponos.board_group";
35
const TITLE_MAX: usize = 200;
36
const HEADER_HEIGHT: f32 = 60.;
37
const PAGE_PADDING: f32 = 20.;
38
const GROUPS_WIDTH: f32 = 240.;
39
const GROUP_ROW_HEIGHT: f32 = 36.;
40
const COLUMN_MIN_WIDTH: f32 = 220.;
41
const COLUMN_GAP: f32 = 12.;
42
const CARD_GAP: f32 = 8.;
43
const RADIUS: f32 = 10.;
44
const EDITOR_WIDTH: f32 = 560.;
45
const BACKDROP_OPACITY: f32 = 0.55;
46
47
#[derive(Clone)]
48
enum Nav {
49
NotLinked,
50
Loading,
51
Loaded(PonosNavigation),
52
Failed(ClientError),
53
}
54
55
#[derive(Clone)]
56
enum Tasks {
57
Loading,
58
Loaded(Vec<PonosTask>),
59
Failed(ClientError),
60
}
61
62
#[derive(Clone)]
63
struct DraggedTask {
64
id: String,
65
title: String,
66
from_status: String,
67
}
68
69
struct TaskGhost {
70
title: String,
71
}
72
73
impl Render for TaskGhost {
74
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
75
div()
76
.w(px(COLUMN_MIN_WIDTH))
77
.px(px(12.))
78
.py(px(10.))
79
.rounded(px(8.))
80
.flyout_surface()
81
.text_size(px(13.))
82
.text_color(theme::text())
83
.truncate()
84
.child(self.title.clone())
85
}
86
}
87
88
struct Editor {
89
/// `None`: nieuwe taak.
90
task: Option<PonosTask>,
91
status: String,
92
assignee: String,
93
target_group: Option<String>,
94
title: Entity<InputState>,
95
description: Entity<TextareaState>,
96
due: Entity<InputState>,
97
saving: bool,
98
error: Option<String>,
99
}
100
101
pub struct PonosBoard {
102
nav: Nav,
103
group: Option<String>,
104
tasks: Tasks,
105
generation: u64,
106
editor: Option<Editor>,
107
/// Alleen `--demo`: verzonnen taken per groep.
108
demo: HashMap<String, Vec<PonosTask>>,
109
}
110
111
/// Het bord als element van het hoofdpaneel (eenmalig aangemaakt).
112
pub fn board_view(cx: &mut App) -> AnyElement {
113
let existing = super::read(cx, |kvt| kvt.board.clone()).flatten();
114
let board = match existing {
115
Some(board) => board,
116
None => {
117
let board = cx.new(PonosBoard::new);
118
if cx.has_global::<super::Kvt>() {
119
cx.global_mut::<super::Kvt>().board = Some(board.clone());
120
}
121
board
122
}
123
};
124
div()
125
.flex_1()
126
.min_w_0()
127
.h_full()
128
.child(board)
129
.into_any_element()
130
}
131
132
/// De tegel is geopend: vers ophalen (bij de eerste keer laadt `new`).
133
pub fn board_opened(cx: &mut App) {
134
if let Some(board) = super::read(cx, |kvt| kvt.board.clone()).flatten() {
135
board.update(cx, |board, cx| board.reload(cx));
136
}
137
}
138
139
/// Na «Taak maken in Ponos» vanuit een bericht.
140
pub(super) fn refresh_board_if_open(cx: &mut App) {
141
board_opened(cx);
142
}
143
144
fn remembered_group(cx: &App) -> Option<String> {
145
let handle = cx.try_global::<AppHandle>()?;
146
handle
147
.0
148
.read(cx)
149
.store
150
.meta(BOARD_GROUP_META_KEY)
151
.ok()
152
.flatten()
153
}
154
155
fn remember_group(group: &str, cx: &App) {
156
if let Some(handle) = cx.try_global::<AppHandle>() {
157
let _ = handle
158
.0
159
.read(cx)
160
.store
161
.set_meta(BOARD_GROUP_META_KEY, group);
162
}
163
}
164
165
/// Gekozen groep als die nog bestaat, anders de eerste (Mijn Taken).
166
fn pick_group(wanted: Option<&str>, navigation: &PonosNavigation) -> Option<String> {
167
wanted
168
.filter(|wanted| navigation.groups.iter().any(|group| group.id == *wanted))
169
.map(str::to_owned)
170
.or_else(|| navigation.groups.first().map(|group| group.id.clone()))
171
}
172
173
fn status_fallback(status: &str) -> String {
174
tr(match status {
175
"in_progress" => "kvt.board_status.in_progress",
176
STATUS_DONE => "kvt.board_status.done",
177
_ => "kvt.board_status.todo",
178
})
179
}
180
181
impl PonosBoard {
182
fn new(cx: &mut Context<Self>) -> Self {
183
let demo = if is_demo(cx) {
184
super::demo::board_tasks()
185
} else {
186
HashMap::new()
187
};
188
let mut board = PonosBoard {
189
nav: Nav::Loading,
190
group: remembered_group(cx),
191
tasks: Tasks::Loading,
192
generation: 0,
193
editor: None,
194
demo,
195
};
196
board.reload(cx);
197
board
198
}
199
200
fn navigation(&self) -> Option<&PonosNavigation> {
201
match &self.nav {
202
Nav::Loaded(navigation) => Some(navigation),
203
_ => None,
204
}
205
}
206
207
fn current_group(&self) -> Option<&PonosGroup> {
208
let group = self.group.as_deref()?;
209
self.navigation()?
210
.groups
211
.iter()
212
.find(|candidate| candidate.id == group)
213
}
214
215
fn user_email(&self) -> String {
216
self.navigation()
217
.map(|navigation| navigation.user_email.clone())
218
.unwrap_or_default()
219
}
220
221
fn status_label(&self, status: &str) -> String {
222
match self.navigation() {
223
Some(navigation) => navigation.status_label(status, || status_fallback(status)),
224
None => status_fallback(status),
225
}
226
}
227
228
// --- laden ------------------------------------------------------------
229
230
fn reload(&mut self, cx: &mut Context<Self>) {
231
self.generation += 1;
232
if is_demo(cx) {
233
let navigation = super::demo::board_navigation(&self.demo);
234
self.group = pick_group(self.group.as_deref(), &navigation);
235
self.tasks = Tasks::Loaded(self.demo_tasks());
236
self.nav = Nav::Loaded(navigation);
237
cx.notify();
238
return;
239
}
240
let Some((token, client)) = token_and_client(cx) else {
241
self.nav = Nav::NotLinked;
242
cx.notify();
243
return;
244
};
245
if !matches!(self.nav, Nav::Loaded(_)) {
246
self.nav = Nav::Loading;
247
}
248
let generation = self.generation;
249
let wanted = self.group.clone();
250
let loading = runtime::spawn(async move {
251
let navigation = client.ponos_navigation(&token).await?;
252
let group = pick_group(wanted.as_deref(), &navigation);
253
let tasks = match &group {
254
Some(group) => client.ponos_tasks(&token, group).await,
255
None => Ok(Vec::new()),
256
};
257
Ok::<_, ClientError>((navigation, group, tasks))
258
});
259
cx.spawn(async move |this, cx| {
260
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
261
cx.update(|cx| {
262
let unauthorized = matches!(&result, Err(ClientError::Unauthorized))
263
|| matches!(&result, Ok((_, _, Err(ClientError::Unauthorized))));
264
if unauthorized {
265
forget_token(cx);
266
}
267
this.update(cx, |this, cx| {
268
if this.generation != generation {
269
return;
270
}
271
match result {
272
Ok((navigation, group, tasks)) => {
273
this.group = group;
274
this.tasks = match tasks {
275
Ok(tasks) => Tasks::Loaded(tasks),
276
Err(error) => Tasks::Failed(error),
277
};
278
this.nav = Nav::Loaded(navigation);
279
}
280
Err(ClientError::Unauthorized) => this.nav = Nav::NotLinked,
281
Err(error) => this.nav = Nav::Failed(error),
282
}
283
cx.notify();
284
})
285
.ok();
286
});
287
})
288
.detach();
289
}
290
291
fn select_group(&mut self, group: String, cx: &mut Context<Self>) {
292
if self.group.as_deref() == Some(group.as_str()) {
293
return;
294
}
295
remember_group(&group, cx);
296
self.group = Some(group);
297
self.tasks = Tasks::Loading;
298
self.editor = None;
299
self.reload(cx);
300
}
301
302
// --- demo -------------------------------------------------------------
303
304
fn demo_tasks(&self) -> Vec<PonosTask> {
305
let Some(group) = self.group.as_deref() else {
306
return Vec::new();
307
};
308
if group == MY_TASKS_GROUP {
309
let mut mine: Vec<PonosTask> = self
310
.demo
311
.values()
312
.flatten()
313
.filter(|task| task.assignee_email == super::demo::BOARD_USER)
314
.cloned()
315
.collect();
316
mine.sort_by(|a, b| a.id.cmp(&b.id));
317
return mine;
318
}
319
self.demo.get(group).cloned().unwrap_or_default()
320
}
321
322
fn demo_task_mut(&mut self, id: &str) -> Option<&mut PonosTask> {
323
self.demo.values_mut().flatten().find(|task| task.id == id)
324
}
325
326
// --- acties -----------------------------------------------------------
327
328
/// Een schrijfactie bij Ponos; daarna altijd opnieuw laden.
329
fn submit<Fut>(
330
&mut self,
331
cx: &mut Context<Self>,
332
done: Option<String>,
333
job: impl FnOnce(String, CardsClient) -> Fut,
334
) where
335
Fut: std::future::Future<Output = Result<(), ClientError>> + Send + 'static,
336
{
337
let Some((token, client)) = token_and_client(cx) else {
338
self.reload(cx);
339
return;
340
};
341
let running = runtime::spawn(job(token, client));
342
cx.spawn(async move |this, cx| {
343
let result = running.await.unwrap_or(Err(ClientError::Unavailable));
344
cx.update(|cx| {
345
match &result {
346
Ok(()) => {
347
if let Some(done) = done {
348
notice(done, cx);
349
}
350
}
351
Err(error) => {
352
if *error == ClientError::Unauthorized {
353
forget_token(cx);
354
}
355
notice(ponos_error(error), cx);
356
}
357
}
358
this.update(cx, |this, cx| {
359
if result.is_ok() {
360
this.editor = None;
361
} else if let Some(editor) = this.editor.as_mut() {
362
editor.saving = false;
363
}
364
this.reload(cx);
365
})
366
.ok();
367
});
368
})
369
.detach();
370
}
371
372
fn drop_task(
373
&mut self,
374
dragged: &DraggedTask,
375
status: &'static str,
376
before: Option<usize>,
377
cx: &mut Context<Self>,
378
) {
379
let Some(group) = self.group.clone() else {
380
return;
381
};
382
let Tasks::Loaded(tasks) = &mut self.tasks else {
383
return;
384
};
385
let position = drop_position(tasks, &dragged.id, status, before);
386
let unchanged = dragged.from_status == status
387
&& column(tasks, status).position(|task| task.id == dragged.id) == Some(position);
388
if unchanged || !apply_move(tasks, &dragged.id, status, position) {
389
return;
390
}
391
cx.notify();
392
let id = dragged.id.clone();
393
if is_demo(cx) {
394
if let Some(task) = self.demo_task_mut(&id) {
395
task.status = status.to_owned();
396
}
397
if group != MY_TASKS_GROUP
398
&& let Some(list) = self.demo.get_mut(&group)
399
{
400
apply_move(list, &id, status, position);
401
}
402
return;
403
}
404
let virtual_group = group == MY_TASKS_GROUP;
405
let status_changed = dragged.from_status != status;
406
if virtual_group && !status_changed {
407
// «Mijn Taken» heeft geen eigen volgorde in Ponos.
408
return;
409
}
410
self.submit(cx, None, move |token, client| async move {
411
if virtual_group {
412
client.ponos_set_status(&token, &group, &id, status).await?;
413
} else {
414
client
415
.ponos_reorder_task(&token, &group, &id, status, position)
416
.await?;
417
}
418
Ok(())
419
});
420
}
421
422
fn open_editor(
423
&mut self,
424
task: Option<PonosTask>,
425
status: &str,
426
window: &mut Window,
427
cx: &mut Context<Self>,
428
) {
429
let (title_text, description_text, due_text) = match &task {
430
Some(task) => (
431
task.title.clone(),
432
task.description.clone(),
433
iso_date_nl(&task.due_date).unwrap_or_default(),
434
),
435
None => Default::default(),
436
};
437
let title = cx.new(|cx| {
438
InputState::new(window, cx)
439
.placeholder(tr("kvt.ponos.title"))
440
.default_value(title_text)
441
});
442
let description = cx.new(|cx| {
443
TextareaState::new(window, cx)
444
.auto_grow(4, 10)
445
.placeholder(tr("kvt.ponos.description"))
446
.default_value(description_text)
447
});
448
let due = cx.new(|cx| {
449
InputState::new(window, cx)
450
.placeholder(tr("kvt.board.due_placeholder"))
451
.default_value(due_text)
452
});
453
title.update(cx, |input, cx| input.focus(window, cx));
454
let assignee = match &task {
455
Some(task) => task.assignee_email.clone(),
456
// Nieuw in «Mijn Taken» kan niet; elders standaard niemand.
457
None => String::new(),
458
};
459
self.editor = Some(Editor {
460
status: task
461
.as_ref()
462
.map_or_else(|| status.to_owned(), |task| task.status.clone()),
463
assignee,
464
target_group: None,
465
task,
466
title,
467
description,
468
due,
469
saving: false,
470
error: None,
471
});
472
cx.notify();
473
}
474
475
fn save_editor(&mut self, cx: &mut Context<Self>) {
476
let Some(group) = self.group.clone() else {
477
return;
478
};
479
let Some(editor) = self.editor.as_mut() else {
480
return;
481
};
482
if editor.saving {
483
return;
484
}
485
let title: String = editor
486
.title
487
.read(cx)
488
.value()
489
.trim()
490
.chars()
491
.take(TITLE_MAX)
492
.collect();
493
let description = editor.description.read(cx).value().trim().to_owned();
494
if title.is_empty() || description.is_empty() {
495
editor.error = Some(tr("kvt.ponos.fill_in"));
496
cx.notify();
497
return;
498
}
499
let Some(due_date) = parse_date_input(&editor.due.read(cx).value()) else {
500
editor.error = Some(tr("kvt.board.bad_date"));
501
cx.notify();
502
return;
503
};
504
let input = TaskInput {
505
title,
506
description,
507
due_date,
508
assignee_email: editor.assignee.clone(),
509
target_group: editor.target_group.clone(),
510
};
511
let status = editor.status.clone();
512
let existing = editor.task.clone();
513
editor.saving = true;
514
editor.error = None;
515
cx.notify();
516
517
if is_demo(cx) {
518
self.save_demo(&group, existing, input, status);
519
self.editor = None;
520
notice(tr("kvt.board.saved"), cx);
521
self.reload(cx);
522
return;
523
}
524
let done = tr(if existing.is_some() {
525
"kvt.board.saved"
526
} else {
527
"kvt.ponos.created"
528
});
529
self.submit(cx, Some(done), move |token, client| async move {
530
match existing {
531
Some(task) => {
532
let saved = client
533
.ponos_update_task(&token, &group, &task.id, &input)
534
.await?;
535
if saved.status != status {
536
let home = input.target_group.as_deref().unwrap_or(&group);
537
client
538
.ponos_set_status(&token, home, &saved.id, &status)
539
.await?;
540
}
541
}
542
None => {
543
let created = client.ponos_create(&token, &group, &input).await?;
544
if created.status != status {
545
client
546
.ponos_set_status(&token, &group, &created.id, &status)
547
.await?;
548
}
549
}
550
}
551
Ok(())
552
});
553
}
554
555
fn save_demo(
556
&mut self,
557
group: &str,
558
existing: Option<PonosTask>,
559
input: TaskInput,
560
status: String,
561
) {
562
match existing {
563
Some(task) => {
564
let home = task.group().to_owned();
565
let Some(list) = self.demo.get_mut(&home) else {
566
return;
567
};
568
let Some(index) = list.iter().position(|other| other.id == task.id) else {
569
return;
570
};
571
let mut updated = list.remove(index);
572
updated.title = input.title;
573
updated.description = input.description;
574
updated.due_date = input.due_date;
575
updated.assignee_email = input.assignee_email;
576
let target = input.target_group.unwrap_or(home.clone());
577
if target == home && updated.status == status {
578
list.insert(index, updated);
579
return;
580
}
581
updated.status = status;
582
updated.group_id = target.clone();
583
updated.home_group_id = target.clone();
584
self.demo.entry(target).or_default().push(updated);
585
}
586
None => {
587
let id = format!(
588
"demo-board-{}",
589
self.demo.values().map(Vec::len).sum::<usize>() + 1
590
);
591
let task = PonosTask {
592
id,
593
group_id: group.to_owned(),
594
home_group_id: group.to_owned(),
595
title: input.title,
596
status,
597
due_date: input.due_date,
598
description: input.description,
599
assignee_email: input.assignee_email,
600
..super::demo::empty_task()
601
};
602
self.demo.entry(group.to_owned()).or_default().push(task);
603
}
604
}
605
}
606
607
fn complete_from_editor(&mut self, cx: &mut Context<Self>) {
608
let Some(group) = self.group.clone() else {
609
return;
610
};
611
let Some(task) = self.editor.as_ref().and_then(|editor| editor.task.clone()) else {
612
return;
613
};
614
if is_demo(cx) {
615
if let Some(demo) = self.demo_task_mut(&task.id) {
616
demo.status = STATUS_DONE.to_owned();
617
}
618
self.editor = None;
619
notice(tr("kvt.tasks.completed"), cx);
620
self.reload(cx);
621
return;
622
}
623
if let Some(editor) = self.editor.as_mut() {
624
editor.saving = true;
625
}
626
self.submit(
627
cx,
628
Some(tr("kvt.tasks.completed")),
629
move |token, client| async move {
630
client.ponos_complete_task(&token, &group, &task.id).await
631
},
632
);
633
}
634
635
// --- weergave ---------------------------------------------------------
636
637
fn groups_list(&self, cx: &mut Context<Self>) -> AnyElement {
638
let Some(navigation) = self.navigation() else {
639
return div().into_any_element();
640
};
641
v_flex()
642
.id("kvt-board-groups")
643
.w(px(GROUPS_WIDTH))
644
.h_full()
645
.flex_none()
646
.p(px(8.))
647
.gap(px(2.))
648
.border_r_1()
649
.border_color(theme::border())
650
.overflow_y_scrollbar()
651
.children(navigation.groups.iter().enumerate().map(|(index, group)| {
652
let selected = self.group.as_deref() == Some(group.id.as_str());
653
let id = group.id.clone();
654
h_flex()
655
.id(ElementId::Name(format!("kvt-board-group-{index}").into()))
656
.w_full()
657
.h(px(GROUP_ROW_HEIGHT))
658
.flex_none()
659
.px(px(10.))
660
.gap(px(8.))
661
.items_center()
662
.rounded(px(6.))
663
.cursor_pointer()
664
.text_size(px(13.))
665
.map(|row| {
666
if selected {
667
row.bg(theme::selection())
668
.text_color(theme::text_strong())
669
.font_weight(FontWeight::SEMIBOLD)
670
} else {
671
row.text_color(theme::text())
672
.hover(|row| row.bg(theme::row_hover()))
673
}
674
})
675
.on_click(cx.listener(move |this, _, _, cx| this.select_group(id.clone(), cx)))
676
.child(symbol(
677
if group.is_virtual { "person" } else { "group" },
678
16.,
679
if selected {
680
theme::accent_text()
681
} else {
682
theme::text_muted()
683
},
684
))
685
.child(
686
div()
687
.flex_1()
688
.min_w_0()
689
.truncate()
690
.child(group.name.clone()),
691
)
692
.when(group.task_count > 0, |row| {
693
row.child(
694
div()
695
.flex_none()
696
.text_size(px(12.))
697
.text_color(theme::text_muted())
698
.child(group.task_count.to_string()),
699
)
700
})
701
}))
702
.into_any_element()
703
}
704
705
fn header(&self, cx: &mut Context<Self>) -> Div {
706
let group = self.current_group();
707
let title = group.map_or_else(|| tr("kvt.board.title"), |group| group.name.clone());
708
let can_create = group.is_some_and(PonosGroup::accepts_new_tasks)
709
&& matches!(self.tasks, Tasks::Loaded(_));
710
let url = match self.group.as_deref() {
711
Some(group) => group_url(&base_url(), group),
712
None => format!("{}/ponos/", base_url()),
713
};
714
h_flex()
715
.h(px(HEADER_HEIGHT))
716
.flex_none()
717
.px(px(PAGE_PADDING))
718
.gap(px(8.))
719
.items_center()
720
.child(
721
div()
722
.flex_1()
723
.min_w_0()
724
.truncate()
725
.text_size(px(16.))
726
.font_weight(FontWeight::BOLD)
727
.text_color(theme::text())
728
.child(title),
729
)
730
.when(can_create, |row| {
731
row.child(
732
primary_button("kvt-board-new", tr("kvt.board.new_task")).on_click(
733
cx.listener(|this, _, window, cx| {
734
this.open_editor(None, STATUSES[0], window, cx)
735
}),
736
),
737
)
738
})
739
.child(
740
secondary_button("kvt-board-refresh", "refresh", tr("kvt.card.refresh"))
741
.on_click(cx.listener(|this, _, _, cx| this.reload(cx))),
742
)
743
.child(
744
secondary_button("kvt-board-open", "open_in_new", tr("kvt.tasks.open_ponos"))
745
.on_click(move |_, _, cx| open_external(&url, cx)),
746
)
747
}
748
749
fn columns(&self, cx: &mut Context<Self>) -> AnyElement {
750
let tasks = match &self.tasks {
751
Tasks::Loading => {
752
return muted(tr("kvt.card.loading"))
753
.px(px(PAGE_PADDING))
754
.into_any_element();
755
}
756
Tasks::Failed(error) => {
757
return muted(ponos_error(error))
758
.px(px(PAGE_PADDING))
759
.into_any_element();
760
}
761
Tasks::Loaded(tasks) => tasks,
762
};
763
let group = self.current_group();
764
let editable = group.is_some_and(PonosGroup::editable);
765
let can_create = group.is_some_and(PonosGroup::accepts_new_tasks);
766
let me = self.user_email();
767
h_flex()
768
.id("kvt-board-columns")
769
.flex_1()
770
.min_h_0()
771
.w_full()
772
.px(px(PAGE_PADDING))
773
.pb(px(PAGE_PADDING))
774
.gap(px(COLUMN_GAP))
775
.items_start()
776
.overflow_x_scrollbar()
777
.children(
778
STATUSES
779
.iter()
780
.map(|&status| self.column(tasks, status, editable, can_create, &me, cx)),
781
)
782
.into_any_element()
783
}
784
785
fn column(
786
&self,
787
tasks: &[PonosTask],
788
status: &'static str,
789
editable: bool,
790
can_create: bool,
791
me: &str,
792
cx: &mut Context<Self>,
793
) -> AnyElement {
794
let cards: Vec<&PonosTask> = column(tasks, status).collect();
795
let today = chrono::Local::now().format("%Y-%m-%d").to_string();
796
let dot = match status {
797
"in_progress" => theme::accent(),
798
STATUS_DONE => theme::green(),
799
_ => theme::text_faint(),
800
};
801
v_flex()
802
.id(ElementId::Name(format!("kvt-board-column-{status}").into()))
803
.debug_selector(move || format!("kvt-board/column/{status}"))
804
.flex_1()
805
.min_w(px(COLUMN_MIN_WIDTH))
806
.h_full()
807
.p(px(10.))
808
.gap(px(CARD_GAP))
809
.rounded(px(RADIUS))
810
.bg(theme::surface())
811
.drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background()))
812
.on_drop(cx.listener(move |this, dragged: &DraggedTask, _, cx| {
813
this.drop_task(dragged, status, None, cx)
814
}))
815
.child(
816
h_flex()
817
.w_full()
818
.h(px(28.))
819
.flex_none()
820
.gap(px(8.))
821
.items_center()
822
.child(div().size(px(8.)).flex_none().rounded_full().bg(dot))
823
.child(
824
div()
825
.flex_1()
826
.min_w_0()
827
.truncate()
828
.text_size(px(13.))
829
.font_weight(FontWeight::SEMIBOLD)
830
.text_color(theme::text())
831
.child(self.status_label(status)),
832
)
833
.child(
834
div()
835
.text_size(px(12.))
836
.text_color(theme::text_muted())
837
.child(cards.len().to_string()),
838
)
839
.when(can_create, |row| {
840
row.child(
841
div()
842
.id(ElementId::Name(format!("kvt-board-add-{status}").into()))
843
.size(px(24.))
844
.flex_none()
845
.flex()
846
.items_center()
847
.justify_center()
848
.rounded_full()
849
.cursor_pointer()
850
.hover(|button| button.bg(theme::row_hover()))
851
.on_click(cx.listener(move |this, _, window, cx| {
852
this.open_editor(None, status, window, cx)
853
}))
854
.child(symbol("add", 16., theme::text_muted())),
855
)
856
}),
857
)
858
.child(
859
v_flex()
860
.id(ElementId::Name(format!("kvt-board-cards-{status}").into()))
861
.w_full()
862
.flex_1()
863
.min_h(px(80.))
864
.gap(px(CARD_GAP))
865
.overflow_y_scrollbar()
866
.when(cards.is_empty(), |list| {
867
list.child(
868
div()
869
.w_full()
870
.py(px(16.))
871
.text_center()
872
.text_size(px(12.))
873
.text_color(theme::text_faint())
874
.child(tr("kvt.board.empty_column")),
875
)
876
})
877
.children(cards.iter().enumerate().map(|(index, task)| {
878
self.card(task, status, index, editable, me, &today, cx)
879
})),
880
)
881
.into_any_element()
882
}
883
884
#[allow(clippy::too_many_arguments)]
885
fn card(
886
&self,
887
task: &PonosTask,
888
status: &'static str,
889
index: usize,
890
editable: bool,
891
me: &str,
892
today: &str,
893
cx: &mut Context<Self>,
894
) -> AnyElement {
895
let movable = editable && task.can_edit;
896
let overdue =
897
status != STATUS_DONE && !task.due_date.is_empty() && task.due_date.as_str() < today;
898
let due = iso_date_nl(&task.due_date);
899
let assignee = if task.assignee_email.is_empty() {
900
None
901
} else if task.assignee_email.eq_ignore_ascii_case(me) {
902
Some(tr("kvt.board.assignee_me"))
903
} else {
904
Some(name_from_email(&task.assignee_email))
905
};
906
let in_my_tasks = self.group.as_deref() == Some(MY_TASKS_GROUP);
907
let open = task.clone();
908
let dragged = DraggedTask {
909
id: task.id.clone(),
910
title: task.title.clone(),
911
from_status: task.status.clone(),
912
};
913
v_flex()
914
.id(ElementId::Name(
915
format!("kvt-board-card-{}", task.id).into(),
916
))
917
.w_full()
918
.flex_none()
919
.px(px(12.))
920
.py(px(10.))
921
.gap(px(6.))
922
.rounded(px(8.))
923
.bg(theme::surface_raised())
924
.cursor_pointer()
925
.hover(|card| card.bg(theme::popup_hover()))
926
.on_click(cx.listener(move |this, _, window, cx| {
927
this.open_editor(Some(open.clone()), &open.status, window, cx)
928
}))
929
.when(movable, |card| {
930
card.on_drag(dragged, |dragged, _, _, cx| {
931
let title = dragged.title.clone();
932
cx.new(|_| TaskGhost { title })
933
})
934
.drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background()))
935
.on_drop(cx.listener(
936
move |this, dragged: &DraggedTask, _, cx| {
937
cx.stop_propagation();
938
this.drop_task(dragged, status, Some(index), cx)
939
},
940
))
941
})
942
.when(in_my_tasks && !task.home_group_name.is_empty(), |card| {
943
card.child(
944
div()
945
.truncate()
946
.text_size(px(11.))
947
.text_color(theme::text_muted())
948
.child(task.home_group_name.clone()),
949
)
950
})
951
.child(
952
div()
953
.text_size(px(13.))
954
.line_height(px(18.))
955
.text_color(if status == STATUS_DONE {
956
theme::text_muted()
957
} else {
958
theme::text()
959
})
960
.when(status == STATUS_DONE, |text| text.line_through())
961
.child(task.title.clone()),
962
)
963
.child(
964
h_flex()
965
.w_full()
966
.flex_wrap()
967
.gap(px(8.))
968
.items_center()
969
.text_size(px(11.))
970
.text_color(theme::text_muted())
971
.when(!task.category_label.is_empty(), |row| {
972
row.child(
973
div()
974
.px(px(6.))
975
.py(px(1.))
976
.rounded(px(4.))
977
.bg(theme::selection())
978
.text_color(theme::text_strong())
979
.child(task.category_label.clone()),
980
)
981
})
982
.children(due.map(|due| {
983
h_flex()
984
.gap(px(3.))
985
.items_center()
986
.text_color(if overdue {
987
theme::red_soft()
988
} else {
989
theme::text_muted()
990
})
991
.child(symbol(
992
"event",
993
12.,
994
if overdue {
995
theme::red_soft()
996
} else {
997
theme::text_muted()
998
},
999
))
1000
.child(due)
1001
}))
1002
.when(task.checklist_total > 0, |row| {
1003
row.child(
1004
h_flex()
1005
.gap(px(3.))
1006
.items_center()
1007
.child(symbol("check", 12., theme::text_muted()))
1008
.child(format!("{}/{}", task.checklist_done, task.checklist_total)),
1009
)
1010
})
1011
.children(assignee.map(|assignee| {
1012
h_flex()
1013
.gap(px(3.))
1014
.items_center()
1015
.child(symbol("person", 12., theme::text_muted()))
1016
.child(assignee)
1017
})),
1018
)
1019
.into_any_element()
1020
}
1021
1022
fn editor_layer(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1023
let editor = self.editor.as_ref()?;
1024
let navigation = self.navigation()?;
1025
let me = navigation.user_email.clone();
1026
let existing = editor.task.clone();
1027
let editable = existing.as_ref().is_none_or(|task| task.can_edit);
1028
let home = existing
1029
.as_ref()
1030
.map(|task| task.group().to_owned())
1031
.or_else(|| self.group.clone())
1032
.unwrap_or_default();
1033
let target = editor.target_group.clone().unwrap_or_else(|| home.clone());
1034
let title = tr(if existing.is_some() {
1035
"kvt.board.edit_task"
1036
} else {
1037
"kvt.ponos.dialog_title"
1038
});
1039
let detail = existing
1040
.as_ref()
1041
.filter(|task| !task.home_group_name.is_empty())
1042
.map(|task| task.home_group_name.clone())
1043
.unwrap_or_default();
1044
let url = existing.as_ref().map(|task| task.url(&base_url()));
1045
let move_groups: Vec<PonosGroup> = navigation
1046
.groups
1047
.iter()
1048
.filter(|group| !group.is_virtual && group.has_task_access)
1049
.cloned()
1050
.collect();
1051
let other_assignee = (!editor.assignee.is_empty()
1052
&& !editor.assignee.eq_ignore_ascii_case(&me))
1053
.then(|| name_from_email(&editor.assignee));
1054
let assignee_is_me = !me.is_empty() && editor.assignee.eq_ignore_ascii_case(&me);
1055
1056
let status_chips =
1057
h_flex()
1058
.w_full()
1059
.flex_wrap()
1060
.gap(px(6.))
1061
.children(STATUSES.iter().enumerate().map(|(index, &status)| {
1062
chip(
1063
format!("kvt-board-status-{index}").into(),
1064
self.status_label(status),
1065
editor.status == status,
1066
)
1067
.on_click(cx.listener(move |this, _, _, cx| {
1068
if let Some(editor) = this.editor.as_mut() {
1069
editor.status = status.to_owned();
1070
cx.notify();
1071
}
1072
}))
1073
}));
1074
let assignee_chips = h_flex()
1075
.w_full()
1076
.flex_wrap()
1077
.gap(px(6.))
1078
.child(
1079
chip(
1080
"kvt-board-assignee-none".into(),
1081
tr("kvt.board.assignee_none"),
1082
editor.assignee.is_empty(),
1083
)
1084
.on_click(cx.listener(|this, _, _, cx| {
1085
if let Some(editor) = this.editor.as_mut() {
1086
editor.assignee.clear();
1087
cx.notify();
1088
}
1089
})),
1090
)
1091
.when(!me.is_empty(), |row| {
1092
let me = me.clone();
1093
row.child(
1094
chip(
1095
"kvt-board-assignee-me".into(),
1096
tr("kvt.board.assignee_me"),
1097
assignee_is_me,
1098
)
1099
.on_click(cx.listener(move |this, _, _, cx| {
1100
if let Some(editor) = this.editor.as_mut() {
1101
editor.assignee = me.clone();
1102
cx.notify();
1103
}
1104
})),
1105
)
1106
})
1107
.children(
1108
other_assignee.map(|name| chip("kvt-board-assignee-other".into(), name, true)),
1109
);
1110
let group_chips =
1111
(existing.is_some() && move_groups.len() > 1).then(|| {
1112
h_flex().w_full().flex_wrap().gap(px(6.)).children(
1113
move_groups.iter().enumerate().map(|(index, group)| {
1114
let id = group.id.clone();
1115
let home = home.clone();
1116
chip(
1117
format!("kvt-board-move-{index}").into(),
1118
group.name.clone(),
1119
group.id == target,
1120
)
1121
.on_click(cx.listener(move |this, _, _, cx| {
1122
if let Some(editor) = this.editor.as_mut() {
1123
editor.target_group = (id != home).then(|| id.clone());
1124
cx.notify();
1125
}
1126
}))
1127
}),
1128
)
1129
});
1130
let can_complete = existing
1131
.as_ref()
1132
.is_some_and(|task| task.status != STATUS_DONE && task.can_edit);
1133
1134
let panel = v_flex()
1135
.debug_selector(|| "kvt-board-editor".into())
1136
.w(px(EDITOR_WIDTH))
1137
.max_w(relative(1.))
1138
.max_h(relative(0.92))
1139
.m(px(32.))
1140
.p(px(16.))
1141
.gap(px(10.))
1142
.rounded(px(RADIUS))
1143
.dialog_surface()
1144
.text_color(theme::text())
1145
.occlude()
1146
.child(
1147
h_flex()
1148
.w_full()
1149
.items_center()
1150
.gap(px(12.))
1151
.child(
1152
v_flex()
1153
.flex_1()
1154
.min_w_0()
1155
.child(
1156
div()
1157
.text_size(px(15.))
1158
.font_weight(FontWeight::SEMIBOLD)
1159
.child(title),
1160
)
1161
.when(!detail.is_empty(), |column| {
1162
column.child(
1163
div()
1164
.truncate()
1165
.text_size(px(12.))
1166
.text_color(theme::text_muted())
1167
.child(detail),
1168
)
1169
}),
1170
)
1171
.child(
1172
div()
1173
.id("kvt-board-editor-close")
1174
.size(px(28.))
1175
.flex_none()
1176
.flex()
1177
.items_center()
1178
.justify_center()
1179
.rounded_full()
1180
.cursor_pointer()
1181
.hover(|button| button.bg(theme::popup_hover()))
1182
.on_click(cx.listener(|this, _, _, cx| {
1183
this.editor = None;
1184
cx.notify();
1185
}))
1186
.child(symbol("close", 16., theme::text_muted())),
1187
),
1188
)
1189
.child(label(tr("kvt.ponos.title")))
1190
.child(
1191
field().child(
1192
div()
1193
.flex_1()
1194
.child(Input::new(&editor.title).appearance(false).bordered(false)),
1195
),
1196
)
1197
.child(label(tr("kvt.ponos.description")))
1198
.child(Textarea::new(&editor.description))
1199
.child(label(tr("kvt.board.status")))
1200
.child(status_chips)
1201
.child(label(tr("kvt.board.due")))
1202
.child(
1203
field().child(
1204
div()
1205
.flex_1()
1206
.child(Input::new(&editor.due).appearance(false).bordered(false)),
1207
),
1208
)
1209
.child(label(tr("kvt.board.assignee")))
1210
.child(assignee_chips)
1211
.when_some(group_chips, |panel, chips| {
1212
panel.child(label(tr("kvt.ponos.group"))).child(chips)
1213
})
1214
.children(editor.error.clone().map(|error| {
1215
div()
1216
.text_size(px(13.))
1217
.text_color(theme::red_soft())
1218
.child(error)
1219
}))
1220
.child(
1221
h_flex()
1222
.w_full()
1223
.gap(px(8.))
1224
.items_center()
1225
.children(url.map(|url| {
1226
secondary_button(
1227
"kvt-board-editor-open",
1228
"open_in_new",
1229
tr("kvt.tasks.open_ponos"),
1230
)
1231
.on_click(move |_, _, cx| open_external(&url, cx))
1232
}))
1233
.child(div().flex_1())
1234
.when(can_complete, |row| {
1235
row.child(
1236
secondary_button(
1237
"kvt-board-complete",
1238
"check_circle",
1239
tr("kvt.board.complete"),
1240
)
1241
.on_click(cx.listener(|this, _, _, cx| this.complete_from_editor(cx))),
1242
)
1243
})
1244
.child(
1245
secondary_button("kvt-board-cancel", "close", tr("common.cancel"))
1246
.on_click(cx.listener(|this, _, _, cx| {
1247
this.editor = None;
1248
cx.notify();
1249
})),
1250
)
1251
.when(editable, |row| {
1252
row.child(
1253
primary_button(
1254
"kvt-board-save",
1255
tr(if editor.saving {
1256
"kvt.ponos.saving"
1257
} else {
1258
"kvt.board.save"
1259
}),
1260
)
1261
.on_click(cx.listener(|this, _, _, cx| this.save_editor(cx))),
1262
)
1263
}),
1264
);
1265
Some(
1266
div()
1267
.id("kvt-board-editor-layer")
1268
.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
1269
if event.keystroke.key == "escape" {
1270
cx.stop_propagation();
1271
this.editor = None;
1272
cx.notify();
1273
}
1274
}))
1275
.absolute()
1276
.top_0()
1277
.left_0()
1278
.size_full()
1279
.flex()
1280
.items_center()
1281
.justify_center()
1282
.child(
1283
div()
1284
.id("kvt-board-editor-backdrop")
1285
.absolute()
1286
.top_0()
1287
.left_0()
1288
.size_full()
1289
.bg(black().opacity(BACKDROP_OPACITY))
1290
.occlude()
1291
.on_click(cx.listener(|this, _, _, cx| {
1292
this.editor = None;
1293
cx.notify();
1294
})),
1295
)
1296
.child(panel)
1297
.into_any_element(),
1298
)
1299
}
1300
}
1301
1302
impl Render for PonosBoard {
1303
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1304
let linked = matches!(link(cx), Link::Linked(_));
1305
if !linked && !is_demo(cx) {
1306
// Ontkoppeld: na opnieuw koppelen vers laden, niets van de oude token tonen.
1307
self.nav = Nav::NotLinked;
1308
self.editor = None;
1309
} else if matches!(self.nav, Nav::NotLinked) {
1310
self.reload(cx);
1311
}
1312
let body = match (&self.nav, linked) {
1313
(_, false) => v_flex()
1314
.p(px(PAGE_PADDING))
1315
.max_w(px(EDITOR_WIDTH))
1316
.child(not_linked())
1317
.into_any_element(),
1318
(Nav::NotLinked | Nav::Loading, _) => muted(tr("kvt.card.loading"))
1319
.px(px(PAGE_PADDING))
1320
.into_any_element(),
1321
(Nav::Failed(error), _) => muted(ponos_error(error))
1322
.px(px(PAGE_PADDING))
1323
.into_any_element(),
1324
(Nav::Loaded(_), _) => h_flex()
1325
.flex_1()
1326
.min_h_0()
1327
.w_full()
1328
.child(self.groups_list(cx))
1329
.child(
1330
v_flex()
1331
.flex_1()
1332
.min_w_0()
1333
.h_full()
1334
.child(self.header(cx))
1335
.child(self.columns(cx)),
1336
)
1337
.into_any_element(),
1338
};
1339
let page_title = (!matches!(self.nav, Nav::Loaded(_)) || !linked).then(|| {
1340
h_flex()
1341
.h(px(HEADER_HEIGHT))
1342
.flex_none()
1343
.px(px(PAGE_PADDING))
1344
.items_center()
1345
.child(
1346
div()
1347
.text_size(px(16.))
1348
.font_weight(FontWeight::BOLD)
1349
.text_color(theme::text())
1350
.child(tr("kvt.board.title")),
1351
)
1352
});
1353
v_flex()
1354
.debug_selector(|| KVT_BOARD_TAG.into())
1355
.relative()
1356
.size_full()
1357
.rounded(px(RADIUS))
1358
.bg(theme::surface())
1359
.overflow_hidden()
1360
.children(page_title)
1361
.child(body)
1362
.children(self.editor_layer(cx))
1363
}
1364
}
1365
1366
#[cfg(test)]
1367
mod tests {
1368
use super::pick_group;
1369
use kvt_sleutels::ponos::{PonosGroup, PonosNavigation};
1370
1371
fn group(id: &str) -> PonosGroup {
1372
PonosGroup {
1373
id: id.to_owned(),
1374
name: id.to_owned(),
1375
is_virtual: false,
1376
can_create_tasks: true,
1377
has_task_access: true,
1378
task_count: 0,
1379
}
1380
}
1381
1382
#[test]
1383
fn remembered_group_wins_when_it_still_exists() {
1384
let navigation = PonosNavigation {
1385
groups: vec![group("__my_tasks__"), group("g1")],
1386
..Default::default()
1387
};
1388
assert_eq!(pick_group(Some("g1"), &navigation).as_deref(), Some("g1"));
1389
assert_eq!(
1390
pick_group(Some("weg"), &navigation).as_deref(),
1391
Some("__my_tasks__")
1392
);
1393
assert_eq!(pick_group(None, &PonosNavigation::default()), None);
1394
}
1395
}
@@ -0,0 +1,1395 @@1
//! Ponos-bord in het hoofdpaneel: de tegel «Ponos» in de navigatierail, direct2
//! onder Agents (Tim). Links alle groepen die je in Ponos ziet (eerst3
//! «Mijn Taken», je persoonlijke groep), rechts het bord met de kolommen van4
//! Ponos. Taken maken, bewerken, afronden en slepen tussen en binnen kolommen.5
//!6
//! Upstream-haken: `views/rail.rs` (tegel), `views/sidebar.rs` (`SidebarTab::Ponos`),7
//! `views/shell.rs` (hoofdpaneel). Zie KVT-FORK.md.8
9
use std::collections::HashMap;10
11
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};12
use gpui_kit::component::scroll::ScrollableElement as _;13
use gpui_kit::component::{h_flex, v_flex};14
use gpui_kit::prelude::FluentBuilder as _;15
use gpui_kit::*;16
use kvt_sleutels::format::{iso_date_nl, parse_date_input};17
use kvt_sleutels::ponos::{18
MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask, STATUS_DONE, STATUSES, TaskInput,19
apply_move, column, drop_position, group_url, name_from_email,20
};21
use kvt_sleutels::{CardsClient, ClientError};22
23
use super::modal::{primary_button, secondary_button};24
use super::tasks::{chip, field, label, muted, not_linked, ponos_error};25
use super::{Link, base_url, forget_token, is_demo, link, notice, open_external, token_and_client};26
use crate::app_state::AppHandle;27
use crate::i18n::tr;28
use crate::runtime;29
use crate::theme::{self, ElevatedSurface as _};30
use crate::views::widgets::symbol;31
32
pub const KVT_BOARD_TAG: &str = "kvt-ponos-board";33
/// Laatst gekozen groep op het bord (alleen een id, in de lokale opslag).34
const BOARD_GROUP_META_KEY: &str = "kvt.ponos.board_group";35
const TITLE_MAX: usize = 200;36
const HEADER_HEIGHT: f32 = 60.;37
const PAGE_PADDING: f32 = 20.;38
const GROUPS_WIDTH: f32 = 240.;39
const GROUP_ROW_HEIGHT: f32 = 36.;40
const COLUMN_MIN_WIDTH: f32 = 220.;41
const COLUMN_GAP: f32 = 12.;42
const CARD_GAP: f32 = 8.;43
const RADIUS: f32 = 10.;44
const EDITOR_WIDTH: f32 = 560.;45
const BACKDROP_OPACITY: f32 = 0.55;46
47
#[derive(Clone)]48
enum Nav {49
NotLinked,50
Loading,51
Loaded(PonosNavigation),52
Failed(ClientError),53
}54
55
#[derive(Clone)]56
enum Tasks {57
Loading,58
Loaded(Vec<PonosTask>),59
Failed(ClientError),60
}61
62
#[derive(Clone)]63
struct DraggedTask {64
id: String,65
title: String,66
from_status: String,67
}68
69
struct TaskGhost {70
title: String,71
}72
73
impl Render for TaskGhost {74
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {75
div()76
.w(px(COLUMN_MIN_WIDTH))77
.px(px(12.))78
.py(px(10.))79
.rounded(px(8.))80
.flyout_surface()81
.text_size(px(13.))82
.text_color(theme::text())83
.truncate()84
.child(self.title.clone())85
}86
}87
88
struct Editor {89
/// `None`: nieuwe taak.90
task: Option<PonosTask>,91
status: String,92
assignee: String,93
target_group: Option<String>,94
title: Entity<InputState>,95
description: Entity<TextareaState>,96
due: Entity<InputState>,97
saving: bool,98
error: Option<String>,99
}100
101
pub struct PonosBoard {102
nav: Nav,103
group: Option<String>,104
tasks: Tasks,105
generation: u64,106
editor: Option<Editor>,107
/// Alleen `--demo`: verzonnen taken per groep.108
demo: HashMap<String, Vec<PonosTask>>,109
}110
111
/// Het bord als element van het hoofdpaneel (eenmalig aangemaakt).112
pub fn board_view(cx: &mut App) -> AnyElement {113
let existing = super::read(cx, |kvt| kvt.board.clone()).flatten();114
let board = match existing {115
Some(board) => board,116
None => {117
let board = cx.new(PonosBoard::new);118
if cx.has_global::<super::Kvt>() {119
cx.global_mut::<super::Kvt>().board = Some(board.clone());120
}121
board122
}123
};124
div()125
.flex_1()126
.min_w_0()127
.h_full()128
.child(board)129
.into_any_element()130
}131
132
/// De tegel is geopend: vers ophalen (bij de eerste keer laadt `new`).133
pub fn board_opened(cx: &mut App) {134
if let Some(board) = super::read(cx, |kvt| kvt.board.clone()).flatten() {135
board.update(cx, |board, cx| board.reload(cx));136
}137
}138
139
/// Na «Taak maken in Ponos» vanuit een bericht.140
pub(super) fn refresh_board_if_open(cx: &mut App) {141
board_opened(cx);142
}143
144
fn remembered_group(cx: &App) -> Option<String> {145
let handle = cx.try_global::<AppHandle>()?;146
handle147
.0148
.read(cx)149
.store150
.meta(BOARD_GROUP_META_KEY)151
.ok()152
.flatten()153
}154
155
fn remember_group(group: &str, cx: &App) {156
if let Some(handle) = cx.try_global::<AppHandle>() {157
let _ = handle158
.0159
.read(cx)160
.store161
.set_meta(BOARD_GROUP_META_KEY, group);162
}163
}164
165
/// Gekozen groep als die nog bestaat, anders de eerste (Mijn Taken).166
fn pick_group(wanted: Option<&str>, navigation: &PonosNavigation) -> Option<String> {167
wanted168
.filter(|wanted| navigation.groups.iter().any(|group| group.id == *wanted))169
.map(str::to_owned)170
.or_else(|| navigation.groups.first().map(|group| group.id.clone()))171
}172
173
fn status_fallback(status: &str) -> String {174
tr(match status {175
"in_progress" => "kvt.board_status.in_progress",176
STATUS_DONE => "kvt.board_status.done",177
_ => "kvt.board_status.todo",178
})179
}180
181
impl PonosBoard {182
fn new(cx: &mut Context<Self>) -> Self {183
let demo = if is_demo(cx) {184
super::demo::board_tasks()185
} else {186
HashMap::new()187
};188
let mut board = PonosBoard {189
nav: Nav::Loading,190
group: remembered_group(cx),191
tasks: Tasks::Loading,192
generation: 0,193
editor: None,194
demo,195
};196
board.reload(cx);197
board198
}199
200
fn navigation(&self) -> Option<&PonosNavigation> {201
match &self.nav {202
Nav::Loaded(navigation) => Some(navigation),203
_ => None,204
}205
}206
207
fn current_group(&self) -> Option<&PonosGroup> {208
let group = self.group.as_deref()?;209
self.navigation()?210
.groups211
.iter()212
.find(|candidate| candidate.id == group)213
}214
215
fn user_email(&self) -> String {216
self.navigation()217
.map(|navigation| navigation.user_email.clone())218
.unwrap_or_default()219
}220
221
fn status_label(&self, status: &str) -> String {222
match self.navigation() {223
Some(navigation) => navigation.status_label(status, || status_fallback(status)),224
None => status_fallback(status),225
}226
}227
228
// --- laden ------------------------------------------------------------229
230
fn reload(&mut self, cx: &mut Context<Self>) {231
self.generation += 1;232
if is_demo(cx) {233
let navigation = super::demo::board_navigation(&self.demo);234
self.group = pick_group(self.group.as_deref(), &navigation);235
self.tasks = Tasks::Loaded(self.demo_tasks());236
self.nav = Nav::Loaded(navigation);237
cx.notify();238
return;239
}240
let Some((token, client)) = token_and_client(cx) else {241
self.nav = Nav::NotLinked;242
cx.notify();243
return;244
};245
if !matches!(self.nav, Nav::Loaded(_)) {246
self.nav = Nav::Loading;247
}248
let generation = self.generation;249
let wanted = self.group.clone();250
let loading = runtime::spawn(async move {251
let navigation = client.ponos_navigation(&token).await?;252
let group = pick_group(wanted.as_deref(), &navigation);253
let tasks = match &group {254
Some(group) => client.ponos_tasks(&token, group).await,255
None => Ok(Vec::new()),256
};257
Ok::<_, ClientError>((navigation, group, tasks))258
});259
cx.spawn(async move |this, cx| {260
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));261
cx.update(|cx| {262
let unauthorized = matches!(&result, Err(ClientError::Unauthorized))263
|| matches!(&result, Ok((_, _, Err(ClientError::Unauthorized))));264
if unauthorized {265
forget_token(cx);266
}267
this.update(cx, |this, cx| {268
if this.generation != generation {269
return;270
}271
match result {272
Ok((navigation, group, tasks)) => {273
this.group = group;274
this.tasks = match tasks {275
Ok(tasks) => Tasks::Loaded(tasks),276
Err(error) => Tasks::Failed(error),277
};278
this.nav = Nav::Loaded(navigation);279
}280
Err(ClientError::Unauthorized) => this.nav = Nav::NotLinked,281
Err(error) => this.nav = Nav::Failed(error),282
}283
cx.notify();284
})285
.ok();286
});287
})288
.detach();289
}290
291
fn select_group(&mut self, group: String, cx: &mut Context<Self>) {292
if self.group.as_deref() == Some(group.as_str()) {293
return;294
}295
remember_group(&group, cx);296
self.group = Some(group);297
self.tasks = Tasks::Loading;298
self.editor = None;299
self.reload(cx);300
}301
302
// --- demo -------------------------------------------------------------303
304
fn demo_tasks(&self) -> Vec<PonosTask> {305
let Some(group) = self.group.as_deref() else {306
return Vec::new();307
};308
if group == MY_TASKS_GROUP {309
let mut mine: Vec<PonosTask> = self310
.demo311
.values()312
.flatten()313
.filter(|task| task.assignee_email == super::demo::BOARD_USER)314
.cloned()315
.collect();316
mine.sort_by(|a, b| a.id.cmp(&b.id));317
return mine;318
}319
self.demo.get(group).cloned().unwrap_or_default()320
}321
322
fn demo_task_mut(&mut self, id: &str) -> Option<&mut PonosTask> {323
self.demo.values_mut().flatten().find(|task| task.id == id)324
}325
326
// --- acties -----------------------------------------------------------327
328
/// Een schrijfactie bij Ponos; daarna altijd opnieuw laden.329
fn submit<Fut>(330
&mut self,331
cx: &mut Context<Self>,332
done: Option<String>,333
job: impl FnOnce(String, CardsClient) -> Fut,334
) where335
Fut: std::future::Future<Output = Result<(), ClientError>> + Send + 'static,336
{337
let Some((token, client)) = token_and_client(cx) else {338
self.reload(cx);339
return;340
};341
let running = runtime::spawn(job(token, client));342
cx.spawn(async move |this, cx| {343
let result = running.await.unwrap_or(Err(ClientError::Unavailable));344
cx.update(|cx| {345
match &result {346
Ok(()) => {347
if let Some(done) = done {348
notice(done, cx);349
}350
}351
Err(error) => {352
if *error == ClientError::Unauthorized {353
forget_token(cx);354
}355
notice(ponos_error(error), cx);356
}357
}358
this.update(cx, |this, cx| {359
if result.is_ok() {360
this.editor = None;361
} else if let Some(editor) = this.editor.as_mut() {362
editor.saving = false;363
}364
this.reload(cx);365
})366
.ok();367
});368
})369
.detach();370
}371
372
fn drop_task(373
&mut self,374
dragged: &DraggedTask,375
status: &'static str,376
before: Option<usize>,377
cx: &mut Context<Self>,378
) {379
let Some(group) = self.group.clone() else {380
return;381
};382
let Tasks::Loaded(tasks) = &mut self.tasks else {383
return;384
};385
let position = drop_position(tasks, &dragged.id, status, before);386
let unchanged = dragged.from_status == status387
&& column(tasks, status).position(|task| task.id == dragged.id) == Some(position);388
if unchanged || !apply_move(tasks, &dragged.id, status, position) {389
return;390
}391
cx.notify();392
let id = dragged.id.clone();393
if is_demo(cx) {394
if let Some(task) = self.demo_task_mut(&id) {395
task.status = status.to_owned();396
}397
if group != MY_TASKS_GROUP398
&& let Some(list) = self.demo.get_mut(&group)399
{400
apply_move(list, &id, status, position);401
}402
return;403
}404
let virtual_group = group == MY_TASKS_GROUP;405
let status_changed = dragged.from_status != status;406
if virtual_group && !status_changed {407
// «Mijn Taken» heeft geen eigen volgorde in Ponos.408
return;409
}410
self.submit(cx, None, move |token, client| async move {411
if virtual_group {412
client.ponos_set_status(&token, &group, &id, status).await?;413
} else {414
client415
.ponos_reorder_task(&token, &group, &id, status, position)416
.await?;417
}418
Ok(())419
});420
}421
422
fn open_editor(423
&mut self,424
task: Option<PonosTask>,425
status: &str,426
window: &mut Window,427
cx: &mut Context<Self>,428
) {429
let (title_text, description_text, due_text) = match &task {430
Some(task) => (431
task.title.clone(),432
task.description.clone(),433
iso_date_nl(&task.due_date).unwrap_or_default(),434
),435
None => Default::default(),436
};437
let title = cx.new(|cx| {438
InputState::new(window, cx)439
.placeholder(tr("kvt.ponos.title"))440
.default_value(title_text)441
});442
let description = cx.new(|cx| {443
TextareaState::new(window, cx)444
.auto_grow(4, 10)445
.placeholder(tr("kvt.ponos.description"))446
.default_value(description_text)447
});448
let due = cx.new(|cx| {449
InputState::new(window, cx)450
.placeholder(tr("kvt.board.due_placeholder"))451
.default_value(due_text)452
});453
title.update(cx, |input, cx| input.focus(window, cx));454
let assignee = match &task {455
Some(task) => task.assignee_email.clone(),456
// Nieuw in «Mijn Taken» kan niet; elders standaard niemand.457
None => String::new(),458
};459
self.editor = Some(Editor {460
status: task461
.as_ref()462
.map_or_else(|| status.to_owned(), |task| task.status.clone()),463
assignee,464
target_group: None,465
task,466
title,467
description,468
due,469
saving: false,470
error: None,471
});472
cx.notify();473
}474
475
fn save_editor(&mut self, cx: &mut Context<Self>) {476
let Some(group) = self.group.clone() else {477
return;478
};479
let Some(editor) = self.editor.as_mut() else {480
return;481
};482
if editor.saving {483
return;484
}485
let title: String = editor486
.title487
.read(cx)488
.value()489
.trim()490
.chars()491
.take(TITLE_MAX)492
.collect();493
let description = editor.description.read(cx).value().trim().to_owned();494
if title.is_empty() || description.is_empty() {495
editor.error = Some(tr("kvt.ponos.fill_in"));496
cx.notify();497
return;498
}499
let Some(due_date) = parse_date_input(&editor.due.read(cx).value()) else {500
editor.error = Some(tr("kvt.board.bad_date"));501
cx.notify();502
return;503
};504
let input = TaskInput {505
title,506
description,507
due_date,508
assignee_email: editor.assignee.clone(),509
target_group: editor.target_group.clone(),510
};511
let status = editor.status.clone();512
let existing = editor.task.clone();513
editor.saving = true;514
editor.error = None;515
cx.notify();516
517
if is_demo(cx) {518
self.save_demo(&group, existing, input, status);519
self.editor = None;520
notice(tr("kvt.board.saved"), cx);521
self.reload(cx);522
return;523
}524
let done = tr(if existing.is_some() {525
"kvt.board.saved"526
} else {527
"kvt.ponos.created"528
});529
self.submit(cx, Some(done), move |token, client| async move {530
match existing {531
Some(task) => {532
let saved = client533
.ponos_update_task(&token, &group, &task.id, &input)534
.await?;535
if saved.status != status {536
let home = input.target_group.as_deref().unwrap_or(&group);537
client538
.ponos_set_status(&token, home, &saved.id, &status)539
.await?;540
}541
}542
None => {543
let created = client.ponos_create(&token, &group, &input).await?;544
if created.status != status {545
client546
.ponos_set_status(&token, &group, &created.id, &status)547
.await?;548
}549
}550
}551
Ok(())552
});553
}554
555
fn save_demo(556
&mut self,557
group: &str,558
existing: Option<PonosTask>,559
input: TaskInput,560
status: String,561
) {562
match existing {563
Some(task) => {564
let home = task.group().to_owned();565
let Some(list) = self.demo.get_mut(&home) else {566
return;567
};568
let Some(index) = list.iter().position(|other| other.id == task.id) else {569
return;570
};571
let mut updated = list.remove(index);572
updated.title = input.title;573
updated.description = input.description;574
updated.due_date = input.due_date;575
updated.assignee_email = input.assignee_email;576
let target = input.target_group.unwrap_or(home.clone());577
if target == home && updated.status == status {578
list.insert(index, updated);579
return;580
}581
updated.status = status;582
updated.group_id = target.clone();583
updated.home_group_id = target.clone();584
self.demo.entry(target).or_default().push(updated);585
}586
None => {587
let id = format!(588
"demo-board-{}",589
self.demo.values().map(Vec::len).sum::<usize>() + 1590
);591
let task = PonosTask {592
id,593
group_id: group.to_owned(),594
home_group_id: group.to_owned(),595
title: input.title,596
status,597
due_date: input.due_date,598
description: input.description,599
assignee_email: input.assignee_email,600
..super::demo::empty_task()601
};602
self.demo.entry(group.to_owned()).or_default().push(task);603
}604
}605
}606
607
fn complete_from_editor(&mut self, cx: &mut Context<Self>) {608
let Some(group) = self.group.clone() else {609
return;610
};611
let Some(task) = self.editor.as_ref().and_then(|editor| editor.task.clone()) else {612
return;613
};614
if is_demo(cx) {615
if let Some(demo) = self.demo_task_mut(&task.id) {616
demo.status = STATUS_DONE.to_owned();617
}618
self.editor = None;619
notice(tr("kvt.tasks.completed"), cx);620
self.reload(cx);621
return;622
}623
if let Some(editor) = self.editor.as_mut() {624
editor.saving = true;625
}626
self.submit(627
cx,628
Some(tr("kvt.tasks.completed")),629
move |token, client| async move {630
client.ponos_complete_task(&token, &group, &task.id).await631
},632
);633
}634
635
// --- weergave ---------------------------------------------------------636
637
fn groups_list(&self, cx: &mut Context<Self>) -> AnyElement {638
let Some(navigation) = self.navigation() else {639
return div().into_any_element();640
};641
v_flex()642
.id("kvt-board-groups")643
.w(px(GROUPS_WIDTH))644
.h_full()645
.flex_none()646
.p(px(8.))647
.gap(px(2.))648
.border_r_1()649
.border_color(theme::border())650
.overflow_y_scrollbar()651
.children(navigation.groups.iter().enumerate().map(|(index, group)| {652
let selected = self.group.as_deref() == Some(group.id.as_str());653
let id = group.id.clone();654
h_flex()655
.id(ElementId::Name(format!("kvt-board-group-{index}").into()))656
.w_full()657
.h(px(GROUP_ROW_HEIGHT))658
.flex_none()659
.px(px(10.))660
.gap(px(8.))661
.items_center()662
.rounded(px(6.))663
.cursor_pointer()664
.text_size(px(13.))665
.map(|row| {666
if selected {667
row.bg(theme::selection())668
.text_color(theme::text_strong())669
.font_weight(FontWeight::SEMIBOLD)670
} else {671
row.text_color(theme::text())672
.hover(|row| row.bg(theme::row_hover()))673
}674
})675
.on_click(cx.listener(move |this, _, _, cx| this.select_group(id.clone(), cx)))676
.child(symbol(677
if group.is_virtual { "person" } else { "group" },678
16.,679
if selected {680
theme::accent_text()681
} else {682
theme::text_muted()683
},684
))685
.child(686
div()687
.flex_1()688
.min_w_0()689
.truncate()690
.child(group.name.clone()),691
)692
.when(group.task_count > 0, |row| {693
row.child(694
div()695
.flex_none()696
.text_size(px(12.))697
.text_color(theme::text_muted())698
.child(group.task_count.to_string()),699
)700
})701
}))702
.into_any_element()703
}704
705
fn header(&self, cx: &mut Context<Self>) -> Div {706
let group = self.current_group();707
let title = group.map_or_else(|| tr("kvt.board.title"), |group| group.name.clone());708
let can_create = group.is_some_and(PonosGroup::accepts_new_tasks)709
&& matches!(self.tasks, Tasks::Loaded(_));710
let url = match self.group.as_deref() {711
Some(group) => group_url(&base_url(), group),712
None => format!("{}/ponos/", base_url()),713
};714
h_flex()715
.h(px(HEADER_HEIGHT))716
.flex_none()717
.px(px(PAGE_PADDING))718
.gap(px(8.))719
.items_center()720
.child(721
div()722
.flex_1()723
.min_w_0()724
.truncate()725
.text_size(px(16.))726
.font_weight(FontWeight::BOLD)727
.text_color(theme::text())728
.child(title),729
)730
.when(can_create, |row| {731
row.child(732
primary_button("kvt-board-new", tr("kvt.board.new_task")).on_click(733
cx.listener(|this, _, window, cx| {734
this.open_editor(None, STATUSES[0], window, cx)735
}),736
),737
)738
})739
.child(740
secondary_button("kvt-board-refresh", "refresh", tr("kvt.card.refresh"))741
.on_click(cx.listener(|this, _, _, cx| this.reload(cx))),742
)743
.child(744
secondary_button("kvt-board-open", "open_in_new", tr("kvt.tasks.open_ponos"))745
.on_click(move |_, _, cx| open_external(&url, cx)),746
)747
}748
749
fn columns(&self, cx: &mut Context<Self>) -> AnyElement {750
let tasks = match &self.tasks {751
Tasks::Loading => {752
return muted(tr("kvt.card.loading"))753
.px(px(PAGE_PADDING))754
.into_any_element();755
}756
Tasks::Failed(error) => {757
return muted(ponos_error(error))758
.px(px(PAGE_PADDING))759
.into_any_element();760
}761
Tasks::Loaded(tasks) => tasks,762
};763
let group = self.current_group();764
let editable = group.is_some_and(PonosGroup::editable);765
let can_create = group.is_some_and(PonosGroup::accepts_new_tasks);766
let me = self.user_email();767
h_flex()768
.id("kvt-board-columns")769
.flex_1()770
.min_h_0()771
.w_full()772
.px(px(PAGE_PADDING))773
.pb(px(PAGE_PADDING))774
.gap(px(COLUMN_GAP))775
.items_start()776
.overflow_x_scrollbar()777
.children(778
STATUSES779
.iter()780
.map(|&status| self.column(tasks, status, editable, can_create, &me, cx)),781
)782
.into_any_element()783
}784
785
fn column(786
&self,787
tasks: &[PonosTask],788
status: &'static str,789
editable: bool,790
can_create: bool,791
me: &str,792
cx: &mut Context<Self>,793
) -> AnyElement {794
let cards: Vec<&PonosTask> = column(tasks, status).collect();795
let today = chrono::Local::now().format("%Y-%m-%d").to_string();796
let dot = match status {797
"in_progress" => theme::accent(),798
STATUS_DONE => theme::green(),799
_ => theme::text_faint(),800
};801
v_flex()802
.id(ElementId::Name(format!("kvt-board-column-{status}").into()))803
.debug_selector(move || format!("kvt-board/column/{status}"))804
.flex_1()805
.min_w(px(COLUMN_MIN_WIDTH))806
.h_full()807
.p(px(10.))808
.gap(px(CARD_GAP))809
.rounded(px(RADIUS))810
.bg(theme::surface())811
.drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background()))812
.on_drop(cx.listener(move |this, dragged: &DraggedTask, _, cx| {813
this.drop_task(dragged, status, None, cx)814
}))815
.child(816
h_flex()817
.w_full()818
.h(px(28.))819
.flex_none()820
.gap(px(8.))821
.items_center()822
.child(div().size(px(8.)).flex_none().rounded_full().bg(dot))823
.child(824
div()825
.flex_1()826
.min_w_0()827
.truncate()828
.text_size(px(13.))829
.font_weight(FontWeight::SEMIBOLD)830
.text_color(theme::text())831
.child(self.status_label(status)),832
)833
.child(834
div()835
.text_size(px(12.))836
.text_color(theme::text_muted())837
.child(cards.len().to_string()),838
)839
.when(can_create, |row| {840
row.child(841
div()842
.id(ElementId::Name(format!("kvt-board-add-{status}").into()))843
.size(px(24.))844
.flex_none()845
.flex()846
.items_center()847
.justify_center()848
.rounded_full()849
.cursor_pointer()850
.hover(|button| button.bg(theme::row_hover()))851
.on_click(cx.listener(move |this, _, window, cx| {852
this.open_editor(None, status, window, cx)853
}))854
.child(symbol("add", 16., theme::text_muted())),855
)856
}),857
)858
.child(859
v_flex()860
.id(ElementId::Name(format!("kvt-board-cards-{status}").into()))861
.w_full()862
.flex_1()863
.min_h(px(80.))864
.gap(px(CARD_GAP))865
.overflow_y_scrollbar()866
.when(cards.is_empty(), |list| {867
list.child(868
div()869
.w_full()870
.py(px(16.))871
.text_center()872
.text_size(px(12.))873
.text_color(theme::text_faint())874
.child(tr("kvt.board.empty_column")),875
)876
})877
.children(cards.iter().enumerate().map(|(index, task)| {878
self.card(task, status, index, editable, me, &today, cx)879
})),880
)881
.into_any_element()882
}883
884
#[allow(clippy::too_many_arguments)]885
fn card(886
&self,887
task: &PonosTask,888
status: &'static str,889
index: usize,890
editable: bool,891
me: &str,892
today: &str,893
cx: &mut Context<Self>,894
) -> AnyElement {895
let movable = editable && task.can_edit;896
let overdue =897
status != STATUS_DONE && !task.due_date.is_empty() && task.due_date.as_str() < today;898
let due = iso_date_nl(&task.due_date);899
let assignee = if task.assignee_email.is_empty() {900
None901
} else if task.assignee_email.eq_ignore_ascii_case(me) {902
Some(tr("kvt.board.assignee_me"))903
} else {904
Some(name_from_email(&task.assignee_email))905
};906
let in_my_tasks = self.group.as_deref() == Some(MY_TASKS_GROUP);907
let open = task.clone();908
let dragged = DraggedTask {909
id: task.id.clone(),910
title: task.title.clone(),911
from_status: task.status.clone(),912
};913
v_flex()914
.id(ElementId::Name(915
format!("kvt-board-card-{}", task.id).into(),916
))917
.w_full()918
.flex_none()919
.px(px(12.))920
.py(px(10.))921
.gap(px(6.))922
.rounded(px(8.))923
.bg(theme::surface_raised())924
.cursor_pointer()925
.hover(|card| card.bg(theme::popup_hover()))926
.on_click(cx.listener(move |this, _, window, cx| {927
this.open_editor(Some(open.clone()), &open.status, window, cx)928
}))929
.when(movable, |card| {930
card.on_drag(dragged, |dragged, _, _, cx| {931
let title = dragged.title.clone();932
cx.new(|_| TaskGhost { title })933
})934
.drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background()))935
.on_drop(cx.listener(936
move |this, dragged: &DraggedTask, _, cx| {937
cx.stop_propagation();938
this.drop_task(dragged, status, Some(index), cx)939
},940
))941
})942
.when(in_my_tasks && !task.home_group_name.is_empty(), |card| {943
card.child(944
div()945
.truncate()946
.text_size(px(11.))947
.text_color(theme::text_muted())948
.child(task.home_group_name.clone()),949
)950
})951
.child(952
div()953
.text_size(px(13.))954
.line_height(px(18.))955
.text_color(if status == STATUS_DONE {956
theme::text_muted()957
} else {958
theme::text()959
})960
.when(status == STATUS_DONE, |text| text.line_through())961
.child(task.title.clone()),962
)963
.child(964
h_flex()965
.w_full()966
.flex_wrap()967
.gap(px(8.))968
.items_center()969
.text_size(px(11.))970
.text_color(theme::text_muted())971
.when(!task.category_label.is_empty(), |row| {972
row.child(973
div()974
.px(px(6.))975
.py(px(1.))976
.rounded(px(4.))977
.bg(theme::selection())978
.text_color(theme::text_strong())979
.child(task.category_label.clone()),980
)981
})982
.children(due.map(|due| {983
h_flex()984
.gap(px(3.))985
.items_center()986
.text_color(if overdue {987
theme::red_soft()988
} else {989
theme::text_muted()990
})991
.child(symbol(992
"event",993
12.,994
if overdue {995
theme::red_soft()996
} else {997
theme::text_muted()998
},999
))1000
.child(due)1001
}))1002
.when(task.checklist_total > 0, |row| {1003
row.child(1004
h_flex()1005
.gap(px(3.))1006
.items_center()1007
.child(symbol("check", 12., theme::text_muted()))1008
.child(format!("{}/{}", task.checklist_done, task.checklist_total)),1009
)1010
})1011
.children(assignee.map(|assignee| {1012
h_flex()1013
.gap(px(3.))1014
.items_center()1015
.child(symbol("person", 12., theme::text_muted()))1016
.child(assignee)1017
})),1018
)1019
.into_any_element()1020
}1021
1022
fn editor_layer(&self, cx: &mut Context<Self>) -> Option<AnyElement> {1023
let editor = self.editor.as_ref()?;1024
let navigation = self.navigation()?;1025
let me = navigation.user_email.clone();1026
let existing = editor.task.clone();1027
let editable = existing.as_ref().is_none_or(|task| task.can_edit);1028
let home = existing1029
.as_ref()1030
.map(|task| task.group().to_owned())1031
.or_else(|| self.group.clone())1032
.unwrap_or_default();1033
let target = editor.target_group.clone().unwrap_or_else(|| home.clone());1034
let title = tr(if existing.is_some() {1035
"kvt.board.edit_task"1036
} else {1037
"kvt.ponos.dialog_title"1038
});1039
let detail = existing1040
.as_ref()1041
.filter(|task| !task.home_group_name.is_empty())1042
.map(|task| task.home_group_name.clone())1043
.unwrap_or_default();1044
let url = existing.as_ref().map(|task| task.url(&base_url()));1045
let move_groups: Vec<PonosGroup> = navigation1046
.groups1047
.iter()1048
.filter(|group| !group.is_virtual && group.has_task_access)1049
.cloned()1050
.collect();1051
let other_assignee = (!editor.assignee.is_empty()1052
&& !editor.assignee.eq_ignore_ascii_case(&me))1053
.then(|| name_from_email(&editor.assignee));1054
let assignee_is_me = !me.is_empty() && editor.assignee.eq_ignore_ascii_case(&me);1055
1056
let status_chips =1057
h_flex()1058
.w_full()1059
.flex_wrap()1060
.gap(px(6.))1061
.children(STATUSES.iter().enumerate().map(|(index, &status)| {1062
chip(1063
format!("kvt-board-status-{index}").into(),1064
self.status_label(status),1065
editor.status == status,1066
)1067
.on_click(cx.listener(move |this, _, _, cx| {1068
if let Some(editor) = this.editor.as_mut() {1069
editor.status = status.to_owned();1070
cx.notify();1071
}1072
}))1073
}));1074
let assignee_chips = h_flex()1075
.w_full()1076
.flex_wrap()1077
.gap(px(6.))1078
.child(1079
chip(1080
"kvt-board-assignee-none".into(),1081
tr("kvt.board.assignee_none"),1082
editor.assignee.is_empty(),1083
)1084
.on_click(cx.listener(|this, _, _, cx| {1085
if let Some(editor) = this.editor.as_mut() {1086
editor.assignee.clear();1087
cx.notify();1088
}1089
})),1090
)1091
.when(!me.is_empty(), |row| {1092
let me = me.clone();1093
row.child(1094
chip(1095
"kvt-board-assignee-me".into(),1096
tr("kvt.board.assignee_me"),1097
assignee_is_me,1098
)1099
.on_click(cx.listener(move |this, _, _, cx| {1100
if let Some(editor) = this.editor.as_mut() {1101
editor.assignee = me.clone();1102
cx.notify();1103
}1104
})),1105
)1106
})1107
.children(1108
other_assignee.map(|name| chip("kvt-board-assignee-other".into(), name, true)),1109
);1110
let group_chips =1111
(existing.is_some() && move_groups.len() > 1).then(|| {1112
h_flex().w_full().flex_wrap().gap(px(6.)).children(1113
move_groups.iter().enumerate().map(|(index, group)| {1114
let id = group.id.clone();1115
let home = home.clone();1116
chip(1117
format!("kvt-board-move-{index}").into(),1118
group.name.clone(),1119
group.id == target,1120
)1121
.on_click(cx.listener(move |this, _, _, cx| {1122
if let Some(editor) = this.editor.as_mut() {1123
editor.target_group = (id != home).then(|| id.clone());1124
cx.notify();1125
}1126
}))1127
}),1128
)1129
});1130
let can_complete = existing1131
.as_ref()1132
.is_some_and(|task| task.status != STATUS_DONE && task.can_edit);1133
1134
let panel = v_flex()1135
.debug_selector(|| "kvt-board-editor".into())1136
.w(px(EDITOR_WIDTH))1137
.max_w(relative(1.))1138
.max_h(relative(0.92))1139
.m(px(32.))1140
.p(px(16.))1141
.gap(px(10.))1142
.rounded(px(RADIUS))1143
.dialog_surface()1144
.text_color(theme::text())1145
.occlude()1146
.child(1147
h_flex()1148
.w_full()1149
.items_center()1150
.gap(px(12.))1151
.child(1152
v_flex()1153
.flex_1()1154
.min_w_0()1155
.child(1156
div()1157
.text_size(px(15.))1158
.font_weight(FontWeight::SEMIBOLD)1159
.child(title),1160
)1161
.when(!detail.is_empty(), |column| {1162
column.child(1163
div()1164
.truncate()1165
.text_size(px(12.))1166
.text_color(theme::text_muted())1167
.child(detail),1168
)1169
}),1170
)1171
.child(1172
div()1173
.id("kvt-board-editor-close")1174
.size(px(28.))1175
.flex_none()1176
.flex()1177
.items_center()1178
.justify_center()1179
.rounded_full()1180
.cursor_pointer()1181
.hover(|button| button.bg(theme::popup_hover()))1182
.on_click(cx.listener(|this, _, _, cx| {1183
this.editor = None;1184
cx.notify();1185
}))1186
.child(symbol("close", 16., theme::text_muted())),1187
),1188
)1189
.child(label(tr("kvt.ponos.title")))1190
.child(1191
field().child(1192
div()1193
.flex_1()1194
.child(Input::new(&editor.title).appearance(false).bordered(false)),1195
),1196
)1197
.child(label(tr("kvt.ponos.description")))1198
.child(Textarea::new(&editor.description))1199
.child(label(tr("kvt.board.status")))1200
.child(status_chips)1201
.child(label(tr("kvt.board.due")))1202
.child(1203
field().child(1204
div()1205
.flex_1()1206
.child(Input::new(&editor.due).appearance(false).bordered(false)),1207
),1208
)1209
.child(label(tr("kvt.board.assignee")))1210
.child(assignee_chips)1211
.when_some(group_chips, |panel, chips| {1212
panel.child(label(tr("kvt.ponos.group"))).child(chips)1213
})1214
.children(editor.error.clone().map(|error| {1215
div()1216
.text_size(px(13.))1217
.text_color(theme::red_soft())1218
.child(error)1219
}))1220
.child(1221
h_flex()1222
.w_full()1223
.gap(px(8.))1224
.items_center()1225
.children(url.map(|url| {1226
secondary_button(1227
"kvt-board-editor-open",1228
"open_in_new",1229
tr("kvt.tasks.open_ponos"),1230
)1231
.on_click(move |_, _, cx| open_external(&url, cx))1232
}))1233
.child(div().flex_1())1234
.when(can_complete, |row| {1235
row.child(1236
secondary_button(1237
"kvt-board-complete",1238
"check_circle",1239
tr("kvt.board.complete"),1240
)1241
.on_click(cx.listener(|this, _, _, cx| this.complete_from_editor(cx))),1242
)1243
})1244
.child(1245
secondary_button("kvt-board-cancel", "close", tr("common.cancel"))1246
.on_click(cx.listener(|this, _, _, cx| {1247
this.editor = None;1248
cx.notify();1249
})),1250
)1251
.when(editable, |row| {1252
row.child(1253
primary_button(1254
"kvt-board-save",1255
tr(if editor.saving {1256
"kvt.ponos.saving"1257
} else {1258
"kvt.board.save"1259
}),1260
)1261
.on_click(cx.listener(|this, _, _, cx| this.save_editor(cx))),1262
)1263
}),1264
);1265
Some(1266
div()1267
.id("kvt-board-editor-layer")1268
.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {1269
if event.keystroke.key == "escape" {1270
cx.stop_propagation();1271
this.editor = None;1272
cx.notify();1273
}1274
}))1275
.absolute()1276
.top_0()1277
.left_0()1278
.size_full()1279
.flex()1280
.items_center()1281
.justify_center()1282
.child(1283
div()1284
.id("kvt-board-editor-backdrop")1285
.absolute()1286
.top_0()1287
.left_0()1288
.size_full()1289
.bg(black().opacity(BACKDROP_OPACITY))1290
.occlude()1291
.on_click(cx.listener(|this, _, _, cx| {1292
this.editor = None;1293
cx.notify();1294
})),1295
)1296
.child(panel)1297
.into_any_element(),1298
)1299
}1300
}1301
1302
impl Render for PonosBoard {1303
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {1304
let linked = matches!(link(cx), Link::Linked(_));1305
if !linked && !is_demo(cx) {1306
// Ontkoppeld: na opnieuw koppelen vers laden, niets van de oude token tonen.1307
self.nav = Nav::NotLinked;1308
self.editor = None;1309
} else if matches!(self.nav, Nav::NotLinked) {1310
self.reload(cx);1311
}1312
let body = match (&self.nav, linked) {1313
(_, false) => v_flex()1314
.p(px(PAGE_PADDING))1315
.max_w(px(EDITOR_WIDTH))1316
.child(not_linked())1317
.into_any_element(),1318
(Nav::NotLinked | Nav::Loading, _) => muted(tr("kvt.card.loading"))1319
.px(px(PAGE_PADDING))1320
.into_any_element(),1321
(Nav::Failed(error), _) => muted(ponos_error(error))1322
.px(px(PAGE_PADDING))1323
.into_any_element(),1324
(Nav::Loaded(_), _) => h_flex()1325
.flex_1()1326
.min_h_0()1327
.w_full()1328
.child(self.groups_list(cx))1329
.child(1330
v_flex()1331
.flex_1()1332
.min_w_0()1333
.h_full()1334
.child(self.header(cx))1335
.child(self.columns(cx)),1336
)1337
.into_any_element(),1338
};1339
let page_title = (!matches!(self.nav, Nav::Loaded(_)) || !linked).then(|| {1340
h_flex()1341
.h(px(HEADER_HEIGHT))1342
.flex_none()1343
.px(px(PAGE_PADDING))1344
.items_center()1345
.child(1346
div()1347
.text_size(px(16.))1348
.font_weight(FontWeight::BOLD)1349
.text_color(theme::text())1350
.child(tr("kvt.board.title")),1351
)1352
});1353
v_flex()1354
.debug_selector(|| KVT_BOARD_TAG.into())1355
.relative()1356
.size_full()1357
.rounded(px(RADIUS))1358
.bg(theme::surface())1359
.overflow_hidden()1360
.children(page_title)1361
.child(body)1362
.children(self.editor_layer(cx))1363
}1364
}1365
1366
#[cfg(test)]1367
mod tests {1368
use super::pick_group;1369
use kvt_sleutels::ponos::{PonosGroup, PonosNavigation};1370
1371
fn group(id: &str) -> PonosGroup {1372
PonosGroup {1373
id: id.to_owned(),1374
name: id.to_owned(),1375
is_virtual: false,1376
can_create_tasks: true,1377
has_task_access: true,1378
task_count: 0,1379
}1380
}1381
1382
#[test]1383
fn remembered_group_wins_when_it_still_exists() {1384
let navigation = PonosNavigation {1385
groups: vec![group("__my_tasks__"), group("g1")],1386
..Default::default()1387
};1388
assert_eq!(pick_group(Some("g1"), &navigation).as_deref(), Some("g1"));1389
assert_eq!(1390
pick_group(Some("weg"), &navigation).as_deref(),1391
Some("__my_tasks__")1392
);1393
assert_eq!(pick_group(None, &PonosNavigation::default()), None);1394
}1395
}@@ -5,6 +5,10 @@ use kvt_sleutels::{
5
5
Card, CardField, CardKind, CardLinks, CardRef, FieldRef, SearchResult, StoredToken,
6
6
};
7
7
8
use std::collections::HashMap;
9
10
use kvt_sleutels::ponos::{MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask};
11
8
12
use super::DEFAULT_COMPANY as COMPANY;
9
13
10
14
pub(super) fn token() -> StoredToken {
@@ -241,59 +245,204 @@ pub(super) fn ponos_groups() -> Vec<kvt_sleutels::ponos::PonosGroup> {
241
245
is_virtual: false,
242
246
can_create_tasks: true,
243
247
has_task_access: true,
248
task_count: 0,
244
249
})
245
250
.collect()
246
251
}
247
252
248
pub(super) fn my_tasks() -> Vec<kvt_sleutels::ponos::PonosTask> {
253
/// Verzonnen gebruiker van het demobord (geen echt adres).
254
pub(super) const BOARD_USER: &str = "dana.demo@example.com";
255
256
pub(super) fn empty_task() -> PonosTask {
257
PonosTask {
258
id: String::new(),
259
group_id: String::new(),
260
home_group_id: String::new(),
261
home_group_name: String::new(),
262
title: String::new(),
263
status: "todo".to_owned(),
264
due_date: String::new(),
265
description: String::new(),
266
assignee_email: String::new(),
267
category_label: String::new(),
268
checklist_total: 0,
269
checklist_done: 0,
270
can_edit: true,
271
}
272
}
273
274
/// Verzonnen taken per groep voor het Ponos-bord in `--demo`.
275
pub(super) fn board_tasks() -> HashMap<String, Vec<PonosTask>> {
249
276
let today = chrono::Local::now().date_naive();
250
let task = |id: &str, group: &str, title: &str, status: &str, due: Option<i64>| {
251
kvt_sleutels::ponos::PonosTask {
252
id: id.to_owned(),
253
group_id: "demo-group-0".to_owned(),
254
home_group_id: "demo-group-0".to_owned(),
255
home_group_name: group.to_owned(),
256
title: title.to_owned(),
257
status: status.to_owned(),
258
due_date: due
259
.map(|days| {
260
(today + chrono::Duration::days(days))
261
.format("%Y-%m-%d")
262
.to_string()
263
})
264
.unwrap_or_default(),
265
}
266
};
267
kvt_sleutels::ponos::sort_open(vec![
268
task(
269
"demo-task-1",
270
"ICT",
277
let groups = ponos_groups();
278
let mut board: HashMap<String, Vec<PonosTask>> = HashMap::new();
279
#[allow(clippy::type_complexity)]
280
let rows: [(usize, &str, &str, Option<i64>, &str, &str, (u32, u32)); 13] = [
281
(
282
0,
271
283
"Laptop klaarzetten voor nieuwe collega",
272
284
"todo",
273
285
Some(-1),
286
BOARD_USER,
287
"Hardware",
288
(1, 4),
289
),
290
(
291
0,
292
"Printer receptie controleren",
293
"todo",
294
None,
295
BOARD_USER,
296
"",
297
(0, 0),
298
),
299
(
300
0,
301
"Wifi in hal 3 meten",
302
"todo",
303
Some(6),
304
"",
305
"Netwerk",
306
(0, 0),
307
),
308
(
309
0,
310
"Teams-koppeling testen",
311
"in_progress",
312
Some(1),
313
BOARD_USER,
314
"",
315
(2, 3),
316
),
317
(
318
0,
319
"Back-up NAS nakijken",
320
"in_progress",
321
None,
322
"jonas.ortega@example.com",
323
"",
324
(0, 0),
325
),
326
(
327
0,
328
"Licenties verlengd",
329
"done",
330
None,
331
BOARD_USER,
332
"",
333
(0, 0),
274
334
),
275
task(
276
"demo-task-2",
277
"Service Noord",
335
(
336
1,
278
337
"Rapport WO2699001 nakijken",
279
338
"in_progress",
280
339
Some(2),
340
BOARD_USER,
341
"Rapport",
342
(0, 0),
281
343
),
282
task(
283
"demo-task-3",
284
"Werkplaats",
344
(
345
1,
346
"Onderdelen bestellen voor PRJ2600140",
347
"todo",
348
Some(4),
349
"mila.van.der.berg@example.com",
350
"",
351
(0, 0),
352
),
353
(
354
1,
355
"Klant terugbellen over storing",
356
"todo",
357
Some(0),
358
BOARD_USER,
359
"",
360
(0, 0),
361
),
362
(1, "Servicebus ingepland", "done", None, "", "", (0, 0)),
363
(
364
2,
285
365
"Brandstoffilters bestellen",
286
366
"todo",
287
367
Some(9),
368
BOARD_USER,
369
"Inkoop",
370
(0, 0),
288
371
),
289
task(
290
"demo-task-4",
291
"ICT",
292
"Printer receptie controleren",
293
"todo",
372
(2, "Hefbrug keuren", "in_progress", Some(12), "", "", (0, 0)),
373
(
374
2,
375
"Gereedschapskist aangevuld",
376
"done",
294
377
None,
378
"",
379
"",
380
(0, 0),
381
),
382
];
383
for (index, (group, title, status, due, assignee, category, (done, total))) in
384
rows.into_iter().enumerate()
385
{
386
let group = &groups[group];
387
board.entry(group.id.clone()).or_default().push(PonosTask {
388
id: format!("demo-board-task-{index}"),
389
group_id: group.id.clone(),
390
home_group_id: group.id.clone(),
391
home_group_name: group.name.clone(),
392
title: title.to_owned(),
393
status: status.to_owned(),
394
due_date: due
395
.map(|days| {
396
(today + chrono::Duration::days(days))
397
.format("%Y-%m-%d")
398
.to_string()
399
})
400
.unwrap_or_default(),
401
description: "Verzonnen taak voor de demo.".to_owned(),
402
assignee_email: assignee.to_owned(),
403
category_label: category.to_owned(),
404
checklist_total: total,
405
checklist_done: done,
406
..empty_task()
407
});
408
}
409
board
410
}
411
412
/// Groepen zoals Ponos ze geeft: eerst «Mijn Taken», met open taken geteld.
413
pub(super) fn board_navigation(board: &HashMap<String, Vec<PonosTask>>) -> PonosNavigation {
414
let open = |tasks: &mut dyn Iterator<Item = &PonosTask>| {
415
tasks.filter(|task| task.status != "done").count() as u32
416
};
417
let mut groups = vec![PonosGroup {
418
id: MY_TASKS_GROUP.to_owned(),
419
name: "Mijn Taken".to_owned(),
420
is_virtual: true,
421
can_create_tasks: false,
422
has_task_access: true,
423
task_count: open(
424
&mut board
425
.values()
426
.flatten()
427
.filter(|task| task.assignee_email == BOARD_USER),
295
428
),
296
])
429
}];
430
groups.extend(ponos_groups().into_iter().map(|mut group| {
431
group.task_count = open(&mut board.get(&group.id).into_iter().flatten());
432
group
433
}));
434
PonosNavigation {
435
groups,
436
status_labels: [
437
("todo", "Nog te doen"),
438
("in_progress", "Onderhanden"),
439
("done", "Afgerond"),
440
]
441
.into_iter()
442
.map(|(status, label)| (status.to_owned(), label.to_owned()))
443
.collect(),
444
user_email: BOARD_USER.to_owned(),
445
}
297
446
}
298
447
299
448
/// Twee verzonnen werkorders in de zichtbare periode.
@@ -5,6 +5,10 @@ use kvt_sleutels::{5
Card, CardField, CardKind, CardLinks, CardRef, FieldRef, SearchResult, StoredToken,5
Card, CardField, CardKind, CardLinks, CardRef, FieldRef, SearchResult, StoredToken,6
};6
};7
7
8
use std::collections::HashMap;9
10
use kvt_sleutels::ponos::{MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask};11
8
use super::DEFAULT_COMPANY as COMPANY;12
use super::DEFAULT_COMPANY as COMPANY;9
13
10
pub(super) fn token() -> StoredToken {14
pub(super) fn token() -> StoredToken {@@ -241,59 +245,204 @@ pub(super) fn ponos_groups() -> Vec<kvt_sleutels::ponos::PonosGroup> {241
is_virtual: false,245
is_virtual: false,242
can_create_tasks: true,246
can_create_tasks: true,243
has_task_access: true,247
has_task_access: true,248
task_count: 0,244
})249
})245
.collect()250
.collect()246
}251
}247
252
248
pub(super) fn my_tasks() -> Vec<kvt_sleutels::ponos::PonosTask> {253
/// Verzonnen gebruiker van het demobord (geen echt adres).254
pub(super) const BOARD_USER: &str = "dana.demo@example.com";255
256
pub(super) fn empty_task() -> PonosTask {257
PonosTask {258
id: String::new(),259
group_id: String::new(),260
home_group_id: String::new(),261
home_group_name: String::new(),262
title: String::new(),263
status: "todo".to_owned(),264
due_date: String::new(),265
description: String::new(),266
assignee_email: String::new(),267
category_label: String::new(),268
checklist_total: 0,269
checklist_done: 0,270
can_edit: true,271
}272
}273
274
/// Verzonnen taken per groep voor het Ponos-bord in `--demo`.275
pub(super) fn board_tasks() -> HashMap<String, Vec<PonosTask>> {249
let today = chrono::Local::now().date_naive();276
let today = chrono::Local::now().date_naive();250
let task = |id: &str, group: &str, title: &str, status: &str, due: Option<i64>| {277
let groups = ponos_groups();251
kvt_sleutels::ponos::PonosTask {278
let mut board: HashMap<String, Vec<PonosTask>> = HashMap::new();252
id: id.to_owned(),279
#[allow(clippy::type_complexity)]253
group_id: "demo-group-0".to_owned(),280
let rows: [(usize, &str, &str, Option<i64>, &str, &str, (u32, u32)); 13] = [254
home_group_id: "demo-group-0".to_owned(),281
(255
home_group_name: group.to_owned(),282
0,256
title: title.to_owned(),257
status: status.to_owned(),258
due_date: due259
.map(|days| {260
(today + chrono::Duration::days(days))261
.format("%Y-%m-%d")262
.to_string()263
})264
.unwrap_or_default(),265
}266
};267
kvt_sleutels::ponos::sort_open(vec![268
task(269
"demo-task-1",270
"ICT",271
"Laptop klaarzetten voor nieuwe collega",283
"Laptop klaarzetten voor nieuwe collega",272
"todo",284
"todo",273
Some(-1),285
Some(-1),286
BOARD_USER,287
"Hardware",288
(1, 4),289
),290
(291
0,292
"Printer receptie controleren",293
"todo",294
None,295
BOARD_USER,296
"",297
(0, 0),298
),299
(300
0,301
"Wifi in hal 3 meten",302
"todo",303
Some(6),304
"",305
"Netwerk",306
(0, 0),307
),308
(309
0,310
"Teams-koppeling testen",311
"in_progress",312
Some(1),313
BOARD_USER,314
"",315
(2, 3),316
),317
(318
0,319
"Back-up NAS nakijken",320
"in_progress",321
None,322
"jonas.ortega@example.com",323
"",324
(0, 0),325
),326
(327
0,328
"Licenties verlengd",329
"done",330
None,331
BOARD_USER,332
"",333
(0, 0),274
),334
),275
task(335
(276
"demo-task-2",336
1,277
"Service Noord",278
"Rapport WO2699001 nakijken",337
"Rapport WO2699001 nakijken",279
"in_progress",338
"in_progress",280
Some(2),339
Some(2),340
BOARD_USER,341
"Rapport",342
(0, 0),281
),343
),282
task(344
(283
"demo-task-3",345
1,284
"Werkplaats",346
"Onderdelen bestellen voor PRJ2600140",347
"todo",348
Some(4),349
"mila.van.der.berg@example.com",350
"",351
(0, 0),352
),353
(354
1,355
"Klant terugbellen over storing",356
"todo",357
Some(0),358
BOARD_USER,359
"",360
(0, 0),361
),362
(1, "Servicebus ingepland", "done", None, "", "", (0, 0)),363
(364
2,285
"Brandstoffilters bestellen",365
"Brandstoffilters bestellen",286
"todo",366
"todo",287
Some(9),367
Some(9),368
BOARD_USER,369
"Inkoop",370
(0, 0),288
),371
),289
task(372
(2, "Hefbrug keuren", "in_progress", Some(12), "", "", (0, 0)),290
"demo-task-4",373
(291
"ICT",374
2,292
"Printer receptie controleren",375
"Gereedschapskist aangevuld",293
"todo",376
"done",294
None,377
None,378
"",379
"",380
(0, 0),381
),382
];383
for (index, (group, title, status, due, assignee, category, (done, total))) in384
rows.into_iter().enumerate()385
{386
let group = &groups[group];387
board.entry(group.id.clone()).or_default().push(PonosTask {388
id: format!("demo-board-task-{index}"),389
group_id: group.id.clone(),390
home_group_id: group.id.clone(),391
home_group_name: group.name.clone(),392
title: title.to_owned(),393
status: status.to_owned(),394
due_date: due395
.map(|days| {396
(today + chrono::Duration::days(days))397
.format("%Y-%m-%d")398
.to_string()399
})400
.unwrap_or_default(),401
description: "Verzonnen taak voor de demo.".to_owned(),402
assignee_email: assignee.to_owned(),403
category_label: category.to_owned(),404
checklist_total: total,405
checklist_done: done,406
..empty_task()407
});408
}409
board410
}411
412
/// Groepen zoals Ponos ze geeft: eerst «Mijn Taken», met open taken geteld.413
pub(super) fn board_navigation(board: &HashMap<String, Vec<PonosTask>>) -> PonosNavigation {414
let open = |tasks: &mut dyn Iterator<Item = &PonosTask>| {415
tasks.filter(|task| task.status != "done").count() as u32416
};417
let mut groups = vec![PonosGroup {418
id: MY_TASKS_GROUP.to_owned(),419
name: "Mijn Taken".to_owned(),420
is_virtual: true,421
can_create_tasks: false,422
has_task_access: true,423
task_count: open(424
&mut board425
.values()426
.flatten()427
.filter(|task| task.assignee_email == BOARD_USER),295
),428
),296
])429
}];430
groups.extend(ponos_groups().into_iter().map(|mut group| {431
group.task_count = open(&mut board.get(&group.id).into_iter().flatten());432
group433
}));434
PonosNavigation {435
groups,436
status_labels: [437
("todo", "Nog te doen"),438
("in_progress", "Onderhanden"),439
("done", "Afgerond"),440
]441
.into_iter()442
.map(|(status, label)| (status.to_owned(), label.to_owned()))443
.collect(),444
user_email: BOARD_USER.to_owned(),445
}297
}446
}298
447
299
/// Twee verzonnen werkorders in de zichtbare periode.448
/// Twee verzonnen werkorders in de zichtbare periode.@@ -1,4 +1,5 @@
1
//! Berichtmenu: «Ticket maken in Asclepius» en «Taak maken in Ponos».
1
//! Berichtmenu: «Ticket maken in Asclepius» en «Taak maken in Ponos» (beide een
2
//! dialoog in de app, vooraf ingevuld met het bericht).
2
3
//!
3
4
//! Upstream-haak: `views/message_actions.rs` (veld `kvt` in `MessageMenu`) en
4
5
//! `views/conversation.rs` (`message_menu`).
@@ -8,10 +9,10 @@ use std::rc::Rc;
8
9
use chrono::Local;
9
10
use gpui_kit::assets::IconName;
10
11
use gpui_kit::*;
11
use kvt_sleutels::asclepius::{MessageSource, new_ticket_url};
12
use kvt_sleutels::asclepius::MessageSource;
12
13
use kvt_sleutels::format::date_time_nl;
13
14
14
use super::{base_url, installed, open_external};
15
use super::installed;
15
16
use crate::app_state::AppHandle;
16
17
use crate::i18n::tr;
17
18
use crate::runtime;
@@ -52,7 +53,7 @@ pub fn menu_entries(conversation_id: Option<String>, message_id: &str, cx: &App)
52
53
entry(
53
54
"kvt.message.asclepius",
54
55
IconName::Ticket,
55
|source, _, cx| open_external(&new_ticket_url(&base_url(), &source), cx),
56
|source, window, cx| super::ticket_form::open_new(Some(source), window, cx),
56
57
),
57
58
entry(
58
59
"kvt.message.ponos",
@@ -82,7 +83,9 @@ fn with_source(
82
83
sender: record.sender_name.clone().unwrap_or_default(),
83
84
sent_at: date_time_nl(record.created_at.with_timezone(&Local).naive_local()),
84
85
link: None,
86
mentions: Vec::new(),
85
87
};
88
let mentioned = mentioned_users(&record.mentions_json);
86
89
let Some(engine) = state.engine.clone() else {
87
90
let link = state
88
91
.mode
@@ -92,11 +95,79 @@ fn with_source(
92
95
return;
93
96
};
94
97
let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned());
95
let linking =
96
runtime::spawn(async move { engine.message_link(&conversation_id, &message_id).await });
98
let linking = runtime::spawn(async move {
99
let link = engine
100
.message_link(&conversation_id, &message_id)
101
.await
102
.ok();
103
// Vermeldingen: het adres via het profiel (best effort), voor `@naam:domein` in Asclepius.
104
let mut mentions = Vec::new();
105
for (name, user_id) in mentioned {
106
if let Ok(profile) = engine.person_profile(&user_id).await
107
&& let Some(email) = profile.email.filter(|email| email.contains('@'))
108
{
109
mentions.push((name, email));
110
}
111
}
112
(link, mentions)
113
});
97
114
cx.spawn(async move |cx| {
98
let link = linking.await.ok().and_then(Result::ok);
99
cx.update(|cx| then(MessageSource { link, ..source }, cx));
115
let (link, mentions) = linking.await.unwrap_or_default();
116
cx.update(|cx| {
117
then(
118
MessageSource {
119
link,
120
mentions,
121
..source
122
},
123
cx,
124
)
125
});
100
126
})
101
127
.detach();
102
128
}
129
130
/// Vermelde personen (naam, Teams-id) uit het bericht; groepen en dubbelen niet.
131
fn mentioned_users(mentions_json: &str) -> Vec<(String, String)> {
132
let infos: Vec<teams_core::MentionInfo> =
133
serde_json::from_str(mentions_json).unwrap_or_default();
134
let mut users: Vec<(String, String)> = Vec::new();
135
for info in infos.into_iter().filter(|info| !info.group) {
136
let Some(user_id) = info.user_id.filter(|id| !id.is_empty()) else {
137
continue;
138
};
139
let name = info.name.trim().to_owned();
140
if name.is_empty() || users.iter().any(|(_, known)| *known == user_id) {
141
continue;
142
}
143
users.push((name, user_id));
144
}
145
users.truncate(MENTIONS_MAX);
146
users
147
}
148
149
/// Zoveel profielen halen we hooguit op voor één bericht.
150
const MENTIONS_MAX: usize = 10;
151
152
#[cfg(test)]
153
mod tests {
154
use super::mentioned_users;
155
156
#[test]
157
fn mentioned_users_skips_groups_and_duplicates() {
158
let json = r#"[
159
{"user_id":"8:orgid:a","name":"Jonas Ortega","id":0},
160
{"user_id":"8:orgid:a","name":"Jonas","id":1},
161
{"user_id":null,"name":"Iedereen","id":2,"group":true},
162
{"user_id":"8:orgid:b","name":"Mara","id":3}
163
]"#;
164
assert_eq!(
165
mentioned_users(json),
166
[
167
("Jonas Ortega".to_owned(), "8:orgid:a".to_owned()),
168
("Mara".to_owned(), "8:orgid:b".to_owned())
169
]
170
);
171
assert!(mentioned_users("geen json").is_empty());
172
}
173
}
@@ -1,4 +1,5 @@1
//! Berichtmenu: «Ticket maken in Asclepius» en «Taak maken in Ponos».1
//! Berichtmenu: «Ticket maken in Asclepius» en «Taak maken in Ponos» (beide een2
//! dialoog in de app, vooraf ingevuld met het bericht).2
//!3
//!3
//! Upstream-haak: `views/message_actions.rs` (veld `kvt` in `MessageMenu`) en4
//! Upstream-haak: `views/message_actions.rs` (veld `kvt` in `MessageMenu`) en4
//! `views/conversation.rs` (`message_menu`).5
//! `views/conversation.rs` (`message_menu`).@@ -8,10 +9,10 @@ use std::rc::Rc;8
use chrono::Local;9
use chrono::Local;9
use gpui_kit::assets::IconName;10
use gpui_kit::assets::IconName;10
use gpui_kit::*;11
use gpui_kit::*;11
use kvt_sleutels::asclepius::{MessageSource, new_ticket_url};12
use kvt_sleutels::asclepius::MessageSource;12
use kvt_sleutels::format::date_time_nl;13
use kvt_sleutels::format::date_time_nl;13
14
14
use super::{base_url, installed, open_external};15
use super::installed;15
use crate::app_state::AppHandle;16
use crate::app_state::AppHandle;16
use crate::i18n::tr;17
use crate::i18n::tr;17
use crate::runtime;18
use crate::runtime;@@ -52,7 +53,7 @@ pub fn menu_entries(conversation_id: Option<String>, message_id: &str, cx: &App)52
entry(53
entry(53
"kvt.message.asclepius",54
"kvt.message.asclepius",54
IconName::Ticket,55
IconName::Ticket,55
|source, _, cx| open_external(&new_ticket_url(&base_url(), &source), cx),56
|source, window, cx| super::ticket_form::open_new(Some(source), window, cx),56
),57
),57
entry(58
entry(58
"kvt.message.ponos",59
"kvt.message.ponos",@@ -82,7 +83,9 @@ fn with_source(82
sender: record.sender_name.clone().unwrap_or_default(),83
sender: record.sender_name.clone().unwrap_or_default(),83
sent_at: date_time_nl(record.created_at.with_timezone(&Local).naive_local()),84
sent_at: date_time_nl(record.created_at.with_timezone(&Local).naive_local()),84
link: None,85
link: None,86
mentions: Vec::new(),85
};87
};88
let mentioned = mentioned_users(&record.mentions_json);86
let Some(engine) = state.engine.clone() else {89
let Some(engine) = state.engine.clone() else {87
let link = state90
let link = state88
.mode91
.mode@@ -92,11 +95,79 @@ fn with_source(92
return;95
return;93
};96
};94
let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned());97
let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned());95
let linking =98
let linking = runtime::spawn(async move {96
runtime::spawn(async move { engine.message_link(&conversation_id, &message_id).await });99
let link = engine100
.message_link(&conversation_id, &message_id)101
.await102
.ok();103
// Vermeldingen: het adres via het profiel (best effort), voor `@naam:domein` in Asclepius.104
let mut mentions = Vec::new();105
for (name, user_id) in mentioned {106
if let Ok(profile) = engine.person_profile(&user_id).await107
&& let Some(email) = profile.email.filter(|email| email.contains('@'))108
{109
mentions.push((name, email));110
}111
}112
(link, mentions)113
});97
cx.spawn(async move |cx| {114
cx.spawn(async move |cx| {98
let link = linking.await.ok().and_then(Result::ok);115
let (link, mentions) = linking.await.unwrap_or_default();99
cx.update(|cx| then(MessageSource { link, ..source }, cx));116
cx.update(|cx| {117
then(118
MessageSource {119
link,120
mentions,121
..source122
},123
cx,124
)125
});100
})126
})101
.detach();127
.detach();102
}128
}129
130
/// Vermelde personen (naam, Teams-id) uit het bericht; groepen en dubbelen niet.131
fn mentioned_users(mentions_json: &str) -> Vec<(String, String)> {132
let infos: Vec<teams_core::MentionInfo> =133
serde_json::from_str(mentions_json).unwrap_or_default();134
let mut users: Vec<(String, String)> = Vec::new();135
for info in infos.into_iter().filter(|info| !info.group) {136
let Some(user_id) = info.user_id.filter(|id| !id.is_empty()) else {137
continue;138
};139
let name = info.name.trim().to_owned();140
if name.is_empty() || users.iter().any(|(_, known)| *known == user_id) {141
continue;142
}143
users.push((name, user_id));144
}145
users.truncate(MENTIONS_MAX);146
users147
}148
149
/// Zoveel profielen halen we hooguit op voor één bericht.150
const MENTIONS_MAX: usize = 10;151
152
#[cfg(test)]153
mod tests {154
use super::mentioned_users;155
156
#[test]157
fn mentioned_users_skips_groups_and_duplicates() {158
let json = r#"[159
{"user_id":"8:orgid:a","name":"Jonas Ortega","id":0},160
{"user_id":"8:orgid:a","name":"Jonas","id":1},161
{"user_id":null,"name":"Iedereen","id":2,"group":true},162
{"user_id":"8:orgid:b","name":"Mara","id":3}163
]"#;164
assert_eq!(165
mentioned_users(json),166
[167
("Jonas Ortega".to_owned(), "8:orgid:a".to_owned()),168
("Mara".to_owned(), "8:orgid:b".to_owned())169
]170
);171
assert!(mentioned_users("geen json").is_empty());172
}173
}@@ -6,15 +6,19 @@
6
6
//! geen eigen berichtformaten). Zie KVT-FORK.md en ADR 0024.
7
7
//!
8
8
//! Daarnaast: «Ticket maken in Asclepius» en «Taak maken in Ponos» in het
9
//! berichtmenu (`message`), het paneel «Mijn taken» (`tasks`) en de eigen
10
//! Daedalus-planning als read-only agenda (`calendar`).
9
//! berichtmenu (`message`, `tasks`), het Ponos-bord achter de tegel in de
10
//! navigatierail (`board`), de Asclepius-tegel eronder (`tickets`), de eigen
11
//! Daedalus-planning als read-only agenda (`calendar`) en eigen vensterknoppen
12
//! in de titelbalk (`window_controls`).
11
13
//!
12
14
//! Upstream-haken: `views/shell.rs` (install, overlay, dialog-telling),
13
15
//! `views/message_row.rs` en `views/post_card.rs` (kaartjes), `settings/general.rs`
14
16
//! (instellingen, via `settings/kvt.rs`), `views/composer/plus_menu.rs` (picker), `views/composer.rs`
15
17
//! (`mod kvt`), `views/message_actions.rs` en `views/conversation.rs` (berichtmenu),
16
//! `views/status_menu.rs` (Mijn taken), `app-state/src/call/week.rs` (agenda).
18
//! `views/rail.rs`, `views/sidebar.rs` en `views/shell.rs` (Ponos-tegel en -bord),
19
//! `app-state/src/call/week.rs` (agenda).
17
20
21
mod board;
18
22
pub mod calendar;
19
23
mod card;
20
24
mod demo;
@@ -23,6 +27,9 @@ mod modal;
23
27
mod picker;
24
28
mod session;
25
29
mod tasks;
30
mod ticket_form;
31
mod tickets;
32
pub mod window_controls;
26
33
27
34
use std::collections::HashMap;
28
35
@@ -34,11 +41,13 @@ use crate::app_state::AppHandle;
34
41
use crate::i18n::tr;
35
42
use crate::runtime;
36
43
44
pub use board::{board_opened, board_view};
37
45
pub use card::{blocks_without_card_links, message_cards};
38
46
pub use message::{MenuEntry, menu_entries};
39
47
pub use modal::render_modal;
40
48
pub use picker::{open_picker, plus_item};
41
pub use tasks::extend_settings_menu;
49
pub use tickets::{open_ticket_link, tickets_opened, tickets_unread, tickets_view};
50
pub use window_controls::{title_bar_system_window_controls, title_buttons};
42
51
43
52
/// Alleen voor testen tegen een andere Login/Mímir (bijv. .test); altijd https.
44
53
const BASE_URL_ENV: &str = "KVT_SLEUTELS_URL";
@@ -83,9 +92,14 @@ pub(crate) struct Kvt {
83
92
connecting: Option<tokio::task::AbortHandle>,
84
93
connect_generation: u64,
85
94
ponos_dialog: Option<Entity<tasks::PonosDialog>>,
86
tasks: Option<tasks::TasksLoad>,
87
/// Alleen `--demo`: «Mijn taken» zonder Ponos.
88
demo_tasks: Vec<kvt_sleutels::ponos::PonosTask>,
95
/// Ponos-bord in het hoofdpaneel (aangemaakt bij de eerste keer openen).
96
board: Option<Entity<board::PonosBoard>>,
97
/// Asclepius-tickets in het hoofdpaneel (ook voor de badge op de tegel).
98
tickets: Option<Entity<tickets::TicketsPage>>,
99
/// «Nieuw ticket maken» (ook vanuit een bericht).
100
ticket_form: Option<Entity<ticket_form::TicketForm>>,
101
/// Ticketvenster na een klik op een ticketlink (alleen met toegang).
102
ticket_window: Option<Entity<tickets::TicketThread>>,
89
103
/// Daedalus-planning in de agenda (instelling).
90
104
planning: bool,
91
105
/// Token waarmee de agendabron nu staat (zie `calendar::sync`).
@@ -118,8 +132,10 @@ pub fn install(demo: bool, cx: &mut App) {
118
132
connecting: None,
119
133
connect_generation: 0,
120
134
ponos_dialog: None,
121
tasks: None,
122
demo_tasks: if demo { demo::my_tasks() } else { Vec::new() },
135
board: None,
136
tickets: None,
137
ticket_form: None,
138
ticket_window: None,
123
139
planning: true,
124
140
calendar_source: None,
125
141
});
@@ -505,13 +521,28 @@ pub fn disconnect(cx: &mut App) {
505
521
notice(tr("kvt.notice.disconnected"), cx);
506
522
}
507
523
524
/// KVT-tegels in de navigatierail.
525
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
526
pub enum RailTile {
527
Ponos,
528
Asclepius,
529
}
530
531
/// Navigatierail: Ponos direct onder Agents, Asclepius daaronder (laatste tegels).
532
pub fn with_rail_tiles<T>(mut items: Vec<T>, tile: impl Fn(RailTile, String) -> T) -> Vec<T> {
533
items.push(tile(RailTile::Ponos, tr("kvt.rail.ponos")));
534
items.push(tile(RailTile::Asclepius, tr("kvt.rail.asclepius")));
535
items
536
}
537
508
538
/// Telt mee voor de modale lagen van de shell.
509
539
pub fn dialog_open(cx: &App) -> bool {
510
540
read(cx, |kvt| {
511
541
kvt.modal.is_some()
512
542
|| kvt.picker.is_some()
513
543
|| kvt.ponos_dialog.is_some()
514
|| kvt.tasks.is_some()
544
|| kvt.ticket_form.is_some()
545
|| kvt.ticket_window.is_some()
515
546
})
516
547
.unwrap_or(false)
517
548
}
@@ -525,18 +556,31 @@ pub fn overlay(cx: &App) -> Vec<AnyElement> {
525
556
if let Some(picker) = read(cx, |kvt| kvt.picker.clone()).flatten() {
526
557
layers.push(picker.into_any_element());
527
558
}
528
if let Some(tasks) = tasks::render_tasks(cx) {
529
layers.push(tasks);
530
}
531
559
if let Some(dialog) = read(cx, |kvt| kvt.ponos_dialog.clone()).flatten() {
532
560
layers.push(dialog.into_any_element());
533
561
}
562
if let Some(thread) = read(cx, |kvt| kvt.ticket_window.clone()).flatten() {
563
layers.push(tickets::window_overlay(thread));
564
}
565
if let Some(form) = read(cx, |kvt| kvt.ticket_form.clone()).flatten() {
566
layers.push(form.into_any_element());
567
}
534
568
layers
535
569
}
536
570
537
571
#[cfg(test)]
538
572
mod tests {
539
use super::{device_name, host_of};
573
use super::{device_name, host_of, with_rail_tiles};
574
575
#[test]
576
fn ponos_then_asclepius_come_last_below_agents() {
577
app_base::ui_locale::apply_locale("nl");
578
let items = with_rail_tiles(
579
vec!["Activiteit".to_owned(), "Agents".to_owned()],
580
|_, label| label,
581
);
582
assert_eq!(items, ["Activiteit", "Agents", "Ponos", "Asclepius"]);
583
}
540
584
541
585
#[test]
542
586
fn host_of_base_url() {
@@ -6,15 +6,19 @@6
//! geen eigen berichtformaten). Zie KVT-FORK.md en ADR 0024.6
//! geen eigen berichtformaten). Zie KVT-FORK.md en ADR 0024.7
//!7
//!8
//! Daarnaast: «Ticket maken in Asclepius» en «Taak maken in Ponos» in het8
//! Daarnaast: «Ticket maken in Asclepius» en «Taak maken in Ponos» in het9
//! berichtmenu (`message`), het paneel «Mijn taken» (`tasks`) en de eigen9
//! berichtmenu (`message`, `tasks`), het Ponos-bord achter de tegel in de10
//! Daedalus-planning als read-only agenda (`calendar`).10
//! navigatierail (`board`), de Asclepius-tegel eronder (`tickets`), de eigen11
//! Daedalus-planning als read-only agenda (`calendar`) en eigen vensterknoppen12
//! in de titelbalk (`window_controls`).11
//!13
//!12
//! Upstream-haken: `views/shell.rs` (install, overlay, dialog-telling),14
//! Upstream-haken: `views/shell.rs` (install, overlay, dialog-telling),13
//! `views/message_row.rs` en `views/post_card.rs` (kaartjes), `settings/general.rs`15
//! `views/message_row.rs` en `views/post_card.rs` (kaartjes), `settings/general.rs`14
//! (instellingen, via `settings/kvt.rs`), `views/composer/plus_menu.rs` (picker), `views/composer.rs`16
//! (instellingen, via `settings/kvt.rs`), `views/composer/plus_menu.rs` (picker), `views/composer.rs`15
//! (`mod kvt`), `views/message_actions.rs` en `views/conversation.rs` (berichtmenu),17
//! (`mod kvt`), `views/message_actions.rs` en `views/conversation.rs` (berichtmenu),16
//! `views/status_menu.rs` (Mijn taken), `app-state/src/call/week.rs` (agenda).18
//! `views/rail.rs`, `views/sidebar.rs` en `views/shell.rs` (Ponos-tegel en -bord),19
//! `app-state/src/call/week.rs` (agenda).17
20
21
mod board;18
pub mod calendar;22
pub mod calendar;19
mod card;23
mod card;20
mod demo;24
mod demo;@@ -23,6 +27,9 @@ mod modal;23
mod picker;27
mod picker;24
mod session;28
mod session;25
mod tasks;29
mod tasks;30
mod ticket_form;31
mod tickets;32
pub mod window_controls;26
33
27
use std::collections::HashMap;34
use std::collections::HashMap;28
35
@@ -34,11 +41,13 @@ use crate::app_state::AppHandle;34
use crate::i18n::tr;41
use crate::i18n::tr;35
use crate::runtime;42
use crate::runtime;36
43
44
pub use board::{board_opened, board_view};37
pub use card::{blocks_without_card_links, message_cards};45
pub use card::{blocks_without_card_links, message_cards};38
pub use message::{MenuEntry, menu_entries};46
pub use message::{MenuEntry, menu_entries};39
pub use modal::render_modal;47
pub use modal::render_modal;40
pub use picker::{open_picker, plus_item};48
pub use picker::{open_picker, plus_item};41
pub use tasks::extend_settings_menu;49
pub use tickets::{open_ticket_link, tickets_opened, tickets_unread, tickets_view};50
pub use window_controls::{title_bar_system_window_controls, title_buttons};42
51
43
/// Alleen voor testen tegen een andere Login/Mímir (bijv. .test); altijd https.52
/// Alleen voor testen tegen een andere Login/Mímir (bijv. .test); altijd https.44
const BASE_URL_ENV: &str = "KVT_SLEUTELS_URL";53
const BASE_URL_ENV: &str = "KVT_SLEUTELS_URL";@@ -83,9 +92,14 @@ pub(crate) struct Kvt {83
connecting: Option<tokio::task::AbortHandle>,92
connecting: Option<tokio::task::AbortHandle>,84
connect_generation: u64,93
connect_generation: u64,85
ponos_dialog: Option<Entity<tasks::PonosDialog>>,94
ponos_dialog: Option<Entity<tasks::PonosDialog>>,86
tasks: Option<tasks::TasksLoad>,95
/// Ponos-bord in het hoofdpaneel (aangemaakt bij de eerste keer openen).87
/// Alleen `--demo`: «Mijn taken» zonder Ponos.96
board: Option<Entity<board::PonosBoard>>,88
demo_tasks: Vec<kvt_sleutels::ponos::PonosTask>,97
/// Asclepius-tickets in het hoofdpaneel (ook voor de badge op de tegel).98
tickets: Option<Entity<tickets::TicketsPage>>,99
/// «Nieuw ticket maken» (ook vanuit een bericht).100
ticket_form: Option<Entity<ticket_form::TicketForm>>,101
/// Ticketvenster na een klik op een ticketlink (alleen met toegang).102
ticket_window: Option<Entity<tickets::TicketThread>>,89
/// Daedalus-planning in de agenda (instelling).103
/// Daedalus-planning in de agenda (instelling).90
planning: bool,104
planning: bool,91
/// Token waarmee de agendabron nu staat (zie `calendar::sync`).105
/// Token waarmee de agendabron nu staat (zie `calendar::sync`).@@ -118,8 +132,10 @@ pub fn install(demo: bool, cx: &mut App) {118
connecting: None,132
connecting: None,119
connect_generation: 0,133
connect_generation: 0,120
ponos_dialog: None,134
ponos_dialog: None,121
tasks: None,135
board: None,122
demo_tasks: if demo { demo::my_tasks() } else { Vec::new() },136
tickets: None,137
ticket_form: None,138
ticket_window: None,123
planning: true,139
planning: true,124
calendar_source: None,140
calendar_source: None,125
});141
});@@ -505,13 +521,28 @@ pub fn disconnect(cx: &mut App) {505
notice(tr("kvt.notice.disconnected"), cx);521
notice(tr("kvt.notice.disconnected"), cx);506
}522
}507
523
524
/// KVT-tegels in de navigatierail.525
#[derive(Debug, Clone, Copy, PartialEq, Eq)]526
pub enum RailTile {527
Ponos,528
Asclepius,529
}530
531
/// Navigatierail: Ponos direct onder Agents, Asclepius daaronder (laatste tegels).532
pub fn with_rail_tiles<T>(mut items: Vec<T>, tile: impl Fn(RailTile, String) -> T) -> Vec<T> {533
items.push(tile(RailTile::Ponos, tr("kvt.rail.ponos")));534
items.push(tile(RailTile::Asclepius, tr("kvt.rail.asclepius")));535
items536
}537
508
/// Telt mee voor de modale lagen van de shell.538
/// Telt mee voor de modale lagen van de shell.509
pub fn dialog_open(cx: &App) -> bool {539
pub fn dialog_open(cx: &App) -> bool {510
read(cx, |kvt| {540
read(cx, |kvt| {511
kvt.modal.is_some()541
kvt.modal.is_some()512
|| kvt.picker.is_some()542
|| kvt.picker.is_some()513
|| kvt.ponos_dialog.is_some()543
|| kvt.ponos_dialog.is_some()514
|| kvt.tasks.is_some()544
|| kvt.ticket_form.is_some()545
|| kvt.ticket_window.is_some()515
})546
})516
.unwrap_or(false)547
.unwrap_or(false)517
}548
}@@ -525,18 +556,31 @@ pub fn overlay(cx: &App) -> Vec<AnyElement> {525
if let Some(picker) = read(cx, |kvt| kvt.picker.clone()).flatten() {556
if let Some(picker) = read(cx, |kvt| kvt.picker.clone()).flatten() {526
layers.push(picker.into_any_element());557
layers.push(picker.into_any_element());527
}558
}528
if let Some(tasks) = tasks::render_tasks(cx) {529
layers.push(tasks);530
}531
if let Some(dialog) = read(cx, |kvt| kvt.ponos_dialog.clone()).flatten() {559
if let Some(dialog) = read(cx, |kvt| kvt.ponos_dialog.clone()).flatten() {532
layers.push(dialog.into_any_element());560
layers.push(dialog.into_any_element());533
}561
}562
if let Some(thread) = read(cx, |kvt| kvt.ticket_window.clone()).flatten() {563
layers.push(tickets::window_overlay(thread));564
}565
if let Some(form) = read(cx, |kvt| kvt.ticket_form.clone()).flatten() {566
layers.push(form.into_any_element());567
}534
layers568
layers535
}569
}536
570
537
#[cfg(test)]571
#[cfg(test)]538
mod tests {572
mod tests {539
use super::{device_name, host_of};573
use super::{device_name, host_of, with_rail_tiles};574
575
#[test]576
fn ponos_then_asclepius_come_last_below_agents() {577
app_base::ui_locale::apply_locale("nl");578
let items = with_rail_tiles(579
vec!["Activiteit".to_owned(), "Agents".to_owned()],580
|_, label| label,581
);582
assert_eq!(items, ["Activiteit", "Agents", "Ponos", "Asclepius"]);583
}540
584
541
#[test]585
#[test]542
fn host_of_base_url() {586
fn host_of_base_url() {@@ -1,23 +1,19 @@
1
//! Ponos: «Taak maken van bericht» (dialoog) en het paneel «Mijn taken».
2
//!
3
//! Upstream-haak voor het paneel: `views/status_menu.rs` (instellingenmenu).
1
//! Ponos: «Taak maken van bericht» (dialoog) en gedeelde bouwstenen voor het
2
//! bord (`board.rs`). Het oude paneel «Mijn taken» (…-menu) is vervangen door
3
//! de tegel Ponos in de navigatierail.
4
4
5
use gpui_kit::assets::IconName;
6
5
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
7
use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
8
use gpui_kit::component::scroll::ScrollableElement as _;
9
6
use gpui_kit::component::{h_flex, v_flex};
10
7
use gpui_kit::prelude::FluentBuilder as _;
11
8
use gpui_kit::*;
12
9
use kvt_sleutels::ClientError;
13
10
use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource};
14
use kvt_sleutels::format::iso_date_nl;
15
use kvt_sleutels::ponos::{PonosGroup, PonosTask};
11
use kvt_sleutels::ponos::PonosGroup;
16
12
17
13
use super::modal::{primary_button, secondary_button};
18
14
use super::{
19
Link, base_url, connect, error_text, forget_token, installed, is_demo, link, notice,
20
open_external, read, token_and_client, update,
15
Link, connect, error_text, forget_token, installed, is_demo, link, notice, token_and_client,
16
update,
21
17
};
22
18
use crate::app_state::AppHandle;
23
19
use crate::i18n::tr;
@@ -26,7 +22,6 @@ use crate::theme::{self, ElevatedSurface as _};
26
22
use crate::views::widgets::symbol;
27
23
28
24
pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog";
29
pub const KVT_TASKS_PANEL_TAG: &str = "kvt-tasks-panel";
30
25
/// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag).
31
26
const GROUP_META_KEY: &str = "kvt.ponos.group";
32
27
/// Ponos staat 200 tekens toe in de titel.
@@ -40,15 +35,6 @@ const SECTION_GAP: f32 = 12.;
40
35
const CLOSE_SIZE: f32 = 28.;
41
36
const CHIP_HEIGHT: f32 = 28.;
42
37
const FIELD_HEIGHT: f32 = 36.;
43
const ROW_HEIGHT: f32 = 48.;
44
const LIST_MAX_HEIGHT: f32 = 420.;
45
46
#[derive(Clone)]
47
pub(crate) enum TasksLoad {
48
Loading,
49
Loaded(Vec<PonosTask>),
50
Failed(ClientError),
51
}
52
38
53
39
#[derive(Clone)]
54
40
enum Groups {
@@ -195,7 +181,7 @@ impl PonosDialog {
195
181
Ok(_) => {
196
182
close_create(cx);
197
183
notice(tr("kvt.ponos.created"), cx);
198
refresh_tasks_if_open(cx);
184
super::board::refresh_board_if_open(cx);
199
185
}
200
186
Err(error) => {
201
187
if error == ClientError::Unauthorized {
@@ -303,245 +289,9 @@ impl Render for PonosDialog {
303
289
}
304
290
}
305
291
306
// --- Mijn taken -------------------------------------------------------------
307
308
/// Regel «Mijn taken in Ponos» in het instellingenmenu (`…` rechtsboven).
309
pub fn extend_settings_menu(popup: PopupMenu, cx: &App) -> PopupMenu {
310
if !installed(cx) {
311
return popup;
312
}
313
popup.separator().item(
314
PopupMenuItem::new(tr("kvt.tasks.menu"))
315
.icon(IconName::ClipboardCheck)
316
.on_click(|_, _, cx| open_tasks(cx)),
317
)
318
}
319
320
pub(crate) fn open_tasks(cx: &mut App) {
321
update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loading));
322
load_tasks(cx);
323
}
324
325
fn close_tasks(cx: &mut App) {
326
update(cx, |kvt| kvt.tasks = None);
327
}
328
329
fn refresh_tasks_if_open(cx: &mut App) {
330
if read(cx, |kvt| kvt.tasks.is_some()).unwrap_or(false) {
331
load_tasks(cx);
332
}
333
}
334
335
fn load_tasks(cx: &mut App) {
336
if is_demo(cx) {
337
let tasks = read(cx, |kvt| kvt.demo_tasks.clone()).unwrap_or_default();
338
update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loaded(tasks)));
339
return;
340
}
341
let Some((token, client)) = token_and_client(cx) else {
342
return;
343
};
344
let loading = runtime::spawn(async move { client.ponos_my_tasks(&token).await });
345
cx.spawn(async move |cx| {
346
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
347
cx.update(|cx| {
348
if result == Err(ClientError::Unauthorized) {
349
forget_token(cx);
350
}
351
let load = match result {
352
Ok(tasks) => TasksLoad::Loaded(tasks),
353
Err(error) => TasksLoad::Failed(error),
354
};
355
update(cx, |kvt| {
356
if kvt.tasks.is_some() {
357
kvt.tasks = Some(load);
358
}
359
});
360
});
361
})
362
.detach();
363
}
364
365
fn complete(task: PonosTask, cx: &mut App) {
366
let remove = |kvt: &mut super::Kvt, id: &str| {
367
if let Some(TasksLoad::Loaded(tasks)) = kvt.tasks.as_mut() {
368
tasks.retain(|task| task.id != id);
369
}
370
kvt.demo_tasks.retain(|task| task.id != id);
371
};
372
if is_demo(cx) {
373
update(cx, |kvt| remove(kvt, &task.id));
374
notice(tr("kvt.tasks.completed"), cx);
375
return;
376
}
377
let Some((token, client)) = token_and_client(cx) else {
378
return;
379
};
380
let (group, id) = (task.group().to_owned(), task.id.clone());
381
let completing = runtime::spawn({
382
let id = id.clone();
383
async move { client.ponos_complete_task(&token, &group, &id).await }
384
});
385
cx.spawn(async move |cx| {
386
let result = completing.await.unwrap_or(Err(ClientError::Unavailable));
387
cx.update(|cx| match result {
388
Ok(()) => {
389
update(cx, |kvt| remove(kvt, &id));
390
notice(tr("kvt.tasks.completed"), cx);
391
}
392
Err(error) => {
393
if error == ClientError::Unauthorized {
394
forget_token(cx);
395
}
396
notice(ponos_error(&error), cx);
397
}
398
});
399
})
400
.detach();
401
}
402
403
pub fn render_tasks(cx: &App) -> Option<AnyElement> {
404
let load = read(cx, |kvt| kvt.tasks.clone()).flatten()?;
405
let body = if !matches!(link(cx), Link::Linked(_)) {
406
not_linked().into_any_element()
407
} else {
408
match load {
409
TasksLoad::Loading => muted(tr("kvt.card.loading")).into_any_element(),
410
TasksLoad::Failed(error) => muted(ponos_error(&error)).into_any_element(),
411
TasksLoad::Loaded(tasks) if tasks.is_empty() => {
412
muted(tr("kvt.tasks.empty")).into_any_element()
413
}
414
TasksLoad::Loaded(tasks) => v_flex()
415
.id("kvt-tasks-list")
416
.w_full()
417
.max_h(px(LIST_MAX_HEIGHT))
418
.overflow_y_scrollbar()
419
.children(
420
tasks
421
.into_iter()
422
.enumerate()
423
.map(|(index, task)| task_row(index, task)),
424
)
425
.into_any_element(),
426
}
427
};
428
let ponos = format!("{}/ponos/", base_url());
429
Some(
430
layer("kvt-tasks", |cx| close_tasks(cx))
431
.child(
432
panel(KVT_TASKS_PANEL_TAG)
433
.child(header(tr("kvt.tasks.title"), String::new(), |cx| {
434
close_tasks(cx)
435
}))
436
.child(body)
437
.child(
438
h_flex()
439
.w_full()
440
.gap(px(8.))
441
.child(
442
secondary_button(
443
"kvt-tasks-open",
444
"open_in_new",
445
tr("kvt.tasks.open_ponos"),
446
)
447
.on_click(move |_, _, cx| open_external(&ponos, cx)),
448
)
449
.child(
450
secondary_button(
451
"kvt-tasks-refresh",
452
"refresh",
453
tr("kvt.card.refresh"),
454
)
455
.on_click(|_, _, cx| open_tasks(cx)),
456
),
457
),
458
)
459
.into_any_element(),
460
)
461
}
462
463
fn task_row(index: usize, task: PonosTask) -> AnyElement {
464
let today = chrono::Local::now()
465
.date_naive()
466
.format("%Y-%m-%d")
467
.to_string();
468
let overdue = !task.due_date.is_empty() && task.due_date.as_str() < today.as_str();
469
let mut detail = Vec::new();
470
if !task.home_group_name.is_empty() {
471
detail.push(task.home_group_name.clone());
472
}
473
if task.status == "in_progress" {
474
detail.push(tr("kvt.tasks.in_progress"));
475
}
476
let due = iso_date_nl(&task.due_date);
477
let url = task.url(&base_url());
478
let done = task.clone();
479
h_flex()
480
.id(ElementId::Name(format!("kvt-task-{index}").into()))
481
.w_full()
482
.h(px(ROW_HEIGHT))
483
.flex_none()
484
.px(px(8.))
485
.gap(px(10.))
486
.items_center()
487
.rounded(px(6.))
488
.cursor_pointer()
489
.hover(|row| row.bg(theme::popup_hover()))
490
.on_click(move |_, _, cx| open_external(&url, cx))
491
.child(
492
div()
493
.id(ElementId::Name(format!("kvt-task-done-{index}").into()))
494
.size(px(CLOSE_SIZE))
495
.flex_none()
496
.flex()
497
.items_center()
498
.justify_center()
499
.rounded_full()
500
.hover(|button| button.bg(theme::row_hover()))
501
.on_click(move |_, _, cx| {
502
cx.stop_propagation();
503
complete(done.clone(), cx);
504
})
505
.child(symbol("check_circle", 18., theme::text_muted())),
506
)
507
.child(
508
v_flex()
509
.flex_1()
510
.min_w_0()
511
.child(
512
div()
513
.truncate()
514
.text_size(px(13.))
515
.text_color(theme::text())
516
.child(task.title.clone()),
517
)
518
.when(!detail.is_empty(), |column| {
519
column.child(
520
div()
521
.truncate()
522
.text_size(px(12.))
523
.text_color(theme::text_muted())
524
.child(detail.join(" · ")),
525
)
526
}),
527
)
528
.children(due.map(|due| {
529
div()
530
.flex_none()
531
.text_size(px(12.))
532
.text_color(if overdue {
533
theme::red_soft()
534
} else {
535
theme::text_muted()
536
})
537
.child(due)
538
}))
539
.into_any_element()
540
}
541
542
292
// --- gedeelde bouwstenen ----------------------------------------------------
543
293
544
fn ponos_error(error: &ClientError) -> String {
294
pub(super) fn ponos_error(error: &ClientError) -> String {
545
295
match error {
546
296
ClientError::Forbidden => tr("kvt.ponos.forbidden"),
547
297
ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"),
@@ -628,7 +378,7 @@ fn header(title: String, detail: String, close: fn(&mut App)) -> Div {
628
378
)
629
379
}
630
380
631
fn label(text: String) -> Div {
381
pub(super) fn label(text: String) -> Div {
632
382
div()
633
383
.text_size(px(12.))
634
384
.font_weight(FontWeight::SEMIBOLD)
@@ -636,7 +386,7 @@ fn label(text: String) -> Div {
636
386
.child(text)
637
387
}
638
388
639
fn muted(text: String) -> Div {
389
pub(super) fn muted(text: String) -> Div {
640
390
div()
641
391
.w_full()
642
392
.py(px(8.))
@@ -645,7 +395,7 @@ fn muted(text: String) -> Div {
645
395
.child(text)
646
396
}
647
397
648
fn field() -> Div {
398
pub(super) fn field() -> Div {
649
399
h_flex()
650
400
.w_full()
651
401
.h(px(FIELD_HEIGHT))
@@ -656,7 +406,7 @@ fn field() -> Div {
656
406
.bg(theme::popup_hover())
657
407
}
658
408
659
fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
409
pub(super) fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
660
410
h_flex()
661
411
.id(id)
662
412
.h(px(CHIP_HEIGHT))
@@ -680,7 +430,7 @@ fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
680
430
.child(label)
681
431
}
682
432
683
fn not_linked() -> Div {
433
pub(super) fn not_linked() -> Div {
684
434
v_flex()
685
435
.w_full()
686
436
.gap(px(8.))
@@ -1,23 +1,19 @@1
//! Ponos: «Taak maken van bericht» (dialoog) en het paneel «Mijn taken».1
//! Ponos: «Taak maken van bericht» (dialoog) en gedeelde bouwstenen voor het2
//!2
//! bord (`board.rs`). Het oude paneel «Mijn taken» (…-menu) is vervangen door3
//! Upstream-haak voor het paneel: `views/status_menu.rs` (instellingenmenu).3
//! de tegel Ponos in de navigatierail.4
4
5
use gpui_kit::assets::IconName;6
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};5
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};7
use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};8
use gpui_kit::component::scroll::ScrollableElement as _;9
use gpui_kit::component::{h_flex, v_flex};6
use gpui_kit::component::{h_flex, v_flex};10
use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;8
use gpui_kit::*;12
use kvt_sleutels::ClientError;9
use kvt_sleutels::ClientError;13
use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource};10
use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource};14
use kvt_sleutels::format::iso_date_nl;11
use kvt_sleutels::ponos::PonosGroup;15
use kvt_sleutels::ponos::{PonosGroup, PonosTask};16
12
17
use super::modal::{primary_button, secondary_button};13
use super::modal::{primary_button, secondary_button};18
use super::{14
use super::{19
Link, base_url, connect, error_text, forget_token, installed, is_demo, link, notice,15
Link, connect, error_text, forget_token, installed, is_demo, link, notice, token_and_client,20
open_external, read, token_and_client, update,16
update,21
};17
};22
use crate::app_state::AppHandle;18
use crate::app_state::AppHandle;23
use crate::i18n::tr;19
use crate::i18n::tr;@@ -26,7 +22,6 @@ use crate::theme::{self, ElevatedSurface as _};26
use crate::views::widgets::symbol;22
use crate::views::widgets::symbol;27
23
28
pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog";24
pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog";29
pub const KVT_TASKS_PANEL_TAG: &str = "kvt-tasks-panel";30
/// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag).25
/// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag).31
const GROUP_META_KEY: &str = "kvt.ponos.group";26
const GROUP_META_KEY: &str = "kvt.ponos.group";32
/// Ponos staat 200 tekens toe in de titel.27
/// Ponos staat 200 tekens toe in de titel.@@ -40,15 +35,6 @@ const SECTION_GAP: f32 = 12.;40
const CLOSE_SIZE: f32 = 28.;35
const CLOSE_SIZE: f32 = 28.;41
const CHIP_HEIGHT: f32 = 28.;36
const CHIP_HEIGHT: f32 = 28.;42
const FIELD_HEIGHT: f32 = 36.;37
const FIELD_HEIGHT: f32 = 36.;43
const ROW_HEIGHT: f32 = 48.;44
const LIST_MAX_HEIGHT: f32 = 420.;45
46
#[derive(Clone)]47
pub(crate) enum TasksLoad {48
Loading,49
Loaded(Vec<PonosTask>),50
Failed(ClientError),51
}52
38
53
#[derive(Clone)]39
#[derive(Clone)]54
enum Groups {40
enum Groups {@@ -195,7 +181,7 @@ impl PonosDialog {195
Ok(_) => {181
Ok(_) => {196
close_create(cx);182
close_create(cx);197
notice(tr("kvt.ponos.created"), cx);183
notice(tr("kvt.ponos.created"), cx);198
refresh_tasks_if_open(cx);184
super::board::refresh_board_if_open(cx);199
}185
}200
Err(error) => {186
Err(error) => {201
if error == ClientError::Unauthorized {187
if error == ClientError::Unauthorized {@@ -303,245 +289,9 @@ impl Render for PonosDialog {303
}289
}304
}290
}305
291
306
// --- Mijn taken -------------------------------------------------------------307
308
/// Regel «Mijn taken in Ponos» in het instellingenmenu (`…` rechtsboven).309
pub fn extend_settings_menu(popup: PopupMenu, cx: &App) -> PopupMenu {310
if !installed(cx) {311
return popup;312
}313
popup.separator().item(314
PopupMenuItem::new(tr("kvt.tasks.menu"))315
.icon(IconName::ClipboardCheck)316
.on_click(|_, _, cx| open_tasks(cx)),317
)318
}319
320
pub(crate) fn open_tasks(cx: &mut App) {321
update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loading));322
load_tasks(cx);323
}324
325
fn close_tasks(cx: &mut App) {326
update(cx, |kvt| kvt.tasks = None);327
}328
329
fn refresh_tasks_if_open(cx: &mut App) {330
if read(cx, |kvt| kvt.tasks.is_some()).unwrap_or(false) {331
load_tasks(cx);332
}333
}334
335
fn load_tasks(cx: &mut App) {336
if is_demo(cx) {337
let tasks = read(cx, |kvt| kvt.demo_tasks.clone()).unwrap_or_default();338
update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loaded(tasks)));339
return;340
}341
let Some((token, client)) = token_and_client(cx) else {342
return;343
};344
let loading = runtime::spawn(async move { client.ponos_my_tasks(&token).await });345
cx.spawn(async move |cx| {346
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));347
cx.update(|cx| {348
if result == Err(ClientError::Unauthorized) {349
forget_token(cx);350
}351
let load = match result {352
Ok(tasks) => TasksLoad::Loaded(tasks),353
Err(error) => TasksLoad::Failed(error),354
};355
update(cx, |kvt| {356
if kvt.tasks.is_some() {357
kvt.tasks = Some(load);358
}359
});360
});361
})362
.detach();363
}364
365
fn complete(task: PonosTask, cx: &mut App) {366
let remove = |kvt: &mut super::Kvt, id: &str| {367
if let Some(TasksLoad::Loaded(tasks)) = kvt.tasks.as_mut() {368
tasks.retain(|task| task.id != id);369
}370
kvt.demo_tasks.retain(|task| task.id != id);371
};372
if is_demo(cx) {373
update(cx, |kvt| remove(kvt, &task.id));374
notice(tr("kvt.tasks.completed"), cx);375
return;376
}377
let Some((token, client)) = token_and_client(cx) else {378
return;379
};380
let (group, id) = (task.group().to_owned(), task.id.clone());381
let completing = runtime::spawn({382
let id = id.clone();383
async move { client.ponos_complete_task(&token, &group, &id).await }384
});385
cx.spawn(async move |cx| {386
let result = completing.await.unwrap_or(Err(ClientError::Unavailable));387
cx.update(|cx| match result {388
Ok(()) => {389
update(cx, |kvt| remove(kvt, &id));390
notice(tr("kvt.tasks.completed"), cx);391
}392
Err(error) => {393
if error == ClientError::Unauthorized {394
forget_token(cx);395
}396
notice(ponos_error(&error), cx);397
}398
});399
})400
.detach();401
}402
403
pub fn render_tasks(cx: &App) -> Option<AnyElement> {404
let load = read(cx, |kvt| kvt.tasks.clone()).flatten()?;405
let body = if !matches!(link(cx), Link::Linked(_)) {406
not_linked().into_any_element()407
} else {408
match load {409
TasksLoad::Loading => muted(tr("kvt.card.loading")).into_any_element(),410
TasksLoad::Failed(error) => muted(ponos_error(&error)).into_any_element(),411
TasksLoad::Loaded(tasks) if tasks.is_empty() => {412
muted(tr("kvt.tasks.empty")).into_any_element()413
}414
TasksLoad::Loaded(tasks) => v_flex()415
.id("kvt-tasks-list")416
.w_full()417
.max_h(px(LIST_MAX_HEIGHT))418
.overflow_y_scrollbar()419
.children(420
tasks421
.into_iter()422
.enumerate()423
.map(|(index, task)| task_row(index, task)),424
)425
.into_any_element(),426
}427
};428
let ponos = format!("{}/ponos/", base_url());429
Some(430
layer("kvt-tasks", |cx| close_tasks(cx))431
.child(432
panel(KVT_TASKS_PANEL_TAG)433
.child(header(tr("kvt.tasks.title"), String::new(), |cx| {434
close_tasks(cx)435
}))436
.child(body)437
.child(438
h_flex()439
.w_full()440
.gap(px(8.))441
.child(442
secondary_button(443
"kvt-tasks-open",444
"open_in_new",445
tr("kvt.tasks.open_ponos"),446
)447
.on_click(move |_, _, cx| open_external(&ponos, cx)),448
)449
.child(450
secondary_button(451
"kvt-tasks-refresh",452
"refresh",453
tr("kvt.card.refresh"),454
)455
.on_click(|_, _, cx| open_tasks(cx)),456
),457
),458
)459
.into_any_element(),460
)461
}462
463
fn task_row(index: usize, task: PonosTask) -> AnyElement {464
let today = chrono::Local::now()465
.date_naive()466
.format("%Y-%m-%d")467
.to_string();468
let overdue = !task.due_date.is_empty() && task.due_date.as_str() < today.as_str();469
let mut detail = Vec::new();470
if !task.home_group_name.is_empty() {471
detail.push(task.home_group_name.clone());472
}473
if task.status == "in_progress" {474
detail.push(tr("kvt.tasks.in_progress"));475
}476
let due = iso_date_nl(&task.due_date);477
let url = task.url(&base_url());478
let done = task.clone();479
h_flex()480
.id(ElementId::Name(format!("kvt-task-{index}").into()))481
.w_full()482
.h(px(ROW_HEIGHT))483
.flex_none()484
.px(px(8.))485
.gap(px(10.))486
.items_center()487
.rounded(px(6.))488
.cursor_pointer()489
.hover(|row| row.bg(theme::popup_hover()))490
.on_click(move |_, _, cx| open_external(&url, cx))491
.child(492
div()493
.id(ElementId::Name(format!("kvt-task-done-{index}").into()))494
.size(px(CLOSE_SIZE))495
.flex_none()496
.flex()497
.items_center()498
.justify_center()499
.rounded_full()500
.hover(|button| button.bg(theme::row_hover()))501
.on_click(move |_, _, cx| {502
cx.stop_propagation();503
complete(done.clone(), cx);504
})505
.child(symbol("check_circle", 18., theme::text_muted())),506
)507
.child(508
v_flex()509
.flex_1()510
.min_w_0()511
.child(512
div()513
.truncate()514
.text_size(px(13.))515
.text_color(theme::text())516
.child(task.title.clone()),517
)518
.when(!detail.is_empty(), |column| {519
column.child(520
div()521
.truncate()522
.text_size(px(12.))523
.text_color(theme::text_muted())524
.child(detail.join(" · ")),525
)526
}),527
)528
.children(due.map(|due| {529
div()530
.flex_none()531
.text_size(px(12.))532
.text_color(if overdue {533
theme::red_soft()534
} else {535
theme::text_muted()536
})537
.child(due)538
}))539
.into_any_element()540
}541
542
// --- gedeelde bouwstenen ----------------------------------------------------292
// --- gedeelde bouwstenen ----------------------------------------------------543
293
544
fn ponos_error(error: &ClientError) -> String {294
pub(super) fn ponos_error(error: &ClientError) -> String {545
match error {295
match error {546
ClientError::Forbidden => tr("kvt.ponos.forbidden"),296
ClientError::Forbidden => tr("kvt.ponos.forbidden"),547
ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"),297
ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"),@@ -628,7 +378,7 @@ fn header(title: String, detail: String, close: fn(&mut App)) -> Div {628
)378
)629
}379
}630
380
631
fn label(text: String) -> Div {381
pub(super) fn label(text: String) -> Div {632
div()382
div()633
.text_size(px(12.))383
.text_size(px(12.))634
.font_weight(FontWeight::SEMIBOLD)384
.font_weight(FontWeight::SEMIBOLD)@@ -636,7 +386,7 @@ fn label(text: String) -> Div {636
.child(text)386
.child(text)637
}387
}638
388
639
fn muted(text: String) -> Div {389
pub(super) fn muted(text: String) -> Div {640
div()390
div()641
.w_full()391
.w_full()642
.py(px(8.))392
.py(px(8.))@@ -645,7 +395,7 @@ fn muted(text: String) -> Div {645
.child(text)395
.child(text)646
}396
}647
397
648
fn field() -> Div {398
pub(super) fn field() -> Div {649
h_flex()399
h_flex()650
.w_full()400
.w_full()651
.h(px(FIELD_HEIGHT))401
.h(px(FIELD_HEIGHT))@@ -656,7 +406,7 @@ fn field() -> Div {656
.bg(theme::popup_hover())406
.bg(theme::popup_hover())657
}407
}658
408
659
fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {409
pub(super) fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {660
h_flex()410
h_flex()661
.id(id)411
.id(id)662
.h(px(CHIP_HEIGHT))412
.h(px(CHIP_HEIGHT))@@ -680,7 +430,7 @@ fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {680
.child(label)430
.child(label)681
}431
}682
432
683
fn not_linked() -> Div {433
pub(super) fn not_linked() -> Div {684
v_flex()434
v_flex()685
.w_full()435
.w_full()686
.gap(px(8.))436
.gap(px(8.))@@ -0,0 +1,680 @@
1
//! Asclepius: «Nieuw ticket maken» in de app, met de velden van het webformulier.
2
//! Ook voor «Ticket maken in Asclepius» in het berichtmenu, dan vooraf ingevuld
3
//! met het bericht; vermeldingen worden `@naam:domein` zoals Asclepius ze kent.
4
5
use std::path::PathBuf;
6
7
use gpui_kit::component::checkbox::Checkbox;
8
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
9
use gpui_kit::component::{Disableable as _, h_flex, v_flex};
10
use gpui_kit::prelude::FluentBuilder as _;
11
use gpui_kit::*;
12
use kvt_sleutels::ClientError;
13
use kvt_sleutels::asclepius::MessageSource;
14
use kvt_sleutels::tickets::{
15
ATTACHMENT_MAX_BYTES, ATTACHMENTS_MAX, DESCRIPTION_MAX, Lookups, NewAttachment, NewTicket,
16
TITLE_MAX, mentions_to_asclepius, mime_for, parse_participants, priority_from_flags,
17
};
18
19
use super::modal::{primary_button, secondary_button};
20
use super::tasks::{chip, field, label, muted, not_linked};
21
use super::tickets::ticket_error;
22
use super::{Link, forget_token, installed, is_demo, link, notice, token_and_client, update};
23
use crate::i18n::{tr, tr_args};
24
use crate::runtime;
25
use crate::theme::{self, ElevatedSurface as _};
26
use crate::views::widgets::symbol;
27
28
pub const KVT_TICKET_FORM_TAG: &str = "kvt-asclepius-form";
29
const BACKDROP_OPACITY: f32 = 0.55;
30
const PANEL_WIDTH: f32 = 560.;
31
const PANEL_MARGIN: f32 = 32.;
32
const PANEL_RADIUS: f32 = 10.;
33
const PANEL_PADDING: f32 = 16.;
34
const SECTION_GAP: f32 = 10.;
35
const CLOSE_SIZE: f32 = 28.;
36
37
#[derive(Clone)]
38
enum LookupState {
39
Loading,
40
Loaded(Lookups),
41
Failed(ClientError),
42
}
43
44
struct PickedFile {
45
name: String,
46
size: usize,
47
attachment: NewAttachment,
48
}
49
50
pub struct TicketForm {
51
source: Option<MessageSource>,
52
lookups: LookupState,
53
category: Option<String>,
54
subcategory: Option<String>,
55
title: Entity<InputState>,
56
description: Entity<TextareaState>,
57
participants: Entity<InputState>,
58
blocked: bool,
59
fully_blocked: bool,
60
files: Vec<PickedFile>,
61
saving: bool,
62
error: Option<String>,
63
}
64
65
/// Opent het formulier; `source` is het bericht bij «Ticket maken in Asclepius».
66
pub(super) fn open_new(source: Option<MessageSource>, window: &mut Window, cx: &mut App) {
67
if !installed(cx) {
68
return;
69
}
70
let form = cx.new(|cx| TicketForm::new(source, window, cx));
71
update(cx, |kvt| kvt.ticket_form = Some(form.clone()));
72
if is_demo(cx) {
73
form.update(cx, |form, cx| form.set_lookups(Ok(demo_lookups()), cx));
74
return;
75
}
76
let Some((token, client)) = token_and_client(cx) else {
77
return;
78
};
79
let loading = runtime::spawn(async move { client.asclepius_lookups(&token).await });
80
let weak = form.downgrade();
81
cx.spawn(async move |cx| {
82
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
83
cx.update(|cx| {
84
if result == Err(ClientError::Unauthorized) {
85
forget_token(cx);
86
}
87
weak.update(cx, |form, cx| form.set_lookups(result, cx))
88
.ok();
89
});
90
})
91
.detach();
92
}
93
94
fn tr_with(key: &str, name: &str, value: String) -> String {
95
tr_args(
96
key,
97
&std::collections::HashMap::from([(name.to_owned(), value)]),
98
)
99
}
100
101
fn close(cx: &mut App) {
102
update(cx, |kvt| kvt.ticket_form = None);
103
}
104
105
/// Knop «Nieuw ticket» in de kop van de tegel.
106
pub(super) fn new_ticket_button<T: 'static>(cx: &mut Context<T>) -> Option<Stateful<Div>> {
107
matches!(link(cx), Link::Linked(_)).then(|| {
108
primary_button("kvt-tickets-new", tr("kvt.tickets.new"))
109
.on_click(|_, window, cx| open_new(None, window, cx))
110
})
111
}
112
113
/// Beschrijving uit het bericht, met de vermeldingen als Asclepius-token.
114
fn prefilled_description(source: &MessageSource) -> String {
115
mentions_to_asclepius(&source.description(DESCRIPTION_MAX), &source.mentions)
116
}
117
118
impl TicketForm {
119
fn new(source: Option<MessageSource>, window: &mut Window, cx: &mut Context<Self>) -> Self {
120
let title_text = source
121
.as_ref()
122
.map(|source| source.title(TITLE_MAX))
123
.unwrap_or_default();
124
let description_text = source
125
.as_ref()
126
.map(prefilled_description)
127
.unwrap_or_default();
128
let title = cx.new(|cx| {
129
InputState::new(window, cx)
130
.placeholder(tr("kvt.tickets.form.title_placeholder"))
131
.default_value(title_text)
132
});
133
let description = cx.new(|cx| {
134
TextareaState::new(window, cx)
135
.auto_grow(4, 10)
136
.placeholder(tr("kvt.tickets.form.description_placeholder"))
137
.default_value(description_text)
138
});
139
let participants = cx.new(|cx| {
140
InputState::new(window, cx).placeholder(tr("kvt.tickets.form.participants_placeholder"))
141
});
142
title.update(cx, |input, cx| input.focus(window, cx));
143
TicketForm {
144
source,
145
lookups: LookupState::Loading,
146
category: None,
147
subcategory: None,
148
title,
149
description,
150
participants,
151
blocked: false,
152
fully_blocked: false,
153
files: Vec::new(),
154
saving: false,
155
error: None,
156
}
157
}
158
159
fn set_lookups(&mut self, result: Result<Lookups, ClientError>, cx: &mut Context<Self>) {
160
self.lookups = match result {
161
Ok(lookups) => LookupState::Loaded(lookups),
162
Err(error) => LookupState::Failed(error),
163
};
164
cx.notify();
165
}
166
167
fn pick_files(&mut self, cx: &mut Context<Self>) {
168
let receiver = cx.prompt_for_paths(PathPromptOptions {
169
files: true,
170
directories: false,
171
multiple: true,
172
prompt: None,
173
});
174
cx.spawn(async move |this, cx| {
175
let Ok(Ok(Some(paths))) = receiver.await else {
176
return;
177
};
178
let reading = runtime::spawn(async move { read_files(paths) });
179
let read = reading.await.unwrap_or_default();
180
this.update(cx, |this, cx| {
181
for file in read {
182
match file {
183
Ok(file) if this.files.len() < ATTACHMENTS_MAX => this.files.push(file),
184
Ok(_) => {
185
this.error = Some(tr_with(
186
"kvt.tickets.form.too_many_files",
187
"max",
188
ATTACHMENTS_MAX.to_string(),
189
))
190
}
191
Err(name) => {
192
this.error =
193
Some(tr_with("kvt.tickets.form.file_too_large", "name", name))
194
}
195
}
196
}
197
cx.notify();
198
})
199
.ok();
200
})
201
.detach();
202
}
203
204
fn save(&mut self, cx: &mut Context<Self>) {
205
if self.saving {
206
return;
207
}
208
let title = self.title.read(cx).value().trim().to_owned();
209
let description = self.description.read(cx).value().trim().to_owned();
210
let participants_text = self.participants.read(cx).value().to_string();
211
let Some(category) = self.category.clone() else {
212
self.error = Some(tr("kvt.tickets.form.pick_category"));
213
cx.notify();
214
return;
215
};
216
if title.is_empty() || description.is_empty() {
217
self.error = Some(tr("kvt.tickets.form.fill_in"));
218
cx.notify();
219
return;
220
}
221
let participant_emails = match parse_participants(&participants_text) {
222
Ok(emails) => emails,
223
Err(bad) => {
224
self.error = Some(tr_with("kvt.tickets.form.bad_email", "email", bad));
225
cx.notify();
226
return;
227
}
228
};
229
let ticket = NewTicket {
230
title,
231
category,
232
subcategory: self.subcategory.clone(),
233
description,
234
priority: priority_from_flags(self.blocked, self.fully_blocked),
235
participant_emails,
236
attachments: self
237
.files
238
.iter()
239
.map(|file| file.attachment.clone())
240
.collect(),
241
};
242
if is_demo(cx) {
243
close(cx);
244
notice(
245
tr_with("kvt.tickets.form.created", "id", "4103".to_owned()),
246
cx,
247
);
248
return;
249
}
250
let Some((token, client)) = token_and_client(cx) else {
251
return;
252
};
253
self.saving = true;
254
self.error = None;
255
cx.notify();
256
let creating =
257
runtime::spawn(async move { client.asclepius_create(&token, &ticket).await });
258
cx.spawn(async move |this, cx| {
259
let result = creating.await.unwrap_or(Err(ClientError::Unavailable));
260
cx.update(|cx| match result {
261
Ok(id) => {
262
close(cx);
263
notice(
264
tr_with("kvt.tickets.form.created", "id", id.to_string()),
265
cx,
266
);
267
super::tickets::created(id, cx);
268
}
269
Err(error) => {
270
if error == ClientError::Unauthorized {
271
forget_token(cx);
272
}
273
this.update(cx, |this, cx| {
274
this.saving = false;
275
this.error = Some(ticket_error(&error));
276
cx.notify();
277
})
278
.ok();
279
}
280
});
281
})
282
.detach();
283
}
284
285
fn categories(&self, cx: &mut Context<Self>) -> AnyElement {
286
let lookups = match &self.lookups {
287
LookupState::Loading => return muted(tr("kvt.card.loading")).into_any_element(),
288
LookupState::Failed(error) => return muted(ticket_error(error)).into_any_element(),
289
LookupState::Loaded(lookups) => lookups,
290
};
291
let categories = h_flex().w_full().flex_wrap().gap(px(6.)).children(
292
lookups
293
.form_categories()
294
.into_iter()
295
.enumerate()
296
.map(|(index, category)| {
297
let selected = self.category.as_deref() == Some(category.as_str());
298
chip(
299
format!("kvt-ticket-category-{index}").into(),
300
category.clone(),
301
selected,
302
)
303
.on_click(cx.listener(move |this, _, _, cx| {
304
if this.category.as_deref() != Some(category.as_str()) {
305
this.category = Some(category.clone());
306
this.subcategory = None;
307
}
308
this.error = None;
309
cx.notify();
310
}))
311
}),
312
);
313
let subcategories = self
314
.category
315
.as_deref()
316
.map(|category| lookups.subcategories_of(category).to_vec())
317
.unwrap_or_default();
318
v_flex()
319
.w_full()
320
.gap(px(SECTION_GAP))
321
.child(categories)
322
.when(!subcategories.is_empty(), |column| {
323
column
324
.child(label(tr("kvt.tickets.form.subcategory")))
325
.child(
326
h_flex().w_full().flex_wrap().gap(px(6.)).children(
327
subcategories
328
.into_iter()
329
.enumerate()
330
.map(|(index, subcategory)| {
331
let selected =
332
self.subcategory.as_deref() == Some(subcategory.as_str());
333
chip(
334
format!("kvt-ticket-subcategory-{index}").into(),
335
subcategory.clone(),
336
selected,
337
)
338
.on_click(cx.listener(
339
move |this, _, _, cx| {
340
// Nogmaals klikken haalt de keuze weg (subcategorie is optioneel).
341
this.subcategory =
342
(!selected).then(|| subcategory.clone());
343
cx.notify();
344
},
345
))
346
}),
347
),
348
)
349
})
350
.into_any_element()
351
}
352
353
fn files(&self, cx: &mut Context<Self>) -> Div {
354
h_flex()
355
.w_full()
356
.flex_wrap()
357
.gap(px(6.))
358
.items_center()
359
.children(self.files.iter().enumerate().map(|(index, file)| {
360
h_flex()
361
.id(ElementId::Name(format!("kvt-ticket-file-{index}").into()))
362
.h(px(28.))
363
.pl(px(10.))
364
.pr(px(4.))
365
.gap(px(6.))
366
.items_center()
367
.rounded(px(6.))
368
.bg(theme::popup_hover())
369
.text_size(px(12.))
370
.child(symbol("attach_file", 14., theme::text_muted()))
371
.child(format!("{} ({})", file.name, size_label(file.size)))
372
.child(
373
div()
374
.id(ElementId::Name(
375
format!("kvt-ticket-file-remove-{index}").into(),
376
))
377
.size(px(20.))
378
.flex()
379
.items_center()
380
.justify_center()
381
.rounded_full()
382
.cursor_pointer()
383
.hover(|button| button.bg(theme::row_hover()))
384
.on_click(cx.listener(move |this, _, _, cx| {
385
if index < this.files.len() {
386
this.files.remove(index);
387
}
388
cx.notify();
389
}))
390
.child(symbol("close", 12., theme::text_muted())),
391
)
392
}))
393
.when(self.files.len() < ATTACHMENTS_MAX, |row| {
394
row.child(
395
secondary_button(
396
"kvt-ticket-add-file",
397
"attach_file",
398
tr("kvt.tickets.form.add_files"),
399
)
400
.on_click(cx.listener(|this, _, _, cx| this.pick_files(cx))),
401
)
402
})
403
}
404
}
405
406
fn read_files(paths: Vec<PathBuf>) -> Vec<Result<PickedFile, String>> {
407
paths
408
.into_iter()
409
.filter_map(|path| {
410
let name = path.file_name()?.to_string_lossy().into_owned();
411
let size = std::fs::metadata(&path).ok()?.len() as usize;
412
if size > ATTACHMENT_MAX_BYTES {
413
return Some(Err(name));
414
}
415
let data = std::fs::read(&path).ok()?;
416
Some(Ok(PickedFile {
417
size: data.len(),
418
attachment: NewAttachment {
419
mime: mime_for(&name).to_owned(),
420
filename: name.clone(),
421
data,
422
},
423
name,
424
}))
425
})
426
.collect()
427
}
428
429
fn size_label(bytes: usize) -> String {
430
if bytes >= 1024 * 1024 {
431
format!("{:.1} MB", bytes as f64 / (1024. * 1024.)).replace('.', ",")
432
} else {
433
format!("{} kB", bytes.div_ceil(1024).max(1))
434
}
435
}
436
437
impl Render for TicketForm {
438
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
439
let linked = matches!(link(cx), Link::Linked(_));
440
let ready = linked && matches!(self.lookups, LookupState::Loaded(_));
441
let detail = self
442
.source
443
.as_ref()
444
.filter(|source| !source.sender.is_empty())
445
.map(|source| format!("{} · {}", source.sender, source.sent_at))
446
.unwrap_or_default();
447
let blocked = self.blocked;
448
let body = if !linked {
449
v_flex().w_full().child(not_linked())
450
} else {
451
v_flex()
452
.w_full()
453
.gap(px(SECTION_GAP))
454
.child(label(tr("kvt.tickets.form.title")))
455
.child(
456
field().child(
457
div()
458
.flex_1()
459
.child(Input::new(&self.title).appearance(false).bordered(false)),
460
),
461
)
462
.child(label(tr("kvt.tickets.form.category")))
463
.child(self.categories(cx))
464
.child(label(tr("kvt.tickets.form.description")))
465
.child(Textarea::new(&self.description))
466
.child(
467
Checkbox::new("kvt-ticket-blocked")
468
.label(tr("kvt.tickets.form.blocked"))
469
.checked(self.blocked)
470
.on_click(cx.listener(|this, checked: &bool, _, cx| {
471
this.blocked = *checked;
472
if !*checked {
473
this.fully_blocked = false;
474
}
475
cx.notify();
476
})),
477
)
478
.child(
479
Checkbox::new("kvt-ticket-fully-blocked")
480
.label(tr("kvt.tickets.form.fully_blocked"))
481
.checked(self.fully_blocked)
482
.disabled(!blocked)
483
.on_click(cx.listener(|this, checked: &bool, _, cx| {
484
this.fully_blocked = *checked && this.blocked;
485
cx.notify();
486
})),
487
)
488
.child(label(tr("kvt.tickets.form.participants")))
489
.child(
490
field().child(
491
div().flex_1().child(
492
Input::new(&self.participants)
493
.appearance(false)
494
.bordered(false),
495
),
496
),
497
)
498
.child(
499
div()
500
.text_size(px(12.))
501
.text_color(theme::text_muted())
502
.child(tr("kvt.tickets.form.participants_hint")),
503
)
504
.child(label(tr("kvt.tickets.form.attachments")))
505
.child(self.files(cx))
506
};
507
div()
508
.id("kvt-ticket-form-layer")
509
.absolute()
510
.top_0()
511
.left_0()
512
.size_full()
513
.flex()
514
.items_center()
515
.justify_center()
516
.child(
517
div()
518
.id("kvt-ticket-form-backdrop")
519
.absolute()
520
.top_0()
521
.left_0()
522
.size_full()
523
.bg(black().opacity(BACKDROP_OPACITY))
524
.occlude()
525
.on_click(|_, _, cx| close(cx)),
526
)
527
.child(
528
v_flex()
529
.id("kvt-ticket-form-panel")
530
.debug_selector(|| KVT_TICKET_FORM_TAG.into())
531
.w(px(PANEL_WIDTH))
532
.max_w(relative(1.))
533
.max_h(relative(0.92))
534
.m(px(PANEL_MARGIN))
535
.p(px(PANEL_PADDING))
536
.gap(px(SECTION_GAP))
537
.rounded(px(PANEL_RADIUS))
538
.dialog_surface()
539
.text_color(theme::text())
540
.overflow_y_scroll()
541
.occlude()
542
.on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| {
543
if event.keystroke.key == "escape" {
544
close(cx);
545
}
546
}))
547
.child(
548
h_flex()
549
.w_full()
550
.items_center()
551
.gap(px(SECTION_GAP))
552
.child(
553
v_flex()
554
.flex_1()
555
.min_w_0()
556
.child(
557
div()
558
.text_size(px(15.))
559
.font_weight(FontWeight::SEMIBOLD)
560
.child(tr("kvt.tickets.form.heading")),
561
)
562
.when(!detail.is_empty(), |column| {
563
column.child(
564
div()
565
.truncate()
566
.text_size(px(12.))
567
.text_color(theme::text_muted())
568
.child(detail),
569
)
570
}),
571
)
572
.child(
573
div()
574
.id("kvt-ticket-form-close")
575
.size(px(CLOSE_SIZE))
576
.flex_none()
577
.flex()
578
.items_center()
579
.justify_center()
580
.rounded_full()
581
.cursor_pointer()
582
.hover(|button| button.bg(theme::popup_hover()))
583
.on_click(|_, _, cx| close(cx))
584
.child(symbol("close", 16., theme::text_muted())),
585
),
586
)
587
.child(body)
588
.children(self.error.clone().map(|error| {
589
div()
590
.text_size(px(13.))
591
.text_color(theme::red_soft())
592
.child(error)
593
}))
594
.child(
595
h_flex()
596
.w_full()
597
.gap(px(8.))
598
.justify_end()
599
.child(
600
secondary_button(
601
"kvt-ticket-form-cancel",
602
"close",
603
tr("common.cancel"),
604
)
605
.on_click(|_, _, cx| close(cx)),
606
)
607
.when(ready, |row| {
608
row.child(
609
primary_button(
610
"kvt-ticket-form-submit",
611
tr(if self.saving {
612
"kvt.tickets.sending"
613
} else {
614
"kvt.tickets.form.submit"
615
}),
616
)
617
.on_click(cx.listener(|this, _, _, cx| this.save(cx))),
618
)
619
}),
620
),
621
)
622
}
623
}
624
625
pub(super) fn demo_lookups() -> Lookups {
626
let mut lookups = Lookups {
627
categories: [
628
"Hardware",
629
"Hardware bestellen",
630
"Software",
631
"Rechten en toegang",
632
"Indiensttreding",
633
]
634
.map(str::to_owned)
635
.to_vec(),
636
..Lookups::default()
637
};
638
lookups.subcategories.insert(
639
"Hardware".to_owned(),
640
["Laptop", "Monitor", "Printer"].map(str::to_owned).to_vec(),
641
);
642
lookups
643
}
644
645
#[cfg(test)]
646
mod tests {
647
use super::{demo_lookups, prefilled_description, size_label};
648
use kvt_sleutels::asclepius::MessageSource;
649
650
#[test]
651
fn message_mentions_become_asclepius_tokens() {
652
let source = MessageSource {
653
text: "@Jonas Ortega kun jij hiernaar kijken?".to_owned(),
654
sender: "Dana Demo".to_owned(),
655
sent_at: "15 jan 2026 13:39".to_owned(),
656
link: None,
657
mentions: vec![(
658
"Jonas Ortega".to_owned(),
659
"jonas.ortega@example.com".to_owned(),
660
)],
661
};
662
let description = prefilled_description(&source);
663
assert!(description.starts_with("> @jonas.ortega:examplecom kun jij"));
664
}
665
666
#[test]
667
fn ict_only_categories_are_not_offered() {
668
assert!(
669
!demo_lookups()
670
.form_categories()
671
.contains(&"Indiensttreding".to_owned())
672
);
673
}
674
675
#[test]
676
fn sizes_are_short_and_dutch() {
677
assert_eq!(size_label(500), "1 kB");
678
assert_eq!(size_label(3 * 1024 * 1024 + 512 * 1024), "3,5 MB");
679
}
680
}
@@ -0,0 +1,680 @@1
//! Asclepius: «Nieuw ticket maken» in de app, met de velden van het webformulier.2
//! Ook voor «Ticket maken in Asclepius» in het berichtmenu, dan vooraf ingevuld3
//! met het bericht; vermeldingen worden `@naam:domein` zoals Asclepius ze kent.4
5
use std::path::PathBuf;6
7
use gpui_kit::component::checkbox::Checkbox;8
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};9
use gpui_kit::component::{Disableable as _, h_flex, v_flex};10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;12
use kvt_sleutels::ClientError;13
use kvt_sleutels::asclepius::MessageSource;14
use kvt_sleutels::tickets::{15
ATTACHMENT_MAX_BYTES, ATTACHMENTS_MAX, DESCRIPTION_MAX, Lookups, NewAttachment, NewTicket,16
TITLE_MAX, mentions_to_asclepius, mime_for, parse_participants, priority_from_flags,17
};18
19
use super::modal::{primary_button, secondary_button};20
use super::tasks::{chip, field, label, muted, not_linked};21
use super::tickets::ticket_error;22
use super::{Link, forget_token, installed, is_demo, link, notice, token_and_client, update};23
use crate::i18n::{tr, tr_args};24
use crate::runtime;25
use crate::theme::{self, ElevatedSurface as _};26
use crate::views::widgets::symbol;27
28
pub const KVT_TICKET_FORM_TAG: &str = "kvt-asclepius-form";29
const BACKDROP_OPACITY: f32 = 0.55;30
const PANEL_WIDTH: f32 = 560.;31
const PANEL_MARGIN: f32 = 32.;32
const PANEL_RADIUS: f32 = 10.;33
const PANEL_PADDING: f32 = 16.;34
const SECTION_GAP: f32 = 10.;35
const CLOSE_SIZE: f32 = 28.;36
37
#[derive(Clone)]38
enum LookupState {39
Loading,40
Loaded(Lookups),41
Failed(ClientError),42
}43
44
struct PickedFile {45
name: String,46
size: usize,47
attachment: NewAttachment,48
}49
50
pub struct TicketForm {51
source: Option<MessageSource>,52
lookups: LookupState,53
category: Option<String>,54
subcategory: Option<String>,55
title: Entity<InputState>,56
description: Entity<TextareaState>,57
participants: Entity<InputState>,58
blocked: bool,59
fully_blocked: bool,60
files: Vec<PickedFile>,61
saving: bool,62
error: Option<String>,63
}64
65
/// Opent het formulier; `source` is het bericht bij «Ticket maken in Asclepius».66
pub(super) fn open_new(source: Option<MessageSource>, window: &mut Window, cx: &mut App) {67
if !installed(cx) {68
return;69
}70
let form = cx.new(|cx| TicketForm::new(source, window, cx));71
update(cx, |kvt| kvt.ticket_form = Some(form.clone()));72
if is_demo(cx) {73
form.update(cx, |form, cx| form.set_lookups(Ok(demo_lookups()), cx));74
return;75
}76
let Some((token, client)) = token_and_client(cx) else {77
return;78
};79
let loading = runtime::spawn(async move { client.asclepius_lookups(&token).await });80
let weak = form.downgrade();81
cx.spawn(async move |cx| {82
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));83
cx.update(|cx| {84
if result == Err(ClientError::Unauthorized) {85
forget_token(cx);86
}87
weak.update(cx, |form, cx| form.set_lookups(result, cx))88
.ok();89
});90
})91
.detach();92
}93
94
fn tr_with(key: &str, name: &str, value: String) -> String {95
tr_args(96
key,97
&std::collections::HashMap::from([(name.to_owned(), value)]),98
)99
}100
101
fn close(cx: &mut App) {102
update(cx, |kvt| kvt.ticket_form = None);103
}104
105
/// Knop «Nieuw ticket» in de kop van de tegel.106
pub(super) fn new_ticket_button<T: 'static>(cx: &mut Context<T>) -> Option<Stateful<Div>> {107
matches!(link(cx), Link::Linked(_)).then(|| {108
primary_button("kvt-tickets-new", tr("kvt.tickets.new"))109
.on_click(|_, window, cx| open_new(None, window, cx))110
})111
}112
113
/// Beschrijving uit het bericht, met de vermeldingen als Asclepius-token.114
fn prefilled_description(source: &MessageSource) -> String {115
mentions_to_asclepius(&source.description(DESCRIPTION_MAX), &source.mentions)116
}117
118
impl TicketForm {119
fn new(source: Option<MessageSource>, window: &mut Window, cx: &mut Context<Self>) -> Self {120
let title_text = source121
.as_ref()122
.map(|source| source.title(TITLE_MAX))123
.unwrap_or_default();124
let description_text = source125
.as_ref()126
.map(prefilled_description)127
.unwrap_or_default();128
let title = cx.new(|cx| {129
InputState::new(window, cx)130
.placeholder(tr("kvt.tickets.form.title_placeholder"))131
.default_value(title_text)132
});133
let description = cx.new(|cx| {134
TextareaState::new(window, cx)135
.auto_grow(4, 10)136
.placeholder(tr("kvt.tickets.form.description_placeholder"))137
.default_value(description_text)138
});139
let participants = cx.new(|cx| {140
InputState::new(window, cx).placeholder(tr("kvt.tickets.form.participants_placeholder"))141
});142
title.update(cx, |input, cx| input.focus(window, cx));143
TicketForm {144
source,145
lookups: LookupState::Loading,146
category: None,147
subcategory: None,148
title,149
description,150
participants,151
blocked: false,152
fully_blocked: false,153
files: Vec::new(),154
saving: false,155
error: None,156
}157
}158
159
fn set_lookups(&mut self, result: Result<Lookups, ClientError>, cx: &mut Context<Self>) {160
self.lookups = match result {161
Ok(lookups) => LookupState::Loaded(lookups),162
Err(error) => LookupState::Failed(error),163
};164
cx.notify();165
}166
167
fn pick_files(&mut self, cx: &mut Context<Self>) {168
let receiver = cx.prompt_for_paths(PathPromptOptions {169
files: true,170
directories: false,171
multiple: true,172
prompt: None,173
});174
cx.spawn(async move |this, cx| {175
let Ok(Ok(Some(paths))) = receiver.await else {176
return;177
};178
let reading = runtime::spawn(async move { read_files(paths) });179
let read = reading.await.unwrap_or_default();180
this.update(cx, |this, cx| {181
for file in read {182
match file {183
Ok(file) if this.files.len() < ATTACHMENTS_MAX => this.files.push(file),184
Ok(_) => {185
this.error = Some(tr_with(186
"kvt.tickets.form.too_many_files",187
"max",188
ATTACHMENTS_MAX.to_string(),189
))190
}191
Err(name) => {192
this.error =193
Some(tr_with("kvt.tickets.form.file_too_large", "name", name))194
}195
}196
}197
cx.notify();198
})199
.ok();200
})201
.detach();202
}203
204
fn save(&mut self, cx: &mut Context<Self>) {205
if self.saving {206
return;207
}208
let title = self.title.read(cx).value().trim().to_owned();209
let description = self.description.read(cx).value().trim().to_owned();210
let participants_text = self.participants.read(cx).value().to_string();211
let Some(category) = self.category.clone() else {212
self.error = Some(tr("kvt.tickets.form.pick_category"));213
cx.notify();214
return;215
};216
if title.is_empty() || description.is_empty() {217
self.error = Some(tr("kvt.tickets.form.fill_in"));218
cx.notify();219
return;220
}221
let participant_emails = match parse_participants(&participants_text) {222
Ok(emails) => emails,223
Err(bad) => {224
self.error = Some(tr_with("kvt.tickets.form.bad_email", "email", bad));225
cx.notify();226
return;227
}228
};229
let ticket = NewTicket {230
title,231
category,232
subcategory: self.subcategory.clone(),233
description,234
priority: priority_from_flags(self.blocked, self.fully_blocked),235
participant_emails,236
attachments: self237
.files238
.iter()239
.map(|file| file.attachment.clone())240
.collect(),241
};242
if is_demo(cx) {243
close(cx);244
notice(245
tr_with("kvt.tickets.form.created", "id", "4103".to_owned()),246
cx,247
);248
return;249
}250
let Some((token, client)) = token_and_client(cx) else {251
return;252
};253
self.saving = true;254
self.error = None;255
cx.notify();256
let creating =257
runtime::spawn(async move { client.asclepius_create(&token, &ticket).await });258
cx.spawn(async move |this, cx| {259
let result = creating.await.unwrap_or(Err(ClientError::Unavailable));260
cx.update(|cx| match result {261
Ok(id) => {262
close(cx);263
notice(264
tr_with("kvt.tickets.form.created", "id", id.to_string()),265
cx,266
);267
super::tickets::created(id, cx);268
}269
Err(error) => {270
if error == ClientError::Unauthorized {271
forget_token(cx);272
}273
this.update(cx, |this, cx| {274
this.saving = false;275
this.error = Some(ticket_error(&error));276
cx.notify();277
})278
.ok();279
}280
});281
})282
.detach();283
}284
285
fn categories(&self, cx: &mut Context<Self>) -> AnyElement {286
let lookups = match &self.lookups {287
LookupState::Loading => return muted(tr("kvt.card.loading")).into_any_element(),288
LookupState::Failed(error) => return muted(ticket_error(error)).into_any_element(),289
LookupState::Loaded(lookups) => lookups,290
};291
let categories = h_flex().w_full().flex_wrap().gap(px(6.)).children(292
lookups293
.form_categories()294
.into_iter()295
.enumerate()296
.map(|(index, category)| {297
let selected = self.category.as_deref() == Some(category.as_str());298
chip(299
format!("kvt-ticket-category-{index}").into(),300
category.clone(),301
selected,302
)303
.on_click(cx.listener(move |this, _, _, cx| {304
if this.category.as_deref() != Some(category.as_str()) {305
this.category = Some(category.clone());306
this.subcategory = None;307
}308
this.error = None;309
cx.notify();310
}))311
}),312
);313
let subcategories = self314
.category315
.as_deref()316
.map(|category| lookups.subcategories_of(category).to_vec())317
.unwrap_or_default();318
v_flex()319
.w_full()320
.gap(px(SECTION_GAP))321
.child(categories)322
.when(!subcategories.is_empty(), |column| {323
column324
.child(label(tr("kvt.tickets.form.subcategory")))325
.child(326
h_flex().w_full().flex_wrap().gap(px(6.)).children(327
subcategories328
.into_iter()329
.enumerate()330
.map(|(index, subcategory)| {331
let selected =332
self.subcategory.as_deref() == Some(subcategory.as_str());333
chip(334
format!("kvt-ticket-subcategory-{index}").into(),335
subcategory.clone(),336
selected,337
)338
.on_click(cx.listener(339
move |this, _, _, cx| {340
// Nogmaals klikken haalt de keuze weg (subcategorie is optioneel).341
this.subcategory =342
(!selected).then(|| subcategory.clone());343
cx.notify();344
},345
))346
}),347
),348
)349
})350
.into_any_element()351
}352
353
fn files(&self, cx: &mut Context<Self>) -> Div {354
h_flex()355
.w_full()356
.flex_wrap()357
.gap(px(6.))358
.items_center()359
.children(self.files.iter().enumerate().map(|(index, file)| {360
h_flex()361
.id(ElementId::Name(format!("kvt-ticket-file-{index}").into()))362
.h(px(28.))363
.pl(px(10.))364
.pr(px(4.))365
.gap(px(6.))366
.items_center()367
.rounded(px(6.))368
.bg(theme::popup_hover())369
.text_size(px(12.))370
.child(symbol("attach_file", 14., theme::text_muted()))371
.child(format!("{} ({})", file.name, size_label(file.size)))372
.child(373
div()374
.id(ElementId::Name(375
format!("kvt-ticket-file-remove-{index}").into(),376
))377
.size(px(20.))378
.flex()379
.items_center()380
.justify_center()381
.rounded_full()382
.cursor_pointer()383
.hover(|button| button.bg(theme::row_hover()))384
.on_click(cx.listener(move |this, _, _, cx| {385
if index < this.files.len() {386
this.files.remove(index);387
}388
cx.notify();389
}))390
.child(symbol("close", 12., theme::text_muted())),391
)392
}))393
.when(self.files.len() < ATTACHMENTS_MAX, |row| {394
row.child(395
secondary_button(396
"kvt-ticket-add-file",397
"attach_file",398
tr("kvt.tickets.form.add_files"),399
)400
.on_click(cx.listener(|this, _, _, cx| this.pick_files(cx))),401
)402
})403
}404
}405
406
fn read_files(paths: Vec<PathBuf>) -> Vec<Result<PickedFile, String>> {407
paths408
.into_iter()409
.filter_map(|path| {410
let name = path.file_name()?.to_string_lossy().into_owned();411
let size = std::fs::metadata(&path).ok()?.len() as usize;412
if size > ATTACHMENT_MAX_BYTES {413
return Some(Err(name));414
}415
let data = std::fs::read(&path).ok()?;416
Some(Ok(PickedFile {417
size: data.len(),418
attachment: NewAttachment {419
mime: mime_for(&name).to_owned(),420
filename: name.clone(),421
data,422
},423
name,424
}))425
})426
.collect()427
}428
429
fn size_label(bytes: usize) -> String {430
if bytes >= 1024 * 1024 {431
format!("{:.1} MB", bytes as f64 / (1024. * 1024.)).replace('.', ",")432
} else {433
format!("{} kB", bytes.div_ceil(1024).max(1))434
}435
}436
437
impl Render for TicketForm {438
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {439
let linked = matches!(link(cx), Link::Linked(_));440
let ready = linked && matches!(self.lookups, LookupState::Loaded(_));441
let detail = self442
.source443
.as_ref()444
.filter(|source| !source.sender.is_empty())445
.map(|source| format!("{} · {}", source.sender, source.sent_at))446
.unwrap_or_default();447
let blocked = self.blocked;448
let body = if !linked {449
v_flex().w_full().child(not_linked())450
} else {451
v_flex()452
.w_full()453
.gap(px(SECTION_GAP))454
.child(label(tr("kvt.tickets.form.title")))455
.child(456
field().child(457
div()458
.flex_1()459
.child(Input::new(&self.title).appearance(false).bordered(false)),460
),461
)462
.child(label(tr("kvt.tickets.form.category")))463
.child(self.categories(cx))464
.child(label(tr("kvt.tickets.form.description")))465
.child(Textarea::new(&self.description))466
.child(467
Checkbox::new("kvt-ticket-blocked")468
.label(tr("kvt.tickets.form.blocked"))469
.checked(self.blocked)470
.on_click(cx.listener(|this, checked: &bool, _, cx| {471
this.blocked = *checked;472
if !*checked {473
this.fully_blocked = false;474
}475
cx.notify();476
})),477
)478
.child(479
Checkbox::new("kvt-ticket-fully-blocked")480
.label(tr("kvt.tickets.form.fully_blocked"))481
.checked(self.fully_blocked)482
.disabled(!blocked)483
.on_click(cx.listener(|this, checked: &bool, _, cx| {484
this.fully_blocked = *checked && this.blocked;485
cx.notify();486
})),487
)488
.child(label(tr("kvt.tickets.form.participants")))489
.child(490
field().child(491
div().flex_1().child(492
Input::new(&self.participants)493
.appearance(false)494
.bordered(false),495
),496
),497
)498
.child(499
div()500
.text_size(px(12.))501
.text_color(theme::text_muted())502
.child(tr("kvt.tickets.form.participants_hint")),503
)504
.child(label(tr("kvt.tickets.form.attachments")))505
.child(self.files(cx))506
};507
div()508
.id("kvt-ticket-form-layer")509
.absolute()510
.top_0()511
.left_0()512
.size_full()513
.flex()514
.items_center()515
.justify_center()516
.child(517
div()518
.id("kvt-ticket-form-backdrop")519
.absolute()520
.top_0()521
.left_0()522
.size_full()523
.bg(black().opacity(BACKDROP_OPACITY))524
.occlude()525
.on_click(|_, _, cx| close(cx)),526
)527
.child(528
v_flex()529
.id("kvt-ticket-form-panel")530
.debug_selector(|| KVT_TICKET_FORM_TAG.into())531
.w(px(PANEL_WIDTH))532
.max_w(relative(1.))533
.max_h(relative(0.92))534
.m(px(PANEL_MARGIN))535
.p(px(PANEL_PADDING))536
.gap(px(SECTION_GAP))537
.rounded(px(PANEL_RADIUS))538
.dialog_surface()539
.text_color(theme::text())540
.overflow_y_scroll()541
.occlude()542
.on_key_down(cx.listener(|_, event: &KeyDownEvent, _, cx| {543
if event.keystroke.key == "escape" {544
close(cx);545
}546
}))547
.child(548
h_flex()549
.w_full()550
.items_center()551
.gap(px(SECTION_GAP))552
.child(553
v_flex()554
.flex_1()555
.min_w_0()556
.child(557
div()558
.text_size(px(15.))559
.font_weight(FontWeight::SEMIBOLD)560
.child(tr("kvt.tickets.form.heading")),561
)562
.when(!detail.is_empty(), |column| {563
column.child(564
div()565
.truncate()566
.text_size(px(12.))567
.text_color(theme::text_muted())568
.child(detail),569
)570
}),571
)572
.child(573
div()574
.id("kvt-ticket-form-close")575
.size(px(CLOSE_SIZE))576
.flex_none()577
.flex()578
.items_center()579
.justify_center()580
.rounded_full()581
.cursor_pointer()582
.hover(|button| button.bg(theme::popup_hover()))583
.on_click(|_, _, cx| close(cx))584
.child(symbol("close", 16., theme::text_muted())),585
),586
)587
.child(body)588
.children(self.error.clone().map(|error| {589
div()590
.text_size(px(13.))591
.text_color(theme::red_soft())592
.child(error)593
}))594
.child(595
h_flex()596
.w_full()597
.gap(px(8.))598
.justify_end()599
.child(600
secondary_button(601
"kvt-ticket-form-cancel",602
"close",603
tr("common.cancel"),604
)605
.on_click(|_, _, cx| close(cx)),606
)607
.when(ready, |row| {608
row.child(609
primary_button(610
"kvt-ticket-form-submit",611
tr(if self.saving {612
"kvt.tickets.sending"613
} else {614
"kvt.tickets.form.submit"615
}),616
)617
.on_click(cx.listener(|this, _, _, cx| this.save(cx))),618
)619
}),620
),621
)622
}623
}624
625
pub(super) fn demo_lookups() -> Lookups {626
let mut lookups = Lookups {627
categories: [628
"Hardware",629
"Hardware bestellen",630
"Software",631
"Rechten en toegang",632
"Indiensttreding",633
]634
.map(str::to_owned)635
.to_vec(),636
..Lookups::default()637
};638
lookups.subcategories.insert(639
"Hardware".to_owned(),640
["Laptop", "Monitor", "Printer"].map(str::to_owned).to_vec(),641
);642
lookups643
}644
645
#[cfg(test)]646
mod tests {647
use super::{demo_lookups, prefilled_description, size_label};648
use kvt_sleutels::asclepius::MessageSource;649
650
#[test]651
fn message_mentions_become_asclepius_tokens() {652
let source = MessageSource {653
text: "@Jonas Ortega kun jij hiernaar kijken?".to_owned(),654
sender: "Dana Demo".to_owned(),655
sent_at: "15 jan 2026 13:39".to_owned(),656
link: None,657
mentions: vec![(658
"Jonas Ortega".to_owned(),659
"jonas.ortega@example.com".to_owned(),660
)],661
};662
let description = prefilled_description(&source);663
assert!(description.starts_with("> @jonas.ortega:examplecom kun jij"));664
}665
666
#[test]667
fn ict_only_categories_are_not_offered() {668
assert!(669
!demo_lookups()670
.form_categories()671
.contains(&"Indiensttreding".to_owned())672
);673
}674
675
#[test]676
fn sizes_are_short_and_dutch() {677
assert_eq!(size_label(500), "1 kB");678
assert_eq!(size_label(3 * 1024 * 1024 + 512 * 1024), "3,5 MB");679
}680
}@@ -0,0 +1,1448 @@
1
//! Asclepius-tegel: je tickets (zoals «Mijn tickets» op het web, plus aan jou
2
//! toegewezen) links, het gesprek van het gekozen ticket rechts. Antwoorden kan
3
//! hier; behandelen (status, toewijzing) blijft in Asclepius (fase 2).
4
//!
5
//! Ongelezen is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at`
6
//! nieuwer is dan toen je het opende. Elke minuut `ticket_updates`.
7
8
use std::collections::HashMap;
9
use std::time::Duration;
10
11
use chrono::{DateTime, Local};
12
use gpui_kit::component::input::{Textarea, TextareaState};
13
use gpui_kit::component::scroll::ScrollableElement as _;
14
use gpui_kit::component::{h_flex, v_flex};
15
use gpui_kit::prelude::FluentBuilder as _;
16
use gpui_kit::*;
17
use kvt_sleutels::format::date_time_nl;
18
use kvt_sleutels::tickets::{
19
SeenTickets, TextPart, Ticket, TicketAttachment, TicketDetail, TicketFilter, TicketMessage,
20
mention_label, mention_token, split_mentions, ticket_id_from_url,
21
};
22
use kvt_sleutels::{CardsClient, ClientError};
23
24
use super::modal::{primary_button, secondary_button};
25
use super::tasks::{chip, muted, not_linked};
26
use super::{
27
Link, base_url, error_text, forget_token, installed, is_demo, link, notice, token_and_client,
28
update,
29
};
30
use crate::app_state::AppHandle;
31
use crate::i18n::tr;
32
use crate::runtime;
33
use crate::theme::{self, ElevatedSurface as _};
34
use crate::views::widgets::symbol;
35
36
pub const KVT_TICKETS_TAG: &str = "kvt-asclepius-tickets";
37
const SEEN_META_KEY: &str = "kvt.asclepius.seen";
38
const POLL_INTERVAL: Duration = Duration::from_secs(60);
39
const HEADER_HEIGHT: f32 = 60.;
40
const PAGE_PADDING: f32 = 20.;
41
const LIST_WIDTH: f32 = 320.;
42
const RADIUS: f32 = 10.;
43
const BUBBLE_RADIUS: f32 = 14.;
44
45
// Ghost-berichten zoals op het web (`.message.is-ghost`), ongeacht het thema.
46
const GHOST_BG: u32 = 0x5b21b6;
47
const GHOST_BORDER: u32 = 0xf9a8d4;
48
const GHOST_TEXT: u32 = 0xfce7f3;
49
50
#[derive(Clone)]
51
enum List {
52
NotLinked,
53
Loading,
54
Loaded(Vec<Ticket>),
55
Failed(ClientError),
56
}
57
58
#[derive(Clone)]
59
enum Detail {
60
Loading,
61
Loaded(TicketDetail),
62
Failed(ClientError),
63
}
64
65
pub(super) fn ticket_error(error: &ClientError) -> String {
66
match error {
67
ClientError::Forbidden | ClientError::NotFound => tr("kvt.tickets.not_found"),
68
ClientError::BadRequest => tr("kvt.tickets.failed"),
69
other => error_text(other),
70
}
71
}
72
73
/// `2026-01-15T13:39:00+01:00` → `15 jan 2026 13:39` (lokale tijd).
74
pub(super) fn when(value: &str) -> String {
75
DateTime::parse_from_rfc3339(value.trim())
76
.map(|moment| date_time_nl(moment.with_timezone(&Local).naive_local()))
77
.unwrap_or_else(|_| value.get(..16).unwrap_or(value).replace('T', " "))
78
}
79
80
pub(super) fn status_label(status: &str) -> String {
81
let key = format!("kvt.tickets.status.{}", status.trim().replace(' ', "_"));
82
let label = tr(&key);
83
if label == key || label.is_empty() {
84
status.to_owned()
85
} else {
86
label
87
}
88
}
89
90
fn me(cx: &App) -> String {
91
match link(cx) {
92
Link::Linked(stored) => stored.email.to_lowercase(),
93
_ => String::new(),
94
}
95
}
96
97
// --- lokaal ongelezen ----------------------------------------------------------
98
99
fn load_seen(cx: &App) -> SeenTickets {
100
cx.try_global::<AppHandle>()
101
.and_then(|handle| handle.0.read(cx).store.meta(SEEN_META_KEY).ok().flatten())
102
.map(|json| SeenTickets::from_json(&json))
103
.unwrap_or_default()
104
}
105
106
fn save_seen(seen: &SeenTickets, cx: &App) {
107
if let Some(handle) = cx.try_global::<AppHandle>() {
108
let _ = handle
109
.0
110
.read(cx)
111
.store
112
.set_meta(SEEN_META_KEY, &seen.to_json());
113
}
114
}
115
116
// --- gesprek van één ticket (tegel en ticketvenster) ----------------------------
117
118
pub struct TicketThread {
119
id: u64,
120
detail: Detail,
121
reply: Entity<TextareaState>,
122
sending: bool,
123
error: Option<String>,
124
generation: u64,
125
scroll: ScrollHandle,
126
}
127
128
impl TicketThread {
129
pub(super) fn new(id: u64, window: &mut Window, cx: &mut Context<Self>) -> Self {
130
let mut thread = Self::with_detail(id, None, window, cx);
131
thread.reload(cx);
132
thread
133
}
134
135
/// Met een al opgehaald ticket (ticketvenster: eerst kijken of je toegang hebt).
136
fn with_detail(
137
id: u64,
138
detail: Option<TicketDetail>,
139
window: &mut Window,
140
cx: &mut Context<Self>,
141
) -> Self {
142
let reply = cx.new(|cx| {
143
TextareaState::new(window, cx)
144
.auto_grow(2, 8)
145
.placeholder(tr("kvt.tickets.reply_placeholder"))
146
});
147
let scroll = ScrollHandle::new();
148
if detail.is_some() {
149
scroll.scroll_to_bottom();
150
}
151
TicketThread {
152
id,
153
detail: detail.map_or(Detail::Loading, Detail::Loaded),
154
reply,
155
sending: false,
156
error: None,
157
generation: 0,
158
scroll,
159
}
160
}
161
162
pub(super) fn id(&self) -> u64 {
163
self.id
164
}
165
166
pub(super) fn reload(&mut self, cx: &mut Context<Self>) {
167
self.generation += 1;
168
let generation = self.generation;
169
let id = self.id;
170
if is_demo(cx) {
171
self.detail = match demo_detail(id) {
172
Some(detail) => Detail::Loaded(detail),
173
None => Detail::Failed(ClientError::NotFound),
174
};
175
self.scroll.scroll_to_bottom();
176
cx.notify();
177
return;
178
}
179
let Some((token, client)) = token_and_client(cx) else {
180
return;
181
};
182
let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await });
183
cx.spawn(async move |this, cx| {
184
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
185
cx.update(|cx| {
186
if result == Err(ClientError::Unauthorized) {
187
forget_token(cx);
188
}
189
let opened = result.as_ref().ok().map(|detail| detail.ticket.clone());
190
this.update(cx, |this, cx| {
191
if this.generation != generation {
192
return;
193
}
194
let first = !matches!(this.detail, Detail::Loaded(_));
195
this.detail = match result {
196
Ok(detail) => Detail::Loaded(detail),
197
Err(error) => Detail::Failed(error),
198
};
199
if first {
200
this.scroll.scroll_to_bottom();
201
}
202
cx.notify();
203
})
204
.ok();
205
if let Some(ticket) = opened {
206
ticket_seen(&ticket, cx);
207
}
208
});
209
})
210
.detach();
211
}
212
213
fn mention(&mut self, email: &str, window: &mut Window, cx: &mut Context<Self>) {
214
let Some(token) = mention_token(email) else {
215
return;
216
};
217
let current = self.reply.read(cx).value().to_string();
218
let joined = if current.is_empty() || current.ends_with([' ', '\n']) {
219
format!("{current}{token} ")
220
} else {
221
format!("{current} {token} ")
222
};
223
self.reply.update(cx, |reply, cx| {
224
reply.set_value(joined, window, cx);
225
reply.focus(window, cx);
226
});
227
}
228
229
fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
230
if self.sending {
231
return;
232
}
233
let text = self.reply.read(cx).value().trim().to_owned();
234
if text.is_empty() {
235
return;
236
}
237
self.sending = true;
238
self.error = None;
239
cx.notify();
240
if is_demo(cx) {
241
demo_reply(self.id, &text, &me(cx));
242
self.sending = false;
243
self.reply
244
.update(cx, |reply, cx| reply.set_value("", window, cx));
245
self.scroll.scroll_to_bottom();
246
self.reload(cx);
247
refresh_list(cx);
248
return;
249
}
250
let Some((token, client)) = token_and_client(cx) else {
251
self.sending = false;
252
return;
253
};
254
let id = self.id;
255
let sending =
256
runtime::spawn(async move { client.asclepius_reply(&token, id, &text).await });
257
let reply = self.reply.clone();
258
cx.spawn_in(window, async move |this, cx| {
259
let result = sending.await.unwrap_or(Err(ClientError::Unavailable));
260
this.update_in(cx, |this, window, cx| {
261
this.sending = false;
262
match &result {
263
Ok(()) => {
264
reply.update(cx, |reply, cx| reply.set_value("", window, cx));
265
this.scroll.scroll_to_bottom();
266
this.reload(cx);
267
refresh_list(cx);
268
}
269
Err(error) => {
270
if *error == ClientError::Unauthorized {
271
forget_token(cx);
272
}
273
this.error = Some(ticket_error(error));
274
}
275
}
276
cx.notify();
277
})
278
.ok();
279
})
280
.detach();
281
}
282
283
fn header(&self, detail: &TicketDetail) -> Div {
284
let ticket = &detail.ticket;
285
let mut meta = vec![format!("#{}", ticket.id), status_label(&ticket.status)];
286
if !ticket.category.is_empty() {
287
meta.push(if ticket.subcategory.is_empty() {
288
ticket.category.clone()
289
} else {
290
format!("{} › {}", ticket.category, ticket.subcategory)
291
});
292
}
293
if !ticket.created_at.is_empty() {
294
meta.push(when(&ticket.created_at));
295
}
296
v_flex()
297
.w_full()
298
.flex_none()
299
.px(px(PAGE_PADDING))
300
.py(px(12.))
301
.gap(px(2.))
302
.border_b_1()
303
.border_color(theme::border())
304
.child(
305
div()
306
.text_size(px(16.))
307
.font_weight(FontWeight::BOLD)
308
.text_color(theme::text())
309
.child(ticket.title.clone()),
310
)
311
.child(
312
div()
313
.text_size(px(12.))
314
.text_color(theme::text_muted())
315
.child(meta.join(" · ")),
316
)
317
}
318
319
fn message(
320
&self,
321
index: usize,
322
message: &TicketMessage,
323
known: &[String],
324
cx: &mut Context<Self>,
325
) -> AnyElement {
326
let ghost = message.is_ghost;
327
let from_ict = message.sender_role == "admin";
328
let text_color = if ghost {
329
rgb(GHOST_TEXT).into()
330
} else {
331
theme::text()
332
};
333
let muted_color = if ghost {
334
rgb(GHOST_TEXT).into()
335
} else {
336
theme::text_muted()
337
};
338
let mention_color: Hsla = if ghost {
339
rgb(GHOST_BORDER).into()
340
} else {
341
theme::accent_text()
342
};
343
let mut role = Vec::new();
344
if from_ict {
345
role.push(tr("kvt.tickets.ict"));
346
}
347
if ghost {
348
role.push(tr("kvt.tickets.ghost"));
349
}
350
let head = h_flex()
351
.w_full()
352
.gap(px(8.))
353
.items_center()
354
.child(
355
div()
356
.text_size(px(13.))
357
.font_weight(FontWeight::SEMIBOLD)
358
.text_color(text_color)
359
.child(message.sender_name()),
360
)
361
.when(!role.is_empty(), |row| {
362
row.child(
363
div()
364
.text_size(px(11.))
365
.text_color(muted_color)
366
.child(role.join(" · ")),
367
)
368
})
369
.child(div().flex_1())
370
.child(
371
div()
372
.text_size(px(11.))
373
.text_color(muted_color)
374
.child(when(&message.created_at)),
375
);
376
let body = message_text(&message.message_text, known, mention_color);
377
let attachments: Vec<AnyElement> = message
378
.attachments
379
.iter()
380
.enumerate()
381
.map(|(position, attachment)| {
382
attachment_chip(index, position, attachment, ghost, cx).into_any_element()
383
})
384
.collect();
385
v_flex()
386
.id(ElementId::Name(
387
format!("kvt-ticket-message-{index}").into(),
388
))
389
.w_full()
390
.p(px(12.))
391
.gap(px(6.))
392
.rounded(px(BUBBLE_RADIUS))
393
.map(|bubble| {
394
if ghost {
395
bubble
396
.bg(rgb(GHOST_BG))
397
.border_2()
398
.border_color(rgb(GHOST_BORDER))
399
} else if from_ict {
400
bubble.bg(theme::popup_hover())
401
} else {
402
bubble.bg(theme::surface_raised())
403
}
404
})
405
.child(head)
406
.child(div().text_size(px(13.)).text_color(text_color).child(body))
407
.when(!attachments.is_empty(), |bubble| {
408
bubble.child(h_flex().flex_wrap().gap(px(6.)).children(attachments))
409
})
410
.into_any_element()
411
}
412
413
fn composer(&self, detail: &TicketDetail, cx: &mut Context<Self>) -> Div {
414
let me = me(cx);
415
let mut people: Vec<String> = detail
416
.participant_emails
417
.iter()
418
.chain(std::iter::once(&detail.ticket.assigned_email))
419
.map(|email| email.to_lowercase())
420
.filter(|email| !email.is_empty() && *email != me)
421
.collect();
422
people.sort();
423
people.dedup();
424
let names = sender_names(detail);
425
v_flex()
426
.w_full()
427
.flex_none()
428
.px(px(PAGE_PADDING))
429
.py(px(12.))
430
.gap(px(8.))
431
.border_t_1()
432
.border_color(theme::border())
433
.when(!people.is_empty(), |column| {
434
column.child(
435
h_flex()
436
.w_full()
437
.flex_wrap()
438
.gap(px(6.))
439
.items_center()
440
.child(
441
div()
442
.text_size(px(12.))
443
.text_color(theme::text_muted())
444
.child(tr("kvt.tickets.mention")),
445
)
446
.children(people.into_iter().enumerate().map(|(index, email)| {
447
let label = names
448
.get(&email)
449
.cloned()
450
.unwrap_or_else(|| kvt_sleutels::ponos::name_from_email(&email));
451
chip(
452
format!("kvt-ticket-mention-{index}").into(),
453
format!("@{label}"),
454
false,
455
)
456
.on_click(cx.listener(
457
move |this, _, window, cx| this.mention(&email, window, cx),
458
))
459
})),
460
)
461
})
462
.child(Textarea::new(&self.reply))
463
.children(self.error.clone().map(|error| {
464
div()
465
.text_size(px(13.))
466
.text_color(theme::red_soft())
467
.child(error)
468
}))
469
.child(
470
h_flex()
471
.w_full()
472
.gap(px(8.))
473
.items_center()
474
.when(detail.ticket.is_closed(), |row| {
475
row.child(
476
div()
477
.text_size(px(12.))
478
.text_color(theme::text_muted())
479
.child(tr("kvt.tickets.closed_hint")),
480
)
481
})
482
.child(div().flex_1())
483
.child(
484
primary_button(
485
"kvt-ticket-send",
486
tr(if self.sending {
487
"kvt.tickets.sending"
488
} else {
489
"kvt.tickets.send"
490
}),
491
)
492
.on_click(cx.listener(|this, _, window, cx| this.send(window, cx))),
493
),
494
)
495
}
496
}
497
498
fn sender_names(detail: &TicketDetail) -> HashMap<String, String> {
499
detail
500
.messages
501
.iter()
502
.filter(|message| !message.sender_display_name.trim().is_empty())
503
.map(|message| {
504
(
505
message.sender_email.to_lowercase(),
506
message.sender_display_name.trim().to_owned(),
507
)
508
})
509
.collect()
510
}
511
512
/// Tekst met Asclepius-vermeldingen als `@Voornaam` (vet, accentkleur), zoals op het web.
513
fn message_text(text: &str, known: &[String], mention: Hsla) -> StyledText {
514
let (shown, ranges) = mention_display(text, known);
515
let style = HighlightStyle {
516
color: Some(mention),
517
font_weight: Some(FontWeight::BOLD),
518
..HighlightStyle::default()
519
};
520
StyledText::new(shown).with_highlights(ranges.into_iter().map(|range| (range, style)))
521
}
522
523
/// Getoonde tekst en de plekken van de vermeldingen daarin.
524
fn mention_display(text: &str, known: &[String]) -> (String, Vec<std::ops::Range<usize>>) {
525
let mut shown = String::new();
526
let mut ranges = Vec::new();
527
for part in split_mentions(text.trim_end(), known) {
528
match part {
529
TextPart::Text(text) => shown.push_str(&text),
530
TextPart::Mention { key, email } => {
531
let start = shown.len();
532
shown.push_str(&mention_label(&key, email.as_deref()));
533
ranges.push(start..shown.len());
534
}
535
}
536
}
537
(shown, ranges)
538
}
539
540
fn attachment_chip(
541
message: usize,
542
position: usize,
543
attachment: &TicketAttachment,
544
ghost: bool,
545
cx: &mut Context<TicketThread>,
546
) -> Stateful<Div> {
547
let attachment = attachment.clone();
548
let name = attachment.original_name.clone();
549
h_flex()
550
.id(ElementId::Name(
551
format!("kvt-ticket-attachment-{message}-{position}").into(),
552
))
553
.h(px(28.))
554
.px(px(10.))
555
.gap(px(6.))
556
.items_center()
557
.rounded(px(6.))
558
.cursor_pointer()
559
.text_size(px(12.))
560
.map(|chip| {
561
if ghost {
562
chip.border_1()
563
.border_color(rgb(GHOST_BORDER))
564
.text_color(rgb(GHOST_TEXT))
565
} else {
566
chip.bg(theme::popup_hover())
567
.text_color(theme::text())
568
.hover(|chip| chip.bg(theme::row_hover()))
569
}
570
})
571
.on_click(cx.listener(move |_, _, _, cx| open_attachment(attachment.clone(), cx)))
572
.child(symbol(
573
"attach_file",
574
14.,
575
if ghost {
576
rgb(GHOST_TEXT).into()
577
} else {
578
theme::text_muted()
579
},
580
))
581
.child(name)
582
}
583
584
/// Bijlagen gaan alleen met de token: ophalen, in de tijdelijke map zetten en openen.
585
fn open_attachment(attachment: TicketAttachment, cx: &mut App) {
586
if is_demo(cx) {
587
notice(tr("kvt.tickets.demo_attachment"), cx);
588
return;
589
}
590
let Some((token, client)) = token_and_client(cx) else {
591
return;
592
};
593
let id = attachment.id;
594
let name: String = attachment
595
.original_name
596
.chars()
597
.filter(|c| c.is_alphanumeric() || "-_. ".contains(*c))
598
.collect();
599
let name = if name.trim().is_empty() {
600
"bijlage".to_owned()
601
} else {
602
name
603
};
604
let downloading = runtime::spawn(async move {
605
let bytes = client.asclepius_attachment(&token, id).await?;
606
let directory = std::env::temp_dir().join("rusty-teams-asclepius");
607
std::fs::create_dir_all(&directory).map_err(|_| ClientError::Unavailable)?;
608
let path = directory.join(format!("{id}-{name}"));
609
std::fs::write(&path, bytes).map_err(|_| ClientError::Unavailable)?;
610
Ok::<_, ClientError>(path)
611
});
612
cx.spawn(async move |cx| {
613
let result = downloading.await.unwrap_or(Err(ClientError::Unavailable));
614
cx.update(|cx| match result {
615
Ok(path) => cx.open_with_system(&path),
616
Err(error) => {
617
if error == ClientError::Unauthorized {
618
forget_token(cx);
619
}
620
notice(ticket_error(&error), cx);
621
}
622
});
623
})
624
.detach();
625
}
626
627
impl Render for TicketThread {
628
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
629
let detail = match &self.detail {
630
Detail::Loading => {
631
return v_flex()
632
.size_full()
633
.child(muted(tr("kvt.card.loading")).px(px(PAGE_PADDING)))
634
.into_any_element();
635
}
636
Detail::Failed(error) => {
637
return v_flex()
638
.size_full()
639
.child(muted(ticket_error(error)).px(px(PAGE_PADDING)))
640
.into_any_element();
641
}
642
Detail::Loaded(detail) => detail.clone(),
643
};
644
let mut known = detail.participant_emails.clone();
645
known.push(detail.ticket.assigned_email.clone());
646
known.push(detail.ticket.user_email.clone());
647
known.extend(
648
detail
649
.messages
650
.iter()
651
.map(|message| message.sender_email.clone()),
652
);
653
let messages: Vec<AnyElement> = detail
654
.messages
655
.iter()
656
.enumerate()
657
.map(|(index, message)| self.message(index, message, &known, cx))
658
.collect();
659
v_flex()
660
.debug_selector(|| "kvt-ticket-thread".into())
661
.size_full()
662
.min_h_0()
663
.child(self.header(&detail))
664
.child(
665
div()
666
.id("kvt-ticket-messages")
667
.flex_1()
668
.min_h_0()
669
.overflow_y_scroll()
670
.track_scroll(&self.scroll)
671
.child(
672
v_flex()
673
.w_full()
674
.px(px(PAGE_PADDING))
675
.py(px(12.))
676
.gap(px(10.))
677
.children(messages),
678
),
679
)
680
.child(self.composer(&detail, cx))
681
.into_any_element()
682
}
683
}
684
685
// --- tegelpagina -------------------------------------------------------------
686
687
pub struct TicketsPage {
688
filter: TicketFilter,
689
list: List,
690
/// Open tickets, ook als het filter op Afgehandeld staat (badge in de rail).
691
open: Vec<Ticket>,
692
selected: Option<Entity<TicketThread>>,
693
seen: SeenTickets,
694
generation: u64,
695
since: Option<String>,
696
polling: bool,
697
}
698
699
/// De pagina (eenmalig aangemaakt; ook voor de badge als de tegel dicht is).
700
fn page(cx: &mut App) -> Option<Entity<TicketsPage>> {
701
if !super::installed(cx) {
702
return None;
703
}
704
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
705
return Some(page);
706
}
707
let page = cx.new(TicketsPage::new);
708
cx.global_mut::<super::Kvt>().tickets = Some(page.clone());
709
Some(page)
710
}
711
712
/// De tegel als element van het hoofdpaneel.
713
pub fn tickets_view(cx: &mut App) -> AnyElement {
714
match page(cx) {
715
Some(page) => div()
716
.flex_1()
717
.min_w_0()
718
.h_full()
719
.child(page)
720
.into_any_element(),
721
None => div().into_any_element(),
722
}
723
}
724
725
/// De tegel is geopend: vers ophalen.
726
pub fn tickets_opened(cx: &mut App) {
727
if let Some(page) = page(cx) {
728
page.update(cx, |page, cx| page.reload(cx));
729
}
730
}
731
732
/// Aantal ongelezen open tickets, voor de badge op de tegel.
733
pub fn tickets_unread(cx: &mut App) -> usize {
734
if !matches!(link(cx), Link::Linked(_)) {
735
return 0;
736
}
737
page(cx).map_or(0, |page| {
738
let page = page.read(cx);
739
page.seen.unread_count(&page.open)
740
})
741
}
742
743
fn refresh_list(cx: &mut App) {
744
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
745
page.update(cx, |page, cx| page.reload(cx));
746
}
747
}
748
749
/// Net aangemaakt: lijst opnieuw en het nieuwe ticket openen (als de tegel bestaat).
750
pub(super) fn created(id: u64, cx: &mut App) {
751
let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() else {
752
return;
753
};
754
let Some(window) = cx.active_window() else {
755
page.update(cx, |page, cx| page.reload(cx));
756
return;
757
};
758
window
759
.update(cx, |_, window, cx| {
760
page.update(cx, |page, cx| {
761
page.filter = TicketFilter::Open;
762
page.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));
763
page.reload(cx);
764
})
765
})
766
.ok();
767
}
768
769
/// Een ticket is bekeken (tegel of ticketvenster): niet meer ongelezen.
770
pub(super) fn ticket_seen(ticket: &Ticket, cx: &mut App) {
771
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {
772
page.update(cx, |page, cx| {
773
if page.seen.mark(ticket) {
774
save_seen(&page.seen, cx);
775
cx.notify();
776
}
777
});
778
}
779
}
780
781
impl TicketsPage {
782
fn new(cx: &mut Context<Self>) -> Self {
783
let mut page = TicketsPage {
784
filter: TicketFilter::Open,
785
list: List::Loading,
786
open: Vec::new(),
787
selected: None,
788
seen: load_seen(cx),
789
generation: 0,
790
since: None,
791
polling: false,
792
};
793
page.reload(cx);
794
page.start_polling(cx);
795
page
796
}
797
798
fn reload(&mut self, cx: &mut Context<Self>) {
799
self.generation += 1;
800
let generation = self.generation;
801
let filter = self.filter;
802
if is_demo(cx) {
803
let all = demo_tickets();
804
self.open = all.iter().filter(|t| !t.is_closed()).cloned().collect();
805
if self.seen.initialize(&self.open) {
806
// Demo: één ticket ongelezen, om de stip te tonen.
807
self.seen.seen.insert(DEMO_UNREAD, String::new());
808
}
809
self.list = List::Loaded(
810
all.into_iter()
811
.filter(|t| t.is_closed() == (filter == TicketFilter::Closed))
812
.collect(),
813
);
814
cx.notify();
815
return;
816
}
817
let Some((token, client)) = token_and_client(cx) else {
818
self.list = List::NotLinked;
819
cx.notify();
820
return;
821
};
822
if !matches!(self.list, List::Loaded(_)) {
823
self.list = List::Loading;
824
}
825
let loading = runtime::spawn(async move {
826
let open = client.asclepius_tickets(&token, TicketFilter::Open).await?;
827
let shown = match filter {
828
TicketFilter::Open => open.clone(),
829
TicketFilter::Closed => {
830
client
831
.asclepius_tickets(&token, TicketFilter::Closed)
832
.await?
833
}
834
};
835
Ok::<_, ClientError>((open, shown))
836
});
837
cx.spawn(async move |this, cx| {
838
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
839
cx.update(|cx| {
840
if matches!(result, Err(ClientError::Unauthorized)) {
841
forget_token(cx);
842
}
843
this.update(cx, |this, cx| {
844
if this.generation != generation {
845
return;
846
}
847
match result {
848
Ok((open, shown)) => {
849
if this.seen.initialize(&open) {
850
save_seen(&this.seen, cx);
851
}
852
this.since = Some(chrono::Utc::now().to_rfc3339());
853
this.open = open;
854
this.list = List::Loaded(shown);
855
}
856
Err(ClientError::Unauthorized) => this.list = List::NotLinked,
857
Err(error) => this.list = List::Failed(error),
858
}
859
cx.notify();
860
cx.refresh_windows();
861
})
862
.ok();
863
});
864
})
865
.detach();
866
}
867
868
/// Elke minuut `ticket_updates`; bij wijzigingen de lijst en het open ticket opnieuw.
869
fn start_polling(&mut self, cx: &mut Context<Self>) {
870
if self.polling || is_demo(cx) {
871
return;
872
}
873
self.polling = true;
874
cx.spawn(async move |this, cx| {
875
loop {
876
cx.background_executor().timer(POLL_INTERVAL).await;
877
let Ok(Some((since, token))) = this.update(cx, |this, cx| {
878
let since = this.since.clone()?;
879
let (token, client) = token_and_client(cx)?;
880
Some((since, (token, client)))
881
}) else {
882
if this.upgrade().is_none() {
883
return;
884
}
885
continue;
886
};
887
let (token, client): (String, CardsClient) = token;
888
let polling =
889
runtime::spawn(async move { client.asclepius_updates(&token, &since).await });
890
let result = polling.await.unwrap_or(Err(ClientError::Unavailable));
891
let alive = this.update(cx, |this, cx| {
892
if let Ok((changed, server_time)) = result {
893
if !server_time.is_empty() {
894
this.since = Some(server_time);
895
}
896
if !changed.is_empty() {
897
let open_id = this.selected.as_ref().map(|thread| thread.read(cx).id());
898
if let Some(thread) = this.selected.clone()
899
&& changed.iter().any(|t| Some(t.id) == open_id)
900
{
901
thread.update(cx, |thread, cx| thread.reload(cx));
902
}
903
this.reload(cx);
904
}
905
}
906
});
907
if alive.is_err() {
908
return;
909
}
910
}
911
})
912
.detach();
913
}
914
915
fn set_filter(&mut self, filter: TicketFilter, cx: &mut Context<Self>) {
916
if self.filter == filter {
917
return;
918
}
919
self.filter = filter;
920
self.list = List::Loading;
921
self.reload(cx);
922
}
923
924
fn select(&mut self, ticket: &Ticket, window: &mut Window, cx: &mut Context<Self>) {
925
if self
926
.selected
927
.as_ref()
928
.is_some_and(|thread| thread.read(cx).id() == ticket.id)
929
{
930
return;
931
}
932
let id = ticket.id;
933
self.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));
934
if self.seen.mark(ticket) {
935
save_seen(&self.seen, cx);
936
}
937
cx.notify();
938
cx.refresh_windows();
939
}
940
941
fn header(&self, cx: &mut Context<Self>) -> Div {
942
h_flex()
943
.h(px(HEADER_HEIGHT))
944
.flex_none()
945
.px(px(PAGE_PADDING))
946
.gap(px(8.))
947
.items_center()
948
.child(
949
div()
950
.flex_1()
951
.min_w_0()
952
.truncate()
953
.text_size(px(16.))
954
.font_weight(FontWeight::BOLD)
955
.text_color(theme::text())
956
.child(tr("kvt.tickets.title")),
957
)
958
.children(super::ticket_form::new_ticket_button(cx))
959
.child(
960
secondary_button("kvt-tickets-refresh", "refresh", tr("kvt.card.refresh"))
961
.on_click(cx.listener(|this, _, _, cx| this.reload(cx))),
962
)
963
}
964
965
fn list(&self, cx: &mut Context<Self>) -> AnyElement {
966
let filters = h_flex()
967
.w_full()
968
.flex_none()
969
.px(px(12.))
970
.pb(px(8.))
971
.gap(px(6.))
972
.child(
973
chip(
974
"kvt-tickets-filter-open".into(),
975
tr("kvt.tickets.filter_open"),
976
self.filter == TicketFilter::Open,
977
)
978
.on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Open, cx))),
979
)
980
.child(
981
chip(
982
"kvt-tickets-filter-closed".into(),
983
tr("kvt.tickets.filter_closed"),
984
self.filter == TicketFilter::Closed,
985
)
986
.on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Closed, cx))),
987
);
988
let selected = self.selected.as_ref().map(|thread| thread.read(cx).id());
989
let rows: AnyElement = match &self.list {
990
List::Loading | List::NotLinked => {
991
muted(tr("kvt.card.loading")).px(px(12.)).into_any_element()
992
}
993
List::Failed(error) => muted(ticket_error(error)).px(px(12.)).into_any_element(),
994
List::Loaded(tickets) if tickets.is_empty() => muted(tr(match self.filter {
995
TicketFilter::Open => "kvt.tickets.empty_open",
996
TicketFilter::Closed => "kvt.tickets.empty_closed",
997
}))
998
.px(px(12.))
999
.into_any_element(),
1000
List::Loaded(tickets) => v_flex()
1001
.w_full()
1002
.px(px(8.))
1003
.gap(px(2.))
1004
.children(tickets.iter().enumerate().map(|(index, ticket)| {
1005
let unread = self.seen.is_unread(ticket);
1006
let active = selected == Some(ticket.id);
1007
let row_ticket = ticket.clone();
1008
v_flex()
1009
.id(ElementId::Name(format!("kvt-tickets-row-{index}").into()))
1010
.debug_selector(move || format!("kvt-tickets/row/{index}"))
1011
.w_full()
1012
.px(px(10.))
1013
.py(px(8.))
1014
.gap(px(2.))
1015
.rounded(px(6.))
1016
.cursor_pointer()
1017
.map(|row| {
1018
if active {
1019
row.bg(theme::selection())
1020
} else {
1021
row.hover(|row| row.bg(theme::row_hover()))
1022
}
1023
})
1024
.on_click(cx.listener(move |this, _, window, cx| {
1025
this.select(&row_ticket, window, cx)
1026
}))
1027
.child(
1028
h_flex()
1029
.w_full()
1030
.gap(px(6.))
1031
.items_center()
1032
.child(
1033
div()
1034
.flex_1()
1035
.min_w_0()
1036
.truncate()
1037
.text_size(px(13.))
1038
.text_color(theme::text_strong())
1039
.when(unread, |title| title.font_weight(FontWeight::BOLD))
1040
.child(ticket.title.clone()),
1041
)
1042
.when(unread, |row| {
1043
row.child(
1044
div()
1045
.size(px(8.))
1046
.flex_none()
1047
.rounded_full()
1048
.bg(theme::accent()),
1049
)
1050
}),
1051
)
1052
.child(
1053
div()
1054
.truncate()
1055
.text_size(px(12.))
1056
.text_color(theme::text_muted())
1057
.child(format!(
1058
"#{} · {} · {}",
1059
ticket.id,
1060
status_label(&ticket.status),
1061
when(&ticket.updated_at)
1062
)),
1063
)
1064
}))
1065
.into_any_element(),
1066
};
1067
v_flex()
1068
.id("kvt-tickets-list")
1069
.w(px(LIST_WIDTH))
1070
.h_full()
1071
.flex_none()
1072
.border_r_1()
1073
.border_color(theme::border())
1074
.child(filters)
1075
.child(
1076
div()
1077
.id("kvt-tickets-rows")
1078
.flex_1()
1079
.min_h_0()
1080
.overflow_y_scrollbar()
1081
.child(rows),
1082
)
1083
.into_any_element()
1084
}
1085
}
1086
1087
impl Render for TicketsPage {
1088
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1089
let linked = matches!(link(cx), Link::Linked(_));
1090
if !linked && !is_demo(cx) {
1091
self.list = List::NotLinked;
1092
self.selected = None;
1093
self.open.clear();
1094
} else if matches!(self.list, List::NotLinked) {
1095
self.reload(cx);
1096
}
1097
let body = if !linked {
1098
v_flex()
1099
.p(px(PAGE_PADDING))
1100
.max_w(px(560.))
1101
.child(not_linked())
1102
.into_any_element()
1103
} else {
1104
h_flex()
1105
.flex_1()
1106
.min_h_0()
1107
.w_full()
1108
.child(self.list(cx))
1109
.child(
1110
div()
1111
.flex_1()
1112
.min_w_0()
1113
.h_full()
1114
.child(match &self.selected {
1115
Some(thread) => thread.clone().into_any_element(),
1116
None => muted(tr("kvt.tickets.pick"))
1117
.px(px(PAGE_PADDING))
1118
.into_any_element(),
1119
}),
1120
)
1121
.into_any_element()
1122
};
1123
v_flex()
1124
.debug_selector(|| KVT_TICKETS_TAG.into())
1125
.relative()
1126
.size_full()
1127
.rounded(px(RADIUS))
1128
.bg(theme::surface())
1129
.overflow_hidden()
1130
.child(self.header(cx))
1131
.child(body)
1132
}
1133
}
1134
1135
// --- ticketvenster (links naar een ticket) ----------------------------------------
1136
1137
const WINDOW_WIDTH: f32 = 720.;
1138
const WINDOW_MARGIN: f32 = 32.;
1139
const WINDOW_BACKDROP: f32 = 0.55;
1140
pub const KVT_TICKET_WINDOW_TAG: &str = "kvt-asclepius-window";
1141
1142
/// Een link naar een Asclepius-ticket (`…/asclepius/index.php?open=…`): heb je toegang, dan
1143
/// opent het ticket in een venster in de app; anders gewoon in de browser. `false` als het
1144
/// geen ticketlink is of je niet gekoppeld bent (dan opent de shell de link zelf).
1145
pub fn open_ticket_link(url: &str, cx: &mut App) -> bool {
1146
if !installed(cx) || !matches!(link(cx), Link::Linked(_)) {
1147
return false;
1148
}
1149
let Some(id) = ticket_id_from_url(&base_url(), url) else {
1150
return false;
1151
};
1152
let url = url.to_owned();
1153
if is_demo(cx) {
1154
match demo_detail(id) {
1155
Some(detail) => cx.defer(move |cx| show_window(detail, cx)),
1156
None => cx.open_url(&url),
1157
}
1158
return true;
1159
}
1160
let Some((token, client)) = token_and_client(cx) else {
1161
return false;
1162
};
1163
let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await });
1164
cx.spawn(async move |cx| {
1165
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
1166
cx.update(|cx| match result {
1167
Ok(detail) => show_window(detail, cx),
1168
Err(error) => {
1169
if error == ClientError::Unauthorized {
1170
forget_token(cx);
1171
}
1172
// Geen toegang of Asclepius niet bereikbaar: een gewone link.
1173
cx.open_url(&url);
1174
}
1175
});
1176
})
1177
.detach();
1178
true
1179
}
1180
1181
fn show_window(detail: TicketDetail, cx: &mut App) {
1182
let Some(window) = cx
1183
.active_window()
1184
.or_else(|| cx.windows().into_iter().next())
1185
else {
1186
return;
1187
};
1188
let ticket = detail.ticket.clone();
1189
window
1190
.update(cx, |_, window, cx| {
1191
let thread =
1192
cx.new(|cx| TicketThread::with_detail(ticket.id, Some(detail), window, cx));
1193
update(cx, |kvt| kvt.ticket_window = Some(thread));
1194
cx.refresh_windows();
1195
})
1196
.ok();
1197
ticket_seen(&ticket, cx);
1198
}
1199
1200
fn close_window(cx: &mut App) {
1201
update(cx, |kvt| kvt.ticket_window = None);
1202
cx.refresh_windows();
1203
}
1204
1205
/// Laag voor `kvt::overlay`.
1206
pub(super) fn window_overlay(thread: Entity<TicketThread>) -> AnyElement {
1207
div()
1208
.id("kvt-ticket-window-layer")
1209
.absolute()
1210
.top_0()
1211
.left_0()
1212
.size_full()
1213
.flex()
1214
.items_center()
1215
.justify_center()
1216
.child(
1217
div()
1218
.id("kvt-ticket-window-backdrop")
1219
.absolute()
1220
.top_0()
1221
.left_0()
1222
.size_full()
1223
.bg(black().opacity(WINDOW_BACKDROP))
1224
.occlude()
1225
.on_click(|_, _, cx| close_window(cx)),
1226
)
1227
.child(
1228
div()
1229
.id("kvt-ticket-window")
1230
.debug_selector(|| KVT_TICKET_WINDOW_TAG.into())
1231
.relative()
1232
.w(px(WINDOW_WIDTH))
1233
.max_w(relative(1.))
1234
.h(relative(0.85))
1235
.m(px(WINDOW_MARGIN))
1236
.rounded(px(RADIUS))
1237
.dialog_surface()
1238
.overflow_hidden()
1239
.occlude()
1240
.child(thread)
1241
.child(
1242
div()
1243
.id("kvt-ticket-window-close")
1244
.absolute()
1245
.top(px(10.))
1246
.right(px(10.))
1247
.size(px(28.))
1248
.flex()
1249
.items_center()
1250
.justify_center()
1251
.rounded_full()
1252
.cursor_pointer()
1253
.hover(|button| button.bg(theme::popup_hover()))
1254
.on_click(|_, _, cx| close_window(cx))
1255
.child(symbol("close", 16., theme::text_muted())),
1256
),
1257
)
1258
.into_any_element()
1259
}
1260
1261
// --- demo ------------------------------------------------------------------------
1262
1263
const DEMO_UNREAD: u64 = 4102;
1264
1265
thread_local! {
1266
static DEMO_REPLIES: std::cell::RefCell<HashMap<u64, Vec<TicketMessage>>> =
1267
std::cell::RefCell::new(HashMap::new());
1268
}
1269
1270
fn demo_ticket(id: u64, title: &str, status: &str, category: &str, updated: &str) -> Ticket {
1271
Ticket {
1272
id,
1273
title: title.to_owned(),
1274
category: category.to_owned(),
1275
user_email: super::demo::token().email,
1276
assigned_email: "ict.medewerker@example.com".to_owned(),
1277
status: status.to_owned(),
1278
created_at: "2026-01-12T09:15:00+01:00".to_owned(),
1279
updated_at: updated.to_owned(),
1280
message_count: 3,
1281
..Ticket::default()
1282
}
1283
}
1284
1285
pub(super) fn demo_tickets() -> Vec<Ticket> {
1286
vec![
1287
Ticket {
1288
subcategory: "Laptop".to_owned(),
1289
..demo_ticket(
1290
DEMO_UNREAD,
1291
"Laptop start niet meer op",
1292
"in behandeling",
1293
"Hardware",
1294
"2026-01-15T13:39:00+01:00",
1295
)
1296
},
1297
demo_ticket(
1298
4098,
1299
"Toegang tot gedeelde map Projecten",
1300
"afwachtende op gebruiker",
1301
"Rechten en toegang",
1302
"2026-01-14T16:02:00+01:00",
1303
),
1304
demo_ticket(
1305
4090,
1306
"Nieuwe headset",
1307
"ingediend",
1308
"Hardware bestellen",
1309
"2026-01-13T10:20:00+01:00",
1310
),
1311
demo_ticket(
1312
4012,
1313
"Printer op kantoor geeft een fout",
1314
"afgehandeld",
1315
"Hardware",
1316
"2026-01-08T11:00:00+01:00",
1317
),
1318
]
1319
}
1320
1321
fn demo_message(
1322
id: u64,
1323
email: &str,
1324
name: &str,
1325
role: &str,
1326
text: &str,
1327
at: &str,
1328
) -> TicketMessage {
1329
TicketMessage {
1330
id,
1331
sender_email: email.to_owned(),
1332
sender_role: role.to_owned(),
1333
sender_display_name: name.to_owned(),
1334
message_text: text.to_owned(),
1335
created_at: at.to_owned(),
1336
..TicketMessage::default()
1337
}
1338
}
1339
1340
pub(super) fn demo_detail(id: u64) -> Option<TicketDetail> {
1341
let ticket = demo_tickets().into_iter().find(|ticket| ticket.id == id)?;
1342
let me = super::demo::token();
1343
let ict = "ict.medewerker@example.com";
1344
let mut messages = vec![
1345
demo_message(
1346
1,
1347
&me.email,
1348
&me.name,
1349
"user",
1350
"Mijn laptop gaat niet meer aan sinds vanochtend. Het lampje knippert oranje.",
1351
"2026-01-15T09:15:00+01:00",
1352
),
1353
demo_message(
1354
2,
1355
ict,
1356
"Sam Ict",
1357
"admin",
1358
"Dank je. Kun je de lader een minuut loskoppelen en het opnieuw proberen? @dana.demo:examplecom",
1359
"2026-01-15T10:02:00+01:00",
1360
),
1361
TicketMessage {
1362
is_ghost: true,
1363
..demo_message(
1364
3,
1365
ict,
1366
"Sam Ict",
1367
"admin",
1368
"Intern: garantie loopt nog tot maart, eventueel omruilen via de leverancier.",
1369
"2026-01-15T10:05:00+01:00",
1370
)
1371
},
1372
TicketMessage {
1373
attachments: vec![TicketAttachment {
1374
id: 77,
1375
original_name: "foto-lampje.jpg".to_owned(),
1376
mime_type: "image/jpeg".to_owned(),
1377
file_size: 120_000,
1378
}],
1379
..demo_message(
1380
4,
1381
&me.email,
1382
&me.name,
1383
"user",
1384
"Gedaan, hij knippert nog steeds. Foto erbij.",
1385
"2026-01-15T13:39:00+01:00",
1386
)
1387
},
1388
];
1389
if id != DEMO_UNREAD {
1390
messages.truncate(1);
1391
messages[0].message_text = format!("{}.", ticket.title);
1392
}
1393
DEMO_REPLIES.with(|replies| {
1394
messages.extend(replies.borrow().get(&id).cloned().unwrap_or_default());
1395
});
1396
Some(TicketDetail {
1397
description: messages[0].message_text.clone(),
1398
participant_emails: vec![me.email.clone(), "jonas.ortega@example.com".to_owned()],
1399
messages,
1400
ticket,
1401
})
1402
}
1403
1404
fn demo_reply(id: u64, text: &str, email: &str) {
1405
let me = super::demo::token();
1406
DEMO_REPLIES.with(|replies| {
1407
let mut replies = replies.borrow_mut();
1408
let list = replies.entry(id).or_default();
1409
list.push(demo_message(
1410
100 + list.len() as u64,
1411
if email.is_empty() { &me.email } else { email },
1412
&me.name,
1413
"user",
1414
text,
1415
&chrono::Local::now().to_rfc3339(),
1416
));
1417
});
1418
}
1419
1420
#[cfg(test)]
1421
mod tests {
1422
use super::{DEMO_UNREAD, demo_detail, demo_tickets, mention_display, when};
1423
use kvt_sleutels::tickets::Ticket;
1424
1425
#[test]
1426
fn dates_are_dutch_and_local() {
1427
let shown = when("2026-01-15T13:39:00+01:00");
1428
assert!(shown.starts_with("15 jan 2026") || shown.starts_with("16 jan 2026"));
1429
assert_eq!(when("geen datum"), "geen datum");
1430
}
1431
1432
#[test]
1433
fn demo_has_a_ghost_and_a_closed_ticket() {
1434
let detail = demo_detail(DEMO_UNREAD).unwrap();
1435
assert!(detail.messages.iter().any(|message| message.is_ghost));
1436
assert!(demo_tickets().iter().any(Ticket::is_closed));
1437
}
1438
1439
#[test]
1440
fn mentions_render_as_first_names() {
1441
let (shown, ranges) = mention_display(
1442
"Graag @dana.demo:examplecom",
1443
&["dana.demo@example.com".to_owned()],
1444
);
1445
assert_eq!(shown, "Graag @Dana");
1446
assert_eq!(ranges, [6..11]);
1447
}
1448
}
@@ -0,0 +1,1448 @@1
//! Asclepius-tegel: je tickets (zoals «Mijn tickets» op het web, plus aan jou2
//! toegewezen) links, het gesprek van het gekozen ticket rechts. Antwoorden kan3
//! hier; behandelen (status, toewijzing) blijft in Asclepius (fase 2).4
//!5
//! Ongelezen is lokaal (`kvt.asclepius.seen`): een ticket waarvan `updated_at`6
//! nieuwer is dan toen je het opende. Elke minuut `ticket_updates`.7
8
use std::collections::HashMap;9
use std::time::Duration;10
11
use chrono::{DateTime, Local};12
use gpui_kit::component::input::{Textarea, TextareaState};13
use gpui_kit::component::scroll::ScrollableElement as _;14
use gpui_kit::component::{h_flex, v_flex};15
use gpui_kit::prelude::FluentBuilder as _;16
use gpui_kit::*;17
use kvt_sleutels::format::date_time_nl;18
use kvt_sleutels::tickets::{19
SeenTickets, TextPart, Ticket, TicketAttachment, TicketDetail, TicketFilter, TicketMessage,20
mention_label, mention_token, split_mentions, ticket_id_from_url,21
};22
use kvt_sleutels::{CardsClient, ClientError};23
24
use super::modal::{primary_button, secondary_button};25
use super::tasks::{chip, muted, not_linked};26
use super::{27
Link, base_url, error_text, forget_token, installed, is_demo, link, notice, token_and_client,28
update,29
};30
use crate::app_state::AppHandle;31
use crate::i18n::tr;32
use crate::runtime;33
use crate::theme::{self, ElevatedSurface as _};34
use crate::views::widgets::symbol;35
36
pub const KVT_TICKETS_TAG: &str = "kvt-asclepius-tickets";37
const SEEN_META_KEY: &str = "kvt.asclepius.seen";38
const POLL_INTERVAL: Duration = Duration::from_secs(60);39
const HEADER_HEIGHT: f32 = 60.;40
const PAGE_PADDING: f32 = 20.;41
const LIST_WIDTH: f32 = 320.;42
const RADIUS: f32 = 10.;43
const BUBBLE_RADIUS: f32 = 14.;44
45
// Ghost-berichten zoals op het web (`.message.is-ghost`), ongeacht het thema.46
const GHOST_BG: u32 = 0x5b21b6;47
const GHOST_BORDER: u32 = 0xf9a8d4;48
const GHOST_TEXT: u32 = 0xfce7f3;49
50
#[derive(Clone)]51
enum List {52
NotLinked,53
Loading,54
Loaded(Vec<Ticket>),55
Failed(ClientError),56
}57
58
#[derive(Clone)]59
enum Detail {60
Loading,61
Loaded(TicketDetail),62
Failed(ClientError),63
}64
65
pub(super) fn ticket_error(error: &ClientError) -> String {66
match error {67
ClientError::Forbidden | ClientError::NotFound => tr("kvt.tickets.not_found"),68
ClientError::BadRequest => tr("kvt.tickets.failed"),69
other => error_text(other),70
}71
}72
73
/// `2026-01-15T13:39:00+01:00` → `15 jan 2026 13:39` (lokale tijd).74
pub(super) fn when(value: &str) -> String {75
DateTime::parse_from_rfc3339(value.trim())76
.map(|moment| date_time_nl(moment.with_timezone(&Local).naive_local()))77
.unwrap_or_else(|_| value.get(..16).unwrap_or(value).replace('T', " "))78
}79
80
pub(super) fn status_label(status: &str) -> String {81
let key = format!("kvt.tickets.status.{}", status.trim().replace(' ', "_"));82
let label = tr(&key);83
if label == key || label.is_empty() {84
status.to_owned()85
} else {86
label87
}88
}89
90
fn me(cx: &App) -> String {91
match link(cx) {92
Link::Linked(stored) => stored.email.to_lowercase(),93
_ => String::new(),94
}95
}96
97
// --- lokaal ongelezen ----------------------------------------------------------98
99
fn load_seen(cx: &App) -> SeenTickets {100
cx.try_global::<AppHandle>()101
.and_then(|handle| handle.0.read(cx).store.meta(SEEN_META_KEY).ok().flatten())102
.map(|json| SeenTickets::from_json(&json))103
.unwrap_or_default()104
}105
106
fn save_seen(seen: &SeenTickets, cx: &App) {107
if let Some(handle) = cx.try_global::<AppHandle>() {108
let _ = handle109
.0110
.read(cx)111
.store112
.set_meta(SEEN_META_KEY, &seen.to_json());113
}114
}115
116
// --- gesprek van één ticket (tegel en ticketvenster) ----------------------------117
118
pub struct TicketThread {119
id: u64,120
detail: Detail,121
reply: Entity<TextareaState>,122
sending: bool,123
error: Option<String>,124
generation: u64,125
scroll: ScrollHandle,126
}127
128
impl TicketThread {129
pub(super) fn new(id: u64, window: &mut Window, cx: &mut Context<Self>) -> Self {130
let mut thread = Self::with_detail(id, None, window, cx);131
thread.reload(cx);132
thread133
}134
135
/// Met een al opgehaald ticket (ticketvenster: eerst kijken of je toegang hebt).136
fn with_detail(137
id: u64,138
detail: Option<TicketDetail>,139
window: &mut Window,140
cx: &mut Context<Self>,141
) -> Self {142
let reply = cx.new(|cx| {143
TextareaState::new(window, cx)144
.auto_grow(2, 8)145
.placeholder(tr("kvt.tickets.reply_placeholder"))146
});147
let scroll = ScrollHandle::new();148
if detail.is_some() {149
scroll.scroll_to_bottom();150
}151
TicketThread {152
id,153
detail: detail.map_or(Detail::Loading, Detail::Loaded),154
reply,155
sending: false,156
error: None,157
generation: 0,158
scroll,159
}160
}161
162
pub(super) fn id(&self) -> u64 {163
self.id164
}165
166
pub(super) fn reload(&mut self, cx: &mut Context<Self>) {167
self.generation += 1;168
let generation = self.generation;169
let id = self.id;170
if is_demo(cx) {171
self.detail = match demo_detail(id) {172
Some(detail) => Detail::Loaded(detail),173
None => Detail::Failed(ClientError::NotFound),174
};175
self.scroll.scroll_to_bottom();176
cx.notify();177
return;178
}179
let Some((token, client)) = token_and_client(cx) else {180
return;181
};182
let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await });183
cx.spawn(async move |this, cx| {184
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));185
cx.update(|cx| {186
if result == Err(ClientError::Unauthorized) {187
forget_token(cx);188
}189
let opened = result.as_ref().ok().map(|detail| detail.ticket.clone());190
this.update(cx, |this, cx| {191
if this.generation != generation {192
return;193
}194
let first = !matches!(this.detail, Detail::Loaded(_));195
this.detail = match result {196
Ok(detail) => Detail::Loaded(detail),197
Err(error) => Detail::Failed(error),198
};199
if first {200
this.scroll.scroll_to_bottom();201
}202
cx.notify();203
})204
.ok();205
if let Some(ticket) = opened {206
ticket_seen(&ticket, cx);207
}208
});209
})210
.detach();211
}212
213
fn mention(&mut self, email: &str, window: &mut Window, cx: &mut Context<Self>) {214
let Some(token) = mention_token(email) else {215
return;216
};217
let current = self.reply.read(cx).value().to_string();218
let joined = if current.is_empty() || current.ends_with([' ', '\n']) {219
format!("{current}{token} ")220
} else {221
format!("{current} {token} ")222
};223
self.reply.update(cx, |reply, cx| {224
reply.set_value(joined, window, cx);225
reply.focus(window, cx);226
});227
}228
229
fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {230
if self.sending {231
return;232
}233
let text = self.reply.read(cx).value().trim().to_owned();234
if text.is_empty() {235
return;236
}237
self.sending = true;238
self.error = None;239
cx.notify();240
if is_demo(cx) {241
demo_reply(self.id, &text, &me(cx));242
self.sending = false;243
self.reply244
.update(cx, |reply, cx| reply.set_value("", window, cx));245
self.scroll.scroll_to_bottom();246
self.reload(cx);247
refresh_list(cx);248
return;249
}250
let Some((token, client)) = token_and_client(cx) else {251
self.sending = false;252
return;253
};254
let id = self.id;255
let sending =256
runtime::spawn(async move { client.asclepius_reply(&token, id, &text).await });257
let reply = self.reply.clone();258
cx.spawn_in(window, async move |this, cx| {259
let result = sending.await.unwrap_or(Err(ClientError::Unavailable));260
this.update_in(cx, |this, window, cx| {261
this.sending = false;262
match &result {263
Ok(()) => {264
reply.update(cx, |reply, cx| reply.set_value("", window, cx));265
this.scroll.scroll_to_bottom();266
this.reload(cx);267
refresh_list(cx);268
}269
Err(error) => {270
if *error == ClientError::Unauthorized {271
forget_token(cx);272
}273
this.error = Some(ticket_error(error));274
}275
}276
cx.notify();277
})278
.ok();279
})280
.detach();281
}282
283
fn header(&self, detail: &TicketDetail) -> Div {284
let ticket = &detail.ticket;285
let mut meta = vec![format!("#{}", ticket.id), status_label(&ticket.status)];286
if !ticket.category.is_empty() {287
meta.push(if ticket.subcategory.is_empty() {288
ticket.category.clone()289
} else {290
format!("{} › {}", ticket.category, ticket.subcategory)291
});292
}293
if !ticket.created_at.is_empty() {294
meta.push(when(&ticket.created_at));295
}296
v_flex()297
.w_full()298
.flex_none()299
.px(px(PAGE_PADDING))300
.py(px(12.))301
.gap(px(2.))302
.border_b_1()303
.border_color(theme::border())304
.child(305
div()306
.text_size(px(16.))307
.font_weight(FontWeight::BOLD)308
.text_color(theme::text())309
.child(ticket.title.clone()),310
)311
.child(312
div()313
.text_size(px(12.))314
.text_color(theme::text_muted())315
.child(meta.join(" · ")),316
)317
}318
319
fn message(320
&self,321
index: usize,322
message: &TicketMessage,323
known: &[String],324
cx: &mut Context<Self>,325
) -> AnyElement {326
let ghost = message.is_ghost;327
let from_ict = message.sender_role == "admin";328
let text_color = if ghost {329
rgb(GHOST_TEXT).into()330
} else {331
theme::text()332
};333
let muted_color = if ghost {334
rgb(GHOST_TEXT).into()335
} else {336
theme::text_muted()337
};338
let mention_color: Hsla = if ghost {339
rgb(GHOST_BORDER).into()340
} else {341
theme::accent_text()342
};343
let mut role = Vec::new();344
if from_ict {345
role.push(tr("kvt.tickets.ict"));346
}347
if ghost {348
role.push(tr("kvt.tickets.ghost"));349
}350
let head = h_flex()351
.w_full()352
.gap(px(8.))353
.items_center()354
.child(355
div()356
.text_size(px(13.))357
.font_weight(FontWeight::SEMIBOLD)358
.text_color(text_color)359
.child(message.sender_name()),360
)361
.when(!role.is_empty(), |row| {362
row.child(363
div()364
.text_size(px(11.))365
.text_color(muted_color)366
.child(role.join(" · ")),367
)368
})369
.child(div().flex_1())370
.child(371
div()372
.text_size(px(11.))373
.text_color(muted_color)374
.child(when(&message.created_at)),375
);376
let body = message_text(&message.message_text, known, mention_color);377
let attachments: Vec<AnyElement> = message378
.attachments379
.iter()380
.enumerate()381
.map(|(position, attachment)| {382
attachment_chip(index, position, attachment, ghost, cx).into_any_element()383
})384
.collect();385
v_flex()386
.id(ElementId::Name(387
format!("kvt-ticket-message-{index}").into(),388
))389
.w_full()390
.p(px(12.))391
.gap(px(6.))392
.rounded(px(BUBBLE_RADIUS))393
.map(|bubble| {394
if ghost {395
bubble396
.bg(rgb(GHOST_BG))397
.border_2()398
.border_color(rgb(GHOST_BORDER))399
} else if from_ict {400
bubble.bg(theme::popup_hover())401
} else {402
bubble.bg(theme::surface_raised())403
}404
})405
.child(head)406
.child(div().text_size(px(13.)).text_color(text_color).child(body))407
.when(!attachments.is_empty(), |bubble| {408
bubble.child(h_flex().flex_wrap().gap(px(6.)).children(attachments))409
})410
.into_any_element()411
}412
413
fn composer(&self, detail: &TicketDetail, cx: &mut Context<Self>) -> Div {414
let me = me(cx);415
let mut people: Vec<String> = detail416
.participant_emails417
.iter()418
.chain(std::iter::once(&detail.ticket.assigned_email))419
.map(|email| email.to_lowercase())420
.filter(|email| !email.is_empty() && *email != me)421
.collect();422
people.sort();423
people.dedup();424
let names = sender_names(detail);425
v_flex()426
.w_full()427
.flex_none()428
.px(px(PAGE_PADDING))429
.py(px(12.))430
.gap(px(8.))431
.border_t_1()432
.border_color(theme::border())433
.when(!people.is_empty(), |column| {434
column.child(435
h_flex()436
.w_full()437
.flex_wrap()438
.gap(px(6.))439
.items_center()440
.child(441
div()442
.text_size(px(12.))443
.text_color(theme::text_muted())444
.child(tr("kvt.tickets.mention")),445
)446
.children(people.into_iter().enumerate().map(|(index, email)| {447
let label = names448
.get(&email)449
.cloned()450
.unwrap_or_else(|| kvt_sleutels::ponos::name_from_email(&email));451
chip(452
format!("kvt-ticket-mention-{index}").into(),453
format!("@{label}"),454
false,455
)456
.on_click(cx.listener(457
move |this, _, window, cx| this.mention(&email, window, cx),458
))459
})),460
)461
})462
.child(Textarea::new(&self.reply))463
.children(self.error.clone().map(|error| {464
div()465
.text_size(px(13.))466
.text_color(theme::red_soft())467
.child(error)468
}))469
.child(470
h_flex()471
.w_full()472
.gap(px(8.))473
.items_center()474
.when(detail.ticket.is_closed(), |row| {475
row.child(476
div()477
.text_size(px(12.))478
.text_color(theme::text_muted())479
.child(tr("kvt.tickets.closed_hint")),480
)481
})482
.child(div().flex_1())483
.child(484
primary_button(485
"kvt-ticket-send",486
tr(if self.sending {487
"kvt.tickets.sending"488
} else {489
"kvt.tickets.send"490
}),491
)492
.on_click(cx.listener(|this, _, window, cx| this.send(window, cx))),493
),494
)495
}496
}497
498
fn sender_names(detail: &TicketDetail) -> HashMap<String, String> {499
detail500
.messages501
.iter()502
.filter(|message| !message.sender_display_name.trim().is_empty())503
.map(|message| {504
(505
message.sender_email.to_lowercase(),506
message.sender_display_name.trim().to_owned(),507
)508
})509
.collect()510
}511
512
/// Tekst met Asclepius-vermeldingen als `@Voornaam` (vet, accentkleur), zoals op het web.513
fn message_text(text: &str, known: &[String], mention: Hsla) -> StyledText {514
let (shown, ranges) = mention_display(text, known);515
let style = HighlightStyle {516
color: Some(mention),517
font_weight: Some(FontWeight::BOLD),518
..HighlightStyle::default()519
};520
StyledText::new(shown).with_highlights(ranges.into_iter().map(|range| (range, style)))521
}522
523
/// Getoonde tekst en de plekken van de vermeldingen daarin.524
fn mention_display(text: &str, known: &[String]) -> (String, Vec<std::ops::Range<usize>>) {525
let mut shown = String::new();526
let mut ranges = Vec::new();527
for part in split_mentions(text.trim_end(), known) {528
match part {529
TextPart::Text(text) => shown.push_str(&text),530
TextPart::Mention { key, email } => {531
let start = shown.len();532
shown.push_str(&mention_label(&key, email.as_deref()));533
ranges.push(start..shown.len());534
}535
}536
}537
(shown, ranges)538
}539
540
fn attachment_chip(541
message: usize,542
position: usize,543
attachment: &TicketAttachment,544
ghost: bool,545
cx: &mut Context<TicketThread>,546
) -> Stateful<Div> {547
let attachment = attachment.clone();548
let name = attachment.original_name.clone();549
h_flex()550
.id(ElementId::Name(551
format!("kvt-ticket-attachment-{message}-{position}").into(),552
))553
.h(px(28.))554
.px(px(10.))555
.gap(px(6.))556
.items_center()557
.rounded(px(6.))558
.cursor_pointer()559
.text_size(px(12.))560
.map(|chip| {561
if ghost {562
chip.border_1()563
.border_color(rgb(GHOST_BORDER))564
.text_color(rgb(GHOST_TEXT))565
} else {566
chip.bg(theme::popup_hover())567
.text_color(theme::text())568
.hover(|chip| chip.bg(theme::row_hover()))569
}570
})571
.on_click(cx.listener(move |_, _, _, cx| open_attachment(attachment.clone(), cx)))572
.child(symbol(573
"attach_file",574
14.,575
if ghost {576
rgb(GHOST_TEXT).into()577
} else {578
theme::text_muted()579
},580
))581
.child(name)582
}583
584
/// Bijlagen gaan alleen met de token: ophalen, in de tijdelijke map zetten en openen.585
fn open_attachment(attachment: TicketAttachment, cx: &mut App) {586
if is_demo(cx) {587
notice(tr("kvt.tickets.demo_attachment"), cx);588
return;589
}590
let Some((token, client)) = token_and_client(cx) else {591
return;592
};593
let id = attachment.id;594
let name: String = attachment595
.original_name596
.chars()597
.filter(|c| c.is_alphanumeric() || "-_. ".contains(*c))598
.collect();599
let name = if name.trim().is_empty() {600
"bijlage".to_owned()601
} else {602
name603
};604
let downloading = runtime::spawn(async move {605
let bytes = client.asclepius_attachment(&token, id).await?;606
let directory = std::env::temp_dir().join("rusty-teams-asclepius");607
std::fs::create_dir_all(&directory).map_err(|_| ClientError::Unavailable)?;608
let path = directory.join(format!("{id}-{name}"));609
std::fs::write(&path, bytes).map_err(|_| ClientError::Unavailable)?;610
Ok::<_, ClientError>(path)611
});612
cx.spawn(async move |cx| {613
let result = downloading.await.unwrap_or(Err(ClientError::Unavailable));614
cx.update(|cx| match result {615
Ok(path) => cx.open_with_system(&path),616
Err(error) => {617
if error == ClientError::Unauthorized {618
forget_token(cx);619
}620
notice(ticket_error(&error), cx);621
}622
});623
})624
.detach();625
}626
627
impl Render for TicketThread {628
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {629
let detail = match &self.detail {630
Detail::Loading => {631
return v_flex()632
.size_full()633
.child(muted(tr("kvt.card.loading")).px(px(PAGE_PADDING)))634
.into_any_element();635
}636
Detail::Failed(error) => {637
return v_flex()638
.size_full()639
.child(muted(ticket_error(error)).px(px(PAGE_PADDING)))640
.into_any_element();641
}642
Detail::Loaded(detail) => detail.clone(),643
};644
let mut known = detail.participant_emails.clone();645
known.push(detail.ticket.assigned_email.clone());646
known.push(detail.ticket.user_email.clone());647
known.extend(648
detail649
.messages650
.iter()651
.map(|message| message.sender_email.clone()),652
);653
let messages: Vec<AnyElement> = detail654
.messages655
.iter()656
.enumerate()657
.map(|(index, message)| self.message(index, message, &known, cx))658
.collect();659
v_flex()660
.debug_selector(|| "kvt-ticket-thread".into())661
.size_full()662
.min_h_0()663
.child(self.header(&detail))664
.child(665
div()666
.id("kvt-ticket-messages")667
.flex_1()668
.min_h_0()669
.overflow_y_scroll()670
.track_scroll(&self.scroll)671
.child(672
v_flex()673
.w_full()674
.px(px(PAGE_PADDING))675
.py(px(12.))676
.gap(px(10.))677
.children(messages),678
),679
)680
.child(self.composer(&detail, cx))681
.into_any_element()682
}683
}684
685
// --- tegelpagina -------------------------------------------------------------686
687
pub struct TicketsPage {688
filter: TicketFilter,689
list: List,690
/// Open tickets, ook als het filter op Afgehandeld staat (badge in de rail).691
open: Vec<Ticket>,692
selected: Option<Entity<TicketThread>>,693
seen: SeenTickets,694
generation: u64,695
since: Option<String>,696
polling: bool,697
}698
699
/// De pagina (eenmalig aangemaakt; ook voor de badge als de tegel dicht is).700
fn page(cx: &mut App) -> Option<Entity<TicketsPage>> {701
if !super::installed(cx) {702
return None;703
}704
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {705
return Some(page);706
}707
let page = cx.new(TicketsPage::new);708
cx.global_mut::<super::Kvt>().tickets = Some(page.clone());709
Some(page)710
}711
712
/// De tegel als element van het hoofdpaneel.713
pub fn tickets_view(cx: &mut App) -> AnyElement {714
match page(cx) {715
Some(page) => div()716
.flex_1()717
.min_w_0()718
.h_full()719
.child(page)720
.into_any_element(),721
None => div().into_any_element(),722
}723
}724
725
/// De tegel is geopend: vers ophalen.726
pub fn tickets_opened(cx: &mut App) {727
if let Some(page) = page(cx) {728
page.update(cx, |page, cx| page.reload(cx));729
}730
}731
732
/// Aantal ongelezen open tickets, voor de badge op de tegel.733
pub fn tickets_unread(cx: &mut App) -> usize {734
if !matches!(link(cx), Link::Linked(_)) {735
return 0;736
}737
page(cx).map_or(0, |page| {738
let page = page.read(cx);739
page.seen.unread_count(&page.open)740
})741
}742
743
fn refresh_list(cx: &mut App) {744
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {745
page.update(cx, |page, cx| page.reload(cx));746
}747
}748
749
/// Net aangemaakt: lijst opnieuw en het nieuwe ticket openen (als de tegel bestaat).750
pub(super) fn created(id: u64, cx: &mut App) {751
let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() else {752
return;753
};754
let Some(window) = cx.active_window() else {755
page.update(cx, |page, cx| page.reload(cx));756
return;757
};758
window759
.update(cx, |_, window, cx| {760
page.update(cx, |page, cx| {761
page.filter = TicketFilter::Open;762
page.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));763
page.reload(cx);764
})765
})766
.ok();767
}768
769
/// Een ticket is bekeken (tegel of ticketvenster): niet meer ongelezen.770
pub(super) fn ticket_seen(ticket: &Ticket, cx: &mut App) {771
if let Some(page) = super::read(cx, |kvt| kvt.tickets.clone()).flatten() {772
page.update(cx, |page, cx| {773
if page.seen.mark(ticket) {774
save_seen(&page.seen, cx);775
cx.notify();776
}777
});778
}779
}780
781
impl TicketsPage {782
fn new(cx: &mut Context<Self>) -> Self {783
let mut page = TicketsPage {784
filter: TicketFilter::Open,785
list: List::Loading,786
open: Vec::new(),787
selected: None,788
seen: load_seen(cx),789
generation: 0,790
since: None,791
polling: false,792
};793
page.reload(cx);794
page.start_polling(cx);795
page796
}797
798
fn reload(&mut self, cx: &mut Context<Self>) {799
self.generation += 1;800
let generation = self.generation;801
let filter = self.filter;802
if is_demo(cx) {803
let all = demo_tickets();804
self.open = all.iter().filter(|t| !t.is_closed()).cloned().collect();805
if self.seen.initialize(&self.open) {806
// Demo: één ticket ongelezen, om de stip te tonen.807
self.seen.seen.insert(DEMO_UNREAD, String::new());808
}809
self.list = List::Loaded(810
all.into_iter()811
.filter(|t| t.is_closed() == (filter == TicketFilter::Closed))812
.collect(),813
);814
cx.notify();815
return;816
}817
let Some((token, client)) = token_and_client(cx) else {818
self.list = List::NotLinked;819
cx.notify();820
return;821
};822
if !matches!(self.list, List::Loaded(_)) {823
self.list = List::Loading;824
}825
let loading = runtime::spawn(async move {826
let open = client.asclepius_tickets(&token, TicketFilter::Open).await?;827
let shown = match filter {828
TicketFilter::Open => open.clone(),829
TicketFilter::Closed => {830
client831
.asclepius_tickets(&token, TicketFilter::Closed)832
.await?833
}834
};835
Ok::<_, ClientError>((open, shown))836
});837
cx.spawn(async move |this, cx| {838
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));839
cx.update(|cx| {840
if matches!(result, Err(ClientError::Unauthorized)) {841
forget_token(cx);842
}843
this.update(cx, |this, cx| {844
if this.generation != generation {845
return;846
}847
match result {848
Ok((open, shown)) => {849
if this.seen.initialize(&open) {850
save_seen(&this.seen, cx);851
}852
this.since = Some(chrono::Utc::now().to_rfc3339());853
this.open = open;854
this.list = List::Loaded(shown);855
}856
Err(ClientError::Unauthorized) => this.list = List::NotLinked,857
Err(error) => this.list = List::Failed(error),858
}859
cx.notify();860
cx.refresh_windows();861
})862
.ok();863
});864
})865
.detach();866
}867
868
/// Elke minuut `ticket_updates`; bij wijzigingen de lijst en het open ticket opnieuw.869
fn start_polling(&mut self, cx: &mut Context<Self>) {870
if self.polling || is_demo(cx) {871
return;872
}873
self.polling = true;874
cx.spawn(async move |this, cx| {875
loop {876
cx.background_executor().timer(POLL_INTERVAL).await;877
let Ok(Some((since, token))) = this.update(cx, |this, cx| {878
let since = this.since.clone()?;879
let (token, client) = token_and_client(cx)?;880
Some((since, (token, client)))881
}) else {882
if this.upgrade().is_none() {883
return;884
}885
continue;886
};887
let (token, client): (String, CardsClient) = token;888
let polling =889
runtime::spawn(async move { client.asclepius_updates(&token, &since).await });890
let result = polling.await.unwrap_or(Err(ClientError::Unavailable));891
let alive = this.update(cx, |this, cx| {892
if let Ok((changed, server_time)) = result {893
if !server_time.is_empty() {894
this.since = Some(server_time);895
}896
if !changed.is_empty() {897
let open_id = this.selected.as_ref().map(|thread| thread.read(cx).id());898
if let Some(thread) = this.selected.clone()899
&& changed.iter().any(|t| Some(t.id) == open_id)900
{901
thread.update(cx, |thread, cx| thread.reload(cx));902
}903
this.reload(cx);904
}905
}906
});907
if alive.is_err() {908
return;909
}910
}911
})912
.detach();913
}914
915
fn set_filter(&mut self, filter: TicketFilter, cx: &mut Context<Self>) {916
if self.filter == filter {917
return;918
}919
self.filter = filter;920
self.list = List::Loading;921
self.reload(cx);922
}923
924
fn select(&mut self, ticket: &Ticket, window: &mut Window, cx: &mut Context<Self>) {925
if self926
.selected927
.as_ref()928
.is_some_and(|thread| thread.read(cx).id() == ticket.id)929
{930
return;931
}932
let id = ticket.id;933
self.selected = Some(cx.new(|cx| TicketThread::new(id, window, cx)));934
if self.seen.mark(ticket) {935
save_seen(&self.seen, cx);936
}937
cx.notify();938
cx.refresh_windows();939
}940
941
fn header(&self, cx: &mut Context<Self>) -> Div {942
h_flex()943
.h(px(HEADER_HEIGHT))944
.flex_none()945
.px(px(PAGE_PADDING))946
.gap(px(8.))947
.items_center()948
.child(949
div()950
.flex_1()951
.min_w_0()952
.truncate()953
.text_size(px(16.))954
.font_weight(FontWeight::BOLD)955
.text_color(theme::text())956
.child(tr("kvt.tickets.title")),957
)958
.children(super::ticket_form::new_ticket_button(cx))959
.child(960
secondary_button("kvt-tickets-refresh", "refresh", tr("kvt.card.refresh"))961
.on_click(cx.listener(|this, _, _, cx| this.reload(cx))),962
)963
}964
965
fn list(&self, cx: &mut Context<Self>) -> AnyElement {966
let filters = h_flex()967
.w_full()968
.flex_none()969
.px(px(12.))970
.pb(px(8.))971
.gap(px(6.))972
.child(973
chip(974
"kvt-tickets-filter-open".into(),975
tr("kvt.tickets.filter_open"),976
self.filter == TicketFilter::Open,977
)978
.on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Open, cx))),979
)980
.child(981
chip(982
"kvt-tickets-filter-closed".into(),983
tr("kvt.tickets.filter_closed"),984
self.filter == TicketFilter::Closed,985
)986
.on_click(cx.listener(|this, _, _, cx| this.set_filter(TicketFilter::Closed, cx))),987
);988
let selected = self.selected.as_ref().map(|thread| thread.read(cx).id());989
let rows: AnyElement = match &self.list {990
List::Loading | List::NotLinked => {991
muted(tr("kvt.card.loading")).px(px(12.)).into_any_element()992
}993
List::Failed(error) => muted(ticket_error(error)).px(px(12.)).into_any_element(),994
List::Loaded(tickets) if tickets.is_empty() => muted(tr(match self.filter {995
TicketFilter::Open => "kvt.tickets.empty_open",996
TicketFilter::Closed => "kvt.tickets.empty_closed",997
}))998
.px(px(12.))999
.into_any_element(),1000
List::Loaded(tickets) => v_flex()1001
.w_full()1002
.px(px(8.))1003
.gap(px(2.))1004
.children(tickets.iter().enumerate().map(|(index, ticket)| {1005
let unread = self.seen.is_unread(ticket);1006
let active = selected == Some(ticket.id);1007
let row_ticket = ticket.clone();1008
v_flex()1009
.id(ElementId::Name(format!("kvt-tickets-row-{index}").into()))1010
.debug_selector(move || format!("kvt-tickets/row/{index}"))1011
.w_full()1012
.px(px(10.))1013
.py(px(8.))1014
.gap(px(2.))1015
.rounded(px(6.))1016
.cursor_pointer()1017
.map(|row| {1018
if active {1019
row.bg(theme::selection())1020
} else {1021
row.hover(|row| row.bg(theme::row_hover()))1022
}1023
})1024
.on_click(cx.listener(move |this, _, window, cx| {1025
this.select(&row_ticket, window, cx)1026
}))1027
.child(1028
h_flex()1029
.w_full()1030
.gap(px(6.))1031
.items_center()1032
.child(1033
div()1034
.flex_1()1035
.min_w_0()1036
.truncate()1037
.text_size(px(13.))1038
.text_color(theme::text_strong())1039
.when(unread, |title| title.font_weight(FontWeight::BOLD))1040
.child(ticket.title.clone()),1041
)1042
.when(unread, |row| {1043
row.child(1044
div()1045
.size(px(8.))1046
.flex_none()1047
.rounded_full()1048
.bg(theme::accent()),1049
)1050
}),1051
)1052
.child(1053
div()1054
.truncate()1055
.text_size(px(12.))1056
.text_color(theme::text_muted())1057
.child(format!(1058
"#{} · {} · {}",1059
ticket.id,1060
status_label(&ticket.status),1061
when(&ticket.updated_at)1062
)),1063
)1064
}))1065
.into_any_element(),1066
};1067
v_flex()1068
.id("kvt-tickets-list")1069
.w(px(LIST_WIDTH))1070
.h_full()1071
.flex_none()1072
.border_r_1()1073
.border_color(theme::border())1074
.child(filters)1075
.child(1076
div()1077
.id("kvt-tickets-rows")1078
.flex_1()1079
.min_h_0()1080
.overflow_y_scrollbar()1081
.child(rows),1082
)1083
.into_any_element()1084
}1085
}1086
1087
impl Render for TicketsPage {1088
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {1089
let linked = matches!(link(cx), Link::Linked(_));1090
if !linked && !is_demo(cx) {1091
self.list = List::NotLinked;1092
self.selected = None;1093
self.open.clear();1094
} else if matches!(self.list, List::NotLinked) {1095
self.reload(cx);1096
}1097
let body = if !linked {1098
v_flex()1099
.p(px(PAGE_PADDING))1100
.max_w(px(560.))1101
.child(not_linked())1102
.into_any_element()1103
} else {1104
h_flex()1105
.flex_1()1106
.min_h_0()1107
.w_full()1108
.child(self.list(cx))1109
.child(1110
div()1111
.flex_1()1112
.min_w_0()1113
.h_full()1114
.child(match &self.selected {1115
Some(thread) => thread.clone().into_any_element(),1116
None => muted(tr("kvt.tickets.pick"))1117
.px(px(PAGE_PADDING))1118
.into_any_element(),1119
}),1120
)1121
.into_any_element()1122
};1123
v_flex()1124
.debug_selector(|| KVT_TICKETS_TAG.into())1125
.relative()1126
.size_full()1127
.rounded(px(RADIUS))1128
.bg(theme::surface())1129
.overflow_hidden()1130
.child(self.header(cx))1131
.child(body)1132
}1133
}1134
1135
// --- ticketvenster (links naar een ticket) ----------------------------------------1136
1137
const WINDOW_WIDTH: f32 = 720.;1138
const WINDOW_MARGIN: f32 = 32.;1139
const WINDOW_BACKDROP: f32 = 0.55;1140
pub const KVT_TICKET_WINDOW_TAG: &str = "kvt-asclepius-window";1141
1142
/// Een link naar een Asclepius-ticket (`…/asclepius/index.php?open=…`): heb je toegang, dan1143
/// opent het ticket in een venster in de app; anders gewoon in de browser. `false` als het1144
/// geen ticketlink is of je niet gekoppeld bent (dan opent de shell de link zelf).1145
pub fn open_ticket_link(url: &str, cx: &mut App) -> bool {1146
if !installed(cx) || !matches!(link(cx), Link::Linked(_)) {1147
return false;1148
}1149
let Some(id) = ticket_id_from_url(&base_url(), url) else {1150
return false;1151
};1152
let url = url.to_owned();1153
if is_demo(cx) {1154
match demo_detail(id) {1155
Some(detail) => cx.defer(move |cx| show_window(detail, cx)),1156
None => cx.open_url(&url),1157
}1158
return true;1159
}1160
let Some((token, client)) = token_and_client(cx) else {1161
return false;1162
};1163
let loading = runtime::spawn(async move { client.asclepius_ticket(&token, id).await });1164
cx.spawn(async move |cx| {1165
let result = loading.await.unwrap_or(Err(ClientError::Unavailable));1166
cx.update(|cx| match result {1167
Ok(detail) => show_window(detail, cx),1168
Err(error) => {1169
if error == ClientError::Unauthorized {1170
forget_token(cx);1171
}1172
// Geen toegang of Asclepius niet bereikbaar: een gewone link.1173
cx.open_url(&url);1174
}1175
});1176
})1177
.detach();1178
true1179
}1180
1181
fn show_window(detail: TicketDetail, cx: &mut App) {1182
let Some(window) = cx1183
.active_window()1184
.or_else(|| cx.windows().into_iter().next())1185
else {1186
return;1187
};1188
let ticket = detail.ticket.clone();1189
window1190
.update(cx, |_, window, cx| {1191
let thread =1192
cx.new(|cx| TicketThread::with_detail(ticket.id, Some(detail), window, cx));1193
update(cx, |kvt| kvt.ticket_window = Some(thread));1194
cx.refresh_windows();1195
})1196
.ok();1197
ticket_seen(&ticket, cx);1198
}1199
1200
fn close_window(cx: &mut App) {1201
update(cx, |kvt| kvt.ticket_window = None);1202
cx.refresh_windows();1203
}1204
1205
/// Laag voor `kvt::overlay`.1206
pub(super) fn window_overlay(thread: Entity<TicketThread>) -> AnyElement {1207
div()1208
.id("kvt-ticket-window-layer")1209
.absolute()1210
.top_0()1211
.left_0()1212
.size_full()1213
.flex()1214
.items_center()1215
.justify_center()1216
.child(1217
div()1218
.id("kvt-ticket-window-backdrop")1219
.absolute()1220
.top_0()1221
.left_0()1222
.size_full()1223
.bg(black().opacity(WINDOW_BACKDROP))1224
.occlude()1225
.on_click(|_, _, cx| close_window(cx)),1226
)1227
.child(1228
div()1229
.id("kvt-ticket-window")1230
.debug_selector(|| KVT_TICKET_WINDOW_TAG.into())1231
.relative()1232
.w(px(WINDOW_WIDTH))1233
.max_w(relative(1.))1234
.h(relative(0.85))1235
.m(px(WINDOW_MARGIN))1236
.rounded(px(RADIUS))1237
.dialog_surface()1238
.overflow_hidden()1239
.occlude()1240
.child(thread)1241
.child(1242
div()1243
.id("kvt-ticket-window-close")1244
.absolute()1245
.top(px(10.))1246
.right(px(10.))1247
.size(px(28.))1248
.flex()1249
.items_center()1250
.justify_center()1251
.rounded_full()1252
.cursor_pointer()1253
.hover(|button| button.bg(theme::popup_hover()))1254
.on_click(|_, _, cx| close_window(cx))1255
.child(symbol("close", 16., theme::text_muted())),1256
),1257
)1258
.into_any_element()1259
}1260
1261
// --- demo ------------------------------------------------------------------------1262
1263
const DEMO_UNREAD: u64 = 4102;1264
1265
thread_local! {1266
static DEMO_REPLIES: std::cell::RefCell<HashMap<u64, Vec<TicketMessage>>> =1267
std::cell::RefCell::new(HashMap::new());1268
}1269
1270
fn demo_ticket(id: u64, title: &str, status: &str, category: &str, updated: &str) -> Ticket {1271
Ticket {1272
id,1273
title: title.to_owned(),1274
category: category.to_owned(),1275
user_email: super::demo::token().email,1276
assigned_email: "ict.medewerker@example.com".to_owned(),1277
status: status.to_owned(),1278
created_at: "2026-01-12T09:15:00+01:00".to_owned(),1279
updated_at: updated.to_owned(),1280
message_count: 3,1281
..Ticket::default()1282
}1283
}1284
1285
pub(super) fn demo_tickets() -> Vec<Ticket> {1286
vec![1287
Ticket {1288
subcategory: "Laptop".to_owned(),1289
..demo_ticket(1290
DEMO_UNREAD,1291
"Laptop start niet meer op",1292
"in behandeling",1293
"Hardware",1294
"2026-01-15T13:39:00+01:00",1295
)1296
},1297
demo_ticket(1298
4098,1299
"Toegang tot gedeelde map Projecten",1300
"afwachtende op gebruiker",1301
"Rechten en toegang",1302
"2026-01-14T16:02:00+01:00",1303
),1304
demo_ticket(1305
4090,1306
"Nieuwe headset",1307
"ingediend",1308
"Hardware bestellen",1309
"2026-01-13T10:20:00+01:00",1310
),1311
demo_ticket(1312
4012,1313
"Printer op kantoor geeft een fout",1314
"afgehandeld",1315
"Hardware",1316
"2026-01-08T11:00:00+01:00",1317
),1318
]1319
}1320
1321
fn demo_message(1322
id: u64,1323
email: &str,1324
name: &str,1325
role: &str,1326
text: &str,1327
at: &str,1328
) -> TicketMessage {1329
TicketMessage {1330
id,1331
sender_email: email.to_owned(),1332
sender_role: role.to_owned(),1333
sender_display_name: name.to_owned(),1334
message_text: text.to_owned(),1335
created_at: at.to_owned(),1336
..TicketMessage::default()1337
}1338
}1339
1340
pub(super) fn demo_detail(id: u64) -> Option<TicketDetail> {1341
let ticket = demo_tickets().into_iter().find(|ticket| ticket.id == id)?;1342
let me = super::demo::token();1343
let ict = "ict.medewerker@example.com";1344
let mut messages = vec![1345
demo_message(1346
1,1347
&me.email,1348
&me.name,1349
"user",1350
"Mijn laptop gaat niet meer aan sinds vanochtend. Het lampje knippert oranje.",1351
"2026-01-15T09:15:00+01:00",1352
),1353
demo_message(1354
2,1355
ict,1356
"Sam Ict",1357
"admin",1358
"Dank je. Kun je de lader een minuut loskoppelen en het opnieuw proberen? @dana.demo:examplecom",1359
"2026-01-15T10:02:00+01:00",1360
),1361
TicketMessage {1362
is_ghost: true,1363
..demo_message(1364
3,1365
ict,1366
"Sam Ict",1367
"admin",1368
"Intern: garantie loopt nog tot maart, eventueel omruilen via de leverancier.",1369
"2026-01-15T10:05:00+01:00",1370
)1371
},1372
TicketMessage {1373
attachments: vec![TicketAttachment {1374
id: 77,1375
original_name: "foto-lampje.jpg".to_owned(),1376
mime_type: "image/jpeg".to_owned(),1377
file_size: 120_000,1378
}],1379
..demo_message(1380
4,1381
&me.email,1382
&me.name,1383
"user",1384
"Gedaan, hij knippert nog steeds. Foto erbij.",1385
"2026-01-15T13:39:00+01:00",1386
)1387
},1388
];1389
if id != DEMO_UNREAD {1390
messages.truncate(1);1391
messages[0].message_text = format!("{}.", ticket.title);1392
}1393
DEMO_REPLIES.with(|replies| {1394
messages.extend(replies.borrow().get(&id).cloned().unwrap_or_default());1395
});1396
Some(TicketDetail {1397
description: messages[0].message_text.clone(),1398
participant_emails: vec![me.email.clone(), "jonas.ortega@example.com".to_owned()],1399
messages,1400
ticket,1401
})1402
}1403
1404
fn demo_reply(id: u64, text: &str, email: &str) {1405
let me = super::demo::token();1406
DEMO_REPLIES.with(|replies| {1407
let mut replies = replies.borrow_mut();1408
let list = replies.entry(id).or_default();1409
list.push(demo_message(1410
100 + list.len() as u64,1411
if email.is_empty() { &me.email } else { email },1412
&me.name,1413
"user",1414
text,1415
&chrono::Local::now().to_rfc3339(),1416
));1417
});1418
}1419
1420
#[cfg(test)]1421
mod tests {1422
use super::{DEMO_UNREAD, demo_detail, demo_tickets, mention_display, when};1423
use kvt_sleutels::tickets::Ticket;1424
1425
#[test]1426
fn dates_are_dutch_and_local() {1427
let shown = when("2026-01-15T13:39:00+01:00");1428
assert!(shown.starts_with("15 jan 2026") || shown.starts_with("16 jan 2026"));1429
assert_eq!(when("geen datum"), "geen datum");1430
}1431
1432
#[test]1433
fn demo_has_a_ghost_and_a_closed_ticket() {1434
let detail = demo_detail(DEMO_UNREAD).unwrap();1435
assert!(detail.messages.iter().any(|message| message.is_ghost));1436
assert!(demo_tickets().iter().any(Ticket::is_closed));1437
}1438
1439
#[test]1440
fn mentions_render_as_first_names() {1441
let (shown, ranges) = mention_display(1442
"Graag @dana.demo:examplecom",1443
&["dana.demo@example.com".to_owned()],1444
);1445
assert_eq!(shown, "Graag @Dana");1446
assert_eq!(ranges, [6..11]);1447
}1448
}@@ -0,0 +1,224 @@
1
//! KVT-fork: minimaliseren, maximaliseren/herstellen en sluiten in de titelbalk.
2
//!
3
//! Alleen op Linux en Windows, en alleen als de instelling aan staat. Op macOS
4
//! blijven de verkeerslichten van het systeem. Sluiten volgt dezelfde route als
5
//! de systeemknop (inclusief sluiten naar de tray). Zie KVT-FORK.md.
6
7
use gpui_kit::assets::IconName;
8
use gpui_kit::component::button::{Button, ButtonVariants as _};
9
use gpui_kit::component::h_flex;
10
use gpui_kit::prelude::FluentBuilder as _;
11
use gpui_kit::*;
12
use store::Store;
13
14
use crate::i18n::tr;
15
use crate::notify::NotificationCenter;
16
17
/// Kleine titelbalk-iconen, strak gegroepeerd zodat de zoekbalk ruimte houdt.
18
const CONTROL_SIZE: f32 = 20.;
19
const CONTROL_GAP: f32 = 0.;
20
21
/// Of de eigen knoppen en client-side decorations gewenst zijn.
22
pub fn enabled(cx: &App) -> bool {
23
app_base::kvt_window::available()
24
&& cx
25
.try_global::<Active>()
26
.map(|active| active.enabled)
27
.unwrap_or(app_base::kvt_window::DEFAULT_ENABLED)
28
}
29
30
pub fn install(store: &Store, cx: &mut App) {
31
cx.set_global(Active {
32
enabled: app_base::kvt_window::load(store),
33
});
34
}
35
36
/// Zet de instelling, vraagt de passende decorations aan en ververst de vensters.
37
pub fn set_enabled(enabled: bool, store: &Store, window: &Window, cx: &mut App) {
38
app_base::kvt_window::save(store, enabled);
39
cx.set_global(Active { enabled });
40
apply_decorations(window, enabled);
41
cx.refresh_windows();
42
}
43
44
/// Decorations voor het hoofdvenster bij het openen.
45
pub fn window_decorations(enabled: bool) -> WindowDecorations {
46
if enabled && app_base::kvt_window::available() {
47
WindowDecorations::Client
48
} else {
49
WindowDecorations::Server
50
}
51
}
52
53
pub fn apply_decorations(window: &Window, enabled: bool) {
54
if app_base::kvt_window::available() {
55
window.request_decorations(window_decorations(enabled));
56
}
57
}
58
59
pub fn title_bar_system_window_controls(cx: &App) -> bool {
60
!enabled(cx)
61
}
62
63
/// Knoppen rechts in de titelbalk, na «…» en de avatar, als één groep zodat
64
/// de zoekbalk bij een smal venster ruimte houdt. Leeg als ze niet getoond
65
/// moeten worden.
66
pub fn title_buttons(
67
notifications: &Entity<NotificationCenter>,
68
window: &Window,
69
cx: &App,
70
) -> Vec<AnyElement> {
71
if !enabled(cx) {
72
return Vec::new();
73
}
74
let supported = window.window_controls();
75
let maximized = window.is_maximized();
76
let mut buttons = Vec::new();
77
if supported.minimize {
78
buttons.push(control_button(
79
"title-window-minimize",
80
"shell/title-bar/minimize",
81
IconName::ChevronDown,
82
tr("kvt.window.minimize"),
83
Action::Minimize,
84
notifications.clone(),
85
));
86
}
87
if supported.maximize {
88
if maximized {
89
buttons.push(control_button(
90
"title-window-restore",
91
"shell/title-bar/restore",
92
IconName::WindowRestore,
93
tr("kvt.window.restore"),
94
Action::Restore,
95
notifications.clone(),
96
));
97
} else {
98
buttons.push(control_button(
99
"title-window-maximize",
100
"shell/title-bar/maximize",
101
IconName::ChevronUp,
102
tr("kvt.window.maximize"),
103
Action::Maximize,
104
notifications.clone(),
105
));
106
}
107
}
108
buttons.push(control_button(
109
"title-window-close",
110
"shell/title-bar/close",
111
IconName::Close,
112
tr("kvt.window.close"),
113
Action::Close,
114
notifications.clone(),
115
));
116
if buttons.is_empty() {
117
return Vec::new();
118
}
119
vec![
120
h_flex()
121
.debug_selector(|| "shell/title-bar/window-controls".into())
122
.flex_none()
123
.h_full()
124
.items_center()
125
.gap(px(CONTROL_GAP))
126
.children(buttons)
127
.into_any_element(),
128
]
129
}
130
131
#[derive(Clone, Copy)]
132
enum Action {
133
Minimize,
134
Maximize,
135
Restore,
136
Close,
137
}
138
139
impl Action {
140
fn window_control_area(self) -> WindowControlArea {
141
match self {
142
Self::Minimize => WindowControlArea::Min,
143
Self::Maximize | Self::Restore => WindowControlArea::Max,
144
Self::Close => WindowControlArea::Close,
145
}
146
}
147
}
148
149
fn control_button(
150
id: &'static str,
151
selector: &'static str,
152
icon: IconName,
153
tooltip: String,
154
action: Action,
155
notifications: Entity<NotificationCenter>,
156
) -> AnyElement {
157
let is_windows = cfg!(target_os = "windows");
158
let is_linux = cfg!(target_os = "linux");
159
Button::new(id)
160
.ghost()
161
.compact()
162
.p_0()
163
.size(px(CONTROL_SIZE))
164
.icon(icon)
165
.tooltip(tooltip)
166
.debug_selector(|| selector.into())
167
.when(is_windows, |button| {
168
button.window_control_area(action.window_control_area())
169
})
170
.when(is_linux || cfg!(not(any(target_os = "windows", target_os = "macos"))), |button| {
171
button
172
.on_mouse_down(MouseButton::Left, |_, window, cx| {
173
window.prevent_default();
174
cx.stop_propagation();
175
})
176
.on_click(move |_, window, cx| {
177
cx.stop_propagation();
178
match action {
179
Action::Minimize => window.minimize_window(),
180
Action::Maximize | Action::Restore => window.zoom_window(),
181
Action::Close => close_main_window(¬ifications, window, cx),
182
}
183
})
184
})
185
.into_any_element()
186
}
187
188
/// Zelfde pad als de systeem-sluitknop: `on_window_should_close` in de shell
189
/// (tray verbergen of echt sluiten).
190
fn close_main_window(
191
notifications: &Entity<NotificationCenter>,
192
window: &mut Window,
193
cx: &mut App,
194
) {
195
let keep_open = notifications.update(cx, |notifications, cx| notifications.intercept_close(cx));
196
if !keep_open {
197
window.remove_window();
198
}
199
}
200
201
struct Active {
202
enabled: bool,
203
}
204
205
impl Global for Active {}
206
207
#[cfg(test)]
208
mod tests {
209
use super::window_decorations;
210
use gpui_kit::WindowDecorations;
211
212
#[test]
213
fn client_decorations_follow_the_setting() {
214
assert_eq!(
215
window_decorations(true),
216
if cfg!(target_os = "macos") {
217
WindowDecorations::Server
218
} else {
219
WindowDecorations::Client
220
}
221
);
222
assert_eq!(window_decorations(false), WindowDecorations::Server);
223
}
224
}
@@ -0,0 +1,224 @@1
//! KVT-fork: minimaliseren, maximaliseren/herstellen en sluiten in de titelbalk.2
//!3
//! Alleen op Linux en Windows, en alleen als de instelling aan staat. Op macOS4
//! blijven de verkeerslichten van het systeem. Sluiten volgt dezelfde route als5
//! de systeemknop (inclusief sluiten naar de tray). Zie KVT-FORK.md.6
7
use gpui_kit::assets::IconName;8
use gpui_kit::component::button::{Button, ButtonVariants as _};9
use gpui_kit::component::h_flex;10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;12
use store::Store;13
14
use crate::i18n::tr;15
use crate::notify::NotificationCenter;16
17
/// Kleine titelbalk-iconen, strak gegroepeerd zodat de zoekbalk ruimte houdt.18
const CONTROL_SIZE: f32 = 20.;19
const CONTROL_GAP: f32 = 0.;20
21
/// Of de eigen knoppen en client-side decorations gewenst zijn.22
pub fn enabled(cx: &App) -> bool {23
app_base::kvt_window::available()24
&& cx25
.try_global::<Active>()26
.map(|active| active.enabled)27
.unwrap_or(app_base::kvt_window::DEFAULT_ENABLED)28
}29
30
pub fn install(store: &Store, cx: &mut App) {31
cx.set_global(Active {32
enabled: app_base::kvt_window::load(store),33
});34
}35
36
/// Zet de instelling, vraagt de passende decorations aan en ververst de vensters.37
pub fn set_enabled(enabled: bool, store: &Store, window: &Window, cx: &mut App) {38
app_base::kvt_window::save(store, enabled);39
cx.set_global(Active { enabled });40
apply_decorations(window, enabled);41
cx.refresh_windows();42
}43
44
/// Decorations voor het hoofdvenster bij het openen.45
pub fn window_decorations(enabled: bool) -> WindowDecorations {46
if enabled && app_base::kvt_window::available() {47
WindowDecorations::Client48
} else {49
WindowDecorations::Server50
}51
}52
53
pub fn apply_decorations(window: &Window, enabled: bool) {54
if app_base::kvt_window::available() {55
window.request_decorations(window_decorations(enabled));56
}57
}58
59
pub fn title_bar_system_window_controls(cx: &App) -> bool {60
!enabled(cx)61
}62
63
/// Knoppen rechts in de titelbalk, na «…» en de avatar, als één groep zodat64
/// de zoekbalk bij een smal venster ruimte houdt. Leeg als ze niet getoond65
/// moeten worden.66
pub fn title_buttons(67
notifications: &Entity<NotificationCenter>,68
window: &Window,69
cx: &App,70
) -> Vec<AnyElement> {71
if !enabled(cx) {72
return Vec::new();73
}74
let supported = window.window_controls();75
let maximized = window.is_maximized();76
let mut buttons = Vec::new();77
if supported.minimize {78
buttons.push(control_button(79
"title-window-minimize",80
"shell/title-bar/minimize",81
IconName::ChevronDown,82
tr("kvt.window.minimize"),83
Action::Minimize,84
notifications.clone(),85
));86
}87
if supported.maximize {88
if maximized {89
buttons.push(control_button(90
"title-window-restore",91
"shell/title-bar/restore",92
IconName::WindowRestore,93
tr("kvt.window.restore"),94
Action::Restore,95
notifications.clone(),96
));97
} else {98
buttons.push(control_button(99
"title-window-maximize",100
"shell/title-bar/maximize",101
IconName::ChevronUp,102
tr("kvt.window.maximize"),103
Action::Maximize,104
notifications.clone(),105
));106
}107
}108
buttons.push(control_button(109
"title-window-close",110
"shell/title-bar/close",111
IconName::Close,112
tr("kvt.window.close"),113
Action::Close,114
notifications.clone(),115
));116
if buttons.is_empty() {117
return Vec::new();118
}119
vec![120
h_flex()121
.debug_selector(|| "shell/title-bar/window-controls".into())122
.flex_none()123
.h_full()124
.items_center()125
.gap(px(CONTROL_GAP))126
.children(buttons)127
.into_any_element(),128
]129
}130
131
#[derive(Clone, Copy)]132
enum Action {133
Minimize,134
Maximize,135
Restore,136
Close,137
}138
139
impl Action {140
fn window_control_area(self) -> WindowControlArea {141
match self {142
Self::Minimize => WindowControlArea::Min,143
Self::Maximize | Self::Restore => WindowControlArea::Max,144
Self::Close => WindowControlArea::Close,145
}146
}147
}148
149
fn control_button(150
id: &'static str,151
selector: &'static str,152
icon: IconName,153
tooltip: String,154
action: Action,155
notifications: Entity<NotificationCenter>,156
) -> AnyElement {157
let is_windows = cfg!(target_os = "windows");158
let is_linux = cfg!(target_os = "linux");159
Button::new(id)160
.ghost()161
.compact()162
.p_0()163
.size(px(CONTROL_SIZE))164
.icon(icon)165
.tooltip(tooltip)166
.debug_selector(|| selector.into())167
.when(is_windows, |button| {168
button.window_control_area(action.window_control_area())169
})170
.when(is_linux || cfg!(not(any(target_os = "windows", target_os = "macos"))), |button| {171
button172
.on_mouse_down(MouseButton::Left, |_, window, cx| {173
window.prevent_default();174
cx.stop_propagation();175
})176
.on_click(move |_, window, cx| {177
cx.stop_propagation();178
match action {179
Action::Minimize => window.minimize_window(),180
Action::Maximize | Action::Restore => window.zoom_window(),181
Action::Close => close_main_window(¬ifications, window, cx),182
}183
})184
})185
.into_any_element()186
}187
188
/// Zelfde pad als de systeem-sluitknop: `on_window_should_close` in de shell189
/// (tray verbergen of echt sluiten).190
fn close_main_window(191
notifications: &Entity<NotificationCenter>,192
window: &mut Window,193
cx: &mut App,194
) {195
let keep_open = notifications.update(cx, |notifications, cx| notifications.intercept_close(cx));196
if !keep_open {197
window.remove_window();198
}199
}200
201
struct Active {202
enabled: bool,203
}204
205
impl Global for Active {}206
207
#[cfg(test)]208
mod tests {209
use super::window_decorations;210
use gpui_kit::WindowDecorations;211
212
#[test]213
fn client_decorations_follow_the_setting() {214
assert_eq!(215
window_decorations(true),216
if cfg!(target_os = "macos") {217
WindowDecorations::Server218
} else {219
WindowDecorations::Client220
}221
);222
assert_eq!(window_decorations(false), WindowDecorations::Server);223
}224
}@@ -3124,6 +3124,11 @@ const STATE_RING_COLORS: &[&str] = &[
3124
3124
"if state.failed",
3125
3125
];
3126
3126
const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[
3127
(
3128
"kvt/tickets.rs",
3129
"rgb(GHOST_BORDER)",
3130
"KVT-fork: ghost-berichten van Asclepius houden de roze rand van het web",
3131
),
3127
3132
(
3128
3133
"notify/ring_view.rs",
3129
3134
"theme::green()",
@@ -3124,6 +3124,11 @@ const STATE_RING_COLORS: &[&str] = &[3124
"if state.failed",3124
"if state.failed",3125
];3125
];3126
const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[3126
const OUTLINE_ALLOWLIST: &[(&str, &str, &str)] = &[3127
(3128
"kvt/tickets.rs",3129
"rgb(GHOST_BORDER)",3130
"KVT-fork: ghost-berichten van Asclepius houden de roze rand van het web",3131
),3127
(3132
(3128
"notify/ring_view.rs",3133
"notify/ring_view.rs",3129
"theme::green()",3134
"theme::green()",@@ -168,6 +168,9 @@ fn main_window_options(cx: &App) -> WindowOptions {
168
168
options.window_bounds = Some(WindowBounds::Windowed(bounds));
169
169
options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
170
170
options.app_id = Some(LINUX_APP_ID.to_owned());
171
options.window_decorations = Some(crate::kvt::window_controls::window_decorations(
172
crate::kvt::window_controls::enabled(cx),
173
));
171
174
if let Some(titlebar) = options.titlebar.as_mut() {
172
175
titlebar.title = Some(APP_NAME.into());
173
176
}
@@ -326,6 +329,7 @@ fn main() {
326
329
.detach();
327
330
theme::load_fonts(cx);
328
331
active_appearance::install(&store, cx);
332
crate::kvt::window_controls::install(&store, cx);
329
333
active_locale::install(&store, cx);
330
334
theme::apply(cx);
331
335
bind_keys(cx);
@@ -168,6 +168,9 @@ fn main_window_options(cx: &App) -> WindowOptions {168
options.window_bounds = Some(WindowBounds::Windowed(bounds));168
options.window_bounds = Some(WindowBounds::Windowed(bounds));169
options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));169
options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));170
options.app_id = Some(LINUX_APP_ID.to_owned());170
options.app_id = Some(LINUX_APP_ID.to_owned());171
options.window_decorations = Some(crate::kvt::window_controls::window_decorations(172
crate::kvt::window_controls::enabled(cx),173
));171
if let Some(titlebar) = options.titlebar.as_mut() {174
if let Some(titlebar) = options.titlebar.as_mut() {172
titlebar.title = Some(APP_NAME.into());175
titlebar.title = Some(APP_NAME.into());173
}176
}@@ -326,6 +329,7 @@ fn main() {326
.detach();329
.detach();327
theme::load_fonts(cx);330
theme::load_fonts(cx);328
active_appearance::install(&store, cx);331
active_appearance::install(&store, cx);332
crate::kvt::window_controls::install(&store, cx);329
active_locale::install(&store, cx);333
active_locale::install(&store, cx);330
theme::apply(cx);334
theme::apply(cx);331
bind_keys(cx);335
bind_keys(cx);@@ -2,7 +2,7 @@ use gpui_kit::component::{h_flex, v_flex};
2
2
use gpui_kit::prelude::FluentBuilder as _;
3
3
use gpui_kit::*;
4
4
5
use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};
5
use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled, toggle_row};
6
6
use crate::active_appearance;
7
7
use crate::active_locale;
8
8
use crate::app_state::AppState;
@@ -120,6 +120,21 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
120
120
theme_choices,
121
121
),
122
122
))
123
.when(app_base::kvt_window::available(), |view| {
124
let store = app.clone();
125
let on = crate::kvt::window_controls::enabled(cx);
126
view.child(toggle_row(
127
"settings-window-controls",
128
tr("kvt.window.title"),
129
tr("kvt.window.detail"),
130
theme::text_muted(),
131
on,
132
)
133
.on_click(move |_, window, cx| {
134
let store = store.read(cx).store.clone();
135
crate::kvt::window_controls::set_enabled(!on, &store, window, cx);
136
}))
137
})
123
138
.child(choice_group(
124
139
tr("settings.appearance.color_scheme"),
125
140
tr("settings.appearance.color_scheme_detail"),
@@ -2,7 +2,7 @@ use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::prelude::FluentBuilder as _;2
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;3
use gpui_kit::*;4
4
5
use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};5
use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled, toggle_row};6
use crate::active_appearance;6
use crate::active_appearance;7
use crate::active_locale;7
use crate::active_locale;8
use crate::app_state::AppState;8
use crate::app_state::AppState;@@ -120,6 +120,21 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {120
theme_choices,120
theme_choices,121
),121
),122
))122
))123
.when(app_base::kvt_window::available(), |view| {124
let store = app.clone();125
let on = crate::kvt::window_controls::enabled(cx);126
view.child(toggle_row(127
"settings-window-controls",128
tr("kvt.window.title"),129
tr("kvt.window.detail"),130
theme::text_muted(),131
on,132
)133
.on_click(move |_, window, cx| {134
let store = store.read(cx).store.clone();135
crate::kvt::window_controls::set_enabled(!on, &store, window, cx);136
}))137
})123
.child(choice_group(138
.child(choice_group(124
tr("settings.appearance.color_scheme"),139
tr("settings.appearance.color_scheme"),125
tr("settings.appearance.color_scheme_detail"),140
tr("settings.appearance.color_scheme_detail"),@@ -174,6 +174,19 @@ impl ItemKind {
174
174
fn is_object(&self) -> bool {
175
175
matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))
176
176
}
177
178
fn is_custom_emoji(&self) -> bool {
179
matches!(self, ItemKind::Remote(remote) if remote.is_custom_emoji())
180
}
181
}
182
183
impl AttachmentTray {
184
pub fn attachment_count(&self) -> usize {
185
self.items
186
.iter()
187
.filter(|item| !item.kind.is_custom_emoji())
188
.count()
189
}
177
190
}
178
191
179
192
impl TrayItem {
@@ -269,7 +282,7 @@ impl AttachmentTray {
269
282
/// `None` when the tray is full.
270
283
pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {
271
284
self.notice = None;
272
if self.items.len() >= MAX_ATTACHMENTS {
285
if !remote.is_custom_emoji() && self.attachment_count() >= MAX_ATTACHMENTS {
273
286
self.notice = Some(limit_notice(1));
274
287
return None;
275
288
}
@@ -303,7 +316,7 @@ impl AttachmentTray {
303
316
reference: FileReference,
304
317
) -> Option<u64> {
305
318
self.notice = None;
306
if self.items.len() >= MAX_ATTACHMENTS {
319
if self.attachment_count() >= MAX_ATTACHMENTS {
307
320
self.notice = Some(limit_notice(1));
308
321
return None;
309
322
}
@@ -327,7 +340,7 @@ impl AttachmentTray {
327
340
self.notice = None;
328
341
let accepted = names
329
342
.len()
330
.min(MAX_ATTACHMENTS.saturating_sub(self.items.len()));
343
.min(MAX_ATTACHMENTS.saturating_sub(self.attachment_count()));
331
344
let ids = names[..accepted]
332
345
.iter()
333
346
.map(|name| self.push(name.clone(), 0, ItemKind::Reading))
@@ -1476,6 +1489,26 @@ mod tests {
1476
1489
assert!(tray.notice().is_some());
1477
1490
}
1478
1491
1492
fn org_emoji() -> RemoteImage {
1493
RemoteImage::custom_emoji(&teams_core::OrgEmoji {
1494
id: "em-1".into(),
1495
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
1496
name: "ship-it".into(),
1497
keywords: vec![],
1498
source: None,
1499
})
1500
}
1501
1502
#[test]
1503
fn a_full_tray_still_accepts_a_custom_emoji() {
1504
let mut tray = AttachmentTray::default();
1505
for _ in 0..MAX_ATTACHMENTS {
1506
assert!(tray.add_remote(gif("Wave")).is_some());
1507
}
1508
assert!(tray.add_remote(org_emoji()).is_some());
1509
assert!(tray.add_remote(gif("Wave")).is_none());
1510
}
1511
1479
1512
#[test]
1480
1513
fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1481
1514
let mut tray = AttachmentTray::default();
@@ -174,6 +174,19 @@ impl ItemKind {174
fn is_object(&self) -> bool {174
fn is_object(&self) -> bool {175
matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))175
matches!(self, ItemKind::Image { .. } | ItemKind::Remote(_))176
}176
}177
178
fn is_custom_emoji(&self) -> bool {179
matches!(self, ItemKind::Remote(remote) if remote.is_custom_emoji())180
}181
}182
183
impl AttachmentTray {184
pub fn attachment_count(&self) -> usize {185
self.items186
.iter()187
.filter(|item| !item.kind.is_custom_emoji())188
.count()189
}177
}190
}178
191
179
impl TrayItem {192
impl TrayItem {@@ -269,7 +282,7 @@ impl AttachmentTray {269
/// `None` when the tray is full.282
/// `None` when the tray is full.270
pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {283
pub fn add_remote(&mut self, remote: RemoteImage) -> Option<u64> {271
self.notice = None;284
self.notice = None;272
if self.items.len() >= MAX_ATTACHMENTS {285
if !remote.is_custom_emoji() && self.attachment_count() >= MAX_ATTACHMENTS {273
self.notice = Some(limit_notice(1));286
self.notice = Some(limit_notice(1));274
return None;287
return None;275
}288
}@@ -303,7 +316,7 @@ impl AttachmentTray {303
reference: FileReference,316
reference: FileReference,304
) -> Option<u64> {317
) -> Option<u64> {305
self.notice = None;318
self.notice = None;306
if self.items.len() >= MAX_ATTACHMENTS {319
if self.attachment_count() >= MAX_ATTACHMENTS {307
self.notice = Some(limit_notice(1));320
self.notice = Some(limit_notice(1));308
return None;321
return None;309
}322
}@@ -327,7 +340,7 @@ impl AttachmentTray {327
self.notice = None;340
self.notice = None;328
let accepted = names341
let accepted = names329
.len()342
.len()330
.min(MAX_ATTACHMENTS.saturating_sub(self.items.len()));343
.min(MAX_ATTACHMENTS.saturating_sub(self.attachment_count()));331
let ids = names[..accepted]344
let ids = names[..accepted]332
.iter()345
.iter()333
.map(|name| self.push(name.clone(), 0, ItemKind::Reading))346
.map(|name| self.push(name.clone(), 0, ItemKind::Reading))@@ -1476,6 +1489,26 @@ mod tests {1476
assert!(tray.notice().is_some());1489
assert!(tray.notice().is_some());1477
}1490
}1478
1491
1492
fn org_emoji() -> RemoteImage {1493
RemoteImage::custom_emoji(&teams_core::OrgEmoji {1494
id: "em-1".into(),1495
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),1496
name: "ship-it".into(),1497
keywords: vec![],1498
source: None,1499
})1500
}1501
1502
#[test]1503
fn a_full_tray_still_accepts_a_custom_emoji() {1504
let mut tray = AttachmentTray::default();1505
for _ in 0..MAX_ATTACHMENTS {1506
assert!(tray.add_remote(gif("Wave")).is_some());1507
}1508
assert!(tray.add_remote(org_emoji()).is_some());1509
assert!(tray.add_remote(gif("Wave")).is_none());1510
}1511
1479
#[test]1512
#[test]1480
fn images_come_back_in_the_order_asked_for_and_only_when_known() {1513
fn images_come_back_in_the_order_asked_for_and_only_when_known() {1481
let mut tray = AttachmentTray::default();1514
let mut tray = AttachmentTray::default();@@ -2120,7 +2120,7 @@ impl Composer {
2120
2120
2121
2121
/// Images that no longer sit in the text give way to new attachments.
2122
2122
fn make_room(&mut self, needed: usize, cx: &App) {
2123
if self.tray.items().len() + needed > MAX_ATTACHMENTS {
2123
if self.tray.attachment_count() + needed > MAX_ATTACHMENTS {
2124
2124
let referenced: Vec<u64> = self
2125
2125
.input
2126
2126
.read(cx)
@@ -2187,7 +2187,9 @@ impl Composer {
2187
2187
window: &mut Window,
2188
2188
cx: &mut Context<Self>,
2189
2189
) {
2190
self.make_room(1, cx);
2190
if !image.is_custom_emoji() {
2191
self.make_room(1, cx);
2192
}
2191
2193
if let Some(id) = self.tray.add_remote(image) {
2192
2194
self.insert_image_token(id, window, cx);
2193
2195
}
@@ -2120,7 +2120,7 @@ impl Composer {2120
2120
2121
/// Images that no longer sit in the text give way to new attachments.2121
/// Images that no longer sit in the text give way to new attachments.2122
fn make_room(&mut self, needed: usize, cx: &App) {2122
fn make_room(&mut self, needed: usize, cx: &App) {2123
if self.tray.items().len() + needed > MAX_ATTACHMENTS {2123
if self.tray.attachment_count() + needed > MAX_ATTACHMENTS {2124
let referenced: Vec<u64> = self2124
let referenced: Vec<u64> = self2125
.input2125
.input2126
.read(cx)2126
.read(cx)@@ -2187,7 +2187,9 @@ impl Composer {2187
window: &mut Window,2187
window: &mut Window,2188
cx: &mut Context<Self>,2188
cx: &mut Context<Self>,2189
) {2189
) {2190
self.make_room(1, cx);2190
if !image.is_custom_emoji() {2191
self.make_room(1, cx);2192
}2191
if let Some(id) = self.tray.add_remote(image) {2193
if let Some(id) = self.tray.add_remote(image) {2192
self.insert_image_token(id, window, cx);2194
self.insert_image_token(id, window, cx);2193
}2195
}@@ -11,13 +11,17 @@ use gpui_kit::component::{
11
11
};
12
12
use gpui_kit::prelude::FluentBuilder as _;
13
13
use gpui_kit::*;
14
use teams_core::Gif;
14
use gpui_kit::component::tooltip::Tooltip;
15
use std::collections::HashMap;
16
use teams_core::{Gif, OrgEmoji};
15
17
16
18
use super::skin_tone_choices::{tone_badge, tone_choices};
17
19
use crate::app_state::AppState;
18
20
use crate::emoji;
19
21
use crate::emoticons;
20
22
use crate::gifs::{self, GifError};
23
use crate::i18n::{tr, tr_args};
24
use crate::org_emojis::{self, OrgEmojiError};
21
25
use crate::remote_image::{RemoteImage, image_source};
22
26
use crate::stickers::{self, Sticker};
23
27
use crate::theme;
@@ -39,6 +43,10 @@ const GIF_MIN_HEIGHT: f32 = 48.;
39
43
const GIF_MAX_HEIGHT: f32 = 200.;
40
44
const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];
41
45
const STICKER_COLUMNS: usize = 4;
46
const ORG_COLUMNS: usize = 8;
47
const ORG_GAP: f32 = 4.;
48
const ORG_CELL: f32 =
49
(CONTENT_WIDTH - ORG_GAP * (ORG_COLUMNS - 1) as f32) / ORG_COLUMNS as f32;
42
50
const STICKER_GAP: f32 = 6.;
43
51
const POPULAR_LABEL: &str = "Beliebt";
44
52
const TILE_RADIUS: f32 = 6.;
@@ -48,16 +56,18 @@ enum Tab {
48
56
Emoji,
49
57
Gif,
50
58
Sticker,
59
Org,
51
60
}
52
61
53
62
impl Tab {
54
const ALL: [Tab; 3] = [Tab::Emoji, Tab::Gif, Tab::Sticker];
63
const ALL: [Tab; 4] = [Tab::Emoji, Tab::Gif, Tab::Sticker, Tab::Org];
55
64
56
65
fn key(self) -> &'static str {
57
66
match self {
58
67
Tab::Emoji => "emoji",
59
68
Tab::Gif => "gif",
60
69
Tab::Sticker => "sticker",
70
Tab::Org => "org",
61
71
}
62
72
}
63
73
@@ -65,20 +75,38 @@ impl Tab {
65
75
Tab::ALL.into_iter().find(|tab| tab.key() == key)
66
76
}
67
77
68
fn label(self) -> &'static str {
69
match self {
70
Tab::Emoji => "Emoji",
71
Tab::Gif => "GIF",
72
Tab::Sticker => "Sticker",
73
}
78
fn label(self) -> String {
79
tr(match self {
80
Tab::Emoji => "fun_picker.tab.emoji",
81
Tab::Gif => "fun_picker.tab.gif",
82
Tab::Sticker => "fun_picker.tab.sticker",
83
Tab::Org => "fun_picker.tab.org",
84
})
74
85
}
75
86
76
fn placeholder(self) -> &'static str {
77
match self {
78
Tab::Emoji => "Emoji suchen",
79
Tab::Gif => "GIFs suchen",
80
Tab::Sticker => "Sticker suchen",
81
}
87
fn placeholder(self) -> String {
88
tr(match self {
89
Tab::Emoji => "fun_picker.search.emoji",
90
Tab::Gif => "fun_picker.search.gif",
91
Tab::Sticker => "fun_picker.search.sticker",
92
Tab::Org => "fun_picker.search.org",
93
})
94
}
95
}
96
97
enum OrgState {
98
Loading,
99
Ready(Vec<OrgEmoji>),
100
Failed,
101
}
102
103
fn org_empty_message(query: &str) -> String {
104
if query.is_empty() {
105
tr("fun_picker.org.empty")
106
} else {
107
let mut args = HashMap::new();
108
args.insert("query".into(), query.to_owned());
109
tr_args("fun_picker.org.empty_query", &args)
82
110
}
83
111
}
84
112
@@ -122,6 +150,10 @@ pub struct FunPicker {
122
150
chip: StickerChip,
123
151
sticker_rows: Vec<Vec<&'static Sticker>>,
124
152
sticker_scroll: UniformListScrollHandle,
153
org: OrgState,
154
org_generation: u64,
155
org_task: Option<Task<()>>,
156
org_scroll: UniformListScrollHandle,
125
157
_subscription: Subscription,
126
158
}
127
159
@@ -218,6 +250,10 @@ impl FunPicker {
218
250
chip: StickerChip::Popular,
219
251
sticker_rows: sticker_rows("", StickerChip::Popular),
220
252
sticker_scroll: UniformListScrollHandle::new(),
253
org: OrgState::Loading,
254
org_generation: 0,
255
org_task: None,
256
org_scroll: UniformListScrollHandle::new(),
221
257
_subscription: subscription,
222
258
}
223
259
}
@@ -271,6 +307,7 @@ impl FunPicker {
271
307
self.sticker_rows = sticker_rows(&self.query, self.chip);
272
308
self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);
273
309
}
310
Tab::Org => self.load_org_emojis(cx),
274
311
}
275
312
cx.notify();
276
313
}
@@ -279,7 +316,7 @@ impl FunPicker {
279
316
&mut self,
280
317
input: &Entity<InputState>,
281
318
event: &InputEvent,
282
_: &mut Window,
319
window: &mut Window,
283
320
cx: &mut Context<Self>,
284
321
) {
285
322
match event {
@@ -299,6 +336,12 @@ impl FunPicker {
299
336
self.pick_emoji(&glyph, cx);
300
337
}
301
338
}
339
InputEvent::PressEnter { .. } if self.tab == Tab::Org => {
340
if let Some(emoji) = self.visible_org_emojis().first().cloned() {
341
let image = RemoteImage::custom_emoji(&emoji);
342
self.pick_image(image, window, cx);
343
}
344
}
302
345
_ => {}
303
346
}
304
347
}
@@ -391,11 +434,11 @@ impl FunPicker {
391
434
div()
392
435
.id(("fun-picker-tab", tab as usize))
393
436
.h(px(32.))
394
.px(px(14.))
437
.px(px(8.))
395
438
.flex()
396
439
.items_center()
397
440
.cursor_pointer()
398
.text_size(px(13.))
441
.text_size(px(12.))
399
442
.font_weight(FontWeight::SEMIBOLD)
400
443
.border_b_2()
401
444
.border_color(if selected {
@@ -729,6 +772,156 @@ impl FunPicker {
729
772
.child(div().flex_1().min_h_0().child(grid))
730
773
.into_any_element()
731
774
}
775
776
fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
777
match &self.org {
778
OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
779
.into_iter()
780
.cloned()
781
.collect(),
782
_ => Vec::new(),
783
}
784
}
785
786
fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
787
if matches!(self.org, OrgState::Ready(_)) {
788
self.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
789
return;
790
}
791
self.org_generation += 1;
792
let generation = self.org_generation;
793
self.org = OrgState::Loading;
794
let (demo, engine) = {
795
let state = self.app.read(cx);
796
(state.mode.demo, state.engine.clone())
797
};
798
self.org_task = Some(cx.spawn(async move |this, cx| {
799
let outcome = org_emojis::list(engine, demo, false)
800
.await
801
.unwrap_or(Err(OrgEmojiError::Failed));
802
this.update(cx, |this, cx| {
803
if this.org_generation != generation {
804
return;
805
}
806
this.org = match outcome {
807
Ok(emojis) => OrgState::Ready(emojis),
808
Err(_) => OrgState::Failed,
809
};
810
this.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
811
cx.notify();
812
})
813
.ok();
814
}));
815
}
816
817
fn reload_org_emojis(&mut self, cx: &mut Context<Self>) {
818
self.org = OrgState::Loading;
819
self.load_org_emojis(cx);
820
}
821
822
fn org_tile(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
823
let picked = RemoteImage::custom_emoji(emoji);
824
let name = emoji.name.clone();
825
let label = name.clone();
826
v_flex()
827
.id(("fun-picker-org", index))
828
.w(px(ORG_CELL))
829
.flex_none()
830
.items_center()
831
.gap(px(2.))
832
.p(px(2.))
833
.rounded(px(TILE_RADIUS))
834
.cursor_pointer()
835
.hover(|tile| tile.bg(theme::popup_hover()))
836
.child(
837
img(bounded(image_source(&emoji.image_url())))
838
.size(px(ORG_CELL - 8.))
839
.object_fit(ObjectFit::Contain),
840
)
841
.child(
842
div()
843
.w(px(ORG_CELL))
844
.overflow_hidden()
845
.text_ellipsis()
846
.text_center()
847
.text_size(px(9.))
848
.text_color(theme::text_muted())
849
.child(label),
850
)
851
.tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
852
.on_click(cx.listener(move |this, _, window, cx| {
853
this.pick_image(picked.clone(), window, cx)
854
}))
855
.into_any_element()
856
}
857
858
fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
859
match &self.org {
860
OrgState::Loading => Self::message(String::new())
861
.child(
862
div()
863
.size_full()
864
.flex()
865
.items_center()
866
.justify_center()
867
.text_color(theme::text_muted())
868
.child("…"),
869
)
870
.into_any_element(),
871
OrgState::Failed => Self::message(tr("fun_picker.org.failed"))
872
.child(
873
div()
874
.id("fun-picker-org-retry")
875
.h(px(28.))
876
.px(px(12.))
877
.flex()
878
.items_center()
879
.rounded(px(6.))
880
.bg(theme::popup_hover())
881
.text_color(theme::text())
882
.cursor_pointer()
883
.hover(|button| button.bg(theme::border_strong()))
884
.child(tr("fun_picker.org.retry"))
885
.on_click(cx.listener(|this, _, _, cx| this.reload_org_emojis(cx))),
886
)
887
.into_any_element(),
888
OrgState::Ready(emojis) => {
889
let visible = org_emojis::filter(emojis.as_slice(), &self.query);
890
if visible.is_empty() {
891
return Self::message(org_empty_message(&self.query)).into_any_element();
892
}
893
let rows: Vec<Vec<OrgEmoji>> = visible
894
.into_iter()
895
.cloned()
896
.collect::<Vec<_>>()
897
.chunks(ORG_COLUMNS)
898
.map(|chunk| chunk.to_vec())
899
.collect();
900
uniform_list(
901
"fun-picker-org-list",
902
rows.len(),
903
cx.processor(move |this, range: std::ops::Range<usize>, _, cx| {
904
range
905
.map(|index| {
906
let tiles = rows[index].iter().enumerate().map(|(column, emoji)| {
907
this.org_tile(emoji, index * ORG_COLUMNS + column, cx)
908
});
909
h_flex()
910
.h(px(ORG_CELL + 16. + ORG_GAP))
911
.gap(px(ORG_GAP))
912
.children(tiles)
913
.into_any_element()
914
})
915
.collect::<Vec<_>>()
916
}),
917
)
918
.track_scroll(&self.org_scroll)
919
.size_full()
920
.into_any_element()
921
}
922
}
923
}
924
732
925
}
733
926
734
927
impl Render for FunPicker {
@@ -738,6 +931,7 @@ impl Render for FunPicker {
738
931
Tab::Emoji => self.render_emoji(cx),
739
932
Tab::Gif => self.render_gifs(cx),
740
933
Tab::Sticker => self.render_stickers(cx),
934
Tab::Org => self.render_org(cx),
741
935
};
742
936
v_flex()
743
937
.w(px(WIDTH))
@@ -11,13 +11,17 @@ use gpui_kit::component::{11
};11
};12
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::prelude::FluentBuilder as _;13
use gpui_kit::*;13
use gpui_kit::*;14
use teams_core::Gif;14
use gpui_kit::component::tooltip::Tooltip;15
use std::collections::HashMap;16
use teams_core::{Gif, OrgEmoji};15
17
16
use super::skin_tone_choices::{tone_badge, tone_choices};18
use super::skin_tone_choices::{tone_badge, tone_choices};17
use crate::app_state::AppState;19
use crate::app_state::AppState;18
use crate::emoji;20
use crate::emoji;19
use crate::emoticons;21
use crate::emoticons;20
use crate::gifs::{self, GifError};22
use crate::gifs::{self, GifError};23
use crate::i18n::{tr, tr_args};24
use crate::org_emojis::{self, OrgEmojiError};21
use crate::remote_image::{RemoteImage, image_source};25
use crate::remote_image::{RemoteImage, image_source};22
use crate::stickers::{self, Sticker};26
use crate::stickers::{self, Sticker};23
use crate::theme;27
use crate::theme;@@ -39,6 +43,10 @@ const GIF_MIN_HEIGHT: f32 = 48.;39
const GIF_MAX_HEIGHT: f32 = 200.;43
const GIF_MAX_HEIGHT: f32 = 200.;40
const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];44
const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];41
const STICKER_COLUMNS: usize = 4;45
const STICKER_COLUMNS: usize = 4;46
const ORG_COLUMNS: usize = 8;47
const ORG_GAP: f32 = 4.;48
const ORG_CELL: f32 =49
(CONTENT_WIDTH - ORG_GAP * (ORG_COLUMNS - 1) as f32) / ORG_COLUMNS as f32;42
const STICKER_GAP: f32 = 6.;50
const STICKER_GAP: f32 = 6.;43
const POPULAR_LABEL: &str = "Beliebt";51
const POPULAR_LABEL: &str = "Beliebt";44
const TILE_RADIUS: f32 = 6.;52
const TILE_RADIUS: f32 = 6.;@@ -48,16 +56,18 @@ enum Tab {48
Emoji,56
Emoji,49
Gif,57
Gif,50
Sticker,58
Sticker,59
Org,51
}60
}52
61
53
impl Tab {62
impl Tab {54
const ALL: [Tab; 3] = [Tab::Emoji, Tab::Gif, Tab::Sticker];63
const ALL: [Tab; 4] = [Tab::Emoji, Tab::Gif, Tab::Sticker, Tab::Org];55
64
56
fn key(self) -> &'static str {65
fn key(self) -> &'static str {57
match self {66
match self {58
Tab::Emoji => "emoji",67
Tab::Emoji => "emoji",59
Tab::Gif => "gif",68
Tab::Gif => "gif",60
Tab::Sticker => "sticker",69
Tab::Sticker => "sticker",70
Tab::Org => "org",61
}71
}62
}72
}63
73
@@ -65,20 +75,38 @@ impl Tab {65
Tab::ALL.into_iter().find(|tab| tab.key() == key)75
Tab::ALL.into_iter().find(|tab| tab.key() == key)66
}76
}67
77
68
fn label(self) -> &'static str {78
fn label(self) -> String {69
match self {79
tr(match self {70
Tab::Emoji => "Emoji",80
Tab::Emoji => "fun_picker.tab.emoji",71
Tab::Gif => "GIF",81
Tab::Gif => "fun_picker.tab.gif",72
Tab::Sticker => "Sticker",82
Tab::Sticker => "fun_picker.tab.sticker",73
}83
Tab::Org => "fun_picker.tab.org",84
})74
}85
}75
86
76
fn placeholder(self) -> &'static str {87
fn placeholder(self) -> String {77
match self {88
tr(match self {78
Tab::Emoji => "Emoji suchen",89
Tab::Emoji => "fun_picker.search.emoji",79
Tab::Gif => "GIFs suchen",90
Tab::Gif => "fun_picker.search.gif",80
Tab::Sticker => "Sticker suchen",91
Tab::Sticker => "fun_picker.search.sticker",81
}92
Tab::Org => "fun_picker.search.org",93
})94
}95
}96
97
enum OrgState {98
Loading,99
Ready(Vec<OrgEmoji>),100
Failed,101
}102
103
fn org_empty_message(query: &str) -> String {104
if query.is_empty() {105
tr("fun_picker.org.empty")106
} else {107
let mut args = HashMap::new();108
args.insert("query".into(), query.to_owned());109
tr_args("fun_picker.org.empty_query", &args)82
}110
}83
}111
}84
112
@@ -122,6 +150,10 @@ pub struct FunPicker {122
chip: StickerChip,150
chip: StickerChip,123
sticker_rows: Vec<Vec<&'static Sticker>>,151
sticker_rows: Vec<Vec<&'static Sticker>>,124
sticker_scroll: UniformListScrollHandle,152
sticker_scroll: UniformListScrollHandle,153
org: OrgState,154
org_generation: u64,155
org_task: Option<Task<()>>,156
org_scroll: UniformListScrollHandle,125
_subscription: Subscription,157
_subscription: Subscription,126
}158
}127
159
@@ -218,6 +250,10 @@ impl FunPicker {218
chip: StickerChip::Popular,250
chip: StickerChip::Popular,219
sticker_rows: sticker_rows("", StickerChip::Popular),251
sticker_rows: sticker_rows("", StickerChip::Popular),220
sticker_scroll: UniformListScrollHandle::new(),252
sticker_scroll: UniformListScrollHandle::new(),253
org: OrgState::Loading,254
org_generation: 0,255
org_task: None,256
org_scroll: UniformListScrollHandle::new(),221
_subscription: subscription,257
_subscription: subscription,222
}258
}223
}259
}@@ -271,6 +307,7 @@ impl FunPicker {271
self.sticker_rows = sticker_rows(&self.query, self.chip);307
self.sticker_rows = sticker_rows(&self.query, self.chip);272
self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);308
self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);273
}309
}310
Tab::Org => self.load_org_emojis(cx),274
}311
}275
cx.notify();312
cx.notify();276
}313
}@@ -279,7 +316,7 @@ impl FunPicker {279
&mut self,316
&mut self,280
input: &Entity<InputState>,317
input: &Entity<InputState>,281
event: &InputEvent,318
event: &InputEvent,282
_: &mut Window,319
window: &mut Window,283
cx: &mut Context<Self>,320
cx: &mut Context<Self>,284
) {321
) {285
match event {322
match event {@@ -299,6 +336,12 @@ impl FunPicker {299
self.pick_emoji(&glyph, cx);336
self.pick_emoji(&glyph, cx);300
}337
}301
}338
}339
InputEvent::PressEnter { .. } if self.tab == Tab::Org => {340
if let Some(emoji) = self.visible_org_emojis().first().cloned() {341
let image = RemoteImage::custom_emoji(&emoji);342
self.pick_image(image, window, cx);343
}344
}302
_ => {}345
_ => {}303
}346
}304
}347
}@@ -391,11 +434,11 @@ impl FunPicker {391
div()434
div()392
.id(("fun-picker-tab", tab as usize))435
.id(("fun-picker-tab", tab as usize))393
.h(px(32.))436
.h(px(32.))394
.px(px(14.))437
.px(px(8.))395
.flex()438
.flex()396
.items_center()439
.items_center()397
.cursor_pointer()440
.cursor_pointer()398
.text_size(px(13.))441
.text_size(px(12.))399
.font_weight(FontWeight::SEMIBOLD)442
.font_weight(FontWeight::SEMIBOLD)400
.border_b_2()443
.border_b_2()401
.border_color(if selected {444
.border_color(if selected {@@ -729,6 +772,156 @@ impl FunPicker {729
.child(div().flex_1().min_h_0().child(grid))772
.child(div().flex_1().min_h_0().child(grid))730
.into_any_element()773
.into_any_element()731
}774
}775
776
fn visible_org_emojis(&self) -> Vec<OrgEmoji> {777
match &self.org {778
OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)779
.into_iter()780
.cloned()781
.collect(),782
_ => Vec::new(),783
}784
}785
786
fn load_org_emojis(&mut self, cx: &mut Context<Self>) {787
if matches!(self.org, OrgState::Ready(_)) {788
self.org_scroll.scroll_to_item(0, ScrollStrategy::Top);789
return;790
}791
self.org_generation += 1;792
let generation = self.org_generation;793
self.org = OrgState::Loading;794
let (demo, engine) = {795
let state = self.app.read(cx);796
(state.mode.demo, state.engine.clone())797
};798
self.org_task = Some(cx.spawn(async move |this, cx| {799
let outcome = org_emojis::list(engine, demo, false)800
.await801
.unwrap_or(Err(OrgEmojiError::Failed));802
this.update(cx, |this, cx| {803
if this.org_generation != generation {804
return;805
}806
this.org = match outcome {807
Ok(emojis) => OrgState::Ready(emojis),808
Err(_) => OrgState::Failed,809
};810
this.org_scroll.scroll_to_item(0, ScrollStrategy::Top);811
cx.notify();812
})813
.ok();814
}));815
}816
817
fn reload_org_emojis(&mut self, cx: &mut Context<Self>) {818
self.org = OrgState::Loading;819
self.load_org_emojis(cx);820
}821
822
fn org_tile(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {823
let picked = RemoteImage::custom_emoji(emoji);824
let name = emoji.name.clone();825
let label = name.clone();826
v_flex()827
.id(("fun-picker-org", index))828
.w(px(ORG_CELL))829
.flex_none()830
.items_center()831
.gap(px(2.))832
.p(px(2.))833
.rounded(px(TILE_RADIUS))834
.cursor_pointer()835
.hover(|tile| tile.bg(theme::popup_hover()))836
.child(837
img(bounded(image_source(&emoji.image_url())))838
.size(px(ORG_CELL - 8.))839
.object_fit(ObjectFit::Contain),840
)841
.child(842
div()843
.w(px(ORG_CELL))844
.overflow_hidden()845
.text_ellipsis()846
.text_center()847
.text_size(px(9.))848
.text_color(theme::text_muted())849
.child(label),850
)851
.tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))852
.on_click(cx.listener(move |this, _, window, cx| {853
this.pick_image(picked.clone(), window, cx)854
}))855
.into_any_element()856
}857
858
fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {859
match &self.org {860
OrgState::Loading => Self::message(String::new())861
.child(862
div()863
.size_full()864
.flex()865
.items_center()866
.justify_center()867
.text_color(theme::text_muted())868
.child("…"),869
)870
.into_any_element(),871
OrgState::Failed => Self::message(tr("fun_picker.org.failed"))872
.child(873
div()874
.id("fun-picker-org-retry")875
.h(px(28.))876
.px(px(12.))877
.flex()878
.items_center()879
.rounded(px(6.))880
.bg(theme::popup_hover())881
.text_color(theme::text())882
.cursor_pointer()883
.hover(|button| button.bg(theme::border_strong()))884
.child(tr("fun_picker.org.retry"))885
.on_click(cx.listener(|this, _, _, cx| this.reload_org_emojis(cx))),886
)887
.into_any_element(),888
OrgState::Ready(emojis) => {889
let visible = org_emojis::filter(emojis.as_slice(), &self.query);890
if visible.is_empty() {891
return Self::message(org_empty_message(&self.query)).into_any_element();892
}893
let rows: Vec<Vec<OrgEmoji>> = visible894
.into_iter()895
.cloned()896
.collect::<Vec<_>>()897
.chunks(ORG_COLUMNS)898
.map(|chunk| chunk.to_vec())899
.collect();900
uniform_list(901
"fun-picker-org-list",902
rows.len(),903
cx.processor(move |this, range: std::ops::Range<usize>, _, cx| {904
range905
.map(|index| {906
let tiles = rows[index].iter().enumerate().map(|(column, emoji)| {907
this.org_tile(emoji, index * ORG_COLUMNS + column, cx)908
});909
h_flex()910
.h(px(ORG_CELL + 16. + ORG_GAP))911
.gap(px(ORG_GAP))912
.children(tiles)913
.into_any_element()914
})915
.collect::<Vec<_>>()916
}),917
)918
.track_scroll(&self.org_scroll)919
.size_full()920
.into_any_element()921
}922
}923
}924
732
}925
}733
926
734
impl Render for FunPicker {927
impl Render for FunPicker {@@ -738,6 +931,7 @@ impl Render for FunPicker {738
Tab::Emoji => self.render_emoji(cx),931
Tab::Emoji => self.render_emoji(cx),739
Tab::Gif => self.render_gifs(cx),932
Tab::Gif => self.render_gifs(cx),740
Tab::Sticker => self.render_stickers(cx),933
Tab::Sticker => self.render_stickers(cx),934
Tab::Org => self.render_org(cx),741
};935
};742
v_flex()936
v_flex()743
.w(px(WIDTH))937
.w(px(WIDTH))@@ -245,6 +245,24 @@ impl Render for RailView {
245
245
calendar,
246
246
self.agents_running(cx),
247
247
);
248
// KVT-fork: tegels Ponos en Asclepius direct onder Agents.
249
let tickets_unread = crate::kvt::tickets_unread(cx);
250
let items = crate::kvt::with_rail_tiles(items, |tile, label| match tile {
251
crate::kvt::RailTile::Ponos => RailItem {
252
tab: SidebarTab::Ponos,
253
label,
254
shortcut_label: "Open Ponos",
255
icon: IconName::ClipboardCheck,
256
badge: RailBadge::None,
257
},
258
crate::kvt::RailTile::Asclepius => RailItem {
259
tab: SidebarTab::Asclepius,
260
label,
261
shortcut_label: "Open Asclepius",
262
icon: IconName::Ticket,
263
badge: count_badge_for(tickets_unread),
264
},
265
});
248
266
v_flex()
249
267
.debug_selector(|| "shell/islands/rail".into())
250
268
.w(px(RAIL_WIDTH))
@@ -245,6 +245,24 @@ impl Render for RailView {245
calendar,245
calendar,246
self.agents_running(cx),246
self.agents_running(cx),247
);247
);248
// KVT-fork: tegels Ponos en Asclepius direct onder Agents.249
let tickets_unread = crate::kvt::tickets_unread(cx);250
let items = crate::kvt::with_rail_tiles(items, |tile, label| match tile {251
crate::kvt::RailTile::Ponos => RailItem {252
tab: SidebarTab::Ponos,253
label,254
shortcut_label: "Open Ponos",255
icon: IconName::ClipboardCheck,256
badge: RailBadge::None,257
},258
crate::kvt::RailTile::Asclepius => RailItem {259
tab: SidebarTab::Asclepius,260
label,261
shortcut_label: "Open Asclepius",262
icon: IconName::Ticket,263
badge: count_badge_for(tickets_unread),264
},265
});248
v_flex()266
v_flex()249
.debug_selector(|| "shell/islands/rail".into())267
.debug_selector(|| "shell/islands/rail".into())250
.w(px(RAIL_WIDTH))268
.w(px(RAIL_WIDTH))@@ -1,4 +1,4 @@
1
use std::collections::HashSet;
1
use std::collections::{HashMap, HashSet};
2
2
use std::rc::Rc;
3
3
4
4
use gpui_kit::base::PopoverState;
@@ -21,6 +21,11 @@ use crate::emoji;
21
21
use crate::emoticons;
22
22
use crate::rows::reaction_glyph;
23
23
use crate::theme;
24
use crate::i18n::{tr, tr_args};
25
use crate::org_emojis::{self, OrgEmojiError};
26
use crate::remote_image::image_source;
27
use crate::views::image_memory::bounded;
28
use teams_core::OrgEmoji;
24
29
25
30
const PICKER_QUICK: [&str; 6] = [
26
31
"\u{1F44D}",
@@ -52,6 +57,30 @@ const PICKER_WIDTH: f32 = 296.;
52
57
const CELL_SIZE: f32 = 32.;
53
58
const GRID_COLUMNS: usize = 8;
54
59
const GRID_LIMIT: usize = 32;
60
const ORG_COLUMNS: usize = 8;
61
62
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63
enum Tab {
64
Emoji,
65
Org,
66
}
67
68
enum OrgState {
69
Loading,
70
Ready(Vec<OrgEmoji>),
71
Failed,
72
}
73
74
fn org_empty_message(query: &str) -> String {
75
if query.is_empty() {
76
tr("reaction_picker.org.empty")
77
} else {
78
let mut args = HashMap::new();
79
args.insert("query".into(), query.to_owned());
80
tr_args("reaction_picker.org.empty_query", &args)
81
}
82
}
83
55
84
56
85
pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
57
86
pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;
@@ -73,6 +102,10 @@ pub struct ReactionPicker {
73
102
skin_tone: u8,
74
103
tone_menu: Option<(String, Point<Pixels>)>,
75
104
customizing: bool,
105
tab: Tab,
106
org: OrgState,
107
org_generation: u64,
108
org_task: Option<Task<()>>,
76
109
_subscription: Subscription,
77
110
}
78
111
@@ -95,6 +128,10 @@ impl ReactionPicker {
95
128
skin_tone: 0,
96
129
tone_menu: None,
97
130
customizing: false,
131
tab: Tab::Emoji,
132
org: OrgState::Loading,
133
org_generation: 0,
134
org_task: None,
98
135
_subscription: subscription,
99
136
}
100
137
}
@@ -131,10 +168,15 @@ impl ReactionPicker {
131
168
cx.notify();
132
169
});
133
170
self.query.clear();
171
self.tab = Tab::Emoji;
134
172
self.input.update(cx, |state, cx| {
135
173
state.set_value("", window, cx);
174
state.set_placeholder("Search emoji", window, cx);
136
175
state.focus(window, cx);
137
176
});
177
if !self.customizing {
178
self.load_org_emojis(cx);
179
}
138
180
cx.notify();
139
181
}
140
182
@@ -151,7 +193,12 @@ impl ReactionPicker {
151
193
cx.notify();
152
194
}
153
195
InputEvent::PressEnter { .. } => {
154
if let Some(first) = self.results(cx).first().cloned() {
196
let first = if self.tab == Tab::Org {
197
self.visible_org_emojis().first().map(|emoji| emoji.key())
198
} else {
199
self.results(cx).first().cloned()
200
};
201
if let Some(first) = first {
155
202
self.pick(&first, false, window, cx);
156
203
}
157
204
}
@@ -315,6 +362,154 @@ impl ReactionPicker {
315
362
this.pick(&picked, event.modifiers().shift, window, cx)
316
363
}))
317
364
}
365
366
fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
367
match &self.org {
368
OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
369
.into_iter()
370
.cloned()
371
.collect(),
372
_ => Vec::new(),
373
}
374
}
375
376
fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
377
if tab == self.tab {
378
return;
379
}
380
self.tab = tab;
381
let placeholder = if tab == Tab::Org {
382
tr("reaction_picker.search.org")
383
} else {
384
"Search emoji".to_owned()
385
};
386
self.input.update(cx, |state, cx| {
387
state.set_placeholder(placeholder, window, cx);
388
state.focus(window, cx);
389
});
390
if tab == Tab::Org {
391
self.load_org_emojis(cx);
392
}
393
cx.notify();
394
}
395
396
fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
397
if matches!(self.org, OrgState::Ready(_)) {
398
return;
399
}
400
self.org_generation += 1;
401
let generation = self.org_generation;
402
self.org = OrgState::Loading;
403
let (demo, engine) = {
404
let state = self.app.read(cx);
405
(state.mode.demo, state.engine.clone())
406
};
407
self.org_task = Some(cx.spawn(async move |this, cx| {
408
let outcome = org_emojis::list(engine, demo, false)
409
.await
410
.unwrap_or(Err(OrgEmojiError::Failed));
411
this.update(cx, |this, cx| {
412
if this.org_generation != generation {
413
return;
414
}
415
this.org = match outcome {
416
Ok(emojis) => OrgState::Ready(emojis),
417
Err(_) => OrgState::Failed,
418
};
419
cx.notify();
420
})
421
.ok();
422
}));
423
}
424
425
fn tab_button(&self, tab: Tab, label_key: &str, cx: &mut Context<Self>) -> Stateful<Div> {
426
let selected = tab == self.tab;
427
div()
428
.id(("reaction-picker-tab", tab as usize))
429
.h(px(26.))
430
.px(px(8.))
431
.flex()
432
.items_center()
433
.cursor_pointer()
434
.text_size(px(12.))
435
.font_weight(FontWeight::SEMIBOLD)
436
.border_b_2()
437
.border_color(if selected {
438
theme::accent()
439
} else {
440
transparent_black()
441
})
442
.text_color(if selected {
443
theme::accent_text()
444
} else {
445
theme::text_muted()
446
})
447
.hover(|button| button.text_color(theme::text_strong()))
448
.child(tr(label_key))
449
.on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
450
}
451
452
fn org_cell(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
453
let key = emoji.key();
454
let name = emoji.name.clone();
455
let selected = self.selected.contains(&key);
456
div()
457
.id(("reaction-picker-org", index))
458
.size(px(CELL_SIZE))
459
.flex_none()
460
.p(px(3.))
461
.rounded(px(6.))
462
.cursor_pointer()
463
.when(selected, |cell| cell.bg(theme::reaction_on_own()))
464
.hover(|cell| cell.bg(theme::popup_hover()))
465
.child(
466
img(bounded(image_source(&emoji.image_url())))
467
.size_full()
468
.object_fit(ObjectFit::Contain),
469
)
470
.tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
471
.on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
472
this.pick(&key, event.modifiers().shift, window, cx)
473
}))
474
.into_any_element()
475
}
476
477
fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
478
match &self.org {
479
OrgState::Loading => div()
480
.text_size(px(11.))
481
.text_color(theme::text_muted())
482
.child("…")
483
.into_any_element(),
484
OrgState::Failed => div()
485
.text_size(px(11.))
486
.text_color(theme::text_muted())
487
.child(tr("fun_picker.org.failed"))
488
.into_any_element(),
489
OrgState::Ready(_) => {
490
let visible = self.visible_org_emojis();
491
if visible.is_empty() {
492
return div()
493
.text_size(px(11.))
494
.text_color(theme::text_muted())
495
.child(org_empty_message(&self.query))
496
.into_any_element();
497
}
498
let mut rows = Vec::new();
499
let mut row = Vec::new();
500
for (index, emoji) in visible.iter().enumerate() {
501
row.push(self.org_cell(emoji, index, cx));
502
if row.len() == ORG_COLUMNS {
503
rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
504
}
505
}
506
if !row.is_empty() {
507
rows.push(h_flex().gap(px(2.)).children(row));
508
}
509
v_flex().gap(px(2.)).children(rows).into_any_element()
510
}
511
}
512
}
318
513
}
319
514
320
515
impl Render for ReactionPicker {
@@ -343,11 +538,35 @@ impl Render for ReactionPicker {
343
538
if !row.is_empty() {
344
539
rows.push(h_flex().gap(px(2.)).children(row));
345
540
}
541
let tabs = (!self.customizing).then(|| {
542
h_flex()
543
.flex_none()
544
.gap(px(2.))
545
.child(self.tab_button(Tab::Emoji, "reaction_picker.tab.emoji", cx))
546
.child(self.tab_button(Tab::Org, "reaction_picker.tab.org", cx))
547
});
548
let body = if self.tab == Tab::Org && !self.customizing {
549
self.render_org(cx)
550
} else {
551
v_flex()
552
.gap(px(2.))
553
.child(
554
div()
555
.text_size(px(11.))
556
.text_color(theme::text_muted())
557
.child(label),
558
)
559
.child(v_flex().gap(px(2.)).children(rows))
560
.into_any_element()
561
};
346
562
v_flex()
347
563
.w(px(PICKER_WIDTH))
348
564
.gap(px(8.))
349
565
.p(px(8.))
350
.child(h_flex().gap(px(2.)).children(quick))
566
.children(tabs)
567
.when(self.tab != Tab::Org || self.customizing, |picker| {
568
picker.child(h_flex().gap(px(2.)).children(quick))
569
})
351
570
.child(
352
571
h_flex()
353
572
.gap(px(4.))
@@ -365,13 +584,7 @@ impl Render for ReactionPicker {
365
584
)
366
585
.children(self.customize_button(cx)),
367
586
)
368
.child(
369
div()
370
.text_size(px(11.))
371
.text_color(theme::text_muted())
372
.child(label),
373
)
374
.child(v_flex().gap(px(2.)).children(rows))
587
.child(body)
375
588
.children(self.tone_menu(cx))
376
589
}
377
590
}
@@ -1,4 +1,4 @@1
use std::collections::HashSet;1
use std::collections::{HashMap, HashSet};2
use std::rc::Rc;2
use std::rc::Rc;3
3
4
use gpui_kit::base::PopoverState;4
use gpui_kit::base::PopoverState;@@ -21,6 +21,11 @@ use crate::emoji;21
use crate::emoticons;21
use crate::emoticons;22
use crate::rows::reaction_glyph;22
use crate::rows::reaction_glyph;23
use crate::theme;23
use crate::theme;24
use crate::i18n::{tr, tr_args};25
use crate::org_emojis::{self, OrgEmojiError};26
use crate::remote_image::image_source;27
use crate::views::image_memory::bounded;28
use teams_core::OrgEmoji;24
29
25
const PICKER_QUICK: [&str; 6] = [30
const PICKER_QUICK: [&str; 6] = [26
"\u{1F44D}",31
"\u{1F44D}",@@ -52,6 +57,30 @@ const PICKER_WIDTH: f32 = 296.;52
const CELL_SIZE: f32 = 32.;57
const CELL_SIZE: f32 = 32.;53
const GRID_COLUMNS: usize = 8;58
const GRID_COLUMNS: usize = 8;54
const GRID_LIMIT: usize = 32;59
const GRID_LIMIT: usize = 32;60
const ORG_COLUMNS: usize = 8;61
62
#[derive(Debug, Clone, Copy, PartialEq, Eq)]63
enum Tab {64
Emoji,65
Org,66
}67
68
enum OrgState {69
Loading,70
Ready(Vec<OrgEmoji>),71
Failed,72
}73
74
fn org_empty_message(query: &str) -> String {75
if query.is_empty() {76
tr("reaction_picker.org.empty")77
} else {78
let mut args = HashMap::new();79
args.insert("query".into(), query.to_owned());80
tr_args("reaction_picker.org.empty_query", &args)81
}82
}83
55
84
56
pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;85
pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;57
pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;86
pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;@@ -73,6 +102,10 @@ pub struct ReactionPicker {73
skin_tone: u8,102
skin_tone: u8,74
tone_menu: Option<(String, Point<Pixels>)>,103
tone_menu: Option<(String, Point<Pixels>)>,75
customizing: bool,104
customizing: bool,105
tab: Tab,106
org: OrgState,107
org_generation: u64,108
org_task: Option<Task<()>>,76
_subscription: Subscription,109
_subscription: Subscription,77
}110
}78
111
@@ -95,6 +128,10 @@ impl ReactionPicker {95
skin_tone: 0,128
skin_tone: 0,96
tone_menu: None,129
tone_menu: None,97
customizing: false,130
customizing: false,131
tab: Tab::Emoji,132
org: OrgState::Loading,133
org_generation: 0,134
org_task: None,98
_subscription: subscription,135
_subscription: subscription,99
}136
}100
}137
}@@ -131,10 +168,15 @@ impl ReactionPicker {131
cx.notify();168
cx.notify();132
});169
});133
self.query.clear();170
self.query.clear();171
self.tab = Tab::Emoji;134
self.input.update(cx, |state, cx| {172
self.input.update(cx, |state, cx| {135
state.set_value("", window, cx);173
state.set_value("", window, cx);174
state.set_placeholder("Search emoji", window, cx);136
state.focus(window, cx);175
state.focus(window, cx);137
});176
});177
if !self.customizing {178
self.load_org_emojis(cx);179
}138
cx.notify();180
cx.notify();139
}181
}140
182
@@ -151,7 +193,12 @@ impl ReactionPicker {151
cx.notify();193
cx.notify();152
}194
}153
InputEvent::PressEnter { .. } => {195
InputEvent::PressEnter { .. } => {154
if let Some(first) = self.results(cx).first().cloned() {196
let first = if self.tab == Tab::Org {197
self.visible_org_emojis().first().map(|emoji| emoji.key())198
} else {199
self.results(cx).first().cloned()200
};201
if let Some(first) = first {155
self.pick(&first, false, window, cx);202
self.pick(&first, false, window, cx);156
}203
}157
}204
}@@ -315,6 +362,154 @@ impl ReactionPicker {315
this.pick(&picked, event.modifiers().shift, window, cx)362
this.pick(&picked, event.modifiers().shift, window, cx)316
}))363
}))317
}364
}365
366
fn visible_org_emojis(&self) -> Vec<OrgEmoji> {367
match &self.org {368
OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)369
.into_iter()370
.cloned()371
.collect(),372
_ => Vec::new(),373
}374
}375
376
fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {377
if tab == self.tab {378
return;379
}380
self.tab = tab;381
let placeholder = if tab == Tab::Org {382
tr("reaction_picker.search.org")383
} else {384
"Search emoji".to_owned()385
};386
self.input.update(cx, |state, cx| {387
state.set_placeholder(placeholder, window, cx);388
state.focus(window, cx);389
});390
if tab == Tab::Org {391
self.load_org_emojis(cx);392
}393
cx.notify();394
}395
396
fn load_org_emojis(&mut self, cx: &mut Context<Self>) {397
if matches!(self.org, OrgState::Ready(_)) {398
return;399
}400
self.org_generation += 1;401
let generation = self.org_generation;402
self.org = OrgState::Loading;403
let (demo, engine) = {404
let state = self.app.read(cx);405
(state.mode.demo, state.engine.clone())406
};407
self.org_task = Some(cx.spawn(async move |this, cx| {408
let outcome = org_emojis::list(engine, demo, false)409
.await410
.unwrap_or(Err(OrgEmojiError::Failed));411
this.update(cx, |this, cx| {412
if this.org_generation != generation {413
return;414
}415
this.org = match outcome {416
Ok(emojis) => OrgState::Ready(emojis),417
Err(_) => OrgState::Failed,418
};419
cx.notify();420
})421
.ok();422
}));423
}424
425
fn tab_button(&self, tab: Tab, label_key: &str, cx: &mut Context<Self>) -> Stateful<Div> {426
let selected = tab == self.tab;427
div()428
.id(("reaction-picker-tab", tab as usize))429
.h(px(26.))430
.px(px(8.))431
.flex()432
.items_center()433
.cursor_pointer()434
.text_size(px(12.))435
.font_weight(FontWeight::SEMIBOLD)436
.border_b_2()437
.border_color(if selected {438
theme::accent()439
} else {440
transparent_black()441
})442
.text_color(if selected {443
theme::accent_text()444
} else {445
theme::text_muted()446
})447
.hover(|button| button.text_color(theme::text_strong()))448
.child(tr(label_key))449
.on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))450
}451
452
fn org_cell(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {453
let key = emoji.key();454
let name = emoji.name.clone();455
let selected = self.selected.contains(&key);456
div()457
.id(("reaction-picker-org", index))458
.size(px(CELL_SIZE))459
.flex_none()460
.p(px(3.))461
.rounded(px(6.))462
.cursor_pointer()463
.when(selected, |cell| cell.bg(theme::reaction_on_own()))464
.hover(|cell| cell.bg(theme::popup_hover()))465
.child(466
img(bounded(image_source(&emoji.image_url())))467
.size_full()468
.object_fit(ObjectFit::Contain),469
)470
.tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))471
.on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {472
this.pick(&key, event.modifiers().shift, window, cx)473
}))474
.into_any_element()475
}476
477
fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {478
match &self.org {479
OrgState::Loading => div()480
.text_size(px(11.))481
.text_color(theme::text_muted())482
.child("…")483
.into_any_element(),484
OrgState::Failed => div()485
.text_size(px(11.))486
.text_color(theme::text_muted())487
.child(tr("fun_picker.org.failed"))488
.into_any_element(),489
OrgState::Ready(_) => {490
let visible = self.visible_org_emojis();491
if visible.is_empty() {492
return div()493
.text_size(px(11.))494
.text_color(theme::text_muted())495
.child(org_empty_message(&self.query))496
.into_any_element();497
}498
let mut rows = Vec::new();499
let mut row = Vec::new();500
for (index, emoji) in visible.iter().enumerate() {501
row.push(self.org_cell(emoji, index, cx));502
if row.len() == ORG_COLUMNS {503
rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));504
}505
}506
if !row.is_empty() {507
rows.push(h_flex().gap(px(2.)).children(row));508
}509
v_flex().gap(px(2.)).children(rows).into_any_element()510
}511
}512
}318
}513
}319
514
320
impl Render for ReactionPicker {515
impl Render for ReactionPicker {@@ -343,11 +538,35 @@ impl Render for ReactionPicker {343
if !row.is_empty() {538
if !row.is_empty() {344
rows.push(h_flex().gap(px(2.)).children(row));539
rows.push(h_flex().gap(px(2.)).children(row));345
}540
}541
let tabs = (!self.customizing).then(|| {542
h_flex()543
.flex_none()544
.gap(px(2.))545
.child(self.tab_button(Tab::Emoji, "reaction_picker.tab.emoji", cx))546
.child(self.tab_button(Tab::Org, "reaction_picker.tab.org", cx))547
});548
let body = if self.tab == Tab::Org && !self.customizing {549
self.render_org(cx)550
} else {551
v_flex()552
.gap(px(2.))553
.child(554
div()555
.text_size(px(11.))556
.text_color(theme::text_muted())557
.child(label),558
)559
.child(v_flex().gap(px(2.)).children(rows))560
.into_any_element()561
};346
v_flex()562
v_flex()347
.w(px(PICKER_WIDTH))563
.w(px(PICKER_WIDTH))348
.gap(px(8.))564
.gap(px(8.))349
.p(px(8.))565
.p(px(8.))350
.child(h_flex().gap(px(2.)).children(quick))566
.children(tabs)567
.when(self.tab != Tab::Org || self.customizing, |picker| {568
picker.child(h_flex().gap(px(2.)).children(quick))569
})351
.child(570
.child(352
h_flex()571
h_flex()353
.gap(px(4.))572
.gap(px(4.))@@ -365,13 +584,7 @@ impl Render for ReactionPicker {365
)584
)366
.children(self.customize_button(cx)),585
.children(self.customize_button(cx)),367
)586
)368
.child(587
.child(body)369
div()370
.text_size(px(11.))371
.text_color(theme::text_muted())372
.child(label),373
)374
.child(v_flex().gap(px(2.)).children(rows))375
.children(self.tone_menu(cx))588
.children(self.tone_menu(cx))376
}589
}377
}590
}@@ -78,8 +78,31 @@ fn faces_width(count: usize) -> f32 {
78
78
diameter + count.saturating_sub(1) as f32 * (diameter - FACE_OVERLAP)
79
79
}
80
80
81
fn generic_custom_emoji(size: f32) -> AnyElement {
82
let glyph = (size * 0.7).round().max(8.);
83
div()
84
.size(px(size))
85
.flex_none()
86
.rounded(px((size * 0.25).round().max(2.)))
87
.bg(theme::popup_hover())
88
.flex()
89
.items_center()
90
.justify_center()
91
.text_size(px(glyph))
92
.line_height(px(size))
93
.text_color(theme::text_muted())
94
.child("☺")
95
.into_any_element()
96
}
97
81
98
fn reaction_emoji(glyph: &str, label: &str, size: f32, directory: &Directory) -> AnyElement {
82
99
let Some(image) = custom_emoji_image(glyph) else {
100
if chatsvc::hides_raw_reaction_key(glyph)
101
|| chatsvc::hides_raw_reaction_key(label)
102
|| label.is_empty() && chatsvc::is_custom_reaction_type(glyph)
103
{
104
return generic_custom_emoji(size);
105
}
83
106
return div()
84
107
.flex_none()
85
108
.h(px(size))
@@ -78,8 +78,31 @@ fn faces_width(count: usize) -> f32 {78
diameter + count.saturating_sub(1) as f32 * (diameter - FACE_OVERLAP)78
diameter + count.saturating_sub(1) as f32 * (diameter - FACE_OVERLAP)79
}79
}80
80
81
fn generic_custom_emoji(size: f32) -> AnyElement {82
let glyph = (size * 0.7).round().max(8.);83
div()84
.size(px(size))85
.flex_none()86
.rounded(px((size * 0.25).round().max(2.)))87
.bg(theme::popup_hover())88
.flex()89
.items_center()90
.justify_center()91
.text_size(px(glyph))92
.line_height(px(size))93
.text_color(theme::text_muted())94
.child("☺")95
.into_any_element()96
}97
81
fn reaction_emoji(glyph: &str, label: &str, size: f32, directory: &Directory) -> AnyElement {98
fn reaction_emoji(glyph: &str, label: &str, size: f32, directory: &Directory) -> AnyElement {82
let Some(image) = custom_emoji_image(glyph) else {99
let Some(image) = custom_emoji_image(glyph) else {100
if chatsvc::hides_raw_reaction_key(glyph)101
|| chatsvc::hides_raw_reaction_key(label)102
|| label.is_empty() && chatsvc::is_custom_reaction_type(glyph)103
{104
return generic_custom_emoji(size);105
}83
return div()106
return div()84
.flex_none()107
.flex_none()85
.h(px(size))108
.h(px(size))@@ -102,6 +102,9 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:
102
102
}
103
103
104
104
fn open_link(url: &str, cx: &mut App) {
105
if crate::kvt::open_ticket_link(url, cx) {
106
return; // KVT-fork: Asclepius-ticket in de app (met toegang)
107
}
105
108
if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() {
106
109
let text = opening_link_text(url);
107
110
handle
@@ -1007,6 +1010,7 @@ impl AppShell {
1007
1010
quick_view_open: bool,
1008
1011
calls_open: bool,
1009
1012
manage_team_open: bool,
1013
mut ponos: Option<AnyElement>, // KVT-fork: Ponos-bord
1010
1014
) -> Div {
1011
1015
h_flex()
1012
1016
.debug_selector(|| "shell/islands".into())
@@ -1030,6 +1034,7 @@ impl AppShell {
1030
1034
},
1031
1035
))
1032
1036
.child(match () {
1037
_ if ponos.is_some() => ponos.take().unwrap_or_else(|| div().into_any_element()),
1033
1038
_ if calls_open => self
1034
1039
.calls_page
1035
1040
.clone()
@@ -1108,13 +1113,22 @@ impl Render for AppShell {
1108
1113
let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar;
1109
1114
let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats;
1110
1115
let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls;
1116
let kvt_tab = self.sidebar.read(cx).tab(); // KVT-fork: Ponos/Asclepius-tegel
1117
let ponos_open = matches!(kvt_tab, SidebarTab::Ponos | SidebarTab::Asclepius); // KVT-fork
1118
let ponos_board = match kvt_tab {
1119
// KVT-fork
1120
SidebarTab::Ponos => Some(crate::kvt::board_view(cx)),
1121
SidebarTab::Asclepius => Some(crate::kvt::tickets_view(cx)),
1122
_ => None,
1123
};
1111
1124
let splash = self.render_splash(cx);
1112
1125
let state = self.state.read(cx);
1113
1126
let calendar_open = calendar_tab;
1114
1127
let quick_view_open = chats_tab && state.quick_view.is_some();
1115
let manage_team_open = !calendar_tab && !calls_tab && state.manage_team.is_some();
1128
let manage_team_open =
1129
!calendar_tab && !calls_tab && !ponos_open && state.manage_team.is_some();
1116
1130
let calls_open = calls_tab;
1117
let show_sidebar = !calendar_open && !calls_open;
1131
let show_sidebar = !calendar_open && !calls_open && !ponos_open;
1118
1132
let banner = state
1119
1133
.connection_banner_text()
1120
1134
.filter(|_| !self.splash.is_up())
@@ -1154,7 +1168,8 @@ impl Render for AppShell {
1154
1168
own_status_button(&self.state, state),
1155
1169
]
1156
1170
.into_iter()
1157
.flatten(),
1171
.flatten()
1172
.chain(crate::kvt::title_buttons(&self.notifications, window, cx)),
1158
1173
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),
1159
1174
);
1160
1175
let shell = div()
@@ -1370,6 +1385,7 @@ impl Render for AppShell {
1370
1385
quick_view_open,
1371
1386
calls_open,
1372
1387
manage_team_open,
1388
ponos_board,
1373
1389
),
1374
1390
&self.splash,
1375
1391
cx,
@@ -102,6 +102,9 @@ pub fn install_globals(state: &Entity<AppState>, user_input: Arc<UserInput>, cx:102
}102
}103
103
104
fn open_link(url: &str, cx: &mut App) {104
fn open_link(url: &str, cx: &mut App) {105
if crate::kvt::open_ticket_link(url, cx) {106
return; // KVT-fork: Asclepius-ticket in de app (met toegang)107
}105
if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() {108
if let Some(handle) = cx.try_global::<crate::app_state::AppHandle>() {106
let text = opening_link_text(url);109
let text = opening_link_text(url);107
handle110
handle@@ -1007,6 +1010,7 @@ impl AppShell {1007
quick_view_open: bool,1010
quick_view_open: bool,1008
calls_open: bool,1011
calls_open: bool,1009
manage_team_open: bool,1012
manage_team_open: bool,1013
mut ponos: Option<AnyElement>, // KVT-fork: Ponos-bord1010
) -> Div {1014
) -> Div {1011
h_flex()1015
h_flex()1012
.debug_selector(|| "shell/islands".into())1016
.debug_selector(|| "shell/islands".into())@@ -1030,6 +1034,7 @@ impl AppShell {1030
},1034
},1031
))1035
))1032
.child(match () {1036
.child(match () {1037
_ if ponos.is_some() => ponos.take().unwrap_or_else(|| div().into_any_element()),1033
_ if calls_open => self1038
_ if calls_open => self1034
.calls_page1039
.calls_page1035
.clone()1040
.clone()@@ -1108,13 +1113,22 @@ impl Render for AppShell {1108
let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar;1113
let calendar_tab = self.sidebar.read(cx).tab() == SidebarTab::Calendar;1109
let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats;1114
let chats_tab = self.sidebar.read(cx).tab() == SidebarTab::Chats;1110
let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls;1115
let calls_tab = self.sidebar.read(cx).tab() == SidebarTab::Calls;1116
let kvt_tab = self.sidebar.read(cx).tab(); // KVT-fork: Ponos/Asclepius-tegel1117
let ponos_open = matches!(kvt_tab, SidebarTab::Ponos | SidebarTab::Asclepius); // KVT-fork1118
let ponos_board = match kvt_tab {1119
// KVT-fork1120
SidebarTab::Ponos => Some(crate::kvt::board_view(cx)),1121
SidebarTab::Asclepius => Some(crate::kvt::tickets_view(cx)),1122
_ => None,1123
};1111
let splash = self.render_splash(cx);1124
let splash = self.render_splash(cx);1112
let state = self.state.read(cx);1125
let state = self.state.read(cx);1113
let calendar_open = calendar_tab;1126
let calendar_open = calendar_tab;1114
let quick_view_open = chats_tab && state.quick_view.is_some();1127
let quick_view_open = chats_tab && state.quick_view.is_some();1115
let manage_team_open = !calendar_tab && !calls_tab && state.manage_team.is_some();1128
let manage_team_open =1129
!calendar_tab && !calls_tab && !ponos_open && state.manage_team.is_some();1116
let calls_open = calls_tab;1130
let calls_open = calls_tab;1117
let show_sidebar = !calendar_open && !calls_open;1131
let show_sidebar = !calendar_open && !calls_open && !ponos_open;1118
let banner = state1132
let banner = state1119
.connection_banner_text()1133
.connection_banner_text()1120
.filter(|_| !self.splash.is_up())1134
.filter(|_| !self.splash.is_up())@@ -1154,7 +1168,8 @@ impl Render for AppShell {1154
own_status_button(&self.state, state),1168
own_status_button(&self.state, state),1155
]1169
]1156
.into_iter()1170
.into_iter()1157
.flatten(),1171
.flatten()1172
.chain(crate::kvt::title_buttons(&self.notifications, window, cx)),1158
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),1173
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),1159
);1174
);1160
let shell = div()1175
let shell = div()@@ -1370,6 +1385,7 @@ impl Render for AppShell {1370
quick_view_open,1385
quick_view_open,1371
calls_open,1386
calls_open,1372
manage_team_open,1387
manage_team_open,1388
ponos_board,1373
),1389
),1374
&self.splash,1390
&self.splash,1375
cx,1391
cx,@@ -96,6 +96,10 @@ pub enum SidebarTab {
96
96
Calendar,
97
97
Calls,
98
98
Agents,
99
/// KVT-fork: Ponos-bord in het hoofdpaneel (`crate::kvt::board_view`).
100
Ponos,
101
/// KVT-fork: Asclepius-tickets in het hoofdpaneel (`crate::kvt::tickets_view`).
102
Asclepius,
99
103
}
100
104
101
105
impl SidebarTab {
@@ -107,6 +111,8 @@ impl SidebarTab {
107
111
SidebarTab::Calendar => tr("rail.calendar"),
108
112
SidebarTab::Calls => tr("rail.calls"),
109
113
SidebarTab::Agents => tr("rail.agents"),
114
SidebarTab::Ponos => tr("kvt.rail.ponos"),
115
SidebarTab::Asclepius => tr("kvt.rail.asclepius"),
110
116
}
111
117
}
112
118
}
@@ -549,6 +555,8 @@ impl SidebarView {
549
555
let activity = self.activity_panel.read(cx).activity();
550
556
activity.update(cx, |activity, cx| activity.mark_seen(cx));
551
557
}
558
SidebarTab::Ponos => crate::kvt::board_opened(cx),
559
SidebarTab::Asclepius => crate::kvt::tickets_opened(cx),
552
560
_ => {}
553
561
}
554
562
cx.notify();
@@ -583,7 +591,9 @@ impl SidebarView {
583
591
SidebarTab::Activity
584
592
| SidebarTab::Calendar
585
593
| SidebarTab::Calls
586
| SidebarTab::Agents => None,
594
| SidebarTab::Agents
595
| SidebarTab::Ponos
596
| SidebarTab::Asclepius => None,
587
597
};
588
598
if let Some(selection) = selection {
589
599
self.state
@@ -2146,7 +2156,10 @@ impl Render for SidebarView {
2146
2156
Some(panel) => panel.clone().into_any_element(),
2147
2157
None => div().into_any_element(),
2148
2158
},
2149
SidebarTab::Calls | SidebarTab::Calendar => div().into_any_element(),
2159
SidebarTab::Calls
2160
| SidebarTab::Calendar
2161
| SidebarTab::Ponos
2162
| SidebarTab::Asclepius => div().into_any_element(),
2150
2163
};
2151
2164
let header = match self.tab {
2152
2165
SidebarTab::Chats => Some(
@@ -2172,7 +2185,11 @@ impl Render for SidebarView {
2172
2185
.child(self.channel_filter_bar(cx)),
2173
2186
),
2174
2187
SidebarTab::Agents => Some(page_header(&self.tab.title())),
2175
SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Calendar => None,
2188
SidebarTab::Activity
2189
| SidebarTab::Calls
2190
| SidebarTab::Calendar
2191
| SidebarTab::Ponos
2192
| SidebarTab::Asclepius => None,
2176
2193
};
2177
2194
v_flex()
2178
2195
.debug_selector(|| "shell/islands/sidebar".into())
@@ -96,6 +96,10 @@ pub enum SidebarTab {96
Calendar,96
Calendar,97
Calls,97
Calls,98
Agents,98
Agents,99
/// KVT-fork: Ponos-bord in het hoofdpaneel (`crate::kvt::board_view`).100
Ponos,101
/// KVT-fork: Asclepius-tickets in het hoofdpaneel (`crate::kvt::tickets_view`).102
Asclepius,99
}103
}100
104
101
impl SidebarTab {105
impl SidebarTab {@@ -107,6 +111,8 @@ impl SidebarTab {107
SidebarTab::Calendar => tr("rail.calendar"),111
SidebarTab::Calendar => tr("rail.calendar"),108
SidebarTab::Calls => tr("rail.calls"),112
SidebarTab::Calls => tr("rail.calls"),109
SidebarTab::Agents => tr("rail.agents"),113
SidebarTab::Agents => tr("rail.agents"),114
SidebarTab::Ponos => tr("kvt.rail.ponos"),115
SidebarTab::Asclepius => tr("kvt.rail.asclepius"),110
}116
}111
}117
}112
}118
}@@ -549,6 +555,8 @@ impl SidebarView {549
let activity = self.activity_panel.read(cx).activity();555
let activity = self.activity_panel.read(cx).activity();550
activity.update(cx, |activity, cx| activity.mark_seen(cx));556
activity.update(cx, |activity, cx| activity.mark_seen(cx));551
}557
}558
SidebarTab::Ponos => crate::kvt::board_opened(cx),559
SidebarTab::Asclepius => crate::kvt::tickets_opened(cx),552
_ => {}560
_ => {}553
}561
}554
cx.notify();562
cx.notify();@@ -583,7 +591,9 @@ impl SidebarView {583
SidebarTab::Activity591
SidebarTab::Activity584
| SidebarTab::Calendar592
| SidebarTab::Calendar585
| SidebarTab::Calls593
| SidebarTab::Calls586
| SidebarTab::Agents => None,594
| SidebarTab::Agents595
| SidebarTab::Ponos596
| SidebarTab::Asclepius => None,587
};597
};588
if let Some(selection) = selection {598
if let Some(selection) = selection {589
self.state599
self.state@@ -2146,7 +2156,10 @@ impl Render for SidebarView {2146
Some(panel) => panel.clone().into_any_element(),2156
Some(panel) => panel.clone().into_any_element(),2147
None => div().into_any_element(),2157
None => div().into_any_element(),2148
},2158
},2149
SidebarTab::Calls | SidebarTab::Calendar => div().into_any_element(),2159
SidebarTab::Calls2160
| SidebarTab::Calendar2161
| SidebarTab::Ponos2162
| SidebarTab::Asclepius => div().into_any_element(),2150
};2163
};2151
let header = match self.tab {2164
let header = match self.tab {2152
SidebarTab::Chats => Some(2165
SidebarTab::Chats => Some(@@ -2172,7 +2185,11 @@ impl Render for SidebarView {2172
.child(self.channel_filter_bar(cx)),2185
.child(self.channel_filter_bar(cx)),2173
),2186
),2174
SidebarTab::Agents => Some(page_header(&self.tab.title())),2187
SidebarTab::Agents => Some(page_header(&self.tab.title())),2175
SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Calendar => None,2188
SidebarTab::Activity2189
| SidebarTab::Calls2190
| SidebarTab::Calendar2191
| SidebarTab::Ponos2192
| SidebarTab::Asclepius => None,2176
};2193
};2177
v_flex()2194
v_flex()2178
.debug_selector(|| "shell/islands/sidebar".into())2195
.debug_selector(|| "shell/islands/sidebar".into())@@ -307,6 +307,7 @@ impl RenderOnce for TitleBarRow {
307
307
.h(px(TITLE_BAR_HEIGHT))
308
308
.border_b_0()
309
309
.bg(theme::background())
310
.system_window_controls(crate::kvt::title_bar_system_window_controls(cx))
310
311
.child(row);
311
312
let on_search = self.on_search;
312
313
div()
@@ -307,6 +307,7 @@ impl RenderOnce for TitleBarRow {307
.h(px(TITLE_BAR_HEIGHT))307
.h(px(TITLE_BAR_HEIGHT))308
.border_b_0()308
.border_b_0()309
.bg(theme::background())309
.bg(theme::background())310
.system_window_controls(crate::kvt::title_bar_system_window_controls(cx))310
.child(row);311
.child(row);311
let on_search = self.on_search;312
let on_search = self.on_search;312
div()313
div()@@ -0,0 +1,387 @@
1
use serde::{Deserialize, Serialize};
2
use serde_json::Value;
3
use session::{Request, Session};
4
5
use crate::error::Result;
6
use crate::messages::ensure_success;
7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
use crate::reactions::CustomEmoji;
9
10
/// Official web client (2024): `GET /api/csa/{region}/api/v1/customemoji/metadata`
11
/// with the CSA bearer (`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`).
12
/// Optional `x-ms-continuation` asks for changes since the previous `continuationToken`.
13
/// We use the same path on `teams.cloud.microsoft` (the host of every other CSA call here)
14
/// and `DEFAULT_REGION` (`emea`). Live check: the host, the region, and the token audience.
15
const METADATA_PATH: &str = "customemoji/metadata";
16
const CONTINUATION_HEADER: &str = "x-ms-continuation";
17
const CUSTOM_CATEGORY: &str = "customEmoji";
18
const ITEMTYPE: &str = "http://schema.skype.com/CustomEmoji";
19
const DISPLAY_SIZE: u32 = 20;
20
21
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22
pub struct OrgEmoji {
23
pub id: String,
24
pub document_id: String,
25
pub name: String,
26
pub keywords: Vec<String>,
27
#[serde(default, skip_serializing_if = "Option::is_none")]
28
pub source: Option<String>,
29
}
30
31
impl OrgEmoji {
32
pub fn key(&self) -> String {
33
format!("{};{}", self.name, self.document_id)
34
}
35
36
pub fn image_url(&self) -> String {
37
if let Some(source) = &self.source {
38
return source.clone();
39
}
40
CustomEmoji {
41
name: self.name.clone(),
42
object_id: self.document_id.clone(),
43
}
44
.image_url()
45
}
46
47
pub fn html(&self) -> String {
48
custom_emoji_html(&self.name, &self.document_id, &self.image_url())
49
}
50
51
pub fn matches(&self, query: &str) -> bool {
52
let query = query.trim();
53
if query.is_empty() {
54
return true;
55
}
56
let query = query.to_ascii_lowercase();
57
self.name.to_ascii_lowercase().contains(&query)
58
|| self
59
.keywords
60
.iter()
61
.any(|keyword| keyword.to_ascii_lowercase().contains(&query))
62
}
63
}
64
65
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
66
pub struct OrgEmojiCatalog {
67
pub emojis: Vec<OrgEmoji>,
68
pub deleted_ids: Vec<String>,
69
pub continuation: Option<String>,
70
}
71
72
pub struct CustomEmojis<T: CsaTransport = SessionTransport> {
73
transport: T,
74
url: String,
75
}
76
77
impl CustomEmojis<SessionTransport> {
78
pub fn new(session: &Session) -> Self {
79
CustomEmojis::with_transport(SessionTransport::new(session), DEFAULT_REGION)
80
}
81
}
82
83
impl<T: CsaTransport> CustomEmojis<T> {
84
pub fn with_transport(transport: T, region: &str) -> Self {
85
CustomEmojis {
86
transport,
87
url: format!("https://teams.cloud.microsoft/api/csa/{region}/api/v1/{METADATA_PATH}"),
88
}
89
}
90
91
/// A request without `x-ms-continuation` returns the full catalogue.
92
pub async fn list(&self) -> Result<OrgEmojiCatalog> {
93
self.fetch(None).await
94
}
95
96
pub async fn list_since(&self, continuation: &str) -> Result<OrgEmojiCatalog> {
97
self.fetch(Some(continuation)).await
98
}
99
100
async fn fetch(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
101
let mut request = Request::get(&self.url);
102
if let Some(token) = continuation.map(str::trim).filter(|token| !token.is_empty()) {
103
request
104
.headers
105
.push((CONTINUATION_HEADER.to_owned(), token.to_owned()));
106
}
107
let answer = self.transport.send(request).await?;
108
ensure_success(&answer)?;
109
Ok(parse_metadata(&answer.body))
110
}
111
}
112
113
/// The HTML the official client accepts when a custom emoji is sent in a message.
114
pub fn custom_emoji_html(name: &str, object_id: &str, source: &str) -> String {
115
format!(
116
"<img alt=\"{alt}\" itemid=\"{itemid}\" itemtype=\"{ITEMTYPE}\" src=\"{src}\" width=\"{DISPLAY_SIZE}\" height=\"{DISPLAY_SIZE}\" style=\"width:{DISPLAY_SIZE}px;height:{DISPLAY_SIZE}px;\">",
117
alt = escape_attr(name),
118
itemid = escape_attr(&format!("{name};{object_id}")),
119
src = escape_attr(source),
120
)
121
}
122
123
pub fn parse_metadata(body: &Value) -> OrgEmojiCatalog {
124
let continuation = continuation_token(body.get("continuationToken"));
125
let mut emojis = Vec::new();
126
let mut deleted_ids = Vec::new();
127
let entries = body
128
.get("categories")
129
.and_then(Value::as_array)
130
.into_iter()
131
.flatten()
132
.filter(|category| category.get("id").and_then(Value::as_str) == Some(CUSTOM_CATEGORY))
133
.flat_map(|category| {
134
category
135
.get("emoticons")
136
.and_then(Value::as_array)
137
.into_iter()
138
.flatten()
139
});
140
for entry in entries {
141
match parse_emoticon(entry) {
142
ParsedEmoticon::Live(emoji) => emojis.push(emoji),
143
ParsedEmoticon::Deleted(id) => deleted_ids.push(id),
144
ParsedEmoticon::Skip => {}
145
}
146
}
147
OrgEmojiCatalog {
148
emojis,
149
deleted_ids,
150
continuation,
151
}
152
}
153
154
/// Apply a delta (or a full list) to a previously cached catalogue.
155
pub fn merge_catalog(previous: &[OrgEmoji], incoming: OrgEmojiCatalog, full: bool) -> OrgEmojiCatalog {
156
if full {
157
return incoming;
158
}
159
let mut by_id: std::collections::HashMap<String, OrgEmoji> = previous
160
.iter()
161
.cloned()
162
.map(|emoji| (emoji.id.clone(), emoji))
163
.collect();
164
for id in &incoming.deleted_ids {
165
by_id.remove(id);
166
}
167
for emoji in incoming.emojis {
168
by_id.insert(emoji.id.clone(), emoji);
169
}
170
let mut emojis: Vec<OrgEmoji> = by_id.into_values().collect();
171
emojis.sort_by(|left, right| left.name.cmp(&right.name).then(left.id.cmp(&right.id)));
172
OrgEmojiCatalog {
173
emojis,
174
deleted_ids: Vec::new(),
175
continuation: incoming.continuation,
176
}
177
}
178
179
enum ParsedEmoticon {
180
Live(OrgEmoji),
181
Deleted(String),
182
Skip,
183
}
184
185
fn parse_emoticon(entry: &Value) -> ParsedEmoticon {
186
let id = entry
187
.get("id")
188
.and_then(Value::as_str)
189
.map(str::trim)
190
.filter(|id| !id.is_empty())
191
.map(str::to_owned);
192
if entry.get("isDeleted").and_then(Value::as_bool) == Some(true) {
193
return id.map(ParsedEmoticon::Deleted).unwrap_or(ParsedEmoticon::Skip);
194
}
195
let Some(document_id) = entry
196
.get("documentId")
197
.and_then(Value::as_str)
198
.map(str::trim)
199
.filter(|id| crate::links::is_ams_object_id(id))
200
else {
201
return ParsedEmoticon::Skip;
202
};
203
let Some(name) = entry
204
.get("shortcuts")
205
.and_then(Value::as_array)
206
.into_iter()
207
.flatten()
208
.filter_map(Value::as_str)
209
.map(str::trim)
210
.find(|name| !name.is_empty())
211
.or_else(|| {
212
entry
213
.get("description")
214
.and_then(Value::as_str)
215
.map(str::trim)
216
.filter(|name| !name.is_empty())
217
})
218
.map(str::to_owned)
219
else {
220
return ParsedEmoticon::Skip;
221
};
222
let keywords = entry
223
.get("keywords")
224
.and_then(Value::as_array)
225
.into_iter()
226
.flatten()
227
.filter_map(Value::as_str)
228
.map(str::trim)
229
.filter(|keyword| !keyword.is_empty())
230
.map(str::to_owned)
231
.collect();
232
ParsedEmoticon::Live(OrgEmoji {
233
id: id.unwrap_or_else(|| document_id.to_owned()),
234
document_id: document_id.to_owned(),
235
name,
236
keywords,
237
source: None,
238
})
239
}
240
241
fn continuation_token(value: Option<&Value>) -> Option<String> {
242
match value {
243
Some(Value::String(text)) => Some(text.clone()).filter(|text| !text.is_empty()),
244
Some(Value::Number(number)) => Some(number.to_string()),
245
_ => None,
246
}
247
}
248
249
fn escape_attr(value: &str) -> String {
250
value
251
.replace('&', "&")
252
.replace('<', "<")
253
.replace('>', ">")
254
.replace('"', """)
255
}
256
257
#[cfg(test)]
258
mod tests {
259
use std::sync::Mutex;
260
261
use serde_json::Value;
262
use session::{ApiResponse, Method};
263
264
use super::*;
265
266
struct Canned {
267
body: Value,
268
requests: Mutex<Vec<Request>>,
269
}
270
271
impl CsaTransport for &Canned {
272
async fn send(&self, request: Request) -> Result<ApiResponse> {
273
self.requests.lock().unwrap().push(request);
274
Ok(ApiResponse {
275
status: 200,
276
body: self.body.clone(),
277
retry_after: None,
278
})
279
}
280
}
281
282
fn fixture() -> Value {
283
serde_json::from_str(include_str!("../tests/fixtures/custom_emoji_metadata.json")).unwrap()
284
}
285
286
#[test]
287
fn metadata_keeps_live_emoticons_and_skips_deleted_or_unsafe_ids() {
288
let catalog = parse_metadata(&fixture());
289
assert_eq!(catalog.continuation.as_deref(), Some("42"));
290
let names: Vec<&str> = catalog.emojis.iter().map(|emoji| emoji.name.as_str()).collect();
291
assert_eq!(names, ["absolute-cinema", "tsignal"]);
292
assert!(catalog.emojis.iter().all(|emoji| crate::links::is_ams_object_id(&emoji.document_id)));
293
assert!(catalog.emojis[0].matches("cinema"));
294
assert!(catalog.emojis[0].matches("movie"));
295
assert!(!catalog.emojis[0].matches("tsignal"));
296
assert_eq!(catalog.deleted_ids, ["em-gone"]);
297
}
298
299
#[test]
300
fn merge_catalog_removes_deleted_ids_and_keeps_the_rest() {
301
let previous = vec![
302
OrgEmoji {
303
id: "em-1".into(),
304
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),
305
name: "absolute-cinema".into(),
306
keywords: vec!["cinema".into()],
307
source: None,
308
},
309
OrgEmoji {
310
id: "em-gone".into(),
311
document_id: "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef".into(),
312
name: "old-one".into(),
313
keywords: vec![],
314
source: None,
315
},
316
];
317
let incoming = OrgEmojiCatalog {
318
emojis: vec![OrgEmoji {
319
id: "em-2".into(),
320
document_id: "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853".into(),
321
name: "tsignal".into(),
322
keywords: vec!["tsignal".into()],
323
source: None,
324
}],
325
deleted_ids: vec!["em-gone".into()],
326
continuation: Some("43".into()),
327
};
328
let merged = merge_catalog(&previous, incoming, false);
329
let names: Vec<&str> = merged.emojis.iter().map(|emoji| emoji.name.as_str()).collect();
330
assert_eq!(names, ["absolute-cinema", "tsignal"]);
331
assert!(merged.deleted_ids.is_empty());
332
assert_eq!(merged.continuation.as_deref(), Some("43"));
333
}
334
335
#[test]
336
fn html_names_the_custom_emoji_itemtype_and_itemid() {
337
let html = custom_emoji_html(
338
"say \"hi\" & <wave>",
339
"0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",
340
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim",
341
);
342
assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));
343
assert!(html.contains("itemid=\"say "hi" & <wave>;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));
344
assert!(html.contains("alt=\"say "hi" & <wave>\""));
345
assert!(html.contains("width=\"20\" height=\"20\""));
346
assert!(html.contains("style=\"width:20px;height:20px;\""));
347
assert!(html.contains("/views/imgt2_anim"));
348
}
349
350
#[tokio::test]
351
async fn list_uses_the_csa_metadata_path_and_omits_continuation_for_a_full_fetch() {
352
let transport = Canned {
353
body: fixture(),
354
requests: Mutex::new(Vec::new()),
355
};
356
let client = CustomEmojis::with_transport(&transport, "emea");
357
let catalog = client.list().await.unwrap();
358
assert_eq!(catalog.emojis.len(), 2);
359
let sent = transport.requests.lock().unwrap();
360
assert_eq!(
361
sent[0].url,
362
"https://teams.cloud.microsoft/api/csa/emea/api/v1/customemoji/metadata"
363
);
364
assert_eq!(sent[0].method, Method::Get);
365
assert!(
366
sent[0]
367
.headers
368
.iter()
369
.all(|(name, _)| name != CONTINUATION_HEADER)
370
);
371
}
372
373
#[tokio::test]
374
async fn list_since_sends_the_continuation_header() {
375
let transport = Canned {
376
body: fixture(),
377
requests: Mutex::new(Vec::new()),
378
};
379
let client = CustomEmojis::with_transport(&transport, "emea");
380
client.list_since("42").await.unwrap();
381
let sent = transport.requests.lock().unwrap();
382
assert_eq!(
383
sent[0].headers,
384
vec![(CONTINUATION_HEADER.to_owned(), "42".to_owned())]
385
);
386
}
387
}
@@ -0,0 +1,387 @@1
use serde::{Deserialize, Serialize};2
use serde_json::Value;3
use session::{Request, Session};4
5
use crate::error::Result;6
use crate::messages::ensure_success;7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};8
use crate::reactions::CustomEmoji;9
10
/// Official web client (2024): `GET /api/csa/{region}/api/v1/customemoji/metadata`11
/// with the CSA bearer (`https://chatsvcagg.teams.microsoft.com`, `user_impersonation`).12
/// Optional `x-ms-continuation` asks for changes since the previous `continuationToken`.13
/// We use the same path on `teams.cloud.microsoft` (the host of every other CSA call here)14
/// and `DEFAULT_REGION` (`emea`). Live check: the host, the region, and the token audience.15
const METADATA_PATH: &str = "customemoji/metadata";16
const CONTINUATION_HEADER: &str = "x-ms-continuation";17
const CUSTOM_CATEGORY: &str = "customEmoji";18
const ITEMTYPE: &str = "http://schema.skype.com/CustomEmoji";19
const DISPLAY_SIZE: u32 = 20;20
21
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]22
pub struct OrgEmoji {23
pub id: String,24
pub document_id: String,25
pub name: String,26
pub keywords: Vec<String>,27
#[serde(default, skip_serializing_if = "Option::is_none")]28
pub source: Option<String>,29
}30
31
impl OrgEmoji {32
pub fn key(&self) -> String {33
format!("{};{}", self.name, self.document_id)34
}35
36
pub fn image_url(&self) -> String {37
if let Some(source) = &self.source {38
return source.clone();39
}40
CustomEmoji {41
name: self.name.clone(),42
object_id: self.document_id.clone(),43
}44
.image_url()45
}46
47
pub fn html(&self) -> String {48
custom_emoji_html(&self.name, &self.document_id, &self.image_url())49
}50
51
pub fn matches(&self, query: &str) -> bool {52
let query = query.trim();53
if query.is_empty() {54
return true;55
}56
let query = query.to_ascii_lowercase();57
self.name.to_ascii_lowercase().contains(&query)58
|| self59
.keywords60
.iter()61
.any(|keyword| keyword.to_ascii_lowercase().contains(&query))62
}63
}64
65
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]66
pub struct OrgEmojiCatalog {67
pub emojis: Vec<OrgEmoji>,68
pub deleted_ids: Vec<String>,69
pub continuation: Option<String>,70
}71
72
pub struct CustomEmojis<T: CsaTransport = SessionTransport> {73
transport: T,74
url: String,75
}76
77
impl CustomEmojis<SessionTransport> {78
pub fn new(session: &Session) -> Self {79
CustomEmojis::with_transport(SessionTransport::new(session), DEFAULT_REGION)80
}81
}82
83
impl<T: CsaTransport> CustomEmojis<T> {84
pub fn with_transport(transport: T, region: &str) -> Self {85
CustomEmojis {86
transport,87
url: format!("https://teams.cloud.microsoft/api/csa/{region}/api/v1/{METADATA_PATH}"),88
}89
}90
91
/// A request without `x-ms-continuation` returns the full catalogue.92
pub async fn list(&self) -> Result<OrgEmojiCatalog> {93
self.fetch(None).await94
}95
96
pub async fn list_since(&self, continuation: &str) -> Result<OrgEmojiCatalog> {97
self.fetch(Some(continuation)).await98
}99
100
async fn fetch(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {101
let mut request = Request::get(&self.url);102
if let Some(token) = continuation.map(str::trim).filter(|token| !token.is_empty()) {103
request104
.headers105
.push((CONTINUATION_HEADER.to_owned(), token.to_owned()));106
}107
let answer = self.transport.send(request).await?;108
ensure_success(&answer)?;109
Ok(parse_metadata(&answer.body))110
}111
}112
113
/// The HTML the official client accepts when a custom emoji is sent in a message.114
pub fn custom_emoji_html(name: &str, object_id: &str, source: &str) -> String {115
format!(116
"<img alt=\"{alt}\" itemid=\"{itemid}\" itemtype=\"{ITEMTYPE}\" src=\"{src}\" width=\"{DISPLAY_SIZE}\" height=\"{DISPLAY_SIZE}\" style=\"width:{DISPLAY_SIZE}px;height:{DISPLAY_SIZE}px;\">",117
alt = escape_attr(name),118
itemid = escape_attr(&format!("{name};{object_id}")),119
src = escape_attr(source),120
)121
}122
123
pub fn parse_metadata(body: &Value) -> OrgEmojiCatalog {124
let continuation = continuation_token(body.get("continuationToken"));125
let mut emojis = Vec::new();126
let mut deleted_ids = Vec::new();127
let entries = body128
.get("categories")129
.and_then(Value::as_array)130
.into_iter()131
.flatten()132
.filter(|category| category.get("id").and_then(Value::as_str) == Some(CUSTOM_CATEGORY))133
.flat_map(|category| {134
category135
.get("emoticons")136
.and_then(Value::as_array)137
.into_iter()138
.flatten()139
});140
for entry in entries {141
match parse_emoticon(entry) {142
ParsedEmoticon::Live(emoji) => emojis.push(emoji),143
ParsedEmoticon::Deleted(id) => deleted_ids.push(id),144
ParsedEmoticon::Skip => {}145
}146
}147
OrgEmojiCatalog {148
emojis,149
deleted_ids,150
continuation,151
}152
}153
154
/// Apply a delta (or a full list) to a previously cached catalogue.155
pub fn merge_catalog(previous: &[OrgEmoji], incoming: OrgEmojiCatalog, full: bool) -> OrgEmojiCatalog {156
if full {157
return incoming;158
}159
let mut by_id: std::collections::HashMap<String, OrgEmoji> = previous160
.iter()161
.cloned()162
.map(|emoji| (emoji.id.clone(), emoji))163
.collect();164
for id in &incoming.deleted_ids {165
by_id.remove(id);166
}167
for emoji in incoming.emojis {168
by_id.insert(emoji.id.clone(), emoji);169
}170
let mut emojis: Vec<OrgEmoji> = by_id.into_values().collect();171
emojis.sort_by(|left, right| left.name.cmp(&right.name).then(left.id.cmp(&right.id)));172
OrgEmojiCatalog {173
emojis,174
deleted_ids: Vec::new(),175
continuation: incoming.continuation,176
}177
}178
179
enum ParsedEmoticon {180
Live(OrgEmoji),181
Deleted(String),182
Skip,183
}184
185
fn parse_emoticon(entry: &Value) -> ParsedEmoticon {186
let id = entry187
.get("id")188
.and_then(Value::as_str)189
.map(str::trim)190
.filter(|id| !id.is_empty())191
.map(str::to_owned);192
if entry.get("isDeleted").and_then(Value::as_bool) == Some(true) {193
return id.map(ParsedEmoticon::Deleted).unwrap_or(ParsedEmoticon::Skip);194
}195
let Some(document_id) = entry196
.get("documentId")197
.and_then(Value::as_str)198
.map(str::trim)199
.filter(|id| crate::links::is_ams_object_id(id))200
else {201
return ParsedEmoticon::Skip;202
};203
let Some(name) = entry204
.get("shortcuts")205
.and_then(Value::as_array)206
.into_iter()207
.flatten()208
.filter_map(Value::as_str)209
.map(str::trim)210
.find(|name| !name.is_empty())211
.or_else(|| {212
entry213
.get("description")214
.and_then(Value::as_str)215
.map(str::trim)216
.filter(|name| !name.is_empty())217
})218
.map(str::to_owned)219
else {220
return ParsedEmoticon::Skip;221
};222
let keywords = entry223
.get("keywords")224
.and_then(Value::as_array)225
.into_iter()226
.flatten()227
.filter_map(Value::as_str)228
.map(str::trim)229
.filter(|keyword| !keyword.is_empty())230
.map(str::to_owned)231
.collect();232
ParsedEmoticon::Live(OrgEmoji {233
id: id.unwrap_or_else(|| document_id.to_owned()),234
document_id: document_id.to_owned(),235
name,236
keywords,237
source: None,238
})239
}240
241
fn continuation_token(value: Option<&Value>) -> Option<String> {242
match value {243
Some(Value::String(text)) => Some(text.clone()).filter(|text| !text.is_empty()),244
Some(Value::Number(number)) => Some(number.to_string()),245
_ => None,246
}247
}248
249
fn escape_attr(value: &str) -> String {250
value251
.replace('&', "&")252
.replace('<', "<")253
.replace('>', ">")254
.replace('"', """)255
}256
257
#[cfg(test)]258
mod tests {259
use std::sync::Mutex;260
261
use serde_json::Value;262
use session::{ApiResponse, Method};263
264
use super::*;265
266
struct Canned {267
body: Value,268
requests: Mutex<Vec<Request>>,269
}270
271
impl CsaTransport for &Canned {272
async fn send(&self, request: Request) -> Result<ApiResponse> {273
self.requests.lock().unwrap().push(request);274
Ok(ApiResponse {275
status: 200,276
body: self.body.clone(),277
retry_after: None,278
})279
}280
}281
282
fn fixture() -> Value {283
serde_json::from_str(include_str!("../tests/fixtures/custom_emoji_metadata.json")).unwrap()284
}285
286
#[test]287
fn metadata_keeps_live_emoticons_and_skips_deleted_or_unsafe_ids() {288
let catalog = parse_metadata(&fixture());289
assert_eq!(catalog.continuation.as_deref(), Some("42"));290
let names: Vec<&str> = catalog.emojis.iter().map(|emoji| emoji.name.as_str()).collect();291
assert_eq!(names, ["absolute-cinema", "tsignal"]);292
assert!(catalog.emojis.iter().all(|emoji| crate::links::is_ams_object_id(&emoji.document_id)));293
assert!(catalog.emojis[0].matches("cinema"));294
assert!(catalog.emojis[0].matches("movie"));295
assert!(!catalog.emojis[0].matches("tsignal"));296
assert_eq!(catalog.deleted_ids, ["em-gone"]);297
}298
299
#[test]300
fn merge_catalog_removes_deleted_ids_and_keeps_the_rest() {301
let previous = vec![302
OrgEmoji {303
id: "em-1".into(),304
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".into(),305
name: "absolute-cinema".into(),306
keywords: vec!["cinema".into()],307
source: None,308
},309
OrgEmoji {310
id: "em-gone".into(),311
document_id: "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef".into(),312
name: "old-one".into(),313
keywords: vec![],314
source: None,315
},316
];317
let incoming = OrgEmojiCatalog {318
emojis: vec![OrgEmoji {319
id: "em-2".into(),320
document_id: "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853".into(),321
name: "tsignal".into(),322
keywords: vec!["tsignal".into()],323
source: None,324
}],325
deleted_ids: vec!["em-gone".into()],326
continuation: Some("43".into()),327
};328
let merged = merge_catalog(&previous, incoming, false);329
let names: Vec<&str> = merged.emojis.iter().map(|emoji| emoji.name.as_str()).collect();330
assert_eq!(names, ["absolute-cinema", "tsignal"]);331
assert!(merged.deleted_ids.is_empty());332
assert_eq!(merged.continuation.as_deref(), Some("43"));333
}334
335
#[test]336
fn html_names_the_custom_emoji_itemtype_and_itemid() {337
let html = custom_emoji_html(338
"say \"hi\" & <wave>",339
"0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",340
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim",341
);342
assert!(html.contains("itemtype=\"http://schema.skype.com/CustomEmoji\""));343
assert!(html.contains("itemid=\"say "hi" & <wave>;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8\""));344
assert!(html.contains("alt=\"say "hi" & <wave>\""));345
assert!(html.contains("width=\"20\" height=\"20\""));346
assert!(html.contains("style=\"width:20px;height:20px;\""));347
assert!(html.contains("/views/imgt2_anim"));348
}349
350
#[tokio::test]351
async fn list_uses_the_csa_metadata_path_and_omits_continuation_for_a_full_fetch() {352
let transport = Canned {353
body: fixture(),354
requests: Mutex::new(Vec::new()),355
};356
let client = CustomEmojis::with_transport(&transport, "emea");357
let catalog = client.list().await.unwrap();358
assert_eq!(catalog.emojis.len(), 2);359
let sent = transport.requests.lock().unwrap();360
assert_eq!(361
sent[0].url,362
"https://teams.cloud.microsoft/api/csa/emea/api/v1/customemoji/metadata"363
);364
assert_eq!(sent[0].method, Method::Get);365
assert!(366
sent[0]367
.headers368
.iter()369
.all(|(name, _)| name != CONTINUATION_HEADER)370
);371
}372
373
#[tokio::test]374
async fn list_since_sends_the_continuation_header() {375
let transport = Canned {376
body: fixture(),377
requests: Mutex::new(Vec::new()),378
};379
let client = CustomEmojis::with_transport(&transport, "emea");380
client.list_since("42").await.unwrap();381
let sent = transport.requests.lock().unwrap();382
assert_eq!(383
sent[0].headers,384
vec![(CONTINUATION_HEADER.to_owned(), "42".to_owned())]385
);386
}387
}@@ -14,6 +14,7 @@ pub mod chat_settings;
14
14
pub mod compose_copilot;
15
15
pub mod conversations;
16
16
pub mod copilot;
17
pub mod custom_emojis;
17
18
pub mod drafts;
18
19
pub mod emotions;
19
20
mod error;
@@ -87,6 +88,7 @@ pub use drafts::{ScheduledDraft, ScheduledDrafts};
87
88
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
88
89
pub use error::{Error, Result};
89
90
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
91
pub use custom_emojis::{CustomEmojis, OrgEmoji, OrgEmojiCatalog, custom_emoji_html, merge_catalog, parse_metadata};
90
92
pub use gifs::{Gif, Gifs};
91
93
pub use google_calendar::{
92
94
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,
@@ -104,7 +106,7 @@ pub use language_settings::{
104
106
};
105
107
pub use links::{
106
108
LinkImage, LinkInfo, MessageLinks, ams_full_size_url, hosted_content_image_url,
107
is_ams_image_url, is_link_image_url,
109
hosted_content_object_id, is_ams_image_url, is_link_image_url,
108
110
};
109
111
pub use mask::mask_conversation_id;
110
112
pub use members::{
@@ -123,7 +125,8 @@ pub use presence::{
123
125
error_status, is_endpoint_missing,
124
126
};
125
127
pub use reactions::{
126
CustomEmoji, custom_emoji, emotion_glyph, emotion_key, emotion_keys, insert_skin_tone,
128
CustomEmoji, custom_emoji, custom_emoji_display_name, custom_reaction_key, emotion_glyph,
129
emotion_key, emotion_keys, hides_raw_reaction_key, insert_skin_tone, is_custom_reaction_type,
127
130
reaction_glyph_for_key, reaction_key, reaction_keys,
128
131
};
129
132
pub use read_horizon::ReadHorizon;
@@ -14,6 +14,7 @@ pub mod chat_settings;14
pub mod compose_copilot;14
pub mod compose_copilot;15
pub mod conversations;15
pub mod conversations;16
pub mod copilot;16
pub mod copilot;17
pub mod custom_emojis;17
pub mod drafts;18
pub mod drafts;18
pub mod emotions;19
pub mod emotions;19
mod error;20
mod error;@@ -87,6 +88,7 @@ pub use drafts::{ScheduledDraft, ScheduledDrafts};87
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};88
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};88
pub use error::{Error, Result};89
pub use error::{Error, Result};89
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};90
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};91
pub use custom_emojis::{CustomEmojis, OrgEmoji, OrgEmojiCatalog, custom_emoji_html, merge_catalog, parse_metadata};90
pub use gifs::{Gif, Gifs};92
pub use gifs::{Gif, Gifs};91
pub use google_calendar::{93
pub use google_calendar::{92
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,94
AuthPending, GoogleCalendar, GoogleEventDraft, GoogleOAuth, TokenBundle, allocate_redirect_uri,@@ -104,7 +106,7 @@ pub use language_settings::{104
};106
};105
pub use links::{107
pub use links::{106
LinkImage, LinkInfo, MessageLinks, ams_full_size_url, hosted_content_image_url,108
LinkImage, LinkInfo, MessageLinks, ams_full_size_url, hosted_content_image_url,107
is_ams_image_url, is_link_image_url,109
hosted_content_object_id, is_ams_image_url, is_link_image_url,108
};110
};109
pub use mask::mask_conversation_id;111
pub use mask::mask_conversation_id;110
pub use members::{112
pub use members::{@@ -123,7 +125,8 @@ pub use presence::{123
error_status, is_endpoint_missing,125
error_status, is_endpoint_missing,124
};126
};125
pub use reactions::{127
pub use reactions::{126
CustomEmoji, custom_emoji, emotion_glyph, emotion_key, emotion_keys, insert_skin_tone,128
CustomEmoji, custom_emoji, custom_emoji_display_name, custom_reaction_key, emotion_glyph,129
emotion_key, emotion_keys, hides_raw_reaction_key, insert_skin_tone, is_custom_reaction_type,127
reaction_glyph_for_key, reaction_key, reaction_keys,130
reaction_glyph_for_key, reaction_key, reaction_keys,128
};131
};129
pub use read_horizon::ReadHorizon;132
pub use read_horizon::ReadHorizon;@@ -48,6 +48,21 @@ pub fn is_link_image_url(url: &str) -> bool {
48
48
49
49
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.
50
50
pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
51
let (_, url) = hosted_content_fields(graph_url)?;
52
(is_link_image_url(&url) || is_ams_image_url(&url)).then_some(url)
53
}
54
55
/// The `id=` value from a Graph `hostedContents` link, used when `url=` is empty
56
/// (custom emoji reactions).
57
pub fn hosted_content_object_id(graph_url: &str) -> Option<String> {
58
let (id, url) = hosted_content_fields(graph_url)?;
59
if is_ams_object_id(&id) {
60
return Some(id);
61
}
62
object_id_from_ams_path(&url).map(str::to_owned)
63
}
64
65
fn hosted_content_fields(graph_url: &str) -> Option<(String, String)> {
51
66
let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?;
52
67
let encoded = after.split('/').next()?;
53
68
let bytes = STANDARD
@@ -55,8 +70,31 @@ pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
55
70
.or_else(|_| URL_SAFE_NO_PAD.decode(encoded))
56
71
.ok()?;
57
72
let decoded = String::from_utf8(bytes).ok()?;
58
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;
59
(is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned())
73
let id = decoded
74
.strip_prefix("id=")?
75
.split(',')
76
.next()
77
.filter(|id| !id.is_empty())?
78
.to_owned();
79
let url = decoded
80
.split_once(HOSTED_URL_KEY)
81
.map(|(_, url)| url.to_owned())
82
.unwrap_or_default();
83
Some((id, url))
84
}
85
86
pub(crate) fn is_ams_object_id(object_id: &str) -> bool {
87
!object_id.is_empty()
88
&& object_id.contains('-')
89
&& object_id
90
.chars()
91
.all(|character| character.is_ascii_alphanumeric() || character == '-')
92
}
93
94
pub(crate) fn object_id_from_ams_path(url: &str) -> Option<&str> {
95
let path = url.split_once("/v1/objects/")?.1;
96
let id = path.split(['/', '?', '#']).next()?;
97
is_ams_object_id(id).then_some(id)
60
98
}
61
99
62
100
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.
@@ -229,6 +267,21 @@ mod tests {
229
267
);
230
268
}
231
269
270
#[test]
271
fn custom_emoji_hosted_content_ids_carry_the_object_id_when_url_is_empty() {
272
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";
273
let id = STANDARD.encode(format!("id={object_id},type=1,url="));
274
let graph = format!(
275
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value"
276
);
277
assert_eq!(hosted_content_image_url(&graph), None);
278
assert_eq!(hosted_content_object_id(&graph).as_deref(), Some(object_id));
279
assert_eq!(
280
hosted_content_object_id("https://example.com/not-hosted"),
281
None
282
);
283
}
284
232
285
#[test]
233
286
fn ams_object_views_are_recognized_inside_hosted_content_ids() {
234
287
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 {48
48
49
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.49
/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.50
pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {50
pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {51
let (_, url) = hosted_content_fields(graph_url)?;52
(is_link_image_url(&url) || is_ams_image_url(&url)).then_some(url)53
}54
55
/// The `id=` value from a Graph `hostedContents` link, used when `url=` is empty56
/// (custom emoji reactions).57
pub fn hosted_content_object_id(graph_url: &str) -> Option<String> {58
let (id, url) = hosted_content_fields(graph_url)?;59
if is_ams_object_id(&id) {60
return Some(id);61
}62
object_id_from_ams_path(&url).map(str::to_owned)63
}64
65
fn hosted_content_fields(graph_url: &str) -> Option<(String, String)> {51
let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?;66
let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?;52
let encoded = after.split('/').next()?;67
let encoded = after.split('/').next()?;53
let bytes = STANDARD68
let bytes = STANDARD@@ -55,8 +70,31 @@ pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {55
.or_else(|_| URL_SAFE_NO_PAD.decode(encoded))70
.or_else(|_| URL_SAFE_NO_PAD.decode(encoded))56
.ok()?;71
.ok()?;57
let decoded = String::from_utf8(bytes).ok()?;72
let decoded = String::from_utf8(bytes).ok()?;58
let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;73
let id = decoded59
(is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned())74
.strip_prefix("id=")?75
.split(',')76
.next()77
.filter(|id| !id.is_empty())?78
.to_owned();79
let url = decoded80
.split_once(HOSTED_URL_KEY)81
.map(|(_, url)| url.to_owned())82
.unwrap_or_default();83
Some((id, url))84
}85
86
pub(crate) fn is_ams_object_id(object_id: &str) -> bool {87
!object_id.is_empty()88
&& object_id.contains('-')89
&& object_id90
.chars()91
.all(|character| character.is_ascii_alphanumeric() || character == '-')92
}93
94
pub(crate) fn object_id_from_ams_path(url: &str) -> Option<&str> {95
let path = url.split_once("/v1/objects/")?.1;96
let id = path.split(['/', '?', '#']).next()?;97
is_ams_object_id(id).then_some(id)60
}98
}61
99
62
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.100
/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.@@ -229,6 +267,21 @@ mod tests {229
);267
);230
}268
}231
269
270
#[test]271
fn custom_emoji_hosted_content_ids_carry_the_object_id_when_url_is_empty() {272
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";273
let id = STANDARD.encode(format!("id={object_id},type=1,url="));274
let graph = format!(275
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value"276
);277
assert_eq!(hosted_content_image_url(&graph), None);278
assert_eq!(hosted_content_object_id(&graph).as_deref(), Some(object_id));279
assert_eq!(280
hosted_content_object_id("https://example.com/not-hosted"),281
None282
);283
}284
232
#[test]285
#[test]233
fn ams_object_views_are_recognized_inside_hosted_content_ids() {286
fn ams_object_views_are_recognized_inside_hosted_content_ids() {234
let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo";287
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> {
145
145
emotion_keys(glyph).first().copied()
146
146
}
147
147
148
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149
pub struct CustomEmoji<'a> {
150
pub name: &'a str,
151
pub object_id: &'a str,
148
const CUSTOM_TYPE: &str = "custom";
149
const CUSTOM_UNDERSCORE: &str = "custom_";
150
const CUSTOM_COLON: &str = "custom:";
151
152
#[derive(Debug, Clone, PartialEq, Eq)]
153
pub struct CustomEmoji {
154
pub name: String,
155
pub object_id: String,
152
156
}
153
157
154
impl CustomEmoji<'_> {
158
impl CustomEmoji {
159
pub fn key(&self) -> String {
160
format!("{}{CUSTOM_EMOJI_SEPARATOR}{}", self.name, self.object_id)
161
}
162
155
163
pub fn image_url(&self) -> String {
156
164
format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id)
157
165
}
166
167
/// The name to show in a tooltip or as `:name:`. `None` when we only have a placeholder.
168
pub fn display_name(&self) -> Option<&str> {
169
let name = self.name.trim();
170
(!name.is_empty() && !name.eq_ignore_ascii_case(CUSTOM_TYPE)).then_some(name)
171
}
158
172
}
159
173
160
/// `absolute-cinema;0-wcde-d3-5f5e...`: an org emoji, name and AMS object of its image.
161
pub fn custom_emoji(key: &str) -> Option<CustomEmoji<'_>> {
162
let (name, object_id) = key.split_once(CUSTOM_EMOJI_SEPARATOR)?;
163
let valid_object = !object_id.is_empty()
164
&& object_id
165
.chars()
166
.all(|character| character.is_ascii_alphanumeric() || character == '-');
167
(!name.is_empty() && valid_object).then_some(CustomEmoji { name, object_id })
174
/// An org custom emoji hidden in a reaction key.
175
///
176
/// Known shapes:
177
/// - `name;objectId` (chat service emotions)
178
/// - a Graph `hostedContents/...` URL whose id is `id={objectId},type=1,url=`
179
/// - an AMS object URL
180
/// - `custom_{objectId}` or a bare object id
181
pub fn custom_emoji(key: &str) -> Option<CustomEmoji> {
182
let key = key.trim();
183
if let Some((name, object_id)) = key.split_once(CUSTOM_EMOJI_SEPARATOR) {
184
let object_id = object_id
185
.split([CUSTOM_EMOJI_SEPARATOR, '|'])
186
.next()
187
.unwrap_or(object_id)
188
.trim();
189
let name = name
190
.strip_prefix(CUSTOM_UNDERSCORE)
191
.or_else(|| name.strip_prefix(CUSTOM_COLON))
192
.unwrap_or(name)
193
.trim();
194
if !name.is_empty() && crate::links::is_ams_object_id(object_id) {
195
return Some(CustomEmoji {
196
name: name.to_owned(),
197
object_id: object_id.to_owned(),
198
});
199
}
200
}
201
if let Some(object_id) = crate::links::hosted_content_object_id(key) {
202
return Some(CustomEmoji {
203
name: CUSTOM_TYPE.to_owned(),
204
object_id,
205
});
206
}
207
if let Some(object_id) = crate::links::object_id_from_ams_path(key) {
208
return Some(CustomEmoji {
209
name: CUSTOM_TYPE.to_owned(),
210
object_id: object_id.to_owned(),
211
});
212
}
213
if let Some(object_id) = key
214
.strip_prefix(CUSTOM_UNDERSCORE)
215
.or_else(|| key.strip_prefix(CUSTOM_COLON))
216
.map(str::trim)
217
.filter(|id| crate::links::is_ams_object_id(id))
218
{
219
return Some(CustomEmoji {
220
name: CUSTOM_TYPE.to_owned(),
221
object_id: object_id.to_owned(),
222
});
223
}
224
crate::links::is_ams_object_id(key).then(|| CustomEmoji {
225
name: CUSTOM_TYPE.to_owned(),
226
object_id: key.to_owned(),
227
})
228
}
229
230
/// Canonical `name;objectId` key from a Graph (or mixed) custom reaction payload.
231
///
232
/// Graph stores `reactionType: "custom"` with the name and image in `displayName`
233
/// and `reactionContentUrl`. Returns `None` when this is not a custom reaction.
234
pub fn custom_reaction_key(
235
reaction_type: &str,
236
display_name: Option<&str>,
237
content_url: Option<&str>,
238
reaction_id: Option<&str>,
239
) -> Option<String> {
240
let display_name = display_name.map(str::trim).filter(|name| !name.is_empty());
241
if let Some(emoji) = custom_emoji(reaction_type) {
242
let name = display_name
243
.or_else(|| emoji.display_name())
244
.unwrap_or(&emoji.name);
245
return Some(
246
CustomEmoji {
247
name: name.to_owned(),
248
object_id: emoji.object_id,
249
}
250
.key(),
251
);
252
}
253
let object_id = content_url
254
.and_then(crate::links::hosted_content_object_id)
255
.or_else(|| {
256
content_url
257
.and_then(crate::links::object_id_from_ams_path)
258
.map(str::to_owned)
259
})
260
.or_else(|| {
261
reaction_id
262
.map(str::trim)
263
.filter(|id| crate::links::is_ams_object_id(id))
264
.map(str::to_owned)
265
});
266
match (display_name, object_id) {
267
(Some(name), Some(object_id)) => Some(
268
CustomEmoji {
269
name: name.to_owned(),
270
object_id,
271
}
272
.key(),
273
),
274
(None, Some(object_id)) if is_custom_reaction_type(reaction_type) => Some(
275
CustomEmoji {
276
name: CUSTOM_TYPE.to_owned(),
277
object_id,
278
}
279
.key(),
280
),
281
(Some(name), None) if is_custom_reaction_type(reaction_type) => {
282
Some(format!("{CUSTOM_COLON}{name}"))
283
}
284
_ if is_custom_reaction_type(reaction_type) => Some(CUSTOM_TYPE.to_owned()),
285
_ => None,
286
}
287
}
288
289
pub fn is_custom_reaction_type(reaction_type: &str) -> bool {
290
let key = reaction_type.trim();
291
key.eq_ignore_ascii_case(CUSTOM_TYPE)
292
|| key.starts_with(CUSTOM_UNDERSCORE)
293
|| key.starts_with(CUSTOM_COLON)
294
|| custom_emoji(key).is_some()
295
}
296
297
/// A reaction key that must not be drawn as text in a pill (`custom`, `name;id`, ...).
298
pub fn hides_raw_reaction_key(key: &str) -> bool {
299
if ["like", "heart", "laugh", "surprised", "sad", "angry"].contains(&key) {
300
return false;
301
}
302
if reaction_glyph_for_key(key).is_some() {
303
return false;
304
}
305
if key.chars().any(|character| !character.is_ascii()) {
306
return false;
307
}
308
is_custom_reaction_type(key)
309
|| custom_emoji_display_name(key).is_some()
310
|| crate::links::is_ams_object_id(key)
311
|| key.contains(CUSTOM_EMOJI_SEPARATOR)
312
}
313
314
pub fn custom_emoji_display_name(key: &str) -> Option<String> {
315
if let Some(name) = custom_emoji(key)
316
.as_ref()
317
.and_then(CustomEmoji::display_name)
318
{
319
return Some(name.to_owned());
320
}
321
let key = key.trim();
322
key.strip_prefix(CUSTOM_COLON)
323
.or_else(|| key.strip_prefix(CUSTOM_UNDERSCORE))
324
.map(str::trim)
325
.filter(|name| !name.is_empty() && !crate::links::is_ams_object_id(name))
326
.map(str::to_owned)
168
327
}
169
328
170
329
#[cfg(test)]
@@ -183,6 +342,95 @@ mod tests {
183
342
assert_eq!(custom_emoji("like"), None);
184
343
assert_eq!(custom_emoji("x;../evil"), None);
185
344
assert_eq!(custom_emoji(";0-wcde-d3-1"), None);
345
assert_eq!(custom_emoji("custom"), None);
346
}
347
348
#[test]
349
fn custom_emoji_keys_accept_graph_and_prefixed_variants() {
350
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";
351
let hosted = format!(
352
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value",
353
base64_id(object_id)
354
);
355
let from_url = custom_emoji(&hosted).expect("hosted content");
356
assert_eq!(from_url.object_id, object_id);
357
assert_eq!(
358
from_url.image_url(),
359
format!(
360
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim"
361
)
362
);
363
364
let from_prefix = custom_emoji(&format!("custom_{object_id}")).expect("prefixed");
365
assert_eq!(from_prefix.object_id, object_id);
366
367
let from_bare = custom_emoji(object_id).expect("bare object id");
368
assert_eq!(from_bare.object_id, object_id);
369
370
let from_ams = custom_emoji(&format!(
371
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim"
372
))
373
.expect("ams url");
374
assert_eq!(from_ams.object_id, object_id);
375
}
376
377
#[test]
378
fn graph_custom_reaction_payloads_become_a_name_and_object_key() {
379
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";
380
let hosted = format!(
381
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value",
382
base64_id(object_id)
383
);
384
assert_eq!(
385
custom_reaction_key("custom", Some("tsignal"), Some(&hosted), None).as_deref(),
386
Some("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")
387
);
388
assert_eq!(
389
custom_reaction_key("custom", Some("party-parrot"), None, Some(object_id)).as_deref(),
390
Some("party-parrot;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")
391
);
392
assert_eq!(
393
custom_reaction_key("custom", Some("tsignal"), None, None).as_deref(),
394
Some("custom:tsignal")
395
);
396
assert_eq!(
397
custom_reaction_key("custom", None, None, None).as_deref(),
398
Some("custom")
399
);
400
assert_eq!(custom_reaction_key("like", None, None, None), None);
401
assert_eq!(
402
custom_reaction_key(
403
"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",
404
None,
405
None,
406
None
407
)
408
.as_deref(),
409
Some("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8")
410
);
411
assert!(hides_raw_reaction_key("custom"));
412
assert!(hides_raw_reaction_key("custom:tsignal"));
413
assert!(hides_raw_reaction_key(
414
"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8"
415
));
416
assert!(!hides_raw_reaction_key("like"));
417
assert!(!hides_raw_reaction_key("\u{1F44D}"));
418
assert_eq!(
419
custom_emoji_display_name("custom:tsignal").as_deref(),
420
Some("tsignal")
421
);
422
assert_eq!(
423
custom_emoji_display_name("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")
424
.as_deref(),
425
Some("tsignal")
426
);
427
}
428
429
fn base64_id(object_id: &str) -> String {
430
base64::Engine::encode(
431
&base64::engine::general_purpose::STANDARD,
432
format!("id={object_id},type=1,url="),
433
)
186
434
}
187
435
188
436
#[test]
@@ -145,26 +145,185 @@ pub fn emotion_key(glyph: &str) -> Option<&'static str> {145
emotion_keys(glyph).first().copied()145
emotion_keys(glyph).first().copied()146
}146
}147
147
148
#[derive(Debug, Clone, Copy, PartialEq, Eq)]148
const CUSTOM_TYPE: &str = "custom";149
pub struct CustomEmoji<'a> {149
const CUSTOM_UNDERSCORE: &str = "custom_";150
pub name: &'a str,150
const CUSTOM_COLON: &str = "custom:";151
pub object_id: &'a str,151
152
#[derive(Debug, Clone, PartialEq, Eq)]153
pub struct CustomEmoji {154
pub name: String,155
pub object_id: String,152
}156
}153
157
154
impl CustomEmoji<'_> {158
impl CustomEmoji {159
pub fn key(&self) -> String {160
format!("{}{CUSTOM_EMOJI_SEPARATOR}{}", self.name, self.object_id)161
}162
155
pub fn image_url(&self) -> String {163
pub fn image_url(&self) -> String {156
format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id)164
format!("{AMS_OBJECTS_BASE}{}{CUSTOM_EMOJI_VIEW}", self.object_id)157
}165
}166
167
/// The name to show in a tooltip or as `:name:`. `None` when we only have a placeholder.168
pub fn display_name(&self) -> Option<&str> {169
let name = self.name.trim();170
(!name.is_empty() && !name.eq_ignore_ascii_case(CUSTOM_TYPE)).then_some(name)171
}158
}172
}159
173
160
/// `absolute-cinema;0-wcde-d3-5f5e...`: an org emoji, name and AMS object of its image.174
/// An org custom emoji hidden in a reaction key.161
pub fn custom_emoji(key: &str) -> Option<CustomEmoji<'_>> {175
///162
let (name, object_id) = key.split_once(CUSTOM_EMOJI_SEPARATOR)?;176
/// Known shapes:163
let valid_object = !object_id.is_empty()177
/// - `name;objectId` (chat service emotions)164
&& object_id178
/// - a Graph `hostedContents/...` URL whose id is `id={objectId},type=1,url=`165
.chars()179
/// - an AMS object URL166
.all(|character| character.is_ascii_alphanumeric() || character == '-');180
/// - `custom_{objectId}` or a bare object id167
(!name.is_empty() && valid_object).then_some(CustomEmoji { name, object_id })181
pub fn custom_emoji(key: &str) -> Option<CustomEmoji> {182
let key = key.trim();183
if let Some((name, object_id)) = key.split_once(CUSTOM_EMOJI_SEPARATOR) {184
let object_id = object_id185
.split([CUSTOM_EMOJI_SEPARATOR, '|'])186
.next()187
.unwrap_or(object_id)188
.trim();189
let name = name190
.strip_prefix(CUSTOM_UNDERSCORE)191
.or_else(|| name.strip_prefix(CUSTOM_COLON))192
.unwrap_or(name)193
.trim();194
if !name.is_empty() && crate::links::is_ams_object_id(object_id) {195
return Some(CustomEmoji {196
name: name.to_owned(),197
object_id: object_id.to_owned(),198
});199
}200
}201
if let Some(object_id) = crate::links::hosted_content_object_id(key) {202
return Some(CustomEmoji {203
name: CUSTOM_TYPE.to_owned(),204
object_id,205
});206
}207
if let Some(object_id) = crate::links::object_id_from_ams_path(key) {208
return Some(CustomEmoji {209
name: CUSTOM_TYPE.to_owned(),210
object_id: object_id.to_owned(),211
});212
}213
if let Some(object_id) = key214
.strip_prefix(CUSTOM_UNDERSCORE)215
.or_else(|| key.strip_prefix(CUSTOM_COLON))216
.map(str::trim)217
.filter(|id| crate::links::is_ams_object_id(id))218
{219
return Some(CustomEmoji {220
name: CUSTOM_TYPE.to_owned(),221
object_id: object_id.to_owned(),222
});223
}224
crate::links::is_ams_object_id(key).then(|| CustomEmoji {225
name: CUSTOM_TYPE.to_owned(),226
object_id: key.to_owned(),227
})228
}229
230
/// Canonical `name;objectId` key from a Graph (or mixed) custom reaction payload.231
///232
/// Graph stores `reactionType: "custom"` with the name and image in `displayName`233
/// and `reactionContentUrl`. Returns `None` when this is not a custom reaction.234
pub fn custom_reaction_key(235
reaction_type: &str,236
display_name: Option<&str>,237
content_url: Option<&str>,238
reaction_id: Option<&str>,239
) -> Option<String> {240
let display_name = display_name.map(str::trim).filter(|name| !name.is_empty());241
if let Some(emoji) = custom_emoji(reaction_type) {242
let name = display_name243
.or_else(|| emoji.display_name())244
.unwrap_or(&emoji.name);245
return Some(246
CustomEmoji {247
name: name.to_owned(),248
object_id: emoji.object_id,249
}250
.key(),251
);252
}253
let object_id = content_url254
.and_then(crate::links::hosted_content_object_id)255
.or_else(|| {256
content_url257
.and_then(crate::links::object_id_from_ams_path)258
.map(str::to_owned)259
})260
.or_else(|| {261
reaction_id262
.map(str::trim)263
.filter(|id| crate::links::is_ams_object_id(id))264
.map(str::to_owned)265
});266
match (display_name, object_id) {267
(Some(name), Some(object_id)) => Some(268
CustomEmoji {269
name: name.to_owned(),270
object_id,271
}272
.key(),273
),274
(None, Some(object_id)) if is_custom_reaction_type(reaction_type) => Some(275
CustomEmoji {276
name: CUSTOM_TYPE.to_owned(),277
object_id,278
}279
.key(),280
),281
(Some(name), None) if is_custom_reaction_type(reaction_type) => {282
Some(format!("{CUSTOM_COLON}{name}"))283
}284
_ if is_custom_reaction_type(reaction_type) => Some(CUSTOM_TYPE.to_owned()),285
_ => None,286
}287
}288
289
pub fn is_custom_reaction_type(reaction_type: &str) -> bool {290
let key = reaction_type.trim();291
key.eq_ignore_ascii_case(CUSTOM_TYPE)292
|| key.starts_with(CUSTOM_UNDERSCORE)293
|| key.starts_with(CUSTOM_COLON)294
|| custom_emoji(key).is_some()295
}296
297
/// A reaction key that must not be drawn as text in a pill (`custom`, `name;id`, ...).298
pub fn hides_raw_reaction_key(key: &str) -> bool {299
if ["like", "heart", "laugh", "surprised", "sad", "angry"].contains(&key) {300
return false;301
}302
if reaction_glyph_for_key(key).is_some() {303
return false;304
}305
if key.chars().any(|character| !character.is_ascii()) {306
return false;307
}308
is_custom_reaction_type(key)309
|| custom_emoji_display_name(key).is_some()310
|| crate::links::is_ams_object_id(key)311
|| key.contains(CUSTOM_EMOJI_SEPARATOR)312
}313
314
pub fn custom_emoji_display_name(key: &str) -> Option<String> {315
if let Some(name) = custom_emoji(key)316
.as_ref()317
.and_then(CustomEmoji::display_name)318
{319
return Some(name.to_owned());320
}321
let key = key.trim();322
key.strip_prefix(CUSTOM_COLON)323
.or_else(|| key.strip_prefix(CUSTOM_UNDERSCORE))324
.map(str::trim)325
.filter(|name| !name.is_empty() && !crate::links::is_ams_object_id(name))326
.map(str::to_owned)168
}327
}169
328
170
#[cfg(test)]329
#[cfg(test)]@@ -183,6 +342,95 @@ mod tests {183
assert_eq!(custom_emoji("like"), None);342
assert_eq!(custom_emoji("like"), None);184
assert_eq!(custom_emoji("x;../evil"), None);343
assert_eq!(custom_emoji("x;../evil"), None);185
assert_eq!(custom_emoji(";0-wcde-d3-1"), None);344
assert_eq!(custom_emoji(";0-wcde-d3-1"), None);345
assert_eq!(custom_emoji("custom"), None);346
}347
348
#[test]349
fn custom_emoji_keys_accept_graph_and_prefixed_variants() {350
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";351
let hosted = format!(352
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value",353
base64_id(object_id)354
);355
let from_url = custom_emoji(&hosted).expect("hosted content");356
assert_eq!(from_url.object_id, object_id);357
assert_eq!(358
from_url.image_url(),359
format!(360
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim"361
)362
);363
364
let from_prefix = custom_emoji(&format!("custom_{object_id}")).expect("prefixed");365
assert_eq!(from_prefix.object_id, object_id);366
367
let from_bare = custom_emoji(object_id).expect("bare object id");368
assert_eq!(from_bare.object_id, object_id);369
370
let from_ams = custom_emoji(&format!(371
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/{object_id}/views/imgt2_anim"372
))373
.expect("ams url");374
assert_eq!(from_ams.object_id, object_id);375
}376
377
#[test]378
fn graph_custom_reaction_payloads_become_a_name_and_object_key() {379
let object_id = "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853";380
let hosted = format!(381
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{}/$value",382
base64_id(object_id)383
);384
assert_eq!(385
custom_reaction_key("custom", Some("tsignal"), Some(&hosted), None).as_deref(),386
Some("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")387
);388
assert_eq!(389
custom_reaction_key("custom", Some("party-parrot"), None, Some(object_id)).as_deref(),390
Some("party-parrot;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")391
);392
assert_eq!(393
custom_reaction_key("custom", Some("tsignal"), None, None).as_deref(),394
Some("custom:tsignal")395
);396
assert_eq!(397
custom_reaction_key("custom", None, None, None).as_deref(),398
Some("custom")399
);400
assert_eq!(custom_reaction_key("like", None, None, None), None);401
assert_eq!(402
custom_reaction_key(403
"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",404
None,405
None,406
None407
)408
.as_deref(),409
Some("absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8")410
);411
assert!(hides_raw_reaction_key("custom"));412
assert!(hides_raw_reaction_key("custom:tsignal"));413
assert!(hides_raw_reaction_key(414
"absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8"415
));416
assert!(!hides_raw_reaction_key("like"));417
assert!(!hides_raw_reaction_key("\u{1F44D}"));418
assert_eq!(419
custom_emoji_display_name("custom:tsignal").as_deref(),420
Some("tsignal")421
);422
assert_eq!(423
custom_emoji_display_name("tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853")424
.as_deref(),425
Some("tsignal")426
);427
}428
429
fn base64_id(object_id: &str) -> String {430
base64::Engine::encode(431
&base64::engine::general_purpose::STANDARD,432
format!("id={object_id},type=1,url="),433
)186
}434
}187
435
188
#[test]436
#[test]@@ -0,0 +1,46 @@
1
{
2
"continuationToken": "42",
3
"categories": [
4
{
5
"id": "customEmoji",
6
"title": "Custom Emoji",
7
"description": "Custom Emoji",
8
"emoticons": [
9
{
10
"id": "em-1",
11
"documentId": "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",
12
"shortcuts": ["absolute-cinema"],
13
"description": "absolute-cinema",
14
"createdOn": 1710000000000,
15
"isDeleted": false,
16
"unicode": null,
17
"diverse": false,
18
"keywords": ["cinema", "movie"],
19
"creator": "user-1",
20
"etag": "\"1\""
21
},
22
{
23
"id": "em-2",
24
"documentId": "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853",
25
"shortcuts": ["tsignal"],
26
"description": "tsignal",
27
"isDeleted": false,
28
"keywords": ["tsignal"]
29
},
30
{
31
"id": "em-gone",
32
"documentId": "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef",
33
"shortcuts": ["old-one"],
34
"isDeleted": true,
35
"keywords": []
36
},
37
{
38
"id": "em-bad",
39
"documentId": "../evil",
40
"shortcuts": ["bad"],
41
"isDeleted": false
42
}
43
]
44
}
45
]
46
}
@@ -0,0 +1,46 @@1
{2
"continuationToken": "42",3
"categories": [4
{5
"id": "customEmoji",6
"title": "Custom Emoji",7
"description": "Custom Emoji",8
"emoticons": [9
{10
"id": "em-1",11
"documentId": "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8",12
"shortcuts": ["absolute-cinema"],13
"description": "absolute-cinema",14
"createdOn": 1710000000000,15
"isDeleted": false,16
"unicode": null,17
"diverse": false,18
"keywords": ["cinema", "movie"],19
"creator": "user-1",20
"etag": "\"1\""21
},22
{23
"id": "em-2",24
"documentId": "0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853",25
"shortcuts": ["tsignal"],26
"description": "tsignal",27
"isDeleted": false,28
"keywords": ["tsignal"]29
},30
{31
"id": "em-gone",32
"documentId": "0-weu-d1-deadbeefdeadbeefdeadbeefdeadbeef",33
"shortcuts": ["old-one"],34
"isDeleted": true,35
"keywords": []36
},37
{38
"id": "em-bad",39
"documentId": "../evil",40
"shortcuts": ["bad"],41
"isDeleted": false42
}43
]44
}45
]46
}@@ -36,6 +36,7 @@ mod folders;
36
36
mod forward_sync;
37
37
mod forwarded;
38
38
mod gifs;
39
mod org_emojis;
39
40
mod hidden_chats;
40
41
mod image_size;
41
42
mod images;
@@ -127,7 +128,7 @@ pub use chatsvc::{
127
128
pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};
128
129
pub use chatsvc::{
129
130
CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,
130
ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage,
131
ForwardResult, Gif, OrgEmoji, OrgEmojiCatalog, PinnedMessage, custom_emoji_html, PostFollowState, PresenceStatus, SavedMessage,
131
132
ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind,
132
133
WorkLocationSource,
133
134
};
@@ -36,6 +36,7 @@ mod folders;36
mod forward_sync;36
mod forward_sync;37
mod forwarded;37
mod forwarded;38
mod gifs;38
mod gifs;39
mod org_emojis;39
mod hidden_chats;40
mod hidden_chats;40
mod image_size;41
mod image_size;41
mod images;42
mod images;@@ -127,7 +128,7 @@ pub use chatsvc::{127
pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};128
pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};128
pub use chatsvc::{129
pub use chatsvc::{129
CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,130
CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind,130
ForwardResult, Gif, PinnedMessage, PostFollowState, PresenceStatus, SavedMessage,131
ForwardResult, Gif, OrgEmoji, OrgEmojiCatalog, PinnedMessage, custom_emoji_html, PostFollowState, PresenceStatus, SavedMessage,131
ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind,132
ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind,132
WorkLocationSource,133
WorkLocationSource,133
};134
};@@ -280,7 +280,13 @@ fn quote_info(content: &str) -> Option<QuoteInfo> {
280
280
281
281
fn reaction_info(reaction: &Reaction) -> ReactionInfo {
282
282
ReactionInfo {
283
reaction_type: reaction.reaction_type.clone(),
283
reaction_type: chatsvc::custom_reaction_key(
284
&reaction.reaction_type,
285
reaction.display_name.as_deref(),
286
reaction.reaction_content_url.as_deref(),
287
reaction.reaction_id.as_deref(),
288
)
289
.unwrap_or_else(|| reaction.reaction_type.clone()),
284
290
user_id: reaction
285
291
.user
286
292
.as_ref()
@@ -671,4 +677,35 @@ mod tests {
671
677
assert!(!mentions_of(mentioned)[0].group);
672
678
}
673
679
}
680
681
#[test]
682
fn graph_custom_emoji_reactions_keep_their_name_and_object() {
683
let hosted = concat!(
684
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/",
685
"aWQ9MC13dWstZDItZjM4MjU3YzBmYmEyZDI5ODFlYzJhMzY4YzVjZjE4NTMsdHlwZT0xLHVybD0=/",
686
"$value",
687
);
688
let message: Message = serde_json::from_value(json!({
689
"id": "m1",
690
"messageType": "message",
691
"createdDateTime": "2026-05-03T14:30:00Z",
692
"from": {"user": {"id": "u1", "displayName": "Ann"}},
693
"body": {"contentType": "html", "content": "<p>hi</p>"},
694
"reactions": [{
695
"reactionType": "custom",
696
"displayName": "tsignal",
697
"reactionContentUrl": hosted,
698
"createdDateTime": "2026-05-03T14:37:23.278Z",
699
"user": {"user": {"id": "u2", "displayName": "Bo"}},
700
}],
701
}))
702
.unwrap();
703
let record = message_record("c", &message).expect("record");
704
let reactions = crate::stored::reactions(&record);
705
assert_eq!(
706
reactions[0].reaction_type,
707
"tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"
708
);
709
assert_eq!(reactions[0].user_id.as_deref(), Some("u2"));
710
}
674
711
}
@@ -280,7 +280,13 @@ fn quote_info(content: &str) -> Option<QuoteInfo> {280
280
281
fn reaction_info(reaction: &Reaction) -> ReactionInfo {281
fn reaction_info(reaction: &Reaction) -> ReactionInfo {282
ReactionInfo {282
ReactionInfo {283
reaction_type: reaction.reaction_type.clone(),283
reaction_type: chatsvc::custom_reaction_key(284
&reaction.reaction_type,285
reaction.display_name.as_deref(),286
reaction.reaction_content_url.as_deref(),287
reaction.reaction_id.as_deref(),288
)289
.unwrap_or_else(|| reaction.reaction_type.clone()),284
user_id: reaction290
user_id: reaction285
.user291
.user286
.as_ref()292
.as_ref()@@ -671,4 +677,35 @@ mod tests {671
assert!(!mentions_of(mentioned)[0].group);677
assert!(!mentions_of(mentioned)[0].group);672
}678
}673
}679
}680
681
#[test]682
fn graph_custom_emoji_reactions_keep_their_name_and_object() {683
let hosted = concat!(684
"https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/",685
"aWQ9MC13dWstZDItZjM4MjU3YzBmYmEyZDI5ODFlYzJhMzY4YzVjZjE4NTMsdHlwZT0xLHVybD0=/",686
"$value",687
);688
let message: Message = serde_json::from_value(json!({689
"id": "m1",690
"messageType": "message",691
"createdDateTime": "2026-05-03T14:30:00Z",692
"from": {"user": {"id": "u1", "displayName": "Ann"}},693
"body": {"contentType": "html", "content": "<p>hi</p>"},694
"reactions": [{695
"reactionType": "custom",696
"displayName": "tsignal",697
"reactionContentUrl": hosted,698
"createdDateTime": "2026-05-03T14:37:23.278Z",699
"user": {"user": {"id": "u2", "displayName": "Bo"}},700
}],701
}))702
.unwrap();703
let record = message_record("c", &message).expect("record");704
let reactions = crate::stored::reactions(&record);705
assert_eq!(706
reactions[0].reaction_type,707
"tsignal;0-wuk-d2-f38257c0fba2d2981ec2a368c5cf1853"708
);709
assert_eq!(reactions[0].user_id.as_deref(), Some("u2"));710
}674
}711
}@@ -0,0 +1,124 @@
1
use chrono::{Duration, Utc};
2
use store::Store;
3
4
use chatsvc::{OrgEmoji, OrgEmojiCatalog, merge_catalog};
5
6
use crate::engine::SyncEngine;
7
use crate::error::Result;
8
use crate::remote::Remote;
9
10
pub const META_ORG_EMOJIS: &str = "org_emojis";
11
pub const META_ORG_EMOJIS_AT: &str = "org_emojis_at";
12
const CACHE_TTL: Duration = Duration::minutes(30);
13
14
impl<R: Remote> SyncEngine<R> {
15
/// Fresh catalogue from the store when it is younger than 30 minutes.
16
/// Otherwise a CSA refresh (delta when a continuation token is cached),
17
/// falling back to the stale cache if the network call fails.
18
pub async fn list_org_emojis(&self, force: bool) -> Result<Vec<OrgEmoji>> {
19
let now = Utc::now();
20
if !force {
21
if let Some(fresh) = cached_if_fresh(&self.store, now)? {
22
return Ok(fresh.emojis);
23
}
24
}
25
let previous = load_catalog(&self.store)?.unwrap_or_default();
26
let use_delta = !force
27
&& previous
28
.continuation
29
.as_deref()
30
.is_some_and(|token| !token.is_empty());
31
let incoming = if use_delta {
32
match self
33
.remote
34
.list_org_emojis(previous.continuation.as_deref())
35
.await
36
{
37
Ok(page) => page,
38
Err(_) => match self.remote.list_org_emojis(None).await {
39
Ok(page) => page,
40
Err(error) => return stale_or_err(previous, error),
41
},
42
}
43
} else {
44
match self.remote.list_org_emojis(None).await {
45
Ok(page) => page,
46
Err(error) => return stale_or_err(previous, error),
47
}
48
};
49
let merged = merge_catalog(&previous.emojis, incoming, !use_delta);
50
save_catalog(&self.store, &merged, now)?;
51
Ok(merged.emojis)
52
}
53
}
54
55
fn stale_or_err(previous: OrgEmojiCatalog, error: crate::error::Error) -> Result<Vec<OrgEmoji>> {
56
if previous.emojis.is_empty() {
57
Err(error)
58
} else {
59
Ok(previous.emojis)
60
}
61
}
62
63
pub fn cached_if_fresh(store: &Store, now: chrono::DateTime<Utc>) -> Result<Option<OrgEmojiCatalog>> {
64
let Some(cached_at) = store.meta_time(META_ORG_EMOJIS_AT)? else {
65
return Ok(None);
66
};
67
if now.signed_duration_since(cached_at) >= CACHE_TTL {
68
return Ok(None);
69
}
70
load_catalog(store)
71
}
72
73
pub fn load_catalog(store: &Store) -> Result<Option<OrgEmojiCatalog>> {
74
let Some(json) = store.meta(META_ORG_EMOJIS)? else {
75
return Ok(None);
76
};
77
Ok(serde_json::from_str(&json).ok())
78
}
79
80
pub fn save_catalog(
81
store: &Store,
82
catalog: &OrgEmojiCatalog,
83
now: chrono::DateTime<Utc>,
84
) -> Result<()> {
85
let json = serde_json::to_string(catalog).map_err(|error| crate::error::Error::Folders(error.to_string()))?;
86
store.set_meta(META_ORG_EMOJIS, &json)?;
87
store.set_meta_time(META_ORG_EMOJIS_AT, now)?;
88
Ok(())
89
}
90
91
#[cfg(test)]
92
mod tests {
93
use chatsvc::OrgEmoji;
94
use chrono::TimeZone;
95
use store::Store;
96
97
use super::*;
98
99
fn emoji(id: &str, name: &str) -> OrgEmoji {
100
OrgEmoji {
101
id: id.to_owned(),
102
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".to_owned(),
103
name: name.to_owned(),
104
keywords: vec![],
105
source: None,
106
}
107
}
108
109
#[test]
110
fn store_returns_a_fresh_catalogue_and_hides_a_stale_one() {
111
let store = Store::open_in_memory().unwrap();
112
let t0 = Utc.with_ymd_and_hms(2026, 5, 3, 12, 0, 0).unwrap();
113
let catalog = OrgEmojiCatalog {
114
emojis: vec![emoji("em-1", "ship-it")],
115
deleted_ids: vec![],
116
continuation: Some("42".into()),
117
};
118
save_catalog(&store, &catalog, t0).unwrap();
119
let fresh = cached_if_fresh(&store, t0 + Duration::minutes(29)).unwrap().unwrap();
120
assert_eq!(fresh.emojis[0].name, "ship-it");
121
assert!(cached_if_fresh(&store, t0 + Duration::minutes(31)).unwrap().is_none());
122
assert_eq!(load_catalog(&store).unwrap().unwrap().continuation.as_deref(), Some("42"));
123
}
124
}
@@ -0,0 +1,124 @@1
use chrono::{Duration, Utc};2
use store::Store;3
4
use chatsvc::{OrgEmoji, OrgEmojiCatalog, merge_catalog};5
6
use crate::engine::SyncEngine;7
use crate::error::Result;8
use crate::remote::Remote;9
10
pub const META_ORG_EMOJIS: &str = "org_emojis";11
pub const META_ORG_EMOJIS_AT: &str = "org_emojis_at";12
const CACHE_TTL: Duration = Duration::minutes(30);13
14
impl<R: Remote> SyncEngine<R> {15
/// Fresh catalogue from the store when it is younger than 30 minutes.16
/// Otherwise a CSA refresh (delta when a continuation token is cached),17
/// falling back to the stale cache if the network call fails.18
pub async fn list_org_emojis(&self, force: bool) -> Result<Vec<OrgEmoji>> {19
let now = Utc::now();20
if !force {21
if let Some(fresh) = cached_if_fresh(&self.store, now)? {22
return Ok(fresh.emojis);23
}24
}25
let previous = load_catalog(&self.store)?.unwrap_or_default();26
let use_delta = !force27
&& previous28
.continuation29
.as_deref()30
.is_some_and(|token| !token.is_empty());31
let incoming = if use_delta {32
match self33
.remote34
.list_org_emojis(previous.continuation.as_deref())35
.await36
{37
Ok(page) => page,38
Err(_) => match self.remote.list_org_emojis(None).await {39
Ok(page) => page,40
Err(error) => return stale_or_err(previous, error),41
},42
}43
} else {44
match self.remote.list_org_emojis(None).await {45
Ok(page) => page,46
Err(error) => return stale_or_err(previous, error),47
}48
};49
let merged = merge_catalog(&previous.emojis, incoming, !use_delta);50
save_catalog(&self.store, &merged, now)?;51
Ok(merged.emojis)52
}53
}54
55
fn stale_or_err(previous: OrgEmojiCatalog, error: crate::error::Error) -> Result<Vec<OrgEmoji>> {56
if previous.emojis.is_empty() {57
Err(error)58
} else {59
Ok(previous.emojis)60
}61
}62
63
pub fn cached_if_fresh(store: &Store, now: chrono::DateTime<Utc>) -> Result<Option<OrgEmojiCatalog>> {64
let Some(cached_at) = store.meta_time(META_ORG_EMOJIS_AT)? else {65
return Ok(None);66
};67
if now.signed_duration_since(cached_at) >= CACHE_TTL {68
return Ok(None);69
}70
load_catalog(store)71
}72
73
pub fn load_catalog(store: &Store) -> Result<Option<OrgEmojiCatalog>> {74
let Some(json) = store.meta(META_ORG_EMOJIS)? else {75
return Ok(None);76
};77
Ok(serde_json::from_str(&json).ok())78
}79
80
pub fn save_catalog(81
store: &Store,82
catalog: &OrgEmojiCatalog,83
now: chrono::DateTime<Utc>,84
) -> Result<()> {85
let json = serde_json::to_string(catalog).map_err(|error| crate::error::Error::Folders(error.to_string()))?;86
store.set_meta(META_ORG_EMOJIS, &json)?;87
store.set_meta_time(META_ORG_EMOJIS_AT, now)?;88
Ok(())89
}90
91
#[cfg(test)]92
mod tests {93
use chatsvc::OrgEmoji;94
use chrono::TimeZone;95
use store::Store;96
97
use super::*;98
99
fn emoji(id: &str, name: &str) -> OrgEmoji {100
OrgEmoji {101
id: id.to_owned(),102
document_id: "0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8".to_owned(),103
name: name.to_owned(),104
keywords: vec![],105
source: None,106
}107
}108
109
#[test]110
fn store_returns_a_fresh_catalogue_and_hides_a_stale_one() {111
let store = Store::open_in_memory().unwrap();112
let t0 = Utc.with_ymd_and_hms(2026, 5, 3, 12, 0, 0).unwrap();113
let catalog = OrgEmojiCatalog {114
emojis: vec![emoji("em-1", "ship-it")],115
deleted_ids: vec![],116
continuation: Some("42".into()),117
};118
save_catalog(&store, &catalog, t0).unwrap();119
let fresh = cached_if_fresh(&store, t0 + Duration::minutes(29)).unwrap().unwrap();120
assert_eq!(fresh.emojis[0].name, "ship-it");121
assert!(cached_if_fresh(&store, t0 + Duration::minutes(31)).unwrap().is_none());122
assert_eq!(load_catalog(&store).unwrap().unwrap().continuation.as_deref(), Some("42"));123
}124
}@@ -14,7 +14,7 @@ use chatsvc::{
14
14
use chatsvc::{
15
15
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
16
16
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,
17
InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,
17
InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, CustomEmojis, OrgEmojiCatalog,
18
18
MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,
19
19
PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus,
20
20
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote,
@@ -615,6 +615,10 @@ pub trait Remote {
615
615
Err(Error::Unsupported("GIF search"))
616
616
}
617
617
618
async fn list_org_emojis(&self, _continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
619
Err(Error::Unsupported("custom emoji catalogue"))
620
}
621
618
622
async fn server_search_init(
619
623
&self,
620
624
_identity: &SearchIdentity,
@@ -1635,6 +1639,14 @@ impl Remote for Graph {
1635
1639
Ok(Gifs::new(self.session()).search(query).await?)
1636
1640
}
1637
1641
1642
async fn list_org_emojis(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {
1643
let client = CustomEmojis::new(self.session());
1644
match continuation.map(str::trim).filter(|token| !token.is_empty()) {
1645
Some(token) => Ok(client.list_since(token).await?),
1646
None => Ok(client.list().await?),
1647
}
1648
}
1649
1638
1650
async fn server_search_init(
1639
1651
&self,
1640
1652
identity: &SearchIdentity,
@@ -14,7 +14,7 @@ use chatsvc::{14
use chatsvc::{14
use chatsvc::{15
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,15
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,16
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,16
ConversationState, Conversations, ForcedAvailability, ForwardResult, Gif, Gifs, HistoryShare,17
InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo,17
InvokeRequest, InvokeResponse, Language, LanguageSettings, LanguageSettingsClient, LinkInfo, CustomEmojis, OrgEmojiCatalog,18
MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,18
MemberHorizon, MessageEmotions, MessageLanguage, MessageLinks, MessageWindow, Messages,19
PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus,19
PinnedMessage, Pins, PostFollowState, PresenceLookup, PresenceService, PresenceStatus,20
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote,20
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote,@@ -615,6 +615,10 @@ pub trait Remote {615
Err(Error::Unsupported("GIF search"))615
Err(Error::Unsupported("GIF search"))616
}616
}617
617
618
async fn list_org_emojis(&self, _continuation: Option<&str>) -> Result<OrgEmojiCatalog> {619
Err(Error::Unsupported("custom emoji catalogue"))620
}621
618
async fn server_search_init(622
async fn server_search_init(619
&self,623
&self,620
_identity: &SearchIdentity,624
_identity: &SearchIdentity,@@ -1635,6 +1639,14 @@ impl Remote for Graph {1635
Ok(Gifs::new(self.session()).search(query).await?)1639
Ok(Gifs::new(self.session()).search(query).await?)1636
}1640
}1637
1641
1642
async fn list_org_emojis(&self, continuation: Option<&str>) -> Result<OrgEmojiCatalog> {1643
let client = CustomEmojis::new(self.session());1644
match continuation.map(str::trim).filter(|token| !token.is_empty()) {1645
Some(token) => Ok(client.list_since(token).await?),1646
None => Ok(client.list().await?),1647
}1648
}1649
1638
async fn server_search_init(1650
async fn server_search_init(1639
&self,1651
&self,1640
identity: &SearchIdentity,1652
identity: &SearchIdentity,@@ -79,6 +79,7 @@ const BLOCK_ELEMENTS: [&str; 12] = [
79
79
const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];
80
80
const LANGUAGE_PREFIX: &str = "language-";
81
81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
82
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
82
83
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
83
84
const MAX_HEADING_LEVEL: u8 = 3;
84
85
const MARK_BACKGROUND: u32 = 0xffff00;
@@ -448,9 +449,28 @@ fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {
448
449
449
450
fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {
450
451
let value = element.value();
451
let is_emoji = value
452
.attr("itemtype")
453
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
452
let itemtype = value.attr("itemtype").unwrap_or("");
453
if itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) {
454
let name = value
455
.attr("alt")
456
.or_else(|| {
457
value
458
.attr("itemid")
459
.and_then(|itemid| itemid.split_once(';').map(|(name, _)| name))
460
})
461
.unwrap_or_default()
462
.to_owned();
463
if let Some(source) = value.attr("src").filter(|source| !source.is_empty()) {
464
spans.push(Span::CustomEmoji {
465
name,
466
url: source.to_owned(),
467
});
468
} else if !name.is_empty() {
469
push_text(spans, &format!(":{name}:"));
470
}
471
return;
472
}
473
let is_emoji = itemtype.contains(EMOJI_ITEMTYPE);
454
474
if is_emoji {
455
475
if let Some(alt) = value.attr("alt") {
456
476
push_text(spans, &without_repeated_skin_tone(alt));
@@ -79,6 +79,7 @@ const BLOCK_ELEMENTS: [&str; 12] = [79
const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];79
const SKIPPED_ELEMENTS: [&str; 4] = ["script", "style", "attachment", "head"];80
const LANGUAGE_PREFIX: &str = "language-";80
const LANGUAGE_PREFIX: &str = "language-";81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";81
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";82
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";82
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";83
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";83
const MAX_HEADING_LEVEL: u8 = 3;84
const MAX_HEADING_LEVEL: u8 = 3;84
const MARK_BACKGROUND: u32 = 0xffff00;85
const MARK_BACKGROUND: u32 = 0xffff00;@@ -448,9 +449,28 @@ fn push_custom_emoji(element: ElementRef<'_>, spans: &mut Vec<Span>) {448
449
449
fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {450
fn push_image(element: ElementRef<'_>, spans: &mut Vec<Span>) {450
let value = element.value();451
let value = element.value();451
let is_emoji = value452
let itemtype = value.attr("itemtype").unwrap_or("");452
.attr("itemtype")453
if itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) {453
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));454
let name = value455
.attr("alt")456
.or_else(|| {457
value458
.attr("itemid")459
.and_then(|itemid| itemid.split_once(';').map(|(name, _)| name))460
})461
.unwrap_or_default()462
.to_owned();463
if let Some(source) = value.attr("src").filter(|source| !source.is_empty()) {464
spans.push(Span::CustomEmoji {465
name,466
url: source.to_owned(),467
});468
} else if !name.is_empty() {469
push_text(spans, &format!(":{name}:"));470
}471
return;472
}473
let is_emoji = itemtype.contains(EMOJI_ITEMTYPE);454
if is_emoji {474
if is_emoji {455
if let Some(alt) = value.attr("alt") {475
if let Some(alt) = value.attr("alt") {456
push_text(spans, &without_repeated_skin_tone(alt));476
push_text(spans, &without_repeated_skin_tone(alt));@@ -16,6 +16,7 @@ use crate::mentions::MentionInput;
16
16
use crate::spans::{Span, html_to_spans};
17
17
18
18
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
19
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";
19
20
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
20
21
const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";
21
22
const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";
@@ -318,6 +319,10 @@ fn inline_reply_quote(record: &MessageRecord) -> Option<QuoteInfo> {
318
319
})
319
320
}
320
321
322
fn is_emoji_itemtype(itemtype: &str) -> bool {
323
itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) || itemtype.contains(EMOJI_ITEMTYPE)
324
}
325
321
326
pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
322
327
if record.deleted {
323
328
return Vec::new();
@@ -336,7 +341,7 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
336
341
let value = element.value();
337
342
let is_emoji = value
338
343
.attr("itemtype")
339
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
344
.is_some_and(is_emoji_itemtype);
340
345
let src = value.attr("src").filter(|src| !src.is_empty());
341
346
let Some(url) = (match value.name() {
342
347
"img" if !is_emoji => src.map(str::to_owned),
@@ -384,7 +389,7 @@ pub fn edit_preserved(record: &MessageRecord) -> EditPreserved {
384
389
let value = element.value();
385
390
let is_emoji = value
386
391
.attr("itemtype")
387
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));
392
.is_some_and(is_emoji_itemtype);
388
393
match value.name() {
389
394
"img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {
390
395
preserved
@@ -991,6 +996,7 @@ mod tests {
991
996
r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
992
997
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">"#,
993
998
r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
999
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">"#,
994
1000
r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
995
1001
);
996
1002
let found = images(&record(html, "[]"));
@@ -16,6 +16,7 @@ use crate::mentions::MentionInput;16
use crate::spans::{Span, html_to_spans};16
use crate::spans::{Span, html_to_spans};17
17
18
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";18
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";19
const CUSTOM_EMOJI_ITEMTYPE: &str = "schema.skype.com/CustomEmoji";19
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";20
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";20
const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";21
const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";21
const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";22
const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";@@ -318,6 +319,10 @@ fn inline_reply_quote(record: &MessageRecord) -> Option<QuoteInfo> {318
})319
})319
}320
}320
321
322
fn is_emoji_itemtype(itemtype: &str) -> bool {323
itemtype.contains(CUSTOM_EMOJI_ITEMTYPE) || itemtype.contains(EMOJI_ITEMTYPE)324
}325
321
pub fn images(record: &MessageRecord) -> Vec<ImageRef> {326
pub fn images(record: &MessageRecord) -> Vec<ImageRef> {322
if record.deleted {327
if record.deleted {323
return Vec::new();328
return Vec::new();@@ -336,7 +341,7 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {336
let value = element.value();341
let value = element.value();337
let is_emoji = value342
let is_emoji = value338
.attr("itemtype")343
.attr("itemtype")339
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));344
.is_some_and(is_emoji_itemtype);340
let src = value.attr("src").filter(|src| !src.is_empty());345
let src = value.attr("src").filter(|src| !src.is_empty());341
let Some(url) = (match value.name() {346
let Some(url) = (match value.name() {342
"img" if !is_emoji => src.map(str::to_owned),347
"img" if !is_emoji => src.map(str::to_owned),@@ -384,7 +389,7 @@ pub fn edit_preserved(record: &MessageRecord) -> EditPreserved {384
let value = element.value();389
let value = element.value();385
let is_emoji = value390
let is_emoji = value386
.attr("itemtype")391
.attr("itemtype")387
.is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE));392
.is_some_and(is_emoji_itemtype);388
match value.name() {393
match value.name() {389
"img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {394
"img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => {390
preserved395
preserved@@ -991,6 +996,7 @@ mod tests {991
r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,996
r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,992
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">"#,997
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">"#,993
r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,998
r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,999
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">"#,994
r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,1000
r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,995
);1001
);996
let found = images(&record(html, "[]"));1002
let found = images(&record(html, "[]"));@@ -539,4 +539,14 @@ fn org_emoji_keep_their_image_and_name() {
539
539
html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),
540
540
vec![text(":crying_cat:")]
541
541
);
542
let official = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim";
543
assert_eq!(
544
html_to_spans(&format!(
545
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>"#
546
)),
547
vec![Span::CustomEmoji {
548
name: "absolute-cinema".to_owned(),
549
url: official.to_owned(),
550
}]
551
);
542
552
}
@@ -539,4 +539,14 @@ fn org_emoji_keep_their_image_and_name() {539
html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),539
html_to_spans("<p><customemoji alt=\"crying_cat\"></customemoji></p>"),540
vec![text(":crying_cat:")]540
vec![text(":crying_cat:")]541
);541
);542
let official = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim";543
assert_eq!(544
html_to_spans(&format!(545
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>"#546
)),547
vec![Span::CustomEmoji {548
name: "absolute-cinema".to_owned(),549
url: official.to_owned(),550
}]551
);542
}552
}@@ -112,6 +112,12 @@ pub struct Attachment {
112
112
#[serde(rename_all = "camelCase")]
113
113
pub struct Reaction {
114
114
pub reaction_type: String,
115
#[serde(default)]
116
pub display_name: Option<String>,
117
#[serde(default)]
118
pub reaction_content_url: Option<String>,
119
#[serde(default)]
120
pub reaction_id: Option<String>,
115
121
pub created_date_time: Option<DateTime<Utc>>,
116
122
pub user: Option<Sender>,
117
123
}
@@ -112,6 +112,12 @@ pub struct Attachment {112
#[serde(rename_all = "camelCase")]112
#[serde(rename_all = "camelCase")]113
pub struct Reaction {113
pub struct Reaction {114
pub reaction_type: String,114
pub reaction_type: String,115
#[serde(default)]116
pub display_name: Option<String>,117
#[serde(default)]118
pub reaction_content_url: Option<String>,119
#[serde(default)]120
pub reaction_id: Option<String>,115
pub created_date_time: Option<DateTime<Utc>>,121
pub created_date_time: Option<DateTime<Utc>>,116
pub user: Option<Sender>,122
pub user: Option<Sender>,117
}123
}@@ -19,6 +19,8 @@ pub struct MessageSource {
19
19
pub sent_at: String,
20
20
/// Link naar het bericht in Teams, als die er is.
21
21
pub link: Option<String>,
22
/// Vermelde personen in het bericht (naam zoals in de tekst, e-mailadres), als bekend.
23
pub mentions: Vec<(String, String)>,
22
24
}
23
25
24
26
impl MessageSource {
@@ -90,6 +92,7 @@ mod tests {
90
92
sender: "Mara Lindqvist".into(),
91
93
sent_at: "15 jan 2026 13:39".into(),
92
94
link: Some("https://teams.microsoft.com/l/message/19:x/1".into()),
95
mentions: Vec::new(),
93
96
}
94
97
}
95
98
@@ -19,6 +19,8 @@ pub struct MessageSource {19
pub sent_at: String,19
pub sent_at: String,20
/// Link naar het bericht in Teams, als die er is.20
/// Link naar het bericht in Teams, als die er is.21
pub link: Option<String>,21
pub link: Option<String>,22
/// Vermelde personen in het bericht (naam zoals in de tekst, e-mailadres), als bekend.23
pub mentions: Vec<(String, String)>,22
}24
}23
25
24
impl MessageSource {26
impl MessageSource {@@ -90,6 +92,7 @@ mod tests {90
sender: "Mara Lindqvist".into(),92
sender: "Mara Lindqvist".into(),91
sent_at: "15 jan 2026 13:39".into(),93
sent_at: "15 jan 2026 13:39".into(),92
link: Some("https://teams.microsoft.com/l/message/19:x/1".into()),94
link: Some("https://teams.microsoft.com/l/message/19:x/1".into()),95
mentions: Vec::new(),93
}96
}94
}97
}95
98
@@ -26,6 +26,38 @@ pub fn iso_date_nl(value: &str) -> Option<String> {
26
26
.map(date_nl)
27
27
}
28
28
29
/// Invoer van een datum: `15 jan 2026`, `15-01-2026`, `15-1-26`, `15/01/2026`
30
/// of `2026-01-15`, als `YYYY-MM-DD`. Leeg → `Some("")` (geen datum),
31
/// onleesbaar → `None`.
32
pub fn parse_date_input(value: &str) -> Option<String> {
33
let value = value.trim().to_lowercase();
34
if value.is_empty() {
35
return Some(String::new());
36
}
37
let parts: Vec<&str> = value
38
.split([' ', '-', '/', '.'])
39
.filter(|part| !part.is_empty())
40
.collect();
41
let [first, second, third] = parts.as_slice() else {
42
return None;
43
};
44
let number = |part: &str| part.parse::<u32>().ok();
45
let (year, month, day) = if first.len() == 4 {
46
(number(first)? as i32, number(second)?, number(third)?)
47
} else {
48
let month = number(second).or_else(|| {
49
MONTHS
50
.iter()
51
.position(|name| second.starts_with(name))
52
.map(|index| index as u32 + 1)
53
})?;
54
let year = number(third)? as i32;
55
let year = if third.len() == 2 { 2000 + year } else { year };
56
(year, month, number(first)?)
57
};
58
NaiveDate::from_ymd_opt(year, month, day).map(|date| date.format("%Y-%m-%d").to_string())
59
}
60
29
61
#[cfg(test)]
30
62
mod tests {
31
63
use super::*;
@@ -41,4 +73,29 @@ mod tests {
41
73
assert_eq!(iso_date_nl("2026-03-02").as_deref(), Some("2 mrt 2026"));
42
74
assert_eq!(iso_date_nl(""), None);
43
75
}
76
77
#[test]
78
fn reads_dates_as_people_type_them() {
79
for input in [
80
"15 jan 2026",
81
"15-01-2026",
82
"15-1-26",
83
"15/01/2026",
84
"2026-01-15",
85
" 15 Januari 2026 ",
86
] {
87
assert_eq!(
88
parse_date_input(input).as_deref(),
89
Some("2026-01-15"),
90
"{input}"
91
);
92
}
93
assert_eq!(
94
parse_date_input("2 mrt 2026").as_deref(),
95
Some("2026-03-02")
96
);
97
assert_eq!(parse_date_input("").as_deref(), Some(""));
98
assert_eq!(parse_date_input("31-02-2026"), None);
99
assert_eq!(parse_date_input("morgen"), None);
100
}
44
101
}
@@ -26,6 +26,38 @@ pub fn iso_date_nl(value: &str) -> Option<String> {26
.map(date_nl)26
.map(date_nl)27
}27
}28
28
29
/// Invoer van een datum: `15 jan 2026`, `15-01-2026`, `15-1-26`, `15/01/2026`30
/// of `2026-01-15`, als `YYYY-MM-DD`. Leeg → `Some("")` (geen datum),31
/// onleesbaar → `None`.32
pub fn parse_date_input(value: &str) -> Option<String> {33
let value = value.trim().to_lowercase();34
if value.is_empty() {35
return Some(String::new());36
}37
let parts: Vec<&str> = value38
.split([' ', '-', '/', '.'])39
.filter(|part| !part.is_empty())40
.collect();41
let [first, second, third] = parts.as_slice() else {42
return None;43
};44
let number = |part: &str| part.parse::<u32>().ok();45
let (year, month, day) = if first.len() == 4 {46
(number(first)? as i32, number(second)?, number(third)?)47
} else {48
let month = number(second).or_else(|| {49
MONTHS50
.iter()51
.position(|name| second.starts_with(name))52
.map(|index| index as u32 + 1)53
})?;54
let year = number(third)? as i32;55
let year = if third.len() == 2 { 2000 + year } else { year };56
(year, month, number(first)?)57
};58
NaiveDate::from_ymd_opt(year, month, day).map(|date| date.format("%Y-%m-%d").to_string())59
}60
29
#[cfg(test)]61
#[cfg(test)]30
mod tests {62
mod tests {31
use super::*;63
use super::*;@@ -41,4 +73,29 @@ mod tests {41
assert_eq!(iso_date_nl("2026-03-02").as_deref(), Some("2 mrt 2026"));73
assert_eq!(iso_date_nl("2026-03-02").as_deref(), Some("2 mrt 2026"));42
assert_eq!(iso_date_nl(""), None);74
assert_eq!(iso_date_nl(""), None);43
}75
}76
77
#[test]78
fn reads_dates_as_people_type_them() {79
for input in [80
"15 jan 2026",81
"15-01-2026",82
"15-1-26",83
"15/01/2026",84
"2026-01-15",85
" 15 Januari 2026 ",86
] {87
assert_eq!(88
parse_date_input(input).as_deref(),89
Some("2026-01-15"),90
"{input}"91
);92
}93
assert_eq!(94
parse_date_input("2 mrt 2026").as_deref(),95
Some("2026-03-02")96
);97
assert_eq!(parse_date_input("").as_deref(), Some(""));98
assert_eq!(parse_date_input("31-02-2026"), None);99
assert_eq!(parse_date_input("morgen"), None);100
}44
}101
}@@ -20,6 +20,7 @@ pub mod model;
20
20
pub mod planning;
21
21
pub mod ponos;
22
22
pub mod session;
23
pub mod tickets;
23
24
pub mod token;
24
25
25
26
pub use client::{CardsClient, ClientError};
@@ -20,6 +20,7 @@ pub mod model;20
pub mod planning;20
pub mod planning;21
pub mod ponos;21
pub mod ponos;22
pub mod session;22
pub mod session;23
pub mod tickets;23
pub mod token;24
pub mod token;24
25
25
pub use client::{CardsClient, ClientError};26
pub use client::{CardsClient, ClientError};@@ -1,6 +1,9 @@
1
1
//! Ponos (`/ponos/ponos_api.php`) met het app-token (scope `ponos`): groepen,
2
//! «Mijn taken», een taak maken en afronden. Ponos staat een app-token alleen
3
//! deze taakacties toe.
2
//! «Mijn taken», het bord per groep (lezen, maken, bewerken, slepen) en
3
//! afronden. Ponos staat een app-token alleen taakacties toe (ict/ponos
4
//! `ponos_app_token_actions()`), geen groepen, leden of sleutels.
5
6
use std::collections::HashMap;
4
7
5
8
use serde::Deserialize;
6
9
use url::Url;
@@ -10,6 +13,10 @@ use crate::client::{CardsClient, ClientError, json_or_error};
10
13
/// Virtuele groep met de taken die aan de gebruiker zijn toegewezen.
11
14
pub const MY_TASKS_GROUP: &str = "__my_tasks__";
12
15
16
/// De kolommen van een Ponos-bord, in deze volgorde (`PONOS_STATUS_*`).
17
pub const STATUSES: [&str; 3] = ["todo", "in_progress", "done"];
18
pub const STATUS_DONE: &str = "done";
19
13
20
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
14
21
pub struct PonosGroup {
15
22
pub id: String,
@@ -20,6 +27,9 @@ pub struct PonosGroup {
20
27
pub can_create_tasks: bool,
21
28
#[serde(default = "yes")]
22
29
pub has_task_access: bool,
30
/// Open taken (todo + in progress).
31
#[serde(default)]
32
pub task_count: u32,
23
33
}
24
34
25
35
fn yes() -> bool {
@@ -31,6 +41,11 @@ impl PonosGroup {
31
41
pub fn accepts_new_tasks(&self) -> bool {
32
42
!self.is_virtual && self.can_create_tasks && self.has_task_access
33
43
}
44
45
/// Taken in deze groep mogen worden bewerkt en versleept.
46
pub fn editable(&self) -> bool {
47
self.is_virtual || self.has_task_access
48
}
34
49
}
35
50
36
51
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
@@ -49,6 +64,18 @@ pub struct PonosTask {
49
64
/// `YYYY-MM-DD` of leeg.
50
65
#[serde(default)]
51
66
pub due_date: String,
67
#[serde(default)]
68
pub description: String,
69
#[serde(default)]
70
pub assignee_email: String,
71
#[serde(default)]
72
pub category_label: String,
73
#[serde(default)]
74
pub checklist_total: u32,
75
#[serde(default)]
76
pub checklist_done: u32,
77
#[serde(default = "yes")]
78
pub can_edit: bool,
52
79
}
53
80
54
81
impl PonosTask {
@@ -69,6 +96,64 @@ impl PonosTask {
69
96
}
70
97
}
71
98
99
/// Velden van een nieuwe of bewerkte taak. Bij bewerken gaan alle velden mee
100
/// (leeg = wissen); `target_group` verplaatst de taak naar een andere groep.
101
#[derive(Debug, Clone, Default, PartialEq, Eq)]
102
pub struct TaskInput {
103
pub title: String,
104
pub description: String,
105
/// `YYYY-MM-DD` of leeg.
106
pub due_date: String,
107
pub assignee_email: String,
108
pub target_group: Option<String>,
109
}
110
111
impl TaskInput {
112
fn form(&self) -> Vec<(&'static str, &str)> {
113
let mut form = vec![
114
("title", self.title.as_str()),
115
("description", self.description.as_str()),
116
("due_date", self.due_date.as_str()),
117
("assignee_email", self.assignee_email.as_str()),
118
];
119
if let Some(group) = self.target_group.as_deref() {
120
form.push(("target_group", group));
121
}
122
form
123
}
124
}
125
126
/// `navigation`: alle groepen die de gebruiker ziet (eerst «Mijn taken»),
127
/// de namen van de statussen en wie er is ingelogd.
128
#[derive(Debug, Clone, Default, PartialEq, Eq)]
129
pub struct PonosNavigation {
130
pub groups: Vec<PonosGroup>,
131
pub status_labels: HashMap<String, String>,
132
pub user_email: String,
133
}
134
135
impl PonosNavigation {
136
/// Naam van een status zoals Ponos die toont, anders `fallback`.
137
pub fn status_label(&self, status: &str, fallback: impl FnOnce() -> String) -> String {
138
self.status_labels
139
.get(status)
140
.filter(|label| !label.trim().is_empty())
141
.cloned()
142
.unwrap_or_else(fallback)
143
}
144
}
145
146
/// Ponos-webpagina van een groep.
147
pub fn group_url(base_url: &str, group: &str) -> String {
148
let mut url = Url::parse(&format!(
149
"{}/ponos/index.php",
150
base_url.trim_end_matches('/')
151
))
152
.unwrap_or_else(|_| Url::parse("https://sleutels.kvt.nl/ponos/index.php").expect("vaste url"));
153
url.query_pairs_mut().append_pair("group", group);
154
url.to_string()
155
}
156
72
157
pub fn task_url(base_url: &str, group: &str, task: &str) -> String {
73
158
let mut url = Url::parse(&format!(
74
159
"{}/ponos/index.php",
@@ -85,6 +170,20 @@ pub fn task_url(base_url: &str, group: &str, task: &str) -> String {
85
170
struct NavigationEnvelope {
86
171
#[serde(default)]
87
172
groups: Vec<PonosGroup>,
173
#[serde(default)]
174
statuses: HashMap<String, String>,
175
#[serde(default)]
176
user_email: String,
177
}
178
179
impl From<NavigationEnvelope> for PonosNavigation {
180
fn from(envelope: NavigationEnvelope) -> Self {
181
PonosNavigation {
182
groups: envelope.groups,
183
status_labels: envelope.statuses,
184
user_email: envelope.user_email,
185
}
186
}
88
187
}
89
188
90
189
#[derive(Deserialize)]
@@ -152,6 +251,104 @@ impl CardsClient {
152
251
.collect())
153
252
}
154
253
254
/// Alle groepen (ook «Mijn taken») met de statusnamen, voor het bord.
255
pub async fn ponos_navigation(&self, token: &str) -> Result<PonosNavigation, ClientError> {
256
let envelope: NavigationEnvelope =
257
self.ponos_get(token, &[("action", "navigation")]).await?;
258
Ok(envelope.into())
259
}
260
261
/// Alle taken op het bord van een groep (ook afgerond, niet gearchiveerd),
262
/// in de volgorde van Ponos.
263
pub async fn ponos_tasks(
264
&self,
265
token: &str,
266
group: &str,
267
) -> Result<Vec<PonosTask>, ClientError> {
268
let envelope: TasksEnvelope = self
269
.ponos_get(token, &[("action", "list_tasks"), ("group", group)])
270
.await?;
271
Ok(envelope.tasks)
272
}
273
274
/// Nieuwe taak met alle velden uit `input` (`target_group` telt niet).
275
pub async fn ponos_create(
276
&self,
277
token: &str,
278
group: &str,
279
input: &TaskInput,
280
) -> Result<PonosTask, ClientError> {
281
let input = TaskInput {
282
target_group: None,
283
..input.clone()
284
};
285
let mut form = vec![("action", "create_task"), ("group", group)];
286
form.extend(input.form());
287
let envelope: TaskEnvelope = self.ponos_post(token, &form).await?;
288
Ok(envelope.task)
289
}
290
291
/// Taak bewerken; met `target_group` ook naar een andere groep.
292
pub async fn ponos_update_task(
293
&self,
294
token: &str,
295
group: &str,
296
task: &str,
297
input: &TaskInput,
298
) -> Result<PonosTask, ClientError> {
299
let mut form = vec![("action", "update_task"), ("group", group), ("task", task)];
300
form.extend(input.form());
301
let envelope: TaskEnvelope = self.ponos_post(token, &form).await?;
302
Ok(envelope.task)
303
}
304
305
/// Slepen: taak naar kolom `status` op plek `position` (0 = boven) in zijn groep.
306
pub async fn ponos_reorder_task(
307
&self,
308
token: &str,
309
group: &str,
310
task: &str,
311
status: &str,
312
position: usize,
313
) -> Result<PonosTask, ClientError> {
314
let position = position.to_string();
315
let envelope: TaskEnvelope = self
316
.ponos_post(
317
token,
318
&[
319
("action", "reorder_task"),
320
("group", group),
321
("task", task),
322
("status", status),
323
("position", &position),
324
],
325
)
326
.await?;
327
Ok(envelope.task)
328
}
329
330
/// Alleen de status (behoudt de plek niet; Ponos zet hem onderaan).
331
pub async fn ponos_set_status(
332
&self,
333
token: &str,
334
group: &str,
335
task: &str,
336
status: &str,
337
) -> Result<PonosTask, ClientError> {
338
let envelope: TaskEnvelope = self
339
.ponos_post(
340
token,
341
&[
342
("action", "update_status"),
343
("group", group),
344
("task", task),
345
("status", status),
346
],
347
)
348
.await?;
349
Ok(envelope.task)
350
}
351
155
352
/// Open taken die aan de gebruiker zijn toegewezen, eerst die met de vroegste deadline.
156
353
pub async fn ponos_my_tasks(&self, token: &str) -> Result<Vec<PonosTask>, ClientError> {
157
354
let envelope: TasksEnvelope = self
@@ -208,6 +405,89 @@ impl CardsClient {
208
405
}
209
406
}
210
407
408
/// Taken van één kolom, in de volgorde van Ponos.
409
pub fn column<'a>(tasks: &'a [PonosTask], status: &'a str) -> impl Iterator<Item = &'a PonosTask> {
410
tasks.iter().filter(move |task| task.status == status)
411
}
412
413
/// Plek die Ponos verwacht (`reorder_task`, zonder de gesleepte taak zelf) als
414
/// `dragged` boven taak nummer `before` van kolom `status` valt; `None` = onderaan.
415
pub fn drop_position(
416
tasks: &[PonosTask],
417
dragged: &str,
418
status: &str,
419
before: Option<usize>,
420
) -> usize {
421
let others: Vec<&PonosTask> = column(tasks, status)
422
.filter(|task| task.id != dragged)
423
.collect();
424
match before {
425
None => others.len(),
426
Some(index) => {
427
let target = column(tasks, status)
428
.nth(index)
429
.map(|task| task.id.as_str());
430
match target {
431
Some(id) if id != dragged => others
432
.iter()
433
.position(|task| task.id == id)
434
.unwrap_or(others.len()),
435
// Op zichzelf: plek blijft gelijk.
436
Some(_) => column(tasks, status)
437
.position(|task| task.id == dragged)
438
.unwrap_or(0),
439
None => others.len(),
440
}
441
}
442
}
443
}
444
445
/// Lokaal hetzelfde doen als `reorder_task` (meteen tonen, daarna verversen).
446
/// Geeft `false` als de taak er niet is.
447
pub fn apply_move(tasks: &mut Vec<PonosTask>, id: &str, status: &str, position: usize) -> bool {
448
let Some(from) = tasks.iter().position(|task| task.id == id) else {
449
return false;
450
};
451
let mut task = tasks.remove(from);
452
task.status = status.to_owned();
453
let slots: Vec<usize> = tasks
454
.iter()
455
.enumerate()
456
.filter(|(_, other)| other.status == status)
457
.map(|(index, _)| index)
458
.collect();
459
let insert_at = match slots.get(position) {
460
Some(&index) => index,
461
None => slots.last().map_or(tasks.len(), |&last| last + 1),
462
};
463
tasks.insert(insert_at, task);
464
true
465
}
466
467
/// Naam uit een e-mailadres: `jan.de.vries@example.com` → `Jan de Vries`.
468
pub fn name_from_email(email: &str) -> String {
469
const LOWER: [&str; 6] = ["de", "van", "der", "den", "het", "ter"];
470
let local = email.split('@').next().unwrap_or_default();
471
local
472
.split(['.', '_', '-'])
473
.filter(|part| !part.is_empty())
474
.enumerate()
475
.map(|(index, part)| {
476
let lower = part.to_lowercase();
477
if index > 0 && LOWER.contains(&lower.as_str()) {
478
lower
479
} else {
480
let mut chars = lower.chars();
481
chars
482
.next()
483
.map(|first| first.to_uppercase().chain(chars).collect())
484
.unwrap_or_default()
485
}
486
})
487
.collect::<Vec<String>>()
488
.join(" ")
489
}
490
211
491
/// Alleen open taken; met deadline eerst (vroegste bovenaan), daarna zonder.
212
492
pub fn sort_open(tasks: Vec<PonosTask>) -> Vec<PonosTask> {
213
493
let mut open: Vec<PonosTask> = tasks.into_iter().filter(PonosTask::is_open).collect();
@@ -266,4 +546,124 @@ mod tests {
266
546
"https://sleutels.kvt.nl/ponos/index.php?group=g1&task=t1"
267
547
);
268
548
}
549
550
fn board() -> Vec<PonosTask> {
551
let json = r#"{"ok":true,"tasks":[
552
{"id":"a","group_id":"g","title":"A","status":"todo"},
553
{"id":"b","group_id":"g","title":"B","status":"todo"},
554
{"id":"p","group_id":"g","title":"P","status":"in_progress"},
555
{"id":"c","group_id":"g","title":"C","status":"todo"},
556
{"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}]}"#;
557
serde_json::from_str::<TasksEnvelope>(json).unwrap().tasks
558
}
559
560
fn ids<'a>(tasks: &'a [PonosTask], status: &'a str) -> Vec<&'a str> {
561
column(tasks, status).map(|task| task.id.as_str()).collect()
562
}
563
564
#[test]
565
fn navigation_keeps_all_groups_and_status_names() {
566
let json = r#"{"ok":true,"groups":[
567
{"id":"__my_tasks__","name":"Mijn Taken","virtual":true,"can_create_tasks":false,"task_count":2},
568
{"id":"g1","name":"ICT","can_create_tasks":true,"has_task_access":true},
569
{"id":"g2","name":"Alleen lezen","can_create_tasks":true,"has_task_access":false}],
570
"statuses":{"todo":"Nog te doen","in_progress":"Onderhanden","done":"Afgerond"},
571
"user_email":"tester@example.com"}"#;
572
let navigation: PonosNavigation = serde_json::from_str::<NavigationEnvelope>(json)
573
.unwrap()
574
.into();
575
assert_eq!(navigation.groups.len(), 3);
576
assert_eq!(navigation.groups[0].task_count, 2);
577
assert!(navigation.groups[0].editable() && !navigation.groups[0].accepts_new_tasks());
578
assert!(navigation.groups[1].editable() && navigation.groups[1].accepts_new_tasks());
579
assert!(!navigation.groups[2].editable());
580
assert_eq!(
581
navigation.status_label("in_progress", || "x".into()),
582
"Onderhanden"
583
);
584
assert_eq!(
585
navigation.status_label("onbekend", || "Terugval".into()),
586
"Terugval"
587
);
588
assert_eq!(navigation.user_email, "tester@example.com");
589
}
590
591
#[test]
592
fn board_tasks_read_the_extra_fields() {
593
let tasks = board();
594
assert_eq!(ids(&tasks, "todo"), ["a", "b", "c"]);
595
let done = &tasks[4];
596
assert_eq!(done.assignee_email, "jan.de.vries@example.com");
597
assert_eq!((done.checklist_done, done.checklist_total), (1, 3));
598
assert!(!done.can_edit);
599
assert!(tasks[0].can_edit, "zonder veld: bewerken mag");
600
}
601
602
#[test]
603
fn drop_position_matches_ponos_reorder() {
604
let tasks = board();
605
// c boven a: plek 0.
606
assert_eq!(drop_position(&tasks, "c", "todo", Some(0)), 0);
607
// a boven c (index 2): zonder a is c plek 1.
608
assert_eq!(drop_position(&tasks, "a", "todo", Some(2)), 1);
609
// a op zichzelf blijft 0; onderaan = aantal anderen.
610
assert_eq!(drop_position(&tasks, "a", "todo", Some(0)), 0);
611
assert_eq!(drop_position(&tasks, "a", "todo", None), 2);
612
// Naar een andere kolom.
613
assert_eq!(drop_position(&tasks, "a", "in_progress", Some(0)), 0);
614
assert_eq!(drop_position(&tasks, "a", "in_progress", None), 1);
615
assert_eq!(drop_position(&tasks, "a", "done", Some(9)), 1);
616
}
617
618
#[test]
619
fn apply_move_reorders_and_changes_status() {
620
let mut tasks = board();
621
assert!(apply_move(&mut tasks, "c", "todo", 0));
622
assert_eq!(ids(&tasks, "todo"), ["c", "a", "b"]);
623
assert!(apply_move(&mut tasks, "c", "todo", 99));
624
assert_eq!(ids(&tasks, "todo"), ["a", "b", "c"]);
625
assert!(apply_move(&mut tasks, "b", "in_progress", 0));
626
assert_eq!(ids(&tasks, "in_progress"), ["b", "p"]);
627
assert_eq!(ids(&tasks, "todo"), ["a", "c"]);
628
assert!(apply_move(&mut tasks, "a", "done", 5));
629
assert_eq!(ids(&tasks, "done"), ["d", "a"]);
630
let mut only = vec![tasks[0].clone()];
631
assert!(apply_move(&mut only, &tasks[0].id.clone(), "todo", 0));
632
assert!(!apply_move(&mut tasks, "bestaat-niet", "todo", 0));
633
assert_eq!(tasks.len(), 5);
634
}
635
636
#[test]
637
fn task_input_sends_every_field_and_optional_group() {
638
let input = TaskInput {
639
title: "T".into(),
640
description: "O".into(),
641
due_date: "2026-12-03".into(),
642
assignee_email: String::new(),
643
target_group: Some("g2".into()),
644
};
645
let form = input.form();
646
assert!(
647
form.contains(&("assignee_email", "")),
648
"leeg = toewijzing wissen"
649
);
650
assert!(form.contains(&("target_group", "g2")));
651
let rest = TaskInput {
652
target_group: None,
653
..input
654
};
655
let without = rest.form();
656
assert!(!without.iter().any(|(key, _)| *key == "target_group"));
657
}
658
659
#[test]
660
fn names_from_kvt_addresses() {
661
assert_eq!(name_from_email("jan.de.vries@example.com"), "Jan de Vries");
662
assert_eq!(name_from_email("PIET_JANSEN@example.com"), "Piet Jansen");
663
assert_eq!(name_from_email(""), "");
664
assert_eq!(
665
group_url("https://sleutels.kvt.nl/", "__my_tasks__"),
666
"https://sleutels.kvt.nl/ponos/index.php?group=__my_tasks__"
667
);
668
}
269
669
}
@@ -1,6 +1,9 @@1
//! Ponos (`/ponos/ponos_api.php`) met het app-token (scope `ponos`): groepen,1
//! Ponos (`/ponos/ponos_api.php`) met het app-token (scope `ponos`): groepen,2
//! «Mijn taken», een taak maken en afronden. Ponos staat een app-token alleen2
//! «Mijn taken», het bord per groep (lezen, maken, bewerken, slepen) en3
//! deze taakacties toe.3
//! afronden. Ponos staat een app-token alleen taakacties toe (ict/ponos4
//! `ponos_app_token_actions()`), geen groepen, leden of sleutels.5
6
use std::collections::HashMap;4
7
5
use serde::Deserialize;8
use serde::Deserialize;6
use url::Url;9
use url::Url;@@ -10,6 +13,10 @@ use crate::client::{CardsClient, ClientError, json_or_error};10
/// Virtuele groep met de taken die aan de gebruiker zijn toegewezen.13
/// Virtuele groep met de taken die aan de gebruiker zijn toegewezen.11
pub const MY_TASKS_GROUP: &str = "__my_tasks__";14
pub const MY_TASKS_GROUP: &str = "__my_tasks__";12
15
16
/// De kolommen van een Ponos-bord, in deze volgorde (`PONOS_STATUS_*`).17
pub const STATUSES: [&str; 3] = ["todo", "in_progress", "done"];18
pub const STATUS_DONE: &str = "done";19
13
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]20
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]14
pub struct PonosGroup {21
pub struct PonosGroup {15
pub id: String,22
pub id: String,@@ -20,6 +27,9 @@ pub struct PonosGroup {20
pub can_create_tasks: bool,27
pub can_create_tasks: bool,21
#[serde(default = "yes")]28
#[serde(default = "yes")]22
pub has_task_access: bool,29
pub has_task_access: bool,30
/// Open taken (todo + in progress).31
#[serde(default)]32
pub task_count: u32,23
}33
}24
34
25
fn yes() -> bool {35
fn yes() -> bool {@@ -31,6 +41,11 @@ impl PonosGroup {31
pub fn accepts_new_tasks(&self) -> bool {41
pub fn accepts_new_tasks(&self) -> bool {32
!self.is_virtual && self.can_create_tasks && self.has_task_access42
!self.is_virtual && self.can_create_tasks && self.has_task_access33
}43
}44
45
/// Taken in deze groep mogen worden bewerkt en versleept.46
pub fn editable(&self) -> bool {47
self.is_virtual || self.has_task_access48
}34
}49
}35
50
36
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]51
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]@@ -49,6 +64,18 @@ pub struct PonosTask {49
/// `YYYY-MM-DD` of leeg.64
/// `YYYY-MM-DD` of leeg.50
#[serde(default)]65
#[serde(default)]51
pub due_date: String,66
pub due_date: String,67
#[serde(default)]68
pub description: String,69
#[serde(default)]70
pub assignee_email: String,71
#[serde(default)]72
pub category_label: String,73
#[serde(default)]74
pub checklist_total: u32,75
#[serde(default)]76
pub checklist_done: u32,77
#[serde(default = "yes")]78
pub can_edit: bool,52
}79
}53
80
54
impl PonosTask {81
impl PonosTask {@@ -69,6 +96,64 @@ impl PonosTask {69
}96
}70
}97
}71
98
99
/// Velden van een nieuwe of bewerkte taak. Bij bewerken gaan alle velden mee100
/// (leeg = wissen); `target_group` verplaatst de taak naar een andere groep.101
#[derive(Debug, Clone, Default, PartialEq, Eq)]102
pub struct TaskInput {103
pub title: String,104
pub description: String,105
/// `YYYY-MM-DD` of leeg.106
pub due_date: String,107
pub assignee_email: String,108
pub target_group: Option<String>,109
}110
111
impl TaskInput {112
fn form(&self) -> Vec<(&'static str, &str)> {113
let mut form = vec![114
("title", self.title.as_str()),115
("description", self.description.as_str()),116
("due_date", self.due_date.as_str()),117
("assignee_email", self.assignee_email.as_str()),118
];119
if let Some(group) = self.target_group.as_deref() {120
form.push(("target_group", group));121
}122
form123
}124
}125
126
/// `navigation`: alle groepen die de gebruiker ziet (eerst «Mijn taken»),127
/// de namen van de statussen en wie er is ingelogd.128
#[derive(Debug, Clone, Default, PartialEq, Eq)]129
pub struct PonosNavigation {130
pub groups: Vec<PonosGroup>,131
pub status_labels: HashMap<String, String>,132
pub user_email: String,133
}134
135
impl PonosNavigation {136
/// Naam van een status zoals Ponos die toont, anders `fallback`.137
pub fn status_label(&self, status: &str, fallback: impl FnOnce() -> String) -> String {138
self.status_labels139
.get(status)140
.filter(|label| !label.trim().is_empty())141
.cloned()142
.unwrap_or_else(fallback)143
}144
}145
146
/// Ponos-webpagina van een groep.147
pub fn group_url(base_url: &str, group: &str) -> String {148
let mut url = Url::parse(&format!(149
"{}/ponos/index.php",150
base_url.trim_end_matches('/')151
))152
.unwrap_or_else(|_| Url::parse("https://sleutels.kvt.nl/ponos/index.php").expect("vaste url"));153
url.query_pairs_mut().append_pair("group", group);154
url.to_string()155
}156
72
pub fn task_url(base_url: &str, group: &str, task: &str) -> String {157
pub fn task_url(base_url: &str, group: &str, task: &str) -> String {73
let mut url = Url::parse(&format!(158
let mut url = Url::parse(&format!(74
"{}/ponos/index.php",159
"{}/ponos/index.php",@@ -85,6 +170,20 @@ pub fn task_url(base_url: &str, group: &str, task: &str) -> String {85
struct NavigationEnvelope {170
struct NavigationEnvelope {86
#[serde(default)]171
#[serde(default)]87
groups: Vec<PonosGroup>,172
groups: Vec<PonosGroup>,173
#[serde(default)]174
statuses: HashMap<String, String>,175
#[serde(default)]176
user_email: String,177
}178
179
impl From<NavigationEnvelope> for PonosNavigation {180
fn from(envelope: NavigationEnvelope) -> Self {181
PonosNavigation {182
groups: envelope.groups,183
status_labels: envelope.statuses,184
user_email: envelope.user_email,185
}186
}88
}187
}89
188
90
#[derive(Deserialize)]189
#[derive(Deserialize)]@@ -152,6 +251,104 @@ impl CardsClient {152
.collect())251
.collect())153
}252
}154
253
254
/// Alle groepen (ook «Mijn taken») met de statusnamen, voor het bord.255
pub async fn ponos_navigation(&self, token: &str) -> Result<PonosNavigation, ClientError> {256
let envelope: NavigationEnvelope =257
self.ponos_get(token, &[("action", "navigation")]).await?;258
Ok(envelope.into())259
}260
261
/// Alle taken op het bord van een groep (ook afgerond, niet gearchiveerd),262
/// in de volgorde van Ponos.263
pub async fn ponos_tasks(264
&self,265
token: &str,266
group: &str,267
) -> Result<Vec<PonosTask>, ClientError> {268
let envelope: TasksEnvelope = self269
.ponos_get(token, &[("action", "list_tasks"), ("group", group)])270
.await?;271
Ok(envelope.tasks)272
}273
274
/// Nieuwe taak met alle velden uit `input` (`target_group` telt niet).275
pub async fn ponos_create(276
&self,277
token: &str,278
group: &str,279
input: &TaskInput,280
) -> Result<PonosTask, ClientError> {281
let input = TaskInput {282
target_group: None,283
..input.clone()284
};285
let mut form = vec![("action", "create_task"), ("group", group)];286
form.extend(input.form());287
let envelope: TaskEnvelope = self.ponos_post(token, &form).await?;288
Ok(envelope.task)289
}290
291
/// Taak bewerken; met `target_group` ook naar een andere groep.292
pub async fn ponos_update_task(293
&self,294
token: &str,295
group: &str,296
task: &str,297
input: &TaskInput,298
) -> Result<PonosTask, ClientError> {299
let mut form = vec![("action", "update_task"), ("group", group), ("task", task)];300
form.extend(input.form());301
let envelope: TaskEnvelope = self.ponos_post(token, &form).await?;302
Ok(envelope.task)303
}304
305
/// Slepen: taak naar kolom `status` op plek `position` (0 = boven) in zijn groep.306
pub async fn ponos_reorder_task(307
&self,308
token: &str,309
group: &str,310
task: &str,311
status: &str,312
position: usize,313
) -> Result<PonosTask, ClientError> {314
let position = position.to_string();315
let envelope: TaskEnvelope = self316
.ponos_post(317
token,318
&[319
("action", "reorder_task"),320
("group", group),321
("task", task),322
("status", status),323
("position", &position),324
],325
)326
.await?;327
Ok(envelope.task)328
}329
330
/// Alleen de status (behoudt de plek niet; Ponos zet hem onderaan).331
pub async fn ponos_set_status(332
&self,333
token: &str,334
group: &str,335
task: &str,336
status: &str,337
) -> Result<PonosTask, ClientError> {338
let envelope: TaskEnvelope = self339
.ponos_post(340
token,341
&[342
("action", "update_status"),343
("group", group),344
("task", task),345
("status", status),346
],347
)348
.await?;349
Ok(envelope.task)350
}351
155
/// Open taken die aan de gebruiker zijn toegewezen, eerst die met de vroegste deadline.352
/// Open taken die aan de gebruiker zijn toegewezen, eerst die met de vroegste deadline.156
pub async fn ponos_my_tasks(&self, token: &str) -> Result<Vec<PonosTask>, ClientError> {353
pub async fn ponos_my_tasks(&self, token: &str) -> Result<Vec<PonosTask>, ClientError> {157
let envelope: TasksEnvelope = self354
let envelope: TasksEnvelope = self@@ -208,6 +405,89 @@ impl CardsClient {208
}405
}209
}406
}210
407
408
/// Taken van één kolom, in de volgorde van Ponos.409
pub fn column<'a>(tasks: &'a [PonosTask], status: &'a str) -> impl Iterator<Item = &'a PonosTask> {410
tasks.iter().filter(move |task| task.status == status)411
}412
413
/// Plek die Ponos verwacht (`reorder_task`, zonder de gesleepte taak zelf) als414
/// `dragged` boven taak nummer `before` van kolom `status` valt; `None` = onderaan.415
pub fn drop_position(416
tasks: &[PonosTask],417
dragged: &str,418
status: &str,419
before: Option<usize>,420
) -> usize {421
let others: Vec<&PonosTask> = column(tasks, status)422
.filter(|task| task.id != dragged)423
.collect();424
match before {425
None => others.len(),426
Some(index) => {427
let target = column(tasks, status)428
.nth(index)429
.map(|task| task.id.as_str());430
match target {431
Some(id) if id != dragged => others432
.iter()433
.position(|task| task.id == id)434
.unwrap_or(others.len()),435
// Op zichzelf: plek blijft gelijk.436
Some(_) => column(tasks, status)437
.position(|task| task.id == dragged)438
.unwrap_or(0),439
None => others.len(),440
}441
}442
}443
}444
445
/// Lokaal hetzelfde doen als `reorder_task` (meteen tonen, daarna verversen).446
/// Geeft `false` als de taak er niet is.447
pub fn apply_move(tasks: &mut Vec<PonosTask>, id: &str, status: &str, position: usize) -> bool {448
let Some(from) = tasks.iter().position(|task| task.id == id) else {449
return false;450
};451
let mut task = tasks.remove(from);452
task.status = status.to_owned();453
let slots: Vec<usize> = tasks454
.iter()455
.enumerate()456
.filter(|(_, other)| other.status == status)457
.map(|(index, _)| index)458
.collect();459
let insert_at = match slots.get(position) {460
Some(&index) => index,461
None => slots.last().map_or(tasks.len(), |&last| last + 1),462
};463
tasks.insert(insert_at, task);464
true465
}466
467
/// Naam uit een e-mailadres: `jan.de.vries@example.com` → `Jan de Vries`.468
pub fn name_from_email(email: &str) -> String {469
const LOWER: [&str; 6] = ["de", "van", "der", "den", "het", "ter"];470
let local = email.split('@').next().unwrap_or_default();471
local472
.split(['.', '_', '-'])473
.filter(|part| !part.is_empty())474
.enumerate()475
.map(|(index, part)| {476
let lower = part.to_lowercase();477
if index > 0 && LOWER.contains(&lower.as_str()) {478
lower479
} else {480
let mut chars = lower.chars();481
chars482
.next()483
.map(|first| first.to_uppercase().chain(chars).collect())484
.unwrap_or_default()485
}486
})487
.collect::<Vec<String>>()488
.join(" ")489
}490
211
/// Alleen open taken; met deadline eerst (vroegste bovenaan), daarna zonder.491
/// Alleen open taken; met deadline eerst (vroegste bovenaan), daarna zonder.212
pub fn sort_open(tasks: Vec<PonosTask>) -> Vec<PonosTask> {492
pub fn sort_open(tasks: Vec<PonosTask>) -> Vec<PonosTask> {213
let mut open: Vec<PonosTask> = tasks.into_iter().filter(PonosTask::is_open).collect();493
let mut open: Vec<PonosTask> = tasks.into_iter().filter(PonosTask::is_open).collect();@@ -266,4 +546,124 @@ mod tests {266
"https://sleutels.kvt.nl/ponos/index.php?group=g1&task=t1"546
"https://sleutels.kvt.nl/ponos/index.php?group=g1&task=t1"267
);547
);268
}548
}549
550
fn board() -> Vec<PonosTask> {551
let json = r#"{"ok":true,"tasks":[552
{"id":"a","group_id":"g","title":"A","status":"todo"},553
{"id":"b","group_id":"g","title":"B","status":"todo"},554
{"id":"p","group_id":"g","title":"P","status":"in_progress"},555
{"id":"c","group_id":"g","title":"C","status":"todo"},556
{"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}]}"#;557
serde_json::from_str::<TasksEnvelope>(json).unwrap().tasks558
}559
560
fn ids<'a>(tasks: &'a [PonosTask], status: &'a str) -> Vec<&'a str> {561
column(tasks, status).map(|task| task.id.as_str()).collect()562
}563
564
#[test]565
fn navigation_keeps_all_groups_and_status_names() {566
let json = r#"{"ok":true,"groups":[567
{"id":"__my_tasks__","name":"Mijn Taken","virtual":true,"can_create_tasks":false,"task_count":2},568
{"id":"g1","name":"ICT","can_create_tasks":true,"has_task_access":true},569
{"id":"g2","name":"Alleen lezen","can_create_tasks":true,"has_task_access":false}],570
"statuses":{"todo":"Nog te doen","in_progress":"Onderhanden","done":"Afgerond"},571
"user_email":"tester@example.com"}"#;572
let navigation: PonosNavigation = serde_json::from_str::<NavigationEnvelope>(json)573
.unwrap()574
.into();575
assert_eq!(navigation.groups.len(), 3);576
assert_eq!(navigation.groups[0].task_count, 2);577
assert!(navigation.groups[0].editable() && !navigation.groups[0].accepts_new_tasks());578
assert!(navigation.groups[1].editable() && navigation.groups[1].accepts_new_tasks());579
assert!(!navigation.groups[2].editable());580
assert_eq!(581
navigation.status_label("in_progress", || "x".into()),582
"Onderhanden"583
);584
assert_eq!(585
navigation.status_label("onbekend", || "Terugval".into()),586
"Terugval"587
);588
assert_eq!(navigation.user_email, "tester@example.com");589
}590
591
#[test]592
fn board_tasks_read_the_extra_fields() {593
let tasks = board();594
assert_eq!(ids(&tasks, "todo"), ["a", "b", "c"]);595
let done = &tasks[4];596
assert_eq!(done.assignee_email, "jan.de.vries@example.com");597
assert_eq!((done.checklist_done, done.checklist_total), (1, 3));598
assert!(!done.can_edit);599
assert!(tasks[0].can_edit, "zonder veld: bewerken mag");600
}601
602
#[test]603
fn drop_position_matches_ponos_reorder() {604
let tasks = board();605
// c boven a: plek 0.606
assert_eq!(drop_position(&tasks, "c", "todo", Some(0)), 0);607
// a boven c (index 2): zonder a is c plek 1.608
assert_eq!(drop_position(&tasks, "a", "todo", Some(2)), 1);609
// a op zichzelf blijft 0; onderaan = aantal anderen.610
assert_eq!(drop_position(&tasks, "a", "todo", Some(0)), 0);611
assert_eq!(drop_position(&tasks, "a", "todo", None), 2);612
// Naar een andere kolom.613
assert_eq!(drop_position(&tasks, "a", "in_progress", Some(0)), 0);614
assert_eq!(drop_position(&tasks, "a", "in_progress", None), 1);615
assert_eq!(drop_position(&tasks, "a", "done", Some(9)), 1);616
}617
618
#[test]619
fn apply_move_reorders_and_changes_status() {620
let mut tasks = board();621
assert!(apply_move(&mut tasks, "c", "todo", 0));622
assert_eq!(ids(&tasks, "todo"), ["c", "a", "b"]);623
assert!(apply_move(&mut tasks, "c", "todo", 99));624
assert_eq!(ids(&tasks, "todo"), ["a", "b", "c"]);625
assert!(apply_move(&mut tasks, "b", "in_progress", 0));626
assert_eq!(ids(&tasks, "in_progress"), ["b", "p"]);627
assert_eq!(ids(&tasks, "todo"), ["a", "c"]);628
assert!(apply_move(&mut tasks, "a", "done", 5));629
assert_eq!(ids(&tasks, "done"), ["d", "a"]);630
let mut only = vec![tasks[0].clone()];631
assert!(apply_move(&mut only, &tasks[0].id.clone(), "todo", 0));632
assert!(!apply_move(&mut tasks, "bestaat-niet", "todo", 0));633
assert_eq!(tasks.len(), 5);634
}635
636
#[test]637
fn task_input_sends_every_field_and_optional_group() {638
let input = TaskInput {639
title: "T".into(),640
description: "O".into(),641
due_date: "2026-12-03".into(),642
assignee_email: String::new(),643
target_group: Some("g2".into()),644
};645
let form = input.form();646
assert!(647
form.contains(&("assignee_email", "")),648
"leeg = toewijzing wissen"649
);650
assert!(form.contains(&("target_group", "g2")));651
let rest = TaskInput {652
target_group: None,653
..input654
};655
let without = rest.form();656
assert!(!without.iter().any(|(key, _)| *key == "target_group"));657
}658
659
#[test]660
fn names_from_kvt_addresses() {661
assert_eq!(name_from_email("jan.de.vries@example.com"), "Jan de Vries");662
assert_eq!(name_from_email("PIET_JANSEN@example.com"), "Piet Jansen");663
assert_eq!(name_from_email(""), "");664
assert_eq!(665
group_url("https://sleutels.kvt.nl/", "__my_tasks__"),666
"https://sleutels.kvt.nl/ponos/index.php?group=__my_tasks__"667
);668
}269
}669
}@@ -0,0 +1,1024 @@
1
//! Asclepius-tickets via `/asclepius/api.php` met de app-token (scope `asclepius`).
2
//!
3
//! Wat de token mag, bepaalt Asclepius (`asclepius_app_token.php`): je eigen tickets
4
//! (ingediend, deelnemer, gemachtigde of aan jou toegewezen), lezen, aanmaken en een
5
//! gewoon bericht plaatsen. Geen status, toewijzing of ghost-berichten plaatsen.
6
//! Ghosts komen alleen mee voor ICT, binnen de regels van de webinterface.
7
8
use std::collections::{HashMap, HashSet};
9
10
use base64::Engine as _;
11
use serde::de::{self, Deserializer};
12
use serde::{Deserialize, Serialize};
13
use url::Url;
14
15
use crate::client::{CardsClient, ClientError, json_or_error};
16
17
/// Status van een gesloten ticket.
18
pub const STATUS_CLOSED: &str = "afgehandeld";
19
/// Categorieën die op het web alleen ICT kiest; het formulier toont ze niet.
20
pub const ICT_ONLY_CATEGORIES: [&str; 2] = ["Uitdiensttreding", "Indiensttreding"];
21
/// Asclepius: titel max. 150 tekens, beschrijving max. 20 000 in het formulier.
22
pub const TITLE_MAX: usize = 150;
23
pub const DESCRIPTION_MAX: usize = 20_000;
24
/// Zelfde grenzen als `add_ticket_message`.
25
pub const ATTACHMENTS_MAX: usize = 10;
26
pub const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
27
28
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
29
pub enum TicketFilter {
30
#[default]
31
Open,
32
Closed,
33
}
34
35
impl TicketFilter {
36
pub fn as_str(self) -> &'static str {
37
match self {
38
TicketFilter::Open => "open",
39
TicketFilter::Closed => "closed",
40
}
41
}
42
}
43
44
// --- lenient velden (SQLite via PDO geeft soms "12" in plaats van 12) ---------
45
46
fn de_u64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
47
match serde_json::Value::deserialize(deserializer)? {
48
serde_json::Value::Number(number) => number
49
.as_u64()
50
.or_else(|| number.as_f64().map(|value| value as u64))
51
.ok_or_else(|| de::Error::custom("geen getal")),
52
serde_json::Value::String(text) => text.trim().parse().map_err(de::Error::custom),
53
serde_json::Value::Null => Ok(0),
54
_ => Err(de::Error::custom("geen getal")),
55
}
56
}
57
58
fn de_i64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
59
match serde_json::Value::deserialize(deserializer)? {
60
serde_json::Value::Number(number) => Ok(number
61
.as_i64()
62
.or_else(|| number.as_f64().map(|value| value as i64))
63
.unwrap_or(0)),
64
serde_json::Value::String(text) => Ok(text.trim().parse().unwrap_or(0)),
65
serde_json::Value::Bool(value) => Ok(i64::from(value)),
66
_ => Ok(0),
67
}
68
}
69
70
fn de_bool<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
71
Ok(match serde_json::Value::deserialize(deserializer)? {
72
serde_json::Value::Bool(value) => value,
73
serde_json::Value::Number(number) => number.as_i64().unwrap_or(0) != 0,
74
serde_json::Value::String(text) => matches!(text.trim(), "1" | "true"),
75
_ => false,
76
})
77
}
78
79
fn de_string<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
80
Ok(match serde_json::Value::deserialize(deserializer)? {
81
serde_json::Value::String(text) => text,
82
serde_json::Value::Number(number) => number.to_string(),
83
_ => String::new(),
84
})
85
}
86
87
// --- model ------------------------------------------------------------------
88
89
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
90
pub struct Ticket {
91
#[serde(deserialize_with = "de_u64")]
92
pub id: u64,
93
#[serde(default, deserialize_with = "de_string")]
94
pub title: String,
95
#[serde(default, deserialize_with = "de_string")]
96
pub category: String,
97
#[serde(default, deserialize_with = "de_string")]
98
pub subcategory: String,
99
#[serde(default, deserialize_with = "de_string")]
100
pub user_email: String,
101
#[serde(default, deserialize_with = "de_string")]
102
pub requester_display_name: String,
103
#[serde(default, deserialize_with = "de_string")]
104
pub assigned_email: String,
105
#[serde(default, deserialize_with = "de_string")]
106
pub status: String,
107
#[serde(default, deserialize_with = "de_i64")]
108
pub priority: i64,
109
#[serde(default, deserialize_with = "de_string")]
110
pub created_at: String,
111
#[serde(default, deserialize_with = "de_string")]
112
pub updated_at: String,
113
#[serde(default, deserialize_with = "de_i64")]
114
pub message_count: i64,
115
}
116
117
impl Ticket {
118
pub fn is_closed(&self) -> bool {
119
is_closed(&self.status)
120
}
121
122
pub fn url(&self, base_url: &str) -> String {
123
ticket_url(base_url, self.id)
124
}
125
}
126
127
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
128
pub struct TicketAttachment {
129
#[serde(deserialize_with = "de_u64")]
130
pub id: u64,
131
#[serde(default, deserialize_with = "de_string")]
132
pub original_name: String,
133
#[serde(default, deserialize_with = "de_string")]
134
pub mime_type: String,
135
#[serde(default, deserialize_with = "de_i64")]
136
pub file_size: i64,
137
}
138
139
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
140
pub struct TicketMessage {
141
#[serde(deserialize_with = "de_u64")]
142
pub id: u64,
143
#[serde(default, deserialize_with = "de_string")]
144
pub sender_email: String,
145
/// `admin` (ICT) of `user`.
146
#[serde(default, deserialize_with = "de_string")]
147
pub sender_role: String,
148
#[serde(default, deserialize_with = "de_string")]
149
pub sender_display_name: String,
150
#[serde(default, deserialize_with = "de_string")]
151
pub message_text: String,
152
#[serde(default, deserialize_with = "de_string")]
153
pub created_at: String,
154
#[serde(default, deserialize_with = "de_bool")]
155
pub is_ghost: bool,
156
#[serde(default)]
157
pub attachments: Vec<TicketAttachment>,
158
}
159
160
impl TicketMessage {
161
pub fn sender_name(&self) -> String {
162
if self.sender_display_name.trim().is_empty() {
163
crate::ponos::name_from_email(&self.sender_email)
164
} else {
165
self.sender_display_name.trim().to_owned()
166
}
167
}
168
}
169
170
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
171
pub struct TicketDetail {
172
#[serde(flatten)]
173
pub ticket: Ticket,
174
#[serde(default, deserialize_with = "de_string")]
175
pub description: String,
176
#[serde(default)]
177
pub participant_emails: Vec<String>,
178
#[serde(default)]
179
pub messages: Vec<TicketMessage>,
180
}
181
182
#[derive(Debug, Clone, Default, PartialEq)]
183
pub struct Lookups {
184
pub categories: Vec<String>,
185
/// Categorie → subcategorieën, in de volgorde van Asclepius.
186
pub subcategories: HashMap<String, Vec<String>>,
187
}
188
189
impl Lookups {
190
/// Categorieën voor het formulier, zonder de ICT-only categorieën (zoals op het web).
191
pub fn form_categories(&self) -> Vec<String> {
192
self.categories
193
.iter()
194
.filter(|category| !ICT_ONLY_CATEGORIES.contains(&category.as_str()))
195
.cloned()
196
.collect()
197
}
198
199
pub fn subcategories_of(&self, category: &str) -> &[String] {
200
self.subcategories
201
.get(category)
202
.map(Vec::as_slice)
203
.unwrap_or_default()
204
}
205
}
206
207
#[derive(Debug, Clone, PartialEq, Eq)]
208
pub struct NewAttachment {
209
pub filename: String,
210
pub mime: String,
211
pub data: Vec<u8>,
212
}
213
214
#[derive(Debug, Clone, Default, PartialEq, Eq)]
215
pub struct NewTicket {
216
pub title: String,
217
pub category: String,
218
pub subcategory: Option<String>,
219
pub description: String,
220
/// 0–2, uit de twee vinkjes van het webformulier (`priority_from_flags`).
221
pub priority: u8,
222
pub participant_emails: Vec<String>,
223
pub attachments: Vec<NewAttachment>,
224
}
225
226
#[derive(Serialize)]
227
struct AttachmentBody<'a> {
228
filename: &'a str,
229
mime: &'a str,
230
data_base64: String,
231
}
232
233
#[derive(Serialize)]
234
struct CreateBody<'a> {
235
title: &'a str,
236
category: &'a str,
237
#[serde(skip_serializing_if = "Option::is_none")]
238
subcategory: Option<&'a str>,
239
description: &'a str,
240
priority: u8,
241
participant_emails: &'a [String],
242
#[serde(skip_serializing_if = "Vec::is_empty")]
243
attachments: Vec<AttachmentBody<'a>>,
244
}
245
246
impl NewTicket {
247
fn body(&self) -> CreateBody<'_> {
248
CreateBody {
249
title: &self.title,
250
category: &self.category,
251
subcategory: self
252
.subcategory
253
.as_deref()
254
.filter(|value| !value.is_empty()),
255
description: &self.description,
256
priority: self.priority.min(2),
257
participant_emails: &self.participant_emails,
258
attachments: self
259
.attachments
260
.iter()
261
.map(|attachment| AttachmentBody {
262
filename: &attachment.filename,
263
mime: &attachment.mime,
264
data_base64: base64::engine::general_purpose::STANDARD.encode(&attachment.data),
265
})
266
.collect(),
267
}
268
}
269
}
270
271
// --- regels -----------------------------------------------------------------
272
273
pub fn is_closed(status: &str) -> bool {
274
status.trim().eq_ignore_ascii_case(STATUS_CLOSED)
275
}
276
277
/// Zelfde als `getPriorityFromFlags` op het web: het tweede vinkje telt alleen met het eerste.
278
/// MIME-type uit de extensie (Asclepius controleert de inhoud zelf ook).
279
pub fn mime_for(filename: &str) -> &'static str {
280
let extension = filename
281
.rsplit_once('.')
282
.map(|(_, extension)| extension.to_ascii_lowercase())
283
.unwrap_or_default();
284
match extension.as_str() {
285
"png" => "image/png",
286
"jpg" | "jpeg" => "image/jpeg",
287
"gif" => "image/gif",
288
"webp" => "image/webp",
289
"pdf" => "application/pdf",
290
"txt" | "log" => "text/plain",
291
"csv" => "text/csv",
292
"doc" => "application/msword",
293
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
294
"xls" => "application/vnd.ms-excel",
295
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
296
"ppt" => "application/vnd.ms-powerpoint",
297
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
298
"zip" => "application/zip",
299
"eml" => "message/rfc822",
300
_ => "application/octet-stream",
301
}
302
}
303
304
pub fn priority_from_flags(blocked: bool, fully_blocked: bool) -> u8 {
305
match (blocked, fully_blocked) {
306
(true, true) => 2,
307
(true, false) => 1,
308
_ => 0,
309
}
310
}
311
312
/// `https://sleutels.kvt.nl/asclepius/index.php?open=123`.
313
pub fn ticket_url(base_url: &str, id: u64) -> String {
314
format!(
315
"{}/asclepius/index.php?open={id}",
316
base_url.trim_end_matches('/')
317
)
318
}
319
320
/// Ticketnummer uit een Asclepius-link op dezelfde host als `base_url`
321
/// (`/asclepius/`, `index.php` of `admin.php`, met `?open=`). Anders `None`.
322
pub fn ticket_id_from_url(base_url: &str, url: &str) -> Option<u64> {
323
let base = Url::parse(base_url).ok()?;
324
let url = Url::parse(url.trim()).ok()?;
325
if url.scheme() != "https" || !url.host_str()?.eq_ignore_ascii_case(base.host_str()?) {
326
return None;
327
}
328
let path = url.path().trim_end_matches('/');
329
if !matches!(
330
path,
331
"/asclepius" | "/asclepius/index.php" | "/asclepius/admin.php"
332
) {
333
return None;
334
}
335
url.query_pairs()
336
.find(|(key, _)| key == "open")
337
.and_then(|(_, value)| value.trim().parse::<u64>().ok())
338
.filter(|id| *id > 0)
339
}
340
341
/// Komen de opgegeven deelnemers als lijst van geldige adressen, zonder dubbele.
342
pub fn parse_participants(text: &str) -> Result<Vec<String>, String> {
343
let mut seen = HashSet::new();
344
let mut emails = Vec::new();
345
for part in text.split([',', ';', '\n', ' ']) {
346
let email = part.trim().trim_matches(['<', '>']).to_lowercase();
347
if email.is_empty() {
348
continue;
349
}
350
let valid = email.split_once('@').is_some_and(|(local, domain)| {
351
!local.is_empty() && domain.contains('.') && !domain.starts_with('.')
352
});
353
if !valid {
354
return Err(email);
355
}
356
if seen.insert(email.clone()) {
357
emails.push(email);
358
}
359
}
360
Ok(emails)
361
}
362
363
// --- @-vermeldingen ----------------------------------------------------------
364
365
/// `jan@example.com` → `@jan:examplecom` (zoals Asclepius vermeldingen opslaat).
366
pub fn mention_token(email: &str) -> Option<String> {
367
let email = email.trim().to_lowercase();
368
let (local, domain) = email.rsplit_once('@')?;
369
let domain = domain.replace('.', "");
370
let domain_ok = !domain.is_empty()
371
&& domain
372
.chars()
373
.all(|c| c.is_ascii_alphanumeric() || c == '-');
374
(!local.is_empty() && domain_ok).then(|| format!("@{local}:{domain}"))
375
}
376
377
/// Teams-vermeldingen (`@Naam` in de tekst) naar Asclepius-tokens, als het adres bekend is.
378
/// Elke naam één keer, de langste eerst (zodat `@Jan de Vries` niet als `@Jan` telt).
379
pub fn mentions_to_asclepius(text: &str, mentions: &[(String, String)]) -> String {
380
let mut ordered: Vec<&(String, String)> = mentions.iter().collect();
381
ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count()));
382
let mut out = text.to_owned();
383
for (name, email) in ordered {
384
let name = name.trim().trim_start_matches('@');
385
let Some(token) = mention_token(email) else {
386
continue;
387
};
388
if name.is_empty() {
389
continue;
390
}
391
let needle = format!("@{name}");
392
let mut result = String::with_capacity(out.len());
393
let mut rest = out.as_str();
394
while let Some(index) = rest.find(&needle) {
395
result.push_str(&rest[..index]);
396
result.push_str(&token);
397
rest = &rest[index + needle.len()..];
398
}
399
result.push_str(rest);
400
out = result;
401
}
402
out
403
}
404
405
/// Een stuk berichttekst: gewone tekst of een Asclepius-vermelding.
406
#[derive(Debug, Clone, PartialEq, Eq)]
407
pub enum TextPart {
408
Text(String),
409
/// `key` zonder `@` (`jan:examplecom`); `email` als die bekend is.
410
Mention {
411
key: String,
412
email: Option<String>,
413
},
414
}
415
416
fn mention_key_char(c: char) -> bool {
417
c.is_ascii_alphanumeric() || "._%+-".contains(c)
418
}
419
420
/// Asclepius-tokens (`@jan:examplecom`) in de tekst, met het adres uit `known` als dat erbij hoort.
421
/// Niet in code (```…``` of `…`), niet midden in een woord of adres.
422
pub fn split_mentions(text: &str, known: &[String]) -> Vec<TextPart> {
423
let by_key: HashMap<String, String> = known
424
.iter()
425
.filter_map(|email| {
426
mention_token(email).map(|token| (token[1..].to_owned(), email.to_lowercase()))
427
})
428
.collect();
429
let mut parts = Vec::new();
430
let mut plain = String::new();
431
let chars: Vec<(usize, char)> = text.char_indices().collect();
432
let mut index = 0;
433
let mut in_fence = false;
434
let mut in_code = false;
435
while index < chars.len() {
436
let (byte, c) = chars[index];
437
if text[byte..].starts_with("```") {
438
in_fence = !in_fence;
439
plain.push_str("```");
440
index += 3;
441
continue;
442
}
443
if c == '`' && !in_fence {
444
in_code = !in_code;
445
}
446
let before = index.checked_sub(1).map(|i| chars[i].1);
447
let opens = before.is_none_or(|b| !(b.is_alphanumeric() || "@./-_".contains(b)));
448
if c == '@' && opens && !in_fence && !in_code {
449
// local
450
let mut end = index + 1;
451
while end < chars.len() && mention_key_char(chars[end].1) {
452
end += 1;
453
}
454
let local_end = end;
455
if local_end > index + 1 && end < chars.len() && chars[end].1 == ':' {
456
let mut domain_end = end + 1;
457
while domain_end < chars.len()
458
&& (chars[domain_end].1.is_ascii_alphanumeric() || chars[domain_end].1 == '-')
459
{
460
domain_end += 1;
461
}
462
let next = chars.get(domain_end).map(|(_, c)| *c);
463
let next_ok = next.is_none_or(|n| n != ':' && !n.is_alphanumeric());
464
if domain_end > end + 1 && next_ok {
465
let start = chars[index + 1].0;
466
let stop = chars.get(domain_end).map_or(text.len(), |(b, _)| *b);
467
let key = text[start..stop].to_lowercase();
468
let local = &text[start..chars[local_end].0];
469
if !local.ends_with('.') {
470
if !plain.is_empty() {
471
parts.push(TextPart::Text(std::mem::take(&mut plain)));
472
}
473
parts.push(TextPart::Mention {
474
email: by_key.get(&key).cloned(),
475
key,
476
});
477
index = domain_end;
478
continue;
479
}
480
}
481
}
482
}
483
plain.push(c);
484
index += 1;
485
}
486
if !plain.is_empty() {
487
parts.push(TextPart::Text(plain));
488
}
489
parts
490
}
491
492
/// Naam voor een vermelding: uit het adres als dat bekend is, anders het deel voor de `:`.
493
pub fn mention_label(key: &str, email: Option<&str>) -> String {
494
let name = match email {
495
Some(email) => crate::ponos::name_from_email(email),
496
None => crate::ponos::name_from_email(key.split(':').next().unwrap_or(key)),
497
};
498
let first = name.split(' ').next().unwrap_or_default();
499
format!("@{}", if first.is_empty() { key } else { first })
500
}
501
502
// --- lokaal ongelezen ----------------------------------------------------------
503
504
/// Laatst gezien per ticket (`updated_at`), alleen in de lokale opslag.
505
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
506
pub struct SeenTickets {
507
/// Na de eerste lijst: oude tickets tellen dan niet als ongelezen.
508
#[serde(default)]
509
pub initialized: bool,
510
#[serde(default)]
511
pub seen: HashMap<u64, String>,
512
}
513
514
impl SeenTickets {
515
pub fn from_json(text: &str) -> Self {
516
serde_json::from_str(text).unwrap_or_default()
517
}
518
519
pub fn to_json(&self) -> String {
520
serde_json::to_string(self).unwrap_or_default()
521
}
522
523
/// Eerste keer: alles wat er nu is telt als gelezen.
524
pub fn initialize(&mut self, tickets: &[Ticket]) -> bool {
525
if self.initialized {
526
return false;
527
}
528
for ticket in tickets {
529
self.seen.insert(ticket.id, ticket.updated_at.clone());
530
}
531
self.initialized = true;
532
true
533
}
534
535
pub fn is_unread(&self, ticket: &Ticket) -> bool {
536
if !self.initialized {
537
return false;
538
}
539
match self.seen.get(&ticket.id) {
540
Some(seen) => ticket.updated_at.as_str() > seen.as_str(),
541
None => true,
542
}
543
}
544
545
pub fn mark(&mut self, ticket: &Ticket) -> bool {
546
let changed = self.seen.get(&ticket.id) != Some(&ticket.updated_at);
547
self.seen.insert(ticket.id, ticket.updated_at.clone());
548
changed
549
}
550
551
pub fn unread_count(&self, tickets: &[Ticket]) -> usize {
552
tickets
553
.iter()
554
.filter(|ticket| self.is_unread(ticket))
555
.count()
556
}
557
}
558
559
// --- client -------------------------------------------------------------------
560
561
#[derive(Deserialize)]
562
struct ListEnvelope {
563
#[serde(default)]
564
tickets: Vec<Ticket>,
565
}
566
567
#[derive(Deserialize)]
568
struct UpdatesEnvelope {
569
#[serde(default)]
570
tickets: Vec<Ticket>,
571
#[serde(default)]
572
server_time: String,
573
}
574
575
#[derive(Deserialize)]
576
struct DetailEnvelope {
577
ticket: TicketDetail,
578
}
579
580
#[derive(Deserialize)]
581
struct LookupsEnvelope {
582
#[serde(default)]
583
categories: Vec<String>,
584
#[serde(default)]
585
subcategories: serde_json::Value,
586
}
587
588
#[derive(Deserialize)]
589
struct CreatedEnvelope {
590
#[serde(deserialize_with = "de_u64")]
591
ticket_id: u64,
592
}
593
594
#[derive(Deserialize)]
595
struct SuccessEnvelope {
596
#[serde(default, deserialize_with = "de_bool")]
597
success: bool,
598
}
599
600
async fn api_json<T: serde::de::DeserializeOwned>(
601
response: reqwest::Response,
602
) -> Result<T, ClientError> {
603
match response.status().as_u16() {
604
// Ongeldige invoer of te grote bijlage: de app toont «niet gelukt».
605
413 | 422 => Err(ClientError::BadRequest),
606
_ => json_or_error(response).await,
607
}
608
}
609
610
impl CardsClient {
611
fn asclepius_url(&self) -> String {
612
format!("{}/asclepius/api.php", self.base_url())
613
}
614
615
async fn asclepius_get<T: serde::de::DeserializeOwned>(
616
&self,
617
token: &str,
618
query: &[(&str, &str)],
619
) -> Result<T, ClientError> {
620
let response = self
621
.http()
622
.get(self.asclepius_url())
623
.query(query)
624
.bearer_auth(token)
625
.send()
626
.await
627
.map_err(|_| ClientError::Unavailable)?;
628
api_json(response).await
629
}
630
631
async fn asclepius_post<T: serde::de::DeserializeOwned>(
632
&self,
633
token: &str,
634
body: &impl Serialize,
635
) -> Result<T, ClientError> {
636
let body = serde_json::to_vec(body).map_err(|_| ClientError::BadRequest)?;
637
let response = self
638
.http()
639
.post(self.asclepius_url())
640
.header(reqwest::header::CONTENT_TYPE, "application/json")
641
.body(body)
642
.bearer_auth(token)
643
.send()
644
.await
645
.map_err(|_| ClientError::Unavailable)?;
646
api_json(response).await
647
}
648
649
/// Je tickets (zoals «Mijn tickets» op het web, plus aan jou toegewezen).
650
pub async fn asclepius_tickets(
651
&self,
652
token: &str,
653
filter: TicketFilter,
654
) -> Result<Vec<Ticket>, ClientError> {
655
let envelope: ListEnvelope = self
656
.asclepius_get(token, &[("filter", filter.as_str())])
657
.await?;
658
Ok(envelope.tickets)
659
}
660
661
/// Eén ticket met berichten; ghosts alleen als Asclepius ze voor jou toont (ICT).
662
pub async fn asclepius_ticket(
663
&self,
664
token: &str,
665
id: u64,
666
) -> Result<TicketDetail, ClientError> {
667
let id = id.to_string();
668
let envelope: DetailEnvelope = self
669
.asclepius_get(token, &[("id", id.as_str()), ("include_ghosts", "1")])
670
.await?;
671
Ok(envelope.ticket)
672
}
673
674
/// Tickets die sinds `since` (ISO of `server_time` van de vorige keer) veranderd zijn.
675
pub async fn asclepius_updates(
676
&self,
677
token: &str,
678
since: &str,
679
) -> Result<(Vec<Ticket>, String), ClientError> {
680
let envelope: UpdatesEnvelope = self
681
.asclepius_get(
682
token,
683
&[("action", "ticket_updates"), ("updated_since", since)],
684
)
685
.await?;
686
Ok((envelope.tickets, envelope.server_time))
687
}
688
689
pub async fn asclepius_lookups(&self, token: &str) -> Result<Lookups, ClientError> {
690
let envelope: LookupsEnvelope = self
691
.asclepius_get(token, &[("action", "ticket_lookups")])
692
.await?;
693
let mut subcategories = HashMap::new();
694
if let serde_json::Value::Object(map) = envelope.subcategories {
695
for (category, values) in map {
696
let list: Vec<String> = values
697
.as_array()
698
.map(|values| {
699
values
700
.iter()
701
.filter_map(|value| value.as_str().map(str::to_owned))
702
.collect()
703
})
704
.unwrap_or_default();
705
if !list.is_empty() {
706
subcategories.insert(category, list);
707
}
708
}
709
}
710
Ok(Lookups {
711
categories: envelope.categories,
712
subcategories,
713
})
714
}
715
716
/// Maakt het ticket op jouw naam; geeft het ticketnummer.
717
pub async fn asclepius_create(
718
&self,
719
token: &str,
720
ticket: &NewTicket,
721
) -> Result<u64, ClientError> {
722
let created: CreatedEnvelope = self.asclepius_post(token, &ticket.body()).await?;
723
Ok(created.ticket_id)
724
}
725
726
/// Een gewoon bericht (geen ghost, geen status).
727
pub async fn asclepius_reply(
728
&self,
729
token: &str,
730
id: u64,
731
text: &str,
732
) -> Result<(), ClientError> {
733
let envelope: SuccessEnvelope = self
734
.asclepius_post(
735
token,
736
&serde_json::json!({
737
"action": "add_ticket_message",
738
"ticket_id": id,
739
"message": text,
740
}),
741
)
742
.await?;
743
if envelope.success {
744
Ok(())
745
} else {
746
Err(ClientError::BadRequest)
747
}
748
}
749
750
/// De inhoud van een bijlage (alleen met de token, dus niet via de browser).
751
pub async fn asclepius_attachment(&self, token: &str, id: u64) -> Result<Vec<u8>, ClientError> {
752
let id = id.to_string();
753
let response = self
754
.http()
755
.get(self.asclepius_url())
756
.query(&[("action", "get_attachment"), ("id", id.as_str())])
757
.bearer_auth(token)
758
.send()
759
.await
760
.map_err(|_| ClientError::Unavailable)?;
761
match response.status().as_u16() {
762
200 => response
763
.bytes()
764
.await
765
.map(|bytes| bytes.to_vec())
766
.map_err(|_| ClientError::Unavailable),
767
401 => Err(ClientError::Unauthorized),
768
403 => Err(ClientError::Forbidden),
769
404 => Err(ClientError::NotFound),
770
_ => Err(ClientError::Unavailable),
771
}
772
}
773
}
774
775
#[cfg(test)]
776
mod tests {
777
use super::*;
778
779
#[test]
780
fn list_tolerates_string_numbers_and_nulls() {
781
let json = r#"{"success":true,"filter":"open","tickets":[
782
{"id":"12","title":"Printer","category":"Hardware bestellen","subcategory":null,
783
"user_email":"jan@example.com","assigned_email":null,"status":"ingediend","priority":"1",
784
"created_at":"2026-01-15T10:00:00+01:00","updated_at":"2026-01-15T11:00:00+01:00",
785
"message_count":"3","is_private":0}]}"#;
786
let envelope: ListEnvelope = serde_json::from_str(json).unwrap();
787
let ticket = &envelope.tickets[0];
788
assert_eq!(ticket.id, 12);
789
assert_eq!(ticket.priority, 1);
790
assert_eq!(ticket.subcategory, "");
791
assert_eq!(ticket.assigned_email, "");
792
assert_eq!(ticket.message_count, 3);
793
assert!(!ticket.is_closed());
794
}
795
796
#[test]
797
fn detail_reads_messages_ghosts_and_attachments() {
798
let json = r#"{"success":true,"ticket":{"id":7,"title":"VPN","status":"afgehandeld",
799
"description":"Werkt niet","participant_emails":["jan@example.com"],
800
"messages":[
801
{"id":1,"sender_email":"jan@example.com","sender_role":"user","message_text":"Hoi","created_at":"x","is_ghost":0,"attachments":[]},
802
{"id":"2","sender_email":"ict@example.com","sender_role":"admin","sender_display_name":"ICT Bot","message_text":"Intern","is_ghost":"1",
803
"attachments":[{"id":"9","original_name":"log.txt","mime_type":"text/plain","file_size":"12","download_url":"https://x"}]}
804
]}}"#;
805
let envelope: DetailEnvelope = serde_json::from_str(json).unwrap();
806
let detail = envelope.ticket;
807
assert_eq!(detail.ticket.id, 7);
808
assert!(detail.ticket.is_closed());
809
assert_eq!(detail.participant_emails, ["jan@example.com"]);
810
assert!(!detail.messages[0].is_ghost);
811
assert!(detail.messages[1].is_ghost);
812
assert_eq!(detail.messages[1].attachments[0].id, 9);
813
assert_eq!(detail.messages[0].sender_name(), "Jan");
814
assert_eq!(detail.messages[1].sender_name(), "ICT Bot");
815
}
816
817
#[test]
818
fn create_body_matches_the_api() {
819
let ticket = NewTicket {
820
title: "Scanner".into(),
821
category: "Hardware bestellen".into(),
822
subcategory: Some(String::new()),
823
description: "Graag".into(),
824
priority: priority_from_flags(true, true),
825
participant_emails: vec!["piet@example.com".into()],
826
attachments: vec![NewAttachment {
827
filename: "a.png".into(),
828
mime: "image/png".into(),
829
data: vec![1, 2, 3],
830
}],
831
};
832
let value = serde_json::to_value(ticket.body()).unwrap();
833
assert_eq!(value["priority"], 2);
834
assert!(value.get("subcategory").is_none());
835
assert_eq!(value["participant_emails"][0], "piet@example.com");
836
assert_eq!(value["attachments"][0]["data_base64"], "AQID");
837
assert!(value.get("action").is_none());
838
}
839
840
#[test]
841
fn priority_follows_the_web_checkboxes() {
842
assert_eq!(priority_from_flags(false, false), 0);
843
assert_eq!(priority_from_flags(true, false), 1);
844
assert_eq!(priority_from_flags(true, true), 2);
845
assert_eq!(priority_from_flags(false, true), 0);
846
}
847
848
#[test]
849
fn form_hides_ict_only_categories() {
850
let lookups = Lookups {
851
categories: vec![
852
"Hardware bestellen".into(),
853
"Uitdiensttreding".into(),
854
"Indiensttreding".into(),
855
],
856
subcategories: HashMap::from([("Hardware bestellen".into(), vec!["Laptop".into()])]),
857
};
858
assert_eq!(lookups.form_categories(), ["Hardware bestellen"]);
859
assert_eq!(lookups.subcategories_of("Hardware bestellen"), ["Laptop"]);
860
assert!(lookups.subcategories_of("Anders").is_empty());
861
}
862
863
#[test]
864
fn ticket_links_on_the_same_host_only() {
865
let base = "https://sleutels.kvt.nl";
866
assert_eq!(
867
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=776"),
868
Some(776)
869
);
870
assert_eq!(
871
ticket_id_from_url(base, "https://Sleutels.kvt.nl/asclepius/?open=5#mention-1"),
872
Some(5)
873
);
874
assert_eq!(
875
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/admin.php?open=9"),
876
Some(9)
877
);
878
assert_eq!(
879
ticket_id_from_url(base, "https://evil.example/asclepius/index.php?open=1"),
880
None
881
);
882
assert_eq!(
883
ticket_id_from_url(base, "http://sleutels.kvt.nl/asclepius/index.php?open=1"),
884
None
885
);
886
assert_eq!(
887
ticket_id_from_url(base, "https://sleutels.kvt.nl/ponos/?open=1"),
888
None
889
);
890
assert_eq!(
891
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php"),
892
None
893
);
894
assert_eq!(
895
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=0"),
896
None
897
);
898
assert_eq!(
899
ticket_url(base, 12),
900
"https://sleutels.kvt.nl/asclepius/index.php?open=12"
901
);
902
}
903
904
#[test]
905
fn participants_are_validated_and_deduplicated() {
906
assert_eq!(
907
parse_participants("Piet@example.com, jan@example.com; piet@example.com").unwrap(),
908
["piet@example.com", "jan@example.com"]
909
);
910
assert_eq!(parse_participants(" ").unwrap(), Vec::<String>::new());
911
assert_eq!(
912
parse_participants("jan, piet@example.com"),
913
Err("jan".into())
914
);
915
}
916
917
#[test]
918
fn mention_tokens_match_asclepius() {
919
assert_eq!(
920
mention_token("jan@example.com").as_deref(),
921
Some("@jan:examplecom")
922
);
923
assert_eq!(
924
mention_token("J.DeVries@example.be").as_deref(),
925
Some("@j.devries:examplebe")
926
);
927
assert_eq!(mention_token("geen-adres"), None);
928
}
929
930
#[test]
931
fn teams_mentions_become_asclepius_tokens() {
932
let mentions = vec![
933
("Jan".to_owned(), "jan.peters@example.com".to_owned()),
934
(
935
"Jan de Vries".to_owned(),
936
"j.devries@example.com".to_owned(),
937
),
938
];
939
assert_eq!(
940
mentions_to_asclepius("@Jan de Vries en @Jan, kijk even", &mentions),
941
"@j.devries:examplecom en @jan.peters:examplecom, kijk even"
942
);
943
assert_eq!(
944
mentions_to_asclepius("geen vermelding", &mentions),
945
"geen vermelding"
946
);
947
}
948
949
#[test]
950
fn asclepius_tokens_are_split_out_for_display() {
951
let known = vec!["jan.peters@example.com".to_owned()];
952
let parts = split_mentions("Hoi @jan.peters:examplecom en @piet:examplecom!", &known);
953
assert_eq!(
954
parts,
955
vec![
956
TextPart::Text("Hoi ".into()),
957
TextPart::Mention {
958
key: "jan.peters:examplecom".into(),
959
email: Some("jan.peters@example.com".into())
960
},
961
TextPart::Text(" en ".into()),
962
TextPart::Mention {
963
key: "piet:examplecom".into(),
964
email: None
965
},
966
TextPart::Text("!".into()),
967
]
968
);
969
assert_eq!(
970
mention_label("jan.peters:examplecom", Some("jan.peters@example.com")),
971
"@Jan"
972
);
973
assert_eq!(mention_label("piet:examplecom", None), "@Piet");
974
}
975
976
#[test]
977
fn no_mentions_in_code_addresses_or_times() {
978
let none = |text: &str| {
979
split_mentions(text, &[])
980
.iter()
981
.all(|part| matches!(part, TextPart::Text(_)))
982
};
983
assert!(none("mail jan@example.com:examplecom"));
984
assert!(none("`@jan:examplecom`"));
985
assert!(none("```\n@jan:examplecom\n```"));
986
assert!(none("@jan:examplecom:extra"));
987
assert!(none("om 10:30 @ kantoor"));
988
}
989
990
#[test]
991
fn unread_is_local_and_starts_clean() {
992
let mut seen = SeenTickets::default();
993
let ticket = Ticket {
994
id: 1,
995
updated_at: "2026-01-15T10:00:00+01:00".into(),
996
..Default::default()
997
};
998
assert!(!seen.is_unread(&ticket));
999
assert!(seen.initialize(std::slice::from_ref(&ticket)));
1000
assert!(!seen.initialize(&[]));
1001
assert!(!seen.is_unread(&ticket));
1002
let newer = Ticket {
1003
updated_at: "2026-01-15T12:00:00+01:00".into(),
1004
..ticket.clone()
1005
};
1006
assert!(seen.is_unread(&newer));
1007
let fresh = Ticket {
1008
id: 2,
1009
..ticket.clone()
1010
};
1011
assert_eq!(seen.unread_count(&[newer.clone(), fresh]), 2);
1012
assert!(seen.mark(&newer));
1013
assert!(!seen.is_unread(&newer));
1014
let restored = SeenTickets::from_json(&seen.to_json());
1015
assert_eq!(restored, seen);
1016
}
1017
1018
#[test]
1019
fn mime_comes_from_the_extension() {
1020
assert_eq!(mime_for("Scherm.PNG"), "image/png");
1021
assert_eq!(mime_for("rapport.pdf"), "application/pdf");
1022
assert_eq!(mime_for("geen-extensie"), "application/octet-stream");
1023
}
1024
}
@@ -0,0 +1,1024 @@1
//! Asclepius-tickets via `/asclepius/api.php` met de app-token (scope `asclepius`).2
//!3
//! Wat de token mag, bepaalt Asclepius (`asclepius_app_token.php`): je eigen tickets4
//! (ingediend, deelnemer, gemachtigde of aan jou toegewezen), lezen, aanmaken en een5
//! gewoon bericht plaatsen. Geen status, toewijzing of ghost-berichten plaatsen.6
//! Ghosts komen alleen mee voor ICT, binnen de regels van de webinterface.7
8
use std::collections::{HashMap, HashSet};9
10
use base64::Engine as _;11
use serde::de::{self, Deserializer};12
use serde::{Deserialize, Serialize};13
use url::Url;14
15
use crate::client::{CardsClient, ClientError, json_or_error};16
17
/// Status van een gesloten ticket.18
pub const STATUS_CLOSED: &str = "afgehandeld";19
/// Categorieën die op het web alleen ICT kiest; het formulier toont ze niet.20
pub const ICT_ONLY_CATEGORIES: [&str; 2] = ["Uitdiensttreding", "Indiensttreding"];21
/// Asclepius: titel max. 150 tekens, beschrijving max. 20 000 in het formulier.22
pub const TITLE_MAX: usize = 150;23
pub const DESCRIPTION_MAX: usize = 20_000;24
/// Zelfde grenzen als `add_ticket_message`.25
pub const ATTACHMENTS_MAX: usize = 10;26
pub const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;27
28
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]29
pub enum TicketFilter {30
#[default]31
Open,32
Closed,33
}34
35
impl TicketFilter {36
pub fn as_str(self) -> &'static str {37
match self {38
TicketFilter::Open => "open",39
TicketFilter::Closed => "closed",40
}41
}42
}43
44
// --- lenient velden (SQLite via PDO geeft soms "12" in plaats van 12) ---------45
46
fn de_u64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {47
match serde_json::Value::deserialize(deserializer)? {48
serde_json::Value::Number(number) => number49
.as_u64()50
.or_else(|| number.as_f64().map(|value| value as u64))51
.ok_or_else(|| de::Error::custom("geen getal")),52
serde_json::Value::String(text) => text.trim().parse().map_err(de::Error::custom),53
serde_json::Value::Null => Ok(0),54
_ => Err(de::Error::custom("geen getal")),55
}56
}57
58
fn de_i64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {59
match serde_json::Value::deserialize(deserializer)? {60
serde_json::Value::Number(number) => Ok(number61
.as_i64()62
.or_else(|| number.as_f64().map(|value| value as i64))63
.unwrap_or(0)),64
serde_json::Value::String(text) => Ok(text.trim().parse().unwrap_or(0)),65
serde_json::Value::Bool(value) => Ok(i64::from(value)),66
_ => Ok(0),67
}68
}69
70
fn de_bool<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {71
Ok(match serde_json::Value::deserialize(deserializer)? {72
serde_json::Value::Bool(value) => value,73
serde_json::Value::Number(number) => number.as_i64().unwrap_or(0) != 0,74
serde_json::Value::String(text) => matches!(text.trim(), "1" | "true"),75
_ => false,76
})77
}78
79
fn de_string<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {80
Ok(match serde_json::Value::deserialize(deserializer)? {81
serde_json::Value::String(text) => text,82
serde_json::Value::Number(number) => number.to_string(),83
_ => String::new(),84
})85
}86
87
// --- model ------------------------------------------------------------------88
89
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]90
pub struct Ticket {91
#[serde(deserialize_with = "de_u64")]92
pub id: u64,93
#[serde(default, deserialize_with = "de_string")]94
pub title: String,95
#[serde(default, deserialize_with = "de_string")]96
pub category: String,97
#[serde(default, deserialize_with = "de_string")]98
pub subcategory: String,99
#[serde(default, deserialize_with = "de_string")]100
pub user_email: String,101
#[serde(default, deserialize_with = "de_string")]102
pub requester_display_name: String,103
#[serde(default, deserialize_with = "de_string")]104
pub assigned_email: String,105
#[serde(default, deserialize_with = "de_string")]106
pub status: String,107
#[serde(default, deserialize_with = "de_i64")]108
pub priority: i64,109
#[serde(default, deserialize_with = "de_string")]110
pub created_at: String,111
#[serde(default, deserialize_with = "de_string")]112
pub updated_at: String,113
#[serde(default, deserialize_with = "de_i64")]114
pub message_count: i64,115
}116
117
impl Ticket {118
pub fn is_closed(&self) -> bool {119
is_closed(&self.status)120
}121
122
pub fn url(&self, base_url: &str) -> String {123
ticket_url(base_url, self.id)124
}125
}126
127
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]128
pub struct TicketAttachment {129
#[serde(deserialize_with = "de_u64")]130
pub id: u64,131
#[serde(default, deserialize_with = "de_string")]132
pub original_name: String,133
#[serde(default, deserialize_with = "de_string")]134
pub mime_type: String,135
#[serde(default, deserialize_with = "de_i64")]136
pub file_size: i64,137
}138
139
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]140
pub struct TicketMessage {141
#[serde(deserialize_with = "de_u64")]142
pub id: u64,143
#[serde(default, deserialize_with = "de_string")]144
pub sender_email: String,145
/// `admin` (ICT) of `user`.146
#[serde(default, deserialize_with = "de_string")]147
pub sender_role: String,148
#[serde(default, deserialize_with = "de_string")]149
pub sender_display_name: String,150
#[serde(default, deserialize_with = "de_string")]151
pub message_text: String,152
#[serde(default, deserialize_with = "de_string")]153
pub created_at: String,154
#[serde(default, deserialize_with = "de_bool")]155
pub is_ghost: bool,156
#[serde(default)]157
pub attachments: Vec<TicketAttachment>,158
}159
160
impl TicketMessage {161
pub fn sender_name(&self) -> String {162
if self.sender_display_name.trim().is_empty() {163
crate::ponos::name_from_email(&self.sender_email)164
} else {165
self.sender_display_name.trim().to_owned()166
}167
}168
}169
170
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]171
pub struct TicketDetail {172
#[serde(flatten)]173
pub ticket: Ticket,174
#[serde(default, deserialize_with = "de_string")]175
pub description: String,176
#[serde(default)]177
pub participant_emails: Vec<String>,178
#[serde(default)]179
pub messages: Vec<TicketMessage>,180
}181
182
#[derive(Debug, Clone, Default, PartialEq)]183
pub struct Lookups {184
pub categories: Vec<String>,185
/// Categorie → subcategorieën, in de volgorde van Asclepius.186
pub subcategories: HashMap<String, Vec<String>>,187
}188
189
impl Lookups {190
/// Categorieën voor het formulier, zonder de ICT-only categorieën (zoals op het web).191
pub fn form_categories(&self) -> Vec<String> {192
self.categories193
.iter()194
.filter(|category| !ICT_ONLY_CATEGORIES.contains(&category.as_str()))195
.cloned()196
.collect()197
}198
199
pub fn subcategories_of(&self, category: &str) -> &[String] {200
self.subcategories201
.get(category)202
.map(Vec::as_slice)203
.unwrap_or_default()204
}205
}206
207
#[derive(Debug, Clone, PartialEq, Eq)]208
pub struct NewAttachment {209
pub filename: String,210
pub mime: String,211
pub data: Vec<u8>,212
}213
214
#[derive(Debug, Clone, Default, PartialEq, Eq)]215
pub struct NewTicket {216
pub title: String,217
pub category: String,218
pub subcategory: Option<String>,219
pub description: String,220
/// 0–2, uit de twee vinkjes van het webformulier (`priority_from_flags`).221
pub priority: u8,222
pub participant_emails: Vec<String>,223
pub attachments: Vec<NewAttachment>,224
}225
226
#[derive(Serialize)]227
struct AttachmentBody<'a> {228
filename: &'a str,229
mime: &'a str,230
data_base64: String,231
}232
233
#[derive(Serialize)]234
struct CreateBody<'a> {235
title: &'a str,236
category: &'a str,237
#[serde(skip_serializing_if = "Option::is_none")]238
subcategory: Option<&'a str>,239
description: &'a str,240
priority: u8,241
participant_emails: &'a [String],242
#[serde(skip_serializing_if = "Vec::is_empty")]243
attachments: Vec<AttachmentBody<'a>>,244
}245
246
impl NewTicket {247
fn body(&self) -> CreateBody<'_> {248
CreateBody {249
title: &self.title,250
category: &self.category,251
subcategory: self252
.subcategory253
.as_deref()254
.filter(|value| !value.is_empty()),255
description: &self.description,256
priority: self.priority.min(2),257
participant_emails: &self.participant_emails,258
attachments: self259
.attachments260
.iter()261
.map(|attachment| AttachmentBody {262
filename: &attachment.filename,263
mime: &attachment.mime,264
data_base64: base64::engine::general_purpose::STANDARD.encode(&attachment.data),265
})266
.collect(),267
}268
}269
}270
271
// --- regels -----------------------------------------------------------------272
273
pub fn is_closed(status: &str) -> bool {274
status.trim().eq_ignore_ascii_case(STATUS_CLOSED)275
}276
277
/// Zelfde als `getPriorityFromFlags` op het web: het tweede vinkje telt alleen met het eerste.278
/// MIME-type uit de extensie (Asclepius controleert de inhoud zelf ook).279
pub fn mime_for(filename: &str) -> &'static str {280
let extension = filename281
.rsplit_once('.')282
.map(|(_, extension)| extension.to_ascii_lowercase())283
.unwrap_or_default();284
match extension.as_str() {285
"png" => "image/png",286
"jpg" | "jpeg" => "image/jpeg",287
"gif" => "image/gif",288
"webp" => "image/webp",289
"pdf" => "application/pdf",290
"txt" | "log" => "text/plain",291
"csv" => "text/csv",292
"doc" => "application/msword",293
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",294
"xls" => "application/vnd.ms-excel",295
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",296
"ppt" => "application/vnd.ms-powerpoint",297
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",298
"zip" => "application/zip",299
"eml" => "message/rfc822",300
_ => "application/octet-stream",301
}302
}303
304
pub fn priority_from_flags(blocked: bool, fully_blocked: bool) -> u8 {305
match (blocked, fully_blocked) {306
(true, true) => 2,307
(true, false) => 1,308
_ => 0,309
}310
}311
312
/// `https://sleutels.kvt.nl/asclepius/index.php?open=123`.313
pub fn ticket_url(base_url: &str, id: u64) -> String {314
format!(315
"{}/asclepius/index.php?open={id}",316
base_url.trim_end_matches('/')317
)318
}319
320
/// Ticketnummer uit een Asclepius-link op dezelfde host als `base_url`321
/// (`/asclepius/`, `index.php` of `admin.php`, met `?open=`). Anders `None`.322
pub fn ticket_id_from_url(base_url: &str, url: &str) -> Option<u64> {323
let base = Url::parse(base_url).ok()?;324
let url = Url::parse(url.trim()).ok()?;325
if url.scheme() != "https" || !url.host_str()?.eq_ignore_ascii_case(base.host_str()?) {326
return None;327
}328
let path = url.path().trim_end_matches('/');329
if !matches!(330
path,331
"/asclepius" | "/asclepius/index.php" | "/asclepius/admin.php"332
) {333
return None;334
}335
url.query_pairs()336
.find(|(key, _)| key == "open")337
.and_then(|(_, value)| value.trim().parse::<u64>().ok())338
.filter(|id| *id > 0)339
}340
341
/// Komen de opgegeven deelnemers als lijst van geldige adressen, zonder dubbele.342
pub fn parse_participants(text: &str) -> Result<Vec<String>, String> {343
let mut seen = HashSet::new();344
let mut emails = Vec::new();345
for part in text.split([',', ';', '\n', ' ']) {346
let email = part.trim().trim_matches(['<', '>']).to_lowercase();347
if email.is_empty() {348
continue;349
}350
let valid = email.split_once('@').is_some_and(|(local, domain)| {351
!local.is_empty() && domain.contains('.') && !domain.starts_with('.')352
});353
if !valid {354
return Err(email);355
}356
if seen.insert(email.clone()) {357
emails.push(email);358
}359
}360
Ok(emails)361
}362
363
// --- @-vermeldingen ----------------------------------------------------------364
365
/// `jan@example.com` → `@jan:examplecom` (zoals Asclepius vermeldingen opslaat).366
pub fn mention_token(email: &str) -> Option<String> {367
let email = email.trim().to_lowercase();368
let (local, domain) = email.rsplit_once('@')?;369
let domain = domain.replace('.', "");370
let domain_ok = !domain.is_empty()371
&& domain372
.chars()373
.all(|c| c.is_ascii_alphanumeric() || c == '-');374
(!local.is_empty() && domain_ok).then(|| format!("@{local}:{domain}"))375
}376
377
/// Teams-vermeldingen (`@Naam` in de tekst) naar Asclepius-tokens, als het adres bekend is.378
/// Elke naam één keer, de langste eerst (zodat `@Jan de Vries` niet als `@Jan` telt).379
pub fn mentions_to_asclepius(text: &str, mentions: &[(String, String)]) -> String {380
let mut ordered: Vec<&(String, String)> = mentions.iter().collect();381
ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count()));382
let mut out = text.to_owned();383
for (name, email) in ordered {384
let name = name.trim().trim_start_matches('@');385
let Some(token) = mention_token(email) else {386
continue;387
};388
if name.is_empty() {389
continue;390
}391
let needle = format!("@{name}");392
let mut result = String::with_capacity(out.len());393
let mut rest = out.as_str();394
while let Some(index) = rest.find(&needle) {395
result.push_str(&rest[..index]);396
result.push_str(&token);397
rest = &rest[index + needle.len()..];398
}399
result.push_str(rest);400
out = result;401
}402
out403
}404
405
/// Een stuk berichttekst: gewone tekst of een Asclepius-vermelding.406
#[derive(Debug, Clone, PartialEq, Eq)]407
pub enum TextPart {408
Text(String),409
/// `key` zonder `@` (`jan:examplecom`); `email` als die bekend is.410
Mention {411
key: String,412
email: Option<String>,413
},414
}415
416
fn mention_key_char(c: char) -> bool {417
c.is_ascii_alphanumeric() || "._%+-".contains(c)418
}419
420
/// Asclepius-tokens (`@jan:examplecom`) in de tekst, met het adres uit `known` als dat erbij hoort.421
/// Niet in code (```…``` of `…`), niet midden in een woord of adres.422
pub fn split_mentions(text: &str, known: &[String]) -> Vec<TextPart> {423
let by_key: HashMap<String, String> = known424
.iter()425
.filter_map(|email| {426
mention_token(email).map(|token| (token[1..].to_owned(), email.to_lowercase()))427
})428
.collect();429
let mut parts = Vec::new();430
let mut plain = String::new();431
let chars: Vec<(usize, char)> = text.char_indices().collect();432
let mut index = 0;433
let mut in_fence = false;434
let mut in_code = false;435
while index < chars.len() {436
let (byte, c) = chars[index];437
if text[byte..].starts_with("```") {438
in_fence = !in_fence;439
plain.push_str("```");440
index += 3;441
continue;442
}443
if c == '`' && !in_fence {444
in_code = !in_code;445
}446
let before = index.checked_sub(1).map(|i| chars[i].1);447
let opens = before.is_none_or(|b| !(b.is_alphanumeric() || "@./-_".contains(b)));448
if c == '@' && opens && !in_fence && !in_code {449
// local450
let mut end = index + 1;451
while end < chars.len() && mention_key_char(chars[end].1) {452
end += 1;453
}454
let local_end = end;455
if local_end > index + 1 && end < chars.len() && chars[end].1 == ':' {456
let mut domain_end = end + 1;457
while domain_end < chars.len()458
&& (chars[domain_end].1.is_ascii_alphanumeric() || chars[domain_end].1 == '-')459
{460
domain_end += 1;461
}462
let next = chars.get(domain_end).map(|(_, c)| *c);463
let next_ok = next.is_none_or(|n| n != ':' && !n.is_alphanumeric());464
if domain_end > end + 1 && next_ok {465
let start = chars[index + 1].0;466
let stop = chars.get(domain_end).map_or(text.len(), |(b, _)| *b);467
let key = text[start..stop].to_lowercase();468
let local = &text[start..chars[local_end].0];469
if !local.ends_with('.') {470
if !plain.is_empty() {471
parts.push(TextPart::Text(std::mem::take(&mut plain)));472
}473
parts.push(TextPart::Mention {474
email: by_key.get(&key).cloned(),475
key,476
});477
index = domain_end;478
continue;479
}480
}481
}482
}483
plain.push(c);484
index += 1;485
}486
if !plain.is_empty() {487
parts.push(TextPart::Text(plain));488
}489
parts490
}491
492
/// Naam voor een vermelding: uit het adres als dat bekend is, anders het deel voor de `:`.493
pub fn mention_label(key: &str, email: Option<&str>) -> String {494
let name = match email {495
Some(email) => crate::ponos::name_from_email(email),496
None => crate::ponos::name_from_email(key.split(':').next().unwrap_or(key)),497
};498
let first = name.split(' ').next().unwrap_or_default();499
format!("@{}", if first.is_empty() { key } else { first })500
}501
502
// --- lokaal ongelezen ----------------------------------------------------------503
504
/// Laatst gezien per ticket (`updated_at`), alleen in de lokale opslag.505
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]506
pub struct SeenTickets {507
/// Na de eerste lijst: oude tickets tellen dan niet als ongelezen.508
#[serde(default)]509
pub initialized: bool,510
#[serde(default)]511
pub seen: HashMap<u64, String>,512
}513
514
impl SeenTickets {515
pub fn from_json(text: &str) -> Self {516
serde_json::from_str(text).unwrap_or_default()517
}518
519
pub fn to_json(&self) -> String {520
serde_json::to_string(self).unwrap_or_default()521
}522
523
/// Eerste keer: alles wat er nu is telt als gelezen.524
pub fn initialize(&mut self, tickets: &[Ticket]) -> bool {525
if self.initialized {526
return false;527
}528
for ticket in tickets {529
self.seen.insert(ticket.id, ticket.updated_at.clone());530
}531
self.initialized = true;532
true533
}534
535
pub fn is_unread(&self, ticket: &Ticket) -> bool {536
if !self.initialized {537
return false;538
}539
match self.seen.get(&ticket.id) {540
Some(seen) => ticket.updated_at.as_str() > seen.as_str(),541
None => true,542
}543
}544
545
pub fn mark(&mut self, ticket: &Ticket) -> bool {546
let changed = self.seen.get(&ticket.id) != Some(&ticket.updated_at);547
self.seen.insert(ticket.id, ticket.updated_at.clone());548
changed549
}550
551
pub fn unread_count(&self, tickets: &[Ticket]) -> usize {552
tickets553
.iter()554
.filter(|ticket| self.is_unread(ticket))555
.count()556
}557
}558
559
// --- client -------------------------------------------------------------------560
561
#[derive(Deserialize)]562
struct ListEnvelope {563
#[serde(default)]564
tickets: Vec<Ticket>,565
}566
567
#[derive(Deserialize)]568
struct UpdatesEnvelope {569
#[serde(default)]570
tickets: Vec<Ticket>,571
#[serde(default)]572
server_time: String,573
}574
575
#[derive(Deserialize)]576
struct DetailEnvelope {577
ticket: TicketDetail,578
}579
580
#[derive(Deserialize)]581
struct LookupsEnvelope {582
#[serde(default)]583
categories: Vec<String>,584
#[serde(default)]585
subcategories: serde_json::Value,586
}587
588
#[derive(Deserialize)]589
struct CreatedEnvelope {590
#[serde(deserialize_with = "de_u64")]591
ticket_id: u64,592
}593
594
#[derive(Deserialize)]595
struct SuccessEnvelope {596
#[serde(default, deserialize_with = "de_bool")]597
success: bool,598
}599
600
async fn api_json<T: serde::de::DeserializeOwned>(601
response: reqwest::Response,602
) -> Result<T, ClientError> {603
match response.status().as_u16() {604
// Ongeldige invoer of te grote bijlage: de app toont «niet gelukt».605
413 | 422 => Err(ClientError::BadRequest),606
_ => json_or_error(response).await,607
}608
}609
610
impl CardsClient {611
fn asclepius_url(&self) -> String {612
format!("{}/asclepius/api.php", self.base_url())613
}614
615
async fn asclepius_get<T: serde::de::DeserializeOwned>(616
&self,617
token: &str,618
query: &[(&str, &str)],619
) -> Result<T, ClientError> {620
let response = self621
.http()622
.get(self.asclepius_url())623
.query(query)624
.bearer_auth(token)625
.send()626
.await627
.map_err(|_| ClientError::Unavailable)?;628
api_json(response).await629
}630
631
async fn asclepius_post<T: serde::de::DeserializeOwned>(632
&self,633
token: &str,634
body: &impl Serialize,635
) -> Result<T, ClientError> {636
let body = serde_json::to_vec(body).map_err(|_| ClientError::BadRequest)?;637
let response = self638
.http()639
.post(self.asclepius_url())640
.header(reqwest::header::CONTENT_TYPE, "application/json")641
.body(body)642
.bearer_auth(token)643
.send()644
.await645
.map_err(|_| ClientError::Unavailable)?;646
api_json(response).await647
}648
649
/// Je tickets (zoals «Mijn tickets» op het web, plus aan jou toegewezen).650
pub async fn asclepius_tickets(651
&self,652
token: &str,653
filter: TicketFilter,654
) -> Result<Vec<Ticket>, ClientError> {655
let envelope: ListEnvelope = self656
.asclepius_get(token, &[("filter", filter.as_str())])657
.await?;658
Ok(envelope.tickets)659
}660
661
/// Eén ticket met berichten; ghosts alleen als Asclepius ze voor jou toont (ICT).662
pub async fn asclepius_ticket(663
&self,664
token: &str,665
id: u64,666
) -> Result<TicketDetail, ClientError> {667
let id = id.to_string();668
let envelope: DetailEnvelope = self669
.asclepius_get(token, &[("id", id.as_str()), ("include_ghosts", "1")])670
.await?;671
Ok(envelope.ticket)672
}673
674
/// Tickets die sinds `since` (ISO of `server_time` van de vorige keer) veranderd zijn.675
pub async fn asclepius_updates(676
&self,677
token: &str,678
since: &str,679
) -> Result<(Vec<Ticket>, String), ClientError> {680
let envelope: UpdatesEnvelope = self681
.asclepius_get(682
token,683
&[("action", "ticket_updates"), ("updated_since", since)],684
)685
.await?;686
Ok((envelope.tickets, envelope.server_time))687
}688
689
pub async fn asclepius_lookups(&self, token: &str) -> Result<Lookups, ClientError> {690
let envelope: LookupsEnvelope = self691
.asclepius_get(token, &[("action", "ticket_lookups")])692
.await?;693
let mut subcategories = HashMap::new();694
if let serde_json::Value::Object(map) = envelope.subcategories {695
for (category, values) in map {696
let list: Vec<String> = values697
.as_array()698
.map(|values| {699
values700
.iter()701
.filter_map(|value| value.as_str().map(str::to_owned))702
.collect()703
})704
.unwrap_or_default();705
if !list.is_empty() {706
subcategories.insert(category, list);707
}708
}709
}710
Ok(Lookups {711
categories: envelope.categories,712
subcategories,713
})714
}715
716
/// Maakt het ticket op jouw naam; geeft het ticketnummer.717
pub async fn asclepius_create(718
&self,719
token: &str,720
ticket: &NewTicket,721
) -> Result<u64, ClientError> {722
let created: CreatedEnvelope = self.asclepius_post(token, &ticket.body()).await?;723
Ok(created.ticket_id)724
}725
726
/// Een gewoon bericht (geen ghost, geen status).727
pub async fn asclepius_reply(728
&self,729
token: &str,730
id: u64,731
text: &str,732
) -> Result<(), ClientError> {733
let envelope: SuccessEnvelope = self734
.asclepius_post(735
token,736
&serde_json::json!({737
"action": "add_ticket_message",738
"ticket_id": id,739
"message": text,740
}),741
)742
.await?;743
if envelope.success {744
Ok(())745
} else {746
Err(ClientError::BadRequest)747
}748
}749
750
/// De inhoud van een bijlage (alleen met de token, dus niet via de browser).751
pub async fn asclepius_attachment(&self, token: &str, id: u64) -> Result<Vec<u8>, ClientError> {752
let id = id.to_string();753
let response = self754
.http()755
.get(self.asclepius_url())756
.query(&[("action", "get_attachment"), ("id", id.as_str())])757
.bearer_auth(token)758
.send()759
.await760
.map_err(|_| ClientError::Unavailable)?;761
match response.status().as_u16() {762
200 => response763
.bytes()764
.await765
.map(|bytes| bytes.to_vec())766
.map_err(|_| ClientError::Unavailable),767
401 => Err(ClientError::Unauthorized),768
403 => Err(ClientError::Forbidden),769
404 => Err(ClientError::NotFound),770
_ => Err(ClientError::Unavailable),771
}772
}773
}774
775
#[cfg(test)]776
mod tests {777
use super::*;778
779
#[test]780
fn list_tolerates_string_numbers_and_nulls() {781
let json = r#"{"success":true,"filter":"open","tickets":[782
{"id":"12","title":"Printer","category":"Hardware bestellen","subcategory":null,783
"user_email":"jan@example.com","assigned_email":null,"status":"ingediend","priority":"1",784
"created_at":"2026-01-15T10:00:00+01:00","updated_at":"2026-01-15T11:00:00+01:00",785
"message_count":"3","is_private":0}]}"#;786
let envelope: ListEnvelope = serde_json::from_str(json).unwrap();787
let ticket = &envelope.tickets[0];788
assert_eq!(ticket.id, 12);789
assert_eq!(ticket.priority, 1);790
assert_eq!(ticket.subcategory, "");791
assert_eq!(ticket.assigned_email, "");792
assert_eq!(ticket.message_count, 3);793
assert!(!ticket.is_closed());794
}795
796
#[test]797
fn detail_reads_messages_ghosts_and_attachments() {798
let json = r#"{"success":true,"ticket":{"id":7,"title":"VPN","status":"afgehandeld",799
"description":"Werkt niet","participant_emails":["jan@example.com"],800
"messages":[801
{"id":1,"sender_email":"jan@example.com","sender_role":"user","message_text":"Hoi","created_at":"x","is_ghost":0,"attachments":[]},802
{"id":"2","sender_email":"ict@example.com","sender_role":"admin","sender_display_name":"ICT Bot","message_text":"Intern","is_ghost":"1",803
"attachments":[{"id":"9","original_name":"log.txt","mime_type":"text/plain","file_size":"12","download_url":"https://x"}]}804
]}}"#;805
let envelope: DetailEnvelope = serde_json::from_str(json).unwrap();806
let detail = envelope.ticket;807
assert_eq!(detail.ticket.id, 7);808
assert!(detail.ticket.is_closed());809
assert_eq!(detail.participant_emails, ["jan@example.com"]);810
assert!(!detail.messages[0].is_ghost);811
assert!(detail.messages[1].is_ghost);812
assert_eq!(detail.messages[1].attachments[0].id, 9);813
assert_eq!(detail.messages[0].sender_name(), "Jan");814
assert_eq!(detail.messages[1].sender_name(), "ICT Bot");815
}816
817
#[test]818
fn create_body_matches_the_api() {819
let ticket = NewTicket {820
title: "Scanner".into(),821
category: "Hardware bestellen".into(),822
subcategory: Some(String::new()),823
description: "Graag".into(),824
priority: priority_from_flags(true, true),825
participant_emails: vec!["piet@example.com".into()],826
attachments: vec![NewAttachment {827
filename: "a.png".into(),828
mime: "image/png".into(),829
data: vec![1, 2, 3],830
}],831
};832
let value = serde_json::to_value(ticket.body()).unwrap();833
assert_eq!(value["priority"], 2);834
assert!(value.get("subcategory").is_none());835
assert_eq!(value["participant_emails"][0], "piet@example.com");836
assert_eq!(value["attachments"][0]["data_base64"], "AQID");837
assert!(value.get("action").is_none());838
}839
840
#[test]841
fn priority_follows_the_web_checkboxes() {842
assert_eq!(priority_from_flags(false, false), 0);843
assert_eq!(priority_from_flags(true, false), 1);844
assert_eq!(priority_from_flags(true, true), 2);845
assert_eq!(priority_from_flags(false, true), 0);846
}847
848
#[test]849
fn form_hides_ict_only_categories() {850
let lookups = Lookups {851
categories: vec![852
"Hardware bestellen".into(),853
"Uitdiensttreding".into(),854
"Indiensttreding".into(),855
],856
subcategories: HashMap::from([("Hardware bestellen".into(), vec!["Laptop".into()])]),857
};858
assert_eq!(lookups.form_categories(), ["Hardware bestellen"]);859
assert_eq!(lookups.subcategories_of("Hardware bestellen"), ["Laptop"]);860
assert!(lookups.subcategories_of("Anders").is_empty());861
}862
863
#[test]864
fn ticket_links_on_the_same_host_only() {865
let base = "https://sleutels.kvt.nl";866
assert_eq!(867
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=776"),868
Some(776)869
);870
assert_eq!(871
ticket_id_from_url(base, "https://Sleutels.kvt.nl/asclepius/?open=5#mention-1"),872
Some(5)873
);874
assert_eq!(875
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/admin.php?open=9"),876
Some(9)877
);878
assert_eq!(879
ticket_id_from_url(base, "https://evil.example/asclepius/index.php?open=1"),880
None881
);882
assert_eq!(883
ticket_id_from_url(base, "http://sleutels.kvt.nl/asclepius/index.php?open=1"),884
None885
);886
assert_eq!(887
ticket_id_from_url(base, "https://sleutels.kvt.nl/ponos/?open=1"),888
None889
);890
assert_eq!(891
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php"),892
None893
);894
assert_eq!(895
ticket_id_from_url(base, "https://sleutels.kvt.nl/asclepius/index.php?open=0"),896
None897
);898
assert_eq!(899
ticket_url(base, 12),900
"https://sleutels.kvt.nl/asclepius/index.php?open=12"901
);902
}903
904
#[test]905
fn participants_are_validated_and_deduplicated() {906
assert_eq!(907
parse_participants("Piet@example.com, jan@example.com; piet@example.com").unwrap(),908
["piet@example.com", "jan@example.com"]909
);910
assert_eq!(parse_participants(" ").unwrap(), Vec::<String>::new());911
assert_eq!(912
parse_participants("jan, piet@example.com"),913
Err("jan".into())914
);915
}916
917
#[test]918
fn mention_tokens_match_asclepius() {919
assert_eq!(920
mention_token("jan@example.com").as_deref(),921
Some("@jan:examplecom")922
);923
assert_eq!(924
mention_token("J.DeVries@example.be").as_deref(),925
Some("@j.devries:examplebe")926
);927
assert_eq!(mention_token("geen-adres"), None);928
}929
930
#[test]931
fn teams_mentions_become_asclepius_tokens() {932
let mentions = vec![933
("Jan".to_owned(), "jan.peters@example.com".to_owned()),934
(935
"Jan de Vries".to_owned(),936
"j.devries@example.com".to_owned(),937
),938
];939
assert_eq!(940
mentions_to_asclepius("@Jan de Vries en @Jan, kijk even", &mentions),941
"@j.devries:examplecom en @jan.peters:examplecom, kijk even"942
);943
assert_eq!(944
mentions_to_asclepius("geen vermelding", &mentions),945
"geen vermelding"946
);947
}948
949
#[test]950
fn asclepius_tokens_are_split_out_for_display() {951
let known = vec!["jan.peters@example.com".to_owned()];952
let parts = split_mentions("Hoi @jan.peters:examplecom en @piet:examplecom!", &known);953
assert_eq!(954
parts,955
vec![956
TextPart::Text("Hoi ".into()),957
TextPart::Mention {958
key: "jan.peters:examplecom".into(),959
email: Some("jan.peters@example.com".into())960
},961
TextPart::Text(" en ".into()),962
TextPart::Mention {963
key: "piet:examplecom".into(),964
email: None965
},966
TextPart::Text("!".into()),967
]968
);969
assert_eq!(970
mention_label("jan.peters:examplecom", Some("jan.peters@example.com")),971
"@Jan"972
);973
assert_eq!(mention_label("piet:examplecom", None), "@Piet");974
}975
976
#[test]977
fn no_mentions_in_code_addresses_or_times() {978
let none = |text: &str| {979
split_mentions(text, &[])980
.iter()981
.all(|part| matches!(part, TextPart::Text(_)))982
};983
assert!(none("mail jan@example.com:examplecom"));984
assert!(none("`@jan:examplecom`"));985
assert!(none("```\n@jan:examplecom\n```"));986
assert!(none("@jan:examplecom:extra"));987
assert!(none("om 10:30 @ kantoor"));988
}989
990
#[test]991
fn unread_is_local_and_starts_clean() {992
let mut seen = SeenTickets::default();993
let ticket = Ticket {994
id: 1,995
updated_at: "2026-01-15T10:00:00+01:00".into(),996
..Default::default()997
};998
assert!(!seen.is_unread(&ticket));999
assert!(seen.initialize(std::slice::from_ref(&ticket)));1000
assert!(!seen.initialize(&[]));1001
assert!(!seen.is_unread(&ticket));1002
let newer = Ticket {1003
updated_at: "2026-01-15T12:00:00+01:00".into(),1004
..ticket.clone()1005
};1006
assert!(seen.is_unread(&newer));1007
let fresh = Ticket {1008
id: 2,1009
..ticket.clone()1010
};1011
assert_eq!(seen.unread_count(&[newer.clone(), fresh]), 2);1012
assert!(seen.mark(&newer));1013
assert!(!seen.is_unread(&newer));1014
let restored = SeenTickets::from_json(&seen.to_json());1015
assert_eq!(restored, seen);1016
}1017
1018
#[test]1019
fn mime_comes_from_the_extension() {1020
assert_eq!(mime_for("Scherm.PNG"), "image/png");1021
assert_eq!(mime_for("rapport.pdf"), "application/pdf");1022
assert_eq!(mime_for("geen-extensie"), "application/octet-stream");1023
}1024
}@@ -38,3 +38,11 @@ Options for the message format were: an own card format, or a plain link with re
38
38
- «Create Ponos task» and «My tasks» call Ponos directly; the dialog lists only groups where the user may create tasks.
39
39
- 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.
40
40
- The Asclepius embed view and a virtual Asclepius team are not part of this release.
41
42
## Addendum: Ponos tile and board (next release)
43
44
- 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.
45
- 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»).
46
- 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.
47
- 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.
48
- 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 re38
- «Create Ponos task» and «My tasks» call Ponos directly; the dialog lists only groups where the user may create tasks.38
- «Create Ponos task» and «My tasks» call Ponos directly; the dialog lists only groups where the user may create tasks.39
- 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.39
- 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.40
- The Asclepius embed view and a virtual Asclepius team are not part of this release.40
- The Asclepius embed view and a virtual Asclepius team are not part of this release.41
42
## Addendum: Ponos tile and board (next release)43
44
- 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.45
- 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»).46
- 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.47
- 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.48
- Planned, not built: the Asclepius integration (virtual team / embed view) becomes the next tile, directly below Ponos.@@ -0,0 +1,70 @@
1
#!/usr/bin/env bash
2
# Pack or unpack a Cargo/rustup (and optional cargo-xwin) cache as one tarball.
3
# BlueGit `cache.paths` copies only files, not directories, so a directory
4
# such as cargo-home/ would otherwise be skipped (see bluegit runner saveCache).
5
# Does not cache target/: too large for the runner's job-cache budget.
6
set -euo pipefail
7
8
usage() {
9
echo "usage: $0 restore|save linux|windows" >&2
10
exit 2
11
}
12
13
cmd="${1:-}"
14
kind="${2:-}"
15
[[ "$cmd" == restore || "$cmd" == save ]] || usage
16
[[ "$kind" == linux || "$kind" == windows ]] || usage
17
18
archive=".ci-cache/cargo-${kind}.tar.gz"
19
20
# Locations in the job workspace (set by the CI job / ci-setup.sh).
21
cargo_home="${CARGO_HOME:-$PWD/cargo-home}"
22
rustup_home="${RUSTUP_HOME:-$PWD/rustup-home}"
23
xwin_cache="${XWIN_CACHE_DIR:-$PWD/xwin-cache}"
24
25
relpath() {
26
local abs="$1"
27
case "$abs" in
28
"$PWD"/*) printf '%s\n' "${abs#"$PWD"/}" ;;
29
/*) printf '%s\n' "$abs" ;;
30
*) printf '%s\n' "$abs" ;;
31
esac
32
}
33
34
if [[ "$cmd" == restore ]]; then
35
if [[ -f "$archive" ]]; then
36
tar -xzf "$archive"
37
echo "CI-cache hersteld ($archive)."
38
else
39
echo "Geen CI-cache ($archive)."
40
fi
41
exit 0
42
fi
43
44
mkdir -p .ci-cache
45
parts=()
46
add_if_dir() {
47
local p="$1"
48
[[ -d "$p" ]] || return 0
49
parts+=("$(relpath "$p")")
50
}
51
52
# Registry and git checkouts, not registry/src (that is rebuilt from .crate files).
53
add_if_dir "$cargo_home/bin"
54
add_if_dir "$cargo_home/registry/index"
55
add_if_dir "$cargo_home/registry/cache"
56
add_if_dir "$cargo_home/git/db"
57
add_if_dir "$rustup_home"
58
if [[ "$kind" == windows ]]; then
59
add_if_dir "$xwin_cache"
60
fi
61
62
if [[ ${#parts[@]} -eq 0 ]]; then
63
echo "Niets te cachen."
64
exit 0
65
fi
66
67
# gzip -1: kleiner bestand voor de 10 GB-jobcache, weinig CPU.
68
tar -c --use-compress-program='gzip -1' -f "$archive" "${parts[@]}"
69
echo "CI-cache opgeslagen ($archive): ${parts[*]}"
70
ls -lh "$archive"
@@ -0,0 +1,70 @@1
#!/usr/bin/env bash2
# Pack or unpack a Cargo/rustup (and optional cargo-xwin) cache as one tarball.3
# BlueGit `cache.paths` copies only files, not directories, so a directory4
# such as cargo-home/ would otherwise be skipped (see bluegit runner saveCache).5
# Does not cache target/: too large for the runner's job-cache budget.6
set -euo pipefail7
8
usage() {9
echo "usage: $0 restore|save linux|windows" >&210
exit 211
}12
13
cmd="${1:-}"14
kind="${2:-}"15
[[ "$cmd" == restore || "$cmd" == save ]] || usage16
[[ "$kind" == linux || "$kind" == windows ]] || usage17
18
archive=".ci-cache/cargo-${kind}.tar.gz"19
20
# Locations in the job workspace (set by the CI job / ci-setup.sh).21
cargo_home="${CARGO_HOME:-$PWD/cargo-home}"22
rustup_home="${RUSTUP_HOME:-$PWD/rustup-home}"23
xwin_cache="${XWIN_CACHE_DIR:-$PWD/xwin-cache}"24
25
relpath() {26
local abs="$1"27
case "$abs" in28
"$PWD"/*) printf '%s\n' "${abs#"$PWD"/}" ;;29
/*) printf '%s\n' "$abs" ;;30
*) printf '%s\n' "$abs" ;;31
esac32
}33
34
if [[ "$cmd" == restore ]]; then35
if [[ -f "$archive" ]]; then36
tar -xzf "$archive"37
echo "CI-cache hersteld ($archive)."38
else39
echo "Geen CI-cache ($archive)."40
fi41
exit 042
fi43
44
mkdir -p .ci-cache45
parts=()46
add_if_dir() {47
local p="$1"48
[[ -d "$p" ]] || return 049
parts+=("$(relpath "$p")")50
}51
52
# Registry and git checkouts, not registry/src (that is rebuilt from .crate files).53
add_if_dir "$cargo_home/bin"54
add_if_dir "$cargo_home/registry/index"55
add_if_dir "$cargo_home/registry/cache"56
add_if_dir "$cargo_home/git/db"57
add_if_dir "$rustup_home"58
if [[ "$kind" == windows ]]; then59
add_if_dir "$xwin_cache"60
fi61
62
if [[ ${#parts[@]} -eq 0 ]]; then63
echo "Niets te cachen."64
exit 065
fi66
67
# gzip -1: kleiner bestand voor de 10 GB-jobcache, weinig CPU.68
tar -c --use-compress-program='gzip -1' -f "$archive" "${parts[@]}"69
echo "CI-cache opgeslagen ($archive): ${parts[*]}"70
ls -lh "$archive"@@ -1,14 +1,24 @@
1
1
#!/usr/bin/env bash
2
2
# KVT fork: tools for the BlueGit CI jobs in blue-ci-cd.yml, on an Ubuntu image.
3
# ci-setup.sh linux Linux build (as .github/actions/setup-linux): headers, clang 21, mold
3
# ci-setup.sh linux Linux build (as .github/actions/setup-linux): headers, clang 21, mold (clang-21 zonder lldb/lld/clangd)
4
4
# ci-setup.sh windows the above plus the cross-build bits: lld/llvm 21, wine, cargo-xwin
5
5
# Rust comes from rustup (stable) into $CARGO_HOME, which the jobs cache.
6
6
set -euo pipefail
7
7
mode="${1:-linux}"
8
8
export DEBIAN_FRONTEND=noninteractive
9
# Keep Cargo and rustup in the workspace so ci-cache.sh can pack them.
10
# BlueGit cache only copies files, not directories; the job stores a tarball.
11
if [[ -n "${CI:-}" ]]; then
12
export CARGO_HOME="${CARGO_HOME:-$PWD/cargo-home}"
13
export RUSTUP_HOME="${RUSTUP_HOME:-$PWD/rustup-home}"
14
export PATH="$CARGO_HOME/bin:$PATH"
15
if [[ "$mode" == windows ]]; then
16
export XWIN_CACHE_DIR="${XWIN_CACHE_DIR:-$PWD/xwin-cache}"
17
fi
18
fi
9
19
apt-get update -qq
10
20
apt-get install -y -qq --no-install-recommends \
11
ca-certificates curl git gnupg lsb-release wget software-properties-common \
21
ca-certificates curl git gnupg lsb-release wget \
12
22
build-essential binutils file python3 unzip xz-utils patch jq \
13
23
clang mold pkg-config libclang-dev \
14
24
libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \
@@ -17,8 +27,12 @@ apt-get install -y -qq --no-install-recommends \
17
27
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \
18
28
desktop-file-utils >/dev/null
19
29
# webrtc-sys needs clang 21 (check_clang_version in vendor/webrtc-sys/build.rs).
20
curl -fsSL https://apt.llvm.org/llvm.sh -o /tmp/llvm.sh
21
bash /tmp/llvm.sh 21 >/dev/null
30
# Alleen het apt.llvm.org-repo toevoegen en clang-21 installeren: llvm.sh zelf zet er
31
# ook lldb, lld en clangd bij (honderden MB extra uitpakken op de gedeelde runner).
32
codename="$(lsb_release -cs)"
33
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key -o /etc/apt/trusted.gpg.d/apt.llvm.org.asc
34
echo "deb https://apt.llvm.org/$codename/ llvm-toolchain-$codename-21 main" > /etc/apt/sources.list.d/llvm-21.list
35
apt-get update -qq
22
36
apt-get install -y -qq --no-install-recommends clang-21 >/dev/null
23
37
if [[ "$mode" == windows ]]; then
24
38
# cargo-xwin (ureq/native-tls) needs OpenSSL headers to build on the Linux host.
@@ -1,14 +1,24 @@1
#!/usr/bin/env bash1
#!/usr/bin/env bash2
# KVT fork: tools for the BlueGit CI jobs in blue-ci-cd.yml, on an Ubuntu image.2
# KVT fork: tools for the BlueGit CI jobs in blue-ci-cd.yml, on an Ubuntu image.3
# ci-setup.sh linux Linux build (as .github/actions/setup-linux): headers, clang 21, mold3
# ci-setup.sh linux Linux build (as .github/actions/setup-linux): headers, clang 21, mold (clang-21 zonder lldb/lld/clangd)4
# ci-setup.sh windows the above plus the cross-build bits: lld/llvm 21, wine, cargo-xwin4
# ci-setup.sh windows the above plus the cross-build bits: lld/llvm 21, wine, cargo-xwin5
# Rust comes from rustup (stable) into $CARGO_HOME, which the jobs cache.5
# Rust comes from rustup (stable) into $CARGO_HOME, which the jobs cache.6
set -euo pipefail6
set -euo pipefail7
mode="${1:-linux}"7
mode="${1:-linux}"8
export DEBIAN_FRONTEND=noninteractive8
export DEBIAN_FRONTEND=noninteractive9
# Keep Cargo and rustup in the workspace so ci-cache.sh can pack them.10
# BlueGit cache only copies files, not directories; the job stores a tarball.11
if [[ -n "${CI:-}" ]]; then12
export CARGO_HOME="${CARGO_HOME:-$PWD/cargo-home}"13
export RUSTUP_HOME="${RUSTUP_HOME:-$PWD/rustup-home}"14
export PATH="$CARGO_HOME/bin:$PATH"15
if [[ "$mode" == windows ]]; then16
export XWIN_CACHE_DIR="${XWIN_CACHE_DIR:-$PWD/xwin-cache}"17
fi18
fi9
apt-get update -qq19
apt-get update -qq10
apt-get install -y -qq --no-install-recommends \20
apt-get install -y -qq --no-install-recommends \11
ca-certificates curl git gnupg lsb-release wget software-properties-common \21
ca-certificates curl git gnupg lsb-release wget \12
build-essential binutils file python3 unzip xz-utils patch jq \22
build-essential binutils file python3 unzip xz-utils patch jq \13
clang mold pkg-config libclang-dev \23
clang mold pkg-config libclang-dev \14
libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \24
libglib2.0-dev libfontconfig-dev libasound2-dev libva-dev \@@ -17,8 +27,12 @@ apt-get install -y -qq --no-install-recommends \17
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \27
libxrandr-dev libxcomposite-dev libwayland-dev libpipewire-0.3-dev \18
desktop-file-utils >/dev/null28
desktop-file-utils >/dev/null19
# webrtc-sys needs clang 21 (check_clang_version in vendor/webrtc-sys/build.rs).29
# webrtc-sys needs clang 21 (check_clang_version in vendor/webrtc-sys/build.rs).20
curl -fsSL https://apt.llvm.org/llvm.sh -o /tmp/llvm.sh30
# Alleen het apt.llvm.org-repo toevoegen en clang-21 installeren: llvm.sh zelf zet er21
bash /tmp/llvm.sh 21 >/dev/null31
# ook lldb, lld en clangd bij (honderden MB extra uitpakken op de gedeelde runner).32
codename="$(lsb_release -cs)"33
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key -o /etc/apt/trusted.gpg.d/apt.llvm.org.asc34
echo "deb https://apt.llvm.org/$codename/ llvm-toolchain-$codename-21 main" > /etc/apt/sources.list.d/llvm-21.list35
apt-get update -qq22
apt-get install -y -qq --no-install-recommends clang-21 >/dev/null36
apt-get install -y -qq --no-install-recommends clang-21 >/dev/null23
if [[ "$mode" == windows ]]; then37
if [[ "$mode" == windows ]]; then24
# cargo-xwin (ureq/native-tls) needs OpenSSL headers to build on the Linux host.38
# cargo-xwin (ureq/native-tls) needs OpenSSL headers to build on the Linux host.@@ -55,4 +55,19 @@ PY
55
55
rm dist/kvt/teams-linux-amd64
56
56
! "$HERE/release-assets.sh" sums v0.6.1-kvt.2 2>/dev/null || fail "missing linux binary accepted"
57
57
58
# CI cache helper: tarball round-trip (BlueGit caches files, not directories).
59
cachework="$(mktemp -d)"
60
mkdir -p "$cachework/cargo-home/registry/cache/demo" "$cachework/rustup-home/toolchains"
61
echo crate > "$cachework/cargo-home/registry/cache/demo/foo.crate"
62
echo rustc > "$cachework/rustup-home/toolchains/marker"
63
(cd "$cachework" && CARGO_HOME="$cachework/cargo-home" RUSTUP_HOME="$cachework/rustup-home" "$HERE/ci-cache.sh" save linux)
64
[[ -f "$cachework/.ci-cache/cargo-linux.tar.gz" ]] || fail "cache archive missing"
65
rm -rf "$cachework/cargo-home" "$cachework/rustup-home"
66
(cd "$cachework" && CARGO_HOME="$cachework/cargo-home" RUSTUP_HOME="$cachework/rustup-home" "$HERE/ci-cache.sh" restore linux)
67
[[ -f "$cachework/cargo-home/registry/cache/demo/foo.crate" ]] || fail "cache restore cargo"
68
[[ -f "$cachework/rustup-home/toolchains/marker" ]] || fail "cache restore rustup"
69
out="$(cd "$cachework" && "$HERE/ci-cache.sh" restore windows)"
70
grep -q 'Geen CI-cache' <<<"$out" || fail "missing windows cache message"
71
rm -rf "$cachework"
72
58
73
echo "packaging/kvt tests: ok"
@@ -55,4 +55,19 @@ PY55
rm dist/kvt/teams-linux-amd6455
rm dist/kvt/teams-linux-amd6456
! "$HERE/release-assets.sh" sums v0.6.1-kvt.2 2>/dev/null || fail "missing linux binary accepted"56
! "$HERE/release-assets.sh" sums v0.6.1-kvt.2 2>/dev/null || fail "missing linux binary accepted"57
57
58
# CI cache helper: tarball round-trip (BlueGit caches files, not directories).59
cachework="$(mktemp -d)"60
mkdir -p "$cachework/cargo-home/registry/cache/demo" "$cachework/rustup-home/toolchains"61
echo crate > "$cachework/cargo-home/registry/cache/demo/foo.crate"62
echo rustc > "$cachework/rustup-home/toolchains/marker"63
(cd "$cachework" && CARGO_HOME="$cachework/cargo-home" RUSTUP_HOME="$cachework/rustup-home" "$HERE/ci-cache.sh" save linux)64
[[ -f "$cachework/.ci-cache/cargo-linux.tar.gz" ]] || fail "cache archive missing"65
rm -rf "$cachework/cargo-home" "$cachework/rustup-home"66
(cd "$cachework" && CARGO_HOME="$cachework/cargo-home" RUSTUP_HOME="$cachework/rustup-home" "$HERE/ci-cache.sh" restore linux)67
[[ -f "$cachework/cargo-home/registry/cache/demo/foo.crate" ]] || fail "cache restore cargo"68
[[ -f "$cachework/rustup-home/toolchains/marker" ]] || fail "cache restore rustup"69
out="$(cd "$cachework" && "$HERE/ci-cache.sh" restore windows)"70
grep -q 'Geen CI-cache' <<<"$out" || fail "missing windows cache message"71
rm -rf "$cachework"72
58
echo "packaging/kvt tests: ok"73
echo "packaging/kvt tests: ok"@@ -47,6 +47,7 @@ pub struct TitleBar {
47
47
style: StyleRefinement,
48
48
children: SmallVec<[AnyElement; 1]>,
49
49
on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
50
system_window_controls: bool,
50
51
}
51
52
52
53
impl TitleBar {
@@ -56,6 +57,7 @@ impl TitleBar {
56
57
style: StyleRefinement::default(),
57
58
children: SmallVec::new(),
58
59
on_close_window: None,
60
system_window_controls: true,
59
61
}
60
62
}
61
63
@@ -105,6 +107,15 @@ impl TitleBar {
105
107
}
106
108
self
107
109
}
110
111
/// Whether this title bar draws the built-in minimize/maximize/close buttons.
112
///
113
/// Defaults to `true`. Set to `false` when the window draws its own buttons,
114
/// so the two sets are not stacked.
115
pub fn system_window_controls(mut self, show: bool) -> Self {
116
self.system_window_controls = show;
117
self
118
}
108
119
}
109
120
110
121
// We don't need implementation the click event for the control buttons.
@@ -346,7 +357,7 @@ impl RenderOnce for TitleBar {
346
357
cx.theme().background,
347
358
))
348
359
.refine_style(&self.style)
349
.when(is_linux, |this| {
360
.when(is_linux || cfg!(target_os = "windows"), |this| {
350
361
this.on_double_click(|_, window, _| window.zoom_window())
351
362
})
352
363
.when(is_macos, |this| {
@@ -402,8 +413,10 @@ impl RenderOnce for TitleBar {
402
413
})
403
414
.children(self.children),
404
415
)
405
.child(WindowControls {
406
on_close_window: self.on_close_window,
416
.when(self.system_window_controls, |this| {
417
this.child(WindowControls {
418
on_close_window: self.on_close_window,
419
})
407
420
}),
408
421
)
409
422
}
@@ -47,6 +47,7 @@ pub struct TitleBar {47
style: StyleRefinement,47
style: StyleRefinement,48
children: SmallVec<[AnyElement; 1]>,48
children: SmallVec<[AnyElement; 1]>,49
on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,49
on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,50
system_window_controls: bool,50
}51
}51
52
52
impl TitleBar {53
impl TitleBar {@@ -56,6 +57,7 @@ impl TitleBar {56
style: StyleRefinement::default(),57
style: StyleRefinement::default(),57
children: SmallVec::new(),58
children: SmallVec::new(),58
on_close_window: None,59
on_close_window: None,60
system_window_controls: true,59
}61
}60
}62
}61
63
@@ -105,6 +107,15 @@ impl TitleBar {105
}107
}106
self108
self107
}109
}110
111
/// Whether this title bar draws the built-in minimize/maximize/close buttons.112
///113
/// Defaults to `true`. Set to `false` when the window draws its own buttons,114
/// so the two sets are not stacked.115
pub fn system_window_controls(mut self, show: bool) -> Self {116
self.system_window_controls = show;117
self118
}108
}119
}109
120
110
// We don't need implementation the click event for the control buttons.121
// We don't need implementation the click event for the control buttons.@@ -346,7 +357,7 @@ impl RenderOnce for TitleBar {346
cx.theme().background,357
cx.theme().background,347
))358
))348
.refine_style(&self.style)359
.refine_style(&self.style)349
.when(is_linux, |this| {360
.when(is_linux || cfg!(target_os = "windows"), |this| {350
this.on_double_click(|_, window, _| window.zoom_window())361
this.on_double_click(|_, window, _| window.zoom_window())351
})362
})352
.when(is_macos, |this| {363
.when(is_macos, |this| {@@ -402,8 +413,10 @@ impl RenderOnce for TitleBar {402
})413
})403
.children(self.children),414
.children(self.children),404
)415
)405
.child(WindowControls {416
.when(self.system_window_controls, |this| {406
on_close_window: self.on_close_window,417
this.child(WindowControls {418
on_close_window: self.on_close_window,419
})407
}),420
}),408
)421
)409
}422
}