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

getShowIntro.ts

43 lines1.3 KB

1import { createIsomorphicFn } from "@tanstack/react-start";
2import { getCookie, setCookie } from "@tanstack/react-start/server";
3import { z } from "zod";
4​
5// NOTE: when we'll have different users -> respect the user's id
6const INTRO_COOKIE_NAME = "intro-visibility";
7const INTRO_COOKIE_AGE = 60 * 60 * 24 * 365; // 1 year
8​
9const showIntroSchema = z.enum(["hidden", "visible"]).catch("visible");
10​
11type ShowIntroUtils = {
12 showIntroState: z.infer<typeof showIntroSchema>;
13 updateShowIntro: (state: "hidden" | "visible") => void;
14};
15​
16export const getShowIntro = createIsomorphicFn()
17 .server((): ShowIntroUtils => {
18 const showIntro = getCookie(INTRO_COOKIE_NAME);
19 return {
20 showIntroState: showIntroSchema.parse(showIntro),
21 updateShowIntro: (state: "hidden" | "visible") => {
22 setCookie(INTRO_COOKIE_NAME, state, {
23 path: "/",
24 maxAge: INTRO_COOKIE_AGE,
25 });
26 },
27 };
28 })
29 .client((): ShowIntroUtils => {
30 const showIntro = document.cookie
31 .split("; ")
32 .find((row) => row.startsWith(`${INTRO_COOKIE_NAME}=`))
33 ?.split("=")[1];
34​
35 return {
36 showIntroState: showIntroSchema.parse(showIntro),
37 updateShowIntro: (state: "hidden" | "visible") => {
38 document.cookie = `${INTRO_COOKIE_NAME}=${state}; path=/; max-age=${
39 INTRO_COOKIE_AGE
40 }`;
41 },
42 };
43 });