स्टैक ड्रिल-डाउन

खास जानकारी

स्टैक ड्रिल-डाउन, हैरारकी के हिसाब से नेविगेशन का एक पैटर्न है. यह मोबाइल ऐप्लिकेशन में आम तौर पर इस्तेमाल होता है. इसमें किसी लिंक को चालू करने पर, पिछली स्क्रीन के ऊपर एक नई फ़ुल-स्क्रीन व्यू दिखता है. व्यू का कॉन्टेंट, ऐप्लिकेशन के हिसाब से तय होता है. जैसे, सेटिंग का सब-पेज, फ़ीड में मौजूद कोई थ्रेड, फ़ाइल ब्राउज़र में मौजूद कोई फ़ोल्डर, गैलरी में मौजूद ज़्यादा जानकारी वाला पेज वगैरह. उपयोगकर्ता, मौजूदा व्यू को स्क्रीन से दाईं ओर स्वाइप करके या 'वापस जाएं' बटन पर टैप करके वापस लौटता है. ब्राउज़र का इतिहास सिंक रहता है, ताकि ओएस-लेवल पर बैक जेस्चर, डीप लिंक, और आगे/पीछे जाने की प्रोसेस, सभी एक साथ काम करें.

इस गाइड में, स्टैक को इस तरह लागू किया गया है:

  • हॉरिज़ॉन्टल सीएसएस स्क्रोल-स्नैप कंटेनर, जिसमें हर व्यू ठीक एक स्नैप स्टॉप होता है. ड्रिल डाउन करने पर, एक नया व्यू जुड़ जाता है और उस पर आसानी से स्क्रोल किया जा सकता है. स्वाइप-बैक जेस्चर को ब्राउज़र नेटिव तौर पर हैंडल करता है. इससे मोमेंटम, वेलोसिटी, और इंटरप्शन ट्रैकिंग की सुविधा बिना किसी पॉइंटर-इवेंट JavaScript के मुफ़्त में मिलती है.
  • स्टैक पर मौजूद एक scrollsnapchange इवेंट लिसनर, जो स्नैप टारगेट बदलने पर ट्रिगर होता है. इसका इस्तेमाल, "ऐक्टिव व्यू में बदलाव हुआ" के लिए एकमात्र भरोसेमंद सोर्स के तौर पर किया जाता है. इसलिए, स्वाइप, क्लिक, प्रोग्राम के हिसाब से स्क्रोल, और popstate पाथ, सभी एक कॉलबैक में इकट्ठा होते हैं. यह कॉलबैक, inert को अपडेट करता है, फ़ोकस को पहले जैसा करता है, उपयोगकर्ता के स्वाइप किए गए व्यू को हटाता है, और ब्राउज़िंग इतिहास को फिर से व्यवस्थित करता है.
  • pushState / popstate इंटिग्रेशन, ताकि हर ड्रिल-डाउन से इतिहास में एक एंट्री जुड़ जाए. साथ ही, ओएस-लेवल का बैक जेस्चर काम करे और डीप लिंक सीधे सही व्यू में खुलें.
  • हर व्यू पर स्क्रोल-ड्रिवन view() ऐनिमेशन (ज़रूरी नहीं) जो पैरालैक्स + डिम + शैडो इफ़ेक्ट जनरेट करता है. यह इफ़ेक्ट सीधे तौर पर स्वाइप जेस्चर से जुड़ा होता है. इससे, दिखने वाला मोशन, उपयोगकर्ता की उंगली से कंट्रोल होता है, न कि किसी ट्वीन से.

JavaScript से चलने वाले transform ऐनिमेशन के मुकाबले, यह तरीका ज़्यादा बेहतर है. इसकी वजह यह है कि स्नैप मैकेनिज़्म की मदद से, उपयोगकर्ता पैनल की पोज़िशन को सीधे जेस्चर से कंट्रोल कर सकता है. इसके लिए, उसे अपनी उंगली का इस्तेमाल करना होता है, न कि किसी ट्वीन का. साथ ही, यह इंटरैक्शन के उन पैटर्न से मैच करता है जिनकी उम्मीद उपयोगकर्ता, खास ऑपरेटिंग सिस्टम के लिए बने ऐप्लिकेशन से करते हैं.

लागू करना

1. मार्कअप

