-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
931 lines (850 loc) · 46.6 KB
/
Copy pathindex.html
File metadata and controls
931 lines (850 loc) · 46.6 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Power BI Data Modeling, Explained — Cardinality, Filter Direction & Filter Context</title>
<style>
:root{
--brand-red:#CF3338;
--brand-red-dark:#C00000;
--bg-light:#EEECE1;
--text-body:#707070;
--text-dark:#1F2120;
--white:#FFFFFF;
--font-heading:'Pragmatica','Arial Black',Arial,sans-serif;
--font-body:Arial,Helvetica,sans-serif;
--font-mono:Consolas,'Courier New',monospace;
--dim:#3a6ea5; /* used only sparingly for the "one" side chip text on white tables */
--line:#d8d5c7;
--shadow:0 2px 10px rgba(31,33,32,.08);
--shadow-lg:0 8px 30px rgba(31,33,32,.16);
}
*{box-sizing:border-box}
html,body{margin:0;padding:0}
body{
font-family:var(--font-body);
color:var(--text-dark);
background:var(--bg-light);
line-height:1.5;
-webkit-font-smoothing:antialiased;
}
.topbar{
border-top:6px solid var(--brand-red);
background:var(--white);
box-shadow:var(--shadow);
position:sticky;top:0;z-index:50;
}
.topbar-inner{
max-width:1080px;margin:0 auto;padding:14px 24px;
display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;
}
.brandless-title{
font-family:var(--font-heading);font-weight:900;letter-spacing:.02em;
color:var(--text-dark);font-size:16px;
}
nav.tabs{display:flex;gap:4px;flex-wrap:wrap}
nav.tabs button{
font-family:var(--font-body);font-size:13px;font-weight:700;
border:none;background:transparent;color:var(--text-body);
padding:9px 14px;border-radius:6px;cursor:pointer;transition:.15s;
border-bottom:3px solid transparent;
}
nav.tabs button:hover{color:var(--text-dark);background:var(--bg-light)}
nav.tabs button.active{color:var(--brand-red);border-bottom-color:var(--brand-red)}
header.hero{
max-width:1080px;margin:0 auto;padding:38px 24px 8px;
}
header.hero h1{
font-family:var(--font-heading);font-weight:900;color:var(--brand-red);
font-size:34px;line-height:1.1;margin:0 0 10px;
}
header.hero p.lede{
color:var(--text-body);font-size:16px;max-width:680px;margin:0;
}
main{max-width:1080px;margin:0 auto;padding:8px 24px 80px}
.scene{display:none;animation:fade .25s ease}
.scene.active{display:block}
@keyframes fade{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
.scene h2{
font-family:var(--font-heading);font-weight:900;color:var(--text-dark);
font-size:24px;margin:28px 0 6px;
}
.scene .sub{color:var(--text-body);font-size:15px;margin:0 0 18px;max-width:760px}
.panel{
background:var(--white);border-radius:12px;box-shadow:var(--shadow);
padding:22px;margin:16px 0;position:relative;
}
.panel.stage{overflow:visible}
.controls{
display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:0 0 18px;
}
.seg{display:inline-flex;background:var(--bg-light);border-radius:8px;padding:4px;gap:2px}
.seg button{
border:none;background:transparent;font-family:var(--font-body);font-size:13px;font-weight:700;
color:var(--text-body);padding:7px 13px;border-radius:6px;cursor:pointer;transition:.15s;
}
.seg button.active{background:var(--brand-red);color:#fff;box-shadow:var(--shadow)}
.seg button:not(.active):hover{color:var(--text-dark)}
.toggle{display:inline-flex;align-items:center;gap:8px;font-size:13px;font-weight:700;color:var(--text-body);cursor:pointer;user-select:none}
.toggle input{display:none}
.toggle .track{width:42px;height:24px;border-radius:12px;background:#cfccbe;position:relative;transition:.2s}
.toggle .track::after{content:"";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:#fff;box-shadow:var(--shadow);transition:.2s}
.toggle input:checked + .track{background:var(--brand-red)}
.toggle input:checked + .track::after{transform:translateX(18px)}
.btn{
font-family:var(--font-body);font-size:13px;font-weight:700;border:none;cursor:pointer;
padding:9px 16px;border-radius:8px;transition:.15s;
}
.btn.primary{background:var(--brand-red);color:#fff;box-shadow:var(--shadow)}
.btn.primary:hover{background:var(--brand-red-dark)}
.btn.ghost{background:var(--bg-light);color:var(--text-dark)}
.btn.ghost:hover{background:#e2dfd1}
.btn:disabled{opacity:.4;cursor:default}
/* ---- data tables ---- */
.tablewrap{display:inline-block;vertical-align:top}
table.dm{
border-collapse:separate;border-spacing:0;background:#fff;border-radius:10px;overflow:hidden;
box-shadow:0 0 0 1px var(--line), var(--shadow);font-size:13px;min-width:200px;
}
table.dm caption{
caption-side:top;text-align:left;font-family:var(--font-mono);font-weight:700;font-size:13px;
color:var(--text-dark);padding:0 0 8px 2px;display:flex;align-items:center;gap:8px;
}
table.dm caption .role{
font-family:var(--font-body);font-size:10px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;
padding:2px 7px;border-radius:10px;
}
.role.fact{background:#fde7e7;color:var(--brand-red)}
.role.dim{background:#e8eef5;color:var(--dim)}
table.dm th{
background:var(--text-dark);color:#fff;font-weight:700;text-align:left;padding:8px 12px;font-size:11px;
letter-spacing:.04em;text-transform:uppercase;
}
table.dm td{padding:7px 12px;border-bottom:1px solid var(--line);color:var(--text-dark);white-space:nowrap}
table.dm tr:last-child td{border-bottom:none}
table.dm td.key{font-family:var(--font-mono);font-weight:700}
table.dm td.num{text-align:right;font-variant-numeric:tabular-nums}
/* clickable dimension rows */
table.dm.pick tbody tr{cursor:pointer;transition:background .15s}
table.dm.pick tbody tr:hover{background:#faf6ee}
table.dm tbody tr.sel{background:#fff3d6 !important;box-shadow:inset 3px 0 0 var(--brand-red)}
table.dm tbody tr.match{background:#fde7e7 !important;animation:pop .4s ease}
table.dm tbody tr.dim-out{opacity:.32;filter:grayscale(.4)}
@keyframes pop{0%{background:#fff}40%{background:#f8c9ca}100%{background:#fde7e7}}
/* ---- relationship stage ---- */
.stage-grid{
display:grid;grid-template-columns:1fr auto 1fr;gap:0;align-items:start;
position:relative;
}
.stage-col{display:flex;flex-direction:column;align-items:center;gap:6px;min-width:0}
.rel-mid{
align-self:center;display:flex;flex-direction:column;align-items:center;justify-content:center;
padding:0 6px;min-width:120px;position:relative;
}
.rel-line{
width:100%;height:3px;background:linear-gradient(90deg,var(--dim),var(--brand-red));border-radius:2px;position:relative;
}
.rel-line .one,.rel-line .star{
position:absolute;top:-9px;font-family:var(--font-mono);font-weight:900;font-size:16px;color:var(--text-dark);
}
.rel-line .one{left:-2px}
.rel-line .star{right:-2px;color:var(--brand-red);font-size:20px;top:-12px}
.rel-arrow{font-size:12px;color:var(--text-body);margin-top:10px;text-align:center;font-weight:700;line-height:1.3}
.rel-arrow .dir{color:var(--brand-red)}
svg.flow{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible;z-index:5}
.pulse-dot{fill:var(--brand-red);filter:drop-shadow(0 0 6px rgba(207,51,56,.8))}
/* measure readout */
.measure{
margin-top:16px;background:var(--text-dark);color:#fff;border-radius:10px;padding:16px 20px;
display:flex;align-items:baseline;gap:14px;flex-wrap:wrap;
}
.measure .label{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:#c9c6bb;font-weight:700}
.measure .val{font-family:var(--font-heading);font-weight:900;font-size:40px;color:#fff;font-variant-numeric:tabular-nums;line-height:1}
.measure .val .cur{color:var(--brand-red)}
.measure .ctx{font-family:var(--font-mono);font-size:12px;color:#ffd9da;margin-left:auto}
.callout{
border-left:4px solid var(--brand-red);background:#fff;border-radius:0 8px 8px 0;
padding:12px 16px;margin:14px 0;font-size:14px;color:var(--text-dark);box-shadow:var(--shadow);
}
.callout strong{color:var(--brand-red)}
.narrate{
min-height:24px;font-size:14px;font-weight:700;color:var(--brand-red);margin:14px 0 0;transition:.2s;
}
.hint{font-size:13px;color:var(--text-body);font-style:italic}
/* pivot / filter context */
table.pivot{border-collapse:separate;border-spacing:0;background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 0 0 1px var(--line),var(--shadow);font-size:14px}
table.pivot th{background:var(--text-dark);color:#fff;padding:9px 16px;text-align:right;font-size:12px;letter-spacing:.04em}
table.pivot th.rowhdr{text-align:left}
table.pivot td{padding:9px 16px;border-bottom:1px solid var(--line);text-align:right;font-variant-numeric:tabular-nums}
table.pivot td.rowlbl{text-align:left;font-weight:700;color:var(--text-dark)}
table.pivot tr.total td{background:var(--bg-light);font-weight:800}
table.pivot td.flash{animation:cellflash .6s ease}
@keyframes cellflash{0%{background:#fff3d6}100%{background:transparent}}
table.pivot td.calc{color:var(--brand-red);font-weight:700}
.slicer{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:6px}
.slicer button{
border:1.5px solid var(--line);background:#fff;border-radius:20px;padding:7px 16px;font-size:13px;font-weight:700;
color:var(--text-body);cursor:pointer;transition:.15s;
}
.slicer button:hover{border-color:var(--brand-red);color:var(--brand-red)}
.slicer button.on{background:var(--brand-red);border-color:var(--brand-red);color:#fff}
.twocol{display:grid;grid-template-columns:1fr 1fr;gap:22px;align-items:start}
/* On narrow screens keep the relationship side-by-side (the whole point) and scroll horizontally
instead of stacking — stacking would break the connector geometry and rotate the arrow. */
.panel.stage{overflow-x:auto;overflow-y:visible}
@media(max-width:760px){
.twocol{grid-template-columns:1fr}
.stage-grid{min-width:620px}
header.hero h1{font-size:27px}
.scene h2{font-size:21px}
}
code.dax{font-family:var(--font-mono);background:var(--bg-light);padding:2px 6px;border-radius:4px;color:var(--text-dark);font-size:13px}
pre.dax{font-family:var(--font-mono);background:var(--text-dark);color:#f2efe6;padding:14px 18px;border-radius:10px;font-size:13px;overflow:auto;margin:12px 0}
pre.dax .fn{color:#ff8a8d;font-weight:700}
pre.dax .col{color:#ffd9da}
pre.dax .cmt{color:#9b988c}
.legend{display:flex;gap:18px;flex-wrap:wrap;font-size:12px;color:var(--text-body);margin-top:14px}
.legend span{display:inline-flex;align-items:center;gap:6px}
.legend i{width:14px;height:14px;border-radius:3px;display:inline-block}
footer{max-width:1080px;margin:0 auto;padding:30px 24px 60px;color:var(--text-body);font-size:13px;border-top:1px solid var(--line)}
footer a{color:var(--brand-red)}
.kbd{font-family:var(--font-mono);background:var(--bg-light);border:1px solid var(--line);border-radius:4px;padding:1px 6px;font-size:12px}
</style>
</head>
<body>
<div class="topbar">
<div class="topbar-inner">
<div class="brandless-title">Data Modeling, Explained</div>
<nav class="tabs" id="tabs">
<button data-scene="intro" class="active">Start here</button>
<button data-scene="cardinality">1 · Cardinality</button>
<button data-scene="direction">2 · Filter direction</button>
<button data-scene="context">3 · Filter context</button>
</nav>
</div>
</div>
<header class="hero">
<h1>Power BI Data Modeling, Explained</h1>
<p class="lede">Three ideas trip up almost everyone learning the Data Model: <strong>cardinality</strong>, <strong>filter direction</strong>, and <strong>filter context</strong>. They're hard to teach on static slides because they're really about <em>movement</em> — filters flowing from one table to another. So let's make them move.</p>
</header>
<main>
<!-- ======================= INTRO ======================= -->
<section class="scene active" id="scene-intro">
<div class="panel">
<h2 style="margin-top:6px">The one model we'll use the whole way through</h2>
<p class="sub">Everything below uses the same little star schema from <em>Modern Data Analytics in Excel</em>: an <strong>orders</strong> fact table and a <strong>users</strong> dimension table, joined on <code class="dax">Region</code>. Get this picture in your head and the three concepts fall out of it.</p>
<div class="panel stage" style="box-shadow:none;padding:8px 0">
<div class="stage-grid" id="introStage">
<div class="stage-col">
<div class="tablewrap">
<table class="dm" id="introUsers">
<caption>users <span class="role dim">dimension · the "one" side</span></caption>
<thead><tr><th>Region</th><th>Manager</th></tr></thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="rel-mid">
<div class="rel-line"><span class="one">1</span><span class="star">✲</span></div>
<div class="rel-arrow">Region<br><span class="dir">one → many</span></div>
</div>
<div class="stage-col">
<div class="tablewrap">
<table class="dm" id="introOrders">
<caption>orders <span class="role fact">fact · the "many" side</span></caption>
<thead><tr><th>Order</th><th>Region</th><th>Sales</th></tr></thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="callout" style="margin-top:22px">
Read the relationship line like a sentence: <strong>one</strong> region in <code class="dax">users</code> (the <strong>1</strong>) connects to <strong>many</strong> rows in <code class="dax">orders</code> (the <strong>✲</strong>). That single line is doing three jobs at once — and each tab below pulls one of those jobs into focus.
</div>
<div class="twocol" style="margin-top:8px">
<div class="callout" style="border-color:var(--text-dark)">
<strong style="color:var(--text-dark)">① Cardinality</strong> — <em>how many</em> rows on each side of the line. One manager, many orders. This is the <code class="dax">1</code> and the <code class="dax">✲</code>.
</div>
<div class="callout" style="border-color:var(--text-dark)">
<strong style="color:var(--text-dark)">② Filter direction</strong> — <em>which way</em> a filter travels along the line. Down the arrow, from the one to the many.
</div>
</div>
<div class="callout" style="border-color:var(--text-dark);margin-top:0">
<strong style="color:var(--text-dark)">③ Filter context</strong> — <em>what's selected right now</em> when a number is calculated. Every value in a report is computed inside a filter context, and the relationship line is how that context spreads to the fact table.
</div>
<button class="btn primary" style="margin-top:12px" onclick="go('cardinality')">Start with cardinality →</button>
</div>
</section>
<!-- ======================= CARDINALITY ======================= -->
<section class="scene" id="scene-cardinality">
<h2>① Cardinality — how many match how many</h2>
<p class="sub">Cardinality is just <strong>the count of matching rows on each side of a relationship</strong>. Pick a row on the left and watch how many rows it lights up on the right. Switch the relationship type to feel the difference.</p>
<div class="controls">
<div class="seg" id="cardSeg">
<button data-card="one" class="active">One-to-one</button>
<button data-card="many">One-to-many</button>
<button data-card="m2m">Many-to-many</button>
</div>
<span class="hint" id="cardHint">Click a row in the left table.</span>
</div>
<div class="panel stage">
<svg class="flow" id="cardSvg"></svg>
<div class="stage-grid" id="cardStage">
<div class="stage-col">
<div class="tablewrap"><div id="cardLeft"></div></div>
</div>
<div class="rel-mid">
<div class="rel-line"><span class="one" id="cardLeftCard">1</span><span class="star" id="cardRightCard">1</span></div>
<div class="rel-arrow" id="cardRelLabel">Product ID</div>
</div>
<div class="stage-col">
<div class="tablewrap"><div id="cardRight"></div></div>
</div>
</div>
<p class="narrate" id="cardNarrate"> </p>
<div class="legend">
<span><i style="background:#fff3d6;box-shadow:inset 3px 0 0 var(--brand-red)"></i> the row you picked</span>
<span><i style="background:#fde7e7"></i> rows it matches</span>
<span><i style="background:#e9e7db"></i> filtered out</span>
</div>
</div>
<div class="callout" id="cardExplain"></div>
<div class="panel" id="bridgePanel" style="display:none">
<h2 style="font-size:18px;margin-top:0">Why many-to-many needs a bridge table</h2>
<p class="sub" style="margin-bottom:14px">A customer can hit many promotions, and a promotion has many customers — so neither side is a clean "one." Power Pivot can't model that directly. The fix from the book: a <strong>bridge table</strong> that lists each pairing once, turning one tangled many-to-many into two tidy one-to-manys.</p>
<div class="stage-grid">
<div class="stage-col"><div class="tablewrap"><div id="bridgeCust"></div></div></div>
<div class="rel-mid"><div class="rel-line"><span class="one">1</span><span class="star">✲</span></div><div class="rel-arrow">Customer</div></div>
<div class="stage-col"><div class="tablewrap"><div id="bridgeMid"></div></div></div>
<div class="rel-mid"><div class="rel-line"><span class="one">✲</span><span class="star" style="color:var(--dim)">1</span></div><div class="rel-arrow">Promotion</div></div>
<div class="stage-col"><div class="tablewrap"><div id="bridgePromo"></div></div></div>
</div>
</div>
<div class="callout" style="border-color:var(--text-dark)">
<strong style="color:var(--text-dark)">The teaching line:</strong> Power Pivot is built for <strong>one-to-many</strong>. The whole point of splitting data into a fact table and dimension tables is to get clean one-to-many relationships — one row per region in <code class="dax">users</code>, many matching rows in <code class="dax">orders</code>. Hold onto the <em>direction</em> of that match; it's exactly what the next tab is about.
</div>
<button class="btn primary" onclick="go('direction')">Next: which way does a filter travel? →</button>
</section>
<!-- ======================= FILTER DIRECTION ======================= -->
<section class="scene" id="scene-direction">
<h2>② Filter direction — the arrow on the line</h2>
<p class="sub">That relationship line has an arrowhead, and it points from the <strong>one</strong> side to the <strong>many</strong> side. Filters slide <em>down</em> the arrow, never back up it by default. Click a region in <code class="dax">users</code> and watch the filter travel into <code class="dax">orders</code>.</p>
<div class="controls">
<span class="hint">Filter from:</span>
<div class="seg" id="dirSeg">
<button data-from="users" class="active">users (the "one")</button>
<button data-from="orders">orders (the "many")</button>
</div>
<label class="toggle">
<input type="checkbox" id="biDir" />
<span class="track"></span>
<span>Both-directions filter</span>
</label>
<button class="btn ghost" id="dirReset">Clear filter</button>
</div>
<div class="panel stage">
<svg class="flow" id="dirSvg"></svg>
<div class="stage-grid" id="dirStage">
<div class="stage-col">
<div class="tablewrap">
<table class="dm pick" id="dirUsers">
<caption>users <span class="role dim">the "one"</span></caption>
<thead><tr><th>Region</th><th>Manager</th></tr></thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="rel-mid">
<div class="rel-line" id="dirLine"><span class="one">1</span><span class="star">✲</span></div>
<div class="rel-arrow">Region<br><span class="dir" id="dirArrow">users → orders</span></div>
</div>
<div class="stage-col">
<div class="tablewrap">
<table class="dm pick" id="dirOrders">
<caption>orders <span class="role fact">the "many"</span></caption>
<thead><tr><th>Order</th><th>Region</th><th>Sales</th></tr></thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
<div class="measure">
<span class="label">Total Sales</span>
<span class="val">$<span id="dirMeasure">0</span></span>
<span class="ctx" id="dirCtx">no filter — all regions</span>
</div>
<p class="narrate" id="dirNarrate"> </p>
</div>
<div class="callout" id="dirExplain">
Pick a region on the left to see the filter flow.
</div>
<div class="twocol">
<div class="callout" style="border-color:var(--text-dark)">
<strong style="color:var(--text-dark)">Why default to one direction?</strong> Filtering from the <em>few</em> rows (regions) to the <em>many</em> rows (orders) is fast and unambiguous. Going the other way is slower and often means something. That's why Power Pivot locks it to single-direction and Power BI defaults to it.
</div>
<div class="callout" style="border-color:var(--text-dark)">
<strong style="color:var(--text-dark)">Need it to go both ways?</strong> Flip the toggle above — that's bidirectional cross-filtering (the <code class="dax">CROSSFILTER()</code> escape hatch the book mentions). Handy, but use it sparingly: it can create ambiguity in bigger models.
</div>
</div>
<button class="btn primary" onclick="go('context')">Next: how a number knows what to add up →</button>
</section>
<!-- ======================= FILTER CONTEXT ======================= -->
<section class="scene" id="scene-context">
<h2>③ Filter context — what's selected when a number is calculated</h2>
<p class="sub">Every number in a report is computed inside a <strong>filter context</strong>: the set of filters in force at that exact spot — the slicer, the row it's on, the column it's under. Change the context and the number recalculates. Click the slicer and watch.</p>
<div class="panel">
<p class="hint" style="margin-top:0">Region slicer — click to filter the whole report (click again to clear):</p>
<div class="slicer" id="ctxSlicer"></div>
<div class="twocol" style="margin-top:18px">
<div>
<table class="pivot" id="ctxPivot" style="width:100%">
<thead>
<tr><th class="rowhdr">Manager</th><th>Total Sales</th><th>Express Air<br><span style="font-weight:400;font-size:10px;color:#c9c6bb">CALCULATE</span></th><th>All-Region Sales<br><span style="font-weight:400;font-size:10px;color:#c9c6bb">CALCULATE+ALL</span></th></tr>
</thead>
<tbody></tbody>
</table>
</div>
<div>
<div class="callout" style="margin-top:0">
<strong>Watch the columns react differently.</strong>
<ul style="margin:8px 0 0;padding-left:18px;color:var(--text-body)">
<li><strong style="color:var(--text-dark)">Total Sales</strong> obeys the filter context completely — slicer <em>and</em> row.</li>
<li><strong style="color:var(--brand-red)">Express Air</strong> uses <code class="dax">CALCULATE</code> to <em>add</em> a Ship Mode filter on top of the context.</li>
<li><strong style="color:var(--brand-red)">All-Region Sales</strong> uses <code class="dax">CALCULATE(…, ALL())</code> to <em>ignore</em> the region slicer — it stays put no matter what you click.</li>
</ul>
</div>
<pre class="dax"><span class="cmt">-- obeys whatever context it lands in</span>
Total Sales = <span class="fn">SUM</span>( orders[<span class="col">Sales</span>] )
<span class="cmt">-- ADDS a filter to the current context</span>
Express Air =
<span class="fn">CALCULATE</span>( [Total Sales],
orders[<span class="col">Ship Mode</span>] = "Express Air" )
<span class="cmt">-- REMOVES the region filter from context</span>
All-Region Sales =
<span class="fn">CALCULATE</span>( [Total Sales], <span class="fn">ALL</span>( users[<span class="col">Region</span>] ) )</pre>
</div>
</div>
<p class="narrate" id="ctxNarrate">Right now the filter context is: <strong>everything</strong> (no slicer). Each manager row still adds its own region context.</p>
</div>
<div class="callout" style="border-color:var(--text-dark)">
<strong style="color:var(--text-dark)">Tie it together:</strong> the slicer sets a filter context on <code class="dax">users</code>. <strong>Filter direction</strong> (tab 2) carries that context down the relationship into <code class="dax">orders</code>. <strong>Cardinality</strong> (tab 1) is what makes that flow safe — one region, many orders. <code class="dax">CALCULATE</code> is simply how you rewrite the context on purpose: add to it, or clear it with <code class="dax">ALL</code>.
</div>
<button class="btn ghost" onclick="go('intro')">↺ Back to the overview</button>
</section>
</main>
<footer>
Built for teaching from <em>Modern Data Analytics in Excel</em>. Same <code class="dax">users</code>/<code class="dax">orders</code> model as Chapter 7. Open this file in any browser — nothing to install. Inspired in spirit by Garrick Aden-Buie's <a href="https://www.garrickadenbuie.com/project/tidyexplain/">tidyexplain</a> animations.
</footer>
<script>
/* ============================================================
DATA — the book's users / orders star schema
============================================================ */
const REGIONS = {
Central: {manager:"Mariana", color:"#CF3338"},
East: {manager:"Daniel", color:"#3a6ea5"},
West: {manager:"Sofia", color:"#5a8f4e"}
};
const users = [
{region:"Central", manager:"Mariana"},
{region:"East", manager:"Daniel"},
{region:"West", manager:"Sofia"}
];
// orders fact table — multiple per region
const orders = [
{id:"#1001", region:"Central", sales:420, ship:"Express Air", prio:"High"},
{id:"#1002", region:"East", sales:155, ship:"Regular Air", prio:"Low"},
{id:"#1003", region:"Central", sales:980, ship:"Regular Air", prio:"High"},
{id:"#1004", region:"West", sales:240, ship:"Express Air", prio:"Medium"},
{id:"#1005", region:"East", sales:610, ship:"Express Air", prio:"High"},
{id:"#1006", region:"West", sales:330, ship:"Regular Air", prio:"Low"},
{id:"#1007", region:"Central", sales:75, ship:"Regular Air", prio:"Medium"},
{id:"#1008", region:"East", sales:520, ship:"Regular Air", prio:"Medium"},
{id:"#1009", region:"West", sales:145, ship:"Express Air", prio:"High"}
];
const fmt = n => n.toLocaleString("en-US");
/* ============================================================
TAB NAVIGATION
============================================================ */
const tabs = document.getElementById("tabs");
function go(scene){
document.querySelectorAll(".scene").forEach(s=>s.classList.toggle("active", s.id==="scene-"+scene));
tabs.querySelectorAll("button").forEach(b=>b.classList.toggle("active", b.dataset.scene===scene));
window.scrollTo({top:0, behavior:"smooth"});
if(scene==="direction") setTimeout(drawDirLine, 60);
if(scene==="cardinality") setTimeout(()=>renderCard(), 60);
}
tabs.addEventListener("click", e=>{ if(e.target.dataset.scene) go(e.target.dataset.scene); });
/* ============================================================
INTRO stage tables
============================================================ */
(function renderIntro(){
const ub = document.querySelector("#introUsers tbody");
ub.innerHTML = users.map(u=>`<tr><td class="key">${u.region}</td><td>${u.manager}</td></tr>`).join("");
const ob = document.querySelector("#introOrders tbody");
ob.innerHTML = orders.map(o=>`<tr><td>${o.id}</td><td class="key">${o.region}</td><td class="num">$${o.sales}</td></tr>`).join("");
})();
/* ============================================================
SCENE 1 — CARDINALITY
============================================================ */
const cardData = {
one: {
label:"Product ID",
leftCap:`product_details <span class="role dim">one row each</span>`,
rightCap:`supplier_details <span class="role dim">one row each</span>`,
leftHead:["Product ID","Product"], rightHead:["Product ID","Supplier"],
left:[["P-01","Stapler"],["P-02","Notebook"],["P-03","Monitor"],["P-04","Chair"]],
right:[["P-01","Acme Co."],["P-02","BrightPaper"],["P-03","Visio Ltd."],["P-04","SeatWorks"]],
leftKey:0, rightKey:0,
lc:"1", rc:"1",
explain:`<strong>One-to-one:</strong> each Product ID shows up exactly once on <em>both</em> sides. Pick any product and it matches a single supplier row. Clean, but redundant — the book notes you'd usually just merge these into one table. Power Pivot doesn't even offer 1:1; it's tuned for one-to-many.`
},
many: {
label:"Region",
leftCap:`users <span class="role dim">dimension · the "one"</span>`,
rightCap:`orders <span class="role fact">fact · the "many"</span>`,
leftHead:["Region","Manager"], rightHead:["Order","Region","Sales"],
left: users.map(u=>[u.region,u.manager]),
right: orders.map(o=>[o.id,o.region,"$"+o.sales]),
leftKey:0, rightKey:1,
lc:"1", rc:"✲",
explain:`<strong>One-to-many:</strong> one region in <code class="dax">users</code> matches <em>several</em> rows in <code class="dax">orders</code>. This is the workhorse of every Data Model — pick "Central" and watch all its orders light up. The single matched row on the left is the <strong>1</strong>; the cluster on the right is the <strong>✲</strong> (many).`
},
m2m: {
label:"Customer ↔ Promotion",
leftCap:`customers <span class="role dim">many sides</span>`,
rightCap:`purchases <span class="role fact">many sides</span>`,
leftHead:["Customer","City"], rightHead:["Customer","Promotion"],
left:[["Ava","Austin"],["Ben","Boston"],["Cleo","Austin"]],
right:[["Ava","Spring Sale"],["Ava","Holiday"],["Ben","Spring Sale"],["Cleo","Holiday"],["Cleo","Spring Sale"]],
leftKey:0, rightKey:0,
lc:"✲", rc:"✲",
explain:`<strong>Many-to-many:</strong> Ava appears in several promotions, and each promotion has several customers. Neither side is a unique "one," so a direct relationship is ambiguous — Power Pivot won't allow it. The fix is a <strong>bridge table</strong> (shown below) that lists each customer–promotion pairing once.`
}
};
let cardType = "one";
let cardSel = null;
function renderCard(){
const d = cardData[cardType];
document.getElementById("cardLeftCard").textContent = d.lc;
document.getElementById("cardRightCard").textContent = d.rc;
document.getElementById("cardRightCard").style.color = d.rc==="✲" ? "var(--brand-red)" : "var(--dim)";
document.getElementById("cardRelLabel").textContent = d.label;
document.getElementById("cardExplain").innerHTML = d.explain;
document.getElementById("bridgePanel").style.display = cardType==="m2m" ? "block" : "none";
document.getElementById("cardLeft").innerHTML = buildTable(d.leftCap, d.leftHead, d.left, true, d.leftKey);
document.getElementById("cardRight").innerHTML = buildTable(d.rightCap, d.rightHead, d.right, false, d.rightKey);
// wire clicks on left rows
document.querySelectorAll("#cardLeft table tbody tr").forEach((tr,i)=>{
tr.addEventListener("click", ()=>pickCard(i));
});
cardSel = null;
document.getElementById("cardNarrate").innerHTML = " ";
clearSvg("cardSvg");
if(cardType==="m2m") renderBridge();
}
function buildTable(caption, head, rows, pick, keyCol){
const ths = head.map(h=>`<th>${h}</th>`).join("");
const trs = rows.map((r,ri)=>{
const tds = r.map((c,ci)=>{
const cls = ci===keyCol ? "key" : (String(c).startsWith("$") ? "num":"");
return `<td class="${cls}">${c}</td>`;
}).join("");
return `<tr data-i="${ri}">${tds}</tr>`;
}).join("");
return `<table class="dm ${pick?'pick':''}"><caption>${caption}</caption><thead><tr>${ths}</tr></thead><tbody>${trs}</tbody></table>`;
}
function pickCard(i){
const d = cardData[cardType];
cardSel = i;
const leftRows = document.querySelectorAll("#cardLeft table tbody tr");
const rightRows = document.querySelectorAll("#cardRight table tbody tr");
leftRows.forEach((tr,ri)=>tr.classList.toggle("sel", ri===i));
const keyVal = d.left[i][d.leftKey];
let matchCount = 0;
rightRows.forEach((tr,ri)=>{
const isMatch = d.right[ri][d.rightKey] === keyVal;
tr.classList.remove("match","dim-out");
if(isMatch){ tr.classList.add("match"); matchCount++; }
else tr.classList.add("dim-out");
});
drawCardLines(i, keyVal, d);
const noun = matchCount===1 ? "row" : "rows";
let msg;
if(cardType==="one") msg = `“${keyVal}” → exactly <strong>1</strong> matching row. That's one-to-one.`;
else if(cardType==="many") msg = `“${keyVal}” → <strong>${matchCount}</strong> matching ${noun} in orders. One region, many orders — one-to-many.`;
else msg = `“${keyVal}” appears in <strong>${matchCount}</strong> ${noun} on the right — and those promotions have other customers too. That two-way “many” is why it needs a bridge.`;
document.getElementById("cardNarrate").innerHTML = msg;
}
function drawCardLines(i, keyVal, d){
const svg = document.getElementById("cardSvg");
const stage = document.getElementById("cardStage");
clearSvg("cardSvg");
const sb = stage.getBoundingClientRect();
const leftRow = document.querySelectorAll("#cardLeft table tbody tr")[i];
const lb = leftRow.getBoundingClientRect();
const x1 = lb.right - sb.left;
const y1 = lb.top + lb.height/2 - sb.top;
document.querySelectorAll("#cardRight table tbody tr").forEach((tr,ri)=>{
if(d.right[ri][d.rightKey]!==keyVal) return;
const rb = tr.getBoundingClientRect();
const x2 = rb.left - sb.left;
const y2 = rb.top + rb.height/2 - sb.top;
const mx = (x1+x2)/2;
const path = document.createElementNS("http://www.w3.org/2000/svg","path");
path.setAttribute("d", `M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`);
path.setAttribute("fill","none");
path.setAttribute("stroke","var(--brand-red)");
path.setAttribute("stroke-width","2.5");
path.setAttribute("stroke-linecap","round");
path.setAttribute("opacity","0.85");
const len = Math.hypot(x2-x1,y2-y1)+Math.abs(y2-y1);
path.style.strokeDasharray = len;
path.style.strokeDashoffset = len;
path.style.transition = "stroke-dashoffset .5s ease";
svg.appendChild(path);
requestAnimationFrame(()=>{ path.style.strokeDashoffset = 0; });
});
}
document.getElementById("cardSeg").addEventListener("click", e=>{
if(!e.target.dataset.card) return;
cardType = e.target.dataset.card;
document.querySelectorAll("#cardSeg button").forEach(b=>b.classList.toggle("active", b===e.target));
document.getElementById("cardHint").textContent =
cardType==="m2m" ? "Click a customer — notice the match runs both ways." : "Click a row in the left table.";
renderCard();
});
function renderBridge(){
const cust = [["Ava","Austin"],["Ben","Boston"],["Cleo","Austin"]];
const promo = [["Spring Sale","20% off"],["Holiday","BOGO"]];
const bridge = [["Ava","Spring Sale"],["Ava","Holiday"],["Ben","Spring Sale"],["Cleo","Holiday"],["Cleo","Spring Sale"]];
document.getElementById("bridgeCust").innerHTML =
buildTable(`customers <span class="role dim">"one"</span>`, ["Customer","City"], cust, false, 0);
document.getElementById("bridgeMid").innerHTML =
buildTable(`promo_bridge <span class="role fact">bridge</span>`, ["Customer","Promotion"], bridge, false, 0);
document.getElementById("bridgePromo").innerHTML =
buildTable(`promotions <span class="role dim">"one"</span>`, ["Promotion","Offer"], promo, false, 0);
}
/* ============================================================
SCENE 2 — FILTER DIRECTION
============================================================ */
let dirFrom = "users";
let biDir = false;
let dirSel = null; // selected region (string) or order id
(function renderDir(){
const ub = document.querySelector("#dirUsers tbody");
ub.innerHTML = users.map(u=>`<tr data-region="${u.region}"><td class="key">${u.region}</td><td>${u.manager}</td></tr>`).join("");
const ob = document.querySelector("#dirOrders tbody");
ob.innerHTML = orders.map(o=>`<tr data-id="${o.id}" data-region="${o.region}"><td>${o.id}</td><td class="key">${o.region}</td><td class="num">$${o.sales}</td></tr>`).join("");
document.querySelectorAll("#dirUsers tbody tr").forEach(tr=>{
tr.addEventListener("click", ()=>{ if(dirFrom==="users") filterFromUsers(tr.dataset.region); else nudgeWrongWay("users"); });
});
document.querySelectorAll("#dirOrders tbody tr").forEach(tr=>{
tr.addEventListener("click", ()=>{ if(dirFrom==="orders") filterFromOrders(tr.dataset.id, tr.dataset.region); else nudgeWrongWay("orders"); });
});
setDirMeasure(orders.reduce((s,o)=>s+o.sales,0), "no filter — all regions", false);
})();
function clearDirHighlights(){
document.querySelectorAll("#dirUsers tbody tr, #dirOrders tbody tr")
.forEach(tr=>tr.classList.remove("sel","match","dim-out"));
clearSvg("dirSvg");
}
function filterFromUsers(region){
clearDirHighlights();
dirSel = region;
const ur = document.querySelector(`#dirUsers tbody tr[data-region="${region}"]`);
ur.classList.add("sel");
// pulse is decorative only; the teaching state is applied independently below
animatePulse("dirSvg", "dirStage", ur, "#dirOrders");
let cnt=0;
document.querySelectorAll("#dirOrders tbody tr").forEach(tr=>{
if(tr.dataset.region===region){ const n=cnt++; setTimeout(()=>tr.classList.add("match"), 360 + n*70); }
else tr.classList.add("dim-out");
});
const total = orders.filter(o=>o.region===region).reduce((s,o)=>s+o.sales,0);
setTimeout(()=>{
setDirMeasure(total, `users[Region] = "${region}"`, true);
document.getElementById("dirNarrate").innerHTML =
`Filter flows <strong>down the arrow</strong>: picking <strong>${region}</strong> in users lights up only its orders, and Total Sales drops to that region.`;
}, 360);
}
function filterFromOrders(id, region){
clearDirHighlights();
dirSel = id;
const or = document.querySelector(`#dirOrders tbody tr[data-id="${id}"]`);
or.classList.add("sel");
const o = orders.find(x=>x.id===id);
if(biDir){
// bidirectional: filter travels BACK up to users (pulse decorative only)
animatePulse("dirSvg","dirStage", or, "#dirUsers", null, true);
setTimeout(()=>{
document.querySelectorAll("#dirUsers tbody tr").forEach(tr=>{
if(tr.dataset.region===region) tr.classList.add("match"); else tr.classList.add("dim-out");
});
setDirMeasure(o.sales, `orders[${id}] → users (both-directions ON)`, true);
document.getElementById("dirNarrate").innerHTML =
`With <strong>both-directions ON</strong>, the filter climbs <em>back up</em> the line — one order now narrows users to just its region.`;
}, 360);
} else {
// single direction: nothing flows back
setDirMeasure(o.sales, `orders[${id}] — context stays on orders`, true);
document.querySelectorAll("#dirUsers tbody tr").forEach(tr=>tr.classList.add("dim-out"));
// brief "blocked" flash on the line
const line = document.getElementById("dirLine");
line.style.transition="none"; line.style.filter="grayscale(1)"; line.style.opacity=".4";
setTimeout(()=>{ line.style.transition=".4s"; line.style.filter=""; line.style.opacity="1"; }, 30);
document.querySelectorAll("#dirUsers tbody tr").forEach(tr=>setTimeout(()=>tr.classList.remove("dim-out"),700));
document.getElementById("dirNarrate").innerHTML =
`Nothing flows back. The arrow points users → orders, so selecting an order does <strong>not</strong> filter users. <em>(Flip “Both-directions” to change that.)</em>`;
}
}
let wrongTimer=null;
function nudgeWrongWay(side){
const narr = document.getElementById("dirNarrate");
narr.innerHTML = side==="orders"
? `You're set to filter <strong>from users</strong>. Switch the selector to “orders (the many)” to try filtering the other way.`
: `You're set to filter <strong>from orders</strong>. Switch back to “users (the one)” above.`;
clearTimeout(wrongTimer);
}
function setDirMeasure(val, ctx, animate){
const el = document.getElementById("dirMeasure");
document.getElementById("dirCtx").textContent = ctx;
if(!animate){ el.textContent = fmt(val); return; }
const from = parseInt(el.textContent.replace(/,/g,""))||0;
const start = performance.now(), dur=450;
function step(t){
const k = Math.min(1,(t-start)/dur);
const e = 1-Math.pow(1-k,3);
el.textContent = fmt(Math.round(from+(val-from)*e));
if(k<1) requestAnimationFrame(step);
}
requestAnimationFrame(step);
setTimeout(()=>{ el.textContent = fmt(val); }, dur+60); // guarantee final value even if rAF throttles
}
document.getElementById("dirSeg").addEventListener("click", e=>{
if(!e.target.dataset.from) return;
dirFrom = e.target.dataset.from;
document.querySelectorAll("#dirSeg button").forEach(b=>b.classList.toggle("active", b===e.target));
resetDir();
});
document.getElementById("biDir").addEventListener("change", e=>{
biDir = e.target.checked;
updateDirArrow();
resetDir();
});
document.getElementById("dirReset").addEventListener("click", resetDir);
function updateDirArrow(){
const arrow = document.getElementById("dirArrow");
const line = document.getElementById("dirLine");
if(biDir){ arrow.innerHTML = "users ⇄ orders"; line.querySelector(".one").textContent="1"; }
else { arrow.innerHTML = "users → orders"; }
}
function resetDir(){
clearDirHighlights();
dirSel=null;
setDirMeasure(orders.reduce((s,o)=>s+o.sales,0), "no filter — all regions", true);
document.getElementById("dirNarrate").innerHTML = dirFrom==="users"
? "Click a region on the left."
: (biDir ? "Click an order — with both-directions on, it'll filter users too."
: "Click an order — single direction means nothing flows back to users.");
}
/* shared pulse animation: a glowing dot travels from a source row to the target table */
function animatePulse(svgId, stageId, sourceRow, targetSel, onArrive, reverse){
const svg = document.getElementById(svgId);
const stage = document.getElementById(stageId);
clearSvg(svgId);
const sb = stage.getBoundingClientRect();
const srcB = sourceRow.getBoundingClientRect();
const tgt = document.querySelector(targetSel);
const tb = tgt.getBoundingClientRect();
const x1 = (reverse ? srcB.left : srcB.right) - sb.left;
const y1 = srcB.top + srcB.height/2 - sb.top;
const x2 = (reverse ? tb.right : tb.left) - sb.left;
const y2 = tb.top + tb.height/2 - sb.top;
const mx = (x1+x2)/2;
const d = `M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`;
const path = document.createElementNS("http://www.w3.org/2000/svg","path");
path.setAttribute("d",d); path.setAttribute("fill","none");
path.setAttribute("stroke","var(--brand-red)"); path.setAttribute("stroke-width","2.5");
path.setAttribute("opacity",".4"); path.setAttribute("stroke-dasharray","5 5");
svg.appendChild(path);
const dot = document.createElementNS("http://www.w3.org/2000/svg","circle");
dot.setAttribute("r","7"); dot.setAttribute("class","pulse-dot");
svg.appendChild(dot);
const total = path.getTotalLength();
const start = performance.now(), dur=520;
function step(t){
const k = Math.min(1,(t-start)/dur);
const e = k<.5 ? 2*k*k : 1-Math.pow(-2*k+2,2)/2;
const pt = path.getPointAtLength(e*total);
dot.setAttribute("cx",pt.x); dot.setAttribute("cy",pt.y);
dot.setAttribute("r", 7 - 2*Math.sin(k*Math.PI)*-1);
if(k<1) requestAnimationFrame(step);
else { dot.remove(); if(onArrive) onArrive(); }
}
requestAnimationFrame(step);
}
function drawDirLine(){ /* placeholder kept for tab-switch hook; lines drawn on demand */ }
/* ============================================================
SCENE 3 — FILTER CONTEXT
============================================================ */
let ctxRegion = null; // null = no slicer
const allRegionsTotal = orders.reduce((s,o)=>s+o.sales,0);
(function buildSlicer(){
const wrap = document.getElementById("ctxSlicer");
wrap.innerHTML = Object.keys(REGIONS).map(r=>`<button data-region="${r}">${r}</button>`).join("");
wrap.querySelectorAll("button").forEach(b=>{
b.addEventListener("click", ()=>{
ctxRegion = (ctxRegion===b.dataset.region) ? null : b.dataset.region;
wrap.querySelectorAll("button").forEach(x=>x.classList.toggle("on", x.dataset.region===ctxRegion));
renderPivot(true);
});
});
renderPivot(false);
})();
function renderPivot(flash){
const tbody = document.querySelector("#ctxPivot tbody");
// managers visible depend on slicer (region filters users → managers)
const visUsers = ctxRegion ? users.filter(u=>u.region===ctxRegion) : users;
let rows = "";
let gTotal=0, gExpress=0;
visUsers.forEach(u=>{
const regOrders = orders.filter(o=>o.region===u.region);
const total = regOrders.reduce((s,o)=>s+o.sales,0);
const express = regOrders.filter(o=>o.ship==="Express Air").reduce((s,o)=>s+o.sales,0);
gTotal+=total; gExpress+=express;
rows += `<tr>
<td class="rowlbl">${u.manager} <span style="color:#b8b5a8;font-weight:400">· ${u.region}</span></td>
<td>$${fmt(total)}</td>
<td class="calc">$${fmt(express)}</td>
<td class="calc">$${fmt(allRegionsTotal)}</td>
</tr>`;
});
rows += `<tr class="total">
<td class="rowlbl">Total</td>
<td>$${fmt(gTotal)}</td>
<td class="calc">$${fmt(gExpress)}</td>
<td class="calc">$${fmt(allRegionsTotal)}</td>
</tr>`;
tbody.innerHTML = rows;
if(flash) tbody.querySelectorAll("td").forEach(td=>{ td.classList.add("flash"); setTimeout(()=>td.classList.remove("flash"),600); });
const narr = document.getElementById("ctxNarrate");
if(ctxRegion){
narr.innerHTML = `Filter context now includes <strong>users[Region] = "${ctxRegion}"</strong>. <strong>Total Sales</strong> and <strong>Express Air</strong> shrank to ${ctxRegion}. But <strong style="color:var(--brand-red)">All-Region Sales</strong> didn't move — <code class="dax" style="background:#f3efe4">ALL()</code> stripped the region filter right back out.`;
} else {
narr.innerHTML = `Right now the slicer context is <strong>everything</strong>. Each manager row still carries its own region context — that's why the rows differ. Click a region above to add a slicer filter on top.`;
}
}
/* ============================================================
utils
============================================================ */
function clearSvg(id){ const s=document.getElementById(id); while(s.firstChild) s.removeChild(s.firstChild); }
window.addEventListener("resize", ()=>{
if(document.getElementById("scene-cardinality").classList.contains("active") && cardSel!==null){
const d=cardData[cardType]; drawCardLines(cardSel, d.left[cardSel][d.leftKey], d);
}
});
</script>
</body>
</html>