File size: 28,295 Bytes
59027a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
export interface Props {
  tableOfContentAutoCollapse?: boolean;
}
const { tableOfContentAutoCollapse = false } = Astro.props as Props;
---

<nav
  class="table-of-contents"
  aria-label="Table of Contents"
  data-auto-collapse={tableOfContentAutoCollapse ? "1" : "0"}
>
  <div class="title">Table of Contents</div>
  <div id="article-toc-placeholder"></div>
</nav>
<details class="table-of-contents-mobile">
  <summary>Table of Contents</summary>
  <div id="article-toc-mobile-placeholder"></div>
</details>

<script is:inline>
  // Build TOC from article headings (h2/h3/h4) and render into the sticky aside
  const buildTOC = () => {
    const holder = document.getElementById("article-toc-placeholder");
    const holderMobile = document.getElementById(
      "article-toc-mobile-placeholder",
    );
    // Always rebuild TOC to avoid stale entries
    if (holder) holder.innerHTML = "";
    if (holderMobile) holderMobile.innerHTML = "";
    const articleRoot = document.querySelector("section.content-grid main");
    if (!articleRoot) return;
    const headings = articleRoot.querySelectorAll("h2, h3, h4");
    if (!headings.length) return;

    // Inclure tous les titres H2/H3/H4 sans filtrer "Table of contents"
    const headingsArr = Array.from(headings);
    if (!headingsArr.length) return;

    // Ensure unique ids for headings (deduplicate duplicates)
    const usedIds = new Set();
    const slugify = (s) =>
      String(s || "")
        .toLowerCase()
        .trim()
        .replace(/\s+/g, "_")
        .replace(/[^a-z0-9_\-]/g, "");
    headingsArr.forEach((h) => {
      let id = (h.id || "").trim();
      if (!id) {
        const base = slugify(h.textContent || "");
        id = base || "section";
      }
      let candidate = id;
      let n = 2;
      while (usedIds.has(candidate)) {
        candidate = `${id}-${n++}`;
      }
      if (h.id !== candidate) h.id = candidate;
      usedIds.add(candidate);
    });

    const nav = document.createElement("nav");
    let ulStack = [document.createElement("ul")];
    nav.appendChild(ulStack[0]);

    const levelOf = (tag) => (tag === "H2" ? 2 : tag === "H3" ? 3 : 4);
    let prev = 2;
    let headingCount = 0;
    headingsArr.forEach((h) => {
      const lvl = levelOf(h.tagName);
      // adjust depth
      while (lvl > prev) {
        const ul = document.createElement("ul");
        ulStack[ulStack.length - 1].lastElementChild?.appendChild(ul);
        ulStack.push(ul);
        prev++;
      }
      while (lvl < prev) {
        ulStack.pop();
        prev--;
      }
      const li = document.createElement("li");
      const a = document.createElement("a");
      a.href = "#" + h.id;
      a.textContent = h.textContent;
      a.target = "_self";
      li.appendChild(a);
      // Ajouter un index unique à chaque heading pour le tracking
      li.setAttribute("data-heading-idx", String(headingCount));
      headingCount++;
      ulStack[ulStack.length - 1].appendChild(li);
    });

    if (holder) holder.appendChild(nav);
    const navClone = nav.cloneNode(true);
    if (holderMobile) holderMobile.appendChild(navClone);

    // active link on scroll
    const links = [
      ...(holder ? holder.querySelectorAll("a") : []),
      ...(holderMobile ? holderMobile.querySelectorAll("a") : []),
    ];
    // Read breakpoint from CSS var and set autoCollapse only on desktop (disabled on mobile)
    const getCollapsePx = () => {
      const root = document.documentElement;
      const raw = getComputedStyle(root)
        .getPropertyValue("--bp-content-collapse")
        .trim();
      return raw || "1100px";
    };
    const mq = window.matchMedia(`(max-width: ${getCollapsePx()})`);
    const attrEnabled =
      document
        .querySelector(".table-of-contents")
        ?.getAttribute("data-auto-collapse") === "1";
    let autoCollapse = attrEnabled && !mq.matches;

    // Inject styles for collapsible & animation (tous les niveaux)
    const ensureStyles = () => {
      if (document.getElementById("toc-collapse-style")) return;
      const style = document.createElement("style");
      style.id = "toc-collapse-style";
      style.textContent = `
        .table-of-contents nav.table-of-contents-collapsible li > ul,
        details.table-of-contents-mobile nav.table-of-contents-collapsible li > ul { overflow: hidden; transition: height 200ms ease; }
        .table-of-contents nav.table-of-contents-collapsible li.collapsed > ul,
        details.table-of-contents-mobile nav.table-of-contents-collapsible li.collapsed > ul { display: block; }
      `;
      document.head.appendChild(style);
    };
    ensureStyles();

    const getAllItemsWithChildren = () => {
      const sideNav = holder ? holder.querySelector("nav") : null;
      const mobileNav = holderMobile ? holderMobile.querySelector("nav") : null;
      const q = (navEl) =>
        navEl
          ? Array.from(navEl.querySelectorAll("li[data-heading-idx]")).filter(
              (li) => li.querySelector(":scope > ul"),
            )
          : [];
      return {
        sideNav,
        mobileNav,
        sideItems: q(sideNav),
        mobileItems: q(mobileNav),
      };
    };

    const setNavCollapsible = () => {
      const sideNav = holder ? holder.querySelector("nav") : null;
      const mobileNav = holderMobile ? holderMobile.querySelector("nav") : null;
      if (sideNav) sideNav.classList.add("table-of-contents-collapsible");
      if (mobileNav) mobileNav.classList.add("table-of-contents-collapsible");
    };

    const measure = (el) => {
      if (!el) return 0;
      // Temporarily set height to auto to measure scrollHeight reliably
      const prev = el.style.height;
      el.style.height = "auto";

      // Force un reflow pour que le navigateur calcule les wraps de texte
      void el.offsetHeight;

      // Maintenant scrollHeight inclut la vraie hauteur avec tous les line wraps
      const h = el.scrollHeight;
      el.style.height = prev || "";
      return h;
    };

    // Tracker les animations en cours pour pouvoir les annuler
    const activeAnimations = new Map();

    const cancelAnimation = (el) => {
      if (!el) return;
      const animData = activeAnimations.get(el);
      if (animData) {
        // Nettoyer le listener de l'animation précédente
        el.removeEventListener("transitionend", animData.onEnd);
        activeAnimations.delete(el);
      }
    };

    const animateTo = (el, target) => {
      if (!el) return;

      // Annuler toute animation en cours sur cet élément
      cancelAnimation(el);

      // Obtenir la hauteur ACTUELLE (même si une animation est en cours)
      const current = parseFloat(getComputedStyle(el).height) || 0;

      // Si on est déjà proche de la cible, pas besoin d'animer
      if (Math.abs(current - target) < 1) {
        el.style.height = target ? "auto" : "0px";
        return;
      }

      // Démarrer depuis la hauteur actuelle
      el.style.height = current + "px";
      // Force reflow
      void el.offsetHeight;

      // Aller vers la cible
      el.style.height = target + "px";

      // Créer le listener de fin
      const onEnd = (e) => {
        if (e.propertyName !== "height") return;
        el.removeEventListener("transitionend", onEnd);
        activeAnimations.delete(el);
        if (target > 0) el.style.height = "auto";
      };

      // Sauvegarder le listener pour pouvoir l'annuler plus tard
      activeAnimations.set(el, { onEnd });
      el.addEventListener("transitionend", onEnd);
    };

    let prevActiveIdx = -1;
    let prevActiveElements = new Set();
    let prevActiveHeadingId = null;

    const setCollapsedState = (activeIdx) => {
      if (!autoCollapse) return;
      if (activeIdx == null || activeIdx < 0) activeIdx = 0;
      const { sideItems, mobileItems } = getAllItemsWithChildren();

      // Trouver l'élément <li> correspondant au heading actif et tous ses ancêtres
      const getActiveAndAncestors = (items, targetIdx) => {
        const toExpand = new Set();

        // Trouver le <li> qui correspond au targetIdx
        const findActiveLi = (li) => {
          const idx = Number(li.getAttribute("data-heading-idx") || "-1");
          if (idx === targetIdx) {
            return li;
          }

          const childUl = li.querySelector(":scope > ul");
          if (!childUl) return null;

          const childLis = childUl.querySelectorAll(
            ":scope > li[data-heading-idx]",
          );
          for (const child of childLis) {
            const found = findActiveLi(child);
            if (found) return found;
          }
          return null;
        };

        let activeLi = null;
        for (const li of items) {
          activeLi = findActiveLi(li);
          if (activeLi) break;
        }

        if (!activeLi) return toExpand;

        // Collecter l'élément actif lui-même
        const activeIdx = Number(
          activeLi.getAttribute("data-heading-idx") || "-1",
        );
        toExpand.add(activeIdx);

        // Remonter et collecter TOUS les ancêtres, sans condition
        // La structure de la TOC détermine automatiquement qui doit être ouvert
        let current = activeLi;
        while (current) {
          const parent = current.parentElement?.closest("li[data-heading-idx]");
          if (parent) {
            const parentIdx = Number(
              parent.getAttribute("data-heading-idx") || "-1",
            );
            toExpand.add(parentIdx);
            current = parent;
          } else {
            break;
          }
        }

        return toExpand;
      };

      const update = (items) => {
        const newActiveAncestors = getActiveAndAncestors(items, activeIdx);

        // Étape 0 : Annuler TOUTES les animations en cours avant de commencer
        // Cela évite les conflits si l'utilisateur scroll rapidement
        items.forEach((li) => {
          const sub = li.querySelector(":scope > ul");
          if (sub) cancelAnimation(sub);
        });

        // Étape 1 : Identifier TOUS les éléments qui vont changer d'état
        const allChanges = [];
        items.forEach((li) => {
          const sub = li.querySelector(":scope > ul");
          if (!sub) return;

          const idx = Number(li.getAttribute("data-heading-idx") || "-1");

          // Un élément doit être expanded SI il contient (directement ou indirectement) le heading actif
          // Donc soit il est dans newActiveAncestors, soit un de ses descendants l'est
          let shouldBeExpanded = false;

          // Vérifier si cet élément ou un de ses descendants est dans le chemin actif
          const allDescendants = li.querySelectorAll("li[data-heading-idx]");
          const allRelatedIndices = [
            idx,
            ...Array.from(allDescendants).map((d) =>
              Number(d.getAttribute("data-heading-idx") || "-1"),
            ),
          ];

          // Si au moins un de ces indices est dans newActiveAncestors, garder ouvert
          shouldBeExpanded = allRelatedIndices.some((i) =>
            newActiveAncestors.has(i),
          );

          const isCurrentlyCollapsed = li.classList.contains("collapsed");

          const isChanging =
            (shouldBeExpanded && isCurrentlyCollapsed) ||
            (!shouldBeExpanded && !isCurrentlyCollapsed);

          if (isChanging) {
            allChanges.push({ li, sub, shouldBeExpanded, idx });
          }
        });

        // Étape 2 : Parmi tous les changements, trouver ceux qui sont des "top-level"
        // (= n'ont PAS d'ancêtre qui change aussi)
        const topLevelChanges = [];
        const descendantChanges = [];

        allChanges.forEach((change) => {
          let hasAncestorChanging = false;

          // Remonter l'arbre pour voir si un ancêtre change aussi
          let currentLi = change.li;
          while (currentLi) {
            const parentLi = currentLi.parentElement?.closest(
              "li[data-heading-idx]",
            );
            if (!parentLi) break;

            const parentIdx = Number(
              parentLi.getAttribute("data-heading-idx") || "-1",
            );

            // Vérifier si ce parent est dans la liste des changements
            const parentIsChanging = allChanges.some(
              (c) => c.idx === parentIdx,
            );
            if (parentIsChanging) {
              hasAncestorChanging = true;
              break;
            }

            currentLi = parentLi;
          }

          if (hasAncestorChanging) {
            descendantChanges.push(change);
          } else {
            topLevelChanges.push(change);
          }
        });

        // Étape 3 : Appliquer TOUS les descendants instantanément (sans animation)
        // Ceci doit être fait AVANT toute animation pour que les hauteurs soient correctes
        if (descendantChanges.length > 0) {
          descendantChanges.forEach(({ li, sub, shouldBeExpanded }) => {
            const oldTransition = sub.style.transition;
            sub.style.transition = "none";

            if (shouldBeExpanded) {
              li.classList.remove("collapsed");
              sub.style.height = "auto";
            } else {
              li.classList.add("collapsed");
              sub.style.height = "0px";
            }

            // Forcer un reflow immédiat pour cet élément
            void sub.offsetHeight;
            sub.style.transition = oldTransition || "";
          });

          // Forcer un reflow global pour que TOUS les changements soient appliqués
          void document.body.offsetHeight;

          // IMPORTANT : Attendre un frame pour que le navigateur ait fini tous les calculs
          // avant de mesurer les hauteurs des parents
        }

        // Étape 4 : Animer SEULEMENT les top-level avec requestAnimationFrame
        // Les descendants sont déjà dans leur état final, donc la hauteur du parent sera correcte
        if (topLevelChanges.length > 0) {
          // Double requestAnimationFrame pour être sûr que le DOM est stabilisé
          requestAnimationFrame(() => {
            requestAnimationFrame(() => {
              topLevelChanges.forEach(({ li, sub, shouldBeExpanded }) => {
                if (shouldBeExpanded) {
                  li.classList.remove("collapsed");

                  // CRITIQUE : Avant de mesurer, mettre ABSOLUMENT TOUS les sous-éléments
                  // dans leur état final (expanded OU collapsed) de manière synchrone
                  const allInnerItems = sub.querySelectorAll(
                    "li[data-heading-idx]",
                  );

                  // D'abord, désactiver toutes les transitions
                  allInnerItems.forEach((innerLi) => {
                    const innerSub = innerLi.querySelector(":scope > ul");
                    if (innerSub) {
                      innerSub.style.transition = "none";
                    }
                  });

                  // Ensuite, mettre chaque élément dans son état final
                  allInnerItems.forEach((innerLi) => {
                    const innerIdx = Number(
                      innerLi.getAttribute("data-heading-idx") || "-1",
                    );
                    const innerSub = innerLi.querySelector(":scope > ul");
                    if (innerSub) {
                      if (newActiveAncestors.has(innerIdx)) {
                        // Cet élément devrait être expanded
                        innerLi.classList.remove("collapsed");
                        innerSub.style.height = "auto";
                      } else {
                        // Cet élément devrait être collapsed
                        innerLi.classList.add("collapsed");
                        innerSub.style.height = "0px";
                      }
                    }
                  });

                  // Forcer un reflow global pour que TOUT soit calculé
                  void sub.offsetHeight;

                  // Réactiver les transitions
                  allInnerItems.forEach((innerLi) => {
                    const innerSub = innerLi.querySelector(":scope > ul");
                    if (innerSub) {
                      innerSub.style.transition = "";
                    }
                  });

                  // Maintenant on peut mesurer avec confiance : tous les éléments
                  // sont dans leur état final définitif
                  const target = measure(sub);
                  animateTo(sub, target);
                } else {
                  li.classList.add("collapsed");
                  animateTo(sub, 0);
                }
              });
            });
          });
        }

        prevActiveElements = newActiveAncestors;
      };

      update(sideItems);
      update(mobileItems);
      setNavCollapsible();
      prevActiveIdx = activeIdx;
    };

    // When switching between desktop/mobile, refresh autoCollapse and expand all on mobile
    const expandAll = () => {
      const { sideItems, mobileItems } = getAllItemsWithChildren();
      const expand = (items) =>
        items.forEach((li) => {
          li.classList.remove("collapsed");
          const sub = li.querySelector(":scope > ul");
          if (sub) sub.style.height = "auto";
        });
      expand(sideItems);
      expand(mobileItems);
    };

    const onMqChange = () => {
      autoCollapse = attrEnabled && !mq.matches;
      if (!autoCollapse) {
        expandAll();
      } else {
        setCollapsedState(prevActiveIdx);
      }
    };
    if (mq.addEventListener) mq.addEventListener("change", onMqChange);
    else if (mq.addListener) mq.addListener(onMqChange);

    // Debounce pour traiter la dernière mise à jour après que le scroll se stabilise
    let scrollDebounceTimer = null;
    let lastRequestedIdx = -1;
    let isProcessing = false;

    // Fonction pour mettre à jour l'URL avec l'ancre actuelle
    const updateURL = (headingId) => {
      if (!headingId) return;

      const newUrl = `${window.location.pathname}${window.location.search}#${headingId}`;

      // Mettre à jour l'URL sans recharger la page
      if (window.location.href !== newUrl) {
        history.pushState(null, null, newUrl);

        // Essayer différentes méthodes pour communiquer avec la fenêtre parente
        if (window.parent !== window) {
          try {
            // Méthode 1: Essayer de modifier directement l'URL du parent (si autorisé)
            try {
              window.parent.location.hash = headingId;
              console.debug("Successfully updated parent URL directly");
              return;
            } catch (e) {
              console.debug("Direct parent URL update blocked:", e.message);
            }

            // Méthode 2: Essayer avec window.top (fenêtre racine)
            try {
              if (window.top !== window && window.top !== window.parent) {
                window.top.location.hash = headingId;
                console.debug("Successfully updated top window URL directly");
                return;
              }
            } catch (e) {
              console.debug("Direct top window URL update blocked:", e.message);
            }

            // Méthode 3: Utiliser postMessage avec différents formats vers parent
            const messages = [
              {
                type: "urlChange",
                url: newUrl,
                hash: headingId,
              },
              {
                type: "anchorChange",
                anchorId: headingId,
                url: newUrl,
              },
              {
                type: "HF_SPACE_URL_UPDATE",
                hash: headingId,
                url: newUrl,
              },
              // Format officiel Hugging Face
              {
                queryString: "",
                hash: headingId,
              },
            ];

            messages.forEach((msg) => {
              try {
                window.parent.postMessage(msg, "*");
              } catch (e) {
                console.debug("PostMessage to parent failed:", e.message);
              }
            });

            // Méthode 4: Essayer avec window.top
            try {
              if (window.top !== window) {
                messages.forEach((msg) => {
                  try {
                    window.top.postMessage(msg, "*");
                  } catch (e) {
                    console.debug("PostMessage to top failed:", e.message);
                  }
                });
              }
            } catch (e) {
              console.debug("PostMessage to top window failed:", e.message);
            }

            // Méthode 5: Essayer avec l'origine spécifique Hugging Face
            try {
              window.parent.postMessage(
                {
                  queryString: "",
                  hash: headingId,
                },
                "https://huggingface.co",
              );
              console.debug("Sent HF official format message");
            } catch (e) {
              console.debug("HF official format failed:", e.message);
            }
          } catch (e) {
            console.debug(
              "All parent communication methods failed:",
              e.message,
            );
          }
        }
      }
    };

    const onScroll = () => {
      // active link highlight
      let activeIdx = -1;
      let activeHeadingId = null;

      for (let i = headingsArr.length - 1; i >= 0; i--) {
        const top = headingsArr[i].getBoundingClientRect().top;
        if (top - 60 <= 0) {
          links.forEach((l) => l.classList.remove("active"));
          const id = "#" + headingsArr[i].id;
          const actives = Array.from(links).filter(
            (l) => l.getAttribute("href") === id,
          );
          actives.forEach((a) => a.classList.add("active"));
          // Utiliser l'index du heading actif (n'importe quel niveau)
          activeIdx = i;
          activeHeadingId = headingsArr[i].id;
          break;
        }
      }

      // Update active heading tracking (but don't touch URL hash on scroll)
      if (activeHeadingId && activeHeadingId !== prevActiveHeadingId) {
        prevActiveHeadingId = activeHeadingId;
      }

      if (activeIdx === prevActiveIdx) return;

      // Sauvegarder la dernière demande
      lastRequestedIdx = activeIdx;

      // Si on est en train de traiter, ne rien faire (on traitera la dernière demande après)
      if (isProcessing) return;

      // Debounce : attendre un peu que le scroll se stabilise
      clearTimeout(scrollDebounceTimer);
      scrollDebounceTimer = setTimeout(() => {
        // Traiter la dernière demande
        if (lastRequestedIdx !== prevActiveIdx) {
          isProcessing = true;
          setCollapsedState(lastRequestedIdx);
          // Le processing flag sera réinitialisé après les animations
          setTimeout(() => {
            isProcessing = false;
            // Si une nouvelle demande est arrivée pendant qu'on traitait, la traiter maintenant
            if (lastRequestedIdx !== prevActiveIdx) {
              onScroll();
            }
          }, 250); // Attendre que les animations soient lancées
        }
      }, 100); // Debounce de 100ms
    };

    // If auto-collapse, collapse immediately (expand first section) before any scroll
    if (autoCollapse) setCollapsedState(0);

    window.addEventListener("scroll", onScroll);

    // Gérer la navigation par ancres au chargement de la page
    const handleInitialNavigation = () => {
      const hash = window.location.hash;
      if (hash) {
        const targetElement = document.querySelector(hash);
        if (targetElement) {
          // Attendre que le DOM soit prêt puis faire défiler vers l'élément
          setTimeout(() => {
            targetElement.scrollIntoView({ block: "start" });
            // Mettre à jour l'URL après le scroll
            setTimeout(() => {
              updateURL(hash.substring(1)); // Enlever le # du hash
            }, 100);
          }, 100);
        }
      } else {
        // No anchor - skip auto-setting hash
      }
    };

    // Initialize state
    onScroll();

    // Gérer la navigation initiale
    handleInitialNavigation();

    // Gérer les événements de navigation du navigateur (boutons précédent/suivant)
    window.addEventListener("popstate", (event) => {
      const hash = window.location.hash;
      if (hash) {
        const targetElement = document.querySelector(hash);
        if (targetElement) {
          targetElement.scrollIntoView({ block: "start" });
        }
      } else {
        // Si pas d'ancre, aller au début de la page
        window.scrollTo({ top: 0 });
      }
    });

    // Close mobile accordion when a link inside it is clicked
    if (holderMobile) {
      const details = holderMobile.closest("details");
      holderMobile.addEventListener("click", (ev) => {
        const target = ev.target;
        const anchor =
          target && "closest" in target ? target.closest("a") : null;
        if (anchor instanceof HTMLAnchorElement && details && details.open) {
          details.open = false;
        }
      });
    }
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", buildTOC, { once: true });
  } else {
    buildTOC();
  }
