1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
package main

import "html/template"

// tmpl is the chat page: one page per room, no build step, no framework.
//
// One room per page is what keeps this simple. Each page opens its own SSE
// stream at /room/{id}/events and therefore has its own Last-Event-ID resume
// cursor, so the protocol below never has to name a room: every frame on a
// stream belongs to that stream's single timeline. Multiplexing all rooms onto
// one stream would give N timelines one scalar cursor and force the client to
// route frames — reintroducing exactly the bookkeeping this design removed.
// Switching rooms is a plain navigation, so the browser handles the teardown.
//
// Everything arrives over that stream as one of four operations — prepend,
// append, update, reset — and each one is a single DOM mutation at a position
// the client does not have to work out:
//
//	prepend  older history      log.prepend(fragment)
//	append   new messages       log.append(fragment)
//	update   a message changed  byId.get(id).replaceWith(...)
//	reset    view is invalid    log.replaceChildren()
//
// This works because the server writes history to the response *before* it
// starts forwarding live events, so the two can never interleave: every batch
// is either entirely above what the client holds or entirely below it, and the
// server knows which. Nothing here sorts, compares or scans for a position, so
// rendering a message costs the same whether the log holds ten rows or ten
// thousand.
//
// Rows are keyed by event_id (UNIQUE in hicli's schema, server-assigned, never
// reused), which is also what the SSE resume cursor carries. Edits and
// redactions are not rows: they arrive as fields of the message they affect,
// which is why they need no position and why there is no "remove" operation.
//
// The styling mirrors source-forge's directory listing rather than a typical
// chat UI: the colour tokens (see sharedStyle) are copied verbatim from
// source-forge/page.go so the two apps look like the same site, and each
// message is one tight listing row with a relative timestamp. No bubbles, no
// avatars.
var tmpl = template.Must(template.New("index").Parse(indexTemplate))

// roomsTmpl renders the landing page: the list of joined rooms.
//
// It is a plain page, not a live stream, and that is a deliberate constraint
// rather than a shortcut. Pushing room-list changes would mean the sync handler
// had to do work for every room in the account on every sync; as it stands it
// drops any room nobody has open after a single map lookup (see viewIfOpen).
// The list re-sorts on each load, which is all the freshness a page you glance
// at before clicking through needs.
var roomsTmpl = template.Must(template.New("rooms").Parse(roomsTemplate))

// sharedStyle is the common look for both pages: the colour tokens are copied
// verbatim from source-forge/page.go so the apps read as the same site, and
// both pages render their content as one tight listing with hairline rules.
const sharedStyle = `
  :root {
    --bg: #ffffff;
    --fg: #1a1a1a;
    --muted: #666;
    --link: #0b5fff;
    --border: #e2e2e2;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #1a1a1a;
      --fg: #dddddd;
      --muted: #999;
      --link: #6ea8ff;
      --border: #333;
    }
  }
  * { box-sizing: border-box; }
  html, body { height: 100%; margin: 0; }
  body {
    background: var(--bg); color: var(--fg);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    line-height: 1.5;
    display: flex; flex-direction: column;
  }
  a { color: var(--link); text-decoration: none; }
  a:hover { text-decoration: underline; }

  header {
    padding: 0.5em 1em; border-bottom: 1px solid var(--border);
    background: var(--bg); display: flex; align-items: baseline; gap: 0.6em;
    position: sticky; top: 0; z-index: 1;
  }
  header h1 { font-size: 1.2rem; font-weight: 600; margin: 0; }
  header .who { color: var(--muted); font-size: 0.85em; }
  header .status { margin-left: auto; font-size: 0.85em; color: var(--muted); }
  header .status.live::before { content: "\25cf "; color: #2e7d32; }
  header .status.down::before { content: "\25cf "; color: #c62828; }

  /* The notification toggle is a plain text button: it is a setting, not an
     action, so it should not look like the send button. */
  header .notify {
    font: inherit; font-size: 0.85em;
    background: none; border: 0; padding: 0;
    color: var(--muted); cursor: pointer;
  }
  header .notify:hover:not(:disabled) { text-decoration: underline; }
  header .notify:disabled { cursor: default; opacity: 0.7; }
  header .notify.on { color: var(--link); }
`

// humanAgoJS is the relative-timestamp helper, shared by both pages so a room's
// last activity is phrased exactly like a message's timestamp. Ported from
// source-forge's humanAgo (serve.go).
const humanAgoJS = `
function humanAgo(ms) {
  const secs = Math.floor((Date.now() - ms) / 1000);
  if (secs < 60) return "just now";
  const units = [
    ["year",   365 * 24 * 3600],
    ["month",   30 * 24 * 3600],
    ["week",     7 * 24 * 3600],
    ["day",          24 * 3600],
    ["hour",              3600],
    ["minute",              60],
  ];
  for (const [name, unitSecs] of units) {
    const n = Math.floor(secs / unitSecs);
    if (n >= 1) return n + " " + name + (n === 1 ? "" : "s") + " ago";
  }
  return "just now";
}

// fmtAbs is the absolute timestamp shown on hover.
function fmtAbs(ms) {
  const d = new Date(ms);
  const pad = (n) => String(n).padStart(2, "0");
  return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()) +
         " " + pad(d.getHours()) + ":" + pad(d.getMinutes());
}
`