स्टैटिक एचटीएमएल, सिर्फ़ एक खाली स्टैक कंटेनर होता है. व्यू, JavaScript में बनाए जाते हैं और उपयोगकर्ता के नेविगेट करने पर जोड़े जाते हैं.

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

हर व्यू, .Stack (स्नैप टारगेट) का .Stack-view डायरेक्ट चाइल्ड होता है. इसमें .Stack-viewContent रैपर होता है. इसमें व्यू का कॉन्टेंट होता है और पैरालैक्स ट्रांसफ़ॉर्म लागू होता है — दूसरा चरण देखें. किसी भी समय, स्टैक में हर ऐक्टिव इतिहास एंट्री के लिए एक व्यू होता है. यह व्यू, ड्रिल-डाउन ऑर्डर में बाएं से दाएं होता है. जब उपयोगकर्ता रूट से दो लेवल तक ड्रिल-इन कर लेता है, तो रेंडर किया गया डीओएम कुछ ऐसा दिखता है:

<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 एट्रिब्यूट होता है. इसे सातवें चरण में, scrollsnapchange हैंडलर अपने-आप लागू करता है/हटाता है — इसे अपने व्यू बिल्डर से सेट न करें.
  • जिन व्यू को उपयोगकर्ता स्वाइप करके पीछे ले जाता है उन्हें डीओएम से हटा दिया जाता है. ऐसा सातवें चरण में भी किया जाता है. इससे स्टैक में कभी भी currentDepth + 1 से ज़्यादा चाइल्ड व्यू नहीं होते. अगर फ़ॉरवर्ड नेविगेशन की मदद से उन पर वापस जाया जाता है, तो उन्हें कैश मेमोरी में सेव किए गए यूआरएल पाथ से फिर से बनाया जाता है.

2. स्टाइल

स्टैक स्क्रोलर

स्टैक एक हॉरिज़ॉन्टल ग्रिड होता है. इसमें हर चाइल्ड व्यू की चौड़ाई, कंटेनर की चौड़ाई के बराबर होती है. साथ ही, सीएसएस स्क्रोल-स्नैप की मदद से, हर स्नैप में एक व्यू लागू किया जाता है. इससे, स्वाइप-बैक जेस्चर का इस्तेमाल करना आसान हो जाता है.

.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. ड्रिल-डाउन करना

ड्रिल-डाउन की सुविधा, इस क्रम में चार काम करती है: इतिहास की एंट्री को पुश करना, नया व्यू बनाना, उसे जोड़ना, और उस पर आसानी से स्क्रोल करना. स्नैप सेटल होने के बाद, scrollsnapchange हैंडलर (सातवां चरण) उसे वहां से पिक करता है.

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() को कॉल करता है. यह हैंडलर ही एकमात्र ऐसा पाथ है जो इतिहास में बदलाव होने पर, स्टैक को स्क्रोल करता है.

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 (हॉरिज़ॉन्टल स्नैपिंग के लिए) के तौर पर दिखाया जाता है. सभी स्टेट ट्रांज़िशन को इस एक हैंडलर में रखने से, स्वाइप पाथ, क्लिक पाथ, और popstate पाथ एक जैसे रहते हैं.

हैंडलर को अलग से मौजूद onActiveViewChanged फ़ंक्शन में निकाला जाता है, ताकि फ़ॉलबैक (नीचे "फ़ॉलबैक रणनीतियां" देखें) लॉजिक को डुप्लीकेट किए बिना उसका फिर से इस्तेमाल कर सके.

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);
});

