Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(editor): add insert/edit external hyperlink controls

tianma-if74fef8c57b94
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index ab54d1a1..6fa109f0 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -80,6 +80,7 @@ import { ThemeToggle } from "./ThemeToggle";
import { useTheme } from "./ThemeProvider";
import { sanitizeAndScopeCss } from "@/lib/css-sandbox";
import { RevisionHistoryDialog } from "./dialogs/RevisionHistoryDialog";
+import { ExternalLinkDialog } from "./dialogs/ExternalLinkDialog";
import { memoShareQueryKey, ShareMemoDialog } from "./dialogs/ShareMemoDialog";
import { api } from "@/lib/api";
import { isDesktopResourceRuntime, stageDesktopResource, toDesktopResourceUrl } from "@/lib/desktop-resources";
@@ -136,6 +137,11 @@ import { downloadMarkdownFile } from "@/lib/note-markdown-export";
import { openNotePrintPreview, serializeNoteDocumentForPrint } from "@/lib/note-print";
import { isBrowserOffline } from "@/lib/network-status";
import { shouldOpenEditorLink } from "@/lib/editor-link-click";
+import {
+ formatMarkdownLink,
+ insertMarkdownSnippet,
+ isAttachmentLinkHref,
+} from "@/lib/editor-external-link";
import { processFilesSequentially } from "@/lib/file-batch";
import { MEMO_ID_REMAPPED_EVENT } from "@/lib/sync-events";
import { useStandaloneMobileEditor } from "@/hooks/useStandaloneMobileEditor";
@@ -871,7 +877,7 @@ const RichEditorPane = ({
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const [hydratedEditorMemoId, setHydratedEditorMemoId] = useState<string | null>(null);
const [dirtyVersion, setDirtyVersion] = useState(0);
- const [, setEditorStateVersion] = useState(0);
+ const [editorStateVersion, setEditorStateVersion] = useState(0);
const [editorContentVersion, setEditorContentVersion] = useState(0);
const [imageUploadState, setImageUploadState] = useState<"idle" | "compressing" | "uploading" | "error">("idle");
const [historyOpen, setHistoryOpen] = useState(false);
@@ -888,6 +894,13 @@ const RichEditorPane = ({
const [noteLinkPickerOpen, setNoteLinkPickerOpen] = useState(false);
const [noteLinkQuery, setNoteLinkQuery] = useState("");
const [noteLinkHintPosition, setNoteLinkHintPosition] = useState<NoteLinkHintPosition | null>(null);
+ const [externalLinkDialogOpen, setExternalLinkDialogOpen] = useState(false);
+ const [externalLinkDraft, setExternalLinkDraft] = useState<{ href: string; text: string; showTextField: boolean; canRemove: boolean }>({
+ href: "",
+ text: "",
+ showTextField: true,
+ canRemove: false,
+ });
const [resourceMenuTarget, setResourceMenuTarget] = useState<ResourceMenuTarget | null>(null);
const [resourceDialog, setResourceDialog] = useState<ResourceDialogState | null>(null);
const [resourceFilename, setResourceFilename] = useState("");
@@ -966,6 +979,8 @@ const RichEditorPane = ({
const fileInputRef = useRef<HTMLInputElement | null>(null);
const noteSearchInputRef = useRef<HTMLInputElement | null>(null);
const noteReplaceInputRef = useRef<HTMLInputElement | null>(null);
+ const markdownTextAreaRef = useRef<HTMLTextAreaElement | null>(null);
+ const openExternalLinkDialogRef = useRef<() => void>(() => undefined);
const hydratingRef = useRef(false);
const hydratedMemoIdRef = useRef<string | null>(null);
/** Last content source applied to the editor — used to skip redundant setContent. */
@@ -1212,6 +1227,12 @@ const RichEditorPane = ({
},
handleKeyDown: (view, event) => {
const shortcutKey = event.key.toLowerCase();
+ if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && shortcutKey === "k") {
+ event.preventDefault();
+ openExternalLinkDialogRef.current();
+ return true;
+ }
+
if (
(shortcutKey !== "f" && shortcutKey !== "h") ||
(!event.ctrlKey && !event.metaKey) ||
@@ -1302,6 +1323,154 @@ const RichEditorPane = ({
setNoteLinkQuery("");
}, [editor, effectiveReadOnly, memo?.id, t]);
+ const openExternalLinkDialog = useCallback(() => {
+ if (effectiveReadOnly || !memo) {
+ return;
+ }
+
+ if (useMarkdownSourceEditor) {
+ const textarea = markdownTextAreaRef.current;
+ const start = textarea?.selectionStart ?? markdownSource.length;
+ const end = textarea?.selectionEnd ?? start;
+ const selected = markdownSource.slice(start, end);
+ const looksLikeUrl = /^(https?:\/\/\S+|www\.\S+)$/i.test(selected.trim());
+ setExternalLinkDraft({
+ href: looksLikeUrl ? selected.trim() : "",
+ text: looksLikeUrl ? "" : selected,
+ showTextField: !selected.trim() || looksLikeUrl,
+ canRemove: false,
+ });
+ setExternalLinkDialogOpen(true);
+ return;
+ }
+
+ if (!isEditorReady(editor) || useMobilePlainTextEditor) {
+ return;
+ }
+
+ if (editor.isActive("link")) {
+ const href = String(editor.getAttributes("link").href ?? "");
+ if (isAttachmentLinkHref(href)) {
+ return;
+ }
+ editor.chain().focus().extendMarkRange("link").run();
+ }
+
+ const { from, to, empty } = editor.state.selection;
+ const selectedText = editor.state.doc.textBetween(from, to, " ");
+ const activeHref = editor.isActive("link") ? String(editor.getAttributes("link").href ?? "") : "";
+ const looksLikeUrl = empty
+ ? false
+ : /^(https?:\/\/\S+|www\.\S+)$/i.test(selectedText.trim());
+
+ setExternalLinkDraft({
+ href: activeHref || (looksLikeUrl ? selectedText.trim() : ""),
+ text: selectedText,
+ showTextField: empty && !activeHref,
+ canRemove: Boolean(activeHref) && !isAttachmentLinkHref(activeHref),
+ });
+ setExternalLinkDialogOpen(true);
+ }, [
+ editor,
+ effectiveReadOnly,
+ markdownSource,
+ memo,
+ useMarkdownSourceEditor,
+ useMobilePlainTextEditor,
+ ]);
+
+ openExternalLinkDialogRef.current = openExternalLinkDialog;
+
+ const applyExternalLink = useCallback(
+ ({ href, text }: { href: string; text: string }) => {
+ if (effectiveReadOnly) {
+ return;
+ }
+
+ if (useMarkdownSourceEditor) {
+ const textarea = markdownTextAreaRef.current;
+ const start = textarea?.selectionStart ?? markdownSource.length;
+ const end = textarea?.selectionEnd ?? start;
+ const selected = markdownSource.slice(start, end);
+ const label = selected.trim() ? selected : text;
+ const snippet = formatMarkdownLink(label, href);
+ const { next, caret } = insertMarkdownSnippet(markdownSource, snippet, start, end);
+ setMarkdownSource(next);
+ setHasUnsavedChanges(true);
+ setDirtyVersion((version) => version + 1);
+ window.requestAnimationFrame(() => {
+ const node = markdownTextAreaRef.current;
+ if (!node) return;
+ node.focus();
+ node.setSelectionRange(caret, caret);
+ });
+ return;
+ }
+
+ if (!isEditorReady(editor)) {
+ return;
+ }
+
+ const inLink = editor.isActive("link");
+ if (inLink) {
+ editor.chain().focus().extendMarkRange("link").run();
+ }
+
+ const { from, to, empty } = editor.state.selection;
+ const selectedText = editor.state.doc.textBetween(from, to, "\n");
+
+ if (!empty || inLink) {
+ const label = selectedText || text || href;
+ editor
+ .chain()
+ .focus()
+ .insertContentAt(
+ { from, to },
+ {
+ type: "text",
+ text: label,
+ marks: [{ type: "link", attrs: { href, target: "_blank" } }],
+ }
+ )
+ .run();
+ return;
+ }
+
+ editor
+ .chain()
+ .focus()
+ .insertContent({
+ type: "text",
+ text: text || href,
+ marks: [{ type: "link", attrs: { href, target: "_blank" } }],
+ })
+ .run();
+ },
+ [editor, effectiveReadOnly, markdownSource, useMarkdownSourceEditor]
+ );
+
+ const removeExternalLink = useCallback(() => {
+ if (!isEditorReady(editor) || effectiveReadOnly) {
+ return;
+ }
+ editor.chain().focus().extendMarkRange("link").unsetLink().run();
+ }, [editor, effectiveReadOnly]);
+
+ const externalLinkActive = useMemo(() => {
+ if (!isEditorReady(editor) || useMarkdownSourceEditor || useMobilePlainTextEditor) {
+ return false;
+ }
+ try {
+ if (!editor.isActive("link")) {
+ return false;
+ }
+ const href = String(editor.getAttributes("link").href ?? "");
+ return Boolean(href) && !isAttachmentLinkHref(href);
+ } catch {
+ return false;
+ }
+ }, [editor, editorStateVersion, useMarkdownSourceEditor, useMobilePlainTextEditor]);
+
const cancelResourceMenuHide = useCallback(() => {
if (resourceMenuHideTimerRef.current !== null) {
window.clearTimeout(resourceMenuHideTimerRef.current);
@@ -3138,6 +3307,16 @@ const RichEditorPane = ({
return (
<div className="relative flex h-full min-w-0 flex-col bg-white">
{selectionActionBar}
+ <ExternalLinkDialog
+ open={externalLinkDialogOpen}
+ onOpenChange={setExternalLinkDialogOpen}
+ initialHref={externalLinkDraft.href}
+ initialText={externalLinkDraft.text}
+ showTextField={externalLinkDraft.showTextField}
+ canRemove={externalLinkDraft.canRemove}
+ onApply={applyExternalLink}
+ onRemove={removeExternalLink}
+ />
{noteLinkPickerOpen && (
<div className="absolute left-3 right-3 top-14 z-30 h-[min(22rem,calc(100%-4rem))] max-w-xl rounded-lg border border-slate-200 bg-white shadow-xl sm:left-5 sm:right-auto sm:w-[28rem]" role="dialog" aria-label={t("noteLinkPicker.title")}>
<Command shouldFilter={false}>
@@ -3693,6 +3872,8 @@ const RichEditorPane = ({
markdownMode={useMarkdownSourceEditor}
onMarkdownModeChange={handleMarkdownModeChange}
onPickAttachment={() => fileInputRef.current?.click()}
+ onPickExternalLink={openExternalLinkDialog}
+ externalLinkActive={externalLinkActive}
onPickNoteLink={() => setNoteLinkPickerOpen(true)}
/>
)}
@@ -3843,8 +4024,15 @@ const RichEditorPane = ({
</>
) : useMarkdownSourceEditor ? (
<textarea
+ ref={markdownTextAreaRef}
value={markdownSource}
onChange={(event) => handleMarkdownSourceChange(event.target.value)}
+ onKeyDown={(event) => {
+ if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "k") {
+ event.preventDefault();
+ openExternalLinkDialog();
+ }
+ }}
readOnly={effectiveReadOnly}
spellCheck={false}
aria-label={t("editor.markdownSourceAria")}
diff --git a/apps/web/src/components/EditorToolbar.tsx b/apps/web/src/components/EditorToolbar.tsx
index 25e51ce1..39caedc2 100644
--- a/apps/web/src/components/EditorToolbar.tsx
+++ b/apps/web/src/components/EditorToolbar.tsx
@@ -15,6 +15,7 @@ import {
ChartNoAxesCombined,
Minus,
Paperclip,
+ Link,
Link2,
} from "lucide-react";
import { cn } from "@/lib/utils";
@@ -117,14 +118,19 @@ export const EditorToolbar = ({
markdownMode = false,
onMarkdownModeChange,
onPickAttachment,
+ onPickExternalLink,
onPickNoteLink,
+ externalLinkActive = false,
}: {
editor: Editor | null;
readOnly: boolean;
markdownMode?: boolean;
onMarkdownModeChange?: () => void;
onPickAttachment?: () => void;
+ /** Insert or edit an external hyperlink (not a note reference). */
+ onPickExternalLink?: () => void;
onPickNoteLink?: () => void;
+ externalLinkActive?: boolean;
}) => {
const { t } = useTranslation();
const editorReady = isToolbarEditorReady(editor);
@@ -240,6 +246,23 @@ export const EditorToolbar = ({
<ToolbarDivider />
</>
)}
+ {onPickExternalLink && (
+ <>
+ <EditorToolbarButton
+ title={
+ externalLinkActive
+ ? t("editorToolbar.externalLinkEdit")
+ : t("editorToolbar.externalLinkShortcut")
+ }
+ active={externalLinkActive}
+ disabled={readOnly}
+ onClick={onPickExternalLink}
+ >
+ <Link className="h-4 w-4" />
+ </EditorToolbarButton>
+ <ToolbarDivider />
+ </>
+ )}
{onPickNoteLink && (
<>
<EditorToolbarButton
diff --git a/apps/web/src/components/dialogs/ExternalLinkDialog.tsx b/apps/web/src/components/dialogs/ExternalLinkDialog.tsx
new file mode 100644
index 00000000..b91c4e9f
--- /dev/null
+++ b/apps/web/src/components/dialogs/ExternalLinkDialog.tsx
@@ -0,0 +1,170 @@
+import { useEffect, useId, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Link as LinkIcon } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { normalizeExternalLinkHref } from "@/lib/editor-external-link";
+
+export type ExternalLinkDialogValues = {
+ href: string;
+ text: string;
+};
+
+export const ExternalLinkDialog = ({
+ open,
+ onOpenChange,
+ initialHref = "",
+ initialText = "",
+ canRemove = false,
+ showTextField = true,
+ onApply,
+ onRemove,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ initialHref?: string;
+ initialText?: string;
+ canRemove?: boolean;
+ /** When false, only the URL field is shown (selection already has text). */
+ showTextField?: boolean;
+ onApply: (values: ExternalLinkDialogValues) => void;
+ onRemove?: () => void;
+}) => {
+ const { t } = useTranslation();
+ const hrefId = useId();
+ const textId = useId();
+ const hrefInputRef = useRef<HTMLInputElement>(null);
+ const [href, setHref] = useState(initialHref);
+ const [text, setText] = useState(initialText);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!open) {
+ return;
+ }
+ setHref(initialHref);
+ setText(initialText);
+ setError(null);
+ const timer = window.setTimeout(() => {
+ hrefInputRef.current?.focus();
+ hrefInputRef.current?.select();
+ }, 0);
+ return () => window.clearTimeout(timer);
+ }, [open, initialHref, initialText]);
+
+ const submit = () => {
+ const normalized = normalizeExternalLinkHref(href);
+ if (!normalized.ok) {
+ setError(
+ normalized.reason === "empty"
+ ? t("externalLinkDialog.errorEmpty")
+ : normalized.reason === "unsupported"
+ ? t("externalLinkDialog.errorUnsupported")
+ : t("externalLinkDialog.errorInvalid")
+ );
+ return;
+ }
+ onApply({
+ href: normalized.href,
+ text: text.trim() || normalized.href,
+ });
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-md gap-0 overflow-hidden p-0">
+ <DialogHeader className="border-b border-slate-200 px-5 py-5 pr-12 text-left">
+ <DialogTitle className="flex items-center gap-2 text-base">
+ <LinkIcon className="h-5 w-5 text-emerald-600" />
+ {canRemove ? t("externalLinkDialog.editTitle") : t("externalLinkDialog.title")}
+ </DialogTitle>
+ <DialogDescription className="pt-1 leading-5">
+ {t("externalLinkDialog.description")}
+ </DialogDescription>
+ </DialogHeader>
+
+ <form
+ className="space-y-4 px-5 py-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ submit();
+ }}
+ >
+ <div className="space-y-1.5">
+ <label htmlFor={hrefId} className="text-xs font-medium text-slate-600">
+ {t("externalLinkDialog.urlLabel")}
+ </label>
+ <Input
+ ref={hrefInputRef}
+ id={hrefId}
+ value={href}
+ onChange={(event) => {
+ setHref(event.target.value);
+ if (error) setError(null);
+ }}
+ placeholder={t("externalLinkDialog.urlPlaceholder")}
+ inputMode="url"
+ autoComplete="url"
+ aria-invalid={Boolean(error) || undefined}
+ />
+ </div>
+
+ {showTextField && (
+ <div className="space-y-1.5">
+ <label htmlFor={textId} className="text-xs font-medium text-slate-600">
+ {t("externalLinkDialog.textLabel")}
+ </label>
+ <Input
+ id={textId}
+ value={text}
+ onChange={(event) => setText(event.target.value)}
+ placeholder={t("externalLinkDialog.textPlaceholder")}
+ />
+ </div>
+ )}
+
+ {error && (
+ <p className="text-xs text-rose-600" role="alert">
+ {error}
+ </p>
+ )}
+
+ <DialogFooter className="gap-2 border-t border-slate-100 pt-4 sm:justify-between">
+ <div className="flex min-w-0 flex-1 flex-wrap gap-2">
+ {canRemove && onRemove && (
+ <Button
+ type="button"
+ variant="ghost"
+ className="text-rose-700 hover:bg-rose-50 hover:text-rose-800"
+ onClick={() => {
+ onRemove();
+ onOpenChange(false);
+ }}
+ >
+ {t("externalLinkDialog.remove")}
+ </Button>
+ )}
+ </div>
+ <div className="flex flex-wrap justify-end gap-2">
+ <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>
+ {t("common.cancel")}
+ </Button>
+ <Button type="submit" variant="solid">
+ {t("externalLinkDialog.apply")}
+ </Button>
+ </div>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/apps/web/src/lib/editor-external-link.test.mjs b/apps/web/src/lib/editor-external-link.test.mjs
new file mode 100644
index 00000000..030860e7
--- /dev/null
+++ b/apps/web/src/lib/editor-external-link.test.mjs
@@ -0,0 +1,101 @@
+import { describe, expect, test } from "bun:test";
+import {
+ formatMarkdownLink,
+ insertMarkdownSnippet,
+ isAttachmentLinkHref,
+ isNoteLinkHref,
+ normalizeExternalLinkHref,
+} from "./editor-external-link.ts";
+
+describe("normalizeExternalLinkHref", () => {
+ test("rejects empty input", () => {
+ expect(normalizeExternalLinkHref(" ")).toEqual({ ok: false, reason: "empty" });
+ });
+
+ test("accepts https URLs", () => {
+ expect(normalizeExternalLinkHref("https://www.edgeever.org/docs")).toEqual({
+ ok: true,
+ href: "https://www.edgeever.org/docs",
+ });
+ });
+
+ test("adds https for bare domains", () => {
+ expect(normalizeExternalLinkHref("example.com/path")).toEqual({
+ ok: true,
+ href: "https://example.com/path",
+ });
+ });
+
+ test("adds https for www hosts", () => {
+ expect(normalizeExternalLinkHref("www.example.com")).toEqual({
+ ok: true,
+ href: "https://www.example.com/",
+ });
+ });
+
+ test("accepts mailto", () => {
+ const result = normalizeExternalLinkHref("mailto:[email protected]");
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.href).toBe("mailto:[email protected]");
+ }
+ });
+
+ test("accepts protocol-relative URLs", () => {
+ expect(normalizeExternalLinkHref("//cdn.example.com/a.js")).toEqual({
+ ok: true,
+ href: "https://cdn.example.com/a.js",
+ });
+ });
+
+ test("accepts same-origin relative paths", () => {
+ expect(normalizeExternalLinkHref("/share/abc")).toEqual({ ok: true, href: "/share/abc" });
+ });
+
+ test("accepts internal note and resource hrefs", () => {
+ expect(normalizeExternalLinkHref("#memo=note_1")).toEqual({ ok: true, href: "#memo=note_1" });
+ expect(normalizeExternalLinkHref("edgeever-resource://res_1")).toEqual({
+ ok: true,
+ href: "edgeever-resource://res_1",
+ });
+ });
+
+ test("rejects javascript and data URLs", () => {
+ expect(normalizeExternalLinkHref("javascript:alert(1)")).toEqual({
+ ok: false,
+ reason: "unsupported",
+ });
+ expect(normalizeExternalLinkHref("data:text/html,hi")).toEqual({
+ ok: false,
+ reason: "unsupported",
+ });
+ });
+
+ test("rejects plain words without a scheme", () => {
+ expect(normalizeExternalLinkHref("not a link")).toEqual({ ok: false, reason: "invalid" });
+ });
+});
+
+describe("link href classifiers", () => {
+ test("detects note and attachment hrefs", () => {
+ expect(isNoteLinkHref("#memo=abc")).toBe(true);
+ expect(isNoteLinkHref("https://example.com")).toBe(false);
+ expect(isAttachmentLinkHref("/api/v1/resources/res_1/blob")).toBe(true);
+ expect(isAttachmentLinkHref("https://example.com")).toBe(false);
+ });
+});
+
+describe("markdown helpers", () => {
+ test("formats a markdown link", () => {
+ expect(formatMarkdownLink("EdgeEver", "https://www.edgeever.org")).toBe(
+ "[EdgeEver](https://www.edgeever.org)"
+ );
+ });
+
+ test("inserts a snippet at the caret", () => {
+ expect(insertMarkdownSnippet("hello world", "[x](y)", 6, 11)).toEqual({
+ next: "hello [x](y)",
+ caret: 12,
+ });
+ });
+});
diff --git a/apps/web/src/lib/editor-external-link.ts b/apps/web/src/lib/editor-external-link.ts
new file mode 100644
index 00000000..ba09ab0e
--- /dev/null
+++ b/apps/web/src/lib/editor-external-link.ts
@@ -0,0 +1,103 @@
+/** Helpers for insert/edit external hyperlinks in the rich-text editor. */
+
+const BLOCKED_PROTOCOL = /^(javascript|data|vbscript):/i;
+const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
+const LOOKS_LIKE_DOMAIN = /^(?:www\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+(?:[/:?#].*)?$/i;
+
+export type NormalizeExternalLinkResult =
+ | { ok: true; href: string }
+ | { ok: false; reason: "empty" | "invalid" | "unsupported" };
+
+/**
+ * Normalize user-entered URL for an external hyperlink.
+ * Accepts http(s), mailto, and bare domains (adds https://).
+ * Rejects javascript:/data:/vbscript: and other unusable values.
+ */
+export const normalizeExternalLinkHref = (raw: string): NormalizeExternalLinkResult => {
+ const trimmed = raw.trim();
+ if (!trimmed) {
+ return { ok: false, reason: "empty" };
+ }
+
+ if (BLOCKED_PROTOCOL.test(trimmed)) {
+ return { ok: false, reason: "unsupported" };
+ }
+
+ // Internal note / resource schemes stay as-is (user may paste them intentionally).
+ if (
+ trimmed.startsWith("#memo=") ||
+ trimmed.startsWith("edgeever-resource://") ||
+ trimmed.startsWith("/api/v1/resources/")
+ ) {
+ return { ok: true, href: trimmed };
+ }
+
+ let candidate = trimmed;
+ if (!HAS_SCHEME.test(candidate)) {
+ if (candidate.startsWith("//")) {
+ candidate = `https:${candidate}`;
+ } else if (candidate.startsWith("/") || candidate.startsWith("#") || candidate.startsWith("?")) {
+ // Same-origin relative paths and hash fragments.
+ return { ok: true, href: candidate };
+ } else if (LOOKS_LIKE_DOMAIN.test(candidate) || candidate.toLowerCase().startsWith("www.")) {
+ candidate = `https://${candidate}`;
+ } else {
+ return { ok: false, reason: "invalid" };
+ }
+ }
+
+ try {
+ // Relative paths already returned; absolute URLs must parse.
+ if (candidate.startsWith("/") || candidate.startsWith("#") || candidate.startsWith("?")) {
+ return { ok: true, href: candidate };
+ }
+ const parsed = new URL(candidate);
+ if (BLOCKED_PROTOCOL.test(parsed.protocol)) {
+ return { ok: false, reason: "unsupported" };
+ }
+ // mailto: and other harmless schemes keep their string form.
+ if (parsed.protocol === "mailto:" || parsed.protocol === "http:" || parsed.protocol === "https:") {
+ return { ok: true, href: parsed.href };
+ }
+ // Allow other uncommon but non-script schemes (ftp, tel, …) as typed.
+ return { ok: true, href: candidate };
+ } catch {
+ return { ok: false, reason: "invalid" };
+ }
+};
+
+export const isAttachmentLinkHref = (href: string | null | undefined): boolean => {
+ if (!href) return false;
+ return (
+ href.includes("/api/v1/resources/") ||
+ href.startsWith("edgeever-resource://") ||
+ href.includes("edgeever-attachment")
+ );
+};
+
+export const isNoteLinkHref = (href: string | null | undefined): boolean => {
+ if (!href) return false;
+ return href.startsWith("#memo=");
+};
+
+/** Build Markdown link syntax for source mode. */
+export const formatMarkdownLink = (label: string, href: string): string => {
+ const safeLabel = (label.trim() || href).replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
+ return `[${safeLabel}](${href})`;
+};
+
+/**
+ * Insert `snippet` into `source` at `selectionStart`/`selectionEnd`,
+ * replacing the selected range. Returns the next source and caret position.
+ */
+export const insertMarkdownSnippet = (
+ source: string,
+ snippet: string,
+ selectionStart: number,
+ selectionEnd: number
+): { next: string; caret: number } => {
+ const start = Math.max(0, Math.min(selectionStart, source.length));
+ const end = Math.max(start, Math.min(selectionEnd, source.length));
+ const next = `${source.slice(0, start)}${snippet}${source.slice(end)}`;
+ return { next, caret: start + snippet.length };
+};
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 987fd43d..04fd1bb8 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -816,6 +816,23 @@ export const enUS = {
switchToRichText: "Switch to rich text mode",
attachment: "Upload attachment",
noteLink: "Link a note",
+ externalLink: "Insert link",
+ externalLinkEdit: "Edit link",
+ externalLinkShortcut: "Insert link (Ctrl/⌘K)",
+ },
+ externalLinkDialog: {
+ title: "Insert link",
+ editTitle: "Edit link",
+ description: "Add a web address to the selected text, or insert a new linked phrase.",
+ urlLabel: "URL",
+ urlPlaceholder: "https://example.com",
+ textLabel: "Display text",
+ textPlaceholder: "Optional — defaults to the URL",
+ apply: "Apply",
+ remove: "Remove link",
+ errorEmpty: "Enter a URL.",
+ errorInvalid: "Enter a valid URL, such as example.com or https://example.com.",
+ errorUnsupported: "This URL scheme is not allowed.",
},
noteLinkPicker: {
title: "Link a note",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index ccbb8f98..cd7681f8 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -816,6 +816,23 @@ export const zhCN = {
switchToRichText: "切换到富文本模式",
attachment: "上传附件",
noteLink: "引用笔记",
+ externalLink: "插入超链接",
+ externalLinkEdit: "编辑超链接",
+ externalLinkShortcut: "插入超链接 (Ctrl/⌘K)",
+ },
+ externalLinkDialog: {
+ title: "插入超链接",
+ editTitle: "编辑超链接",
+ description: "为选中文字添加网址,或插入一段可点击的链接文本。",
+ urlLabel: "网址",
+ urlPlaceholder: "https://example.com",
+ textLabel: "显示文字",
+ textPlaceholder: "可选,默认使用网址",
+ apply: "应用",
+ remove: "移除链接",
+ errorEmpty: "请输入网址。",
+ errorInvalid: "请输入有效网址,例如 example.com 或 https://example.com。",
+ errorUnsupported: "不支持此网址协议。",
},
noteLinkPicker: {
title: "引用笔记",