Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update link selector to format links automatically #100

Merged
merged 3 commits into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,23 @@ import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

export function isValidUrl(url: string) {
try {
new URL(url);
return true;
} catch (e) {
return false;
}
}

export function getUrlFromString(str: string) {
if (isValidUrl(str)) return str;
try {
if (str.includes(".") && !str.includes(" ")) {
return new URL(`https://${str}`).toString();
}
} catch (e) {
return null;
}
}
8 changes: 4 additions & 4 deletions ui/editor/components/link-selector.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { cn } from "@/lib/utils";
import { cn, getUrlFromString } from "@/lib/utils";
import { Editor } from "@tiptap/core";
import { Check, Trash } from "lucide-react";
import { Dispatch, FC, SetStateAction, useEffect, useRef } from "react";
Expand Down Expand Up @@ -43,15 +43,15 @@ export const LinkSelector: FC<LinkSelectorProps> = ({
onSubmit={(e) => {
e.preventDefault();
const input = e.target[0] as HTMLInputElement;
input.value &&
editor.chain().focus().setLink({ href: input.value }).run();
const url = getUrlFromString(input.value);
url && editor.chain().focus().setLink({ href: url }).run();
setIsOpen(false);
}}
className="fixed top-full z-[99999] mt-1 flex w-60 overflow-hidden rounded border border-stone-200 bg-white p-1 shadow-xl animate-in fade-in slide-in-from-top-1"
>
<input
ref={inputRef}
type="url"
type="text"
placeholder="Paste a link"
className="flex-1 bg-white p-1 text-sm outline-none"
defaultValue={editor.getAttributes("link").href || ""}
Expand Down
Loading