feat(integration): add URL scheme support and enhance custom integration management

- Introduced URL scheme handling in the integration module, allowing users to define and execute URL schemes.
- Added validation for URL scheme templates to ensure correct format and required fields.
- Enhanced the CustomIntegrationManager to support both HTTP and URL scheme integrations.
- Implemented a preview feature for URL schemes in the CustomIntegrationModal.
- Updated UI components to accommodate new integration types and improve user experience.

This update expands the capabilities of custom integrations, enabling seamless interaction with external applications through URL schemes.

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-08-02 16:41:54 +08:00
parent 244aca2ad6
commit 44fe72bd92
10 changed files with 1021 additions and 258 deletions
+2 -1
View File
@@ -20,7 +20,8 @@
"Bash(pnpm add:*)",
"Bash(pnpm -w run typecheck)",
"Bash(pnpm --filter @follow/components run typecheck)",
"Bash(pnpm -w run lint:fix)"
"Bash(pnpm -w run lint:fix)",
"Bash(pnpm exec tsc:*)"
],
"deny": []
}
@@ -1,6 +1,7 @@
import { existsSync } from "node:fs"
import fsp from "node:fs/promises"
import { shell } from "electron"
import path from "pathe"
import { store } from "~/lib/store"
@@ -347,4 +348,46 @@ ${content}
throw error
}
}
@IpcMethod()
async openURLScheme(context: IpcContext, scheme: string) {
const requestId = Math.random().toString(36).slice(2, 8)
try {
// Validate URL scheme format
if (!scheme.includes("://")) {
throw new Error("Invalid URL scheme format. Must include protocol (e.g., 'app://')")
}
// Log URL scheme execution (mask sensitive data)
const safeScheme = scheme.replaceAll(/(\?|&)([^=]+)=([^&]+)/g, (_, prefix, key, value) =>
// Mask potential sensitive query parameters
key.toLowerCase().includes("token") ||
key.toLowerCase().includes("key") ||
key.toLowerCase().includes("password")
? `${prefix}${key}=***`
: `${prefix}${key}=${value}`,
)
logger.info(`[URLScheme:${requestId}] Opening URL scheme`, {
scheme: safeScheme,
protocol: scheme.split("://")[0],
})
// Use Electron's shell.openExternal to open URL scheme
// This will trigger the system's default handler for the scheme
await shell.openExternal(scheme)
logger.info(`[URLScheme:${requestId}] URL scheme opened successfully`)
return { success: true }
} catch (error) {
logger.error(`[URLScheme:${requestId}] Failed to open URL scheme`, {
error: error instanceof Error ? error.message : String(error),
scheme: scheme.split("://")[0], // Only log protocol for privacy
})
throw error
}
}
}
@@ -1,3 +1,4 @@
import { Spring } from "@follow/components/constants/spring.js"
import { nextFrame } from "@follow/utils/dom"
import { useAnimationControls } from "motion/react"
import { useCallback, useEffect, useLayoutEffect } from "react"
@@ -19,10 +20,8 @@ export const useModalAnimate = (isTop: boolean) => {
const noticeModal = useCallback(() => {
animateController
.start({
scale: 1.05,
transition: {
duration: 0.06,
},
scale: 1.01,
transition: Spring.snappy(0.06),
})
.then(() => {
animateController.start({
@@ -0,0 +1,141 @@
import { Button } from "@follow/components/ui/button/index.js"
import type { URLSchemeTemplate } from "@follow/shared/settings/interface"
import { cn } from "@follow/utils"
import { useState } from "react"
import { useTranslation } from "react-i18next"
import { CustomIntegrationManager } from "./custom-integration-manager"
interface URLSchemePreviewProps {
urlSchemeTemplate: URLSchemeTemplate
className?: string
}
export const URLSchemePreview = ({ urlSchemeTemplate, className }: URLSchemePreviewProps) => {
const { t } = useTranslation("settings")
const [preview, setPreview] = useState<string | null>(null)
const [isOpen, setIsOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const generatePreview = async (template: URLSchemeTemplate) => {
setIsLoading(true)
try {
const previewScheme = CustomIntegrationManager.getURLSchemePreview(template)
setPreview(previewScheme)
} catch (error) {
console.error("Failed to generate URL scheme preview:", error)
setPreview(null)
} finally {
setIsLoading(false)
}
}
return (
<div className={cn("space-y-2", className)}>
<Button
type="button"
variant="outline"
size="sm"
buttonClassName="w-full py-2"
textClassName="flex w-full justify-between"
onClick={() => {
setIsOpen(!isOpen)
if (!isOpen) {
generatePreview(urlSchemeTemplate)
}
}}
>
<span className="flex items-center gap-2">
<i className="i-mingcute-eye-line" />
{t("integration.custom_integrations.preview.title", "Preview URL Scheme")}
</span>
<i className={cn("i-mgc-right-cute-re transition-transform", isOpen && "rotate-90")} />
</Button>
{isOpen && (
<div className="space-y-3">
{isLoading ? (
<div className="bg-material-medium flex items-center justify-center rounded-lg p-4">
<div className="flex items-center gap-2">
<i className="i-mgc-loading-3-cute-re animate-spin" />
<span className="text-text-tertiary text-sm">Generating preview...</span>
</div>
</div>
) : preview ? (
<div className="bg-material-medium space-y-3 rounded-lg p-4">
{/* URL Scheme Preview */}
<div>
<h4 className="text-text-secondary mb-2 text-sm font-medium">
Generated URL Scheme
</h4>
<div className="bg-material-medium flex items-center gap-2 rounded p-2 font-mono text-sm">
<span className="bg-green/10 text-green rounded px-2 py-1 text-xs font-bold">
SCHEME
</span>
<span className="text-text-secondary break-all">{preview}</span>
</div>
</div>
{/* Protocol Info */}
<div>
<h4 className="text-text-secondary mb-2 text-sm font-medium">
Protocol Information
</h4>
<div className="bg-material-medium space-y-1 rounded p-2">
<div className="flex font-mono text-sm">
<span className="text-text-secondary min-w-0 flex-shrink-0 pr-2">
Protocol:
</span>
<span className="text-text-tertiary min-w-0 flex-1 break-all">
{preview.split("://")[0]}://
</span>
</div>
<div className="flex font-mono text-sm">
<span className="text-text-secondary min-w-0 flex-shrink-0 pr-2">Action:</span>
<span className="text-text-tertiary min-w-0 flex-1 break-all">
{preview.includes("?") ? "Open with parameters" : "Direct open"}
</span>
</div>
</div>
</div>
{/* Placeholders Info */}
<div className="border-border border-t pt-3">
<h4 className="text-text-secondary mb-2 text-sm font-medium">
Available Placeholders for URL Schemes
</h4>
<div className="grid grid-cols-2 gap-2 text-xs">
{CustomIntegrationManager.getAvailablePlaceholders().map((placeholder) => (
<div key={placeholder.key} className="bg-material-opaque rounded p-2">
<code className="text-text font-bold">{placeholder.key}</code>
<div className="text-text-tertiary mt-1">{placeholder.description}</div>
</div>
))}
</div>
</div>
{/* Usage Note */}
<div className="bg-blue/10 border-blue/20 rounded border p-3">
<div className="flex items-start gap-2">
<i className="i-mgc-information-cute-re text-blue mt-0.5 flex-shrink-0" />
<div className="text-blue text-sm">
<div className="mb-1 font-medium">URL Scheme Behavior</div>
<div className="text-blue/80">
URL schemes will attempt to open the target application with the provided
data. Make sure the application is installed and registered for the URL scheme
on your system.
</div>
</div>
</div>
</div>
</div>
) : (
<div className="bg-material-medium flex items-center justify-center rounded-lg p-4">
<span className="text-text-tertiary text-sm">Failed to generate preview</span>
</div>
)}
</div>
)}
</div>
)
}
@@ -1,4 +1,8 @@
import type { CustomIntegration, FetchTemplate } from "@follow/shared/settings/interface"
import type {
CustomIntegration,
FetchTemplate,
URLSchemeTemplate,
} from "@follow/shared/settings/interface"
import type { EntryModel } from "@follow/store/entry/types"
import { getSummary } from "@follow/store/summary/getters"
import { tracker } from "@follow/tracker"
@@ -9,6 +13,7 @@ import { getIntegrationSettings } from "~/atoms/settings/integration"
import { parseHtml } from "~/lib/parse-html"
import { getFetchAdapter } from "./fetch-adapter"
import { URLSchemeHandler } from "./url-scheme-handler"
/**
* Placeholder values that can be used in custom integration templates
@@ -208,37 +213,84 @@ export class CustomIntegrationManager {
// Build placeholder context
const context = await this.buildPlaceholderContext(entry)
// Process fetch template
const { url, headers, body, method } = await this.processFetchTemplate(
integration.fetchTemplate,
context,
)
if (integration.type === "url-scheme" && integration.urlSchemeTemplate) {
// Execute URL scheme
await URLSchemeHandler.getInstance().executeURLScheme(integration.urlSchemeTemplate, {
title: context.title,
url: context.url,
content_html: context.contentHtml,
content_markdown: context.contentMarkdown,
summary: context.summary,
author: context.author,
published_at: context.publishedAt,
description: context.description,
})
return { success: true }
} else if ((integration.type === "http" || !integration.type) && integration.fetchTemplate) {
// Execute HTTP request (existing logic)
const { url, headers, body, method } = await this.processFetchTemplate(
integration.fetchTemplate,
context,
)
// Prepare request options for fetch adapter
const finalHeaders = { ...headers }
// Prepare request options for fetch adapter
const finalHeaders = { ...headers }
// Set content-type if not already set and we have a body
if (
body &&
["POST", "PUT", "PATCH"].includes(method) &&
!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")
) {
finalHeaders["Content-Type"] = "application/json"
// Set content-type if not already set and we have a body
if (
body &&
["POST", "PUT", "PATCH"].includes(method) &&
!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")
) {
finalHeaders["Content-Type"] = "application/json"
}
// Execute the HTTP request using fetch adapter
const response = await getFetchAdapter().fetch(url, {
method: method as "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
headers: finalHeaders,
body: body && ["POST", "PUT", "PATCH"].includes(method) ? body : undefined,
})
// Check if request was successful
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}: ${response.statusText}`)
}
return { success: true }
} else {
// Handle backward compatibility for integrations without type field
if (integration.fetchTemplate) {
// Treat as HTTP integration
const { url, headers, body, method } = await this.processFetchTemplate(
integration.fetchTemplate,
context,
)
const finalHeaders = { ...headers }
if (
body &&
["POST", "PUT", "PATCH"].includes(method) &&
!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")
) {
finalHeaders["Content-Type"] = "application/json"
}
const response = await getFetchAdapter().fetch(url, {
method: method as "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
headers: finalHeaders,
body: body && ["POST", "PUT", "PATCH"].includes(method) ? body : undefined,
})
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}: ${response.statusText}`)
}
return { success: true }
}
}
// Execute the HTTP request using fetch adapter
const response = await getFetchAdapter().fetch(url, {
method: method as "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
headers: finalHeaders,
body: body && ["POST", "PUT", "PATCH"].includes(method) ? body : undefined,
})
// Check if request was successful
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}: ${response.statusText}`)
}
return { success: true }
return { success: false, error: "Invalid integration configuration" }
} catch (error) {
const errorMessage = (error as Error)?.message || "Unknown error"
return { success: false, error: errorMessage }
@@ -297,6 +349,79 @@ export class CustomIntegrationManager {
}
}
/**
* Validate a URL scheme template
*/
static validateURLSchemeTemplate(template: URLSchemeTemplate): {
valid: boolean
errors: string[]
} {
const errors: string[] = []
if (!template.scheme?.trim()) {
errors.push("URL scheme is required")
}
if (template.scheme && !template.scheme.includes("://")) {
errors.push("URL scheme must include protocol (e.g., 'app://')")
}
try {
if (template.scheme) {
// Replace placeholders with sample values for validation
const testScheme = template.scheme.replaceAll(/\[.*?\]/g, "test")
new URL(testScheme)
}
} catch {
errors.push("Invalid URL scheme format")
}
return {
valid: errors.length === 0,
errors,
}
}
/**
* Validate a custom integration
*/
static validateCustomIntegration(integration: Partial<CustomIntegration>): {
valid: boolean
errors: string[]
} {
const errors: string[] = []
if (!integration.name?.trim()) {
errors.push("Integration name is required")
}
// Type is optional for backward compatibility, default to "http"
const integrationType = integration.type || "http"
if (integrationType === "http") {
if (!integration.fetchTemplate) {
errors.push("HTTP template is required for HTTP integrations")
} else {
const templateValidation = this.validateFetchTemplate(integration.fetchTemplate)
errors.push(...templateValidation.errors)
}
} else if (integrationType === "url-scheme") {
if (!integration.urlSchemeTemplate) {
errors.push("URL scheme template is required for URL scheme integrations")
} else {
const templateValidation = this.validateURLSchemeTemplate(integration.urlSchemeTemplate)
errors.push(...templateValidation.errors)
}
} else {
errors.push("Invalid integration type. Must be 'http' or 'url-scheme'")
}
return {
valid: errors.length === 0,
errors,
}
}
/**
* Get template preview with sample data
*/
@@ -323,4 +448,35 @@ export class CustomIntegrationManager {
return this.processFetchTemplate(fetchTemplate, sampleContext)
}
/**
* Get URL scheme preview with sample data
*/
static getURLSchemePreview(
template: URLSchemeTemplate,
sampleEntry?: Partial<EntryModel>,
): string {
// Create sample context
const sampleData = {
title: sampleEntry?.title || "Sample Article Title",
url: sampleEntry?.url || "https://example.com/article",
content_html: sampleEntry?.content || "<p>This is sample HTML content</p>",
content_markdown: "# Sample Article\n\nThis is sample markdown content.",
summary: "This is a sample summary of the article content.",
author: sampleEntry?.author || "John Doe",
published_at: sampleEntry?.publishedAt?.toISOString() || new Date().toISOString(),
description: sampleEntry?.description || "Sample article description",
}
let result = template.scheme
// Replace all placeholders with sample data
Object.entries(sampleData).forEach(([key, value]) => {
const placeholder = `[${key}]`
const encodedValue = encodeURIComponent(value || "")
result = result.replaceAll(placeholder, encodedValue)
})
return result
}
}
@@ -0,0 +1,129 @@
import type { URLSchemeTemplate } from "@follow/shared/settings/interface"
import { toast } from "sonner"
import { ipcServices } from "~/lib/client"
export class URLSchemeHandler {
private static instance: URLSchemeHandler
static getInstance(): URLSchemeHandler {
if (!URLSchemeHandler.instance) {
URLSchemeHandler.instance = new URLSchemeHandler()
}
return URLSchemeHandler.instance
}
/**
* Replace placeholders in URL scheme with actual values
*/
private replacePlaceholders(template: string, data: Record<string, string>): string {
let result = template
// Replace all placeholders like [title], [url], etc.
Object.entries(data).forEach(([key, value]) => {
const placeholder = `[${key}]`
const encodedValue = encodeURIComponent(value || "")
result = result.replaceAll(placeholder, encodedValue)
})
return result
}
/**
* Execute URL scheme with data placeholders
*/
async executeURLScheme(
template: URLSchemeTemplate,
data: {
title?: string
url?: string
content_html?: string
content_markdown?: string
summary?: string
author?: string
published_at?: string
description?: string
},
): Promise<void> {
try {
const finalScheme = this.replacePlaceholders(template.scheme, data)
// Validate URL scheme format
if (!finalScheme.includes("://")) {
throw new Error("Invalid URL scheme format. Must include protocol (e.g., 'app://')")
}
await this.openURLScheme(finalScheme)
// Since URL schemes don't return responses, we assume success
toast.success("URL scheme executed successfully")
} catch (error) {
console.error("URL scheme execution failed:", error)
toast.error(`URL scheme failed: ${error instanceof Error ? error.message : String(error)}`)
}
}
/**
* Platform-specific URL scheme opening
*/
private async openURLScheme(scheme: string): Promise<void> {
if (window.electron && ipcServices) {
// Electron environment - use IPC service
await ipcServices.integration.openURLScheme(scheme)
} else {
// Browser environment - use window.open
// Note: This may be blocked by popup blockers for non-user-initiated actions
const opened = window.open(scheme, "_blank")
if (!opened) {
throw new Error("Failed to open URL scheme. This may be blocked by popup blockers.")
}
}
}
/**
* Check if URL scheme is supported on current platform
*/
canExecuteURLScheme(): boolean {
// URL schemes work in both Electron and browser contexts
// Browser support depends on registered protocol handlers
return true
}
/**
* Get common URL scheme examples for different app types
*/
static getExamples(): { name: string; scheme: string; description: string }[] {
return [
{
name: "Obsidian",
scheme: "obsidian://new?vault=MyVault&name=[title]&content=[content_markdown]",
description: "Create new note in Obsidian vault",
},
{
name: "Bear",
scheme: "bear://x-callback-url/create?title=[title]&text=[content_markdown]&tags=follow",
description: "Create new note in Bear with tags",
},
{
name: "Drafts",
scheme: "drafts://x-callback-url/create?text=[title]%0A%0A[content_markdown]",
description: "Create new draft with title and content",
},
{
name: "Things 3",
scheme: "things:///add?title=[title]&notes=[summary]&list=Reading",
description: "Add item to Things 3 reading list",
},
{
name: "Notion",
scheme: "notion://new?title=[title]&content=[content_markdown]",
description: "Create new Notion page",
},
{
name: "DEVONthink",
scheme: "x-devonthink://createText?title=[title]&text=[content_markdown]&destination=Inbox",
description: "Create new text document in DEVONthink",
},
]
}
}
@@ -12,10 +12,14 @@ import { Input, TextArea } from "@follow/components/ui/input/index.js"
import { KeyValueEditor } from "@follow/components/ui/key-value-editor/index.js"
import { ScrollArea } from "@follow/components/ui/scroll-area/index.js"
import { ResponsiveSelect } from "@follow/components/ui/select/responsive.js"
import type { CustomIntegration } from "@follow/shared/settings/interface"
import type {
CustomIntegration,
FetchTemplate,
URLSchemeTemplate,
} from "@follow/shared/settings/interface"
import { nextFrame } from "@follow/utils"
import { zodResolver } from "@hookform/resolvers/zod"
import { useEffect } from "react"
import { memo, useCallback, useEffect, useMemo } from "react"
import { useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { toast } from "sonner"
@@ -24,77 +28,163 @@ import { z } from "zod"
import { useCurrentModal } from "~/components/ui/modal/stacked/hooks"
import { CustomIntegrationPreview } from "~/modules/integration/CustomIntegrationPreview"
import { PlaceholderHelp } from "~/modules/integration/PlaceholderHelp"
import { URLSchemePreview } from "~/modules/integration/URLSchemePreview"
const formSchema = z.object({
name: z.string().min(1, "Name is required"),
icon: z.string().min(1, "Icon is required"),
fetchTemplate: z.object({
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
url: z.string().min(1, "URL is required"),
headers: z.record(z.string()),
body: z.string().optional(),
}),
enabled: z.boolean(),
const httpTemplateSchema = z.object({
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
url: z.string().url("URL is required"),
headers: z.record(z.string()),
body: z.string().optional(),
})
const urlSchemeTemplateSchema = z.object({
scheme: z.string().url("URL scheme is required"),
})
const createFormSchema = () =>
z
.object({
name: z.string().min(1, "Name is required"),
icon: z.string().min(1, "Icon is required"),
type: z.enum(["http", "url-scheme"]),
fetchTemplate: z.any().optional(),
urlSchemeTemplate: z.any().optional(),
enabled: z.boolean(),
})
.superRefine((data, ctx) => {
try {
if (data.type === "http") {
httpTemplateSchema.parse(data.fetchTemplate)
} else if (data.type === "url-scheme") {
urlSchemeTemplateSchema.parse(data.urlSchemeTemplate)
}
} catch (error) {
if (error instanceof z.ZodError) {
error.errors.forEach((zodError) => {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: zodError.message,
path:
data.type === "http"
? ["fetchTemplate", ...zodError.path]
: ["urlSchemeTemplate", ...zodError.path],
})
})
}
}
})
type FormData = z.infer<ReturnType<typeof createFormSchema>>
interface CustomIntegrationModalProps {
integration?: CustomIntegration
onSave: (integration: Omit<CustomIntegration, "id"> & { id?: string }) => void
}
const getCommonIcons = (t: any) =>
[
{
value: "i-mgc-bookmark-cute-re",
label: t("integration.custom_integrations.icons.bookmark"),
icon: "i-mgc-bookmark-cute-re",
},
{
value: "i-mgc-pic-cute-re",
label: t("integration.custom_integrations.icons.picture"),
icon: "i-mgc-pic-cute-re",
},
{
value: "i-mgc-share-forward-cute-re",
label: t("integration.custom_integrations.icons.share"),
icon: "i-mgc-share-forward-cute-re",
},
{
value: "i-mgc-external-link-cute-re",
label: t("integration.custom_integrations.icons.external_link"),
icon: "i-mgc-external-link-cute-re",
},
{
value: "i-mgc-save-cute-re",
label: t("integration.custom_integrations.icons.save"),
icon: "i-mgc-save-cute-re",
},
{
value: "i-mgc-documents-cute-re",
label: t("integration.custom_integrations.icons.document"),
icon: "i-mgc-documents-cute-re",
},
{
value: "i-mgc-link-cute-re",
label: t("integration.custom_integrations.icons.link"),
icon: "i-mgc-link-cute-re",
},
{
value: "i-mgc-star-cute-re",
label: t("integration.custom_integrations.icons.star"),
icon: "i-mgc-star-cute-re",
},
{
value: "i-mgc-download-2-cute-re",
label: t("integration.custom_integrations.icons.download"),
icon: "i-mgc-download-2-cute-re",
},
{
value: "i-mgc-send-plane-cute-re",
label: t("integration.custom_integrations.icons.send"),
icon: "i-mgc-send-plane-cute-re",
},
] as const
// Constants
const HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"] as const
const INTEGRATION_TYPES = [
{ value: "http", icon: "i-mgc-world-2-cute-re" },
{ value: "url-scheme", icon: "i-mgc-link-cute-re" },
] as const
const ICON_OPTIONS = [
{ value: "i-mgc-bookmark-cute-re", key: "bookmark" },
{ value: "i-mgc-pic-cute-re", key: "picture" },
{ value: "i-mgc-share-forward-cute-re", key: "share" },
{ value: "i-mgc-external-link-cute-re", key: "external_link" },
{ value: "i-mgc-save-cute-re", key: "save" },
{ value: "i-mgc-documents-cute-re", key: "document" },
{ value: "i-mgc-link-cute-re", key: "link" },
{ value: "i-mgc-star-cute-re", key: "star" },
{ value: "i-mgc-download-2-cute-re", key: "download" },
{ value: "i-mgc-send-plane-cute-re", key: "send" },
] as const
// Helper functions
const getDefaultFetchTemplate = (): FetchTemplate => ({
method: "GET",
url: "",
headers: {},
body: "",
})
const getDefaultURLSchemeTemplate = (): URLSchemeTemplate => ({
scheme: "",
})
// Memoized icon selector component
const IconSelector = memo(
({
value,
onChange,
icons,
}: {
value: string
onChange: (value: string) => void
icons: Array<{ value: string; label: string; icon: string }>
}) => (
<ResponsiveSelect
value={value}
onValueChange={onChange}
items={icons.map((icon) => ({
label: icon.label,
value: icon.value,
}))}
renderItem={(item) => (
<div className="flex items-center gap-2">
<i className={item.value} />
{item.label}
</div>
)}
/>
),
)
// Memoized type selector component
const TypeSelector = memo(
({
value,
onChange,
items,
getTypeIcon,
}: {
value: string
onChange: (value: string) => void
items: Array<{ label: string; value: string }>
getTypeIcon: (type: string) => string
}) => (
<ResponsiveSelect
value={value}
onValueChange={onChange}
items={items}
renderItem={(item) => (
<div className="flex items-center gap-2">
<i className={getTypeIcon(item.value)} />
{item.label}
</div>
)}
/>
),
)
// Memoized method selector component
const MethodSelector = memo(
({
value,
onChange,
items,
}: {
value: string
onChange: (value: string) => void
items: Array<{ label: string; value: string }>
}) => <ResponsiveSelect value={value} onValueChange={onChange} items={items} />,
)
// Memoized input field component
const MemoizedInput = memo(Input)
const MemoizedTextArea = memo(TextArea)
const MemoizedKeyValueEditor = memo(KeyValueEditor)
export const CustomIntegrationModalContent = ({
integration,
@@ -102,60 +192,177 @@ export const CustomIntegrationModalContent = ({
}: CustomIntegrationModalProps) => {
const { dismiss } = useCurrentModal()
const { t } = useTranslation("settings")
const commonIcons = getCommonIcons(t)
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
const getCommonIcons = useCallback(
() =>
ICON_OPTIONS.map((icon) => ({
value: icon.value,
label: t(`integration.custom_integrations.icons.${icon.key}`),
icon: icon.value,
})),
[t],
)
// Memoized values
const commonIcons = useMemo(
(): Array<{ value: string; label: string; icon: string }> => getCommonIcons(),
[getCommonIcons],
)
const defaultValues = useMemo((): FormData => {
const integrationType = (integration?.type as "http" | "url-scheme") || "http"
return {
name: integration?.name || "",
icon: integration?.icon || getCommonIcons(() => "")[0].value,
fetchTemplate: integration?.fetchTemplate || {
method: "GET",
url: "",
headers: {},
body: "",
},
icon: integration?.icon || commonIcons[0]?.value || ICON_OPTIONS[0].value,
type: integrationType,
fetchTemplate:
integrationType === "http"
? integration?.fetchTemplate || getDefaultFetchTemplate()
: getDefaultFetchTemplate(),
urlSchemeTemplate:
integrationType === "url-scheme"
? integration?.urlSchemeTemplate || getDefaultURLSchemeTemplate()
: getDefaultURLSchemeTemplate(),
enabled: integration?.enabled ?? true,
},
}
}, [integration, commonIcons])
const formSchema = useMemo(() => createFormSchema(), [])
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues,
})
const onSubmit = (values: z.infer<typeof formSchema>) => {
try {
onSave({
id: integration?.id,
...values,
})
toast.success(
integration
? t("integration.custom_integrations.edit.success")
: t("integration.custom_integrations.create.success"),
)
dismiss()
} catch {
toast.error(
integration
? t("integration.custom_integrations.edit.error")
: t("integration.custom_integrations.create.error"),
)
}
const onSubmit = useCallback(
(values: FormData) => {
try {
// Clean up data based on type - only include relevant template
const cleanedValues = {
id: integration?.id,
name: values.name,
icon: values.icon,
type: values.type,
enabled: values.enabled,
...(values.type === "http"
? { fetchTemplate: values.fetchTemplate }
: { urlSchemeTemplate: values.urlSchemeTemplate }),
}
onSave(cleanedValues)
toast.success(
integration
? t("integration.custom_integrations.edit.success")
: t("integration.custom_integrations.create.success"),
)
dismiss()
} catch {
toast.error(
integration
? t("integration.custom_integrations.edit.error")
: t("integration.custom_integrations.create.error"),
)
}
},
[onSave, integration, t, dismiss],
)
// Only watch essential fields for conditional rendering to minimize re-renders
const selectedType = form.watch("type")
const selectedMethod = form.watch("fetchTemplate.method") // Only watch method for body field display
// Computed values with minimal dependencies
const showBodyField = useMemo(
() => selectedMethod && ["POST", "PUT", "PATCH"].includes(selectedMethod),
[selectedMethod],
)
const shouldShowHTTPPreview = useMemo(() => selectedType === "http", [selectedType])
const shouldShowURLSchemePreview = useMemo(() => selectedType === "url-scheme", [selectedType])
// Get templates only when needed for preview
const getWatchedFetchTemplate = useCallback(() => {
if (!shouldShowHTTPPreview) return null
const template = form.getValues("fetchTemplate")
return template?.url ? template : null
}, [form, shouldShowHTTPPreview])
const getWatchedURLSchemeTemplate = useCallback(() => {
if (!shouldShowURLSchemePreview) return null
const template = form.getValues("urlSchemeTemplate")
return template?.scheme ? template : null
}, [form, shouldShowURLSchemePreview])
// Event handlers
const handleTypeChange = useCallback(
(onChange: (value: string) => void) => (value: string) => {
onChange(value)
// Clear templates for the type we're switching away from
if (value === "http") {
form.setValue("urlSchemeTemplate", getDefaultURLSchemeTemplate())
const currentFetchTemplate = form.getValues("fetchTemplate")
if (!currentFetchTemplate?.url && !currentFetchTemplate?.method) {
form.setValue("fetchTemplate", getDefaultFetchTemplate())
}
} else if (value === "url-scheme") {
form.setValue("fetchTemplate", getDefaultFetchTemplate())
const currentUrlSchemeTemplate = form.getValues("urlSchemeTemplate")
if (!currentUrlSchemeTemplate?.scheme) {
form.setValue("urlSchemeTemplate", getDefaultURLSchemeTemplate())
}
}
// Clear any existing validation errors
form.clearErrors()
},
[form],
)
// Memoized items
const integrationTypeItems = useMemo(
() => [
{
label: t("integration.custom_integrations.form.type.http"),
value: "http" as const,
},
{
label: t("integration.custom_integrations.form.type.url_scheme"),
value: "url-scheme" as const,
},
],
[t],
)
const httpMethodItems = useMemo(
() =>
HTTP_METHODS.map((method) => ({
label: method,
value: method,
})),
[],
)
// Helper functions
const getTypeIcon = (type: string) => {
const typeConfig = INTEGRATION_TYPES.find((t) => t.value === type)
return typeConfig?.icon || "i-mgc-world-2-cute-re"
}
const selectedMethod = form.watch("fetchTemplate.method")
const showBodyField = selectedMethod && ["POST", "PUT", "PATCH"].includes(selectedMethod)
// Watch the entire fetchTemplate for preview
const watchedFetchTemplate = form.watch("fetchTemplate")
useEffect(() => {
nextFrame(() => {
form.setFocus("name")
})
}, [])
}, [form])
return (
<div className="flex max-h-[80vh] w-[500px] flex-col">
{/* Static Header */}
{/* Scrollable Content */}
<div className="relative -mx-4 flex h-0 flex-1">
<ScrollArea.ScrollArea flex rootClassName="flex-1" viewportClassName="px-4">
@@ -170,7 +377,6 @@ export const CustomIntegrationModalContent = ({
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
@@ -178,7 +384,7 @@ export const CustomIntegrationModalContent = ({
{t("integration.custom_integrations.form.name.label")}
</FormLabel>
<FormControl>
<Input
<MemoizedInput
placeholder={t("integration.custom_integrations.form.name.placeholder")}
{...field}
autoFocus
@@ -190,7 +396,6 @@ export const CustomIntegrationModalContent = ({
/>
<FormField
control={form.control}
name="icon"
render={({ field }) => (
<FormItem>
@@ -198,19 +403,10 @@ export const CustomIntegrationModalContent = ({
{t("integration.custom_integrations.form.icon.label")}
</FormLabel>
<FormControl>
<ResponsiveSelect
<IconSelector
value={field.value}
onValueChange={field.onChange}
items={commonIcons.map((icon) => ({
label: icon.label,
value: icon.value,
}))}
renderItem={(item) => (
<div className="flex items-center gap-2">
<i className={item.value} />
{item.label}
</div>
)}
onChange={field.onChange}
icons={commonIcons}
/>
</FormControl>
<FormDescription className="pl-2.5">
@@ -221,120 +417,196 @@ export const CustomIntegrationModalContent = ({
)}
/>
{/* HTTP Method */}
{/* Integration Type */}
<FormField
control={form.control}
name="fetchTemplate.method"
name="type"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.method.label")}
{t("integration.custom_integrations.form.type.label")}
</FormLabel>
<FormControl>
<ResponsiveSelect
<TypeSelector
value={field.value}
onValueChange={field.onChange}
items={["GET", "POST", "PUT", "PATCH", "DELETE"].map((method) => ({
label: method,
value: method,
}))}
onChange={handleTypeChange(field.onChange)}
items={integrationTypeItems}
getTypeIcon={getTypeIcon}
/>
</FormControl>
<FormDescription className="pl-2.5">
{t("integration.custom_integrations.form.method.description")}
{t("integration.custom_integrations.form.type.description")}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
)}
/>
{/* URL */}
<FormField
control={form.control}
name="fetchTemplate.url"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.url.label")}
</FormLabel>
<FormControl>
<Input
placeholder={t("integration.custom_integrations.form.url.placeholder")}
{...field}
/>
</FormControl>
<FormDescription className="pl-2.5">
{t("integration.custom_integrations.form.url.description")}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
)}
/>
{/* HTTP Fields */}
{selectedType === "http" && (
<>
{/* HTTP Method */}
<FormField
name="fetchTemplate.method"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.method.label")}
</FormLabel>
<FormControl>
<MethodSelector
value={field.value}
onChange={field.onChange}
items={httpMethodItems}
/>
</FormControl>
<FormDescription className="pl-2.5">
{t("integration.custom_integrations.form.method.description")}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
)}
/>
{/* Headers */}
<FormField
control={form.control}
name="fetchTemplate.headers"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.headers.label")}
</FormLabel>
<FormControl>
<KeyValueEditor
value={field.value}
onChange={field.onChange}
keyPlaceholder={t(
"integration.custom_integrations.form.headers.key_placeholder",
)}
valuePlaceholder={t(
"integration.custom_integrations.form.headers.value_placeholder",
)}
addButtonText={t("integration.custom_integrations.form.headers.add")}
/>
</FormControl>
<FormDescription className="pl-2.5">
{t("integration.custom_integrations.form.headers.description")}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
)}
/>
{/* URL */}
<FormField
name="fetchTemplate.url"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.url.label")}
</FormLabel>
<FormControl>
<MemoizedInput
placeholder={t(
"integration.custom_integrations.form.url.placeholder",
)}
{...field}
/>
</FormControl>
<FormDescription className="pl-2.5">
{t("integration.custom_integrations.form.url.description")}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
)}
/>
{/* Request Body (conditional) */}
{showBodyField && (
<FormField
control={form.control}
name="fetchTemplate.body"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.body.label")}
</FormLabel>
<FormControl>
<TextArea
placeholder={t("integration.custom_integrations.form.body.placeholder")}
className="resize-none p-2.5 font-mono text-sm"
rows={4}
{...field}
/>
</FormControl>
<FormDescription className="pl-2.5">
{t("integration.custom_integrations.form.body.description")}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
{/* Headers */}
<FormField
name="fetchTemplate.headers"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.headers.label")}
</FormLabel>
<FormControl>
<MemoizedKeyValueEditor
value={field.value}
onChange={field.onChange}
keyPlaceholder={t(
"integration.custom_integrations.form.headers.key_placeholder",
)}
valuePlaceholder={t(
"integration.custom_integrations.form.headers.value_placeholder",
)}
addButtonText={t("integration.custom_integrations.form.headers.add")}
/>
</FormControl>
<FormDescription className="pl-2.5">
{t("integration.custom_integrations.form.headers.description")}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
)}
/>
{/* Request Body (conditional) */}
{showBodyField && (
<FormField
name="fetchTemplate.body"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.body.label")}
</FormLabel>
<FormControl>
<MemoizedTextArea
placeholder={t(
"integration.custom_integrations.form.body.placeholder",
)}
className="resize-none p-2.5 font-mono text-sm"
rows={4}
{...field}
/>
</FormControl>
<FormDescription className="pl-2.5">
{t("integration.custom_integrations.form.body.description")}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
)}
/>
)}
/>
</>
)}
{/* URL Scheme Fields */}
{selectedType === "url-scheme" && (
<>
{/* URL Scheme */}
<FormField
name="urlSchemeTemplate.scheme"
render={({ field }) => (
<FormItem>
<FormLabel className="pl-2.5">
{t("integration.custom_integrations.form.scheme.label", "URL Scheme")}
</FormLabel>
<FormControl>
<MemoizedInput
placeholder={t(
"integration.custom_integrations.form.scheme.placeholder",
"e.g., obsidian://new?vault=MyVault&name=[title]&content=[content_markdown]",
)}
{...field}
className="font-mono text-sm"
/>
</FormControl>
<FormDescription className="pl-2.5">
{t(
"integration.custom_integrations.form.scheme.description",
"Enter the URL scheme for the external application. Use placeholders like [title], [url], [content_markdown], etc.",
)}
</FormDescription>
<FormMessage className="pl-2.5" />
</FormItem>
)}
/>
</>
)}
{/* Template Preview */}
{watchedFetchTemplate.url && (
<CustomIntegrationPreview
fetchTemplate={watchedFetchTemplate}
className="border-t pt-4"
/>
)}
{shouldShowHTTPPreview &&
(() => {
const template = getWatchedFetchTemplate()
return template ? (
<CustomIntegrationPreview
key="http-preview"
fetchTemplate={template}
className="border-t pt-4"
/>
) : null
})()}
{shouldShowURLSchemePreview &&
(() => {
const template = getWatchedURLSchemeTemplate()
return template ? (
<URLSchemePreview
key="url-scheme-preview"
urlSchemeTemplate={template}
className="border-t pt-4"
/>
) : null
})()}
</form>
</Form>
</div>
@@ -347,7 +619,7 @@ export const CustomIntegrationModalContent = ({
{t("words.cancel", { ns: "common" })}
</Button>
<Button
type="submit"
type="button"
disabled={form.formState.isSubmitting}
onClick={form.handleSubmit(onSubmit)}
>
@@ -60,29 +60,32 @@ export const CustomIntegrationSection = memo(({ searchQuery }: CustomIntegration
return customIntegrations.some(
(integration) =>
integration.name.toLowerCase().includes(query) ||
integration.fetchTemplate.url.toLowerCase().includes(query) ||
integration.fetchTemplate.method.toLowerCase().includes(query) ||
Object.keys(integration.fetchTemplate.headers || {}).some(
integration.fetchTemplate?.url?.toLowerCase().includes(query) ||
integration.fetchTemplate?.method?.toLowerCase().includes(query) ||
Object.keys(integration.fetchTemplate?.headers || {}).some(
(key) =>
key.toLowerCase().includes(query) ||
integration.fetchTemplate.headers?.[key]?.toLowerCase().includes(query) ||
integration.fetchTemplate?.headers?.[key]?.toLowerCase().includes(query) ||
false,
) ||
(integration.fetchTemplate.body &&
integration.fetchTemplate.body.toLowerCase().includes(query)),
(integration.fetchTemplate?.body &&
integration.fetchTemplate.body.toLowerCase().includes(query)) ||
(integration.type === "url-scheme" &&
integration.urlSchemeTemplate?.scheme?.toLowerCase().includes(query)),
)
}, [searchQuery, t, settings.customIntegration])
const handleCreateCustomIntegration = useCallback(() => {
present({
title: t("integration.custom_integrations.create.title"),
content: ({ dismiss: _dismiss }) => (
content: () => (
<CustomIntegrationModalContent
onSave={(integrationData) => {
const newIntegration: CustomIntegration = {
id: nanoid(),
...integrationData,
id: nanoid(),
}
const currentIntegrations = settings.customIntegration || []
setIntegrationSetting("customIntegration", [...currentIntegrations, newIntegration])
}}
@@ -95,7 +98,7 @@ export const CustomIntegrationSection = memo(({ searchQuery }: CustomIntegration
(integration: CustomIntegration) => {
present({
title: t("integration.custom_integrations.edit.title"),
content: ({ dismiss: _dismiss }) => (
content: () => (
<CustomIntegrationModalContent
integration={integration}
onSave={(integrationData) => {
@@ -247,9 +250,13 @@ const CustomIntegrationsSection = ({
</div>
<p className="text-text-tertiary truncate text-xs">
<span className="bg-fill text-text-secondary mr-2 rounded px-1.5 py-0.5 font-mono text-xs">
{integration.fetchTemplate.method}
{integration.type === "url-scheme"
? "URL"
: integration.fetchTemplate?.method || "GET"}
</span>
{integration.fetchTemplate.url}
{integration.type === "url-scheme"
? integration.urlSchemeTemplate?.scheme
: integration.fetchTemplate?.url}
</p>
</div>
<div className="flex items-center gap-1">
+8
View File
@@ -367,6 +367,14 @@
"integration.custom_integrations.form.method.label": "HTTP Method",
"integration.custom_integrations.form.name.label": "Integration Name",
"integration.custom_integrations.form.name.placeholder": "Enter integration name",
"integration.custom_integrations.form.scheme.description": "Enter the URL scheme for the external application. Use placeholders like [title], [url], [content_markdown], etc.",
"integration.custom_integrations.form.scheme.examples.title": "Common Examples",
"integration.custom_integrations.form.scheme.label": "URL Scheme",
"integration.custom_integrations.form.scheme.placeholder": "e.g., obsidian://new?vault=MyVault&name=[title]&content=[content_markdown]",
"integration.custom_integrations.form.type.description": "Choose between HTTP API requests or URL scheme redirects to external applications",
"integration.custom_integrations.form.type.http": "HTTP Request",
"integration.custom_integrations.form.type.label": "Integration Type",
"integration.custom_integrations.form.type.url_scheme": "URL Scheme",
"integration.custom_integrations.form.url.description": "Use placeholders: [title], [url], [content_html], [summary], [content_markdown]",
"integration.custom_integrations.form.url.label": "URL",
"integration.custom_integrations.form.url.placeholder": "https://example.com/api/share",
@@ -154,11 +154,18 @@ export interface FetchTemplate {
body?: string
}
export interface URLSchemeTemplate {
scheme: string // e.g., "obsidian://", "bear://", "drafts://action"
// URL schemes use query parameters or path segments for data
}
export interface CustomIntegration {
id: string
name: string
icon: string
fetchTemplate: FetchTemplate
type?: "http" | "url-scheme" // Optional for backward compatibility
fetchTemplate?: FetchTemplate // Keep optional for url-scheme integrations
urlSchemeTemplate?: URLSchemeTemplate
enabled: boolean
}