Skip to content

Open source alternative to Semrush and Ahrefs

1.4 KB
Raw Blame
import { identity, sortBy } from "remeda";
import { z } from "zod";
import { useTimestampedSearchHistory } from "@/client/hooks/useTimestampedSearchHistory";
import {
  promptExplorerModelSchema,
  webSearchCountrySelectionSchema,
} from "@/types/schemas/ai-search";

const promptExplorerSearchBodySchema = z.object({
  prompt: z.string(),
  highlightBrand: z.string(),
  models: z.array(promptExplorerModelSchema),
  webSearch: z.boolean(),
  webSearchCountryCode: webSearchCountrySelectionSchema,
});

type PromptExplorerSearchBody = z.infer<typeof promptExplorerSearchBodySchema>;

function sameModels(a: string[], b: string[]): boolean {
  if (a.length !== b.length) return false;
  const sortedA = sortBy(a, identity());
  const sortedB = sortBy(b, identity());
  return sortedA.every((model, index) => model === sortedB[index]);
}

function isSameSearch(
  a: PromptExplorerSearchBody,
  b: PromptExplorerSearchBody,
): boolean {
  return (
    a.prompt === b.prompt &&
    a.highlightBrand === b.highlightBrand &&
    a.webSearch === b.webSearch &&
    a.webSearchCountryCode === b.webSearchCountryCode &&
    sameModels(a.models, b.models)
  );
}

export function usePromptExplorerSearchHistory(projectId: string) {
  return useTimestampedSearchHistory({
    storageKey: `prompt-explorer-search-history:${projectId}`,
    bodySchema: promptExplorerSearchBodySchema,
    isSame: isSameSearch,
  });
}