Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

try-it.tsx

67 lines2.4 KB

1import type { LinkOptions } from "@tanstack/react-router";
2import { Check, Play } from "lucide-react";
3import { createContext, useContext } from "react";
4import type { ReactNode } from "react";
5​
6import { useIsSectionDone } from "./guide-store";
7​
8/**
9 * Opens the app on a section's screen. Provided where the app is out of view
10 * (the small-screen layout, where it lives in a sheet); without a provider the
11 * guide renders no "Try it" buttons, because the app is already on screen.
12 */
13export type TryItHandler = (sectionId: string, target: LinkOptions) => void;
14​
15const TryItContext = createContext<TryItHandler | null>(null);
16​
17export function TryItProvider({
18 onTryIt,
19 children,
20}: {
21 onTryIt: TryItHandler;
22 children: ReactNode;
23}) {
24 return <TryItContext value={onTryIt}>{children}</TryItContext>;
26​
27/** Whether the app is in a sheet (small screens) rather than beside the guide. */
28export function useIsAppInSheet(): boolean {
29 return useContext(TryItContext) !== null;
31​
32/**
33 * Copy that depends on where the app is. Most guide copy is the same in both
34 * layouts; use this only where it can't be.
35 */
36export function ByGuideLayout({ beside, inSheet }: { beside: ReactNode; inSheet: ReactNode }) {
37 return useIsAppInSheet() ? inSheet : beside;
39​
40export function TryItButton({ sectionId, target }: { sectionId: string; target: LinkOptions }) {
41 const onTryIt = useContext(TryItContext);
42 const done = useIsSectionDone(sectionId);
43 if (!onTryIt) return null;
44​
45 return (
46 <div className="mt-5 flex items-center gap-3">
47 <button
48 type="button"
49 onClick={(event) => {
50 // Safari doesn't focus buttons on tap; focus it so closing the app returns here.
51 event.currentTarget.focus({ preventScroll: true });
52 onTryIt(sectionId, target);
53 }}
54 className="inline-flex h-10 items-center gap-2 rounded-full bg-notes-accent pr-4.5 pl-4 text-[15px] font-semibold text-black shadow-sm transition-transform outline-none focus-visible:ring-3 focus-visible:ring-notes-accent/40 active:scale-95"
55 >
56 <Play className="size-4 fill-current" aria-hidden />
57 Try it
58 </button>
59 {done && (
60 <span className="inline-flex items-center gap-1 text-sm font-medium text-emerald-700 dark:text-emerald-400">
61 <Check className="size-4" aria-hidden />
62 You did it
63 </span>
64 )}
65 </div>
66 );