Detalhamento da pilha

Visão geral

O detalhamento de pilha é um padrão de navegação hierárquica, comum em apps para dispositivos móveis, em que a ativação de um link abre uma nova visualização em tela cheia sobre a anterior. O conteúdo da visualização é definido pelo aplicativo: uma subpágina de configurações, uma conversa em um feed, uma pasta em um navegador de arquivos, uma página de detalhes em uma galeria etc. O usuário retorna deslizando a visualização atual para fora da tela à direita ou tocando em um botão "Voltar". O histórico do navegador permanece sincronizado para que o gesto de voltar no nível do SO, os links diretos e a navegação de retorno/para frente funcionem de maneira coerente.

Este guia implementa a pilha como:

  • Um contêiner de ajuste de rolagem CSS horizontal em que cada visualização é exatamente uma parada de ajuste. O detalhamento adiciona uma nova visualização e rola suavemente até ela. O gesto de deslizar para trás é processado de forma nativa pelo navegador, oferecendo rastreamento de impulso, velocidade e interrupção sem custo financeiro e sem JavaScript de evento de ponteiro.
  • Um listener de eventos scrollsnapchange na pilha que é acionado quando o destino de ajuste muda. Isso é usado como a única fonte de verdade para "a visualização ativa mudou". Assim, os caminhos de deslizar, clicar, rolar de forma programática e popstate convergem em um único callback que atualiza inert, restaura o foco, remove as visualizações que o usuário deslizou e reconcilia o histórico do navegador.
  • Uma integração de pushState / popstate para que cada detalhamento adicione uma entrada de histórico, o gesto de voltar no nível do SO funcione e os links diretos sejam abertos diretamente na visualização certa.
  • Uma animação view() (opcional) acionada por rolagem em cada visualização que produz um efeito de paralaxe + escurecimento + sombra vinculado diretamente ao gesto de deslizar. Assim, o movimento visível é acionado pelo dedo do usuário, não por uma interpolação.

Essa abordagem é preferível às animações transform baseadas em JavaScript porque o mecanismo de ajuste dá ao usuário controle gestual direto da posição do painel (o dedo dele o controla, não uma interpolação) e corresponde aos padrões de interação que os usuários esperam de apps nativos para dispositivos móveis.

Implementação

1. Marcação

O HTML estático é apenas um contêiner de pilha vazio. As visualizações são criadas em JavaScript e adicionadas ao final conforme o usuário navega.

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

Cada visualização é um filho direto .Stack-view de .Stack (o destino de ajuste) com um wrapper .Stack-viewContent dentro dele (onde o conteúdo da visualização fica e onde a transformação de paralaxe é aplicada, consulte a etapa 2). A qualquer momento, a pilha tem uma visualização por entrada de histórico de atividades ativa, da esquerda para a direita, em ordem de detalhamento. Depois que o usuário detalha dois níveis da raiz, o DOM renderizado fica assim:

<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>

Observações:

  • Todas as visualizações, exceto a que está visível no momento, têm o atributo inert. Isso é aplicado/removido automaticamente pelo gerenciador scrollsnapchange na etapa 7. Não defina isso nos builders de visualização.
  • As visualizações que o usuário desliza para trás são removidas do DOM (também pela etapa 7) para que a pilha nunca ultrapasse os filhos de currentDepth + 1. Eles são recriados sob demanda com base nos caminhos do URL armazenados em cache se a navegação para frente retornar a eles.

2. Estilos

O rolador de pilha

A pilha é uma grade horizontal em que cada visualização filha tem exatamente a largura do contêiner, com o ajuste de rolagem CSS aplicando uma visualização por ajuste. Isso dá ao gesto de deslizar para voltar uma sensação nativa.

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

O efeito de "pilha" (paralaxe / escurecimento / sombra)

Uma animação view(inline) orientada por rolagem acompanha o progresso de cada visualização pelo scroller de pilha e aplica um efeito de paralaxe e escurecimento à visualização que está saindo, além de uma sombra nas visualizações de detalhamento que estão entrando, para que sejam lidas como "cards" empilhados sobre a visualização anterior.

