Navegar/cambiar entre pantallas de UI
Para navegar entre las diferentes pantallas de UI, es necesario utilizar un sistema de enrutamiento. Un sistema de enrutamiento le permite definir rutas (o caminos) para diferentes pantallas y gestionar la navegación entre ellas.
TanStack Router
TanStack Router es un sistema de enrutamiento para aplicaciones web que le permite gestionar la navegación entre diferentes páginas o componentes de forma sencilla y eficiente. Está diseñado para ser flexible y fácil de usar, y ofrece funciones avanzadas como soporte para parámetros dinámicos, gestión del estado del enrutador e integración con bibliotecas de renderizado como React, Vue y Angular.
La principal ventaja de TanStack Router es su capacidad de generar automáticamente la gestión de rutas mediante createFileRoute. Con createFileRoute, puede definir sus rutas simplemente creando archivos en una estructura de carpetas específica. Por ejemplo, si crea un archivo about.tsx en la carpeta src/routes, TanStack Router generará automáticamente una ruta para /about que renderiza el componente definido en about.tsx.
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/about")({
component: About,
});
function About() {
return (
<main className="page-wrap px-4 py-12">
<section className="island-shell rounded-2xl p-6 sm:p-8">
<p className="island-kicker mb-2">About</p>
<h1 className="display-title mb-3 text-4xl font-bold text-[var(--sea-ink)] sm:text-5xl">
A small starter with room to grow.
</h1>
<p className="m-0 max-w-3xl text-base leading-8 text-[var(--sea-ink-soft)]">
TanStack Start gives you type-safe routing, server functions, and modern SSR defaults. Use this as a
clean foundation, then layer in your own routes, styling, and add-ons.
</p>
</section>
</main>
);
}¿Cómo navegar entre pantallas/rutas?
Para navegar entre pantallas/rutas, utilice la función de navegación proporcionada por su sistema de enrutamiento.
Plantillas
En todas las plantillas, la interfaz StepLabelProps ya está extendida para incluir una función navigate. Puede encontrarla en el archivo pixi-vn.d.ts.
Para habilitar esto, la función de navegación debe incluirse en la interfaz StepLabelProps.
import { narration } from "@drincs/pixi-vn";
declare module "@drincs/pixi-vn" {
interface StepLabelProps {
navigate: (route: string) => void;
}
}Pruebas
Si se usa el Game.testing del plugin de Vite.js (consulte la sección "Vite.js plugin" más arriba y la
Agent Skill pixi-vn-testing) para permitir que un agente de IA pruebe el juego automáticamente, llame también a
Game.testing.setProps
aquí, para que navigate (y cualquier otra cosa que devuelva este hook) permanezca disponible para una sesión de prueba:
import { Game, StepLabelProps } from "@drincs/pixi-vn";
import useMyNavigate from "./useMyNavigate";
export default function useGameProps(): StepLabelProps {
const navigate = useMyNavigate();
const props = {
navigate,
};
Game.testing.setProps(props);
return props;
}ink
En todas las plantillas de ink, se ha introducido un comando hashtag personalizado para navegar entre rutas. To do this, you need to use the following syntax:
# navigate [route]route: La ruta/camino de destino. Por ejemplo,# navigate /new-route.
Cuando cree una nueva label, puede utilizar la función navigate para cambiar entre rutas:
export const startLabel = newLabel("start", [
({ navigate }) => {
navigate("/new-route");
},
]);Otras funcionalidades
Usar los botones de retroceso y avance del navegador puede provocar que el juego quede en un estado inconsistente. Esto se debe a que esas teclas permiten al jugador navegar entre rutas, no entre steps narrativos.
Se recomienda evitar que la ruta cambie cuando se presiona el botón de retroceso del navegador. Hay muchas formas de hacerlo, pero se sugiere el siguiente enfoque:
Intercepte el evento popstate, que se activa después de presionar el botón de retroceso del navegador, y llame a history.forward() para cancelar la navegación. Para permitir que los usuarios naveguen hacia atrás si presionan el botón de retroceso dos veces seguidas, podemos añadir un nuevo estado a la pila del historial en cada cambio de ruta.
Por ejemplo:
import { useLocation } from "@tanstack/react-router";
import { useEffect } from "react";
/**
* useConfirmBackNavigation
*
* Prevent accidental browser "back" navigation.
* Behavior:
* - On each `href` change it pushes a history state (`pushState`).
* - Listens for `popstate` and calls `history.forward()` to cancel a single
* press of the browser back button.
* - If the user presses back twice in succession (i.e. the second press occurs
* before the first is handled), the browser will navigate back.
*
* Usage: call this hook at the app root to avoid unintended back navigations
* (e.g. accidental taps or gestures). Returns `null`.
*/
export default function useConfirmBackNavigation() {
const { href } = useLocation();
useEffect(() => {
const isInIframe =
typeof window !== "undefined" && window.self !== window.top;
if (isInIframe) return;
const listener = () => {
window.history.forward();
};
window.addEventListener("popstate", listener);
return () => {
window.removeEventListener("popstate", listener);
};
}, []);
useEffect(() => {
window.history.pushState(null, href, href);
}, [href]);
}