Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

22.1 KB
Raw Blame
import {
  createElement,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";

import { useAuth } from "@editor/auth/UseSession";
import { useToolWorkflow } from "@editor/contexts/ToolWorkflowContext";
import { useNavigationActions } from "@editor/contexts/NavigationContext";
import { ViewerContext } from "@editor/contexts/ViewerContext";
import { usePortalAccess } from "@editor/hooks/usePortalAccess";
import { useAppConfig } from "@editor/contexts/AppConfigContext";
import { useFileActions } from "@editor/contexts/file/fileHooks";
import { fileStorage } from "@editor/services/fileStorage";
import { FileDocIcon } from "@editor/components/shared/FileDocIcon";
import { getFileDocVariant } from "@editor/components/shared/filePreview/getFileTypeIcon";
import { detectFileExtension } from "@editor/utils/fileUtils";
import { openExternalUrl } from "@editor/utils/safeNavigation";
import {
  rankByFuzzy,
  idToWords,
  FUZZY_MIN_SCORE,
} from "@editor/utils/fuzzySearch";
import type { StirlingFileStub } from "@editor/types/fileContext";
import type { ToolId } from "@editor/types/toolId";
import {
  isComingSoonTool,
  type ToolRegistry,
} from "@editor/data/toolsTaxonomy";
import { SETTINGS_SEARCH_INDEX } from "@editor/data/settingsSearchIndex";
import { SETTINGS_SECTION_REGISTRY } from "@editor/data/settingsSectionRegistry";
import {
  buildMatchSnippet,
  findSettingsContentMatch,
} from "@editor/data/settingsContentSearch";
import {
  PROCESSOR_SEARCH_INDEX,
  isPortalEntityScopeAccessible,
  type ProcessorSearchEntry,
} from "@editor/data/processorSearchIndex";
import { useProcessorEntityGroups } from "@editor/data/processorEntitySearch";
import {
  PORTAL_ENTITY_SCOPE_DEFS,
  PORTAL_DOCS_SCOPE_ID,
  type SuperSearchGates,
  type SuperSearchGroup,
  type SuperSearchGroupId,
  type SuperSearchQueryOptions,
  type SuperSearchResult,
  type SuperSearchScope,
  type UseSuperSearchResult,
} from "@editor/types/superSearch";

// Re-exported so existing consumers keep one import site; the definitions
// live in the types leaf (see that module for why).
export type {
  SuperSearchGates,
  SuperSearchGroup,
  SuperSearchGroupId,
  SuperSearchQueryOptions,
  SuperSearchResult,
  SuperSearchScope,
  UseSuperSearchResult,
};

/**
 * How many results a ranker computes per group. This is the ceiling the
 * dropdown can reveal via "show more" — the component shows a small initial
 * slice per group and expands to the rest on demand.
 */
export const GROUP_RESULT_CEILING = 24;
/** Group display order in the dropdown. */
const GROUP_ORDER: SuperSearchGroupId[] = [
  "files",
  "tools",
  "settings",
  "processor",
];

/**
 * Whether the current user can enter the Processor at all: explicit portal
 * access, admin, or single-user mode with login disabled. Null gates (config
 * still loading) stay closed.
 */
export function isProcessorGateOpen(gates: SuperSearchGates | null): boolean {
  return (
    !!gates &&
    (gates.portalAccessible === true || gates.isAdmin || !gates.loginEnabled)
  );
}

/** The editor's visibility gates, from app config + the session's flags. */
export function useSuperSearchGates(): SuperSearchGates | null {
  const authState = useAuth();
  const { config } = useAppConfig();
  // Through the seam, not authState: on SaaS the editor's Supabase session
  // carries no permission flags, so reading it here hid every processor lane.
  const portalAccessible = usePortalAccess();
  return useMemo(
    () =>
      config
        ? {
            isAdmin: authState.isAdmin ?? config.isAdmin ?? false,
            loginEnabled: config.enableLogin ?? false,
            portalAccessible,
            isAnonymous: authState.isAnonymous,
            showSettingsWhenNoLogin: config.showSettingsWhenNoLogin ?? true,
          }
        : null,
    [authState.isAdmin, authState.isAnonymous, portalAccessible, config],
  );
}

/**
 * The editor bar's filter chips — one per source lane, granular over the
 * Processor's contents (pages plus each entity type). Processor lanes only
 * show when this build ships the portal and the user can enter it.
 */
export function useEditorSearchScopes(): SuperSearchScope[] {
  const { t } = useTranslation();
  const gates = useSuperSearchGates();
  const processorAvailable =
    PROCESSOR_SEARCH_INDEX.length > 0 && isProcessorGateOpen(gates);

  return useMemo(() => {
    const visibleViewIds = new Set(
      PROCESSOR_SEARCH_INDEX.map((entry) => entry.id),
    );
    return [
      {
        id: "files",
        label: t("superSearch.group.files", "Files"),
        aliases: ["file", "files"],
      },
      {
        id: "tools",
        label: t("superSearch.group.tools", "Tools"),
        aliases: ["tool", "tools"],
      },
      {
        id: "settings",
        label: t("superSearch.group.settings", "Settings"),
        aliases: ["setting", "settings"],
      },
      ...(processorAvailable
        ? [
            {
              id: "processor",
              label: t("superSearch.group.pages", "Pages"),
              aliases: ["page", "pages", "processor", "portal"],
            },
            ...PORTAL_ENTITY_SCOPE_DEFS.filter(
              (def) =>
                // A settings-hosted entity is reachable wherever the processor is.
                (def.settingsKey !== undefined ||
                  visibleViewIds.has(def.viewId)) &&
                isPortalEntityScopeAccessible(def.id, gates?.isAdmin ?? false),
            ).map((def) => ({
              id: def.id,
              label: t(def.labelKey, def.labelFallback),
              aliases: [...def.aliases],
            })),
            ...(visibleViewIds.has("docs")
              ? [
                  {
                    id: PORTAL_DOCS_SCOPE_ID,
                    label: t("superSearch.group.docs", "Docs"),
                    aliases: ["doc", "docs", "documentation"],
                  },
                ]
              : []),
          ]
        : []),
    ];
  }, [t, processorAvailable, gates?.isAdmin]);
}

/**
 * Shared scope handling for hosts that accept SuperSearchQueryOptions:
 * which source lanes are enabled for the current chip/prefix selection.
 */
export function useSearchScopeFilter(options?: SuperSearchQueryOptions): {
  scopeEnabled: (scopeId: string) => boolean;
} {
  const scopedIds = useMemo(
    () => new Set(options?.scopeIds ?? []),
    [options?.scopeIds],
  );
  const hasScopedSearch = scopedIds.size > 0;
  const scopeEnabled = useCallback(
    (scopeId: string) => !hasScopedSearch || scopedIds.has(scopeId),
    [hasScopedSearch, scopedIds],
  );
  return { scopeEnabled };
}

// ---------------------------------------------------------------------------
// Shared sources. Every host bar (editor workbench, portal shell) builds its
// results from these, so a query ranks identically everywhere — only the
// select actions differ (in-app contexts vs cross-app navigation).
// ---------------------------------------------------------------------------

/** Loads the My Files stubs whenever the search surface is open. */
export function useMyFilesStubs(active: boolean): {
  stubs: StirlingFileStub[];
  loadingFiles: boolean;
} {
  const [stubs, setStubs] = useState<StirlingFileStub[]>([]);
  const [loadingFiles, setLoadingFiles] = useState(false);
  const loadedOnceRef = useRef(false);

  useEffect(() => {
    if (!active) return;
    // Refresh whenever the surface opens so newly added files appear.
    let cancelled = false;
    if (!loadedOnceRef.current) setLoadingFiles(true);
    fileStorage
      .getLeafStirlingFileStubs()
      .then((all) => {
        if (cancelled) return;
        setStubs(all);
        loadedOnceRef.current = true;
      })
      .catch((err) => {
        console.error("[SuperSearch] Failed to load file stubs:", err);
      })
      .finally(() => {
        if (!cancelled) setLoadingFiles(false);
      });
    return () => {
      cancelled = true;
    };
  }, [active]);

  return { stubs, loadingFiles };
}

export function rankFileResults(
  stubs: StirlingFileStub[],
  trimmed: string,
  openFile: (stub: StirlingFileStub) => void | Promise<void>,
  limit = GROUP_RESULT_CEILING,
): SuperSearchResult[] {
  if (!trimmed) return [];
  return rankByFuzzy(stubs, trimmed, [(s) => s.name])
    .slice(0, limit)
    .map(({ item, score }) => ({
      key: `file:${item.id}`,
      group: "files",
      title: item.name,
      privateContent: true,
      // The file-type doc icon (PDF/image/doc/…) the sidebar and grid use,
      // rather than a flat generic file glyph.
      icon: createElement(FileDocIcon, {
        variant: getFileDocVariant(
          detectFileExtension(item.name.toLowerCase()),
          (item.type ?? "").toLowerCase(),
        ),
        size: "1.15rem",
      }),
      score,
      onSelect: () => openFile(item),
    }));
}

export function rankToolResults(
  registry: Partial<ToolRegistry>,
  trimmed: string,
  openTool: (id: ToolId) => void,
  limit = GROUP_RESULT_CEILING,
): SuperSearchResult[] {
  if (!trimmed) return [];
  // Coming-soon placeholders are listed in the catalogue but can't open —
  // selecting one would land on the "tool not found" panel.
  const entries = (
    Object.entries(registry) as [ToolId, ToolRegistry[ToolId] | undefined][]
  ).filter(([id, tool]) => tool && !isComingSoonTool(id, tool));
  return rankByFuzzy(entries, trimmed, [
    ([id]) => idToWords(id),
    ([, v]) => v?.name ?? "",
    ([, v]) => v?.description ?? "",
    ([, v]) => v?.synonyms?.join(" ") ?? "",
  ])
    .slice(0, limit)
    .map(({ item: [id, tool], score }) => ({
      key: `tool:${id}`,
      group: "tools",
      title: tool?.name ?? id,
      subtitle: tool?.description,
      icon: tool?.icon,
      score,
      onSelect: () => openTool(id),
    }));
}

export function rankSettingsResults(
  trimmed: string,
  t: TFunction,
  gates: SuperSearchGates | null,
  openSettings: (section: string, anchor?: string) => void,
  limit = GROUP_RESULT_CEILING,
): SuperSearchResult[] {
  if (!trimmed) return [];

  // Sections gated like the settings nav. The registry resolves per build
  // (core / proprietary / saas / desktop), so this only ever sees sections
  // the current build's settings page can actually show.
  const visibleSections = SETTINGS_SECTION_REGISTRY.filter((s) => {
    // Null gates (config still loading): hide every gated section.
    // requiresLogin keys off the deployment's login *mode*, mirroring the nav
    // builder: with login on the editor is login-walled (an unauthenticated
    // visitor never reaches this code), and with login off those sections
    // (account, API keys) have no meaning. Actual per-session auth state only
    // matters on SaaS, where requiresAccount/isAnonymous carries it.
    if (s.requiresLogin && !(gates?.loginEnabled ?? false)) return false;
    // Admin-area sections mirror the builder's gate: admins always; no-login
    // mode only while system.showSettingsWhenNoLogin keeps the admin preview.
    const adminGateOpen =
      !!gates &&
      (gates.isAdmin ||
        (!gates.loginEnabled && (gates.showSettingsWhenNoLogin ?? true)));
    if (s.adminArea && !adminGateOpen) return false;
    // Account-bound sections mirror the SaaS builder's `!isAnonymous` gate.
    if (s.requiresAccount && (gates ? (gates.isAnonymous ?? false) : true))
      return false;
    // The processor's own sections mirror its nav builder's portalAccess gate.
    if (s.requiresPortalAccess && gates?.portalAccessible !== true)
      return false;
    return true;
  });
  // Row context: the display label of the section the row lives in.
  const sectionLabelFor = new Map(
    visibleSections.map((s) => [s.key, t(s.labelKey, s.labelFallback)]),
  );

  // Row-level entries (deep-link by slug) take priority. Rows for
  // sections this build/user can't open are dropped with them.
  const rowMatches = rankByFuzzy(
    SETTINGS_SEARCH_INDEX.filter((e) => sectionLabelFor.has(e.section)),
    trimmed,
    [
      (e) => t(e.labelKey, e.labelFallback),
      (e) => e.labelFallback,
      (e) => e.keywords?.join(" ") ?? "",
    ],
  );
  const rows: SuperSearchResult[] = rowMatches.map(({ item, score }) => ({
    key: `setting:${item.section}:${item.anchor}`,
    group: "settings",
    title: t(item.labelKey, item.labelFallback),
    subtitle: sectionLabelFor.get(item.section),
    iconName: "settings",
    score: score + 1, // nudge rows above bare section matches
    onSelect: () => openSettings(item.section, item.anchor),
  }));
  // The nav group a section lives under, shown as result context (joined to a
  // content-match snippet with " · ").
  const groupTitle = (s: (typeof SETTINGS_SECTION_REGISTRY)[number]) =>
    s.groupLabelKey
      ? t(s.groupLabelKey, s.groupLabelFallback ?? "")
      : undefined;

  const sectionMatches = rankByFuzzy(visibleSections, trimmed, [
    (s) => t(s.labelKey, s.labelFallback),
    (s) => s.labelFallback,
    (s) => s.keywords?.join(" ") ?? "",
  ]);
  const sections: SuperSearchResult[] = sectionMatches.map(
    ({ item, score }) => ({
      key: `setting-section:${item.key}`,
      group: "settings",
      title: t(item.labelKey, item.labelFallback),
      subtitle: groupTitle(item),
      iconName: "settings",
      score,
      onSelect: () => openSettings(item.key),
    }),
  );

  // Content matches: sections whose rendered copy contains the query, so terms
  // with no curated keyword ("SMTP", a field label) still find their section.
  // Ranked below every label/keyword match; 3+ chars so a single letter doesn't
  // match half the modal. Sections already surfaced by a label match — their
  // own or a row's — are skipped so the same hit isn't listed twice.
  const labelMatchedKeys = new Set<string>([
    ...sectionMatches.map(({ item }) => item.key),
    ...rowMatches.map(({ item }) => item.section),
  ]);
  const contentMatches: SuperSearchResult[] =
    trimmed.length < 3
      ? []
      : visibleSections
          .filter((s) => !labelMatchedKeys.has(s.key))
          .flatMap((s) => {
            const match = findSettingsContentMatch(s.key, trimmed, t);
            if (!match) return [];
            const snippet = buildMatchSnippet(match, trimmed);
            const group = groupTitle(s);
            return [
              {
                key: `setting-content:${s.key}`,
                group: "settings",
                title: t(s.labelKey, s.labelFallback),
                subtitle: group ? `${group} · ${snippet}` : snippet,
                iconName: "settings",
                // Always below the weakest possible label/keyword match.
                score: FUZZY_MIN_SCORE - 10,
                onSelect: () => openSettings(s.key),
              },
            ];
          });

  return [...rows, ...sections, ...contentMatches]
    .sort((a, b) => b.score - a.score)
    .slice(0, limit);
}

export function rankProcessorResults(
  trimmed: string,
  t: TFunction,
  gates: SuperSearchGates | null,
  selectEntry: (entry: ProcessorSearchEntry) => void,
  limit = GROUP_RESULT_CEILING,
): SuperSearchResult[] {
  if (!trimmed || PROCESSOR_SEARCH_INDEX.length === 0) return [];
  // Only offer Processor pages to users who can actually enter that app.
  if (!isProcessorGateOpen(gates)) return [];
  return rankByFuzzy(PROCESSOR_SEARCH_INDEX, trimmed, [
    (e) => t(e.labelKey, e.labelFallback),
    (e) => e.labelFallback,
    (e) => e.keywords?.join(" ") ?? "",
  ])
    .slice(0, limit)
    .map(({ item, score }) => ({
      key: `processor:${item.id}`,
      group: "processor",
      title: t(item.labelKey, item.labelFallback),
      iconName: "layout-grid",
      score,
      onSelect: () => selectEntry(item),
    }));
}

/**
 * Orders the sources into the shared group layout, dropping empties. Hosts
 * pass their own order so local results lead (the editor puts its own
 * files/tools first and Processor pages last; the portal the reverse).
 */
export function assembleSuperSearchGroups(
  byId: Partial<Record<SuperSearchGroupId, SuperSearchResult[]>>,
  t: TFunction,
  order: SuperSearchGroupId[] = GROUP_ORDER,
): SuperSearchGroup[] {
  const labels: Record<SuperSearchGroupId, string> = {
    files: t("superSearch.group.files", "Files"),
    tools: t("superSearch.group.tools", "Tools"),
    settings: t("superSearch.group.settings", "Settings"),
    processor: t("superSearch.group.processor", "Processor"),
  };
  return order
    .map((id) => ({
      id,
      label: labels[id],
      results: byId[id] ?? [],
    }))
    .filter((g) => g.results.length > 0);
}

/**
 * The editor's results provider: the shared sources wired to in-app select
 * actions (open file → viewer, select tool in the workbench, deep-link into
 * the settings page, route into the Processor).
 *
 * @param query   current search text
 * @param active  whether the search surface is open; gates the My Files load
 */
export function useSuperSearch(
  query: string,
  active: boolean,
  options?: SuperSearchQueryOptions,
): UseSuperSearchResult {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const {
    toolRegistry,
    handleToolSelect,
    handleToolSelectForced,
    toolAvailability,
  } = useToolWorkflow();
  const { actions: navActions } = useNavigationActions();
  const { actions: fileActions } = useFileActions();
  // ViewerContext is only present once the viewer subtree mounts; treat as
  // optional. Read through a ref: the provider value is rebuilt every viewer
  // render, and a direct dependency would re-rank every result lane on each
  // page turn — openFile only needs the value at click time.
  const viewer = useContext(ViewerContext);
  const viewerRef = useRef(viewer);
  useEffect(() => {
    viewerRef.current = viewer;
  }, [viewer]);

  const trimmed = query.trim();
  const { stubs, loadingFiles } = useMyFilesStubs(active);
  const { scopeEnabled } = useSearchScopeFilter(options);

  // --- Actions -----------------------------------------------------------
  const openFile = useCallback(
    async (stub: StirlingFileStub) => {
      try {
        // The file already lives in storage — load it as a stub so its id and
        // metadata are preserved (addFiles would persist a duplicate record).
        await fileActions.addStirlingFileStubs([stub], { selectFiles: true });
        // Leaving the library is the view changing; HomePage takes the path with it.
        navActions.setWorkbench("viewer");
        viewerRef.current?.setActiveFileId?.(stub.id);
      } catch (err) {
        console.error("[SuperSearch] Failed to open file:", stub.name, err);
      }
    },
    [fileActions, navActions],
  );

  const openTool = useCallback(
    (id: ToolId) => {
      // Link tools have no in-editor UI — selecting one shows a "tool not
      // found" panel. Open their destination directly, matching how the
      // editor's tool lists treat them.
      const link = toolRegistry[id]?.link;
      if (link) {
        openExternalUrl(link);
        return;
      }
      // Tools whose backend endpoint isn't served in this environment are
      // flagged unavailable; handleToolSelect silently no-ops them. For a
      // search ("take me to Repair") we still want the click to open the
      // tool's UI, so fall back to the forced path for those. Available tools
      // keep the normal path so the unsaved-changes guard still applies.
      const available = toolAvailability[id]?.available !== false;
      if (available) {
        handleToolSelect(id);
      } else {
        handleToolSelectForced(id);
      }
    },
    [handleToolSelect, handleToolSelectForced, toolAvailability, toolRegistry],
  );

  const openSettings = useCallback(
    (section: string, anchor?: string) => {
      const path = anchor
        ? `/settings/${section}#${encodeURIComponent(anchor)}`
        : `/settings/${section}`;
      navigate(path);
    },
    [navigate],
  );

  const selectProcessorEntry = useCallback(
    (item: ProcessorSearchEntry) => {
      if (item.externalUrl) {
        openExternalUrl(item.externalUrl);
      } else {
        navigate(item.path);
      }
    },
    [navigate],
  );

  // --- Assemble ----------------------------------------------------------
  const gates = useSuperSearchGates();

  // Processor entities (users, policies, pipelines, sources) join the pages
  // under the Processor section — same access gate as the pages group, each
  // entity type filterable by its own scope.
  const entityGroups = useProcessorEntityGroups(
    trimmed,
    active && trimmed.length > 0 && isProcessorGateOpen(gates),
    t,
    navigate,
    scopeEnabled,
    gates?.isAdmin ?? false,
  );

  const groups = useMemo<SuperSearchGroup[]>(() => {
    const assembledGroups = assembleSuperSearchGroups(
      {
        files: scopeEnabled("files")
          ? rankFileResults(stubs, trimmed, openFile)
          : [],
        tools: scopeEnabled("tools")
          ? rankToolResults(toolRegistry, trimmed, openTool)
          : [],
        settings: scopeEnabled("settings")
          ? rankSettingsResults(trimmed, t, gates, openSettings)
          : [],
        processor: scopeEnabled("processor")
          ? rankProcessorResults(trimmed, t, gates, selectProcessorEntry)
          : [],
      },
      t,
    );

    // Section order: Editor first, Settings second, Processor last.
    const processorSection = t("superSearch.group.processor", "Processor");
    const sectionFor = (groupId: string): string => {
      if (groupId === "processor") return processorSection;
      if (groupId === "settings")
        return t("superSearch.group.settings", "Settings");
      return t("portal.nav.editor", "Editor");
    };
    return [
      ...assembledGroups.map((group) => ({
        ...group,
        label:
          group.id === "processor"
            ? t("superSearch.group.pages", "Pages")
            : group.label,
        sectionLabel: sectionFor(group.id),
      })),
      ...entityGroups.map((group) => ({
        ...group,
        sectionLabel: processorSection,
      })),
    ];
  }, [
    stubs,
    trimmed,
    openFile,
    toolRegistry,
    openTool,
    gates,
    openSettings,
    selectProcessorEntry,
    scopeEnabled,
    entityGroups,
    t,
  ]);

  const flatResults = useMemo(() => groups.flatMap((g) => g.results), [groups]);

  return { groups, flatResults, loadingFiles };
}