/* 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; }
  }
}

OBSERVAÇÃO: esse efeito é comum em aplicativos modernos de pilha nativa e é um bom ponto de partida, mas os efeitos visuais exatos podem ser personalizados para se adequar aos estilos de transição existentes, conforme necessário.

3. Estado do módulo

A pilha rastreia quatro partes do estado no escopo do módulo:

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;

Além de três auxiliares específicos do aplicativo, os únicos lugares em que o roteamento e a renderização de visualização do app são conectados:

// 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. Detalhar

Um detalhamento faz quatro coisas nesta ordem: envia uma entrada de histórico, cria a nova visualização, adiciona-a ao final e rola suavemente até ela. O gerenciador scrollsnapchange (etapa 7) assume o controle quando o ajuste é concluído.

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. Processamento de cliques e do botão "Voltar"

Interceptar cliques em links dentro da pilha e convertê-los em detalhamentos. Preserve o comportamento da tecla modificadora para que o comando/clique do meio ainda abra o link em uma nova guia.

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. Sincronizar do histórico (popstate)

popstate é disparado quando o usuário usa o botão "Voltar" ou "Avançar" do navegador/SO ou quando o JavaScript chama history.back() / .go(). Esse gerenciador é o único caminho que rola a pilha em resposta a uma mudança no histórico.

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: a única fonte de verdade

Após cada confirmação de ajuste, seja acionada por um deslize, um clique ou uma rolagem programática, o navegador dispara um evento scrollsnapchange no contêiner de rolagem, com o elemento recém-ajustado exposto como event.snapTargetInline (para ajuste horizontal). Colocar todas as transições de estado dentro desse gerenciador é o que mantém os caminhos de deslizar, clicar e popstate coerentes.

O gerenciador é extraído para uma função onActiveViewChanged independente para que o substituto (consulte "Estratégias de substituição" abaixo) possa reutilizá-lo sem duplicar a lógica.

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

Quando o carregamento de página ocorre, o URL pode já apontar para uma visualização profunda (um link compartilhado, um favorito, uma atualização em uma página profunda). Crie a visualização inicial que corresponda ao URL (raiz ou link direto, mas nunca ambos), adicione-a ao final da pilha vazia, preencha a entrada de histórico de profundidade 0 e execute uma passagem de rolagem inicial com behavior: 'instant' para que o paralaxe não seja animado na primeira pintura.

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

Práticas recomendadas

  • USE o evento scrollsnapchange (com um substituto IntersectionObserver, consulte "Estratégias de substituição") como a fonte de informações para "a visualização Active View mudou", não as coordenadas do evento de rolagem. O commit de ajuste é o único evento que é acionado de forma consistente em caminhos de deslizar, clicar, rolagem programática e popstate.
  • FAÇA transformações em um filho do destino de ajuste, nunca no próprio destino. Uma transformação no destino de ajuste é enviada de volta para a geometria de ajuste do contêiner de rolagem, e o scroller vai apresentar falhas no meio do gesto.
  • RECOMENDADO: aplique inert a todas as visualizações, exceto à que está visível no momento. Sem isso, o foco e a navegação do leitor de tela vazam para as visualizações ocultas atrás do paralaxe, que são invisíveis para usuários com visão, mas representam uma falha grave de acessibilidade.
  • FAÇA push de uma entrada de histórico em cada detalhamento e processe popstate para que o gesto de voltar do SO e os botões de voltar/avançar do navegador funcionem. É isso que faz o padrão parecer um app nativo.
  • RECONCILIE o histórico do gerenciador de visualização ativa alterada quando um gesto de deslizar para trás chegar a uma visualização com profundidade diferente de currentDepth. Sem isso, um retorno subsequente do SO leva o usuário a um lugar inesperado, porque o cursor do histórico do navegador não está sincronizado com o que está na tela.
  • REMOVA as visualizações que o usuário já passou do DOM. Caso contrário, uma sessão de detalhamento longa pode acumular dezenas de subárvores separadas. O caminho do URL armazenado em cache em entriesByDepth é suficiente para recriar qualquer visualização se a navegação para frente retornar a ela.
  • CHAME .focus({preventScroll: true}) ao restaurar o foco dentro da pilha. O preventScroll: false padrão faz com que o navegador role o destino do foco para a visualização, o que entra em conflito com o contêiner de ajuste e pode deixar o usuário no meio do ajuste.
  • FAÇA a preservação do cmd/ctrl/clique do meio em links internos para que os URLs continuem compartilháveis e possam ser abertos em uma nova guia.
  • USE behavior: 'instant' para saltos de histórico em várias etapas E para transições de popstate espaciais (toIdx > fromIdx). Caso contrário, os saltos em várias etapas vão disparar scrollsnapchange em cada snap intermediário e realizar N rodadas de trabalho inerte/foco/histórico. Os popstates de avanço geralmente são falsos. O Safari do iOS trata os deslizamentos de borda como avanço do navegador, mesmo com overscroll-behavior-x: none definido, e uma troca instantânea é muito menos enganosa do que animar um "detalhamento" que o usuário não iniciou. O caminho de detalhamento iniciado pelo usuário (drillDown) não é afetado porque ele rola diretamente, não por popstate.
  • FAÇA o seguinte: respeite prefers-reduced-motion: declare scroll-behavior: smooth apenas dentro de @media (prefers-reduced-motion: no-preference) e chame scrollTo / scrollBy com behavior: 'auto' (não 'smooth') para que a preferência no nível do SO entre em vigor sem ramificação de JS por chamada. A codificação de behavior: 'smooth' ignora a configuração do usuário.
  • RECOMENDADO: renderize elementos <a href> reais como acionadores de detalhamento, não <button onclick> ou <div>. As âncoras reais recebem visualização de URL ao passar o cursor, compartilhamento, clique do meio, função de leitor de tela e SEO sem custo financeiro.
  • É RECOMENDÁVEL incluir um botão "Voltar" explícito em todas as visualizações detalhadas. O gesto de deslizar só funciona em telas touchscreen. Os usuários de teclado, ponteiro e computador precisam de uma affordance visível.
  • NÃO chame history.pushState do gerenciador popstate, porque isso envia novas entradas enquanto o usuário está tentando voltar e quebra o botão "Voltar" do navegador.
  • NÃO use um listener de eventos scroll para controlar o paralaxe quando as animações acionadas por rolagem estiverem disponíveis. O caminho CSS é executado no compositor. Um listener de rolagem JS é executado na linha de execução principal e vai perder frames visivelmente durante o gesto.
  • NÃO mude as visualizações removidas do DOM após um gesto de deslizar para voltar. Trate entriesByDepth como o registro canônico: uma entrada removida tem view: null e é recriada sob demanda em updateFromHistoryState.

Estratégias de fallback

Os recursos que podem exigir substitutos são scroll-snap-events e scroll-driven-animations, que têm histórias robustas de substituto ou aprimoramento progressivo e são seguros para uso neste caso de uso:

Eventos de ajuste de rolagem

O evento scrollsnapchange é a maneira mais limpa de detectar "a Active View mudou": um listener na pilha, acionado exatamente uma vez por commit de ajuste. Em navegadores sem ele, o mesmo efeito pode ser preenchido com um IntersectionObserver que observa cada visualização para ter visibilidade total dentro da pilha. O substituto é enviado para a mesma função onActiveViewChanged que o caminho principal usa, então toda a lógica de transição de estado permanece em um só lugar.

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

Animações de rolagem

O efeito de paralaxe / escurecimento / sombra acionado por rolagem é um aprimoramento progressivo do núcleo de navegação. O portão CSS @supports (animation-timeline: view()) (mostrado na etapa 2) limita a animação aos navegadores compatíveis. Em todos os outros lugares, as visualizações simplesmente cortam entre os pontos de ajuste sem transição. O componente é totalmente funcional sem o efeito de paralaxe: o ajuste, a sincronização do histórico, o gerenciamento de foco e o inert ainda funcionam.

Se um substituto de paralaxe for necessário para destinos de referência mais antigos, anexe um listener scroll à pilha e escreva uma propriedade personalizada de CSS que descreva o progresso de cada visualização pela porta de rolagem. Em seguida, use transform e filter com base nessa propriedade:

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