Open platform to collect and prioritize feedback
feat(ui): Supports inserting non-standard links Updates LinkInsertModal and CommentEditor to support custom link schemes defined by the Fider admin, such as mailto:, bitcoin:, monero:, etc.
widal0016ebcdfa36b39
diff --git a/public/components/common/form/CommentEditor.tsx b/public/components/common/form/CommentEditor.tsxindex 28d2ac90a..d162ac4b7 100644--- a/public/components/common/form/CommentEditor.tsx+++ b/public/components/common/form/CommentEditor.tsx@@ -11,6 +11,7 @@ import Text from "@tiptap/extension-text"import HardBreak from "@tiptap/extension-hard-break"import { i18n } from "@lingui/core"import { plainText } from "@fider/services/markdown"+import { useAllowedProtocols } from "@fider/hooks"import "./CommentEditor.scss"@@ -247,6 +248,7 @@ const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {const [imageUploads, setImageUploads] = useState<ImageUpload[]>([])const [isLinkModalOpen, setIsLinkModalOpen] = useState(false)const [selectedText, setSelectedText] = useState("")+ const allowedProtocols = useAllowedProtocols()// Use a ref instead of state for tracking document images// This avoids the async state update issue and prevents unnecessary re-renders@@ -437,10 +439,7 @@ const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {const handleInsertLink = (text: string, url: string) => {if (!editor) return- // Ensure URL has protocol- const urlWithProtocol = url.startsWith("http://") || url.startsWith("https://") ? url : `https://${url}`-- editor.chain().focus().insertContent(`<a href="${urlWithProtocol}" target="_blank" rel="noopener nofollow">${text}</a>`).run()+ editor.chain().focus().insertContent(`<a href="${url}" target="_blank" rel="noopener nofollow">${text}</a>`).run()}// Handle keyboard shortcuts@@ -475,9 +474,10 @@ const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {: [StarterKit,Link.configure({- openOnClick: false,+ openOnClick: true,autolink: true,defaultProtocol: "https",+ protocols: allowedProtocols,HTMLAttributes: {class: "text-link",target: "_blank",diff --git a/public/components/common/form/LinkInsertModal.tsx b/public/components/common/form/LinkInsertModal.tsxindex 051641fb1..b29ac7df6 100644--- a/public/components/common/form/LinkInsertModal.tsx+++ b/public/components/common/form/LinkInsertModal.tsx@@ -4,6 +4,8 @@ import { Form } from "./Form"import { Failure } from "@fider/services"import { Trans } from "@lingui/react/macro"import { i18n } from "@lingui/core"+import { isValidUrl, normalizeUrl } from "@fider/services/markdown"+import { useAllowedSchemesRegex } from "@fider/hooks"interface LinkInsertModalProps {isOpen: boolean@@ -17,6 +19,7 @@ const LinkInsertModal = ({ isOpen, onClose, onInsertLink, selectedText = "" }: Lconst [url, setUrl] = useState("")const [error, setError] = useState<Failure | undefined>(undefined)const textInputRef = useRef<HTMLInputElement>(null)+ const allowedSchemes = useAllowedSchemesRegex()// Create an error item with the given field, message ID, and messageconst createError = (field: string, messageId: string, message: string) => ({@@ -35,15 +38,9 @@ const LinkInsertModal = ({ isOpen, onClose, onInsertLink, selectedText = "" }: LerrorItems.push(createError("text", "linkmodal.text.required", "Text is required"))}- if (!url.trim()) {- errorItems.push(createError("url", "linkmodal.url.required", "URL is required"))- } else {- // Basic URL validation- try {- new URL(url.startsWith("http://") || url.startsWith("https://") ? url : `https://${url}`)- } catch {- errorItems.push(createError("url", "linkmodal.url.invalid", "Please enter a valid URL"))- }+ // Validate URL against allowed schemes+ if (!isValidUrl(url, allowedSchemes)) {+ errorItems.push(createError("url", "linkmodal.url.invalid", "Please enter a valid URL or crypto address"))}if (errorItems.length > 0) {@@ -52,8 +49,8 @@ const LinkInsertModal = ({ isOpen, onClose, onInsertLink, selectedText = "" }: L}// Form is valid, handle submission- const urlWithProtocol = url.startsWith("http://") || url.startsWith("https://") ? url : `https://${url}`- onInsertLink(text.trim(), urlWithProtocol)+ const finalUrl = normalizeUrl(url)+ onInsertLink(text.trim(), finalUrl)setText("")setUrl("")onClose()diff --git a/public/hooks/use-fider.ts b/public/hooks/use-fider.tsindex a6e74cb3c..c8ecb9663 100644--- a/public/hooks/use-fider.ts+++ b/public/hooks/use-fider.ts@@ -2,5 +2,49 @@ import { useContext } from "react"import { FiderContext } from "@fider/services"export const useFider = () => useContext(FiderContext)-// useContext() doesn't work in tests++// Parse allowed schemes and extract all derived data in one go+const parseAllowedSchemesData = (allowedSchemesString: string) => {+ const schemes = allowedSchemesString+ .split("\n")+ .filter((s) => s.trim())+ .map((s) => s.trim())++ const regexArray = schemes.map((s) => new RegExp(s, "i"))++ const protocols = new Set<string>(["http", "https"])+ schemes.forEach((scheme) => {+ if (scheme.startsWith("^")) {+ const match = scheme.match(/^\^([a-zA-Z][a-zA-Z0-9+.-]*):/)+ if (match) {+ protocols.add(match[1])+ }+ }+ })++ return {+ raw: allowedSchemesString,+ regexArray,+ protocols: Array.from(protocols),+ }+}++// Hook that provides all parsed allowed schemes data+const useAllowedSchemesData = () => {+ const fider = useFider()+ const allowedSchemes = fider.session.tenant.allowedSchemes+ return parseAllowedSchemesData(allowedSchemes)+}++// Hook version - get parsed allowed schemes as RegExp array+export const useAllowedSchemesRegex = (): RegExp[] => {+ return useAllowedSchemesData().regexArray+}++// Extract protocol names from allowed schemes for Tiptap Link extension+export const useAllowedProtocols = (): string[] => {+ return useAllowedSchemesData().protocols+}++// For non-React contexts, we need to pass the schemes as a parameterexport const fiderAllowedSchemes = { get: () => useFider().session.tenant.allowedSchemes }diff --git a/public/services/markdown.spec.ts b/public/services/markdown.spec.tsindex 9bba59524..41dcc5cee 100644--- a/public/services/markdown.spec.ts+++ b/public/services/markdown.spec.ts@@ -86,3 +86,50 @@ testCases.forEach((x) => {expect(result).toEqual(x.expectedPlainText)})})++// Test the new URL validation utilities+describe("URL validation utilities", () => {+ test("should always allow HTTP/HTTPS URLs even when no allowed schemes provided", () => {+ // HTTP/HTTPS URLs are always allowed, even when no allowed schemes provided+ expect(markdown.isValidUrl("https://example.com")).toBe(true)+ expect(markdown.isValidUrl("http://example.com")).toBe(true)+ expect(markdown.isValidUrl("example.com")).toBe(true) // gets normalized to https://++ // But crypto URLs are rejected when no allowed schemes provided+ expect(markdown.isValidUrl("monero:4AdUndXHHZ6cFhR4L5n4eL3p5N1L7cKyK4n8v7f3v2")).toBe(false)+ })++ test("should validate URLs when allowed schemes provided", () => {+ const mockAllowedSchemes = [new RegExp("^monero:[48]", "i"), new RegExp("^bitcoin:(1|3|bc1)", "i")]++ // HTTP/HTTPS URLs should work+ expect(markdown.isValidUrl("https://example.com", mockAllowedSchemes)).toBe(true)+ expect(markdown.isValidUrl("http://example.com", mockAllowedSchemes)).toBe(true)+ expect(markdown.isValidUrl("example.com", mockAllowedSchemes)).toBe(true) // gets normalized to https://++ // Crypto URLs should work+ expect(markdown.isValidUrl("monero:4AdUndXHHZ6cFhR4L5n4eL3p5N1L7cKyK4n8v7f3v2", mockAllowedSchemes)).toBe(true)+ expect(markdown.isValidUrl("bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", mockAllowedSchemes)).toBe(true)++ // Non-allowed crypto should be rejected+ expect(markdown.isValidUrl("litecoin:LTC1qy2e3r4t5y6u7i8o9p0", mockAllowedSchemes)).toBe(false)+ })++ test("should reject invalid URL schemes", () => {+ const mockAllowedSchemes = [new RegExp("^https?://", "i")]+ expect(markdown.isValidUrl("http:invalid-address", mockAllowedSchemes)).toBe(false)+ })++ test("should reject empty URLs", () => {+ expect(markdown.isValidUrl("")).toBe(false)+ expect(markdown.isValidUrl(" ")).toBe(false)+ })++ test("should normalize URLs correctly", () => {+ const regularUrl = markdown.normalizeUrl("example.com")+ expect(regularUrl).toBe("https://example.com")++ const cryptoUrl = markdown.normalizeUrl("monero:4AdUndXHHZ6cFhR4L5n4eL3p5N1L7cKyK4n8v7f3v2")+ expect(cryptoUrl).toBe("monero:4AdUndXHHZ6cFhR4L5n4eL3p5N1L7cKyK4n8v7f3v2")+ })+})diff --git a/public/services/markdown.ts b/public/services/markdown.tsindex bfb6bd181..bb29f5145 100644--- a/public/services/markdown.ts+++ b/public/services/markdown.ts@@ -101,3 +101,34 @@ export const plainText = (input: string): string => {const text = sanitize(marked(input, { renderer: plainTextRenderer }).trim())return decodeHtmlEntities(text).trim()}++/**+ * Normalizes a URL, adding protocol if needed for regular URLs+ * @param url The URL to normalize+ * @returns The normalized URL+ */+export const normalizeUrl = (url: string) => {+ // Parse the scheme from the URL (e.g. https, mailto, monero, bitcoin, etc.)+ const trimmedUrl = url.trim()+ const scheme = trimmedUrl.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/)?.[1]?.toLowerCase()+ // For URLs without a scheme, add https://, otherwise return the URL as is+ return scheme ? trimmedUrl : `https://${trimmedUrl}`+}++/**+ * URL validation with allowed schemes+ * @param url The URL to validate+ * @param allowedSchemesRegex Array of RegExp patterns for allowed schemes+ * @returns true if valid, false otherwise+ */+export const isValidUrl = (url: string, allowedSchemesRegex?: RegExp[]): boolean => {+ // Return false if the URL is empty+ if (!url || !url.trim()) {+ return false+ }+ // Normalize the URL+ const normalizedUrl = normalizeUrl(url)+ // Check URL against allowed schemes, always including https?://+ const allowed = [new RegExp("^https?://", "i"), ...(allowedSchemesRegex || [])]+ return allowed.some((pattern) => pattern.test(normalizedUrl))+}