Skip to content

Open source alternative to Semrush and Ahrefs

Fold small UI duplicates and settle pattern drift before the ShadCN port (EVE-285) (#715)

Ben Senescuef7ea399953f
diff --git a/src/client/components/AuthConfigErrorCard.tsx b/src/client/components/AuthConfigErrorCard.tsx
index a79bc683..c73450a4 100644
--- a/src/client/components/AuthConfigErrorCard.tsx
+++ b/src/client/components/AuthConfigErrorCard.tsx
@@ -1,5 +1,4 @@
import { ShieldAlert } from "lucide-react";
-import { isHostedClientAuthMode } from "@/lib/auth-mode";
const CLOUDFLARE_SETUP_GUIDE_URL =
"https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE.md#2-configure-authentication-and-secrets";
@@ -13,7 +12,10 @@ export function AuthConfigErrorCard({
message,
onRetry,
}: AuthConfigErrorCardProps) {
- const isHostedMode = isHostedClientAuthMode();
+ // Only name a mode's settings when the client build names that mode. With
+ // AUTH_MODE unset here the server mode is unknown, and the alert above
+ // already carries the server's exact message.
+ const clientAuthMode = import.meta.env.AUTH_MODE;
return (
<div className="card w-full max-w-2xl bg-base-100 border border-base-300 shadow-xl">
@@ -27,21 +29,22 @@ export function AuthConfigErrorCard({
<span>{message}</span>
</div>
- {isHostedMode ? (
+ {clientAuthMode === "hosted" ? (
<p className="text-sm text-base-content/70">
Hosted mode requires{" "}
<code className="mx-1">BETTER_AUTH_SECRET</code>
(32+ characters), <code className="mx-1">BETTER_AUTH_URL</code>, and
Google OAuth credentials on the deployment.
</p>
- ) : (
+ ) : null}
+ {clientAuthMode === "cloudflare_access" ? (
<p className="text-sm text-base-content/70">
Cloudflare Access mode requires
<code className="mx-1">TEAM_DOMAIN</code> (a full https URL) and
<code className="mx-1">POLICY_AUD</code> set on the deployment, with
an Access application protecting this hostname.
</p>
- )}
+ ) : null}
<div className="card-actions justify-end">
<button className="btn btn-ghost btn-sm" onClick={onRetry}>
diff --git a/src/client/components/Markdown.tsx b/src/client/components/Markdown.tsx
index fc566e39..728ef908 100644
--- a/src/client/components/Markdown.tsx
+++ b/src/client/components/Markdown.tsx
@@ -1,6 +1,7 @@
import type { ComponentPropsWithoutRef, ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
+import { safeHttpUrl } from "@/shared/safe-url";
type Props = {
/** Raw Markdown source to render. */
@@ -34,7 +35,7 @@ export function Markdown({ children, className }: Props) {
type AnchorProps = ComponentPropsWithoutRef<"a">;
function SafeAnchor({ href, children, ...rest }: AnchorProps) {
- const safeHref = isHttpUrl(href) ? href : undefined;
+ const safeHref = safeHttpUrl(href);
if (!safeHref) {
return <span className="underline decoration-dotted">{children}</span>;
}
@@ -51,20 +52,6 @@ function SafeAnchor({ href, children, ...rest }: AnchorProps) {
);
}
-function isHttpUrl(value: string | undefined): value is string {
- if (!value) return false;
- try {
- const url = new URL(value);
- if (url.protocol !== "http:" && url.protocol !== "https:") return false;
- // Mirror server-side `safeHttpUrl` — a `user:pass@host` URL shows one
- // hostname in link text while auth hits another.
- if (url.username || url.password) return false;
- return true;
- } catch {
- return false;
- }
-}
-
export const MARKDOWN_COMPONENTS = {
h1: ({ children }: { children?: ReactNode }) => (
<h1 className="mt-5 mb-2 text-base font-semibold first:mt-0">{children}</h1>
diff --git a/src/client/components/SafeExternalLink.tsx b/src/client/components/SafeExternalLink.tsx
index e7162a05..26369e22 100644
--- a/src/client/components/SafeExternalLink.tsx
+++ b/src/client/components/SafeExternalLink.tsx
@@ -1,6 +1,6 @@
import { ExternalLink } from "lucide-react";
-import { getSafeExternalUrl } from "./table/url";
+import { safeHttpUrl } from "@/shared/safe-url";
export function SafeExternalLink({
url,
@@ -11,7 +11,7 @@ export function SafeExternalLink({
label: string;
className: string;
}) {
- const safeUrl = getSafeExternalUrl(url);
+ const safeUrl = safeHttpUrl(url);
if (!safeUrl) {
return <span className={className}>{label}</span>;
}
diff --git a/src/client/components/SegmentedToggle.tsx b/src/client/components/SegmentedToggle.tsx
index 303a9616..9bec6646 100644
--- a/src/client/components/SegmentedToggle.tsx
+++ b/src/client/components/SegmentedToggle.tsx
@@ -22,6 +22,8 @@ export function SegmentedToggle<T extends string>({
{items.map((item) => (
<button
key={item.value}
+ type="button"
+ aria-pressed={value === item.value}
className={`btn btn-xs gap-1.5 px-2 ${value === item.value ? "bg-primary/20 text-primary shadow-sm" : "btn-ghost text-base-content/40"}`}
onClick={() => onChange(item.value)}
title={item.label}
diff --git a/src/client/components/ThemePreferenceMenuItems.tsx b/src/client/components/ThemePreferenceMenuItems.tsx
index 2c743a51..5fe0fbef 100644
--- a/src/client/components/ThemePreferenceMenuItems.tsx
+++ b/src/client/components/ThemePreferenceMenuItems.tsx
@@ -11,9 +11,48 @@ const THEME_OPTIONS: {
{ value: "dark", label: "Dark", icon: Moon },
];
-export function ThemePreferenceMenuItems() {
+/** System / Light / Dark segmented radio, shared by Settings and account menus. */
+export function ThemePreferenceRadio() {
const { themePreference, setThemePreference } = useThemePreference();
+ return (
+ <div
+ role="radiogroup"
+ aria-label="Theme preference"
+ className="flex gap-0.5 rounded-lg bg-base-200 p-0.5"
+ >
+ {THEME_OPTIONS.map((option) => {
+ const isActive = option.value === themePreference;
+ const Icon = option.icon;
+
+ return (
+ <div
+ key={option.value}
+ className="tooltip tooltip-bottom flex flex-1 before:whitespace-nowrap"
+ data-tip={option.label}
+ >
+ <button
+ type="button"
+ role="radio"
+ aria-checked={isActive}
+ aria-label={option.label}
+ className={`flex flex-1 cursor-pointer items-center justify-center rounded-md px-2.5 py-1.5 transition-colors ${
+ isActive
+ ? "bg-base-100 text-base-content shadow-sm"
+ : "text-base-content/50 hover:text-base-content/80"
+ }`}
+ onClick={() => setThemePreference(option.value)}
+ >
+ <Icon className="size-4" />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+export function ThemePreferenceMenuItems() {
return (
<>
<li className="menu-title pt-2">
@@ -21,39 +60,7 @@ export function ThemePreferenceMenuItems() {
</li>
<li>
- <div
- role="radiogroup"
- aria-label="Theme preference"
- className="flex gap-0.5 rounded-lg bg-base-200 p-0.5"
- >
- {THEME_OPTIONS.map((option) => {
- const isActive = option.value === themePreference;
- const Icon = option.icon;
-
- return (
- <div
- key={option.value}
- className="tooltip tooltip-bottom flex flex-1 before:whitespace-nowrap"
- data-tip={option.label}
- >
- <button
- type="button"
- role="radio"
- aria-checked={isActive}
- aria-label={option.label}
- className={`flex flex-1 cursor-pointer items-center justify-center rounded-md px-2.5 py-1.5 transition-colors ${
- isActive
- ? "bg-base-100 text-base-content shadow-sm"
- : "text-base-content/50 hover:text-base-content/80"
- }`}
- onClick={() => setThemePreference(option.value)}
- >
- <Icon className="size-4" />
- </button>
- </div>
- );
- })}
- </div>
+ <ThemePreferenceRadio />
</li>
</>
);
diff --git a/src/client/components/table/ScoreBadge.tsx b/src/client/components/table/ScoreBadge.tsx
index 8c47d60c..e25b43ed 100644
--- a/src/client/components/table/ScoreBadge.tsx
+++ b/src/client/components/table/ScoreBadge.tsx
@@ -14,7 +14,7 @@ export function ScoreBadge({ value }: { value: number | null }) {
<span
className={`score-badge ${scoreTierClass(value)} inline-flex size-6 items-center justify-center rounded-full text-[10px] font-semibold tabular-nums`}
>
- {value ?? "—"}
+ {value ?? "-"}
</span>
);
}
diff --git a/src/client/components/table/url.tsx b/src/client/components/table/url.tsx
index 5db636de..81c1ee0d 100644
--- a/src/client/components/table/url.tsx
+++ b/src/client/components/table/url.tsx
@@ -1,4 +1,5 @@
import { ExternalLink } from "lucide-react";
+import { safeHttpUrl } from "@/shared/safe-url";
export function formatUrlForDisplay(value: string): string {
try {
@@ -21,10 +22,10 @@ export function resolveUrlHref(
): string | null {
if (!value) return null;
if (/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(value)) {
- return getSafeExternalUrl(value);
+ return safeHttpUrl(value);
}
if (!baseDomain) return null;
- return getSafeExternalUrl(
+ return safeHttpUrl(
`https://${baseDomain}${value.startsWith("/") ? value : `/${value}`}`,
);
}
@@ -52,14 +53,3 @@ export function ExternalUrlCell({
</a>
);
}
-
-export function getSafeExternalUrl(value: string) {
- try {
- const parsed = new URL(value);
- return parsed.protocol === "http:" || parsed.protocol === "https:"
- ? parsed.toString()
- : null;
- } catch {
- return null;
- }
-}
diff --git a/src/client/features/audit/AuditDetail.tsx b/src/client/features/audit/AuditDetail.tsx
index cd47916c..9162d4fa 100644
--- a/src/client/features/audit/AuditDetail.tsx
+++ b/src/client/features/audit/AuditDetail.tsx
@@ -14,8 +14,8 @@ import {
formatStartedAt,
HttpStatusBadge,
StatusBadge,
- SUPPORT_EMAIL,
} from "@/client/features/audit/shared";
+import { SUPPORT_EMAIL } from "@/client/lib/support";
export function AuditDetail({
projectId,
diff --git a/src/client/features/audit/shared.tsx b/src/client/features/audit/shared.tsx
index 0ecf39d1..ffa1c89f 100644
--- a/src/client/features/audit/shared.tsx
+++ b/src/client/features/audit/shared.tsx
@@ -1,7 +1,5 @@
import { AlertCircle, CheckCircle, Loader2 } from "lucide-react";
-export const SUPPORT_EMAIL = "[email protected]";
-
export function extractPathname(url: string): string {
try {
return new URL(url).pathname;
diff --git a/src/client/features/backlinks/BacklinksPage.tsx b/src/client/features/backlinks/BacklinksPage.tsx
index 33e0cef3..f403f447 100644
--- a/src/client/features/backlinks/BacklinksPage.tsx
+++ b/src/client/features/backlinks/BacklinksPage.tsx
@@ -113,7 +113,6 @@ export function BacklinksPage({
</div>
<BacklinksSearchCard
- errorMessage={data.overviewErrorMessage}
initialValues={data.searchCardInitialValues}
onSubmit={(values) => {
searchTabs.openTab({ type: "backlinks", ...values });
diff --git a/src/client/features/backlinks/BacklinksSearchCard.tsx b/src/client/features/backlinks/BacklinksSearchCard.tsx
index 3c5f7561..24e0e5fe 100644
--- a/src/client/features/backlinks/BacklinksSearchCard.tsx
+++ b/src/client/features/backlinks/BacklinksSearchCard.tsx
@@ -45,11 +45,9 @@ function getBacklinksValidationErrors(
}
export function BacklinksSearchCard({
- errorMessage,
initialValues,
onSubmit,
}: {
- errorMessage: string | null;
initialValues: SearchDraft;
onSubmit: (values: SearchDraft) => void;
}) {
@@ -142,12 +140,6 @@ export function BacklinksSearchCard({
</form.Field>
</div>
</form>
-
- {errorMessage ? (
- <div className="rounded-lg border border-error/30 bg-error/10 p-3 text-sm text-error">
- {errorMessage}
- </div>
- ) : null}
</div>
</div>
);
diff --git a/src/client/features/backlinks/BacklinksTable.test.ts b/src/client/features/backlinks/BacklinksTable.test.ts
index c3369b21..a6abb0fb 100644
--- a/src/client/features/backlinks/BacklinksTable.test.ts
+++ b/src/client/features/backlinks/BacklinksTable.test.ts
@@ -25,6 +25,6 @@ it("distinguishes zero from missing spam scores without changing boundary values
const scores = $("tbody tr")
.map((_, row) => $(row).find("td").eq(6).text())
.get();
- expect(scores).toEqual(["—", "—", "0", "39", "40"]);
+ expect(scores).toEqual(["-", "-", "0", "39", "40"]);
expect($("[title='Spam score unknown']")).toHaveLength(2);
});
diff --git a/src/client/features/backlinks/BacklinksTableColumns.tsx b/src/client/features/backlinks/BacklinksTableColumns.tsx
index d7375308..2bc2ab57 100644
--- a/src/client/features/backlinks/BacklinksTableColumns.tsx
+++ b/src/client/features/backlinks/BacklinksTableColumns.tsx
@@ -277,7 +277,7 @@ function buildBaseColumns(
{value != null ? (
Math.round(value)
) : (
- <span title="Spam score unknown">—</span>
+ <span title="Spam score unknown">-</span>
)}
</div>
);
@@ -343,7 +343,7 @@ export function buildBacklinksColumns(
const dr = domain ? (ratings[domain] ?? null) : null;
return (
<div className="text-right tabular-nums text-sm">
- {dr == null ? "—" : formatDecimal(dr)}
+ {dr == null ? "-" : formatDecimal(dr)}
</div>
);
}),
diff --git a/src/client/features/backlinks/ReferringDomainsTable.tsx b/src/client/features/backlinks/ReferringDomainsTable.tsx
index a75bbad1..17e9e8c3 100644
--- a/src/client/features/backlinks/ReferringDomainsTable.tsx
+++ b/src/client/features/backlinks/ReferringDomainsTable.tsx
@@ -146,7 +146,7 @@ function buildReferringDomainColumns(domainRatings: DomainRatings | null) {
cell: ({ row }) => {
const domain = row.original.domain;
const dr = domain ? (ratings[domain] ?? null) : null;
- return dr == null ? "—" : formatDecimal(dr);
+ return dr == null ? "-" : formatDecimal(dr);
},
});
diff --git a/src/client/features/billing/PlanOfferCard.tsx b/src/client/features/billing/PlanOfferCard.tsx
index 612054d2..924b9aac 100644
--- a/src/client/features/billing/PlanOfferCard.tsx
+++ b/src/client/features/billing/PlanOfferCard.tsx
@@ -1,7 +1,6 @@
import type { ReactNode } from "react";
import type { PlanOffer } from "@/client/features/billing/plan-offers";
-
-const SUPPORT_EMAIL = "[email protected]";
+import { SUPPORT_EMAIL } from "@/client/lib/support";
// Shared card for the full-page checkout screens (/subscribe, /yc). Callers
// pass the CTA and any extra notes as children.
diff --git a/src/client/features/domain/DomainOverviewPage.tsx b/src/client/features/domain/DomainOverviewPage.tsx
index 070d082b..041156df 100644
--- a/src/client/features/domain/DomainOverviewPage.tsx
+++ b/src/client/features/domain/DomainOverviewPage.tsx
@@ -2,7 +2,6 @@
import { useCallback, useEffect, useMemo, useRef, type FormEvent } from "react";
import { useForm, useStore } from "@tanstack/react-form";
import { Globe } from "lucide-react";
-import { toast } from "sonner";
import {
DEFAULT_DOMAIN_KEYWORDS_PAGE_SIZE,
type DomainSearchParams,
@@ -388,9 +387,6 @@ function useDomainOverviewState({
tab: routeState.tab,
locationCode: routeState.locationCode,
});
- if (!overview.hasData) {
- toast.info("Not enough data for this domain");
- }
}, [
addSearch,
overview,
diff --git a/src/client/features/domain/components/DomainTableTabSurface.tsx b/src/client/features/domain/components/DomainTableTabSurface.tsx
index c8fc4f28..c71a5d19 100644
--- a/src/client/features/domain/components/DomainTableTabSurface.tsx
+++ b/src/client/features/domain/components/DomainTableTabSurface.tsx
@@ -10,6 +10,8 @@ type DomainTableExportAction = {
};
type Props = {
+ /** The scope's condition limit when saved filters exceed it, else null. */
+ overBudgetLimit: number | null;
showFilters: boolean;
onToggleFilters: () => void;
activeFilterCount: number;
@@ -25,6 +27,7 @@ type Props = {
};
export function DomainTableTabSurface({
+ overBudgetLimit,
showFilters,
onToggleFilters,
activeFilterCount,
@@ -40,6 +43,15 @@ export function DomainTableTabSurface({
}: Props) {
return (
<>
+ {overBudgetLimit != null ? (
+ <div className="alert alert-warning mb-3">
+ <span>
+ Saved filters exceed this scope&apos;s {overBudgetLimit}-condition
+ limit and were not applied. Open Filters to trim them.
+ </span>
+ </div>
+ ) : null}
+
<div className="flex items-center gap-2 px-4 py-2 border-b border-base-300">
<button
className={`btn btn-ghost btn-sm gap-1.5 ${showFilters ? "btn-active" : ""}`}
diff --git a/src/client/features/domain/components/KeywordsTab.tsx b/src/client/features/domain/components/KeywordsTab.tsx
index ce89c59c..0834bfcd 100644
--- a/src/client/features/domain/components/KeywordsTab.tsx
+++ b/src/client/features/domain/components/KeywordsTab.tsx
@@ -251,16 +251,8 @@ export function KeywordsTab({
}
/>
- {filtersOverBudget ? (
- <div className="alert alert-warning mb-3">
- <span>
- Saved filters exceed this scope&apos;s {maxConditions}-condition
- limit and were not applied. Open Filters to trim them.
- </span>
- </div>
- ) : null}
-
<DomainTableTabSurface
+ overBudgetLimit={filtersOverBudget ? maxConditions : null}
showFilters={showFilters}
onToggleFilters={() => setShowFilters((prev) => !prev)}
activeFilterCount={activeFilterCount}
diff --git a/src/client/features/domain/components/PagesTab.tsx b/src/client/features/domain/components/PagesTab.tsx
index 005c7427..8cfaacac 100644
--- a/src/client/features/domain/components/PagesTab.tsx
+++ b/src/client/features/domain/components/PagesTab.tsx
@@ -161,84 +161,74 @@ export function PagesTab({
});
return (
- <>
- {filtersOverBudget ? (
- <div className="alert alert-warning mb-3">
- <span>
- Saved filters exceed this scope&apos;s {maxConditions}-condition
- limit and were not applied. Open Filters to trim them.
- </span>
- </div>
- ) : null}
-
- <DomainTableTabSurface
- showFilters={showFilters}
- onToggleFilters={() => setShowFilters((prev) => !prev)}
- activeFilterCount={activeFilterCount}
- countLabel="pages"
- totalCount={totalCount}
- fallbackCount={rows.length}
- isLoading={isLoading}
- showTableLoading={showTableLoading}
- exportActions={[
- {
- label: "Export to Sheets",
- icon: <Sheet className="size-4" />,
- onClick: () => exportAll("sheets"),
- },
- {
- label: "Copy data (JSON)",
- icon: <Copy className="size-4" />,
- onClick: () => exportAll("copy-json"),
- },
- {
- label: "Download CSV",
- icon: <Download className="size-4" />,
- onClick: () => exportAll("csv"),
- },
- {
- label: "Download Excel",
- icon: <FileSpreadsheet className="size-4" />,
- onClick: () => exportAll("excel"),
- },
- ]}
- filterPanel={
- showFilters ? (
- <DomainFilterPanel
- activeFilterCount={activeFilterCount}
- appliedFilters={restoredFilters}
- fields={PAGE_FILTER_FIELDS}
- textFields={PAGE_TEXT_FILTERS}
- rangeFields={PAGE_RANGE_FILTERS}
- countConditions={countPageFilterConditions}
- maxConditions={maxConditions}
- onApply={applyFilters}
- onClear={resetFilters}
- />
- ) : null
- }
- pagination={
- <TablePagination
- page={routeState.page}
- pageSize={routeState.pageSize}
- pageSizes={DOMAIN_KEYWORDS_PAGE_SIZES}
- totalCount={totalCount}
- hasNextPage={hasNextPage}
- isLoading={isLoading}
- onPageChange={onPageChange}
- onPageSizeChange={onPageSizeChange}
- renderPageButton={DomainPageLink}
+ <DomainTableTabSurface
+ overBudgetLimit={filtersOverBudget ? maxConditions : null}
+ showFilters={showFilters}
+ onToggleFilters={() => setShowFilters((prev) => !prev)}
+ activeFilterCount={activeFilterCount}
+ countLabel="pages"
+ totalCount={totalCount}
+ fallbackCount={rows.length}
+ isLoading={isLoading}
+ showTableLoading={showTableLoading}
+ exportActions={[
+ {
+ label: "Export to Sheets",
+ icon: <Sheet className="size-4" />,
+ onClick: () => exportAll("sheets"),
+ },
+ {
+ label: "Copy data (JSON)",
+ icon: <Copy className="size-4" />,
+ onClick: () => exportAll("copy-json"),
+ },
+ {
+ label: "Download CSV",
+ icon: <Download className="size-4" />,
+ onClick: () => exportAll("csv"),
+ },
+ {
+ label: "Download Excel",
+ icon: <FileSpreadsheet className="size-4" />,
+ onClick: () => exportAll("excel"),
+ },
+ ]}
+ filterPanel={
+ showFilters ? (
+ <DomainFilterPanel
+ activeFilterCount={activeFilterCount}
+ appliedFilters={restoredFilters}
+ fields={PAGE_FILTER_FIELDS}
+ textFields={PAGE_TEXT_FILTERS}
+ rangeFields={PAGE_RANGE_FILTERS}
+ countConditions={countPageFilterConditions}
+ maxConditions={maxConditions}
+ onApply={applyFilters}
+ onClear={resetFilters}
/>
- }
- >
- <DomainPagesTable
- domain={hostname}
- rows={rows}
- sortMode={routeState.sort}
- currentSortOrder={routeState.order}
- onSortClick={onSortClick}
+ ) : null
+ }
+ pagination={
+ <TablePagination
+ page={routeState.page}
+ pageSize={routeState.pageSize}
+ pageSizes={DOMAIN_KEYWORDS_PAGE_SIZES}
+ totalCount={totalCount}
+ hasNextPage={hasNextPage}
+ isLoading={isLoading}
+ onPageChange={onPageChange}
+ onPageSizeChange={onPageSizeChange}
+ renderPageButton={DomainPageLink}
/>
- </DomainTableTabSurface>
- </>
+ }
+ >
+ <DomainPagesTable
+ domain={hostname}
+ rows={rows}
+ sortMode={routeState.sort}
+ currentSortOrder={routeState.order}
+ onSortClick={onSortClick}
+ />
+ </DomainTableTabSurface>
);
}
diff --git a/src/client/features/domain/domainRouteState.test.ts b/src/client/features/domain/domainRouteState.test.ts
index 0026b657..993d157e 100644
--- a/src/client/features/domain/domainRouteState.test.ts
+++ b/src/client/features/domain/domainRouteState.test.ts
@@ -65,6 +65,6 @@ describe("getDomainRouteState", () => {
expect(state.defaultLocationCode).toBe(2704);
expect(state.locationCode).toBe(2704);
- expect(state.sentLocationCode).toBe(2352);
+ expect(state.sentLocationCode).toBeUndefined();
});
});
diff --git a/src/client/features/domain/domainRouteState.ts b/src/client/features/domain/domainRouteState.ts
index 68acde68..b3fc3553 100644
--- a/src/client/features/domain/domainRouteState.ts
+++ b/src/client/features/domain/domainRouteState.ts
@@ -90,7 +90,12 @@ export function getDomainRouteState(
tab: search.tab ?? "keywords",
defaultLocationCode,
locationCode: normalizedLocationCode,
- sentLocationCode: search.loc,
+ // A non-Labs `loc` is dropped so the server uses the same default the
+ // location select shows.
+ sentLocationCode:
+ search.loc != null && isLabsLocationCode(search.loc)
+ ? search.loc
+ : undefined,
page: search.page != null && search.page > 0 ? search.page : 1,
pageSize: search.size ?? DEFAULT_DOMAIN_KEYWORDS_PAGE_SIZE,
appliedFilters: {
diff --git a/src/client/features/domain/utils.ts b/src/client/features/domain/utils.ts
index 85819bfb..e3be4d3d 100644
--- a/src/client/features/domain/utils.ts
+++ b/src/client/features/domain/utils.ts
@@ -75,7 +75,8 @@ export function formatMetric(
value: number | null | undefined,
hasData: boolean | undefined,
) {
- if (!hasData) return "Not enough data";
+ // The page's "Not enough data" banner explains the empty values.
+ if (!hasData) return "-";
return formatRounded(value);
}
diff --git a/src/client/features/keywords/components/DisplayPrimitives.tsx b/src/client/features/keywords/components/DisplayPrimitives.tsx
index b06743b6..14f2a5f2 100644
--- a/src/client/features/keywords/components/DisplayPrimitives.tsx
+++ b/src/client/features/keywords/components/DisplayPrimitives.tsx
@@ -1,7 +1,6 @@
import { ChevronDown, ChevronUp } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
-import { sortBy } from "remeda";
import {
Area,
AreaChart,
@@ -11,7 +10,11 @@ import {
YAxis,
} from "recharts";
import type { MonthlySearch } from "@/types/keywords";
-import { formatCompactNumber } from "../utils";
+import {
+ formatCompactNumber,
+ lastTwelveMonths,
+ MONTH_SHORT_LABELS,
+} from "../utils";
import {
FloatingTooltip,
useFloatingTooltip,
@@ -26,8 +29,7 @@ export type SortField =
export type SortDir = "asc" | "desc";
export function AreaTrendChart({ trend }: { trend: MonthlySearch[] }) {
- const sorted = sortBy(trend, (item) => item.year * 100 + item.month);
- const last12 = sorted.slice(-12);
+ const last12 = lastTwelveMonths(trend);
const containerRef = useRef<HTMLDivElement | null>(null);
const [chartWidth, setChartWidth] = useState(0);
@@ -51,25 +53,9 @@ export function AreaTrendChart({ trend }: { trend: MonthlySearch[] }) {
};
}, []);
- const monthLabels = [
- "Jan",
- "Feb",
- "Mar",
- "Apr",
- "May",
- "Jun",
- "Jul",
- "Aug",
- "Sep",
- "Oct",
- "Nov",
- "Dec",
- ];
const data = last12.map((m) => ({
- month: monthLabels[m.month - 1],
- year: m.year,
+ month: MONTH_SHORT_LABELS[m.month - 1],
searchVolume: m.searchVolume,
- label: `${monthLabels[m.month - 1]} ${m.year}`,
}));
return (
diff --git a/src/client/features/keywords/page/KeywordResearchResults.tsx b/src/client/features/keywords/page/KeywordResearchResults.tsx
index 604e83a0..0cefef7b 100644
--- a/src/client/features/keywords/page/KeywordResearchResults.tsx
+++ b/src/client/features/keywords/page/KeywordResearchResults.tsx
@@ -6,7 +6,10 @@ import {
Sheet,
SlidersHorizontal,
} from "lucide-react";
-import { sortBy } from "remeda";
+import {
+ lastTwelveMonths,
+ MONTH_SHORT_LABELS,
+} from "@/client/features/keywords/utils";
import {
AreaTrendChart,
OverviewStats,
@@ -32,36 +35,13 @@ import {
TableExportMenu,
} from "@/client/components/table/TableBulkActionBar";
-const MONTH_SHORT_LABELS = [
- "Jan",
- "Feb",
- "Mar",
- "Apr",
- "May",
- "Jun",
- "Jul",
- "Aug",
- "Sep",
- "Oct",
- "Nov",
- "Dec",
-] as const;
-
function formatTrendRangeLabel(trend: KeywordResearchRow["trend"]): string {
- if (trend.length === 0) return "Last 12 available months";
-
- const sorted = sortBy(trend, (item) => item.year * 100 + item.month);
- const last12 = sorted.slice(-12);
- const start = last12[0];
- const end = last12[last12.length - 1];
+ const last12 = lastTwelveMonths(trend);
+ if (last12.length === 0) return "Last 12 available months";
- const toLabel = (month: number, year: number) => {
- const monthLabel = MONTH_SHORT_LABELS[month - 1] ?? `M${month}`;
- return `${monthLabel} ${year}`;
- };
-
- const startLabel = toLabel(start.month, start.year);
- const endLabel = toLabel(end.month, end.year);
+ const [startLabel, endLabel] = [last12[0], last12[last12.length - 1]].map(
+ (m) => `${MONTH_SHORT_LABELS[m.month - 1] ?? `M${m.month}`} ${m.year}`,
+ );
return startLabel === endLabel ? startLabel : `${startLabel} - ${endLabel}`;
}
diff --git a/src/client/features/keywords/utils.ts b/src/client/features/keywords/utils.ts
index 909b86d5..ebdaedf9 100644
--- a/src/client/features/keywords/utils.ts
+++ b/src/client/features/keywords/utils.ts
@@ -1,5 +1,28 @@
+import { sortBy } from "remeda";
+import type { MonthlySearch } from "@/types/keywords";
+
export { LOCATIONS } from "./locations";
+export const MONTH_SHORT_LABELS = [
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec",
+] as const;
+
+/** The most recent 12 months of a trend, oldest first. */
+export function lastTwelveMonths(trend: MonthlySearch[]): MonthlySearch[] {
+ return sortBy(trend, (item) => item.year * 100 + item.month).slice(-12);
+}
+
export function parseTerms(value: string): string[] {
return value
.toLowerCase()
diff --git a/src/client/features/reports/ReportTemplatesList.tsx b/src/client/features/reports/ReportTemplatesList.tsx
index 5bb360b9..3e6bf9bc 100644
--- a/src/client/features/reports/ReportTemplatesList.tsx
+++ b/src/client/features/reports/ReportTemplatesList.tsx
@@ -34,8 +34,16 @@ export function ReportTemplatesList({
</thead>
<tbody>
{templates.map((template) => (
- <tr key={template.id}>
- <td className="font-medium">{template.name}</td>
+ <tr key={template.id} className="hover:bg-base-200">
+ <td>
+ <button
+ type="button"
+ className="link link-hover text-left font-medium"
+ onClick={() => onEdit(template)}
+ >
+ {template.name}
+ </button>
+ </td>
<td className="max-w-[420px] text-base-content/70">
{template.description}
</td>
diff --git a/src/client/features/reports/ReportsList.tsx b/src/client/features/reports/ReportsList.tsx
index 05f26728..aee29270 100644
--- a/src/client/features/reports/ReportsList.tsx
+++ b/src/client/features/reports/ReportsList.tsx
@@ -56,7 +56,7 @@ export function ReportsList({
that produced it: what a reader needs to tell two reports
on the same site apart. */}
<td className="text-base-content/70">
- {report.templateName ?? report.skill ?? "—"}
+ {report.templateName ?? report.skill ?? "-"}
</td>
<td className="whitespace-nowrap text-base-content/70">
{formatRelativeTime(report.updatedAt)}
diff --git a/src/client/features/reports/shared.tsx b/src/client/features/reports/shared.tsx
index cdf7a2d1..8eaf4c20 100644
--- a/src/client/features/reports/shared.tsx
+++ b/src/client/features/reports/shared.tsx
@@ -14,7 +14,7 @@ import {
} from "@/serverFunctions/reports";
import { sharePath } from "@/shared/report-share";
-// Query keys for both reports pages. staleTime is 0 wherever these are used:
+// Query keys for the reports and templates pages. staleTime is 0 wherever these are used:
// the pages exist to inspect what an agent just wrote, so the app-wide
// five-minute staleTime would show a pre-save list as current.
export const reportsQueryKey = (projectId: string) =>
@@ -23,6 +23,9 @@ export const reportsQueryKey = (projectId: string) =>
export const reportQueryKey = (projectId: string, reportId: string) =>
["report", projectId, reportId] as const;
+export const reportTemplatesQueryKey = (projectId: string) =>
+ ["report-templates", projectId] as const;
+
/**
* "Ben · Claude Code". The person is the half that means something (it comes
* from the session); the client half is a self-reported hint, so it stands
diff --git a/src/client/features/sam/samBetaOptIn.ts b/src/client/features/sam/samBetaOptIn.ts
index 1d142965..e8f5fd3c 100644
--- a/src/client/features/sam/samBetaOptIn.ts
+++ b/src/client/features/sam/samBetaOptIn.ts
@@ -13,10 +13,25 @@ const subscribe = (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
-const read = () => localStorage.getItem(STORAGE_KEY) === "1";
+// Opting in is one-way, so the in-memory flag wins. It covers a localStorage
+// that cannot read or store (private browsing, strict modes, a full quota).
+let optedInThisSession = false;
+const read = () => {
+ if (optedInThisSession) return true;
+ try {
+ return localStorage.getItem(STORAGE_KEY) === "1";
+ } catch {
+ return false;
+ }
+};
export function optInToSamBeta() {
- localStorage.setItem(STORAGE_KEY, "1");
+ optedInThisSession = true;
+ try {
+ localStorage.setItem(STORAGE_KEY, "1");
+ } catch {
+ // Kept in memory above.
+ }
captureClientEvent("sam:beta_opt_in");
listeners.forEach((listener) => listener());
}
diff --git a/src/client/features/saved-keywords/SavedKeywordsBulkTagsModal.tsx b/src/client/features/saved-keywords/SavedKeywordsBulkTagsModal.tsx
index 0a334072..1bd94d2d 100644
--- a/src/client/features/saved-keywords/SavedKeywordsBulkTagsModal.tsx
+++ b/src/client/features/saved-keywords/SavedKeywordsBulkTagsModal.tsx
@@ -1,8 +1,8 @@
import { Check, Loader2, Plus, Search, X } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { Modal } from "@/client/components/Modal";
-import { resolveTagColor, tagDotClass } from "@/shared/tag-colors";
import type { SavedKeywordTag, SavedKeywordTagSummary } from "@/types/keywords";
+import { TagCheckboxRow } from "./TagCheckboxRow";
import { TagChip } from "./TagChip";
type Mode = "add" | "remove";
@@ -195,35 +195,15 @@ export function SavedKeywordsBulkTagsModal({
</div>
) : null}
- {filteredAvailable.map((tag) => {
- const checked = normalizedAddSet.has(tag.normalizedName);
- const color = resolveTagColor(tag);
- return (
- <button
- key={tag.id}
- type="button"
- onClick={() => handleToggleAdd(tag)}
- className="flex w-full items-center gap-2 px-3 py-1.5 text-left hover:bg-base-200"
- >
- <span
- className={`flex size-4 shrink-0 items-center justify-center rounded border ${
- checked
- ? "border-primary bg-primary text-primary-content"
- : "border-base-300"
- }`}
- >
- {checked ? <Check className="size-3" /> : null}
- </span>
- <span
- className={`size-2 shrink-0 rounded-full ${tagDotClass(color)}`}
- />
- <span className="flex-1 truncate text-sm">{tag.name}</span>
- <span className="text-[11px] tabular-nums text-base-content/45">
- {tag.keywordCount}
- </span>
- </button>
- );
- })}
+ {filteredAvailable.map((tag) => (
+ <TagCheckboxRow
+ key={tag.id}
+ tag={tag}
+ checked={normalizedAddSet.has(tag.normalizedName)}
+ onToggle={() => handleToggleAdd(tag)}
+ className="w-full px-3 py-1.5 hover:bg-base-200"
+ />
+ ))}
</div>
</div>
) : (
diff --git a/src/client/features/saved-keywords/SavedKeywordsFilters.tsx b/src/client/features/saved-keywords/SavedKeywordsFilters.tsx
index c60c87f8..893f1248 100644
--- a/src/client/features/saved-keywords/SavedKeywordsFilters.tsx
+++ b/src/client/features/saved-keywords/SavedKeywordsFilters.tsx
@@ -10,7 +10,7 @@ export function SavedKeywordsFilters({
activeFilterCount,
showFilters,
onToggleFilters,
- onResetAllFilters,
+ onResetFilters,
availableTags,
selectedTagIds,
busyTagIds,
@@ -23,7 +23,7 @@ export function SavedKeywordsFilters({
activeFilterCount: number;
showFilters: boolean;
onToggleFilters: () => void;
- onResetAllFilters: () => void;
+ onResetFilters: () => void;
availableTags: SavedKeywordTagSummary[];
selectedTagIds: string[];
busyTagIds: Set<string>;
@@ -68,7 +68,7 @@ export function SavedKeywordsFilters({
<SavedKeywordsFilterPanel
form={filtersForm}
activeFilterCount={activeFilterCount}
- onReset={onResetAllFilters}
+ onReset={onResetFilters}
/>
) : null}
</>
diff --git a/src/client/features/saved-keywords/SavedKeywordsTable.tsx b/src/client/features/saved-keywords/SavedKeywordsTable.tsx
index a670fdbc..bf950bec 100644
--- a/src/client/features/saved-keywords/SavedKeywordsTable.tsx
+++ b/src/client/features/saved-keywords/SavedKeywordsTable.tsx
@@ -127,6 +127,10 @@ export function SavedKeywordsTable({
getRowId: (row) => row.id,
enableRowSelection: true,
manualSorting: true,
+ // The server sorts by one column, so there is always exactly one sort:
+ // a click flips its direction and shift+click does not add a second.
+ enableSortingRemoval: false,
+ enableMultiSort: false,
});
return (
diff --git a/src/client/features/saved-keywords/SavedKeywordsTagFilter.tsx b/src/client/features/saved-keywords/SavedKeywordsTagFilter.tsx
index 64926ce6..ce58a5ab 100644
--- a/src/client/features/saved-keywords/SavedKeywordsTagFilter.tsx
+++ b/src/client/features/saved-keywords/SavedKeywordsTagFilter.tsx
@@ -1,5 +1,4 @@
import {
- Check,
ChevronDown,
MoreHorizontal,
Search,
@@ -7,13 +6,10 @@ import {
X,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
-import {
- resolveTagColor,
- tagDotClass,
- type TagColorKey,
-} from "@/shared/tag-colors";
+import type { TagColorKey } from "@/shared/tag-colors";
import type { SavedKeywordTagSummary } from "@/types/keywords";
import { ManageTagRow } from "./ManageTagRow";
+import { TagCheckboxRow } from "./TagCheckboxRow";
import { TagChip } from "./TagChip";
export function SavedKeywordsTagFilter({
@@ -102,7 +98,7 @@ export function SavedKeywordsTagFilter({
<ChevronDown className="size-3.5 opacity-60" />
</button>
- {selectedTags.length > 0 ? (
+ {hasSelection ? (
<div className="mt-2 flex flex-wrap items-center gap-1.5">
{selectedTags.map((tag) => (
<TagChip
@@ -144,7 +140,6 @@ export function SavedKeywordsTagFilter({
onDeleteTag(tagId);
setManagingTagId(null);
}}
- onClearSelection={onClearSelection}
/>
) : null}
</div>
@@ -163,7 +158,6 @@ function TagFilterPopover({
onStartManaging,
onUpdateTag,
onDeleteTag,
- onClearSelection,
}: {
availableTags: SavedKeywordTagSummary[];
filteredTags: SavedKeywordTagSummary[];
@@ -179,7 +173,6 @@ function TagFilterPopover({
input: { name?: string; color?: TagColorKey | null },
) => void;
onDeleteTag: (tagId: string) => void;
- onClearSelection: () => void;
}) {
return (
<div className="absolute right-0 top-full z-20 mt-2 w-80 max-w-[calc(100vw-2rem)] overflow-hidden rounded-lg border border-base-300 bg-base-100 shadow-2xl">
@@ -228,21 +221,6 @@ function TagFilterPopover({
/>
))}
</div>
-
- {selectedTagIds.length > 0 ? (
- <div className="flex items-center justify-between border-t border-base-300 px-2 py-1.5 text-xs">
- <span className="text-base-content/55">
- {selectedTagIds.length} selected
- </span>
- <button
- type="button"
- className="rounded px-2 py-1 text-base-content/70 hover:bg-base-200"
- onClick={onClearSelection}
- >
- Clear all
- </button>
- </div>
- ) : null}
</div>
);
}
@@ -266,32 +244,15 @@ function TagFilterRow({
onUpdate: (input: { name?: string; color?: TagColorKey | null }) => void;
onDelete: () => void;
}) {
- const color = resolveTagColor(tag);
return (
<div>
<div className="group flex items-center gap-2 px-2 py-1.5 hover:bg-base-200">
- <button
- type="button"
- className="flex min-w-0 flex-1 items-center gap-2 text-left"
- onClick={onToggle}
- >
- <span
- className={`flex size-4 shrink-0 items-center justify-center rounded border ${
- checked
- ? "border-primary bg-primary text-primary-content"
- : "border-base-300"
- }`}
- >
- {checked ? <Check className="size-3" /> : null}
- </span>
- <span
- className={`size-2 shrink-0 rounded-full ${tagDotClass(color)}`}
- />
- <span className="min-w-0 flex-1 truncate text-sm">{tag.name}</span>
- <span className="shrink-0 text-[11px] tabular-nums text-base-content/45">
- {tag.keywordCount}
- </span>
- </button>
+ <TagCheckboxRow
+ tag={tag}
+ checked={checked}
+ onToggle={onToggle}
+ className="min-w-0 flex-1"
+ />
<button
type="button"
className={`rounded p-1 text-base-content/45 hover:bg-base-300 hover:text-base-content ${
diff --git a/src/client/features/saved-keywords/TagCheckboxRow.tsx b/src/client/features/saved-keywords/TagCheckboxRow.tsx
new file mode 100644
index 00000000..e251a3e6
--- /dev/null
+++ b/src/client/features/saved-keywords/TagCheckboxRow.tsx
@@ -0,0 +1,41 @@
+import { Check } from "lucide-react";
+import { resolveTagColor, tagDotClass } from "@/shared/tag-colors";
+import type { SavedKeywordTagSummary } from "@/types/keywords";
+
+/** Checkbox, color dot, name and keyword count for one tag in a tag list. */
+export function TagCheckboxRow({
+ tag,
+ checked,
+ onToggle,
+ className,
+}: {
+ tag: SavedKeywordTagSummary;
+ checked: boolean;
+ onToggle: () => void;
+ className: string;
+}) {
+ return (
+ <button
+ type="button"
+ className={`flex items-center gap-2 text-left ${className}`}
+ onClick={onToggle}
+ >
+ <span
+ className={`flex size-4 shrink-0 items-center justify-center rounded border ${
+ checked
+ ? "border-primary bg-primary text-primary-content"
+ : "border-base-300"
+ }`}
+ >
+ {checked ? <Check className="size-3" /> : null}
+ </span>
+ <span
+ className={`size-2 shrink-0 rounded-full ${tagDotClass(resolveTagColor(tag))}`}
+ />
+ <span className="min-w-0 flex-1 truncate text-sm">{tag.name}</span>
+ <span className="shrink-0 text-[11px] tabular-nums text-base-content/45">
+ {tag.keywordCount}
+ </span>
+ </button>
+ );
+}
diff --git a/src/client/features/search-performance/SearchPerformanceColumns.tsx b/src/client/features/search-performance/SearchPerformanceColumns.tsx
index 9c941b19..30f25aff 100644
--- a/src/client/features/search-performance/SearchPerformanceColumns.tsx
+++ b/src/client/features/search-performance/SearchPerformanceColumns.tsx
@@ -2,7 +2,7 @@ import { createColumnHelper, type ColumnDef } from "@tanstack/react-table";
import type { MutableRefObject } from "react";
import { makeSelectionColumn } from "@/client/components/table/AppDataTable";
import { SortableHeader } from "@/client/components/table/SortableHeader";
-import { getSafeExternalUrl } from "@/client/components/table/url";
+import { safeHttpUrl } from "@/shared/safe-url";
import type { SelectionAnchor } from "@/client/components/table/tableSelection";
import type {
getSearchPerformanceReport,
@@ -108,7 +108,7 @@ export function buildStrikingColumns(
// the scheme check is defense-in-depth before rendering an href.
cell: ({ getValue }) => (
<a
- href={getSafeExternalUrl(getValue()) ?? undefined}
+ href={safeHttpUrl(getValue()) ?? undefined}
target="_blank"
rel="noreferrer"
className="link link-hover block max-w-sm truncate"
diff --git a/src/client/features/team/TeamSettings.tsx b/src/client/features/team/TeamSettings.tsx
index a8ca6c0c..8425e278 100644
--- a/src/client/features/team/TeamSettings.tsx
+++ b/src/client/features/team/TeamSettings.tsx
@@ -1,4 +1,9 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ useMutation,
+ useMutationState,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { QueryError } from "@/client/components/QueryState";
@@ -19,6 +24,19 @@ import { authClient, useSession } from "@/lib/auth-client";
import { hasOrgPermission } from "@/lib/org-permissions";
import { getTeam, sendTeamInvitation } from "@/serverFunctions/organization";
+const RESEND_KEY = ["team", "resend-invitation"];
+const REMOVE_KEY = ["team", "remove-member"];
+const CANCEL_KEY = ["team", "cancel-invitation"];
+
+// Every in-flight call for one action, so each row stays disabled while its
+// own request runs even when another row starts the same action.
+function usePendingVariables(mutationKey: string[]) {
+ return useMutationState({
+ filters: { mutationKey, status: "pending" },
+ select: (mutation) => mutation.state.variables,
+ });
+}
+
// The Organization tab of account settings: who has access to the active org.
export function TeamSettings() {
const { data: session } = useSession();
@@ -42,6 +60,7 @@ export function TeamSettings() {
// Same server call as inviting: for an already-pending address it re-mails
// the same link with a refreshed expiry.
const resendMutation = useMutation({
+ mutationKey: RESEND_KEY,
mutationFn: (email: string) => sendTeamInvitation({ data: { email } }),
onSuccess: () => {
captureClientEvent("team:invitation_resend");
@@ -54,6 +73,7 @@ export function TeamSettings() {
});
const removeMemberMutation = useMutation({
+ mutationKey: REMOVE_KEY,
mutationFn: async (memberId: string) => {
const result = await authClient.organization.removeMember({
memberIdOrEmail: memberId,
@@ -70,6 +90,7 @@ export function TeamSettings() {
});
const cancelInvitationMutation = useMutation({
+ mutationKey: CANCEL_KEY,
mutationFn: async (invitationId: string) => {
const result = await authClient.organization.cancelInvitation({
invitationId,
@@ -87,6 +108,10 @@ export function TeamSettings() {
},
});
+ const pendingResends = usePendingVariables(RESEND_KEY);
+ const pendingRemovals = usePendingVariables(REMOVE_KEY);
+ const pendingCancels = usePendingVariables(CANCEL_KEY);
+
const role = orgContextQuery.data?.role ?? "member";
const canManageTeam = hasOrgPermission(role, { invitation: ["create"] });
// billing:manage is the owner-only statement (organization:delete is
@@ -152,7 +177,7 @@ export function TeamSettings() {
isSelf={member.userId === session?.user?.id}
canManageTeam={canManageTeam}
isOwner={isOwner}
- isRemoving={removeMemberMutation.isPending}
+ isRemoving={pendingRemovals.includes(member.id)}
onRemove={() => removeMemberMutation.mutate(member.id)}
onTransferOwnership={() => setTransferTarget(member)}
/>
@@ -162,8 +187,8 @@ export function TeamSettings() {
key={invitation.id}
invitation={invitation}
canManageTeam={canManageTeam}
- isResending={resendMutation.isPending}
- isCanceling={cancelInvitationMutation.isPending}
+ isResending={pendingResends.includes(invitation.email)}
+ isCanceling={pendingCancels.includes(invitation.id)}
onResend={() => resendMutation.mutate(invitation.email)}
onCancel={() =>
cancelInvitationMutation.mutate(invitation.id)
diff --git a/src/client/lib/clipboard.ts b/src/client/lib/clipboard.ts
index 56058bdd..92fdd342 100644
--- a/src/client/lib/clipboard.ts
+++ b/src/client/lib/clipboard.ts
@@ -1,4 +1,5 @@
import { normalizeExportValue, type CsvValue, type ExportValue } from "./csv";
+import { safeHttpUrl } from "@/shared/safe-url";
export const GOOGLE_SHEETS_NEW_URL = "https://sheets.new";
@@ -54,22 +55,13 @@ function buildHtmlTable(headers: string[], rows: ExportValue[][]): string {
function escapeHtmlCell(value: ExportValue): string {
if (typeof value === "number" || typeof value === "boolean")
return String(value);
- if (isLinkableUrl(value)) {
+ if (safeHttpUrl(value)) {
const safeValue = escapeHtml(value);
return `<a href="${escapeHtml(value)}">${safeValue}</a>`;
}
return escapeHtml(value);
}
-function isLinkableUrl(value: string): boolean {
- try {
- const url = new URL(value);
- return url.protocol === "http:" || url.protocol === "https:";
- } catch {
- return false;
- }
-}
-
function escapeHtml(value: string): string {
return value
.replace(/&/g, "&amp;")
diff --git a/src/client/lib/support.ts b/src/client/lib/support.ts
new file mode 100644
index 00000000..f2e72eda
--- /dev/null
+++ b/src/client/lib/support.ts
@@ -0,0 +1 @@
+export const SUPPORT_EMAIL = "[email protected]";
diff --git a/src/client/lib/theme.ts b/src/client/lib/theme.ts
index e59012de..a45543a3 100644
--- a/src/client/lib/theme.ts
+++ b/src/client/lib/theme.ts
@@ -8,10 +8,18 @@ const DARK_THEME_NAME = "openseo-dark";
const THEME_STORAGE_KEY = "theme-preference";
const THEME_CHANGE_EVENT = "theme-preference-change";
+// Set when localStorage cannot store a pick (private browsing, strict modes,
+// a full quota): the pick then holds for this page session and wins over
+// whatever localStorage still returns.
+let unsavedThemePreference: ThemePreference | null = null;
+
function readThemePreference(): ThemePreference {
if (typeof window === "undefined") {
return "system";
}
+ if (unsavedThemePreference) {
+ return unsavedThemePreference;
+ }
try {
const stored = window.localStorage.getItem(THEME_STORAGE_KEY);
@@ -31,8 +39,9 @@ function writeThemePreference(themePreference: ThemePreference) {
} else {
window.localStorage.setItem(THEME_STORAGE_KEY, themePreference);
}
+ unsavedThemePreference = null;
} catch {
- // localStorage can be unavailable in private browsing or strict browser modes.
+ unsavedThemePreference = themePreference;
}
}
diff --git a/src/routes/_app/settings/index.tsx b/src/routes/_app/settings/index.tsx
index cda40f7d..85f20c64 100644
--- a/src/routes/_app/settings/index.tsx
+++ b/src/routes/_app/settings/index.tsx
@@ -1,9 +1,8 @@
import { createFileRoute } from "@tanstack/react-router";
-import { Monitor, Moon, Sun } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { ApiKeySettings } from "@/client/features/settings/ApiKeySettings";
-import { type ThemePreference, useThemePreference } from "@/client/lib/theme";
+import { ThemePreferenceRadio } from "@/client/components/ThemePreferenceMenuItems";
import { authClient, useSession } from "@/lib/auth-client";
import { isHostedClientAuthMode } from "@/lib/auth-mode";
import { version } from "../../../../package.json";
@@ -12,19 +11,8 @@ export const Route = createFileRoute("/_app/settings/")({
component: PersonalSettings,
});
-const THEME_OPTIONS: {
- value: ThemePreference;
- label: string;
- icon: typeof Sun;
-}[] = [
- { value: "system", label: "System", icon: Monitor },
- { value: "light", label: "Light", icon: Sun },
- { value: "dark", label: "Dark", icon: Moon },
-];
-
function PersonalSettings() {
const isHosted = isHostedClientAuthMode();
- const { themePreference, setThemePreference } = useThemePreference();
const { data: session } = useSession();
const [isSaving, setIsSaving] = useState(false);
@@ -54,34 +42,7 @@ function PersonalSettings() {
<h2 className="text-sm font-medium text-base-content/50">Appearance</h2>
<div className="flex items-center justify-between gap-6">
<span className="text-sm">Theme</span>
- <div
- role="radiogroup"
- aria-label="Theme preference"
- className="flex gap-0.5 rounded-lg bg-base-200 p-0.5"
- >
- {THEME_OPTIONS.map((option) => {
- const isActive = option.value === themePreference;
- const Icon = option.icon;
-
- return (
- <button
- key={option.value}
- type="button"
- role="radio"
- aria-checked={isActive}
- aria-label={option.label}
- className={`flex cursor-pointer items-center justify-center rounded-md px-3 py-1.5 transition-colors ${
- isActive
- ? "bg-base-100 text-base-content shadow-sm"
- : "text-base-content/50 hover:text-base-content/80"
- }`}
- onClick={() => setThemePreference(option.value)}
- >
- <Icon className="size-4" />
- </button>
- );
- })}
- </div>
+ <ThemePreferenceRadio />
</div>
</section>
diff --git a/src/routes/_app/support.tsx b/src/routes/_app/support.tsx
index 58aecd98..e9d34133 100644
--- a/src/routes/_app/support.tsx
+++ b/src/routes/_app/support.tsx
@@ -2,8 +2,8 @@ import { createFileRoute } from "@tanstack/react-router";
import { Check, Copy } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
+import { SUPPORT_EMAIL } from "@/client/lib/support";
-const SUPPORT_EMAIL = "[email protected]";
const DISCORD_URL = "https://discord.gg/c9uGs3cFXr";
const GITHUB_URL = "https://github.com/every-app/open-seo";
diff --git a/src/routes/_authenticated.subscribe.tsx b/src/routes/_authenticated.subscribe.tsx
index 24bef8c4..5d93c315 100644
--- a/src/routes/_authenticated.subscribe.tsx
+++ b/src/routes/_authenticated.subscribe.tsx
@@ -18,8 +18,7 @@ import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection"
import { normalizeAuthRedirect } from "@/lib/auth-redirect";
import { useCanManageBilling } from "@/client/features/team/organizationQueries";
import { AUTUMN_MANAGED_ACCESS_FEATURE_ID } from "@/shared/billing";
-
-const SUPPORT_EMAIL = "[email protected]";
+import { SUPPORT_EMAIL } from "@/client/lib/support";
const PLAN_FEATURES = [
"Keyword research, backlinks, rank tracking, and site audits",
@@ -269,7 +268,11 @@ function SubscribePage() {
<div className="text-center space-y-2">
<p className="text-sm text-base-content/60">
- Questions? Email {SUPPORT_EMAIL}.
+ Questions? Email{" "}
+ <a className="link" href={`mailto:${SUPPORT_EMAIL}`}>
+ {SUPPORT_EMAIL}
+ </a>
+ .
</p>
{isUpgradeFlow ? (
<button
diff --git a/src/routes/_authenticated.yc.tsx b/src/routes/_authenticated.yc.tsx
index e125aed5..24578b8d 100644
--- a/src/routes/_authenticated.yc.tsx
+++ b/src/routes/_authenticated.yc.tsx
@@ -20,8 +20,7 @@ import { captureClientEvent } from "@/client/lib/posthog";
import { useSession } from "@/lib/auth-client";
import { isHostedClientAuthMode } from "@/lib/auth-mode";
import { BILLING_ROUTE } from "@/shared/billing";
-
-const SUPPORT_EMAIL = "[email protected]";
+import { SUPPORT_EMAIL } from "@/client/lib/support";
const PLAN_FEATURES = [
"Keyword research, backlinks, rank tracking, and site audits",
@@ -197,7 +196,11 @@ function YcPlanPage() {
<div className="text-center space-y-2">
<p className="text-sm text-base-content/60">
- Questions? Email {SUPPORT_EMAIL}.
+ Questions? Email{" "}
+ <a className="link" href={`mailto:${SUPPORT_EMAIL}`}>
+ {SUPPORT_EMAIL}
+ </a>
+ .
</p>
<Link
to="/"
diff --git a/src/routes/_project/p/$projectId/reports/templates.tsx b/src/routes/_project/p/$projectId/reports/templates.tsx
index e5884821..4d590081 100644
--- a/src/routes/_project/p/$projectId/reports/templates.tsx
+++ b/src/routes/_project/p/$projectId/reports/templates.tsx
@@ -7,7 +7,10 @@ import { ConfirmDeleteModal } from "@/client/components/ConfirmDeleteModal";
import { QueryState } from "@/client/components/QueryState";
import { ReportTemplateForm } from "@/client/features/reports/ReportTemplateForm";
import { ReportTemplatesList } from "@/client/features/reports/ReportTemplatesList";
-import { reportsQueryKey } from "@/client/features/reports/shared";
+import {
+ reportsQueryKey,
+ reportTemplatesQueryKey,
+} from "@/client/features/reports/shared";
import { captureClientEvent } from "@/client/lib/posthog";
import {
deleteReportTemplate,
@@ -21,9 +24,6 @@ export const Route = createFileRoute(
component: ReportTemplatesPage,
});
-const templatesQueryKey = (projectId: string) =>
- ["report-templates", projectId] as const;
-
function ReportTemplatesPage() {
const { projectId } = Route.useParams();
const queryClient = useQueryClient();
@@ -34,13 +34,14 @@ function ReportTemplatesPage() {
);
const templatesQuery = useQuery({
- queryKey: templatesQueryKey(projectId),
+ queryKey: reportTemplatesQueryKey(projectId),
queryFn: () => listReportTemplates({ data: { projectId } }),
+ staleTime: 0,
});
const invalidate = () => {
void queryClient.invalidateQueries({
- queryKey: templatesQueryKey(projectId),
+ queryKey: reportTemplatesQueryKey(projectId),
});
// The reports list renders the template name in its Type column.
void queryClient.invalidateQueries({
diff --git a/src/routes/_project/p/$projectId/saved.tsx b/src/routes/_project/p/$projectId/saved.tsx
index d98c74d6..23b9ab8f 100644
--- a/src/routes/_project/p/$projectId/saved.tsx
+++ b/src/routes/_project/p/$projectId/saved.tsx
@@ -69,19 +69,27 @@ function SavedKeywordsPage() {
const [committedFilterValues, setCommittedFilterValues] = useState(
filters.values,
);
+ const [committedTagIds, setCommittedTagIds] = useState(selectedTagIds);
+ // Field edits and tag toggles share one debounce, so a burst of changes
+ // sends one query.
useEffect(() => {
const timer = window.setTimeout(() => {
setCommittedFilterValues(filters.values);
+ setCommittedTagIds(selectedTagIds);
setPage(1);
}, FILTER_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
- }, [filters.values]);
+ }, [filters.values, selectedTagIds]);
const appliedFilters = useMemo(
() => compileSavedKeywordsFilters(committedFilterValues),
[committedFilterValues],
);
+ const visibleFilters = useMemo(
+ () => compileSavedKeywordsFilters(filters.values),
+ [filters.values],
+ );
const sortState = sorting[0];
const sort = toSavedKeywordSort(sortState?.id);
@@ -90,7 +98,7 @@ function SavedKeywordsPage() {
? "desc"
: "asc"
: "desc";
- const tagFilterKey = selectedTagIds.join("|");
+ const tagFilterKey = committedTagIds.join("|");
const hasActiveFilters =
filters.activeFilterCount > 0 || selectedTagIds.length > 0;
@@ -98,13 +106,13 @@ function SavedKeywordsPage() {
() => ({
projectId,
...appliedFilters,
- tagIds: selectedTagIds.length > 0 ? selectedTagIds : undefined,
+ tagIds: committedTagIds.length > 0 ? committedTagIds : undefined,
page,
pageSize,
sort,
order,
}),
- [appliedFilters, order, page, pageSize, projectId, selectedTagIds, sort],
+ [appliedFilters, committedTagIds, order, page, pageSize, projectId, sort],
);
const { data, isLoading, isFetching } = useQuery({
@@ -196,7 +204,9 @@ function SavedKeywordsPage() {
const tagManage = useTagManage(projectId);
const exporter = useSavedKeywordsExport({
projectId,
- appliedFilters,
+ // The visible filters, so an export started inside the debounce window
+ // still matches what the user picked.
+ appliedFilters: visibleFilters,
selectedTagIds,
sort,
order,
@@ -216,12 +226,6 @@ function SavedKeywordsPage() {
}
};
- const handleClearAllFilters = () => {
- filters.resetFilters();
- setSelectedTagIds([]);
- setPage(1);
- };
-
return (
<div className="overflow-auto px-4 py-4 pb-24 md:px-6 md:py-6 md:pb-8">
<div className="mx-auto max-w-6xl space-y-4">
@@ -240,7 +244,7 @@ function SavedKeywordsPage() {
activeFilterCount={filters.activeFilterCount}
showFilters={showFilters}
onToggleFilters={() => setShowFilters((v) => !v)}
- onResetAllFilters={handleClearAllFilters}
+ onResetFilters={filters.resetFilters}
availableTags={availableTags}
selectedTagIds={selectedTagIds}
busyTagIds={tagManage.busyTagIds}
@@ -250,12 +254,8 @@ function SavedKeywordsPage() {
? current.filter((id) => id !== tagId)
: [...current, tagId],
);
- setPage(1);
- }}
- onClearTagSelection={() => {
- setSelectedTagIds([]);
- setPage(1);
}}
+ onClearTagSelection={() => setSelectedTagIds([])}
onUpdateTag={(input) => void tagManage.updateTag(input)}
onDeleteTag={(tagId) => void handleDeleteTag(tagId)}
/>
diff --git a/src/routes/_project/p/$projectId/settings/integrations.tsx b/src/routes/_project/p/$projectId/settings/integrations.tsx
index 2654fb67..9fafca16 100644
--- a/src/routes/_project/p/$projectId/settings/integrations.tsx
+++ b/src/routes/_project/p/$projectId/settings/integrations.tsx
@@ -25,16 +25,13 @@ function ProjectIntegrationsRoute() {
return (
<div className="space-y-8">
{/* The ids are the targets old #search-console / #google-analytics deep
- links are redirected to from the settings index. */}
- <section id="search-console" className="scroll-mt-6 space-y-3">
- <h2 className="text-sm font-medium text-base-content/50">
- Search Console
- </h2>
+ links are redirected to from the settings index. Each card's title
+ names its integration, so the sections carry no heading. */}
+ <section id="search-console" className="scroll-mt-6">
<GoogleConnectionCard provider="gsc" projectId={projectId} />
</section>
- <section id="google-analytics" className="scroll-mt-6 space-y-3">
- <h2 className="text-sm font-medium text-base-content/50">Analytics</h2>
+ <section id="google-analytics" className="scroll-mt-6">
<GoogleConnectionCard provider="ga4" projectId={projectId} />
</section>
diff --git a/src/server/features/ai-search/services/brandLookupShaping.ts b/src/server/features/ai-search/services/brandLookupShaping.ts
index 7d2df705..a25b19fa 100644
--- a/src/server/features/ai-search/services/brandLookupShaping.ts
+++ b/src/server/features/ai-search/services/brandLookupShaping.ts
@@ -9,7 +9,7 @@ import type {
LlmMentionItem,
LlmTopPagesItem,
} from "@/server/lib/dataforseoLlmSchemas";
-import { safeHostname, safeHttpUrl } from "@/server/features/ai-search/safeUrl";
+import { safeHostname, safeHttpUrl } from "@/shared/safe-url";
import { deriveCitedSources } from "@/server/features/ai-search/services/citedSources";
import {
computeShareOfVoice,
diff --git a/src/server/features/ai-search/services/citedSources.ts b/src/server/features/ai-search/services/citedSources.ts
index 5d18041e..c3433e1a 100644
--- a/src/server/features/ai-search/services/citedSources.ts
+++ b/src/server/features/ai-search/services/citedSources.ts
@@ -4,7 +4,7 @@ import type {
LlmMentionItem,
LlmTopPagesItem,
} from "@/server/lib/dataforseoLlmSchemas";
-import { safeHostname, safeHttpUrl } from "@/server/features/ai-search/safeUrl";
+import { safeHostname, safeHttpUrl } from "@/shared/safe-url";
import { roundOrNull } from "@/server/features/ai-search/services/shareOfVoice";
import type { BrandLookupResult } from "@/types/schemas/ai-search";
import {
diff --git a/src/server/features/ai-search/services/promptExplorer.ts b/src/server/features/ai-search/services/promptExplorer.ts
index 512d7215..c0141be4 100644
--- a/src/server/features/ai-search/services/promptExplorer.ts
+++ b/src/server/features/ai-search/services/promptExplorer.ts
@@ -9,7 +9,7 @@ import {
getCached,
setCached,
} from "@/server/lib/r2-cache";
-import { safeHostname, safeHttpUrl } from "@/server/features/ai-search/safeUrl";
+import { safeHostname, safeHttpUrl } from "@/shared/safe-url";
import {
promptExplorerModelResultSchema,
type PromptExplorerCitation,
diff --git a/src/server/features/ai-search/safeUrl.test.ts b/src/shared/safe-url.test.ts
similarity index 93%
rename from src/server/features/ai-search/safeUrl.test.ts
rename to src/shared/safe-url.test.ts
index 75138f89..7309abf8 100644
--- a/src/server/features/ai-search/safeUrl.test.ts
+++ b/src/shared/safe-url.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { safeHostname, safeHttpUrl } from "./safeUrl";
+import { safeHostname, safeHttpUrl } from "./safe-url";
describe("safeHttpUrl", () => {
it.each(["http://example.com", "https://example.com/path?q=1#frag"])(
diff --git a/src/server/features/ai-search/safeUrl.ts b/src/shared/safe-url.ts
similarity index 70%
rename from src/server/features/ai-search/safeUrl.ts
rename to src/shared/safe-url.ts
index 9f58bc87..2e355504 100644
--- a/src/server/features/ai-search/safeUrl.ts
+++ b/src/shared/safe-url.ts
@@ -1,11 +1,11 @@
/**
- * Validate a URL string against an http(s) scheme allow-list.
+ * Validate a URL string against an http(s) scheme allow-list. The one check
+ * for every external URL the app renders as `<a href>` or exports as a link.
*
- * AI Search renders citation and top-page URLs as `<a href>` in the UI. The
- * URLs come from either DataForSEO (mostly safe but still external) or LLM
- * responses (untrusted — a crafted prompt can coax a model into emitting
- * `javascript:`/`data:` payloads). Without this filter, those links are
- * clickable from inside an authenticated session.
+ * The URLs come from DataForSEO (mostly safe but still external), Search
+ * Console, or LLM responses (untrusted — a crafted prompt can coax a model
+ * into emitting `javascript:`/`data:` payloads). Without this filter, those
+ * links are clickable from inside an authenticated session.
*
* Returns the URL string unchanged if its protocol is `http:` or `https:`,
* otherwise null. Callers should drop null entries before rendering.