diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 832dd83d8..ec997af15 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -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": [] } diff --git a/apps/desktop/layer/main/src/ipc/services/integration.ts b/apps/desktop/layer/main/src/ipc/services/integration.ts index 7551d3260..80288d4b5 100644 --- a/apps/desktop/layer/main/src/ipc/services/integration.ts +++ b/apps/desktop/layer/main/src/ipc/services/integration.ts @@ -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 + } + } } diff --git a/apps/desktop/layer/renderer/src/components/ui/modal/stacked/internal/use-animate.ts b/apps/desktop/layer/renderer/src/components/ui/modal/stacked/internal/use-animate.ts index 8f990f015..58f72d051 100644 --- a/apps/desktop/layer/renderer/src/components/ui/modal/stacked/internal/use-animate.ts +++ b/apps/desktop/layer/renderer/src/components/ui/modal/stacked/internal/use-animate.ts @@ -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({ diff --git a/apps/desktop/layer/renderer/src/modules/integration/URLSchemePreview.tsx b/apps/desktop/layer/renderer/src/modules/integration/URLSchemePreview.tsx new file mode 100644 index 000000000..4a0d04b0d --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/integration/URLSchemePreview.tsx @@ -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(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 ( +
+ + + {isOpen && ( +
+ {isLoading ? ( +
+
+ + Generating preview... +
+
+ ) : preview ? ( +
+ {/* URL Scheme Preview */} +
+

+ Generated URL Scheme +

+
+ + SCHEME + + {preview} +
+
+ + {/* Protocol Info */} +
+

+ Protocol Information +

+
+
+ + Protocol: + + + {preview.split("://")[0]}:// + +
+
+ Action: + + {preview.includes("?") ? "Open with parameters" : "Direct open"} + +
+
+
+ + {/* Placeholders Info */} +
+

+ Available Placeholders for URL Schemes +

+
+ {CustomIntegrationManager.getAvailablePlaceholders().map((placeholder) => ( +
+ {placeholder.key} +
{placeholder.description}
+
+ ))} +
+
+ + {/* Usage Note */} +
+
+ +
+
URL Scheme Behavior
+
+ 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. +
+
+
+
+
+ ) : ( +
+ Failed to generate preview +
+ )} +
+ )} +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts b/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts index 58e35e6e1..90c2d7e1f 100644 --- a/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts +++ b/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts @@ -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): { + 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, + ): string { + // Create sample context + const sampleData = { + title: sampleEntry?.title || "Sample Article Title", + url: sampleEntry?.url || "https://example.com/article", + content_html: sampleEntry?.content || "

This is sample HTML content

", + 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 + } } diff --git a/apps/desktop/layer/renderer/src/modules/integration/url-scheme-handler.ts b/apps/desktop/layer/renderer/src/modules/integration/url-scheme-handler.ts new file mode 100644 index 000000000..44c24be34 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/integration/url-scheme-handler.ts @@ -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 { + 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 { + 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 { + 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]¬es=[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", + }, + ] + } +} diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationModal.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationModal.tsx index 48bb9fadf..07568710e 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationModal.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationModal.tsx @@ -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> + interface CustomIntegrationModalProps { integration?: CustomIntegration onSave: (integration: Omit & { 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 }> + }) => ( + ({ + label: icon.label, + value: icon.value, + }))} + renderItem={(item) => ( +
+ + {item.label} +
+ )} + /> + ), +) + +// 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 + }) => ( + ( +
+ + {item.label} +
+ )} + /> + ), +) + +// Memoized method selector component +const MethodSelector = memo( + ({ + value, + onChange, + items, + }: { + value: string + onChange: (value: string) => void + items: Array<{ label: string; value: string }> + }) => , +) + +// 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>({ - 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({ + resolver: zodResolver(formSchema), + defaultValues, }) - const onSubmit = (values: z.infer) => { - 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 (
- {/* Static Header */} - {/* Scrollable Content */}
@@ -170,7 +377,6 @@ export const CustomIntegrationModalContent = ({
( @@ -178,7 +384,7 @@ export const CustomIntegrationModalContent = ({ {t("integration.custom_integrations.form.name.label")} - ( @@ -198,19 +403,10 @@ export const CustomIntegrationModalContent = ({ {t("integration.custom_integrations.form.icon.label")} - ({ - label: icon.label, - value: icon.value, - }))} - renderItem={(item) => ( -
- - {item.label} -
- )} + onChange={field.onChange} + icons={commonIcons} />
@@ -221,120 +417,196 @@ export const CustomIntegrationModalContent = ({ )} /> - {/* HTTP Method */} + {/* Integration Type */} ( - {t("integration.custom_integrations.form.method.label")} + {t("integration.custom_integrations.form.type.label")} - ({ - label: method, - value: method, - }))} + onChange={handleTypeChange(field.onChange)} + items={integrationTypeItems} + getTypeIcon={getTypeIcon} /> - {t("integration.custom_integrations.form.method.description")} + {t("integration.custom_integrations.form.type.description")} )} /> - {/* URL */} - ( - - - {t("integration.custom_integrations.form.url.label")} - - - - - - {t("integration.custom_integrations.form.url.description")} - - - - )} - /> + {/* HTTP Fields */} + {selectedType === "http" && ( + <> + {/* HTTP Method */} + ( + + + {t("integration.custom_integrations.form.method.label")} + + + + + + {t("integration.custom_integrations.form.method.description")} + + + + )} + /> - {/* Headers */} - ( - - - {t("integration.custom_integrations.form.headers.label")} - - - - - - {t("integration.custom_integrations.form.headers.description")} - - - - )} - /> + {/* URL */} + ( + + + {t("integration.custom_integrations.form.url.label")} + + + + + + {t("integration.custom_integrations.form.url.description")} + + + + )} + /> - {/* Request Body (conditional) */} - {showBodyField && ( - ( - - - {t("integration.custom_integrations.form.body.label")} - - -