Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Orama search (again) #115

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 24 additions & 26 deletions app/modules/color-scheme/components.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useLayoutEffect, useMemo } from "react";
import { useMemo } from "react";
import type { SerializeFrom } from "@remix-run/node";
import { useMatches, useNavigation } from "@remix-run/react";
import type { loader as rootLoader } from "../../root";
import type { ColorScheme } from "./types";
import { useLayoutEffect } from "~/ui/utils";

export function useColorScheme(): ColorScheme {
let rootLoaderData = useMatches()[0].data as SerializeFrom<typeof rootLoader>;
Expand All @@ -29,34 +30,31 @@ export function ColorSchemeScript() {
// we don't want this script to ever change
);

if (typeof document !== "undefined") {
// eslint-disable-next-line
useLayoutEffect(() => {
if (colorScheme === "light") {
document.documentElement.classList.remove("dark");
} else if (colorScheme === "dark") {
document.documentElement.classList.add("dark");
} else if (colorScheme === "system") {
function check(media: MediaQueryList) {
if (media.matches) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
useLayoutEffect(() => {
if (colorScheme === "light") {
document.documentElement.classList.remove("dark");
} else if (colorScheme === "dark") {
document.documentElement.classList.add("dark");
} else if (colorScheme === "system") {
function check(media: MediaQueryList) {
if (media.matches) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}

let media = window.matchMedia("(prefers-color-scheme: dark)");
check(media);
let media = window.matchMedia("(prefers-color-scheme: dark)");
check(media);

// @ts-expect-error I can't figure out what TypeScript wants here ...
media.addEventListener("change", check);
// @ts-expect-error
return () => media.removeEventListener("change", check);
} else {
console.error("Impossible color scheme state:", colorScheme);
}
}, [colorScheme]);
}
// @ts-expect-error I can't figure out what TypeScript wants here ...
media.addEventListener("change", check);
// @ts-expect-error
return () => media.removeEventListener("change", check);
} else {
console.error("Impossible color scheme state:", colorScheme);
}
}, [colorScheme]);

return <script dangerouslySetInnerHTML={{ __html: script }} />;
}
46 changes: 46 additions & 0 deletions app/modules/search/ab-session.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { createCookieSessionStorage } from "@remix-run/node";

export let unencryptedSession = createCookieSessionStorage({
cookie: {
name: "ab_session",
path: "/",
sameSite: "lax",
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7), // 1 week
},
});

const SESSION_KEY = "ab-docsearch-bucket";

export async function bucketUser(request: Request) {
let session = await unencryptedSession.getSession(
request.headers.get("Cookie")
);

let { searchParams } = new URL(request.url);
let bucket = searchParams.get("bucket");

// if the bucket isn't being overridden by a query parameter, use the session
if (!isBucketValue(bucket)) {
bucket = session.get(SESSION_KEY);
}

// if no bucket in the session, assign the user
if (!isBucketValue(bucket)) {
bucket = Math.random() > 0.5 ? "orama" : "docsearch";
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BEFORE MERGING: Change this to 0.1

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BEFORE MERGING ;)

}

let safeBucket = isBucketValue(bucket) ? bucket : "docsearch";

session.set(SESSION_KEY, safeBucket);

return {
bucket: safeBucket,
headers: {
"Set-Cookie": await unencryptedSession.commitSession(session),
},
};
}

function isBucketValue(bucket: any): bucket is "docsearch" | "orama" {
return bucket === "docsearch" || bucket === "orama";
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import type { DocSearchProps } from "@docsearch/react";
import "@docsearch/css/dist/style.css";
import "~/styles/docsearch.css";
import { useHydrated } from "~/ui/utils";
import { Suspense, lazy } from "react";

Expand Down
71 changes: 71 additions & 0 deletions app/modules/search/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Suspense, lazy } from "react";
import { type loader as rootLoader } from "~/root";
import { useHydrated } from "~/ui/utils";
import { useRouteLoaderData } from "@remix-run/react";

import "@docsearch/css/dist/style.css";
import "~/styles/search.css";

const DocSearchButton = lazy(() =>
import("./docsearch").then((module) => ({
default: module.DocSearch,
}))
);
const OramaSearchButton = lazy(() =>
import("./orama").then((module) => ({
default: module.SearchButton,
}))
);
const OramaSearch = lazy(() =>
import("./orama").then((module) => ({
default: module.SearchModalProvider,
}))
);

export function SearchModalProvider({
children,
}: {
children: React.ReactNode;
}) {
let bucket = useBucket();

if (bucket === "orama") {
return (
<Suspense fallback={null}>
<OramaSearch>{children}</OramaSearch>
</Suspense>
);
}

return <>{children}</>;
}

export function SearchButton() {
let hydrated = useHydrated();
let bucket = useBucket();

if (!hydrated) {
// The Algolia doc search container is hard-coded at 40px. It doesn't
// render anything on the server, so we get a mis-match after hydration.
// This placeholder prevents layout shift when the search appears.
return <div className="h-10" />;
}

return (
<Suspense fallback={<div className="h-10" />}>
<div className="animate-[fadeIn_100ms_ease-in_1]">
{bucket === "orama" ? <OramaSearchButton /> : <DocSearchButton />}
</div>
</Suspense>
);
}