पेज लोड होने पर, हो सकता है कि यूआरएल पहले से ही किसी डीप व्यू पर ले जाए. जैसे, शेयर किया गया लिंक, बुकमार्क, डीप पेज पर रीफ़्रेश. यूआरएल से मैच करने वाला शुरुआती व्यू बनाएं — रूट या डीप-लिंक किया गया, लेकिन दोनों नहीं — इसे खाली स्टैक में जोड़ें, डेप्थ-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 फ़ॉलबैक के साथ — "फ़ॉलबैक रणनीतियां" देखें) का इस्तेमाल करें, न कि स्क्रोल-इवेंट कोऑर्डिनेट का. Snap commit ही ऐसा इवेंट है जो स्वाइप, क्लिक, प्रोग्राम के हिसाब से स्क्रोल, और popstate पाथ पर लगातार ट्रिगर होता है.
  • स्नैप टारगेट के चाइल्ड एलिमेंट पर ट्रांसफ़ॉर्मेशन लागू करें, स्नैप टारगेट पर कभी नहीं. स्नैप टारगेट पर ट्रांसफ़ॉर्म करने से, स्क्रोल कंटेनर की स्नैप ज्यामिति में फ़ीडबैक मिलता है. साथ ही, जेस्चर के बीच में स्क्रोलर में गड़बड़ी होगी.
  • DO: inert को हर व्यू पर लागू करें. हालांकि, इसे उस व्यू पर लागू न करें जो फ़िलहाल दिख रहा है. इसके बिना, फ़ोकस और स्क्रीन रीडर नेविगेशन, पैरालैक्स के पीछे छिपे व्यू में लीक हो जाते हैं. ये व्यू, देखने में सक्षम उपयोगकर्ताओं को नहीं दिखते, लेकिन सुलभता की गंभीर समस्या पैदा करते हैं.
  • हर ड्रिल-डाउन पर इतिहास की एंट्री को पुश करें और popstate को हैंडल करें, ताकि ओएस-लेवल का बैक जेस्चर और ब्राउज़र के बैक/फ़ॉरवर्ड बटन काम करें. इस वजह से, यह पैटर्न खास ऐप्लिकेशन जैसा लगता है.
  • जब स्वाइप-बैक करने पर कोई ऐसा व्यू दिखता है जिसकी डेप्थ currentDepth से मैच नहीं होती, तो active-view-changed हैंडलर से इतिहास को रीकंसाइल करें. इसके बिना, ओएस के बैक बटन को दबाने पर उपयोगकर्ता को किसी ऐसी जगह पर रीडायरेक्ट किया जा सकता है जहां वह नहीं जाना चाहता. ऐसा इसलिए होता है, क्योंकि ब्राउज़र का इतिहास कर्सर, स्क्रीन पर मौजूद कॉन्टेंट के साथ सिंक नहीं होता.
  • ज़रूर करें: उन व्यू को डीओएम से हटाएं जिन्हें उपयोगकर्ता ने स्वाइप करके हटा दिया है. ड्रिल-डाउन सेशन लंबा होने पर, अलग किए गए दर्जनों सबट्री इकट्ठा हो सकते हैं. entriesByDepth में कैश मेमोरी में सेव किया गया यूआरएल पाथ, किसी भी व्यू को फिर से बनाने के लिए काफ़ी है. ऐसा तब होता है, जब फ़ॉरवर्ड नेविगेशन उस पर वापस आता है.
  • स्टैक में फ़ोकस वापस लाते समय, .focus({preventScroll: true}) को कॉल करें. डिफ़ॉल्ट preventScroll: false, ब्राउज़र को फ़ोकस टारगेट को व्यू में स्क्रोल करने के लिए मजबूर करता है. इससे स्नैप कंटेनर के साथ समस्या होती है और उपयोगकर्ता स्नैप के बीच में पहुंच सकता है.
  • DO: इंटरनल लिंक पर cmd/ctrl/माउस के बीच वाले बटन से क्लिक करने की सुविधा को बनाए रखें, ताकि यूआरएल शेयर किए जा सकें और नए टैब में खोले जा सकें.
  • ज़रूर इस्तेमाल करें behavior: 'instant', एक से ज़्यादा चरणों वाले इतिहास के जंप के लिए और स्पेसियल-फ़ॉरवर्ड पॉपस्टेट ट्रांज़िशन (toIdx > fromIdx) के लिए. ऐसा न करने पर, एक से ज़्यादा चरणों वाले जंप, हर इंटरमीडिएट स्नैप पर scrollsnapchange को ट्रिगर करेंगे और इनर्ट/फ़ोकस/इतिहास के काम के N राउंड करेंगे. फ़ॉरवर्ड पॉपस्टेट अक्सर नकली होते हैं — 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' नहीं) के साथ कॉल करें, ताकि ओएस-लेवल की प्राथमिकता, हर कॉल के लिए जेएस ब्रांचिंग के बिना लागू हो. behavior: 'smooth' को हार्ड-कोड करने से, उपयोगकर्ता की सेटिंग को बायपास कर दिया जाता है.
  • DO रेंडर करने के लिए, ड्रिल-डाउन ट्रिगर के तौर पर असल <a href> एलिमेंट का इस्तेमाल करें, न कि <button onclick> या <div> का. असली ऐंकर टैग में, कर्सर घुमाने पर यूआरएल की झलक दिखती है. साथ ही, शेयर करने की सुविधा, मिडल-क्लिक, स्क्रीन रीडर की भूमिका, और एसईओ की सुविधा बिना किसी शुल्क के मिलती है.
  • हर ड्रिल-डाउन व्यू में, 'वापस जाएं' बटन ज़रूर शामिल करें. स्वाइप जेस्चर सिर्फ़ टच स्क्रीन पर काम करता है. कीबोर्ड, पॉइंटर, और डेस्कटॉप का इस्तेमाल करने वाले लोगों को एक विज़ुअल अफ़ोर्डेंस की ज़रूरत होती है.
  • popstate हैंडलर से history.pushState को कॉल न करें. ऐसा करने से, जब उपयोगकर्ता वापस जाने की कोशिश करता है, तब नई एंट्री पुश होती हैं और ब्राउज़र का 'वापस जाएं' बटन काम नहीं करता.
  • स्क्रोल-ड्रिवन ऐनिमेशन उपलब्ध होने पर, scroll इवेंट लिसनर की मदद से पैरालैक्स को न चलाएं. सीएसएस पाथ, कंपोज़िटर पर चलता है. वहीं, जेएस स्क्रोल लिसनर, मुख्य थ्रेड पर चलता है. इससे जेस्चर के दौरान फ़्रेम ड्रॉप होते हुए दिखेंगे.
  • स्वाइप-बैक के बाद, डीओएम से हटाए गए व्यू में बदलाव न करें. entriesByDepth को कैननिकल रिकॉर्ड के तौर पर मानें: छांटी गई एंट्री में view: null होता है और इसे updateFromHistoryState में मांग के हिसाब से फिर से बनाया जाता है.