// notifyJS is the desktop-notification client, included by both pages.
//
// It deliberately contains no policy: which messages deserve a notification is
// decided by the account's Matrix push rules, evaluated server-side by hicli
// (see the notification type in serve.go). This code only renders what arrives.
//
// Nor does it coordinate with other tabs. Every tab opens /notifications, but
// the server sends each notification to exactly one of them, so there is no
// deduplication to do here — no SharedWorker, no BroadcastChannel, no lock.
// The one thing a tab decides for itself is whether the notification is
// pointless because the user is already looking at that very room.
//
// Permission is requested on a click rather than on load: browsers increasingly
// refuse requestPermission() outside a user gesture (Firefox since 72), and an
// unprompted permission dialog on page load is obnoxious anyway.
const notifyJS = `
const notifyToggle = document.getElementById("notify-toggle");

// Persisted so the choice survives navigation between rooms, which is a full
// page load in this app.
const NOTIFY_KEY = "webchat-notify";
function notifyEnabled() {
  return localStorage.getItem(NOTIFY_KEY) === "on" && Notification.permission === "granted";
}

function renderNotifyToggle() {
  if (!notifyToggle) return;
  if (!("Notification" in window)) {
    notifyToggle.textContent = "notifications unsupported";
    notifyToggle.disabled = true;
    return;
  }
  if (Notification.permission === "denied") {
    notifyToggle.textContent = "notifications blocked";
    notifyToggle.disabled = true;
    return;
  }
  notifyToggle.textContent = notifyEnabled() ? "notifications on" : "notifications off";
  notifyToggle.classList.toggle("on", notifyEnabled());
}

if (notifyToggle) {
  notifyToggle.addEventListener("click", async () => {
    if (notifyEnabled()) {
      localStorage.setItem(NOTIFY_KEY, "off");
      renderNotifyToggle();
      return;
    }
    // Asking again when already granted is a no-op that resolves immediately,
    // so this needs no permission check of its own.
    const permission = await Notification.requestPermission();
    localStorage.setItem(NOTIFY_KEY, permission === "granted" ? "on" : "off");
    renderNotifyToggle();
    if (permission === "granted") connectNotifications();
  });
  renderNotifyToggle();
}

// currentRoomID is set by the chat page; the room list leaves it null. It is
// used only to decide whether a click needs to navigate.
var currentRoomID = window.currentRoomID || null;

let notifySource = null;
function connectNotifications() {
  if (notifySource || !("Notification" in window)) return;
  // The stream is only opened once notifications are actually wanted. Opening
  // it regardless would make every idle tab a candidate leader on the server
  // and let notifications be routed to a tab that will never show them.
  if (!notifyEnabled()) return;

  notifySource = new EventSource("/notifications");
  notifySource.addEventListener("notify", (e) => {
    if (!notifyEnabled()) return;
    const n = JSON.parse(e.data);
    // No "am I showing this room?" check here on purpose: this tab is usually
    // not the one displaying it. The server suppresses notifications for rooms
    // some tab reports as visible, which is the only place that knows.
    const title = n.highlight ? n.room_name + " — " + n.display : n.room_name;
    const notification = new Notification(title, {
      body: n.display + ": " + n.body,
      // Collapses a burst from one room into a single notification rather than
      // stacking one per message.
      tag: n.room_id,
      silent: !n.sound,
    });
    notification.addEventListener("click", () => {
      window.focus();
      if (n.room_id !== currentRoomID) window.location.href = n.path;
      notification.close();
    });
  });
}

connectNotifications();
`

// roomsTemplate is the room list.
//
// Rooms arrive already sorted newest-activity-first (hicli's GetBySortTS), so
// the page does no ordering of its own. Timestamps are rendered client-side
// from the epoch millis, for the same reason the chat page does it: the server
// cannot know the viewer's timezone, and "3 hours ago" has to stay honest on a
// page left open.
const roomsTemplate = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>webchat · rooms</title>
<style>` + sharedStyle + `
  #rooms { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
  #rooms li {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 0 0.75em;
    border-bottom: 1px solid var(--border);
  }
  /* The link fills the row, so the whole row is the click target. */
  #rooms li a {
    grid-column: 1 / -1;
    display: grid;
    grid-template-columns: subgrid;
    padding: 0.3em 1em;
    color: var(--fg);
  }
  #rooms li a:hover { background: var(--border); text-decoration: none; }
  #rooms .name {
    grid-column: 1;
    font-weight: 600;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  #rooms .ago {
    grid-column: 2;
    color: var(--muted); font-size: 0.85em; white-space: nowrap;
  }
  #empty { padding: 1em; color: var(--muted); }
</style>
</head>
<body>
<header>
  <h1>webchat</h1>
  <span class="who">{{.UserID}}</span>
  <button type="button" class="notify" id="notify-toggle" style="margin-left:auto"></button>
</header>

{{if .Rooms}}
<ul id="rooms">
  {{range .Rooms}}
  <li>
    <a href="{{.Path}}">
      <span class="name" title="{{.ID}}">{{.Name}}</span>
      <span class="ago" data-ts="{{.Activity}}"></span>
    </a>
  </li>
  {{end}}
</ul>
{{else}}
<div id="empty">No rooms yet — the initial sync may still be running. Reload in a moment.</div>
{{end}}