function useBucket() {
const data = useRouteLoaderData<typeof rootLoader>("root");

if (!data) {
throw new Error("useBucket must be used within root route loader");
}

return data.bucket;
}
143 changes: 143 additions & 0 deletions app/modules/search/orama.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { Suspense, createContext, lazy, useContext, useState } from "react";
import { useHydrated, useLayoutEffect } from "~/ui/utils";
import { useColorScheme } from "~/modules/color-scheme/components";

import "@orama/searchbox/dist/index.css";

const OramaSearch = lazy(() =>
import("@orama/searchbox").then((module) => ({
default: module.SearchBox,
}))
);

const SearchModalContext = createContext<null | ((show: boolean) => void)>(
null
);

export function SearchModalProvider({
children,
}: {
children: React.ReactNode;
}) {
let [showSearchModal, setShowSearchModal] = useState(false);
const isHydrated = useHydrated();
const colorScheme = useSearchModalColorScheme();

return (
<SearchModalContext.Provider value={setShowSearchModal}>
<Suspense fallback={null}>
{isHydrated ? (
<OramaSearch
cloudConfig={{
// The search endpoint for the Orama index
url: "https://cloud.orama.run/v1/indexes/react-router-dev-nwm58f",
// The public API key for performing search. This is commit-safe.
key: "23DOEM1uyLIqnumsPZICJzw2Xn7GSFkj",
}}
show={showSearchModal}
onClose={() => setShowSearchModal(false)}
colorScheme={colorScheme}
theme="secondary"
themeConfig={{
light: {
"--background-color-fourth": "#f7f7f7",
},
dark: {
"--background-color-fourth": "#383838",
},
}}
resultsMap={{
description: "content",
}}
facetProperty="section"
backdrop
/>
) : null}
</Suspense>
{children}
</SearchModalContext.Provider>
);
}

function useSetShowSearchModal() {
let context = useContext(SearchModalContext);
if (!context) {
throw new Error("useSearchModal must be used within a SearchModalProvider");
}
return context;
}

export function SearchButton() {
let hydrated = useHydrated();
let setShowSearchModal = useSetShowSearchModal();

if (!hydrated) {
return <div className="h-10" />;
}

// TODO: replace styles
return (
<>
<div className="animate-[fadeIn_100ms_ease-in_1]">
<button
onClick={() => setShowSearchModal(true)}
type="button"
className="DocSearch DocSearch-Button"
aria-label="Search"
>
<span className="DocSearch-Button-Container">
<svg
width="20"
height="20"
className="DocSearch-Search-Icon"
viewBox="0 0 20 20"
>
<path
d="M14.386 14.386l4.0877 4.0877-4.0877-4.0877c-2.9418 2.9419-7.7115 2.9419-10.6533 0-2.9419-2.9418-2.9419-7.7115 0-10.6533 2.9418-2.9419 7.7115-2.9419 10.6533 0 2.9419 2.9418 2.9419 7.7115 0 10.6533z"
stroke="currentColor"
fill="none"
fillRule="evenodd"
strokeLinecap="round"
strokeLinejoin="round"
></path>
</svg>
<span className="DocSearch-Button-Placeholder">Search</span>
</span>
<span className="DocSearch-Button-Keys">
<kbd className="DocSearch-Button-Key">⌘</kbd>
<kbd className="DocSearch-Button-Key">K</kbd>
</span>
</button>
</div>
</>
);
}

// TODO: integrate this with ColorSchemeScript so we're not setting multiple listeners on the same media query
function useSearchModalColorScheme() {
let colorScheme = useColorScheme();
let [systemColorScheme, setSystemColorScheme] = useState<
null | "light" | "dark"
>(null);
useLayoutEffect(() => {
if (colorScheme !== "system") {
setSystemColorScheme(null);
return;
}
let media = window.matchMedia("(prefers-color-scheme: dark)");
let handleMedia = () =>
setSystemColorScheme(media.matches ? "dark" : "light");
handleMedia();
media.addEventListener("change", handleMedia);
return () => {
media.removeEventListener("change", handleMedia);
};
}, [colorScheme]);
if (colorScheme !== "system") {
return colorScheme;
}
if (systemColorScheme) {
return systemColorScheme;
}
return "dark";
}
6 changes: 5 additions & 1 deletion app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
import { isHost } from "./modules/http-utils/is-host";
import iconsHref from "~/icons.svg";
import stylesheet from "~/styles/tailwind.css?url";
import { bucketUser } from "./modules/search/ab-session.server";

export const links: LinksFunction = () => [
{ rel: "stylesheet", href: stylesheet },
Expand Down Expand Up @@ -49,12 +50,15 @@ export let loader = async ({ request }: LoaderFunctionArgs) => {
let colorScheme = await parseColorScheme(request);
let isProductionHost = isHost("reactrouter.com", request);

let { bucket, headers } = await bucketUser(request);

return json(
{ colorScheme, isProductionHost },
{ colorScheme, isProductionHost, bucket },
{
headers: {
"Cache-Control": CACHE_CONTROL.doc,
Vary: "Cookie",
...headers,
},
}
);
Expand Down
Loading