फ़ॉलबैक रणनीतियां

जिन सुविधाओं के लिए फ़ॉलबैक की ज़रूरत पड़ सकती है वे हैं: scroll-snap-events और scroll-driven-animations. इन दोनों सुविधाओं के लिए, फ़ॉलबैक या परतदार वृद्धि की बेहतर सुविधाएं उपलब्ध हैं. साथ ही, इस इस्तेमाल के उदाहरण के लिए इनका इस्तेमाल करना सुरक्षित है:

स्क्रोल स्नैप इवेंट

scrollsnapchange इवेंट, "ऐक्टिव व्यू में बदलाव" का पता लगाने का सबसे आसान तरीका है. यह स्टैक पर एक लिसनर है, जो हर स्नैप कमिट पर सिर्फ़ एक बार ट्रिगर होता है. जिन ब्राउज़र में यह सुविधा नहीं है उनमें 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);
}

स्क्रोल-ड्रिवन ऐनिमेशन

स्क्रोल-ड्रिवन पैरालैक्स / डिम / शैडो इफ़ेक्ट, नेविगेशन कोर के ऊपर एक परतदार वृद्धि है. सीएसएस @supports (animation-timeline: view()) गेट (दूसरे चरण में दिखाया गया है) ऐनिमेशन को सिर्फ़ उन ब्राउज़र तक सीमित रखता है जो इसे सपोर्ट करते हैं. अन्य सभी ब्राउज़र पर, व्यू बिना किसी ट्रांज़िशन के स्नैप स्टॉप के बीच कट जाते हैं. यह कॉम्पोनेंट, पैरालैक्स के बिना भी पूरी तरह से काम करता है. स्नैप, इतिहास सिंक करना, फ़ोकस मैनेजमेंट, और inert अब भी काम करते हैं.

अगर पुराने बेसलाइन टारगेट के लिए पैरालैक्स फ़ॉलबैक की ज़रूरत है, तो स्टैक में scroll लिसनर अटैच करें. साथ ही, सीएसएस की कस्टम प्रॉपर्टी लिखें, जिसमें स्क्रोलपोर्ट के ज़रिए हर व्यू की प्रोग्रेस के बारे में बताया गया हो. इसके बाद, उस प्रॉपर्टी से 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})`;
    }
  });
}