BlueGit

ict rusty-teams

fix(chat): render adaptive cards, name bot chats, stop phantom selection, clear toast corners

- Adaptive cards render as cards: columns, images, markdown text with links, buttons.
  OpenUrl opens the browser; bot-side actions show disabled.
- Card images load through a native HTTP client (page fetch hits CORS).
- 1:1 bot chats take the bot name instead of "(only you)".
- A mouse move without the left button ends a selection whose mouse-up was missed
  (button released outside the window, screenshot overlay).
- Toast windows paint a transparent root, so rounded corners no longer show dark squares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
425cd4d289fad4b84e68cb6254267fc35026aea9
Parent
d35cfee7
26 files changed +1494 −157
Cargo.lock +158 −1
@@ -262,6 +262,7 @@ dependencies = [
262 262 "directories",
263 263 "embed-resource",
264 264 "gpui-kit",
265 "gpui-pre-reqwest-client",
265 266 "graph",
266 267 "image",
267 268 "raw-window-handle",
@@ -649,6 +650,29 @@ dependencies = [
649 650 "arrayvec",
650 651 ]
651 652
653 [[package]]
654 name = "aws-lc-rs"
655 version = "1.18.1"
656 source = "registry+https://github.com/rust-lang/crates.io-index"
657 checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"
658 dependencies = [
659 "aws-lc-sys",
660 "zeroize",
661 ]
662
663 [[package]]
664 name = "aws-lc-sys"
665 version = "0.45.0"
666 source = "registry+https://github.com/rust-lang/crates.io-index"
667 checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"
668 dependencies = [
669 "cc",
670 "cmake",
671 "dunce",
672 "fs_extra",
673 "pkg-config",
674 ]
675
652 676 [[package]]
653 677 name = "backtrace"
654 678 version = "0.3.76"
@@ -1159,6 +1183,15 @@ dependencies = [
1159 1183 "tokio",
1160 1184 ]
1161 1185
1186 [[package]]
1187 name = "cmake"
1188 version = "0.1.58"
1189 source = "registry+https://github.com/rust-lang/crates.io-index"
1190 checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
1191 dependencies = [
1192 "cc",
1193 ]
1194
1162 1195 [[package]]
1163 1196 name = "cocoa"
1164 1197 version = "0.25.0"
@@ -1520,7 +1553,7 @@ dependencies = [
1520 1553 "alsa",
1521 1554 "coreaudio-rs",
1522 1555 "dasp_sample",
1523 "jni",
1556 "jni 0.21.1",
1524 1557 "js-sys",
1525 1558 "libc",
1526 1559 "mach2",
@@ -2333,6 +2366,12 @@ dependencies = [
2333 2366 "pkg-config",
2334 2367 ]
2335 2368
2369 [[package]]
2370 name = "fs_extra"
2371 version = "1.3.0"
2372 source = "registry+https://github.com/rust-lang/crates.io-index"
2373 checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
2374
2336 2375 [[package]]
2337 2376 name = "fsevent-sys"
2338 2377 version = "4.1.0"
@@ -3085,6 +3124,18 @@ dependencies = [
3085 3124 "url",
3086 3125 ]
3087 3126
3127 [[package]]
3128 name = "gpui-pre-http-client-tls"
3129 version = "0.3.8"
3130 source = "registry+https://github.com/rust-lang/crates.io-index"
3131 checksum = "9bbac58d44e80c2bfdd736cacd334e5c9446d5847cd584193ee3c8634c729c2b"
3132 dependencies = [
3133 "log",
3134 "rustls",
3135 "rustls-platform-verifier",
3136 "webpki-roots",
3137 ]
3138
3088 3139 [[package]]
3089 3140 name = "gpui-pre-linux"
3090 3141 version = "0.3.8"
@@ -3275,6 +3326,24 @@ dependencies = [
3275 3326 "windows-registry 0.4.0",
3276 3327 ]
3277 3328
3329 [[package]]
3330 name = "gpui-pre-reqwest-client"
3331 version = "0.3.8"
3332 source = "registry+https://github.com/rust-lang/crates.io-index"
3333 checksum = "894b8d8618c92cbd4da28a04dd3fcf3c0e0607074fa99416a864ac9b63b18aae"
3334 dependencies = [
3335 "anyhow",
3336 "bytes",
3337 "futures",
3338 "gpui-pre-http-client",
3339 "gpui-pre-http-client-tls",
3340 "gpui-pre-reqwest",
3341 "gpui-pre-util",
3342 "log",
3343 "regex",
3344 "tokio",
3345 ]
3346
3278 3347 [[package]]
3279 3348 name = "gpui-pre-scheduler"
3280 3349 version = "0.3.8"
@@ -4177,6 +4246,36 @@ dependencies = [
4177 4246 "windows-sys 0.45.0",
4178 4247 ]
4179 4248
4249 [[package]]
4250 name = "jni"
4251 version = "0.22.4"
4252 source = "registry+https://github.com/rust-lang/crates.io-index"
4253 checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
4254 dependencies = [
4255 "cfg-if",
4256 "combine",
4257 "jni-macros",
4258 "jni-sys 0.4.1",
4259 "log",
4260 "simd_cesu8",
4261 "thiserror 2.0.21",
4262 "walkdir",
4263 "windows-link 0.2.1",
4264 ]
4265
4266 [[package]]
4267 name = "jni-macros"
4268 version = "0.22.4"
4269 source = "registry+https://github.com/rust-lang/crates.io-index"
4270 checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
4271 dependencies = [
4272 "proc-macro2",
4273 "quote",
4274 "rustc_version",
4275 "simd_cesu8",
4276 "syn 2.0.119",
4277 ]
4278
4180 4279 [[package]]
4181 4280 name = "jni-sys"
4182 4281 version = "0.3.1"
@@ -6792,6 +6891,8 @@ version = "0.23.45"
6792 6891 source = "registry+https://github.com/rust-lang/crates.io-index"
6793 6892 checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
6794 6893 dependencies = [
6894 "aws-lc-rs",
6895 "log",
6795 6896 "once_cell",
6796 6897 "ring",
6797 6898 "rustls-pki-types",
@@ -6831,12 +6932,40 @@ dependencies = [
6831 6932 "zeroize",
6832 6933 ]
6833 6934
6935 [[package]]
6936 name = "rustls-platform-verifier"
6937 version = "0.7.1"
6938 source = "registry+https://github.com/rust-lang/crates.io-index"
6939 checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
6940 dependencies = [
6941 "core-foundation 0.10.1",
6942 "core-foundation-sys",
6943 "jni 0.22.4",
6944 "log",
6945 "once_cell",
6946 "rustls",
6947 "rustls-native-certs",
6948 "rustls-platform-verifier-android",
6949 "rustls-webpki",
6950 "security-framework",
6951 "security-framework-sys",
6952 "webpki-root-certs",
6953 "windows-sys 0.61.2",
6954 ]
6955
6956 [[package]]
6957 name = "rustls-platform-verifier-android"
6958 version = "0.2.0"
6959 source = "registry+https://github.com/rust-lang/crates.io-index"
6960 checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
6961
6834 6962 [[package]]
6835 6963 name = "rustls-webpki"
6836 6964 version = "0.103.15"
6837 6965 source = "registry+https://github.com/rust-lang/crates.io-index"
6838 6966 checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
6839 6967 dependencies = [
6968 "aws-lc-rs",
6840 6969 "ring",
6841 6970 "rustls-pki-types",
6842 6971 "untrusted",
@@ -7281,6 +7410,16 @@ version = "0.3.10"
7281 7410 source = "registry+https://github.com/rust-lang/crates.io-index"
7282 7411 checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
7283 7412
7413 [[package]]
7414 name = "simd_cesu8"
7415 version = "1.2.0"
7416 source = "registry+https://github.com/rust-lang/crates.io-index"
7417 checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
7418 dependencies = [
7419 "rustc_version",
7420 "simdutf8",
7421 ]
7422
7284 7423 [[package]]
7285 7424 name = "simd_helpers"
7286 7425 version = "0.1.0"
@@ -8900,6 +9039,24 @@ dependencies = [
8900 9039 "wasm-bindgen",
8901 9040 ]
8902 9041
9042 [[package]]
9043 name = "webpki-root-certs"
9044 version = "1.0.9"
9045 source = "registry+https://github.com/rust-lang/crates.io-index"
9046 checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
9047 dependencies = [
9048 "rustls-pki-types",
9049 ]
9050
9051 [[package]]
9052 name = "webpki-roots"
9053 version = "1.0.9"
9054 source = "registry+https://github.com/rust-lang/crates.io-index"
9055 checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
9056 dependencies = [
9057 "rustls-pki-types",
9058 ]
9059
8903 9060 [[package]]
8904 9061 name = "webview"
8905 9062 version = "0.1.0"
@@ -262,6 +262,7 @@ dependencies = [
262 "directories",
262 "directories",
263 "embed-resource",
263 "embed-resource",
264 "gpui-kit",
264 "gpui-kit",
265 "gpui-pre-reqwest-client",
265 "graph",
266 "graph",
266 "image",
267 "image",
267 "raw-window-handle",
268 "raw-window-handle",
@@ -649,6 +650,29 @@ dependencies = [
649 "arrayvec",
650 "arrayvec",
650]
651]
651
652
653[[package]]
654name = "aws-lc-rs"
655version = "1.18.1"
656source = "registry+https://github.com/rust-lang/crates.io-index"
657checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"
658dependencies = [
659 "aws-lc-sys",
660 "zeroize",
661]
662
663[[package]]
664name = "aws-lc-sys"
665version = "0.45.0"
666source = "registry+https://github.com/rust-lang/crates.io-index"
667checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"
668dependencies = [
669 "cc",
670 "cmake",
671 "dunce",
672 "fs_extra",
673 "pkg-config",
674]
675
652[[package]]
676[[package]]
653name = "backtrace"
677name = "backtrace"
654version = "0.3.76"
678version = "0.3.76"
@@ -1159,6 +1183,15 @@ dependencies = [
1159 "tokio",
1183 "tokio",
1160]
1184]
1161
1185
1186[[package]]
1187name = "cmake"
1188version = "0.1.58"
1189source = "registry+https://github.com/rust-lang/crates.io-index"
1190checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
1191dependencies = [
1192 "cc",
1193]
1194
1162[[package]]
1195[[package]]
1163name = "cocoa"
1196name = "cocoa"
1164version = "0.25.0"
1197version = "0.25.0"
@@ -1520,7 +1553,7 @@ dependencies = [
1520 "alsa",
1553 "alsa",
1521 "coreaudio-rs",
1554 "coreaudio-rs",
1522 "dasp_sample",
1555 "dasp_sample",
1523 "jni",
1556 "jni 0.21.1",
1524 "js-sys",
1557 "js-sys",
1525 "libc",
1558 "libc",
1526 "mach2",
1559 "mach2",
@@ -2333,6 +2366,12 @@ dependencies = [
2333 "pkg-config",
2366 "pkg-config",
2334]
2367]
2335
2368
2369[[package]]
2370name = "fs_extra"
2371version = "1.3.0"
2372source = "registry+https://github.com/rust-lang/crates.io-index"
2373checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
2374
2336[[package]]
2375[[package]]
2337name = "fsevent-sys"
2376name = "fsevent-sys"
2338version = "4.1.0"
2377version = "4.1.0"
@@ -3085,6 +3124,18 @@ dependencies = [
3085 "url",
3124 "url",
3086]
3125]
3087
3126
3127[[package]]
3128name = "gpui-pre-http-client-tls"
3129version = "0.3.8"
3130source = "registry+https://github.com/rust-lang/crates.io-index"
3131checksum = "9bbac58d44e80c2bfdd736cacd334e5c9446d5847cd584193ee3c8634c729c2b"
3132dependencies = [
3133 "log",
3134 "rustls",
3135 "rustls-platform-verifier",
3136 "webpki-roots",
3137]
3138
3088[[package]]
3139[[package]]
3089name = "gpui-pre-linux"
3140name = "gpui-pre-linux"
3090version = "0.3.8"
3141version = "0.3.8"
@@ -3275,6 +3326,24 @@ dependencies = [
3275 "windows-registry 0.4.0",
3326 "windows-registry 0.4.0",
3276]
3327]
3277
3328
3329[[package]]
3330name = "gpui-pre-reqwest-client"
3331version = "0.3.8"
3332source = "registry+https://github.com/rust-lang/crates.io-index"
3333checksum = "894b8d8618c92cbd4da28a04dd3fcf3c0e0607074fa99416a864ac9b63b18aae"
3334dependencies = [
3335 "anyhow",
3336 "bytes",
3337 "futures",
3338 "gpui-pre-http-client",
3339 "gpui-pre-http-client-tls",
3340 "gpui-pre-reqwest",
3341 "gpui-pre-util",
3342 "log",
3343 "regex",
3344 "tokio",
3345]
3346
3278[[package]]
3347[[package]]
3279name = "gpui-pre-scheduler"
3348name = "gpui-pre-scheduler"
3280version = "0.3.8"
3349version = "0.3.8"
@@ -4177,6 +4246,36 @@ dependencies = [
4177 "windows-sys 0.45.0",
4246 "windows-sys 0.45.0",
4178]
4247]
4179
4248
4249[[package]]
4250name = "jni"
4251version = "0.22.4"
4252source = "registry+https://github.com/rust-lang/crates.io-index"
4253checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
4254dependencies = [
4255 "cfg-if",
4256 "combine",
4257 "jni-macros",
4258 "jni-sys 0.4.1",
4259 "log",
4260 "simd_cesu8",
4261 "thiserror 2.0.21",
4262 "walkdir",
4263 "windows-link 0.2.1",
4264]
4265
4266[[package]]
4267name = "jni-macros"
4268version = "0.22.4"
4269source = "registry+https://github.com/rust-lang/crates.io-index"
4270checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
4271dependencies = [
4272 "proc-macro2",
4273 "quote",
4274 "rustc_version",
4275 "simd_cesu8",
4276 "syn 2.0.119",
4277]
4278
4180[[package]]
4279[[package]]
4181name = "jni-sys"
4280name = "jni-sys"
4182version = "0.3.1"
4281version = "0.3.1"
@@ -6792,6 +6891,8 @@ version = "0.23.45"
6792source = "registry+https://github.com/rust-lang/crates.io-index"
6891source = "registry+https://github.com/rust-lang/crates.io-index"
6793checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
6892checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
6794dependencies = [
6893dependencies = [
6894 "aws-lc-rs",
6895 "log",
6795 "once_cell",
6896 "once_cell",
6796 "ring",
6897 "ring",
6797 "rustls-pki-types",
6898 "rustls-pki-types",
@@ -6831,12 +6932,40 @@ dependencies = [
6831 "zeroize",
6932 "zeroize",
6832]
6933]
6833
6934
6935[[package]]
6936name = "rustls-platform-verifier"
6937version = "0.7.1"
6938source = "registry+https://github.com/rust-lang/crates.io-index"
6939checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
6940dependencies = [
6941 "core-foundation 0.10.1",
6942 "core-foundation-sys",
6943 "jni 0.22.4",
6944 "log",
6945 "once_cell",
6946 "rustls",
6947 "rustls-native-certs",
6948 "rustls-platform-verifier-android",
6949 "rustls-webpki",
6950 "security-framework",
6951 "security-framework-sys",
6952 "webpki-root-certs",
6953 "windows-sys 0.61.2",
6954]
6955
6956[[package]]
6957name = "rustls-platform-verifier-android"
6958version = "0.2.0"
6959source = "registry+https://github.com/rust-lang/crates.io-index"
6960checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
6961
6834[[package]]
6962[[package]]
6835name = "rustls-webpki"
6963name = "rustls-webpki"
6836version = "0.103.15"
6964version = "0.103.15"
6837source = "registry+https://github.com/rust-lang/crates.io-index"
6965source = "registry+https://github.com/rust-lang/crates.io-index"
6838checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
6966checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
6839dependencies = [
6967dependencies = [
6968 "aws-lc-rs",
6840 "ring",
6969 "ring",
6841 "rustls-pki-types",
6970 "rustls-pki-types",
6842 "untrusted",
6971 "untrusted",
@@ -7281,6 +7410,16 @@ version = "0.3.10"
7281source = "registry+https://github.com/rust-lang/crates.io-index"
7410source = "registry+https://github.com/rust-lang/crates.io-index"
7282checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
7411checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
7283
7412
7413[[package]]
7414name = "simd_cesu8"
7415version = "1.2.0"
7416source = "registry+https://github.com/rust-lang/crates.io-index"
7417checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
7418dependencies = [
7419 "rustc_version",
7420 "simdutf8",
7421]
7422
7284[[package]]
7423[[package]]
7285name = "simd_helpers"
7424name = "simd_helpers"
7286version = "0.1.0"
7425version = "0.1.0"
@@ -8900,6 +9039,24 @@ dependencies = [
8900 "wasm-bindgen",
9039 "wasm-bindgen",
8901]
9040]
8902
9041
9042[[package]]
9043name = "webpki-root-certs"
9044version = "1.0.9"
9045source = "registry+https://github.com/rust-lang/crates.io-index"
9046checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
9047dependencies = [
9048 "rustls-pki-types",
9049]
9050
9051[[package]]
9052name = "webpki-roots"
9053version = "1.0.9"
9054source = "registry+https://github.com/rust-lang/crates.io-index"
9055checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
9056dependencies = [
9057 "rustls-pki-types",
9058]
9059
8903[[package]]
9060[[package]]
8904name = "webview"
9061name = "webview"
8905version = "0.1.0"
9062version = "0.1.0"
Cargo.toml +1 −0
@@ -33,6 +33,7 @@ graph = { path = "crates/graph" }
33 33 store = { path = "crates/store" }
34 34 teams-core = { path = "crates/core" }
35 35 gpui-kit = "=0.7.1"
36 reqwest_client = { package = "gpui-pre-reqwest-client", version = "=0.3.8" }
36 37 chatsvc = { path = "crates/chatsvc" }
37 38 webview = { path = "crates/webview" }
38 39
@@ -33,6 +33,7 @@ graph = { path = "crates/graph" }
33store = { path = "crates/store" }
33store = { path = "crates/store" }
34teams-core = { path = "crates/core" }
34teams-core = { path = "crates/core" }
35gpui-kit = "=0.7.1"
35gpui-kit = "=0.7.1"
36reqwest_client = { package = "gpui-pre-reqwest-client", version = "=0.3.8" }
36chatsvc = { path = "crates/chatsvc" }
37chatsvc = { path = "crates/chatsvc" }
37webview = { path = "crates/webview" }
38webview = { path = "crates/webview" }
38
39
README.md +1 −1
@@ -14,7 +14,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
14 14 - Send, edit, delete, react, quote-reply, @mentions
15 15 - Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
16 16 - Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
17 - Inline images, file cards, Adaptive Cards as text
17 - Inline images, file cards, Adaptive Cards (layout, links, images; only open-URL buttons work)
18 18 - Read receipts, presence (last known status shown at start), unread jump
19 19 - Select and copy message text, `Ctrl+A` in the composer
20 20 - Local full-text search and a `Ctrl+K` switcher, served from the cache
@@ -14,7 +14,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
14- Send, edit, delete, react, quote-reply, @mentions
14- Send, edit, delete, react, quote-reply, @mentions
15- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
15- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
16- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
16- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
17- Inline images, file cards, Adaptive Cards as text
17- Inline images, file cards, Adaptive Cards (layout, links, images; only open-URL buttons work)
18- Read receipts, presence (last known status shown at start), unread jump
18- Read receipts, presence (last known status shown at start), unread jump
19- Select and copy message text, `Ctrl+A` in the composer
19- Select and copy message text, `Ctrl+A` in the composer
20- Local full-text search and a `Ctrl+K` switcher, served from the cache
20- Local full-text search and a `Ctrl+K` switcher, served from the cache
ROADMAP.md +1 −1
@@ -76,7 +76,7 @@ Feature parity with the Microsoft Teams desktop client.
76 76 | Unread jump with New divider | Done | |
77 77 | Read receipts | Done | |
78 78 | Select and copy message text | Done | |
79 | Adaptive Cards | Partial | Shown as text, actions do not work |
79 | Adaptive Cards | Partial | Rendered as cards; only open-URL buttons work |
80 80 | Typing indicator | Missing | Event arrives, ignored |
81 81 | Link previews | Missing | |
82 82 | Loop components | Missing | |
@@ -76,7 +76,7 @@ Feature parity with the Microsoft Teams desktop client.
76| Unread jump with New divider | Done | |
76| Unread jump with New divider | Done | |
77| Read receipts | Done | |
77| Read receipts | Done | |
78| Select and copy message text | Done | |
78| Select and copy message text | Done | |
79| Adaptive Cards | Partial | Shown as text, actions do not work |
79| Adaptive Cards | Partial | Rendered as cards; only open-URL buttons work |
80| Typing indicator | Missing | Event arrives, ignored |
80| Typing indicator | Missing | Event arrives, ignored |
81| Link previews | Missing | |
81| Link previews | Missing | |
82| Loop components | Missing | |
82| Loop components | Missing | |
crates/app/Cargo.toml +1 −0
@@ -22,6 +22,7 @@ chatsvc.workspace = true
22 22 chrono.workspace = true
23 23 directories.workspace = true
24 24 gpui-kit.workspace = true
25 reqwest_client.workspace = true
25 26 graph.workspace = true
26 27 serde_json.workspace = true
27 28 session.workspace = true
@@ -22,6 +22,7 @@ chatsvc.workspace = true
22chrono.workspace = true
22chrono.workspace = true
23directories.workspace = true
23directories.workspace = true
24gpui-kit.workspace = true
24gpui-kit.workspace = true
25reqwest_client.workspace = true
25graph.workspace = true
26graph.workspace = true
26serde_json.workspace = true
27serde_json.workspace = true
27session.workspace = true
28session.workspace = true
crates/app/src/demo.rs +68 −0
@@ -19,6 +19,10 @@ const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
19 19 const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
20 20 const STAGING_SIZE: (usize, usize) = (960, 540);
21 21 const PRIORITY_CHAT: &str = "demo-chat-priya";
22 const BOT_CHAT: &str = "demo-chat-wiki-bot";
23 const BOT_NAME: &str = "Wiki Bot";
24 const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
25 const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
22 26 const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
23 27 const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
24 28 (
@@ -150,6 +154,16 @@ struct DemoChat {
150 154 fn demo_chats() -> Vec<DemoChat> {
151 155 let group = |extra: &[(&str, &str)]| people(extra);
152 156 vec![
157 DemoChat {
158 id: BOT_CHAT,
159 kind: "oneOnOne",
160 title: BOT_NAME,
161 members: people(&[]),
162 time: at(0, 13, 45),
163 unread: true,
164 preview: Some(("", BOT_NAME, "Mara Lindqvist edited your page")),
165 deleted: false,
166 },
153 167 DemoChat {
154 168 id: "demo-chat-mara",
155 169 kind: "oneOnOne",
@@ -469,6 +483,7 @@ pub fn seed(store: &Store) {
469 483 let _ = store.upsert_messages(&unread_messages());
470 484 let _ = store.upsert_messages(&channel_messages());
471 485 let _ = store.upsert_messages(&priority_messages());
486 let _ = store.upsert_messages(&bot_messages());
472 487 }
473 488
474 489 fn photo(palette: &Palette) -> Arc<Image> {
@@ -583,6 +598,59 @@ fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> Messag
583 598 record
584 599 }
585 600
601 fn bot_messages() -> Vec<MessageRecord> {
602 let card = serde_json::json!({
603 "type": "AdaptiveCard",
604 "body": [
605 {"type": "ColumnSet", "columns": [
606 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
607 {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"}
608 ]},
609 {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [
610 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"}
611 ]}
612 ]},
613 {"type": "ColumnSet", "separator": true, "columns": [
614 {"type": "Column", "width": "auto", "items": [
615 {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"}
616 ]},
617 {"type": "Column", "width": "stretch", "items": [
618 {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"},
619 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
620 ]}
621 ]},
622 {"type": "ActionSet", "actions": [
623 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
624 {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
625 {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
626 {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}}
627 ]}
628 ]
629 });
630 let attachments = serde_json::json!([{
631 "content_type": "application/vnd.microsoft.card.adaptive",
632 "name": null,
633 "url": null,
634 "text": null,
635 "content": card.to_string()
636 }]);
637 let mut record = with_attachments(
638 message(
639 BOT_CHAT,
640 "b1",
641 None,
642 ("", BOT_NAME),
643 at(0, 13, 45),
644 "<attachment id=\"b1\"></attachment>",
645 "[]",
646 false,
647 ),
648 &attachments.to_string(),
649 );
650 record.sender_id = None;
651 vec![record]
652 }
653
586 654 fn priority_messages() -> Vec<MessageRecord> {
587 655 let priya = (PRIYA_ID, "Priya Nair");
588 656 let me = (DEMO_USER_ID, DEMO_USER_NAME);
@@ -19,6 +19,10 @@ const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
19const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
19const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
20const STAGING_SIZE: (usize, usize) = (960, 540);
20const STAGING_SIZE: (usize, usize) = (960, 540);
21const PRIORITY_CHAT: &str = "demo-chat-priya";
21const PRIORITY_CHAT: &str = "demo-chat-priya";
22const BOT_CHAT: &str = "demo-chat-wiki-bot";
23const BOT_NAME: &str = "Wiki Bot";
24const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
25const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
22const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
26const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
23const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
27const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
24 (
28 (
@@ -150,6 +154,16 @@ struct DemoChat {
150fn demo_chats() -> Vec<DemoChat> {
154fn demo_chats() -> Vec<DemoChat> {
151 let group = |extra: &[(&str, &str)]| people(extra);
155 let group = |extra: &[(&str, &str)]| people(extra);
152 vec![
156 vec![
157 DemoChat {
158 id: BOT_CHAT,
159 kind: "oneOnOne",
160 title: BOT_NAME,
161 members: people(&[]),
162 time: at(0, 13, 45),
163 unread: true,
164 preview: Some(("", BOT_NAME, "Mara Lindqvist edited your page")),
165 deleted: false,
166 },
153 DemoChat {
167 DemoChat {
154 id: "demo-chat-mara",
168 id: "demo-chat-mara",
155 kind: "oneOnOne",
169 kind: "oneOnOne",
@@ -469,6 +483,7 @@ pub fn seed(store: &Store) {
469 let _ = store.upsert_messages(&unread_messages());
483 let _ = store.upsert_messages(&unread_messages());
470 let _ = store.upsert_messages(&channel_messages());
484 let _ = store.upsert_messages(&channel_messages());
471 let _ = store.upsert_messages(&priority_messages());
485 let _ = store.upsert_messages(&priority_messages());
486 let _ = store.upsert_messages(&bot_messages());
472}
487}
473
488
474fn photo(palette: &Palette) -> Arc<Image> {
489fn photo(palette: &Palette) -> Arc<Image> {
@@ -583,6 +598,59 @@ fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> Messag
583 record
598 record
584}
599}
585
600
601fn bot_messages() -> Vec<MessageRecord> {
602 let card = serde_json::json!({
603 "type": "AdaptiveCard",
604 "body": [
605 {"type": "ColumnSet", "columns": [
606 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
607 {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"}
608 ]},
609 {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [
610 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"}
611 ]}
612 ]},
613 {"type": "ColumnSet", "separator": true, "columns": [
614 {"type": "Column", "width": "auto", "items": [
615 {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"}
616 ]},
617 {"type": "Column", "width": "stretch", "items": [
618 {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"},
619 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
620 ]}
621 ]},
622 {"type": "ActionSet", "actions": [
623 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
624 {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
625 {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
626 {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}}
627 ]}
628 ]
629 });
630 let attachments = serde_json::json!([{
631 "content_type": "application/vnd.microsoft.card.adaptive",
632 "name": null,
633 "url": null,
634 "text": null,
635 "content": card.to_string()
636 }]);
637 let mut record = with_attachments(
638 message(
639 BOT_CHAT,
640 "b1",
641 None,
642 ("", BOT_NAME),
643 at(0, 13, 45),
644 "<attachment id=\"b1\"></attachment>",
645 "[]",
646 false,
647 ),
648 &attachments.to_string(),
649 );
650 record.sender_id = None;
651 vec![record]
652}
653
586fn priority_messages() -> Vec<MessageRecord> {
654fn priority_messages() -> Vec<MessageRecord> {
587 let priya = (PRIYA_ID, "Priya Nair");
655 let priya = (PRIYA_ID, "Priya Nair");
588 let me = (DEMO_USER_ID, DEMO_USER_NAME);
656 let me = (DEMO_USER_ID, DEMO_USER_NAME);
crates/app/src/main.rs +7 −1
@@ -38,6 +38,7 @@ use app_state::{AppState, Mode};
38 38 use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
39 39
40 40 pub const APP_NAME: &str = "Rusty Teams";
41 const HTTP_USER_AGENT: &str = "teams-linux";
41 42 const WINDOW_WIDTH: f32 = 1240.;
42 43 const WINDOW_HEIGHT: f32 = 820.;
43 44 const WINDOW_MIN_WIDTH: f32 = 640.;
@@ -149,7 +150,12 @@ fn main() {
149 150 let receiver = (!arguments.demo)
150 151 .then(|| backend::start(store.clone(), transport(arguments.endpoint.as_deref(), arguments.database.as_deref())));
151 152
152 gpui_kit::application()
153 let mut application = gpui_kit::application();
154 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
155 application = application.with_http_client(Arc::new(http_client));
156 }
157
158 application
153 159 .with_assets(assets::AppAssets)
154 160 .run(move |cx| {
155 161 gpui_kit::init(cx);
@@ -38,6 +38,7 @@ use app_state::{AppState, Mode};
38use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
38use views::shell::{AppShell, OpenTarget, Startup, bind_keys};
39
39
40pub const APP_NAME: &str = "Rusty Teams";
40pub const APP_NAME: &str = "Rusty Teams";
41const HTTP_USER_AGENT: &str = "teams-linux";
41const WINDOW_WIDTH: f32 = 1240.;
42const WINDOW_WIDTH: f32 = 1240.;
42const WINDOW_HEIGHT: f32 = 820.;
43const WINDOW_HEIGHT: f32 = 820.;
43const WINDOW_MIN_WIDTH: f32 = 640.;
44const WINDOW_MIN_WIDTH: f32 = 640.;
@@ -149,7 +150,12 @@ fn main() {
149 let receiver = (!arguments.demo)
150 let receiver = (!arguments.demo)
150 .then(|| backend::start(store.clone(), transport(arguments.endpoint.as_deref(), arguments.database.as_deref())));
151 .then(|| backend::start(store.clone(), transport(arguments.endpoint.as_deref(), arguments.database.as_deref())));
151
152
152 gpui_kit::application()
153 let mut application = gpui_kit::application();
154 if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
155 application = application.with_http_client(Arc::new(http_client));
156 }
157
158 application
153 .with_assets(assets::AppAssets)
159 .with_assets(assets::AppAssets)
154 .run(move |cx| {
160 .run(move |cx| {
155 gpui_kit::init(cx);
161 gpui_kit::init(cx);
crates/app/src/notify/center.rs +4 −2
@@ -757,12 +757,14 @@ fn open_popup<V: Render>(
757 757 let center = cx.entity();
758 758 cx.defer(move |cx| {
759 759 let view_center = center.clone();
760 let Ok((handle, _)) = gpui_kit::open_window(options, cx, move |window, cx| {
761 build(view_center, window, cx)
760 let Ok(handle) = cx.open_window(options, move |window, cx| {
761 let view = build(view_center, window, cx);
762 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
762 763 }) else {
763 764 center.update(cx, |this, _| opened(this, None));
764 765 return;
765 766 };
767 let handle = AnyWindowHandle::from(handle);
766 768 let native = handle
767 769 .update(cx, |_, window, _| platform::native_handle(window))
768 770 .ok()
@@ -757,12 +757,14 @@ fn open_popup<V: Render>(
757 let center = cx.entity();
757 let center = cx.entity();
758 cx.defer(move |cx| {
758 cx.defer(move |cx| {
759 let view_center = center.clone();
759 let view_center = center.clone();
760 let Ok((handle, _)) = gpui_kit::open_window(options, cx, move |window, cx| {
760 let Ok(handle) = cx.open_window(options, move |window, cx| {
761 build(view_center, window, cx)
761 let view = build(view_center, window, cx);
762 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
762 }) else {
763 }) else {
763 center.update(cx, |this, _| opened(this, None));
764 center.update(cx, |this, _| opened(this, None));
764 return;
765 return;
765 };
766 };
767 let handle = AnyWindowHandle::from(handle);
766 let native = handle
768 let native = handle
767 .update(cx, |_, window, _| platform::native_handle(window))
769 .update(cx, |_, window, _| platform::native_handle(window))
768 .ok()
770 .ok()
crates/app/src/rows.rs +11 −1
@@ -6,7 +6,8 @@ use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6 6 use gpui_kit::Image;
7 7 use store::MessageRecord;
8 8 use teams_core::{
9 Draft, FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions,
9 AdaptiveCard, Draft, FileCard, ImageRef, ReactionInfo, Span, adaptive_cards, card_texts, files,
10 images, message_spans, reactions,
10 11 };
11 12
12 13 use crate::format;
@@ -125,6 +126,7 @@ pub struct MessageRow {
125 126 pub images: Vec<ImageRef>,
126 127 pub local_images: Vec<LocalImage>,
127 128 pub files: Vec<FileCard>,
129 pub adaptive_cards: Vec<AdaptiveCard>,
128 130 pub reply_count: Option<usize>,
129 131 pub new_marker: bool,
130 132 pub reply_faces: Vec<Face>,
@@ -379,6 +381,13 @@ pub fn reply_excerpt(record: &MessageRecord) -> String {
379 381 let excerpt = match first_line {
380 382 Some(line) => line.to_owned(),
381 383 None if !images(record).is_empty() => "Image".to_owned(),
384 None if let Some(line) = card_texts(record)
385 .iter()
386 .flat_map(|text| text.lines())
387 .next() =>
388 {
389 line.to_owned()
390 }
382 391 None => files(record)
383 392 .into_iter()
384 393 .next()
@@ -431,6 +440,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
431 440 images,
432 441 local_images: Vec::new(),
433 442 files: files(record),
443 adaptive_cards: adaptive_cards(record),
434 444 reply_count: None,
435 445 new_marker: false,
436 446 reply_faces: Vec::new(),
@@ -6,7 +6,8 @@ use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
6use gpui_kit::Image;
7use store::MessageRecord;
7use store::MessageRecord;
8use teams_core::{
8use teams_core::{
9 Draft, FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions,
9 AdaptiveCard, Draft, FileCard, ImageRef, ReactionInfo, Span, adaptive_cards, card_texts, files,
10 images, message_spans, reactions,
10};
11};
11
12
12use crate::format;
13use crate::format;
@@ -125,6 +126,7 @@ pub struct MessageRow {
125 pub images: Vec<ImageRef>,
126 pub images: Vec<ImageRef>,
126 pub local_images: Vec<LocalImage>,
127 pub local_images: Vec<LocalImage>,
127 pub files: Vec<FileCard>,
128 pub files: Vec<FileCard>,
129 pub adaptive_cards: Vec<AdaptiveCard>,
128 pub reply_count: Option<usize>,
130 pub reply_count: Option<usize>,
129 pub new_marker: bool,
131 pub new_marker: bool,
130 pub reply_faces: Vec<Face>,
132 pub reply_faces: Vec<Face>,
@@ -379,6 +381,13 @@ pub fn reply_excerpt(record: &MessageRecord) -> String {
379 let excerpt = match first_line {
381 let excerpt = match first_line {
380 Some(line) => line.to_owned(),
382 Some(line) => line.to_owned(),
381 None if !images(record).is_empty() => "Image".to_owned(),
383 None if !images(record).is_empty() => "Image".to_owned(),
384 None if let Some(line) = card_texts(record)
385 .iter()
386 .flat_map(|text| text.lines())
387 .next() =>
388 {
389 line.to_owned()
390 }
382 None => files(record)
391 None => files(record)
383 .into_iter()
392 .into_iter()
384 .next()
393 .next()
@@ -431,6 +440,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
431 images,
440 images,
432 local_images: Vec::new(),
441 local_images: Vec::new(),
433 files: files(record),
442 files: files(record),
443 adaptive_cards: adaptive_cards(record),
434 reply_count: None,
444 reply_count: None,
435 new_marker: false,
445 new_marker: false,
436 reply_faces: Vec::new(),
446 reply_faces: Vec::new(),
crates/app/src/views/adaptive_card.rs added +337 −0
@@ -0,0 +1,337 @@
1 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
2 use gpui_kit::prelude::FluentBuilder as _;
3 use gpui_kit::*;
4 use teams_core::{
5 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
6 CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
7 VerticalAlignment,
8 };
9
10 use crate::render::{layout_blocks, render_blocks};
11 use crate::theme;
12
13 const CARD_WIDTH: f32 = 480.;
14 const CARD_FULL_WIDTH: f32 = 720.;
15 const CARD_PADDING: f32 = 12.;
16 const CARD_RADIUS: f32 = 10.;
17 const CARD_BORDER_WIDTH: f32 = 1.;
18 const COLUMN_GAP: f32 = 8.;
19 const SEPARATOR_PADDING: f32 = 8.;
20 const ACTION_GAP: f32 = 8.;
21 const ACTION_RADIUS: f32 = 6.;
22 const ACTION_TEXT_SIZE: f32 = 13.;
23 const ACTION_DISABLED_OPACITY: f32 = 0.5;
24 const ACTION_DISABLED_TOOLTIP: &str = "Not supported in this app";
25 const FACT_TITLE_WIDTH: f32 = 96.;
26 const FACT_GAP: f32 = 2.;
27 const CONTAINER_PADDING: f32 = 8.;
28 const CONTAINER_RADIUS: f32 = 6.;
29 const CONTAINER_TINT: f32 = 0.16;
30 const TEXT_LINE_HEIGHT: f32 = 1.35;
31 const IMAGE_RADIUS: f32 = 4.;
32 const IMAGE_SET_GAP: f32 = 6.;
33 const SMALL_IMAGE: f32 = 40.;
34 const MEDIUM_IMAGE: f32 = 80.;
35 const LARGE_IMAGE: f32 = 160.;
36 const EXTERNAL_IMAGE_SCHEME: &str = "https://";
37
38 pub fn cards_view(cards: &[AdaptiveCard], id: &str, cx: &App) -> Vec<AnyElement> {
39 cards
40 .iter()
41 .enumerate()
42 .map(|(index, card)| card_view(card, &format!("{id}-card-{index}"), cx))
43 .collect()
44 }
45
46 fn card_view(card: &AdaptiveCard, id: &str, cx: &App) -> AnyElement {
47 let width = if card.full_width {
48 CARD_FULL_WIDTH
49 } else {
50 CARD_WIDTH
51 };
52 v_flex()
53 .w(px(width))
54 .max_w(relative(1.))
55 .p(px(CARD_PADDING))
56 .rounded(px(CARD_RADIUS))
57 .bg(theme::surface())
58 .border(px(CARD_BORDER_WIDTH))
59 .border_color(theme::border())
60 .text_color(theme::text_strong())
61 .child(items_view(&card.items, id, cx))
62 .when(!card.actions.is_empty(), |card_element| {
63 card_element.child(
64 div()
65 .mt(px(spacing_pixels(CardSpacing::Default)))
66 .child(actions_view(&card.actions, &format!("{id}-actions"))),
67 )
68 })
69 .into_any_element()
70 }
71
72 fn items_view(items: &[CardItem], id: &str, cx: &App) -> Div {
73 v_flex()
74 .w_full()
75 .children(items.iter().enumerate().map(|(index, item)| {
76 let item_id = format!("{id}-{index}");
77 div()
78 .w_full()
79 .when(index > 0, |wrapper| {
80 wrapper.mt(px(spacing_pixels(item.spacing)))
81 })
82 .when(index > 0 && item.separator, |wrapper| {
83 wrapper
84 .pt(px(SEPARATOR_PADDING))
85 .border_t_1()
86 .border_color(theme::border())
87 })
88 .child(element_view(&item.element, &item_id, cx))
89 }))
90 }
91
92 fn spacing_pixels(spacing: CardSpacing) -> f32 {
93 match spacing {
94 CardSpacing::None => 0.,
95 CardSpacing::Small => 4.,
96 CardSpacing::Default => 8.,
97 CardSpacing::Medium => 12.,
98 CardSpacing::Large | CardSpacing::Padding => 16.,
99 CardSpacing::ExtraLarge => 24.,
100 }
101 }
102
103 fn element_view(element: &CardElement, id: &str, cx: &App) -> AnyElement {
104 match element {
105 CardElement::Text(text) => text_view(text, id, cx),
106 CardElement::Image(image) => image_view(image, id),
107 CardElement::ImageSet(images) => h_flex()
108 .flex_wrap()
109 .gap(px(IMAGE_SET_GAP))
110 .children(
111 images
112 .iter()
113 .enumerate()
114 .map(|(index, image)| image_view(image, &format!("{id}-{index}"))),
115 )
116 .into_any_element(),
117 CardElement::Columns(columns) => columns_view(columns, id, cx),
118 CardElement::Container { style, items } => {
119 let tint = container_tint(*style);
120 items_view(items, id, cx)
121 .when_some(tint, |container, tint| {
122 container
123 .p(px(CONTAINER_PADDING))
124 .rounded(px(CONTAINER_RADIUS))
125 .bg(tint)
126 })
127 .into_any_element()
128 }
129 CardElement::Facts(facts) => facts_view(facts, id, cx),
130 CardElement::Actions(actions) => actions_view(actions, id).into_any_element(),
131 }
132 }
133
134 fn container_tint(style: ContainerStyle) -> Option<Hsla> {
135 match style {
136 ContainerStyle::Default => None,
137 ContainerStyle::Emphasis => Some(theme::surface_raised()),
138 ContainerStyle::Accent => Some(theme::accent().opacity(CONTAINER_TINT)),
139 ContainerStyle::Good => Some(theme::green().opacity(CONTAINER_TINT)),
140 ContainerStyle::Warning => Some(theme::amber().opacity(CONTAINER_TINT)),
141 ContainerStyle::Attention => Some(theme::red().opacity(CONTAINER_TINT)),
142 }
143 }
144
145 fn text_size(size: TextSize) -> f32 {
146 match size {
147 TextSize::Small => 11.5,
148 TextSize::Default => 13.5,
149 TextSize::Medium => 15.,
150 TextSize::Large => 17.5,
151 TextSize::ExtraLarge => 21.,
152 }
153 }
154
155 fn text_color(text: &CardText) -> Hsla {
156 match text.color {
157 TextColor::Accent => theme::accent_text(),
158 TextColor::Good => theme::green(),
159 TextColor::Warning => theme::amber(),
160 TextColor::Attention => theme::red_soft(),
161 TextColor::Default | TextColor::Dark | TextColor::Light if text.subtle => {
162 theme::text_muted()
163 }
164 TextColor::Default | TextColor::Dark | TextColor::Light => theme::text_strong(),
165 }
166 }
167
168 fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
169 div()
170 .w_full()
171 .text_size(px(text_size(text.size)))
172 .line_height(relative(TEXT_LINE_HEIGHT))
173 .text_color(text_color(text))
174 .when(text.bold, |element| {
175 element.font_weight(FontWeight::SEMIBOLD)
176 })
177 .when(!text.wrap, |element| element.whitespace_nowrap())
178 .child(render_blocks(&layout_blocks(&text.spans), id, false, cx))
179 .into_any_element()
180 }
181
182 fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
183 v_flex()
184 .w_full()
185 .gap(px(FACT_GAP))
186 .children(facts.iter().enumerate().map(|(index, fact)| {
187 h_flex()
188 .w_full()
189 .items_start()
190 .gap(px(COLUMN_GAP))
191 .text_size(px(text_size(TextSize::Default)))
192 .line_height(relative(TEXT_LINE_HEIGHT))
193 .child(
194 div()
195 .w(px(FACT_TITLE_WIDTH))
196 .flex_none()
197 .font_weight(FontWeight::SEMIBOLD)
198 .text_color(theme::text_muted())
199 .child(fact.title.clone()),
200 )
201 .child(div().flex_1().min_w(px(0.)).child(render_blocks(
202 &layout_blocks(&fact.value),
203 &format!("{id}-{index}"),
204 false,
205 cx,
206 )))
207 }))
208 .into_any_element()
209 }
210
211 fn columns_view(columns: &[CardColumn], id: &str, cx: &App) -> AnyElement {
212 div()
213 .flex()
214 .flex_row()
215 .items_stretch()
216 .w_full()
217 .gap(px(COLUMN_GAP))
218 .children(columns.iter().enumerate().map(|(index, column)| {
219 let content = items_view(&column.items, &format!("{id}-{index}"), cx);
220 let aligned = v_flex()
221 .h_full()
222 .map(|aligned| match column.vertical_alignment {
223 VerticalAlignment::Top => aligned.justify_start(),
224 VerticalAlignment::Center => aligned.justify_center(),
225 VerticalAlignment::Bottom => aligned.justify_end(),
226 });
227 sized_column(aligned, column.width).child(content)
228 }))
229 .into_any_element()
230 }
231
232 fn sized_column(column: Div, width: ColumnWidth) -> Div {
233 match width {
234 ColumnWidth::Auto => column.flex_none(),
235 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
236 ColumnWidth::Weighted(weight) => column
237 .flex_basis(px(0.))
238 .flex_grow(weight.max(0.))
239 .min_w(px(0.)),
240 ColumnWidth::Pixels(pixels) => column.w(px(pixels)).flex_none(),
241 }
242 }
243
244 fn image_view(image: &CardImage, id: &str) -> AnyElement {
245 let width = match (image.width, image.height, named_image_width(image.size)) {
246 (Some(width), _, _) => width,
247 (None, Some(height), _) => height,
248 (None, None, Some(width)) => width,
249 (None, None, None) => MEDIUM_IMAGE,
250 }
251 .min(CARD_FULL_WIDTH - 2. * CARD_PADDING);
252 let height = image.height.unwrap_or(width);
253 let radius = px(if image.person {
254 width.min(height) / 2.
255 } else {
256 IMAGE_RADIUS
257 });
258 let frame = div()
259 .id(ElementId::Name(id.to_owned().into()))
260 .w(px(width))
261 .h(px(height))
262 .max_w(relative(1.))
263 .flex_none()
264 .overflow_hidden()
265 .rounded(radius);
266 if !image.url.starts_with(EXTERNAL_IMAGE_SCHEME) {
267 return frame.bg(theme::surface_raised()).into_any_element();
268 }
269 frame
270 .child(
271 img(image.url.clone())
272 .size_full()
273 .rounded(radius)
274 .object_fit(ObjectFit::Cover)
275 .with_loading(move || image_placeholder(radius))
276 .with_fallback(move || image_placeholder(radius)),
277 )
278 .into_any_element()
279 }
280
281 fn image_placeholder(radius: Pixels) -> AnyElement {
282 div()
283 .size_full()
284 .rounded(radius)
285 .bg(theme::surface_raised())
286 .into_any_element()
287 }
288
289 fn named_image_width(size: ImageSize) -> Option<f32> {
290 match size {
291 ImageSize::Small => Some(SMALL_IMAGE),
292 ImageSize::Medium => Some(MEDIUM_IMAGE),
293 ImageSize::Large => Some(LARGE_IMAGE),
294 ImageSize::Stretch => Some(CARD_WIDTH - 2. * CARD_PADDING),
295 ImageSize::Auto => None,
296 }
297 }
298
299 fn actions_view(actions: &[CardAction], id: &str) -> Div {
300 h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(
301 actions
302 .iter()
303 .enumerate()
304 .map(|(index, action)| action_button(action, format!("{id}-{index}"))),
305 )
306 }
307
308 fn action_button(action: &CardAction, id: String) -> Stateful<Div> {
309 let button = div()
310 .id(ElementId::Name(id.into()))
311 .px(px(12.))
312 .py(px(6.))
313 .rounded(px(ACTION_RADIUS))
314 .border_1()
315 .border_color(theme::border_strong())
316 .text_size(px(ACTION_TEXT_SIZE))
317 .font_weight(FontWeight::SEMIBOLD)
318 .child(action.title.clone());
319 match &action.kind {
320 CardActionKind::OpenUrl(url) => {
321 let url = url.clone();
322 button
323 .text_color(theme::accent_text())
324 .cursor_pointer()
325 .hover(|button| button.bg(theme::row_hover()))
326 .on_click(move |_, _, cx| {
327 cx.stop_propagation();
328 cx.open_url(&url);
329 })
330 }
331 CardActionKind::Unsupported => button
332 .text_color(theme::text_muted())
333 .opacity(ACTION_DISABLED_OPACITY)
334 .tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))
335 .on_click(|_, _, cx| cx.stop_propagation()),
336 }
337 }
@@ -0,0 +1,337 @@
1use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
2use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
4use teams_core::{
5 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
6 CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
7 VerticalAlignment,
8};
9
10use crate::render::{layout_blocks, render_blocks};
11use crate::theme;
12
13const CARD_WIDTH: f32 = 480.;
14const CARD_FULL_WIDTH: f32 = 720.;
15const CARD_PADDING: f32 = 12.;
16const CARD_RADIUS: f32 = 10.;
17const CARD_BORDER_WIDTH: f32 = 1.;
18const COLUMN_GAP: f32 = 8.;
19const SEPARATOR_PADDING: f32 = 8.;
20const ACTION_GAP: f32 = 8.;
21const ACTION_RADIUS: f32 = 6.;
22const ACTION_TEXT_SIZE: f32 = 13.;
23const ACTION_DISABLED_OPACITY: f32 = 0.5;
24const ACTION_DISABLED_TOOLTIP: &str = "Not supported in this app";
25const FACT_TITLE_WIDTH: f32 = 96.;
26const FACT_GAP: f32 = 2.;
27const CONTAINER_PADDING: f32 = 8.;
28const CONTAINER_RADIUS: f32 = 6.;
29const CONTAINER_TINT: f32 = 0.16;
30const TEXT_LINE_HEIGHT: f32 = 1.35;
31const IMAGE_RADIUS: f32 = 4.;
32const IMAGE_SET_GAP: f32 = 6.;
33const SMALL_IMAGE: f32 = 40.;
34const MEDIUM_IMAGE: f32 = 80.;
35const LARGE_IMAGE: f32 = 160.;
36const EXTERNAL_IMAGE_SCHEME: &str = "https://";
37
38pub fn cards_view(cards: &[AdaptiveCard], id: &str, cx: &App) -> Vec<AnyElement> {
39 cards
40 .iter()
41 .enumerate()
42 .map(|(index, card)| card_view(card, &format!("{id}-card-{index}"), cx))
43 .collect()
44}
45
46fn card_view(card: &AdaptiveCard, id: &str, cx: &App) -> AnyElement {
47 let width = if card.full_width {
48 CARD_FULL_WIDTH
49 } else {
50 CARD_WIDTH
51 };
52 v_flex()
53 .w(px(width))
54 .max_w(relative(1.))
55 .p(px(CARD_PADDING))
56 .rounded(px(CARD_RADIUS))
57 .bg(theme::surface())
58 .border(px(CARD_BORDER_WIDTH))
59 .border_color(theme::border())
60 .text_color(theme::text_strong())
61 .child(items_view(&card.items, id, cx))
62 .when(!card.actions.is_empty(), |card_element| {
63 card_element.child(
64 div()
65 .mt(px(spacing_pixels(CardSpacing::Default)))
66 .child(actions_view(&card.actions, &format!("{id}-actions"))),
67 )
68 })
69 .into_any_element()
70}
71
72fn items_view(items: &[CardItem], id: &str, cx: &App) -> Div {
73 v_flex()
74 .w_full()
75 .children(items.iter().enumerate().map(|(index, item)| {
76 let item_id = format!("{id}-{index}");
77 div()
78 .w_full()
79 .when(index > 0, |wrapper| {
80 wrapper.mt(px(spacing_pixels(item.spacing)))
81 })
82 .when(index > 0 && item.separator, |wrapper| {
83 wrapper
84 .pt(px(SEPARATOR_PADDING))
85 .border_t_1()
86 .border_color(theme::border())
87 })
88 .child(element_view(&item.element, &item_id, cx))
89 }))
90}
91
92fn spacing_pixels(spacing: CardSpacing) -> f32 {
93 match spacing {
94 CardSpacing::None => 0.,
95 CardSpacing::Small => 4.,
96 CardSpacing::Default => 8.,
97 CardSpacing::Medium => 12.,
98 CardSpacing::Large | CardSpacing::Padding => 16.,
99 CardSpacing::ExtraLarge => 24.,
100 }
101}
102
103fn element_view(element: &CardElement, id: &str, cx: &App) -> AnyElement {
104 match element {
105 CardElement::Text(text) => text_view(text, id, cx),
106 CardElement::Image(image) => image_view(image, id),
107 CardElement::ImageSet(images) => h_flex()
108 .flex_wrap()
109 .gap(px(IMAGE_SET_GAP))
110 .children(
111 images
112 .iter()
113 .enumerate()
114 .map(|(index, image)| image_view(image, &format!("{id}-{index}"))),
115 )
116 .into_any_element(),
117 CardElement::Columns(columns) => columns_view(columns, id, cx),
118 CardElement::Container { style, items } => {
119 let tint = container_tint(*style);
120 items_view(items, id, cx)
121 .when_some(tint, |container, tint| {
122 container
123 .p(px(CONTAINER_PADDING))
124 .rounded(px(CONTAINER_RADIUS))
125 .bg(tint)
126 })
127 .into_any_element()
128 }
129 CardElement::Facts(facts) => facts_view(facts, id, cx),
130 CardElement::Actions(actions) => actions_view(actions, id).into_any_element(),
131 }
132}
133
134fn container_tint(style: ContainerStyle) -> Option<Hsla> {
135 match style {
136 ContainerStyle::Default => None,
137 ContainerStyle::Emphasis => Some(theme::surface_raised()),
138 ContainerStyle::Accent => Some(theme::accent().opacity(CONTAINER_TINT)),
139 ContainerStyle::Good => Some(theme::green().opacity(CONTAINER_TINT)),
140 ContainerStyle::Warning => Some(theme::amber().opacity(CONTAINER_TINT)),
141 ContainerStyle::Attention => Some(theme::red().opacity(CONTAINER_TINT)),
142 }
143}
144
145fn text_size(size: TextSize) -> f32 {
146 match size {
147 TextSize::Small => 11.5,
148 TextSize::Default => 13.5,
149 TextSize::Medium => 15.,
150 TextSize::Large => 17.5,
151 TextSize::ExtraLarge => 21.,
152 }
153}
154
155fn text_color(text: &CardText) -> Hsla {
156 match text.color {
157 TextColor::Accent => theme::accent_text(),
158 TextColor::Good => theme::green(),
159 TextColor::Warning => theme::amber(),
160 TextColor::Attention => theme::red_soft(),
161 TextColor::Default | TextColor::Dark | TextColor::Light if text.subtle => {
162 theme::text_muted()
163 }
164 TextColor::Default | TextColor::Dark | TextColor::Light => theme::text_strong(),
165 }
166}
167
168fn text_view(text: &CardText, id: &str, cx: &App) -> AnyElement {
169 div()
170 .w_full()
171 .text_size(px(text_size(text.size)))
172 .line_height(relative(TEXT_LINE_HEIGHT))
173 .text_color(text_color(text))
174 .when(text.bold, |element| {
175 element.font_weight(FontWeight::SEMIBOLD)
176 })
177 .when(!text.wrap, |element| element.whitespace_nowrap())
178 .child(render_blocks(&layout_blocks(&text.spans), id, false, cx))
179 .into_any_element()
180}
181
182fn facts_view(facts: &[CardFact], id: &str, cx: &App) -> AnyElement {
183 v_flex()
184 .w_full()
185 .gap(px(FACT_GAP))
186 .children(facts.iter().enumerate().map(|(index, fact)| {
187 h_flex()
188 .w_full()
189 .items_start()
190 .gap(px(COLUMN_GAP))
191 .text_size(px(text_size(TextSize::Default)))
192 .line_height(relative(TEXT_LINE_HEIGHT))
193 .child(
194 div()
195 .w(px(FACT_TITLE_WIDTH))
196 .flex_none()
197 .font_weight(FontWeight::SEMIBOLD)
198 .text_color(theme::text_muted())
199 .child(fact.title.clone()),
200 )
201 .child(div().flex_1().min_w(px(0.)).child(render_blocks(
202 &layout_blocks(&fact.value),
203 &format!("{id}-{index}"),
204 false,
205 cx,
206 )))
207 }))
208 .into_any_element()
209}
210
211fn columns_view(columns: &[CardColumn], id: &str, cx: &App) -> AnyElement {
212 div()
213 .flex()
214 .flex_row()
215 .items_stretch()
216 .w_full()
217 .gap(px(COLUMN_GAP))
218 .children(columns.iter().enumerate().map(|(index, column)| {
219 let content = items_view(&column.items, &format!("{id}-{index}"), cx);
220 let aligned = v_flex()
221 .h_full()
222 .map(|aligned| match column.vertical_alignment {
223 VerticalAlignment::Top => aligned.justify_start(),
224 VerticalAlignment::Center => aligned.justify_center(),
225 VerticalAlignment::Bottom => aligned.justify_end(),
226 });
227 sized_column(aligned, column.width).child(content)
228 }))
229 .into_any_element()
230}
231
232fn sized_column(column: Div, width: ColumnWidth) -> Div {
233 match width {
234 ColumnWidth::Auto => column.flex_none(),
235 ColumnWidth::Stretch => column.flex_1().min_w(px(0.)),
236 ColumnWidth::Weighted(weight) => column
237 .flex_basis(px(0.))
238 .flex_grow(weight.max(0.))
239 .min_w(px(0.)),
240 ColumnWidth::Pixels(pixels) => column.w(px(pixels)).flex_none(),
241 }
242}
243
244fn image_view(image: &CardImage, id: &str) -> AnyElement {
245 let width = match (image.width, image.height, named_image_width(image.size)) {
246 (Some(width), _, _) => width,
247 (None, Some(height), _) => height,
248 (None, None, Some(width)) => width,
249 (None, None, None) => MEDIUM_IMAGE,
250 }
251 .min(CARD_FULL_WIDTH - 2. * CARD_PADDING);
252 let height = image.height.unwrap_or(width);
253 let radius = px(if image.person {
254 width.min(height) / 2.
255 } else {
256 IMAGE_RADIUS
257 });
258 let frame = div()
259 .id(ElementId::Name(id.to_owned().into()))
260 .w(px(width))
261 .h(px(height))
262 .max_w(relative(1.))
263 .flex_none()
264 .overflow_hidden()
265 .rounded(radius);
266 if !image.url.starts_with(EXTERNAL_IMAGE_SCHEME) {
267 return frame.bg(theme::surface_raised()).into_any_element();
268 }
269 frame
270 .child(
271 img(image.url.clone())
272 .size_full()
273 .rounded(radius)
274 .object_fit(ObjectFit::Cover)
275 .with_loading(move || image_placeholder(radius))
276 .with_fallback(move || image_placeholder(radius)),
277 )
278 .into_any_element()
279}
280
281fn image_placeholder(radius: Pixels) -> AnyElement {
282 div()
283 .size_full()
284 .rounded(radius)
285 .bg(theme::surface_raised())
286 .into_any_element()
287}
288
289fn named_image_width(size: ImageSize) -> Option<f32> {
290 match size {
291 ImageSize::Small => Some(SMALL_IMAGE),
292 ImageSize::Medium => Some(MEDIUM_IMAGE),
293 ImageSize::Large => Some(LARGE_IMAGE),
294 ImageSize::Stretch => Some(CARD_WIDTH - 2. * CARD_PADDING),
295 ImageSize::Auto => None,
296 }
297}
298
299fn actions_view(actions: &[CardAction], id: &str) -> Div {
300 h_flex().w_full().flex_wrap().gap(px(ACTION_GAP)).children(
301 actions
302 .iter()
303 .enumerate()
304 .map(|(index, action)| action_button(action, format!("{id}-{index}"))),
305 )
306}
307
308fn action_button(action: &CardAction, id: String) -> Stateful<Div> {
309 let button = div()
310 .id(ElementId::Name(id.into()))
311 .px(px(12.))
312 .py(px(6.))
313 .rounded(px(ACTION_RADIUS))
314 .border_1()
315 .border_color(theme::border_strong())
316 .text_size(px(ACTION_TEXT_SIZE))
317 .font_weight(FontWeight::SEMIBOLD)
318 .child(action.title.clone());
319 match &action.kind {
320 CardActionKind::OpenUrl(url) => {
321 let url = url.clone();
322 button
323 .text_color(theme::accent_text())
324 .cursor_pointer()
325 .hover(|button| button.bg(theme::row_hover()))
326 .on_click(move |_, _, cx| {
327 cx.stop_propagation();
328 cx.open_url(&url);
329 })
330 }
331 CardActionKind::Unsupported => button
332 .text_color(theme::text_muted())
333 .opacity(ACTION_DISABLED_OPACITY)
334 .tooltip(|window, cx| Tooltip::new(ACTION_DISABLED_TOOLTIP).build(window, cx))
335 .on_click(|_, _, cx| cx.stop_propagation()),
336 }
337}
crates/app/src/views/conversation.rs +1 −0
@@ -1618,6 +1618,7 @@ impl ConversationView {
1618 1618 size: image.dimensions,
1619 1619 })
1620 1620 .collect(),
1621 adaptive_cards: Vec::new(),
1621 1622 files: outgoing
1622 1623 .files
1623 1624 .iter()
@@ -1618,6 +1618,7 @@ impl ConversationView {
1618 size: image.dimensions,
1618 size: image.dimensions,
1619 })
1619 })
1620 .collect(),
1620 .collect(),
1621 adaptive_cards: Vec::new(),
1621 files: outgoing
1622 files: outgoing
1622 .files
1623 .files
1623 .iter()
1624 .iter()
crates/app/src/views/message_row.rs +15 −1
@@ -5,6 +5,7 @@ use gpui_kit::prelude::FluentBuilder as _;
5 5 use gpui_kit::*;
6 6 use std::time::Duration;
7 7
8 use super::adaptive_card::cards_view;
8 9 use super::attachments::{FileActions, attachments_view, message_body};
9 10 use super::avatar::{member_stack, person_avatar};
10 11 use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
@@ -148,6 +149,11 @@ fn bubble(
148 149 directory,
149 150 extras.files.as_ref(),
150 151 ));
152 content = content.children(cards_view(
153 &row.adaptive_cards,
154 &format!("message-{index}"),
155 cx,
156 ));
151 157 if has_reactions {
152 158 content = content.child(
153 159 h_flex()
@@ -315,7 +321,10 @@ fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
315 321
316 322 fn has_text(row: &MessageRow) -> bool {
317 323 !row.blocks.is_empty()
318 || (row.images.is_empty() && row.local_images.is_empty() && row.files.is_empty())
324 || (row.images.is_empty()
325 && row.local_images.is_empty()
326 && row.files.is_empty()
327 && row.adaptive_cards.is_empty())
319 328 }
320 329
321 330 fn delivery_note(row: &MessageRow, retry: RowAction, index: usize) -> Option<AnyElement> {
@@ -478,6 +487,11 @@ fn post_card(
478 487 directory,
479 488 files,
480 489 ));
490 body = body.children(cards_view(
491 &row.adaptive_cards,
492 &format!("message-{index}"),
493 cx,
494 ));
481 495 if !row.reactions.is_empty() {
482 496 body = body.child(reaction_pills(
483 497 &row.reactions,
@@ -5,6 +5,7 @@ use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
5use gpui_kit::*;
6use std::time::Duration;
6use std::time::Duration;
7
7
8use super::adaptive_card::cards_view;
8use super::attachments::{FileActions, attachments_view, message_body};
9use super::attachments::{FileActions, attachments_view, message_body};
9use super::avatar::{member_stack, person_avatar};
10use super::avatar::{member_stack, person_avatar};
10use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
@@ -148,6 +149,11 @@ fn bubble(
148 directory,
149 directory,
149 extras.files.as_ref(),
150 extras.files.as_ref(),
150 ));
151 ));
152 content = content.children(cards_view(
153 &row.adaptive_cards,
154 &format!("message-{index}"),
155 cx,
156 ));
151 if has_reactions {
157 if has_reactions {
152 content = content.child(
158 content = content.child(
153 h_flex()
159 h_flex()
@@ -315,7 +321,10 @@ fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
315
321
316fn has_text(row: &MessageRow) -> bool {
322fn has_text(row: &MessageRow) -> bool {
317 !row.blocks.is_empty()
323 !row.blocks.is_empty()
318 || (row.images.is_empty() && row.local_images.is_empty() && row.files.is_empty())
324 || (row.images.is_empty()
325 && row.local_images.is_empty()
326 && row.files.is_empty()
327 && row.adaptive_cards.is_empty())
319}
328}
320
329
321fn delivery_note(row: &MessageRow, retry: RowAction, index: usize) -> Option<AnyElement> {
330fn delivery_note(row: &MessageRow, retry: RowAction, index: usize) -> Option<AnyElement> {
@@ -478,6 +487,11 @@ fn post_card(
478 directory,
487 directory,
479 files,
488 files,
480 ));
489 ));
490 body = body.children(cards_view(
491 &row.adaptive_cards,
492 &format!("message-{index}"),
493 cx,
494 ));
481 if !row.reactions.is_empty() {
495 if !row.reactions.is_empty() {
482 body = body.child(reaction_pills(
496 body = body.child(reaction_pills(
483 &row.reactions,
497 &row.reactions,
crates/app/src/views/mod.rs +1 −0
@@ -1,3 +1,4 @@
1 pub mod adaptive_card;
1 2 pub mod attachment_tray;
2 3 pub mod attachments;
3 4 pub mod avatar;
@@ -1,3 +1,4 @@
1pub mod adaptive_card;
1pub mod attachment_tray;
2pub mod attachment_tray;
2pub mod attachments;
3pub mod attachments;
3pub mod avatar;
4pub mod avatar;
crates/core/src/adaptive_card.rs added +559 −0
@@ -0,0 +1,559 @@
1 use serde_json::Value;
2
3 use crate::markdown::markdown_to_html;
4 use crate::spans::{Span, html_to_spans};
5 use crate::stored::push_plain;
6
7 const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
8 const IMAGE_URL_SCHEME: &str = "https://";
9 const ACTION_TYPE_PREFIX: &str = "Action.";
10 const OPEN_URL_ACTION: &str = "Action.OpenUrl";
11 const PIXEL_SUFFIX: &str = "px";
12
13 #[derive(Debug, Clone, PartialEq)]
14 pub struct AdaptiveCard {
15 pub full_width: bool,
16 pub items: Vec<CardItem>,
17 pub actions: Vec<CardAction>,
18 }
19
20 #[derive(Debug, Clone, PartialEq)]
21 pub struct CardItem {
22 pub separator: bool,
23 pub spacing: CardSpacing,
24 pub element: CardElement,
25 }
26
27 #[derive(Debug, Clone, PartialEq)]
28 pub enum CardElement {
29 Text(CardText),
30 Image(CardImage),
31 ImageSet(Vec<CardImage>),
32 Columns(Vec<CardColumn>),
33 Container {
34 style: ContainerStyle,
35 items: Vec<CardItem>,
36 },
37 Facts(Vec<CardFact>),
38 Actions(Vec<CardAction>),
39 }
40
41 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
42 pub enum CardSpacing {
43 None,
44 Small,
45 Default,
46 Medium,
47 Large,
48 ExtraLarge,
49 Padding,
50 }
51
52 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
53 pub enum TextSize {
54 Small,
55 Default,
56 Medium,
57 Large,
58 ExtraLarge,
59 }
60
61 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
62 pub enum TextColor {
63 Default,
64 Dark,
65 Light,
66 Accent,
67 Good,
68 Warning,
69 Attention,
70 }
71
72 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
73 pub enum ImageSize {
74 Auto,
75 Stretch,
76 Small,
77 Medium,
78 Large,
79 }
80
81 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
82 pub enum ContainerStyle {
83 Default,
84 Emphasis,
85 Accent,
86 Good,
87 Warning,
88 Attention,
89 }
90
91 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
92 pub enum VerticalAlignment {
93 Top,
94 Center,
95 Bottom,
96 }
97
98 #[derive(Debug, Clone, Copy, PartialEq)]
99 pub enum ColumnWidth {
100 Auto,
101 Stretch,
102 Weighted(f32),
103 Pixels(f32),
104 }
105
106 #[derive(Debug, Clone, PartialEq)]
107 pub struct CardText {
108 pub spans: Vec<Span>,
109 pub size: TextSize,
110 pub bold: bool,
111 pub color: TextColor,
112 pub subtle: bool,
113 pub wrap: bool,
114 }
115
116 #[derive(Debug, Clone, PartialEq)]
117 pub struct CardImage {
118 pub url: String,
119 pub size: ImageSize,
120 pub width: Option<f32>,
121 pub height: Option<f32>,
122 pub person: bool,
123 }
124
125 #[derive(Debug, Clone, PartialEq)]
126 pub struct CardColumn {
127 pub width: ColumnWidth,
128 pub vertical_alignment: VerticalAlignment,
129 pub items: Vec<CardItem>,
130 }
131
132 #[derive(Debug, Clone, PartialEq)]
133 pub struct CardFact {
134 pub title: String,
135 pub value: Vec<Span>,
136 }
137
138 #[derive(Debug, Clone, PartialEq)]
139 pub struct CardAction {
140 pub title: String,
141 pub kind: CardActionKind,
142 }
143
144 #[derive(Debug, Clone, PartialEq, Eq)]
145 pub enum CardActionKind {
146 OpenUrl(String),
147 Unsupported,
148 }
149
150 impl AdaptiveCard {
151 pub fn parse(content: &str) -> Option<AdaptiveCard> {
152 let root: Value = serde_json::from_str(content).ok()?;
153 let object = root.as_object()?;
154 let mut items = parse_items(object.get("body"));
155 let actions = parse_actions(object.get("actions"));
156 if items.is_empty()
157 && let Some(item) = fallback_item(&root)
158 {
159 items.push(item);
160 }
161 if items.is_empty() && actions.is_empty() {
162 return None;
163 }
164 let full_width = object
165 .get("msTeams")
166 .and_then(|settings| string_field(settings, "width"))
167 .is_some_and(|width| width.eq_ignore_ascii_case("full"));
168 Some(AdaptiveCard {
169 full_width,
170 items,
171 actions,
172 })
173 }
174
175 pub fn plain_text(&self) -> Option<String> {
176 let mut lines = Vec::new();
177 collect_lines(&self.items, &mut lines);
178 (!lines.is_empty()).then(|| lines.join("\n"))
179 }
180 }
181
182 pub fn card_content_text(content: &str) -> Option<String> {
183 AdaptiveCard::parse(content)?.plain_text()
184 }
185
186 fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
187 for item in items {
188 match &item.element {
189 CardElement::Text(text) => push_line(lines, &text.spans),
190 CardElement::Columns(columns) => columns
191 .iter()
192 .for_each(|column| collect_lines(&column.items, lines)),
193 CardElement::Container { items, .. } => collect_lines(items, lines),
194 CardElement::Facts(facts) => {
195 for fact in facts {
196 let mut line = format!("{}: ", fact.title);
197 push_plain(&mut line, &fact.value);
198 lines.push(line.trim().to_owned());
199 }
200 }
201 CardElement::Image(_) | CardElement::ImageSet(_) | CardElement::Actions(_) => {}
202 }
203 }
204 }
205
206 fn push_line(lines: &mut Vec<String>, spans: &[Span]) {
207 let mut line = String::new();
208 push_plain(&mut line, spans);
209 let line = line.trim();
210 if !line.is_empty() {
211 lines.push(line.to_owned());
212 }
213 }
214
215 fn parse_items(value: Option<&Value>) -> Vec<CardItem> {
216 value
217 .and_then(Value::as_array)
218 .into_iter()
219 .flatten()
220 .filter_map(parse_item)
221 .collect()
222 }
223
224 fn parse_item(value: &Value) -> Option<CardItem> {
225 if !is_visible(value) {
226 return None;
227 }
228 let element = match string_field(value, "type")? {
229 "TextBlock" => parse_text_block(value),
230 "RichTextBlock" => parse_rich_text_block(value),
231 "Image" => parse_image(value).map(CardElement::Image),
232 "ImageSet" => parse_image_set(value),
233 "ColumnSet" => parse_column_set(value),
234 "Container" => parse_container(value),
235 "FactSet" => parse_fact_set(value),
236 "ActionSet" => parse_action_set(value),
237 _ => None,
238 };
239 let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
240 Some(CardItem {
241 separator: value
242 .get("separator")
243 .and_then(Value::as_bool)
244 .unwrap_or(false),
245 spacing: parse_spacing(string_field(value, "spacing")),
246 element,
247 })
248 }
249
250 fn fallback_item(value: &Value) -> Option<CardItem> {
251 let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?;
252 Some(CardItem {
253 separator: false,
254 spacing: CardSpacing::Default,
255 element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),
256 })
257 }
258
259 fn plain_text_block(spans: Vec<Span>) -> CardText {
260 CardText {
261 spans,
262 size: TextSize::Default,
263 bold: false,
264 color: TextColor::Default,
265 subtle: false,
266 wrap: true,
267 }
268 }
269
270 fn parse_text_block(value: &Value) -> Option<CardElement> {
271 let text = string_field(value, "text").filter(|text| !text.trim().is_empty())?;
272 Some(CardElement::Text(CardText {
273 spans: html_to_spans(&markdown_to_html(text)),
274 size: parse_text_size(string_field(value, "size")),
275 bold: string_field(value, "weight").is_some_and(is_bold_weight),
276 color: parse_text_color(string_field(value, "color")),
277 subtle: bool_field(value, "isSubtle"),
278 wrap: bool_field(value, "wrap"),
279 }))
280 }
281
282 fn parse_rich_text_block(value: &Value) -> Option<CardElement> {
283 let spans: Vec<Span> = value
284 .get("inlines")?
285 .as_array()?
286 .iter()
287 .filter_map(parse_text_run)
288 .collect();
289 (!spans.is_empty()).then(|| CardElement::Text(plain_text_block(spans)))
290 }
291
292 fn parse_text_run(value: &Value) -> Option<Span> {
293 let text = value
294 .as_str()
295 .or_else(|| string_field(value, "text"))
296 .filter(|text| !text.is_empty())?;
297 let mut span = Span::Text(text.to_owned());
298 if string_field(value, "weight").is_some_and(is_bold_weight) {
299 span = Span::Bold(vec![span]);
300 }
301 if bool_field(value, "italic") {
302 span = Span::Italic(vec![span]);
303 }
304 if bool_field(value, "strikethrough") {
305 span = Span::Strike(vec![span]);
306 }
307 if bool_field(value, "underline") {
308 span = Span::Underline(vec![span]);
309 }
310 let url = value
311 .get("selectAction")
312 .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION))
313 .and_then(|action| string_field(action, "url"))
314 .filter(|url| is_supported_url(url));
315 Some(match url {
316 Some(url) => Span::Link {
317 url: url.to_owned(),
318 children: vec![span],
319 },
320 None => span,
321 })
322 }
323
324 fn parse_image(value: &Value) -> Option<CardImage> {
325 let url = string_field(value, "url").filter(|url| url.starts_with(IMAGE_URL_SCHEME))?;
326 Some(CardImage {
327 url: url.to_owned(),
328 size: parse_image_size(string_field(value, "size")),
329 width: pixel_field(value, "width"),
330 height: pixel_field(value, "height"),
331 person: string_field(value, "style")
332 .is_some_and(|style| style.eq_ignore_ascii_case("person")),
333 })
334 }
335
336 fn parse_image_set(value: &Value) -> Option<CardElement> {
337 let size = parse_image_size(string_field(value, "imageSize"));
338 let images: Vec<CardImage> = value
339 .get("images")?
340 .as_array()?
341 .iter()
342 .filter(|image| is_visible(image))
343 .filter_map(parse_image)
344 .map(|image| match image.size {
345 ImageSize::Auto => CardImage { size, ..image },
346 _ => image,
347 })
348 .collect();
349 (!images.is_empty()).then_some(CardElement::ImageSet(images))
350 }
351
352 fn parse_column_set(value: &Value) -> Option<CardElement> {
353 let columns: Vec<CardColumn> = value
354 .get("columns")?
355 .as_array()?
356 .iter()
357 .filter(|column| is_visible(column))
358 .filter_map(|column| {
359 let items = parse_items(column.get("items"));
360 (!items.is_empty()).then(|| CardColumn {
361 width: parse_column_width(column.get("width")),
362 vertical_alignment: parse_vertical_alignment(string_field(
363 column,
364 "verticalContentAlignment",
365 )),
366 items,
367 })
368 })
369 .collect();
370 (!columns.is_empty()).then_some(CardElement::Columns(columns))
371 }
372
373 fn parse_container(value: &Value) -> Option<CardElement> {
374 let items = parse_items(value.get("items"));
375 (!items.is_empty()).then(|| CardElement::Container {
376 style: parse_container_style(string_field(value, "style")),
377 items,
378 })
379 }
380
381 fn parse_fact_set(value: &Value) -> Option<CardElement> {
382 let facts: Vec<CardFact> = value
383 .get("facts")?
384 .as_array()?
385 .iter()
386 .filter_map(|fact| {
387 let title = string_field(fact, "title")?;
388 let text = string_field(fact, "value").unwrap_or_default();
389 Some(CardFact {
390 title: title.to_owned(),
391 value: html_to_spans(&markdown_to_html(text)),
392 })
393 })
394 .collect();
395 (!facts.is_empty()).then_some(CardElement::Facts(facts))
396 }
397
398 fn parse_action_set(value: &Value) -> Option<CardElement> {
399 let actions = parse_actions(value.get("actions"));
400 (!actions.is_empty()).then_some(CardElement::Actions(actions))
401 }
402
403 fn parse_actions(value: Option<&Value>) -> Vec<CardAction> {
404 value
405 .and_then(Value::as_array)
406 .into_iter()
407 .flatten()
408 .filter_map(parse_action)
409 .collect()
410 }
411
412 fn parse_action(value: &Value) -> Option<CardAction> {
413 if !is_visible(value) {
414 return None;
415 }
416 let action_type = string_field(value, "type")?;
417 if !action_type.starts_with(ACTION_TYPE_PREFIX) {
418 return None;
419 }
420 let title = string_field(value, "title")
421 .map(str::trim)
422 .filter(|title| !title.is_empty())?;
423 let kind = match string_field(value, "url") {
424 Some(url) if action_type == OPEN_URL_ACTION && is_supported_url(url) => {
425 CardActionKind::OpenUrl(url.to_owned())
426 }
427 _ => CardActionKind::Unsupported,
428 };
429 Some(CardAction {
430 title: title.to_owned(),
431 kind,
432 })
433 }
434
435 fn is_bold_weight(weight: &str) -> bool {
436 weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")
437 }
438
439 fn is_supported_url(url: &str) -> bool {
440 SUPPORTED_URL_SCHEMES
441 .iter()
442 .any(|scheme| url.starts_with(scheme))
443 }
444
445 fn is_visible(value: &Value) -> bool {
446 value
447 .get("isVisible")
448 .and_then(Value::as_bool)
449 .unwrap_or(true)
450 }
451
452 fn bool_field(value: &Value, key: &str) -> bool {
453 value.get(key).and_then(Value::as_bool).unwrap_or(false)
454 }
455
456 fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
457 value.get(key)?.as_str()
458 }
459
460 fn pixel_field(value: &Value, key: &str) -> Option<f32> {
461 let field = value.get(key)?;
462 let pixels = match field.as_str() {
463 Some(text) => text
464 .trim()
465 .strip_suffix(PIXEL_SUFFIX)?
466 .trim()
467 .parse()
468 .ok()?,
469 None => field.as_f64()? as f32,
470 };
471 (pixels > 0.).then_some(pixels)
472 }
473
474 fn parse_column_width(value: Option<&Value>) -> ColumnWidth {
475 let Some(value) = value else {
476 return ColumnWidth::Stretch;
477 };
478 if let Some(weight) = value.as_f64() {
479 return ColumnWidth::Weighted(weight as f32);
480 }
481 let Some(text) = value.as_str().map(str::trim) else {
482 return ColumnWidth::Stretch;
483 };
484 if text.eq_ignore_ascii_case("auto") {
485 return ColumnWidth::Auto;
486 }
487 if let Some(pixels) = text
488 .strip_suffix(PIXEL_SUFFIX)
489 .and_then(|number| number.trim().parse().ok())
490 {
491 return ColumnWidth::Pixels(pixels);
492 }
493 text.parse()
494 .map(ColumnWidth::Weighted)
495 .unwrap_or(ColumnWidth::Stretch)
496 }
497
498 fn parse_spacing(value: Option<&str>) -> CardSpacing {
499 match value.map(str::to_ascii_lowercase).as_deref() {
500 Some("none") => CardSpacing::None,
501 Some("small") => CardSpacing::Small,
502 Some("medium") => CardSpacing::Medium,
503 Some("large") => CardSpacing::Large,
504 Some("extralarge") => CardSpacing::ExtraLarge,
505 Some("padding") => CardSpacing::Padding,
506 _ => CardSpacing::Default,
507 }
508 }
509
510 fn parse_text_size(value: Option<&str>) -> TextSize {
511 match value.map(str::to_ascii_lowercase).as_deref() {
512 Some("small") => TextSize::Small,
513 Some("medium") => TextSize::Medium,
514 Some("large") => TextSize::Large,
515 Some("extralarge") => TextSize::ExtraLarge,
516 _ => TextSize::Default,
517 }
518 }
519
520 fn parse_text_color(value: Option<&str>) -> TextColor {
521 match value.map(str::to_ascii_lowercase).as_deref() {
522 Some("dark") => TextColor::Dark,
523 Some("light") => TextColor::Light,
524 Some("accent") => TextColor::Accent,
525 Some("good") => TextColor::Good,
526 Some("warning") => TextColor::Warning,
527 Some("attention") => TextColor::Attention,
528 _ => TextColor::Default,
529 }
530 }
531
532 fn parse_image_size(value: Option<&str>) -> ImageSize {
533 match value.map(str::to_ascii_lowercase).as_deref() {
534 Some("stretch") => ImageSize::Stretch,
535 Some("small") => ImageSize::Small,
536 Some("medium") => ImageSize::Medium,
537 Some("large") => ImageSize::Large,
538 _ => ImageSize::Auto,
539 }
540 }
541
542 fn parse_container_style(value: Option<&str>) -> ContainerStyle {
543 match value.map(str::to_ascii_lowercase).as_deref() {
544 Some("emphasis") => ContainerStyle::Emphasis,
545 Some("accent") => ContainerStyle::Accent,
546 Some("good") => ContainerStyle::Good,
547 Some("warning") => ContainerStyle::Warning,
548 Some("attention") => ContainerStyle::Attention,
549 _ => ContainerStyle::Default,
550 }
551 }
552
553 fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment {
554 match value.map(str::to_ascii_lowercase).as_deref() {
555 Some("center") => VerticalAlignment::Center,
556 Some("bottom") => VerticalAlignment::Bottom,
557 _ => VerticalAlignment::Top,
558 }
559 }
@@ -0,0 +1,559 @@
1use serde_json::Value;
2
3use crate::markdown::markdown_to_html;
4use crate::spans::{Span, html_to_spans};
5use crate::stored::push_plain;
6
7const SUPPORTED_URL_SCHEMES: [&str; 2] = ["https://", "http://"];
8const IMAGE_URL_SCHEME: &str = "https://";
9const ACTION_TYPE_PREFIX: &str = "Action.";
10const OPEN_URL_ACTION: &str = "Action.OpenUrl";
11const PIXEL_SUFFIX: &str = "px";
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct AdaptiveCard {
15 pub full_width: bool,
16 pub items: Vec<CardItem>,
17 pub actions: Vec<CardAction>,
18}
19
20#[derive(Debug, Clone, PartialEq)]
21pub struct CardItem {
22 pub separator: bool,
23 pub spacing: CardSpacing,
24 pub element: CardElement,
25}
26
27#[derive(Debug, Clone, PartialEq)]
28pub enum CardElement {
29 Text(CardText),
30 Image(CardImage),
31 ImageSet(Vec<CardImage>),
32 Columns(Vec<CardColumn>),
33 Container {
34 style: ContainerStyle,
35 items: Vec<CardItem>,
36 },
37 Facts(Vec<CardFact>),
38 Actions(Vec<CardAction>),
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum CardSpacing {
43 None,
44 Small,
45 Default,
46 Medium,
47 Large,
48 ExtraLarge,
49 Padding,
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum TextSize {
54 Small,
55 Default,
56 Medium,
57 Large,
58 ExtraLarge,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum TextColor {
63 Default,
64 Dark,
65 Light,
66 Accent,
67 Good,
68 Warning,
69 Attention,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum ImageSize {
74 Auto,
75 Stretch,
76 Small,
77 Medium,
78 Large,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum ContainerStyle {
83 Default,
84 Emphasis,
85 Accent,
86 Good,
87 Warning,
88 Attention,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum VerticalAlignment {
93 Top,
94 Center,
95 Bottom,
96}
97
98#[derive(Debug, Clone, Copy, PartialEq)]
99pub enum ColumnWidth {
100 Auto,
101 Stretch,
102 Weighted(f32),
103 Pixels(f32),
104}
105
106#[derive(Debug, Clone, PartialEq)]
107pub struct CardText {
108 pub spans: Vec<Span>,
109 pub size: TextSize,
110 pub bold: bool,
111 pub color: TextColor,
112 pub subtle: bool,
113 pub wrap: bool,
114}
115
116#[derive(Debug, Clone, PartialEq)]
117pub struct CardImage {
118 pub url: String,
119 pub size: ImageSize,
120 pub width: Option<f32>,
121 pub height: Option<f32>,
122 pub person: bool,
123}
124
125#[derive(Debug, Clone, PartialEq)]
126pub struct CardColumn {
127 pub width: ColumnWidth,
128 pub vertical_alignment: VerticalAlignment,
129 pub items: Vec<CardItem>,
130}
131
132#[derive(Debug, Clone, PartialEq)]
133pub struct CardFact {
134 pub title: String,
135 pub value: Vec<Span>,
136}
137
138#[derive(Debug, Clone, PartialEq)]
139pub struct CardAction {
140 pub title: String,
141 pub kind: CardActionKind,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum CardActionKind {
146 OpenUrl(String),
147 Unsupported,
148}
149
150impl AdaptiveCard {
151 pub fn parse(content: &str) -> Option<AdaptiveCard> {
152 let root: Value = serde_json::from_str(content).ok()?;
153 let object = root.as_object()?;
154 let mut items = parse_items(object.get("body"));
155 let actions = parse_actions(object.get("actions"));
156 if items.is_empty()
157 && let Some(item) = fallback_item(&root)
158 {
159 items.push(item);
160 }
161 if items.is_empty() && actions.is_empty() {
162 return None;
163 }
164 let full_width = object
165 .get("msTeams")
166 .and_then(|settings| string_field(settings, "width"))
167 .is_some_and(|width| width.eq_ignore_ascii_case("full"));
168 Some(AdaptiveCard {
169 full_width,
170 items,
171 actions,
172 })
173 }
174
175 pub fn plain_text(&self) -> Option<String> {
176 let mut lines = Vec::new();
177 collect_lines(&self.items, &mut lines);
178 (!lines.is_empty()).then(|| lines.join("\n"))
179 }
180}
181
182pub fn card_content_text(content: &str) -> Option<String> {
183 AdaptiveCard::parse(content)?.plain_text()
184}
185
186fn collect_lines(items: &[CardItem], lines: &mut Vec<String>) {
187 for item in items {
188 match &item.element {
189 CardElement::Text(text) => push_line(lines, &text.spans),
190 CardElement::Columns(columns) => columns
191 .iter()
192 .for_each(|column| collect_lines(&column.items, lines)),
193 CardElement::Container { items, .. } => collect_lines(items, lines),
194 CardElement::Facts(facts) => {
195 for fact in facts {
196 let mut line = format!("{}: ", fact.title);
197 push_plain(&mut line, &fact.value);
198 lines.push(line.trim().to_owned());
199 }
200 }
201 CardElement::Image(_) | CardElement::ImageSet(_) | CardElement::Actions(_) => {}
202 }
203 }
204}
205
206fn push_line(lines: &mut Vec<String>, spans: &[Span]) {
207 let mut line = String::new();
208 push_plain(&mut line, spans);
209 let line = line.trim();
210 if !line.is_empty() {
211 lines.push(line.to_owned());
212 }
213}
214
215fn parse_items(value: Option<&Value>) -> Vec<CardItem> {
216 value
217 .and_then(Value::as_array)
218 .into_iter()
219 .flatten()
220 .filter_map(parse_item)
221 .collect()
222}
223
224fn parse_item(value: &Value) -> Option<CardItem> {
225 if !is_visible(value) {
226 return None;
227 }
228 let element = match string_field(value, "type")? {
229 "TextBlock" => parse_text_block(value),
230 "RichTextBlock" => parse_rich_text_block(value),
231 "Image" => parse_image(value).map(CardElement::Image),
232 "ImageSet" => parse_image_set(value),
233 "ColumnSet" => parse_column_set(value),
234 "Container" => parse_container(value),
235 "FactSet" => parse_fact_set(value),
236 "ActionSet" => parse_action_set(value),
237 _ => None,
238 };
239 let element = element.or_else(|| fallback_item(value).map(|item| item.element))?;
240 Some(CardItem {
241 separator: value
242 .get("separator")
243 .and_then(Value::as_bool)
244 .unwrap_or(false),
245 spacing: parse_spacing(string_field(value, "spacing")),
246 element,
247 })
248}
249
250fn fallback_item(value: &Value) -> Option<CardItem> {
251 let text = string_field(value, "fallbackText").filter(|text| !text.trim().is_empty())?;
252 Some(CardItem {
253 separator: false,
254 spacing: CardSpacing::Default,
255 element: CardElement::Text(plain_text_block(vec![Span::Text(text.to_owned())])),
256 })
257}
258
259fn plain_text_block(spans: Vec<Span>) -> CardText {
260 CardText {
261 spans,
262 size: TextSize::Default,
263 bold: false,
264 color: TextColor::Default,
265 subtle: false,
266 wrap: true,
267 }
268}
269
270fn parse_text_block(value: &Value) -> Option<CardElement> {
271 let text = string_field(value, "text").filter(|text| !text.trim().is_empty())?;
272 Some(CardElement::Text(CardText {
273 spans: html_to_spans(&markdown_to_html(text)),
274 size: parse_text_size(string_field(value, "size")),
275 bold: string_field(value, "weight").is_some_and(is_bold_weight),
276 color: parse_text_color(string_field(value, "color")),
277 subtle: bool_field(value, "isSubtle"),
278 wrap: bool_field(value, "wrap"),
279 }))
280}
281
282fn parse_rich_text_block(value: &Value) -> Option<CardElement> {
283 let spans: Vec<Span> = value
284 .get("inlines")?
285 .as_array()?
286 .iter()
287 .filter_map(parse_text_run)
288 .collect();
289 (!spans.is_empty()).then(|| CardElement::Text(plain_text_block(spans)))
290}
291
292fn parse_text_run(value: &Value) -> Option<Span> {
293 let text = value
294 .as_str()
295 .or_else(|| string_field(value, "text"))
296 .filter(|text| !text.is_empty())?;
297 let mut span = Span::Text(text.to_owned());
298 if string_field(value, "weight").is_some_and(is_bold_weight) {
299 span = Span::Bold(vec![span]);
300 }
301 if bool_field(value, "italic") {
302 span = Span::Italic(vec![span]);
303 }
304 if bool_field(value, "strikethrough") {
305 span = Span::Strike(vec![span]);
306 }
307 if bool_field(value, "underline") {
308 span = Span::Underline(vec![span]);
309 }
310 let url = value
311 .get("selectAction")
312 .filter(|action| string_field(action, "type") == Some(OPEN_URL_ACTION))
313 .and_then(|action| string_field(action, "url"))
314 .filter(|url| is_supported_url(url));
315 Some(match url {
316 Some(url) => Span::Link {
317 url: url.to_owned(),
318 children: vec![span],
319 },
320 None => span,
321 })
322}
323
324fn parse_image(value: &Value) -> Option<CardImage> {
325 let url = string_field(value, "url").filter(|url| url.starts_with(IMAGE_URL_SCHEME))?;
326 Some(CardImage {
327 url: url.to_owned(),
328 size: parse_image_size(string_field(value, "size")),
329 width: pixel_field(value, "width"),
330 height: pixel_field(value, "height"),
331 person: string_field(value, "style")
332 .is_some_and(|style| style.eq_ignore_ascii_case("person")),
333 })
334}
335
336fn parse_image_set(value: &Value) -> Option<CardElement> {
337 let size = parse_image_size(string_field(value, "imageSize"));
338 let images: Vec<CardImage> = value
339 .get("images")?
340 .as_array()?
341 .iter()
342 .filter(|image| is_visible(image))
343 .filter_map(parse_image)
344 .map(|image| match image.size {
345 ImageSize::Auto => CardImage { size, ..image },
346 _ => image,
347 })
348 .collect();
349 (!images.is_empty()).then_some(CardElement::ImageSet(images))
350}
351
352fn parse_column_set(value: &Value) -> Option<CardElement> {
353 let columns: Vec<CardColumn> = value
354 .get("columns")?
355 .as_array()?
356 .iter()
357 .filter(|column| is_visible(column))
358 .filter_map(|column| {
359 let items = parse_items(column.get("items"));
360 (!items.is_empty()).then(|| CardColumn {
361 width: parse_column_width(column.get("width")),
362 vertical_alignment: parse_vertical_alignment(string_field(
363 column,
364 "verticalContentAlignment",
365 )),
366 items,
367 })
368 })
369 .collect();
370 (!columns.is_empty()).then_some(CardElement::Columns(columns))
371}
372
373fn parse_container(value: &Value) -> Option<CardElement> {
374 let items = parse_items(value.get("items"));
375 (!items.is_empty()).then(|| CardElement::Container {
376 style: parse_container_style(string_field(value, "style")),
377 items,
378 })
379}
380
381fn parse_fact_set(value: &Value) -> Option<CardElement> {
382 let facts: Vec<CardFact> = value
383 .get("facts")?
384 .as_array()?
385 .iter()
386 .filter_map(|fact| {
387 let title = string_field(fact, "title")?;
388 let text = string_field(fact, "value").unwrap_or_default();
389 Some(CardFact {
390 title: title.to_owned(),
391 value: html_to_spans(&markdown_to_html(text)),
392 })
393 })
394 .collect();
395 (!facts.is_empty()).then_some(CardElement::Facts(facts))
396}
397
398fn parse_action_set(value: &Value) -> Option<CardElement> {
399 let actions = parse_actions(value.get("actions"));
400 (!actions.is_empty()).then_some(CardElement::Actions(actions))
401}
402
403fn parse_actions(value: Option<&Value>) -> Vec<CardAction> {
404 value
405 .and_then(Value::as_array)
406 .into_iter()
407 .flatten()
408 .filter_map(parse_action)
409 .collect()
410}
411
412fn parse_action(value: &Value) -> Option<CardAction> {
413 if !is_visible(value) {
414 return None;
415 }
416 let action_type = string_field(value, "type")?;
417 if !action_type.starts_with(ACTION_TYPE_PREFIX) {
418 return None;
419 }
420 let title = string_field(value, "title")
421 .map(str::trim)
422 .filter(|title| !title.is_empty())?;
423 let kind = match string_field(value, "url") {
424 Some(url) if action_type == OPEN_URL_ACTION && is_supported_url(url) => {
425 CardActionKind::OpenUrl(url.to_owned())
426 }
427 _ => CardActionKind::Unsupported,
428 };
429 Some(CardAction {
430 title: title.to_owned(),
431 kind,
432 })
433}
434
435fn is_bold_weight(weight: &str) -> bool {
436 weight.eq_ignore_ascii_case("bolder") || weight.eq_ignore_ascii_case("bold")
437}
438
439fn is_supported_url(url: &str) -> bool {
440 SUPPORTED_URL_SCHEMES
441 .iter()
442 .any(|scheme| url.starts_with(scheme))
443}
444
445fn is_visible(value: &Value) -> bool {
446 value
447 .get("isVisible")
448 .and_then(Value::as_bool)
449 .unwrap_or(true)
450}
451
452fn bool_field(value: &Value, key: &str) -> bool {
453 value.get(key).and_then(Value::as_bool).unwrap_or(false)
454}
455
456fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
457 value.get(key)?.as_str()
458}
459
460fn pixel_field(value: &Value, key: &str) -> Option<f32> {
461 let field = value.get(key)?;
462 let pixels = match field.as_str() {
463 Some(text) => text
464 .trim()
465 .strip_suffix(PIXEL_SUFFIX)?
466 .trim()
467 .parse()
468 .ok()?,
469 None => field.as_f64()? as f32,
470 };
471 (pixels > 0.).then_some(pixels)
472}
473
474fn parse_column_width(value: Option<&Value>) -> ColumnWidth {
475 let Some(value) = value else {
476 return ColumnWidth::Stretch;
477 };
478 if let Some(weight) = value.as_f64() {
479 return ColumnWidth::Weighted(weight as f32);
480 }
481 let Some(text) = value.as_str().map(str::trim) else {
482 return ColumnWidth::Stretch;
483 };
484 if text.eq_ignore_ascii_case("auto") {
485 return ColumnWidth::Auto;
486 }
487 if let Some(pixels) = text
488 .strip_suffix(PIXEL_SUFFIX)
489 .and_then(|number| number.trim().parse().ok())
490 {
491 return ColumnWidth::Pixels(pixels);
492 }
493 text.parse()
494 .map(ColumnWidth::Weighted)
495 .unwrap_or(ColumnWidth::Stretch)
496}
497
498fn parse_spacing(value: Option<&str>) -> CardSpacing {
499 match value.map(str::to_ascii_lowercase).as_deref() {
500 Some("none") => CardSpacing::None,
501 Some("small") => CardSpacing::Small,
502 Some("medium") => CardSpacing::Medium,
503 Some("large") => CardSpacing::Large,
504 Some("extralarge") => CardSpacing::ExtraLarge,
505 Some("padding") => CardSpacing::Padding,
506 _ => CardSpacing::Default,
507 }
508}
509
510fn parse_text_size(value: Option<&str>) -> TextSize {
511 match value.map(str::to_ascii_lowercase).as_deref() {
512 Some("small") => TextSize::Small,
513 Some("medium") => TextSize::Medium,
514 Some("large") => TextSize::Large,
515 Some("extralarge") => TextSize::ExtraLarge,
516 _ => TextSize::Default,
517 }
518}
519
520fn parse_text_color(value: Option<&str>) -> TextColor {
521 match value.map(str::to_ascii_lowercase).as_deref() {
522 Some("dark") => TextColor::Dark,
523 Some("light") => TextColor::Light,
524 Some("accent") => TextColor::Accent,
525 Some("good") => TextColor::Good,
526 Some("warning") => TextColor::Warning,
527 Some("attention") => TextColor::Attention,
528 _ => TextColor::Default,
529 }
530}
531
532fn parse_image_size(value: Option<&str>) -> ImageSize {
533 match value.map(str::to_ascii_lowercase).as_deref() {
534 Some("stretch") => ImageSize::Stretch,
535 Some("small") => ImageSize::Small,
536 Some("medium") => ImageSize::Medium,
537 Some("large") => ImageSize::Large,
538 _ => ImageSize::Auto,
539 }
540}
541
542fn parse_container_style(value: Option<&str>) -> ContainerStyle {
543 match value.map(str::to_ascii_lowercase).as_deref() {
544 Some("emphasis") => ContainerStyle::Emphasis,
545 Some("accent") => ContainerStyle::Accent,
546 Some("good") => ContainerStyle::Good,
547 Some("warning") => ContainerStyle::Warning,
548 Some("attention") => ContainerStyle::Attention,
549 _ => ContainerStyle::Default,
550 }
551}
552
553fn parse_vertical_alignment(value: Option<&str>) -> VerticalAlignment {
554 match value.map(str::to_ascii_lowercase).as_deref() {
555 Some("center") => VerticalAlignment::Center,
556 Some("bottom") => VerticalAlignment::Bottom,
557 _ => VerticalAlignment::Top,
558 }
559}
crates/core/src/card.rs deleted +0 −99
@@ -1,99 +0,0 @@
1 use std::fmt;
2
3 use serde::Deserialize;
4 use serde::de::{Deserializer, MapAccess, SeqAccess, Visitor};
5
6 const TEXT_KEYS: [&str; 4] = ["title", "text", "subtitle", "value"];
7
8 enum Node {
9 Object(Vec<(String, Node)>),
10 List(Vec<Node>),
11 Text(String),
12 Other,
13 }
14
15 impl<'de> Deserialize<'de> for Node {
16 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
17 struct NodeVisitor;
18
19 impl<'de> Visitor<'de> for NodeVisitor {
20 type Value = Node;
21
22 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23 formatter.write_str("any JSON value")
24 }
25
26 fn visit_str<E>(self, value: &str) -> Result<Node, E> {
27 Ok(Node::Text(value.to_owned()))
28 }
29
30 fn visit_bool<E>(self, _: bool) -> Result<Node, E> {
31 Ok(Node::Other)
32 }
33
34 fn visit_i64<E>(self, _: i64) -> Result<Node, E> {
35 Ok(Node::Other)
36 }
37
38 fn visit_u64<E>(self, _: u64) -> Result<Node, E> {
39 Ok(Node::Other)
40 }
41
42 fn visit_f64<E>(self, _: f64) -> Result<Node, E> {
43 Ok(Node::Other)
44 }
45
46 fn visit_unit<E>(self) -> Result<Node, E> {
47 Ok(Node::Other)
48 }
49
50 fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<Node, A::Error> {
51 let mut items = Vec::new();
52 while let Some(item) = sequence.next_element()? {
53 items.push(item);
54 }
55 Ok(Node::List(items))
56 }
57
58 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Node, A::Error> {
59 let mut entries = Vec::new();
60 while let Some(entry) = map.next_entry()? {
61 entries.push(entry);
62 }
63 Ok(Node::Object(entries))
64 }
65 }
66
67 deserializer.deserialize_any(NodeVisitor)
68 }
69 }
70
71 /// Adaptive Card text: own text keys first, then nested values in document order.
72 fn collect(node: &Node, lines: &mut Vec<String>) {
73 match node {
74 Node::List(items) => items.iter().for_each(|item| collect(item, lines)),
75 Node::Object(entries) => {
76 for key in TEXT_KEYS {
77 let found = entries.iter().find(|(name, _)| name == key);
78 if let Some((_, Node::Text(text))) = found
79 && !text.trim().is_empty()
80 {
81 lines.push(text.clone());
82 }
83 }
84 for (_, value) in entries {
85 if matches!(value, Node::Object(_) | Node::List(_)) {
86 collect(value, lines);
87 }
88 }
89 }
90 Node::Text(_) | Node::Other => {}
91 }
92 }
93
94 pub fn card_content_text(content: &str) -> Option<String> {
95 let parsed: Node = serde_json::from_str(content).ok()?;
96 let mut lines = Vec::new();
97 collect(&parsed, &mut lines);
98 (!lines.is_empty()).then(|| lines.join("\n"))
99 }
@@ -1,99 +0,0 @@
1use std::fmt;
2
3use serde::Deserialize;
4use serde::de::{Deserializer, MapAccess, SeqAccess, Visitor};
5
6const TEXT_KEYS: [&str; 4] = ["title", "text", "subtitle", "value"];
7
8enum Node {
9 Object(Vec<(String, Node)>),
10 List(Vec<Node>),
11 Text(String),
12 Other,
13}
14
15impl<'de> Deserialize<'de> for Node {
16 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
17 struct NodeVisitor;
18
19 impl<'de> Visitor<'de> for NodeVisitor {
20 type Value = Node;
21
22 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23 formatter.write_str("any JSON value")
24 }
25
26 fn visit_str<E>(self, value: &str) -> Result<Node, E> {
27 Ok(Node::Text(value.to_owned()))
28 }
29
30 fn visit_bool<E>(self, _: bool) -> Result<Node, E> {
31 Ok(Node::Other)
32 }
33
34 fn visit_i64<E>(self, _: i64) -> Result<Node, E> {
35 Ok(Node::Other)
36 }
37
38 fn visit_u64<E>(self, _: u64) -> Result<Node, E> {
39 Ok(Node::Other)
40 }
41
42 fn visit_f64<E>(self, _: f64) -> Result<Node, E> {
43 Ok(Node::Other)
44 }
45
46 fn visit_unit<E>(self) -> Result<Node, E> {
47 Ok(Node::Other)
48 }
49
50 fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<Node, A::Error> {
51 let mut items = Vec::new();
52 while let Some(item) = sequence.next_element()? {
53 items.push(item);
54 }
55 Ok(Node::List(items))
56 }
57
58 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Node, A::Error> {
59 let mut entries = Vec::new();
60 while let Some(entry) = map.next_entry()? {
61 entries.push(entry);
62 }
63 Ok(Node::Object(entries))
64 }
65 }
66
67 deserializer.deserialize_any(NodeVisitor)
68 }
69}
70
71/// Adaptive Card text: own text keys first, then nested values in document order.
72fn collect(node: &Node, lines: &mut Vec<String>) {
73 match node {
74 Node::List(items) => items.iter().for_each(|item| collect(item, lines)),
75 Node::Object(entries) => {
76 for key in TEXT_KEYS {
77 let found = entries.iter().find(|(name, _)| name == key);
78 if let Some((_, Node::Text(text))) = found
79 && !text.trim().is_empty()
80 {
81 lines.push(text.clone());
82 }
83 }
84 for (_, value) in entries {
85 if matches!(value, Node::Object(_) | Node::List(_)) {
86 collect(value, lines);
87 }
88 }
89 }
90 Node::Text(_) | Node::Other => {}
91 }
92}
93
94pub fn card_content_text(content: &str) -> Option<String> {
95 let parsed: Node = serde_json::from_str(content).ok()?;
96 let mut lines = Vec::new();
97 collect(&parsed, &mut lines);
98 (!lines.is_empty()).then(|| lines.join("\n"))
99}
crates/core/src/lib.rs +8 −4
@@ -1,6 +1,6 @@
1 1 mod actions;
2 mod adaptive_card;
2 3 mod avatars;
3 mod card;
4 4 mod channel_sync;
5 5 mod download;
6 6 mod draft;
@@ -23,8 +23,12 @@ mod sidebar_sync;
23 23 mod spans;
24 24 mod stored;
25 25
26 pub use adaptive_card::{
27 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
28 CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
29 VerticalAlignment, card_content_text,
30 };
26 31 pub use avatars::Avatar;
27 pub use card::card_content_text;
28 32 pub use draft::{
29 33 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,
30 34 changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -50,6 +54,6 @@ pub use spans::{Span, html_to_spans};
50 54 pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
51 55 pub use stored::{
52 56 AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,
53 attachments, can_delete, can_edit, copy_text, files, images, mentions, message_spans, quotes,
54 reactions, user_mention_inputs,
57 adaptive_cards, attachments, can_delete, can_edit, card_texts, copy_text, files, images,
58 mentions, message_spans, quotes, reactions, user_mention_inputs,
55 59 };
@@ -1,6 +1,6 @@
1mod actions;
1mod actions;
2mod adaptive_card;
2mod avatars;
3mod avatars;
3mod card;
4mod channel_sync;
4mod channel_sync;
5mod download;
5mod download;
6mod draft;
6mod draft;
@@ -23,8 +23,12 @@ mod sidebar_sync;
23mod spans;
23mod spans;
24mod stored;
24mod stored;
25
25
26pub use adaptive_card::{
27 AdaptiveCard, CardAction, CardActionKind, CardColumn, CardElement, CardFact, CardImage,
28 CardItem, CardSpacing, CardText, ColumnWidth, ContainerStyle, ImageSize, TextColor, TextSize,
29 VerticalAlignment, card_content_text,
30};
26pub use avatars::Avatar;
31pub use avatars::Avatar;
27pub use card::card_content_text;
28pub use draft::{
32pub use draft::{
29 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,
33 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,
30 changed_span, has_markdown, link_url, map_offset, reverse_edits,
34 changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -50,6 +54,6 @@ pub use spans::{Span, html_to_spans};
50pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
54pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
51pub use stored::{
55pub use stored::{
52 AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,
56 AttachmentInfo, FileCard, FileKind, ImageRef, MentionInfo, QuoteInfo, ReactionInfo,
53 attachments, can_delete, can_edit, copy_text, files, images, mentions, message_spans, quotes,
57 adaptive_cards, attachments, can_delete, can_edit, card_texts, copy_text, files, images,
54 reactions, user_mention_inputs,
58 mentions, message_spans, quotes, reactions, user_mention_inputs,
55};
59};
crates/core/src/mapping.rs +1 −1
@@ -2,7 +2,7 @@ use chrono::{DateTime, Utc};
2 2 use graph::{Attachment, Chat, Mention, Message, Reaction};
3 3 use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
4 4
5 use crate::card::card_content_text;
5 use crate::adaptive_card::card_content_text;
6 6 use crate::markdown::plain_text_to_html;
7 7 use crate::preview::OwnedPreview;
8 8 use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
@@ -2,7 +2,7 @@ use chrono::{DateTime, Utc};
2use graph::{Attachment, Chat, Mention, Message, Reaction};
2use graph::{Attachment, Chat, Mention, Message, Reaction};
3use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
3use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
4
4
5use crate::card::card_content_text;
5use crate::adaptive_card::card_content_text;
6use crate::markdown::plain_text_to_html;
6use crate::markdown::plain_text_to_html;
7use crate::preview::OwnedPreview;
7use crate::preview::OwnedPreview;
8use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
8use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
crates/core/src/stored.rs +32 −17
@@ -3,6 +3,7 @@ use scraper::{ElementRef, Html};
3 3 use serde::{Deserialize, Serialize};
4 4 use store::MessageRecord;
5 5
6 use crate::adaptive_card::{AdaptiveCard, card_content_text};
6 7 use crate::mentions::MentionInput;
7 8 use crate::spans::{Span, html_to_spans};
8 9
@@ -84,6 +85,18 @@ impl AttachmentInfo {
84 85 .is_some_and(|content_type| content_type.contains("card"))
85 86 }
86 87
88 pub fn adaptive_card(&self) -> Option<AdaptiveCard> {
89 self.content
90 .as_deref()
91 .filter(|_| self.is_card())
92 .and_then(AdaptiveCard::parse)
93 }
94
95 pub fn card_text(&self) -> Option<String> {
96 let content = self.content.as_deref().filter(|_| self.is_card())?;
97 card_content_text(content).or_else(|| self.text.clone())
98 }
99
87 100 pub fn file_kind(&self) -> FileKind {
88 101 match self.name.as_deref().map(FileKind::from_name) {
89 102 Some(FileKind::Other) | None if self.has_image_content_type() => FileKind::Image,
@@ -126,6 +139,20 @@ pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {
126 139 serde_json::from_str(&record.attachments_json).unwrap_or_default()
127 140 }
128 141
142 pub fn adaptive_cards(record: &MessageRecord) -> Vec<AdaptiveCard> {
143 attachments(record)
144 .iter()
145 .filter_map(AttachmentInfo::adaptive_card)
146 .collect()
147 }
148
149 pub fn card_texts(record: &MessageRecord) -> Vec<String> {
150 attachments(record)
151 .iter()
152 .filter_map(AttachmentInfo::card_text)
153 .collect()
154 }
155
129 156 pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> {
130 157 serde_json::from_str(&record.reactions_json).unwrap_or_default()
131 158 }
@@ -290,10 +317,14 @@ pub fn files(record: &MessageRecord) -> Vec<FileCard> {
290 317 pub fn copy_text(record: &MessageRecord) -> String {
291 318 let mut text = String::new();
292 319 push_plain(&mut text, &message_spans(record));
320 for card_text in card_texts(record) {
321 text.push('\n');
322 text.push_str(&card_text);
323 }
293 324 text.trim().to_owned()
294 325 }
295 326
296 fn push_plain(text: &mut String, spans: &[Span]) {
327 pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {
297 328 for span in spans {
298 329 match span {
299 330 Span::Text(value) | Span::Code(value) => text.push_str(value),
@@ -394,7 +425,6 @@ fn leading_number(text: &str) -> Option<u32> {
394 425 digits.parse().ok()
395 426 }
396 427
397 /// Body spans followed by the flattened text of adaptive-card attachments.
398 428 pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
399 429 spans_with_mentions(record, &mentions(record))
400 430 }
@@ -402,21 +432,6 @@ pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
402 432 fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {
403 433 let mut spans = html_to_spans(&record.body_html);
404 434 merge_split_mentions(&mut spans, infos);
405 for card_text in attachments(record)
406 .iter()
407 .filter(|attachment| attachment.is_card())
408 .filter_map(|attachment| attachment.text.as_deref())
409 {
410 if !spans.is_empty() {
411 spans.push(Span::LineBreak);
412 }
413 for (index, line) in card_text.lines().enumerate() {
414 if index > 0 {
415 spans.push(Span::LineBreak);
416 }
417 spans.push(Span::Text(line.to_owned()));
418 }
419 }
420 435 spans
421 436 }
422 437
@@ -3,6 +3,7 @@ use scraper::{ElementRef, Html};
3use serde::{Deserialize, Serialize};
3use serde::{Deserialize, Serialize};
4use store::MessageRecord;
4use store::MessageRecord;
5
5
6use crate::adaptive_card::{AdaptiveCard, card_content_text};
6use crate::mentions::MentionInput;
7use crate::mentions::MentionInput;
7use crate::spans::{Span, html_to_spans};
8use crate::spans::{Span, html_to_spans};
8
9
@@ -84,6 +85,18 @@ impl AttachmentInfo {
84 .is_some_and(|content_type| content_type.contains("card"))
85 .is_some_and(|content_type| content_type.contains("card"))
85 }
86 }
86
87
88 pub fn adaptive_card(&self) -> Option<AdaptiveCard> {
89 self.content
90 .as_deref()
91 .filter(|_| self.is_card())
92 .and_then(AdaptiveCard::parse)
93 }
94
95 pub fn card_text(&self) -> Option<String> {
96 let content = self.content.as_deref().filter(|_| self.is_card())?;
97 card_content_text(content).or_else(|| self.text.clone())
98 }
99
87 pub fn file_kind(&self) -> FileKind {
100 pub fn file_kind(&self) -> FileKind {
88 match self.name.as_deref().map(FileKind::from_name) {
101 match self.name.as_deref().map(FileKind::from_name) {
89 Some(FileKind::Other) | None if self.has_image_content_type() => FileKind::Image,
102 Some(FileKind::Other) | None if self.has_image_content_type() => FileKind::Image,
@@ -126,6 +139,20 @@ pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> {
126 serde_json::from_str(&record.attachments_json).unwrap_or_default()
139 serde_json::from_str(&record.attachments_json).unwrap_or_default()
127}
140}
128
141
142pub fn adaptive_cards(record: &MessageRecord) -> Vec<AdaptiveCard> {
143 attachments(record)
144 .iter()
145 .filter_map(AttachmentInfo::adaptive_card)
146 .collect()
147}
148
149pub fn card_texts(record: &MessageRecord) -> Vec<String> {
150 attachments(record)
151 .iter()
152 .filter_map(AttachmentInfo::card_text)
153 .collect()
154}
155
129pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> {
156pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> {
130 serde_json::from_str(&record.reactions_json).unwrap_or_default()
157 serde_json::from_str(&record.reactions_json).unwrap_or_default()
131}
158}
@@ -290,10 +317,14 @@ pub fn files(record: &MessageRecord) -> Vec<FileCard> {
290pub fn copy_text(record: &MessageRecord) -> String {
317pub fn copy_text(record: &MessageRecord) -> String {
291 let mut text = String::new();
318 let mut text = String::new();
292 push_plain(&mut text, &message_spans(record));
319 push_plain(&mut text, &message_spans(record));
320 for card_text in card_texts(record) {
321 text.push('\n');
322 text.push_str(&card_text);
323 }
293 text.trim().to_owned()
324 text.trim().to_owned()
294}
325}
295
326
296fn push_plain(text: &mut String, spans: &[Span]) {
327pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {
297 for span in spans {
328 for span in spans {
298 match span {
329 match span {
299 Span::Text(value) | Span::Code(value) => text.push_str(value),
330 Span::Text(value) | Span::Code(value) => text.push_str(value),
@@ -394,7 +425,6 @@ fn leading_number(text: &str) -> Option<u32> {
394 digits.parse().ok()
425 digits.parse().ok()
395}
426}
396
427
397/// Body spans followed by the flattened text of adaptive-card attachments.
398pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
428pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
399 spans_with_mentions(record, &mentions(record))
429 spans_with_mentions(record, &mentions(record))
400}
430}
@@ -402,21 +432,6 @@ pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
402fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {
432fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {
403 let mut spans = html_to_spans(&record.body_html);
433 let mut spans = html_to_spans(&record.body_html);
404 merge_split_mentions(&mut spans, infos);
434 merge_split_mentions(&mut spans, infos);
405 for card_text in attachments(record)
406 .iter()
407 .filter(|attachment| attachment.is_card())
408 .filter_map(|attachment| attachment.text.as_deref())
409 {
410 if !spans.is_empty() {
411 spans.push(Span::LineBreak);
412 }
413 for (index, line) in card_text.lines().enumerate() {
414 if index > 0 {
415 spans.push(Span::LineBreak);
416 }
417 spans.push(Span::Text(line.to_owned()));
418 }
419 }
420 spans
435 spans
421}
436}
422
437
crates/core/tests/adaptive_card.rs added +153 −0
@@ -0,0 +1,153 @@
1 use serde_json::json;
2 use teams_core::{
3 AdaptiveCard, CardActionKind, CardElement, ColumnWidth, ImageSize, Span, TextColor, TextSize,
4 VerticalAlignment, card_content_text,
5 };
6
7 fn digest_card() -> String {
8 json!({
9 "type": "AdaptiveCard",
10 "msTeams": {"width": "Full"},
11 "body": [
12 {"type": "ColumnSet", "columns": [
13 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
14 {"type": "Image", "url": "https://img.example.com/person.png", "size": "small", "style": "person", "height": "32px"}
15 ]},
16 {"type": "Column", "width": "stretch", "items": [
17 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Ada Example edited your page"}
18 ]}
19 ]},
20 {"type": "ColumnSet", "separator": true, "columns": [
21 {"type": "Column", "width": "40px", "items": [
22 {"type": "Image", "url": "https://img.example.com/page.png", "width": "24px", "height": "24px"}
23 ]},
24 {"type": "Column", "width": 2, "items": [
25 {"type": "TextBlock", "weight": "bolder", "wrap": true, "color": "accent", "text": "[**Quarterly Plan**](https://example.com/wiki/plan) in [**Product Space**](https://example.com/wiki/space)"},
26 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "text": "Owned by: Ada Example"}
27 ]}
28 ]},
29 {"type": "ActionSet", "actions": [
30 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/plan"},
31 {"type": "Action.OpenUrl", "title": "Unsafe", "url": "javascript:alert(1)"},
32 {"type": "Action.Submit", "title": "Watch", "data": {"action": "watch"}},
33 {"type": "Action.Submit", "title": "Hidden", "isVisible": false}
34 ]}
35 ]
36 })
37 .to_string()
38 }
39
40 #[test]
41 fn digest_card_keeps_layout_text_and_actions() {
42 let card = AdaptiveCard::parse(&digest_card()).unwrap();
43 assert!(card.full_width);
44 assert_eq!(card.items.len(), 3);
45
46 let CardElement::Columns(columns) = &card.items[0].element else {
47 panic!("first item is a column set");
48 };
49 assert_eq!(columns[0].width, ColumnWidth::Auto);
50 assert_eq!(columns[0].vertical_alignment, VerticalAlignment::Center);
51 let CardElement::Image(image) = &columns[0].items[0].element else {
52 panic!("avatar column holds an image");
53 };
54 assert!(image.person);
55 assert_eq!(image.size, ImageSize::Small);
56 assert_eq!(image.height, Some(32.));
57 let CardElement::Text(title) = &columns[1].items[0].element else {
58 panic!("title column holds text");
59 };
60 assert!(title.bold && title.wrap);
61 assert_eq!(title.size, TextSize::Medium);
62
63 assert!(card.items[1].separator);
64 let CardElement::Columns(columns) = &card.items[1].element else {
65 panic!("second item is a column set");
66 };
67 assert_eq!(columns[0].width, ColumnWidth::Pixels(40.));
68 assert_eq!(columns[1].width, ColumnWidth::Weighted(2.));
69 let CardElement::Text(line) = &columns[1].items[0].element else {
70 panic!("text expected");
71 };
72 assert_eq!(line.color, TextColor::Accent);
73 assert_eq!(
74 line.spans[0],
75 Span::Link {
76 url: "https://example.com/wiki/plan".to_owned(),
77 children: vec![Span::Bold(vec![Span::Text("Quarterly Plan".to_owned())])],
78 }
79 );
80 let CardElement::Text(owner) = &columns[1].items[1].element else {
81 panic!("text expected");
82 };
83 assert!(owner.subtle);
84
85 let CardElement::Actions(actions) = &card.items[2].element else {
86 panic!("third item is an action set");
87 };
88 assert_eq!(actions.len(), 3);
89 assert_eq!(
90 actions[0].kind,
91 CardActionKind::OpenUrl("https://example.com/wiki/plan".to_owned())
92 );
93 assert_eq!(actions[1].kind, CardActionKind::Unsupported);
94 assert_eq!(actions[2].title, "Watch");
95 assert_eq!(actions[2].kind, CardActionKind::Unsupported);
96 }
97
98 #[test]
99 fn plain_text_drops_urls_images_and_buttons() {
100 assert_eq!(
101 card_content_text(&digest_card()).unwrap(),
102 "Ada Example edited your page\nQuarterly Plan in Product Space\nOwned by: Ada Example"
103 );
104 }
105
106 #[test]
107 fn hidden_and_unknown_elements_are_skipped_but_fallback_text_stays() {
108 let card = json!({
109 "body": [
110 {"type": "TextBlock", "text": "hidden", "isVisible": false},
111 {"type": "Carousel", "fallbackText": "Open the carousel elsewhere"},
112 {"type": "Carousel"},
113 {"type": "Image", "url": "http://insecure.example.com/a.png"},
114 {"type": "TextBlock", "text": "shown"}
115 ]
116 })
117 .to_string();
118 assert_eq!(
119 card_content_text(&card).unwrap(),
120 "Open the carousel elsewhere\nshown"
121 );
122 }
123
124 #[test]
125 fn containers_fact_sets_and_rich_text_are_parsed() {
126 let card = json!({
127 "body": [
128 {"type": "Container", "style": "emphasis", "items": [
129 {"type": "RichTextBlock", "inlines": [
130 "plain ",
131 {"type": "TextRun", "text": "bold", "weight": "bolder"},
132 {"type": "TextRun", "text": " link", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/x"}}
133 ]},
134 {"type": "FactSet", "facts": [{"title": "Env", "value": "prod"}]},
135 {"type": "ImageSet", "imageSize": "medium", "images": [
136 {"type": "Image", "url": "https://img.example.com/a.png"}
137 ]}
138 ]}
139 ]
140 })
141 .to_string();
142 assert_eq!(
143 card_content_text(&card).unwrap(),
144 "plain bold link\nEnv: prod"
145 );
146 }
147
148 #[test]
149 fn cards_without_content_are_none() {
150 assert!(AdaptiveCard::parse("not json").is_none());
151 assert!(AdaptiveCard::parse(r#"{"body": []}"#).is_none());
152 assert!(AdaptiveCard::parse("[1]").is_none());
153 }
@@ -0,0 +1,153 @@
1use serde_json::json;
2use teams_core::{
3 AdaptiveCard, CardActionKind, CardElement, ColumnWidth, ImageSize, Span, TextColor, TextSize,
4 VerticalAlignment, card_content_text,
5};
6
7fn digest_card() -> String {
8 json!({
9 "type": "AdaptiveCard",
10 "msTeams": {"width": "Full"},
11 "body": [
12 {"type": "ColumnSet", "columns": [
13 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
14 {"type": "Image", "url": "https://img.example.com/person.png", "size": "small", "style": "person", "height": "32px"}
15 ]},
16 {"type": "Column", "width": "stretch", "items": [
17 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Ada Example edited your page"}
18 ]}
19 ]},
20 {"type": "ColumnSet", "separator": true, "columns": [
21 {"type": "Column", "width": "40px", "items": [
22 {"type": "Image", "url": "https://img.example.com/page.png", "width": "24px", "height": "24px"}
23 ]},
24 {"type": "Column", "width": 2, "items": [
25 {"type": "TextBlock", "weight": "bolder", "wrap": true, "color": "accent", "text": "[**Quarterly Plan**](https://example.com/wiki/plan) in [**Product Space**](https://example.com/wiki/space)"},
26 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "text": "Owned by: Ada Example"}
27 ]}
28 ]},
29 {"type": "ActionSet", "actions": [
30 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/plan"},
31 {"type": "Action.OpenUrl", "title": "Unsafe", "url": "javascript:alert(1)"},
32 {"type": "Action.Submit", "title": "Watch", "data": {"action": "watch"}},
33 {"type": "Action.Submit", "title": "Hidden", "isVisible": false}
34 ]}
35 ]
36 })
37 .to_string()
38}
39
40#[test]
41fn digest_card_keeps_layout_text_and_actions() {
42 let card = AdaptiveCard::parse(&digest_card()).unwrap();
43 assert!(card.full_width);
44 assert_eq!(card.items.len(), 3);
45
46 let CardElement::Columns(columns) = &card.items[0].element else {
47 panic!("first item is a column set");
48 };
49 assert_eq!(columns[0].width, ColumnWidth::Auto);
50 assert_eq!(columns[0].vertical_alignment, VerticalAlignment::Center);
51 let CardElement::Image(image) = &columns[0].items[0].element else {
52 panic!("avatar column holds an image");
53 };
54 assert!(image.person);
55 assert_eq!(image.size, ImageSize::Small);
56 assert_eq!(image.height, Some(32.));
57 let CardElement::Text(title) = &columns[1].items[0].element else {
58 panic!("title column holds text");
59 };
60 assert!(title.bold && title.wrap);
61 assert_eq!(title.size, TextSize::Medium);
62
63 assert!(card.items[1].separator);
64 let CardElement::Columns(columns) = &card.items[1].element else {
65 panic!("second item is a column set");
66 };
67 assert_eq!(columns[0].width, ColumnWidth::Pixels(40.));
68 assert_eq!(columns[1].width, ColumnWidth::Weighted(2.));
69 let CardElement::Text(line) = &columns[1].items[0].element else {
70 panic!("text expected");
71 };
72 assert_eq!(line.color, TextColor::Accent);
73 assert_eq!(
74 line.spans[0],
75 Span::Link {
76 url: "https://example.com/wiki/plan".to_owned(),
77 children: vec![Span::Bold(vec![Span::Text("Quarterly Plan".to_owned())])],
78 }
79 );
80 let CardElement::Text(owner) = &columns[1].items[1].element else {
81 panic!("text expected");
82 };
83 assert!(owner.subtle);
84
85 let CardElement::Actions(actions) = &card.items[2].element else {
86 panic!("third item is an action set");
87 };
88 assert_eq!(actions.len(), 3);
89 assert_eq!(
90 actions[0].kind,
91 CardActionKind::OpenUrl("https://example.com/wiki/plan".to_owned())
92 );
93 assert_eq!(actions[1].kind, CardActionKind::Unsupported);
94 assert_eq!(actions[2].title, "Watch");
95 assert_eq!(actions[2].kind, CardActionKind::Unsupported);
96}
97
98#[test]
99fn plain_text_drops_urls_images_and_buttons() {
100 assert_eq!(
101 card_content_text(&digest_card()).unwrap(),
102 "Ada Example edited your page\nQuarterly Plan in Product Space\nOwned by: Ada Example"
103 );
104}
105
106#[test]
107fn hidden_and_unknown_elements_are_skipped_but_fallback_text_stays() {
108 let card = json!({
109 "body": [
110 {"type": "TextBlock", "text": "hidden", "isVisible": false},
111 {"type": "Carousel", "fallbackText": "Open the carousel elsewhere"},
112 {"type": "Carousel"},
113 {"type": "Image", "url": "http://insecure.example.com/a.png"},
114 {"type": "TextBlock", "text": "shown"}
115 ]
116 })
117 .to_string();
118 assert_eq!(
119 card_content_text(&card).unwrap(),
120 "Open the carousel elsewhere\nshown"
121 );
122}
123
124#[test]
125fn containers_fact_sets_and_rich_text_are_parsed() {
126 let card = json!({
127 "body": [
128 {"type": "Container", "style": "emphasis", "items": [
129 {"type": "RichTextBlock", "inlines": [
130 "plain ",
131 {"type": "TextRun", "text": "bold", "weight": "bolder"},
132 {"type": "TextRun", "text": " link", "selectAction": {"type": "Action.OpenUrl", "url": "https://example.com/x"}}
133 ]},
134 {"type": "FactSet", "facts": [{"title": "Env", "value": "prod"}]},
135 {"type": "ImageSet", "imageSize": "medium", "images": [
136 {"type": "Image", "url": "https://img.example.com/a.png"}
137 ]}
138 ]}
139 ]
140 })
141 .to_string();
142 assert_eq!(
143 card_content_text(&card).unwrap(),
144 "plain bold link\nEnv: prod"
145 );
146}
147
148#[test]
149fn cards_without_content_are_none() {
150 assert!(AdaptiveCard::parse("not json").is_none());
151 assert!(AdaptiveCard::parse(r#"{"body": []}"#).is_none());
152 assert!(AdaptiveCard::parse("[1]").is_none());
153}
crates/core/tests/fixtures/card_golden.json +9 −5
@@ -1,11 +1,11 @@
1 1 [
2 2 {
3 "content": "{\"type\": \"AdaptiveCard\", \"body\": [{\"type\": \"TextBlock\", \"text\": \"Deploy finished\"}, {\"type\": \"FactSet\", \"facts\": [{\"title\": \"Env\", \"value\": \"prod\"}, {\"title\": \"Build\", \"value\": \"42\"}]}], \"title\": \"Header\"}",
4 "expected": "Header\nDeploy finished\nEnv\nprod\nBuild\n42"
3 "content": "{\"type\": \"AdaptiveCard\", \"body\": [{\"type\": \"TextBlock\", \"text\": \"Deploy finished\"}, {\"type\": \"FactSet\", \"facts\": [{\"title\": \"Env\", \"value\": \"prod\"}, {\"title\": \"Build\", \"value\": \"42\"}]}]}",
4 "expected": "Deploy finished\nEnv: prod\nBuild: 42"
5 5 },
6 6 {
7 "content": "{\"body\": [{\"type\": \"Container\", \"items\": [{\"type\": \"TextBlock\", \"text\": \"nested\", \"subtitle\": \"sub\"}, {\"type\": \"TextBlock\", \"text\": \" \"}]}, {\"type\": \"ColumnSet\", \"columns\": [{\"items\": [{\"text\": \"c1\"}]}, {\"items\": [{\"text\": \"c2\"}]}]}]}",
8 "expected": "nested\nsub\nc1\nc2"
7 "content": "{\"body\": [{\"type\": \"Container\", \"items\": [{\"type\": \"TextBlock\", \"text\": \"nested\"}, {\"type\": \"TextBlock\", \"text\": \" \"}]}, {\"type\": \"ColumnSet\", \"columns\": [{\"items\": [{\"type\": \"TextBlock\", \"text\": \"c1\"}]}, {\"items\": [{\"type\": \"TextBlock\", \"text\": \"c2\"}]}]}]}",
8 "expected": "nested\nc1\nc2"
9 9 },
10 10 {
11 11 "content": "{\"body\": []}",
@@ -13,7 +13,11 @@
13 13 },
14 14 {
15 15 "content": "{\"text\": 5, \"value\": \"v\", \"title\": \"t\"}",
16 "expected": "t\nv"
16 "expected": null
17 },
18 {
19 "content": "{\"body\": [{\"type\": \"TextBlock\", \"text\": \"[**Space**](https://example.com/s) edited\"}, {\"type\": \"ActionSet\", \"actions\": [{\"type\": \"Action.OpenUrl\", \"title\": \"Open\", \"url\": \"https://example.com\"}]}]}",
20 "expected": "Space edited"
17 21 },
18 22 {
19 23 "content": "not json",
@@ -1,11 +1,11 @@
1[
1[
2 {
2 {
3 "content": "{\"type\": \"AdaptiveCard\", \"body\": [{\"type\": \"TextBlock\", \"text\": \"Deploy finished\"}, {\"type\": \"FactSet\", \"facts\": [{\"title\": \"Env\", \"value\": \"prod\"}, {\"title\": \"Build\", \"value\": \"42\"}]}], \"title\": \"Header\"}",
3 "content": "{\"type\": \"AdaptiveCard\", \"body\": [{\"type\": \"TextBlock\", \"text\": \"Deploy finished\"}, {\"type\": \"FactSet\", \"facts\": [{\"title\": \"Env\", \"value\": \"prod\"}, {\"title\": \"Build\", \"value\": \"42\"}]}]}",
4 "expected": "Header\nDeploy finished\nEnv\nprod\nBuild\n42"
4 "expected": "Deploy finished\nEnv: prod\nBuild: 42"
5 },
5 },
6 {
6 {
7 "content": "{\"body\": [{\"type\": \"Container\", \"items\": [{\"type\": \"TextBlock\", \"text\": \"nested\", \"subtitle\": \"sub\"}, {\"type\": \"TextBlock\", \"text\": \" \"}]}, {\"type\": \"ColumnSet\", \"columns\": [{\"items\": [{\"text\": \"c1\"}]}, {\"items\": [{\"text\": \"c2\"}]}]}]}",
7 "content": "{\"body\": [{\"type\": \"Container\", \"items\": [{\"type\": \"TextBlock\", \"text\": \"nested\"}, {\"type\": \"TextBlock\", \"text\": \" \"}]}, {\"type\": \"ColumnSet\", \"columns\": [{\"items\": [{\"type\": \"TextBlock\", \"text\": \"c1\"}]}, {\"items\": [{\"type\": \"TextBlock\", \"text\": \"c2\"}]}]}]}",
8 "expected": "nested\nsub\nc1\nc2"
8 "expected": "nested\nc1\nc2"
9 },
9 },
10 {
10 {
11 "content": "{\"body\": []}",
11 "content": "{\"body\": []}",
@@ -13,7 +13,11 @@
13 },
13 },
14 {
14 {
15 "content": "{\"text\": 5, \"value\": \"v\", \"title\": \"t\"}",
15 "content": "{\"text\": 5, \"value\": \"v\", \"title\": \"t\"}",
16 "expected": "t\nv"
16 "expected": null
17 },
18 {
19 "content": "{\"body\": [{\"type\": \"TextBlock\", \"text\": \"[**Space**](https://example.com/s) edited\"}, {\"type\": \"ActionSet\", \"actions\": [{\"type\": \"Action.OpenUrl\", \"title\": \"Open\", \"url\": \"https://example.com\"}]}]}",
20 "expected": "Space edited"
17 },
21 },
18 {
22 {
19 "content": "not json",
23 "content": "not json",
crates/core/tests/spans.rs +12 −21
@@ -341,19 +341,18 @@ fn whitespace_collapses() {
341 341 }
342 342
343 343 #[test]
344 fn card_text_follows_python_order() {
344 fn card_text_lists_texts_and_facts_in_document_order() {
345 345 let card = json!({
346 346 "type": "AdaptiveCard",
347 347 "body": [
348 348 {"type": "TextBlock", "text": "Deploy finished"},
349 349 {"type": "FactSet", "facts": [{"title": "Env", "value": "prod"}]},
350 350 {"type": "TextBlock", "text": " "}
351 ],
352 "title": "Header"
351 ]
353 352 });
354 353 assert_eq!(
355 354 card_content_text(&card.to_string()).unwrap(),
356 "Header\nDeploy finished\nEnv\nprod"
355 "Deploy finished\nEnv: prod"
357 356 );
358 357 }
359 358
@@ -375,25 +374,17 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
375 374 }
376 375
377 376 #[test]
378 fn message_spans_append_card_text_only_for_cards() {
379 let attachments = r#"[
380 {"content_type":"application/vnd.microsoft.card.adaptive","name":null,"url":null,"text":"Line one\nLine two"},
381 {"content_type":"reference","name":"a.pdf","url":"https://files.example.test/a.pdf","text":"[attachment: a.pdf]"}
382 ]"#;
383 assert_eq!(
384 message_spans(&record_with("<p>body</p>", attachments)),
385 vec![
386 text("body"),
387 Span::LineBreak,
388 text("Line one"),
389 Span::LineBreak,
390 text("Line two")
391 ]
392 );
377 fn message_spans_leave_cards_to_the_card_renderer() {
378 let card = json!({"body": [{"type": "TextBlock", "text": "Line one"}]}).to_string();
379 let attachments = json!([
380 {"content_type": "application/vnd.microsoft.card.adaptive", "name": null, "url": null, "text": "Line one", "content": card}
381 ])
382 .to_string();
393 383 assert_eq!(
394 message_spans(&record_with("", attachments)),
395 vec![text("Line one"), Span::LineBreak, text("Line two")]
384 message_spans(&record_with("<p>body</p>", &attachments)),
385 vec![text("body")]
396 386 );
387 assert!(message_spans(&record_with("", &attachments)).is_empty());
397 388 }
398 389
399 390 #[test]
@@ -341,19 +341,18 @@ fn whitespace_collapses() {
341}
341}
342
342
343#[test]
343#[test]
344fn card_text_follows_python_order() {
344fn card_text_lists_texts_and_facts_in_document_order() {
345 let card = json!({
345 let card = json!({
346 "type": "AdaptiveCard",
346 "type": "AdaptiveCard",
347 "body": [
347 "body": [
348 {"type": "TextBlock", "text": "Deploy finished"},
348 {"type": "TextBlock", "text": "Deploy finished"},
349 {"type": "FactSet", "facts": [{"title": "Env", "value": "prod"}]},
349 {"type": "FactSet", "facts": [{"title": "Env", "value": "prod"}]},
350 {"type": "TextBlock", "text": " "}
350 {"type": "TextBlock", "text": " "}
351 ],
351 ]
352 "title": "Header"
353 });
352 });
354 assert_eq!(
353 assert_eq!(
355 card_content_text(&card.to_string()).unwrap(),
354 card_content_text(&card.to_string()).unwrap(),
356 "Header\nDeploy finished\nEnv\nprod"
355 "Deploy finished\nEnv: prod"
357 );
356 );
358}
357}
359
358
@@ -375,25 +374,17 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
375}
374}
376
375
377#[test]
376#[test]
378fn message_spans_append_card_text_only_for_cards() {
377fn message_spans_leave_cards_to_the_card_renderer() {
379 let attachments = r#"[
378 let card = json!({"body": [{"type": "TextBlock", "text": "Line one"}]}).to_string();
380 {"content_type":"application/vnd.microsoft.card.adaptive","name":null,"url":null,"text":"Line one\nLine two"},
379 let attachments = json!([
381 {"content_type":"reference","name":"a.pdf","url":"https://files.example.test/a.pdf","text":"[attachment: a.pdf]"}
380 {"content_type": "application/vnd.microsoft.card.adaptive", "name": null, "url": null, "text": "Line one", "content": card}
382 ]"#;
381 ])
383 assert_eq!(
382 .to_string();
384 message_spans(&record_with("<p>body</p>", attachments)),
385 vec![
386 text("body"),
387 Span::LineBreak,
388 text("Line one"),
389 Span::LineBreak,
390 text("Line two")
391 ]
392 );
393 assert_eq!(
383 assert_eq!(
394 message_spans(&record_with("", attachments)),
384 message_spans(&record_with("<p>body</p>", &attachments)),
395 vec![text("Line one"), Span::LineBreak, text("Line two")]
385 vec![text("body")]
396 );
386 );
387 assert!(message_spans(&record_with("", &attachments)).is_empty());
397}
388}
398
389
399#[test]
390#[test]
crates/graph/src/models.rs +17 −1
@@ -156,12 +156,28 @@ impl Chat {
156 156 })
157 157 .collect();
158 158 if names.is_empty() {
159 "(only you)".to_owned()
159 self.preview_sender_name(my_user_id)
160 .unwrap_or("(only you)")
161 .to_owned()
160 162 } else {
161 163 names.join(", ")
162 164 }
163 165 }
164 166
167 fn preview_sender_name(&self, my_user_id: &str) -> Option<&str> {
168 let sender = self.last_message_preview.as_ref()?.from.as_ref()?;
169 let application = sender
170 .application
171 .as_ref()
172 .and_then(|identity| identity.display_name.as_deref());
173 let other_user = sender
174 .user
175 .as_ref()
176 .filter(|identity| identity.id.as_deref() != Some(my_user_id))
177 .and_then(|identity| identity.display_name.as_deref());
178 application.or(other_user).filter(|name| !name.is_empty())
179 }
180
165 181 pub fn last_message_time(&self) -> Option<DateTime<Utc>> {
166 182 self.last_message_preview
167 183 .as_ref()
@@ -156,12 +156,28 @@ impl Chat {
156 })
156 })
157 .collect();
157 .collect();
158 if names.is_empty() {
158 if names.is_empty() {
159 "(only you)".to_owned()
159 self.preview_sender_name(my_user_id)
160 .unwrap_or("(only you)")
161 .to_owned()
160 } else {
162 } else {
161 names.join(", ")
163 names.join(", ")
162 }
164 }
163 }
165 }
164
166
167 fn preview_sender_name(&self, my_user_id: &str) -> Option<&str> {
168 let sender = self.last_message_preview.as_ref()?.from.as_ref()?;
169 let application = sender
170 .application
171 .as_ref()
172 .and_then(|identity| identity.display_name.as_deref());
173 let other_user = sender
174 .user
175 .as_ref()
176 .filter(|identity| identity.id.as_deref() != Some(my_user_id))
177 .and_then(|identity| identity.display_name.as_deref());
178 application.or(other_user).filter(|name| !name.is_empty())
179 }
180
165 pub fn last_message_time(&self) -> Option<DateTime<Utc>> {
181 pub fn last_message_time(&self) -> Option<DateTime<Utc>> {
166 self.last_message_preview
182 self.last_message_preview
167 .as_ref()
183 .as_ref()
crates/graph/tests/models.rs +28 −0
@@ -35,6 +35,34 @@ fn chat_titles_follow_topic_then_other_members() {
35 35 );
36 36 }
37 37
38 fn solo_chat(sender: Value) -> Chat {
39 serde_json::from_value(serde_json::json!({
40 "id": "19:solo@unq.gbl.spaces",
41 "chatType": "oneOnOne",
42 "members": [{"userId": "user-me", "displayName": "Test Me"}],
43 "lastMessagePreview": {"id": "1", "from": sender}
44 }))
45 .unwrap()
46 }
47
48 #[test]
49 fn chat_with_only_me_is_named_after_the_bot_or_user_of_the_last_message() {
50 let bot =
51 solo_chat(serde_json::json!({"application": {"id": "app-1", "displayName": "Sample Bot"}}));
52 assert_eq!(bot.title("user-me"), "Sample Bot");
53 let other =
54 solo_chat(serde_json::json!({"user": {"id": "user-ada", "displayName": "Ada Example"}}));
55 assert_eq!(other.title("user-me"), "Ada Example");
56 }
57
58 #[test]
59 fn chat_with_only_me_stays_a_note_to_self_without_another_sender() {
60 let mine = solo_chat(serde_json::json!({"user": {"id": "user-me", "displayName": "Test Me"}}));
61 assert_eq!(mine.title("user-me"), "(only you)");
62 let nameless = solo_chat(serde_json::json!({"application": {"id": "app-1"}}));
63 assert_eq!(nameless.title("user-me"), "(only you)");
64 }
65
38 66 #[test]
39 67 fn chat_last_message_time_comes_from_preview() {
40 68 let chats: Vec<Chat> = items("chats.json");
@@ -35,6 +35,34 @@ fn chat_titles_follow_topic_then_other_members() {
35 );
35 );
36}
36}
37
37
38fn solo_chat(sender: Value) -> Chat {
39 serde_json::from_value(serde_json::json!({
40 "id": "19:solo@unq.gbl.spaces",
41 "chatType": "oneOnOne",
42 "members": [{"userId": "user-me", "displayName": "Test Me"}],
43 "lastMessagePreview": {"id": "1", "from": sender}
44 }))
45 .unwrap()
46}
47
48#[test]
49fn chat_with_only_me_is_named_after_the_bot_or_user_of_the_last_message() {
50 let bot =
51 solo_chat(serde_json::json!({"application": {"id": "app-1", "displayName": "Sample Bot"}}));
52 assert_eq!(bot.title("user-me"), "Sample Bot");
53 let other =
54 solo_chat(serde_json::json!({"user": {"id": "user-ada", "displayName": "Ada Example"}}));
55 assert_eq!(other.title("user-me"), "Ada Example");
56}
57
58#[test]
59fn chat_with_only_me_stays_a_note_to_self_without_another_sender() {
60 let mine = solo_chat(serde_json::json!({"user": {"id": "user-me", "displayName": "Test Me"}}));
61 assert_eq!(mine.title("user-me"), "(only you)");
62 let nameless = solo_chat(serde_json::json!({"application": {"id": "app-1"}}));
63 assert_eq!(nameless.title("user-me"), "(only you)");
64}
65
38#[test]
66#[test]
39fn chat_last_message_time_comes_from_preview() {
67fn chat_last_message_time_comes_from_preview() {
40 let chats: Vec<Chat> = items("chats.json");
68 let chats: Vec<Chat> = items("chats.json");
crates/store/src/chats.rs +4 −1
@@ -21,7 +21,10 @@ impl Store {
21 21 last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted)
22 22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
23 23 ON CONFLICT (id) DO UPDATE SET
24 kind = excluded.kind, title = excluded.title, member_summary = excluded.member_summary,
24 kind = excluded.kind,
25 title = CASE WHEN excluded.title = '(only you)' AND chats.title NOT IN ('', '(only you)')
26 THEN chats.title ELSE excluded.title END,
27 member_summary = excluded.member_summary,
25 28 last_message_at = excluded.last_message_at,
26 29 last_read_at = COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at),
27 30 unread = excluded.unread AND (
@@ -21,7 +21,10 @@ impl Store {
21 last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted)
21 last_message_preview, last_message_sender_id, last_message_sender_name, last_message_deleted)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
23 ON CONFLICT (id) DO UPDATE SET
23 ON CONFLICT (id) DO UPDATE SET
24 kind = excluded.kind, title = excluded.title, member_summary = excluded.member_summary,
24 kind = excluded.kind,
25 title = CASE WHEN excluded.title = '(only you)' AND chats.title NOT IN ('', '(only you)')
26 THEN chats.title ELSE excluded.title END,
27 member_summary = excluded.member_summary,
25 last_message_at = excluded.last_message_at,
28 last_message_at = excluded.last_message_at,
26 last_read_at = COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at),
29 last_read_at = COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at),
27 unread = excluded.unread AND (
30 unread = excluded.unread AND (
crates/store/tests/store.rs +19 −0
@@ -78,6 +78,25 @@ fn chat_upsert_replaces_fields_and_members() {
78 78 assert_eq!(store.recent_chats(10).unwrap(), vec![changed]);
79 79 }
80 80
81 #[test]
82 fn chat_upsert_keeps_a_real_title_over_the_only_you_fallback() {
83 let store = Store::open_in_memory().unwrap();
84 store
85 .upsert_chats(&[chat("chat-1", "Sample Bot", Some(at(1)))])
86 .unwrap();
87 store
88 .upsert_chats(&[chat("chat-1", "(only you)", Some(at(2)))])
89 .unwrap();
90 assert_eq!(store.chat("chat-1").unwrap().unwrap().title, "Sample Bot");
91 store
92 .upsert_chats(&[chat("chat-2", "(only you)", Some(at(2)))])
93 .unwrap();
94 store
95 .upsert_chats(&[chat("chat-2", "Sample Bot", Some(at(3)))])
96 .unwrap();
97 assert_eq!(store.chat("chat-2").unwrap().unwrap().title, "Sample Bot");
98 }
99
81 100 #[test]
82 101 fn recent_chats_are_newest_first_with_unknown_last() {
83 102 let store = Store::open_in_memory().unwrap();
@@ -78,6 +78,25 @@ fn chat_upsert_replaces_fields_and_members() {
78 assert_eq!(store.recent_chats(10).unwrap(), vec![changed]);
78 assert_eq!(store.recent_chats(10).unwrap(), vec![changed]);
79}
79}
80
80
81#[test]
82fn chat_upsert_keeps_a_real_title_over_the_only_you_fallback() {
83 let store = Store::open_in_memory().unwrap();
84 store
85 .upsert_chats(&[chat("chat-1", "Sample Bot", Some(at(1)))])
86 .unwrap();
87 store
88 .upsert_chats(&[chat("chat-1", "(only you)", Some(at(2)))])
89 .unwrap();
90 assert_eq!(store.chat("chat-1").unwrap().unwrap().title, "Sample Bot");
91 store
92 .upsert_chats(&[chat("chat-2", "(only you)", Some(at(2)))])
93 .unwrap();
94 store
95 .upsert_chats(&[chat("chat-2", "Sample Bot", Some(at(3)))])
96 .unwrap();
97 assert_eq!(store.chat("chat-2").unwrap().unwrap().title, "Sample Bot");
98}
99
81#[test]
100#[test]
82fn recent_chats_are_newest_first_with_unknown_last() {
101fn recent_chats_are_newest_first_with_unknown_last() {
83 let store = Store::open_in_memory().unwrap();
102 let store = Store::open_in_memory().unwrap();
vendor/gpui-base/src/text_selection.rs +46 −0
@@ -2824,6 +2824,11 @@ fn paint_text_selection(state: &Entity<WindowSelectionState>, window: &mut Windo
2824 2824 if state.touch.drag.is_some() {
2825 2825 return;
2826 2826 }
2827 if event.pressed_button != Some(MouseButton::Left) {
2828 state.mouse_down_prepared = false;
2829 state.end(cx);
2830 return;
2831 }
2827 2832 state.update_in_window(event.position, window, cx)
2828 2833 });
2829 2834 WindowSelectionState::resolve_content_keys(&state, cx);
@@ -4432,6 +4437,47 @@ mod tests {
4432 4437 assert_eq!(clear_count.get(), 3);
4433 4438 }
4434 4439
4440 #[gpui::test]
4441 fn mouse_move_without_button_ends_a_gesture_whose_mouse_up_was_missed(cx: &mut TestAppContext) {
4442 let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
4443 selection: TextSelectionHandle::new("once", cx),
4444 });
4445 cx.update(|window, cx| {
4446 let _ = window.draw(cx);
4447 });
4448
4449 cx.simulate_mouse_down(
4450 point(px(15.), px(10.)),
4451 MouseButton::Left,
4452 gpui::Modifiers::default(),
4453 );
4454 cx.simulate_mouse_move(
4455 point(px(40.), px(10.)),
4456 Some(MouseButton::Left),
4457 gpui::Modifiers::default(),
4458 );
4459 cx.update(|window, cx| {
4460 let state = WindowSelectionState::ensure(window, cx);
4461 assert!(state.read(cx).is_selecting());
4462 });
4463
4464 cx.simulate_mouse_move(point(px(60.), px(10.)), None, gpui::Modifiers::default());
4465 let selection_after_release = cx.update(|window, cx| {
4466 let state = WindowSelectionState::ensure(window, cx);
4467 assert!(!state.read(cx).is_selecting());
4468 TextSelection::selected_text(window, cx)
4469 });
4470
4471 cx.simulate_mouse_move(point(px(85.), px(10.)), None, gpui::Modifiers::default());
4472 cx.update(|window, cx| {
4473 assert_eq!(
4474 TextSelection::selected_text(window, cx),
4475 selection_after_release
4476 );
4477 });
4478 let _ = view;
4479 }
4480
4435 4481 #[gpui::test]
4436 4482 fn selection_layer_handles_real_double_and_triple_click_events(cx: &mut TestAppContext) {
4437 4483 let (text, layout) = laid_out_runs(&["alpha beta"], cx).pop().unwrap();
@@ -2824,6 +2824,11 @@ fn paint_text_selection(state: &Entity<WindowSelectionState>, window: &mut Windo
2824 if state.touch.drag.is_some() {
2824 if state.touch.drag.is_some() {
2825 return;
2825 return;
2826 }
2826 }
2827 if event.pressed_button != Some(MouseButton::Left) {
2828 state.mouse_down_prepared = false;
2829 state.end(cx);
2830 return;
2831 }
2827 state.update_in_window(event.position, window, cx)
2832 state.update_in_window(event.position, window, cx)
2828 });
2833 });
2829 WindowSelectionState::resolve_content_keys(&state, cx);
2834 WindowSelectionState::resolve_content_keys(&state, cx);
@@ -4432,6 +4437,47 @@ mod tests {
4432 assert_eq!(clear_count.get(), 3);
4437 assert_eq!(clear_count.get(), 3);
4433 }
4438 }
4434
4439
4440 #[gpui::test]
4441 fn mouse_move_without_button_ends_a_gesture_whose_mouse_up_was_missed(cx: &mut TestAppContext) {
4442 let (view, cx) = cx.add_window_view(|_, cx| DoubleSelectionElementView {
4443 selection: TextSelectionHandle::new("once", cx),
4444 });
4445 cx.update(|window, cx| {
4446 let _ = window.draw(cx);
4447 });
4448
4449 cx.simulate_mouse_down(
4450 point(px(15.), px(10.)),
4451 MouseButton::Left,
4452 gpui::Modifiers::default(),
4453 );
4454 cx.simulate_mouse_move(
4455 point(px(40.), px(10.)),
4456 Some(MouseButton::Left),
4457 gpui::Modifiers::default(),
4458 );
4459 cx.update(|window, cx| {
4460 let state = WindowSelectionState::ensure(window, cx);
4461 assert!(state.read(cx).is_selecting());
4462 });
4463
4464 cx.simulate_mouse_move(point(px(60.), px(10.)), None, gpui::Modifiers::default());
4465 let selection_after_release = cx.update(|window, cx| {
4466 let state = WindowSelectionState::ensure(window, cx);
4467 assert!(!state.read(cx).is_selecting());
4468 TextSelection::selected_text(window, cx)
4469 });
4470
4471 cx.simulate_mouse_move(point(px(85.), px(10.)), None, gpui::Modifiers::default());
4472 cx.update(|window, cx| {
4473 assert_eq!(
4474 TextSelection::selected_text(window, cx),
4475 selection_after_release
4476 );
4477 });
4478 let _ = view;
4479 }
4480
4435 #[gpui::test]
4481 #[gpui::test]
4436 fn selection_layer_handles_real_double_and_triple_click_events(cx: &mut TestAppContext) {
4482 fn selection_layer_handles_real_double_and_triple_click_events(cx: &mut TestAppContext) {
4437 let (text, layout) = laid_out_runs(&["alpha beta"], cx).pop().unwrap();
4483 let (text, layout) = laid_out_runs(&["alpha beta"], cx).pop().unwrap();