</script>

<style is:global>
  /* Sticky aside */
  .table-of-contents {
    position: sticky;
    top: 32px;
    margin-top: 12px;
  }

  .table-of-contents nav {
    border-left: 1px solid var(--border-color);
    padding-left: 16px;
    font-size: 13px;
  }

  .table-of-contents .title {
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 8px;
  }

  /* Look & feel */
  .table-of-contents nav ul {
    margin: 0 0 6px;
    padding-left: 1em;
  }

  .table-of-contents nav li {
    list-style: none;
    margin: 0.25em 0;
  }

  .table-of-contents nav a,
  .table-of-contents nav a:link,
  .table-of-contents nav a:visited {
    color: var(--text-color);
    text-decoration: none;
    border-bottom: none;
  }

  .table-of-contents nav > ul > li > a {
    font-weight: 700;
  }

  .table-of-contents nav a:hover {
    text-decoration: underline solid var(--muted-color);
  }

  .table-of-contents nav a.active {
    text-decoration: underline;
  }

  /* Mobile accordion */
  .table-of-contents-mobile {
    display: none;
    margin: 8px 0 16px;
  }

  .table-of-contents-mobile > summary {
    cursor: pointer;
    list-style: none;
    padding: var(--spacing-3) var(--spacing-4);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-color);
    font-weight: 600;
    position: relative;
  }

  .table-of-contents-mobile[open] > summary {
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
  }

  /* Disclosure arrow for mobile summary */
  .table-of-contents-mobile > summary::after {
    content: "";
    position: absolute;
    right: var(--spacing-4);
    top: 50%;
    width: 8px;
    height: 8px;
    border-right: 2px solid currentColor;
    border-bottom: 2px solid currentColor;
    transform: translateY(-70%) rotate(45deg);
    transition: transform 150ms ease;
    opacity: 0.7;
  }

  .table-of-contents-mobile[open] > summary::after {
    transform: translateY(-30%) rotate(-135deg);
  }

  .table-of-contents-mobile nav {
    border-left: none;
    padding: 10px 12px;
    font-size: 14px;
    border: 1px solid var(--border-color);
    border-top: none;
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
  }

  .table-of-contents-mobile nav ul {
    margin: 0 0 6px;
    padding-left: 1em;
  }

  .table-of-contents-mobile nav li {
    list-style: none;
    margin: 0.25em 0;
  }

  .table-of-contents-mobile nav a,
  .table-of-contents-mobile nav a:link,
  .table-of-contents-mobile nav a:visited {
    color: var(--text-color);
    text-decoration: none;
    border-bottom: none;
  }

  .table-of-contents-mobile nav > ul > li > a {
    font-weight: 700;
  }

  .table-of-contents-mobile nav a:hover {
    text-decoration: underline solid var(--muted-color);
  }

  .table-of-contents-mobile nav a.active {
    text-decoration: underline;
  }
</style>