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.1 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 {
  UPDATE_NOTES_BULLET_CLASS,
  UPDATE_NOTES_EXPANDED_SCROLL_CLASS,
  UPDATE_NOTES_FOOTER_CLASS,
  UPDATE_NOTES_ITEM_CLASS,
  UPDATE_NOTES_LEAD_CLASS,
  UPDATE_NOTES_LINK_CLASS,
  UPDATE_NOTES_ROOT_CLASS,
  UPDATE_NOTES_SURFACE_CLASS,
} from "@/components/update/update-notes-layout";
import { useReleaseNotes } from "@/hooks/use-release-notes";
import { useT } from "@/i18n";
import { openLink } from "@/lib/open-link";
import { resolveReleaseBodyLinks } from "@/lib/release-body-links";
import {
  type ReleaseNotesLink,
  releaseNotesPreview,
} from "@/lib/release-notes-preview";
import {
  type MouseEvent,
  type ReactElement,
  type ReactNode,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";

type MarkdownPreviewComponent =
  typeof import("@/components/markdown/markdown-preview")["MarkdownPreview"];

let markdownPreviewModule: Promise<MarkdownPreviewComponent> | null = null;
let loadedMarkdownPreview: MarkdownPreviewComponent | null = null;

function loadMarkdownPreview(): Promise<MarkdownPreviewComponent> {
  if (!markdownPreviewModule) {
    markdownPreviewModule = import("@/components/markdown/markdown-preview").then(
      (module) => {
        loadedMarkdownPreview = module.MarkdownPreview;
        return module.MarkdownPreview;
      },
      (error: unknown) => {
        markdownPreviewModule = null;
        throw error;
      },
    );
  }
  return markdownPreviewModule;
}

function useMarkdownPreview(): {
  Preview: MarkdownPreviewComponent | null;
  failed: boolean;
  retry: () => void;
} {
  const [Preview, setPreview] = useState(() => loadedMarkdownPreview);
  const [failed, setFailed] = useState(false);
  useEffect(() => {
    if (Preview || failed) return;
    let live = true;
    loadMarkdownPreview().then(
      (component) => {
        if (live) setPreview(() => component);
      },
      () => {
        if (live) setFailed(true);
      },
    );
    return () => {
      live = false;
    };
  }, [Preview, failed]);
  const retry = useCallback(() => {
    window.location.reload();
  }, []);
  return { Preview, failed, retry };
}

interface ReleaseNotesPanelProps {
  version: string;
  open: boolean;
  releaseNotesUrl?: string | null;
}

function NotesMessage({
  children,
  action,
}: {
  children: ReactNode;
  action?: ReactNode;
}): ReactElement {
  return (
    <div className="flex items-center justify-between gap-2 px-1 py-2">
      <p className="text-ui-11 text-muted-foreground">{children}</p>
      {action}
    </div>
  );
}

// target="_blank" has nowhere to go in the Tauri webview; openLink() uses the system browser.
function handleExternalClick(event: MouseEvent<HTMLAnchorElement>): void {
  if (openLink(event.currentTarget.href)) {
    event.preventDefault();
  }
}

function NotesLink({
  href,
  isRelease,
}: {
  href: string;
  isRelease: boolean;
}): ReactElement {
  const t = useT();
  return (
    <a
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      onClick={handleExternalClick}
      className={UPDATE_NOTES_LINK_CLASS}
      data-testid="update-release-notes-link"
    >
      {isRelease ? t("updateNotes.openRelease") : t("updateNotes.openChangelog")}
    </a>
  );
}

export function ReleaseNotesPanel({
  version,
  open,
  releaseNotesUrl = null,
}: ReleaseNotesPanelProps): ReactElement | null {
  const t = useT();
  // Fetched with the popup: the collapsed preview needs the notes too.
  const { state, notes, retry } = useReleaseNotes({ version, enabled: true });
  const renderer = useMarkdownPreview();
  const scrollRef = useRef<HTMLElement | null>(null);

  // No fallback body: the updater's `notes` is install boilerplate the backend strips.
  const source = notes?.matched ? notes.markdown : null;
  // Notes target the repository, so relative links must point back at it.
  const markdown = useMemo(
    () => (source === null ? null : resolveReleaseBodyLinks(source)),
    [source],
  );

  // Notes that are only a code block or a table preview as nothing.
  const preview = useMemo(
    () => (markdown === null ? null : releaseNotesPreview(markdown)),
    [markdown],
  );

  // Start at the top on expand, and again once async notes land.
  const Preview = renderer.Preview;
  useEffect(() => {
    if (open && markdown && Preview && scrollRef.current) {
      scrollRef.current.scrollTop = 0;
    }
  }, [open, markdown, Preview]);

  // The page the notes are on wins, then the caller's URL, then the API's.
  const notesUrl = notes?.htmlUrl ?? releaseNotesUrl ?? notes?.releaseNotesUrl;
  const link = notesUrl ? (
    <NotesLink href={notesUrl} isRelease={notesUrl === notes?.htmlUrl} />
  ) : null;

  if (
    !open &&
    (!markdown ||
      state === "loading" ||
      state === "idle" ||
      preview?.items.length === 0)
  ) {
    return null;
  }

  return (
    <div
      // Clipped: the only part allowed to shrink, so it must not paint over the buttons.
      className={UPDATE_NOTES_ROOT_CLASS}
      // Lets the parent apply its floor only when this panel renders.
      data-slot="update-release-notes"
      data-testid="update-release-notes-panel"
      data-notes-state={state}
      data-notes-version={version}
      data-notes-tag={notes?.tag ?? undefined}
      data-notes-open={open}
    >
      <div className={UPDATE_NOTES_SURFACE_CLASS}>
        {markdown ? (
          open ? (
            <section
              ref={scrollRef}
              // biome-ignore lint/a11y/noNoninteractiveTabindex: keyboard-scrollable region
              tabIndex={0}
              aria-label={
                notes?.tag
                  ? t("updateNotes.notesFor", { release: notes.tag })
                  : t("updateNotes.notesForVersion", { version })
              }
              // Long notes scroll here instead of pushing the buttons off screen.
              className={UPDATE_NOTES_EXPANDED_SCROLL_CLASS}
              data-testid="update-release-notes-scroll"
            >
              {Preview ? (
                <Preview
                  markdown={markdown}
                  // Rescale Streamdown's headings, code and max-width; `anywhere` splits words.
                  className="max-h-none overflow-visible border-0 bg-transparent p-0 text-ui-11 [&_[data-streamdown=link-safety-modal]>*]:max-w-md [&_img]:h-auto [&_img]:max-w-full [&>*:first-child]:mt-0 [&>*>*:first-child]:mt-0 [&_code]:text-[0.92em] [&_h1]:mt-4 [&_h1]:font-heading [&_h1]:text-ui-13 [&_h2]:mt-4 [&_h2]:font-heading [&_h2]:text-ui-13 [&_h3]:mt-4 [&_h3]:font-heading [&_h3]:text-ui-11 [&_pre]:text-[0.92em] [&_td]:break-words [&_th]:break-words"
                />
              ) : (
                <NotesStatus
                  state={renderer.failed ? "error" : "loading"}
                  release={notes?.tag ?? null}
                  link={link}
                  retry={renderer.retry}
                  retryLabel={t("settings.dialog.panelReload")}
                />
              )}
              {notes?.truncated ? (
                <p className="mt-2 text-ui-10 text-muted-foreground/80">
                  {t("updateNotes.notesTruncated")}
                </p>
              ) : null}
            </section>
          ) : (
            <ReleaseNotesSummary preview={preview} />
          )
        ) : (
          <NotesStatus
            state={state}
            release={notes?.tag ?? null}
            link={link}
            retry={retry}
          />
        )}
      </div>
      {open && markdown && link ? (
        <div className={UPDATE_NOTES_FOOTER_CLASS}>{link}</div>
      ) : null}
    </div>
  );
}

function linked(
  text: string,
  links: ReleaseNotesLink[],
  part: ReleaseNotesLink["part"],
): ReactNode[] {
  const nodes: ReactNode[] = [];
  let from = 0;
  for (const link of links) {
    if (link.part !== part) {
      continue;
    }
    nodes.push(
      text.slice(from, link.start),
      <a
        key={link.start}
        href={link.href}
        target="_blank"
        rel="noopener noreferrer"
        onClick={handleExternalClick}
        className="underline decoration-foreground/40 underline-offset-2 transition-colors hover:decoration-foreground"
      >
        {text.slice(link.start, link.end)}
      </a>,
    );
    from = link.end;
  }
  nodes.push(text.slice(from));
  return nodes;
}

function ReleaseNotesSummary({
  preview,
}: {
  preview: ReturnType<typeof releaseNotesPreview> | null;
}): ReactElement | null {
  const t = useT();
  if (preview === null || preview.items.length === 0) {
    return null;
  }
  const { items, remaining } = preview;

  return (
    <ul
      // Scrollable: in short windows the list overflows its slot and would cover the buttons.
      // biome-ignore lint/a11y/noNoninteractiveTabindex: keyboard-scrollable region
      tabIndex={0}
      // Unversioned: the notes are the release's, not the offered version's.
      aria-label={t("updateNotes.summaryLabel")}
      className="hover-scrollbar min-h-0 flex-1 space-y-1 overflow-y-auto overscroll-contain py-2 pr-1"
      data-testid="update-release-notes-summary"
    >
      {items.map((item, index) => (
        <li
          // Two releases can carry the same bullet text, so index is the key.
          key={`${index}-${item.lead}`}
          className={UPDATE_NOTES_ITEM_CLASS}
        >
          <span aria-hidden="true" className={UPDATE_NOTES_BULLET_CLASS}>
            &bull;
          </span>
          <span className="line-clamp-2 min-w-0">
            <span className={UPDATE_NOTES_LEAD_CLASS}>
              {linked(item.lead, item.links, "lead")}
            </span>
            {item.rest ? (
              <span> {linked(item.rest, item.links, "rest")}</span>
            ) : null}
          </span>
        </li>
      ))}
      {remaining > 0 ? (
        <li className="pl-3 text-ui-10 text-muted-foreground/70">
          {t("updateNotes.moreCount", { count: remaining })}
        </li>
      ) : null}
    </ul>
  );
}

function NotesStatus({
  state,
  release,
  link,
  retry,
  retryLabel,
}: {
  state: ReturnType<typeof useReleaseNotes>["state"];
  release: string | null;
  link: ReactNode;
  retry: () => void;
  retryLabel?: string;
}): ReactElement {
  const t = useT();
  if (state === "loading" || state === "idle") {
    return <NotesMessage>{t("updateNotes.loadingNotes")}</NotesMessage>;
  }

  if (state === "error") {
    return (
      <NotesMessage
        action={
          // The release page may be reachable when the lookup is not.
          <span className="flex shrink-0 items-center gap-3">
            <button
              type="button"
              onClick={retry}
              className={UPDATE_NOTES_LINK_CLASS}
              data-testid="update-release-notes-retry"
            >
              {retryLabel ?? t("updateNotes.retry")}
            </button>
            {link}
          </span>
        }
      >
        {t("updateNotes.loadFailed")}
      </NotesMessage>
    );
  }

  // The release published no notes: link out rather than show the generated list.
  return (
    <NotesMessage action={link}>
      {release
        ? t("updateNotes.noNotesFor", { release })
        : t("updateNotes.noNotes")}
    </NotesMessage>
  );
}