<script>` + humanAgoJS + `
for (const el of document.querySelectorAll("#rooms .ago")) {
  const ts = Number(el.dataset.ts);
  if (!ts) continue;
  el.textContent = humanAgo(ts);
  el.title = fmtAbs(ts);
}
` + notifyJS + `
</script>
</body>
</html>
`

const indexTemplate = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>webchat{{if .RoomName}} · {{.RoomName}}{{end}}</title>
<style>` + sharedStyle + `
  /* The back link sits before the title, so the room name stays the heading. */
  header .back { font-size: 0.9em; }

  /* The message log, styled after source-forge's ul.listing: hairline
     separators and a tight vertical rhythm.

     Rows are a grid rather than inline text with a floated timestamp: with a
     proportional font, nicks can only be aligned by giving them their own
     column, and a float cannot do that. Long messages then wrap inside their
     own column instead of running under the nick. */
  /* The scroller holds both the message log and the pending-upload list, so
     that pending rows sit below every real message without having to be
     ordered among them.

     Staying pinned to the bottom is done with scroll snapping rather than with
     JavaScript. #latest is a zero-height marker below the messages carrying
     scroll-snap-align: end, so "the bottom" is a snap position;
     the spec then requires the container to re-snap to it whenever content is
     added, moved or *resized* (css-scroll-snap §4.1.3), which is exactly the
     set of events that used to need handling by hand — a new message, an image
     finishing decoding, the composer growing under the scroller. Snapping is
     "proximity" rather than "mandatory" so that it stops applying once the
     user has scrolled away to read something; mandatory would drag them back.

     align-content: end keeps a room with less content than viewport height
     against the bottom, so a nearly-empty room does not render floating at the
     top with the composer stranded below it.

     Snapping only engages while the scroller is exactly at the snap position,
     so a viewport left a pixel short simply will not follow new messages. That
     is not papered over here; it is caught by #sentinel below, which reports
     whether the bottom is actually visible after the fact and offers the way
     back. The two together are what make the imprecision harmless.

     NEVER set scroll-behavior: smooth on this element. Re-snapping honours it
     (css-scroll-snap §4.1.3), and an animated scroll adjustment would still be
     in flight when the intersection observer samples the result — turning the
     check below into a race that reports a spurious "not at the bottom". */
  #scroller {
    flex: 1; overflow-y: auto;
    scroll-snap-type: y proximity;
    align-content: end;
  }
  /* Zero-height, so it takes no space and never shows a gap under the last
     message. */
  #latest { scroll-snap-align: end; height: 0; }
  /* The observed element, deliberately separate from the snap target and last
     in the scroller: it is visible exactly when the bottom edge of the newest
     message is, which is the "is it entirely in view" question the banner
     asks. Asking it with threshold 1.0 on the message itself would instead
     wedge the banner open forever on any message taller than the viewport.

     1px rather than 0: a zero-area target is well defined (an edge-adjacent
     intersection counts, with ratio 1), but a real box removes any dependence
     on that corner of the spec. */
  #sentinel { height: 1px; }

  /* The unread-message banner. Sits directly above the composer, where the eye
     already is when typing, and is styled as a quieter variant of a message
     row rather than as a notification: it is the message, just not in view
     yet. The whole bar is the button, so the click target is the full width.

     It appears only when the bottom is genuinely off screen, which means it
     doubles as the recovery path when snapping fails to follow a new message
     — the case that would otherwise silently lose the conversation. */
  #newest {
    display: flex; align-items: baseline; gap: 0.6em;
    width: 100%; text-align: left;
    font: inherit; font-size: 0.9rem;
    padding: 0.35em 1em; cursor: pointer;
    color: var(--fg); background: var(--border);
    border: 0; border-top: 1px solid var(--border);
  }
  #newest:hover { filter: brightness(1.08); }
  #newest .who { font-weight: 600; white-space: nowrap; }
  #newest .body {
    flex: 1; min-width: 0;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    color: var(--muted);
  }
  #newest .arrow { color: var(--link); font-weight: 600; }
  #log {
    list-style: none; padding: 0; margin: 0;
    font-size: 0.95rem;
  }
  #log li {
    display: grid;
    /* The last column is a fixed width, not "auto": the ticker below rewrites
       every timestamp once a minute, and "just now" -> "13 minutes ago" in an
       auto column would resize the body column and rewrap every message in the
       log under the reader. */
    grid-template-columns: 9em 1fr 7.5em;
    gap: 0 0.75em;
    padding: 0.15em 1em;
    border-bottom: 1px solid var(--border);
  }
  #log li .who {
    grid-column: 1;
    font-weight: 600; color: var(--fg);
    text-align: right;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  /* Own messages are distinguished only by sender colour — no bubble. */
  #log li.own .who { color: var(--link); }
  #log li .body {
    grid-column: 2;
    min-width: 0;                /* lets the column actually shrink */
    white-space: pre-wrap;
    overflow-wrap: anywhere;
  }
  #log li.error .body { color: var(--muted); font-style: italic; }
  #log li .ago {
    grid-column: 3;
    color: var(--muted); font-size: 0.85em;
    white-space: nowrap;
  }

  /* A redacted message keeps its text (we still have it cached) behind a
     marker, rather than vanishing. */
  #log li .redacted-marker {
    color: var(--muted); font-style: italic;
    margin-right: 0.4em;
  }
  #log li.redacted .body { color: var(--muted); }

  /* Edits are sub-rows under the message they revise: the full new text with
     the changed words marked, so the message reads as a whole rather than as a
     diff fragment. */
  #log li .edit {
    display: block;
    margin-top: 0.15em;
    padding-left: 1em;
    color: var(--muted);
    text-indent: -1em;   /* hanging indent, so wraps line up under the text */
  }
  #log li .edit::before { content: "\21b3\a0"; }
  #log li .edit del {
    text-decoration: line-through;
    opacity: 0.7;
  }
  #log li .edit ins {
    text-decoration: none;
    color: var(--fg);
    font-weight: 600;
  }
  #log li .edit .edit-ago { font-size: 0.85em; margin-left: 0.4em; }
  /* On narrow screens a 9em nick column eats the message, so stack instead. */
  @media (max-width: 40em) {
    #log li { grid-template-columns: 1fr 7.5em; }
    #log li .who { grid-column: 1; text-align: left; }
    #log li .ago { grid-column: 2; }
    #log li .body { grid-column: 1 / -1; }
  }

  /* Attachments. Images are capped so a screenshot does not fill the viewport;
     click opens the original.

     The height cap is expressed as a *width* limit derived from the aspect
     ratio (--ar, set inline from the event's own w/h) rather than as
     max-height. Both would look identical once loaded, but only this reserves
     the right amount of space beforehand: the browser sizes the placeholder
     from the width and the aspect ratio, so a max-height that turned out to be
     the binding constraint would leave the row too tall and shrink it on
     decode, shifting everything below. Capping width alone means the computed
     height is already <= 24em and nothing moves when the pixels arrive. */
  #log li .body img {
    display: block; margin: 0.25em 0;
    max-width: min(100%, 40em, calc(24em * var(--ar, 1)));
    width: auto; height: auto;
    border: 1px solid var(--border); border-radius: 4px;
    background: var(--border);   /* placeholder tint while loading */
  }
  #log li .body video {
    display: block; margin: 0.25em 0;
    max-width: min(100%, 40em, calc(24em * var(--ar, 1)));
    height: auto;
  }
  #log li .body audio {
    display: block; margin: 0.25em 0;
    max-width: min(100%, 40em);
  }
  #log li .body .file {
    display: inline-block; margin: 0.25em 0;
    padding: 0.2em 0.5em;
    border: 1px solid var(--border); border-radius: 4px;
  }
  #log li .body .file::before { content: "\1f4c4\a0"; }
  #log li .body .size { color: var(--muted); font-size: 0.85em; }
  /* Pending uploads live in their own list below the log, so they are always
     visually last without needing to be positioned among real messages. */
  #pending {
    list-style: none; padding: 0; margin: 0;
    font-size: 0.95rem;
  }
  #pending li {
    display: grid;
    grid-template-columns: 9em 1fr 7.5em;
    gap: 0 0.75em;
    padding: 0.15em 1em;
    border-bottom: 1px solid var(--border);
    opacity: 0.6;
  }
  #pending li .who {
    grid-column: 1; font-weight: 600; text-align: right;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  #pending li .body { grid-column: 2; font-style: italic; color: var(--muted); }
  #pending li .ago { grid-column: 3; color: var(--muted); font-size: 0.85em; }
  #pending li.error .body { color: #c62828; }
  @media (max-width: 40em) {
    #pending li { grid-template-columns: 1fr 7.5em; }
    #pending li .who { grid-column: 1; text-align: left; }
    #pending li .ago { grid-column: 2; }
    #pending li .body { grid-column: 1 / -1; }
  }

  #typing {
    padding: 0 1em; font-size: 0.85em; color: var(--muted); min-height: 1.4em;
  }
  form {
    display: flex; gap: 0.5em; padding: 0.6em 1em;
    border-top: 1px solid var(--border);
  }
  #text {
    flex: 1; padding: 0.4em 0.5em; color: var(--fg); background: var(--bg);
    border: 1px solid var(--border); border-radius: 4px;
    font: inherit; font-size: 0.95rem; resize: none; max-height: 8em;
  }
  #send {
    font: inherit; font-size: 0.95rem; padding: 0.4em 1em; cursor: pointer;
    color: var(--bg); background: var(--link);
    border: 0; border-radius: 4px;
  }
  #send:hover { opacity: 0.9; }
  #send:disabled { opacity: 0.5; cursor: default; }
</style>
</head>
<body>
<header>
  <a class="back" href="/" title="all rooms">←</a>
  <h1>{{if .RoomName}}{{.RoomName}}{{else}}webchat{{end}}</h1>
  <span class="who" title="{{.RoomID}}">{{.UserID}}</span>
  <span class="status" id="status">connecting…</span>
  <button type="button" class="notify" id="notify-toggle"></button>
</header>

<div id="scroller">
  <ul id="log"></ul>
  <ul id="pending"></ul>
  <div id="latest"></div>
  <div id="sentinel"></div>
</div>
<div id="typing"></div>

<button type="button" id="newest" hidden>
  <span class="who"></span>
  <span class="body"></span>
  <span class="arrow">↓</span>
</button>

<form id="composer">
  <textarea id="text" rows="1" placeholder="Message…" autocomplete="off" autofocus></textarea>
  <button type="submit" id="send">Send</button>
</form>

<script>` + humanAgoJS + `
// Every endpoint this page talks to is scoped to one room, so all of them hang
// off this prefix. Rendering it server-side keeps the frontend ignorant of the
// routing scheme — and of how a room ID has to be escaped in a URL.
const base = "{{.Base}}";

// Read by notifyJS, to suppress notifications for the room already on screen.
window.currentRoomID = "{{.RoomID}}";

// The backlog the server rendered into this page, oldest first, plus the
// timeline boundaries it covers. Rendering it here rather than streaming it is
// what keeps the scroll position sane — see handleIndex in serve.go.
const backlogMsgs   = {{.Backlog}};
const backlogNewest = "{{.Newest}}";
const backlogOldest = "{{.Oldest}}";
const backlogHave   = {{.Have}};

const scroller = document.getElementById("scroller");
const sentinel = document.getElementById("sentinel");
const newestEl = document.getElementById("newest");
const log      = document.getElementById("log");
const pending  = document.getElementById("pending");
const statusEl = document.getElementById("status");
const typingEl = document.getElementById("typing");
const form     = document.getElementById("composer");
const text     = document.getElementById("text");
const sendBtn  = document.getElementById("send");

// event_id -> {li, ago, ts}. event_id is UNIQUE in hicli's schema, so this
// doubles as the dedup key. The .ago node is cached here rather than re-queried,
// because the ticker below touches every row once a minute and a querySelector
// per row does not scale to a large backlog.
const rendered = new Map();

function humanSize(bytes) {
  if (!bytes) return "";
  const units = ["B", "kiB", "MiB", "GiB"];
  let n = bytes, i = 0;
  while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; }
  return (i === 0 ? n : n.toFixed(1)) + " " + units[i];
}

// renderMedia appends the element for an attachment, picking by msgtype.
//
// Note on laziness: loading="lazy" only applies to <img> (and <iframe>). The
// equivalent for audio/video is preload="none", which fetches nothing at all
// until the user hits play — strictly better than lazy for our purposes.
function renderMedia(body, msg) {
  const m = msg.media;
  switch (msg.msgtype) {
    case "m.image": {
      const img = document.createElement("img");
      img.src = m.url;
      img.alt = m.filename || msg.body || "image";
      img.loading = "lazy";
      img.decoding = "async";
      // Intrinsic dimensions are what make lazy loading behave: without them
      // every unloaded image is zero-height and the scroll position jumps as
      // images arrive. --ar additionally lets the CSS express the height cap as
      // a width limit, so the space reserved before the image loads is the
      // space it ends up taking — see the img rule in the stylesheet.
      if (m.w) img.width = m.w;
      if (m.h) img.height = m.h;
      if (m.w && m.h) img.style.setProperty("--ar", m.w + " / " + m.h);
      const link = document.createElement("a");
      link.href = m.url;
      link.target = "_blank";
      link.rel = "noreferrer";
      link.appendChild(img);
      body.appendChild(link);
      return;
    }
    case "m.video": {
      const v = document.createElement("video");
      v.src = m.url;
      v.controls = true;
      v.preload = "none";
      if (m.w) v.width = m.w;
      if (m.h) v.height = m.h;
      if (m.w && m.h) v.style.setProperty("--ar", m.w + " / " + m.h);
      body.appendChild(v);
      return;
    }
    case "m.audio": {
      const a = document.createElement("audio");
      a.src = m.url;
      a.controls = true;
      a.preload = "none";
      body.appendChild(a);
      return;
    }
    default: {
      const link = document.createElement("a");
      link.className = "file";
      link.href = m.url;
      link.download = m.filename || "";
      link.textContent = m.filename || msg.body || "file";
      body.appendChild(link);
      if (m.size) {
        const size = document.createElement("span");
        size.className = "size";
        size.textContent = " " + humanSize(m.size);
        body.appendChild(size);
      }
    }
  }
}

// diffWords produces a word-level diff between two strings, as a list of
// {type, text} where type is "same", "del" or "ins".
//
// Standard LCS over whitespace-separated tokens. Messages are short, so the
// O(n*m) table is fine; it is capped anyway to keep a pathological paste from
// freezing the tab.
function diffWords(before, after) {
  // Whitespace is kept as its own token, so the original spacing (including
  // newlines) survives the round trip and reassembling the "same" and "ins"
  // parts reproduces the new text exactly.
  const a = before.split(/(\s+)/).filter((s) => s !== "");
  const b = after.split(/(\s+)/).filter((s) => s !== "");
  const MAX = 400;
  if (a.length > MAX || b.length > MAX) {
    // Too long to diff meaningfully; just show the replacement.
    return [{ type: "ins", text: after }];
  }

  // lcs[i][j] = length of the longest common subsequence of a[i:] and b[j:].
  const lcs = Array.from({ length: a.length + 1 }, () => new Uint16Array(b.length + 1));
  for (let i = a.length - 1; i >= 0; i--) {
    for (let j = b.length - 1; j >= 0; j--) {
      lcs[i][j] = a[i] === b[j]
        ? lcs[i + 1][j + 1] + 1
        : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
    }
  }

  const out = [];
  const push = (type, tok) => {
    const last = out[out.length - 1];
    // Merge runs so we emit one element per changed phrase, not per word. The
    // tokens already carry their own whitespace, so they concatenate directly.
    if (last && last.type === type) last.text += tok;
    else out.push({ type: type, text: tok });
  };
  let i = 0, j = 0;
  while (i < a.length && j < b.length) {
    if (a[i] === b[j])                       { push("same", a[i]); i++; j++; }
    else if (lcs[i + 1][j] >= lcs[i][j + 1]) { push("del",  a[i]); i++; }
    else                                     { push("ins",  b[j]); j++; }
  }
  while (i < a.length) { push("del", a[i]); i++; }
  while (j < b.length) { push("ins", b[j]); j++; }
  return out;
}

// renderEdit builds one edit sub-row: the whole message as it now reads, with
// the words that changed since the previous version marked up.
function renderEdit(prevBody, e) {
  const row = document.createElement("span");
  row.className = "edit";
  for (const part of diffWords(prevBody, e.body)) {
    let node;
    if (part.type === "same")     node = document.createTextNode(part.text);
    else if (part.type === "del") { node = document.createElement("del"); node.textContent = part.text; }
    else                          { node = document.createElement("ins"); node.textContent = part.text; }
    row.appendChild(node);
  }
  const ago = document.createElement("span");
  ago.className = "edit-ago";
  ago.textContent = "edited " + humanAgo(e.timestamp);
  ago.title = fmtAbs(e.timestamp);
  row.appendChild(ago);
  return row;
}

// mk builds the <li> for one message. It is the only place a row is
// constructed: prepend, append and update all go through it, so a message looks
// the same however it arrived.
function mk(msg) {
  const el = document.createElement("li");
  el.className = [
    msg.is_own ? "own" : "",
    msg.error ? "error" : "",
    msg.redacted ? "redacted" : "",
  ].filter((c) => c).join(" ");

  const who = document.createElement("span");
  who.className = "who";
  who.textContent = msg.is_own ? "you" : msg.display;
  who.title = msg.sender;
  el.appendChild(who);

  const body = document.createElement("span");
  body.className = "body";
  if (msg.redacted) {
    const marker = document.createElement("span");
    marker.className = "redacted-marker";
    marker.textContent = "(redacted)";
    body.appendChild(marker);
  }
  // Text first, then the attachment: an image message's body is just its
  // filename, which the element itself already shows, so skip it there.
  if (msg.body && !(msg.media && msg.msgtype !== "m.text")) {
    body.appendChild(document.createTextNode(msg.body));  // never interpret HTML
  }
  if (msg.error) body.title = msg.error;
  // A redacted message keeps no attachment: the content is gone server-side.
  if (msg.media && !msg.redacted) renderMedia(body, msg);
  // Edits are shown against the version before them, so each sub-row reads as
  // the full message with just that revision's changes marked.
  if (msg.edits && !msg.redacted) {
    let prev = msg.body;
    for (const e of msg.edits) {
      body.appendChild(renderEdit(prev, e));
      prev = e.body;
    }
  }
  el.appendChild(body);

  const ago = document.createElement("span");
  ago.className = "ago";
  ago.textContent = humanAgo(msg.timestamp);
  ago.title = fmtAbs(msg.timestamp);
  el.appendChild(ago);

  rendered.set(msg.event_id, { li: el, ago: ago, ts: msg.timestamp });
  return el;
}

// build turns a batch of messages into one fragment, so the whole batch costs a
// single DOM insertion.
//
// A message we already hold is updated in place and left out of the fragment,
// rather than added a second time. That makes append and prepend idempotent,
// which is what lets the server deliver the same message twice without any
// coordination: the only way to see a duplicate is to be told about one, and
// event_id is unique per event.
function build(msgs) {
  const frag = document.createDocumentFragment();
  for (const msg of msgs) {
    const existing = rendered.get(msg.event_id);
    if (existing) {
      existing.li.replaceWith(mk(msg));
      continue;
    }
    frag.appendChild(mk(msg));
  }
  return frag;
}

// applyUpdate re-renders messages in place, keyed by event_id.
//
// An unknown id is dropped, never inserted: the server sends updates for
// whatever changed, which may well be outside the window this client is
// showing, and an update carries no position to insert at.
function applyUpdate(msgs) {
  for (const msg of msgs) {
    const existing = rendered.get(msg.event_id);
    if (!existing) continue;
    existing.li.replaceWith(mk(msg));
  }
}

// ---------------------------------------------------------------------------
// the unread-message banner
// ---------------------------------------------------------------------------

// Following new messages is the stylesheet's job (see #scroller), but snapping
// only engages while the scroller is exactly at the snap position, so a
// viewport a pixel short of the bottom silently stops following. Rather than
// try to make that precise — measuring scroll offsets by hand is what made the
// old code jump — this watches the *result* and offers a way back when the
// newest message is not on screen, whatever the reason.
//
// Watching beats calculating here because the question is literally "is this
// on screen", which the browser can answer exactly and arithmetic over
// scrollHeight can only approximate.
//
// The banner needs *two* conditions, not one, and conflating them is the
// obvious mistake: showing it whenever the bottom is off screen means reading
// history always carries a banner advertising a message that was read long
// ago. So it appears only when both hold:
//
//     an unseen message exists   AND   the bottom is not in view
//
// newestMsg carries the first. It is set only by messages that arrive over the
// stream — never by the backlog the page was rendered with, which by
// definition was already on screen — and cleared again the moment the bottom
// comes into view, which is what "seen" means here. A null newestMsg makes
// showBanner a no-op, so the position half can fire freely without ever
// producing a banner for something already read.
let newestMsg = null;

// bottomWatch reports whether the very bottom of the log is in view.
//
// It is re-registered on every append rather than left observing, and that is
// load-bearing: an observer reports *transitions*, so one that already knows
// the bottom is off screen stays silent when yet another message arrives off
// screen — exactly when the banner needs updating. Re-registering resets the
// remembered state (a fresh registration starts at threshold index -1, which
// no computed index can equal), which guarantees a callback carrying the
// current answer.
//
// The callback runs after layout, and therefore after snapping has had its
// turn, so it sees the settled result rather than the moment of insertion.
const bottomWatch = new IntersectionObserver((entries) => {
  const entry = entries[entries.length - 1];
  if (entry.isIntersecting) {
    // Reaching the bottom is what marks the newest message as seen, so the
    // banner does not come back if the user scrolls up again afterwards.
    newestMsg = null;
    hideBanner();
  } else {
    showBanner();
  }
}, { root: scroller, threshold: 0 });

// Between appends the registration stays live, so scrolling back down to the
// bottom hides the banner on its own — no scroll handler anywhere.
function watchBottom() {
  bottomWatch.unobserve(sentinel);   // observe() alone would be a no-op
  bottomWatch.observe(sentinel);
}

// bannerText is the one-line preview. Attachments have no useful body (for an
// image it is just the filename), so they get a placeholder, mirroring what
// desktop notifications show — see notificationBody in serve.go.
function bannerText(msg) {
  if (msg.media && msg.msgtype !== "m.text") {
    switch (msg.msgtype) {
      case "m.image": return "[image]";
      case "m.video": return "[video]";
      case "m.audio": return "[audio]";
      default:        return "[file]";
    }
  }
  return msg.body || "";
}

function showBanner() {
  if (!newestMsg) return;
  newestEl.querySelector(".who").textContent =
    newestMsg.is_own ? "you" : newestMsg.display;
  newestEl.querySelector(".body").textContent = bannerText(newestMsg);
  newestEl.hidden = false;
}

function hideBanner() {
  newestEl.hidden = true;
}

// Clicking anywhere on the banner returns to the bottom. Landing exactly at
// the bottom is also what re-arms snapping, so following resumes from here.
//
// The message counts as seen from the click, not from the scroll that follows:
// acting on the banner is the acknowledgement. Waiting for the observer to
// confirm arrival would leave it unseen if the scroll came up short, and the
// banner would then reappear for a message the reader has just been taken to.
newestEl.addEventListener("click", () => {
  newestMsg = null;
  scroller.scrollTop = scroller.scrollHeight;
  hideBanner();
});

// reset throws the log away, for when the server tells us our view can no
// longer be reconciled (hicli cleared the room's timeline, or we missed a live
// event). The stream then re-sends history from scratch.
//
// didReset is latched so a later reconnect does not re-offer the backlog the
// page was rendered with: those rows are gone from the DOM, and claiming to
// still hold them would leave a hole. After a reset the stream is the only
// source of history, exactly as it was before the page embedded any.
let didReset = false;
function reset() {
  log.replaceChildren();
  rendered.clear();
  didReset = true;
  // The message the banner was advertising is no longer in the log.
  newestMsg = null;
  hideBanner();
}

// Keep the relative timestamps honest on a long-lived page.
setInterval(() => {
  for (const entry of rendered.values()) {
    entry.ago.textContent = humanAgo(entry.ts);
  }
}, 60000);

// SSE with auto-reconnect. EventSource retries on its own and echoes back the
// last id: it saw as Last-Event-ID — an event ID, which the server re-resolves
// against the current timeline — so there is no manual re-sync on reconnect.
//
// Four message operations, each exactly one DOM mutation. The server always
// knows whether a batch belongs above or below what we hold, so nothing here
// sorts, compares or searches for a position.
// tabID identifies this tab's event stream to the server, so it can report
// whether the room is on screen. Only has to be unique among live streams, and
// deliberately not persisted: a reloaded tab is a new stream.
const tabID = Math.random().toString(36).slice(2) + Date.now().toString(36);

// Tell the server whether this tab is actually showing the room, so it can skip
// notifying about a conversation being read. The server decides this because
// the notification is delivered to a single tab that is usually a different one
// — see the notify handling in serve.go.
//
// sendBeacon on hide: a plain fetch can be cancelled when the page is being
// backgrounded or closed, which is exactly when this matters most.
function reportVisibility() {
  const visible = document.visibilityState === "visible";
  const body = JSON.stringify({ tab: tabID, visible: visible });
  if (!visible && navigator.sendBeacon) {
    navigator.sendBeacon(base + "/visibility", new Blob([body], { type: "application/json" }));
    return;
  }
  fetch(base + "/visibility", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: body,
    keepalive: true,
  }).catch(() => {});
}
document.addEventListener("visibilitychange", reportVisibility);

function connect() {
  // Visibility is passed on connect as well as reported later, so a tab opened
  // in the background never briefly counts as being on screen.
  const params = new URLSearchParams({
    tab: tabID,
    visible: document.visibilityState === "visible" ? "1" : "0",
  });
  // Tell the server what the page already rendered, so it neither replays it
  // nor skips past it: resume forward from the newest row, and continue
  // backwards from the oldest if the page got less than a full backlog.
  //
  // These are query parameters because EventSource sends Last-Event-ID only on
  // a *re*connect — on the first connect there is no header to carry a cursor
  // the server never issued. On later reconnects the header is newer than
  // these and takes precedence server-side. They are cleared after a reset,
  // which throws away the rendered backlog they describe.
  if (!didReset) {
    if (backlogNewest) params.set("since", backlogNewest);
    if (backlogOldest) {
      params.set("before", backlogOldest);
      params.set("have", String(backlogHave));
    }
  }
  const es = new EventSource(base + "/events?" + params);

  es.onopen = () => {
    statusEl.textContent = "live";
    statusEl.className = "status live";
  };
  es.onerror = () => {
    statusEl.textContent = "reconnecting…";
    statusEl.className = "status down";
  };

  // Older history, walking backwards. Arrives newest-chunk-first, so each
  // batch goes above the last.
  //
  // No scroll handling here, deliberately. Rows are inserted above the
  // viewport, and the log is never empty by the time these arrive (the page
  // ships with its backlog), so the scroller is scrolled away from its origin
  // and CSS scroll anchoring holds the visible content still on its own. The
  // code that used to adjust scrollTop by the height difference was double
  // compensating: the browser had already made the same adjustment.
  es.addEventListener("prepend", (e) => {
    const msgs = JSON.parse(e.data).messages;
    if (!msgs.length) return;
    log.prepend(build(msgs));
  });

  // New messages, and gap replay after a reconnect. Always oldest-first and
  // always newer than everything we hold.
  //
  // No scroll handling: #latest is a snap position at the bottom of the
  // scroller, so adding content below re-snaps to it when the user is at the
  // bottom and leaves them alone when they have scrolled away. All this does
  // is ask, afterwards, whether the newest message actually ended up on
  // screen — and show the banner when it did not.
  //
  // Note there is no special case for our own messages: one you just sent
  // arrives here like any other, so sending while reading history leaves you
  // where you are and offers the banner rather than yanking you to the bottom.
  es.addEventListener("append", (e) => {
    const msgs = JSON.parse(e.data).messages;
    if (!msgs.length) return;
    log.append(build(msgs));
    newestMsg = msgs[msgs.length - 1];
    watchBottom();
  });

  // A message changed: edited, redacted, or finally decrypted.
  es.addEventListener("update", (e) => {
    applyUpdate(JSON.parse(e.data).messages);
  });

  // Our view can no longer be reconciled; history follows on this same stream.
  es.addEventListener("reset", () => {
    reset();
  });

  es.addEventListener("typing", (e) => {
    const users = JSON.parse(e.data).users || [];
    typingEl.textContent = users.length
      ? users.join(", ") + (users.length === 1 ? " is" : " are") + " typing…"
      : "";
  });
}

form.addEventListener("submit", async (e) => {
  e.preventDefault();
  const body = text.value.trim();
  if (!body) return;
  sendBtn.disabled = true;
  text.value = "";
  text.style.height = "auto";
  try {
    const res = await fetch(base + "/send", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text: body }),
    });
    if (!res.ok) {
      text.value = body;               // put it back so nothing is lost
      alert("send failed: " + (await res.text()));
    }
  } catch (err) {
    text.value = body;
    alert("send failed: " + err);
  } finally {
    sendBtn.disabled = false;
    text.focus();
    notifyTyping(false);
  }
});

// Enter sends, Shift+Enter inserts a newline.
text.addEventListener("keydown", (e) => {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    form.requestSubmit();
  }
});

// Grow the textarea with its content, up to the CSS max-height.
text.addEventListener("input", () => {
  text.style.height = "auto";
  text.style.height = Math.min(text.scrollHeight, 128) + "px";
});

// Throttled typing notifications.
let typingSent = 0;
function notifyTyping(on) {
  const now = Date.now();
  if (on && now - typingSent < 4000) return;
  typingSent = on ? now : 0;
  fetch(base + "/typing", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ typing: on }),
  }).catch(() => {});
}
text.addEventListener("input", () => notifyTyping(text.value.length > 0));

// ---------------------------------------------------------------------------
// paste-to-send images
// ---------------------------------------------------------------------------

// The homeserver's m.upload.size. Oversized pastes are shrunk to fit rather
// than rejected — see fitToLimit.
const uploadLimit = {{.UploadLimit}};

// Downscaling happens here rather than on the server because the browser has
// already decoded the image in order to offer it as a paste, and because
// attachment encryption is length-preserving: once encrypted, the server cannot
// shrink anything without decrypting and re-encrypting.
//
// An image that already fits is uploaded byte-for-byte untouched, so the common
// case (a screenshot) stays lossless PNG. Only images that would otherwise be
// rejected outright get re-encoded.
async function fitToLimit(file, bitmap) {
  if (file.size <= uploadLimit) {
    return { blob: file, type: file.type, w: bitmap.width, h: bitmap.height };
  }

  // JPEG size is not a predictable function of quality or scale, so this
  // converges by measurement instead of arithmetic: shrink, re-encode, check,
  // repeat. Bounded attempts, because a pathological input should fail loudly
  // rather than spin.
  let scale = Math.sqrt(uploadLimit / file.size);
  let quality = 0.9;
  for (let attempt = 0; attempt < 6; attempt++) {
    const w = Math.max(1, Math.round(bitmap.width * scale));
    const h = Math.max(1, Math.round(bitmap.height * scale));
    const canvas = document.createElement("canvas");
    canvas.width = w;
    canvas.height = h;
    const ctx = canvas.getContext("2d");
    // JPEG has no alpha: without this, transparent regions turn black. Fill
    // with the page background so a transparent screenshot still looks right.
    ctx.fillStyle = getComputedStyle(document.body).backgroundColor || "#fff";
    ctx.fillRect(0, 0, w, h);
    ctx.drawImage(bitmap, 0, 0, w, h);

    const blob = await new Promise((res) => canvas.toBlob(res, "image/jpeg", quality));
    if (!blob) throw new Error("could not re-encode image");
    if (blob.size <= uploadLimit) {
      return { blob: blob, type: "image/jpeg", w: w, h: h };
    }
    // Overshot: back off on both axes and try again.
    scale *= 0.8;
    quality = Math.max(0.4, quality - 0.1);
  }
  throw new Error("image is too large to send");
}

// Pending rows live in their own list below the log, so they are always visually
// last without needing a position among real messages. They are keyed separately
// too: the sent event comes back with a server-assigned event_id that cannot be
// predicted here, so the placeholder is removed rather than updated in place.
function addPendingRow(label) {
  const li = document.createElement("li");
  const who = document.createElement("span");
  who.className = "who";
  who.textContent = "you";
  const bodyEl = document.createElement("span");
  bodyEl.className = "body";
  bodyEl.textContent = label;
  const ago = document.createElement("span");
  ago.className = "ago";
  ago.textContent = "sending…";
  li.append(who, bodyEl, ago);
  pending.appendChild(li);
  return { li: li, body: bodyEl, ago: ago };
}

async function uploadImage(file) {
  const row = addPendingRow("uploading image…");
  try {
    const bitmap = await createImageBitmap(file);
    const fitted = await fitToLimit(file, bitmap);
    bitmap.close();

    const name = file.name ||
      ("pasted-" + new Date().toISOString().replace(/[:.]/g, "-") +
       (fitted.type === "image/png" ? ".png" : ".jpg"));
    const params = new URLSearchParams({
      w: fitted.w, h: fitted.h, filename: name,
    });
    const res = await fetch(base + "/upload?" + params, {
      method: "POST",
      headers: { "Content-Type": fitted.type },
      body: fitted.blob,
    });
    if (!res.ok) throw new Error(await res.text());
    // The message itself arrives over SSE like any other, so the placeholder
    // just goes away.
    row.li.remove();
  } catch (err) {
    row.li.classList.add("error");
    row.body.textContent = "upload failed: " + err.message;
    row.ago.textContent = "failed";
  }
}

// Render the embedded backlog before connecting, so the page is complete at
// first paint and the stream has nothing to catch up on in the common case.
//
// The one explicit scroll in the app. Scroll snapping cannot do this: a snap
// position is only re-snapped to once the container *is* snapped to it, and a
// freshly loaded page sits at scrollTop 0. This puts it at the bottom, and
// snapping keeps it there from then on.
if (backlogMsgs.length) {
  log.append(build(backlogMsgs));
  scroller.scrollTop = scroller.scrollHeight;
}
// Start watching regardless of whether there was a backlog, so the banner is
// correct from the first message in an empty room too. The initial callback
// fires whether or not the bottom is visible, which is what establishes the
// starting state rather than assuming it.
//
// Note this deliberately leaves newestMsg null: the backlog was on the page
// before it was ever displayed, so none of it is unseen. Were it set here, a
// room whose last message is taller than the viewport would greet the reader
// with a banner announcing a message they are already looking at.
watchBottom();

text.addEventListener("paste", (e) => {
  const files = [];
  for (const item of e.clipboardData.items) {
    if (item.kind === "file") {
      const file = item.getAsFile();
      if (file && file.type.startsWith("image/")) files.push(file);
    }
  }
  if (files.length === 0) return;   // plain text paste: leave it alone
  e.preventDefault();
  for (const file of files) uploadImage(file);
});

connect();
` + notifyJS + `
</script>
</body>
</html>
`