הצגת פירוט של ערימה

סקירה כללית

פירוט מקבץ הוא דפוס ניווט היררכי, שנפוץ באפליקציות לנייד, שבו הפעלת קישור דוחפת תצוגה חדשה במסך מלא מעל התצוגה הקודמת. התוכן של התצוגה מוגדר על ידי האפליקציה – דף משנה של הגדרות, שרשור בתוך פיד, תיקייה בתוך דפדפן קבצים, דף פרטים בתוך גלריה וכו'. המשתמש חוזר על ידי החלקת התצוגה הנוכחית אל מחוץ למסך ימינה או על ידי לחיצה על כפתור החזרה. היסטוריית הדפדפן נשארת מסונכרנת, כך שתנועת החזרה ברמת מערכת ההפעלה, קישורי העומק והניווט קדימה/אחורה פועלים באופן עקבי.

במדריך הזה, המחסנית מוטמעת כך:

  • קונטיינר CSS אופקי של גלילה עם נקודות עצירה (scroll snapping), שבו כל תצוגה היא בדיוק נקודת עצירה אחת. כשמבצעים פירוט, נוספת תצוגה חדשה והגלילה אליה חלקה. תנועת ההחלקה לאחור מטופלת באופן מקורי על ידי הדפדפן, ומספקת מעקב אחר תנופה, מהירות והפרעות בחינם, ללא JavaScript של אירוע מצביע.
  • רכיב event listener מסוג scrollsnapchange במחסנית שמופעל כשמטרת ההצמדה משתנה. הוא משמש כמקור האמת היחיד (SSOT) ל "שינוי Active View" – כך שהחלקות, קליקים, גלילה פרוגרמטית ונתיבי popstate מתכנסים כולם לקריאה חוזרת (callback) אחת שמעדכנת את inert, משחזרת את המיקוד, מסירה תצוגות שהמשתמש החליק על פניהן ומתאימה את היסטוריית הגלישה.
  • שילוב של pushState / popstate כך שכל פירוט מוסיף רשומה להיסטוריה, תנועת החזרה ברמת מערכת ההפעלה פועלת וקישורי עומק נפתחים ישירות בתצוגה הנכונה.
  • אנימציה (אופציונלית) של view() שמופעלת בגלילה בכל תצוגה, ויוצרת אפקט של פרלקס + עמעום + צל שקשור ישירות לתנועת ההחלקה. כך, התנועה שרואים מופעלת על ידי האצבע של המשתמש, ולא על ידי אנימציית ביניים.

הגישה הזו עדיפה על אנימציות transform שמבוססות על JavaScript, כי מנגנון ההצמדה נותן למשתמש שליטה ישירה על מיקום החלונית באמצעות תנועות (האצבע שלו מניעה אותה, ולא אנימציית ביניים) ומתאים לדפוסי האינטראקציה שמשתמשים מצפים להם מאפליקציות נייטיב לנייד.

הטמעה

1. Markup

ה-HTML הסטטי הוא רק מאגר ריק של מחסנית. התצוגות נוצרות ב-JavaScript ומתווספות כשהמשתמש מנווט.

<div class="Stack">
  <!-- Intentionally empty. The initial view is appended by JavaScript
       at init time (step 8). -->
</div>

כל תצוגה היא צאצא ישיר של .Stack-view של .Stack (יעד ההצמדה) עם מעטפת .Stack-viewContent בתוכו (שם נמצא תוכן התצוגה, ושם חלה טרנספורמציית הפרלקס – ראו שלב 2). בכל רגע נתון, במחסנית יש תצוגה אחת לכל רשומה פעילה בהיסטוריית הפעילות, משמאל לימין בסדר פירוט. אחרי שהמשתמש נכנס שתי רמות פנימה מהשורש, ה-DOM שעבר רינדור נראה כך:

<div class="Stack">
  <!-- Root view. Has whatever content makes sense as the entry point
       of this section of the app. No back button — there is nothing
       behind the root in the stack. -->
  <div class="Stack-view" inert>
    <div class="Stack-viewContent">
      <!-- Root content; includes <a href> links that drill in. -->
    </div>
  </div>

  <!-- First-level drill-down view. The user got here by activating a
       link in the root view. -->
  <div class="Stack-view" inert>
    <div class="Stack-viewContent">
      <header>
        <!-- DO include a back button. The swipe gesture only works on
             touch — keyboard and pointer users need an explicit control. -->
        <button class="back" aria-label="Back"></button>
        <!-- Title / breadcrumb / etc. -->
      </header>
      <main>
        <!-- View content; may include further drill-down <a href> links. -->
      </main>
    </div>
  </div>

  <!-- Second-level drill-down view. Currently visible — no `inert`
       attribute. Same shape as the first-level view. -->
  <div class="Stack-view">
    <div class="Stack-viewContent">
      <header>
        <button class="back" aria-label="Back"></button>
        <!-- ... -->
      </header>
      <main><!-- ... --></main>
    </div>
  </div>
