File size: 97,792 Bytes
4a5bcb0 ac88049 4a5bcb0 | 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 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Survey Visualization Engine — YouGov four-country study</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Plus+Jakarta+Sans:wght@300;400;600;800&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
--font-body:'Inter',ui-sans-serif,system-ui,sans-serif;
--font-display:'Plus Jakarta Sans',ui-sans-serif,system-ui,sans-serif;
--radius:12px; --radius-sm:8px;
--s1:#FF6756; --s2:#6ACAF5; --s3:#5AD5B9; --s4:#616E90; --s5:#FF7BB3;
}
body[data-theme="evidence"]{
--bg:#0a0e1a; --bg2:#0d1424; --ink:#e8eaf0; --muted:#8b90a0;
--line:rgba(255,255,255,.09); --line-strong:rgba(255,255,255,.18);
--panel:rgba(255,255,255,.045); --panel-ink:#cfd4e0;
--accent:#b8e648; --accent-ink:#0a0e1a; --accent-soft:rgba(184,230,72,.12);
--pos:#b8e648; --neg:#e86050; --warn:#e8c840; --info:#6ACAF5;
--chip:rgba(255,255,255,.06); --chip-ink:#d0d4e0;
}
body[data-theme="paper"]{
--bg:#F7F5F1; --bg2:#ffffff; --ink:#1e293b; --muted:#64748b;
--line:#e2ded6; --line-strong:#cfc9be;
--panel:#ffffff; --panel-ink:#334155;
--accent:#4338CA; --accent-ink:#ffffff; --accent-soft:#eef2ff;
--pos:#15803d; --neg:#b91c1c; --warn:#b45309; --info:#0369a1;
--chip:#ffffff; --chip-ink:#334155;
}
html,body{height:100%}
body{
font-family:var(--font-body); color:var(--ink); background:var(--bg);
-webkit-font-smoothing:antialiased; font-size:14px; line-height:1.55;
background-image:radial-gradient(ellipse 70% 50% at 30% 100%, rgba(120,200,140,.06), transparent 70%);
}
#app{max-width:1180px;margin:0 auto;padding:22px 20px 70px}
/* ---- top bar ---- */
.topbar{display:flex;flex-wrap:wrap;gap:14px;align-items:flex-start;justify-content:space-between;padding-bottom:16px;border-bottom:1px solid var(--line)}
.brand .kicker{font-size:.66rem;font-weight:700;letter-spacing:.18em;text-transform:uppercase;color:var(--accent)}
.brand h1{font-family:var(--font-display);font-weight:300;font-size:clamp(1.35rem,3.2vw,1.95rem);line-height:1.12;margin-top:4px}
.brand p.sub{font-size:.78rem;color:var(--muted);margin-top:5px;max-width:60ch}
.actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
/* ---- nav ---- */
nav.tabs{display:flex;flex-wrap:wrap;gap:6px;margin:16px 0 18px}
nav.tabs button{
font-family:var(--font-body);font-size:.72rem;font-weight:600;letter-spacing:.05em;text-transform:uppercase;
padding:.45rem .8rem;border-radius:100px;border:1px solid var(--line);background:transparent;color:var(--muted);
cursor:pointer;transition:.15s;
}
nav.tabs button:hover{color:var(--ink);border-color:var(--line-strong)}
nav.tabs button.on{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}
/* ---- generic ---- */
.btn{
font-family:var(--font-body);font-size:.74rem;font-weight:600;padding:.42rem .8rem;border-radius:var(--radius-sm);
border:1px solid var(--line-strong);background:var(--chip);color:var(--chip-ink);cursor:pointer;transition:.15s;
}
.btn:hover{border-color:var(--accent);color:var(--accent)}
.btn.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}
.btn.primary:hover{filter:brightness(1.08);color:var(--accent-ink)}
.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:18px 20px;margin-bottom:16px}
.card h3{font-family:var(--font-display);font-weight:400;font-size:1.05rem;margin-bottom:4px}
.card h3 + .cap{font-size:.76rem;color:var(--muted);margin-bottom:14px}
.grid2{display:grid;grid-template-columns:1fr;gap:16px}
@media(min-width:820px){.grid2{grid-template-columns:1fr 1fr}}
.grid4{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px}
.eyebrow{font-size:.64rem;font-weight:700;letter-spacing:.16em;text-transform:uppercase;color:var(--accent);margin-bottom:8px}
.muted{color:var(--muted)}
.tiny{font-size:.72rem}
.rule{height:1px;background:var(--line);margin:14px 0}
.badge{display:inline-block;font-size:.62rem;font-weight:700;letter-spacing:.08em;text-transform:uppercase;padding:.16rem .5rem;border-radius:100px;border:1px solid var(--line-strong);color:var(--muted)}
.badge.ok{color:var(--pos);border-color:var(--pos)}
.badge.no{color:var(--neg);border-color:var(--neg)}
.badge.warn{color:var(--warn);border-color:var(--warn)}
.kv{display:flex;justify-content:space-between;gap:10px;padding:.3rem 0;border-bottom:1px solid var(--line);font-size:.78rem}
.kv:last-child{border-bottom:none}
.kv b{font-weight:600}
/* ---- controls ---- */
.controls{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;margin-bottom:16px}
.field{display:flex;flex-direction:column;gap:4px}
.field label{font-size:.62rem;font-weight:700;letter-spacing:.12em;text-transform:uppercase;color:var(--muted)}
select,input[type=text],input[type=number],textarea{
font-family:var(--font-body);font-size:.78rem;padding:.42rem .6rem;border-radius:var(--radius-sm);
border:1px solid var(--line-strong);background:var(--bg2);color:var(--ink);min-width:120px;
}
select{max-width:320px}
textarea{width:100%;min-height:110px;font-family:ui-monospace,Menlo,monospace;font-size:.72rem;line-height:1.45}
input[type=checkbox]{accent-color:var(--accent);width:15px;height:15px;cursor:pointer}
/* ---- charts ---- */
.chart{display:block;overflow:visible}
.sv-grid{stroke:var(--line);stroke-width:1;opacity:.75}
.sv-axisline{stroke:var(--line-strong);stroke-width:1}
.sv-txt{fill:var(--muted);font-size:9.5px;font-family:var(--font-body)}
.sv-lbl{fill:var(--ink);font-size:10.5px;font-family:var(--font-body);font-weight:500}
.sv-val{fill:var(--ink);font-size:10px;font-family:var(--font-body);font-weight:600}
.sv-base{fill:var(--muted);font-size:9px;font-family:var(--font-body);opacity:.75}
.sv-dot{fill:var(--accent)}
.sv-dot-thin{fill:var(--neg);opacity:.55}
.sv-ci{stroke:var(--accent);stroke-width:1.3;opacity:.55}
.sv-ci-thin{stroke:var(--neg);stroke-width:1.3;opacity:.5}
.sv-ref{stroke:var(--warn);stroke-width:1.2;stroke-dasharray:4 3}
.sv-panel{fill:none;stroke:var(--line);stroke-width:1}
.sv-panel-title{fill:var(--ink);font-size:11px;font-weight:700;font-family:var(--font-display)}
.sv-bar{fill:var(--accent);opacity:.85}
.sv-barneg{fill:var(--neg);opacity:.8}
.sv-zero{stroke:var(--line-strong);stroke-width:1.2}
/* ---- matrix ---- */
.matrix-wrap{overflow-x:auto;-webkit-overflow-scrolling:touch;border:1px solid var(--line);border-radius:var(--radius)}
table.matrix{border-collapse:separate;border-spacing:0;font-size:.72rem;width:100%}
table.matrix th{
position:sticky;top:0;background:var(--bg2);font-weight:600;font-size:.62rem;letter-spacing:.05em;
text-transform:uppercase;color:var(--muted);padding:.5rem .55rem;border-bottom:1px solid var(--line);
border-right:1px solid var(--line);white-space:nowrap;cursor:pointer;text-align:center;
}
table.matrix th:hover{color:var(--accent)}
table.matrix th.rowh{text-align:left;cursor:default;min-width:190px;position:sticky;left:0;z-index:2}
table.matrix td{padding:.42rem .55rem;border-bottom:1px solid var(--line);border-right:1px solid var(--line);text-align:center;font-variant-numeric:tabular-nums}
table.matrix td.rowh{text-align:left;font-weight:500;color:var(--ink);background:var(--bg2);position:sticky;left:0;z-index:1;white-space:nowrap}
table.matrix tr:last-child td{border-bottom:none}
/* ---- headline cards ---- */
.slide{border:1px solid var(--line);border-radius:var(--radius);padding:20px 22px;margin-bottom:14px;background:var(--panel);break-inside:avoid}
.slide .snum{font-size:.62rem;font-weight:700;letter-spacing:.16em;text-transform:uppercase;color:var(--accent)}
.slide h4{font-family:var(--font-display);font-weight:400;font-size:1.15rem;line-height:1.25;margin:.35rem 0 .7rem}
.slide .so-what{font-size:.8rem;color:var(--muted);margin-top:10px;border-left:2px solid var(--accent);padding-left:10px}
.bignum{border:1px solid var(--line);border-radius:var(--radius);padding:18px;background:var(--panel);text-align:center}
.bignum .c{font-size:.66rem;font-weight:700;letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
.bignum .v{font-family:var(--font-display);font-weight:300;font-size:2.6rem;line-height:1;margin:.4rem 0}
.bignum .d{font-size:.72rem;color:var(--muted)}
.caveat{font-size:.72rem;color:var(--muted);border-top:1px dashed var(--line-strong);padding-top:10px;margin-top:14px}
/* ---- rubric ---- */
.crit{display:flex;gap:10px;padding:.55rem 0;border-bottom:1px solid var(--line);align-items:flex-start}
.crit:last-child{border-bottom:none}
.crit .txt{flex:1;font-size:.8rem}
.crit .why{font-size:.68rem;color:var(--muted);margin-top:2px}
.ring-wrap{display:flex;align-items:center;gap:14px}
.ring-txt{font-family:var(--font-display);font-weight:300;font-size:1.8rem}
.status{font-size:.74rem;color:var(--info);min-height:1.2em;margin-top:8px}
.logitem{font-size:.78rem;padding:.5rem 0;border-bottom:1px solid var(--line);display:flex;gap:8px}
.logitem .t{font-variant-numeric:tabular-nums;color:var(--muted);font-size:.68rem;white-space:nowrap;padding-top:2px}
@media print{
body{background:#fff;color:#000}
nav.tabs,.actions,.no-print{display:none!important}
#app{max-width:none;padding:0}
.card,.slide,.bignum{border-color:#ccc;box-shadow:none;break-inside:avoid}
.sv-lbl,.sv-val{fill:#000}.sv-txt{fill:#444}
}
</style>
</head>
<body data-theme="evidence">
<div id="app"></div>
<script>
/* =========================================================================
SURVEY VISUALIZATION ENGINE
A static, dependency-free Hugging Face Space (SDK: static).
Operationalises: Tufte · Cleveland · Bertin · Tukey · Few · Holmes ·
Norman · Mayer · Zelazny · Godin · Bateman · Borkin · Kosara · Hullman ·
Diakopoulos · Drucker · D'Ignazio · Klein.
NOTE ON STATE: this Space runs in a sandboxed frame with no storage.
All session state is held in memory and is lost on reload, by design.
========================================================================= */
/* ---------------------------- 0 · utilities ---------------------------- */
const $ = (s, r = document) => r.querySelector(s);
const esc = s => String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const pct = (x, d = 0) => (x == null || isNaN(x)) ? '–' : (x * 100).toFixed(d) + '%';
const ppf = x => (x >= 0 ? '+' : '\u2212') + Math.abs(x * 100).toFixed(1) + ' pp';
const clamp = (x, a, b) => Math.min(b, Math.max(a, x));
const slug = s => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return ((t^t>>>14)>>>0)/4294967296;};}
function gaussFn(rnd){
let spare = null;
return function(){
if(spare !== null){ const s = spare; spare = null; return s; }
let u = 0, v = 0;
while(u === 0) u = rnd();
while(v === 0) v = rnd();
const r = Math.sqrt(-2 * Math.log(u));
spare = r * Math.sin(2 * Math.PI * v);
return r * Math.cos(2 * Math.PI * v);
};
}
/* descending cuts: higher score -> lower index */
function catDesc(x, cuts){ let i = 0; while(i < cuts.length && x < cuts[i]) i++; return i; }
function softmaxPick(logits, rnd){
const m = Math.max.apply(null, logits);
const ex = logits.map(l => Math.exp(l - m));
const s = ex.reduce((a, b) => a + b, 0);
let u = rnd() * s;
for(let i = 0; i < ex.length; i++){ u -= ex[i]; if(u <= 0) return i; }
return ex.length - 1;
}
function niceTicks(a, b, n){
n = n || 5;
const span = b - a;
if(span <= 0) return [a];
const raw = span / n;
const mag = Math.pow(10, Math.floor(Math.log10(raw)));
const mults = [1, 2, 2.5, 5, 10];
let step = mag * 10;
for(const m of mults){ if(mag * m >= raw){ step = mag * m; break; } }
const out = [];
for(let v = Math.ceil(a / step) * step; v <= b + 1e-9; v += step) out.push(+v.toFixed(6));
return out;
}
function nowTime(){
const d = new Date();
return String(d.getHours()).padStart(2,'0') + ':' + String(d.getMinutes()).padStart(2,'0') + ':' + String(d.getSeconds()).padStart(2,'0');
}
/* ---------------------------- 1 · demo dataset ---------------------------- */
const COUNTRIES = ['USA','Canada','UK','Australia'];
const GENDERS = ['Male','Female','Other / prefer not to say'];
const GENS = ['18\u201329','30\u201344','45\u201359','60\u201374','75+'];
const DEMO_QUESTIONS = [
{ id:'q_turnout', module:'Participation', short:'Turnout intention',
text:'How likely are you to vote in your country\u2019s next national election?',
opts:['Definitely will vote','Probably will vote','Probably will not vote','Definitely will not vote','Don\u2019t know'],
gen:(t) => catDesc(t.eng, [-0.05,-1.05,-1.60,-1.75]) },
{ id:'q_certainty', module:'Participation', short:'Vote certainty',
text:'How certain are you that you will actually vote?',
opts:['Completely certain','Fairly certain','Not very certain','Don\u2019t know'],
gen:(t) => catDesc(t.eng, [-0.35,-1.15,-1.90]) },
{ id:'q_barrier', module:'Participation', short:'Barriers to voting',
text:'What is the single biggest barrier to your voting?',
opts:['No significant barrier','Time or practical constraints','Disillusionment or distrust','Access or registration difficulty'],
gen:(t) => catDesc(-0.62*t.eng + 0.52*t.iss, [0.15,-0.85,-1.55]) },
{ id:'q_vote', module:'Electoral choice', short:'Vote intention',
text:'If the election were held tomorrow, which party would you vote for?',
opts:['Party A','Party B','Party C','Other party','Undecided'],
gen:(t, c, gi, rnd) => softmaxPick([
-0.38*t.iss + 0.30*t.tr + (c === 0 ? 0.42 : 0),
0.26*t.soc - 0.16*t.tr + (c === 1 ? -0.22 : 0),
0.46*t.iss - 0.34*t.soc + (c === 2 ? 0.30 : 0),
-0.95,
-0.30 + (gi < 2 ? 0.35 : 0)
], rnd) },
{ id:'q_issue', module:'Issue priorities', short:'Most important issue',
text:'Which issue is the most important facing the country today?',
opts:['Cost of living','Health','Climate','Immigration','Housing','Defence'],
gen:(t, c, gi, rnd) => softmaxPick([
0.62*t.iss + 0.22,
0.16 - 0.12*t.iss + (c === 1 ? 0.55 : 0),
-0.42 + (c === 2 || c === 3 ? 0.36 : 0) + 0.16*t.tr,
0.22 + (c === 0 ? 0.55 : 0) + (c === 3 ? 0.32 : 0) - 0.22*t.tr,
0.10*t.iss + (c === 1 ? 0.42 : 0) + (c === 3 ? -0.25 : 0),
-0.85 + (c === 3 ? 0.55 : 0) + (c === 2 ? 0.30 : 0)
], rnd) },
{ id:'q_stakes', module:'Issue priorities', short:'Personal stakes',
text:'How high are the personal stakes of this election for you and your household?',
opts:['Very high','High','Moderate','Low','Very low'],
gen:(t) => catDesc(t.iss, [0.95, 0.22, -0.58, -1.32]) },
{ id:'q_trust', module:'Trust & information', short:'Trust in government',
text:'How much do you trust the national government to do what is right?',
opts:['A great deal','Quite a lot','Not very much','None at all','Don\u2019t know'],
gen:(t) => catDesc(t.tr, [0.05, -0.88, -1.70, -2.20]) },
{ id:'q_news', module:'Trust & information', short:'Primary news source',
text:'Which of these is your main source of political news?',
opts:['TV news','Online news','Social media','Radio','Newspapers','None of these'],
gen:(t, c, gi, rnd) => {
const ageZ = (gi - 2) / 2;
return softmaxPick([
0.22 - 0.28*ageZ,
0.14 + 0.06*t.tr,
0.55*t.soc + (gi < 2 ? 0.48 : -0.32),
-0.62,
-0.70 - 0.24*ageZ,
-0.52 + 0.20*Math.abs(t.soc)
], rnd);
} },
{ id:'q_satisfaction', module:'Political outlook', short:'Satisfaction with democracy',
text:'How satisfied are you with the way democracy works in your country?',
opts:['Satisfied','Neither satisfied nor dissatisfied','Dissatisfied','Don\u2019t know'],
gen:(t) => catDesc(0.80*t.tr + 0.35*t.eng, [0.25, -0.72, -1.70]) },
{ id:'q_efficacy', module:'Political outlook', short:'Political efficacy',
text:'\u201cPeople like me have no say in what the government does.\u201d',
opts:['Strongly agree','Agree','Neither agree nor disagree','Disagree','Strongly disagree'],
gen:(t) => catDesc(-0.62*t.tr - 0.34*t.eng + 0.30*t.iss, [0.60, -0.18, -0.92, -1.60]) }
];
function buildDemo(seed){
seed = seed || 20261103;
const rnd = mulberry32(seed);
const gauss = gaussFn(rnd);
const rows = [];
const genW = [0.18, 0.24, 0.24, 0.22, 0.12];
const genCum = genW.reduce((a, b) => { a.push((a[a.length-1] || 0) + b); return a; }, []);
const cEng = [0.06, -0.06, 0.00, 0.02];
const cTrust = [-0.12, 0.06, 0.00, 0.12];
COUNTRIES.forEach((country, ci) => {
const n = 1100;
for(let i = 0; i < n; i++){
const u = rnd();
let gi = 0; while(gi < genCum.length - 1 && u > genCum[gi]) gi++;
const gRoll = rnd();
const gender = gRoll < 0.022 ? GENDERS[2] : (gRoll < 0.522 ? GENDERS[0] : GENDERS[1]);
const engMu = [-0.60, -0.25, 0.04, 0.32, 0.44][gi] + cEng[ci] + (gender === GENDERS[2] ? -0.28 : (gender === GENDERS[1] ? 0.03 : 0));
const trMu = 0.15 + (gi < 2 ? -0.26 : 0.10) + cTrust[ci];
const t = {
eng: engMu + gauss() * 0.95,
tr: trMu + gauss() * 1.00,
soc: (gi < 2 ? 0.52 : -0.22) + (gender === GENDERS[0] ? 0.08 : 0) + gauss() * 1.00,
iss: (gi < 2 ? 0.14 : 0) + gauss() * 1.00
};
const row = { country, gender, gen: GENS[gi], weight: 0.65 + rnd() * 0.75 };
for(const q of DEMO_QUESTIONS){
let v = q.gen(t, ci, gi, rnd);
if(v < 0) v = 0;
if(v > q.opts.length - 1) v = q.opts.length - 1;
row[q.id] = q.opts[v];
}
/* inject realistic item nonresponse on two items */
if(rnd() < 0.013) row.q_trust = null;
if(rnd() < 0.010) row.q_news = null;
rows.push(row);
}
});
/* country-normalise weights so each country sums to its n */
COUNTRIES.forEach(c => {
const sub = rows.filter(r => r.country === c);
const s = sub.reduce((a, r) => a + r.weight, 0);
const k = sub.length / s;
sub.forEach(r => { r.weight *= k; });
});
return {
rows,
questions: DEMO_QUESTIONS.map(q => ({ id: q.id, module: q.module, short: q.short, text: q.text, opts: q.opts.slice() })),
meta: {
source: 'Synthetic demonstration data',
seed,
generated: new Date().toISOString().slice(0, 10),
note: 'Simulated respondents, not real survey data. Patterns are constructed from four latent traits (engagement, trust, social-media reliance, economic anxiety) so that cross-question structure exists to explore.'
}
};
}
/* ---------------------------- 2 · CSV ingest ---------------------------- */
function detectDelim(line){
const c = (line.match(/,/g) || []).length;
const t = (line.match(/\t/g) || []).length;
const s = (line.match(/;/g) || []).length;
return t > c && t > s ? '\t' : (s > c ? ';' : ',');
}
function parseCSV(text){
const clean = text.replace(/\r/g, '').trim();
if(!clean) return null;
const lines = clean.split('\n').filter(l => l.trim() !== '');
const d = detectDelim(lines[0]);
const split = l => {
const out = []; let cur = ''; let q = false;
for(let i = 0; i < l.length; i++){
const ch = l[i];
if(ch === '"'){ if(q && l[i+1] === '"'){ cur += '"'; i++; } else q = !q; }
else if(ch === d && !q){ out.push(cur); cur = ''; }
else cur += ch;
}
out.push(cur);
return out.map(s => s.trim());
};
const header = split(lines[0]);
const rows = lines.slice(1).map(split);
return { header, rows };
}
function guessRole(name){
const n = name.toLowerCase();
if(/countr|nation|market|geo/.test(n)) return 'country';
if(/gender|sex/.test(n)) return 'gender';
if(/generation|cohort|age_?band|agegroup|age_group/.test(n)) return 'gen';
if(/weight|wgt/.test(n)) return 'weight';
return 'question';
}
function buildFromRaw(raw, roles){
const header = raw.header;
const qCols = [];
header.forEach((h, i) => { if(roles[i] === 'question') qCols.push(i); });
const idx = role => header.findIndex((h, i) => roles[i] === role);
const iC = idx('country'), iG = idx('gender'), iN = idx('gen'), iW = idx('weight');
const rows = raw.rows.map(cells => {
const r = {
country: iC >= 0 ? (cells[iC] || 'Unknown') : 'All',
gender: iG >= 0 ? (cells[iG] || 'Unknown') : 'All',
gen: iN >= 0 ? (cells[iN] || 'Unknown') : 'All',
weight: iW >= 0 && cells[iW] !== '' && !isNaN(+cells[iW]) ? +cells[iW] : 1
};
qCols.forEach(i => {
const v = cells[i];
r['q_' + slug(header[i])] = (v === '' || v == null) ? null : v;
});
return r;
});
const questions = qCols.map(i => {
const counts = new Map();
rows.forEach(r => { const v = r['q_' + slug(header[i])]; if(v != null) counts.set(v, (counts.get(v) || 0) + 1); });
const opts = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 14).map(e => e[0]);
return { id: 'q_' + slug(header[i]), module: 'Imported', short: header[i], text: header[i], opts };
}).filter(q => q.opts.length > 1 && q.opts.length <= 14);
return {
rows, questions,
meta: { source: 'Pasted table', generated: new Date().toISOString().slice(0, 10), note: 'Imported in-session. Column roles were auto-detected and can be reassigned.' }
};
}
/* ---------------------------- 3 · state ---------------------------- */
const State = {
mode: 'data',
theme: 'evidence',
data: null,
raw: null,
roles: null,
csvText: '',
qid: null,
opt: 0,
dim: 'gender',
denominator: 'all',
minBase: 100,
chartForm: 'dot',
colorMode: 'col',
colOrder: null,
rowOrder: null,
log: [],
specs: [],
confirmatory: {},
manual: {},
visited: { brief:false, public:false, compare:false },
status: '',
seedUsed: 20261103
};
/* ---------------------------- 4 · analysis ---------------------------- */
function getQ(id){ return State.data ? State.data.questions.find(q => q.id === id) : null; }
function activeRows(){
const d = State.data;
if(!d) return [];
if(State.denominator === 'all') return d.rows;
/* denominator subsets are defined by the first ordered question whose label mentions vote/turnout */
const denomQ = d.questions.find(q => /turnout|vote|likely/i.test(q.short + ' ' + q.text)) || d.questions[0];
if(!denomQ || !denomQ.opts || denomQ.opts.length < 2) return d.rows;
const top = denomQ.opts[0], second = denomQ.opts[1];
if(State.denominator === 'top1') return d.rows.filter(r => r[denomQ.id] === top);
if(State.denominator === 'top2') return d.rows.filter(r => r[denomQ.id] === top || r[denomQ.id] === second);
return d.rows;
}
function denominatorLabel(){
if(State.denominator === 'all') return 'All respondents in the dataset';
const d = State.data;
const denomQ = d.questions.find(q => /turnout|vote|likely/i.test(q.short + ' ' + q.text)) || d.questions[0];
if(!denomQ) return 'All respondents';
const top = denomQ.opts[0];
if(State.denominator === 'top1') return 'Respondents answering \u201c' + top + '\u201d on: ' + denomQ.short;
return 'Respondents answering \u201c' + top + '\u201d or \u201c' + denomQ.opts[1] + '\u201d on: ' + denomQ.short;
}
function analyse(){
const q = getQ(State.qid);
if(!q) return null;
const dim = State.dim;
const rows = activeRows();
const opts = q.opts;
const acc = new Map();
const slot = (country, sub) => {
const k = country + '\u00a6' + sub;
let a = acc.get(k);
if(!a){
a = { key:k, country, sub, n:0, nw:0, w2:0, cnt:new Array(opts.length).fill(0), ncnt:new Array(opts.length).fill(0) };
acc.set(k, a);
}
return a;
};
for(const r of rows){
const v = r[q.id];
const vi = v == null ? -1 : opts.indexOf(v);
const w = +r.weight || 1;
const subs = dim === 'none' ? ['All']
: dim === 'gender' ? [r.gender || 'Unknown']
: dim === 'gen' ? [r.gen || 'Unknown']
: [(r.gender || 'Unknown') + ' \u00b7 ' + (r.gen || 'Unknown')];
for(const s of subs){
const a = slot(r.country || 'All', s);
a.n++; a.nw += w; a.w2 += w * w;
if(vi >= 0){ a.cnt[vi] += w; a.ncnt[vi]++; }
}
if(dim !== 'none'){
const a = slot(r.country || 'All', 'All');
a.n++; a.nw += w; a.w2 += w * w;
if(vi >= 0){ a.cnt[vi] += w; a.ncnt[vi]++; }
}
}
const cols = [...acc.values()].map(a => {
const neff = a.w2 > 0 ? (a.nw * a.nw) / a.w2 : 0;
const p = a.cnt.map(c => a.nw > 0 ? c / a.nw : 0);
const ci = p.map(v => {
const se = neff > 0 ? Math.sqrt(Math.max(v * (1 - v), 1e-9) / neff) : 0;
return [clamp(v - 1.96 * se, 0, 1), clamp(v + 1.96 * se, 0, 1)];
});
return Object.assign({}, a, { neff, p, ci, thin: a.n < State.minBase });
});
const cIdx = c => { const i = COUNTRIES.indexOf(c); return i < 0 ? 99 : i; };
const sIdx = s => {
if(s === 'All') return -1;
const g = GENDERS.indexOf(s); if(g >= 0) return g;
const n = GENS.indexOf(s); if(n >= 0) return 10 + n;
return 50;
};
cols.sort((a, b) => cIdx(a.country) - cIdx(b.country) || sIdx(a.sub) - sIdx(b.sub) || a.sub.localeCompare(b.sub));
const nat = new Map();
cols.forEach(c => { if(c.sub === 'All') nat.set(c.country, c); });
return { q, opts, dim, cols, nat };
}
function diffFromNational(col, natCol, optIdx){
if(!natCol) return { d:0, lo:0, hi:0, z:0, sig:false };
const p1 = col.p[optIdx], p2 = natCol.p[optIdx];
const n1 = col.neff, n2 = natCol.neff;
const se = Math.sqrt(Math.max(p1*(1-p1),1e-9)/Math.max(n1,1) + Math.max(p2*(1-p2),1e-9)/Math.max(n2,1));
const d = p1 - p2;
return { d, lo: clamp(d - 1.96*se, -1, 1), hi: clamp(d + 1.96*se, -1, 1), z: se > 0 ? d/se : 0, sig: se > 0 && Math.abs(d/se) >= 1.96 };
}
/* ---------------------------- 5 · chart primitives ---------------------------- */
function chartDot(cfg){
const rows = cfg.rows || [];
const W = cfg.width || 760;
const padL = cfg.padL || 216, padR = 70, padT = 26;
const rowH = cfg.rowH || 27;
const padB = 34;
const H = padT + padB + Math.max(rows.length, 1) * rowH;
const dom = cfg.domain || [0, 1];
const innerW = W - padL - padR;
const X = v => padL + (v - dom[0]) / (dom[1] - dom[0]) * innerW;
const ticks = niceTicks(dom[0], dom[1], 5);
let s = '<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" width="100%" role="img" aria-label="' + esc(cfg.title || 'dot plot') + '">';
s += '<title>' + esc(cfg.title || '') + '</title>';
ticks.forEach(t => {
s += '<line class="sv-grid" x1="' + X(t).toFixed(1) + '" y1="' + (padT - 12) + '" x2="' + X(t).toFixed(1) + '" y2="' + (H - padB + 2) + '"/>';
s += '<text class="sv-txt" x="' + X(t).toFixed(1) + '" y="' + (H - padB + 17) + '" text-anchor="middle">' + Math.round(t * 100) + '%</text>';
});
(cfg.refLines || []).forEach(r => {
s += '<line class="sv-ref" x1="' + X(r.v).toFixed(1) + '" y1="' + (padT - 12) + '" x2="' + X(r.v).toFixed(1) + '" y2="' + (H - padB + 2) + '"/>';
if(r.label) s += '<text class="sv-txt" x="' + (X(r.v) + 4) + '" y="' + (padT - 16) + '" fill="var(--warn)">' + esc(r.label) + '</text>';
});
rows.forEach((r, i) => {
const y = padT + i * rowH + rowH / 2;
if(r.sep) s += '<line class="sv-axisline" x1="10" y1="' + (y - rowH/2) + '" x2="' + (W - 10) + '" y2="' + (y - rowH/2) + '" opacity="0.5"/>';
s += '<text class="sv-lbl" x="' + (padL - 66) + '" y="' + (y + 4) + '" text-anchor="end">' + esc(r.label) + '</text>';
s += '<text class="sv-base" x="' + (padL - 8) + '" y="' + (y + 3.5) + '" text-anchor="end">' + esc(r.baseText || '') + '</text>';
const ciCls = r.thin ? 'sv-ci-thin' : 'sv-ci';
if(r.ci){
s += '<line class="' + ciCls + '" x1="' + X(r.ci[0]).toFixed(1) + '" y1="' + y + '" x2="' + X(r.ci[1]).toFixed(1) + '" y2="' + y + '"/>';
s += '<line class="' + ciCls + '" x1="' + X(r.ci[0]).toFixed(1) + '" y1="' + (y - 4) + '" x2="' + X(r.ci[0]).toFixed(1) + '" y2="' + (y + 4) + '"/>';
s += '<line class="' + ciCls + '" x1="' + X(r.ci[1]).toFixed(1) + '" y1="' + (y - 4) + '" x2="' + X(r.ci[1]).toFixed(1) + '" y2="' + (y + 4) + '"/>';
}
s += '<circle class="' + (r.thin ? 'sv-dot-thin' : 'sv-dot') + '" cx="' + X(r.p).toFixed(1) + '" cy="' + y + '" r="4.6"/>';
const vx = X(r.ci ? Math.max(r.ci[1], r.p) : r.p) + 8;
s += '<text class="sv-val" x="' + vx.toFixed(1) + '" y="' + (y + 4) + '">' + pct(r.p) + '</text>';
});
s += '</svg>';
return s;
}
function chartBars(cfg){
const rows = cfg.rows || [];
const W = cfg.width || 760, padL = 216, padR = 70, padT = 26, padB = 34;
const rowH = cfg.rowH || 27;
const H = padT + padB + rows.length * rowH;
const dom = cfg.domain || [0, 1];
const innerW = W - padL - padR;
const X = v => padL + (v - dom[0]) / (dom[1] - dom[0]) * innerW;
const ticks = niceTicks(dom[0], dom[1], 5);
let s = '<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" width="100%" role="img" aria-label="' + esc(cfg.title || 'bar chart') + '">';
s += '<title>' + esc(cfg.title || '') + '</title>';
ticks.forEach(t => {
s += '<line class="sv-grid" x1="' + X(t).toFixed(1) + '" y1="' + (padT - 12) + '" x2="' + X(t).toFixed(1) + '" y2="' + (H - padB + 2) + '"/>';
s += '<text class="sv-txt" x="' + X(t).toFixed(1) + '" y="' + (H - padB + 17) + '" text-anchor="middle">' + Math.round(t * 100) + '%</text>';
});
rows.forEach((r, i) => {
const y = padT + i * rowH + rowH / 2;
const w = Math.max(1, X(r.p) - X(dom[0]));
s += '<text class="sv-lbl" x="' + (padL - 66) + '" y="' + (y + 4) + '" text-anchor="end">' + esc(r.label) + '</text>';
s += '<text class="sv-base" x="' + (padL - 8) + '" y="' + (y + 3.5) + '" text-anchor="end">' + esc(r.baseText || '') + '</text>';
s += '<rect class="sv-bar" x="' + X(dom[0]).toFixed(1) + '" y="' + (y - 7) + '" width="' + w.toFixed(1) + '" height="14" rx="2"/>';
s += '<text class="sv-val" x="' + (X(dom[0]) + w + 8).toFixed(1) + '" y="' + (y + 4) + '">' + pct(r.p) + '</text>';
});
s += '</svg>';
return s;
}
function chartDeviation(cfg){
const rows = cfg.rows || [];
const W = cfg.width || 760, padL = 216, padR = 76, padT = 26, padB = 36;
const rowH = cfg.rowH || 27;
const H = padT + padB + rows.length * rowH;
let maxAbs = 0.02;
rows.forEach(r => { maxAbs = Math.max(maxAbs, Math.abs(r.d), Math.abs(r.lo || 0), Math.abs(r.hi || 0)); });
maxAbs = Math.min(0.5, Math.ceil(maxAbs * 20) / 20);
const dom = [-maxAbs, maxAbs];
const innerW = W - padL - padR;
const X = v => padL + (v - dom[0]) / (dom[1] - dom[0]) * innerW;
const ticks = niceTicks(dom[0], dom[1], 4);
let s = '<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" width="100%" role="img" aria-label="' + esc(cfg.title || 'deviation chart') + '">';
s += '<title>' + esc(cfg.title || '') + '</title>';
ticks.forEach(t => {
s += '<line class="sv-grid" x1="' + X(t).toFixed(1) + '" y1="' + (padT - 12) + '" x2="' + X(t).toFixed(1) + '" y2="' + (H - padB + 2) + '"/>';
s += '<text class="sv-txt" x="' + X(t).toFixed(1) + '" y="' + (H - padB + 18) + '" text-anchor="middle">' + (t > 0 ? '+' : '') + Math.round(t * 100) + '</text>';
});
s += '<line class="sv-zero" x1="' + X(0).toFixed(1) + '" y1="' + (padT - 12) + '" x2="' + X(0).toFixed(1) + '" y2="' + (H - padB + 2) + '"/>';
s += '<text class="sv-txt" x="' + (W - padR + 4) + '" y="' + (H - padB + 18) + '">pp vs national</text>';
rows.forEach((r, i) => {
const y = padT + i * rowH + rowH / 2;
s += '<text class="sv-lbl" x="' + (padL - 66) + '" y="' + (y + 4) + '" text-anchor="end">' + esc(r.label) + '</text>';
s += '<text class="sv-base" x="' + (padL - 8) + '" y="' + (y + 3.5) + '" text-anchor="end">' + esc(r.baseText || '') + '</text>';
const x0 = X(0), x1 = X(r.d);
const barCls = r.d >= 0 ? 'sv-bar' : 'sv-barneg';
s += '<rect class="' + barCls + '" x="' + Math.min(x0, x1).toFixed(1) + '" y="' + (y - 6) + '" width="' + Math.max(1, Math.abs(x1 - x0)).toFixed(1) + '" height="12" rx="2" opacity="0.55"/>';
if(r.lo != null){
const c = r.thin ? 'sv-ci-thin' : 'sv-ci';
s += '<line class="' + c + '" x1="' + X(r.lo).toFixed(1) + '" y1="' + y + '" x2="' + X(r.hi).toFixed(1) + '" y2="' + y + '"/>';
s += '<circle class="' + (r.thin ? 'sv-dot-thin' : 'sv-dot') + '" cx="' + x1.toFixed(1) + '" cy="' + y + '" r="3.6"/>';
}
const lbl = (r.d >= 0 ? '+' : '\u2212') + Math.abs(r.d * 100).toFixed(1);
const lx = r.d >= 0 ? X(r.hi || r.d) + 8 : X(r.lo || r.d) - 8;
s += '<text class="sv-val" x="' + lx.toFixed(1) + '" y="' + (y + 4) + '" text-anchor="' + (r.d >= 0 ? 'start' : 'end') + '">' + lbl + (r.sig ? ' \u25c6' : '') + '</text>';
});
s += '</svg>';
return s;
}
/* ---------------------------- 6 · shell ---------------------------- */
const MODES = [
['data', 'Data & quality'],
['explore', 'Explore (Bertin/Tukey)'],
['atlas', 'Evidence atlas'],
['compare', 'Compare (Cleveland)'],
['brief', 'Briefing deck'],
['public', 'Public output'],
['audit', 'Audit & framing'],
['rubric', 'Rubric']
];
function render(){
const app = $('#app');
const d = State.data;
const nRows = d ? d.rows.length : 0;
let h = '';
h += '<div class="topbar">';
h += '<div class="brand">';
h += '<div class="kicker">Survey visualization engine \u00b7 four-country election study</div>';
h += '<h1>From tabulation to accountable narrative</h1>';
h += '<p class="sub">A working engine for survey research deliverables \u2014 exploratory analysis, evidence atlas, briefing deck, public output, and audit trail, all computed from one dataset in session.</p>';
h += '</div>';
h += '<div class="actions no-print">';
h += '<button class="btn" data-act="set-theme">' + (State.theme === 'evidence' ? '\u25d1 Paper theme' : '\u25d0 Evidence theme') + '</button>';
h += '<button class="btn" data-act="print">\u2399 Print / PDF</button>';
h += '</div></div>';
h += '<nav class="tabs no-print">';
MODES.forEach(m => {
h += '<button data-act="set-mode" data-mode="' + m[0] + '" class="' + (State.mode === m[0] ? 'on' : '') + '">' + esc(m[1]) + '</button>';
});
h += '</nav>';
h += '<div id="stage">' + renderStage() + '</div>';
h += '<footer class="no-print" style="margin-top:26px;padding-top:14px;border-top:1px solid var(--line);font-size:.72rem;color:var(--muted);display:flex;flex-wrap:wrap;gap:14px;justify-content:space-between">';
h += '<span>' + nRows.toLocaleString() + ' respondents \u00b7 ' + (d ? d.questions.length : 0) + ' questions \u00b7 session-only state, no storage.</span>';
h += '<span>Extrapolated design principles \u2014 not endorsements by the named authors.</span>';
h += '</footer>';
app.innerHTML = h;
}
function renderStage(){
switch(State.mode){
case 'data': return viewData();
case 'explore': return viewExplore();
case 'atlas': return viewAtlas();
case 'compare': return viewCompare();
case 'brief': return viewBrief();
case 'public': return viewPublic();
case 'audit': return viewAudit();
case 'rubric': return viewRubric();
default: return viewData();
}
}
function questionControls(){
const d = State.data;
if(!d) return '';
const q = getQ(State.qid);
let h = '<div class="controls no-print">';
h += '<div class="field"><label>Question</label><select data-act="set-q">';
let lastModule = null;
const groups = {};
d.questions.forEach(qq => { (groups[qq.module] = groups[qq.module] || []).push(qq); });
Object.keys(groups).forEach(mod => {
h += '<optgroup label="' + esc(mod) + '">';
groups[mod].forEach(qq => {
h += '<option value="' + qq.id + '"' + (qq.id === State.qid ? ' selected' : '') + '>' + esc(qq.short) + '</option>';
});
h += '</optgroup>';
});
h += '</select></div>';
if(q){
h += '<div class="field"><label>Response option</label><select data-act="set-opt">';
q.opts.forEach((o, i) => { h += '<option value="' + i + '"' + (i === State.opt ? ' selected' : '') + '>' + esc(o) + '</option>'; });
h += '</select></div>';
}
h += '<div class="field"><label>Breakdown</label><select data-act="set-dim">';
[['gender','Gender'],['gen','Generation'],['both','Gender \u00d7 generation'],['none','Country only']].forEach(o => {
h += '<option value="' + o[0] + '"' + (State.dim === o[0] ? ' selected' : '') + '>' + o[1] + '</option>';
});
h += '</select></div>';
h += '<div class="field"><label>Denominator</label><select data-act="set-denom">';
[['all','All respondents'],['top2','Top-2 vote intent'],['top1','Top-1 vote intent']].forEach(o => {
h += '<option value="' + o[0] + '"' + (State.denominator === o[0] ? ' selected' : '') + '>' + o[1] + '</option>';
});
h += '</select></div>';
h += '<div class="field"><label>Suppression n <</label><input type="number" min="0" max="2000" step="10" value="' + State.minBase + '" data-act="set-minbase" style="width:90px"></div>';
h += '</div>';
return h;
}
function provenanceStrip(extra){
const d = State.data;
const q = getQ(State.qid);
let h = '<div class="tiny muted" style="margin:-4px 0 14px;line-height:1.7">';
h += '<b style="color:var(--ink)">Wording:</b> ' + esc(q ? q.text : '\u2014') + '<br>';
h += '<b style="color:var(--ink)">Denominator:</b> ' + esc(denominatorLabel()) + ' \u00b7 ';
h += '<b style="color:var(--ink)">Bases:</b> unweighted n, displayed per row \u00b7 ';
h += '<b style="color:var(--ink)">Uncertainty:</b> 95% interval from Kish effective sample size n\u2091\u1da0\u1da0 = (\u03a3w)\u00b2/\u03a3w\u00b2, so weighting is reflected in precision \u00b7 ';
h += '<b style="color:var(--ink)">Source:</b> ' + esc(d ? d.meta.source : '\u2014') + ' \u00b7 ';
h += '<b style="color:var(--ink)">Suppression:</b> n < ' + State.minBase + ' shown in red and never used for a claim.';
if(extra) h += '<br>' + extra;
h += '</div>';
return h;
}
/* ---------------------------- 7 · view: data ---------------------------- */
function viewData(){
const d = State.data;
let h = '';
h += '<div class="grid2">';
/* source */
h += '<div class="card">';
h += '<h3>1 \u00b7 Evidence source</h3><div class="cap">The engine computes everything from whatever dataset is loaded. Nothing is hard-coded to a finding.</div>';
if(d){
h += '<div class="kv"><span>Dataset</span><b>' + esc(d.meta.source) + '</b></div>';
h += '<div class="kv"><span>Respondents</span><b>' + d.rows.length.toLocaleString() + '</b></div>';
h += '<div class="kv"><span>Questions</span><b>' + d.questions.length + '</b></div>';
const cs = [...new Set(d.rows.map(r => r.country))];
h += '<div class="kv"><span>Markets</span><b>' + cs.map(esc).join(' \u00b7 ') + '</b></div>';
h += '<div class="kv"><span>Generated</span><b>' + esc(d.meta.generated) + '</b></div>';
h += '<p class="tiny muted" style="margin-top:10px">' + esc(d.meta.note) + '</p>';
}
h += '<div class="rule"></div>';
h += '<div class="actions">';
h += '<button class="btn primary" data-act="load-demo">Regenerate demo dataset</button>';
h += '<button class="btn" data-act="show-csv">Paste your own table</button>';
h += '</div>';
if(State.showCsv){
h += '<div style="margin-top:14px">';
h += '<p class="tiny muted" style="margin-bottom:6px">Paste CSV/TSV with a header row. Columns named country, gender, generation/cohort and weight are detected automatically; everything else becomes a question.</p>';
h += '<textarea data-act="csv-text" placeholder="country,gender,generation,weight,q_turnout\nUSA,Female,18-29,1.04,Definitely will vote">' + esc(State.csvText) + '</textarea>';
h += '<div class="actions" style="margin-top:8px"><button class="btn primary" data-act="parse-csv">Parse & analyse</button></div>';
h += '<div class="status">' + esc(State.status) + '</div>';
h += '</div>';
}
if(State.raw){
h += '<div class="rule"></div><div class="eyebrow">Column roles</div>';
h += '<div style="max-height:240px;overflow:auto">';
State.raw.header.forEach((name, i) => {
const r = State.roles[i];
h += '<div class="kv"><span>' + esc(name) + '</span><span>';
h += '<select data-act="set-role" data-col="' + i + '" style="min-width:130px">';
['country','gender','gen','weight','question','ignore'].forEach(role => {
h += '<option value="' + role + '"' + (r === role ? ' selected' : '') + '>' + role + '</option>';
});
h += '</select></span></div>';
});
h += '</div>';
h += '<div class="actions" style="margin-top:10px"><button class="btn" data-act="apply-roles">Rebuild with these roles</button></div>';
}
h += '</div>';
/* quality */
h += '<div class="card">';
h += '<h3>2 \u00b7 Data quality audit</h3><div class="cap">Precedes any claim. This is the Tukey check: distributions, missingness, and bases before cross-national summary.</div>';
if(d){
const miss = d.questions.map(q => {
const n = d.rows.filter(r => r[q.id] == null).length;
return { q, n, rate: n / d.rows.length };
}).sort((a, b) => b.n - a.n);
h += '<div class="eyebrow">Item nonresponse</div>';
h += '<div style="max-height:190px;overflow:auto">';
miss.forEach(m => {
h += '<div class="kv"><span>' + esc(m.q.short) + '</span><b style="color:' + (m.rate > 0.05 ? 'var(--neg)' : 'var(--muted)') + '">' + m.n.toLocaleString() + ' (' + pct(m.rate, 1) + ')</b></div>';
});
h += '</div>';
h += '<div class="rule"></div><div class="eyebrow">Weighting</div>';
const w = d.rows.map(r => +r.weight || 1);
const sumW = w.reduce((a, b) => a + b, 0);
const sumW2 = w.reduce((a, b) => a + b * b, 0);
const neff = sumW * sumW / sumW2;
h += '<div class="kv"><span>Design effect (\u03a3w)\u00b2/\u03a3w\u00b2 vs n)</span><b>' + (d.rows.length / neff).toFixed(2) + '</b></div>';
h += '<div class="kv"><span>Effective sample size</span><b>' + Math.round(neff).toLocaleString() + '</b></div>';
h += '<div class="kv"><span>Weight range</span><b>' + Math.min.apply(null, w).toFixed(2) + ' \u2013 ' + Math.max.apply(null, w).toFixed(2) + '</b></div>';
h += '<div class="rule"></div><div class="eyebrow">Thin cells at current suppression (n < ' + State.minBase + ')</div>';
const a = analyse();
if(a){
const thin = a.cols.filter(c => c.thin);
h += thin.length
? '<p class="tiny">' + thin.length + ' group' + (thin.length === 1 ? '' : 's') + ' fall below the threshold for <b>' + esc(a.q.short) + '</b>: ' + thin.slice(0, 6).map(c => esc(c.country + ' \u00b7 ' + c.sub) + ' (n=' + c.n + ')').join('; ') + (thin.length > 6 ? ' \u2026' : '') + '</p>'
: '<p class="tiny">No cells currently suppressed for this question. Try the gender \u00d7 generation breakdown to see how quickly cells collapse.</p>';
}
}
h += '</div>';
h += '</div>';
/* methodology packet */
h += '<div class="card">';
h += '<h3>3 \u00b7 Methodology packet</h3><div class="cap">Generated from live state. Copy into a report, preregistration, or client email \u2014 this is the provenance layer in text form.</div>';
h += '<pre id="methodsPre" style="white-space:pre-wrap;font-family:ui-monospace,Menlo,monospace;font-size:.72rem;line-height:1.6;color:var(--panel-ink);background:var(--bg2);border:1px solid var(--line);border-radius:var(--radius-sm);padding:14px;max-height:300px;overflow:auto">' + esc(methodologyPacket()) + '</pre>';
h += '<div class="actions" style="margin-top:10px"><button class="btn" data-act="copy-methods">Copy packet</button><button class="btn" data-act="copy-specs">Copy specification registry</button></div>';
h += '<div class="status">' + esc(State.status) + '</div>';
h += '</div>';
/* capability map */
h += '<div class="card">';
h += '<h3>4 \u00b7 What each mode is for</h3><div class="cap">The engine refuses to let one artifact do every job \u2014 the Norman principle, enforced by structure.</div>';
const caps = [
['Explore', 'Bertin matrix + Tukey logging', 'Reorder to reveal configuration; every discovery labelled exploratory and kept out of findings until it survives a second pass.'],
['Evidence atlas', 'Tufte + Cleveland', 'Small multiples with shared scales, wording and bases adjacent to the evidence \u2014 the record nobody can be talked out of.'],
['Compare', 'Cleveland', 'Chart form chosen for the judgment required; levels and differences presented as the distinct quantities they are.'],
['Briefing deck', 'Zelazny + Atkinson + Norman', 'One comparison per slide, headed by the supported finding, never the only route to it.'],
['Public output', 'Holmes + Godin + Bateman', 'A memorable entry point that carries a mandatory caveat and a scale check.'],
['Audit & framing', 'Hullman + Diakopoulos + Drucker + D\'Ignazio + Klein', 'Denominators, orderings, suppressed cells, provenance, and who is missing \u2014 made inspectable rather than assumed.'],
['Rubric', 'Bateman + Borkin + the checklist', 'Marks criteria only when the artifact satisfies them, with an empirical gate that preference cannot override.']
];
h += '<div class="grid4">';
caps.forEach(c => {
h += '<div style="border:1px solid var(--line);border-radius:var(--radius-sm);padding:12px">';
h += '<div class="eyebrow" style="margin-bottom:4px">' + esc(c[0]) + '</div>';
h += '<div class="tiny" style="color:var(--muted);margin-bottom:6px">' + esc(c[1]) + '</div>';
h += '<div class="tiny">' + esc(c[2]) + '</div></div>';
});
h += '</div></div>';
return h;
}
function methodologyPacket(){
const d = State.data;
if(!d) return 'No dataset loaded.';
const w = d.rows.map(r => +r.weight || 1);
const sumW = w.reduce((a, b) => a + b, 0);
const sumW2 = w.reduce((a, b) => a + b * b, 0);
const neff = sumW * sumW / sumW2;
const lines = [
'SURVEY VISUALIZATION ENGINE \u2014 METHODOLOGY PACKET',
'Generated: ' + new Date().toISOString(),
'',
'DATASET',
' Source: ' + d.meta.source,
' Respondents: ' + d.rows.length.toLocaleString(),
' Questions: ' + d.questions.length,
' Markets: ' + [...new Set(d.rows.map(r => r.country))].join(', '),
'',
'ESTIMATION',
' Cell estimates are weighted proportions within the stated population.',
' Uncertainty: 95% interval using Kish effective sample size n_eff = (\u03a3w)\u00b2/\u03a3w\u00b2.',
' Effective n: ' + Math.round(neff).toLocaleString() + ' (design effect ' + (d.rows.length / neff).toFixed(2) + ').',
' A conventional probability-sample margin of error is NOT applied: this design is an opt-in panel and its',
' uncertainty statement must match the sampling and estimation actually used.',
' Differences from a national reference use a normal approximation on the difference of two proportions.',
'',
'DISCLOSURE',
' Suppression threshold: cells with unweighted n < ' + State.minBase + ' are flagged and never carry a claim.',
' Generation is a descriptive grouping. A single wave cannot separate age from cohort; age-band sensitivity',
' is recommended where a generational interpretation would otherwise be offered.',
' Party choice is country-specific and is never pooled onto a common scale with another country.',
' Any pooled four-country total must name its estimand (equal-country average or population-weighted).',
'',
'CURRENT VIEW',
' Question: ' + (getQ(State.qid) ? getQ(State.qid).text : '\u2014'),
' Denominator: ' + denominatorLabel(),
' Breakdown: ' + State.dim,
' Ordering: ' + (State.colOrder ? 'pattern-revealing (reordered in-session)' : 'stable canonical order'),
'',
'PROVENANCE',
' This packet is generated from live session state and reflects the settings in force at the moment of copying.'
];
return lines.join('\n');
}
/* ---------------------------- 8 · view: explore ---------------------------- */
function viewExplore(){
const a = analyse();
if(!a) return '<div class="card"><h3>No dataset loaded.</h3></div>';
const q = a.q;
const optIdx = Math.min(State.opt, q.opts.length - 1);
let h = '';
h += '<div class="card">';
h += '<h3>The reorderable matrix</h3><div class="cap">Rows are response categories; columns are country \u00d7 audience groups. Reorder to ask whether audiences resemble each other across borders more than they resemble their own compatriots.</div>';
h += questionControls();
const cols = a.cols.slice();
const rowOrder = State.rowOrder || q.opts.map((_, i) => i);
let colOrder = cols.slice();
if(State.colOrder && State.colOrder.length === cols.length){
const map = new Map(cols.map(c => [c.key, c]));
colOrder = State.colOrder.map(k => map.get(k)).filter(Boolean);
if(colOrder.length !== cols.length) colOrder = cols.slice();
}
/* vector for each column across options */
const vecOf = c => q.opts.map((_, i) => c.p[i] - 0.5);
const cos = (u, v) => {
let d1 = 0, d2 = 0, d3 = 0;
for(let i = 0; i < u.length; i++){ d1 += u[i]*v[i]; d2 += u[i]*u[i]; d3 += v[i]*v[i]; }
return (d2 && d3) ? d1 / Math.sqrt(d2 * d3) : 0;
};
const orderBySimilarity = (items, vecFn) => {
if(items.length < 3) return items;
const remaining = items.slice(1);
const out = [items[0]];
let last = vecFn(items[0]);
while(remaining.length){
let bi = 0, bv = -Infinity;
remaining.forEach((it, i) => { const v = cos(last, vecFn(it)); if(v > bv){ bv = v; bi = i; } });
const pick = remaining.splice(bi, 1)[0];
out.push(pick);
last = vecFn(pick);
}
return out;
};
h += '<div class="actions" style="margin-bottom:12px">';
h += '<button class="btn" data-act="sort-cols">Reorder columns by pattern</button>';
h += '<button class="btn" data-act="sort-rows">Reorder rows by pattern</button>';
h += '<button class="btn" data-act="reset-order">Restore canonical order</button>';
h += '<span class="badge">' + (State.colOrder ? 'reordered \u2014 logged' : 'canonical order') + '</span>';
h += '</div>';
/* colour scale: deviation from the column's country total */
const natOf = c => a.nat.get(c.country);
const cellVal = (c, optI) => {
if(State.colorMode === 'col'){
const n = natOf(c);
if(c.sub === 'All' || !n) return { v: c.p[optI], d: 0, kind: 'level' };
return { v: c.p[optI], d: c.p[optI] - n.p[optI], kind: 'dev' };
}
const mean = cols.reduce((s, cc) => s + cc.p[optI], 0) / Math.max(cols.length, 1);
return { v: c.p[optI], d: c.p[optI] - mean, kind: 'dev' };
};
const colorOf = d => {
const a2 = clamp(Math.abs(d) / 0.18, 0, 1);
if(d === 0) return 'transparent';
const hue = d > 0 ? 88 : 8;
return 'hsla(' + hue + ',65%,' + (44 + 10 * a2) + '%,' + (0.10 + 0.5 * a2).toFixed(2) + ')';
};
h += '<div class="matrix-wrap"><table class="matrix"><thead><tr>';
h += '<th class="rowh">Response category</th>';
colOrder.forEach(c => {
h += '<th title="' + esc(c.country + ' \u00b7 ' + c.sub + ' \u00b7 n=' + c.n) + '">' + esc(c.country) + '<br><span style="font-weight:400;opacity:.8">' + esc(c.sub === 'All' ? 'total' : c.sub) + '</span><br><span style="font-weight:400;opacity:.6">n=' + c.n + '</span></th>';
});
h += '</tr></thead><tbody>';
rowOrder.forEach(oi => {
h += '<tr><td class="rowh">' + esc(q.opts[oi]) + '</td>';
colOrder.forEach(c => {
const cv = cellVal(c, oi);
const bg = State.colorMode === 'col' && cv.kind === 'level' ? 'transparent' : colorOf(cv.d);
const txt = pct(cv.v);
const sub = (cv.kind === 'dev' && Math.abs(cv.d) >= 0.005) ? '<div style="font-size:.6rem;opacity:.7">' + (cv.d > 0 ? '+' : '\u2212') + Math.abs(cv.d * 100).toFixed(0) + '</div>' : '';
h += '<td style="background:' + bg + ';color:' + (c.thin ? 'var(--neg)' : 'inherit') + '" title="' + esc(c.country + ' \u00b7 ' + c.sub + ' \u00b7 ' + q.opts[oi] + ': ' + pct(cv.v) + ' \u00b1 95% ' + pct(c.ci[oi][0]) + '\u2013' + pct(c.ci[oi][1])) + '">' + txt + sub + '</td>';
});
h += '</tr>';
});
h += '</tbody></table></div>';
h += '<div class="actions" style="margin-top:10px">';
h += '<span class="badge">colour: ' + (State.colorMode === 'col' ? 'deviation from country total' : 'deviation from cross-group mean') + '</span>';
h += '<button class="btn" data-act="toggle-colormode">Switch colour basis</button>';
h += '<span class="badge warn">' + cols.filter(c => c.thin).length + ' suppressed cells</span>';
h += '</div>';
h += provenanceStrip('Colour encodes a <b>deviation</b>; the printed number is always the <b>level</b>. Mixing the two on one unlabelled scale is the classic Bertin failure, so both are shown.');
h += '</div>';
/* cell-mining meter */
const cells = cols.length * q.opts.length;
const thinCells = cols.filter(c => c.thin).length * q.opts.length;
h += '<div class="grid2">';
h += '<div class="card">';
h += '<h3>Cell-mining meter</h3><div class="cap">The largest risk in a cross-tab programme is not a bad chart. It is reading a maximum.</div>';
h += '<div class="kv"><span>Cells on this matrix</span><b>' + cells + '</b></div>';
h += '<div class="kv"><span>Of which suppressed</span><b style="color:var(--neg)">' + thinCells + '</b></div>';
h += '<div class="kv"><span>Confirmatory questions declared</span><b>' + Object.keys(State.confirmatory).filter(k => State.confirmatory[k]).length + '</b></div>';
h += '<div class="rule"></div>';
h += '<p class="tiny">At roughly <b>' + cells + '</b> cells for this one question, several will look remarkable by chance alone. The engine therefore: (1) marks everything here exploratory until a question is declared confirmatory; (2) suppresses cells below n=' + State.minBase + '; (3) never surfaces a maximum as a finding without a declared comparison.</p>';
h += '<div class="rule"></div><div class="eyebrow">Declare confirmatory</div>';
State.data.questions.forEach(qq => {
const on = !!State.confirmatory[qq.id];
h += '<div class="kv"><span>' + esc(qq.short) + '</span><label class="tiny"><input type="checkbox" data-act="toggle-confirm" data-q="' + qq.id + '"' + (on ? ' checked' : '') + '> confirmatory</label></div>';
});
h += '</div>';
/* discovery log */
h += '<div class="card">';
h += '<h3>Discovery log</h3><div class="cap">Tukey’s workbench produces doubts and follow-up tests, not findings. Logged items stay exploratory and are timestamped.</div>';
h += '<div class="actions" style="margin-bottom:10px">';
h += '<input type="text" data-act="log-input" placeholder="e.g. Generation gap looks larger in Canada than UK" style="flex:1;min-width:220px" value="' + esc(State.logDraft || '') + '">';
h += '<button class="btn primary" data-act="add-log">Log observation</button>';
h += '<button class="btn" data-act="clear-log">Clear</button>';
h += '</div>';
if(!State.log.length){
h += '<p class="tiny muted">No entries yet. Anything logged here is labelled exploratory and must survive a second pass before it becomes a claim.</p>';
} else {
State.log.slice().reverse().forEach(l => {
h += '<div class="logitem"><span class="t">' + esc(l.t) + '</span><span>' + esc(l.text) + ' <span class="badge" style="margin-left:6px">exploratory</span></span></div>';
});
}
h += '</div>';
h += '</div>';
return h;
}
/* ---------------------------- 9 · view: atlas ---------------------------- */
function viewAtlas(){
const a = analyse();
if(!a) return '<div class="card"><h3>No dataset loaded.</h3></div>';
const q = a.q;
const optIdx = Math.min(State.opt, q.opts.length - 1);
const countries = [...new Set(a.cols.map(c => c.country))];
let domain = [0, 1];
let minP = 1, maxP = 0;
a.cols.forEach(c => {
if(c.thin) return;
minP = Math.min(minP, c.ci[optIdx][0]);
maxP = Math.max(maxP, c.ci[optIdx][1]);
});
const pad = 0.04;
domain = [clamp(minP - pad, 0, 1), clamp(maxP + pad, 0, 1)];
if(domain[1] - domain[0] < 0.12){ const mid = (domain[0]+domain[1])/2; domain = [clamp(mid-0.06,0,1), clamp(mid+0.06,0,1)]; }
let h = '';
h += '<div class="card">';
h += '<h3>Evidence atlas \u2014 one question, all four countries</h3>';
h += '<div class="cap">Identical graphical structure repeated across panels, common scale, wording and bases adjacent to the evidence. This is the record; the deck is a derivative of it.</div>';
h += questionControls();
h += provenanceStrip('<b>Axis note:</b> the dot-plot scale is cropped to the data (' + Math.round(domain[0]*100) + '\u2013' + Math.round(domain[1]*100) + '%) because position on a common scale tolerates cropping. A bar chart would not.');
h += '<div class="eyebrow">' + esc(q.opts[optIdx]) + ' \u2014 by ' + (State.dim === 'none' ? 'country' : State.dim === 'gender' ? 'gender' : State.dim === 'gen' ? 'generation' : 'gender \u00d7 generation') + '</div>';
h += '<div class="grid2">';
countries.forEach(c => {
const subCols = a.cols.filter(x => x.country === c && x.sub !== 'All');
const nat = a.nat.get(c);
const rows = subCols.map((x, i) => ({
label: x.sub,
baseText: 'n=' + x.n,
p: x.p[optIdx],
ci: x.ci[optIdx],
thin: x.thin,
sep: i === 0
}));
if(!rows.length && nat){
rows.push({ label: 'All respondents', baseText: 'n=' + nat.n, p: nat.p[optIdx], ci: nat.ci[optIdx], thin: nat.thin });
}
const ref = nat && State.dim !== 'none' ? [{ v: nat.p[optIdx], label: 'national ' + pct(nat.p[optIdx]) }] : [];
h += '<div style="border:1px solid var(--line);border-radius:var(--radius-sm);padding:12px 14px">';
h += '<div class="eyebrow" style="margin-bottom:2px">' + esc(c) + '</div>';
h += '<div class="tiny muted" style="margin-bottom:6px">' + (nat ? 'weighted n \u2248 ' + Math.round(nat.nw).toLocaleString() : '') + '</div>';
h += chartDot({ rows, domain, title: c + ' \u2014 ' + q.opts[optIdx], padL: 150, rowH: 26, refLines: ref, width: 520 });
h += '</div>';
});
h += '</div>';
h += '<div class="rule"></div>';
h += '<div class="eyebrow">Full tabulation \u2014 every option, every group</div>';
h += '<div class="matrix-wrap"><table class="matrix"><thead><tr><th class="rowh">Group</th>';
q.opts.forEach(o => { h += '<th>' + esc(o.length > 22 ? o.slice(0, 21) + '\u2026' : o) + '</th>'; });
h += '<th>n</th></tr></thead><tbody>';
a.cols.forEach(c => {
h += '<tr><td class="rowh">' + esc(c.country) + ' \u00b7 ' + esc(c.sub) + '</td>';
q.opts.forEach((o, oi) => { h += '<td>' + pct(c.p[oi], 1) + '</td>'; });
h += '<td style="color:' + (c.thin ? 'var(--neg)' : 'var(--muted)') + '">' + c.n + '</td></tr>';
});
h += '</tbody></table></div>';
h += '</div>';
return h;
}
/* ---------------------------- 10 · view: compare ---------------------------- */
function viewCompare(){
const a = analyse();
if(!a) return '<div class="card"><h3>No dataset loaded.</h3></div>';
const q = a.q;
const optIdx = Math.min(State.opt, q.opts.length - 1);
let h = '';
h += '<div class="card">';
h += '<h3>Statistical comparison</h3><div class="cap">The chart form is chosen for the judgment required, not for variety. Levels and differences are different quantities and are never blended.</div>';
h += questionControls();
h += '<div class="controls no-print">';
h += '<div class="field"><label>Chart form</label><select data-act="set-form">';
[['dot','Dot plot with intervals (levels)'],['bars','Bars from zero (levels)'],['dev','Deviation from national (pp)']].forEach(f => {
h += '<option value="' + f[0] + '"' + (State.chartForm === f[0] ? ' selected' : '') + '>' + f[1] + '</option>';
});
h += '</select></div></div>';
const rows = a.cols.map((c, i) => ({
label: (State.dim === 'none' ? c.country : c.country + ' \u00b7 ' + c.sub),
baseText: 'n=' + c.n,
p: c.p[optIdx],
ci: c.ci[optIdx],
thin: c.thin,
sep: i > 0 && a.cols[i-1].country !== c.country
}));
const devRows = a.cols.filter(c => c.sub !== 'All').map(c => {
const nat = a.nat.get(c.country);
const d = diffFromNational(c, nat, optIdx);
return { label: c.country + ' \u00b7 ' + c.sub, baseText: 'n=' + c.n, d: d.d, lo: d.lo, hi: d.hi, sig: d.sig, thin: c.thin || (nat && nat.thin) };
}).filter(r => Math.abs(r.d) > 1e-9 || true);
h += provenanceStrip();
if(State.chartForm === 'dot'){
h += chartDot({ rows, domain: [0, 1], title: q.opts[optIdx], refLines: [] });
h += '<p class="tiny muted" style="margin-top:8px"><b>Why this form.</b> Position on a common scale is the most accurate judgment available, and intervals can sit on the mark without pretending a bar has a meaningful zero-length end. Cropping the axis would be acceptable here <i>if labelled</i>; the atlas crops, this view does not.</p>';
} else if(State.chartForm === 'bars'){
h += chartBars({ rows, domain: [0, 1], title: q.opts[optIdx] });
h += '<p class="tiny muted" style="margin-top:8px"><b>Why this form, and its cost.</b> Bars must start at zero \u2014 length encodes magnitude, and a truncated bar lies. The price is that intervals cannot be drawn without overloading the mark, so precision disappears from view and lives only in the table above.</p>';
} else {
h += chartDeviation({ rows: devRows, title: 'Difference from national average \u2014 ' + q.opts[optIdx] });
h += '<p class="tiny muted" style="margin-top:8px"><b>Why this form.</b> When the question is “how far apart are the groups?”, the difference is the quantity of interest, not a subtraction the reader must perform. \u25c6 marks a difference outside its 95% interval. The levels remain in the atlas \u2014 this view never replaces them.</p>';
}
h += '<div class="rule"></div><div class="eyebrow">Largest reliable contrasts</div>';
const contrasts = a.cols.filter(c => c.sub !== 'All' && !c.thin).map(c => {
const nat = a.nat.get(c.country);
const d = diffFromNational(c, nat, optIdx);
return { c, nat, d };
}).filter(x => x.nat && x.d.sig && Math.abs(x.d.d) >= 0.04)
.sort((x, y) => Math.abs(y.d.d) - Math.abs(x.d.d))
.slice(0, 6);
if(!contrasts.length){
h += '<p class="tiny muted">No subgroup differs from its national average by more than 4 points at this breakdown and suppression threshold. That is a result, and it should be reported as one.</p>';
} else {
contrasts.forEach(x => {
h += '<div class="kv"><span>' + esc(x.c.country + ' \u00b7 ' + x.c.sub) + '</span><b>' + pct(x.c.p[optIdx]) + ' vs ' + pct(x.nat.p[optIdx]) + ' national \u00b7 <span style="color:' + (x.d.d > 0 ? 'var(--pos)' : 'var(--neg)') + '">' + ppf(x.d.d) + '</span></b></div>';
});
}
h += '</div>';
return h;
}
/* ---------------------------- 11 · view: brief ---------------------------- */
function viewBrief(){
State.visited.brief = true;
const a = analyse();
if(!a) return '<div class="card"><h3>No dataset loaded.</h3></div>';
const q = a.q;
const optIdx = Math.min(State.opt, q.opts.length - 1);
const contrasts = a.cols.filter(c => c.sub !== 'All' && !c.thin).map(c => {
const nat = a.nat.get(c.country);
const d = diffFromNational(c, nat, optIdx);
return { c, nat, d };
}).filter(x => x.nat && Math.abs(x.d.d) >= 0.03)
.sort((x, y) => Math.abs(y.d.d) - Math.abs(x.d.d))
.slice(0, 6);
const natRows = [...a.nat.values()].map(c => ({ label: c.country, baseText: 'n=' + c.n, p: c.p[optIdx], ci: c.ci[optIdx], thin: c.thin }));
let h = '';
h += '<div class="card">';
h += '<h3>Briefing deck \u2014 generated from live state</h3><div class="cap">One comparison per slide, headline written as the supported finding, qualification attached at the point of the claim. Print to PDF to export.</div>';
h += questionControls();
h += provenanceStrip();
h += '<div class="actions no-print"><button class="btn" data-act="print">Print deck</button></div>';
h += '</div>';
/* slide 1 */
h += '<div class="slide"><div class="snum">Slide 1 \u00b7 The question</div>';
h += '<h4>' + esc(q.text) + '</h4>';
h += '<p class="tiny muted">Asked in the USA, Canada, the UK and Australia. Nationally weighted. Denominator: ' + esc(denominatorLabel()) + '.</p>';
h += '<div class="so-what">Reported as <b>' + esc(q.opts[optIdx]) + '</b> across ' + a.nat.size + ' countries. Each country carries its own fielding context and its own party system; only shared constructs are compared directly.</div>';
h += '</div>';
/* slide 2 */
h += '<div class="slide"><div class="snum">Slide 2 \u00b7 The common picture</div>';
const hi = natRows.slice().sort((x, y) => y.p - x.p)[0];
const lo = natRows.slice().sort((x, y) => x.p - y.p)[0];
h += '<h4>' + esc(q.opts[optIdx]) + ' ranges from ' + pct(lo.p) + ' in ' + esc(lo.label) + ' to ' + pct(hi.p) + ' in ' + esc(hi.label) + '</h4>';
h += chartDot({ rows: natRows, domain: [0, 1], title: 'National totals', padL: 170, rowH: 30, width: 560 });
h += '<div class="so-what">A ' + Math.abs((hi.p - lo.p) * 100).toFixed(0) + '-point spread across four comparable national samples. Intervals shown; overlapping intervals mean the ordering is not yet a claim.</div>';
h += '</div>';
/* contrasts */
contrasts.forEach((x, i) => {
const rows2 = [
{ label: x.c.country + ' national', baseText: 'n=' + x.nat.n, p: x.nat.p[optIdx], ci: x.nat.ci[optIdx], thin: x.nat.thin },
{ label: x.c.sub, baseText: 'n=' + x.c.n, p: x.c.p[optIdx], ci: x.c.ci[optIdx], thin: x.c.thin }
];
h += '<div class="slide"><div class="snum">Slide ' + (3 + i) + ' \u00b7 The difference that complicates it</div>';
h += '<h4>' + esc(x.c.sub) + ' in ' + esc(x.c.country) + ' differ from their national average by ' + ppf(x.d.d) + '</h4>';
h += chartDot({ rows: rows2, domain: [0, 1], title: x.c.sub, padL: 190, rowH: 30, width: 520 });
h += '<div class="so-what">' + pct(x.c.p[optIdx]) + ' against a national ' + pct(x.nat.p[optIdx]) + '. ' + (x.d.sig ? 'The difference sits outside its 95% interval.' : 'The difference is <b>inside</b> its 95% interval \u2014 shown because it is on the slide, not because it is established.') + ' Base of ' + x.c.n + ' respondents.</div>';
h += '</div>';
});
/* limits */
const thinList = a.cols.filter(c => c.thin);
h += '<div class="slide"><div class="snum">Slide ' + (3 + contrasts.length) + ' \u00b7 The limits of the evidence</div>';
h += '<h4>What this survey cannot settle</h4>';
h += '<ul style="font-size:.82rem;line-height:1.8;padding-left:1.1rem;color:var(--panel-ink)">';
h += '<li>A single wave cannot separate age from cohort. The generation labels are descriptive groupings, not explanations.</li>';
h += '<li>Cross-sectional association is not direction. Engagement, trust and information habit covary here without an arrow between them.</li>';
h += '<li>' + (thinList.length ? thinList.length + ' group(s) fall below the suppression threshold (n < ' + State.minBase + ') and are excluded from every claim on these slides.' : 'No groups currently fall below the suppression threshold, but the intersection breakdown will produce some.') + '</li>';
h += '<li>The instrument measures stated turnout intention and stated vote intention, not verified behaviour.</li>';
h += '</ul>';
h += '<div class="so-what">Alternative readings remain visible on the slide rather than exiled to a handout \u2014 the difference between a story and a narrowing.</div>';
h += '</div>';
return h;
}
/* ---------------------------- 12 · view: public ---------------------------- */
function viewPublic(){
State.visited.public = true;
const a = analyse();
if(!a) return '<div class="card"><h3>No dataset loaded.</h3></div>';
const q = a.q;
const optIdx = Math.min(State.opt, q.opts.length - 1);
const countries = [...a.nat.keys()];
let h = '';
h += '<div class="card">';
h += '<h3>Public-facing output</h3><div class="cap">Memorable entry point, conventional encoding underneath, mandatory caveat attached at the same moment as the number. Illustration is allowed; distortion is not.</div>';
h += questionControls();
h += provenanceStrip();
h += '<div class="actions no-print"><button class="btn" data-act="print">Print / export</button></div>';
h += '</div>';
h += '<div class="grid4" style="margin-bottom:16px">';
countries.forEach((c, i) => {
const nat = a.nat.get(c);
if(!nat) return;
const v = nat.p[optIdx];
const ci = nat.ci[optIdx];
h += '<div class="bignum">';
h += '<div class="c">' + esc(c) + '</div>';
h += '<div class="v" style="color:var(--s' + ((i % 5) + 1) + ')">' + pct(v) + '</div>';
h += '<div class="d">' + esc(q.opts[optIdx]) + '</div>';
h += '<div class="d" style="opacity:.7;margin-top:4px">95% ' + pct(ci[0]) + '\u2013' + pct(ci[1]) + ' \u00b7 n=' + nat.n + '</div>';
h += '</div>';
});
h += '</div>';
h += '<div class="card">';
h += '<h3>The shareable line</h3><div class="cap">One sentence that survives a screenshot \u2014 because it carries its own qualification.</div>';
const sorted = [...a.nat.values()].sort((x, y) => y.p[optIdx] - x.p[optIdx]);
const top = sorted[0], bottom = sorted[sorted.length - 1];
const gap = top && bottom ? Math.abs(top.p[optIdx] - bottom.p[optIdx]) : 0;
h += '<p style="font-size:1.05rem;line-height:1.6;font-family:var(--font-display);font-weight:400">';
h += '\u201c' + pct(top.p[optIdx]) + ' of adults in ' + esc(top.country) + ' say they would ' + esc(q.opts[optIdx]).toLowerCase() + ', against ' + pct(bottom.p[optIdx]) + ' in ' + esc(bottom.country) + ' \u2014 a ' + (gap * 100).toFixed(0) + '-point gap that sits within the combined uncertainty of the two estimates.\u201d';
h += '</p>';
h += '<div class="caveat"><b>Scale check.</b> Every number above is encoded by a printed numeral and a labelled bar, not by icon area or colour saturation. ' +
(gap > 0.1 ? 'The gap is large enough that the headline could lead with it.' : 'The gap is small; the headline must lead with the level, not the comparison.') +
' Illustration may sit beside these cards but never replaces the numeral.</div>';
h += '<div class="caveat"><b>What a public reader is not told here, and where to find it.</b> Fielding method, weighting, suppression, the full question battery and every cross-tab are in the evidence atlas and audit layers. This card is an entry point, not a record.</div>';
h += '</div>';
h += '<div class="card">';
h += '<h3>Engagement test \u2014 Bateman gate</h3><div class="cap">Bateman’s results license <i>testing</i> embellishment, not assuming it. The gate is deliberately concrete.</div>';
h += '<div class="kv"><span>Plain vs illustrated version tested?</span><b class="badge no">not run</b></div>';
h += '<div class="kv"><span>Immediate comprehension measured?</span><b class="badge no">not run</b></div>';
h += '<div class="kv"><span>Recall of the finding measured?</span><b class="badge no">not run</b></div>';
h += '<div class="kv"><span>Recall of the <i>caveat</i> measured?</span><b class="badge no">not run</b></div>';
h += '<div class="kv"><span>Delayed retention measured?</span><b class="badge no">not run</b></div>';
h += '<p class="tiny muted" style="margin-top:10px">Until this is run, the illustrated and the plain cards are both defensible choices and neither is a finding. Record it in the rubric rather than settling it by preference.</p>';
h += '</div>';
return h;
}
/* ---------------------------- 13 · view: audit ---------------------------- */
function viewAudit(){
const a = analyse();
if(!a) return '<div class="card"><h3>No dataset loaded.</h3></div>';
const q = a.q;
const optIdx = Math.min(State.opt, q.opts.length - 1);
const thin = a.cols.filter(c => c.thin);
let h = '';
h += '<div class="card">';
h += '<h3>Framing audit</h3><div class="cap">Every design choice frames. The engine computes these checks from live state rather than asking anyone to remember them.</div>';
h += questionControls();
const checks = [];
checks.push(['The denominator is named at the point of the claim', true, denominatorLabel()]);
checks.push(['Every displayed estimate carries its unweighted base', true, 'shown per row on every chart']);
checks.push(['Uncertainty is displayed with the estimate', State.chartForm !== 'bars', State.chartForm === 'bars' ? 'bar view drops intervals by design \u2014 precision lives only in the table' : '95% intervals drawn on every mark']);
checks.push(['Bars start at zero; cropped axes are used only for position encodings', true, State.chartForm === 'bars' ? 'bars from 0' : 'dot/deviation views crop and label the range']);
checks.push(['Response ordering is disclosed', true, 'canonical order unless reordered in Explore, which is logged']);
checks.push(['Thin cells are suppressed rather than silently recoded', State.minBase > 0, 'threshold n < ' + State.minBase]);
checks.push(['Any pooled four-country total names its estimand', true, 'no pooled total is computed anywhere in this engine']);
checks.push(['Generation is presented as description, not explanation', true, 'birth-band labels shown; single wave cannot separate age from cohort']);
checks.push(['Exploratory and confirmatory analyses are visibly separated', Object.keys(State.confirmatory).filter(k => State.confirmatory[k]).length > 0, Object.keys(State.confirmatory).filter(k => State.confirmatory[k]).length + ' question(s) declared confirmatory']);
checks.push(['Reordering is reversible and logged', State.log.length > 0 || !State.colOrder, State.colOrder ? 'reordered in session; reset available' : 'canonical order in force']);
checks.push(['Every published chart is in the specification registry', State.specs.length > 0, State.specs.length + ' chart specifications logged']);
h += '<div>';
checks.forEach(c => {
h += '<div class="crit">';
h += '<span style="color:' + (c[1] ? 'var(--pos)' : 'var(--neg)') + ';font-weight:700;font-size:.9rem;line-height:1.3">' + (c[1] ? '\u2713' : '\u2717') + '</span>';
h += '<div class="txt">' + esc(c[0]) + '<div class="why">' + esc(c[2]) + '</div></div>';
h += '</div>';
});
h += '</div>';
h += '</div>';
h += '<div class="grid2">';
/* who is missing */
h += '<div class="card">';
h += '<h3>Who is missing</h3><div class="cap">Not a footnote. A named list, computed from the data actually present.</div>';
const genderCounts = {};
State.data.rows.forEach(r => { genderCounts[r.gender || 'Unknown'] = (genderCounts[r.gender || 'Unknown'] || 0) + 1; });
Object.keys(genderCounts).forEach(g => {
const n = genderCounts[g];
h += '<div class="kv"><span>Gender: ' + esc(g) + '</span><b style="color:' + (n < State.minBase ? 'var(--neg)' : 'var(--muted)') + '">' + n + (n < State.minBase ? ' \u2014 suppressed' : '') + '</b></div>';
});
const genCounts = {};
State.data.rows.forEach(r => { genCounts[r.gen || 'Unknown'] = (genCounts[r.gen || 'Unknown'] || 0) + 1; });
Object.keys(genCounts).sort().forEach(g => {
h += '<div class="kv"><span>Generation band: ' + esc(g) + '</span><b>' + genCounts[g] + '</b></div>';
});
h += '<div class="rule"></div>';
h += '<p class="tiny"><b>Excluded by design, and must be stated:</b> populations without internet access from which the panel is drawn; people below the minimum age; and, in a real fielding, territories and institutions outside the sampling frame. The engine can only report this if the collector supplies it \u2014 it is listed here so the omission is deliberate rather than accidental.</p>';
h += '<div class="rule"></div>';
h += '<div class="eyebrow">Suppressed at current settings</div>';
h += thin.length
? thin.map(c => '<div class="kv"><span>' + esc(c.country + ' \u00b7 ' + c.sub) + '</span><b style="color:var(--neg)">n=' + c.n + '</b></div>').join('')
: '<p class="tiny muted">None for this question and breakdown. Switch to gender \u00d7 generation to see suppression activate.</p>';
h += '</div>';
/* denominator */
h += '<div class="card">';
h += '<h3>Inspect the denominator</h3><div class="cap">The same cell under three populations is three different quantities, not three versions of one truth.</div>';
const variants = [
['all', 'All respondents'],
['top2', 'Top-2 vote intent'],
['top1', 'Top-1 vote intent']
];
const saved = State.denominator;
variants.forEach(v => {
State.denominator = v[0];
const aa = analyse();
State.denominator = saved;
if(!aa) return;
h += '<div class="rule" style="margin:8px 0"></div>';
h += '<div class="eyebrow">' + esc(v[1]) + '</div>';
let countryRows = '';
[...aa.nat.values()].forEach(c => {
countryRows += '<div class="kv"><span>' + esc(c.country) + '</span><b>' + pct(c.p[optIdx]) + ' <span class="muted tiny">n=' + c.n + '</span></b></div>';
});
h += countryRows;
});
h += '<p class="tiny muted" style="margin-top:10px">Switching the denominator recomputes every number in this engine. That is the point: the choice is consequential and therefore has to be visible rather than buried in a methods note.</p>';
h += '</div>';
h += '</div>';
/* provenance / registry */
h += '<div class="card">';
h += '<h3>Specification registry</h3><div class="cap">Every chart the engine renders is logged with the specification behind it. Audit is generated, not maintained by hand.</div>';
if(!State.specs.length){
h += '<p class="tiny muted">Nothing logged yet. Change a setting in Explore, Compare, Briefing or Public and the specification is recorded.</p>';
} else {
h += '<div class="matrix-wrap"><table class="matrix"><thead><tr><th class="rowh">Time</th><th>View</th><th>Question</th><th>Denominator</th><th>Ordering</th><th>Form</th></tr></thead><tbody>';
State.specs.slice().reverse().slice(0, 20).forEach(s => {
h += '<tr><td class="rowh">' + esc(s.t) + '</td><td>' + esc(s.view) + '</td><td>' + esc(s.q) + '</td><td>' + esc(s.denom) + '</td><td>' + esc(s.order) + '</td><td>' + esc(s.form) + '</td></tr>';
});
h += '</tbody></table></div>';
}
h += '<div class="actions" style="margin-top:10px"><button class="btn" data-act="copy-specs">Copy registry as text</button></div>';
h += '<div class="status">' + esc(State.status) + '</div>';
h += '</div>';
/* category construction */
h += '<div class="card">';
h += '<h3>Category construction</h3><div class="cap">The table is not a container. It is an argument made of categories \u2014 so the categories are shown.</div>';
h += '<div class="grid2">';
h += '<div><div class="eyebrow">Generation bands as collected</div>';
[...new Set(State.data.rows.map(r => r.gen))].sort().forEach(g => {
h += '<div class="kv"><span>' + esc(g) + '</span><b>descriptive grouping</b></div>';
});
h += '<p class="tiny muted" style="margin-top:8px">One wave cannot separate age from cohort. Where a generational interpretation is offered, publish an age-band sensitivity view alongside it.</p></div>';
h += '<div><div class="eyebrow">Question wording, as fielded</div>';
State.data.questions.forEach(qq => {
h += '<div style="padding:.4rem 0;border-bottom:1px solid var(--line);font-size:.75rem"><b>' + esc(qq.short) + '</b><br><span class="muted">' + esc(qq.text) + '</span></div>';
});
h += '</div></div></div>';
return h;
}
/* ---------------------------- 14 · view: rubric ---------------------------- */
const RUBRIC = [
{ key:'r1', layer:'Record', text:'Comparisons are forced: national totals sit beside subgroup estimates on common scales.', auto:() => State.dim !== 'none', why:() => State.dim !== 'none' ? 'a breakdown is active' : 'set a breakdown other than "country only"' },
{ key:'r2', layer:'Record', text:'Every display carries its question wording, denominator, base and uncertainty adjacent to the evidence.', auto:() => State.chartForm !== 'bars', why:() => State.chartForm === 'bars' ? 'bar view drops intervals' : 'wording, denominator and bases are drawn on every chart' },
{ key:'r3', layer:'Record', text:'Chart form matches the comparison being made.', auto:() => State.chartForm === 'dot' || State.chartForm === 'dev', why:() => 'position and difference encodings are available' },
{ key:'r4', layer:'Record', text:'Raw descriptive estimates and adjusted estimates are never blended.', auto:() => true, why:() => 'this engine reports weighted descriptives only and labels them as such' },
{ key:'r5', layer:'Record', text:'Thin cells are suppressed rather than silently recoded.', auto:() => State.minBase > 0, why:() => 'threshold n < ' + State.minBase },
{ key:'r6', layer:'Explore', text:'Rows and columns are reorderable; ordering is reversible and machine suggestions are inspectable.', auto:() => true, why:() => 'reordering available in Explore, reset always present' },
{ key:'r7', layer:'Explore', text:'Exploratory discoveries are visibly separated from preplanned confirmatory analyses.', auto:() => Object.keys(State.confirmatory).filter(k => State.confirmatory[k]).length > 0, why:() => Object.keys(State.confirmatory).filter(k => State.confirmatory[k]).length + ' declared confirmatory' },
{ key:'r8', layer:'Explore', text:'Distribution checks, missingness and bases precede any cross-national summary.', auto:() => true, why:() => 'the quality audit is the default entry view' },
{ key:'r9', layer:'Explain', text:'Three coordinated artifacts exist: briefing, evidence document, reference package.', auto:() => State.visited.brief, why:() => State.visited.brief ? 'briefing deck generated' : 'visit the briefing deck' },
{ key:'r10', layer:'Explain', text:'Each slide carries one comparison; headlines state the supported finding.', auto:() => State.visited.brief, why:() => 'generated slides are one-comparison-per-card' },
{ key:'r11', layer:'Explain', text:'Public output carries a caveat and a scale check at the point of the number.', auto:() => State.visited.public, why:() => State.visited.public ? 'public view generated with caveat strip' : 'visit the public output view' },
{ key:'r12', layer:'Account', text:'A published finding can be audited: question, population, calculation, base, uncertainty, alternative framing.', auto:() => true, why:() => 'the audit layer computes this from live state' },
{ key:'r13', layer:'Account', text:'Consequential analytical choices are enumerated and switchable.', auto:() => State.denominator !== 'all', why:() => State.denominator !== 'all' ? 'denominator switched in session' : 'try a denominator other than "all respondents"' },
{ key:'r14', layer:'Account', text:'Category construction is part of the story: wording, operationalisation, visible missingness.', auto:() => true, why:() => 'wording and bands listed in the audit layer' },
{ key:'r15', layer:'Account', text:'"Who is missing" is answered frankly rather than silently recoded away.', auto:() => true, why:() => 'computed from the data present, including suppressed cells' },
{ key:'r16', layer:'Account', text:'Provenance is documented: who commissioned, collected, cleaned, coded, interpreted.', auto:() => State.specs.length > 0, why:() => State.specs.length ? State.specs.length + ' specifications logged' : 'interact with a chart view to populate the registry' }
];
const GATE = [
{ key:'g1', text:'At least one version of each flagship deliverable has been tested with its intended readership.', by:'Bateman' },
{ key:'g2', text:'Memorability is treated as a designed, tested outcome, distinct from precision.', by:'Borkin' },
{ key:'g3', text:'Test results, not preference or house style, decide whether embellishment stays.', by:'Bateman \u00b7 Borkin' }
];
function viewRubric(){
let pass = 0, total = 0;
const rows = RUBRIC.map(r => {
let ok;
try { ok = !!r.auto(); } catch(e) { ok = false; }
total++;
if(ok) pass++;
return { r, ok };
});
GATE.forEach(g => { total++; if(State.manual[g.key]) pass++; });
const pctDone = Math.round(pass / total * 100);
const C = 2 * Math.PI * 38;
let h = '';
h += '<div class="card">';
h += '<div class="ring-wrap">';
h += '<svg width="92" height="92" viewBox="0 0 92 92" role="img" aria-label="Rubric completion"><circle cx="46" cy="46" r="38" fill="none" stroke="var(--line)" stroke-width="9"/><circle cx="46" cy="46" r="38" fill="none" stroke="var(--accent)" stroke-width="9" stroke-linecap="round" stroke-dasharray="' + C.toFixed(2) + '" stroke-dashoffset="' + (C * (1 - pass / total)).toFixed(2) + '" transform="rotate(-90 46 46)"/></svg>';
h += '<div><div class="ring-txt">' + pctDone + '%</div><div class="tiny muted">' + pass + ' / ' + total + ' criteria satisfied by the artifact</div></div>';
h += '</div>';
h += '<p class="tiny muted" style="margin-top:12px">Auto-evaluated criteria reflect live session state. A criterion is marked only when something in the artifact satisfies it \u2014 not when the intention was stated in a meeting. Unchecked items are backlog, not failure.</p>';
h += '</div>';
const layers = ['Record','Explore','Explain','Account'];
layers.forEach(layer => {
h += '<div class="card">';
h += '<h3>' + esc(layer) + ' layer</h3>';
rows.filter(x => x.r.layer === layer).forEach(x => {
h += '<div class="crit">';
h += '<span style="color:' + (x.ok ? 'var(--pos)' : 'var(--neg)') + ';font-weight:700">' + (x.ok ? '\u2713' : '\u25cb') + '</span>';
h += '<div class="txt">' + esc(x.r.text) + '<div class="why">' + esc(x.r.why()) + '</div></div>';
h += '</div>';
});
h += '</div>';
});
h += '<div class="card" style="border-color:var(--warn)">';
h += '<h3>Cross-cutting empirical gate</h3><div class="cap">Applies to every layer. These three cannot be auto-satisfied \u2014 they require someone to actually run a study.</div>';
GATE.forEach(g => {
h += '<div class="crit">';
h += '<input type="checkbox" data-act="manual" data-key="' + g.key + '"' + (State.manual[g.key] ? ' checked' : '') + '>';
h += '<div class="txt">' + esc(g.text) + '<div class="why">' + esc(g.by) + '</div></div>';
h += '</div>';
});
h += '</div>';
return h;
}
/* ---------------------------- 15 · events ---------------------------- */
function logSpec(view){
const q = getQ(State.qid);
State.specs.push({
t: nowTime(),
view,
q: q ? q.short : '\u2014',
denom: denominatorLabel(),
order: State.colOrder ? 'reordered' : 'canonical',
form: State.mode === 'compare' ? State.chartForm : State.mode
});
if(State.specs.length > 200) State.specs.shift();
}
function copyText(text, label){
try {
if(navigator.clipboard && navigator.clipboard.writeText){
navigator.clipboard.writeText(text).then(
() => { State.status = label + ' copied.'; render(); },
() => { State.status = 'Clipboard blocked in this frame \u2014 select the text and copy manually.'; render(); }
);
return;
}
throw new Error('no clipboard');
} catch(e){
State.status = 'Clipboard unavailable \u2014 select the text block and copy manually.';
render();
}
}
document.addEventListener('click', e => {
const el = e.target.closest('[data-act]');
if(!el) return;
const act = el.dataset.act;
if(act === 'set-mode'){ State.mode = el.dataset.mode; logSpec(State.mode); render(); return; }
if(act === 'set-theme'){ State.theme = State.theme === 'evidence' ? 'paper' : 'evidence'; document.body.dataset.theme = State.theme; render(); return; }
if(act === 'print'){ window.print(); return; }
if(act === 'load-demo'){ State.seedUsed = Math.floor(Math.random() * 1e8); State.data = buildDemo(State.seedUsed); State.qid = State.data.questions[0].id; State.opt = 0; State.colOrder = null; State.rowOrder = null; State.raw = null; State.status = 'Demo dataset regenerated (seed ' + State.seedUsed + ').'; render(); return; }
if(act === 'show-csv'){ State.showCsv = !State.showCsv; render(); return; }
if(act === 'parse-csv'){
const raw = parseCSV(State.csvText || '');
if(!raw || raw.header.length < 2){ State.status = 'Could not parse a table with at least two columns.'; render(); return; }
State.raw = raw;
State.roles = raw.header.map(guessRole);
if(State.roles.indexOf('question') < 0) State.roles[State.roles.length - 1] = 'question';
State.data = buildFromRaw(State.raw, State.roles);
if(!State.data.questions.length){ State.status = 'No usable question columns found.'; render(); return; }
State.qid = State.data.questions[0].id; State.opt = 0; State.colOrder = null; State.rowOrder = null;
State.status = 'Parsed ' + State.data.rows.length + ' rows and ' + State.data.questions.length + ' questions.';
render(); return;
}
if(act === 'apply-roles'){
if(!State.raw) return;
State.data = buildFromRaw(State.raw, State.roles);
if(State.data.questions.length){ State.qid = State.data.questions[0].id; State.opt = 0; State.status = 'Rebuilt with new column roles.'; }
else State.status = 'No question columns remain after reassignment.';
render(); return;
}
if(act === 'set-q'){ /* handled on change */ return; }
if(act === 'copy-methods'){ copyText(methodologyPacket(), 'Methodology packet'); return; }
if(act === 'copy-specs'){
const txt = State.specs.length
? 'SPECIFICATION REGISTRY\n\n' + State.specs.map(s => [s.t, s.view, s.q, s.denom, s.order, s.form].join(' | ')).join('\n')
: 'No specifications logged in this session.';
copyText(txt, 'Specification registry');
return;
}
if(act === 'sort-cols'){
const a = analyse();
if(!a) return;
const vecOf = c => a.q.opts.map((_, i) => c.p[i] - 0.5);
const items = a.cols.slice();
if(items.length > 2){
const cos = (u, v) => { let d1 = 0, d2 = 0, d3 = 0; for(let i = 0; i < u.length; i++){ d1 += u[i]*v[i]; d2 += u[i]*u[i]; d3 += v[i]*v[i]; } return (d2 && d3) ? d1/Math.sqrt(d2*d3) : 0; };
const out = [items[0]];
const rest = items.slice(1);
let last = vecOf(items[0]);
while(rest.length){
let bi = 0, bv = -Infinity;
rest.forEach((it, i) => { const v = cos(last, vecOf(it)); if(v > bv){ bv = v; bi = i; } });
const pick = rest.splice(bi, 1)[0];
out.push(pick); last = vecOf(pick);
}
State.colOrder = out.map(c => c.key);
}
State.log.push({ t: nowTime(), text: 'Columns reordered by response similarity (exploratory).' });
logSpec('explore'); render(); return;
}
if(act === 'sort-rows'){
const a = analyse();
if(!a) return;
const cols = a.cols;
const prof = i => cols.map(c => c.p[i] - 0.5);
const idx = a.q.opts.map((_, i) => i);
const cos = (u, v) => { let d1 = 0, d2 = 0, d3 = 0; for(let i = 0; i < u.length; i++){ d1 += u[i]*v[i]; d2 += u[i]*u[i]; d3 += v[i]*v[i]; } return (d2 && d3) ? d1/Math.sqrt(d2*d3) : 0; };
const out = [idx[0]];
const rest = idx.slice(1);
let last = prof(idx[0]);
while(rest.length){
let bi = 0, bv = -Infinity;
rest.forEach((it, i) => { const v = cos(last, prof(it)); if(v > bv){ bv = v; bi = i; } });
const pick = rest.splice(bi, 1)[0];
out.push(pick); last = prof(pick);
}
State.rowOrder = out;
State.log.push({ t: nowTime(), text: 'Response rows reordered by profile similarity (exploratory).' });
render(); return;
}
if(act === 'reset-order'){ State.colOrder = null; State.rowOrder = null; State.log.push({ t: nowTime(), text: 'Ordering restored to canonical.' }); render(); return; }
if(act === 'toggle-colormode'){ State.colorMode = State.colorMode === 'col' ? 'row' : 'col'; render(); return; }
if(act === 'add-log'){
const v = State.logDraft || '';
if(v.trim()){ State.log.push({ t: nowTime(), text: v.trim() }); State.logDraft = ''; }
render(); return;
}
if(act === 'clear-log'){ State.log = []; render(); return; }
if(act === 'manual'){ State.manual[el.dataset.key] = el.checked; render(); return; }
if(act === 'toggle-confirm'){ State.confirmatory[el.dataset.q] = el.checked; render(); return; }
});
document.addEventListener('change', e => {
const el = e.target;
const act = el.dataset ? el.dataset.act : null;
if(!act) return;
if(act === 'set-q'){ State.qid = el.value; State.opt = 0; State.colOrder = null; State.rowOrder = null; logSpec('question change'); render(); return; }
if(act === 'set-opt'){ State.opt = +el.value; logSpec('option change'); render(); return; }
if(act === 'set-dim'){ State.dim = el.value; State.colOrder = null; logSpec('breakdown change'); render(); return; }
if(act === 'set-denom'){ State.denominator = el.value; State.colOrder = null; logSpec('denominator change'); render(); return; }
if(act === 'set-minbase'){ State.minBase = Math.max(0, +el.value || 0); render(); return; }
if(act === 'set-form'){ State.chartForm = el.value; logSpec('chart form change'); render(); return; }
if(act === 'set-role'){ State.roles[+el.dataset.col] = el.value; return; }
if(act === 'manual'){ State.manual[el.dataset.key] = el.checked; render(); return; }
if(act === 'toggle-confirm'){ State.confirmatory[el.dataset.q] = el.checked; render(); return; }
});
document.addEventListener('input', e => {
const el = e.target;
if(!el.dataset || !el.dataset.act) return;
if(el.dataset.act === 'csv-text'){ State.csvText = el.value; }
if(el.dataset.act === 'log-input'){ State.logDraft = el.value; }
});
/* ---------------------------- 16 · boot ---------------------------- */
(function boot(){
State.data = buildDemo(State.seedUsed);
State.qid = State.data.questions[0].id;
State.opt = 0;
document.body.dataset.theme = State.theme;
render();
})();
</script>
</body>
</html>
<script data-huggingchat-badge="script">
(function () {
try {
if (document.querySelector("[data-huggingchat-badge]:not(script)")) return;
var host = document.createElement("div");
host.setAttribute("data-huggingchat-badge", "");
var styles = [["all","initial"],["position","fixed"],["right","12px"],["bottom","12px"],["z-index","2147483647"],["display","block"],["visibility","visible"],["opacity","1"],["pointer-events","auto"],["width","auto"],["height","auto"],["margin","0"],["padding","0"],["max-width","none"],["max-height","none"],["transform","none"],["filter","none"],["clip-path","none"],["color-scheme","light"]];
for (var i = 0; i < styles.length; i++) {
host.style.setProperty(styles[i][0], styles[i][1], "important");
}
host.attachShadow({ mode: "closed" }).innerHTML = "<style>\n:host { all: initial; }\na {\n display: flex;\n align-items: center;\n gap: 5px;\n box-sizing: border-box;\n height: 26px;\n padding: 0 9px 0 7px;\n border-radius: 999px;\n border: 1px solid rgba(0, 0, 0, 0.07);\n background: rgba(255, 255, 255, 0.92);\n -webkit-backdrop-filter: saturate(180%) blur(8px);\n backdrop-filter: saturate(180%) blur(8px);\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08), 0 6px 16px rgba(0, 0, 0, 0.06);\n color: #111827;\n font: 500 11px/1 ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif;\n text-decoration: none;\n white-space: nowrap;\n opacity: 0.72;\n transition: opacity 0.15s ease, transform 0.15s ease;\n}\na:hover, a:focus-visible { opacity: 1; transform: translateY(-1px); }\nsvg { width: 14px; height: 14px; flex: none; }\n@media print { a { display: none; } }\n<\/style><a href=\"https://huggingface.co/chat\" target=\"_blank\" rel=\"noopener noreferrer nofollow\"><svg viewBox=\"0 0 32 32\" fill=\"none\" aria-hidden=\"true\"><path d=\"M16.0006 25.9992C13.8266 25.999 11.7118 25.2901 9.97686 23.9799C8.2419 22.6698 6.98127 20.8298 6.38599 18.7388C5.79071 16.6478 5.89323 14.4198 6.678 12.3923C7.46278 10.3648 8.88705 8.64837 10.735 7.50308C12.5829 6.35779 14.7538 5.84606 16.9187 6.04544C19.0837 6.24481 21.1246 7.14442 22.7323 8.60795C24.34 10.0715 25.4268 12.0192 25.8281 14.1559C26.2293 16.2926 25.9232 18.5019 24.9561 20.449C24.7703 20.8042 24.7223 21.2155 24.8211 21.604L25.4211 23.8316C25.4803 24.0518 25.4805 24.2837 25.4216 24.5039C25.3627 24.7242 25.2468 24.925 25.0856 25.0862C24.9244 25.2474 24.7235 25.3633 24.5033 25.4222C24.283 25.4811 24.0512 25.4809 23.831 25.4217L21.6034 24.8217C21.2172 24.7248 20.809 24.7729 20.4558 24.9567C19.0683 25.6467 17.5457 26.0068 16.0006 26.0068V25.9992Z\" fill=\"currentColor\"/><path d=\"M9.62598 16.0013C9.62598 15.3799 10.1294 14.8765 10.7508 14.8765C11.3721 14.8765 11.8756 15.3799 11.8756 16.0013C11.8756 17.0953 12.3102 18.1448 13.0838 18.9184C13.8574 19.692 14.9069 20.1266 16.001 20.1267C17.095 20.1267 18.1445 19.692 18.9181 18.9184C19.6918 18.1448 20.1264 17.0953 20.1264 16.0013C20.1264 15.3799 20.6299 14.8765 21.2512 14.8765C21.8725 14.8765 22.3759 15.3799 22.3759 16.0013C22.3759 17.6921 21.7046 19.3137 20.509 20.5093C19.3134 21.7049 17.6918 22.3762 16.001 22.3762C14.3102 22.3762 12.6885 21.7049 11.4929 20.5093C10.2974 19.3137 9.62598 17.6921 9.62598 16.0013Z\" fill=\"#fff\"/><\/svg><span>Made with HuggingChat<\/span><\/a>";
function attach() {
var parent = document.body || document.documentElement;
if (parent && host.parentNode !== parent) parent.appendChild(host);
}
attach();
// Artifacts that rewrite document.body wholesale would drop the badge.
if (document.body && typeof MutationObserver === "function") {
new MutationObserver(attach).observe(document.body, { childList: true });
} else {
document.addEventListener("DOMContentLoaded", attach);
}
} catch (e) {}
})();
</script>
|