Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

11.2 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import {
  LazyImportBoundary,
  LazyImportFailure,
} from "@/components/lazy-import-boundary";

import { useT } from "@/i18n";

import {
  isImeComposing,
  useShortcut,
  useShortcutAvailable,
} from "@/features/settings/hooks/use-shortcut";
import { useDocumentFlag } from "@/lib/document-flag";
import { Z_LAYER } from "@/lib/z-layers";
import { Search01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
  type ReactNode,
  Suspense,
  lazy,
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import { createPortal } from "react-dom";
import { FIND_SCOPE_ATTRIBUTE } from "../lib/find-attributes.ts";
import { isFindScopeBackgrounded } from "../lib/find-backgrounded.ts";
import { type FindTarget, findTarget, findTargetHolding, onFindRequest, takeFindFocus } from "../lib/find-targets.ts";

const DISMISSIBLE_SURFACE_SELECTOR =
  '[data-slot="popover-content"], [role="menu"], [role="listbox"]';

function hasOpenDismissibleSurface(): boolean {
  const scope = document.querySelector(`[${FIND_SCOPE_ATTRIBUTE}]`);
  return [...document.querySelectorAll(DISMISSIBLE_SURFACE_SELECTOR)].some(
    (surface) =>
      scope?.contains(surface) !== true &&
      surface.getAttribute("data-state") !== "closed",
  );
}

const FindBar = lazy(() => import("./find-bar-loader.tsx"));

function FindBarAfterComposition({
  handoffBlock,
  children,
}: {
  handoffBlock: Promise<void> | null;
  children: ReactNode;
}) {
  if (handoffBlock) {
    throw handoffBlock;
  }
  return children;
}

function FindBarLoading({
  query,
  setQuery,
  close,
  focusToken,
  rememberSelection,
  queueStep,
  beginComposition,
  endComposition,
}: {
  query: string;
  setQuery: (query: string) => void;
  close: () => void;
  focusToken: number;
  rememberSelection: (input: HTMLInputElement) => void;
  queueStep: (delta: -1 | 1) => void;
  beginComposition: () => void;
  endComposition: () => void;
}) {
  const t = useT();
  const inputRef = useRef<HTMLInputElement>(null);
  // biome-ignore lint/correctness/useExhaustiveDependencies: focus per token.
  useLayoutEffect(() => {
    const input = inputRef.current;
    if (!input) return;
    input.focus();
    input.select();
    return () => rememberSelection(input);
  }, [focusToken, rememberSelection]);

  useEffect(() => {
    const onEscape = (event: KeyboardEvent) => {
      if (event.key !== "Escape" || isImeComposing(event)) return;
      if (isFindScopeBackgrounded()) return;
      if (hasOpenDismissibleSurface()) return;
      event.preventDefault();
      event.stopPropagation();
      close();
    };
    window.addEventListener("keydown", onEscape, true);
    return () => window.removeEventListener("keydown", onEscape, true);
  }, [close]);

  return (
    <div
      data-find-skip=""
      data-testid="find-in-page-loading"
      // biome-ignore lint/a11y/useSemanticElements: loading shell is a search landmark.
      role="search"
      aria-busy="true"
      aria-label={t("shell.find.label")}
      className="find-bar-surface fixed top-[calc(var(--studio-content-top-inset,0px)+3.5rem)] right-4 z-50 flex h-13 max-w-[calc(100vw-2rem)] items-center gap-1 rounded-full pr-5 pl-4.5"
    >
      <HugeiconsIcon
        icon={Search01Icon}
        strokeWidth={1.75}
        aria-hidden={true}
        className="mr-1.5 size-[calc(18px*var(--ui-space-scale,1))] shrink-0 text-muted-foreground"
      />
      <input
        ref={inputRef}
        type="text"
        value={query}
        onChange={(event) => setQuery(event.target.value)}
        onCompositionStart={beginComposition}
        onCompositionEnd={endComposition}
        onSelect={(event) => rememberSelection(event.currentTarget)}
        onKeyDown={(event) => {
          if (event.key !== "Enter" || isImeComposing(event.nativeEvent))
            return;
          event.preventDefault();
          queueStep(event.shiftKey ? -1 : 1);
        }}
        placeholder={t("shell.find.label")}
        aria-label={t("shell.find.label")}
        spellCheck={false}
        autoComplete="off"
        autoCorrect="off"
        className="w-40 min-w-0 bg-transparent text-ui-15 outline-none placeholder:text-muted-foreground sm:w-64"
      />
    </div>
  );
}

export function FindInPage({ enabled = true }: { enabled?: boolean }) {
  const t = useT();
  // Session state lives in the mounted shell, so unmounting on sign-out drops the query.
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [scope, setScope] = useState<string | null>(null);
  const [focusToken, setFocusToken] = useState(0);
  const loadingSelectionRef = useRef<{
    start: number;
    end: number;
    direction: "forward" | "backward" | "none";
  } | null>(null);

  const [pendingSteps, setPendingSteps] = useState<
    { query: string; delta: -1 | 1 }[]
  >([]);

  const [handoffBlock, setHandoffBlock] = useState<Promise<void> | null>(null);
  const releaseHandoffRef = useRef<(() => void) | null>(null);

  const releaseHandoffTimerRef = useRef<number | null>(null);
  const beginLoadingComposition = useCallback(() => {
    if (releaseHandoffTimerRef.current !== null) {
      window.clearTimeout(releaseHandoffTimerRef.current);
      releaseHandoffTimerRef.current = null;
    }
    if (releaseHandoffRef.current) {
      return;
    }
    let release: () => void = () => undefined;
    const block = new Promise<void>((resolve) => {
      release = resolve;
    });
    releaseHandoffRef.current = release;
    setHandoffBlock(block);
  }, []);
  const endLoadingComposition = useCallback(() => {
    releaseHandoffTimerRef.current = window.setTimeout(() => {
      releaseHandoffTimerRef.current = null;
      releaseHandoffRef.current?.();
      releaseHandoffRef.current = null;
      setHandoffBlock(null);
    }, 0);
  }, []);
  useEffect(
    () => () => {
      if (releaseHandoffTimerRef.current !== null) {
        window.clearTimeout(releaseHandoffTimerRef.current);
      }
      releaseHandoffRef.current?.();
      releaseHandoffRef.current = null;
    },
    [],
  );
  const originRef = useRef<HTMLElement | null>(null);
  // A native page lent its keys to the bar: they go back to it, not to the stale origin.
  const outsideRef = useRef<FindTarget | null>(null);
  const requestFocus = useCallback((targetId?: string | null) => {
    const active = document.activeElement;
    // Keys in a native page leave `activeElement` stale: that page is where the reader is.
    const outside = targetId === undefined ? takeFindFocus() : undefined;
    // Searches where the reader is: the page while focus is in the browser, else the chat. Pressed
    // again from the bar's own field, it keeps searching what it was.
    if (outside) outsideRef.current = outside;
    else if (!(active instanceof Element && active.closest('[role="search"]'))) outsideRef.current = null;
    if (targetId !== undefined) setScope(targetId);
    else if (outside) setScope(outside.id);
    else if (!(active instanceof Element && active.closest('[role="search"]')))
      setScope(findTargetHolding(active)?.id ?? null);
    if (
      originRef.current === null &&
      outsideRef.current === null &&
      active instanceof HTMLElement &&
      active.closest('[role="search"]') === null
    ) {
      originRef.current = active;
    }
    loadingSelectionRef.current = null;

    setPendingSteps([]);
    setOpen(true);
    setFocusToken((token) => token + 1);
  }, []);
  const rememberLoadingSelection = useCallback((input: HTMLInputElement) => {
    loadingSelectionRef.current = {
      start: input.selectionStart ?? input.value.length,
      end: input.selectionEnd ?? input.value.length,
      direction: input.selectionDirection ?? "none",
    };
  }, []);

  const queueLoadingStep = useCallback(
    (delta: -1 | 1) => {
      setPendingSteps((steps) => [...steps, { query, delta }]);
    },
    [query],
  );
  const clearPendingSteps = useCallback(() => setPendingSteps([]), []);
  const restoreLoadingSelection = useCallback((input: HTMLInputElement) => {
    const selection = loadingSelectionRef.current;
    if (!selection) return false;
    const length = input.value.length;
    input.setSelectionRange(
      Math.min(selection.start, length),
      Math.min(selection.end, length),
      selection.direction,
    );
    return true;
  }, []);
  const close = useCallback(() => {
    const origin = originRef.current;
    const outside = outsideRef.current;
    originRef.current = null;
    outsideRef.current = null;
    setOpen(false);
    requestAnimationFrame(() => {
      const active = document.activeElement;
      // The bar's own cleanup may already have focused the stale origin; the page had the keys.
      if (outside) {
        outside.returnFocus?.();
        return;
      }
      if (
        origin?.isConnected &&
        typeof origin.focus === "function" &&
        (active === null || active === document.body)
      ) {
        origin.focus({ preventScroll: true });
      }
    });
  }, []);

  useEffect(
    () =>
      onFindRequest((targetId) => {
        if (enabled && (targetId === null || findTarget(targetId)?.available())) requestFocus(targetId);
      }),
    [enabled, requestFocus],
  );

  useShortcut("findInPage", () => requestFocus(), {
    enabled,
    claims: () => !isFindScopeBackgrounded(),
  });

  // False while a modal is open.
  const foreground = useShortcutAvailable("findInPage", open);
  useDocumentFlag("data-find-bar-open", enabled && open && foreground);

  if (!enabled || !open) return null;
  // Hidden, not unmounted, under a modal so it returns as it was.
  return createPortal(
    <div
      data-find-bar-layer=""
      hidden={!foreground}
      className="fixed top-0 right-0"
      style={{ zIndex: Z_LAYER.WINDOW_BARS }}
    >
      <LazyImportBoundary
        fallback={
          <LazyImportFailure
            message={t("settings.dialog.panelFailed")}
            reloadLabel={t("settings.dialog.panelReload")}
            dismissLabel={t("common.close")}
            onDismiss={close}
            testId="find-in-page-load-failure"
            className="fixed top-3 right-3 z-[100] max-w-xs rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-lg"
          />
        }
      >
        <Suspense
          fallback={
            <FindBarLoading
              query={query}
              setQuery={setQuery}
              close={close}
              focusToken={focusToken}
              rememberSelection={rememberLoadingSelection}
              queueStep={queueLoadingStep}
              beginComposition={beginLoadingComposition}
              endComposition={endLoadingComposition}
            />
          }
        >
          <FindBarAfterComposition handoffBlock={handoffBlock}>
            <FindBar
              query={query}
              setQuery={setQuery}
              scope={scope}
              setScope={setScope}
              close={close}
              focusToken={focusToken}
              restoreSelection={restoreLoadingSelection}
              pendingSteps={pendingSteps}
              clearPendingSteps={clearPendingSteps}
            />
          </FindBarAfterComposition>
        </Suspense>
      </LazyImportBoundary>
    </div>,
    document.body,
  );
}