</div>

הערות:

  • כל התצוגות, מלבד זו שמוצגת כרגע, כוללות את המאפיין inert. ההגדרה הזו מופעלת או מוסרת באופן אוטומטי על ידי ה-handler של scrollsnapchange בשלב 7 – אל תגדירו אותה מבוני התצוגות שלכם.
  • תצוגות שהמשתמש החליק אחורה מעבר להן מוסרות מה-DOM (גם בשלב 7), כך שהמחסנית אף פעם לא גדלה מעבר ל-currentDepth + 1 צאצאים. הם נבנים מחדש לפי דרישה מנתיבי כתובות ה-URL שלהם שנשמרו במטמון אם הניווט קדימה חוזר אליהם.

2. סגנונות

רכיב הגלילה של הערימה

המחסנית היא רשת אופקית שבה כל תצוגת צאצא היא בדיוק ברוחב של מאגר התגים, עם גלילה עם נקודות עצירה (scroll snapping) ב-CSS שאוכפת תצוגה אחת לכל נקודת עצירה. כך תנועת ההחלקה אחורה מרגישה טבעית.

.Stack {
  /* Use dvh so the height tracks the dynamic viewport on mobile, where
     the address bar can show/hide. svh would clip during the address bar
     animation; vh leaks under it. */
  height: 100dvh;

  /* Lay views out left-to-right, each one full-width, so horizontal
     scrolling moves between them one at a time. */
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 100%;
  grid-template-rows: 100%;
  overflow-x: auto;

  /* `mandatory` guarantees the stack always settles fully on a view —
     never half-way between two. */
  scroll-snap-type: x mandatory;
  /* Prevent the swipe-back gesture from chaining into the browser's
     own history-back gesture (iOS, some Android) or the page's vertical
     scroll. The user is navigating the stack, not the page. */
  overscroll-behavior-x: none;
}

/* Hide the visual scrollbar — the snap and the parallax are the
   affordances; a horizontal scrollbar would look out of place. */
.Stack::-webkit-scrollbar {
  display: none;
}

/* MANDATORY: Opt into smooth programmatic scrolling via CSS, gated on
   prefers-reduced-motion. JS code calls scrollTo/scrollBy with
   behavior: 'auto' which defers to this rule, so the OS-level reduced-
   motion preference automatically downgrades to instant scrolling
   without any per-call JS branching. */
@media (prefers-reduced-motion: no-preference) {
  .Stack {
    scroll-behavior: smooth;
  }
}

.Stack-view {
  scroll-snap-align: start;
  /* `always` prevents the user from blowing through more than one view
     per gesture, so depth changes always happen one step at a time. */
  scroll-snap-stop: always;
}

/* MANDATORY: A separate inner element is required for the parallax
   transform below. Applying transforms directly to the snap target
   (.Stack-view) would feed back into the scroll container's snap
   geometry and the scroller would jump mid-gesture. */
.Stack-viewContent {
  width: 100%;
  height: 100%;
  background-color: #fff;
  /* Each view scrolls its own content vertically, independent of the
     stack's horizontal scroll. */
  overflow-y: auto;
}

אפקט "הערימה" (פרלקס / עמעום / צל)

אנימציית view(inline) שמופעלת בגלילה עוקבת אחרי ההתקדמות של כל תצוגה בסרגל הגלילה של הערימה, ומחילה פרלקסה + עמעום על התצוגה שיוצאת, וגם צל על תצוגות הפירוט שנכנסות, כדי שהן ייראו כמו "כרטיסים" שנערמים מעל התצוגה הקודמת.

/* MANDATORY: Wrap the animation block in @supports. Browsers without
   scroll-driven animations still parse the @keyframes and would
   apply the `to` state as a static style, leaving every view
   permanently transformed. The @supports gate confines the animation
   to browsers where it actually animates. */
@supports (animation-timeline: view()) {
  .Stack-viewContent {
    /* view(inline) tracks this element's progress through its nearest
       scrollable ancestor on the inline (x) axis. */
    animation: parallax linear both;
    animation-timeline: view(inline);
    /* Only animate the EXIT phase — when this view is being covered
       by a deeper one. During its own entry the view stays at rest,
       so the fresh content is fully bright and in position throughout. */
    animation-range: exit 0% exit 100%;
  }

  /* Drill-down views (everything except the root) also get a shadow on
     their left edge during the transition so they feel like cards
     stacking over the previous view. */
  .Stack-view:not(:first-child) .Stack-viewContent {
    animation: parallax linear both, shadow-fade linear both;
    animation-timeline: view(inline), view(inline);
    /* parallax: only exit (the view sliding back as a deeper one comes in).
       shadow-fade: entry through exit (visible the whole time the view is
       transitioning, not when it's at rest). */
    animation-range: exit 0% exit 100%, entry 0% exit 100%;
  }

  @keyframes parallax {
    /* translateX(75%) and brightness(0.8) are examples — adjust to taste. */
    to {
      transform: translateX(75%);
      filter: brightness(0.8);
    }
  }

  @keyframes shadow-fade {
    /* Shadow ramps in during entry, holds across the middle of the
       gesture, and ramps out during exit — so it's only visible while
       the view is mid-transition, not when at rest. */
    0%, 100% { box-shadow: 0 0 1.5rem #0000; }
    25%, 75% { box-shadow: 0 0 1.5rem #0004; }
  }
}

הערה: האפקט הזה פופולרי באפליקציות מודרניות עם מחסנית נייטיב והוא נקודת התחלה טובה, אבל אפשר להתאים אישית את האפקטים החזותיים המדויקים כך שיתאימו לסגנונות מעבר קיימים לפי הצורך.

3. מצב המודול

המחסנית עוקבת אחרי ארבעה חלקי מצב בהיקף המודול:

const stack = document.querySelector('.Stack');

// Reference to the root view DOM element. The Stack starts empty, so
// this is null until the root view is created — either at init (step 8,
// when the URL is '/') or later by synthesizeRootEntry() (when the user
// landed on a deep link and then navigates back). Held as a mutable
// reference because other code (the scrollsnapchange handler, init, etc.)
// uses identity comparisons against it.
let rootView = null;

// Tracks which element to restore focus to when the user swipes back
// into a previous view. Keyed by the view element itself so entries
// are garbage-collected automatically when the view is pruned.
const returnFocus = new WeakMap();

// Maps history depth -> {urlPath, view}. We MUST maintain this map
// ourselves because the History API does not expose state for entries
// other than the current one — so when a view is pruned on swipe-back,
// we still need to remember which URL it represented in case the user
// later forward-navigates back into it.
const entriesByDepth = new Map();

// Tracked manually because history.state on a popstate event tells us
// the destination depth but not where we came from. We need both to
// compute the direction (back vs forward) and the distance.
let currentDepth = 0;

בנוסף, יש שלושה רכיבי עזר ספציפיים לאפליקציה – המקומות היחידים שבהם מתחברים הניתוב ועיבוד התצוגה של האפליקציה:

// Resolve a URL path to the data your app needs to render the
// corresponding drill-down view, or return null for paths this section
// of the app does not handle (the root path '/', external links,
// unknown routes). resolveUrl() is for drill-down routes only — the
// root view is rendered separately by createRootView() below.
function resolveUrl(urlPath) {
  // Replace with your routing logic. For example, match `/view/:id`
  // and look the id up in your app state.
}

// Build the root (home) view of the stack. Application-specific content;
// preserve the .Stack-view / .Stack-viewContent wrapper structure (the
// inner element is required for the parallax — see step 2) and DO NOT
// render a back button — the root view has nothing behind it in the
// stack.
function createRootView() {
  const view = document.createElement('div');
  view.className = 'Stack-view';
  view.innerHTML = `
    <div class="Stack-viewContent">
      <!-- Root content. Include <a href> elements pointing at URL paths
           that resolveUrl() accepts, to enable drill-down from here. -->
    </div>
  `;
  return view;
}

// Build a drill-down view DOM element from the resolved route data.
// Customize the inner content freely, but DO preserve the .Stack-view
// / .Stack-viewContent wrapper structure and DO include a back button
// (the swipe gesture only works on touch).
function createDrillDownView(routeData) {
  const view = document.createElement('div');
  view.className = 'Stack-view';
  view.innerHTML = `
    <div class="Stack-viewContent">
      <header>
        <button class="back" aria-label="Back"></button>
        <!-- Title, breadcrumb, or other view chrome derived from
             routeData. -->
      </header>
      <main>
        <!-- View body, also from routeData. Include further <a href>
             elements pointing at URL paths that resolveUrl() also
             accepts, to enable additional drill-downs from this view. -->
      </main>
    </div>
  `;
  return view;
}

function getCurrentUrlPath() {
  return location.pathname;
}

4. הצגת פירוט

פירוט מבצע ארבע פעולות בסדר הבא: דחיפת רשומת היסטוריה, בניית התצוגה החדשה, הוספה שלה וגלילה חלקה אליה. ה-handler של scrollsnapchange (שלב 7) ממשיך משם אחרי שה-snap מסתיים.

function drillDown(urlPath) {
  const routeData = resolveUrl(urlPath);
  if (!routeData) return;

  const newDepth = currentDepth + 1;
  // Push BEFORE creating the view so the URL is correct if anything
  // observing history (analytics, etc.) reads it during view creation.
  history.pushState({depth: newDepth}, '', urlPath);

  // pushState truncates forward entries in real browser history;
  // mirror that truncation in our depth map so we don't hold references
  // to views the user can no longer reach.
  for (const d of entriesByDepth.keys()) {
    if (d >= newDepth) entriesByDepth.delete(d);
  }
  currentDepth = newDepth;

  const newView = createDrillDownView(routeData);
  stack.appendChild(newView);
  entriesByDepth.set(newDepth, {urlPath, view: newView});

  // Scroll one viewport-width to the right. behavior: 'auto' defers to
  // the CSS `scroll-behavior` set in step 2, which is smooth unless
  // prefers-reduced-motion is set. The snap container locks onto the
  // new view; the scrollsnapchange listener (step 7) fires when the
  // snap settles.
  stack.scrollBy({left: stack.clientWidth, behavior: 'auto'});
}

5. טיפול בקליקים ובכפתור "הקודם"

יירוט קליקים על קישורים בתוך המקבץ והמרה שלהם לפירוט. שמירה על ההתנהגות של מקש הצירוף, כך שלחיצה על cmd או לחיצה אמצעית עדיין פותחת את הקישור בכרטיסייה חדשה.

stack.addEventListener('click', (e) => {
  // Back button: defer to goBack() (defined below), which handles both
  // the normal in-app case and the deep-link case.
  if (e.target.closest('.back')) {
    goBack();
    return;
  }

  // Drill-down link.
  const link = e.target.closest('a');
  if (!link || !stack.contains(link)) return;
  // Let the browser handle modified clicks so users can open links
  // in new tabs / windows. e.button !== 0 filters out middle-clicks.
  if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;

  const urlPath = new URL(link.href).pathname;
  const parentView = link.closest('.Stack-view');
  // If the URL isn't handled by this section of the app (resolveUrl
  // returns null), fall through so the browser navigates normally.
  if (!resolveUrl(urlPath) || !parentView) return;

  e.preventDefault();
  // Record which link the user activated so focus can be restored to
  // it when they swipe (or click) back into this view.
  returnFocus.set(parentView, link);
  drillDown(urlPath);
});

// Going back is usually just history.back(), but there's an important
// edge case: when the user lands directly on a deep-linked URL, there
// is no in-app history entry behind it. Calling history.back() in that
// situation would take them out of the app entirely. MANDATORY: detect
// this case and synthesize a root entry instead, so an in-app Back from
// a deep link lands on the root view and the platform Back from there
// returns the user to where they came from.
function goBack() {
  const atDeepLinkRoot = currentDepth === 0
    && entriesByDepth.get(0)?.view !== rootView;
  if (atDeepLinkRoot) {
    synthesizeRootEntry();
  } else {
    // history.back() fires popstate, which routes through
    // updateFromHistoryState (step 6) and scrolls the stack — the
    // same path a swipe-back converges on.
    history.back();
  }
}

function synthesizeRootEntry() {
  // Push a new history entry pointing at the root URL. This becomes the
  // entry the user "came from"; the original deep-linked entry is now
  // behind us, so platform Back from the root view will return there.
  const newDepth = currentDepth + 1;
  history.pushState({depth: newDepth}, '', '/');

  // Create the root view if it doesn't exist yet (we landed on a deep
  // link and never needed it before now), and insert it at the LEFT end
  // of the stack. Adjust scrollLeft by one viewport width so the user's
  // view doesn't visually jump — they should still be looking at the
  // deep-linked view until the scroll animation below runs.
  if (!rootView) {
    rootView = createRootView();
    stack.prepend(rootView);
    stack.scrollLeft += stack.clientWidth;
  }
  entriesByDepth.set(newDepth, {urlPath: '/', view: rootView});

  // Now scroll to the new entry (the root view). updateFromHistoryState
  // smooth-scrolls one step left, the parallax plays, and
  // scrollsnapchange fires when the root view settles.
  updateFromHistoryState(history.state);
}

6. סנכרון מההיסטוריה (popstate)

האירוע popstate מופעל כשהמשתמש לוחץ על הכפתור "הקודם" או "הבא" בדפדפן או במערכת ההפעלה, או כש-JavaScript מפעיל את history.back() או את .go(). ה-handler הזה הוא הנתיב היחיד שגולל את המחסנית בתגובה לשינוי בהיסטוריה.

window.addEventListener('popstate', (event) => {
  updateFromHistoryState(event.state);
});

function updateFromHistoryState(state, behaviorOverride) {
  const newDepth = state?.depth ?? 0;
  const urlPath = getCurrentUrlPath();

  // Ensure entriesByDepth has an entry for the destination depth.
  // If the URL changed (e.g. forward-nav into a previously-pruned
  // view), clear the cached view reference so the loop below rebuilds.
  const entry = entriesByDepth.get(newDepth) ?? {view: null};
  if (entry.urlPath !== urlPath) {
    entry.urlPath = urlPath;
    entry.view = urlPath === '/' ? rootView : null;
  }
  entriesByDepth.set(newDepth, entry);

  // Rebuild any views between root and the destination that were
  // pruned earlier (when the user swiped back past them). Without
  // this, forward-navigating to a previously-pruned view would have
  // no element to scroll to.
  for (let d = 0; d <= newDepth; d++) {
    const e = entriesByDepth.get(d);
    if (!e || e.view) continue;
    const routeData = resolveUrl(e.urlPath);
    if (!routeData) continue;
    const rebuilt = createDrillDownView(routeData);
    stack.appendChild(rebuilt);
    e.view = rebuilt;
  }

  currentDepth = newDepth;

  const targetView = entriesByDepth.get(newDepth)?.view;
  if (!targetView) return;

  // Compare destination index against current scroll position so we
  // can bail if they're already aligned. This is reached when the
  // scrollsnapchange handler below calls history.go() to sync history
  // after a swipe-back that already completed visually — there's
  // nothing more to scroll.
  const toIdx = [...stack.children].indexOf(targetView);
  const fromIdx = Math.round(stack.scrollLeft / stack.clientWidth);
  if (fromIdx === toIdx) return;

  // Pick a scroll behavior:
  //   - multi-step jumps (e.g. history.go(-3)): 'instant' to skip
  //     intermediate snap points — otherwise smooth-scrolling would
  //     fire scrollsnapchange for each one and do N rounds of
  //     state-transition work for no reason.
  //   - rightward (forward) single-step: 'instant'. Browser-forward is
  //     rare on the web and is often spurious (e.g. iOS Safari treats
  //     edge swipes as forward navigation, even with overscroll-behavior
  //     set). An instant swap reads as "snap" rather than a misleading
  //     drilldown animation the user didn't ask for. The user-initiated
  //     drill-down path (drillDown, step 4) is unaffected — it calls
  //     scrollBy directly and never reaches this code.
  //   - leftward (back) single-step: 'auto' so the CSS `scroll-behavior`
  //     (smooth unless prefers-reduced-motion is set — see step 2)
  //     applies. Back is the common, expected case and benefits from
  //     the animation.
  // NOTE: "forward" here means spatial direction (toIdx > fromIdx),
  // NOT depth direction. synthesizeRootEntry (step 5) pushes a new
  // depth but scrolls LEFT to the root view, which correctly reads as
  // back-style (smooth).
  const forward = toIdx > fromIdx;
  const multiStep = Math.abs(toIdx - fromIdx) > 1;
  const behavior = behaviorOverride ?? (forward || multiStep ? 'instant' : 'auto');
  stack.scrollTo({left: toIdx * stack.clientWidth, behavior});
}

7. ‫scrollsnapchange: המקור הקובע

אחרי כל אישור של הצמדה – בין אם היא מופעלת על ידי החלקה, קליק או גלילה פרוגרמטית – הדפדפן מפעיל אירוע scrollsnapchange בקונטיינר הגלילה, כשהרכיב שהוצמד לאחרונה נחשף בתור event.snapTargetInline (להצמדה אופקית). הוספת כל מעברי המצבים בתוך ה-handler הזה היא מה ששומר על העקביות של נתיב ההחלקה, נתיב הקליק והנתיב של popstate.

ה-handler מחולץ לפונקציה עצמאית של onActiveViewChanged כדי שה-fallback (ראו "אסטרטגיות fallback" בהמשך) יוכל להשתמש בה שוב בלי לשכפל את הלוגיקה.

function onActiveViewChanged(currentView) {
  // Walk the stack in DOM order to update each view's role:
  //  - Views at or before currentView stay in the DOM but get
  //    `inert` (except currentView) so focus, pointer events, and
  //    AT navigation cannot leak into views hidden behind the
  //    parallax.
  //  - Views after currentView are unreachable (the user swiped
  //    back past them) so we drop them from the DOM to free memory.
  //    Their urlPath stays in entriesByDepth so a later forward
  //    navigation can rebuild the view from scratch.
  let seenCurrent = false;
  for (const view of [...stack.children]) {
    if (seenCurrent) {
      for (const e of entriesByDepth.values()) {
        if (e.view === view) e.view = null;
      }
      view.remove();
    } else {
      // MANDATORY: inert non-current views. Without this, tabbing
      // and screen-reader navigation can reach content hidden behind
      // the parallax — a severe accessibility failure that's
      // invisible to sighted users.
      view.toggleAttribute('inert', view !== currentView);
      if (view === currentView) seenCurrent = true;
    }
  }

  // If the visible view's depth doesn't match `currentDepth`, the
  // user got here by swiping (not clicking) — sync history so the
  // browser back/forward buttons stay coherent with what's on screen.
  let currentViewDepth;
  for (const [d, e] of entriesByDepth) {
    if (e.view === currentView) currentViewDepth = d;
  }
  if (currentViewDepth !== undefined && currentViewDepth !== currentDepth) {
    // history.go fires popstate, which re-enters updateFromHistoryState.
    // That call's fromIdx === toIdx check bails out without scrolling.
    history.go(currentViewDepth - currentDepth);
  }

  // Restore focus on the now-active view:
  //  - If we recorded which link the user activated to drill out
  //    of this view, return focus there so a swipe-back lands them
  //    exactly where they left off.
  //  - Otherwise (a freshly-pushed drill-down view), move focus to
  //    the back button so keyboard users have an obvious next action.
  //  - preventScroll is REQUIRED: without it, .focus() scrolls the
  //    snap container to bring the focused element into view, which
  //    fights the snap and can land the user mid-snap.
  const stored = returnFocus.get(currentView);
  if (stored) {
    stored.focus({preventScroll: true});
    returnFocus.delete(currentView);
  } else if (currentView !== rootView) {
    currentView.querySelector('.back')?.focus({preventScroll: true});
  }
}

stack.addEventListener('scrollsnapchange', (event) => {
  // snapTargetInline is the element that was just snapped to on the
  // inline (horizontal) axis. For this stack — where each view is one
  // horizontal snap stop — that's the new active view.
  onActiveViewChanged(event.snapTargetInline);
});

כשטעינת הדף מתבצעת, יכול להיות שכתובת ה-URL כבר מפנה לתצוגה עמוקה (קישור משותף, סימנייה, רענון של דף עמוק). יוצרים את התצוגה הראשונית שתואמת לכתובת ה-URL – ברמה הבסיסית או בקישור עומק, אבל אף פעם לא את שתיהן – מוסיפים אותה למחסנית הריקה, מאכלסים את רשומת ההיסטוריה בעומק 0 ומריצים מעבר גלילה ראשוני עם behavior: 'instant' כדי שהפרלקס לא יונפש ברינדור הראשוני.

const initialUrlPath = getCurrentUrlPath();
const initialRouteData = resolveUrl(initialUrlPath);

// Build the initial view: a drill-down view if the URL maps to one,
// otherwise the root view. Whichever it is, that's the only view in
// the stack right now — the other will be created lazily by
// synthesizeRootEntry (step 5) or drillDown (step 4) if the user
// navigates to it.
let initialView;
if (initialRouteData) {
  initialView = createDrillDownView(initialRouteData);
} else {
  rootView = createRootView();
  initialView = rootView;
}
stack.appendChild(initialView);

entriesByDepth.set(0, {urlPath: initialUrlPath, view: initialView});
// replaceState attaches a `depth` to the entry the user landed on, so
// any subsequent pushState / popstate has a base depth to count from.
history.replaceState({depth: 0}, '');

updateFromHistoryState(history.state, 'instant');

שיטות מומלצות

  • מומלץ להשתמש באירוע scrollsnapchange (עם חלופה של IntersectionObserver – ראו "אסטרטגיות חלופיות") כמקור האמת ל "שינוי ב-Active View", ולא בקואורדינטות של אירוע הגלילה. האירוע Snap commit הוא האירוע היחיד שמופעל באופן עקבי בכל הנתיבים של החלקה, קליק, גלילה פרוגרמטית ו-popstate.
  • כן כדאי להחיל טרנספורמציות על צאצא של יעד ההצמדה, אף פעם לא על יעד ההצמדה עצמו. טרנספורמציה ביעד ההצמדה משפיעה על הגיאומטריה של ההצמדה במאגר הגלילה, וגורמת לתקלה בגלילה באמצע התנועה.
  • מומלץ להחיל את inert על כל תצוגה, חוץ מהתצוגה שגלויה כרגע. בלי זה, המיקוד והניווט של קורא המסך זולגים לתצוגות שמוסתרות מאחורי הפרלקס – הן לא גלויות למשתמשים רואים, אבל זה כשל חמור בנגישות.
  • מומלץ להוסיף רשומה להיסטוריה בכל פירוט ולטפל ב-popstate כדי שתנועת החזרה ברמת מערכת ההפעלה והלחצנים "הקודם" ו"הבא" בדפדפן יפעלו. זה מה שגורם לתבנית להרגיש כמו אפליקציית נייטיב.
  • מומלץ להתאים את ההיסטוריה מהגורם המטפל active-view-changed כשהחלקה אחורה מובילה לתצוגה שהעומק שלה לא תואם ל-currentDepth. בלי זה, אם המשתמש יחזור אחורה במערכת ההפעלה, הוא יגיע למקום לא צפוי כי הסמן של היסטוריית הדפדפן לא מסונכרן עם מה שמופיע במסך.
  • כן כדאי להסיר מה-DOM תצוגות שהמשתמש החליק על פניהן. אחרת, סשן ארוך של פירוט יכול לצבור עשרות עצי משנה מנותקים. נתיב כתובת ה-URL שנשמר במטמון ב-entriesByDepth מספיק כדי לבנות מחדש כל תצוגה אם הניווט קדימה חוזר אליה.
  • צריך להפעיל את .focus({preventScroll: true}) כשמשחזרים את המיקוד בתוך המחסנית. ברירת המחדל preventScroll: false גורמת לדפדפן לגלול את יעד המיקוד לתצוגה, מה שמתנגש עם מאגר ההצמדה ויכול להשאיר את המשתמש באמצע ההצמדה.
  • חשוב לשמור על האפשרות להשתמש ב-cmd/ctrl/לחיצה על הלחצן האמצעי בקישורים פנימיים, כדי שיהיה אפשר לשתף את כתובות ה-URL ולפתוח אותן בכרטיסייה חדשה.
  • מומלץ להשתמש ב-behavior: 'instant' בשביל דילוגים של כמה שלבים בהיסטוריה וגם בשביל מעברי popstate מרחביים קדימה (toIdx > fromIdx). אחרת, דילוגים של כמה שלבים יפעילו את scrollsnapchange בכל תמונת מצב ביניים ויבצעו N סבבים של עבודה על אינרטיות/מיקוד/היסטוריה. אירועי popstate קדימה הם לעיתים קרובות מזויפים – iOS Safari מתייחס להחלקות בקצה המסך כאל מעבר קדימה בדפדפן גם אם overscroll-behavior-x: none מוגדר, והחלפה מיידית מטעה הרבה פחות מאשר הנפשה של "פירוט" שהמשתמש לא יזם. הנתיב לפירוט שהמשתמשים יוזמים (drillDown) לא מושפע כי הגלילה מתבצעת ישירות, ולא דרך popstate.
  • כן: מכבדים את prefers-reduced-motion: מצהירים על scroll-behavior: smooth רק בתוך @media (prefers-reduced-motion: no-preference) וקוראים ל-scrollTo / scrollBy עם behavior: 'auto' (לא 'smooth') כדי שההעדפה ברמת מערכת ההפעלה תיכנס לתוקף בלי הסתעפות JS לכל קריאה. הגדרה של behavior: 'smooth' בתוך הקוד עוקפת את ההגדרה של המשתמש.
  • כן כדאי להציג רכיבי <a href> אמיתיים כטריגרים להצגת פירוט, ולא <button onclick> או <div>. עוגנים אמיתיים מקבלים תצוגה מקדימה של כתובת ה-URL כשמעבירים מעליהם את העכבר, אפשרות לשיתוף, לחיצה אמצעית, תפקיד של קורא מסך ו-SEO בחינם.
  • כן כדאי לכלול הכפתור "הקודם" מפורש בכל תצוגת פירוט. תנועת ההחלקה פועלת רק במגע – משתמשי מקלדת, מצביע ומחשב זקוקים לאפשרות גלויה.
  • אל תקראו ל-history.pushState מה-handler של popstate – זה מוסיף רשומות חדשות בזמן שהמשתמש מנסה לחזור אחורה, ומשבש את הפעולה של הכפתור "הקודם" בדפדפן.
  • אל תפעילו את הפרלקסה באמצעות רכיב event listener מסוג scroll כשאנימציות מבוססות-גלילה זמינות. נתיב ה-CSS פועל על ה-compositor, מאזין גלילה של JS פועל ב-main thread וישמיט פריימים באופן גלוי במהלך התנועה.
  • אל תשנו תצוגות שהסרתם מה-DOM אחרי החלקה אחורה. התייחסות אל entriesByDepth כרשומה הקנונית: לרשומה שצומצמה יש view: null והיא נבנית מחדש על פי דרישה ב-updateFromHistoryState.

אסטרטגיות חלופיות

התכונות שעשויות לדרוש חלופות הן scroll-snap-events ו-scroll-driven-animations. לשתי התכונות יש חלופות חזקות או סיפורים של שיפור הדרגתי (progressive enhancement), והן בטוחות לשימוש במקרה הזה:

אירועי גלילה עם נקודות עצירה (scroll snapping)

האירוע scrollsnapchange הוא הדרך הכי נקייה לזהות ש "ה-Active View השתנה" – listener אחד בסטאק, שמופעל בדיוק פעם אחת בכל שמירת מצב. בדפדפנים שאין בהם את התכונה הזו, אפשר להשיג את אותו אפקט באמצעות IntersectionObserver שצופה בכל תצוגה כדי לקבל ניראות מלאה בתוך המקבץ. החלופה שולחת לאותה פונקציה onActiveViewChanged שבה משתמש הנתיב הראשי, כך שכל הלוגיקה של מעבר המצב נשארת במקום אחד.

// MANDATORY when supporting browsers that haven't shipped scroll-snap-events
// yet. Check `HTMLElement.prototype` (not `window` or `document`) — the
// event handler IDL attribute is added to the prototype when the feature
// is supported, regardless of whether any element has the handler set.
if (!('onscrollsnapchange' in HTMLElement.prototype)) {
  const viewObserver = new IntersectionObserver((entries) => {
    for (const entry of entries) {
      // threshold:1 only fires for fully-visible entries, but the
      // observer also emits a "leaving" entry per view that drops below
      // ratio 1. Filter to the entering side, which is the snap-commit
      // moment we're trying to detect.
      if (entry.intersectionRatio === 1) {
        onActiveViewChanged(entry.target);
      }
    }
  }, {root: stack, threshold: 1});

  // Auto-observe every .Stack-view as it's added to the stack, and stop
  // observing as it's removed. Using a MutationObserver lets the primary
  // code (drillDown, updateFromHistoryState, synthesizeRootEntry, init)
  // stay free of fallback wiring.
  new MutationObserver((mutations) => {
    for (const m of mutations) {
      for (const node of m.addedNodes) {
        if (node.classList?.contains('Stack-view')) viewObserver.observe(node);
      }
      for (const node of m.removedNodes) {
        if (node.classList?.contains('Stack-view')) viewObserver.unobserve(node);
      }
    }
  }).observe(stack, {childList: true});

  // Catch up to any views already in the stack at the time this code
  // runs (typically the initial view appended in step 8).
  for (const view of stack.children) viewObserver.observe(view);
}

אנימציות מבוססות-גלילה

אפקט הפרלקסה / העמעום / הצל שמופעל בגלילה הוא שיפור הדרגתי (progressive enhancement) שנוסף על ליבת הניווט. השער @supports (animation-timeline: view()) של CSS (מוצג בשלב 2) מגביל את האנימציה לדפדפנים תומכים. בכל מקום אחר, התצוגות פשוט נחתכות בין נקודות העצירה ללא מעבר. הרכיב פועל באופן מלא בלי הפרלקסה – הצמדה, סנכרון היסטוריה, ניהול מיקוד ו-inert עדיין פועלים.

אם נדרש פתרון חלופי לפרלקס עבור יעדי בסיס ישנים יותר, צריך לצרף מאזין scroll למחסנית ולכתוב מאפיין מותאם אישית של CSS שמתאר את ההתקדמות של כל תצוגה דרך יציאת הגלילה, ואז להפעיל את transform ו-filter מהמאפיין הזה:

if (!CSS.supports('animation-timeline: view()')) {
  stack.addEventListener('scroll', () => {
    const viewWidth = stack.clientWidth;
    for (const view of stack.children) {
      // Progress: 0 when this view is centered, 1 when it has fully
      // exited to the left. Matches the @keyframes mapping above.
      const offsetLeft = view.offsetLeft - stack.scrollLeft;
      const progress = Math.min(1, Math.max(0, -offsetLeft / viewWidth));
      const content = view.querySelector('.Stack-viewContent');
      content.style.transform = `translateX(${progress * 75}%)`;
      content.style.filter = `brightness(${1 - progress * 0.2})`;
    }
  });
}