Skip to content

A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.

feat: latest changes

dextmorgnf44d44da657e
diff --git a/flowsint-app/electron.vite.config.ts b/flowsint-app/electron.vite.config.ts
index f516f63b..091dd9ee 100644
--- a/flowsint-app/electron.vite.config.ts
+++ b/flowsint-app/electron.vite.config.ts
@@ -1,6 +1,6 @@
import { tanstackRouter } from '@tanstack/router-plugin/vite'
import react from '@vitejs/plugin-react'
-import tailwindcss from "@tailwindcss/vite"
+import tailwindcss from '@tailwindcss/vite'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import { resolve } from 'path'
@@ -16,12 +16,12 @@ export default defineConfig({
{
...tanstackRouter({
target: 'react',
- routesDirectory: "src/renderer/src/routes",
- generatedRouteTree: "src/renderer/src/routeTree.gen.ts",
- routeFileIgnorePrefix: "_",
+ routesDirectory: 'src/renderer/src/routes',
+ generatedRouteTree: 'src/renderer/src/routeTree.gen.ts',
+ routeFileIgnorePrefix: '_',
autoCodeSplitting: true,
verboseFileRoutes: false,
- quoteStyle: "double",
+ quoteStyle: 'double',
semicolons: true
}),
enforce: 'pre'
@@ -30,8 +30,7 @@ export default defineConfig({
babel: {
// plugins: ["babel-plugin-react-compiler"]
}
- }
- ),
+ }),
tailwindcss()
],
resolve: {
@@ -41,12 +40,12 @@ export default defineConfig({
},
server: {
proxy: {
- "/api": {
- target: "http://localhost:5001",
+ '/api': {
+ target: 'http://localhost:5001',
changeOrigin: true,
- secure: false,
- },
- },
- },
+ secure: false
+ }
+ }
+ }
}
-})
\ No newline at end of file
+})
diff --git a/flowsint-app/src/main/index.ts b/flowsint-app/src/main/index.ts
index 5d12cc30..81a2075d 100644
--- a/flowsint-app/src/main/index.ts
+++ b/flowsint-app/src/main/index.ts
@@ -25,7 +25,7 @@ app.on('window-all-closed', () => {
ipcMain.handle('get-window-state', () => {
const mainWindow = getMainWindow()
if (!mainWindow) return { isFullscreen: false, isMaximized: false }
-
+
return {
isFullscreen: mainWindow.isFullScreen(),
isMaximized: mainWindow.isMaximized()
diff --git a/flowsint-app/src/main/main-window.ts b/flowsint-app/src/main/main-window.ts
index fca09517..1e1814f3 100644
--- a/flowsint-app/src/main/main-window.ts
+++ b/flowsint-app/src/main/main-window.ts
@@ -14,7 +14,7 @@ export async function initializeMainWindow() {
mainWindow = new BrowserWindow({
width: 900,
icon: join(__dirname, 'icon.png'),
- title: "Flowsint",
+ title: 'Flowsint',
height: 770,
show: false,
autoHideMenuBar: true,
diff --git a/flowsint-app/src/preload/index.d.ts b/flowsint-app/src/preload/index.d.ts
index 7fb70da2..45429f8a 100644
--- a/flowsint-app/src/preload/index.d.ts
+++ b/flowsint-app/src/preload/index.d.ts
@@ -11,4 +11,3 @@ declare global {
}
}
}
-
diff --git a/flowsint-app/src/renderer/src/api/analysis-service.ts b/flowsint-app/src/renderer/src/api/analysis-service.ts
index 679302b9..84e86c71 100644
--- a/flowsint-app/src/renderer/src/api/analysis-service.ts
+++ b/flowsint-app/src/renderer/src/api/analysis-service.ts
@@ -1,37 +1,36 @@
-import { fetchWithAuth } from './api';
-
+import { fetchWithAuth } from './api'
export const analysisService = {
- get: async (): Promise<any> => {
- return fetchWithAuth('/api/analyses', {
- method: 'GET',
- });
- },
- getByInvestigationId: async (investigationId: string): Promise<any> => {
- return fetchWithAuth(`/api/analyses/investigation/${investigationId}`, {
- method: 'GET',
- });
- },
- getById: async (analysisId: string): Promise<any> => {
- return fetchWithAuth(`/api/analyses/${analysisId}`, {
- method: 'GET',
- });
- },
- create: async (body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/analyses/create`, {
- method: 'POST',
- body: body
- });
- },
- update: async (analysisId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/analyses/${analysisId}`, {
- method: 'PUT',
- body: body
- });
- },
- delete: async (analysisId: string): Promise<any> => {
- return fetchWithAuth(`/api/analyses/${analysisId}`, {
- method: 'DELETE',
- });
- },
-};
\ No newline at end of file
+ get: async (): Promise<any> => {
+ return fetchWithAuth('/api/analyses', {
+ method: 'GET'
+ })
+ },
+ getByInvestigationId: async (investigationId: string): Promise<any> => {
+ return fetchWithAuth(`/api/analyses/investigation/${investigationId}`, {
+ method: 'GET'
+ })
+ },
+ getById: async (analysisId: string): Promise<any> => {
+ return fetchWithAuth(`/api/analyses/${analysisId}`, {
+ method: 'GET'
+ })
+ },
+ create: async (body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/analyses/create`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ update: async (analysisId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/analyses/${analysisId}`, {
+ method: 'PUT',
+ body: body
+ })
+ },
+ delete: async (analysisId: string): Promise<any> => {
+ return fetchWithAuth(`/api/analyses/${analysisId}`, {
+ method: 'DELETE'
+ })
+ }
+}
diff --git a/flowsint-app/src/renderer/src/api/api.ts b/flowsint-app/src/renderer/src/api/api.ts
index 1351098b..6743fd5e 100644
--- a/flowsint-app/src/renderer/src/api/api.ts
+++ b/flowsint-app/src/renderer/src/api/api.ts
@@ -1,45 +1,42 @@
-import { useAuthStore } from '@/stores/auth-store';
+import { useAuthStore } from '@/stores/auth-store'
-const API_URL = import.meta.env.VITE_API_URL;
+const API_URL = import.meta.env.VITE_API_URL
-export async function fetchWithAuth(
- endpoint: string,
- options: RequestInit = {}
-): Promise<any> {
- const token = useAuthStore.getState().token;
+export async function fetchWithAuth(endpoint: string, options: RequestInit = {}): Promise<any> {
+ const token = useAuthStore.getState().token
- const defaultHeaders: HeadersInit = {
- 'Content-Type': 'application/json',
- };
+ const defaultHeaders: HeadersInit = {
+ 'Content-Type': 'application/json'
+ }
- if (token) {
- defaultHeaders['Authorization'] = `Bearer ${token}`;
- }
+ if (token) {
+ defaultHeaders['Authorization'] = `Bearer ${token}`
+ }
- const config: RequestInit = {
- ...options,
- headers: {
- ...defaultHeaders,
- ...options.headers,
- },
- };
+ const config: RequestInit = {
+ ...options,
+ headers: {
+ ...defaultHeaders,
+ ...options.headers
+ }
+ }
- try {
- const response = await fetch(`${API_URL}${endpoint}`, config);
- if (response.status === 401) {
- useAuthStore.getState().logout();
- window.location.href = '/login';
- throw new Error('Session expired, login again.');
- }
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.detail || `Erreur ${response.status}`);
- }
- if (response.status === 204) {
- return null;
- }
- return await response.json();
- } catch (error) {
- throw error;
+ try {
+ const response = await fetch(`${API_URL}${endpoint}`, config)
+ if (response.status === 401) {
+ useAuthStore.getState().logout()
+ window.location.href = '/login'
+ throw new Error('Session expired, login again.')
+ }
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}))
+ throw new Error(errorData.detail || `Erreur ${response.status}`)
+ }
+ if (response.status === 204) {
+ return null
}
-}
\ No newline at end of file
+ return await response.json()
+ } catch (error) {
+ throw error
+ }
+}
diff --git a/flowsint-app/src/renderer/src/api/auth-service.ts b/flowsint-app/src/renderer/src/api/auth-service.ts
index 03ac03d0..d4b5a01d 100644
--- a/flowsint-app/src/renderer/src/api/auth-service.ts
+++ b/flowsint-app/src/renderer/src/api/auth-service.ts
@@ -1,54 +1,54 @@
-import { useAuthStore } from '@/stores/auth-store';
-import { fetchWithAuth } from './api';
+import { useAuthStore } from '@/stores/auth-store'
+import { fetchWithAuth } from './api'
export interface RegisterData {
- username: string;
- email: string;
- password: string;
+ username: string
+ email: string
+ password: string
}
export interface LoginData {
- username: string;
- password: string;
+ username: string
+ password: string
}
export interface AuthResponse {
- access_token: string;
- token_type: string;
- user: {
- id: string;
- username: string;
- email: string;
- };
+ access_token: string
+ token_type: string
+ user: {
+ id: string
+ username: string
+ email: string
+ }
}
export const authService = {
- register: async (data: RegisterData): Promise<AuthResponse> => {
- return fetchWithAuth('/api/auth/register', {
- method: 'POST',
- body: JSON.stringify(data),
- });
- },
+ register: async (data: RegisterData): Promise<AuthResponse> => {
+ return fetchWithAuth('/api/auth/register', {
+ method: 'POST',
+ body: JSON.stringify(data)
+ })
+ },
- login: async (data: LoginData): Promise<AuthResponse> => {
- // Création d'un FormData ou URLSearchParams pour la requête d'authentification
- const formData = new URLSearchParams();
- formData.append('username', data.username);
- formData.append('password', data.password);
+ login: async (data: LoginData): Promise<AuthResponse> => {
+ // Création d'un FormData ou URLSearchParams pour la requête d'authentification
+ const formData = new URLSearchParams()
+ formData.append('username', data.username)
+ formData.append('password', data.password)
- return fetchWithAuth('/api/auth/token', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- body: formData,
- });
- },
- logout: () => {
- useAuthStore.getState().logout()
- },
+ return fetchWithAuth('/api/auth/token', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded'
+ },
+ body: formData
+ })
+ },
+ logout: () => {
+ useAuthStore.getState().logout()
+ },
- getCurrentUser: async () => {
- return fetchWithAuth('/api/users/me');
- }
-};
\ No newline at end of file
+ getCurrentUser: async () => {
+ return fetchWithAuth('/api/users/me')
+ }
+}
diff --git a/flowsint-app/src/renderer/src/api/chat-service.ts b/flowsint-app/src/renderer/src/api/chat-service.ts
index 0fc473e9..2aaced36 100644
--- a/flowsint-app/src/renderer/src/api/chat-service.ts
+++ b/flowsint-app/src/renderer/src/api/chat-service.ts
@@ -1,121 +1,124 @@
-import { fetchWithAuth } from "./api";
-import { useAuthStore } from '@/stores/auth-store';
+import { fetchWithAuth } from './api'
+import { useAuthStore } from '@/stores/auth-store'
export interface ChatResponse {
- content: string
+ content: string
}
export class ChatService {
- private static instance: ChatService
+ private static instance: ChatService
- public static getInstance(): ChatService {
- if (!ChatService.instance) {
- ChatService.instance = new ChatService()
- }
- return ChatService.instance
+ public static getInstance(): ChatService {
+ if (!ChatService.instance) {
+ ChatService.instance = new ChatService()
+ }
+ return ChatService.instance
+ }
+
+ async streamChat(
+ chatId: string,
+ prompt: string,
+ onChunk: (content: string) => void,
+ context?: any
+ ): Promise<string> {
+ const token = useAuthStore.getState().token
+ const API_URL = import.meta.env.VITE_API_URL
+
+ const headers: HeadersInit = {
+ 'Content-Type': 'application/json'
}
- async streamChat(chatId: string, prompt: string, onChunk: (content: string) => void, context?: any): Promise<string> {
- const token = useAuthStore.getState().token;
- const API_URL = import.meta.env.VITE_API_URL;
-
- const headers: HeadersInit = {
- 'Content-Type': 'application/json',
- };
-
- if (token) {
- headers['Authorization'] = `Bearer ${token}`;
- }
-
- const response = await fetch(`${API_URL}/api/chats/stream/${chatId}`, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- prompt,
- context
- }),
- });
-
- if (response.status === 401) {
- useAuthStore.getState().logout();
- window.location.href = '/login';
- throw new Error('Session expired, login again.');
- }
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.detail || `Error ${response.status}`);
- }
+ if (token) {
+ headers['Authorization'] = `Bearer ${token}`
+ }
- const reader = response.body?.getReader()
- if (!reader) {
- console.error("No reader available")
- throw new Error('No reader available')
- }
+ const response = await fetch(`${API_URL}/api/chats/stream/${chatId}`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ prompt,
+ context
+ })
+ })
+
+ if (response.status === 401) {
+ useAuthStore.getState().logout()
+ window.location.href = '/login'
+ throw new Error('Session expired, login again.')
+ }
- let accumulatedContent = ''
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}))
+ throw new Error(errorData.detail || `Error ${response.status}`)
+ }
- while (true) {
- const { done, value } = await reader.read()
- if (done) {
- break
- }
+ const reader = response.body?.getReader()
+ if (!reader) {
+ console.error('No reader available')
+ throw new Error('No reader available')
+ }
- const text = new TextDecoder().decode(value)
- const lines = text.split('\n')
-
- for (const line of lines) {
- if (line.startsWith('data: ')) {
- const data = line.slice(6)
- if (data === '[DONE]') {
- return accumulatedContent
- }
- try {
- const parsed = JSON.parse(data)
- if (parsed.content) {
- accumulatedContent += parsed.content
- onChunk(accumulatedContent)
- }
- } catch (e) {
- console.error("Error parsing SSE data:", data, e)
- }
- }
+ let accumulatedContent = ''
+
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) {
+ break
+ }
+
+ const text = new TextDecoder().decode(value)
+ const lines = text.split('\n')
+
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const data = line.slice(6)
+ if (data === '[DONE]') {
+ return accumulatedContent
+ }
+ try {
+ const parsed = JSON.parse(data)
+ if (parsed.content) {
+ accumulatedContent += parsed.content
+ onChunk(accumulatedContent)
}
+ } catch (e) {
+ console.error('Error parsing SSE data:', data, e)
+ }
}
-
- return accumulatedContent
+ }
}
+
+ return accumulatedContent
+ }
}
export const chatService = ChatService.getInstance()
-
-
export const chatCRUDService = {
- get: async (): Promise<any> => {
- return fetchWithAuth('/api/chats', {
- method: 'GET',
- });
- },
- getByInvestigationId: async (investigationId: string): Promise<any> => {
- return fetchWithAuth(`/api/chats/investigation/${investigationId}`, {
- method: 'GET',
- });
- },
- getById: async (chatId: string): Promise<any> => {
- return fetchWithAuth(`/api/chats/${chatId}`, {
- method: 'GET',
- });
- },
- create: async (body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/chats/create`, {
- method: 'POST',
- body: body
- });
- },
- delete: async (chatId: string): Promise<any> => {
- return fetchWithAuth(`/api/chats/${chatId}`, {
- method: 'DELETE',
- });
- },
-};
\ No newline at end of file
+ get: async (): Promise<any> => {
+ return fetchWithAuth('/api/chats', {
+ method: 'GET'
+ })
+ },
+ getByInvestigationId: async (investigationId: string): Promise<any> => {
+ return fetchWithAuth(`/api/chats/investigation/${investigationId}`, {
+ method: 'GET'
+ })
+ },
+ getById: async (chatId: string): Promise<any> => {
+ return fetchWithAuth(`/api/chats/${chatId}`, {
+ method: 'GET'
+ })
+ },
+ create: async (body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/chats/create`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ delete: async (chatId: string): Promise<any> => {
+ return fetchWithAuth(`/api/chats/${chatId}`, {
+ method: 'DELETE'
+ })
+ }
+}
diff --git a/flowsint-app/src/renderer/src/api/flow-service.ts b/flowsint-app/src/renderer/src/api/flow-service.ts
index 0efb6f39..0d4e403d 100644
--- a/flowsint-app/src/renderer/src/api/flow-service.ts
+++ b/flowsint-app/src/renderer/src/api/flow-service.ts
@@ -1,54 +1,54 @@
-import { fetchWithAuth } from './api';
+import { fetchWithAuth } from './api'
export const flowService = {
- get: async (type?: string): Promise<any> => {
- const url = type ? `/api/flows?category=${type}` : "/api/flows"
- return fetchWithAuth(url, {
- method: 'GET',
- });
- },
- getById: async (flowId: string): Promise<any> => {
- return fetchWithAuth(`/api/flows/${flowId}`, {
- method: 'GET',
- });
- },
- create: async (body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/flows/create`, {
- method: 'POST',
- body: body
- });
- },
- update: async (flowId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/flows/${flowId}`, {
- method: 'PUT',
- body: body
- });
- },
- compute: async (flowId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/flows/${flowId}/compute`, {
- method: 'POST',
- body: body
- });
- },
- delete: async (flowId: string): Promise<any> => {
- return fetchWithAuth(`/api/flows/${flowId}`, {
- method: 'DELETE',
- });
- },
- launch: async (flowId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/flows/${flowId}/launch`, {
- method: 'POST',
- body: body
- });
- },
- getRawMaterial: async (): Promise<any> => {
- return fetchWithAuth(`/api/flows/raw_materials`, {
- method: 'GET',
- });
- },
- getRawMaterialForType: async (type: string): Promise<any> => {
- return fetchWithAuth(`/api/flows/input_type/${type}`, {
- method: 'GET',
- });
- },
-};
\ No newline at end of file
+ get: async (type?: string): Promise<any> => {
+ const url = type ? `/api/flows?category=${type}` : '/api/flows'
+ return fetchWithAuth(url, {
+ method: 'GET'
+ })
+ },
+ getById: async (flowId: string): Promise<any> => {
+ return fetchWithAuth(`/api/flows/${flowId}`, {
+ method: 'GET'
+ })
+ },
+ create: async (body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/flows/create`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ update: async (flowId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/flows/${flowId}`, {
+ method: 'PUT',
+ body: body
+ })
+ },
+ compute: async (flowId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/flows/${flowId}/compute`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ delete: async (flowId: string): Promise<any> => {
+ return fetchWithAuth(`/api/flows/${flowId}`, {
+ method: 'DELETE'
+ })
+ },
+ launch: async (flowId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/flows/${flowId}/launch`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ getRawMaterial: async (): Promise<any> => {
+ return fetchWithAuth(`/api/flows/raw_materials`, {
+ method: 'GET'
+ })
+ },
+ getRawMaterialForType: async (type: string): Promise<any> => {
+ return fetchWithAuth(`/api/flows/input_type/${type}`, {
+ method: 'GET'
+ })
+ }
+}
diff --git a/flowsint-app/src/renderer/src/api/investigation-service.ts b/flowsint-app/src/renderer/src/api/investigation-service.ts
index 98c3da2d..a5fd1f70 100644
--- a/flowsint-app/src/renderer/src/api/investigation-service.ts
+++ b/flowsint-app/src/renderer/src/api/investigation-service.ts
@@ -1,26 +1,25 @@
-import { fetchWithAuth } from './api';
-
+import { fetchWithAuth } from './api'
export const investigationService = {
- get: async (): Promise<any> => {
- return fetchWithAuth('/api/investigations', {
- method: 'GET',
- });
- },
- getById: async (investigationId: string): Promise<any> => {
- return fetchWithAuth(`/api/investigations/${investigationId}`, {
- method: 'GET',
- });
- },
- create: async (body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/investigations/create`, {
- method: 'POST',
- body: body
- });
- },
- delete: async (investigationId: string): Promise<any> => {
- return fetchWithAuth(`/api/investigations/${investigationId}`, {
- method: 'DELETE',
- });
- },
-};
\ No newline at end of file
+ get: async (): Promise<any> => {
+ return fetchWithAuth('/api/investigations', {
+ method: 'GET'
+ })
+ },
+ getById: async (investigationId: string): Promise<any> => {
+ return fetchWithAuth(`/api/investigations/${investigationId}`, {
+ method: 'GET'
+ })
+ },
+ create: async (body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/investigations/create`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ delete: async (investigationId: string): Promise<any> => {
+ return fetchWithAuth(`/api/investigations/${investigationId}`, {
+ method: 'DELETE'
+ })
+ }
+}
diff --git a/flowsint-app/src/renderer/src/api/key-service.ts b/flowsint-app/src/renderer/src/api/key-service.ts
index 52c33c9e..a30195dd 100644
--- a/flowsint-app/src/renderer/src/api/key-service.ts
+++ b/flowsint-app/src/renderer/src/api/key-service.ts
@@ -1,11 +1,12 @@
import { fetchWithAuth } from './api'
export const KeyService = {
- get: () => fetchWithAuth(`/api/keys`, { method: 'GET' }),
- getById: (key_id: string) => fetchWithAuth(`/api/keys/${key_id}`, { method: 'GET' }),
- create: (data: { name: string; key: string }) => fetchWithAuth(`/api/keys/create`, {
- method: 'POST',
- body: JSON.stringify(data)
+ get: () => fetchWithAuth(`/api/keys`, { method: 'GET' }),
+ getById: (key_id: string) => fetchWithAuth(`/api/keys/${key_id}`, { method: 'GET' }),
+ create: (data: { name: string; key: string }) =>
+ fetchWithAuth(`/api/keys/create`, {
+ method: 'POST',
+ body: JSON.stringify(data)
}),
- deleteById: (key_id: string) => fetchWithAuth(`/api/keys/${key_id}`, { method: 'DELETE' }),
-}
\ No newline at end of file
+ deleteById: (key_id: string) => fetchWithAuth(`/api/keys/${key_id}`, { method: 'DELETE' })
+}
diff --git a/flowsint-app/src/renderer/src/api/log-service.ts b/flowsint-app/src/renderer/src/api/log-service.ts
index 7daeef0e..c8bb9eb1 100644
--- a/flowsint-app/src/renderer/src/api/log-service.ts
+++ b/flowsint-app/src/renderer/src/api/log-service.ts
@@ -1,15 +1,14 @@
-import { fetchWithAuth } from './api';
-
+import { fetchWithAuth } from './api'
export const logService = {
- get: async (sketch_id: string): Promise<any> => {
- return fetchWithAuth(`/api/events/sketch/${sketch_id}/logs`, {
- method: 'GET',
- });
- },
- delete: async (sketch_id: string): Promise<any> => {
- return fetchWithAuth(`/api/events/sketch/${sketch_id}/logs`, {
- method: 'DELETE',
- });
- },
-};
\ No newline at end of file
+ get: async (sketch_id: string): Promise<any> => {
+ return fetchWithAuth(`/api/events/sketch/${sketch_id}/logs`, {
+ method: 'GET'
+ })
+ },
+ delete: async (sketch_id: string): Promise<any> => {
+ return fetchWithAuth(`/api/events/sketch/${sketch_id}/logs`, {
+ method: 'DELETE'
+ })
+ }
+}
diff --git a/flowsint-app/src/renderer/src/api/query-keys-examples.ts b/flowsint-app/src/renderer/src/api/query-keys-examples.ts
index 4e8b7320..bb13d929 100644
--- a/flowsint-app/src/renderer/src/api/query-keys-examples.ts
+++ b/flowsint-app/src/renderer/src/api/query-keys-examples.ts
@@ -16,7 +16,7 @@ import { transformService } from './transform-service'
export const useInvestigationsList = () => {
return useQuery({
queryKey: queryKeys.investigations.list,
- queryFn: investigationService.get,
+ queryFn: investigationService.get
})
}
@@ -24,7 +24,7 @@ export const useInvestigationDetail = (investigationId: string) => {
return useQuery({
queryKey: queryKeys.investigations.detail(investigationId),
queryFn: () => investigationService.getById(investigationId),
- enabled: !!investigationId,
+ enabled: !!investigationId
})
}
@@ -32,7 +32,7 @@ export const useInvestigationAnalyses = (investigationId: string) => {
return useQuery({
queryKey: queryKeys.investigations.analyses(investigationId),
queryFn: () => analysisService.getByInvestigationId(investigationId),
- enabled: !!investigationId,
+ enabled: !!investigationId
})
}
@@ -40,7 +40,7 @@ export const useInvestigationAnalyses = (investigationId: string) => {
export const useSketchesList = () => {
return useQuery({
queryKey: queryKeys.sketches.list,
- queryFn: sketchService.get,
+ queryFn: sketchService.get
})
}
@@ -48,7 +48,7 @@ export const useSketchDetail = (sketchId: string) => {
return useQuery({
queryKey: queryKeys.sketches.detail(sketchId),
queryFn: () => sketchService.getById(sketchId),
- enabled: !!sketchId,
+ enabled: !!sketchId
})
}
@@ -56,14 +56,14 @@ export const useSketchGraph = (investigationId: string, sketchId: string) => {
return useQuery({
queryKey: queryKeys.sketches.graph(investigationId, sketchId),
queryFn: () => sketchService.getById(sketchId),
- enabled: !!investigationId && !!sketchId,
+ enabled: !!investigationId && !!sketchId
})
}
// Example 3: Using with mutations and invalidation
export const useCreateAnalysis = () => {
const queryClient = useQueryClient()
-
+
return useMutation({
mutationFn: async (data: { title: string; investigation_id: string; content: any }) => {
return analysisService.create(JSON.stringify(data))
@@ -73,34 +73,31 @@ export const useCreateAnalysis = () => {
queryClient.invalidateQueries({
queryKey: queryKeys.investigations.analyses(variables.investigation_id)
})
-
+
// Also invalidate the general analyses list
queryClient.invalidateQueries({
queryKey: queryKeys.analyses.list
})
- },
+ }
})
}
export const useUpdateAnalysis = () => {
const queryClient = useQueryClient()
-
+
return useMutation({
mutationFn: async ({ analysisId, data }: { analysisId: string; data: any }) => {
return analysisService.update(analysisId, JSON.stringify(data))
},
onSuccess: (data, variables) => {
// Update the cache directly for better UX
- queryClient.setQueryData(
- queryKeys.analyses.detail(variables.analysisId),
- data
- )
-
+ queryClient.setQueryData(queryKeys.analyses.detail(variables.analysisId), data)
+
// Invalidate related queries
queryClient.invalidateQueries({
queryKey: queryKeys.analyses.byInvestigation(data.investigation_id)
})
- },
+ }
})
}
@@ -109,7 +106,7 @@ export const useChatDetail = (chatId: string) => {
return useQuery({
queryKey: queryKeys.chats.detail(chatId),
queryFn: () => chatCRUDService.getById(chatId),
- enabled: !!chatId,
+ enabled: !!chatId
})
}
@@ -117,7 +114,7 @@ export const useChatsByInvestigation = (investigationId: string) => {
return useQuery({
queryKey: queryKeys.chats.byInvestigation(investigationId),
queryFn: () => chatCRUDService.getByInvestigationId(investigationId),
- enabled: !!investigationId,
+ enabled: !!investigationId
})
}
@@ -127,7 +124,7 @@ export const useLogsBySketch = (sketchId: string) => {
queryKey: queryKeys.logs.bySketch(sketchId),
queryFn: () => logService.get(sketchId),
enabled: !!sketchId,
- staleTime: 30_000, // 30 seconds
+ staleTime: 30_000 // 30 seconds
})
}
@@ -135,7 +132,7 @@ export const useLogsBySketch = (sketchId: string) => {
export const useKeysList = () => {
return useQuery({
queryKey: queryKeys.keys.list,
- queryFn: KeyService.get,
+ queryFn: KeyService.get
})
}
@@ -143,7 +140,7 @@ export const useKeyDetail = (keyId: string) => {
return useQuery({
queryKey: queryKeys.keys.detail(keyId),
queryFn: () => KeyService.getById(keyId),
- enabled: !!keyId,
+ enabled: !!keyId
})
}
@@ -152,7 +149,7 @@ export const useScanDetail = (scanId: string) => {
return useQuery({
queryKey: queryKeys.scans.detail(scanId),
queryFn: () => scanService.get(scanId),
- enabled: !!scanId,
+ enabled: !!scanId
})
}
@@ -160,14 +157,14 @@ export const useScanDetail = (scanId: string) => {
export const useTransformsList = () => {
return useQuery({
queryKey: queryKeys.transforms.list,
- queryFn: transformService.get,
+ queryFn: transformService.get
})
}
// Example 9: Complex invalidation patterns
export const useDeleteInvestigation = () => {
const queryClient = useQueryClient()
-
+
return useMutation({
mutationFn: investigationService.delete,
onSuccess: (data, variables) => {
@@ -175,42 +172,42 @@ export const useDeleteInvestigation = () => {
queryClient.invalidateQueries({
queryKey: queryKeys.investigations.list
})
-
+
// Invalidate all related data
queryClient.invalidateQueries({
queryKey: queryKeys.investigations.detail(variables)
})
-
+
// Clear related caches
queryClient.removeQueries({
queryKey: queryKeys.investigations.analyses(variables)
})
-
+
queryClient.removeQueries({
queryKey: queryKeys.investigations.sketches(variables)
})
-
+
queryClient.removeQueries({
queryKey: queryKeys.investigations.flows(variables)
})
- },
+ }
})
}
// Example 10: Prefetching with query keys
export const usePrefetchInvestigation = () => {
const queryClient = useQueryClient()
-
+
return (investigationId: string) => {
queryClient.prefetchQuery({
queryKey: queryKeys.investigations.detail(investigationId),
- queryFn: () => investigationService.getById(investigationId),
+ queryFn: () => investigationService.getById(investigationId)
})
-
+
// Also prefetch related data
queryClient.prefetchQuery({
queryKey: queryKeys.investigations.analyses(investigationId),
- queryFn: () => analysisService.getByInvestigationId(investigationId),
+ queryFn: () => analysisService.getByInvestigationId(investigationId)
})
}
}
diff --git a/flowsint-app/src/renderer/src/api/query-keys.ts b/flowsint-app/src/renderer/src/api/query-keys.ts
index 5424f9af..7b10a29b 100644
--- a/flowsint-app/src/renderer/src/api/query-keys.ts
+++ b/flowsint-app/src/renderer/src/api/query-keys.ts
@@ -3,7 +3,7 @@ export const queryKeys = {
// Auth related queries
auth: {
session: ['auth', 'session'],
- currentUser: ['auth', 'currentUser'],
+ currentUser: ['auth', 'currentUser']
},
// Investigations
@@ -14,7 +14,7 @@ export const queryKeys = {
analyses: (investigationId: string) => [investigationId, 'analyses'],
flows: (investigationId: string) => [investigationId, 'flows'],
dashboard: ['investigations', 'dashboard'],
- selector: (investigationId: string) => ['dashboard', 'selector', investigationId],
+ selector: (investigationId: string) => ['dashboard', 'selector', investigationId]
},
// Sketches/Graphs
@@ -24,7 +24,7 @@ export const queryKeys = {
byInvestigation: (investigationId: string) => [investigationId, 'sketches'],
graph: (investigationId: string, sketchId: string) => [investigationId, 'graph', sketchId],
types: ['sketches', 'types'],
- dashboard: (investigationId: string) => ['dashboard', 'investigation', investigationId],
+ dashboard: (investigationId: string) => ['dashboard', 'investigation', investigationId]
},
// Analyses
@@ -32,14 +32,14 @@ export const queryKeys = {
list: ['analyses', 'list'],
detail: (analysisId: string) => ['analyses', analysisId],
byInvestigation: (investigationId: string) => [investigationId, 'analyses'],
- dashboard: (investigationId: string) => ['analyses', investigationId],
+ dashboard: (investigationId: string) => ['analyses', investigationId]
},
// Flows
flows: {
list: ['flows', 'list'],
detail: (flowId: string) => ['flows', flowId],
- byInvestigation: (investigationId: string) => [investigationId, 'flows'],
+ byInvestigation: (investigationId: string) => [investigationId, 'flows']
},
// Chats
@@ -47,18 +47,18 @@ export const queryKeys = {
list: ['chats', 'list'],
detail: (chatId: string) => ['chats', chatId],
byInvestigation: (investigationId: string) => [investigationId, 'chats'],
- messages: (chatId: string) => [chatId, 'messages'],
+ messages: (chatId: string) => [chatId, 'messages']
},
// API Keys
keys: {
list: ['keys'],
- detail: (keyId: string) => ['keys', keyId],
+ detail: (keyId: string) => ['keys', keyId]
},
// Logs/Events
logs: {
- bySketch: (sketchId: string) => [sketchId, 'logs'],
+ bySketch: (sketchId: string) => [sketchId, 'logs']
},
// Action Items
@@ -67,14 +67,14 @@ export const queryKeys = {
// Scans
scans: {
list: ['scans', 'list'],
- detail: (scanId: string) => ['scans', scanId],
+ detail: (scanId: string) => ['scans', scanId]
},
// Transforms
transforms: {
list: ['transforms', 'list'],
- detail: (transformId: string) => ['transforms', transformId],
- },
+ detail: (transformId: string) => ['transforms', transformId]
+ }
}
// Export individual key groups for easier imports
diff --git a/flowsint-app/src/renderer/src/api/scan-service.ts b/flowsint-app/src/renderer/src/api/scan-service.ts
index 462c1166..02834543 100644
--- a/flowsint-app/src/renderer/src/api/scan-service.ts
+++ b/flowsint-app/src/renderer/src/api/scan-service.ts
@@ -1,8 +1,9 @@
import { fetchWithAuth } from './api'
export const scanService = {
- get: (scan_id: string) => fetchWithAuth(`/api/scans/${scan_id}`, { method: 'GET' }),
- delete: (scan_id: string) => fetchWithAuth(`/api/scans/${scan_id}`, { method: 'DELETE' }),
- getSketchScans: (sketch_id: string) => fetchWithAuth(`/api/scans/sketch/${sketch_id}`, { method: 'GET' }),
- deleteAll: () => fetchWithAuth('/api/scans/all', { method: 'DELETE' })
-}
\ No newline at end of file
+ get: (scan_id: string) => fetchWithAuth(`/api/scans/${scan_id}`, { method: 'GET' }),
+ delete: (scan_id: string) => fetchWithAuth(`/api/scans/${scan_id}`, { method: 'DELETE' }),
+ getSketchScans: (sketch_id: string) =>
+ fetchWithAuth(`/api/scans/sketch/${sketch_id}`, { method: 'GET' }),
+ deleteAll: () => fetchWithAuth('/api/scans/all', { method: 'DELETE' })
+}
diff --git a/flowsint-app/src/renderer/src/api/sketch-service.ts b/flowsint-app/src/renderer/src/api/sketch-service.ts
index 9be7ebf0..445f9113 100644
--- a/flowsint-app/src/renderer/src/api/sketch-service.ts
+++ b/flowsint-app/src/renderer/src/api/sketch-service.ts
@@ -1,77 +1,76 @@
-import { fetchWithAuth } from './api';
-
+import { fetchWithAuth } from './api'
export const sketchService = {
- get: async (): Promise<any> => {
- return fetchWithAuth('/api/sketches', {
- method: 'GET',
- });
- },
- getById: async (sketchId: string): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}`, {
- method: 'GET',
- });
- },
- getGraphDataById: async (sketchId: string, inline: boolean = false): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}/graph?format=${inline ? 'inline' : ''}`, {
- method: 'GET',
- });
- },
- create: async (body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/sketches/create`, {
- method: 'POST',
- body: body
- });
- },
- delete: async (sketchId: string): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}`, {
- method: 'DELETE',
- });
- },
- addNode: async (sketchId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}/nodes/add`, {
- method: 'POST',
- body: body
- });
- },
- addEdge: async (sketchId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}/relations/add`, {
- method: 'POST',
- body: body
- });
- },
- mergeNodes: async (sketchId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}/nodes/merge`, {
- method: 'POST',
- body: body
- });
- },
- deleteNodes: async (sketchId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}/nodes`, {
- method: 'DELETE',
- body: body
- });
- },
- updateNode: async (sketchId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}/nodes/edit`, {
- method: 'PUT',
- body: body
- });
- },
- getNodeNeighbors: async (sketchId: string, nodeId: string): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}/nodes/${nodeId}`, {
- method: 'GET'
- });
- },
- types: async (): Promise<any> => {
- return fetchWithAuth(`/api/types`, {
- method: 'GET'
- });
- },
- update: async (sketchId: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/sketches/${sketchId}`, {
- method: 'PUT',
- body: body
- });
- },
-};
\ No newline at end of file
+ get: async (): Promise<any> => {
+ return fetchWithAuth('/api/sketches', {
+ method: 'GET'
+ })
+ },
+ getById: async (sketchId: string): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}`, {
+ method: 'GET'
+ })
+ },
+ getGraphDataById: async (sketchId: string, inline: boolean = false): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}/graph?format=${inline ? 'inline' : ''}`, {
+ method: 'GET'
+ })
+ },
+ create: async (body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/create`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ delete: async (sketchId: string): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}`, {
+ method: 'DELETE'
+ })
+ },
+ addNode: async (sketchId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}/nodes/add`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ addEdge: async (sketchId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}/relations/add`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ mergeNodes: async (sketchId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}/nodes/merge`, {
+ method: 'POST',
+ body: body
+ })
+ },
+ deleteNodes: async (sketchId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}/nodes`, {
+ method: 'DELETE',
+ body: body
+ })
+ },
+ updateNode: async (sketchId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}/nodes/edit`, {
+ method: 'PUT',
+ body: body
+ })
+ },
+ getNodeNeighbors: async (sketchId: string, nodeId: string): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}/nodes/${nodeId}`, {
+ method: 'GET'
+ })
+ },
+ types: async (): Promise<any> => {
+ return fetchWithAuth(`/api/types`, {
+ method: 'GET'
+ })
+ },
+ update: async (sketchId: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/sketches/${sketchId}`, {
+ method: 'PUT',
+ body: body
+ })
+ }
+}
diff --git a/flowsint-app/src/renderer/src/api/transform-service.ts b/flowsint-app/src/renderer/src/api/transform-service.ts
index 88c3bf06..7506f4f2 100644
--- a/flowsint-app/src/renderer/src/api/transform-service.ts
+++ b/flowsint-app/src/renderer/src/api/transform-service.ts
@@ -1,16 +1,16 @@
-import { fetchWithAuth } from './api';
+import { fetchWithAuth } from './api'
export const transformService = {
- get: async (type?: string): Promise<any> => {
- const url = type ? `/api/transforms?category=${type}` : "/api/transforms"
- return fetchWithAuth(url, {
- method: 'GET',
- });
- },
- launch: async (transformName: string, body: BodyInit): Promise<any> => {
- return fetchWithAuth(`/api/transforms/${transformName}/launch`, {
- method: 'POST',
- body: body
- });
- },
-};
\ No newline at end of file
+ get: async (type?: string): Promise<any> => {
+ const url = type ? `/api/transforms?category=${type}` : '/api/transforms'
+ return fetchWithAuth(url, {
+ method: 'GET'
+ })
+ },
+ launch: async (transformName: string, body: BodyInit): Promise<any> => {
+ return fetchWithAuth(`/api/transforms/${transformName}/launch`, {
+ method: 'POST',
+ body: body
+ })
+ }
+}
diff --git a/flowsint-app/src/renderer/src/components/analyses/analyses-list.tsx b/flowsint-app/src/renderer/src/components/analyses/analyses-list.tsx
index 056ca6f3..963d30f1 100644
--- a/flowsint-app/src/renderer/src/components/analyses/analyses-list.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/analyses-list.tsx
@@ -1,161 +1,177 @@
-import { useQuery } from "@tanstack/react-query"
-import { Button } from "../ui/button"
-import { PlusIcon, FileText } from "lucide-react"
-import { Input } from "../ui/input"
-import { useParams, Link, useNavigate } from "@tanstack/react-router"
-import { SkeletonList } from "../shared/skeleton-list"
-import { useState, useMemo } from "react"
-import { Analysis } from "@/types"
-import { analysisService } from "@/api/analysis-service"
-import { cn } from "@/lib/utils"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { toast } from "sonner"
-import { formatDistanceToNow } from "date-fns"
-import { queryKeys } from "@/api/query-keys"
-import ErrorState from "../shared/error-state"
+import { useQuery } from '@tanstack/react-query'
+import { Button } from '../ui/button'
+import { PlusIcon, FileText } from 'lucide-react'
+import { Input } from '../ui/input'
+import { useParams, Link, useNavigate } from '@tanstack/react-router'
+import { SkeletonList } from '../shared/skeleton-list'
+import { useState, useMemo } from 'react'
+import { Analysis } from '@/types'
+import { analysisService } from '@/api/analysis-service'
+import { cn } from '@/lib/utils'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+import { formatDistanceToNow } from 'date-fns'
+import { queryKeys } from '@/api/query-keys'
+import ErrorState from '../shared/error-state'
-const AnalysisItem = ({ analysis, active }: { analysis: Analysis, active: boolean }) => {
- return (
- <Link
- to="/dashboard/investigations/$investigationId/$type/$id"
- params={{
- investigationId: analysis.investigation_id || "",
- type: "analysis",
- id: analysis.id
- }}
- className={cn("p-2 flex items-center gap-2 border-b shrink-0 hover:bg-muted/50 transition-colors", active && "bg-primary/10")}
- >
- <div className="flex items-center gap-2 w-full">
- <div className="w-10 h-10 bg-muted rounded-full flex items-center justify-center">
- <FileText className="h-5 w-5 text-muted-foreground" />
- </div>
- <div className="flex flex-col flex-1 min-w-0">
- <p className="text-sm font-medium truncate">{analysis.title}</p>
- <p className="text-xs text-muted-foreground">
- {analysis.last_updated_at ? formatDistanceToNow(new Date(analysis.last_updated_at), { addSuffix: true }) : ""}
- </p>
- </div>
- </div>
- </Link>
- )
+const AnalysisItem = ({ analysis, active }: { analysis: Analysis; active: boolean }) => {
+ return (
+ <Link
+ to="/dashboard/investigations/$investigationId/$type/$id"
+ params={{
+ investigationId: analysis.investigation_id || '',
+ type: 'analysis',
+ id: analysis.id
+ }}
+ className={cn(
+ 'p-2 flex items-center gap-2 border-b shrink-0 hover:bg-muted/50 transition-colors',
+ active && 'bg-primary/10'
+ )}
+ >
+ <div className="flex items-center gap-2 w-full">
+ <div className="w-10 h-10 bg-muted rounded-full flex items-center justify-center">
+ <FileText className="h-5 w-5 text-muted-foreground" />
+ </div>
+ <div className="flex flex-col flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">{analysis.title}</p>
+ <p className="text-xs text-muted-foreground">
+ {analysis.last_updated_at
+ ? formatDistanceToNow(new Date(analysis.last_updated_at), { addSuffix: true })
+ : ''}
+ </p>
+ </div>
+ </div>
+ </Link>
+ )
}
const AnalysisList = () => {
- const { investigationId, id, type } = useParams({ strict: false })
- const queryClient = useQueryClient()
- const navigate = useNavigate()
-
- // Fetch all analyses for this investigation
- const { data: analyses, isLoading, error, refetch } = useQuery({
- queryKey: queryKeys.analyses.byInvestigation(investigationId || ""),
- queryFn: () => analysisService.getByInvestigationId(investigationId || ""),
- enabled: !!investigationId,
- })
+ const { investigationId, id, type } = useParams({ strict: false })
+ const queryClient = useQueryClient()
+ const navigate = useNavigate()
- const [searchQuery, setSearchQuery] = useState("")
+ // Fetch all analyses for this investigation
+ const {
+ data: analyses,
+ isLoading,
+ error,
+ refetch
+ } = useQuery({
+ queryKey: queryKeys.analyses.byInvestigation(investigationId || ''),
+ queryFn: () => analysisService.getByInvestigationId(investigationId || ''),
+ enabled: !!investigationId
+ })
- const filteredAnalyses = useMemo(() => {
- if (!analyses) return []
- if (!searchQuery.trim()) return analyses
+ const [searchQuery, setSearchQuery] = useState('')
- const query = searchQuery.toLowerCase().trim()
- return analyses.filter((analysis: Analysis) =>
- analysis.title.toLowerCase().includes(query)
- )
- }, [analyses, searchQuery])
+ const filteredAnalyses = useMemo(() => {
+ if (!analyses) return []
+ if (!searchQuery.trim()) return analyses
- const createMutation = useMutation({
- mutationFn: async () => {
- const newAnalysis: Partial<Analysis> = {
- title: "Untitled Analysis",
- investigation_id: investigationId,
- content: {},
- }
- return analysisService.create(JSON.stringify(newAnalysis))
- },
- onSuccess: async (data) => {
- queryClient.invalidateQueries({ queryKey: queryKeys.analyses.byInvestigation(investigationId || "") })
- toast.success("Analysis created successfully")
- investigationId && navigate({ to: "/dashboard/investigations/$investigationId/$type/$id", params: { investigationId, type: "analysis", id: data.id } })
- },
- onError: (error) => {
- toast.error("Failed to create analysis: " + (error instanceof Error ? error.message : "Unknown error"))
- }
- })
+ const query = searchQuery.toLowerCase().trim()
+ return analyses.filter((analysis: Analysis) => analysis.title.toLowerCase().includes(query))
+ }, [analyses, searchQuery])
- if (error) return (
- <ErrorState
- title="Couldn't load analyses"
- description="Something went wrong while fetching data. Please try again."
- error={error}
- onRetry={() => refetch()}
- />
- )
+ const createMutation = useMutation({
+ mutationFn: async () => {
+ const newAnalysis: Partial<Analysis> = {
+ title: 'Untitled Analysis',
+ investigation_id: investigationId,
+ content: {}
+ }
+ return analysisService.create(JSON.stringify(newAnalysis))
+ },
+ onSuccess: async (data) => {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.analyses.byInvestigation(investigationId || '')
+ })
+ toast.success('Analysis created successfully')
+ investigationId &&
+ navigate({
+ to: '/dashboard/investigations/$investigationId/$type/$id',
+ params: { investigationId, type: 'analysis', id: data.id }
+ })
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to create analysis: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
+
+ if (error)
return (
- <div className="w-full h-full bg-card flex flex-col overflow-hidden">
- <div className="p-2 flex items-center h-11 gap-2 border-b shrink-0">
- <Button
- variant="ghost"
- size="icon"
- className="h-7 w-7"
- onClick={() => createMutation.mutate()}
- disabled={createMutation.isPending}
- title="Create new analysis"
- >
- <PlusIcon className="h-4 w-4" />
- </Button>
- <Input
- type="search"
- className="!border border-border h-7"
- placeholder="Search analyses..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- />
- </div>
+ <ErrorState
+ title="Couldn't load analyses"
+ description="Something went wrong while fetching data. Please try again."
+ error={error}
+ onRetry={() => refetch()}
+ />
+ )
+ return (
+ <div className="w-full h-full bg-card flex flex-col overflow-hidden">
+ <div className="p-2 flex items-center h-11 gap-2 border-b shrink-0">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7"
+ onClick={() => createMutation.mutate()}
+ disabled={createMutation.isPending}
+ title="Create new analysis"
+ >
+ <PlusIcon className="h-4 w-4" />
+ </Button>
+ <Input
+ type="search"
+ className="!border border-border h-7"
+ placeholder="Search analyses..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ </div>
- <div className="flex-1 overflow-auto">
- {isLoading ? (
- <div className="p-2">
- <SkeletonList rowCount={7} />
- </div>
- ) : filteredAnalyses.length > 0 ? (
- <ul>
- {filteredAnalyses.map((analysis: Analysis) => (
- <AnalysisItem
- active={type === "analysis" && id === analysis.id}
- key={analysis.id}
- analysis={analysis}
- />
- ))}
- </ul>
- ) : (
- <div className="p-6 flex flex-col items-center text-center gap-3 text-muted-foreground">
- <FileText className="h-10 w-10 text-yellow-500" />
- <div className="space-y-1">
- <h3 className="text-sm font-semibold text-foreground">
- {searchQuery ? "No matching analyses" : "No analyses yet"}
- </h3>
- <p className="text-xs opacity-70 max-w-xs">
- {searchQuery
- ? "Try adjusting your search query to find what you're looking for."
- : "This investigation doesn't contain any analysis. Analyses let you organize and document your findings."
- }
- </p>
- </div>
- <Button
- size="sm"
- variant="outline"
- onClick={() => createMutation.mutate()}
- disabled={createMutation.isPending}
- >
- <PlusIcon className="w-4 h-4 mr-2" />
- Create your first analysis
- </Button>
- </div>
- )}
+ <div className="flex-1 overflow-auto">
+ {isLoading ? (
+ <div className="p-2">
+ <SkeletonList rowCount={7} />
+ </div>
+ ) : filteredAnalyses.length > 0 ? (
+ <ul>
+ {filteredAnalyses.map((analysis: Analysis) => (
+ <AnalysisItem
+ active={type === 'analysis' && id === analysis.id}
+ key={analysis.id}
+ analysis={analysis}
+ />
+ ))}
+ </ul>
+ ) : (
+ <div className="p-6 flex flex-col items-center text-center gap-3 text-muted-foreground">
+ <FileText className="h-10 w-10 text-yellow-500" />
+ <div className="space-y-1">
+ <h3 className="text-sm font-semibold text-foreground">
+ {searchQuery ? 'No matching analyses' : 'No analyses yet'}
+ </h3>
+ <p className="text-xs opacity-70 max-w-xs">
+ {searchQuery
+ ? "Try adjusting your search query to find what you're looking for."
+ : "This investigation doesn't contain any analysis. Analyses let you organize and document your findings."}
+ </p>
</div>
- </div>
- )
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => createMutation.mutate()}
+ disabled={createMutation.isPending}
+ >
+ <PlusIcon className="w-4 h-4 mr-2" />
+ Create your first analysis
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ )
}
export default AnalysisList
diff --git a/flowsint-app/src/renderer/src/components/analyses/analysis-editor.tsx b/flowsint-app/src/renderer/src/components/analyses/analysis-editor.tsx
index 186455f8..76fe703f 100644
--- a/flowsint-app/src/renderer/src/components/analyses/analysis-editor.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/analysis-editor.tsx
@@ -1,458 +1,504 @@
-import { useState, useEffect, useCallback, useRef } from "react"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { MinimalTiptapEditor } from "@/components/analyses/editor"
-import { analysisService } from "@/api/analysis-service"
-import type { Analysis } from "@/types"
-import { Button } from "@/components/ui/button"
-import { Skeleton } from "@/components/ui/skeleton"
-import { PlusIcon, Trash2, Save, ChevronDown, ChevronsRight, ExternalLink, MoreVertical } from "lucide-react"
-import { toast } from "sonner"
-import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"
-import { useConfirm } from "../use-confirm-dialog"
-import { Editor } from "@tiptap/core"
-import { Link, useParams } from "@tanstack/react-router"
-import { useLayoutStore } from "@/stores/layout-store"
-import default_content from './default_content.json'
+import { useState, useEffect, useCallback, useRef } from 'react'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { MinimalTiptapEditor } from '@/components/analyses/editor'
+import { analysisService } from '@/api/analysis-service'
+import type { Analysis } from '@/types'
+import { Button } from '@/components/ui/button'
+import { Skeleton } from '@/components/ui/skeleton'
import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover"
+ PlusIcon,
+ Trash2,
+ Save,
+ ChevronDown,
+ ChevronsRight,
+ ExternalLink,
+ MoreVertical
+} from 'lucide-react'
+import { toast } from 'sonner'
+import { useKeyboardShortcut } from '@/hooks/use-keyboard-shortcut'
+import { useConfirm } from '../use-confirm-dialog'
+import { Editor } from '@tiptap/core'
+import { Link, useParams } from '@tanstack/react-router'
+import { useLayoutStore } from '@/stores/layout-store'
+import default_content from './default_content.json'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import { queryKeys } from "@/api/query-keys"
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { queryKeys } from '@/api/query-keys'
interface AnalysisEditorProps {
- // Core data
- analysis: Analysis | null
- investigationId: string
+ // Core data
+ analysis: Analysis | null
+ investigationId: string
- // Callbacks
- onAnalysisUpdate?: (analysis: Analysis) => void
- onAnalysisDelete?: (analysisId: string) => void
- onAnalysisCreate?: (investigationId: string) => void
- onAnalysisSelect?: (analysisId: string) => void
+ // Callbacks
+ onAnalysisUpdate?: (analysis: Analysis) => void
+ onAnalysisDelete?: (analysisId: string) => void
+ onAnalysisCreate?: (investigationId: string) => void
+ onAnalysisSelect?: (analysisId: string) => void
- // UI customization
- showHeader?: boolean
- showActions?: boolean
- showToolbar?: boolean
- showAnalysisSelector?: boolean
- showNavigation?: boolean
- className?: string
+ // UI customization
+ showHeader?: boolean
+ showActions?: boolean
+ showToolbar?: boolean
+ showAnalysisSelector?: boolean
+ showNavigation?: boolean
+ className?: string
- // Loading states
- isLoading?: boolean
- isRefetching?: boolean
+ // Loading states
+ isLoading?: boolean
+ isRefetching?: boolean
- // Analysis list for selector
- analyses?: Analysis[]
- currentAnalysisId?: string | null
+ // Analysis list for selector
+ analyses?: Analysis[]
+ currentAnalysisId?: string | null
}
export const AnalysisEditor = ({
- analysis,
- investigationId,
- onAnalysisUpdate,
- onAnalysisDelete,
- onAnalysisCreate,
- onAnalysisSelect,
- showHeader = true,
- showActions = true,
- showAnalysisSelector = false,
- showNavigation = false,
- className = "",
- isLoading = false,
- analyses = [],
- currentAnalysisId,
- showToolbar = false
+ analysis,
+ investigationId,
+ onAnalysisUpdate,
+ onAnalysisDelete,
+ onAnalysisCreate,
+ onAnalysisSelect,
+ showHeader = true,
+ showActions = true,
+ showAnalysisSelector = false,
+ showNavigation = false,
+ className = '',
+ isLoading = false,
+ analyses = [],
+ currentAnalysisId,
+ showToolbar = false
}: AnalysisEditorProps) => {
- const { confirm } = useConfirm()
- const toggleAnalysis = useLayoutStore(s => s.toggleAnalysis)
- const { investigationId: routeInvestigationId, type } = useParams({ strict: false }) as { investigationId: string, type: string }
- const queryClient = useQueryClient()
+ const { confirm } = useConfirm()
+ const toggleAnalysis = useLayoutStore((s) => s.toggleAnalysis)
+ const { investigationId: routeInvestigationId, type } = useParams({ strict: false }) as {
+ investigationId: string
+ type: string
+ }
+ const queryClient = useQueryClient()
- // State/refs for editor
- const editorContentRef = useRef<any>("")
- const [titleValue, setTitleValue] = useState("")
- const [editor, setEditor] = useState<Editor | undefined>(undefined)
- const [isEditingTitle, setIsEditingTitle] = useState(false)
- const [saveStatus, setSaveStatus] = useState<"saved" | "saving" | "unsaved">("saved")
- // Debounced save function
- const debouncedSave = useCallback(
- debounce(() => {
- if (analysis) {
- setSaveStatus("saving")
- saveMutation.mutate({})
- }
- }, 1000), // 1 second delay
- [analysis?.id]
- )
+ // State/refs for editor
+ const editorContentRef = useRef<any>('')
+ const [titleValue, setTitleValue] = useState('')
+ const [editor, setEditor] = useState<Editor | undefined>(undefined)
+ const [isEditingTitle, setIsEditingTitle] = useState(false)
+ const [saveStatus, setSaveStatus] = useState<'saved' | 'saving' | 'unsaved'>('saved')
+ // Debounced save function
+ const debouncedSave = useCallback(
+ debounce(() => {
+ if (analysis) {
+ setSaveStatus('saving')
+ saveMutation.mutate({})
+ }
+ }, 1000), // 1 second delay
+ [analysis?.id]
+ )
- // Handle editor content changes
- const handleEditorChange = useCallback((value: any) => {
- editorContentRef.current = value
- if (analysis) {
- setSaveStatus("unsaved")
- debouncedSave()
- }
- }, [analysis?.id, debouncedSave])
+ // Handle editor content changes
+ const handleEditorChange = useCallback(
+ (value: any) => {
+ editorContentRef.current = value
+ if (analysis) {
+ setSaveStatus('unsaved')
+ debouncedSave()
+ }
+ },
+ [analysis?.id, debouncedSave]
+ )
- // Debounce function
- function debounce(func: Function, wait: number) {
- let timeout: NodeJS.Timeout
- return function executedFunction(...args: any[]) {
- const later = () => {
- clearTimeout(timeout)
- func(...args)
- }
- clearTimeout(timeout)
- timeout = setTimeout(later, wait)
- }
+ // Debounce function
+ function debounce(func: Function, wait: number) {
+ let timeout: NodeJS.Timeout
+ return function executedFunction(...args: any[]) {
+ const later = () => {
+ clearTimeout(timeout)
+ func(...args)
+ }
+ clearTimeout(timeout)
+ timeout = setTimeout(later, wait)
}
+ }
- // Mutations
- const createMutation = useMutation({
- mutationFn: async () => {
- const newAnalysis: Partial<Analysis> = {
- title: "Untitled Analysis",
- investigation_id: investigationId,
- content: default_content,
- }
- const res = await analysisService.create(JSON.stringify(newAnalysis))
- return res
- },
- onSuccess: async () => {
- queryClient.invalidateQueries({ queryKey: queryKeys.analyses.byInvestigation(investigationId || "") })
- onAnalysisCreate?.(investigationId)
- toast.success("New analysis created")
- },
- onError: (error) => {
- toast.error("Failed to create analysis: " + (error instanceof Error ? error.message : "Unknown error"))
- }
- })
-
- const saveMutation = useMutation({
- mutationFn: async (updated: Partial<Analysis>) => {
- if (!analysis) return
- return analysisService.update(analysis.id, JSON.stringify({
- ...analysis,
- ...updated,
- content: editorContentRef.current
- }))
- },
- onSuccess: async (data) => {
- // Use more specific query invalidation with query key factory
- queryClient.setQueryData(queryKeys.analyses.byInvestigation(investigationId || ""), (oldData: Analysis[] | undefined) => {
- if (!oldData) return oldData
- return oldData.map(item => item.id === data.id ? data : item)
- })
- onAnalysisUpdate?.(data)
- setSaveStatus("saved")
- },
- onError: (error) => {
- toast.error("Failed to save analysis: " + (error instanceof Error ? error.message : "Unknown error"))
- setSaveStatus("unsaved")
- }
- })
-
- const deleteMutation = useMutation({
- mutationFn: async (id: string) => {
- return analysisService.delete(id)
- },
- onSuccess: async () => {
- queryClient.invalidateQueries({ queryKey: queryKeys.analyses.byInvestigation(investigationId || "") })
- onAnalysisDelete?.(investigationId)
- toast.success("Analysis deleted")
- },
- onError: (error) => {
- toast.error("Failed to delete analysis: " + (error instanceof Error ? error.message : "Unknown error"))
- }
- })
-
- const updateTitleMutation = useMutation({
- mutationFn: async (newTitle: string) => {
- if (!analysis) return
- return analysisService.update(analysis.id, JSON.stringify({
- ...analysis,
- title: newTitle
- }))
- },
- onSuccess: async (data) => {
- // Use more specific query invalidation
- queryClient.setQueryData(["analyses", investigationId], (oldData: Analysis[] | undefined) => {
- if (!oldData) return oldData
- return oldData.map(item => item.id === data.id ? data : item)
- })
- onAnalysisUpdate?.(data)
- toast.success("Title updated")
- },
- onError: (error) => {
- toast.error("Failed to update title: " + (error instanceof Error ? error.message : "Unknown error"))
- }
- })
-
- // Handle title update
- const handleTitleUpdate = (newTitle: string) => {
- if (!analysis || newTitle === analysis.title) return
- setTitleValue(newTitle)
- updateTitleMutation.mutate(newTitle)
- setIsEditingTitle(false)
+ // Mutations
+ const createMutation = useMutation({
+ mutationFn: async () => {
+ const newAnalysis: Partial<Analysis> = {
+ title: 'Untitled Analysis',
+ investigation_id: investigationId,
+ content: default_content
+ }
+ const res = await analysisService.create(JSON.stringify(newAnalysis))
+ return res
+ },
+ onSuccess: async () => {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.analyses.byInvestigation(investigationId || '')
+ })
+ onAnalysisCreate?.(investigationId)
+ toast.success('New analysis created')
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to create analysis: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
}
+ })
- const deleteAnalysis = async () => {
- if (!analysis?.id) {
- toast.error("No analysis selected")
- return
- }
- if (!await confirm({ title: "Delete Analysis", message: "Are you sure you want to delete this analysis?" })) {
- return
+ const saveMutation = useMutation({
+ mutationFn: async (updated: Partial<Analysis>) => {
+ if (!analysis) return
+ return analysisService.update(
+ analysis.id,
+ JSON.stringify({
+ ...analysis,
+ ...updated,
+ content: editorContentRef.current
+ })
+ )
+ },
+ onSuccess: async (data) => {
+ // Use more specific query invalidation with query key factory
+ queryClient.setQueryData(
+ queryKeys.analyses.byInvestigation(investigationId || ''),
+ (oldData: Analysis[] | undefined) => {
+ if (!oldData) return oldData
+ return oldData.map((item) => (item.id === data.id ? data : item))
}
- deleteMutation.mutate(analysis.id)
+ )
+ onAnalysisUpdate?.(data)
+ setSaveStatus('saved')
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to save analysis: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ setSaveStatus('unsaved')
}
+ })
- const handleManualSave = () => {
- if (analysis) {
- setSaveStatus("saving")
- saveMutation.mutate({})
- }
+ const deleteMutation = useMutation({
+ mutationFn: async (id: string) => {
+ return analysisService.delete(id)
+ },
+ onSuccess: async () => {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.analyses.byInvestigation(investigationId || '')
+ })
+ onAnalysisDelete?.(investigationId)
+ toast.success('Analysis deleted')
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to delete analysis: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
}
+ })
- // Update non-editor UI when analysis changes (avoid resetting content on same doc)
- useEffect(() => {
- if (analysis) {
- setTitleValue(analysis.title || "")
- setSaveStatus("saved")
- } else {
- setTitleValue("")
- setSaveStatus("saved")
- if (editor) {
- editor.commands.setContent("")
- }
- }
- }, [analysis?.id, analysis?.title, editor])
-
-
+ const updateTitleMutation = useMutation({
+ mutationFn: async (newTitle: string) => {
+ if (!analysis) return
+ return analysisService.update(
+ analysis.id,
+ JSON.stringify({
+ ...analysis,
+ title: newTitle
+ })
+ )
+ },
+ onSuccess: async (data) => {
+ // Use more specific query invalidation
+ queryClient.setQueryData(['analyses', investigationId], (oldData: Analysis[] | undefined) => {
+ if (!oldData) return oldData
+ return oldData.map((item) => (item.id === data.id ? data : item))
+ })
+ onAnalysisUpdate?.(data)
+ toast.success('Title updated')
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to update title: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
- useKeyboardShortcut({
- key: "s",
- ctrlOrCmd: true,
- callback: () => {
- handleManualSave()
- },
- })
+ // Handle title update
+ const handleTitleUpdate = (newTitle: string) => {
+ if (!analysis || newTitle === analysis.title) return
+ setTitleValue(newTitle)
+ updateTitleMutation.mutate(newTitle)
+ setIsEditingTitle(false)
+ }
- if (isLoading) {
- return <Skeleton className="h-full w-full" />
+ const deleteAnalysis = async () => {
+ if (!analysis?.id) {
+ toast.error('No analysis selected')
+ return
+ }
+ if (
+ !(await confirm({
+ title: 'Delete Analysis',
+ message: 'Are you sure you want to delete this analysis?'
+ }))
+ ) {
+ return
}
+ deleteMutation.mutate(analysis.id)
+ }
- return (
- <div className={`flex flex-col h-full w-full overflow-y-auto bg-card ${className}`}>
- {/* Header */}
- {showHeader && (
- <div className="bg-card/70 sticky top-0 z-10 backdrop-blur-sm h-11 w-full flex items-center justify-between">
- <div className="flex items-center justify-between p-3 w-full">
- {/* Left section with navigation and title */}
- <div className="flex items-center gap-3 flex-1 min-w-0">
- {showNavigation && type !== "analysis" && (
- <Button className="h-8 w-8" variant="ghost" onClick={toggleAnalysis}>
- <ChevronsRight />
- </Button>
- )}
+ const handleManualSave = () => {
+ if (analysis) {
+ setSaveStatus('saving')
+ saveMutation.mutate({})
+ }
+ }
- {/* Analysis Selector */}
- {showAnalysisSelector && analyses && analyses.length > 0 && (
- <Popover>
- <PopoverTrigger asChild>
- <div>
- <Button variant="ghost" size="icon" className="h-8 w-8">
- <ChevronDown className="h-4 w-4" />
- </Button>
- </div>
- </PopoverTrigger>
- <PopoverContent className="w-[200px] max-h-[300px] overflow-y-auto truncate text-ellipsis p-0" align="start">
- <div className="flex flex-col truncate text-ellipsis">
- {analyses.map((analysisItem) => (
- <Button
- key={analysisItem.id}
- variant="ghost"
- className="justify-start px-2 py-1.5 h-auto truncate text-ellipsis"
- onClick={() => onAnalysisSelect?.(analysisItem.id)}
- >
- <div className="flex flex-col items-start truncate text-ellipsis">
- <span className="font-medium truncate text-ellipsis">{analysisItem.title || "Untitled"}</span>
- <span className="text-xs text-muted-foreground">
- {analysisItem.id === currentAnalysisId ? "Current" : "Switch to this analysis"}
- </span>
- </div>
- </Button>
- ))}
- </div>
- </PopoverContent>
- </Popover>
- )}
+ // Update non-editor UI when analysis changes (avoid resetting content on same doc)
+ useEffect(() => {
+ if (analysis) {
+ setTitleValue(analysis.title || '')
+ setSaveStatus('saved')
+ } else {
+ setTitleValue('')
+ setSaveStatus('saved')
+ if (editor) {
+ editor.commands.setContent('')
+ }
+ }
+ }, [analysis?.id, analysis?.title, editor])
- {/* Title section */}
- <div className="flex items-center gap-2 flex-1 min-w-0">
- {isEditingTitle ? (
- <input
- className="text-md font-medium bg-transparent outline-none border-none p-0 m-0 w-full"
- value={titleValue}
- onChange={e => setTitleValue(e.target.value)}
- onBlur={() => {
- handleTitleUpdate(titleValue)
- setIsEditingTitle(false)
- }}
- onKeyDown={e => {
- if (e.key === 'Enter') {
- handleTitleUpdate(titleValue)
- setIsEditingTitle(false)
- } else if (e.key === 'Escape') {
- setIsEditingTitle(false)
- setTitleValue(analysis?.title || "")
- }
- }}
- autoFocus
- />
- ) : (
- <span
- className="text-md font-medium cursor-pointer hover:text-primary truncate min-w-0 flex-1"
- onClick={() => setIsEditingTitle(true)}
- >
- {titleValue || "Untitled Analysis"}
- </span>
- )}
- </div>
- </div>
+ useKeyboardShortcut({
+ key: 's',
+ ctrlOrCmd: true,
+ callback: () => {
+ handleManualSave()
+ }
+ })
- {/* Action buttons */}
- {showActions && (
- <div className="flex items-center gap-1">
- <Button
- size="icon"
- variant="ghost"
- onClick={handleManualSave}
- disabled={!analysis || saveMutation.isPending}
- title={saveStatus === "saved" ? "Saved" : saveStatus === "saving" ? "Saving..." : "Save"}
- className="h-8 w-8 relative"
- >
- <Save className="w-4 h-4" strokeWidth={1.5} />
- {saveStatus === "saved" && (
- <div className="absolute top-1 right-1 w-2 h-2 bg-green-500 rounded-full" />
- )}
- {saveStatus === "saving" && (
- <div className="absolute top-1 right-1 w-2 h-2 bg-yellow-500 rounded-full animate-pulse" />
- )}
- {saveStatus === "unsaved" && (
- <div className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full" />
- )}
- </Button>
+ if (isLoading) {
+ return <Skeleton className="h-full w-full" />
+ }
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <div>
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8"
- >
- <MoreVertical className="w-4 h-4" strokeWidth={1.5} />
- </Button>
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- {analysis && type !== "analysis" && (
- <DropdownMenuItem asChild>
- <Link to="/dashboard/investigations/$investigationId/$type/$id" params={{
- investigationId: routeInvestigationId || investigationId,
- type: "analysis",
- id: analysis.id
- }}>
- <ExternalLink className="w-4 h-4 mr-2" strokeWidth={1.5} />
- Open in Full Page
- </Link>
- </DropdownMenuItem>
- )}
- {type !== "analysis" && (
- <DropdownMenuItem
- onClick={() => createMutation.mutate()}
- disabled={createMutation.isPending}
- >
- <PlusIcon className="w-4 h-4 mr-2" strokeWidth={1.5} />
- New Analysis
- </DropdownMenuItem>
- )}
- {analysis && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={deleteAnalysis}
- disabled={deleteMutation.isPending}
- variant="destructive"
- >
- <Trash2 className="w-4 h-4 mr-2" strokeWidth={1.5} />
- Delete Analysis
- </DropdownMenuItem>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- )}
- </div>
- </div>
- )}
+ return (
+ <div className={`flex flex-col h-full w-full overflow-y-auto bg-card ${className}`}>
+ {/* Header */}
+ {showHeader && (
+ <div className="bg-card/70 sticky top-0 z-10 backdrop-blur-sm h-11 w-full flex items-center justify-between">
+ <div className="flex items-center justify-between p-3 w-full">
+ {/* Left section with navigation and title */}
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ {showNavigation && type !== 'analysis' && (
+ <Button className="h-8 w-8" variant="ghost" onClick={toggleAnalysis}>
+ <ChevronsRight />
+ </Button>
+ )}
- {/* Editor */}
- <div className="flex-1 min-h-0 flex flex-col">
- {analysis ? (
- <div className="h-full w-full">
- <MinimalTiptapEditor
- key={analysis.id}
- immediatelyRender={true}
- value={(function getInitialContent() {
- const content = analysis.content as any
- if (typeof content === 'string') {
- try {
- return JSON.parse(content)
- } catch {
- return content || ""
- }
- }
- return content || ""
- })()}
- onChange={handleEditorChange}
- className="w-full h-full"
- editorContentClassName="p-5 min-h-[300px]"
- output="json"
- placeholder="Enter your analysis..."
- autofocus={true}
- showToolbar={showToolbar}
- editable={true}
- editorClassName="focus:outline-hidden"
- onEditorReady={setEditor}
- />
+ {/* Analysis Selector */}
+ {showAnalysisSelector && analyses && analyses.length > 0 && (
+ <Popover>
+ <PopoverTrigger asChild>
+ <div>
+ <Button variant="ghost" size="icon" className="h-8 w-8">
+ <ChevronDown className="h-4 w-4" />
+ </Button>
</div>
- ) : (
- <div className="flex flex-col items-center justify-center h-full text-muted-foreground space-y-3">
- <div>No analysis selected.</div>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-[200px] max-h-[300px] overflow-y-auto truncate text-ellipsis p-0"
+ align="start"
+ >
+ <div className="flex flex-col truncate text-ellipsis">
+ {analyses.map((analysisItem) => (
<Button
- className="shadow-none"
- variant="outline"
- onClick={() => createMutation.mutate()}
- disabled={createMutation.isPending}
+ key={analysisItem.id}
+ variant="ghost"
+ className="justify-start px-2 py-1.5 h-auto truncate text-ellipsis"
+ onClick={() => onAnalysisSelect?.(analysisItem.id)}
>
- <PlusIcon className="w-4 h-4 mr-2" strokeWidth={1.5} />
- Create your first analysis
+ <div className="flex flex-col items-start truncate text-ellipsis">
+ <span className="font-medium truncate text-ellipsis">
+ {analysisItem.title || 'Untitled'}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {analysisItem.id === currentAnalysisId
+ ? 'Current'
+ : 'Switch to this analysis'}
+ </span>
+ </div>
</Button>
+ ))}
</div>
+ </PopoverContent>
+ </Popover>
+ )}
+
+ {/* Title section */}
+ <div className="flex items-center gap-2 flex-1 min-w-0">
+ {isEditingTitle ? (
+ <input
+ className="text-md font-medium bg-transparent outline-none border-none p-0 m-0 w-full"
+ value={titleValue}
+ onChange={(e) => setTitleValue(e.target.value)}
+ onBlur={() => {
+ handleTitleUpdate(titleValue)
+ setIsEditingTitle(false)
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ handleTitleUpdate(titleValue)
+ setIsEditingTitle(false)
+ } else if (e.key === 'Escape') {
+ setIsEditingTitle(false)
+ setTitleValue(analysis?.title || '')
+ }
+ }}
+ autoFocus
+ />
+ ) : (
+ <span
+ className="text-md font-medium cursor-pointer hover:text-primary truncate min-w-0 flex-1"
+ onClick={() => setIsEditingTitle(true)}
+ >
+ {titleValue || 'Untitled Analysis'}
+ </span>
)}
+ </div>
</div>
+
+ {/* Action buttons */}
+ {showActions && (
+ <div className="flex items-center gap-1">
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={handleManualSave}
+ disabled={!analysis || saveMutation.isPending}
+ title={
+ saveStatus === 'saved'
+ ? 'Saved'
+ : saveStatus === 'saving'
+ ? 'Saving...'
+ : 'Save'
+ }
+ className="h-8 w-8 relative"
+ >
+ <Save className="w-4 h-4" strokeWidth={1.5} />
+ {saveStatus === 'saved' && (
+ <div className="absolute top-1 right-1 w-2 h-2 bg-green-500 rounded-full" />
+ )}
+ {saveStatus === 'saving' && (
+ <div className="absolute top-1 right-1 w-2 h-2 bg-yellow-500 rounded-full animate-pulse" />
+ )}
+ {saveStatus === 'unsaved' && (
+ <div className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full" />
+ )}
+ </Button>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <div>
+ <Button size="icon" variant="ghost" className="h-8 w-8">
+ <MoreVertical className="w-4 h-4" strokeWidth={1.5} />
+ </Button>
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {analysis && type !== 'analysis' && (
+ <DropdownMenuItem asChild>
+ <Link
+ to="/dashboard/investigations/$investigationId/$type/$id"
+ params={{
+ investigationId: routeInvestigationId || investigationId,
+ type: 'analysis',
+ id: analysis.id
+ }}
+ >
+ <ExternalLink className="w-4 h-4 mr-2" strokeWidth={1.5} />
+ Open in Full Page
+ </Link>
+ </DropdownMenuItem>
+ )}
+ {type !== 'analysis' && (
+ <DropdownMenuItem
+ onClick={() => createMutation.mutate()}
+ disabled={createMutation.isPending}
+ >
+ <PlusIcon className="w-4 h-4 mr-2" strokeWidth={1.5} />
+ New Analysis
+ </DropdownMenuItem>
+ )}
+ {analysis && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={deleteAnalysis}
+ disabled={deleteMutation.isPending}
+ variant="destructive"
+ >
+ <Trash2 className="w-4 h-4 mr-2" strokeWidth={1.5} />
+ Delete Analysis
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
+ </div>
</div>
- )
-}
+ )}
+
+ {/* Editor */}
+ <div className="flex-1 min-h-0 flex flex-col">
+ {analysis ? (
+ <div className="h-full w-full">
+ <MinimalTiptapEditor
+ key={analysis.id}
+ immediatelyRender={true}
+ value={(function getInitialContent() {
+ const content = analysis.content as any
+ if (typeof content === 'string') {
+ try {
+ return JSON.parse(content)
+ } catch {
+ return content || ''
+ }
+ }
+ return content || ''
+ })()}
+ onChange={handleEditorChange}
+ className="w-full h-full"
+ editorContentClassName="p-5 min-h-[300px]"
+ output="json"
+ placeholder="Enter your analysis..."
+ autofocus={true}
+ showToolbar={showToolbar}
+ editable={true}
+ editorClassName="focus:outline-hidden"
+ onEditorReady={setEditor}
+ />
+ </div>
+ ) : (
+ <div className="flex flex-col items-center justify-center h-full text-muted-foreground space-y-3">
+ <div>No analysis selected.</div>
+ <Button
+ className="shadow-none"
+ variant="outline"
+ onClick={() => createMutation.mutate()}
+ disabled={createMutation.isPending}
+ >
+ <PlusIcon className="w-4 h-4 mr-2" strokeWidth={1.5} />
+ Create your first analysis
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/analyses/analysis-page.tsx b/flowsint-app/src/renderer/src/components/analyses/analysis-page.tsx
index db341807..aa7e1fc1 100644
--- a/flowsint-app/src/renderer/src/components/analyses/analysis-page.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/analysis-page.tsx
@@ -1,44 +1,58 @@
-import { useParams } from "@tanstack/react-router"
-import type { Analysis } from "@/types"
-import { AnalysisEditor } from "./analysis-editor"
-import AnalysisSkeleton from "./analysis-skeleton"
+import { useParams } from '@tanstack/react-router'
+import type { Analysis } from '@/types'
+import { AnalysisEditor } from './analysis-editor'
+import AnalysisSkeleton from './analysis-skeleton'
-export const AnalysisPage = ({ analysis, isLoading, isError, refetch }: { analysis: Analysis, isLoading: boolean, isError: boolean, refetch: () => void }) => {
- const { investigationId } = useParams({ strict: false }) as { investigationId: string, id: string }
+export const AnalysisPage = ({
+ analysis,
+ isLoading,
+ isError,
+ refetch
+}: {
+ analysis: Analysis
+ isLoading: boolean
+ isError: boolean
+ refetch: () => void
+}) => {
+ const { investigationId } = useParams({ strict: false }) as {
+ investigationId: string
+ id: string
+ }
- if (isLoading) {
- return (
- <div className="w-full flex gap-3 max-w-4xl mx-auto flex-col items-start justify-start h-full overflow-hidden p-20">
- <AnalysisSkeleton />
- </div>)
- }
+ if (isLoading) {
+ return (
+ <div className="w-full flex gap-3 max-w-4xl mx-auto flex-col items-start justify-start h-full overflow-hidden p-20">
+ <AnalysisSkeleton />
+ </div>
+ )
+ }
- if (isError) {
- return <div className="text-sm text-destructive">Error loading analysis.</div>
- }
+ if (isError) {
+ return <div className="text-sm text-destructive">Error loading analysis.</div>
+ }
- const handleAnalysisUpdate = () => {
- refetch()
- }
+ const handleAnalysisUpdate = () => {
+ refetch()
+ }
- const handleAnalysisDelete = () => {
- // Navigate back to investigation page or to another analysis
- window.history.back()
- }
+ const handleAnalysisDelete = () => {
+ // Navigate back to investigation page or to another analysis
+ window.history.back()
+ }
- return (
- <div className="flex flex-col h-full w-full">
- {/* Analysis Editor */}
- <AnalysisEditor
- showToolbar={true}
- analysis={analysis || null}
- investigationId={investigationId}
- onAnalysisUpdate={handleAnalysisUpdate}
- onAnalysisDelete={handleAnalysisDelete}
- showHeader={true}
- showNavigation={true}
- isLoading={isLoading}
- />
- </div>
- )
-}
+ return (
+ <div className="flex flex-col h-full w-full">
+ {/* Analysis Editor */}
+ <AnalysisEditor
+ showToolbar={true}
+ analysis={analysis || null}
+ investigationId={investigationId}
+ onAnalysisUpdate={handleAnalysisUpdate}
+ onAnalysisDelete={handleAnalysisDelete}
+ showHeader={true}
+ showNavigation={true}
+ isLoading={isLoading}
+ />
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/analyses/analysis-skeleton.tsx b/flowsint-app/src/renderer/src/components/analyses/analysis-skeleton.tsx
index 9585916f..434a32c3 100644
--- a/flowsint-app/src/renderer/src/components/analyses/analysis-skeleton.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/analysis-skeleton.tsx
@@ -2,7 +2,7 @@ import { Skeleton } from '../ui/skeleton'
const AnalysisSkeleton = () => {
return (
- <div className='flex flex-col gap-3 p-6'>
+ <div className="flex flex-col gap-3 p-6">
<Skeleton className="h-10 w-1/2" />
<Skeleton className="h-6 w-full" />
<Skeleton className="h-4 w-full" />
@@ -14,9 +14,8 @@ const AnalysisSkeleton = () => {
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-1/2" />
-
</div>
)
}
-export default AnalysisSkeleton
\ No newline at end of file
+export default AnalysisSkeleton
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/bubble-menu/link-bubble-menu.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/bubble-menu/link-bubble-menu.tsx
index 0b063502..cd707987 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/bubble-menu/link-bubble-menu.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/bubble-menu/link-bubble-menu.tsx
@@ -1,9 +1,9 @@
-import * as React from "react"
-import type { ShouldShowProps } from "../../types"
-import type { Editor } from "@tiptap/react"
-import { BubbleMenu } from "@tiptap/react"
-import { LinkEditBlock } from "../link/link-edit-block"
-import { LinkPopoverBlock } from "../link/link-popover-block"
+import * as React from 'react'
+import type { ShouldShowProps } from '../../types'
+import type { Editor } from '@tiptap/react'
+import { BubbleMenu } from '@tiptap/react'
+import { LinkEditBlock } from '../link/link-edit-block'
+import { LinkPopoverBlock } from '../link/link-popover-block'
interface LinkBubbleMenuProps {
editor: Editor
@@ -17,15 +17,15 @@ interface LinkAttributes {
export const LinkBubbleMenu: React.FC<LinkBubbleMenuProps> = ({ editor }) => {
const [showEdit, setShowEdit] = React.useState(false)
const [linkAttrs, setLinkAttrs] = React.useState<LinkAttributes>({
- href: "",
- target: "",
+ href: '',
+ target: ''
})
- const [selectedText, setSelectedText] = React.useState("")
+ const [selectedText, setSelectedText] = React.useState('')
const updateLinkState = React.useCallback(() => {
const { from, to } = editor.state.selection
- const { href, target } = editor.getAttributes("link")
- const text = editor.state.doc.textBetween(from, to, " ")
+ const { href, target } = editor.getAttributes('link')
+ const text = editor.state.doc.textBetween(from, to, ' ')
setLinkAttrs({ href, target })
setSelectedText(text)
@@ -36,9 +36,9 @@ export const LinkBubbleMenu: React.FC<LinkBubbleMenuProps> = ({ editor }) => {
if (from === to) {
return false
}
- const { href } = editor.getAttributes("link")
+ const { href } = editor.getAttributes('link')
- if (!editor.isActive("link") || !editor.isEditable) {
+ if (!editor.isActive('link') || !editor.isEditable) {
return false
}
@@ -60,21 +60,21 @@ export const LinkBubbleMenu: React.FC<LinkBubbleMenuProps> = ({ editor }) => {
editor
.chain()
.focus()
- .extendMarkRange("link")
+ .extendMarkRange('link')
.insertContent({
- type: "text",
+ type: 'text',
text: text || url,
marks: [
{
- type: "link",
+ type: 'link',
attrs: {
href: url,
- target: openInNewTab ? "_blank" : "",
- },
- },
- ],
+ target: openInNewTab ? '_blank' : ''
+ }
+ }
+ ]
})
- .setLink({ href: url, target: openInNewTab ? "_blank" : "" })
+ .setLink({ href: url, target: openInNewTab ? '_blank' : '' })
.run()
setShowEdit(false)
updateLinkState()
@@ -83,7 +83,7 @@ export const LinkBubbleMenu: React.FC<LinkBubbleMenuProps> = ({ editor }) => {
)
const onUnsetLink = React.useCallback(() => {
- editor.chain().focus().extendMarkRange("link").unsetLink().run()
+ editor.chain().focus().extendMarkRange('link').unsetLink().run()
setShowEdit(false)
updateLinkState()
}, [editor, updateLinkState])
@@ -93,24 +93,20 @@ export const LinkBubbleMenu: React.FC<LinkBubbleMenuProps> = ({ editor }) => {
editor={editor}
shouldShow={shouldShow}
tippyOptions={{
- placement: "bottom-start",
- onHidden: () => setShowEdit(false),
+ placement: 'bottom-start',
+ onHidden: () => setShowEdit(false)
}}
>
{showEdit ? (
<LinkEditBlock
defaultUrl={linkAttrs.href}
defaultText={selectedText}
- defaultIsNewTab={linkAttrs.target === "_blank"}
+ defaultIsNewTab={linkAttrs.target === '_blank'}
onSave={onSetLink}
className="w-full min-w-80 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none"
/>
) : (
- <LinkPopoverBlock
- onClear={onUnsetLink}
- url={linkAttrs.href}
- onEdit={handleEdit}
- />
+ <LinkPopoverBlock onClear={onUnsetLink} url={linkAttrs.href} onEdit={handleEdit} />
)}
</BubbleMenu>
)
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/image/image-edit-block.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/image/image-edit-block.tsx
index 4ebe152c..371f4c55 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/image/image-edit-block.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/image/image-edit-block.tsx
@@ -1,20 +1,17 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import { Button } from "@/components/ui/button"
-import { Label } from "@/components/ui/label"
-import { Input } from "@/components/ui/input"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import { Button } from '@/components/ui/button'
+import { Label } from '@/components/ui/label'
+import { Input } from '@/components/ui/input'
interface ImageEditBlockProps {
editor: Editor
close: () => void
}
-export const ImageEditBlock: React.FC<ImageEditBlockProps> = ({
- editor,
- close,
-}) => {
+export const ImageEditBlock: React.FC<ImageEditBlockProps> = ({ editor, close }) => {
const fileInputRef = React.useRef<HTMLInputElement>(null)
- const [link, setLink] = React.useState("")
+ const [link, setLink] = React.useState('')
const handleClick = React.useCallback(() => {
fileInputRef.current?.click()
@@ -67,9 +64,7 @@ export const ImageEditBlock: React.FC<ImageEditBlockProps> = ({
placeholder="https://example.com"
value={link}
className="grow"
- onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
- setLink(e.target.value)
- }
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setLink(e.target.value)}
/>
<Button type="submit" className="ml-2">
Submit
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/image/image-edit-dialog.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/image/image-edit-dialog.tsx
index 6ae5eadb..6f7ca368 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/image/image-edit-dialog.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/image/image-edit-dialog.tsx
@@ -1,18 +1,18 @@
-import type { Editor } from "@tiptap/react"
-import type { VariantProps } from "class-variance-authority"
-import type { toggleVariants } from "@/components/ui/toggle"
-import { useState } from "react"
-import { ImageIcon } from "lucide-react"
-import { ToolbarButton } from "../toolbar-button"
+import type { Editor } from '@tiptap/react'
+import type { VariantProps } from 'class-variance-authority'
+import type { toggleVariants } from '@/components/ui/toggle'
+import { useState } from 'react'
+import { ImageIcon } from 'lucide-react'
+import { ToolbarButton } from '../toolbar-button'
import {
Dialog,
DialogContent,
DialogHeader,
DialogDescription,
DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog"
-import { ImageEditBlock } from "./image-edit-block"
+ DialogTrigger
+} from '@/components/ui/dialog'
+import { ImageEditBlock } from './image-edit-block'
interface ImageEditDialogProps extends VariantProps<typeof toggleVariants> {
editor: Editor
@@ -25,7 +25,7 @@ const ImageEditDialog = ({ editor, size, variant }: ImageEditDialogProps) => {
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<ToolbarButton
- isActive={editor.isActive("image")}
+ isActive={editor.isActive('image')}
tooltip="Image"
aria-label="Image"
size={size}
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-edit-block.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-edit-block.tsx
index 47f74e29..fc4d717d 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-edit-block.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-edit-block.tsx
@@ -1,9 +1,9 @@
-import * as React from "react"
-import { Button } from "@/components/ui/button"
-import { Label } from "@/components/ui/label"
-import { Switch } from "@/components/ui/switch"
-import { Input } from "@/components/ui/input"
-import { cn } from "@/lib/utils"
+import * as React from 'react'
+import { Button } from '@/components/ui/button'
+import { Label } from '@/components/ui/label'
+import { Switch } from '@/components/ui/switch'
+import { Input } from '@/components/ui/input'
+import { cn } from '@/lib/utils'
export interface LinkEditorProps extends React.HTMLAttributes<HTMLDivElement> {
defaultUrl?: string
@@ -15,22 +15,22 @@ export interface LinkEditorProps extends React.HTMLAttributes<HTMLDivElement> {
export const LinkEditBlock = React.forwardRef<HTMLDivElement, LinkEditorProps>(
({ onSave, defaultIsNewTab, defaultUrl, defaultText, className }, ref) => {
const formRef = React.useRef<HTMLDivElement>(null)
- const [url, setUrl] = React.useState(defaultUrl || "")
- const [text, setText] = React.useState(defaultText || "")
+ const [url, setUrl] = React.useState(defaultUrl || '')
+ const [text, setText] = React.useState(defaultText || '')
const [isNewTab, setIsNewTab] = React.useState(defaultIsNewTab || false)
const handleSave = React.useCallback(
(e: React.FormEvent) => {
e.preventDefault()
if (formRef.current) {
- const isValid = Array.from(
- formRef.current.querySelectorAll("input")
- ).every((input) => input.checkValidity())
+ const isValid = Array.from(formRef.current.querySelectorAll('input')).every((input) =>
+ input.checkValidity()
+ )
if (isValid) {
onSave(url, text, isNewTab)
} else {
- formRef.current.querySelectorAll("input").forEach((input) => {
+ formRef.current.querySelectorAll('input').forEach((input) => {
if (!input.checkValidity()) {
input.reportValidity()
}
@@ -45,7 +45,7 @@ export const LinkEditBlock = React.forwardRef<HTMLDivElement, LinkEditorProps>(
return (
<div ref={formRef}>
- <div className={cn("space-y-4", className)}>
+ <div className={cn('space-y-4', className)}>
<div className="space-y-1">
<Label>URL</Label>
<Input
@@ -83,6 +83,6 @@ export const LinkEditBlock = React.forwardRef<HTMLDivElement, LinkEditorProps>(
}
)
-LinkEditBlock.displayName = "LinkEditBlock"
+LinkEditBlock.displayName = 'LinkEditBlock'
export default LinkEditBlock
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-edit-popover.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-edit-popover.tsx
index 5ec11eb3..424aa0ba 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-edit-popover.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-edit-popover.tsx
@@ -1,15 +1,11 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { VariantProps } from "class-variance-authority"
-import type { toggleVariants } from "@/components/ui/toggle"
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover"
-import { Link2 } from "lucide-react"
-import { ToolbarButton } from "../toolbar-button"
-import { LinkEditBlock } from "./link-edit-block"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { VariantProps } from 'class-variance-authority'
+import type { toggleVariants } from '@/components/ui/toggle'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import { Link2 } from 'lucide-react'
+import { ToolbarButton } from '../toolbar-button'
+import { LinkEditBlock } from './link-edit-block'
interface LinkEditPopoverProps extends VariantProps<typeof toggleVariants> {
editor: Editor
@@ -19,26 +15,26 @@ const LinkEditPopover = ({ editor, size, variant }: LinkEditPopoverProps) => {
const [open, setOpen] = React.useState(false)
const { from, to } = editor.state.selection
- const text = editor.state.doc.textBetween(from, to, " ")
+ const text = editor.state.doc.textBetween(from, to, ' ')
const onSetLink = React.useCallback(
(url: string, text?: string, openInNewTab?: boolean) => {
editor
.chain()
.focus()
- .extendMarkRange("link")
+ .extendMarkRange('link')
.insertContent({
- type: "text",
+ type: 'text',
text: text || url,
marks: [
{
- type: "link",
+ type: 'link',
attrs: {
href: url,
- target: openInNewTab ? "_blank" : "",
- },
- },
- ],
+ target: openInNewTab ? '_blank' : ''
+ }
+ }
+ ]
})
.setLink({ href: url })
.run()
@@ -52,10 +48,10 @@ const LinkEditPopover = ({ editor, size, variant }: LinkEditPopoverProps) => {
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<ToolbarButton
- isActive={editor.isActive("link")}
+ isActive={editor.isActive('link')}
tooltip="Link"
aria-label="Insert link"
- disabled={editor.isActive("codeBlock")}
+ disabled={editor.isActive('codeBlock')}
size={size}
variant={variant}
>
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-popover-block.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-popover-block.tsx
index ea09b568..4904924e 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-popover-block.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/link/link-popover-block.tsx
@@ -1,11 +1,7 @@
-import * as React from "react"
-import { Separator } from "@/components/ui/separator"
-import { ToolbarButton } from "../toolbar-button"
-import {
- Copy,
- ExternalLink,
- Unlink,
-} from "lucide-react"
+import * as React from 'react'
+import { Separator } from '@/components/ui/separator'
+import { ToolbarButton } from '../toolbar-button'
+import { Copy, ExternalLink, Unlink } from 'lucide-react'
interface LinkPopoverBlockProps {
url: string
@@ -13,12 +9,8 @@ interface LinkPopoverBlockProps {
onEdit: (e: React.MouseEvent<HTMLButtonElement>) => void
}
-export const LinkPopoverBlock: React.FC<LinkPopoverBlockProps> = ({
- url,
- onClear,
- onEdit,
-}) => {
- const [copyTitle, setCopyTitle] = React.useState<string>("Copy")
+export const LinkPopoverBlock: React.FC<LinkPopoverBlockProps> = ({ url, onClear, onEdit }) => {
+ const [copyTitle, setCopyTitle] = React.useState<string>('Copy')
const handleCopy = React.useCallback(
(e: React.MouseEvent<HTMLButtonElement>) => {
@@ -26,8 +18,8 @@ export const LinkPopoverBlock: React.FC<LinkPopoverBlockProps> = ({
navigator.clipboard
.writeText(url)
.then(() => {
- setCopyTitle("Copied!")
- setTimeout(() => setCopyTitle("Copy"), 1000)
+ setCopyTitle('Copied!')
+ setTimeout(() => setCopyTitle('Copy'), 1000)
})
.catch(console.error)
},
@@ -35,24 +27,17 @@ export const LinkPopoverBlock: React.FC<LinkPopoverBlockProps> = ({
)
const handleOpenLink = React.useCallback(() => {
- window.open(url, "_blank", "noopener,noreferrer")
+ window.open(url, '_blank', 'noopener,noreferrer')
}, [url])
return (
<div className="flex h-10 overflow-hidden rounded-mdbg-background p-2 shadow-lg">
<div className="inline-flex items-center gap-1">
- <ToolbarButton
- tooltip="Edit link"
- onClick={onEdit}
- className="w-auto px-2"
- >
+ <ToolbarButton tooltip="Edit link" onClick={onEdit} className="w-auto px-2">
Edit link
</ToolbarButton>
<Separator orientation="vertical" />
- <ToolbarButton
- tooltip="Open link in a new tab"
- onClick={handleOpenLink}
- >
+ <ToolbarButton tooltip="Open link in a new tab" onClick={handleOpenLink}>
<ExternalLink className="size-4" />
</ToolbarButton>
<Separator orientation="vertical" />
@@ -66,7 +51,7 @@ export const LinkPopoverBlock: React.FC<LinkPopoverBlockProps> = ({
tooltipOptions={{
onPointerDownOutside: (e) => {
if (e.target === e.currentTarget) e.preventDefault()
- },
+ }
}}
>
<Copy className="size-4" />
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/measured-container.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/measured-container.tsx
index 9c51b9d6..7627deb7 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/measured-container.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/measured-container.tsx
@@ -1,5 +1,5 @@
-import * as React from "react"
-import { useContainerSize } from "../hooks/use-container-size"
+import * as React from 'react'
+import { useContainerSize } from '../hooks/use-container-size'
interface MeasuredContainerProps<T extends React.ElementType> {
as: T
@@ -25,7 +25,7 @@ export const MeasuredContainer = React.forwardRef(
const customStyle = {
[`--${name}-width`]: `${rect.width}px`,
- [`--${name}-height`]: `${rect.height}px`,
+ [`--${name}-height`]: `${rect.height}px`
}
return (
@@ -36,4 +36,4 @@ export const MeasuredContainer = React.forwardRef(
}
)
-MeasuredContainer.displayName = "MeasuredContainer"
+MeasuredContainer.displayName = 'MeasuredContainer'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/five.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/five.tsx
index 73d9553b..71ba0224 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/five.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/five.tsx
@@ -1,55 +1,46 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { FormatAction } from "../../types"
-import type { toggleVariants } from "@/components/ui/toggle"
-import type { VariantProps } from "class-variance-authority"
-import {
- ChevronDown,
- Code,
- Minus,
- Plus,
- Quote,
-} from "lucide-react"
-import { LinkEditPopover } from "../link/link-edit-popover"
-import { ImageEditDialog } from "../image/image-edit-dialog"
-import { ToolbarSection } from "../toolbar-section"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { FormatAction } from '../../types'
+import type { toggleVariants } from '@/components/ui/toggle'
+import type { VariantProps } from 'class-variance-authority'
+import { ChevronDown, Code, Minus, Plus, Quote } from 'lucide-react'
+import { LinkEditPopover } from '../link/link-edit-popover'
+import { ImageEditDialog } from '../image/image-edit-dialog'
+import { ToolbarSection } from '../toolbar-section'
-type InsertElementAction = "codeBlock" | "blockquote" | "horizontalRule"
+type InsertElementAction = 'codeBlock' | 'blockquote' | 'horizontalRule'
interface InsertElement extends FormatAction {
value: InsertElementAction
}
const formatActions: InsertElement[] = [
{
- value: "codeBlock",
- label: "Code block",
+ value: 'codeBlock',
+ label: 'Code block',
icon: <Code className="size-5" />,
action: (editor) => editor.chain().focus().toggleCodeBlock().run(),
- isActive: (editor) => editor.isActive("codeBlock"),
- canExecute: (editor) =>
- editor.can().chain().focus().toggleCodeBlock().run(),
- shortcuts: ["mod", "alt", "C"],
+ isActive: (editor) => editor.isActive('codeBlock'),
+ canExecute: (editor) => editor.can().chain().focus().toggleCodeBlock().run(),
+ shortcuts: ['mod', 'alt', 'C']
},
{
- value: "blockquote",
- label: "Blockquote",
+ value: 'blockquote',
+ label: 'Blockquote',
icon: <Quote className="size-5" />,
action: (editor) => editor.chain().focus().toggleBlockquote().run(),
- isActive: (editor) => editor.isActive("blockquote"),
- canExecute: (editor) =>
- editor.can().chain().focus().toggleBlockquote().run(),
- shortcuts: ["mod", "shift", "B"],
+ isActive: (editor) => editor.isActive('blockquote'),
+ canExecute: (editor) => editor.can().chain().focus().toggleBlockquote().run(),
+ shortcuts: ['mod', 'shift', 'B']
},
{
- value: "horizontalRule",
- label: "Divider",
+ value: 'horizontalRule',
+ label: 'Divider',
icon: <Minus className="size-5" />,
action: (editor) => editor.chain().focus().setHorizontalRule().run(),
isActive: () => false,
- canExecute: (editor) =>
- editor.can().chain().focus().setHorizontalRule().run(),
- shortcuts: ["mod", "alt", "-"],
- },
+ canExecute: (editor) => editor.can().chain().focus().setHorizontalRule().run(),
+ shortcuts: ['mod', 'alt', '-']
+ }
]
interface SectionFiveProps extends VariantProps<typeof toggleVariants> {
@@ -63,7 +54,7 @@ export const SectionFive: React.FC<SectionFiveProps> = ({
activeActions = formatActions.map((action) => action.value),
mainActionCount = 0,
size,
- variant,
+ variant
}) => {
return (
<>
@@ -88,6 +79,6 @@ export const SectionFive: React.FC<SectionFiveProps> = ({
)
}
-SectionFive.displayName = "SectionFive"
+SectionFive.displayName = 'SectionFive'
export default SectionFive
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/four.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/four.tsx
index 49b5a897..80ec8926 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/four.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/four.tsx
@@ -1,20 +1,20 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { FormatAction } from "../../types"
-import type { toggleVariants } from "@/components/ui/toggle"
-import type { VariantProps } from "class-variance-authority"
-import { ChevronDown, List } from "lucide-react"
-import { ToolbarSection } from "../toolbar-section"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { FormatAction } from '../../types'
+import type { toggleVariants } from '@/components/ui/toggle'
+import type { VariantProps } from 'class-variance-authority'
+import { ChevronDown, List } from 'lucide-react'
+import { ToolbarSection } from '../toolbar-section'
-type ListItemAction = "orderedList" | "bulletList"
+type ListItemAction = 'orderedList' | 'bulletList'
interface ListItem extends FormatAction {
value: ListItemAction
}
const formatActions: ListItem[] = [
{
- value: "orderedList",
- label: "Numbered list",
+ value: 'orderedList',
+ label: 'Numbered list',
icon: (
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -26,22 +26,20 @@ const formatActions: ListItem[] = [
<path d="M144-144v-48h96v-24h-48v-48h48v-24h-96v-48h120q10.2 0 17.1 6.9 6.9 6.9 6.9 17.1v48q0 10.2-6.9 17.1-6.9 6.9-17.1 6.9 10.2 0 17.1 6.9 6.9 6.9 6.9 17.1v48q0 10.2-6.9 17.1-6.9 6.9-17.1 6.9H144Zm0-240v-96q0-10.2 6.9-17.1 6.9-6.9 17.1-6.9h72v-24h-96v-48h120q10.2 0 17.1 6.9 6.9 6.9 6.9 17.1v72q0 10.2-6.9 17.1-6.9 6.9-17.1 6.9h-72v24h96v48H144Zm48-240v-144h-48v-48h96v192h-48Zm168 384v-72h456v72H360Zm0-204v-72h456v72H360Zm0-204v-72h456v72H360Z" />
</svg>
),
- isActive: (editor) => editor.isActive("orderedList"),
+ isActive: (editor) => editor.isActive('orderedList'),
action: (editor) => editor.chain().focus().toggleOrderedList().run(),
- canExecute: (editor) =>
- editor.can().chain().focus().toggleOrderedList().run(),
- shortcuts: ["mod", "shift", "7"],
+ canExecute: (editor) => editor.can().chain().focus().toggleOrderedList().run(),
+ shortcuts: ['mod', 'shift', '7']
},
{
- value: "bulletList",
- label: "Bullet list",
+ value: 'bulletList',
+ label: 'Bullet list',
icon: <List className="size-5" />,
- isActive: (editor) => editor.isActive("bulletList"),
+ isActive: (editor) => editor.isActive('bulletList'),
action: (editor) => editor.chain().focus().toggleBulletList().run(),
- canExecute: (editor) =>
- editor.can().chain().focus().toggleBulletList().run(),
- shortcuts: ["mod", "shift", "8"],
- },
+ canExecute: (editor) => editor.can().chain().focus().toggleBulletList().run(),
+ shortcuts: ['mod', 'shift', '8']
+ }
]
interface SectionFourProps extends VariantProps<typeof toggleVariants> {
@@ -55,7 +53,7 @@ export const SectionFour: React.FC<SectionFourProps> = ({
activeActions = formatActions.map((action) => action.value),
mainActionCount = 0,
size,
- variant,
+ variant
}) => {
return (
<ToolbarSection
@@ -76,6 +74,6 @@ export const SectionFour: React.FC<SectionFourProps> = ({
)
}
-SectionFour.displayName = "SectionFour"
+SectionFour.displayName = 'SectionFour'
export default SectionFour
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/one.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/one.tsx
index 873ee658..3e19efaa 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/one.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/one.tsx
@@ -1,25 +1,22 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { Level } from "@tiptap/extension-heading"
-import type { FormatAction } from "../../types"
-import type { VariantProps } from "class-variance-authority"
-import type { toggleVariants } from "@/components/ui/toggle"
-import { cn } from "@/lib/utils"
-import { ChevronDown, Type } from "lucide-react"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { Level } from '@tiptap/extension-heading'
+import type { FormatAction } from '../../types'
+import type { VariantProps } from 'class-variance-authority'
+import type { toggleVariants } from '@/components/ui/toggle'
+import { cn } from '@/lib/utils'
+import { ChevronDown, Type } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import { ToolbarButton } from "../toolbar-button"
-import { ShortcutKey } from "../shortcut-key"
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { ToolbarButton } from '../toolbar-button'
+import { ShortcutKey } from '../shortcut-key'
interface TextStyle
- extends Omit<
- FormatAction,
- "value" | "icon" | "action" | "isActive" | "canExecute"
- > {
+ extends Omit<FormatAction, 'value' | 'icon' | 'action' | 'isActive' | 'canExecute'> {
element: keyof React.JSX.IntrinsicElements
level?: Level
className: string
@@ -27,53 +24,53 @@ interface TextStyle
const formatActions: TextStyle[] = [
{
- label: "Normal Text",
- element: "span",
- className: "grow",
- shortcuts: ["mod", "alt", "0"],
+ label: 'Normal Text',
+ element: 'span',
+ className: 'grow',
+ shortcuts: ['mod', 'alt', '0']
},
{
- label: "Heading 1",
- element: "h1",
+ label: 'Heading 1',
+ element: 'h1',
level: 1,
- className: "m-0 grow text-3xl font-extrabold",
- shortcuts: ["mod", "alt", "1"],
+ className: 'm-0 grow text-3xl font-extrabold',
+ shortcuts: ['mod', 'alt', '1']
},
{
- label: "Heading 2",
- element: "h2",
+ label: 'Heading 2',
+ element: 'h2',
level: 2,
- className: "m-0 grow text-xl font-bold",
- shortcuts: ["mod", "alt", "2"],
+ className: 'm-0 grow text-xl font-bold',
+ shortcuts: ['mod', 'alt', '2']
},
{
- label: "Heading 3",
- element: "h3",
+ label: 'Heading 3',
+ element: 'h3',
level: 3,
- className: "m-0 grow text-lg font-semibold",
- shortcuts: ["mod", "alt", "3"],
+ className: 'm-0 grow text-lg font-semibold',
+ shortcuts: ['mod', 'alt', '3']
},
{
- label: "Heading 4",
- element: "h4",
+ label: 'Heading 4',
+ element: 'h4',
level: 4,
- className: "m-0 grow text-base font-semibold",
- shortcuts: ["mod", "alt", "4"],
+ className: 'm-0 grow text-base font-semibold',
+ shortcuts: ['mod', 'alt', '4']
},
{
- label: "Heading 5",
- element: "h5",
+ label: 'Heading 5',
+ element: 'h5',
level: 5,
- className: "m-0 grow text-sm font-normal",
- shortcuts: ["mod", "alt", "5"],
+ className: 'm-0 grow text-sm font-normal',
+ shortcuts: ['mod', 'alt', '5']
},
{
- label: "Heading 6",
- element: "h6",
+ label: 'Heading 6',
+ element: 'h6',
level: 6,
- className: "m-0 grow text-sm font-normal",
- shortcuts: ["mod", "alt", "6"],
- },
+ className: 'm-0 grow text-sm font-normal',
+ shortcuts: ['mod', 'alt', '6']
+ }
]
interface SectionOneProps extends VariantProps<typeof toggleVariants> {
@@ -84,10 +81,7 @@ interface SectionOneProps extends VariantProps<typeof toggleVariants> {
export const SectionOne: React.FC<SectionOneProps> = React.memo(
({ editor, activeLevels = [1, 2, 3, 4, 5, 6], size, variant }) => {
const filteredActions = React.useMemo(
- () =>
- formatActions.filter(
- (action) => !action.level || activeLevels.includes(action.level)
- ),
+ () => formatActions.filter((action) => !action.level || activeLevels.includes(action.level)),
[activeLevels]
)
@@ -107,10 +101,10 @@ export const SectionOne: React.FC<SectionOneProps> = React.memo(
<DropdownMenuItem
key={label}
onClick={() => handleStyleChange(level)}
- className={cn("flex flex-row items-center justify-between gap-4", {
- "bg-accent": level
- ? editor.isActive("heading", { level })
- : editor.isActive("paragraph"),
+ className={cn('flex flex-row items-center justify-between gap-4', {
+ 'bg-accent': level
+ ? editor.isActive('heading', { level })
+ : editor.isActive('paragraph')
})}
aria-label={label}
>
@@ -125,12 +119,12 @@ export const SectionOne: React.FC<SectionOneProps> = React.memo(
<DropdownMenu>
<DropdownMenuTrigger asChild>
<ToolbarButton
- isActive={editor.isActive("heading")}
+ isActive={editor.isActive('heading')}
tooltip="Text styles"
aria-label="Text styles"
- pressed={editor.isActive("heading")}
+ pressed={editor.isActive('heading')}
className="w-12"
- disabled={editor.isActive("codeBlock")}
+ disabled={editor.isActive('codeBlock')}
size={size}
variant={variant}
>
@@ -146,6 +140,6 @@ export const SectionOne: React.FC<SectionOneProps> = React.memo(
}
)
-SectionOne.displayName = "SectionOne"
+SectionOne.displayName = 'SectionOne'
export default SectionOne
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/three.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/three.tsx
index 11eee777..1fbaedad 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/three.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/three.tsx
@@ -1,21 +1,13 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { toggleVariants } from "@/components/ui/toggle"
-import type { VariantProps } from "class-variance-authority"
-import { ChevronDown, Check } from "lucide-react"
-import { ToolbarButton } from "../toolbar-button"
-import {
- Popover,
- PopoverTrigger,
- PopoverContent,
-} from "@/components/ui/popover"
-import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@/components/ui/tooltip"
-import { useTheme } from "@/components/theme-provider"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { toggleVariants } from '@/components/ui/toggle'
+import type { VariantProps } from 'class-variance-authority'
+import { ChevronDown, Check } from 'lucide-react'
+import { ToolbarButton } from '../toolbar-button'
+import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import { useTheme } from '@/components/theme-provider'
interface ColorItem {
cssVar: string
@@ -31,44 +23,44 @@ interface ColorPalette {
const COLORS: ColorPalette[] = [
{
- label: "Palette 1",
- inverse: "hsl(var(--background))",
+ label: 'Palette 1',
+ inverse: 'hsl(var(--background))',
colors: [
- { cssVar: "hsl(var(--foreground))", label: "Default" },
- { cssVar: "var(--mt-accent-bold-blue)", label: "Bold blue" },
- { cssVar: "var(--mt-accent-bold-teal)", label: "Bold teal" },
- { cssVar: "var(--mt-accent-bold-green)", label: "Bold green" },
- { cssVar: "var(--mt-accent-bold-orange)", label: "Bold orange" },
- { cssVar: "var(--mt-accent-bold-red)", label: "Bold red" },
- { cssVar: "var(--mt-accent-bold-purple)", label: "Bold purple" },
- ],
+ { cssVar: 'hsl(var(--foreground))', label: 'Default' },
+ { cssVar: 'var(--mt-accent-bold-blue)', label: 'Bold blue' },
+ { cssVar: 'var(--mt-accent-bold-teal)', label: 'Bold teal' },
+ { cssVar: 'var(--mt-accent-bold-green)', label: 'Bold green' },
+ { cssVar: 'var(--mt-accent-bold-orange)', label: 'Bold orange' },
+ { cssVar: 'var(--mt-accent-bold-red)', label: 'Bold red' },
+ { cssVar: 'var(--mt-accent-bold-purple)', label: 'Bold purple' }
+ ]
},
{
- label: "Palette 2",
- inverse: "hsl(var(--background))",
+ label: 'Palette 2',
+ inverse: 'hsl(var(--background))',
colors: [
- { cssVar: "var(--mt-accent-gray)", label: "Gray" },
- { cssVar: "var(--mt-accent-blue)", label: "Blue" },
- { cssVar: "var(--mt-accent-teal)", label: "Teal" },
- { cssVar: "var(--mt-accent-green)", label: "Green" },
- { cssVar: "var(--mt-accent-orange)", label: "Orange" },
- { cssVar: "var(--mt-accent-red)", label: "Red" },
- { cssVar: "var(--mt-accent-purple)", label: "Purple" },
- ],
+ { cssVar: 'var(--mt-accent-gray)', label: 'Gray' },
+ { cssVar: 'var(--mt-accent-blue)', label: 'Blue' },
+ { cssVar: 'var(--mt-accent-teal)', label: 'Teal' },
+ { cssVar: 'var(--mt-accent-green)', label: 'Green' },
+ { cssVar: 'var(--mt-accent-orange)', label: 'Orange' },
+ { cssVar: 'var(--mt-accent-red)', label: 'Red' },
+ { cssVar: 'var(--mt-accent-purple)', label: 'Purple' }
+ ]
},
{
- label: "Palette 3",
- inverse: "hsl(var(--foreground))",
+ label: 'Palette 3',
+ inverse: 'hsl(var(--foreground))',
colors: [
- { cssVar: "hsl(var(--background))", label: "White", darkLabel: "Black" },
- { cssVar: "var(--mt-accent-blue-subtler)", label: "Blue subtle" },
- { cssVar: "var(--mt-accent-teal-subtler)", label: "Teal subtle" },
- { cssVar: "var(--mt-accent-green-subtler)", label: "Green subtle" },
- { cssVar: "var(--mt-accent-yellow-subtler)", label: "Yellow subtle" },
- { cssVar: "var(--mt-accent-red-subtler)", label: "Red subtle" },
- { cssVar: "var(--mt-accent-purple-subtler)", label: "Purple subtle" },
- ],
- },
+ { cssVar: 'hsl(var(--background))', label: 'White', darkLabel: 'Black' },
+ { cssVar: 'var(--mt-accent-blue-subtler)', label: 'Blue subtle' },
+ { cssVar: 'var(--mt-accent-teal-subtler)', label: 'Teal subtle' },
+ { cssVar: 'var(--mt-accent-green-subtler)', label: 'Green subtle' },
+ { cssVar: 'var(--mt-accent-yellow-subtler)', label: 'Yellow subtle' },
+ { cssVar: 'var(--mt-accent-red-subtler)', label: 'Red subtle' },
+ { cssVar: 'var(--mt-accent-purple-subtler)', label: 'Purple subtle' }
+ ]
+ }
]
const MemoizedColorButton = React.memo<{
@@ -95,10 +87,7 @@ const MemoizedColorButton = React.memo<{
}}
>
{isSelected && (
- <Check
- className="absolute inset-0 m-auto size-6"
- style={{ color: inverse }}
- />
+ <Check className="absolute inset-0 m-auto size-6" style={{ color: inverse }} />
)}
</ToggleGroupItem>
</TooltipTrigger>
@@ -109,7 +98,7 @@ const MemoizedColorButton = React.memo<{
)
})
-MemoizedColorButton.displayName = "MemoizedColorButton"
+MemoizedColorButton.displayName = 'MemoizedColorButton'
const MemoizedColorPicker = React.memo<{
palette: ColorPalette
@@ -137,19 +126,14 @@ const MemoizedColorPicker = React.memo<{
</ToggleGroup>
))
-MemoizedColorPicker.displayName = "MemoizedColorPicker"
+MemoizedColorPicker.displayName = 'MemoizedColorPicker'
interface SectionThreeProps extends VariantProps<typeof toggleVariants> {
editor: Editor
}
-export const SectionThree: React.FC<SectionThreeProps> = ({
- editor,
- size,
- variant,
-}) => {
- const color =
- editor.getAttributes("textStyle")?.color || "hsl(var(--foreground))"
+export const SectionThree: React.FC<SectionThreeProps> = ({ editor, size, variant }) => {
+ const color = editor.getAttributes('textStyle')?.color || 'hsl(var(--foreground))'
const [selectedColor, setSelectedColor] = React.useState(color)
const handleColorChange = React.useCallback(
@@ -211,6 +195,6 @@ export const SectionThree: React.FC<SectionThreeProps> = ({
)
}
-SectionThree.displayName = "SectionThree"
+SectionThree.displayName = 'SectionThree'
export default SectionThree
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/two.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/two.tsx
index fead65d3..d5a2d5a1 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/section/two.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/section/two.tsx
@@ -1,26 +1,18 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { FormatAction } from "../../types"
-import type { toggleVariants } from "@/components/ui/toggle"
-import type { VariantProps } from "class-variance-authority"
-import {
- Code,
- MoreHorizontal,
- Bold,
- Italic,
- Strikethrough,
- Type,
- Underline,
-} from "lucide-react"
-import { ToolbarSection } from "../toolbar-section"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { FormatAction } from '../../types'
+import type { toggleVariants } from '@/components/ui/toggle'
+import type { VariantProps } from 'class-variance-authority'
+import { Code, MoreHorizontal, Bold, Italic, Strikethrough, Type, Underline } from 'lucide-react'
+import { ToolbarSection } from '../toolbar-section'
type TextStyleAction =
- | "bold"
- | "italic"
- | "underline"
- | "strikethrough"
- | "code"
- | "clearFormatting"
+ | 'bold'
+ | 'italic'
+ | 'underline'
+ | 'strikethrough'
+ | 'code'
+ | 'clearFormatting'
interface TextStyle extends FormatAction {
value: TextStyleAction
@@ -28,71 +20,65 @@ interface TextStyle extends FormatAction {
const formatActions: TextStyle[] = [
{
- value: "bold",
- label: "Bold",
+ value: 'bold',
+ label: 'Bold',
icon: <Bold className="size-5" />,
action: (editor) => editor.chain().focus().toggleBold().run(),
- isActive: (editor) => editor.isActive("bold"),
+ isActive: (editor) => editor.isActive('bold'),
canExecute: (editor) =>
- editor.can().chain().focus().toggleBold().run() &&
- !editor.isActive("codeBlock"),
- shortcuts: ["mod", "B"],
+ editor.can().chain().focus().toggleBold().run() && !editor.isActive('codeBlock'),
+ shortcuts: ['mod', 'B']
},
{
- value: "italic",
- label: "Italic",
+ value: 'italic',
+ label: 'Italic',
icon: <Italic className="size-5" />,
action: (editor) => editor.chain().focus().toggleItalic().run(),
- isActive: (editor) => editor.isActive("italic"),
+ isActive: (editor) => editor.isActive('italic'),
canExecute: (editor) =>
- editor.can().chain().focus().toggleItalic().run() &&
- !editor.isActive("codeBlock"),
- shortcuts: ["mod", "I"],
+ editor.can().chain().focus().toggleItalic().run() && !editor.isActive('codeBlock'),
+ shortcuts: ['mod', 'I']
},
{
- value: "underline",
- label: "Underline",
+ value: 'underline',
+ label: 'Underline',
icon: <Underline className="size-5" />,
action: (editor) => editor.chain().focus().toggleUnderline().run(),
- isActive: (editor) => editor.isActive("underline"),
+ isActive: (editor) => editor.isActive('underline'),
canExecute: (editor) =>
- editor.can().chain().focus().toggleUnderline().run() &&
- !editor.isActive("codeBlock"),
- shortcuts: ["mod", "U"],
+ editor.can().chain().focus().toggleUnderline().run() && !editor.isActive('codeBlock'),
+ shortcuts: ['mod', 'U']
},
{
- value: "strikethrough",
- label: "Strikethrough",
+ value: 'strikethrough',
+ label: 'Strikethrough',
icon: <Strikethrough className="size-5" />,
action: (editor) => editor.chain().focus().toggleStrike().run(),
- isActive: (editor) => editor.isActive("strike"),
+ isActive: (editor) => editor.isActive('strike'),
canExecute: (editor) =>
- editor.can().chain().focus().toggleStrike().run() &&
- !editor.isActive("codeBlock"),
- shortcuts: ["mod", "shift", "S"],
+ editor.can().chain().focus().toggleStrike().run() && !editor.isActive('codeBlock'),
+ shortcuts: ['mod', 'shift', 'S']
},
{
- value: "code",
- label: "Code",
+ value: 'code',
+ label: 'Code',
icon: <Code className="size-5" />,
action: (editor) => editor.chain().focus().toggleCode().run(),
- isActive: (editor) => editor.isActive("code"),
+ isActive: (editor) => editor.isActive('code'),
canExecute: (editor) =>
- editor.can().chain().focus().toggleCode().run() &&
- !editor.isActive("codeBlock"),
- shortcuts: ["mod", "E"],
+ editor.can().chain().focus().toggleCode().run() && !editor.isActive('codeBlock'),
+ shortcuts: ['mod', 'E']
},
{
- value: "clearFormatting",
- label: "Clear formatting",
+ value: 'clearFormatting',
+ label: 'Clear formatting',
icon: <Type className="size-5" />,
action: (editor) => editor.chain().focus().unsetAllMarks().run(),
isActive: () => false,
canExecute: (editor) =>
- editor.can().chain().focus().unsetAllMarks().run() &&
- !editor.isActive("codeBlock"),
- shortcuts: ["mod", "\\"],
- },
+ editor.can().chain().focus().unsetAllMarks().run() && !editor.isActive('codeBlock'),
+ shortcuts: ['mod', '\\']
+ }
]
interface SectionTwoProps extends VariantProps<typeof toggleVariants> {
@@ -106,7 +92,7 @@ export const SectionTwo: React.FC<SectionTwoProps> = ({
activeActions = formatActions.map((action) => action.value),
mainActionCount = 2,
size,
- variant,
+ variant
}) => {
return (
<ToolbarSection
@@ -123,6 +109,6 @@ export const SectionTwo: React.FC<SectionTwoProps> = ({
)
}
-SectionTwo.displayName = "SectionTwo"
+SectionTwo.displayName = 'SectionTwo'
export default SectionTwo
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/shortcut-key.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/shortcut-key.tsx
index 8adc1024..7206a0d0 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/shortcut-key.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/shortcut-key.tsx
@@ -1,23 +1,20 @@
-import * as React from "react"
-import { cn } from "@/lib/utils"
-import { getShortcutKey } from "../utils"
+import * as React from 'react'
+import { cn } from '@/lib/utils'
+import { getShortcutKey } from '../utils'
-export interface ShortcutKeyProps
- extends React.HTMLAttributes<HTMLSpanElement> {
+export interface ShortcutKeyProps extends React.HTMLAttributes<HTMLSpanElement> {
keys: string[]
}
export const ShortcutKey = React.forwardRef<HTMLSpanElement, ShortcutKeyProps>(
({ className, keys, ...props }, ref) => {
const modifiedKeys = keys.map((key) => getShortcutKey(key))
- const ariaLabel = modifiedKeys
- .map((shortcut) => shortcut.readable)
- .join(" + ")
+ const ariaLabel = modifiedKeys.map((shortcut) => shortcut.readable).join(' + ')
return (
<span
aria-label={ariaLabel}
- className={cn("inline-flex items-center gap-0.5", className)}
+ className={cn('inline-flex items-center gap-0.5', className)}
{...props}
ref={ref}
>
@@ -25,7 +22,7 @@ export const ShortcutKey = React.forwardRef<HTMLSpanElement, ShortcutKeyProps>(
<kbd
key={shortcut.symbol}
className={cn(
- "inline-block min-w-2.5 text-center align-baseline font-sans text-xs font-medium capitalize text-[rgb(156,157,160)]",
+ 'inline-block min-w-2.5 text-center align-baseline font-sans text-xs font-medium capitalize text-[rgb(156,157,160)]',
className
)}
@@ -40,4 +37,4 @@ export const ShortcutKey = React.forwardRef<HTMLSpanElement, ShortcutKeyProps>(
}
)
-ShortcutKey.displayName = "ShortcutKey"
+ShortcutKey.displayName = 'ShortcutKey'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/spinner.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/spinner.tsx
index f985c33c..fc8643cd 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/spinner.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/spinner.tsx
@@ -1,37 +1,38 @@
-import * as React from "react"
-import { cn } from "@/lib/utils"
+import * as React from 'react'
+import { cn } from '@/lib/utils'
interface SpinnerProps extends React.SVGProps<SVGSVGElement> {}
-const SpinnerComponent = React.forwardRef<SVGSVGElement, SpinnerProps>(
- function Spinner({ className, ...props }, ref) {
- return (
- <svg
- ref={ref}
- xmlns="http://www.w3.org/2000/svg"
- fill="none"
- viewBox="0 0 24 24"
- className={cn("animate-spin", className)}
- {...props}
- >
- <circle
- className="opacity-25"
- cx="12"
- cy="12"
- r="10"
- stroke="currentColor"
- strokeWidth="4"
- ></circle>
- <path
- className="opacity-75"
- fill="currentColor"
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
- ></path>
- </svg>
- )
- }
-)
+const SpinnerComponent = React.forwardRef<SVGSVGElement, SpinnerProps>(function Spinner(
+ { className, ...props },
+ ref
+) {
+ return (
+ <svg
+ ref={ref}
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ className={cn('animate-spin', className)}
+ {...props}
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ ></circle>
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
+ ></path>
+ </svg>
+ )
+})
-SpinnerComponent.displayName = "Spinner"
+SpinnerComponent.displayName = 'Spinner'
export const Spinner = React.memo(SpinnerComponent)
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/toolbar-button.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/toolbar-button.tsx
index 16d123c3..7874d1d1 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/toolbar-button.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/toolbar-button.tsx
@@ -1,33 +1,22 @@
-import * as React from "react"
-import type { TooltipContentProps } from "@radix-ui/react-tooltip"
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@/components/ui/tooltip"
-import { Toggle } from "@/components/ui/toggle"
-import { cn } from "@/lib/utils"
+import * as React from 'react'
+import type { TooltipContentProps } from '@radix-ui/react-tooltip'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import { Toggle } from '@/components/ui/toggle'
+import { cn } from '@/lib/utils'
-interface ToolbarButtonProps
- extends React.ComponentPropsWithoutRef<typeof Toggle> {
+interface ToolbarButtonProps extends React.ComponentPropsWithoutRef<typeof Toggle> {
isActive?: boolean
tooltip?: string
tooltipOptions?: TooltipContentProps
}
-export const ToolbarButton = React.forwardRef<
- HTMLButtonElement,
- ToolbarButtonProps
->(
- (
- { isActive, children, tooltip, className, tooltipOptions, ...props },
- ref
- ) => {
+export const ToolbarButton = React.forwardRef<HTMLButtonElement, ToolbarButtonProps>(
+ ({ isActive, children, tooltip, className, tooltipOptions, ...props }, ref) => {
const toggleButton = (
<Toggle
size="sm"
ref={ref}
- className={cn("size-8 p-0", { "bg-accent": isActive }, className)}
+ className={cn('size-8 p-0', { 'bg-accent': isActive }, className)}
{...props}
>
{children}
@@ -40,17 +29,17 @@ export const ToolbarButton = React.forwardRef<
return (
<Tooltip>
- <TooltipTrigger asChild><div>{toggleButton}</div></TooltipTrigger>
+ <TooltipTrigger asChild>
+ <div>{toggleButton}</div>
+ </TooltipTrigger>
<TooltipContent {...tooltipOptions}>
- <div className="flex flex-col items-center text-center">
- {tooltip}
- </div>
+ <div className="flex flex-col items-center text-center">{tooltip}</div>
</TooltipContent>
</Tooltip>
)
}
)
-ToolbarButton.displayName = "ToolbarButton"
+ToolbarButton.displayName = 'ToolbarButton'
export default ToolbarButton
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/components/toolbar-section.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/components/toolbar-section.tsx
index 5d4f591f..0fb53bdb 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/components/toolbar-section.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/components/toolbar-section.tsx
@@ -1,19 +1,19 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { FormatAction } from "../types"
-import type { VariantProps } from "class-variance-authority"
-import type { toggleVariants } from "@/components/ui/toggle"
-import { cn } from "@/lib/utils"
-import { ChevronDownIcon } from "lucide-react"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { FormatAction } from '../types'
+import type { VariantProps } from 'class-variance-authority'
+import type { toggleVariants } from '@/components/ui/toggle'
+import { cn } from '@/lib/utils'
+import { ChevronDownIcon } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import { ToolbarButton } from "./toolbar-button"
-import { ShortcutKey } from "./shortcut-key"
-import { getShortcutKey } from "../utils"
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { ToolbarButton } from './toolbar-button'
+import { ShortcutKey } from './shortcut-key'
+import { getShortcutKey } from '../utils'
interface ToolbarSectionProps extends VariantProps<typeof toggleVariants> {
editor: Editor
@@ -31,22 +31,19 @@ export const ToolbarSection: React.FC<ToolbarSectionProps> = ({
activeActions = actions.map((action) => action.value),
mainActionCount = 0,
dropdownIcon,
- dropdownTooltip = "More options",
- dropdownClassName = "w-12",
+ dropdownTooltip = 'More options',
+ dropdownClassName = 'w-12',
size,
- variant,
+ variant
}) => {
const { mainActions, dropdownActions } = React.useMemo(() => {
const sortedActions = actions
.filter((action) => activeActions.includes(action.value))
- .sort(
- (a, b) =>
- activeActions.indexOf(a.value) - activeActions.indexOf(b.value)
- )
+ .sort((a, b) => activeActions.indexOf(a.value) - activeActions.indexOf(b.value))
return {
mainActions: sortedActions.slice(0, mainActionCount),
- dropdownActions: sortedActions.slice(mainActionCount),
+ dropdownActions: sortedActions.slice(mainActionCount)
}
}, [actions, activeActions, mainActionCount])
@@ -57,7 +54,7 @@ export const ToolbarSection: React.FC<ToolbarSectionProps> = ({
onClick={() => action.action(editor)}
disabled={!action.canExecute(editor)}
isActive={action.isActive(editor)}
- tooltip={`${action.label} ${action.shortcuts.map((s) => getShortcutKey(s).symbol).join(" ")}`}
+ tooltip={`${action.label} ${action.shortcuts.map((s) => getShortcutKey(s).symbol).join(' ')}`}
aria-label={action.label}
size={size}
variant={variant}
@@ -74,8 +71,8 @@ export const ToolbarSection: React.FC<ToolbarSectionProps> = ({
key={action.label}
onClick={() => action.action(editor)}
disabled={!action.canExecute(editor)}
- className={cn("flex flex-row items-center justify-between gap-4", {
- "bg-accent": action.isActive(editor),
+ className={cn('flex flex-row items-center justify-between gap-4', {
+ 'bg-accent': action.isActive(editor)
})}
aria-label={action.label}
>
@@ -98,16 +95,16 @@ export const ToolbarSection: React.FC<ToolbarSectionProps> = ({
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div>
- <ToolbarButton
- isActive={isDropdownActive}
- tooltip={dropdownTooltip}
- aria-label={dropdownTooltip}
- className={cn(dropdownClassName)}
- size={size}
- variant={variant}
- >
- {dropdownIcon || <ChevronDownIcon className="size-5" />}
- </ToolbarButton>
+ <ToolbarButton
+ isActive={isDropdownActive}
+ tooltip={dropdownTooltip}
+ aria-label={dropdownTooltip}
+ className={cn(dropdownClassName)}
+ size={size}
+ variant={variant}
+ >
+ {dropdownIcon || <ChevronDownIcon className="size-5" />}
+ </ToolbarButton>
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-full">
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/code-block-lowlight/code-block-lowlight.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/code-block-lowlight/code-block-lowlight.ts
index 36f8e975..54523668 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/code-block-lowlight/code-block-lowlight.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/code-block-lowlight/code-block-lowlight.ts
@@ -1,5 +1,5 @@
-import { CodeBlockLowlight as TiptapCodeBlockLowlight } from "@tiptap/extension-code-block-lowlight"
-import { common, createLowlight } from "lowlight"
+import { CodeBlockLowlight as TiptapCodeBlockLowlight } from '@tiptap/extension-code-block-lowlight'
+import { common, createLowlight } from 'lowlight'
export const CodeBlockLowlight = TiptapCodeBlockLowlight.extend({
addOptions() {
@@ -8,10 +8,10 @@ export const CodeBlockLowlight = TiptapCodeBlockLowlight.extend({
lowlight: createLowlight(common),
defaultLanguage: null,
HTMLAttributes: {
- class: "block-node",
- },
+ class: 'block-node'
+ }
}
- },
+ }
})
export default CodeBlockLowlight
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/code-block-lowlight/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/code-block-lowlight/index.ts
index 4d6759ea..9ded0403 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/code-block-lowlight/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/code-block-lowlight/index.ts
@@ -1 +1 @@
-export * from "./code-block-lowlight"
+export * from './code-block-lowlight'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/color/color.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/color/color.ts
index ecb28430..9582d38b 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/color/color.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/color/color.ts
@@ -1,5 +1,5 @@
-import { Color as TiptapColor } from "@tiptap/extension-color"
-import { Plugin } from "@tiptap/pm/state"
+import { Color as TiptapColor } from '@tiptap/extension-color'
+import { Plugin } from '@tiptap/pm/state'
export const Color = TiptapColor.extend({
addProseMirrorPlugins() {
@@ -8,13 +8,13 @@ export const Color = TiptapColor.extend({
new Plugin({
props: {
handleKeyDown: (_, event) => {
- if (event.key === "Enter") {
+ if (event.key === 'Enter') {
this.editor.commands.unsetColor()
}
return false
- },
- },
- }),
+ }
+ }
+ })
]
- },
+ }
})
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/color/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/color/index.ts
index eb963340..1315dbcf 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/color/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/color/index.ts
@@ -1 +1 @@
-export * from "./color"
+export * from './color'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/file-handler/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/file-handler/index.ts
index dcb87abd..30c17919 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/file-handler/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/file-handler/index.ts
@@ -1,7 +1,7 @@
-import { type Editor, Extension } from "@tiptap/react"
-import { Plugin, PluginKey } from "@tiptap/pm/state"
-import type { FileError, FileValidationOptions } from "../../utils"
-import { filterFiles } from "../../utils"
+import { type Editor, Extension } from '@tiptap/react'
+import { Plugin, PluginKey } from '@tiptap/pm/state'
+import type { FileError, FileValidationOptions } from '../../utils'
+import { filterFiles } from '../../utils'
type FileHandlePluginOptions = {
key?: PluginKey
@@ -12,18 +12,10 @@ type FileHandlePluginOptions = {
} & FileValidationOptions
const FileHandlePlugin = (options: FileHandlePluginOptions) => {
- const {
- key,
- editor,
- onPaste,
- onDrop,
- onValidationError,
- allowedMimeTypes,
- maxFileSize,
- } = options
+ const { key, editor, onPaste, onDrop, onValidationError, allowedMimeTypes, maxFileSize } = options
return new Plugin({
- key: key || new PluginKey("fileHandler"),
+ key: key || new PluginKey('fileHandler'),
props: {
handleDrop(view, event) {
@@ -38,17 +30,14 @@ const FileHandlePlugin = (options: FileHandlePluginOptions) => {
const pos = view.posAtCoords({
left: event.clientX,
- top: event.clientY,
+ top: event.clientY
})
- const [validFiles, errors] = filterFiles(
- Array.from(dataTransfer.files),
- {
- allowedMimeTypes,
- maxFileSize,
- allowBase64: options.allowBase64,
- }
- )
+ const [validFiles, errors] = filterFiles(Array.from(dataTransfer.files), {
+ allowedMimeTypes,
+ maxFileSize,
+ allowBase64: options.allowBase64
+ })
if (errors.length > 0 && onValidationError) {
onValidationError(errors)
@@ -69,15 +58,12 @@ const FileHandlePlugin = (options: FileHandlePluginOptions) => {
return
}
- const [validFiles, errors] = filterFiles(
- Array.from(clipboardData.files),
- {
- allowedMimeTypes,
- maxFileSize,
- allowBase64: options.allowBase64,
- }
- )
- const html = clipboardData.getData("text/html")
+ const [validFiles, errors] = filterFiles(Array.from(clipboardData.files), {
+ allowedMimeTypes,
+ maxFileSize,
+ allowBase64: options.allowBase64
+ })
+ const html = clipboardData.getData('text/html')
if (errors.length > 0 && onValidationError) {
onValidationError(errors)
@@ -86,21 +72,19 @@ const FileHandlePlugin = (options: FileHandlePluginOptions) => {
if (validFiles.length > 0 && onPaste) {
onPaste(editor, validFiles, html)
}
- },
- },
+ }
+ }
})
}
-export const FileHandler = Extension.create<
- Omit<FileHandlePluginOptions, "key" | "editor">
->({
- name: "fileHandler",
+export const FileHandler = Extension.create<Omit<FileHandlePluginOptions, 'key' | 'editor'>>({
+ name: 'fileHandler',
addOptions() {
return {
allowBase64: false,
allowedMimeTypes: [],
- maxFileSize: 0,
+ maxFileSize: 0
}
},
@@ -109,8 +93,8 @@ export const FileHandler = Extension.create<
FileHandlePlugin({
key: new PluginKey(this.name),
editor: this.editor,
- ...this.options,
- }),
+ ...this.options
+ })
]
- },
+ }
})
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/horizontal-rule/horizontal-rule.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/horizontal-rule/horizontal-rule.ts
index 4b6d5334..c530d4f5 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/horizontal-rule/horizontal-rule.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/horizontal-rule/horizontal-rule.ts
@@ -2,17 +2,17 @@
* Wrap the horizontal rule in a div element.
* Also add a keyboard shortcut to insert a horizontal rule.
*/
-import { HorizontalRule as TiptapHorizontalRule } from "@tiptap/extension-horizontal-rule"
+import { HorizontalRule as TiptapHorizontalRule } from '@tiptap/extension-horizontal-rule'
export const HorizontalRule = TiptapHorizontalRule.extend({
addKeyboardShortcuts() {
return {
- "Mod-Alt--": () =>
+ 'Mod-Alt--': () =>
this.editor.commands.insertContent({
- type: this.name,
- }),
+ type: this.name
+ })
}
- },
+ }
})
export default HorizontalRule
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/horizontal-rule/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/horizontal-rule/index.ts
index 7cc78542..e6cb8015 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/horizontal-rule/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/horizontal-rule/index.ts
@@ -1 +1 @@
-export * from "./horizontal-rule"
+export * from './horizontal-rule'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-actions.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-actions.tsx
index b51ee87c..935d5e4e 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-actions.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-actions.tsx
@@ -1,24 +1,14 @@
-import * as React from "react"
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@/components/ui/tooltip"
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
+import * as React from 'react'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import { cn } from '@/lib/utils'
+import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import {
- Copy,
- MoreHorizontal,
- Download,
- Link2,
- Maximize,
-} from "lucide-react"
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { Copy, MoreHorizontal, Download, Link2, Maximize } from 'lucide-react'
interface ImageActionsProps {
shouldMerge?: boolean
@@ -29,8 +19,7 @@ interface ImageActionsProps {
onCopyLink?: () => void
}
-interface ActionButtonProps
- extends React.ButtonHTMLAttributes<HTMLButtonElement> {
+interface ActionButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
icon: React.ReactNode
tooltip: string
}
@@ -41,8 +30,8 @@ export const ActionWrapper = React.memo(
<div
ref={ref}
className={cn(
- "absolute right-3 top-3 flex flex-row rounded-mdpx-0.5 opacity-0 group-hover/node-image:opacity-100",
- "border-[0.5px] bg-[var(--mt-bg-secondary)] [backdrop-filter:saturate(1.8)_blur(20px)]",
+ 'absolute right-3 top-3 flex flex-row rounded-mdpx-0.5 opacity-0 group-hover/node-image:opacity-100',
+ 'border-[0.5px] bg-[var(--mt-bg-secondary)] [backdrop-filter:saturate(1.8)_blur(20px)]',
className
)}
{...props}
@@ -53,7 +42,7 @@ export const ActionWrapper = React.memo(
)
)
-ActionWrapper.displayName = "ActionWrapper"
+ActionWrapper.displayName = 'ActionWrapper'
export const ActionButton = React.memo(
React.forwardRef<HTMLButtonElement, ActionButtonProps>(
@@ -64,8 +53,8 @@ export const ActionButton = React.memo(
ref={ref}
variant="ghost"
className={cn(
- "relative flex h-7 w-7 flex-row rounded-none p-0 text-muted-foreground hover:text-foreground",
- "bg-transparent hover:bg-transparent",
+ 'relative flex h-7 w-7 flex-row rounded-none p-0 text-muted-foreground hover:text-foreground',
+ 'bg-transparent hover:bg-transparent',
className
)}
{...props}
@@ -79,9 +68,9 @@ export const ActionButton = React.memo(
)
)
-ActionButton.displayName = "ActionButton"
+ActionButton.displayName = 'ActionButton'
-type ActionKey = "onView" | "onDownload" | "onCopy" | "onCopyLink"
+type ActionKey = 'onView' | 'onDownload' | 'onCopy' | 'onCopyLink'
const ActionItems: Array<{
key: ActionKey
@@ -90,26 +79,26 @@ const ActionItems: Array<{
isLink?: boolean
}> = [
{
- key: "onView",
+ key: 'onView',
icon: <Maximize className="size-4" />,
- tooltip: "View image",
+ tooltip: 'View image'
},
{
- key: "onDownload",
+ key: 'onDownload',
icon: <Download className="size-4" />,
- tooltip: "Download image",
+ tooltip: 'Download image'
},
{
- key: "onCopy",
+ key: 'onCopy',
icon: <Copy className="size-4" />,
- tooltip: "Copy image to clipboard",
+ tooltip: 'Copy image to clipboard'
},
{
- key: "onCopyLink",
+ key: 'onCopyLink',
icon: <Link2 className="size-4" />,
- tooltip: "Copy image link",
- isLink: true,
- },
+ tooltip: 'Copy image link',
+ isLink: true
+ }
]
export const ImageActions: React.FC<ImageActionsProps> = React.memo(
@@ -131,7 +120,7 @@ export const ImageActions: React.FC<ImageActionsProps> = React.memo(
)
return (
- <ActionWrapper className={cn({ "opacity-100": isOpen })}>
+ <ActionWrapper className={cn({ 'opacity-100': isOpen })}>
{shouldMerge ? (
<DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
<DropdownMenuTrigger asChild>
@@ -143,10 +132,7 @@ export const ImageActions: React.FC<ImageActionsProps> = React.memo(
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" align="end">
{filteredActions.map(({ key, icon, tooltip }) => (
- <DropdownMenuItem
- key={key}
- onClick={(e) => handleAction(e, actions[key])}
- >
+ <DropdownMenuItem key={key} onClick={(e) => handleAction(e, actions[key])}>
<div className="flex flex-row items-center gap-2">
{icon}
<span>{tooltip}</span>
@@ -170,4 +156,4 @@ export const ImageActions: React.FC<ImageActionsProps> = React.memo(
}
)
-ImageActions.displayName = "ImageActions"
+ImageActions.displayName = 'ImageActions'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-overlay.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-overlay.tsx
index 666402a3..0b302553 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-overlay.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-overlay.tsx
@@ -1,13 +1,13 @@
-import * as React from "react"
-import { Spinner } from "../../../components/spinner"
-import { cn } from "@/lib/utils"
+import * as React from 'react'
+import { Spinner } from '../../../components/spinner'
+import { cn } from '@/lib/utils'
export const ImageOverlay = React.memo(() => {
return (
<div
className={cn(
- "flex flex-row items-center justify-center",
- "absolute inset-0 rounded-mdbg-[var(--mt-overlay)] opacity-100 transition-opacity"
+ 'flex flex-row items-center justify-center',
+ 'absolute inset-0 rounded-mdbg-[var(--mt-overlay)] opacity-100 transition-opacity'
)}
>
<Spinner className="size-7" />
@@ -15,4 +15,4 @@ export const ImageOverlay = React.memo(() => {
)
})
-ImageOverlay.displayName = "ImageOverlay"
+ImageOverlay.displayName = 'ImageOverlay'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-view-block.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-view-block.tsx
index 5befd665..de0dd5f8 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-view-block.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/image-view-block.tsx
@@ -1,17 +1,17 @@
-import * as React from "react"
-import { NodeViewWrapper, type NodeViewProps } from "@tiptap/react"
-import type { ElementDimensions } from "../hooks/use-drag-resize"
-import { useDragResize } from "../hooks/use-drag-resize"
-import { ResizeHandle } from "./resize-handle"
-import { cn } from "@/lib/utils"
-import { Controlled as ControlledZoom } from "react-medium-image-zoom"
-import { ActionButton, ActionWrapper, ImageActions } from "./image-actions"
-import { useImageActions } from "../hooks/use-image-actions"
-import { blobUrlToBase64, randomId } from "../../../utils"
-import { Info, Trash2 } from "lucide-react"
-import { ImageOverlay } from "./image-overlay"
-import { Spinner } from "../../../components/spinner"
-import type { UploadReturnType } from "../image"
+import * as React from 'react'
+import { NodeViewWrapper, type NodeViewProps } from '@tiptap/react'
+import type { ElementDimensions } from '../hooks/use-drag-resize'
+import { useDragResize } from '../hooks/use-drag-resize'
+import { ResizeHandle } from './resize-handle'
+import { cn } from '@/lib/utils'
+import { Controlled as ControlledZoom } from 'react-medium-image-zoom'
+import { ActionButton, ActionWrapper, ImageActions } from './image-actions'
+import { useImageActions } from '../hooks/use-image-actions'
+import { blobUrlToBase64, randomId } from '../../../utils'
+import { Info, Trash2 } from 'lucide-react'
+import { ImageOverlay } from './image-overlay'
+import { Spinner } from '../../../components/spinner'
+import type { UploadReturnType } from '../image'
const MAX_HEIGHT = 600
const MIN_HEIGHT = 120
@@ -27,26 +27,21 @@ interface ImageState {
}
const normalizeUploadResponse = (res: UploadReturnType) => ({
- src: typeof res === "string" ? res : res.src,
- id: typeof res === "string" ? randomId() : res.id,
+ src: typeof res === 'string' ? res : res.src,
+ id: typeof res === 'string' ? randomId() : res.id
})
export const ImageViewBlock: React.FC<NodeViewProps> = ({
editor,
node,
selected,
- updateAttributes,
+ updateAttributes
}) => {
- const {
- src: initialSrc,
- width: initialWidth,
- height: initialHeight,
- fileName,
- } = node.attrs
+ const { src: initialSrc, width: initialWidth, height: initialHeight, fileName } = node.attrs
const uploadAttemptedRef = React.useRef(false)
const initSrc = React.useMemo(() => {
- if (typeof initialSrc === "string") {
+ if (typeof initialSrc === 'string') {
return initialSrc
}
return initialSrc.src
@@ -58,13 +53,11 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
imageLoaded: false,
isZoomed: false,
error: false,
- naturalSize: { width: initialWidth, height: initialHeight },
+ naturalSize: { width: initialWidth, height: initialHeight }
})
const containerRef = React.useRef<HTMLDivElement>(null)
- const [activeResizeHandle, setActiveResizeHandle] = React.useState<
- "left" | "right" | null
- >(null)
+ const [activeResizeHandle, setActiveResizeHandle] = React.useState<'left' | 'right' | null>(null)
const onDimensionsChange = React.useCallback(
({ width, height }: ElementDimensions) => {
@@ -73,44 +66,32 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
[updateAttributes]
)
- const aspectRatio =
- imageState.naturalSize.width / imageState.naturalSize.height
+ const aspectRatio = imageState.naturalSize.width / imageState.naturalSize.height
const maxWidth = MAX_HEIGHT * aspectRatio
const containerMaxWidth = containerRef.current
- ? parseFloat(
- getComputedStyle(containerRef.current).getPropertyValue(
- "--editor-width"
- )
- )
+ ? parseFloat(getComputedStyle(containerRef.current).getPropertyValue('--editor-width'))
: Infinity
- const { isLink, onView, onDownload, onCopy, onCopyLink, onRemoveImg } =
- useImageActions({
- editor,
- node,
- src: imageState.src,
- onViewClick: (isZoomed) =>
- setImageState((prev) => ({ ...prev, isZoomed })),
- })
-
- const {
- currentWidth,
- currentHeight,
- updateDimensions,
- initiateResize,
- isResizing,
- } = useDragResize({
- initialWidth: initialWidth ?? imageState.naturalSize.width,
- initialHeight: initialHeight ?? imageState.naturalSize.height,
- contentWidth: imageState.naturalSize.width,
- contentHeight: imageState.naturalSize.height,
- gridInterval: 0.1,
- onDimensionsChange,
- minWidth: MIN_WIDTH,
- minHeight: MIN_HEIGHT,
- maxWidth: containerMaxWidth > 0 ? containerMaxWidth : maxWidth,
+ const { isLink, onView, onDownload, onCopy, onCopyLink, onRemoveImg } = useImageActions({
+ editor,
+ node,
+ src: imageState.src,
+ onViewClick: (isZoomed) => setImageState((prev) => ({ ...prev, isZoomed }))
})
+ const { currentWidth, currentHeight, updateDimensions, initiateResize, isResizing } =
+ useDragResize({
+ initialWidth: initialWidth ?? imageState.naturalSize.width,
+ initialHeight: initialHeight ?? imageState.naturalSize.height,
+ contentWidth: imageState.naturalSize.width,
+ contentHeight: imageState.naturalSize.height,
+ gridInterval: 0.1,
+ onDimensionsChange,
+ minWidth: MIN_WIDTH,
+ minHeight: MIN_HEIGHT,
+ maxWidth: containerMaxWidth > 0 ? containerMaxWidth : maxWidth
+ })
+
const shouldMerge = React.useMemo(() => currentWidth <= 180, [currentWidth])
const handleImageLoad = React.useCallback(
@@ -118,18 +99,18 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
const img = ev.target as HTMLImageElement
const newNaturalSize = {
width: img.naturalWidth,
- height: img.naturalHeight,
+ height: img.naturalHeight
}
setImageState((prev) => ({
...prev,
naturalSize: newNaturalSize,
- imageLoaded: true,
+ imageLoaded: true
}))
updateAttributes({
width: img.width || newNaturalSize.width,
height: img.height || newNaturalSize.height,
alt: img.alt,
- title: img.title,
+ title: img.title
})
if (!initialWidth) {
@@ -144,11 +125,10 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
}, [])
const handleResizeStart = React.useCallback(
- (direction: "left" | "right") =>
- (event: React.PointerEvent<HTMLDivElement>) => {
- setActiveResizeHandle(direction)
- initiateResize(direction)(event)
- },
+ (direction: 'left' | 'right') => (event: React.PointerEvent<HTMLDivElement>) => {
+ setActiveResizeHandle(direction)
+ initiateResize(direction)(event)
+ },
[initiateResize]
)
@@ -164,14 +144,12 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
React.useEffect(() => {
const handleImage = async () => {
- if (!initSrc.startsWith("blob:") || uploadAttemptedRef.current) {
+ if (!initSrc.startsWith('blob:') || uploadAttemptedRef.current) {
return
}
uploadAttemptedRef.current = true
- const imageExtension = editor.options.extensions.find(
- (ext) => ext.name === "image"
- )
+ const imageExtension = editor.options.extensions.find((ext) => ext.name === 'image')
const { uploadFn } = imageExtension?.options ?? {}
if (!uploadFn) {
@@ -197,7 +175,7 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
setImageState((prev) => ({
...prev,
...normalizedData,
- isServerUploading: false,
+ isServerUploading: false
}))
updateAttributes(normalizedData)
@@ -205,7 +183,7 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
setImageState((prev) => ({
...prev,
error: true,
- isServerUploading: false,
+ isServerUploading: false
}))
}
}
@@ -225,17 +203,13 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
maxWidth: `min(${maxWidth}px, 100%)`,
width: currentWidth,
maxHeight: MAX_HEIGHT,
- aspectRatio: `${imageState.naturalSize.width} / ${imageState.naturalSize.height}`,
+ aspectRatio: `${imageState.naturalSize.width} / ${imageState.naturalSize.height}`
}}
>
<div
- className={cn(
- "relative flex h-full cursor-default flex-col items-center gap-2 rounded",
- {
- "outline outline-2 outline-offset-1 outline-primary":
- selected || isResizing,
- }
- )}
+ className={cn('relative flex h-full cursor-default flex-col items-center gap-2 rounded', {
+ 'outline outline-2 outline-offset-1 outline-primary': selected || isResizing
+ })}
>
<div className="h-full contain-paint">
<div className="relative h-full">
@@ -248,37 +222,30 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
{imageState.error && (
<div className="absolute inset-0 flex flex-col items-center justify-center">
<Info className="size-8 text-destructive" />
- <p className="mt-2 text-sm text-muted-foreground">
- Failed to load image
- </p>
+ <p className="mt-2 text-sm text-muted-foreground">Failed to load image</p>
</div>
)}
<ControlledZoom
isZoomed={imageState.isZoomed}
- onZoomChange={() =>
- setImageState((prev) => ({ ...prev, isZoomed: false }))
- }
+ onZoomChange={() => setImageState((prev) => ({ ...prev, isZoomed: false }))}
>
<img
- className={cn(
- "h-auto rounded-mdobject-contain transition-shadow",
- {
- "opacity-0": !imageState.imageLoaded || imageState.error,
- }
- )}
+ className={cn('h-auto rounded-mdobject-contain transition-shadow', {
+ 'opacity-0': !imageState.imageLoaded || imageState.error
+ })}
style={{
maxWidth: `min(100%, ${maxWidth}px)`,
minWidth: `${MIN_WIDTH}px`,
- maxHeight: MAX_HEIGHT,
+ maxHeight: MAX_HEIGHT
}}
width={currentWidth}
height={currentHeight}
src={imageState.src}
onError={handleImageError}
onLoad={handleImageLoad}
- alt={node.attrs.alt || ""}
- title={node.attrs.title || ""}
+ alt={node.attrs.alt || ''}
+ title={node.attrs.title || ''}
id={node.attrs.id}
/>
</ControlledZoom>
@@ -292,18 +259,18 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
!imageState.isServerUploading && (
<>
<ResizeHandle
- onPointerDown={handleResizeStart("left")}
- className={cn("left-1", {
- hidden: isResizing && activeResizeHandle === "right",
+ onPointerDown={handleResizeStart('left')}
+ className={cn('left-1', {
+ hidden: isResizing && activeResizeHandle === 'right'
})}
- isResizing={isResizing && activeResizeHandle === "left"}
+ isResizing={isResizing && activeResizeHandle === 'left'}
/>
<ResizeHandle
- onPointerDown={handleResizeStart("right")}
- className={cn("right-1", {
- hidden: isResizing && activeResizeHandle === "left",
+ onPointerDown={handleResizeStart('right')}
+ className={cn('right-1', {
+ hidden: isResizing && activeResizeHandle === 'left'
})}
- isResizing={isResizing && activeResizeHandle === "right"}
+ isResizing={isResizing && activeResizeHandle === 'right'}
/>
</>
)}
@@ -319,18 +286,16 @@ export const ImageViewBlock: React.FC<NodeViewProps> = ({
</ActionWrapper>
)}
- {!isResizing &&
- !imageState.error &&
- !imageState.isServerUploading && (
- <ImageActions
- shouldMerge={shouldMerge}
- isLink={isLink}
- onView={onView}
- onDownload={onDownload}
- onCopy={onCopy}
- onCopyLink={onCopyLink}
- />
- )}
+ {!isResizing && !imageState.error && !imageState.isServerUploading && (
+ <ImageActions
+ shouldMerge={shouldMerge}
+ isLink={isLink}
+ onView={onView}
+ onDownload={onDownload}
+ onCopy={onCopy}
+ onCopyLink={onCopyLink}
+ />
+ )}
</div>
</div>
</NodeViewWrapper>
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/resize-handle.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/resize-handle.tsx
index 312a8d7e..682c5a2a 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/resize-handle.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/components/resize-handle.tsx
@@ -1,5 +1,5 @@
-import * as React from "react"
-import { cn } from "@/lib/utils"
+import * as React from 'react'
+import { cn } from '@/lib/utils'
interface ResizeProps extends React.HTMLAttributes<HTMLDivElement> {
isResizing?: boolean
@@ -10,13 +10,13 @@ export const ResizeHandle = React.forwardRef<HTMLDivElement, ResizeProps>(
return (
<div
className={cn(
- "absolute top-1/2 h-10 max-h-full w-1.5 -translate-y-1/2 transform cursor-col-resize rounded border-solid border-[var(--mt-transparent-foreground)] bg-[var(--mt-bg-secondary)] p-px transition-all",
- "opacity-0 [backdrop-filter:saturate(1.8)_blur(20px)]",
+ 'absolute top-1/2 h-10 max-h-full w-1.5 -translate-y-1/2 transform cursor-col-resize rounded border-solid border-[var(--mt-transparent-foreground)] bg-[var(--mt-bg-secondary)] p-px transition-all',
+ 'opacity-0 [backdrop-filter:saturate(1.8)_blur(20px)]',
{
- "opacity-80": isResizing,
- "group-hover/node-image:opacity-80": !isResizing,
+ 'opacity-80': isResizing,
+ 'group-hover/node-image:opacity-80': !isResizing
},
- "before:absolute before:inset-y-0 before:-left-1 before:-right-1",
+ 'before:absolute before:inset-y-0 before:-left-1 before:-right-1',
className
)}
ref={ref}
@@ -26,4 +26,4 @@ export const ResizeHandle = React.forwardRef<HTMLDivElement, ResizeProps>(
}
)
-ResizeHandle.displayName = "ResizeHandle"
+ResizeHandle.displayName = 'ResizeHandle'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/hooks/use-drag-resize.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/hooks/use-drag-resize.ts
index b671d540..b65120d2 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/hooks/use-drag-resize.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/hooks/use-drag-resize.ts
@@ -1,6 +1,6 @@
-import { useState, useCallback, useEffect } from "react"
+import { useState, useCallback, useEffect } from 'react'
-type ResizeDirection = "left" | "right"
+type ResizeDirection = 'left' | 'right'
export type ElementDimensions = { width: number; height: number }
type HookParams = {
@@ -24,32 +24,24 @@ export function useDragResize({
minWidth,
minHeight,
maxWidth,
- onDimensionsChange,
+ onDimensionsChange
}: HookParams) {
const [dimensions, updateDimensions] = useState<ElementDimensions>({
width: Math.max(initialWidth ?? minWidth, minWidth),
- height: Math.max(initialHeight ?? minHeight, minHeight),
+ height: Math.max(initialHeight ?? minHeight, minHeight)
})
const [boundaryWidth, setBoundaryWidth] = useState(Infinity)
const [resizeOrigin, setResizeOrigin] = useState(0)
const [initialDimensions, setInitialDimensions] = useState(dimensions)
- const [resizeDirection, setResizeDirection] = useState<
- ResizeDirection | undefined
- >()
+ const [resizeDirection, setResizeDirection] = useState<ResizeDirection | undefined>()
const widthConstraint = useCallback(
(proposedWidth: number, maxAllowedWidth: number) => {
const effectiveMinWidth = Math.max(
minWidth,
- Math.min(
- contentWidth ?? minWidth,
- (gridInterval / 100) * maxAllowedWidth
- )
- )
- return Math.min(
- maxAllowedWidth,
- Math.max(proposedWidth, effectiveMinWidth)
+ Math.min(contentWidth ?? minWidth, (gridInterval / 100) * maxAllowedWidth)
)
+ return Math.min(maxAllowedWidth, Math.max(proposedWidth, effectiveMinWidth))
},
[gridInterval, contentWidth, minWidth]
)
@@ -58,25 +50,19 @@ export function useDragResize({
(event: PointerEvent) => {
event.preventDefault()
const movementDelta =
- (resizeDirection === "left"
- ? resizeOrigin - event.pageX
- : event.pageX - resizeOrigin) * 2
+ (resizeDirection === 'left' ? resizeOrigin - event.pageX : event.pageX - resizeOrigin) * 2
const gridUnitWidth = (gridInterval / 100) * boundaryWidth
const proposedWidth = initialDimensions.width + movementDelta
- const alignedWidth =
- Math.round(proposedWidth / gridUnitWidth) * gridUnitWidth
+ const alignedWidth = Math.round(proposedWidth / gridUnitWidth) * gridUnitWidth
const finalWidth = widthConstraint(alignedWidth, boundaryWidth)
- const aspectRatio =
- contentHeight && contentWidth ? contentHeight / contentWidth : 1
+ const aspectRatio = contentHeight && contentWidth ? contentHeight / contentWidth : 1
updateDimensions({
width: Math.max(finalWidth, minWidth),
height: Math.max(
- contentWidth
- ? finalWidth * aspectRatio
- : (contentHeight ?? minHeight),
+ contentWidth ? finalWidth * aspectRatio : (contentHeight ?? minHeight),
minHeight
- ),
+ )
})
},
[
@@ -89,7 +75,7 @@ export function useDragResize({
contentWidth,
initialDimensions.width,
minWidth,
- minHeight,
+ minHeight
]
)
@@ -107,12 +93,12 @@ export function useDragResize({
const handleKeydown = useCallback(
(event: KeyboardEvent) => {
- if (event.key === "Escape") {
+ if (event.key === 'Escape') {
event.preventDefault()
event.stopPropagation()
updateDimensions({
width: Math.max(initialDimensions.width, minWidth),
- height: Math.max(initialDimensions.height, minHeight),
+ height: Math.max(initialDimensions.height, minHeight)
})
setResizeDirection(undefined)
}
@@ -121,43 +107,32 @@ export function useDragResize({
)
const initiateResize = useCallback(
- (direction: ResizeDirection) =>
- (event: React.PointerEvent<HTMLDivElement>) => {
- event.preventDefault()
- event.stopPropagation()
+ (direction: ResizeDirection) => (event: React.PointerEvent<HTMLDivElement>) => {
+ event.preventDefault()
+ event.stopPropagation()
- setBoundaryWidth(maxWidth)
- setInitialDimensions({
- width: Math.max(
- widthConstraint(dimensions.width, maxWidth),
- minWidth
- ),
- height: Math.max(dimensions.height, minHeight),
- })
- setResizeOrigin(event.pageX)
- setResizeDirection(direction)
- },
- [
- maxWidth,
- widthConstraint,
- dimensions.width,
- dimensions.height,
- minWidth,
- minHeight,
- ]
+ setBoundaryWidth(maxWidth)
+ setInitialDimensions({
+ width: Math.max(widthConstraint(dimensions.width, maxWidth), minWidth),
+ height: Math.max(dimensions.height, minHeight)
+ })
+ setResizeOrigin(event.pageX)
+ setResizeDirection(direction)
+ },
+ [maxWidth, widthConstraint, dimensions.width, dimensions.height, minWidth, minHeight]
)
//@ts-ignore
useEffect(() => {
if (resizeDirection) {
- document.addEventListener("keydown", handleKeydown)
- document.addEventListener("pointermove", handlePointerMove)
- document.addEventListener("pointerup", handlePointerUp)
+ document.addEventListener('keydown', handleKeydown)
+ document.addEventListener('pointermove', handlePointerMove)
+ document.addEventListener('pointerup', handlePointerUp)
return () => {
- document.removeEventListener("keydown", handleKeydown)
- document.removeEventListener("pointermove", handlePointerMove)
- document.removeEventListener("pointerup", handlePointerUp)
+ document.removeEventListener('keydown', handleKeydown)
+ document.removeEventListener('pointermove', handlePointerMove)
+ document.removeEventListener('pointerup', handlePointerUp)
}
}
}, [resizeDirection, handleKeydown, handlePointerMove, handlePointerUp])
@@ -167,6 +142,6 @@ export function useDragResize({
isResizing: !!resizeDirection,
updateDimensions,
currentWidth: Math.max(dimensions.width, minWidth),
- currentHeight: Math.max(dimensions.height, minHeight),
+ currentHeight: Math.max(dimensions.height, minHeight)
}
}
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/hooks/use-image-actions.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/hooks/use-image-actions.ts
index b8e1c51f..790a5f05 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/hooks/use-image-actions.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/hooks/use-image-actions.ts
@@ -1,7 +1,7 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { Node } from "@tiptap/pm/model"
-import { isUrl } from "../../../utils"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { Node } from '@tiptap/pm/model'
+import { isUrl } from '../../../utils'
interface UseImageActionsProps {
editor: Editor
@@ -18,12 +18,7 @@ export type ImageActionHandlers = {
onRemoveImg?: () => void
}
-export const useImageActions = ({
- editor,
- node,
- src,
- onViewClick,
-}: UseImageActionsProps) => {
+export const useImageActions = ({ editor, node, src, onViewClick }: UseImageActionsProps) => {
const isLink = React.useMemo(() => isUrl(src), [src])
const onView = React.useCallback(() => {
@@ -47,7 +42,7 @@ export const useImageActions = ({
const { selection } = tr
const nodeAtSelection = tr.doc.nodeAt(selection.from)
- if (nodeAtSelection && nodeAtSelection.type.name === "image") {
+ if (nodeAtSelection && nodeAtSelection.type.name === 'image') {
if (dispatch) {
tr.deleteSelection()
return true
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/image.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/image.ts
index 6347ac10..669c724f 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/image.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/image.ts
@@ -1,18 +1,13 @@
-import type { ImageOptions } from "@tiptap/extension-image"
-import { Image as TiptapImage } from "@tiptap/extension-image"
-import type { Editor } from "@tiptap/react"
-import { ReactNodeViewRenderer } from "@tiptap/react"
-import { ImageViewBlock } from "./components/image-view-block"
-import {
- filterFiles,
- randomId,
- type FileError,
- type FileValidationOptions,
-} from "../../utils"
-import { ReplaceStep } from "@tiptap/pm/transform"
-import type { Attrs } from "@tiptap/pm/model"
-
-type ImageAction = "download" | "copyImage" | "copyLink"
+import type { ImageOptions } from '@tiptap/extension-image'
+import { Image as TiptapImage } from '@tiptap/extension-image'
+import type { Editor } from '@tiptap/react'
+import { ReactNodeViewRenderer } from '@tiptap/react'
+import { ImageViewBlock } from './components/image-view-block'
+import { filterFiles, randomId, type FileError, type FileValidationOptions } from '../../utils'
+import { ReplaceStep } from '@tiptap/pm/transform'
+import type { Attrs } from '@tiptap/pm/model'
+
+type ImageAction = 'download' | 'copyImage' | 'copyLink'
interface DownloadImageCommandProps {
src: string
@@ -30,35 +25,22 @@ export type UploadReturnType =
src: string
}
-interface CustomImageOptions
- extends ImageOptions,
- Omit<FileValidationOptions, "allowBase64"> {
+interface CustomImageOptions extends ImageOptions, Omit<FileValidationOptions, 'allowBase64'> {
uploadFn?: (file: File, editor: Editor) => Promise<UploadReturnType>
onImageRemoved?: (props: Attrs) => void
onActionSuccess?: (props: ImageActionProps) => void
onActionError?: (error: Error, props: ImageActionProps) => void
- downloadImage?: (
- props: ImageActionProps,
- options: CustomImageOptions
- ) => Promise<void>
- copyImage?: (
- props: ImageActionProps,
- options: CustomImageOptions
- ) => Promise<void>
- copyLink?: (
- props: ImageActionProps,
- options: CustomImageOptions
- ) => Promise<void>
+ downloadImage?: (props: ImageActionProps, options: CustomImageOptions) => Promise<void>
+ copyImage?: (props: ImageActionProps, options: CustomImageOptions) => Promise<void>
+ copyLink?: (props: ImageActionProps, options: CustomImageOptions) => Promise<void>
onValidationError?: (errors: FileError[]) => void
onToggle?: (editor: Editor, files: File[], pos: number) => void
}
-declare module "@tiptap/react" {
+declare module '@tiptap/react' {
interface Commands<ReturnType> {
setImages: {
- setImages: (
- attrs: { src: string | File; alt?: string; title?: string }[]
- ) => ReturnType
+ setImages: (attrs: { src: string | File; alt?: string; title?: string }[]) => ReturnType
}
downloadImage: {
downloadImage: (attrs: DownloadImageCommandProps) => ReturnType
@@ -80,14 +62,14 @@ const handleError = (
props: ImageActionProps,
errorHandler?: (error: Error, props: ImageActionProps) => void
): void => {
- const typedError = error instanceof Error ? error : new Error("Unknown error")
+ const typedError = error instanceof Error ? error : new Error('Unknown error')
errorHandler?.(typedError, props)
}
const handleDataUrl = (src: string): { blob: Blob; extension: string } => {
- const [header, base64Data] = src.split(",")
- const mimeType = header.split(":")[1].split(";")[0]
- const extension = mimeType.split("/")[1]
+ const [header, base64Data] = src.split(',')
+ const mimeType = header.split(':')[1].split(';')[0]
+ const extension = mimeType.split('/')[1]
const byteCharacters = atob(base64Data)
const byteArray = new Uint8Array(byteCharacters.length)
for (let i = 0; i < byteCharacters.length; i++) {
@@ -97,29 +79,21 @@ const handleDataUrl = (src: string): { blob: Blob; extension: string } => {
return { blob, extension }
}
-const handleImageUrl = async (
- src: string
-): Promise<{ blob: Blob; extension: string }> => {
+const handleImageUrl = async (src: string): Promise<{ blob: Blob; extension: string }> => {
const response = await fetch(src)
- if (!response.ok) throw new Error("Failed to fetch image")
+ if (!response.ok) throw new Error('Failed to fetch image')
const blob = await response.blob()
const extension = blob.type.split(/\/|\+/)[1]
return { blob, extension }
}
-const fetchImageBlob = async (
- src: string
-): Promise<{ blob: Blob; extension: string }> => {
- return src.startsWith("data:") ? handleDataUrl(src) : handleImageUrl(src)
+const fetchImageBlob = async (src: string): Promise<{ blob: Blob; extension: string }> => {
+ return src.startsWith('data:') ? handleDataUrl(src) : handleImageUrl(src)
}
-const saveImage = async (
- blob: Blob,
- name: string,
- extension: string
-): Promise<void> => {
+const saveImage = async (blob: Blob, name: string, extension: string): Promise<void> => {
const imageURL = URL.createObjectURL(blob)
- const link = document.createElement("a")
+ const link = document.createElement('a')
link.href = imageURL
link.download = `${name}.${extension}`
document.body.appendChild(link)
@@ -133,42 +107,36 @@ const downloadImage = async (
options: CustomImageOptions
): Promise<void> => {
const { src, alt } = props
- const potentialName = alt || "image"
+ const potentialName = alt || 'image'
try {
const { blob, extension } = await fetchImageBlob(src)
await saveImage(blob, potentialName, extension)
- options.onActionSuccess?.({ ...props, action: "download" })
+ options.onActionSuccess?.({ ...props, action: 'download' })
} catch (error) {
- handleError(error, { ...props, action: "download" }, options.onActionError)
+ handleError(error, { ...props, action: 'download' }, options.onActionError)
}
}
-const copyImage = async (
- props: ImageActionProps,
- options: CustomImageOptions
-): Promise<void> => {
+const copyImage = async (props: ImageActionProps, options: CustomImageOptions): Promise<void> => {
const { src } = props
try {
const res = await fetch(src)
const blob = await res.blob()
await navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })])
- options.onActionSuccess?.({ ...props, action: "copyImage" })
+ options.onActionSuccess?.({ ...props, action: 'copyImage' })
} catch (error) {
- handleError(error, { ...props, action: "copyImage" }, options.onActionError)
+ handleError(error, { ...props, action: 'copyImage' }, options.onActionError)
}
}
-const copyLink = async (
- props: ImageActionProps,
- options: CustomImageOptions
-): Promise<void> => {
+const copyLink = async (props: ImageActionProps, options: CustomImageOptions): Promise<void> => {
const { src } = props
try {
await navigator.clipboard.writeText(src)
- options.onActionSuccess?.({ ...props, action: "copyLink" })
+ options.onActionSuccess?.({ ...props, action: 'copyLink' })
} catch (error) {
- handleError(error, { ...props, action: "copyLink" }, options.onActionError)
+ handleError(error, { ...props, action: 'copyLink' }, options.onActionError)
}
}
@@ -184,33 +152,33 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
onToggle: undefined,
downloadImage: undefined,
copyImage: undefined,
- copyLink: undefined,
+ copyLink: undefined
}
},
addAttributes() {
return {
src: {
- default: null,
+ default: null
},
alt: {
- default: null,
+ default: null
},
title: {
- default: null,
+ default: null
},
id: {
- default: null,
+ default: null
},
width: {
- default: null,
+ default: null
},
height: {
- default: null,
+ default: null
},
fileName: {
- default: null,
- },
+ default: null
+ }
}
},
@@ -222,7 +190,7 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
const [validImages, errors] = filterFiles(attrs, {
allowedMimeTypes: this.options.allowedMimeTypes,
maxFileSize: this.options.maxFileSize,
- allowBase64: this.options.allowBase64,
+ allowBase64: this.options.allowBase64
})
if (errors.length > 0 && this.options.onValidationError) {
@@ -243,8 +211,8 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
src: blobUrl,
alt: image.alt,
title: image.title,
- fileName: image.src.name,
- },
+ fileName: image.src.name
+ }
}
} else {
return {
@@ -254,8 +222,8 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
src: image.src,
alt: image.alt,
title: image.title,
- fileName: null,
- },
+ fileName: null
+ }
}
}
})
@@ -267,28 +235,28 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
downloadImage: (attrs) => () => {
const downloadFunc = this.options.downloadImage || downloadImage
- void downloadFunc({ ...attrs, action: "download" }, this.options)
+ void downloadFunc({ ...attrs, action: 'download' }, this.options)
return true
},
copyImage: (attrs) => () => {
const copyImageFunc = this.options.copyImage || copyImage
- void copyImageFunc({ ...attrs, action: "copyImage" }, this.options)
+ void copyImageFunc({ ...attrs, action: 'copyImage' }, this.options)
return true
},
copyLink: (attrs) => () => {
const copyLinkFunc = this.options.copyLink || copyLink
- void copyLinkFunc({ ...attrs, action: "copyLink" }, this.options)
+ void copyLinkFunc({ ...attrs, action: 'copyLink' }, this.options)
return true
},
toggleImage:
() =>
({ editor }) => {
- const input = document.createElement("input")
- input.type = "file"
- input.accept = this.options.allowedMimeTypes.join(",")
+ const input = document.createElement('input')
+ input.type = 'file'
+ input.accept = this.options.allowedMimeTypes.join(',')
input.onchange = () => {
const files = input.files
if (!files) return
@@ -296,7 +264,7 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
const [validImages, errors] = filterFiles(Array.from(files), {
allowedMimeTypes: this.options.allowedMimeTypes,
maxFileSize: this.options.maxFileSize,
- allowBase64: this.options.allowBase64,
+ allowBase64: this.options.allowBase64
})
if (errors.length > 0 && this.options.onValidationError) {
@@ -307,11 +275,7 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
if (validImages.length === 0) return false
if (this.options.onToggle) {
- this.options.onToggle(
- editor,
- validImages,
- editor.state.selection.from
- )
+ this.options.onToggle(editor, validImages, editor.state.selection.from)
}
return false
@@ -319,7 +283,7 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
input.click()
return true
- },
+ }
}
},
@@ -329,10 +293,10 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
const deletedPages = transaction.before.content.cut(step.from, step.to)
deletedPages.forEach((node) => {
- if (node.type.name === "image") {
+ if (node.type.name === 'image') {
const attrs = node.attrs
- if (attrs.src.startsWith("blob:")) {
+ if (attrs.src.startsWith('blob:')) {
URL.revokeObjectURL(attrs.src)
}
@@ -345,7 +309,7 @@ export const Image = TiptapImage.extend<CustomImageOptions>({
addNodeView() {
return ReactNodeViewRenderer(ImageViewBlock, {
- className: "block-node",
+ className: 'block-node'
})
- },
+ }
})
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/index.ts
index 61769c6d..556dbfdf 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/image/index.ts
@@ -1 +1 @@
-export * from "./image"
+export * from './image'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/index.ts
index 0cbab761..6906d4e8 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/index.ts
@@ -1,9 +1,9 @@
-export * from "./code-block-lowlight"
-export * from "./color"
-export * from "./horizontal-rule"
-export * from "./image"
-export * from "./link"
-export * from "./selection"
-export * from "./unset-all-marks"
-export * from "./reset-marks-on-enter"
-export * from "./file-handler"
+export * from './code-block-lowlight'
+export * from './color'
+export * from './horizontal-rule'
+export * from './image'
+export * from './link'
+export * from './selection'
+export * from './unset-all-marks'
+export * from './reset-marks-on-enter'
+export * from './file-handler'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/link/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/link/index.ts
index 6ada303c..6bbafd20 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/link/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/link/index.ts
@@ -1 +1 @@
-export * from "./link"
+export * from './link'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/link/link.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/link/link.ts
index 82fd2646..d3a600f1 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/link/link.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/link/link.ts
@@ -1,8 +1,8 @@
-import { mergeAttributes } from "@tiptap/react"
-import TiptapLink from "@tiptap/extension-link"
-import type { EditorView } from "@tiptap/pm/view"
-import { getMarkRange } from "@tiptap/react"
-import { Plugin, TextSelection } from "@tiptap/pm/state"
+import { mergeAttributes } from '@tiptap/react'
+import TiptapLink from '@tiptap/extension-link'
+import type { EditorView } from '@tiptap/pm/view'
+import { getMarkRange } from '@tiptap/react'
+import { Plugin, TextSelection } from '@tiptap/pm/state'
export const Link = TiptapLink.extend({
/*
@@ -19,17 +19,13 @@ export const Link = TiptapLink.extend({
parseHTML() {
return [
{
- tag: 'a[href]:not([data-type="button"]):not([href *= "javascript:" i])',
- },
+ tag: 'a[href]:not([data-type="button"]):not([href *= "javascript:" i])'
+ }
]
},
renderHTML({ HTMLAttributes }) {
- return [
- "a",
- mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
- 0,
- ]
+ return ['a', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]
},
addOptions() {
@@ -37,8 +33,8 @@ export const Link = TiptapLink.extend({
...this.parent?.(),
openOnClick: false,
HTMLAttributes: {
- class: "link",
- },
+ class: 'link'
+ }
}
},
@@ -56,7 +52,7 @@ export const Link = TiptapLink.extend({
* Handles the 'Escape' key press when there's a selection within the link.
* This will move the cursor to the end of the link.
*/
- if (event.key === "Escape" && selection.empty !== true) {
+ if (event.key === 'Escape' && selection.empty !== true) {
editor.commands.focus(selection.to, { scrollIntoView: false })
}
@@ -87,11 +83,11 @@ export const Link = TiptapLink.extend({
const transaction = tr.setSelection(new TextSelection($start, $end))
view.dispatch(transaction)
- },
- },
- }),
+ }
+ }
+ })
]
- },
+ }
})
export default Link
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/reset-marks-on-enter/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/reset-marks-on-enter/index.ts
index 4c06c8d8..f514cdd1 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/reset-marks-on-enter/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/reset-marks-on-enter/index.ts
@@ -1 +1 @@
-export * from "./reset-marks-on-enter"
+export * from './reset-marks-on-enter'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/reset-marks-on-enter/reset-marks-on-enter.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/reset-marks-on-enter/reset-marks-on-enter.ts
index 7daee524..ecbbea64 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/reset-marks-on-enter/reset-marks-on-enter.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/reset-marks-on-enter/reset-marks-on-enter.ts
@@ -1,17 +1,17 @@
-import { Extension } from "@tiptap/react"
+import { Extension } from '@tiptap/react'
export const ResetMarksOnEnter = Extension.create({
- name: "resetMarksOnEnter",
+ name: 'resetMarksOnEnter',
addKeyboardShortcuts() {
return {
Enter: ({ editor }) => {
if (
- editor.isActive("bold") ||
- editor.isActive("italic") ||
- editor.isActive("strike") ||
- editor.isActive("underline") ||
- editor.isActive("code")
+ editor.isActive('bold') ||
+ editor.isActive('italic') ||
+ editor.isActive('strike') ||
+ editor.isActive('underline') ||
+ editor.isActive('code')
) {
editor.commands.splitBlock({ keepMarks: false })
@@ -19,7 +19,7 @@ export const ResetMarksOnEnter = Extension.create({
}
return false
- },
+ }
}
- },
+ }
})
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/selection/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/selection/index.ts
index c8f61024..75df11a6 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/selection/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/selection/index.ts
@@ -1 +1 @@
-export * from "./selection"
+export * from './selection'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/selection/selection.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/selection/selection.ts
index 872882c7..9a0d6c57 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/selection/selection.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/selection/selection.ts
@@ -1,16 +1,16 @@
-import { Extension } from "@tiptap/react"
-import { Plugin, PluginKey } from "@tiptap/pm/state"
-import { Decoration, DecorationSet } from "@tiptap/pm/view"
+import { Extension } from '@tiptap/react'
+import { Plugin, PluginKey } from '@tiptap/pm/state'
+import { Decoration, DecorationSet } from '@tiptap/pm/view'
export const Selection = Extension.create({
- name: "selection",
+ name: 'selection',
addProseMirrorPlugins() {
const { editor } = this
return [
new Plugin({
- key: new PluginKey("selection"),
+ key: new PluginKey('selection'),
props: {
decorations(state) {
if (state.selection.empty) {
@@ -27,14 +27,14 @@ export const Selection = Extension.create({
return DecorationSet.create(state.doc, [
Decoration.inline(state.selection.from, state.selection.to, {
- class: "selection",
- }),
+ class: 'selection'
+ })
])
- },
- },
- }),
+ }
+ }
+ })
]
- },
+ }
})
export default Selection
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/unset-all-marks/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/unset-all-marks/index.ts
index 4abdbe86..50d26fbc 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/unset-all-marks/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/unset-all-marks/index.ts
@@ -1 +1 @@
-export * from "./unset-all-marks"
+export * from './unset-all-marks'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/unset-all-marks/unset-all-marks.ts b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/unset-all-marks/unset-all-marks.ts
index 10dcbb23..850faafb 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/extensions/unset-all-marks/unset-all-marks.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/extensions/unset-all-marks/unset-all-marks.ts
@@ -1,9 +1,9 @@
-import { Extension } from "@tiptap/react"
+import { Extension } from '@tiptap/react'
export const UnsetAllMarks = Extension.create({
addKeyboardShortcuts() {
return {
- "Mod-\\": () => this.editor.commands.unsetAllMarks(),
+ 'Mod-\\': () => this.editor.commands.unsetAllMarks()
}
- },
+ }
})
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-container-size.ts b/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-container-size.ts
index 8b50fa5a..4fa3d695 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-container-size.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-container-size.ts
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from "react"
+import { useState, useEffect, useCallback } from 'react'
const DEFAULT_RECT: DOMRect = {
top: 0,
@@ -9,13 +9,11 @@ const DEFAULT_RECT: DOMRect = {
y: 0,
width: 0,
height: 0,
- toJSON: () => "{}",
+ toJSON: () => '{}'
}
export function useContainerSize(element: HTMLElement | null): DOMRect {
- const [size, setSize] = useState<DOMRect>(
- () => element?.getBoundingClientRect() ?? DEFAULT_RECT
- )
+ const [size, setSize] = useState<DOMRect>(() => element?.getBoundingClientRect() ?? DEFAULT_RECT)
const handleResize = useCallback(() => {
if (!element) return
@@ -41,13 +39,13 @@ export function useContainerSize(element: HTMLElement | null): DOMRect {
const resizeObserver = new ResizeObserver(handleResize)
resizeObserver.observe(element)
- window.addEventListener("click", handleResize)
- window.addEventListener("resize", handleResize)
+ window.addEventListener('click', handleResize)
+ window.addEventListener('resize', handleResize)
return () => {
resizeObserver.disconnect()
- window.removeEventListener("click", handleResize)
- window.removeEventListener("resize", handleResize)
+ window.removeEventListener('click', handleResize)
+ window.removeEventListener('resize', handleResize)
}
}, [element, handleResize])
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-minimal-tiptap.ts b/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-minimal-tiptap.ts
index 1f003ad3..5d18888e 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-minimal-tiptap.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-minimal-tiptap.ts
@@ -1,12 +1,12 @@
-import * as React from "react"
-import type { Editor } from "@tiptap/react"
-import type { Content, UseEditorOptions } from "@tiptap/react"
-import { StarterKit } from "@tiptap/starter-kit"
-import { useEditor } from "@tiptap/react"
-import { Typography } from "@tiptap/extension-typography"
-import { Placeholder } from "@tiptap/extension-placeholder"
-import { Underline } from "@tiptap/extension-underline"
-import { TextStyle } from "@tiptap/extension-text-style"
+import * as React from 'react'
+import type { Editor } from '@tiptap/react'
+import type { Content, UseEditorOptions } from '@tiptap/react'
+import { StarterKit } from '@tiptap/starter-kit'
+import { useEditor } from '@tiptap/react'
+import { Typography } from '@tiptap/extension-typography'
+import { Placeholder } from '@tiptap/extension-placeholder'
+import { Underline } from '@tiptap/extension-underline'
+import { TextStyle } from '@tiptap/extension-text-style'
import {
Link,
Image,
@@ -16,16 +16,16 @@ import {
Color,
UnsetAllMarks,
ResetMarksOnEnter,
- FileHandler,
-} from "../extensions"
-import { cn } from "@/lib/utils"
-import { fileToBase64, getOutput, randomId } from "../utils"
-import { useThrottle } from "./use-throttle"
-import { toast } from "sonner"
+ FileHandler
+} from '../extensions'
+import { cn } from '@/lib/utils'
+import { fileToBase64, getOutput, randomId } from '../utils'
+import { useThrottle } from './use-throttle'
+import { toast } from 'sonner'
export interface UseMinimalTiptapEditorProps extends UseEditorOptions {
value?: Content
- output?: "html" | "json" | "text"
+ output?: 'html' | 'json' | 'text'
placeholder?: string
editorClassName?: string
throttleDelay?: number
@@ -48,7 +48,7 @@ async function fakeuploader(file: File): Promise<string> {
const createExtensions = ({
placeholder,
- uploader,
+ uploader
}: {
placeholder: string
uploader?: (file: File) => Promise<string>
@@ -56,18 +56,18 @@ const createExtensions = ({
StarterKit.configure({
horizontalRule: false,
codeBlock: false,
- paragraph: { HTMLAttributes: { class: "text-node" } },
- heading: { HTMLAttributes: { class: "heading-node" } },
- blockquote: { HTMLAttributes: { class: "block-node" } },
- bulletList: { HTMLAttributes: { class: "list-node" } },
- orderedList: { HTMLAttributes: { class: "list-node" } },
- code: { HTMLAttributes: { class: "inline", spellcheck: "false" } },
- dropcursor: { width: 2, class: "ProseMirror-dropcursor border" },
+ paragraph: { HTMLAttributes: { class: 'text-node' } },
+ heading: { HTMLAttributes: { class: 'heading-node' } },
+ blockquote: { HTMLAttributes: { class: 'block-node' } },
+ bulletList: { HTMLAttributes: { class: 'list-node' } },
+ orderedList: { HTMLAttributes: { class: 'list-node' } },
+ code: { HTMLAttributes: { class: 'inline', spellcheck: 'false' } },
+ dropcursor: { width: 2, class: 'ProseMirror-dropcursor border' }
}),
Link,
Underline,
Image.configure({
- allowedMimeTypes: ["image/*"],
+ allowedMimeTypes: ['image/*'],
maxFileSize: 5 * 1024 * 1024,
allowBase64: true,
uploadFn: async (file) => {
@@ -81,62 +81,62 @@ const createExtensions = ({
const id = randomId()
return {
- type: "image",
+ type: 'image',
attrs: {
id,
src: blobUrl,
alt: image.name,
title: image.name,
- fileName: image.name,
- },
+ fileName: image.name
+ }
}
})
)
},
onImageRemoved({ id, src }) {
- console.log("Image removed", { id, src })
+ console.log('Image removed', { id, src })
},
onValidationError(errors) {
errors.forEach((error) => {
- toast.error("Image validation error", {
- position: "bottom-right",
- description: error.reason,
+ toast.error('Image validation error', {
+ position: 'bottom-right',
+ description: error.reason
})
})
},
onActionSuccess({ action }) {
const mapping = {
- copyImage: "Copy Image",
- copyLink: "Copy Link",
- download: "Download",
+ copyImage: 'Copy Image',
+ copyLink: 'Copy Link',
+ download: 'Download'
}
toast.success(mapping[action], {
- position: "bottom-right",
- description: "Image action success",
+ position: 'bottom-right',
+ description: 'Image action success'
})
},
onActionError(error, { action }) {
const mapping = {
- copyImage: "Copy Image",
- copyLink: "Copy Link",
- download: "Download",
+ copyImage: 'Copy Image',
+ copyLink: 'Copy Link',
+ download: 'Download'
}
toast.error(`Failed to ${mapping[action]}`, {
- position: "bottom-right",
- description: error.message,
+ position: 'bottom-right',
+ description: error.message
})
- },
+ }
}),
FileHandler.configure({
allowBase64: true,
- allowedMimeTypes: ["image/*"],
+ allowedMimeTypes: ['image/*'],
maxFileSize: 5 * 1024 * 1024,
onDrop: (editor, files, pos) => {
files.forEach(async (file) => {
const src = await fileToBase64(file)
editor.commands.insertContentAt(pos, {
- type: "image",
- attrs: { src },
+ type: 'image',
+ attrs: { src }
})
})
},
@@ -144,19 +144,19 @@ const createExtensions = ({
files.forEach(async (file) => {
const src = await fileToBase64(file)
editor.commands.insertContent({
- type: "image",
- attrs: { src },
+ type: 'image',
+ attrs: { src }
})
})
},
onValidationError: (errors) => {
errors.forEach((error) => {
- toast.error("Image validation error", {
- position: "bottom-right",
- description: error.reason,
+ toast.error('Image validation error', {
+ position: 'bottom-right',
+ description: error.reason
})
})
- },
+ }
}),
Color,
TextStyle,
@@ -166,13 +166,13 @@ const createExtensions = ({
HorizontalRule,
ResetMarksOnEnter,
CodeBlockLowlight,
- Placeholder.configure({ placeholder: () => placeholder }),
+ Placeholder.configure({ placeholder: () => placeholder })
]
export const useMinimalTiptapEditor = ({
value,
- output = "json",
- placeholder = "",
+ output = 'json',
+ placeholder = '',
editorClassName,
throttleDelay = 0,
onUpdate,
@@ -180,10 +180,7 @@ export const useMinimalTiptapEditor = ({
uploader,
...props
}: UseMinimalTiptapEditorProps) => {
- const throttledSetValue = useThrottle(
- (value: Content) => onUpdate?.(value),
- throttleDelay
- )
+ const throttledSetValue = useThrottle((value: Content) => onUpdate?.(value), throttleDelay)
const handleUpdate = React.useCallback(
(editor: Editor) => throttledSetValue(getOutput(editor, output)),
@@ -208,16 +205,16 @@ export const useMinimalTiptapEditor = ({
extensions: createExtensions({ placeholder, uploader }),
editorProps: {
attributes: {
- autocomplete: "off",
- autocorrect: "off",
- autocapitalize: "off",
- class: cn("focus:outline-none", editorClassName),
- },
+ autocomplete: 'off',
+ autocorrect: 'off',
+ autocapitalize: 'off',
+ class: cn('focus:outline-none', editorClassName)
+ }
},
onUpdate: ({ editor }) => handleUpdate(editor),
onCreate: ({ editor }) => handleCreate(editor),
onBlur: ({ editor }) => handleBlur(editor),
- ...props,
+ ...props
})
return editor
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-throttle.ts b/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-throttle.ts
index 332e3f1c..f3f88fba 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-throttle.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/hooks/use-throttle.ts
@@ -1,4 +1,4 @@
-import { useRef, useCallback } from "react"
+import { useRef, useCallback } from 'react'
export function useThrottle<T extends (...args: any[]) => void>(
callback: T,
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/index.ts b/flowsint-app/src/renderer/src/components/analyses/editor/index.ts
index ce8d6544..1532aab8 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/index.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/index.ts
@@ -1 +1 @@
-export * from "./minimal-tiptap"
+export * from './minimal-tiptap'
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/minimal-tiptap.tsx b/flowsint-app/src/renderer/src/components/analyses/editor/minimal-tiptap.tsx
index 1675dfea..6fcbb681 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/minimal-tiptap.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/minimal-tiptap.tsx
@@ -1,21 +1,20 @@
-import * as React from "react"
-import type { Content, Editor } from "@tiptap/react"
-import type { UseMinimalTiptapEditorProps } from "./hooks/use-minimal-tiptap"
-import { EditorContent } from "@tiptap/react"
-import { Separator } from "@/components/ui/separator"
-import { cn } from "@/lib/utils"
-import { SectionOne } from "./components/section/one"
-import { SectionTwo } from "./components/section/two"
-import { SectionThree } from "./components/section/three"
-import { SectionFour } from "./components/section/four"
-import { SectionFive } from "./components/section/five"
-import { LinkBubbleMenu } from "./components/bubble-menu/link-bubble-menu"
-import { useMinimalTiptapEditor } from "./hooks/use-minimal-tiptap"
-import { MeasuredContainer } from "./components/measured-container"
+import * as React from 'react'
+import type { Content, Editor } from '@tiptap/react'
+import type { UseMinimalTiptapEditorProps } from './hooks/use-minimal-tiptap'
+import { EditorContent } from '@tiptap/react'
+import { Separator } from '@/components/ui/separator'
+import { cn } from '@/lib/utils'
+import { SectionOne } from './components/section/one'
+import { SectionTwo } from './components/section/two'
+import { SectionThree } from './components/section/three'
+import { SectionFour } from './components/section/four'
+import { SectionFive } from './components/section/five'
+import { LinkBubbleMenu } from './components/bubble-menu/link-bubble-menu'
+import { useMinimalTiptapEditor } from './hooks/use-minimal-tiptap'
+import { MeasuredContainer } from './components/measured-container'
// import "./styles/index.css"
-export interface MinimalTiptapProps
- extends Omit<UseMinimalTiptapEditorProps, "onUpdate"> {
+export interface MinimalTiptapProps extends Omit<UseMinimalTiptapEditorProps, 'onUpdate'> {
value?: Content
onChange?: (value: Content) => void
className?: string
@@ -31,14 +30,7 @@ const Toolbar = ({ editor }: { editor: Editor }) => (
<Separator orientation="vertical" className="mx-2 h-7" />
<SectionTwo
editor={editor}
- activeActions={[
- "bold",
- "italic",
- "underline",
- "strikethrough",
- "code",
- "clearFormatting",
- ]}
+ activeActions={['bold', 'italic', 'underline', 'strikethrough', 'code', 'clearFormatting']}
mainActionCount={3}
/>
<Separator orientation="vertical" className="mx-2 h-7" />
@@ -46,60 +38,74 @@ const Toolbar = ({ editor }: { editor: Editor }) => (
<Separator orientation="vertical" className="mx-2 h-7" />
<SectionFour
editor={editor}
- activeActions={["orderedList", "bulletList"]}
+ activeActions={['orderedList', 'bulletList']}
mainActionCount={0}
/>
<Separator orientation="vertical" className="mx-2 h-7" />
<SectionFive
editor={editor}
- activeActions={["codeBlock", "blockquote", "horizontalRule"]}
+ activeActions={['codeBlock', 'blockquote', 'horizontalRule']}
mainActionCount={0}
/>
</div>
</div>
)
-export const MinimalTiptapEditor = React.forwardRef<
- HTMLDivElement,
- MinimalTiptapProps
->(({ value, onChange, className, editorContentClassName, onEditorReady, showToolbar = false, ...props }, ref) => {
- const editor = useMinimalTiptapEditor({
- value,
- onUpdate: onChange,
- shouldRerenderOnTransaction: false,
- ...props,
- })
+export const MinimalTiptapEditor = React.forwardRef<HTMLDivElement, MinimalTiptapProps>(
+ (
+ {
+ value,
+ onChange,
+ className,
+ editorContentClassName,
+ onEditorReady,
+ showToolbar = false,
+ ...props
+ },
+ ref
+ ) => {
+ const editor = useMinimalTiptapEditor({
+ value,
+ onUpdate: onChange,
+ shouldRerenderOnTransaction: false,
+ ...props
+ })
- React.useEffect(() => {
- if (editor && onEditorReady) {
- onEditorReady(editor)
+ React.useEffect(() => {
+ if (editor && onEditorReady) {
+ onEditorReady(editor)
+ }
+ }, [editor, onEditorReady])
+
+ if (!editor) {
+ return null
}
- }, [editor, onEditorReady])
- if (!editor) {
- return null
+ return (
+ <MeasuredContainer
+ as="div"
+ name="editor"
+ ref={ref}
+ className={cn('flex hide-scrollbar w-full flex-col', className)}
+ >
+ {showToolbar && (
+ <div className="border-t">
+ <Toolbar editor={editor} />
+ </div>
+ )}
+ <EditorContent
+ editor={editor}
+ className={cn(
+ 'minimal-tiptap-editor prose dark:prose-invert p-8 w-full max-w-4xl mx-auto',
+ editorContentClassName
+ )}
+ />
+ <LinkBubbleMenu editor={editor} />
+ </MeasuredContainer>
+ )
}
+)
- return (
- <MeasuredContainer
- as="div"
- name="editor"
- ref={ref}
- className={cn(
- "flex hide-scrollbar w-full flex-col",
- className
- )}
- >
- {showToolbar && <div className="border-t"><Toolbar editor={editor} /></div>}
- <EditorContent
- editor={editor}
- className={cn("minimal-tiptap-editor prose dark:prose-invert p-8 w-full max-w-4xl mx-auto", editorContentClassName)}
- />
- <LinkBubbleMenu editor={editor} />
- </MeasuredContainer>
- )
-})
-
-MinimalTiptapEditor.displayName = "MinimalTiptapEditor"
+MinimalTiptapEditor.displayName = 'MinimalTiptapEditor'
export default MinimalTiptapEditor
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/types.ts b/flowsint-app/src/renderer/src/components/analyses/editor/types.ts
index da4907c8..ffc96547 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/types.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/types.ts
@@ -1,6 +1,6 @@
-import type { Editor } from "@tiptap/react"
-import type { EditorView } from "@tiptap/pm/view"
-import type { EditorState } from "@tiptap/pm/state"
+import type { Editor } from '@tiptap/react'
+import type { EditorView } from '@tiptap/pm/view'
+import type { EditorState } from '@tiptap/pm/state'
export interface LinkProps {
url: string
diff --git a/flowsint-app/src/renderer/src/components/analyses/editor/utils.ts b/flowsint-app/src/renderer/src/components/analyses/editor/utils.ts
index 68c332e1..cc50fb85 100644
--- a/flowsint-app/src/renderer/src/components/analyses/editor/utils.ts
+++ b/flowsint-app/src/renderer/src/components/analyses/editor/utils.ts
@@ -1,5 +1,5 @@
-import type { Editor } from "@tiptap/react"
-import type { MinimalTiptapProps } from "./minimal-tiptap"
+import type { Editor } from '@tiptap/react'
+import type { MinimalTiptapProps } from './minimal-tiptap'
type ShortcutKeyResult = {
symbol: string
@@ -8,7 +8,7 @@ type ShortcutKeyResult = {
export type FileError = {
file: File | string
- reason: "type" | "size" | "invalidBase64" | "base64NotAllowed"
+ reason: 'type' | 'size' | 'invalidBase64' | 'base64NotAllowed'
}
export type FileValidationOptions = {
@@ -19,36 +19,30 @@ export type FileValidationOptions = {
type FileInput = File | { src: string | File; alt?: string; title?: string }
-export const isClient = (): boolean => typeof window !== "undefined"
+export const isClient = (): boolean => typeof window !== 'undefined'
export const isServer = (): boolean => !isClient()
-export const isMacOS = (): boolean =>
- isClient() && window.navigator.platform === "MacIntel"
+export const isMacOS = (): boolean => isClient() && window.navigator.platform === 'MacIntel'
const shortcutKeyMap: Record<string, ShortcutKeyResult> = {
- mod: isMacOS()
- ? { symbol: "⌘", readable: "Command" }
- : { symbol: "Ctrl", readable: "Control" },
- alt: isMacOS()
- ? { symbol: "⌥", readable: "Option" }
- : { symbol: "Alt", readable: "Alt" },
- shift: { symbol: "⇧", readable: "Shift" },
+ mod: isMacOS() ? { symbol: '⌘', readable: 'Command' } : { symbol: 'Ctrl', readable: 'Control' },
+ alt: isMacOS() ? { symbol: '⌥', readable: 'Option' } : { symbol: 'Alt', readable: 'Alt' },
+ shift: { symbol: '⇧', readable: 'Shift' }
}
export const getShortcutKey = (key: string): ShortcutKeyResult =>
shortcutKeyMap[key.toLowerCase()] || { symbol: key, readable: key }
-export const getShortcutKeys = (keys: string[]): ShortcutKeyResult[] =>
- keys.map(getShortcutKey)
+export const getShortcutKeys = (keys: string[]): ShortcutKeyResult[] => keys.map(getShortcutKey)
export const getOutput = (
editor: Editor,
- format: MinimalTiptapProps["output"]
+ format: MinimalTiptapProps['output']
): object | string => {
switch (format) {
- case "json":
+ case 'json':
return editor.getJSON()
- case "html":
- return editor.isEmpty ? "" : editor.getHTML()
+ case 'html':
+ return editor.isEmpty ? '' : editor.getHTML()
default:
return editor.getText()
}
@@ -57,28 +51,28 @@ export const getOutput = (
export const isUrl = (
text: string,
options: { requireHostname: boolean; allowBase64?: boolean } = {
- requireHostname: false,
+ requireHostname: false
}
): boolean => {
- if (text.includes("\n")) return false
+ if (text.includes('\n')) return false
try {
const url = new URL(text)
const blockedProtocols = [
- "javascript:",
- "file:",
- "vbscript:",
- ...(options.allowBase64 ? [] : ["data:"]),
+ 'javascript:',
+ 'file:',
+ 'vbscript:',
+ ...(options.allowBase64 ? [] : ['data:'])
]
if (blockedProtocols.includes(url.protocol)) return false
- if (options.allowBase64 && url.protocol === "data:")
+ if (options.allowBase64 && url.protocol === 'data:')
return /^data:image\/[a-z]+;base64,/.test(text)
if (url.hostname) return true
return (
- url.protocol !== "" &&
- (url.pathname.startsWith("//") || url.pathname.startsWith("http")) &&
+ url.protocol !== '' &&
+ (url.pathname.startsWith('//') || url.pathname.startsWith('http')) &&
!options.requireHostname
)
} catch {
@@ -92,15 +86,13 @@ export const sanitizeUrl = (
): string | undefined => {
if (!url) return undefined
- if (options.allowBase64 && url.startsWith("data:image")) {
- return isUrl(url, { requireHostname: false, allowBase64: true })
- ? url
- : undefined
+ if (options.allowBase64 && url.startsWith('data:image')) {
+ return isUrl(url, { requireHostname: false, allowBase64: true }) ? url : undefined
}
return isUrl(url, {
requireHostname: false,
- allowBase64: options.allowBase64,
+ allowBase64: options.allowBase64
}) || /^(\/|#|mailto:|sms:|fax:|tel:)/.test(url)
? url
: `https://${url}`
@@ -113,10 +105,10 @@ export const blobUrlToBase64 = async (blobUrl: string): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => {
- if (typeof reader.result === "string") {
+ if (typeof reader.result === 'string') {
resolve(reader.result)
} else {
- reject(new Error("Failed to convert Blob to base64"))
+ reject(new Error('Failed to convert Blob to base64'))
}
}
reader.onerror = reject
@@ -130,10 +122,10 @@ export const fileToBase64 = (file: File | Blob): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => {
- if (typeof reader.result === "string") {
+ if (typeof reader.result === 'string') {
resolve(reader.result)
} else {
- reject(new Error("Failed to convert File to base64"))
+ reject(new Error('Failed to convert File to base64'))
}
}
reader.onerror = reject
@@ -153,8 +145,8 @@ const validateFileOrBase64 = <T extends FileInput>(
if (isValidType && isValidSize) {
validFiles.push(originalFile)
} else {
- if (!isValidType) errors.push({ file: input, reason: "type" })
- if (!isValidSize) errors.push({ file: input, reason: "size" })
+ if (!isValidType) errors.push({ file: input, reason: 'type' })
+ if (!isValidSize) errors.push({ file: input, reason: 'size' })
}
}
@@ -163,13 +155,12 @@ const checkTypeAndSize = (
{ allowedMimeTypes, maxFileSize }: FileValidationOptions
): { isValidType: boolean; isValidSize: boolean } => {
const mimeType = input instanceof File ? input.type : base64MimeType(input)
- const size =
- input instanceof File ? input.size : atob(input.split(",")[1]).length
+ const size = input instanceof File ? input.size : atob(input.split(',')[1]).length
const isValidType =
allowedMimeTypes.length === 0 ||
allowedMimeTypes.includes(mimeType) ||
- allowedMimeTypes.includes(`${mimeType.split("/")[0]}/*`)
+ allowedMimeTypes.includes(`${mimeType.split('/')[0]}/*`)
const isValidSize = !maxFileSize || size <= maxFileSize
@@ -178,11 +169,11 @@ const checkTypeAndSize = (
const base64MimeType = (encoded: string): string => {
const result = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/)
- return result && result.length > 1 ? result[1] : "unknown"
+ return result && result.length > 1 ? result[1] : 'unknown'
}
const isBase64 = (str: string): boolean => {
- if (str.startsWith("data:")) {
+ if (str.startsWith('data:')) {
const matches = str.match(/^data:[^;]+;base64,(.+)$/)
if (matches && matches[1]) {
str = matches[1]
@@ -206,20 +197,20 @@ export const filterFiles = <T extends FileInput>(
const errors: FileError[] = []
files.forEach((file) => {
- const actualFile = "src" in file ? file.src : file
+ const actualFile = 'src' in file ? file.src : file
if (actualFile instanceof File) {
validateFileOrBase64(actualFile, options, file, validFiles, errors)
- } else if (typeof actualFile === "string") {
+ } else if (typeof actualFile === 'string') {
if (isBase64(actualFile)) {
if (options.allowBase64) {
validateFileOrBase64(actualFile, options, file, validFiles, errors)
} else {
- errors.push({ file: actualFile, reason: "base64NotAllowed" })
+ errors.push({ file: actualFile, reason: 'base64NotAllowed' })
}
} else {
if (!sanitizeUrl(actualFile, { allowBase64: options.allowBase64 })) {
- errors.push({ file: actualFile, reason: "invalidBase64" })
+ errors.push({ file: actualFile, reason: 'invalidBase64' })
} else {
validFiles.push(file)
}
diff --git a/flowsint-app/src/renderer/src/components/analyses/notes-panel.tsx b/flowsint-app/src/renderer/src/components/analyses/notes-panel.tsx
index 8b612e9c..61a7c5b5 100644
--- a/flowsint-app/src/renderer/src/components/analyses/notes-panel.tsx
+++ b/flowsint-app/src/renderer/src/components/analyses/notes-panel.tsx
@@ -1,84 +1,95 @@
-import { useQuery } from "@tanstack/react-query"
-import { useParams } from "@tanstack/react-router"
-import { analysisService } from "@/api/analysis-service"
-import type { Analysis } from "@/types"
-import { useAnalysisPanelStore } from "@/stores/analysis-panel-store"
-import { AnalysisEditor } from "./analysis-editor"
-import { useEffect, memo } from "react"
-import AnalysisSkeleton from "./analysis-skeleton"
+import { useQuery } from '@tanstack/react-query'
+import { useParams } from '@tanstack/react-router'
+import { analysisService } from '@/api/analysis-service'
+import type { Analysis } from '@/types'
+import { useAnalysisPanelStore } from '@/stores/analysis-panel-store'
+import { AnalysisEditor } from './analysis-editor'
+import { useEffect, memo } from 'react'
+import AnalysisSkeleton from './analysis-skeleton'
export const AnalysisPanel = memo(() => {
- const { investigationId } = useParams({ strict: false }) as { investigationId: string }
- const currentAnalysisId = useAnalysisPanelStore(s => s.currentAnalysisId)
- const setCurrentAnalysisId = useAnalysisPanelStore(s => s.setCurrentAnalysisId)
+ const { investigationId } = useParams({ strict: false }) as { investigationId: string }
+ const currentAnalysisId = useAnalysisPanelStore((s) => s.currentAnalysisId)
+ const setCurrentAnalysisId = useAnalysisPanelStore((s) => s.setCurrentAnalysisId)
- // Fetch all analyses for this investigation
- const { data: analyses, isLoading: isLoadingAnalyses, isError, refetch } = useQuery<Analysis[]>({
- queryKey: ["analyses", investigationId],
- queryFn: () => analysisService.getByInvestigationId(investigationId),
- enabled: !!investigationId,
- })
+ // Fetch all analyses for this investigation
+ const {
+ data: analyses,
+ isLoading: isLoadingAnalyses,
+ isError,
+ refetch
+ } = useQuery<Analysis[]>({
+ queryKey: ['analyses', investigationId],
+ queryFn: () => analysisService.getByInvestigationId(investigationId),
+ enabled: !!investigationId
+ })
- // Find the current analysis
- const currentAnalysis = Array.isArray(analyses) ? analyses?.find(a => a.id === currentAnalysisId) || (analyses && analyses[0]) : null
+ // Find the current analysis
+ const currentAnalysis = Array.isArray(analyses)
+ ? analyses?.find((a) => a.id === currentAnalysisId) || (analyses && analyses[0])
+ : null
- // Set currentAnalysisId to first if not set
- useEffect(() => {
- if (analyses && analyses.length > 0 && (!currentAnalysisId || !analyses.some(a => a.id === currentAnalysisId))) {
- setCurrentAnalysisId(analyses[0].id)
- }
- if (analyses && analyses.length === 0) {
- setCurrentAnalysisId(null)
- }
- }, [analyses, currentAnalysisId, setCurrentAnalysisId])
-
- const handleAnalysisUpdate = () => {
- refetch()
+ // Set currentAnalysisId to first if not set
+ useEffect(() => {
+ if (
+ analyses &&
+ analyses.length > 0 &&
+ (!currentAnalysisId || !analyses.some((a) => a.id === currentAnalysisId))
+ ) {
+ setCurrentAnalysisId(analyses[0].id)
}
-
- const handleAnalysisDelete = () => {
- refetch()
- // Set to another analysis or null
- if (analyses && analyses.length > 1) {
- const next = analyses.find(a => a.id !== currentAnalysisId)
- setCurrentAnalysisId(next?.id || null)
- } else {
- setCurrentAnalysisId(null)
- }
+ if (analyses && analyses.length === 0) {
+ setCurrentAnalysisId(null)
}
+ }, [analyses, currentAnalysisId, setCurrentAnalysisId])
- const handleAnalysisCreate = (investigationId: string) => {
- refetch()
- setCurrentAnalysisId(investigationId)
- }
+ const handleAnalysisUpdate = () => {
+ refetch()
+ }
- if (isLoadingAnalyses) {
- return <AnalysisSkeleton />
+ const handleAnalysisDelete = () => {
+ refetch()
+ // Set to another analysis or null
+ if (analyses && analyses.length > 1) {
+ const next = analyses.find((a) => a.id !== currentAnalysisId)
+ setCurrentAnalysisId(next?.id || null)
+ } else {
+ setCurrentAnalysisId(null)
}
+ }
- if (isError) {
- return <div className="text-sm text-destructive">Error loading analyses.</div>
- }
+ const handleAnalysisCreate = (investigationId: string) => {
+ refetch()
+ setCurrentAnalysisId(investigationId)
+ }
+
+ if (isLoadingAnalyses) {
+ return <AnalysisSkeleton />
+ }
+
+ if (isError) {
+ return <div className="text-sm text-destructive">Error loading analyses.</div>
+ }
- return (
- <div className="flex flex-col h-full w-full">
- {/* Analysis Editor with all functionality */}
- <AnalysisEditor
- analysis={currentAnalysis}
- investigationId={investigationId}
- onAnalysisUpdate={handleAnalysisUpdate}
- onAnalysisDelete={handleAnalysisDelete}
- onAnalysisCreate={handleAnalysisCreate}
- onAnalysisSelect={setCurrentAnalysisId}
- showHeader={true}
- showAnalysisSelector={true}
- showNavigation={true}
- isLoading={isLoadingAnalyses}
- analyses={analyses || []}
- currentAnalysisId={currentAnalysisId}
- />
- </div>
- )
+ return (
+ <div className="flex flex-col h-full w-full">
+ {/* Analysis Editor with all functionality */}
+ <AnalysisEditor
+ analysis={currentAnalysis}
+ investigationId={investigationId}
+ onAnalysisUpdate={handleAnalysisUpdate}
+ onAnalysisDelete={handleAnalysisDelete}
+ onAnalysisCreate={handleAnalysisCreate}
+ onAnalysisSelect={setCurrentAnalysisId}
+ showHeader={true}
+ showAnalysisSelector={true}
+ showNavigation={true}
+ isLoading={isLoadingAnalyses}
+ analyses={analyses || []}
+ currentAnalysisId={currentAnalysisId}
+ />
+ </div>
+ )
})
-export default memo(AnalysisPanel)
\ No newline at end of file
+export default memo(AnalysisPanel)
diff --git a/flowsint-app/src/renderer/src/components/chat/chat-history.tsx b/flowsint-app/src/renderer/src/components/chat/chat-history.tsx
index 75401320..0a582f61 100644
--- a/flowsint-app/src/renderer/src/components/chat/chat-history.tsx
+++ b/flowsint-app/src/renderer/src/components/chat/chat-history.tsx
@@ -1,105 +1,140 @@
-import { chatCRUDService } from '@/api/chat-service';
-import { useQuery } from '@tanstack/react-query';
-import { SkeletonList } from '../shared/skeleton-list';
-import { Button } from '../ui/button';
-import { ArrowLeft, Trash, Sparkles } from 'lucide-react';
-import { Chat } from '@/types';
-import { useCallback } from 'react';
-import { formatDistanceToNow } from 'date-fns';
-import { useConfirm } from '../use-confirm-dialog';
-import { useChatState } from '@/stores/use-chat-store';
+import { chatCRUDService } from '@/api/chat-service'
+import { useQuery } from '@tanstack/react-query'
+import { SkeletonList } from '../shared/skeleton-list'
+import { Button } from '../ui/button'
+import { ArrowLeft, Trash, Sparkles } from 'lucide-react'
+import { Chat } from '@/types'
+import { useCallback } from 'react'
+import { formatDistanceToNow } from 'date-fns'
+import { useConfirm } from '../use-confirm-dialog'
+import { useChatState } from '@/stores/use-chat-store'
-const ChatHistory = ({ setView, deleteChatMutation, handleCreateNewChat }: { setView: any, deleteChatMutation: any, handleCreateNewChat: any }) => {
- const { confirm } = useConfirm()
- const setCurrentChatId = useChatState(s => s.setCurrentChatId)
- const { data: chats, isLoading } = useQuery({
- queryKey: ["chats"],
- queryFn: () => chatCRUDService.get(),
- });
+const ChatHistory = ({
+ setView,
+ deleteChatMutation,
+ handleCreateNewChat
+}: {
+ setView: any
+ deleteChatMutation: any
+ handleCreateNewChat: any
+}) => {
+ const { confirm } = useConfirm()
+ const setCurrentChatId = useChatState((s) => s.setCurrentChatId)
+ const { data: chats, isLoading } = useQuery({
+ queryKey: ['chats'],
+ queryFn: () => chatCRUDService.get()
+ })
- const switchToChat = (chatId: string) => {
- setView("chat")
- setCurrentChatId(chatId)
- }
-
- return (
- <div className='h-full flex flex-col'>
- <div className="flex items-center justify-between p-3 border-b w-full">
- <div className="flex w-full items-center justify-between gap-1">
- <div className='flex items-center gap-2'>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6"
- //@ts-ignore
- onClick={() => setView("chat")}
- >
- <ArrowLeft className="h-3 w-3" />
- </Button>
- <span className='opacity-60'>Chat history</span>
- </div>
+ const switchToChat = (chatId: string) => {
+ setView('chat')
+ setCurrentChatId(chatId)
+ }
- </div>
+ return (
+ <div className="h-full flex flex-col">
+ <div className="flex items-center justify-between p-3 border-b w-full">
+ <div className="flex w-full items-center justify-between gap-1">
+ <div className="flex items-center gap-2">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6"
+ //@ts-ignore
+ onClick={() => setView('chat')}
+ >
+ <ArrowLeft className="h-3 w-3" />
+ </Button>
+ <span className="opacity-60">Chat history</span>
+ </div>
+ </div>
+ </div>
+ {isLoading ? (
+ <div className="p-4">
+ <SkeletonList rowCount={4} />
+ </div>
+ ) : chats && chats.length > 0 ? (
+ <div className="grow overflow-auto p-4 flex flex-col gap-2">
+ {chats.map((chat: Chat) => (
+ <ChatItem
+ switchToChat={switchToChat}
+ deleteChatMutation={deleteChatMutation}
+ confirm={confirm}
+ key={chat.id}
+ chat={chat}
+ />
+ ))}
+ </div>
+ ) : (
+ <div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-muted-foreground">
+ <div className="relative mb-6">
+ <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-primary/10 rounded-full blur-xl animate-pulse"></div>
+ <div className="relative bg-gradient-to-br from-primary/10 to-primary/5 rounded-full p-6 border border-primary/20">
+ <Sparkles className="h-8 w-8 text-primary/60" />
</div>
- {isLoading ? <div className='p-4'><SkeletonList rowCount={4} /></div> :
- chats && chats.length > 0 ? (
- <div className='grow overflow-auto p-4 flex flex-col gap-2'>
- {chats.map((chat: Chat) => (<ChatItem switchToChat={switchToChat} deleteChatMutation={deleteChatMutation} confirm={confirm} key={chat.id} chat={chat} />))}
- </div>
- ) : (
- <div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-muted-foreground">
- <div className="relative mb-6">
- <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-primary/10 rounded-full blur-xl animate-pulse"></div>
- <div className="relative bg-gradient-to-br from-primary/10 to-primary/5 rounded-full p-6 border border-primary/20">
- <Sparkles className="h-8 w-8 text-primary/60" />
- </div>
- </div>
- <div className="space-y-2 max-w-sm">
- <h3 className="text-lg font-semibold text-foreground">
- No conversations yet
- </h3>
- <p className="text-sm opacity-70">
- Start chatting with AI to analyze your investigation data and get insights. Your conversation history will appear here.
- </p>
- </div>
- <div className="mt-6">
- <Button
- variant="outline"
- size="sm"
- onClick={handleCreateNewChat}
- className="bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20 hover:from-primary/20 hover:to-primary/10"
- >
- Start your first chat
- </Button>
- </div>
- </div>
- )
- }
+ </div>
+ <div className="space-y-2 max-w-sm">
+ <h3 className="text-lg font-semibold text-foreground">No conversations yet</h3>
+ <p className="text-sm opacity-70">
+ Start chatting with AI to analyze your investigation data and get insights. Your
+ conversation history will appear here.
+ </p>
+ </div>
+ <div className="mt-6">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleCreateNewChat}
+ className="bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20 hover:from-primary/20 hover:to-primary/10"
+ >
+ Start your first chat
+ </Button>
+ </div>
</div>
- )
+ )}
+ </div>
+ )
}
export default ChatHistory
-
-const ChatItem = ({ chat, confirm, deleteChatMutation, switchToChat }: { chat: Chat, confirm: any, deleteChatMutation: any, switchToChat: any }) => {
- const handleDeleteChat = useCallback(async (e: { stopPropagation: () => void; }) => {
- e.stopPropagation()
- if (await confirm({ title: "Are you sure you want to delete this chat?", message: "This action is irreversible." })) {
- await deleteChatMutation.mutateAsync(chat.id)
- }
- }, [])
- return (
- <button onClick={() => switchToChat(chat.id)} className='flex w-full cursor-pointer justify-start items-center bg-muted-foreground/5 backdrop-blur-sm rounded-xl p-2 px-4 hover:bg-muted-foreground/10 transition-all duration-300'>
- <div className='flex items-start flex-col justify-between min-w-0 flex-1 overflow-hidden'>
- <span className='font-semibold text-md truncate text-left w-full'>{chat.title}</span>
- <span className='font-normal text-xs'>{formatDistanceToNow(chat.last_updated_at, { addSuffix: true })}</span>
- </div>
- <div className='flex items-center justify-between flex-shrink-0 ml-2'>
- <Button variant="ghost" size="icon" className='h-6 w-6' onClick={handleDeleteChat}>
- <Trash className='h-3 w-3' />
- </Button>
- </div>
- </button>
- )
-}
\ No newline at end of file
+const ChatItem = ({
+ chat,
+ confirm,
+ deleteChatMutation,
+ switchToChat
+}: {
+ chat: Chat
+ confirm: any
+ deleteChatMutation: any
+ switchToChat: any
+}) => {
+ const handleDeleteChat = useCallback(async (e: { stopPropagation: () => void }) => {
+ e.stopPropagation()
+ if (
+ await confirm({
+ title: 'Are you sure you want to delete this chat?',
+ message: 'This action is irreversible.'
+ })
+ ) {
+ await deleteChatMutation.mutateAsync(chat.id)
+ }
+ }, [])
+ return (
+ <button
+ onClick={() => switchToChat(chat.id)}
+ className="flex w-full cursor-pointer justify-start items-center bg-muted-foreground/5 backdrop-blur-sm rounded-xl p-2 px-4 hover:bg-muted-foreground/10 transition-all duration-300"
+ >
+ <div className="flex items-start flex-col justify-between min-w-0 flex-1 overflow-hidden">
+ <span className="font-semibold text-md truncate text-left w-full">{chat.title}</span>
+ <span className="font-normal text-xs">
+ {formatDistanceToNow(chat.last_updated_at, { addSuffix: true })}
+ </span>
+ </div>
+ <div className="flex items-center justify-between flex-shrink-0 ml-2">
+ <Button variant="ghost" size="icon" className="h-6 w-6" onClick={handleDeleteChat}>
+ <Trash className="h-3 w-3" />
+ </Button>
+ </div>
+ </button>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/chat/chat-prompt.tsx b/flowsint-app/src/renderer/src/components/chat/chat-prompt.tsx
index f67b6b89..91d196e7 100644
--- a/flowsint-app/src/renderer/src/components/chat/chat-prompt.tsx
+++ b/flowsint-app/src/renderer/src/components/chat/chat-prompt.tsx
@@ -1,123 +1,121 @@
-import { Button } from "@/components/ui/button"
-import { Badge } from "@/components/ui/badge"
-import { Textarea } from "@/components/ui/textarea"
-import { XIcon, ArrowUp } from "lucide-react"
-import { useGraphStore } from "@/stores/graph-store"
-import { useRef, useEffect, memo } from "react"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
+import { Button } from '@/components/ui/button'
+import { Badge } from '@/components/ui/badge'
+import { Textarea } from '@/components/ui/textarea'
+import { XIcon, ArrowUp } from 'lucide-react'
+import { useGraphStore } from '@/stores/graph-store'
+import { useRef, useEffect, memo } from 'react'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
interface ChatPanelProps {
- customPrompt: string
- setCustomPrompt: (prompt: string) => void
- handleCustomPrompt: (editorValue: any) => void
- isAiLoading: boolean
- editorValue: any
+ customPrompt: string
+ setCustomPrompt: (prompt: string) => void
+ handleCustomPrompt: (editorValue: any) => void
+ isAiLoading: boolean
+ editorValue: any
}
export const ChatPanel = ({
- customPrompt,
- setCustomPrompt,
- handleCustomPrompt,
- isAiLoading,
- editorValue
+ customPrompt,
+ setCustomPrompt,
+ handleCustomPrompt,
+ isAiLoading,
+ editorValue
}: ChatPanelProps) => {
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const clearSelectedNodes = useGraphStore(s => s.clearSelectedNodes)
- const textareaRef = useRef<HTMLTextAreaElement>(null)
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const clearSelectedNodes = useGraphStore((s) => s.clearSelectedNodes)
+ const textareaRef = useRef<HTMLTextAreaElement>(null)
- // Handle Enter key submission
- const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault()
- e.stopPropagation()
- handleSubmit()
- }
+ // Handle Enter key submission
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault()
+ e.stopPropagation()
+ handleSubmit()
}
+ }
- // Auto-resize textarea
- useEffect(() => {
- if (textareaRef.current) {
- textareaRef.current.style.height = 'auto'
- textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 120)}px`
- }
- }, [customPrompt])
+ // Auto-resize textarea
+ useEffect(() => {
+ if (textareaRef.current) {
+ textareaRef.current.style.height = 'auto'
+ textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 120)}px`
+ }
+ }, [customPrompt])
- const handleSubmit = () => {
- if (customPrompt.trim() && !isAiLoading) {
- handleCustomPrompt(editorValue)
- }
+ const handleSubmit = () => {
+ if (customPrompt.trim() && !isAiLoading) {
+ handleCustomPrompt(editorValue)
}
+ }
- // Limit to 10 items and show remaining count if more
- const displayItems = selectedNodes?.slice(0, 10) || []
- const remainingCount = selectedNodes?.length ? Math.max(0, selectedNodes.length - 10) : 0
+ // Limit to 10 items and show remaining count if more
+ const displayItems = selectedNodes?.slice(0, 10) || []
+ const remainingCount = selectedNodes?.length ? Math.max(0, selectedNodes.length - 10) : 0
- return (
- <div className="h-full flex flex-col">
- <div className="flex-1 p-2 flex flex-col gap-2">
- {selectedNodes?.length > 0 && (
- <div className="flex flex-nowrap overflow-x-auto hide-scrollbar gap-1.5 items-center">
- <ContextList context={displayItems} />
- {remainingCount > 0 && (
- <Badge
- variant="outline"
- className="text-xs"
- >
- +{remainingCount} more
- </Badge>
- )}
- <Button
- size="icon"
- variant="ghost"
- className="h-4 w-4 hover:bg-background/80"
- onClick={clearSelectedNodes}
- >
- <XIcon className="h-3 w-3" />
- </Button>
- </div>
- )}
- <div className="flex-1 flex flex-col justify-end">
- <div className="relative">
- <Textarea
- ref={textareaRef}
- autoFocus
- placeholder="Ask me anything about your investigation..."
- value={customPrompt}
- onChange={(e) => setCustomPrompt(e.target.value)}
- onKeyDown={handleKeyDown}
- className={`
+ return (
+ <div className="h-full flex flex-col">
+ <div className="flex-1 p-2 flex flex-col gap-2">
+ {selectedNodes?.length > 0 && (
+ <div className="flex flex-nowrap overflow-x-auto hide-scrollbar gap-1.5 items-center">
+ <ContextList context={displayItems} />
+ {remainingCount > 0 && (
+ <Badge variant="outline" className="text-xs">
+ +{remainingCount} more
+ </Badge>
+ )}
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-4 w-4 hover:bg-background/80"
+ onClick={clearSelectedNodes}
+ >
+ <XIcon className="h-3 w-3" />
+ </Button>
+ </div>
+ )}
+ <div className="flex-1 flex flex-col justify-end">
+ <div className="relative">
+ <Textarea
+ ref={textareaRef}
+ autoFocus
+ placeholder="Ask me anything about your investigation..."
+ value={customPrompt}
+ onChange={(e) => setCustomPrompt(e.target.value)}
+ onKeyDown={handleKeyDown}
+ className={`
min-h-[44px] max-h-[120px] resize-none
border border-border bg-background
focus:ring-2 focus:ring-primary/20 focus:border-primary
transition-all duration-200
pr-12 py-3 px-4 rounded-xl
`}
- disabled={isAiLoading}
- />
- <Button
- onClick={handleSubmit}
- disabled={!customPrompt.trim() || isAiLoading}
- size="icon"
- variant={"ghost"}
- className={`
+ disabled={isAiLoading}
+ />
+ <Button
+ onClick={handleSubmit}
+ disabled={!customPrompt.trim() || isAiLoading}
+ size="icon"
+ variant={'ghost'}
+ className={`
absolute bg-muted right-2 bottom-2
h-8 w-8 rounded-full
transition-all duration-200
- ${customPrompt.trim() && !isAiLoading
+ ${
+ customPrompt.trim() && !isAiLoading
? 'text-primary-foreground'
: 'bg-muted text-muted-foreground'
}
`}
- >
- {isAiLoading ? (
- <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
- ) : (
- <ArrowUp className="w-4 h-4" />
- )}
- </Button>
- </div>
+ >
+ {isAiLoading ? (
+ <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
+ ) : (
+ <ArrowUp className="w-4 h-4" />
+ )}
+ </Button>
+ </div>
- {/* <div className="text-xs text-muted-foreground flex items-center gap-2">
+ {/* <div className="text-xs text-muted-foreground flex items-center gap-2">
{isAiLoading && (
<div className="flex items-center gap-1">
<div className="w-2 h-2 bg-primary rounded-full animate-pulse" />
@@ -125,25 +123,29 @@ export const ChatPanel = ({
</div>
)}
</div> */}
- </div>
- </div>
- </div >
- )
+ </div>
+ </div>
+ </div>
+ )
}
export const ContextList = memo(({ context }: { context: any }) => {
- const colors = useNodesDisplaySettings(s => s.colors)
- return (
- <div className="flex flex-nowrap overflow-x-auto hide-scrollbar gap-1.5 items-center px-1">
- {context.map((item: any, index: number) => {
- const color = colors[item?.data?.type || item?.type]
- return (
- <Badge key={index} variant="secondary" className="flex items-center border border-border gap-1.5 text-xs">
- <span style={{ background: color }} className="w-1.5 h-1.5 rounded-full" />
- {item.data?.label || 'Unknown'}
- </Badge>
- )
- })}
- </div>
- )
-})
\ No newline at end of file
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ return (
+ <div className="flex flex-nowrap overflow-x-auto hide-scrollbar gap-1.5 items-center px-1">
+ {context.map((item: any, index: number) => {
+ const color = colors[item?.data?.type || item?.type]
+ return (
+ <Badge
+ key={index}
+ variant="secondary"
+ className="flex items-center border border-border gap-1.5 text-xs"
+ >
+ <span style={{ background: color }} className="w-1.5 h-1.5 rounded-full" />
+ {item.data?.label || 'Unknown'}
+ </Badge>
+ )
+ })}
+ </div>
+ )
+})
diff --git a/flowsint-app/src/renderer/src/components/chat/chat-skeleton.tsx b/flowsint-app/src/renderer/src/components/chat/chat-skeleton.tsx
index 8af650e3..32fbf088 100644
--- a/flowsint-app/src/renderer/src/components/chat/chat-skeleton.tsx
+++ b/flowsint-app/src/renderer/src/components/chat/chat-skeleton.tsx
@@ -1,51 +1,51 @@
-import { Skeleton } from "../ui/skeleton"
+import { Skeleton } from '../ui/skeleton'
export function ChatSkeleton() {
- return (
- <div className="grow p-4 flex flex-col gap-4">
- {/* User message skeleton */}
- <div className="flex w-full justify-end">
- <div className="bg-muted-foreground/5 max-w-[80%] p-3 rounded-md">
- <div className="flex flex-col gap-2">
- <Skeleton className="h-4 w-48" />
- <Skeleton className="h-4 w-32" />
- <Skeleton className="h-4 w-40" />
- </div>
- </div>
- </div>
+ return (
+ <div className="grow p-4 flex flex-col gap-4">
+ {/* User message skeleton */}
+ <div className="flex w-full justify-end">
+ <div className="bg-muted-foreground/5 max-w-[80%] p-3 rounded-md">
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-4 w-48" />
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-4 w-40" />
+ </div>
+ </div>
+ </div>
- {/* Bot message skeleton */}
- <div className="flex w-full">
- <div className="w-full p-3 rounded-md">
- <div className="flex flex-col gap-2">
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-3/4" />
- <Skeleton className="h-4 w-5/6" />
- <Skeleton className="h-4 w-2/3" />
- </div>
- </div>
- </div>
+ {/* Bot message skeleton */}
+ <div className="flex w-full">
+ <div className="w-full p-3 rounded-md">
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="h-4 w-5/6" />
+ <Skeleton className="h-4 w-2/3" />
+ </div>
+ </div>
+ </div>
- {/* Another user message skeleton */}
- <div className="flex w-full justify-end">
- <div className="bg-muted-foreground/5 max-w-[80%] p-3 rounded-md">
- <div className="flex flex-col gap-2">
- <Skeleton className="h-4 w-36" />
- <Skeleton className="h-4 w-28" />
- </div>
- </div>
- </div>
+ {/* Another user message skeleton */}
+ <div className="flex w-full justify-end">
+ <div className="bg-muted-foreground/5 max-w-[80%] p-3 rounded-md">
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-4 w-36" />
+ <Skeleton className="h-4 w-28" />
+ </div>
+ </div>
+ </div>
- {/* Another bot message skeleton */}
- <div className="flex w-full">
- <div className="w-full p-3 rounded-md">
- <div className="flex flex-col gap-2">
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-4/5" />
- <Skeleton className="h-4 w-1/2" />
- </div>
- </div>
- </div>
+ {/* Another bot message skeleton */}
+ <div className="flex w-full">
+ <div className="w-full p-3 rounded-md">
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-4/5" />
+ <Skeleton className="h-4 w-1/2" />
+ </div>
</div>
- )
-}
\ No newline at end of file
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/chat/floating-chat.tsx b/flowsint-app/src/renderer/src/components/chat/floating-chat.tsx
index 8cc6722d..6d67ef8d 100644
--- a/flowsint-app/src/renderer/src/components/chat/floating-chat.tsx
+++ b/flowsint-app/src/renderer/src/components/chat/floating-chat.tsx
@@ -19,232 +19,243 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/
import { CopyButton } from '../copy'
function FloatingChat() {
- const [editorValue, setEditorValue] = useState<any>("")
- const bottomRef = useRef<HTMLDivElement>(null)
- const currentChatId = useChatState(s => s.currentChatId)
- const isOpenChat = useLayoutStore(s => s.isOpenChat)
- const toggleChat = useLayoutStore(s => s.toggleChat)
- const closeChat = useLayoutStore(s => s.closeChat)
- const messages = useChatState(s => s.messages)
- const setMessages = useChatState(s => s.setMessages)
- const [view, setView] = useState<"chat" | "history">("chat")
+ const [editorValue, setEditorValue] = useState<any>('')
+ const bottomRef = useRef<HTMLDivElement>(null)
+ const currentChatId = useChatState((s) => s.currentChatId)
+ const isOpenChat = useLayoutStore((s) => s.isOpenChat)
+ const toggleChat = useLayoutStore((s) => s.toggleChat)
+ const closeChat = useLayoutStore((s) => s.closeChat)
+ const messages = useChatState((s) => s.messages)
+ const setMessages = useChatState((s) => s.setMessages)
+ const [view, setView] = useState<'chat' | 'history'>('chat')
- const { data: chat, isLoading } = useQuery({
- queryKey: ["chat", currentChatId],
- enabled: Boolean(currentChatId) && isOpenChat,
- queryFn: () => chatCRUDService.getById(currentChatId as string),
- });
+ const { data: chat, isLoading } = useQuery({
+ queryKey: ['chat', currentChatId],
+ enabled: Boolean(currentChatId) && isOpenChat,
+ queryFn: () => chatCRUDService.getById(currentChatId as string)
+ })
- useEffect(() => {
- setEditorValue("")
- setMessages([])
- }, [currentChatId, setMessages])
+ useEffect(() => {
+ setEditorValue('')
+ setMessages([])
+ }, [currentChatId, setMessages])
- useEffect(() => {
- if (chat?.messages) {
- setMessages(chat.messages)
- }
- }, [chat, setMessages])
+ useEffect(() => {
+ if (chat?.messages) {
+ setMessages(chat.messages)
+ }
+ }, [chat, setMessages])
- // Chat hook
- const {
- isAiLoading,
- customPrompt,
- setCustomPrompt,
- handleCustomPrompt,
- createNewChat,
- deleteChatMutation
- } = useChat({
- onContentUpdate: setEditorValue,
- onSuccess: () => { },
- })
+ // Chat hook
+ const {
+ isAiLoading,
+ customPrompt,
+ setCustomPrompt,
+ handleCustomPrompt,
+ createNewChat,
+ deleteChatMutation
+ } = useChat({
+ onContentUpdate: setEditorValue,
+ onSuccess: () => {}
+ })
- const { isMac } = useKeyboardShortcut({
- key: "e",
- ctrlOrCmd: true,
- callback: toggleChat,
- })
+ const { isMac } = useKeyboardShortcut({
+ key: 'e',
+ ctrlOrCmd: true,
+ callback: toggleChat
+ })
- useKeyboardShortcut({
- key: "Escape",
- ctrlOrCmd: false,
- callback: closeChat,
- })
+ useKeyboardShortcut({
+ key: 'Escape',
+ ctrlOrCmd: false,
+ callback: closeChat
+ })
- const handlecreateNewChat = () => { createNewChat(); setView("chat") }
+ const handlecreateNewChat = () => {
+ createNewChat()
+ setView('chat')
+ }
- // Check if there's content in the editor
- const hasContent = editorValue && (
- typeof editorValue === 'string' ? editorValue.trim() !== '' :
- editorValue.content && editorValue.content.length > 0
- )
- const hasMessages = messages.length > 0
-
- useEffect(() => {
- if (bottomRef.current) {
- bottomRef.current.scrollIntoView({ behavior: "smooth" })
- }
- }, [messages, editorValue])
+ // Check if there's content in the editor
+ const hasContent =
+ editorValue &&
+ (typeof editorValue === 'string'
+ ? editorValue.trim() !== ''
+ : editorValue.content && editorValue.content.length > 0)
+ const hasMessages = messages.length > 0
- const keyboardShortcut = isMac ? "⌘+E" : "Ctrl+E"
+ useEffect(() => {
+ if (bottomRef.current) {
+ bottomRef.current.scrollIntoView({ behavior: 'smooth' })
+ }
+ }, [messages, editorValue])
- return (
- <>
- {!isOpenChat &&
- <div className="fixed bottom-12 right-4 z-10">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- className='h-16 w-16 p-0 rounded-full cursor-pointer bg-background border border-border bg-opacity-100'
- variant="outline"
- onClick={toggleChat}
- >
- {/* <Sparkles className='!h-5 !w-5' /> */}
- <img src="/icon.png" alt="Flowsint" className="h-12 w-12 object-contain" />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent side="left">
- <div className="text-center">
- <div>Toggle assistant</div>
- <div className="text-xs opacity-70">{keyboardShortcut}</div>
- </div>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>}
+ const keyboardShortcut = isMac ? '⌘+E' : 'Ctrl+E'
- {/* Chat Panel */}
- {isOpenChat &&
+ return (
+ <>
+ {!isOpenChat && (
+ <div className="fixed bottom-12 right-4 z-10">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ className="h-16 w-16 p-0 rounded-full cursor-pointer bg-background border border-border bg-opacity-100"
+ variant="outline"
+ onClick={toggleChat}
+ >
+ {/* <Sparkles className='!h-5 !w-5' /> */}
+ <img src="/icon.png" alt="Flowsint" className="h-12 w-12 object-contain" />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="left">
+ <div className="text-center">
+ <div>Toggle assistant</div>
+ <div className="text-xs opacity-70">{keyboardShortcut}</div>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ )}
- <div className="fixed bottom-12 overflow-hidden rounded-2xl right-4 shadow z-21">
- <ResizableChat minWidth={400} minHeight={400} maxWidth={800} maxHeight={800}>
- <Card className="overflow-hidden !backdrop-blur bg-background/90 rounded-2xl gap-0 py-0 h-full">
- {view === "history" ? (
- <ChatHistory setView={setView} deleteChatMutation={deleteChatMutation} handleCreateNewChat={handlecreateNewChat} />
- ) : (
- <>
- <div className="flex items-center justify-between p-3 border-b">
- <div className="flex w-full items-center justify-between gap-1">
- <div className='flex items-center gap-2 truncate text-ellipsis'>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6"
- //@ts-ignore
- onClick={handlecreateNewChat}
- title="Create new chat"
- >
- <Plus className="h-3 w-3" />
- </Button>
- <span className='text-sm opacity-60 truncate text-ellipsis'>{chat?.title}</span>
- </div>
- <div className='flex items-center gap-2'>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6"
- //@ts-ignore
- onClick={() => setView("history")}
- title="Create new chat"
- >
- <History className="h-3 w-3 opacity-60" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6"
- onClick={closeChat}
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- </div>
- </div>
+ {/* Chat Panel */}
+ {isOpenChat && (
+ <div className="fixed bottom-12 overflow-hidden rounded-2xl right-4 shadow z-21">
+ <ResizableChat minWidth={400} minHeight={400} maxWidth={800} maxHeight={800}>
+ <Card className="overflow-hidden !backdrop-blur bg-background/90 rounded-2xl gap-0 py-0 h-full">
+ {view === 'history' ? (
+ <ChatHistory
+ setView={setView}
+ deleteChatMutation={deleteChatMutation}
+ handleCreateNewChat={handlecreateNewChat}
+ />
+ ) : (
+ <>
+ <div className="flex items-center justify-between p-3 border-b">
+ <div className="flex w-full items-center justify-between gap-1">
+ <div className="flex items-center gap-2 truncate text-ellipsis">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6"
+ //@ts-ignore
+ onClick={handlecreateNewChat}
+ title="Create new chat"
+ >
+ <Plus className="h-3 w-3" />
+ </Button>
+ <span className="text-sm opacity-60 truncate text-ellipsis">
+ {chat?.title}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6"
+ //@ts-ignore
+ onClick={() => setView('history')}
+ title="Create new chat"
+ >
+ <History className="h-3 w-3 opacity-60" />
+ </Button>
+ <Button variant="ghost" size="icon" className="h-6 w-6" onClick={closeChat}>
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ </div>
- {/* Content */}
- <div className="flex flex-col flex-1 overflow-auto">
- {isLoading ? (
- <ChatSkeleton />
- ) : hasMessages ? (
- <div className='grow p-4 flex flex-col gap-2'>
- {messages.map((message: ChatMessage) => (
- <ChatMessageComponent key={message.id} message={message} />
- ))}
- {hasContent && (
- <ChatMessageComponent
- key="draft"
- message={{
- content: editorValue,
- is_bot: true,
- id: new Date().getTime().toString(),
- created_at: new Date().toISOString(),
- chatId: currentChatId || undefined
- }}
- />
- )}
- <div ref={bottomRef} />
- </div>
- ) : null}
- {!hasMessages && !hasContent && !isLoading && (
- <div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-muted-foreground">
- {!currentChatId ? (
- // No currentChatId - Empty state with sparkles
- <>
- <div className="relative mb-6">
- <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-primary/10 rounded-full blur-xl animate-pulse"></div>
- <div className="relative bg-gradient-to-br from-primary/10 to-primary/5 rounded-full p-4 border border-primary/20">
- <img src="/icon.png" alt="Flowsint" className="h-12 w-12 object-cover" />
- </div>
- </div>
- <div className="space-y-2 max-w-sm">
- <h3 className="text-lg font-semibold text-foreground">
- No conversations yet
- </h3>
- <p className="text-sm opacity-70">
- Start chatting with AI to analyze your investigation data and get insights. Your conversation history will appear here.
- </p>
- </div>
- <div className="mt-6">
- <Button
- variant="outline"
- size="sm"
- onClick={handlecreateNewChat}
- className="bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20 hover:from-primary/20 hover:to-primary/10"
- >
- Start your first chat
- </Button>
- </div>
- </>
- ) : (
- // Has currentChatId but no messages - Examples of things to ask
- <>
- {/* <div className="relative mb-6">
+ {/* Content */}
+ <div className="flex flex-col flex-1 overflow-auto">
+ {isLoading ? (
+ <ChatSkeleton />
+ ) : hasMessages ? (
+ <div className="grow p-4 flex flex-col gap-2">
+ {messages.map((message: ChatMessage) => (
+ <ChatMessageComponent key={message.id} message={message} />
+ ))}
+ {hasContent && (
+ <ChatMessageComponent
+ key="draft"
+ message={{
+ content: editorValue,
+ is_bot: true,
+ id: new Date().getTime().toString(),
+ created_at: new Date().toISOString(),
+ chatId: currentChatId || undefined
+ }}
+ />
+ )}
+ <div ref={bottomRef} />
+ </div>
+ ) : null}
+ {!hasMessages && !hasContent && !isLoading && (
+ <div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-muted-foreground">
+ {!currentChatId ? (
+ // No currentChatId - Empty state with sparkles
+ <>
+ <div className="relative mb-6">
+ <div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-primary/10 rounded-full blur-xl animate-pulse"></div>
+ <div className="relative bg-gradient-to-br from-primary/10 to-primary/5 rounded-full p-4 border border-primary/20">
+ <img
+ src="/icon.png"
+ alt="Flowsint"
+ className="h-12 w-12 object-cover"
+ />
+ </div>
+ </div>
+ <div className="space-y-2 max-w-sm">
+ <h3 className="text-lg font-semibold text-foreground">
+ No conversations yet
+ </h3>
+ <p className="text-sm opacity-70">
+ Start chatting with AI to analyze your investigation data and get
+ insights. Your conversation history will appear here.
+ </p>
+ </div>
+ <div className="mt-6">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handlecreateNewChat}
+ className="bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20 hover:from-primary/20 hover:to-primary/10"
+ >
+ Start your first chat
+ </Button>
+ </div>
+ </>
+ ) : (
+ // Has currentChatId but no messages - Examples of things to ask
+ <>
+ {/* <div className="relative mb-6">
<div className="absolute inset-0 bg-gradient-to-r from-primary/20 to-primary/10 rounded-full blur-xl animate-pulse"></div>
<div className="relative bg-gradient-to-br from-primary/10 to-primary/5 rounded-full p-6 border border-primary/20">
<Sparkles className="h-8 w-8 text-primary/60" />
</div>
</div> */}
- <div className="space-y-2 max-w-sm">
- <h3 className="text-lg font-semibold text-foreground">
- Start your conversation with <span className="text-primary">Flo</span>
- </h3>
- <p className="text-sm opacity-70">
- Ask me anything about your investigation. Here are some examples:
- </p>
- </div>
- <div className="mt-6 space-y-3 max-w-md">
- <div className="text-xs space-y-1">
- <p className="font-medium text-left">Analysis & Insights</p>
- <ul className="space-y-1 text-left opacity-60">
- <li>• "Analyze the connections between these entities"</li>
- <li>• "What patterns do you see in this data?"</li>
- <li>• "Summarize the key findings from this investigation"</li>
- </ul>
- </div>
- {/* <div className="text-xs opacity-60 space-y-1">
+ <div className="space-y-2 max-w-sm">
+ <h3 className="text-lg font-semibold text-foreground">
+ Start your conversation with{' '}
+ <span className="text-primary">Flo</span>
+ </h3>
+ <p className="text-sm opacity-70">
+ Ask me anything about your investigation. Here are some examples:
+ </p>
+ </div>
+ <div className="mt-6 space-y-3 max-w-md">
+ <div className="text-xs space-y-1">
+ <p className="font-medium text-left">Analysis & Insights</p>
+ <ul className="space-y-1 text-left opacity-60">
+ <li>• "Analyze the connections between these entities"</li>
+ <li>• "What patterns do you see in this data?"</li>
+ <li>• "Summarize the key findings from this investigation"</li>
+ </ul>
+ </div>
+ {/* <div className="text-xs opacity-60 space-y-1">
<p className="font-medium">Data Exploration:</p>
<ul className="space-y-1 text-left">
<li>• "Find all IP addresses related to this domain"</li>
@@ -252,85 +263,88 @@ function FloatingChat() {
<li>• "What social media accounts are linked to this email?"</li>
</ul>
</div> */}
- <div className="text-xs space-y-1">
- <p className="font-medium text-left">Investigation Help</p>
- <ul className="space-y-1 text-left opacity-60">
- <li>• "Suggest next steps for this investigation"</li>
- <li>• "What should I look for next?"</li>
- <li>• "Help me organize this investigation"</li>
- </ul>
- </div>
- </div>
- </>
- )}
- </div>
- )}
- </div>
- <div className='border-t'>
- <ChatPanel
- customPrompt={customPrompt}
- setCustomPrompt={setCustomPrompt}
- handleCustomPrompt={handleCustomPrompt}
- isAiLoading={isAiLoading}
- editorValue={editorValue}
- />
- </div>
- </>
- )}
- </Card>
- </ResizableChat>
- </div>}
- </>
- )
+ <div className="text-xs space-y-1">
+ <p className="font-medium text-left">Investigation Help</p>
+ <ul className="space-y-1 text-left opacity-60">
+ <li>• "Suggest next steps for this investigation"</li>
+ <li>• "What should I look for next?"</li>
+ <li>• "Help me organize this investigation"</li>
+ </ul>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ <div className="border-t">
+ <ChatPanel
+ customPrompt={customPrompt}
+ setCustomPrompt={setCustomPrompt}
+ handleCustomPrompt={handleCustomPrompt}
+ isAiLoading={isAiLoading}
+ editorValue={editorValue}
+ />
+ </div>
+ </>
+ )}
+ </Card>
+ </ResizableChat>
+ </div>
+ )}
+ </>
+ )
}
const ChatMessageComponent = ({ message }: { message: ChatMessage }) => {
-
- if (message.is_bot)
- return (
- <MessageContainer copyContent={message.content}>
- <div className={cn("justify-start",
- "flex w-full",
- )}>
- <div className={cn("w-full",
- "p-3 rounded-xl max-w-full",
- "flex flex-col gap-2"
- )}>
- <MemoizedMarkdown id={message.id} content={message.content} />
- </div>
- </div>
- </MessageContainer>
- )
-
+ if (message.is_bot)
return (
- <MessageContainer copyContent={message.content} >
- <div className={cn("items-end",
- "flex w-full flex-col gap-2",
- )}>
- <div className={cn("bg-muted-foreground/5 max-w-[80%] border border-border",
- "p-1 rounded-lg",
- "flex flex-col items-end overflow-x-hidden"
- )}>
- {/* {message?.context && message.context.length > 0 && <div className='flex items-center w-full overflow-x-auto justify-end mb-2'><ContextList context={message.context} /></div>} */}
- <span className='px-3'><MemoizedMarkdown id={message.id} content={message.content} /></span>
- </div>
- </div >
- </MessageContainer>)
+ <MessageContainer copyContent={message.content}>
+ <div className={cn('justify-start', 'flex w-full')}>
+ <div className={cn('w-full', 'p-3 rounded-xl max-w-full', 'flex flex-col gap-2')}>
+ <MemoizedMarkdown id={message.id} content={message.content} />
+ </div>
+ </div>
+ </MessageContainer>
+ )
+
+ return (
+ <MessageContainer copyContent={message.content}>
+ <div className={cn('items-end', 'flex w-full flex-col gap-2')}>
+ <div
+ className={cn(
+ 'bg-muted-foreground/5 max-w-[80%] border border-border',
+ 'p-1 rounded-lg',
+ 'flex flex-col items-end overflow-x-hidden'
+ )}
+ >
+ {/* {message?.context && message.context.length > 0 && <div className='flex items-center w-full overflow-x-auto justify-end mb-2'><ContextList context={message.context} /></div>} */}
+ <span className="px-3">
+ <MemoizedMarkdown id={message.id} content={message.content} />
+ </span>
+ </div>
+ </div>
+ </MessageContainer>
+ )
}
-const MessageContainer = memo(({ children, copyContent }: { children: React.ReactNode, copyContent?: string }) => {
+const MessageContainer = memo(
+ ({ children, copyContent }: { children: React.ReactNode; copyContent?: string }) => {
return (
- <div className='relative group'>
- {children}
- <div className='-mt-1 group-hover:opacity-100 opacity-0 flex items-center justify-end z-1'>
- <div className='border rounded-md bg-background '><CopyButton content={copyContent ?? ""} /></div>
- </div>
+ <div className="relative group">
+ {children}
+ <div className="-mt-1 group-hover:opacity-100 opacity-0 flex items-center justify-end z-1">
+ <div className="border rounded-md bg-background ">
+ <CopyButton content={copyContent ?? ''} />
+ </div>
</div>
+ </div>
)
-})
+ }
+)
const MemoizedFloatingChat = memo(FloatingChat)
-MemoizedFloatingChat.displayName = 'MemoizedFloatingChat';
+MemoizedFloatingChat.displayName = 'MemoizedFloatingChat'
-export default MemoizedFloatingChat
\ No newline at end of file
+export default MemoizedFloatingChat
diff --git a/flowsint-app/src/renderer/src/components/chat/memoized-markdown.tsx b/flowsint-app/src/renderer/src/components/chat/memoized-markdown.tsx
index 3acc3826..e4278a35 100644
--- a/flowsint-app/src/renderer/src/components/chat/memoized-markdown.tsx
+++ b/flowsint-app/src/renderer/src/components/chat/memoized-markdown.tsx
@@ -1,64 +1,75 @@
-import { marked } from 'marked';
-import { memo, useMemo } from 'react';
-import ReactMarkdown from 'react-markdown';
+import { marked } from 'marked'
+import { memo, useMemo } from 'react'
+import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
-import { dracula } from 'react-syntax-highlighter/dist/esm/styles/prism';
-import { cn } from '@/lib/utils';
-import { CopyButton } from '../copy';
+import { dracula } from 'react-syntax-highlighter/dist/esm/styles/prism'
+import { cn } from '@/lib/utils'
+import { CopyButton } from '../copy'
function parseMarkdownIntoBlocks(markdown: string): string[] {
- const tokens = marked.lexer(markdown);
- return tokens.map(token => token.raw);
+ const tokens = marked.lexer(markdown)
+ return tokens.map((token) => token.raw)
}
const MemoizedMarkdownBlock = memo(
- ({ content }: { content: string }) => {
- return <ReactMarkdown
- components={{
- code({ node, className, children, ...props }) {
- const match = /language-(\w+)/.exec(className || '')
- return match ? (
- <div className='relative'>
- <SyntaxHighlighter
- children={String(children).replace(/\n$/, '')}
- style={dracula}
- language={match[1]}
- PreTag="div"
- className="rounded border border-border bg-muted px-1 py-0.5 !m-0 text-sm w-auto not-prose"
- {...props}
- />
- <div className='absolute top-2 right-2'>
- <CopyButton content={String(children).replace(/\n$/, '')} />
- </div>
- </div>
- ) : (
- <code className={cn("rounded border border-border bg-muted text-primary font-normal w-full px-1 py-0.5 text-sm not-prose", className)} {...props}>
- {children}
- </code>
- )
- }
- }}
- remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
- },
- (prevProps, nextProps) => {
- if (prevProps.content !== nextProps.content) return false;
- return true;
- },
-);
+ ({ content }: { content: string }) => {
+ return (
+ <ReactMarkdown
+ components={{
+ code({ node, className, children, ...props }) {
+ const match = /language-(\w+)/.exec(className || '')
+ return match ? (
+ <div className="relative">
+ <SyntaxHighlighter
+ children={String(children).replace(/\n$/, '')}
+ style={dracula}
+ language={match[1]}
+ PreTag="div"
+ className="rounded border border-border bg-muted px-1 py-0.5 !m-0 text-sm w-auto not-prose"
+ {...props}
+ />
+ <div className="absolute top-2 right-2">
+ <CopyButton content={String(children).replace(/\n$/, '')} />
+ </div>
+ </div>
+ ) : (
+ <code
+ className={cn(
+ 'rounded border border-border bg-muted text-primary font-normal w-full px-1 py-0.5 text-sm not-prose',
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </code>
+ )
+ }
+ }}
+ remarkPlugins={[remarkGfm]}
+ >
+ {content}
+ </ReactMarkdown>
+ )
+ },
+ (prevProps, nextProps) => {
+ if (prevProps.content !== nextProps.content) return false
+ return true
+ }
+)
-MemoizedMarkdownBlock.displayName = 'MemoizedMarkdownBlock';
+MemoizedMarkdownBlock.displayName = 'MemoizedMarkdownBlock'
-export const MemoizedMarkdown = memo(
- ({ content, id }: { content: string; id: string }) => {
- const blocks = useMemo(() => parseMarkdownIntoBlocks(content), [content]);
+export const MemoizedMarkdown = memo(({ content, id }: { content: string; id: string }) => {
+ const blocks = useMemo(() => parseMarkdownIntoBlocks(content), [content])
- return (
- <div className='prose max-w-none dark:prose-invert'>{blocks.map((block, index) => (
- <MemoizedMarkdownBlock content={block} key={`${id}-block_${index}`} />
- ))}
- </div>)
- },
-);
+ return (
+ <div className="prose max-w-none dark:prose-invert">
+ {blocks.map((block, index) => (
+ <MemoizedMarkdownBlock content={block} key={`${id}-block_${index}`} />
+ ))}
+ </div>
+ )
+})
-MemoizedMarkdown.displayName = 'MemoizedMarkdown';
\ No newline at end of file
+MemoizedMarkdown.displayName = 'MemoizedMarkdown'
diff --git a/flowsint-app/src/renderer/src/components/chat/resizable-chat.tsx b/flowsint-app/src/renderer/src/components/chat/resizable-chat.tsx
index fa67588a..ac43c0ff 100644
--- a/flowsint-app/src/renderer/src/components/chat/resizable-chat.tsx
+++ b/flowsint-app/src/renderer/src/components/chat/resizable-chat.tsx
@@ -3,148 +3,161 @@ import { cn } from '@/lib/utils'
import { useLayoutStore } from '@/stores/layout-store'
interface ResizableChatProps {
- children: React.ReactNode
- minWidth?: number
- minHeight?: number
- maxWidth?: number
- maxHeight?: number
+ children: React.ReactNode
+ minWidth?: number
+ minHeight?: number
+ maxWidth?: number
+ maxHeight?: number
}
export const ResizableChat: React.FC<ResizableChatProps> = ({
- children,
- minWidth = 400,
- minHeight = 400,
- maxWidth = 800,
- maxHeight = 800,
+ children,
+ minWidth = 400,
+ minHeight = 400,
+ maxWidth = 800,
+ maxHeight = 800
}) => {
- const { chatWidth, chatHeight, setChatDimensions } = useLayoutStore()
- const [isResizing, setIsResizing] = useState(false)
- const [resizeDirection, setResizeDirection] = useState<'se' | 'sw' | 'ne' | 'nw' | null>(null)
- const [startPos, setStartPos] = useState({ x: 0, y: 0 })
- const [startDimensions, setStartDimensions] = useState({ width: 0, height: 0 })
- const containerRef = useRef<HTMLDivElement>(null)
-
- const handleMouseDown = useCallback((direction: 'se' | 'sw' | 'ne' | 'nw') => (e: React.MouseEvent) => {
- e.preventDefault()
- e.stopPropagation()
-
- setIsResizing(true)
- setResizeDirection(direction)
- setStartPos({ x: e.clientX, y: e.clientY })
- setStartDimensions({ width: chatWidth, height: chatHeight })
-
- document.body.style.cursor = direction.includes('e') ? 'e-resize' : 'w-resize'
- document.body.style.userSelect = 'none'
- }, [chatWidth, chatHeight])
-
- const handleMouseMove = useCallback((e: MouseEvent): void => {
- if (!isResizing || !resizeDirection) return
-
- const deltaX = e.clientX - startPos.x
- const deltaY = e.clientY - startPos.y
-
- let newWidth = startDimensions.width
- let newHeight = startDimensions.height
-
- // Calculate new dimensions based on resize direction
- if (resizeDirection.includes('e')) {
- newWidth = Math.max(minWidth, Math.min(maxWidth, startDimensions.width + deltaX))
- } else if (resizeDirection.includes('w')) {
- newWidth = Math.max(minWidth, Math.min(maxWidth, startDimensions.width - deltaX))
- }
-
- if (resizeDirection.includes('s')) {
- newHeight = Math.max(minHeight, Math.min(maxHeight, startDimensions.height + deltaY))
- } else if (resizeDirection.includes('n')) {
- newHeight = Math.max(minHeight, Math.min(maxHeight, startDimensions.height - deltaY))
- }
-
- setChatDimensions(newWidth, newHeight)
- }, [isResizing, resizeDirection, startPos, startDimensions, minWidth, minHeight, maxWidth, maxHeight, setChatDimensions])
-
- const handleMouseUp = useCallback(() => {
- setIsResizing(false)
- setResizeDirection(null)
- document.body.style.cursor = ''
- document.body.style.userSelect = ''
- }, [])
-
- useEffect(() => {
- if (isResizing) {
- document.addEventListener('mousemove', handleMouseMove)
- document.addEventListener('mouseup', handleMouseUp)
-
- return () => {
- document.removeEventListener('mousemove', handleMouseMove)
- document.removeEventListener('mouseup', handleMouseUp)
- }
- }
- return undefined
- }, [isResizing, handleMouseMove, handleMouseUp])
-
- return (
- <div
- ref={containerRef}
- className={cn(
- "relative group overflow-hidden",
- isResizing && "pointer-events-none"
- )}
- style={{
- width: chatWidth,
- height: chatHeight,
- }}
- >
- {children}
-
- {/* Resize overlay when active */}
- {isResizing && (
- <div className="absolute inset-0 bg-primary/5 border-2 border-primary/30 rounded-2xl pointer-events-none" />
- )}
-
- {/* Resize handles */}
- <div
- className={cn(
- "absolute bottom-0 right-0 w-4 h-4 cursor-se-resize",
- "bg-transparent hover:bg-primary/20 transition-colors",
- "rounded-tl-md border-r border-b border-primary/20",
- "group-hover:border-primary/40",
- isResizing && "bg-primary/30 border-primary/50"
- )}
- onMouseDown={handleMouseDown('se')}
- />
-
- <div
- className={cn(
- "absolute bottom-0 left-0 w-4 h-4 cursor-sw-resize",
- "bg-transparent hover:bg-primary/20 transition-colors",
- "rounded-tr-md border-l border-b border-primary/20",
- "group-hover:border-primary/40",
- isResizing && "bg-primary/30 border-primary/50"
- )}
- onMouseDown={handleMouseDown('sw')}
- />
-
- <div
- className={cn(
- "absolute top-0 right-0 w-4 h-4 cursor-ne-resize",
- "bg-transparent hover:bg-primary/20 transition-colors",
- "rounded-bl-md border-r border-t border-primary/20",
- "group-hover:border-primary/40",
- isResizing && "bg-primary/30 border-primary/50"
- )}
- onMouseDown={handleMouseDown('ne')}
- />
-
- <div
- className={cn(
- "absolute top-0 left-0 w-4 h-4 cursor-nw-resize",
- "bg-transparent hover:bg-primary/20 transition-colors",
- "rounded-br-md border-l border-t border-primary/20",
- "group-hover:border-primary/40",
- isResizing && "bg-primary/30 border-primary/50"
- )}
- onMouseDown={handleMouseDown('nw')}
- />
- </div>
- )
-}
\ No newline at end of file
+ const { chatWidth, chatHeight, setChatDimensions } = useLayoutStore()
+ const [isResizing, setIsResizing] = useState(false)
+ const [resizeDirection, setResizeDirection] = useState<'se' | 'sw' | 'ne' | 'nw' | null>(null)
+ const [startPos, setStartPos] = useState({ x: 0, y: 0 })
+ const [startDimensions, setStartDimensions] = useState({ width: 0, height: 0 })
+ const containerRef = useRef<HTMLDivElement>(null)
+
+ const handleMouseDown = useCallback(
+ (direction: 'se' | 'sw' | 'ne' | 'nw') => (e: React.MouseEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ setIsResizing(true)
+ setResizeDirection(direction)
+ setStartPos({ x: e.clientX, y: e.clientY })
+ setStartDimensions({ width: chatWidth, height: chatHeight })
+
+ document.body.style.cursor = direction.includes('e') ? 'e-resize' : 'w-resize'
+ document.body.style.userSelect = 'none'
+ },
+ [chatWidth, chatHeight]
+ )
+
+ const handleMouseMove = useCallback(
+ (e: MouseEvent): void => {
+ if (!isResizing || !resizeDirection) return
+
+ const deltaX = e.clientX - startPos.x
+ const deltaY = e.clientY - startPos.y
+
+ let newWidth = startDimensions.width
+ let newHeight = startDimensions.height
+
+ // Calculate new dimensions based on resize direction
+ if (resizeDirection.includes('e')) {
+ newWidth = Math.max(minWidth, Math.min(maxWidth, startDimensions.width + deltaX))
+ } else if (resizeDirection.includes('w')) {
+ newWidth = Math.max(minWidth, Math.min(maxWidth, startDimensions.width - deltaX))
+ }
+
+ if (resizeDirection.includes('s')) {
+ newHeight = Math.max(minHeight, Math.min(maxHeight, startDimensions.height + deltaY))
+ } else if (resizeDirection.includes('n')) {
+ newHeight = Math.max(minHeight, Math.min(maxHeight, startDimensions.height - deltaY))
+ }
+
+ setChatDimensions(newWidth, newHeight)
+ },
+ [
+ isResizing,
+ resizeDirection,
+ startPos,
+ startDimensions,
+ minWidth,
+ minHeight,
+ maxWidth,
+ maxHeight,
+ setChatDimensions
+ ]
+ )
+
+ const handleMouseUp = useCallback(() => {
+ setIsResizing(false)
+ setResizeDirection(null)
+ document.body.style.cursor = ''
+ document.body.style.userSelect = ''
+ }, [])
+
+ useEffect(() => {
+ if (isResizing) {
+ document.addEventListener('mousemove', handleMouseMove)
+ document.addEventListener('mouseup', handleMouseUp)
+
+ return () => {
+ document.removeEventListener('mousemove', handleMouseMove)
+ document.removeEventListener('mouseup', handleMouseUp)
+ }
+ }
+ return undefined
+ }, [isResizing, handleMouseMove, handleMouseUp])
+
+ return (
+ <div
+ ref={containerRef}
+ className={cn('relative group overflow-hidden', isResizing && 'pointer-events-none')}
+ style={{
+ width: chatWidth,
+ height: chatHeight
+ }}
+ >
+ {children}
+
+ {/* Resize overlay when active */}
+ {isResizing && (
+ <div className="absolute inset-0 bg-primary/5 border-2 border-primary/30 rounded-2xl pointer-events-none" />
+ )}
+
+ {/* Resize handles */}
+ <div
+ className={cn(
+ 'absolute bottom-0 right-0 w-4 h-4 cursor-se-resize',
+ 'bg-transparent hover:bg-primary/20 transition-colors',
+ 'rounded-tl-md border-r border-b border-primary/20',
+ 'group-hover:border-primary/40',
+ isResizing && 'bg-primary/30 border-primary/50'
+ )}
+ onMouseDown={handleMouseDown('se')}
+ />
+
+ <div
+ className={cn(
+ 'absolute bottom-0 left-0 w-4 h-4 cursor-sw-resize',
+ 'bg-transparent hover:bg-primary/20 transition-colors',
+ 'rounded-tr-md border-l border-b border-primary/20',
+ 'group-hover:border-primary/40',
+ isResizing && 'bg-primary/30 border-primary/50'
+ )}
+ onMouseDown={handleMouseDown('sw')}
+ />
+
+ <div
+ className={cn(
+ 'absolute top-0 right-0 w-4 h-4 cursor-ne-resize',
+ 'bg-transparent hover:bg-primary/20 transition-colors',
+ 'rounded-bl-md border-r border-t border-primary/20',
+ 'group-hover:border-primary/40',
+ isResizing && 'bg-primary/30 border-primary/50'
+ )}
+ onMouseDown={handleMouseDown('ne')}
+ />
+
+ <div
+ className={cn(
+ 'absolute top-0 left-0 w-4 h-4 cursor-nw-resize',
+ 'bg-transparent hover:bg-primary/20 transition-colors',
+ 'rounded-br-md border-l border-t border-primary/20',
+ 'group-hover:border-primary/40',
+ isResizing && 'bg-primary/30 border-primary/50'
+ )}
+ onMouseDown={handleMouseDown('nw')}
+ />
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/command.tsx b/flowsint-app/src/renderer/src/components/command.tsx
index 2558cf5c..818702a2 100644
--- a/flowsint-app/src/renderer/src/components/command.tsx
+++ b/flowsint-app/src/renderer/src/components/command.tsx
@@ -1,248 +1,250 @@
+import * as React from 'react'
+import { Fingerprint, Search, Workflow, FileText, Waypoints } from 'lucide-react'
-import * as React from "react"
import {
- Fingerprint,
- Search,
- Workflow,
- FileText,
- Waypoints,
-} from "lucide-react"
-
-import {
- CommandDialog,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
- CommandSeparator,
-} from "@/components/ui/command"
-import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"
-import { Button } from "./ui/button"
-import { useNavigate } from "@tanstack/react-router"
-import { useQuery } from "@tanstack/react-query"
-import { investigationService } from "@/api/investigation-service"
-import { analysisService } from "@/api/analysis-service"
-import { type Investigation } from "@/types/investigation"
-import { type Analysis } from "@/types"
-import { Skeleton } from "./ui/skeleton"
+ CommandDialog,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator
+} from '@/components/ui/command'
+import { useKeyboardShortcut } from '@/hooks/use-keyboard-shortcut'
+import { Button } from './ui/button'
+import { useNavigate } from '@tanstack/react-router'
+import { useQuery } from '@tanstack/react-query'
+import { investigationService } from '@/api/investigation-service'
+import { analysisService } from '@/api/analysis-service'
+import { type Investigation } from '@/types/investigation'
+import { type Analysis } from '@/types'
+import { Skeleton } from './ui/skeleton'
// Skeleton component for command palette loading
function CommandSkeleton() {
- return (
- <div className="space-y-2 p-2">
- {[...Array(6)].map((_, i) => (
- <div key={i} className="flex items-center gap-2 p-2 rounded-md">
- <Skeleton className="h-4 w-4" />
- <Skeleton className="h-4 flex-1" />
- </div>
- ))}
+ return (
+ <div className="space-y-2 p-2">
+ {[...Array(6)].map((_, i) => (
+ <div key={i} className="flex items-center gap-2 p-2 rounded-md">
+ <Skeleton className="h-4 w-4" />
+ <Skeleton className="h-4 flex-1" />
</div>
- )
+ ))}
+ </div>
+ )
}
export function Command() {
- const [open, setOpen] = React.useState(false)
- const [searchQuery, setSearchQuery] = React.useState("")
- const navigate = useNavigate()
-
- // Fetch investigations when dialog opens
- const { data: investigations = [], isLoading: isLoadingInvestigations } = useQuery({
- queryKey: ["command-investigations"],
- queryFn: investigationService.get,
- enabled: open, // Only fetch when dialog is open
+ const [open, setOpen] = React.useState(false)
+ const [searchQuery, setSearchQuery] = React.useState('')
+ const navigate = useNavigate()
+
+ // Fetch investigations when dialog opens
+ const { data: investigations = [], isLoading: isLoadingInvestigations } = useQuery({
+ queryKey: ['command-investigations'],
+ queryFn: investigationService.get,
+ enabled: open // Only fetch when dialog is open
+ })
+
+ // Fetch all analyses when dialog opens
+ const { data: allAnalyses = [], isLoading: isLoadingAnalyses } = useQuery({
+ queryKey: ['command-analyses'],
+ queryFn: analysisService.get,
+ enabled: open // Only fetch when dialog is open
+ })
+
+ useKeyboardShortcut({
+ key: 'j',
+ ctrlOrCmd: true,
+ callback: () => {
+ setOpen((prev) => !prev)
+ }
+ })
+
+ // Filter investigations and analyses based on search query
+ const filteredData = React.useMemo(() => {
+ if (!searchQuery.trim()) {
+ return { investigations, analyses: allAnalyses }
+ }
+
+ const query = searchQuery.toLowerCase().trim()
+
+ const filteredInvestigations = investigations.filter((investigation: Investigation) => {
+ const matchesName = investigation.name.toLowerCase().includes(query)
+ const matchesDescription = investigation.description?.toLowerCase().includes(query)
+ const matchesSketches = investigation.sketches?.some((sketch) =>
+ sketch.title.toLowerCase().includes(query)
+ )
+ // Check if any analyses in this investigation match the query
+ const investigationAnalyses = allAnalyses.filter(
+ (analysis: Analysis) => analysis.investigation_id === investigation.id
+ )
+ const matchesAnalyses = investigationAnalyses.some(
+ (analysis) =>
+ analysis.title.toLowerCase().includes(query) ||
+ analysis.description?.toLowerCase().includes(query)
+ )
+ return matchesName || matchesDescription || matchesSketches || matchesAnalyses
})
- // Fetch all analyses when dialog opens
- const { data: allAnalyses = [], isLoading: isLoadingAnalyses } = useQuery({
- queryKey: ["command-analyses"],
- queryFn: analysisService.get,
- enabled: open, // Only fetch when dialog is open
+ // Filter analyses to only include those from filtered investigations
+ const filteredAnalyses = allAnalyses.filter((analysis: Analysis) => {
+ const matchesTitle = analysis.title.toLowerCase().includes(query)
+ const matchesDescription = analysis.description?.toLowerCase().includes(query)
+ const belongsToFilteredInvestigation = filteredInvestigations.some(
+ (inv) => inv.id === analysis.investigation_id
+ )
+ return (matchesTitle || matchesDescription) && belongsToFilteredInvestigation
})
- useKeyboardShortcut({
- key: "j",
- ctrlOrCmd: true,
- callback: () => {
- setOpen((prev) => !prev)
- },
- })
+ return { investigations: filteredInvestigations, analyses: filteredAnalyses }
+ }, [investigations, allAnalyses, searchQuery])
- // Filter investigations and analyses based on search query
- const filteredData = React.useMemo(() => {
- if (!searchQuery.trim()) {
- return { investigations, analyses: allAnalyses }
+ // Group analyses by investigation for display
+ const analysesByInvestigation = React.useMemo(() => {
+ const grouped: Record<string, Analysis[]> = {}
+ filteredData.analyses.forEach((analysis: Analysis) => {
+ if (analysis.investigation_id) {
+ if (!grouped[analysis.investigation_id]) {
+ grouped[analysis.investigation_id] = []
}
-
- const query = searchQuery.toLowerCase().trim()
-
- const filteredInvestigations = investigations.filter((investigation: Investigation) => {
- const matchesName = investigation.name.toLowerCase().includes(query)
- const matchesDescription = investigation.description?.toLowerCase().includes(query)
- const matchesSketches = investigation.sketches?.some(sketch =>
- sketch.title.toLowerCase().includes(query)
- )
- // Check if any analyses in this investigation match the query
- const investigationAnalyses = allAnalyses.filter((analysis: Analysis) =>
- analysis.investigation_id === investigation.id
- )
- const matchesAnalyses = investigationAnalyses.some(analysis =>
- analysis.title.toLowerCase().includes(query) ||
- analysis.description?.toLowerCase().includes(query)
- )
- return matchesName || matchesDescription || matchesSketches || matchesAnalyses
- })
-
- // Filter analyses to only include those from filtered investigations
- const filteredAnalyses = allAnalyses.filter((analysis: Analysis) => {
- const matchesTitle = analysis.title.toLowerCase().includes(query)
- const matchesDescription = analysis.description?.toLowerCase().includes(query)
- const belongsToFilteredInvestigation = filteredInvestigations.some(inv => inv.id === analysis.investigation_id)
- return (matchesTitle || matchesDescription) && belongsToFilteredInvestigation
- })
-
- return { investigations: filteredInvestigations, analyses: filteredAnalyses }
- }, [investigations, allAnalyses, searchQuery])
-
- // Group analyses by investigation for display
- const analysesByInvestigation = React.useMemo(() => {
- const grouped: Record<string, Analysis[]> = {}
- filteredData.analyses.forEach((analysis: Analysis) => {
- if (analysis.investigation_id) {
- if (!grouped[analysis.investigation_id]) {
- grouped[analysis.investigation_id] = []
- }
- grouped[analysis.investigation_id].push(analysis)
- }
- })
- return grouped
- }, [filteredData.analyses])
-
- const isLoading = isLoadingInvestigations || isLoadingAnalyses
-
- return (
- <>
- <Button variant="ghost" onClick={() => setOpen(true)} className="text-xs h-8 w-full max-w-3xs border flex rounded-full items-center justify-between hover:border-muted-foreground text-muted-foreground">
- <span className="flex items-center gap-2"><Search /> Search Flowsint{" "}</span>
- <kbd className="pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100">
- <span className="text-xs">⌘</span>J
- </kbd>
- </Button>
- <CommandDialog open={open} onOpenChange={setOpen}>
- <CommandInput
- placeholder="Type a command or search..."
- value={searchQuery}
- onValueChange={setSearchQuery}
- />
- <CommandList>
- {isLoading ? (
- <CommandSkeleton />
- ) : (
- <>
- {filteredData.investigations.length === 0 && filteredData.analyses.length === 0 ? (
- <CommandEmpty>No results found.</CommandEmpty>
- ) : (
- <>
- {filteredData.investigations.length > 0 && (
- <CommandGroup heading="Investigations">
- {filteredData.investigations.map((investigation: Investigation) => (
- <React.Fragment key={investigation.id}>
- <CommandItem
- onSelect={() => {
- navigate({
- to: "/dashboard/investigations/$investigationId",
- params: { investigationId: investigation.id },
- })
- setOpen(false)
- }}
- >
- <div className="flex items-center gap-2">
- <Fingerprint className="h-4 w-4" />
- <span className="flex-1">{investigation.name}</span>
- </div>
- </CommandItem>
-
- {/* Show sketches for this investigation */}
- {investigation.sketches?.map((sketch) => (
- <CommandItem
- key={sketch.id}
- onSelect={() => {
- navigate({
- to: "/dashboard/investigations/$investigationId/$type/$id",
- params: {
- investigationId: investigation.id,
- type: "graph",
- id: sketch.id,
- },
- })
- setOpen(false)
- }}
- >
- <div className="flex items-center gap-2 pl-6">
- <Waypoints className="h-4 w-4" />
- <span className="flex-1">{sketch.title}</span>
- </div>
- </CommandItem>
- ))}
-
- {/* Show analyses for this investigation */}
- {analysesByInvestigation[investigation.id]?.map((analysis) => (
- <CommandItem
- key={analysis.id}
- onSelect={() => {
- navigate({
- to: "/dashboard/investigations/$investigationId/$type/$id",
- params: {
- investigationId: investigation.id,
- type: "analysis",
- id: analysis.id,
- },
- })
- setOpen(false)
- }}
- >
- <div className="flex items-center gap-2 pl-6">
- <FileText className="h-4 w-4" />
- <span className="flex-1">{analysis.title}</span>
- </div>
- </CommandItem>
- ))}
- </React.Fragment>
- ))}
- </CommandGroup>
- )}
-
- <CommandSeparator />
- <CommandGroup heading="Quick Actions">
- <CommandItem
- onSelect={() => {
- navigate({ to: "/dashboard/investigations" })
- setOpen(false)
- }}
- >
- <div className="flex items-center gap-2">
- <Fingerprint className="h-4 w-4" />
- <span>All Investigations</span>
- </div>
- </CommandItem>
- <CommandItem
- onSelect={() => {
- navigate({ to: "/dashboard/flows" })
- setOpen(false)
- }}
- >
- <div className="flex items-center gap-2">
- <Workflow className="h-4 w-4" />
- <span>Transforms</span>
- </div>
- </CommandItem>
- </CommandGroup>
- </>
- )}
- </>
- )}
- </CommandList>
- </CommandDialog>
- </>
- )
+ grouped[analysis.investigation_id].push(analysis)
+ }
+ })
+ return grouped
+ }, [filteredData.analyses])
+
+ const isLoading = isLoadingInvestigations || isLoadingAnalyses
+
+ return (
+ <>
+ <Button
+ variant="ghost"
+ onClick={() => setOpen(true)}
+ className="text-xs h-8 w-full max-w-3xs border flex rounded-full items-center justify-between hover:border-muted-foreground text-muted-foreground"
+ >
+ <span className="flex items-center gap-2">
+ <Search /> Search Flowsint{' '}
+ </span>
+ <kbd className="pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100">
+ <span className="text-xs">⌘</span>J
+ </kbd>
+ </Button>
+ <CommandDialog open={open} onOpenChange={setOpen}>
+ <CommandInput
+ placeholder="Type a command or search..."
+ value={searchQuery}
+ onValueChange={setSearchQuery}
+ />
+ <CommandList>
+ {isLoading ? (
+ <CommandSkeleton />
+ ) : (
+ <>
+ {filteredData.investigations.length === 0 && filteredData.analyses.length === 0 ? (
+ <CommandEmpty>No results found.</CommandEmpty>
+ ) : (
+ <>
+ {filteredData.investigations.length > 0 && (
+ <CommandGroup heading="Investigations">
+ {filteredData.investigations.map((investigation: Investigation) => (
+ <React.Fragment key={investigation.id}>
+ <CommandItem
+ onSelect={() => {
+ navigate({
+ to: '/dashboard/investigations/$investigationId',
+ params: { investigationId: investigation.id }
+ })
+ setOpen(false)
+ }}
+ >
+ <div className="flex items-center gap-2">
+ <Fingerprint className="h-4 w-4" />
+ <span className="flex-1">{investigation.name}</span>
+ </div>
+ </CommandItem>
+
+ {/* Show sketches for this investigation */}
+ {investigation.sketches?.map((sketch) => (
+ <CommandItem
+ key={sketch.id}
+ onSelect={() => {
+ navigate({
+ to: '/dashboard/investigations/$investigationId/$type/$id',
+ params: {
+ investigationId: investigation.id,
+ type: 'graph',
+ id: sketch.id
+ }
+ })
+ setOpen(false)
+ }}
+ >
+ <div className="flex items-center gap-2 pl-6">
+ <Waypoints className="h-4 w-4" />
+ <span className="flex-1">{sketch.title}</span>
+ </div>
+ </CommandItem>
+ ))}
+
+ {/* Show analyses for this investigation */}
+ {analysesByInvestigation[investigation.id]?.map((analysis) => (
+ <CommandItem
+ key={analysis.id}
+ onSelect={() => {
+ navigate({
+ to: '/dashboard/investigations/$investigationId/$type/$id',
+ params: {
+ investigationId: investigation.id,
+ type: 'analysis',
+ id: analysis.id
+ }
+ })
+ setOpen(false)
+ }}
+ >
+ <div className="flex items-center gap-2 pl-6">
+ <FileText className="h-4 w-4" />
+ <span className="flex-1">{analysis.title}</span>
+ </div>
+ </CommandItem>
+ ))}
+ </React.Fragment>
+ ))}
+ </CommandGroup>
+ )}
+
+ <CommandSeparator />
+ <CommandGroup heading="Quick Actions">
+ <CommandItem
+ onSelect={() => {
+ navigate({ to: '/dashboard/investigations' })
+ setOpen(false)
+ }}
+ >
+ <div className="flex items-center gap-2">
+ <Fingerprint className="h-4 w-4" />
+ <span>All Investigations</span>
+ </div>
+ </CommandItem>
+ <CommandItem
+ onSelect={() => {
+ navigate({ to: '/dashboard/flows' })
+ setOpen(false)
+ }}
+ >
+ <div className="flex items-center gap-2">
+ <Workflow className="h-4 w-4" />
+ <span>Transforms</span>
+ </div>
+ </CommandItem>
+ </CommandGroup>
+ </>
+ )}
+ </>
+ )}
+ </CommandList>
+ </CommandDialog>
+ </>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/copy.tsx b/flowsint-app/src/renderer/src/components/copy.tsx
index dc44b5f2..e8190918 100644
--- a/flowsint-app/src/renderer/src/components/copy.tsx
+++ b/flowsint-app/src/renderer/src/components/copy.tsx
@@ -1,47 +1,56 @@
-
-import { useState, useCallback } from "react"
-import { CheckIcon, CopyIcon } from "lucide-react"
-import { useTimeout } from "usehooks-ts"
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
-import { Button } from "@/components/ui/button"
-import { cn } from "@/lib/utils"
+import { useState, useCallback } from 'react'
+import { CheckIcon, CopyIcon } from 'lucide-react'
+import { useTimeout } from 'usehooks-ts'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import { Button } from '@/components/ui/button'
+import { cn } from '@/lib/utils'
interface CopyButtonProps {
- content: string
- delay?: number
- className?: string
+ content: string
+ delay?: number
+ className?: string
}
export function CopyButton({ content, className, delay = 2000 }: CopyButtonProps) {
- const [isCopied, setIsCopied] = useState(false)
+ const [isCopied, setIsCopied] = useState(false)
- const handleCopy = useCallback((e: { stopPropagation: () => void }) => {
- e.stopPropagation()
- navigator.clipboard.writeText(content).then(() => {
- setIsCopied(true)
- })
- }, [content])
+ const handleCopy = useCallback(
+ (e: { stopPropagation: () => void }) => {
+ e.stopPropagation()
+ navigator.clipboard.writeText(content).then(() => {
+ setIsCopied(true)
+ })
+ },
+ [content]
+ )
- useTimeout(
- () => {
- if (isCopied) {
- setIsCopied(false)
- }
- },
- isCopied ? delay : null,
- )
+ useTimeout(
+ () => {
+ if (isCopied) {
+ setIsCopied(false)
+ }
+ },
+ isCopied ? delay : null
+ )
- return (
- <Tooltip open={isCopied}>
- <TooltipTrigger asChild>
- <Button className={cn("h-7 w-7", className)} size={"icon"} variant="ghost" onClick={handleCopy} aria-label="Copy content">
- {isCopied ? <CheckIcon className="!h-3.5 !w-3.5 text-primary" /> : <CopyIcon className="!h-3.5 !w-3.5 opacity-50" />}
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- Copied !
- </TooltipContent>
- </Tooltip>
- )
+ return (
+ <Tooltip open={isCopied}>
+ <TooltipTrigger asChild>
+ <Button
+ className={cn('h-7 w-7', className)}
+ size={'icon'}
+ variant="ghost"
+ onClick={handleCopy}
+ aria-label="Copy content"
+ >
+ {isCopied ? (
+ <CheckIcon className="!h-3.5 !w-3.5 text-primary" />
+ ) : (
+ <CopyIcon className="!h-3.5 !w-3.5 opacity-50" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Copied !</TooltipContent>
+ </Tooltip>
+ )
}
-
diff --git a/flowsint-app/src/renderer/src/components/dashboard/analysis-cards.tsx b/flowsint-app/src/renderer/src/components/dashboard/analysis-cards.tsx
index 4d16f585..58c422d2 100644
--- a/flowsint-app/src/renderer/src/components/dashboard/analysis-cards.tsx
+++ b/flowsint-app/src/renderer/src/components/dashboard/analysis-cards.tsx
@@ -1,172 +1,169 @@
-import { useQuery } from "@tanstack/react-query";
-import { analysisService } from "@/api/analysis-service";
-import { Link } from "@tanstack/react-router";
-import { Card, CardContent } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Skeleton } from "@/components/ui/skeleton";
-import { FileText, Plus, Clock } from "lucide-react";
-import { formatDistanceToNow } from "date-fns";
+import { useQuery } from '@tanstack/react-query'
+import { analysisService } from '@/api/analysis-service'
+import { Link } from '@tanstack/react-router'
+import { Card, CardContent } from '@/components/ui/card'
+import { Button } from '@/components/ui/button'
+import { Badge } from '@/components/ui/badge'
+import { Skeleton } from '@/components/ui/skeleton'
+import { FileText, Plus, Clock } from 'lucide-react'
+import { formatDistanceToNow } from 'date-fns'
interface AnalysisCardProps {
- analysis: any;
+ analysis: any
}
function AnalysisCard({ analysis }: AnalysisCardProps) {
- return (
- <Link
- to="/dashboard/investigations/$investigationId/$type/$id"
- params={{
- investigationId: analysis.investigation_id || "",
- type: "analysis",
- id: analysis.id
- }}
- className="block"
- >
- <Card className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border-2 hover:border-primary/20">
- <CardContent className="h-full flex flex-col">
- {/* Header with title and type */}
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3 flex-1 min-w-0">
- <div className="w-8 h-8 bg-green-100 dark:bg-green-900/20 rounded-lg flex items-center justify-center flex-shrink-0">
- <FileText className="w-4 h-4 text-green-600 dark:text-green-400" />
- </div>
- <div className="flex-1 min-w-0">
- <h3 className="font-semibold text-sm truncate group-hover:text-green-600 dark:group-hover:text-green-400 transition-colors">
- {analysis.title}
- </h3>
- <p className="text-xs text-muted-foreground">
- Analysis document
- </p>
- </div>
- </div>
- <Badge variant="secondary" className="text-xs flex-shrink-0 ml-2">
- Doc
- </Badge>
- </div>
+ return (
+ <Link
+ to="/dashboard/investigations/$investigationId/$type/$id"
+ params={{
+ investigationId: analysis.investigation_id || '',
+ type: 'analysis',
+ id: analysis.id
+ }}
+ className="block"
+ >
+ <Card className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border-2 hover:border-primary/20">
+ <CardContent className="h-full flex flex-col">
+ {/* Header with title and type */}
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <div className="w-8 h-8 bg-green-100 dark:bg-green-900/20 rounded-lg flex items-center justify-center flex-shrink-0">
+ <FileText className="w-4 h-4 text-green-600 dark:text-green-400" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <h3 className="font-semibold text-sm truncate group-hover:text-green-600 dark:group-hover:text-green-400 transition-colors">
+ {analysis.title}
+ </h3>
+ <p className="text-xs text-muted-foreground">Analysis document</p>
+ </div>
+ </div>
+ <Badge variant="secondary" className="text-xs flex-shrink-0 ml-2">
+ Doc
+ </Badge>
+ </div>
- {/* Description */}
- <div className="flex-1 mb-3 min-w-0">
- <p className="text-xs text-muted-foreground line-clamp-2">
- {analysis.description || "No description available"}
- </p>
- </div>
+ {/* Description */}
+ <div className="flex-1 mb-3 min-w-0">
+ <p className="text-xs text-muted-foreground line-clamp-2">
+ {analysis.description || 'No description available'}
+ </p>
+ </div>
- {/* Footer with timestamp */}
- <div className="mt-auto">
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Clock className="w-3 h-3" />
- <span>
- Updated {formatDistanceToNow(new Date(analysis.last_updated_at), { addSuffix: true })}
- </span>
- </div>
- </div>
- </CardContent>
- </Card>
- </Link>
- );
+ {/* Footer with timestamp */}
+ <div className="mt-auto">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Clock className="w-3 h-3" />
+ <span>
+ Updated{' '}
+ {formatDistanceToNow(new Date(analysis.last_updated_at), { addSuffix: true })}
+ </span>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </Link>
+ )
}
function AnalysisCardsSkeleton() {
- return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Skeleton className="h-6 w-6" />
- <Skeleton className="h-6 w-48" />
- </div>
- <Skeleton className="h-8 w-24" />
- </div>
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {Array.from({ length: 8 }).map((_, i) => (
- <Card key={i} className="w-full">
- <CardContent className="p-4 h-full flex flex-col">
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3">
- <Skeleton className="w-8 h-8 rounded-lg" />
- <div className="flex-1">
- <Skeleton className="h-4 w-32 mb-1" />
- <Skeleton className="h-3 w-20" />
- </div>
- </div>
- <Skeleton className="h-5 w-8" />
- </div>
- <div className="flex-1 mb-3">
- <Skeleton className="h-3 w-full mb-1" />
- <Skeleton className="h-3 w-3/4" />
- </div>
- <div className="mt-auto">
- <Skeleton className="h-3 w-24" />
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-6 w-6" />
+ <Skeleton className="h-6 w-48" />
</div>
- );
+ <Skeleton className="h-8 w-24" />
+ </div>
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {Array.from({ length: 8 }).map((_, i) => (
+ <Card key={i} className="w-full">
+ <CardContent className="p-4 h-full flex flex-col">
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3">
+ <Skeleton className="w-8 h-8 rounded-lg" />
+ <div className="flex-1">
+ <Skeleton className="h-4 w-32 mb-1" />
+ <Skeleton className="h-3 w-20" />
+ </div>
+ </div>
+ <Skeleton className="h-5 w-8" />
+ </div>
+ <div className="flex-1 mb-3">
+ <Skeleton className="h-3 w-full mb-1" />
+ <Skeleton className="h-3 w-3/4" />
+ </div>
+ <div className="mt-auto">
+ <Skeleton className="h-3 w-24" />
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ </div>
+ )
}
export function AnalysisCards() {
- const { data: analyses, isLoading } = useQuery({
- queryKey: ["analyses", "dashboard"],
- queryFn: analysisService.get,
- });
+ const { data: analyses, isLoading } = useQuery({
+ queryKey: ['analyses', 'dashboard'],
+ queryFn: analysisService.get
+ })
- if (isLoading) {
- return <AnalysisCardsSkeleton />;
- }
-
- if (!analyses || analyses.length === 0) {
- return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <FileText className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Recent Analyses</h2>
- </div>
- <Button size="sm" variant="outline">
- <Plus className="w-4 h-4 mr-2" />
- New Analysis
- </Button>
- </div>
- <div className="text-center py-12">
- <FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
- <h3 className="text-lg font-semibold mb-2">No analyses yet</h3>
- <p className="text-muted-foreground mb-4">
- Create your first analysis to start documenting your findings.
- </p>
- <Button>
- <Plus className="w-4 h-4 mr-2" />
- Create Analysis
- </Button>
- </div>
- </div>
- );
- }
+ if (isLoading) {
+ return <AnalysisCardsSkeleton />
+ }
+ if (!analyses || analyses.length === 0) {
return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <FileText className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Recent Analyses</h2>
- <span className="text-sm text-muted-foreground">
- {analyses.length} analyses
- </span>
- </div>
- <div className="flex items-center gap-2">
- <Button size="sm" variant="outline">
- <Plus className="w-4 h-4 mr-2" />
- New Analysis
- </Button>
- </div>
- </div>
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileText className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Recent Analyses</h2>
+ </div>
+ <Button size="sm" variant="outline">
+ <Plus className="w-4 h-4 mr-2" />
+ New Analysis
+ </Button>
+ </div>
+ <div className="text-center py-12">
+ <FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
+ <h3 className="text-lg font-semibold mb-2">No analyses yet</h3>
+ <p className="text-muted-foreground mb-4">
+ Create your first analysis to start documenting your findings.
+ </p>
+ <Button>
+ <Plus className="w-4 h-4 mr-2" />
+ Create Analysis
+ </Button>
+ </div>
+ </div>
+ )
+ }
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {analyses.slice(0, 8).map((analysis: any) => (
- <AnalysisCard key={analysis.id} analysis={analysis} />
- ))}
- </div>
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileText className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Recent Analyses</h2>
+ <span className="text-sm text-muted-foreground">{analyses.length} analyses</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline">
+ <Plus className="w-4 h-4 mr-2" />
+ New Analysis
+ </Button>
</div>
- );
-}
\ No newline at end of file
+ </div>
+
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {analyses.slice(0, 8).map((analysis: any) => (
+ <AnalysisCard key={analysis.id} analysis={analysis} />
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/dashboard/investigation-analyses.tsx b/flowsint-app/src/renderer/src/components/dashboard/investigation-analyses.tsx
index 7d162aa3..ee0b7210 100644
--- a/flowsint-app/src/renderer/src/components/dashboard/investigation-analyses.tsx
+++ b/flowsint-app/src/renderer/src/components/dashboard/investigation-analyses.tsx
@@ -1,176 +1,172 @@
-import { useQuery } from "@tanstack/react-query";
-import { analysisService } from "@/api/analysis-service";
-import { Link } from "@tanstack/react-router";
-import { Card, CardContent } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Skeleton } from "@/components/ui/skeleton";
-import { FileText, Plus, Clock } from "lucide-react";
-import { formatDistanceToNow } from "date-fns";
+import { useQuery } from '@tanstack/react-query'
+import { analysisService } from '@/api/analysis-service'
+import { Link } from '@tanstack/react-router'
+import { Card, CardContent } from '@/components/ui/card'
+import { Button } from '@/components/ui/button'
+import { Badge } from '@/components/ui/badge'
+import { Skeleton } from '@/components/ui/skeleton'
+import { FileText, Plus, Clock } from 'lucide-react'
+import { formatDistanceToNow } from 'date-fns'
interface InvestigationAnalysesProps {
- investigationId: string;
+ investigationId: string
}
function AnalysisCard({ analysis, investigationId }: { analysis: any; investigationId: string }) {
- return (
- <Link
- to="/dashboard/investigations/$investigationId/$type/$id"
- params={{
- investigationId: investigationId,
- type: "analysis",
- id: analysis.id
- }}
- className="block"
- >
- <Card className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border-2 hover:border-primary/20">
- <CardContent className="h-full flex flex-col">
- {/* Header with title and type */}
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3 flex-1 min-w-0">
- <div className="w-8 h-8 bg-green-100 dark:bg-green-900/20 rounded-lg flex items-center justify-center flex-shrink-0">
- <FileText className="w-4 h-4 text-green-600 dark:text-green-400" />
- </div>
- <div className="flex-1 min-w-0">
- <h3 className="font-semibold text-sm truncate group-hover:text-green-600 dark:group-hover:text-green-400 transition-colors">
- {analysis.title}
- </h3>
- <p className="text-xs text-muted-foreground">
- Analysis document
- </p>
- </div>
- </div>
- <Badge variant="secondary" className="text-xs flex-shrink-0 ml-2">
- Doc
- </Badge>
- </div>
-
- {/* Description */}
- <div className="flex-1 mb-3 min-w-0">
- <p className="text-xs text-muted-foreground line-clamp-2">
- {analysis.description || "No description available"}
- </p>
- </div>
-
- {/* Footer with timestamp */}
- <div className="mt-auto">
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Clock className="w-3 h-3" />
- <span>
- Updated {formatDistanceToNow(new Date(analysis.last_updated_at), { addSuffix: true })}
- </span>
- </div>
- </div>
- </CardContent>
- </Card>
- </Link>
- );
+ return (
+ <Link
+ to="/dashboard/investigations/$investigationId/$type/$id"
+ params={{
+ investigationId: investigationId,
+ type: 'analysis',
+ id: analysis.id
+ }}
+ className="block"
+ >
+ <Card className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border-2 hover:border-primary/20">
+ <CardContent className="h-full flex flex-col">
+ {/* Header with title and type */}
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <div className="w-8 h-8 bg-green-100 dark:bg-green-900/20 rounded-lg flex items-center justify-center flex-shrink-0">
+ <FileText className="w-4 h-4 text-green-600 dark:text-green-400" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <h3 className="font-semibold text-sm truncate group-hover:text-green-600 dark:group-hover:text-green-400 transition-colors">
+ {analysis.title}
+ </h3>
+ <p className="text-xs text-muted-foreground">Analysis document</p>
+ </div>
+ </div>
+ <Badge variant="secondary" className="text-xs flex-shrink-0 ml-2">
+ Doc
+ </Badge>
+ </div>
+
+ {/* Description */}
+ <div className="flex-1 mb-3 min-w-0">
+ <p className="text-xs text-muted-foreground line-clamp-2">
+ {analysis.description || 'No description available'}
+ </p>
+ </div>
+
+ {/* Footer with timestamp */}
+ <div className="mt-auto">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Clock className="w-3 h-3" />
+ <span>
+ Updated{' '}
+ {formatDistanceToNow(new Date(analysis.last_updated_at), { addSuffix: true })}
+ </span>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </Link>
+ )
}
function InvestigationAnalysesSkeleton() {
- return (
- <div className="space-y-4 @container">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Skeleton className="h-6 w-6" />
- <Skeleton className="h-6 w-48" />
- </div>
- <Skeleton className="h-8 w-24" />
- </div>
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {Array.from({ length: 8 }).map((_, i) => (
- <Card key={i} className="w-full">
- <CardContent className="p-4 h-full flex flex-col">
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3">
- <Skeleton className="w-8 h-8 rounded-lg" />
- <div className="flex-1">
- <Skeleton className="h-4 w-32 mb-1" />
- <Skeleton className="h-3 w-20" />
- </div>
- </div>
- <Skeleton className="h-5 w-8" />
- </div>
- <div className="flex-1 mb-3">
- <Skeleton className="h-3 w-full mb-1" />
- <Skeleton className="h-3 w-3/4" />
- </div>
- <div className="mt-auto">
- <Skeleton className="h-3 w-24" />
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
+ return (
+ <div className="space-y-4 @container">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-6 w-6" />
+ <Skeleton className="h-6 w-48" />
</div>
- );
+ <Skeleton className="h-8 w-24" />
+ </div>
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {Array.from({ length: 8 }).map((_, i) => (
+ <Card key={i} className="w-full">
+ <CardContent className="p-4 h-full flex flex-col">
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3">
+ <Skeleton className="w-8 h-8 rounded-lg" />
+ <div className="flex-1">
+ <Skeleton className="h-4 w-32 mb-1" />
+ <Skeleton className="h-3 w-20" />
+ </div>
+ </div>
+ <Skeleton className="h-5 w-8" />
+ </div>
+ <div className="flex-1 mb-3">
+ <Skeleton className="h-3 w-full mb-1" />
+ <Skeleton className="h-3 w-3/4" />
+ </div>
+ <div className="mt-auto">
+ <Skeleton className="h-3 w-24" />
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ </div>
+ )
}
export function InvestigationAnalyses({ investigationId }: InvestigationAnalysesProps) {
- const { data: analyses, isLoading } = useQuery({
- queryKey: ["analyses", "investigation", investigationId],
- queryFn: () => analysisService.getByInvestigationId(investigationId),
- staleTime: 30000, // 30 seconds
- refetchOnWindowFocus: false,
- refetchOnMount: false,
- });
+ const { data: analyses, isLoading } = useQuery({
+ queryKey: ['analyses', 'investigation', investigationId],
+ queryFn: () => analysisService.getByInvestigationId(investigationId),
+ staleTime: 30000, // 30 seconds
+ refetchOnWindowFocus: false,
+ refetchOnMount: false
+ })
- if (isLoading) {
- return <InvestigationAnalysesSkeleton />;
- }
-
- if (!analyses || analyses.length === 0) {
- return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <FileText className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Analyses</h2>
- </div>
- <Button size="sm" variant="outline">
- <Plus className="w-4 h-4 mr-2" />
- New Analysis
- </Button>
- </div>
- <div className="text-center py-12">
- <FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
- <h3 className="text-lg font-semibold mb-2">No analyses yet</h3>
- <p className="text-muted-foreground mb-4">
- Create your first analysis to start documenting your findings.
- </p>
- <Button>
- <Plus className="w-4 h-4 mr-2" />
- Create Analysis
- </Button>
- </div>
- </div>
- );
- }
+ if (isLoading) {
+ return <InvestigationAnalysesSkeleton />
+ }
+ if (!analyses || analyses.length === 0) {
return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <FileText className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Analyses</h2>
- <span className="text-sm text-muted-foreground">
- {analyses.length} analyses
- </span>
- </div>
- <div className="flex items-center gap-2">
- <Button size="sm" variant="outline">
- <Plus className="w-4 h-4 mr-2" />
- New Analysis
- </Button>
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileText className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Analyses</h2>
+ </div>
+ <Button size="sm" variant="outline">
+ <Plus className="w-4 h-4 mr-2" />
+ New Analysis
+ </Button>
+ </div>
+ <div className="text-center py-12">
+ <FileText className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
+ <h3 className="text-lg font-semibold mb-2">No analyses yet</h3>
+ <p className="text-muted-foreground mb-4">
+ Create your first analysis to start documenting your findings.
+ </p>
+ <Button>
+ <Plus className="w-4 h-4 mr-2" />
+ Create Analysis
+ </Button>
+ </div>
+ </div>
+ )
+ }
- </div>
- </div>
-
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {analyses.slice(0, 8).map((analysis: any) => (
- <AnalysisCard key={analysis.id} analysis={analysis} investigationId={investigationId} />
- ))}
- </div>
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileText className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Analyses</h2>
+ <span className="text-sm text-muted-foreground">{analyses.length} analyses</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline">
+ <Plus className="w-4 h-4 mr-2" />
+ New Analysis
+ </Button>
</div>
- );
-}
\ No newline at end of file
+ </div>
+
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {analyses.slice(0, 8).map((analysis: any) => (
+ <AnalysisCard key={analysis.id} analysis={analysis} investigationId={investigationId} />
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/dashboard/investigation-cards.tsx b/flowsint-app/src/renderer/src/components/dashboard/investigation-cards.tsx
index de515e08..44777524 100644
--- a/flowsint-app/src/renderer/src/components/dashboard/investigation-cards.tsx
+++ b/flowsint-app/src/renderer/src/components/dashboard/investigation-cards.tsx
@@ -1,222 +1,226 @@
-import { useQuery } from "@tanstack/react-query";
-import { investigationService } from "@/api/investigation-service";
-import { Link } from "@tanstack/react-router";
-import { Card, CardContent } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Skeleton } from "@/components/ui/skeleton";
-import { FolderOpen, Plus, Clock, FileText, BarChart3, Search } from "lucide-react";
-import { formatDistanceToNow } from "date-fns";
-import NewInvestigation from "@/components/investigations/new-investigation";
-import { queryKeys } from "@/api/query-keys";
-import ErrorState from "@/components/shared/error-state";
+import { useQuery } from '@tanstack/react-query'
+import { investigationService } from '@/api/investigation-service'
+import { Link } from '@tanstack/react-router'
+import { Card, CardContent } from '@/components/ui/card'
+import { Button } from '@/components/ui/button'
+import { Badge } from '@/components/ui/badge'
+import { Skeleton } from '@/components/ui/skeleton'
+import { FolderOpen, Plus, Clock, FileText, BarChart3, Search } from 'lucide-react'
+import { formatDistanceToNow } from 'date-fns'
+import NewInvestigation from '@/components/investigations/new-investigation'
+import { queryKeys } from '@/api/query-keys'
+import ErrorState from '@/components/shared/error-state'
interface InvestigationCardProps {
- investigation: any;
+ investigation: any
}
function InvestigationCard({ investigation }: InvestigationCardProps) {
- const sketchCount = investigation.sketches?.length || 0;
- const analysisCount = investigation.analyses?.length || 0;
- const totalItems = sketchCount + analysisCount;
+ const sketchCount = investigation.sketches?.length || 0
+ const analysisCount = investigation.analyses?.length || 0
+ const totalItems = sketchCount + analysisCount
- return (
- <Link
- to="/dashboard/investigations/$investigationId"
- params={{ investigationId: investigation.id }}
- className="block"
- >
- <Card className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border hover:border-primary/20">
- <CardContent className="h-full flex flex-col">
- {/* Header with title and count */}
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3 flex-1 min-w-0">
- <div className="w-8 h-8 bg-primary/10 rounded-lg flex items-center justify-center flex-shrink-0">
- <Search className="w-4 h-4 text-primary" />
- </div>
- <div className="flex-1 min-w-0">
- <h3 className="font-semibold text-sm truncate group-hover:text-primary transition-colors">
- {investigation.name}
- </h3>
- <p className="text-xs text-muted-foreground">
- {totalItems} items
- </p>
- </div>
- </div>
- <Badge variant="secondary" className="text-xs flex-shrink-0 ml-2">
- {totalItems}
- </Badge>
- </div>
+ return (
+ <Link
+ to="/dashboard/investigations/$investigationId"
+ params={{ investigationId: investigation.id }}
+ className="block"
+ >
+ <Card className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border hover:border-primary/20">
+ <CardContent className="h-full flex flex-col">
+ {/* Header with title and count */}
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <div className="w-8 h-8 bg-primary/10 rounded-lg flex items-center justify-center flex-shrink-0">
+ <Search className="w-4 h-4 text-primary" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <h3 className="font-semibold text-sm truncate group-hover:text-primary transition-colors">
+ {investigation.name}
+ </h3>
+ <p className="text-xs text-muted-foreground">{totalItems} items</p>
+ </div>
+ </div>
+ <Badge variant="secondary" className="text-xs flex-shrink-0 ml-2">
+ {totalItems}
+ </Badge>
+ </div>
- {/* Stats row */}
- <div className="flex items-center gap-4 text-xs text-muted-foreground mb-3">
- <div className="flex items-center gap-1">
- <BarChart3 className="w-3 h-3" />
- <span>{sketchCount} graphs</span>
- </div>
- <div className="flex items-center gap-1">
- <FileText className="w-3 h-3" />
- <span>{analysisCount} docs</span>
- </div>
- </div>
+ {/* Stats row */}
+ <div className="flex items-center gap-4 text-xs text-muted-foreground mb-3">
+ <div className="flex items-center gap-1">
+ <BarChart3 className="w-3 h-3" />
+ <span>{sketchCount} graphs</span>
+ </div>
+ <div className="flex items-center gap-1">
+ <FileText className="w-3 h-3" />
+ <span>{analysisCount} docs</span>
+ </div>
+ </div>
- {/* Footer with timestamp */}
- <div className="mt-auto">
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Clock className="w-3 h-3" />
- <span>
- Updated {formatDistanceToNow(new Date(investigation.last_updated_at), { addSuffix: true })}
- </span>
- </div>
- </div>
- </CardContent>
- </Card>
- </Link>
- );
+ {/* Footer with timestamp */}
+ <div className="mt-auto">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Clock className="w-3 h-3" />
+ <span>
+ Updated{' '}
+ {formatDistanceToNow(new Date(investigation.last_updated_at), { addSuffix: true })}
+ </span>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </Link>
+ )
}
function InvestigationCardsSkeleton() {
- return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Skeleton className="h-6 w-6" />
- <Skeleton className="h-6 w-48" />
- </div>
- <Skeleton className="h-8 w-24" />
- </div>
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {Array.from({ length: 8 }).map((_, i) => (
- <Card key={i} className="w-full">
- <CardContent className="p-4 h-full flex flex-col">
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3">
- <Skeleton className="w-8 h-8 rounded-lg" />
- <div className="flex-1">
- <Skeleton className="h-4 w-32 mb-1" />
- <Skeleton className="h-3 w-16" />
- </div>
- </div>
- <Skeleton className="h-5 w-8" />
- </div>
- <div className="flex gap-4 mb-3">
- <Skeleton className="h-3 w-16" />
- <Skeleton className="h-3 w-16" />
- </div>
- <div className="mt-auto">
- <Skeleton className="h-3 w-24" />
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-6 w-6" />
+ <Skeleton className="h-6 w-48" />
</div>
- );
+ <Skeleton className="h-8 w-24" />
+ </div>
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {Array.from({ length: 8 }).map((_, i) => (
+ <Card key={i} className="w-full">
+ <CardContent className="p-4 h-full flex flex-col">
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3">
+ <Skeleton className="w-8 h-8 rounded-lg" />
+ <div className="flex-1">
+ <Skeleton className="h-4 w-32 mb-1" />
+ <Skeleton className="h-3 w-16" />
+ </div>
+ </div>
+ <Skeleton className="h-5 w-8" />
+ </div>
+ <div className="flex gap-4 mb-3">
+ <Skeleton className="h-3 w-16" />
+ <Skeleton className="h-3 w-16" />
+ </div>
+ <div className="mt-auto">
+ <Skeleton className="h-3 w-24" />
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ </div>
+ )
}
export function InvestigationCards() {
- const { data: investigations, isLoading, error, refetch } = useQuery({
- queryKey: queryKeys.investigations.dashboard,
- queryFn: investigationService.get,
- staleTime: 30000, // 30 seconds
- refetchOnWindowFocus: false,
- refetchOnMount: false,
- });
-
- if (isLoading) {
- return <InvestigationCardsSkeleton />;
- }
-
- if (error) {
- return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Search className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Investigations</h2>
- </div>
- <div className="flex items-center gap-2">
- <Button disabled size="sm">
- <Plus className="w-4 h-4 mr-2" />
- New Investigation
- </Button>
- </div>
- </div>
- <ErrorState
- title="Couldn't load investigations"
- description="Something went wrong while fetching data. Please try again."
- error={error}
- onRetry={() => refetch()}
- />
- </div>
- );
- }
+ const {
+ data: investigations,
+ isLoading,
+ error,
+ refetch
+ } = useQuery({
+ queryKey: queryKeys.investigations.dashboard,
+ queryFn: investigationService.get,
+ staleTime: 30000, // 30 seconds
+ refetchOnWindowFocus: false,
+ refetchOnMount: false
+ })
- if (!investigations || investigations.length === 0) {
- return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Search className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Investigations</h2>
- </div>
- <NewInvestigation noDropDown>
- <Button size="sm">
- <Plus className="w-4 h-4 mr-2" />
- New Investigation
- </Button>
- </NewInvestigation>
- </div>
+ if (isLoading) {
+ return <InvestigationCardsSkeleton />
+ }
- {/* Compact dashed card empty state */}
- <Card className="border-dashed">
- <CardContent className="p-6">
- <div className="w-full flex flex-col items-center text-center gap-3">
- <div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center">
- <FolderOpen className="h-5 w-5 text-muted-foreground" />
- </div>
- <div className="text-base font-medium">No investigations yet</div>
- <div className="text-sm text-muted-foreground max-w-md">
- Create an investigation to group graphs and analyses by case or topic.
- </div>
- <NewInvestigation noDropDown>
- <Button>
- <Plus className="w-4 h-4 mr-2" />
- Create investigation
- </Button>
- </NewInvestigation>
- </div>
- </CardContent>
- </Card>
- </div>
- );
- }
+ if (error) {
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Search className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Investigations</h2>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button disabled size="sm">
+ <Plus className="w-4 h-4 mr-2" />
+ New Investigation
+ </Button>
+ </div>
+ </div>
+ <ErrorState
+ title="Couldn't load investigations"
+ description="Something went wrong while fetching data. Please try again."
+ error={error}
+ onRetry={() => refetch()}
+ />
+ </div>
+ )
+ }
+ if (!investigations || investigations.length === 0) {
return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Search className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Investigations</h2>
- <span className="text-sm text-muted-foreground">
- {investigations.length} investigations
- </span>
- </div>
- <div className="flex items-center gap-2">
- <NewInvestigation noDropDown>
- <Button size="sm">
- <Plus className="w-4 h-4 mr-2" />
- New Investigation
- </Button>
- </NewInvestigation>
- </div>
- </div>
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Search className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Investigations</h2>
+ </div>
+ <NewInvestigation noDropDown>
+ <Button size="sm">
+ <Plus className="w-4 h-4 mr-2" />
+ New Investigation
+ </Button>
+ </NewInvestigation>
+ </div>
- <div className="grid grid-cols-1 cq-xs:grid-cols-2 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {investigations.slice(0, 8).map((investigation: any) => (
- <InvestigationCard key={investigation.id} investigation={investigation} />
- ))}
+ {/* Compact dashed card empty state */}
+ <Card className="border-dashed">
+ <CardContent className="p-6">
+ <div className="w-full flex flex-col items-center text-center gap-3">
+ <div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center">
+ <FolderOpen className="h-5 w-5 text-muted-foreground" />
+ </div>
+ <div className="text-base font-medium">No investigations yet</div>
+ <div className="text-sm text-muted-foreground max-w-md">
+ Create an investigation to group graphs and analyses by case or topic.
+ </div>
+ <NewInvestigation noDropDown>
+ <Button>
+ <Plus className="w-4 h-4 mr-2" />
+ Create investigation
+ </Button>
+ </NewInvestigation>
</div>
+ </CardContent>
+ </Card>
+ </div>
+ )
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Search className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Investigations</h2>
+ <span className="text-sm text-muted-foreground">
+ {investigations.length} investigations
+ </span>
</div>
- );
-}
\ No newline at end of file
+ <div className="flex items-center gap-2">
+ <NewInvestigation noDropDown>
+ <Button size="sm">
+ <Plus className="w-4 h-4 mr-2" />
+ New Investigation
+ </Button>
+ </NewInvestigation>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 cq-xs:grid-cols-2 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {investigations.slice(0, 8).map((investigation: any) => (
+ <InvestigationCard key={investigation.id} investigation={investigation} />
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/dashboard/investigation-skeleton.tsx b/flowsint-app/src/renderer/src/components/dashboard/investigation-skeleton.tsx
index 2f805c80..2f0a0671 100644
--- a/flowsint-app/src/renderer/src/components/dashboard/investigation-skeleton.tsx
+++ b/flowsint-app/src/renderer/src/components/dashboard/investigation-skeleton.tsx
@@ -2,92 +2,95 @@ import { Skeleton } from '@/components/ui/skeleton'
import { Card, CardContent, CardHeader } from '@/components/ui/card'
export function InvestigationSkeleton() {
- return (
- <div className="h-full w-full px-4 py-12 bg-background overflow-auto">
- <div className='max-w-4xl mx-auto flex flex-col gap-12 items-center justify-start' style={{ containerType: 'inline-size' }}>
- {/* Recent Investigations Skeleton */}
- <div className="w-full space-y-4">
- <div className="flex items-center justify-between">
- <Skeleton className="h-7 w-48" />
- <Skeleton className="h-9 w-28" />
- </div>
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {[...Array(2)].map((_, i) => (
- <Card key={i} className="p-4">
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <Skeleton className="h-5 w-32" />
- <Skeleton className="h-4 w-20" />
- </div>
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-3/4" />
- <div className="flex items-center gap-2">
- <Skeleton className="h-4 w-4" />
- <Skeleton className="h-4 w-24" />
- </div>
- </div>
- </Card>
- ))}
- </div>
+ return (
+ <div className="h-full w-full px-4 py-12 bg-background overflow-auto">
+ <div
+ className="max-w-4xl mx-auto flex flex-col gap-12 items-center justify-start"
+ style={{ containerType: 'inline-size' }}
+ >
+ {/* Recent Investigations Skeleton */}
+ <div className="w-full space-y-4">
+ <div className="flex items-center justify-between">
+ <Skeleton className="h-7 w-48" />
+ <Skeleton className="h-9 w-28" />
+ </div>
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {[...Array(2)].map((_, i) => (
+ <Card key={i} className="p-4">
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <Skeleton className="h-5 w-32" />
+ <Skeleton className="h-4 w-20" />
+ </div>
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-4 w-4" />
+ <Skeleton className="h-4 w-24" />
+ </div>
</div>
+ </Card>
+ ))}
+ </div>
+ </div>
- {/* Get Started Section Skeleton */}
- <div className="w-full space-y-4">
- <Skeleton className="h-7 w-48" />
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {[...Array(3)].map((_, i) => (
- <Card key={i}>
- <CardHeader className="flex flex-row items-center gap-3 pb-2">
- <Skeleton className="h-9 w-9 rounded-lg" />
- <Skeleton className="h-6 w-32" />
- </CardHeader>
- <CardContent>
- <Skeleton className="h-4 w-full mb-2" />
- <Skeleton className="h-4 w-3/4" />
- </CardContent>
- </Card>
- ))}
- </div>
- </div>
+ {/* Get Started Section Skeleton */}
+ <div className="w-full space-y-4">
+ <Skeleton className="h-7 w-48" />
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {[...Array(3)].map((_, i) => (
+ <Card key={i}>
+ <CardHeader className="flex flex-row items-center gap-3 pb-2">
+ <Skeleton className="h-9 w-9 rounded-lg" />
+ <Skeleton className="h-6 w-32" />
+ </CardHeader>
+ <CardContent>
+ <Skeleton className="h-4 w-full mb-2" />
+ <Skeleton className="h-4 w-3/4" />
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ </div>
- {/* Discover Section Skeleton */}
- <div className="w-full space-y-4">
- <Skeleton className="h-7 w-48" />
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {[...Array(2)].map((_, i) => (
- <Card key={i}>
- <CardHeader className="flex flex-row items-center gap-3 pb-2">
- <Skeleton className="h-9 w-9 rounded-lg" />
- <Skeleton className="h-6 w-40" />
- </CardHeader>
- <CardContent>
- <Skeleton className="h-4 w-full mb-2" />
- <Skeleton className="h-4 w-3/4" />
- </CardContent>
- </Card>
- ))}
- </div>
- </div>
+ {/* Discover Section Skeleton */}
+ <div className="w-full space-y-4">
+ <Skeleton className="h-7 w-48" />
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {[...Array(2)].map((_, i) => (
+ <Card key={i}>
+ <CardHeader className="flex flex-row items-center gap-3 pb-2">
+ <Skeleton className="h-9 w-9 rounded-lg" />
+ <Skeleton className="h-6 w-40" />
+ </CardHeader>
+ <CardContent>
+ <Skeleton className="h-4 w-full mb-2" />
+ <Skeleton className="h-4 w-3/4" />
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ </div>
- {/* Useful Resources Skeleton */}
- <div className="w-full space-y-4">
- <Skeleton className="h-7 w-48" />
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {[...Array(2)].map((_, i) => (
- <Card key={i}>
- <CardHeader className="flex flex-row items-center gap-3 pb-2">
- <Skeleton className="h-9 w-9 rounded-lg" />
- <Skeleton className="h-6 w-40" />
- </CardHeader>
- <CardContent>
- <Skeleton className="h-4 w-full mb-2" />
- <Skeleton className="h-4 w-3/4" />
- </CardContent>
- </Card>
- ))}
- </div>
- </div>
- </div>
+ {/* Useful Resources Skeleton */}
+ <div className="w-full space-y-4">
+ <Skeleton className="h-7 w-48" />
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {[...Array(2)].map((_, i) => (
+ <Card key={i}>
+ <CardHeader className="flex flex-row items-center gap-3 pb-2">
+ <Skeleton className="h-9 w-9 rounded-lg" />
+ <Skeleton className="h-6 w-40" />
+ </CardHeader>
+ <CardContent>
+ <Skeleton className="h-4 w-full mb-2" />
+ <Skeleton className="h-4 w-3/4" />
+ </CardContent>
+ </Card>
+ ))}
+ </div>
</div>
- )
-}
\ No newline at end of file
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/dashboard/investigation-sketches.tsx b/flowsint-app/src/renderer/src/components/dashboard/investigation-sketches.tsx
index 6466e047..bbf31e35 100644
--- a/flowsint-app/src/renderer/src/components/dashboard/investigation-sketches.tsx
+++ b/flowsint-app/src/renderer/src/components/dashboard/investigation-sketches.tsx
@@ -1,198 +1,198 @@
-import { useQuery } from "@tanstack/react-query";
-import { investigationService } from "@/api/investigation-service";
-import { Link } from "@tanstack/react-router";
-import { Card, CardContent } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Skeleton } from "@/components/ui/skeleton";
-import { BarChart3, Plus, Clock } from "lucide-react";
-import { formatDistanceToNow } from "date-fns";
-import NewSketch from "@/components/graphs/new-sketch";
-import ErrorState from "@/components/shared/error-state";
+import { useQuery } from '@tanstack/react-query'
+import { investigationService } from '@/api/investigation-service'
+import { Link } from '@tanstack/react-router'
+import { Card, CardContent } from '@/components/ui/card'
+import { Button } from '@/components/ui/button'
+import { Badge } from '@/components/ui/badge'
+import { Skeleton } from '@/components/ui/skeleton'
+import { BarChart3, Plus, Clock } from 'lucide-react'
+import { formatDistanceToNow } from 'date-fns'
+import NewSketch from '@/components/graphs/new-sketch'
+import ErrorState from '@/components/shared/error-state'
interface InvestigationSketchesProps {
- investigationId: string;
- title: string
+ investigationId: string
+ title: string
}
function SketchCard({ sketch, investigationId }: { sketch: any; investigationId: string }) {
- return (
- <Link
- to="/dashboard/investigations/$investigationId/$type/$id"
- params={{
- investigationId: investigationId,
- type: "graph",
- id: sketch.id
- }}
- className="block"
- >
- <Card className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border-2 hover:border-primary/20">
- <CardContent className="h-full flex flex-col">
- {/* Header with title and type */}
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3 flex-1 min-w-0">
- <div className="w-8 h-8 bg-blue-100 dark:bg-blue-900/20 rounded-lg flex items-center justify-center flex-shrink-0">
- <BarChart3 className="w-4 h-4 text-blue-600 dark:text-blue-400" />
- </div>
- <div className="flex-1 min-w-0">
- <h3 className="font-semibold text-sm truncate group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
- {sketch.title}
- </h3>
- <p className="text-xs text-muted-foreground">
- Graph sketch
- </p>
- </div>
- </div>
- <Badge variant="secondary" className="text-xs flex-shrink-0 ml-2">
- Graph
- </Badge>
- </div>
+ return (
+ <Link
+ to="/dashboard/investigations/$investigationId/$type/$id"
+ params={{
+ investigationId: investigationId,
+ type: 'graph',
+ id: sketch.id
+ }}
+ className="block"
+ >
+ <Card className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border-2 hover:border-primary/20">
+ <CardContent className="h-full flex flex-col">
+ {/* Header with title and type */}
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <div className="w-8 h-8 bg-blue-100 dark:bg-blue-900/20 rounded-lg flex items-center justify-center flex-shrink-0">
+ <BarChart3 className="w-4 h-4 text-blue-600 dark:text-blue-400" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <h3 className="font-semibold text-sm truncate group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
+ {sketch.title}
+ </h3>
+ <p className="text-xs text-muted-foreground">Graph sketch</p>
+ </div>
+ </div>
+ <Badge variant="secondary" className="text-xs flex-shrink-0 ml-2">
+ Graph
+ </Badge>
+ </div>
- {/* Description */}
- <div className="flex-1 mb-3 min-w-0">
- <p className="text-xs text-muted-foreground line-clamp-2">
- {sketch.description || "No description available"}
- </p>
- </div>
+ {/* Description */}
+ <div className="flex-1 mb-3 min-w-0">
+ <p className="text-xs text-muted-foreground line-clamp-2">
+ {sketch.description || 'No description available'}
+ </p>
+ </div>
- {/* Footer with timestamp */}
- <div className="mt-auto">
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Clock className="w-3 h-3" />
- <span>
- Updated {formatDistanceToNow(new Date(sketch.last_updated_at), { addSuffix: true })}
- </span>
- </div>
- </div>
- </CardContent>
- </Card>
- </Link>
- );
+ {/* Footer with timestamp */}
+ <div className="mt-auto">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Clock className="w-3 h-3" />
+ <span>
+ Updated {formatDistanceToNow(new Date(sketch.last_updated_at), { addSuffix: true })}
+ </span>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </Link>
+ )
}
function InvestigationSketchesSkeleton() {
- return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Skeleton className="h-6 w-6" />
- <Skeleton className="h-6 w-48" />
- </div>
- <Skeleton className="h-8 w-24" />
- </div>
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {Array.from({ length: 8 }).map((_, i) => (
- <Card key={i} className="w-full">
- <CardContent className="p-4 h-full flex flex-col">
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3">
- <Skeleton className="w-8 h-8 rounded-lg" />
- <div className="flex-1">
- <Skeleton className="h-4 w-32 mb-1" />
- <Skeleton className="h-3 w-20" />
- </div>
- </div>
- <Skeleton className="h-5 w-8" />
- </div>
- <div className="flex-1 mb-3">
- <Skeleton className="h-3 w-full mb-1" />
- <Skeleton className="h-3 w-3/4" />
- </div>
- <div className="mt-auto">
- <Skeleton className="h-3 w-24" />
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-6 w-6" />
+ <Skeleton className="h-6 w-48" />
</div>
- );
+ <Skeleton className="h-8 w-24" />
+ </div>
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {Array.from({ length: 8 }).map((_, i) => (
+ <Card key={i} className="w-full">
+ <CardContent className="p-4 h-full flex flex-col">
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3">
+ <Skeleton className="w-8 h-8 rounded-lg" />
+ <div className="flex-1">
+ <Skeleton className="h-4 w-32 mb-1" />
+ <Skeleton className="h-3 w-20" />
+ </div>
+ </div>
+ <Skeleton className="h-5 w-8" />
+ </div>
+ <div className="flex-1 mb-3">
+ <Skeleton className="h-3 w-full mb-1" />
+ <Skeleton className="h-3 w-3/4" />
+ </div>
+ <div className="mt-auto">
+ <Skeleton className="h-3 w-24" />
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ </div>
+ )
}
export function InvestigationSketches({ investigationId, title }: InvestigationSketchesProps) {
- const { data: investigation, isLoading, error, refetch } = useQuery({
- queryKey: ["investigation", "sketches", investigationId],
- queryFn: () => investigationService.getById(investigationId),
- staleTime: 30000, // 30 seconds
- refetchOnWindowFocus: false,
- refetchOnMount: false,
- });
+ const {
+ data: investigation,
+ isLoading,
+ error,
+ refetch
+ } = useQuery({
+ queryKey: ['investigation', 'sketches', investigationId],
+ queryFn: () => investigationService.getById(investigationId),
+ staleTime: 30000, // 30 seconds
+ refetchOnWindowFocus: false,
+ refetchOnMount: false
+ })
- if (isLoading) {
- return <InvestigationSketchesSkeleton />;
- }
+ if (isLoading) {
+ return <InvestigationSketchesSkeleton />
+ }
- if (error) {
- return (
- <ErrorState
- title="Couldn't load sketches"
- description="Something went wrong while fetching data. Please try again."
- error={error}
- onRetry={() => refetch()}
- />
- );
- }
+ if (error) {
+ return (
+ <ErrorState
+ title="Couldn't load sketches"
+ description="Something went wrong while fetching data. Please try again."
+ error={error}
+ onRetry={() => refetch()}
+ />
+ )
+ }
- const sketches = investigation?.sketches || [];
-
- if (sketches.length === 0) {
- return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <BarChart3 className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Sketches</h2>
- </div>
- <NewSketch>
- <Button size="sm">
- <Plus className="w-4 h-4 mr-2" />
- New Sketch
- </Button>
- </NewSketch>
- </div>
- <div className="text-center py-12">
- <BarChart3 className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
- <h3 className="text-lg font-semibold mb-2">No sketches yet</h3>
- <p className="text-muted-foreground mb-4">
- Create your first sketch to start visualizing your investigation data.
- </p>
- <NewSketch>
- <Button>
- <Plus className="w-4 h-4 mr-2" />
- Create Sketch
- </Button>
- </NewSketch>
- </div>
- </div>
- );
- }
+ const sketches = investigation?.sketches || []
+ if (sketches.length === 0) {
return (
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <BarChart3 className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">{title}</h2>
- <span className="text-sm text-muted-foreground">
- {sketches.length} sketches
- </span>
- </div>
- <div className="flex items-center gap-2">
- <NewSketch>
- <Button size="sm">
- <Plus className="w-4 h-4 mr-2" />
- New Sketch
- </Button>
- </NewSketch>
-
- </div>
- </div>
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <BarChart3 className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Sketches</h2>
+ </div>
+ <NewSketch>
+ <Button size="sm">
+ <Plus className="w-4 h-4 mr-2" />
+ New Sketch
+ </Button>
+ </NewSketch>
+ </div>
+ <div className="text-center py-12">
+ <BarChart3 className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
+ <h3 className="text-lg font-semibold mb-2">No sketches yet</h3>
+ <p className="text-muted-foreground mb-4">
+ Create your first sketch to start visualizing your investigation data.
+ </p>
+ <NewSketch>
+ <Button>
+ <Plus className="w-4 h-4 mr-2" />
+ Create Sketch
+ </Button>
+ </NewSketch>
+ </div>
+ </div>
+ )
+ }
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
- {sketches.slice(0, 8).map((sketch: any) => (
- <SketchCard key={sketch.id} sketch={sketch} investigationId={investigationId} />
- ))}
- </div>
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <BarChart3 className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">{title}</h2>
+ <span className="text-sm text-muted-foreground">{sketches.length} sketches</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <NewSketch>
+ <Button size="sm">
+ <Plus className="w-4 h-4 mr-2" />
+ New Sketch
+ </Button>
+ </NewSketch>
</div>
- );
-}
\ No newline at end of file
+ </div>
+
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-4">
+ {sketches.slice(0, 8).map((sketch: any) => (
+ <SketchCard key={sketch.id} sketch={sketch} investigationId={investigationId} />
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/dashboard/main-chart.tsx b/flowsint-app/src/renderer/src/components/dashboard/main-chart.tsx
index bd27a881..85b83910 100644
--- a/flowsint-app/src/renderer/src/components/dashboard/main-chart.tsx
+++ b/flowsint-app/src/renderer/src/components/dashboard/main-chart.tsx
@@ -1,289 +1,265 @@
-import * as React from "react"
-import { Area, AreaChart, CartesianGrid, XAxis } from "recharts"
+import * as React from 'react'
+import { Area, AreaChart, CartesianGrid, XAxis } from 'recharts'
-import { useIsMobile } from "@/hooks/use-mobile"
+import { useIsMobile } from '@/hooks/use-mobile'
import {
- Card,
- CardAction,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card"
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle
+} from '@/components/ui/card'
import {
- ChartConfig,
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
-} from "@/components/ui/chart"
+ ChartConfig,
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent
+} from '@/components/ui/chart'
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select"
-import {
- ToggleGroup,
- ToggleGroupItem,
-} from "@/components/ui/toggle-group"
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select'
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
-export const description = "An interactive area chart"
+export const description = 'An interactive area chart'
const chartData = [
- { date: "2024-04-01", desktop: 222, mobile: 150 },
- { date: "2024-04-02", desktop: 97, mobile: 180 },
- { date: "2024-04-03", desktop: 167, mobile: 120 },
- { date: "2024-04-04", desktop: 242, mobile: 260 },
- { date: "2024-04-05", desktop: 373, mobile: 290 },
- { date: "2024-04-06", desktop: 301, mobile: 340 },
- { date: "2024-04-07", desktop: 245, mobile: 180 },
- { date: "2024-04-08", desktop: 409, mobile: 320 },
- { date: "2024-04-09", desktop: 59, mobile: 110 },
- { date: "2024-04-10", desktop: 261, mobile: 190 },
- { date: "2024-04-11", desktop: 327, mobile: 350 },
- { date: "2024-04-12", desktop: 292, mobile: 210 },
- { date: "2024-04-13", desktop: 342, mobile: 380 },
- { date: "2024-04-14", desktop: 137, mobile: 220 },
- { date: "2024-04-15", desktop: 120, mobile: 170 },
- { date: "2024-04-16", desktop: 138, mobile: 190 },
- { date: "2024-04-17", desktop: 446, mobile: 360 },
- { date: "2024-04-18", desktop: 364, mobile: 410 },
- { date: "2024-04-19", desktop: 243, mobile: 180 },
- { date: "2024-04-20", desktop: 89, mobile: 150 },
- { date: "2024-04-21", desktop: 137, mobile: 200 },
- { date: "2024-04-22", desktop: 224, mobile: 170 },
- { date: "2024-04-23", desktop: 138, mobile: 230 },
- { date: "2024-04-24", desktop: 387, mobile: 290 },
- { date: "2024-04-25", desktop: 215, mobile: 250 },
- { date: "2024-04-26", desktop: 75, mobile: 130 },
- { date: "2024-04-27", desktop: 383, mobile: 420 },
- { date: "2024-04-28", desktop: 122, mobile: 180 },
- { date: "2024-04-29", desktop: 315, mobile: 240 },
- { date: "2024-04-30", desktop: 454, mobile: 380 },
- { date: "2024-05-01", desktop: 165, mobile: 220 },
- { date: "2024-05-02", desktop: 293, mobile: 310 },
- { date: "2024-05-03", desktop: 247, mobile: 190 },
- { date: "2024-05-04", desktop: 385, mobile: 420 },
- { date: "2024-05-05", desktop: 481, mobile: 390 },
- { date: "2024-05-06", desktop: 498, mobile: 520 },
- { date: "2024-05-07", desktop: 388, mobile: 300 },
- { date: "2024-05-08", desktop: 149, mobile: 210 },
- { date: "2024-05-09", desktop: 227, mobile: 180 },
- { date: "2024-05-10", desktop: 293, mobile: 330 },
- { date: "2024-05-11", desktop: 335, mobile: 270 },
- { date: "2024-05-12", desktop: 197, mobile: 240 },
- { date: "2024-05-13", desktop: 197, mobile: 160 },
- { date: "2024-05-14", desktop: 448, mobile: 490 },
- { date: "2024-05-15", desktop: 473, mobile: 380 },
- { date: "2024-05-16", desktop: 338, mobile: 400 },
- { date: "2024-05-17", desktop: 499, mobile: 420 },
- { date: "2024-05-18", desktop: 315, mobile: 350 },
- { date: "2024-05-19", desktop: 235, mobile: 180 },
- { date: "2024-05-20", desktop: 177, mobile: 230 },
- { date: "2024-05-21", desktop: 82, mobile: 140 },
- { date: "2024-05-22", desktop: 81, mobile: 120 },
- { date: "2024-05-23", desktop: 252, mobile: 290 },
- { date: "2024-05-24", desktop: 294, mobile: 220 },
- { date: "2024-05-25", desktop: 201, mobile: 250 },
- { date: "2024-05-26", desktop: 213, mobile: 170 },
- { date: "2024-05-27", desktop: 420, mobile: 460 },
- { date: "2024-05-28", desktop: 233, mobile: 190 },
- { date: "2024-05-29", desktop: 78, mobile: 130 },
- { date: "2024-05-30", desktop: 340, mobile: 280 },
- { date: "2024-05-31", desktop: 178, mobile: 230 },
- { date: "2024-06-01", desktop: 178, mobile: 200 },
- { date: "2024-06-02", desktop: 470, mobile: 410 },
- { date: "2024-06-03", desktop: 103, mobile: 160 },
- { date: "2024-06-04", desktop: 439, mobile: 380 },
- { date: "2024-06-05", desktop: 88, mobile: 140 },
- { date: "2024-06-06", desktop: 294, mobile: 250 },
- { date: "2024-06-07", desktop: 323, mobile: 370 },
- { date: "2024-06-08", desktop: 385, mobile: 320 },
- { date: "2024-06-09", desktop: 438, mobile: 480 },
- { date: "2024-06-10", desktop: 155, mobile: 200 },
- { date: "2024-06-11", desktop: 92, mobile: 150 },
- { date: "2024-06-12", desktop: 492, mobile: 420 },
- { date: "2024-06-13", desktop: 81, mobile: 130 },
- { date: "2024-06-14", desktop: 426, mobile: 380 },
- { date: "2024-06-15", desktop: 307, mobile: 350 },
- { date: "2024-06-16", desktop: 371, mobile: 310 },
- { date: "2024-06-17", desktop: 475, mobile: 520 },
- { date: "2024-06-18", desktop: 107, mobile: 170 },
- { date: "2024-06-19", desktop: 341, mobile: 290 },
- { date: "2024-06-20", desktop: 408, mobile: 450 },
- { date: "2024-06-21", desktop: 169, mobile: 210 },
- { date: "2024-06-22", desktop: 317, mobile: 270 },
- { date: "2024-06-23", desktop: 480, mobile: 530 },
- { date: "2024-06-24", desktop: 132, mobile: 180 },
- { date: "2024-06-25", desktop: 141, mobile: 190 },
- { date: "2024-06-26", desktop: 434, mobile: 380 },
- { date: "2024-06-27", desktop: 448, mobile: 490 },
- { date: "2024-06-28", desktop: 149, mobile: 200 },
- { date: "2024-06-29", desktop: 103, mobile: 160 },
- { date: "2024-06-30", desktop: 446, mobile: 400 },
+ { date: '2024-04-01', desktop: 222, mobile: 150 },
+ { date: '2024-04-02', desktop: 97, mobile: 180 },
+ { date: '2024-04-03', desktop: 167, mobile: 120 },
+ { date: '2024-04-04', desktop: 242, mobile: 260 },
+ { date: '2024-04-05', desktop: 373, mobile: 290 },
+ { date: '2024-04-06', desktop: 301, mobile: 340 },
+ { date: '2024-04-07', desktop: 245, mobile: 180 },
+ { date: '2024-04-08', desktop: 409, mobile: 320 },
+ { date: '2024-04-09', desktop: 59, mobile: 110 },
+ { date: '2024-04-10', desktop: 261, mobile: 190 },
+ { date: '2024-04-11', desktop: 327, mobile: 350 },
+ { date: '2024-04-12', desktop: 292, mobile: 210 },
+ { date: '2024-04-13', desktop: 342, mobile: 380 },
+ { date: '2024-04-14', desktop: 137, mobile: 220 },
+ { date: '2024-04-15', desktop: 120, mobile: 170 },
+ { date: '2024-04-16', desktop: 138, mobile: 190 },
+ { date: '2024-04-17', desktop: 446, mobile: 360 },
+ { date: '2024-04-18', desktop: 364, mobile: 410 },
+ { date: '2024-04-19', desktop: 243, mobile: 180 },
+ { date: '2024-04-20', desktop: 89, mobile: 150 },
+ { date: '2024-04-21', desktop: 137, mobile: 200 },
+ { date: '2024-04-22', desktop: 224, mobile: 170 },
+ { date: '2024-04-23', desktop: 138, mobile: 230 },
+ { date: '2024-04-24', desktop: 387, mobile: 290 },
+ { date: '2024-04-25', desktop: 215, mobile: 250 },
+ { date: '2024-04-26', desktop: 75, mobile: 130 },
+ { date: '2024-04-27', desktop: 383, mobile: 420 },
+ { date: '2024-04-28', desktop: 122, mobile: 180 },
+ { date: '2024-04-29', desktop: 315, mobile: 240 },
+ { date: '2024-04-30', desktop: 454, mobile: 380 },
+ { date: '2024-05-01', desktop: 165, mobile: 220 },
+ { date: '2024-05-02', desktop: 293, mobile: 310 },
+ { date: '2024-05-03', desktop: 247, mobile: 190 },
+ { date: '2024-05-04', desktop: 385, mobile: 420 },
+ { date: '2024-05-05', desktop: 481, mobile: 390 },
+ { date: '2024-05-06', desktop: 498, mobile: 520 },
+ { date: '2024-05-07', desktop: 388, mobile: 300 },
+ { date: '2024-05-08', desktop: 149, mobile: 210 },
+ { date: '2024-05-09', desktop: 227, mobile: 180 },
+ { date: '2024-05-10', desktop: 293, mobile: 330 },
+ { date: '2024-05-11', desktop: 335, mobile: 270 },
+ { date: '2024-05-12', desktop: 197, mobile: 240 },
+ { date: '2024-05-13', desktop: 197, mobile: 160 },
+ { date: '2024-05-14', desktop: 448, mobile: 490 },
+ { date: '2024-05-15', desktop: 473, mobile: 380 },
+ { date: '2024-05-16', desktop: 338, mobile: 400 },
+ { date: '2024-05-17', desktop: 499, mobile: 420 },
+ { date: '2024-05-18', desktop: 315, mobile: 350 },
+ { date: '2024-05-19', desktop: 235, mobile: 180 },
+ { date: '2024-05-20', desktop: 177, mobile: 230 },
+ { date: '2024-05-21', desktop: 82, mobile: 140 },
+ { date: '2024-05-22', desktop: 81, mobile: 120 },
+ { date: '2024-05-23', desktop: 252, mobile: 290 },
+ { date: '2024-05-24', desktop: 294, mobile: 220 },
+ { date: '2024-05-25', desktop: 201, mobile: 250 },
+ { date: '2024-05-26', desktop: 213, mobile: 170 },
+ { date: '2024-05-27', desktop: 420, mobile: 460 },
+ { date: '2024-05-28', desktop: 233, mobile: 190 },
+ { date: '2024-05-29', desktop: 78, mobile: 130 },
+ { date: '2024-05-30', desktop: 340, mobile: 280 },
+ { date: '2024-05-31', desktop: 178, mobile: 230 },
+ { date: '2024-06-01', desktop: 178, mobile: 200 },
+ { date: '2024-06-02', desktop: 470, mobile: 410 },
+ { date: '2024-06-03', desktop: 103, mobile: 160 },
+ { date: '2024-06-04', desktop: 439, mobile: 380 },
+ { date: '2024-06-05', desktop: 88, mobile: 140 },
+ { date: '2024-06-06', desktop: 294, mobile: 250 },
+ { date: '2024-06-07', desktop: 323, mobile: 370 },
+ { date: '2024-06-08', desktop: 385, mobile: 320 },
+ { date: '2024-06-09', desktop: 438, mobile: 480 },
+ { date: '2024-06-10', desktop: 155, mobile: 200 },
+ { date: '2024-06-11', desktop: 92, mobile: 150 },
+ { date: '2024-06-12', desktop: 492, mobile: 420 },
+ { date: '2024-06-13', desktop: 81, mobile: 130 },
+ { date: '2024-06-14', desktop: 426, mobile: 380 },
+ { date: '2024-06-15', desktop: 307, mobile: 350 },
+ { date: '2024-06-16', desktop: 371, mobile: 310 },
+ { date: '2024-06-17', desktop: 475, mobile: 520 },
+ { date: '2024-06-18', desktop: 107, mobile: 170 },
+ { date: '2024-06-19', desktop: 341, mobile: 290 },
+ { date: '2024-06-20', desktop: 408, mobile: 450 },
+ { date: '2024-06-21', desktop: 169, mobile: 210 },
+ { date: '2024-06-22', desktop: 317, mobile: 270 },
+ { date: '2024-06-23', desktop: 480, mobile: 530 },
+ { date: '2024-06-24', desktop: 132, mobile: 180 },
+ { date: '2024-06-25', desktop: 141, mobile: 190 },
+ { date: '2024-06-26', desktop: 434, mobile: 380 },
+ { date: '2024-06-27', desktop: 448, mobile: 490 },
+ { date: '2024-06-28', desktop: 149, mobile: 200 },
+ { date: '2024-06-29', desktop: 103, mobile: 160 },
+ { date: '2024-06-30', desktop: 446, mobile: 400 }
]
const chartConfig = {
- visitors: {
- label: "Visitors",
- },
- desktop: {
- label: "Desktop",
- color: "var(--primary)",
- },
- mobile: {
- label: "Mobile",
- color: "var(--primary)",
- },
+ visitors: {
+ label: 'Visitors'
+ },
+ desktop: {
+ label: 'Desktop',
+ color: 'var(--primary)'
+ },
+ mobile: {
+ label: 'Mobile',
+ color: 'var(--primary)'
+ }
} satisfies ChartConfig
export function ChartAreaInteractive() {
- const isMobile = useIsMobile()
- const [timeRange, setTimeRange] = React.useState("90d")
+ const isMobile = useIsMobile()
+ const [timeRange, setTimeRange] = React.useState('90d')
- React.useEffect(() => {
- if (isMobile) {
- setTimeRange("7d")
- }
- }, [isMobile])
+ React.useEffect(() => {
+ if (isMobile) {
+ setTimeRange('7d')
+ }
+ }, [isMobile])
- const filteredData = chartData.filter((item) => {
- const date = new Date(item.date)
- const referenceDate = new Date("2024-06-30")
- let daysToSubtract = 90
- if (timeRange === "30d") {
- daysToSubtract = 30
- } else if (timeRange === "7d") {
- daysToSubtract = 7
- }
- const startDate = new Date(referenceDate)
- startDate.setDate(startDate.getDate() - daysToSubtract)
- return date >= startDate
- })
+ const filteredData = chartData.filter((item) => {
+ const date = new Date(item.date)
+ const referenceDate = new Date('2024-06-30')
+ let daysToSubtract = 90
+ if (timeRange === '30d') {
+ daysToSubtract = 30
+ } else if (timeRange === '7d') {
+ daysToSubtract = 7
+ }
+ const startDate = new Date(referenceDate)
+ startDate.setDate(startDate.getDate() - daysToSubtract)
+ return date >= startDate
+ })
- return (
- <Card className="@container/card">
- <CardHeader>
- <CardTitle>Total Visitors</CardTitle>
- <CardDescription>
- <span className="hidden @[540px]/card:block">
- Total for the last 3 months
- </span>
- <span className="@[540px]/card:hidden">Last 3 months</span>
- </CardDescription>
- <CardAction>
- <ToggleGroup
- type="single"
- value={timeRange}
- onValueChange={setTimeRange}
- variant="outline"
- className="hidden *:data-[slot=toggle-group-item]:!px-4 @[767px]/card:flex"
- >
- <ToggleGroupItem value="90d">Last 3 months</ToggleGroupItem>
- <ToggleGroupItem value="30d">Last 30 days</ToggleGroupItem>
- <ToggleGroupItem value="7d">Last 7 days</ToggleGroupItem>
- </ToggleGroup>
- <Select value={timeRange} onValueChange={setTimeRange}>
- <SelectTrigger
- className="flex w-40 **:data-[slot=select-value]:block **:data-[slot=select-value]:truncate @[767px]/card:hidden"
- size="sm"
- aria-label="Select a value"
- >
- <SelectValue placeholder="Last 3 months" />
- </SelectTrigger>
- <SelectContent className="rounded-xl">
- <SelectItem value="90d" className="rounded-lg">
- Last 3 months
- </SelectItem>
- <SelectItem value="30d" className="rounded-lg">
- Last 30 days
- </SelectItem>
- <SelectItem value="7d" className="rounded-lg">
- Last 7 days
- </SelectItem>
- </SelectContent>
- </Select>
- </CardAction>
- </CardHeader>
- <CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">
- <ChartContainer
- config={chartConfig}
- className="aspect-auto h-[250px] w-full"
- >
- <AreaChart data={filteredData}>
- <defs>
- <linearGradient id="fillDesktop" x1="0" y1="0" x2="0" y2="1">
- <stop
- offset="5%"
- stopColor="var(--color-desktop)"
- stopOpacity={1.0}
- />
- <stop
- offset="95%"
- stopColor="var(--color-desktop)"
- stopOpacity={0.1}
- />
- </linearGradient>
- <linearGradient id="fillMobile" x1="0" y1="0" x2="0" y2="1">
- <stop
- offset="5%"
- stopColor="var(--color-mobile)"
- stopOpacity={0.8}
- />
- <stop
- offset="95%"
- stopColor="var(--color-mobile)"
- stopOpacity={0.1}
- />
- </linearGradient>
- </defs>
- <CartesianGrid vertical={false} />
- <XAxis
- dataKey="date"
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- minTickGap={32}
- tickFormatter={(value) => {
- const date = new Date(value)
- return date.toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- })
- }}
- />
- <ChartTooltip
- cursor={false}
- content={
- <ChartTooltipContent
- labelFormatter={(value) => {
- return new Date(value).toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- })
- }}
- indicator="dot"
- />
- }
- />
- <Area
- dataKey="mobile"
- type="natural"
- fill="url(#fillMobile)"
- stroke="var(--color-mobile)"
- stackId="a"
- />
- <Area
- dataKey="desktop"
- type="natural"
- fill="url(#fillDesktop)"
- stroke="var(--color-desktop)"
- stackId="a"
- />
- </AreaChart>
- </ChartContainer>
- </CardContent>
- </Card>
- )
+ return (
+ <Card className="@container/card">
+ <CardHeader>
+ <CardTitle>Total Visitors</CardTitle>
+ <CardDescription>
+ <span className="hidden @[540px]/card:block">Total for the last 3 months</span>
+ <span className="@[540px]/card:hidden">Last 3 months</span>
+ </CardDescription>
+ <CardAction>
+ <ToggleGroup
+ type="single"
+ value={timeRange}
+ onValueChange={setTimeRange}
+ variant="outline"
+ className="hidden *:data-[slot=toggle-group-item]:!px-4 @[767px]/card:flex"
+ >
+ <ToggleGroupItem value="90d">Last 3 months</ToggleGroupItem>
+ <ToggleGroupItem value="30d">Last 30 days</ToggleGroupItem>
+ <ToggleGroupItem value="7d">Last 7 days</ToggleGroupItem>
+ </ToggleGroup>
+ <Select value={timeRange} onValueChange={setTimeRange}>
+ <SelectTrigger
+ className="flex w-40 **:data-[slot=select-value]:block **:data-[slot=select-value]:truncate @[767px]/card:hidden"
+ size="sm"
+ aria-label="Select a value"
+ >
+ <SelectValue placeholder="Last 3 months" />
+ </SelectTrigger>
+ <SelectContent className="rounded-xl">
+ <SelectItem value="90d" className="rounded-lg">
+ Last 3 months
+ </SelectItem>
+ <SelectItem value="30d" className="rounded-lg">
+ Last 30 days
+ </SelectItem>
+ <SelectItem value="7d" className="rounded-lg">
+ Last 7 days
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </CardAction>
+ </CardHeader>
+ <CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">
+ <ChartContainer config={chartConfig} className="aspect-auto h-[250px] w-full">
+ <AreaChart data={filteredData}>
+ <defs>
+ <linearGradient id="fillDesktop" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="var(--color-desktop)" stopOpacity={1.0} />
+ <stop offset="95%" stopColor="var(--color-desktop)" stopOpacity={0.1} />
+ </linearGradient>
+ <linearGradient id="fillMobile" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="var(--color-mobile)" stopOpacity={0.8} />
+ <stop offset="95%" stopColor="var(--color-mobile)" stopOpacity={0.1} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ dataKey="date"
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ minTickGap={32}
+ tickFormatter={(value) => {
+ const date = new Date(value)
+ return date.toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric'
+ })
+ }}
+ />
+ <ChartTooltip
+ cursor={false}
+ content={
+ <ChartTooltipContent
+ labelFormatter={(value) => {
+ return new Date(value).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric'
+ })
+ }}
+ indicator="dot"
+ />
+ }
+ />
+ <Area
+ dataKey="mobile"
+ type="natural"
+ fill="url(#fillMobile)"
+ stroke="var(--color-mobile)"
+ stackId="a"
+ />
+ <Area
+ dataKey="desktop"
+ type="natural"
+ fill="url(#fillDesktop)"
+ stroke="var(--color-desktop)"
+ stackId="a"
+ />
+ </AreaChart>
+ </ChartContainer>
+ </CardContent>
+ </Card>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/dashboard/recent-investigations.tsx b/flowsint-app/src/renderer/src/components/dashboard/recent-investigations.tsx
index 535e18c0..b38f0e1b 100644
--- a/flowsint-app/src/renderer/src/components/dashboard/recent-investigations.tsx
+++ b/flowsint-app/src/renderer/src/components/dashboard/recent-investigations.tsx
@@ -1,97 +1,110 @@
-import { PlusCircle } from 'lucide-react';
-import { Link } from '@tanstack/react-router';
-import { Button } from '@/components/ui/button';
-import { formatDistanceToNow } from 'date-fns';
-import { investigationService } from '@/api/investigation-service';
-import { useQuery } from '@tanstack/react-query';
-import { Skeleton } from '@/components/ui/skeleton';
-import ErrorState from '@/components/shared/error-state';
-
+import { PlusCircle } from 'lucide-react'
+import { Link } from '@tanstack/react-router'
+import { Button } from '@/components/ui/button'
+import { formatDistanceToNow } from 'date-fns'
+import { investigationService } from '@/api/investigation-service'
+import { useQuery } from '@tanstack/react-query'
+import { Skeleton } from '@/components/ui/skeleton'
+import ErrorState from '@/components/shared/error-state'
function LoadingSkeleton() {
- return (
- <div className="w-full mt-2">
- <Skeleton className="h-7 w-48 mb-2" />
- <div className="border-b border-border mb-2" />
- <div className="flex flex-col gap-2">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="flex items-center justify-between px-4 py-3">
- <div className="flex items-center gap-3">
- <Skeleton className="h-10 w-10 rounded-lg" />
- <div className="flex flex-col gap-2">
- <Skeleton className="h-5 w-32" />
- <Skeleton className="h-4 w-24" />
- </div>
- </div>
- <Skeleton className="h-8 w-16" />
- </div>
- ))}
+ return (
+ <div className="w-full mt-2">
+ <Skeleton className="h-7 w-48 mb-2" />
+ <div className="border-b border-border mb-2" />
+ <div className="flex flex-col gap-2">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <div key={i} className="flex items-center justify-between px-4 py-3">
+ <div className="flex items-center gap-3">
+ <Skeleton className="h-10 w-10 rounded-lg" />
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-5 w-32" />
+ <Skeleton className="h-4 w-24" />
+ </div>
</div>
- </div>
- );
+ <Skeleton className="h-8 w-16" />
+ </div>
+ ))}
+ </div>
+ </div>
+ )
}
export function RecentInvestigations() {
- const { data: investigations = [], isLoading, error, refetch } = useQuery({
- queryKey: ['recent-investigations'],
- queryFn: () => investigationService.get(),
- });
+ const {
+ data: investigations = [],
+ isLoading,
+ error,
+ refetch
+ } = useQuery({
+ queryKey: ['recent-investigations'],
+ queryFn: () => investigationService.get()
+ })
- if (isLoading) {
- return <LoadingSkeleton />;
- }
+ if (isLoading) {
+ return <LoadingSkeleton />
+ }
- if (error) {
- return (
- <ErrorState
- title="Couldn't load recent investigations"
- description="Something went wrong while fetching data. Please try again."
- error={error}
- onRetry={() => refetch()}
- />
- );
- }
-
- if (!investigations?.length) {
- return (
- <div className="w-full mt-2">
- <h2 className="text-xl font-bold mb-2 text-foreground">Recent investigations</h2>
- <div className="border-b border-border mb-2" />
- <div className="flex items-center gap-3 px-2 py-3">
- <span className="bg-muted rounded-full p-2"><PlusCircle className="w-5 h-5 text-muted-foreground" /></span>
- <span className="text-foreground font-medium">No recent investigations</span>
- </div>
- </div>
- );
- }
+ if (error) {
+ return (
+ <ErrorState
+ title="Couldn't load recent investigations"
+ description="Something went wrong while fetching data. Please try again."
+ error={error}
+ onRetry={() => refetch()}
+ />
+ )
+ }
+ if (!investigations?.length) {
return (
- <div className="w-full mt-2">
- <h2 className="text-xl font-bold mb-2 text-foreground">Recent investigations ({investigations.length})</h2>
- <div className="border-b border-border mb-2" />
- <div className="flex flex-col gap-2">
- {investigations.slice(0, 5).map((investigation) => (
- <Link
- key={investigation.id}
- to="/dashboard/investigations/$investigationId"
- params={{ investigationId: investigation.id }}
- className="flex items-center justify-between px-4 py-3 rounded-lg hover:bg-muted/50 transition-colors"
- >
- <div className="flex items-center gap-3">
- <span className="bg-muted rounded-lg p-2">
- <PlusCircle className="w-4 h-4 text-muted-foreground" />
- </span>
- <div className="flex flex-col">
- <span className="font-medium text-foreground">{investigation.name}</span>
- <span className="text-sm text-muted-foreground">
- Updated {formatDistanceToNow(new Date(investigation.last_updated_at), { addSuffix: true })}
- </span>
- </div>
- </div>
- <Button variant="ghost" size="sm">Open</Button>
- </Link>
- ))}
- </div>
+ <div className="w-full mt-2">
+ <h2 className="text-xl font-bold mb-2 text-foreground">Recent investigations</h2>
+ <div className="border-b border-border mb-2" />
+ <div className="flex items-center gap-3 px-2 py-3">
+ <span className="bg-muted rounded-full p-2">
+ <PlusCircle className="w-5 h-5 text-muted-foreground" />
+ </span>
+ <span className="text-foreground font-medium">No recent investigations</span>
</div>
- );
-}
\ No newline at end of file
+ </div>
+ )
+ }
+
+ return (
+ <div className="w-full mt-2">
+ <h2 className="text-xl font-bold mb-2 text-foreground">
+ Recent investigations ({investigations.length})
+ </h2>
+ <div className="border-b border-border mb-2" />
+ <div className="flex flex-col gap-2">
+ {investigations.slice(0, 5).map((investigation) => (
+ <Link
+ key={investigation.id}
+ to="/dashboard/investigations/$investigationId"
+ params={{ investigationId: investigation.id }}
+ className="flex items-center justify-between px-4 py-3 rounded-lg hover:bg-muted/50 transition-colors"
+ >
+ <div className="flex items-center gap-3">
+ <span className="bg-muted rounded-lg p-2">
+ <PlusCircle className="w-4 h-4 text-muted-foreground" />
+ </span>
+ <div className="flex flex-col">
+ <span className="font-medium text-foreground">{investigation.name}</span>
+ <span className="text-sm text-muted-foreground">
+ Updated{' '}
+ {formatDistanceToNow(new Date(investigation.last_updated_at), {
+ addSuffix: true
+ })}
+ </span>
+ </div>
+ </div>
+ <Button variant="ghost" size="sm">
+ Open
+ </Button>
+ </Link>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/dashboard/section-cards.tsx b/flowsint-app/src/renderer/src/components/dashboard/section-cards.tsx
index 93996d66..81fd1183 100644
--- a/flowsint-app/src/renderer/src/components/dashboard/section-cards.tsx
+++ b/flowsint-app/src/renderer/src/components/dashboard/section-cards.tsx
@@ -1,101 +1,97 @@
-import { TrendingUp, TrendingDown } from "lucide-react"
-import { Badge } from "@/components/ui/badge"
+import { TrendingUp, TrendingDown } from 'lucide-react'
+import { Badge } from '@/components/ui/badge'
import {
- Card,
- CardAction,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card"
+ Card,
+ CardAction,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle
+} from '@/components/ui/card'
export function SectionCards() {
- return (
- <div className="*:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card grid grid-cols-1 gap-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:shadow-xs @xl/main:grid-cols-2 @2xl/main:grid-cols-4 @5xl/main:grid-cols-4">
- <Card className="@container/card">
- <CardHeader>
- <CardDescription>Total items</CardDescription>
- <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
- 127981
- </CardTitle>
- <CardAction>
- <Badge variant="outline">
- <TrendingUp />
- +12.5%
- </Badge>
- </CardAction>
- </CardHeader>
- <CardFooter className="flex-col items-start gap-1.5 text-sm">
- <div className="line-clamp-1 flex gap-2 font-medium">
- Trending up this month <TrendingUp className="size-4" />
- </div>
- <div className="text-muted-foreground">
- Discovered assets for the last 6 months
- </div>
- </CardFooter>
- </Card>
- <Card className="@container/card">
- <CardHeader>
- <CardDescription>New assets</CardDescription>
- <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
- 1234
- </CardTitle>
- <CardAction>
- <Badge variant="outline">
- <TrendingDown />
- -20%
- </Badge>
- </CardAction>
- </CardHeader>
- <CardFooter className="flex-col items-start gap-1.5 text-sm">
- <div className="line-clamp-1 flex gap-2 font-medium">
- Down 20% this period <TrendingDown className="size-4" />
- </div>
- <div className="text-muted-foreground">
- Newly discovered assets
- </div>
- </CardFooter>
- </Card>
- <Card className="@container/card">
- <CardHeader>
- <CardDescription>Active Accounts</CardDescription>
- <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
- 45,678
- </CardTitle>
- <CardAction>
- <Badge variant="outline">
- <TrendingUp />
- +12.5%
- </Badge>
- </CardAction>
- </CardHeader>
- <CardFooter className="flex-col items-start gap-1.5 text-sm">
- <div className="line-clamp-1 flex gap-2 font-medium">
- Strong user retention <TrendingUp className="size-4" />
- </div>
- <div className="text-muted-foreground">Engagement exceed targets</div>
- </CardFooter>
- </Card>
- <Card className="@container/card">
- <CardHeader>
- <CardDescription>Growth Rate</CardDescription>
- <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
- 4.5%
- </CardTitle>
- <CardAction>
- <Badge variant="outline">
- <TrendingUp />
- +4.5%
- </Badge>
- </CardAction>
- </CardHeader>
- <CardFooter className="flex-col items-start gap-1.5 text-sm">
- <div className="line-clamp-1 flex gap-2 font-medium">
- Steady performance increase <TrendingUp className="size-4" />
- </div>
- <div className="text-muted-foreground">Meets growth projections</div>
- </CardFooter>
- </Card>
- </div>
- )
+ return (
+ <div className="*:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card grid grid-cols-1 gap-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:shadow-xs @xl/main:grid-cols-2 @2xl/main:grid-cols-4 @5xl/main:grid-cols-4">
+ <Card className="@container/card">
+ <CardHeader>
+ <CardDescription>Total items</CardDescription>
+ <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
+ 127981
+ </CardTitle>
+ <CardAction>
+ <Badge variant="outline">
+ <TrendingUp />
+ +12.5%
+ </Badge>
+ </CardAction>
+ </CardHeader>
+ <CardFooter className="flex-col items-start gap-1.5 text-sm">
+ <div className="line-clamp-1 flex gap-2 font-medium">
+ Trending up this month <TrendingUp className="size-4" />
+ </div>
+ <div className="text-muted-foreground">Discovered assets for the last 6 months</div>
+ </CardFooter>
+ </Card>
+ <Card className="@container/card">
+ <CardHeader>
+ <CardDescription>New assets</CardDescription>
+ <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
+ 1234
+ </CardTitle>
+ <CardAction>
+ <Badge variant="outline">
+ <TrendingDown />
+ -20%
+ </Badge>
+ </CardAction>
+ </CardHeader>
+ <CardFooter className="flex-col items-start gap-1.5 text-sm">
+ <div className="line-clamp-1 flex gap-2 font-medium">
+ Down 20% this period <TrendingDown className="size-4" />
+ </div>
+ <div className="text-muted-foreground">Newly discovered assets</div>
+ </CardFooter>
+ </Card>
+ <Card className="@container/card">
+ <CardHeader>
+ <CardDescription>Active Accounts</CardDescription>
+ <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
+ 45,678
+ </CardTitle>
+ <CardAction>
+ <Badge variant="outline">
+ <TrendingUp />
+ +12.5%
+ </Badge>
+ </CardAction>
+ </CardHeader>
+ <CardFooter className="flex-col items-start gap-1.5 text-sm">
+ <div className="line-clamp-1 flex gap-2 font-medium">
+ Strong user retention <TrendingUp className="size-4" />
+ </div>
+ <div className="text-muted-foreground">Engagement exceed targets</div>
+ </CardFooter>
+ </Card>
+ <Card className="@container/card">
+ <CardHeader>
+ <CardDescription>Growth Rate</CardDescription>
+ <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
+ 4.5%
+ </CardTitle>
+ <CardAction>
+ <Badge variant="outline">
+ <TrendingUp />
+ +4.5%
+ </Badge>
+ </CardAction>
+ </CardHeader>
+ <CardFooter className="flex-col items-start gap-1.5 text-sm">
+ <div className="line-clamp-1 flex gap-2 font-medium">
+ Steady performance increase <TrendingUp className="size-4" />
+ </div>
+ <div className="text-muted-foreground">Meets growth projections</div>
+ </CardFooter>
+ </Card>
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/flows/context-menu.tsx b/flowsint-app/src/renderer/src/components/flows/context-menu.tsx
index ffb17755..7aa393e8 100644
--- a/flowsint-app/src/renderer/src/components/flows/context-menu.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/context-menu.tsx
@@ -1,84 +1,78 @@
-import { useCallback } from 'react';
-import { Pencil, Trash } from 'lucide-react';
-import { GraphNode } from '@/stores/graph-store';
-import BaseContextMenu from '@/components/xyflow/context-menu';
-import { FlowNode, useFlowStore } from '@/stores/flow-store';
+import { useCallback } from 'react'
+import { Pencil, Trash } from 'lucide-react'
+import { GraphNode } from '@/types/graph'
+import BaseContextMenu from '@/components/xyflow/context-menu'
+import { FlowNode, useFlowStore } from '@/stores/flow-store'
interface GraphContextMenuProps {
- node: GraphNode | FlowNode;
- top?: number;
- left?: number;
- right?: number;
- bottom?: number;
- rawTop?: number;
- rawLeft?: number;
- wrapperWidth: number;
- wrapperHeight: number;
- onEdit?: () => void;
- onDelete?: () => void;
- setMenu: (menu: any | null) => void;
- [key: string]: any;
+ node: GraphNode | FlowNode
+ top?: number
+ left?: number
+ right?: number
+ bottom?: number
+ rawTop?: number
+ rawLeft?: number
+ wrapperWidth: number
+ wrapperHeight: number
+ setMenu: (menu: unknown | null) => void
+ [key: string]: unknown
}
export default function ContextMenu({
- node,
- top,
- left,
- right,
- bottom,
- wrapperWidth,
- wrapperHeight,
- onEdit,
- onDelete,
- setMenu,
- ...props
-}: GraphContextMenuProps) {
+ node,
+ top,
+ left,
+ right,
+ bottom,
+ wrapperWidth,
+ wrapperHeight,
+ setMenu,
+ ...props
+}: GraphContextMenuProps): JSX.Element {
+ const setOpenParamsDialog = useFlowStore((s) => s.setOpenParamsDialog)
+ const deleteNode = useFlowStore((s) => s.deleteNode)
- const setOpenParamsDialog = useFlowStore(s => s.setOpenParamsDialog)
- const deleteNode = useFlowStore(s => s.deleteNode)
+ const handleOpenParamsModal = useCallback(() => {
+ setOpenParamsDialog(true, node as FlowNode)
+ setMenu(null)
+ }, [setOpenParamsDialog, node, setMenu])
- const handleOpenParamsModal = useCallback(() => {
- setOpenParamsDialog(true, node as FlowNode)
- setMenu(null)
- }, [setOpenParamsDialog, node, setMenu])
+ const handleDeleteFlow = useCallback(() => {
+ deleteNode(node.id as string)
+ setMenu(null)
+ }, [deleteNode, node.id, setMenu])
- const handleDeleteFlow = useCallback(() => {
- deleteNode(node.id as string)
- setMenu(null)
- }, [deleteNode, node.id, setMenu])
-
- return (
- <BaseContextMenu
- node={node}
- top={top}
- left={left}
- right={right}
- bottom={bottom}
- wrapperWidth={wrapperWidth}
- wrapperHeight={wrapperHeight}
- {...props}
+ return (
+ <BaseContextMenu
+ top={top}
+ left={left}
+ right={right}
+ bottom={bottom}
+ wrapperWidth={wrapperWidth}
+ wrapperHeight={wrapperHeight}
+ {...props}
+ >
+ {/* Header with title and action buttons */}
+ <div className="px-3 py-2 border-b gap-1 border-border flex items-center justify-between flex-shrink-0">
+ <div className="flex text-xs items-center gap-1 truncate">
+ <span className="block truncate">{node.data.name}</span>
+ </div>
+ </div>
+ <div className="flex flex-col gap-1 p-1">
+ {/* Transforms list */}
+ <button
+ onClick={handleOpenParamsModal}
+ className="w-full flex items-center gap-2 p-2 rounded-sm hover:bg-muted text-left transition-colors"
+ >
+ <Pencil className="h-4 w-4 opacity-60" /> Edit
+ </button>
+ <button
+ onClick={handleDeleteFlow}
+ className="w-full flex items-center gap-2 p-2 rounded-sm hover:bg-muted text-left transition-colors"
>
- {/* Header with title and action buttons */}
- <div className="px-3 py-2 border-b gap-1 border-border flex items-center justify-between flex-shrink-0">
- <div className='flex text-xs items-center gap-1 truncate'>
- <span className='block truncate'>{node.data.name}</span>
- </div>
- </div>
- <div className='flex flex-col gap-1 p-1'>
- {/* Transforms list */}
- <button
- onClick={handleOpenParamsModal}
- className="w-full flex items-center gap-2 p-2 rounded-sm hover:bg-muted text-left transition-colors"
- >
- <Pencil className="h-4 w-4 opacity-60" /> Edit
- </button>
- <button
- onClick={handleDeleteFlow}
- className="w-full flex items-center gap-2 p-2 rounded-sm hover:bg-muted text-left transition-colors"
- >
- <Trash className="h-4 w-4 text-red-500 opacity-60" /> Delete
- </button>
- </div>
- </BaseContextMenu >
- );
-}
\ No newline at end of file
+ <Trash className="h-4 w-4 text-red-500 opacity-60" /> Delete
+ </button>
+ </div>
+ </BaseContextMenu>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/flows/controls.tsx b/flowsint-app/src/renderer/src/components/flows/controls.tsx
index 1306a83e..4a5a7a73 100644
--- a/flowsint-app/src/renderer/src/components/flows/controls.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/controls.tsx
@@ -1,111 +1,116 @@
-
-import { Button } from "@/components/ui/button"
-import { Panel } from "@xyflow/react"
-import { Save, Trash2, ZoomIn, ZoomOut, Maximize, LayoutGrid } from "lucide-react"
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
-import { FlowNamePanel } from "./flow-name-panel"
+import { Button } from '@/components/ui/button'
+import { Panel } from '@xyflow/react'
+import { Save, Trash2, ZoomIn, ZoomOut, Maximize, LayoutGrid } from 'lucide-react'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
+import { FlowNamePanel } from './flow-name-panel'
interface FlowControlsProps {
- loading: boolean
- handleSaveFlow: () => void
- handleDeleteFlow: () => void
- onLayout: () => void
- fitView: () => void
- zoomIn: () => void
- zoomOut: () => void
- isSaved: boolean,
- flow?: any
+ loading: boolean
+ handleSaveFlow: () => void
+ handleDeleteFlow: () => void
+ onLayout: () => void
+ fitView: () => void
+ zoomIn: () => void
+ zoomOut: () => void
+ isSaved: boolean
+ flow?: any
}
export function FlowControls({
- loading,
- handleSaveFlow,
- handleDeleteFlow,
- onLayout,
- fitView,
- zoomIn,
- zoomOut,
- isSaved,
- flow
-}: FlowControlsProps) {
- return (
- <TooltipProvider>
- <FlowNamePanel flow={flow} />
- <Panel position="bottom-right" className="flex gap-2 mt-28 mr-2 z-40">
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="outline" size="icon" className="bg-card" onClick={handleSaveFlow} disabled={loading}>
- <Save className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Save flow</p>
- </TooltipContent>
- </Tooltip>
+ loading,
+ handleSaveFlow,
+ handleDeleteFlow,
+ onLayout,
+ fitView,
+ zoomIn,
+ zoomOut,
+ isSaved,
+ flow
+}: FlowControlsProps): JSX.Element {
+ return (
+ <TooltipProvider>
+ <FlowNamePanel flow={flow} />
+ <Panel position="bottom-right" className="flex gap-2 mt-28 mr-2 z-40">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ className="bg-card"
+ onClick={handleSaveFlow}
+ disabled={loading}
+ >
+ <Save className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Save flow</p>
+ </TooltipContent>
+ </Tooltip>
- {isSaved && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="outline"
- size="icon"
- className="bg-card"
- onClick={handleDeleteFlow}
- disabled={loading}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Delete flow</p>
- </TooltipContent>
- </Tooltip>
- )}
+ {isSaved && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="outline"
+ size="icon"
+ className="bg-card"
+ onClick={handleDeleteFlow}
+ disabled={loading}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Delete flow</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="outline" size="icon" className="bg-card" onClick={onLayout}>
- <LayoutGrid className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Auto Layout</p>
- </TooltipContent>
- </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="outline" size="icon" className="bg-card" onClick={onLayout}>
+ <LayoutGrid className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Auto Layout</p>
+ </TooltipContent>
+ </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="outline" size="icon" className="bg-card" onClick={fitView}>
- <Maximize className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Fit View</p>
- </TooltipContent>
- </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="outline" size="icon" className="bg-card" onClick={fitView}>
+ <Maximize className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Fit View</p>
+ </TooltipContent>
+ </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="outline" size="icon" className="bg-card" onClick={zoomIn}>
- <ZoomIn className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Zoom In</p>
- </TooltipContent>
- </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="outline" size="icon" className="bg-card" onClick={zoomIn}>
+ <ZoomIn className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Zoom In</p>
+ </TooltipContent>
+ </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button variant="outline" size="icon" className="bg-card" onClick={zoomOut}>
- <ZoomOut className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Zoom Out</p>
- </TooltipContent>
- </Tooltip>
- </Panel>
- </TooltipProvider>
- )
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="outline" size="icon" className="bg-card" onClick={zoomOut}>
+ <ZoomOut className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Zoom Out</p>
+ </TooltipContent>
+ </Tooltip>
+ </Panel>
+ </TooltipProvider>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/flows/editor.tsx b/flowsint-app/src/renderer/src/components/flows/editor.tsx
index 68074f29..a238a80a 100644
--- a/flowsint-app/src/renderer/src/components/flows/editor.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/editor.tsx
@@ -1,698 +1,718 @@
-
-import type React from "react"
-import { useState, useCallback, useRef, useEffect, memo } from "react"
+import type React from 'react'
+import { useState, useCallback, useRef, useEffect, memo } from 'react'
import {
- ReactFlow,
- ReactFlowProvider,
- Panel,
- Background,
- type NodeTypes,
- type Node,
- useReactFlow,
- type NodeMouseHandler,
- type ColorMode,
- MarkerType,
- type EdgeMarker,
- MiniMap,
-} from "@xyflow/react"
-import "@xyflow/react/dist/style.css"
-import { Play, Pause, SkipForward, RefreshCw } from "lucide-react"
-import { Button } from "@/components/ui/button"
-import TransformNode from "./transform-node"
-import TypeNode from "./type-node"
-import { type TransformNodeData } from "@/types/transform"
-import { FlowControls } from "./controls"
-import { getFlowDagreLayoutedElements } from "@/lib/utils"
-import { toast } from "sonner"
-import { SaveModal } from "./save-modal"
-import { useConfirm } from "@/components/use-confirm-dialog"
-import { useParams, useRouter } from "@tanstack/react-router"
-import { flowService } from "@/api/flow-service"
-import { useFlowStore, type FlowNode, type FlowEdge } from "@/stores/flow-store"
+ ReactFlow,
+ ReactFlowProvider,
+ Panel,
+ Background,
+ type NodeTypes,
+ type Node,
+ useReactFlow,
+ type NodeMouseHandler,
+ type ColorMode,
+ MarkerType,
+ type EdgeMarker,
+ MiniMap
+} from '@xyflow/react'
+import '@xyflow/react/dist/style.css'
+import { Play, Pause, SkipForward, RefreshCw } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import TransformNode from './transform-node'
+import TypeNode from './type-node'
+import { type TransformNodeData } from '@/types/transform'
+import { FlowControls } from './controls'
+import { getFlowDagreLayoutedElements } from '@/lib/utils'
+import { toast } from 'sonner'
+import { SaveModal } from './save-modal'
+import { useConfirm } from '@/components/use-confirm-dialog'
+import { useParams, useRouter } from '@tanstack/react-router'
+import { flowService } from '@/api/flow-service'
+import { useFlowStore, type FlowNode, type FlowEdge } from '@/stores/flow-store'
import type { CSSProperties } from 'react'
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select"
-import { useTheme } from "../theme-provider"
-import ParamsDialog from "./params-dialog"
-import FlowSheet from "./flow-sheet"
-import ContextMenu from "./context-menu"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { queryKeys } from "@/api/query-keys"
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select'
+import { useTheme } from '../theme-provider'
+import ParamsDialog from './params-dialog'
+import FlowSheet from './flow-sheet'
+import ContextMenu from './context-menu'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { queryKeys } from '@/api/query-keys'
const nodeTypes: NodeTypes = {
- transform: TransformNode,
- type: TypeNode,
+ transform: TransformNode,
+ type: TypeNode
}
interface FlowEditorProps {
- theme?: ColorMode
- initialEdges: FlowEdge[]
- initialNodes: FlowNode[]
- flow?: any
+ theme?: ColorMode
+ initialEdges: FlowEdge[]
+ initialNodes: FlowNode[]
+ flow?: any
}
-const defaultEdgeStyle: CSSProperties = { stroke: "#64748b" }
+const defaultEdgeStyle: CSSProperties = { stroke: '#64748b' }
const defaultMarkerEnd: EdgeMarker = {
- type: MarkerType.ArrowClosed,
- width: 15,
- height: 15,
- color: "#64748b",
+ type: MarkerType.ArrowClosed,
+ width: 15,
+ height: 15,
+ color: '#64748b'
}
const FlowEditor = memo(({ initialEdges, initialNodes, theme, flow }: FlowEditorProps) => {
- // #### React Flow and UI State ####
- const { fitView, zoomIn, zoomOut, setCenter } = useReactFlow()
- const reactFlowWrapper = useRef<HTMLDivElement>(null)
- const [reactFlowInstance, setReactFlowInstance] = useState<any>(null)
- const router = useRouter()
- const { confirm } = useConfirm()
- const { flowId } = useParams({ strict: false })
- const [showModal, setShowModal] = useState(false)
- const hasInitialized = useRef(false)
- const queryClient = useQueryClient()
-
- // #### Simulation State ####
- const [isSimulating, setIsSimulating] = useState(false)
- const [currentStepIndex, setCurrentStepIndex] = useState(0)
- const [simulationSpeed, setSimulationSpeed] = useState(1000) // ms per step
- const [flowBranches, setFlowBranches] = useState<any[]>([])
-
- // #### Transform Store State ####
- const nodes = useFlowStore(state => state.nodes)
- const edges = useFlowStore(state => state.edges)
- const loading = useFlowStore(state => state.loading)
- const setNodes = useFlowStore(state => state.setNodes)
- const setEdges = useFlowStore(state => state.setEdges)
- const onNodesChange = useFlowStore(state => state.onNodesChange)
- const onEdgesChange = useFlowStore(state => state.onEdgesChange)
- const onConnect = useFlowStore(state => state.onConnect)
- const setSelectedNode = useFlowStore(state => state.setSelectedNode)
- const setLoading = useFlowStore(state => state.setLoading)
- const colors = useNodesDisplaySettings(s => s.colors)
-
- // #### TanStack Query Mutations ####
- // Create flow mutation
- const createFlowMutation = useMutation({
- mutationFn: flowService.create,
- onSuccess: (data) => {
- toast.success("Transform saved successfully.")
- router.navigate({ to: `/dashboard/flows/${data.id}` })
- },
- onError: (error) => {
- toast.error("Error creating transform: " + (error instanceof Error ? error.message : "Unknown error"))
- },
- })
-
- // Update flow mutation
- const updateFlowMutation = useMutation({
- mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>
- flowService.update(flowId, body),
- onSuccess: () => {
- toast.success("Transform saved successfully.")
- // Invalidate the flow detail query
- if (flowId) {
- queryClient.invalidateQueries({
- queryKey: queryKeys.flows.detail(flowId)
- })
- }
- },
- onError: (error) => {
- toast.error("Error saving transform: " + (error instanceof Error ? error.message : "Unknown error"))
- },
- })
-
- // Delete flow mutation
- const deleteFlowMutation = useMutation({
- mutationFn: flowService.delete,
- onSuccess: () => {
- router.navigate({ to: "/dashboard/flows" })
- toast.success("Flow deleted successfully.")
- // Invalidate flows list
- queryClient.invalidateQueries({
- queryKey: queryKeys.flows.list
- })
- },
- onError: (error) => {
- toast.error("Error deleting flow: " + (error instanceof Error ? error.message : "Unknown error"))
- },
- })
-
- // Compute flow mutation
- const computeFlowMutation = useMutation({
- mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>
- flowService.compute(flowId, body),
- onSuccess: (response) => {
- setFlowBranches(response.flowBranches)
- startSimulation()
- },
- onError: (error) => {
- toast.error("Error computing flow: " + (error instanceof Error ? error.message : "Unknown error"))
- },
- })
-
- const [menu, setMenu] = useState<{
- node: FlowNode;
- top?: number;
- left?: number;
- right?: number;
- bottom?: number;
- rawTop?: number;
- rawLeft?: number;
- wrapperWidth: number;
- wrapperHeight: number;
- setMenu: (menu: any | null) => void;
- } | null>(null);
-
- // #### Initialization Effects ####
- // Initialize store with initial data
- useEffect(() => {
- if (!hasInitialized.current && (initialNodes.length > 0 || initialEdges.length > 0)) {
- setNodes(initialNodes)
- setEdges(initialEdges)
- hasInitialized.current = true
+ // #### React Flow and UI State ####
+ const { fitView, zoomIn, zoomOut, setCenter } = useReactFlow()
+ const reactFlowWrapper = useRef<HTMLDivElement>(null)
+ const [reactFlowInstance, setReactFlowInstance] = useState<any>(null)
+ const router = useRouter()
+ const { confirm } = useConfirm()
+ const { flowId } = useParams({ strict: false })
+ const [showModal, setShowModal] = useState(false)
+ const hasInitialized = useRef(false)
+ const queryClient = useQueryClient()
+
+ // #### Simulation State ####
+ const [isSimulating, setIsSimulating] = useState(false)
+ const [currentStepIndex, setCurrentStepIndex] = useState(0)
+ const [simulationSpeed, setSimulationSpeed] = useState(1000) // ms per step
+ const [flowBranches, setFlowBranches] = useState<any[]>([])
+
+ // #### Transform Store State ####
+ const nodes = useFlowStore((state) => state.nodes)
+ const edges = useFlowStore((state) => state.edges)
+ const loading = useFlowStore((state) => state.loading)
+ const setNodes = useFlowStore((state) => state.setNodes)
+ const setEdges = useFlowStore((state) => state.setEdges)
+ const onNodesChange = useFlowStore((state) => state.onNodesChange)
+ const onEdgesChange = useFlowStore((state) => state.onEdgesChange)
+ const onConnect = useFlowStore((state) => state.onConnect)
+ const setSelectedNode = useFlowStore((state) => state.setSelectedNode)
+ const setLoading = useFlowStore((state) => state.setLoading)
+ const colors = useNodesDisplaySettings((s) => s.colors)
+
+ // #### TanStack Query Mutations ####
+ // Create flow mutation
+ const createFlowMutation = useMutation({
+ mutationFn: flowService.create,
+ onSuccess: (data) => {
+ toast.success('Transform saved successfully.')
+ router.navigate({ to: `/dashboard/flows/${data.id}` })
+ },
+ onError: (error) => {
+ toast.error(
+ 'Error creating transform: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
+
+ // Update flow mutation
+ const updateFlowMutation = useMutation({
+ mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>
+ flowService.update(flowId, body),
+ onSuccess: () => {
+ toast.success('Transform saved successfully.')
+ // Invalidate the flow detail query
+ if (flowId) {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.flows.detail(flowId)
+ })
+ }
+ },
+ onError: (error) => {
+ toast.error(
+ 'Error saving transform: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
+
+ // Delete flow mutation
+ const deleteFlowMutation = useMutation({
+ mutationFn: flowService.delete,
+ onSuccess: () => {
+ router.navigate({ to: '/dashboard/flows' })
+ toast.success('Flow deleted successfully.')
+ // Invalidate flows list
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.flows.list
+ })
+ },
+ onError: (error) => {
+ toast.error(
+ 'Error deleting flow: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
+
+ // Compute flow mutation
+ const computeFlowMutation = useMutation({
+ mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>
+ flowService.compute(flowId, body),
+ onSuccess: (response) => {
+ setFlowBranches(response.flowBranches)
+ startSimulation()
+ },
+ onError: (error) => {
+ toast.error(
+ 'Error computing flow: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
+
+ const [menu, setMenu] = useState<{
+ node: FlowNode
+ top?: number
+ left?: number
+ right?: number
+ bottom?: number
+ rawTop?: number
+ rawLeft?: number
+ wrapperWidth: number
+ wrapperHeight: number
+ setMenu: (menu: any | null) => void
+ } | null>(null)
+
+ // #### Initialization Effects ####
+ // Initialize store with initial data
+ useEffect(() => {
+ if (!hasInitialized.current && (initialNodes.length > 0 || initialEdges.length > 0)) {
+ setNodes(initialNodes)
+ setEdges(initialEdges)
+ hasInitialized.current = true
+ }
+ }, [initialNodes, initialEdges, setNodes, setEdges])
+
+ const onNodeContextMenu = useCallback(
+ (event: React.MouseEvent, node: Node) => {
+ // Prevent native context menu from showing
+ event.preventDefault()
+
+ // Calculate position of the context menu. We want to make sure it
+ // doesn't get positioned off-screen.
+ if (!reactFlowWrapper.current) return
+
+ const pane = reactFlowWrapper.current.getBoundingClientRect()
+ const relativeX = event.clientX - pane.left
+ const relativeY = event.clientY - pane.top
+
+ setMenu({
+ node: node as FlowNode,
+ rawTop: relativeY,
+ rawLeft: relativeX,
+ wrapperWidth: pane.width,
+ wrapperHeight: pane.height,
+ setMenu: setMenu
+ })
+ },
+ [setMenu]
+ )
+
+ // Center view on selected node
+ // useEffect(() => {
+ // if (selectedNode && reactFlowInstance) {
+ // const nodeWidth = selectedNode.measured?.width ?? 0
+ // const nodeHeight = selectedNode.measured?.height ?? 0
+ // setCenter(
+ // selectedNode.position.x + nodeWidth / 2,
+ // selectedNode.position.y + nodeHeight / 2 + 20,
+ // { duration: 500, zoom: 1.5 }
+ // )
+ // }
+ // }, [selectedNode, reactFlowInstance, setCenter])
+
+ // #### Drag and Drop Handlers ####
+ const onDragOver = useCallback((event: React.DragEvent<HTMLDivElement>) => {
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'move'
+ }, [])
+
+ const onDrop = useCallback(
+ //@ts-ignore
+ (event: React.DragEvent<HTMLDivElement>) => {
+ event.preventDefault()
+ if (!reactFlowWrapper.current || !reactFlowInstance) return
+ const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect()
+ const transformData = JSON.parse(
+ event.dataTransfer.getData('application/json')
+ ) as TransformNodeData & {
+ category: string
+ }
+
+ if (transformData.type === 'type') {
+ const existsType = nodes.find((node) => node.data.type === 'type')
+ if (existsType) {
+ return toast.error('Only one type node is allowed')
+ }
+ }
+ const position = reactFlowInstance.screenToFlowPosition({
+ x: event.clientX - reactFlowBounds.left,
+ y: event.clientY - reactFlowBounds.top
+ })
+ const newNode: FlowNode = {
+ id: `${transformData.name}-${Date.now()}`,
+ type: transformData.type === 'type' ? 'type' : 'transform',
+ position,
+ data: {
+ id: transformData.id,
+ class_name: transformData.class_name,
+ module: transformData.module || '',
+ key: transformData.name,
+ color: colors[transformData.category.toLowerCase()] || '#94a3b8',
+ name: transformData.name,
+ category: transformData.category,
+ type: transformData.type,
+ inputs: transformData.inputs,
+ outputs: transformData.outputs,
+ documentation: transformData.documentation,
+ description: transformData.description,
+ required_params: transformData.required_params,
+ params: transformData.params,
+ params_schema: transformData.params_schema,
+ icon: transformData.icon
+ }
+ }
+ const updatedNodes = [...nodes, newNode]
+ setNodes(updatedNodes)
+ const nodeWidth = newNode.measured?.width ?? 0
+ const nodeHeight = newNode.measured?.height ?? 0
+ setCenter(newNode.position.x + nodeWidth / 2, newNode.position.y + nodeHeight / 2 + 20, {
+ duration: 500,
+ zoom: 1.5
+ })
+ },
+ [reactFlowInstance, nodes, setNodes, setCenter]
+ )
+
+ // #### Node Interaction Handlers ####
+ const onNodeClick: NodeMouseHandler = useCallback(
+ (_: React.MouseEvent, node: Node) => {
+ const typedNode = node as FlowNode
+ setSelectedNode(typedNode)
+ // const nodeWidth = typedNode.measured?.width ?? 0
+ // const nodeHeight = typedNode.measured?.height ?? 0
+ // setCenter(typedNode.position.x + nodeWidth / 2, typedNode.position.y + nodeHeight / 2 + 20, {
+ // duration: 500,
+ // zoom: 1.5,
+ // })
+ },
+ [setCenter, setSelectedNode]
+ )
+
+ const onPaneClick = useCallback(() => {
+ setSelectedNode(null)
+ setMenu(null)
+ }, [setSelectedNode, setMenu])
+
+ // #### Layout and Node Management ####
+ const onLayout = useCallback(() => {
+ // Wait for nodes to be measured before running layout
+ setTimeout(() => {
+ const layouted = getFlowDagreLayoutedElements(
+ nodes.map((node) => ({
+ ...node,
+ measured: {
+ width: node.measured?.width ?? 150,
+ height: node.measured?.height ?? 40
+ },
+ data: {
+ ...node.data,
+ key: node.data.class_name || node.id
+ }
+ })),
+ edges as FlowEdge[],
+ { direction: 'LR' }
+ )
+ setNodes(layouted.nodes as FlowNode[])
+ setEdges(layouted.edges as FlowEdge[])
+ window.requestAnimationFrame(() => {
+ fitView()
+ })
+ }, 100)
+ }, [nodes, edges, setNodes, setEdges, fitView])
+
+ // #### Transform CRUD Operations ####
+ const saveFlow = useCallback(
+ async (name: string, description: string) => {
+ setLoading(true)
+ try {
+ const inputType = nodes.find((node) => node.data.type === 'type')?.data?.class_name
+ if (!inputType) {
+ toast.error('Make sure your transform contains an input type.')
+ return
}
- }, [initialNodes, initialEdges, setNodes, setEdges])
-
- const onNodeContextMenu = useCallback(
- (event: React.MouseEvent, node: Node) => {
- // Prevent native context menu from showing
- event.preventDefault();
-
- // Calculate position of the context menu. We want to make sure it
- // doesn't get positioned off-screen.
- if (!reactFlowWrapper.current) return;
-
- const pane = reactFlowWrapper.current.getBoundingClientRect();
- const relativeX = event.clientX - pane.left;
- const relativeY = event.clientY - pane.top;
-
- setMenu({
- node: node as FlowNode,
- rawTop: relativeY,
- rawLeft: relativeX,
- wrapperWidth: pane.width,
- wrapperHeight: pane.height,
- setMenu: setMenu,
- });
- },
- [setMenu],
- );
-
- // Center view on selected node
- // useEffect(() => {
- // if (selectedNode && reactFlowInstance) {
- // const nodeWidth = selectedNode.measured?.width ?? 0
- // const nodeHeight = selectedNode.measured?.height ?? 0
- // setCenter(
- // selectedNode.position.x + nodeWidth / 2,
- // selectedNode.position.y + nodeHeight / 2 + 20,
- // { duration: 500, zoom: 1.5 }
- // )
- // }
- // }, [selectedNode, reactFlowInstance, setCenter])
-
- // #### Drag and Drop Handlers ####
- const onDragOver = useCallback((event: React.DragEvent<HTMLDivElement>) => {
- event.preventDefault()
- event.dataTransfer.dropEffect = "move"
- }, [])
-
- const onDrop = useCallback(
- //@ts-ignore
- (event: React.DragEvent<HTMLDivElement>) => {
- event.preventDefault()
- if (!reactFlowWrapper.current || !reactFlowInstance) return
- const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect()
- const transformData = JSON.parse(event.dataTransfer.getData("application/json")) as TransformNodeData & {
- category: string
- }
-
- if (transformData.type === "type") {
- const existsType = nodes.find((node) => node.data.type === "type")
- if (existsType) {
- return toast.error("Only one type node is allowed")
- }
- }
- const position = reactFlowInstance.screenToFlowPosition({
- x: event.clientX - reactFlowBounds.left,
- y: event.clientY - reactFlowBounds.top,
- })
- const newNode: FlowNode = {
- id: `${transformData.name}-${Date.now()}`,
- type: transformData.type === "type" ? "type" : "transform",
- position,
- data: {
- id: transformData.id,
- class_name: transformData.class_name,
- module: transformData.module || "",
- key: transformData.name,
- color: colors[transformData.category.toLowerCase()] || "#94a3b8",
- name: transformData.name,
- category: transformData.category,
- type: transformData.type,
- inputs: transformData.inputs,
- outputs: transformData.outputs,
- documentation: transformData.documentation,
- description: transformData.description,
- required_params: transformData.required_params,
- params: transformData.params,
- params_schema: transformData.params_schema,
- icon: transformData.icon
- },
- }
- const updatedNodes = [...nodes, newNode]
- setNodes(updatedNodes)
- const nodeWidth = newNode.measured?.width ?? 0
- const nodeHeight = newNode.measured?.height ?? 0
- setCenter(newNode.position.x + nodeWidth / 2, newNode.position.y + nodeHeight / 2 + 20, {
- duration: 500,
- zoom: 1.5,
- })
- },
- [reactFlowInstance, nodes, setNodes, setCenter],
- )
-
- // #### Node Interaction Handlers ####
- const onNodeClick: NodeMouseHandler = useCallback(
- (_: React.MouseEvent, node: Node) => {
- const typedNode = node as FlowNode
- setSelectedNode(typedNode)
- // const nodeWidth = typedNode.measured?.width ?? 0
- // const nodeHeight = typedNode.measured?.height ?? 0
- // setCenter(typedNode.position.x + nodeWidth / 2, typedNode.position.y + nodeHeight / 2 + 20, {
- // duration: 500,
- // zoom: 1.5,
- // })
- },
- [setCenter, setSelectedNode],
- )
- const onPaneClick = useCallback(() => {
- setSelectedNode(null)
- setMenu(null)
- }, [setSelectedNode, setMenu])
-
- // #### Layout and Node Management ####
- const onLayout = useCallback(() => {
- // Wait for nodes to be measured before running layout
- setTimeout(() => {
- const layouted = getFlowDagreLayoutedElements(
- nodes.map(node => ({
- ...node,
- measured: {
- width: node.measured?.width ?? 150,
- height: node.measured?.height ?? 40
- },
- data: {
- ...node.data,
- key: node.data.class_name || node.id,
- },
- })),
- edges as FlowEdge[],
- { direction: "LR" }
- )
- setNodes(layouted.nodes as FlowNode[])
- setEdges(layouted.edges as FlowEdge[])
- window.requestAnimationFrame(() => {
- fitView()
- })
- }, 100)
- }, [nodes, edges, setNodes, setEdges, fitView])
-
- // #### Transform CRUD Operations ####
- const saveFlow = useCallback(
- async (name: string, description: string) => {
- setLoading(true)
- try {
- const inputType = nodes.find((node) => node.data.type === "type")?.data?.class_name
- if (!inputType) {
- toast.error("Make sure your transform contains an input type.")
- return
- }
-
- const body = JSON.stringify({
- name: name,
- description: description,
- category: [inputType],
- flow_schema: {
- nodes,
- edges,
- },
- })
-
- if (flowId) {
- await updateFlowMutation.mutateAsync({ flowId, body })
- } else {
- await createFlowMutation.mutateAsync(body)
- }
- } catch (error) {
- console.error("Error saving flow:", error)
- } finally {
- setLoading(false)
- setShowModal(false)
- }
- },
- [nodes, edges, flowId, createFlowMutation, updateFlowMutation, setLoading],
- )
+ const body = JSON.stringify({
+ name: name,
+ description: description,
+ category: [inputType],
+ flow_schema: {
+ nodes,
+ edges
+ }
+ })
- const handleSaveFlow = useCallback(async () => {
- if (!flowId) {
- setShowModal(true)
+ if (flowId) {
+ await updateFlowMutation.mutateAsync({ flowId, body })
} else {
- await saveFlow(flow?.name || "", flow?.description || "")
+ await createFlowMutation.mutateAsync(body)
}
- }, [flowId, saveFlow, flow])
-
- const handleDeleteFlow = useCallback(async () => {
- if (!flowId) return
- if (
- await confirm({
- title: "Are you sure you want to delete this flow ?",
- message: "All of the flow's settings will be lost.",
- })
- ) {
- setLoading(true)
- await deleteFlowMutation.mutateAsync(flowId)
- setLoading(false)
- }
- }, [flowId, confirm, deleteFlowMutation, setLoading])
+ } catch (error) {
+ console.error('Error saving flow:', error)
+ } finally {
+ setLoading(false)
+ setShowModal(false)
+ }
+ },
+ [nodes, edges, flowId, createFlowMutation, updateFlowMutation, setLoading]
+ )
+
+ const handleSaveFlow = useCallback(async () => {
+ if (!flowId) {
+ setShowModal(true)
+ } else {
+ await saveFlow(flow?.name || '', flow?.description || '')
+ }
+ }, [flowId, saveFlow, flow])
+
+ const handleDeleteFlow = useCallback(async () => {
+ if (!flowId) return
+ if (
+ await confirm({
+ title: 'Are you sure you want to delete this flow ?',
+ message: "All of the flow's settings will be lost."
+ })
+ ) {
+ setLoading(true)
+ await deleteFlowMutation.mutateAsync(flowId)
+ setLoading(false)
+ }
+ }, [flowId, confirm, deleteFlowMutation, setLoading])
- // #### Flow Computation ####
- const handleComputeFlow = useCallback(async () => {
- if (!flowId) {
- toast.error("Save the flow first to compute it.")
- return
- }
+ // #### Flow Computation ####
+ const handleComputeFlow = useCallback(async () => {
+ if (!flowId) {
+ toast.error('Save the flow first to compute it.')
+ return
+ }
- setLoading(true)
- try {
- const body = {
- nodes,
- edges,
- initialValue: "domain"
+ setLoading(true)
+ try {
+ const body = {
+ nodes,
+ edges,
+ initialValue: 'domain'
+ }
+ await computeFlowMutation.mutateAsync({ flowId, body: JSON.stringify(body) })
+ } catch (error) {
+ console.error('Error computing flow:', error)
+ } finally {
+ setLoading(false)
+ }
+ }, [flowId, nodes, edges, computeFlowMutation, setLoading])
+
+ // #### Simulation State Management ####
+ // Update the updateNodeState function with proper types
+ const updateNodeState = useCallback(
+ (nds: FlowNode[], nodeId: string, state: 'pending' | 'processing' | 'completed' | 'error') => {
+ return nds.map((node) => {
+ // focus on node
+ if (node.id === nodeId) {
+ const nodeWidth = node.measured?.width ?? 0
+ const nodeHeight = node.measured?.height ?? 0
+ setCenter(node.position.x + nodeWidth / 2, node.position.y + nodeHeight / 2 + 20, {
+ duration: 500,
+ zoom: 1
+ })
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ computationState: state
}
- await computeFlowMutation.mutateAsync({ flowId, body: JSON.stringify(body) })
- } catch (error) {
- console.error("Error computing flow:", error)
- } finally {
- setLoading(false)
+ }
}
- }, [flowId, nodes, edges, computeFlowMutation, setLoading])
-
- // #### Simulation State Management ####
- // Update the updateNodeState function with proper types
- const updateNodeState = useCallback((nds: FlowNode[], nodeId: string, state: 'pending' | 'processing' | 'completed' | 'error') => {
- return nds.map((node) => {
- // focus on node
- if (node.id === nodeId) {
- const nodeWidth = node.measured?.width ?? 0
- const nodeHeight = node.measured?.height ?? 0
- setCenter(
- node.position.x + nodeWidth / 2,
- node.position.y + nodeHeight / 2 + 20,
- { duration: 500, zoom: 1 }
- )
- return {
- ...node,
- data: {
- ...node.data,
- computationState: state,
- },
- }
- }
- return node
+ return node
+ })
+ },
+ [setCenter]
+ )
+
+ // #### Simulation Effect ####
+ useEffect(() => {
+ if (!isSimulating || loading) return
+
+ let timer: NodeJS.Timeout
+
+ const totalSteps = flowBranches.reduce((sum, branch) => sum + branch.steps.length, 0)
+
+ if (currentStepIndex < totalSteps) {
+ // Find the current branch and step
+ let stepFound = false
+ let branchIndex = 0
+ let stepIndex = 0
+ let currentStepCount = 0
+
+ for (let i = 0; i < flowBranches.length; i++) {
+ const branch = flowBranches[i]
+ if (currentStepCount + branch.steps.length > currentStepIndex) {
+ branchIndex = i
+ stepIndex = currentStepIndex - currentStepCount
+ stepFound = true
+ break
+ }
+ currentStepCount += branch.steps.length
+ }
+
+ if (stepFound) {
+ const currentStep = flowBranches[branchIndex].steps[stepIndex]
+
+ // Update node states with proper types
+ setNodes((nds: FlowNode[]) => updateNodeState(nds, currentStep.nodeId, 'processing'))
+
+ // Update edges with proper types
+ setEdges((eds: FlowEdge[]) => {
+ return eds.map((edge) => ({
+ ...edge,
+ style: {
+ ...edge.style,
+ stroke:
+ edge.source === currentStep.nodeId || edge.target === currentStep.nodeId
+ ? '#3b82f6'
+ : '#64748b',
+ strokeWidth:
+ edge.source === currentStep.nodeId || edge.target === currentStep.nodeId ? 2 : 1
+ },
+ animated: edge.source === currentStep.nodeId || edge.target === currentStep.nodeId
+ }))
})
- }, [setCenter])
-
- // #### Simulation Effect ####
- useEffect(() => {
- if (!isSimulating || loading) return
-
- let timer: NodeJS.Timeout
-
- const totalSteps = flowBranches.reduce((sum, branch) => sum + branch.steps.length, 0)
-
- if (currentStepIndex < totalSteps) {
- // Find the current branch and step
- let stepFound = false
- let branchIndex = 0
- let stepIndex = 0
- let currentStepCount = 0
-
- for (let i = 0; i < flowBranches.length; i++) {
- const branch = flowBranches[i]
- if (currentStepCount + branch.steps.length > currentStepIndex) {
- branchIndex = i
- stepIndex = currentStepIndex - currentStepCount
- stepFound = true
- break
- }
- currentStepCount += branch.steps.length
- }
- if (stepFound) {
- const currentStep = flowBranches[branchIndex].steps[stepIndex]
-
- // Update node states with proper types
- setNodes((nds: FlowNode[]) => updateNodeState(nds, currentStep.nodeId, "processing"))
-
- // Update edges with proper types
- setEdges((eds: FlowEdge[]) => {
- return eds.map((edge) => ({
- ...edge,
- style: {
- ...edge.style,
- stroke: edge.source === currentStep.nodeId || edge.target === currentStep.nodeId ? "#3b82f6" : "#64748b",
- strokeWidth: edge.source === currentStep.nodeId || edge.target === currentStep.nodeId ? 2 : 1,
- },
- animated: edge.source === currentStep.nodeId || edge.target === currentStep.nodeId,
- }))
- })
-
- // After delay, mark as completed and move to next step
- timer = setTimeout(() => {
- setNodes((nds: FlowNode[]) => updateNodeState(nds, currentStep.nodeId, "completed"))
- setCurrentStepIndex((prev) => prev + 1)
- }, simulationSpeed)
- }
- } else {
- // End of simulation
- fitView({ duration: 500 })
- resetSimulation()
+ // After delay, mark as completed and move to next step
+ timer = setTimeout(() => {
+ setNodes((nds: FlowNode[]) => updateNodeState(nds, currentStep.nodeId, 'completed'))
+ setCurrentStepIndex((prev) => prev + 1)
+ }, simulationSpeed)
+ }
+ } else {
+ // End of simulation
+ fitView({ duration: 500 })
+ resetSimulation()
+ }
+
+ return () => clearTimeout(timer)
+ }, [
+ isSimulating,
+ currentStepIndex,
+ simulationSpeed,
+ loading,
+ flowBranches,
+ updateNodeState,
+ setCurrentStepIndex
+ ])
+
+ // #### Simulation Control Functions ####
+ const startSimulation = () => {
+ // Reset all nodes to pending state
+ setNodes((nds: FlowNode[]) =>
+ nds.map((node) => ({
+ ...node,
+ data: {
+ ...node.data,
+ computationState: 'pending'
}
+ }))
+ )
- return () => clearTimeout(timer)
- }, [isSimulating, currentStepIndex, simulationSpeed, loading, flowBranches, updateNodeState, setCurrentStepIndex])
-
- // #### Simulation Control Functions ####
- const startSimulation = () => {
- // Reset all nodes to pending state
- setNodes((nds: FlowNode[]) =>
- nds.map((node) => ({
- ...node,
- data: {
- ...node.data,
- computationState: "pending",
- },
- }))
- )
-
- // Reset all edges
- setEdges((eds: FlowEdge[]) =>
- eds.map((edge) => ({
- ...edge,
- style: {
- ...edge.style,
- stroke: "#64748b",
- strokeWidth: 1,
- },
- animated: false,
- }))
- )
-
- setCurrentStepIndex(0)
- setIsSimulating(true)
- }
+ // Reset all edges
+ setEdges((eds: FlowEdge[]) =>
+ eds.map((edge) => ({
+ ...edge,
+ style: {
+ ...edge.style,
+ stroke: '#64748b',
+ strokeWidth: 1
+ },
+ animated: false
+ }))
+ )
- const pauseSimulation = () => {
- setIsSimulating(false)
- }
+ setCurrentStepIndex(0)
+ setIsSimulating(true)
+ }
- const skipToEnd = () => {
- setIsSimulating(false)
-
- // Mark all nodes as completed
- setNodes((nds: FlowNode[]) =>
- nds.map((node) => ({
- ...node,
- data: {
- ...node.data,
- computationState: "completed",
- },
- }))
- )
-
- // Reset edge styling
- setEdges((eds: FlowEdge[]) =>
- eds.map((edge) => ({
- ...edge,
- style: {
- ...edge.style,
- stroke: "#64748b",
- strokeWidth: 1,
- },
- animated: false,
- }))
- )
-
- const totalSteps = flowBranches.reduce((sum, branch) => sum + branch.steps.length, 0)
- setCurrentStepIndex(totalSteps)
- }
+ const pauseSimulation = () => {
+ setIsSimulating(false)
+ }
- const resetSimulation = () => {
- setIsSimulating(false)
- setCurrentStepIndex(0)
-
- // Reset all nodes
- setNodes((nds: FlowNode[]) =>
- nds.map((node) => ({
- ...node,
- data: {
- ...node.data,
- computationState: undefined,
- },
- }))
- )
-
- // Reset all edges
- setEdges((eds: FlowEdge[]) =>
- eds.map((edge) => ({
- ...edge,
- style: {
- ...edge.style,
- stroke: "#64748b",
- strokeWidth: 1,
- },
- animated: false,
- }))
- )
- }
+ const skipToEnd = () => {
+ setIsSimulating(false)
- // #### Render ####
- return (
- <>
- <div ref={reactFlowWrapper} className="w-full h-full bg-background">
- <ReactFlow
- nodes={nodes}
- edges={edges}
- onNodesChange={onNodesChange}
- onEdgesChange={onEdgesChange}
- onConnect={onConnect}
- onInit={setReactFlowInstance}
- onDrop={onDrop}
- onDragOver={onDragOver}
- onNodeClick={onNodeClick}
- onPaneClick={onPaneClick}
- onNodeContextMenu={onNodeContextMenu}
- nodeTypes={nodeTypes}
- fitView
- proOptions={{ hideAttribution: true }}
- colorMode={theme}
- >
- {flowId &&
- <Panel position="top-right" className="space-x-2 mt-14 mr-2 z-50 flex items-center">
- {isSimulating ? (
- <Button size="sm" variant="outline" className="h-7" onClick={pauseSimulation}>
- <Pause className="h-4 w-4 mr-1" /> Pause
- </Button>
- ) : (
- <Button size="sm" variant="default" className="h-7" onClick={handleComputeFlow}>
- <Play className="h-4 w-4 mr-1" /> Compute
- </Button>
- )}
- <Button size="sm" variant="outline" className="h-7" onClick={skipToEnd}>
- <SkipForward className="h-4 w-4 mr-1" /> Skip
- </Button>
- <Button size="sm" variant="outline" className="h-7" onClick={resetSimulation}>
- <RefreshCw className="h-4 w-4 mr-1" /> Reset
- </Button>
- <Select
- value={String(simulationSpeed)}
- onValueChange={(value) => setSimulationSpeed(Number(value))}
- >
- <SelectTrigger className="!h-7">
- <SelectValue placeholder="Select speed" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="2000">Slow</SelectItem>
- <SelectItem value="1000">Normal</SelectItem>
- <SelectItem value="750">Fast</SelectItem>
- <SelectItem value="400">Very fast</SelectItem>
- </SelectContent>
- </Select>
- </Panel>}
- <FlowControls
- loading={loading}
- flow={flow}
- handleSaveFlow={handleSaveFlow}
- handleDeleteFlow={handleDeleteFlow}
- onLayout={onLayout}
- fitView={fitView}
- zoomIn={zoomIn}
- zoomOut={zoomOut}
- isSaved={Boolean(flowId)}
- />
- <Background bgColor="var(--background)" />
- <ParamsDialog />
- {menu && <ContextMenu
- {...menu}
- >
- </ContextMenu>}
- <MiniMap className="bg-background" position="bottom-left" pannable zoomable />
- </ReactFlow>
- </div>
- <FlowSheet onLayout={onLayout} />
- <SaveModal open={showModal} onOpenChange={setShowModal} onSave={saveFlow} isLoading={loading} />
- </>
+ // Mark all nodes as completed
+ setNodes((nds: FlowNode[]) =>
+ nds.map((node) => ({
+ ...node,
+ data: {
+ ...node.data,
+ computationState: 'completed'
+ }
+ }))
)
-})
-FlowEditorComp.displayName = "FlowEditorComp"
+ // Reset edge styling
+ setEdges((eds: FlowEdge[]) =>
+ eds.map((edge) => ({
+ ...edge,
+ style: {
+ ...edge.style,
+ stroke: '#64748b',
+ strokeWidth: 1
+ },
+ animated: false
+ }))
+ )
-// #### Main Component ####
-function FlowEditorComp({
- initialEdges = [],
- initialNodes = [],
- flow
-}: FlowEditorProps) {
- const { theme } = useTheme()
-
- // Transform any plain edges into edges with required properties
- const enhancedEdges = initialEdges.map(edge => ({
+ const totalSteps = flowBranches.reduce((sum, branch) => sum + branch.steps.length, 0)
+ setCurrentStepIndex(totalSteps)
+ }
+
+ const resetSimulation = () => {
+ setIsSimulating(false)
+ setCurrentStepIndex(0)
+
+ // Reset all nodes
+ setNodes((nds: FlowNode[]) =>
+ nds.map((node) => ({
+ ...node,
+ data: {
+ ...node.data,
+ computationState: undefined
+ }
+ }))
+ )
+
+ // Reset all edges
+ setEdges((eds: FlowEdge[]) =>
+ eds.map((edge) => ({
...edge,
- animated: true,
- style: defaultEdgeStyle,
- markerEnd: defaultMarkerEnd
- })) as FlowEdge[]
-
- return (
- <ReactFlowProvider>
- <FlowEditor
- flow={flow}
- initialEdges={enhancedEdges}
- initialNodes={initialNodes}
- theme={theme as ColorMode}
- />
- </ReactFlowProvider>
+ style: {
+ ...edge.style,
+ stroke: '#64748b',
+ strokeWidth: 1
+ },
+ animated: false
+ }))
)
-}
+ }
+
+ // #### Render ####
+ return (
+ <>
+ <div ref={reactFlowWrapper} className="w-full h-full bg-background">
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ onConnect={onConnect}
+ onInit={setReactFlowInstance}
+ onDrop={onDrop}
+ onDragOver={onDragOver}
+ onNodeClick={onNodeClick}
+ onPaneClick={onPaneClick}
+ onNodeContextMenu={onNodeContextMenu}
+ nodeTypes={nodeTypes}
+ fitView
+ proOptions={{ hideAttribution: true }}
+ colorMode={theme}
+ >
+ {flowId && (
+ <Panel position="top-right" className="space-x-2 mt-14 mr-2 z-50 flex items-center">
+ {isSimulating ? (
+ <Button size="sm" variant="outline" className="h-7" onClick={pauseSimulation}>
+ <Pause className="h-4 w-4 mr-1" /> Pause
+ </Button>
+ ) : (
+ <Button size="sm" variant="default" className="h-7" onClick={handleComputeFlow}>
+ <Play className="h-4 w-4 mr-1" /> Compute
+ </Button>
+ )}
+ <Button size="sm" variant="outline" className="h-7" onClick={skipToEnd}>
+ <SkipForward className="h-4 w-4 mr-1" /> Skip
+ </Button>
+ <Button size="sm" variant="outline" className="h-7" onClick={resetSimulation}>
+ <RefreshCw className="h-4 w-4 mr-1" /> Reset
+ </Button>
+ <Select
+ value={String(simulationSpeed)}
+ onValueChange={(value) => setSimulationSpeed(Number(value))}
+ >
+ <SelectTrigger className="!h-7">
+ <SelectValue placeholder="Select speed" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="2000">Slow</SelectItem>
+ <SelectItem value="1000">Normal</SelectItem>
+ <SelectItem value="750">Fast</SelectItem>
+ <SelectItem value="400">Very fast</SelectItem>
+ </SelectContent>
+ </Select>
+ </Panel>
+ )}
+ <FlowControls
+ loading={loading}
+ flow={flow}
+ handleSaveFlow={handleSaveFlow}
+ handleDeleteFlow={handleDeleteFlow}
+ onLayout={onLayout}
+ fitView={fitView}
+ zoomIn={zoomIn}
+ zoomOut={zoomOut}
+ isSaved={Boolean(flowId)}
+ />
+ <Background bgColor="var(--background)" />
+ <ParamsDialog />
+ {menu && <ContextMenu {...menu}></ContextMenu>}
+ <MiniMap className="bg-background" position="bottom-left" pannable zoomable />
+ </ReactFlow>
+ </div>
+ <FlowSheet onLayout={onLayout} />
+ <SaveModal
+ open={showModal}
+ onOpenChange={setShowModal}
+ onSave={saveFlow}
+ isLoading={loading}
+ />
+ </>
+ )
+})
+FlowEditorComp.displayName = 'FlowEditorComp'
+// #### Main Component ####
+function FlowEditorComp({ initialEdges = [], initialNodes = [], flow }: FlowEditorProps) {
+ const { theme } = useTheme()
+
+ // Transform any plain edges into edges with required properties
+ const enhancedEdges = initialEdges.map((edge) => ({
+ ...edge,
+ animated: true,
+ style: defaultEdgeStyle,
+ markerEnd: defaultMarkerEnd
+ })) as FlowEdge[]
+
+ return (
+ <ReactFlowProvider>
+ <FlowEditor
+ flow={flow}
+ initialEdges={enhancedEdges}
+ initialNodes={initialNodes}
+ theme={theme as ColorMode}
+ />
+ </ReactFlowProvider>
+ )
+}
export default FlowEditorComp
diff --git a/flowsint-app/src/renderer/src/components/flows/flow-list.tsx b/flowsint-app/src/renderer/src/components/flows/flow-list.tsx
index 328b94db..37478f44 100644
--- a/flowsint-app/src/renderer/src/components/flows/flow-list.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/flow-list.tsx
@@ -1,103 +1,116 @@
-import { flowService } from "@/api/flow-service"
-import { useQuery } from "@tanstack/react-query"
-import { Link } from "@tanstack/react-router"
-import { SkeletonList } from "../shared/skeleton-list"
-import { Input } from "../ui/input"
-import { useState, useMemo } from "react"
-import { formatDistanceToNow } from "date-fns"
-import { Pencil, PlusIcon } from "lucide-react"
-import { Button } from "../ui/button"
-import NewFlow from "./new-flow"
-import ErrorState from "../shared/error-state"
+import { flowService } from '@/api/flow-service'
+import { useQuery } from '@tanstack/react-query'
+import { Link } from '@tanstack/react-router'
+import { SkeletonList } from '../shared/skeleton-list'
+import { Input } from '../ui/input'
+import { useState, useMemo } from 'react'
+import { formatDistanceToNow } from 'date-fns'
+import { Pencil, PlusIcon } from 'lucide-react'
+import { Button } from '../ui/button'
+import NewFlow from './new-flow'
+import ErrorState from '../shared/error-state'
const FlowsList = () => {
- const { data: flows, isLoading, error, refetch } = useQuery({
- queryKey: ["flows"],
- queryFn: () => flowService.get(),
- })
- const [searchQuery, setSearchQuery] = useState("")
+ const {
+ data: flows,
+ isLoading,
+ error,
+ refetch
+ } = useQuery({
+ queryKey: ['flows'],
+ queryFn: () => flowService.get()
+ })
+ const [searchQuery, setSearchQuery] = useState('')
- const filteredflows = useMemo(() => {
- if (!flows) return []
- if (!searchQuery.trim()) return flows
+ const filteredflows = useMemo(() => {
+ if (!flows) return []
+ if (!searchQuery.trim()) return flows
- const query = searchQuery.toLowerCase().trim()
- return flows.filter((flow) => {
- const matchesName = flow.name?.toLowerCase().includes(query)
- const matchesCategory = flow.category
- ? (Array.isArray(flow.category)
- ? flow.category.some(cat => cat.toLowerCase().includes(query))
- : flow.category.toLowerCase().includes(query))
- : false
- return matchesName || matchesCategory
- })
- }, [flows, searchQuery])
+ const query = searchQuery.toLowerCase().trim()
+ return flows.filter((flow) => {
+ const matchesName = flow.name?.toLowerCase().includes(query)
+ const matchesCategory = flow.category
+ ? Array.isArray(flow.category)
+ ? flow.category.some((cat) => cat.toLowerCase().includes(query))
+ : flow.category.toLowerCase().includes(query)
+ : false
+ return matchesName || matchesCategory
+ })
+ }, [flows, searchQuery])
- if (isLoading) return <div className="p-2"><SkeletonList rowCount={10} /></div>
- if (error) return (
- <ErrorState
- title="Couldn't load flows"
- description="Something went wrong while fetching data. Please try again."
- error={error}
- onRetry={() => refetch()}
- />
+ if (isLoading)
+ return (
+ <div className="p-2">
+ <SkeletonList rowCount={10} />
+ </div>
)
-
+ if (error)
return (
- <div className="flex flex-col h-full min-h-0 overflow-hidden bg-card">
- <div className="p-2 border-b flex items-center gap-1">
- <NewFlow>
- <Button variant="ghost" size="icon" className="h-7 w-7">
- <PlusIcon className="h-4 w-4" />
- </Button>
- </NewFlow>
- <Input
- type="search"
- className="h-7"
- placeholder="Search flows..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- />
- </div>
+ <ErrorState
+ title="Couldn't load flows"
+ description="Something went wrong while fetching data. Please try again."
+ error={error}
+ onRetry={() => refetch()}
+ />
+ )
+
+ return (
+ <div className="flex flex-col h-full min-h-0 overflow-hidden bg-card">
+ <div className="p-2 border-b flex items-center gap-1">
+ <NewFlow>
+ <Button variant="ghost" size="icon" className="h-7 w-7">
+ <PlusIcon className="h-4 w-4" />
+ </Button>
+ </NewFlow>
+ <Input
+ type="search"
+ className="h-7"
+ placeholder="Search flows..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ </div>
- {filteredflows.length > 0 ? (
- <ul className="flex-1 overflow-auto divide-y">
- {filteredflows.map((flow: any) => (
- <li key={flow.id}>
- <Link
- to={`/dashboard/flows/$flowId`}
- params={{ flowId: flow.id }}
- className="block px-4 py-3 hover:bg-muted cursor-pointer"
- title={flow.description || "No description"}
- >
- <div className="font-semibold text-sm truncate">{flow.name || "(Unnamed flow)"}</div>
- <div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
- {flow.category && (
- <span className="truncate">
- {Array.isArray(flow.category) ? flow.category.join(", ") : flow.category}
- </span>
- )}
- {flow.last_updated_at && (
- <>
- {Boolean(flow.category.length) && <span>•</span>}
- <div className="flex items-center gap-1 whitespace-nowrap">
- <Pencil className="h-3 w-3" />
- {formatDistanceToNow(new Date(flow.last_updated_at), { addSuffix: true })}
- </div>
- </>
- )}
- </div>
- </Link>
- </li>
- ))}
- </ul>
- ) : (
- <div className="flex-1 flex items-center justify-center p-4 text-center text-muted-foreground">
- {searchQuery ? "No matching flows found" : "No flows found"}
+ {filteredflows.length > 0 ? (
+ <ul className="flex-1 overflow-auto divide-y">
+ {filteredflows.map((flow: any) => (
+ <li key={flow.id}>
+ <Link
+ to={`/dashboard/flows/$flowId`}
+ params={{ flowId: flow.id }}
+ className="block px-4 py-3 hover:bg-muted cursor-pointer"
+ title={flow.description || 'No description'}
+ >
+ <div className="font-semibold text-sm truncate">
+ {flow.name || '(Unnamed flow)'}
</div>
- )}
+ <div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
+ {flow.category && (
+ <span className="truncate">
+ {Array.isArray(flow.category) ? flow.category.join(', ') : flow.category}
+ </span>
+ )}
+ {flow.last_updated_at && (
+ <>
+ {Boolean(flow.category.length) && <span>•</span>}
+ <div className="flex items-center gap-1 whitespace-nowrap">
+ <Pencil className="h-3 w-3" />
+ {formatDistanceToNow(new Date(flow.last_updated_at), { addSuffix: true })}
+ </div>
+ </>
+ )}
+ </div>
+ </Link>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <div className="flex-1 flex items-center justify-center p-4 text-center text-muted-foreground">
+ {searchQuery ? 'No matching flows found' : 'No flows found'}
</div>
- )
+ )}
+ </div>
+ )
}
export default FlowsList
diff --git a/flowsint-app/src/renderer/src/components/flows/flow-name-panel.tsx b/flowsint-app/src/renderer/src/components/flows/flow-name-panel.tsx
index a670e12f..45ed5dba 100644
--- a/flowsint-app/src/renderer/src/components/flows/flow-name-panel.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/flow-name-panel.tsx
@@ -1,161 +1,166 @@
-
-import { useEffect, useRef, useState, type KeyboardEvent } from "react"
-import { Panel } from "@xyflow/react"
-import { Card } from "@/components/ui/card"
-import { toast } from "sonner"
-import { flowService } from "@/api/flow-service"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { queryKeys } from "@/api/query-keys"
-import type { Flow } from "@/types/flow"
+import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
+import { Panel } from '@xyflow/react'
+import { Card } from '@/components/ui/card'
+import { toast } from 'sonner'
+import { flowService } from '@/api/flow-service'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { queryKeys } from '@/api/query-keys'
+import type { Flow } from '@/types/flow'
interface FlowNamePanelProps {
- flow?: Flow
- onUpdate?: (updates: Partial<Flow>) => void
- disabled?: boolean
+ flow?: Flow
+ onUpdate?: (updates: Partial<Flow>) => void
+ disabled?: boolean
}
export const FlowNamePanel = ({ flow, onUpdate, disabled = false }: FlowNamePanelProps) => {
- const [isEditingName, setIsEditingName] = useState(false)
- const [isEditingDesc, setIsEditingDesc] = useState(false)
- const [name, setName] = useState(flow?.name || "My flow")
- const [description, setDescription] = useState(flow?.description || "")
- const [isSaving, setIsSaving] = useState(false)
- const nameInputRef = useRef<HTMLInputElement>(null)
- const descInputRef = useRef<HTMLInputElement>(null)
- const queryClient = useQueryClient()
+ const [isEditingName, setIsEditingName] = useState(false)
+ const [isEditingDesc, setIsEditingDesc] = useState(false)
+ const [name, setName] = useState(flow?.name || 'My flow')
+ const [description, setDescription] = useState(flow?.description || '')
+ const [isSaving, setIsSaving] = useState(false)
+ const nameInputRef = useRef<HTMLInputElement>(null)
+ const descInputRef = useRef<HTMLInputElement>(null)
+ const queryClient = useQueryClient()
- // Update flow mutation
- const updateFlowMutation = useMutation({
- mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>
- flowService.update(flowId, body),
- onSuccess: (data, variables) => {
- if (onUpdate) {
- onUpdate(variables.body as Partial<Flow>)
- }
- // Invalidate the flow detail query
- queryClient.invalidateQueries({
- queryKey: queryKeys.flows.detail(variables.flowId)
- })
- toast.success("Flow updated successfully.")
- },
- onError: (error) => {
- toast.error("Failed to update flow: " + (error instanceof Error ? error.message : "Unknown error"))
- },
- })
+ // Update flow mutation
+ const updateFlowMutation = useMutation({
+ mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>
+ flowService.update(flowId, body),
+ onSuccess: (data, variables) => {
+ if (onUpdate) {
+ onUpdate(variables.body as Partial<Flow>)
+ }
+ // Invalidate the flow detail query
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.flows.detail(variables.flowId)
+ })
+ toast.success('Flow updated successfully.')
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to update flow: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
- useEffect(() => {
- if (flow) {
- setName(flow.name || "My flow")
- setDescription(flow.description || "")
- }
- }, [flow])
+ useEffect(() => {
+ if (flow) {
+ setName(flow.name || 'My flow')
+ setDescription(flow.description || '')
+ }
+ }, [flow])
- useEffect(() => {
- if (isEditingName && nameInputRef.current) {
- nameInputRef.current.focus()
- }
- }, [isEditingName])
+ useEffect(() => {
+ if (isEditingName && nameInputRef.current) {
+ nameInputRef.current.focus()
+ }
+ }, [isEditingName])
- useEffect(() => {
- if (isEditingDesc && descInputRef.current) {
- descInputRef.current.focus()
- }
- }, [isEditingDesc])
+ useEffect(() => {
+ if (isEditingDesc && descInputRef.current) {
+ descInputRef.current.focus()
+ }
+ }, [isEditingDesc])
+
+ const handleSaveField = async (field: 'name' | 'description', value: string) => {
+ if (!flow?.id) return
- const handleSaveField = async (field: "name" | "description", value: string) => {
- if (!flow?.id) return
+ const trimmedValue = value.trim()
+ if (field === 'name' && trimmedValue === '') return
- const trimmedValue = value.trim()
- if (field === "name" && trimmedValue === "") return
+ if (
+ (field === 'name' && trimmedValue === flow.name) ||
+ (field === 'description' && trimmedValue === flow.description)
+ ) {
+ field === 'name' ? setIsEditingName(false) : setIsEditingDesc(false)
+ return
+ }
- if (
- (field === "name" && trimmedValue === flow.name) ||
- (field === "description" && trimmedValue === flow.description)
- ) {
- field === "name" ? setIsEditingName(false) : setIsEditingDesc(false)
- return
- }
-
- setIsSaving(true)
- try {
- const updates = { [field]: trimmedValue }
- await updateFlowMutation.mutateAsync({
- flowId: flow.id,
- body: JSON.stringify(updates)
- })
- } catch (error) {
- // Revert local state on error
- if (field === "name") {
- setName(flow.name)
- } else {
- setDescription(flow.description || "")
- }
- } finally {
- setIsSaving(false)
- field === "name" ? setIsEditingName(false) : setIsEditingDesc(false)
- }
+ setIsSaving(true)
+ try {
+ const updates = { [field]: trimmedValue }
+ await updateFlowMutation.mutateAsync({
+ flowId: flow.id,
+ body: JSON.stringify(updates)
+ })
+ } catch (error) {
+ // Revert local state on error
+ if (field === 'name') {
+ setName(flow.name)
+ } else {
+ setDescription(flow.description || '')
+ }
+ } finally {
+ setIsSaving(false)
+ field === 'name' ? setIsEditingName(false) : setIsEditingDesc(false)
}
+ }
- const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>, field: "name" | "description", value: string) => {
- if (e.key === "Enter") {
- e.preventDefault()
- handleSaveField(field, value)
- } else if (e.key === "Escape") {
- if (field === "name") {
- setIsEditingName(false)
- setName(flow?.name || "My flow")
- } else {
- setIsEditingDesc(false)
- setDescription(flow?.description || "")
- }
- }
+ const handleKeyDown = (
+ e: KeyboardEvent<HTMLInputElement>,
+ field: 'name' | 'description',
+ value: string
+ ) => {
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ handleSaveField(field, value)
+ } else if (e.key === 'Escape') {
+ if (field === 'name') {
+ setIsEditingName(false)
+ setName(flow?.name || 'My flow')
+ } else {
+ setIsEditingDesc(false)
+ setDescription(flow?.description || '')
+ }
}
+ }
- return (
- <Panel position="top-left" className="m-4">
- <Card className="px-3 py-2 gap-1 w-sm rounded-mdgap-1">
- {isEditingName ? (
- <input
- ref={nameInputRef}
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- onBlur={() => handleSaveField("name", name)}
- onKeyDown={(e) => handleKeyDown(e, "name", name)}
- disabled={disabled || isSaving}
- className="!text-xl font-semibold bg-transparent border-b border-gray-300 focus:border-primary focus:outline-none !px-1 !py-0.5 w-full"
- placeholder="Enter flow name"
- />
- ) : (
- <h1
- className="text-xl font-semibold cursor-pointer hover:bg-foreground/10 px-1 py-0.5 rounded-mdtransition-colors"
- onClick={() => !disabled && setIsEditingName(true)}
- >
- {name || "My flow"}
- </h1>
- )}
+ return (
+ <Panel position="top-left" className="m-4">
+ <Card className="px-3 py-2 gap-1 w-sm rounded-mdgap-1">
+ {isEditingName ? (
+ <input
+ ref={nameInputRef}
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ onBlur={() => handleSaveField('name', name)}
+ onKeyDown={(e) => handleKeyDown(e, 'name', name)}
+ disabled={disabled || isSaving}
+ className="!text-xl font-semibold bg-transparent border-b border-gray-300 focus:border-primary focus:outline-none !px-1 !py-0.5 w-full"
+ placeholder="Enter flow name"
+ />
+ ) : (
+ <h1
+ className="text-xl font-semibold cursor-pointer hover:bg-foreground/10 px-1 py-0.5 rounded-mdtransition-colors"
+ onClick={() => !disabled && setIsEditingName(true)}
+ >
+ {name || 'My flow'}
+ </h1>
+ )}
- {isEditingDesc ? (
- <input
- ref={descInputRef}
- type="text"
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- onBlur={() => handleSaveField("description", description)}
- onKeyDown={(e) => handleKeyDown(e, "description", description)}
- disabled={disabled || isSaving}
- className="text-sm text-muted-foreground bg-transparent border-b border-gray-300 focus:border-primary focus:outline-none px-1 py-0.5 w-full"
- placeholder="Add a description..."
- />
- ) : (
- <p
- className="text-sm text-muted-foreground cursor-pointer hover:bg-foreground/10 px-1 py-0.5 rounded-mdtransition-colors min-h-[1.5rem]"
- onClick={() => !disabled && setIsEditingDesc(true)}
- >
- {description || <span className="italic text-gray-400">Add a description...</span>}
- </p>
- )}
- </Card>
- </Panel>
- )
+ {isEditingDesc ? (
+ <input
+ ref={descInputRef}
+ type="text"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ onBlur={() => handleSaveField('description', description)}
+ onKeyDown={(e) => handleKeyDown(e, 'description', description)}
+ disabled={disabled || isSaving}
+ className="text-sm text-muted-foreground bg-transparent border-b border-gray-300 focus:border-primary focus:outline-none px-1 py-0.5 w-full"
+ placeholder="Add a description..."
+ />
+ ) : (
+ <p
+ className="text-sm text-muted-foreground cursor-pointer hover:bg-foreground/10 px-1 py-0.5 rounded-mdtransition-colors min-h-[1.5rem]"
+ onClick={() => !disabled && setIsEditingDesc(true)}
+ >
+ {description || <span className="italic text-gray-400">Add a description...</span>}
+ </p>
+ )}
+ </Card>
+ </Panel>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/flows/flow-navigation.tsx b/flowsint-app/src/renderer/src/components/flows/flow-navigation.tsx
index 0ea35bb8..1ab62b3a 100644
--- a/flowsint-app/src/renderer/src/components/flows/flow-navigation.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/flow-navigation.tsx
@@ -1,47 +1,55 @@
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
-import { UserPlus, Users } from "lucide-react"
-import RawMaterial from "./raw-material"
-import TransformsList from "./flow-list"
-import { useLayoutStore } from "@/stores/layout-store"
-import { useParams } from "@tanstack/react-router"
-import { useEffect } from "react"
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
+import { UserPlus, Users } from 'lucide-react'
+import RawMaterial from './raw-material'
+import TransformsList from './flow-list'
+import { useLayoutStore } from '@/stores/layout-store'
+import { useParams } from '@tanstack/react-router'
+import { useEffect } from 'react'
const TransformNavigation = () => {
- const { flowId } = useParams({ strict: false })
- const activeTransformTab = useLayoutStore((s) => s.activeTransformTab)
- const setActiveTransformTab = useLayoutStore((s) => s.setActiveTransformTab)
+ const { flowId } = useParams({ strict: false })
+ const activeTransformTab = useLayoutStore((s) => s.activeTransformTab)
+ const setActiveTransformTab = useLayoutStore((s) => s.setActiveTransformTab)
- useEffect(() => {
- setActiveTransformTab(flowId ? "items" : "transforms")
- }, [setActiveTransformTab, flowId])
+ useEffect(() => {
+ setActiveTransformTab(flowId ? 'items' : 'transforms')
+ }, [setActiveTransformTab, flowId])
- return (
- <div className="h-full w-full bg-card flex flex-col min-h-0">
- <Tabs
- value={activeTransformTab}
- onValueChange={setActiveTransformTab}
- defaultValue="transforms"
- className="w-full h-full flex flex-col gap-0 min-h-0">
- <TabsList className="w-full p-0 rounded-none my-0 border-b flex-shrink-0">
- <TabsTrigger value="transforms"><Users className="h-3 w-3 opacity-60" /> Transforms</TabsTrigger>
- {flowId && <TabsTrigger value="items"><UserPlus className="h-3 w-3 opacity-60" /> Items</TabsTrigger>}
- </TabsList>
- <TabsContent
- value="transforms"
- className="my-0 w-full flex-1 flex flex-col min-h-0 overflow-hidden"
- >
- <TransformsList />
- </TabsContent>
- {flowId &&
- <TabsContent
- value="items"
- className="my-0 w-full flex-1 flex flex-col min-h-0 overflow-hidden"
- >
- <RawMaterial />
- </TabsContent>}
- </Tabs>
- </div>
- )
+ return (
+ <div className="h-full w-full bg-card flex flex-col min-h-0">
+ <Tabs
+ value={activeTransformTab}
+ onValueChange={setActiveTransformTab}
+ defaultValue="transforms"
+ className="w-full h-full flex flex-col gap-0 min-h-0"
+ >
+ <TabsList className="w-full p-0 rounded-none my-0 border-b flex-shrink-0">
+ <TabsTrigger value="transforms">
+ <Users className="h-3 w-3 opacity-60" /> Transforms
+ </TabsTrigger>
+ {flowId && (
+ <TabsTrigger value="items">
+ <UserPlus className="h-3 w-3 opacity-60" /> Items
+ </TabsTrigger>
+ )}
+ </TabsList>
+ <TabsContent
+ value="transforms"
+ className="my-0 w-full flex-1 flex flex-col min-h-0 overflow-hidden"
+ >
+ <TransformsList />
+ </TabsContent>
+ {flowId && (
+ <TabsContent
+ value="items"
+ className="my-0 w-full flex-1 flex flex-col min-h-0 overflow-hidden"
+ >
+ <RawMaterial />
+ </TabsContent>
+ )}
+ </Tabs>
+ </div>
+ )
}
export default TransformNavigation
diff --git a/flowsint-app/src/renderer/src/components/flows/flow-sheet.tsx b/flowsint-app/src/renderer/src/components/flows/flow-sheet.tsx
index ea2a29b5..20f8ce26 100644
--- a/flowsint-app/src/renderer/src/components/flows/flow-sheet.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/flow-sheet.tsx
@@ -1,211 +1,248 @@
import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetDescription,
-
-} from "@/components/ui/sheet"
-import { FlowEdge, FlowNode, useFlowStore } from "@/stores/flow-store"
-import { memo, useCallback, useMemo, useState } from "react"
-import { TriangleAlert, Loader2, ArrowRight } from "lucide-react"
-import { TooltipProvider, Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import { Transform } from "@/types/transform"
-import { useQuery } from "@tanstack/react-query"
-import { Input } from "../ui/input"
-import { Alert, AlertDescription } from "../ui/alert"
-import { useIcon } from "@/hooks/use-icon"
-import { flowService } from "@/api/flow-service"
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription
+} from '@/components/ui/sheet'
+import { FlowEdge, FlowNode, useFlowStore } from '@/stores/flow-store'
+import { memo, useCallback, useMemo, useState } from 'react'
+import { TriangleAlert, Loader2, ArrowRight } from 'lucide-react'
+import { TooltipProvider, Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { Transform } from '@/types/transform'
+import { useQuery } from '@tanstack/react-query'
+import { Input } from '../ui/input'
+import { Alert, AlertDescription } from '../ui/alert'
+import { useIcon } from '@/hooks/use-icon'
+import { flowService } from '@/api/flow-service'
const FlowSheet = ({ onLayout }: { onLayout: () => void }) => {
- const openFlowSheet = useFlowStore(state => state.openFlowSheet)
- const setOpenFlowSheet = useFlowStore(state => state.setOpenFlowSheet)
- const selectedNode = useFlowStore(state => state.selectedNode)
- const setNodes = useFlowStore(state => state.setNodes)
- const setEdges = useFlowStore(state => state.setEdges)
- const colors = useNodesDisplaySettings(s => s.colors)
-
- const { data: materials, isLoading, error } = useQuery({
- queryKey: ["raw_material", selectedNode?.data.outputs.type],
- enabled: !!selectedNode?.data.outputs.type,
- queryFn: () => flowService.getRawMaterialForType(selectedNode?.data.outputs.type.toLowerCase() || ""),
+ const openFlowSheet = useFlowStore((state) => state.openFlowSheet)
+ const setOpenFlowSheet = useFlowStore((state) => state.setOpenFlowSheet)
+ const selectedNode = useFlowStore((state) => state.selectedNode)
+ const setNodes = useFlowStore((state) => state.setNodes)
+ const setEdges = useFlowStore((state) => state.setEdges)
+ const colors = useNodesDisplaySettings((s) => s.colors)
+
+ const {
+ data: materials,
+ isLoading,
+ error
+ } = useQuery({
+ queryKey: ['raw_material', selectedNode?.data.outputs.type],
+ enabled: !!selectedNode?.data.outputs.type,
+ queryFn: () =>
+ flowService.getRawMaterialForType(selectedNode?.data.outputs.type.toLowerCase() || '')
+ })
+ const [searchTerm, setSearchTerm] = useState<string>('')
+
+ const filteredTransforms = useMemo(() => {
+ if (!materials?.items || !selectedNode) return []
+ if (!searchTerm.trim()) {
+ return materials?.items
+ }
+ const term = searchTerm.toLowerCase()
+ return materials?.items.filter((transform: Transform) => {
+ return (
+ transform.class_name.toLowerCase().includes(term) ||
+ transform.name.toLowerCase().includes(term) ||
+ transform.module.toLowerCase().includes(term) ||
+ transform.inputs.type.toLowerCase().includes(term) ||
+ transform.outputs.type.toLowerCase().includes(term) ||
+ (transform.documentation && transform.documentation.toLowerCase().includes(term))
+ )
})
- const [searchTerm, setSearchTerm] = useState<string>("")
-
- const filteredTransforms = useMemo(() => {
- if (!materials?.items || !selectedNode) return []
- if (!searchTerm.trim()) {
- return materials?.items
- }
- const term = searchTerm.toLowerCase()
- return materials?.items.filter((transform: Transform) => {
- return (
- transform.class_name.toLowerCase().includes(term) ||
- transform.name.toLowerCase().includes(term) ||
- transform.module.toLowerCase().includes(term) ||
- transform.inputs.type.toLowerCase().includes(term) ||
- transform.outputs.type.toLowerCase().includes(term) ||
- (transform.documentation && transform.documentation.toLowerCase().includes(term))
- )
- })
- }, [searchTerm, materials?.items, selectedNode])
-
- const handleClick = useCallback((transform: Transform) => {
- if (!selectedNode) return
- const position = { x: selectedNode.position.x + 350, y: selectedNode.position.y }
- const newNode: FlowNode = {
- id: `${transform.name}-${Date.now()}`,
- type: transform.type === "type" ? "type" : "transform",
- position,
- data: {
- id: transform.id,
- class_name: transform.class_name,
- module: transform.module || "",
- key: transform.name,
- color: colors[transform.category.toLowerCase()] || "#94a3b8",
- name: transform.name,
- category: transform.category,
- type: transform.type,
- inputs: transform.inputs,
- outputs: transform.outputs,
- documentation: transform.documentation,
- description: transform.description,
- required_params: transform.required_params,
- params: transform.params,
- params_schema: transform.params_schema,
- icon: transform.icon
- },
+ }, [searchTerm, materials?.items, selectedNode])
+
+ const handleClick = useCallback(
+ (transform: Transform) => {
+ if (!selectedNode) return
+ const position = { x: selectedNode.position.x + 350, y: selectedNode.position.y }
+ const newNode: FlowNode = {
+ id: `${transform.name}-${Date.now()}`,
+ type: transform.type === 'type' ? 'type' : 'transform',
+ position,
+ data: {
+ id: transform.id,
+ class_name: transform.class_name,
+ module: transform.module || '',
+ key: transform.name,
+ color: colors[transform.category.toLowerCase()] || '#94a3b8',
+ name: transform.name,
+ category: transform.category,
+ type: transform.type,
+ inputs: transform.inputs,
+ outputs: transform.outputs,
+ documentation: transform.documentation,
+ description: transform.description,
+ required_params: transform.required_params,
+ params: transform.params,
+ params_schema: transform.params_schema,
+ icon: transform.icon
}
- setNodes((prev) => ([...prev, newNode]))
-
- const connection: FlowEdge = {
- id: `${selectedNode.id}-${newNode.id}`,
- source: selectedNode.id,
- target: newNode.id,
- sourceHandle: selectedNode.data.outputs.type,
- targetHandle: transform.inputs.type
- }
- setEdges((prev) => ([...prev, connection]))
- // onLayout && onLayout()
- setOpenFlowSheet(false)
- }, [selectedNode, setNodes, setEdges, onLayout, setOpenFlowSheet])
-
- return (
- <div>
- <Sheet open={openFlowSheet} onOpenChange={setOpenFlowSheet}>
- <SheetContent className="sm:max-w-xl">
- <SheetHeader>
- <SheetTitle>Add connector to <span className="text-primary">{selectedNode?.data.class_name}</span></SheetTitle>
- <SheetDescription>Choose a transform to launch from the list below.</SheetDescription>
- </SheetHeader>
- <div className="p-4 grow overflow-auto border-t">
- <Input
- placeholder="Search transforms..."
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
- className="mb-4"
- />
-
- {isLoading && (
- <div className="flex items-center justify-center py-8">
- <Loader2 className="h-6 w-6 animate-spin" />
- <span className="ml-2">Loading transforms...</span>
- </div>
- )}
-
- {error && (
- <Alert variant="destructive" className="mb-4">
- <TriangleAlert className="h-4 w-4" />
- <AlertDescription>
- Failed to load transforms. Please try again.
- </AlertDescription>
- </Alert>
- )}
-
- {!isLoading && !error && (
- <div className="flex flex-col gap-2">
- {filteredTransforms.length === 0 ? (
- <div className="text-center py-8 text-muted-foreground">
- {searchTerm.trim() ? 'No transforms found matching your search.' : 'No transforms available for this node type.'}
- </div>
- ) : (
- filteredTransforms.map((transform: Transform) => (
- <TransformItem key={transform.id} transform={transform} onClick={() => handleClick(transform)} />
- ))
- )}
- </div>
- )}
- </div>
- </SheetContent>
- </Sheet>
- </div>
- )
+ }
+ setNodes((prev) => [...prev, newNode])
+
+ const connection: FlowEdge = {
+ id: `${selectedNode.id}-${newNode.id}`,
+ source: selectedNode.id,
+ target: newNode.id,
+ sourceHandle: selectedNode.data.outputs.type,
+ targetHandle: transform.inputs.type
+ }
+ setEdges((prev) => [...prev, connection])
+ // onLayout && onLayout()
+ setOpenFlowSheet(false)
+ },
+ [selectedNode, setNodes, setEdges, onLayout, setOpenFlowSheet]
+ )
+
+ return (
+ <div>
+ <Sheet open={openFlowSheet} onOpenChange={setOpenFlowSheet}>
+ <SheetContent className="sm:max-w-xl">
+ <SheetHeader>
+ <SheetTitle>
+ Add connector to <span className="text-primary">{selectedNode?.data.class_name}</span>
+ </SheetTitle>
+ <SheetDescription>Choose a transform to launch from the list below.</SheetDescription>
+ </SheetHeader>
+ <div className="p-4 grow overflow-auto border-t">
+ <Input
+ placeholder="Search transforms..."
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ className="mb-4"
+ />
+
+ {isLoading && (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 className="h-6 w-6 animate-spin" />
+ <span className="ml-2">Loading transforms...</span>
+ </div>
+ )}
+
+ {error && (
+ <Alert variant="destructive" className="mb-4">
+ <TriangleAlert className="h-4 w-4" />
+ <AlertDescription>Failed to load transforms. Please try again.</AlertDescription>
+ </Alert>
+ )}
+
+ {!isLoading && !error && (
+ <div className="flex flex-col gap-2">
+ {filteredTransforms.length === 0 ? (
+ <div className="text-center py-8 text-muted-foreground">
+ {searchTerm.trim()
+ ? 'No transforms found matching your search.'
+ : 'No transforms available for this node type.'}
+ </div>
+ ) : (
+ filteredTransforms.map((transform: Transform) => (
+ <TransformItem
+ key={transform.id}
+ transform={transform}
+ onClick={() => handleClick(transform)}
+ />
+ ))
+ )}
+ </div>
+ )}
+ </div>
+ </SheetContent>
+ </Sheet>
+ </div>
+ )
}
-
export default FlowSheet
// Custom equality function for TransformItem
function areEqual(prevProps: { transform: Transform }, nextProps: { transform: Transform }) {
- return (
- prevProps.transform.class_name === nextProps.transform.class_name &&
- prevProps.transform.name === nextProps.transform.name &&
- prevProps.transform.module === nextProps.transform.module &&
- prevProps.transform.documentation === nextProps.transform.documentation
- )
+ return (
+ prevProps.transform.class_name === nextProps.transform.class_name &&
+ prevProps.transform.name === nextProps.transform.name &&
+ prevProps.transform.module === nextProps.transform.module &&
+ prevProps.transform.documentation === nextProps.transform.documentation
+ )
}
// Memoized transform item component for the sidebar
-const TransformItem = memo(({ transform, onClick }: { transform: Transform, onClick: () => void }) => {
- const colors = useNodesDisplaySettings(s => s.colors)
+const TransformItem = memo(
+ ({ transform, onClick }: { transform: Transform; onClick: () => void }) => {
+ const colors = useNodesDisplaySettings((s) => s.colors)
const borderInputColor = colors[transform.inputs.type.toLowerCase()]
const borderOutputColor = colors[transform.outputs.type.toLowerCase()]
- const Icon = transform.type === "type" ? useIcon(transform.outputs.type.toLowerCase() as string, null) : transform.icon ? useIcon(transform.icon, null) : null
+ const Icon =
+ transform.type === 'type'
+ ? useIcon(transform.outputs.type.toLowerCase() as string, null)
+ : transform.icon
+ ? useIcon(transform.icon, null)
+ : null
return (
- <TooltipProvider>
- <button
- onClick={onClick}
- className="p-3 rounded-md relative w-full overflow-hidden cursor-grab bg-card border ring-2 ring-transparent hover:ring-primary transition-all group"
- style={{ borderLeftWidth: "5px", borderRightWidth: "5px", borderLeftColor: borderInputColor ?? borderOutputColor, borderRightColor: borderOutputColor, cursor: "grab" }}
- >
- <div className="flex justify-between grow items-start">
- <div className="flex items-start gap-2 grow truncate text-ellipsis">
- <div className="space-y-1 truncate text-left">
- <div className="flex items-center gap-2 truncate text-ellipsis">
- {Icon && <Icon size={24} />}
- <h3 className="text-sm font-medium truncate text-ellipsis">{transform.class_name}</h3>
- </div>
- <p className="text-sm font-normal opacity-60 truncate text-ellipsis">{transform.description}</p>
- <div className="mt-2 flex items-center gap-2 text-xs">
- <div className="flex items-center gap-1">
- <span className="text-muted-foreground">Takes</span>
- <span className="font-bold truncate text-ellipsis">{transform.inputs.type}</span>
- </div>
- <span><ArrowRight className="h-3 w-3" /></span>
- <div className="flex items-center gap-1">
- <span className="text-muted-foreground">Returns</span>
- <span className="font-bold truncate text-ellipsis">{transform.outputs.type}</span>
- </div>
- </div>
- </div>
- </div>
+ <TooltipProvider>
+ <button
+ onClick={onClick}
+ className="p-3 rounded-md relative w-full overflow-hidden cursor-grab bg-card border ring-2 ring-transparent hover:ring-primary transition-all group"
+ style={{
+ borderLeftWidth: '5px',
+ borderRightWidth: '5px',
+ borderLeftColor: borderInputColor ?? borderOutputColor,
+ borderRightColor: borderOutputColor,
+ cursor: 'grab'
+ }}
+ >
+ <div className="flex justify-between grow items-start">
+ <div className="flex items-start gap-2 grow truncate text-ellipsis">
+ <div className="space-y-1 truncate text-left">
+ <div className="flex items-center gap-2 truncate text-ellipsis">
+ {Icon && <Icon size={24} />}
+ <h3 className="text-sm font-medium truncate text-ellipsis">
+ {transform.class_name}
+ </h3>
+ </div>
+ <p className="text-sm font-normal opacity-60 truncate text-ellipsis">
+ {transform.description}
+ </p>
+ <div className="mt-2 flex items-center gap-2 text-xs">
+ <div className="flex items-center gap-1">
+ <span className="text-muted-foreground">Takes</span>
+ <span className="font-bold truncate text-ellipsis">
+ {transform.inputs.type}
+ </span>
+ </div>
+ <span>
+ <ArrowRight className="h-3 w-3" />
+ </span>
+ <div className="flex items-center gap-1">
+ <span className="text-muted-foreground">Returns</span>
+ <span className="font-bold truncate text-ellipsis">
+ {transform.outputs.type}
+ </span>
+ </div>
</div>
- {transform.required_params &&
- <div className="absolute bottom-3 right-3">
- <Tooltip>
- <TooltipTrigger asChild>
- <TriangleAlert className="h-4 w-4 text-yellow-500" />
- </TooltipTrigger>
- <TooltipContent>
- <p>API key required</p>
- </TooltipContent>
- </Tooltip>
- </div>}
- </button>
- </TooltipProvider >
+ </div>
+ </div>
+ </div>
+ {transform.required_params && (
+ <div className="absolute bottom-3 right-3">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <TriangleAlert className="h-4 w-4 text-yellow-500" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>API key required</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ )}
+ </button>
+ </TooltipProvider>
)
-}, areEqual)
+ },
+ areEqual
+)
-TransformItem.displayName = "TransformItem"
+TransformItem.displayName = 'TransformItem'
diff --git a/flowsint-app/src/renderer/src/components/flows/new-flow.tsx b/flowsint-app/src/renderer/src/components/flows/new-flow.tsx
index dbb248b7..9b285d32 100644
--- a/flowsint-app/src/renderer/src/components/flows/new-flow.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/new-flow.tsx
@@ -7,50 +7,54 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import { queryKeys } from '@/api/query-keys'
const NewFlow = ({ children }: { children: ReactNode }) => {
- const navigate = useNavigate()
- const queryClient = useQueryClient()
- const setNodes = useFlowStore(state => state.setNodes)
- const setEdges = useFlowStore(state => state.setEdges)
+ const navigate = useNavigate()
+ const queryClient = useQueryClient()
+ const setNodes = useFlowStore((state) => state.setNodes)
+ const setEdges = useFlowStore((state) => state.setEdges)
- const createFlowMutation = useMutation({
- mutationFn: flowService.create,
- onSuccess: (response) => {
- // Reset nodes and edges
- setNodes([])
- setEdges([])
- navigate({ to: `/dashboard/flows/${response.id}` })
- // Invalidate flows list
- queryClient.invalidateQueries({
- queryKey: queryKeys.flows.list
- })
- },
- onError: (error) => {
- toast.error('Failed to create flow: ' + (error instanceof Error ? error.message : "Unknown error"))
- }
- })
+ const createFlowMutation = useMutation({
+ mutationFn: flowService.create,
+ onSuccess: (response) => {
+ // Reset nodes and edges
+ setNodes([])
+ setEdges([])
+ navigate({ to: `/dashboard/flows/${response.id}` })
+ // Invalidate flows list
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.flows.list
+ })
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to create flow: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
- const handleCreateTransform = useCallback(async () => {
- toast.promise(
- createFlowMutation.mutateAsync(JSON.stringify({
- name: "New flow",
- description: "A new example flow.",
- category: [],
- flow_schema: {}
- })),
- {
- loading: 'Creating transform...',
- success: 'Transform created successfully.',
- error: 'Failed to create flow.'
- }
- )
- }, [createFlowMutation])
+ const handleCreateTransform = useCallback(async () => {
+ toast.promise(
+ createFlowMutation.mutateAsync(
+ JSON.stringify({
+ name: 'New flow',
+ description: 'A new example flow.',
+ category: [],
+ flow_schema: {}
+ })
+ ),
+ {
+ loading: 'Creating transform...',
+ success: 'Transform created successfully.',
+ error: 'Failed to create flow.'
+ }
+ )
+ }, [createFlowMutation])
- if (!isValidElement(children)) {
- return null
- }
+ if (!isValidElement(children)) {
+ return null
+ }
- return cloneElement(children as React.ReactElement<any>, {
- onClick: handleCreateTransform
- })
+ return cloneElement(children as React.ReactElement<any>, {
+ onClick: handleCreateTransform
+ })
}
-export default NewFlow
\ No newline at end of file
+export default NewFlow
diff --git a/flowsint-app/src/renderer/src/components/flows/params-dialog.tsx b/flowsint-app/src/renderer/src/components/flows/params-dialog.tsx
index 5e306e10..5b302370 100644
--- a/flowsint-app/src/renderer/src/components/flows/params-dialog.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/params-dialog.tsx
@@ -7,124 +7,125 @@ import { Label } from '../ui/label'
import { Input } from '../ui/input'
import KeySelector from '../keys/key-select'
import { type Key } from '@/types/key'
-import { useQuery } from "@tanstack/react-query"
-import { KeyService } from "@/api/key-service"
+import { useQuery } from '@tanstack/react-query'
+import { KeyService } from '@/api/key-service'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '../ui/tabs'
import { MemoizedMarkdown } from '../chat/memoized-markdown'
import { cn } from '@/lib/utils'
const ParamsDialog = () => {
- const openParamsDialog = useFlowStore(s => s.openParamsDialog)
- const setOpenParamsDialog = useFlowStore(s => s.setOpenParamsDialog)
- const selectedNode = useFlowStore(s => s.selectedNode)
- const updateNode = useFlowStore(s => s.updateNode)
- const [params, setParams] = useState<Record<string, string>>({})
- const [settings, setSettings] = useState<Record<string, string>>({
- duration: '30',
- retry: '3',
- timeout: '60',
- priority: 'medium'
- })
+ const openParamsDialog = useFlowStore((s) => s.openParamsDialog)
+ const setOpenParamsDialog = useFlowStore((s) => s.setOpenParamsDialog)
+ const selectedNode = useFlowStore((s) => s.selectedNode)
+ const updateNode = useFlowStore((s) => s.updateNode)
+ const [params, setParams] = useState<Record<string, string>>({})
+ const [settings, setSettings] = useState<Record<string, string>>({
+ duration: '30',
+ retry: '3',
+ timeout: '60',
+ priority: 'medium'
+ })
- // Initialize params and settings when selectedNode changes
- useEffect(() => {
- if (selectedNode?.data.params) {
- setParams(selectedNode.data.params)
- }
- if (selectedNode?.data.settings) {
- setSettings({ ...settings, ...selectedNode.data.settings })
- }
- }, [selectedNode])
+ // Initialize params and settings when selectedNode changes
+ useEffect(() => {
+ if (selectedNode?.data.params) {
+ setParams(selectedNode.data.params)
+ }
+ if (selectedNode?.data.settings) {
+ setSettings({ ...settings, ...selectedNode.data.settings })
+ }
+ }, [selectedNode])
- // Fetch keys to convert between IDs and Key objects
- const { data: keys = [] } = useQuery<Key[]>({
- queryKey: ['keys'],
- queryFn: () => KeyService.get(),
- })
-
- const handleSave = useCallback(async () => {
- if (!selectedNode) return
- const updatedNode = {
- ...selectedNode,
- data: {
- ...selectedNode.data,
- params,
- settings
- }
- }
- updateNode(updatedNode)
- setOpenParamsDialog(false)
- }, [selectedNode, updateNode, params, settings, setOpenParamsDialog])
+ // Fetch keys to convert between IDs and Key objects
+ const { data: keys = [] } = useQuery<Key[]>({
+ queryKey: ['keys'],
+ queryFn: () => KeyService.get()
+ })
+ const handleSave = useCallback(async () => {
if (!selectedNode) return
+ const updatedNode = {
+ ...selectedNode,
+ data: {
+ ...selectedNode.data,
+ params,
+ settings
+ }
+ }
+ updateNode(updatedNode)
+ setOpenParamsDialog(false)
+ }, [selectedNode, updateNode, params, settings, setOpenParamsDialog])
+
+ if (!selectedNode) return
- return (
- <Dialog open={openParamsDialog} onOpenChange={setOpenParamsDialog}>
- <DialogContent className="!w-[90vw] !max-w-[900px] h-[90vh] overflow-y-auto flex flex-col">
- <DialogHeader>
- <DialogTitle>Configure <span className="text-primary">{selectedNode.data.class_name}</span></DialogTitle>
- <div className={cn("justify-start", "flex w-full")}>
- <div className={cn("w-full", "p-3 rounded-xl max-w-full", "flex flex-col gap-2")}>
- <div className="max-w-none">
- {selectedNode?.data.description?.toString()}
- </div>
- </div>
- </div>
- </DialogHeader>
- <Tabs defaultValue="parameters" className="w-full">
- <TabsList className="grid w-full grid-cols-2">
- <TabsTrigger value="parameters">Parameters</TabsTrigger>
- <TabsTrigger value="documentation">Documentation</TabsTrigger>
- </TabsList>
- <TabsContent value="parameters" className="space-y-4 mt-4">
- <div className="grid gap-4">
- {selectedNode?.data?.params_schema?.map((param: TransformParamSchemaItem) => (
- <div className="space-y-2" key={param.name}>
- <div className="flex items-start flex-col">
- <Label htmlFor={param.name} className="text-sm font-medium">
- {param.name}
- {param.required && <span className="text-destructive ml-1">*</span>}
- </Label>
- <p className='text-sm opacity-60'>{param.description}</p>
- </div>
- {param.type === 'vaultSecret' ? (
- <KeySelector
- onChange={(key) => setParams({ ...params, [param.name]: key.id })}
- value={keys.find(key => key.id === params[param.name])}
- />
- ) : (
- <Input
- id={param.name}
- type={param.type}
- placeholder={param.default ?? param.name}
- value={params[param.name] || ""}
- onChange={(e) => setParams({ ...params, [param.name]: e.target.value })}
- />
- )}
- </div>
- ))}
- </div>
- </TabsContent>
- <TabsContent value="documentation" className="space-y-4 mt-4">
- <div className="grid gap-4">
- <div className={cn("w-full", "p-3 rounded-xl max-w-full", "flex flex-col gap-2")}>
- <MemoizedMarkdown id={selectedNode.id} content={selectedNode?.data.documentation?.toString() ?? ""} />
- </div>
- </div>
- </TabsContent>
- </Tabs>
+ return (
+ <Dialog open={openParamsDialog} onOpenChange={setOpenParamsDialog}>
+ <DialogContent className="!w-[90vw] !max-w-[900px] h-[90vh] overflow-y-auto flex flex-col">
+ <DialogHeader>
+ <DialogTitle>
+ Configure <span className="text-primary">{selectedNode.data.class_name}</span>
+ </DialogTitle>
+ <div className={cn('justify-start', 'flex w-full')}>
+ <div className={cn('w-full', 'p-3 rounded-xl max-w-full', 'flex flex-col gap-2')}>
+ <div className="max-w-none">{selectedNode?.data.description?.toString()}</div>
+ </div>
+ </div>
+ </DialogHeader>
+ <Tabs defaultValue="parameters" className="w-full">
+ <TabsList className="grid w-full grid-cols-2">
+ <TabsTrigger value="parameters">Parameters</TabsTrigger>
+ <TabsTrigger value="documentation">Documentation</TabsTrigger>
+ </TabsList>
+ <TabsContent value="parameters" className="space-y-4 mt-4">
+ <div className="grid gap-4">
+ {selectedNode?.data?.params_schema?.map((param: TransformParamSchemaItem) => (
+ <div className="space-y-2" key={param.name}>
+ <div className="flex items-start flex-col">
+ <Label htmlFor={param.name} className="text-sm font-medium">
+ {param.name}
+ {param.required && <span className="text-destructive ml-1">*</span>}
+ </Label>
+ <p className="text-sm opacity-60">{param.description}</p>
+ </div>
+ {param.type === 'vaultSecret' ? (
+ <KeySelector
+ onChange={(key) => setParams({ ...params, [param.name]: key.id })}
+ value={keys.find((key) => key.id === params[param.name])}
+ />
+ ) : (
+ <Input
+ id={param.name}
+ type={param.type}
+ placeholder={param.default ?? param.name}
+ value={params[param.name] || ''}
+ onChange={(e) => setParams({ ...params, [param.name]: e.target.value })}
+ />
+ )}
+ </div>
+ ))}
+ </div>
+ </TabsContent>
+ <TabsContent value="documentation" className="space-y-4 mt-4">
+ <div className="grid gap-4">
+ <div className={cn('w-full', 'p-3 rounded-xl max-w-full', 'flex flex-col gap-2')}>
+ <MemoizedMarkdown
+ id={selectedNode.id}
+ content={selectedNode?.data.documentation?.toString() ?? ''}
+ />
+ </div>
+ </div>
+ </TabsContent>
+ </Tabs>
- <DialogFooter className="mt-auto">
- <Button variant="outline" onClick={() => setOpenParamsDialog(false)}>
- Cancel
- </Button>
- <Button onClick={handleSave}>
- Save configuration
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog >
- )
+ <DialogFooter className="mt-auto">
+ <Button variant="outline" onClick={() => setOpenParamsDialog(false)}>
+ Cancel
+ </Button>
+ <Button onClick={handleSave}>Save configuration</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
}
-export default ParamsDialog
\ No newline at end of file
+export default ParamsDialog
diff --git a/flowsint-app/src/renderer/src/components/flows/raw-material.tsx b/flowsint-app/src/renderer/src/components/flows/raw-material.tsx
index bd718255..16b56301 100644
--- a/flowsint-app/src/renderer/src/components/flows/raw-material.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/raw-material.tsx
@@ -1,93 +1,100 @@
-import { useMemo, useState } from "react"
-import { Search, X } from "lucide-react"
-import TransformItem from "./transform-list-item"
-import { type Transform } from "@/types/transform"
-import { Input } from "../ui/input"
-import { Button } from "../ui/button"
-import { useQuery } from "@tanstack/react-query"
-import { SkeletonList } from "../shared/skeleton-list"
-import { flowService } from "@/api/flow-service"
-
+import { useMemo, useState } from 'react'
+import { Search, X } from 'lucide-react'
+import TransformItem from './transform-list-item'
+import { type Transform } from '@/types/transform'
+import { Input } from '../ui/input'
+import { Button } from '../ui/button'
+import { useQuery } from '@tanstack/react-query'
+import { SkeletonList } from '../shared/skeleton-list'
+import { flowService } from '@/api/flow-service'
export default function RawMaterial() {
+ const {
+ data: materials,
+ isLoading,
+ error
+ } = useQuery({
+ queryKey: ['raw_material'],
+ queryFn: () => flowService.getRawMaterial()
+ })
+ const [searchTerm, setSearchTerm] = useState<string>('')
- const { data: materials, isLoading, error } = useQuery({
- queryKey: ["raw_material"],
- queryFn: () => flowService.getRawMaterial(),
- })
- const [searchTerm, setSearchTerm] = useState<string>("")
-
- const filteredTransforms = useMemo(() => {
- if (!materials?.items) return {}
- const result: Record<string, Transform[]> = {}
- if (!searchTerm.trim()) {
- return materials?.items
- }
- const term = searchTerm.toLowerCase()
+ const filteredTransforms = useMemo(() => {
+ if (!materials?.items) return {}
+ const result: Record<string, Transform[]> = {}
+ if (!searchTerm.trim()) {
+ return materials?.items
+ }
+ const term = searchTerm.toLowerCase()
- Object.entries(materials?.items).forEach(([category, items]) => {
- // @ts-ignore
- const filtered = items.filter(
- (item: any) =>
- item.name.toLowerCase().includes(term) ||
- item.class_name.toLowerCase().includes(term) ||
- (item.doc && item.doc.toLowerCase().includes(term)),
- )
- if (filtered.length > 0) {
- result[category] = filtered
- }
- })
+ Object.entries(materials?.items).forEach(([category, items]) => {
+ // @ts-ignore
+ const filtered = items.filter(
+ (item: any) =>
+ item.name.toLowerCase().includes(term) ||
+ item.class_name.toLowerCase().includes(term) ||
+ (item.doc && item.doc.toLowerCase().includes(term))
+ )
+ if (filtered.length > 0) {
+ result[category] = filtered
+ }
+ })
- return result
- }, [searchTerm, materials?.items])
+ return result
+ }, [searchTerm, materials?.items])
- if (error) return <div>error</div>
+ if (error) return <div>error</div>
- if (isLoading) return <div><SkeletonList rowCount={7} /></div>
+ if (isLoading)
return (
- <div className="flex flex-col w-full h-full min-h-0 bg-card overflow-y-auto p-4">
- <div className="relative mb-4 flex-shrink-0">
- <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- type="text"
- placeholder="Search transforms..."
- className="pl-8 !border border-border"
- value={searchTerm}
- onChange={(e) => setSearchTerm(e.target.value)}
+ <div>
+ <SkeletonList rowCount={7} />
+ </div>
+ )
+ return (
+ <div className="flex flex-col w-full h-full min-h-0 bg-card overflow-y-auto p-4">
+ <div className="relative mb-4 flex-shrink-0">
+ <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ type="text"
+ placeholder="Search transforms..."
+ className="pl-8 !border border-border"
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ />
+ {searchTerm && (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="absolute right-1 top-1.5 h-6 w-6"
+ onClick={() => setSearchTerm('')}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ <div className="flex-1 w-full">
+ {Object.entries(filteredTransforms).map(([category, transforms]) => (
+ <div key={category} className="space-y-2 w-full">
+ <h3 className="text-sm font-medium capitalize mt-4">{category.replace('_', ' ')}</h3>
+ <div className="space-y-2">
+ {/* @ts-ignore */}
+ {transforms.map((transform: Transform) => (
+ <TransformItem
+ key={transform.name}
+ transform={transform}
+ category={transform.category}
/>
- {searchTerm && (
- <Button
- variant="ghost"
- size="icon"
- className="absolute right-1 top-1.5 h-6 w-6"
- onClick={() => setSearchTerm("")}
- >
- <X className="h-4 w-4" />
- </Button>
- )}
- </div>
- <div className="flex-1 w-full">
- {Object.entries(filteredTransforms).map(([category, transforms]) => (
- <div key={category} className="space-y-2 w-full">
- <h3 className="text-sm font-medium capitalize mt-4">{category.replace("_", " ")}</h3>
- <div className="space-y-2">
- {/* @ts-ignore */}
- {transforms.map((transform: Transform) => (
- <TransformItem
- key={transform.name}
- transform={transform}
- category={transform.category}
- />
- ))}
- </div>
- </div>
- ))}
- {Object.keys(filteredTransforms).length === 0 && (
- <div className="text-center py-4 text-muted-foreground">
- No transforms found matching "{searchTerm}"
- </div>
- )}
+ ))}
</div>
- </div>
- )
-}
\ No newline at end of file
+ </div>
+ ))}
+ {Object.keys(filteredTransforms).length === 0 && (
+ <div className="text-center py-4 text-muted-foreground">
+ No transforms found matching "{searchTerm}"
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/flows/save-modal.tsx b/flowsint-app/src/renderer/src/components/flows/save-modal.tsx
index 2c95ca8e..1ec01d80 100644
--- a/flowsint-app/src/renderer/src/components/flows/save-modal.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/save-modal.tsx
@@ -1,92 +1,93 @@
-
-import { useState } from "react"
-import { Button } from "@/components/ui/button"
+import { useState } from '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 { Label } from "@/components/ui/label"
-import { Textarea } from "@/components/ui/textarea"
-import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Textarea } from '@/components/ui/textarea'
+import { useKeyboardShortcut } from '@/hooks/use-keyboard-shortcut'
interface SaveModalProps {
- open: boolean
- onOpenChange: (open: boolean) => void
- onSave: (name: string, description: string) => void
- isLoading: boolean
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onSave: (name: string, description: string) => void
+ isLoading: boolean
}
export function SaveModal({ open, onOpenChange, onSave, isLoading }: SaveModalProps) {
- const [name, setName] = useState("My Transform")
- const [description, setDescription] = useState("")
- const [nameError, setNameError] = useState("")
+ const [name, setName] = useState('My Transform')
+ const [description, setDescription] = useState('')
+ const [nameError, setNameError] = useState('')
- useKeyboardShortcut({
- key: "s",
- ctrlOrCmd: true,
- callback: () => {
- handleSave()
- },
- })
+ useKeyboardShortcut({
+ key: 's',
+ ctrlOrCmd: true,
+ callback: () => {
+ handleSave()
+ }
+ })
- const handleSave = () => {
- if (!name.trim()) {
- setNameError("Flow name is required")
- return
- }
- onSave(name, description)
+ const handleSave = () => {
+ if (!name.trim()) {
+ setNameError('Flow name is required')
+ return
}
+ onSave(name, description)
+ }
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>Save Flow</DialogTitle>
- <DialogDescription>Give your flow a name and description before saving.</DialogDescription>
- </DialogHeader>
- <div className="grid gap-4 py-4">
- <div className="grid gap-2">
- <Label htmlFor="name" className="flex items-center justify-between">
- Name
- {nameError && <span className="text-xs text-destructive">{nameError}</span>}
- </Label>
- <Input
- id="name"
- value={name}
- onChange={(e) => {
- setName(e.target.value)
- if (e.target.value.trim()) setNameError("")
- }}
- placeholder="Enter flow name"
- className={nameError ? "border-destructive" : ""}
- />
- </div>
- <div className="grid gap-2">
- <Label htmlFor="description">Description</Label>
- <Textarea
- id="description"
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- placeholder="Enter a description (optional)"
- className="resize-none"
- rows={3}
- />
- </div>
- </div>
- <DialogFooter>
- <Button variant="outline" onClick={() => onOpenChange(false)}>
- Cancel
- </Button>
- <Button onClick={handleSave} disabled={isLoading}>
- {isLoading ? "Saving..." : "Save flow"}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>Save Flow</DialogTitle>
+ <DialogDescription>
+ Give your flow a name and description before saving.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 py-4">
+ <div className="grid gap-2">
+ <Label htmlFor="name" className="flex items-center justify-between">
+ Name
+ {nameError && <span className="text-xs text-destructive">{nameError}</span>}
+ </Label>
+ <Input
+ id="name"
+ value={name}
+ onChange={(e) => {
+ setName(e.target.value)
+ if (e.target.value.trim()) setNameError('')
+ }}
+ placeholder="Enter flow name"
+ className={nameError ? 'border-destructive' : ''}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="description">Description</Label>
+ <Textarea
+ id="description"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="Enter a description (optional)"
+ className="resize-none"
+ rows={3}
+ />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button onClick={handleSave} disabled={isLoading}>
+ {isLoading ? 'Saving...' : 'Save flow'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/flows/test-flow.tsx b/flowsint-app/src/renderer/src/components/flows/test-flow.tsx
index caff3088..1b638778 100644
--- a/flowsint-app/src/renderer/src/components/flows/test-flow.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/test-flow.tsx
@@ -1,26 +1,25 @@
-
-import { memo } from "react"
-import { Dialog, DialogContent, DialogDescription, DialogTitle } from "../ui/dialog"
-import { DynamicForm } from "../graphs/dynamic-form"
+import { memo } from 'react'
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../ui/dialog'
+import { DynamicForm } from '../graphs/dynamic-form'
interface TestTransformProps {
- open: boolean
- setOpen: (open: boolean) => void // This should accept a boolean parameter
- loading: boolean
- type: string
- onSubmit: (data: any) => Promise<void>
+ open: boolean
+ setOpen: (open: boolean) => void // This should accept a boolean parameter
+ loading: boolean
+ type: string
+ onSubmit: (data: any) => Promise<void>
}
const TestTransform = memo(({ open, setOpen, type, loading, onSubmit }: TestTransformProps) => {
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogContent>
- <DialogTitle>Test transform</DialogTitle>
- <DialogDescription>Fill the required data</DialogDescription>
- <DynamicForm currentNodeType={type} isForm={true} loading={loading} onSubmit={onSubmit} />
- </DialogContent>
- </Dialog>
- )
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent>
+ <DialogTitle>Test transform</DialogTitle>
+ <DialogDescription>Fill the required data</DialogDescription>
+ <DynamicForm currentNodeType={type} isForm={true} loading={loading} onSubmit={onSubmit} />
+ </DialogContent>
+ </Dialog>
+ )
})
export default TestTransform
diff --git a/flowsint-app/src/renderer/src/components/flows/transform-item.tsx b/flowsint-app/src/renderer/src/components/flows/transform-item.tsx
index 63857a81..d3d97d2d 100644
--- a/flowsint-app/src/renderer/src/components/flows/transform-item.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/transform-item.tsx
@@ -1,59 +1,76 @@
-import { Badge } from "@/components/ui/badge"
-import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card"
-import { hexToRgba } from "@/lib/utils"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import { Link } from "@tanstack/react-router"
-import { FileCode2, Calendar } from "lucide-react"
-import { memo, useMemo } from "react"
+import { Badge } from '@/components/ui/badge'
+import {
+ Card,
+ CardHeader,
+ CardTitle,
+ CardDescription,
+ CardContent,
+ CardFooter
+} from '@/components/ui/card'
+import { hexToRgba } from '@/lib/utils'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { Link } from '@tanstack/react-router'
+import { FileCode2, Calendar } from 'lucide-react'
+import { memo, useMemo } from 'react'
export const TransformItem = memo(({ transform }: { transform: any }) => {
- const formattedDate = transform.created_at
- ? new Date(transform.created_at).toLocaleDateString("en-US", {
- month: "short",
- day: "numeric",
- year: "numeric",
- })
- : null
+ const formattedDate = transform.created_at
+ ? new Date(transform.created_at).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric'
+ })
+ : null
- const stepsCount = transform?.flow_schema?.edges?.length || 0
+ const stepsCount = transform?.flow_schema?.edges?.length || 0
- return (
- <Link to={`/dashboard/flows/$flowId`} className="block h-full transition-all" params={{ flowId: transform.id }}>
- <Card className="h-full border hover:border-primary/50 hover:shadow-md transition-all">
- <CardHeader className="pb-2 relative">
- <CardTitle className="text-lg w-full flex items-start justify-between font-medium">
- <p className=" line-clamp-2">{transform.name}</p>
- </CardTitle>
- <CardDescription className="line-clamp-2">
- {transform.description || "No description provided"}
- </CardDescription>
- </CardHeader>
- <CardContent className="pb-2">
- <div className="flex items-center text-sm text-muted-foreground">
- <FileCode2 className="h-4 w-4 mr-1" />
- <span>
- {stepsCount} {stepsCount === 1 ? "step" : "steps"}
- </span>
- </div>
- </CardContent>
- <CardFooter className="flex flex-col items-start gap-2">
- <div className="flex items-center justify-between w-full ">
- {formattedDate && (
- <div className="flex items-center text-xs text-muted-foreground">
- <Calendar className="h-3 w-3 mr-1" />
- {formattedDate}
- </div>
- )}
- <div className="flex gap-2 items-center flex-wrap">
- {transform.category.map((category: string) => {
- const color = useNodesDisplaySettings((state) => state.colors[category as keyof typeof state.colors] || "#000000")
- const bgColor = useMemo(() => hexToRgba(color, 0.3), [color])
- return <Badge key={category} style={{ backgroundColor: bgColor }}>{category}</Badge>
- })}
- </div>
- </div>
- </CardFooter>
- </Card>
- </Link>
- )
-})
\ No newline at end of file
+ return (
+ <Link
+ to={`/dashboard/flows/$flowId`}
+ className="block h-full transition-all"
+ params={{ flowId: transform.id }}
+ >
+ <Card className="h-full border hover:border-primary/50 hover:shadow-md transition-all">
+ <CardHeader className="pb-2 relative">
+ <CardTitle className="text-lg w-full flex items-start justify-between font-medium">
+ <p className=" line-clamp-2">{transform.name}</p>
+ </CardTitle>
+ <CardDescription className="line-clamp-2">
+ {transform.description || 'No description provided'}
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="pb-2">
+ <div className="flex items-center text-sm text-muted-foreground">
+ <FileCode2 className="h-4 w-4 mr-1" />
+ <span>
+ {stepsCount} {stepsCount === 1 ? 'step' : 'steps'}
+ </span>
+ </div>
+ </CardContent>
+ <CardFooter className="flex flex-col items-start gap-2">
+ <div className="flex items-center justify-between w-full ">
+ {formattedDate && (
+ <div className="flex items-center text-xs text-muted-foreground">
+ <Calendar className="h-3 w-3 mr-1" />
+ {formattedDate}
+ </div>
+ )}
+ <div className="flex gap-2 items-center flex-wrap">
+ {transform.category.map((category: string) => {
+ const color = useNodesDisplaySettings(
+ (state) => state.colors[category as keyof typeof state.colors] || '#000000'
+ )
+ const bgColor = useMemo(() => hexToRgba(color, 0.3), [color])
+ return (
+ <Badge key={category} style={{ backgroundColor: bgColor }}>
+ {category}
+ </Badge>
+ )
+ })}
+ </div>
+ </div>
+ </CardFooter>
+ </Card>
+ </Link>
+ )
+})
diff --git a/flowsint-app/src/renderer/src/components/flows/transform-list-item.tsx b/flowsint-app/src/renderer/src/components/flows/transform-list-item.tsx
index 441c3cfe..6bb891a0 100644
--- a/flowsint-app/src/renderer/src/components/flows/transform-list-item.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/transform-list-item.tsx
@@ -1,14 +1,19 @@
-
-import type React from "react"
-import { memo, useCallback, useState } from "react"
-import { Button } from "@/components/ui/button"
-import { Info, GripVertical, TriangleAlert } from "lucide-react"
-import { TooltipProvider, Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
-import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import { Badge } from "../ui/badge"
-import { type TransformItemProps } from "@/types/transform"
-import { useIcon } from "@/hooks/use-icon"
+import type React from 'react'
+import { memo, useCallback, useState } from 'react'
+import { Button } from '@/components/ui/button'
+import { Info, GripVertical, TriangleAlert } from 'lucide-react'
+import { TooltipProvider, Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger
+} from '@/components/ui/dialog'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { Badge } from '../ui/badge'
+import { type TransformItemProps } from '@/types/transform'
+import { useIcon } from '@/hooks/use-icon'
// Custom equality function for TransformItem
function areEqual(prevProps: TransformItemProps, nextProps: TransformItemProps) {
@@ -24,10 +29,15 @@ function areEqual(prevProps: TransformItemProps, nextProps: TransformItemProps)
// Memoized transform item component for the sidebar
const TransformItem = memo(({ transform, category }: TransformItemProps) => {
- const colors = useNodesDisplaySettings(s => s.colors)
+ const colors = useNodesDisplaySettings((s) => s.colors)
const borderInputColor = colors[transform.inputs.type.toLowerCase()]
const borderOutputColor = colors[transform.outputs.type.toLowerCase()]
- const Icon = transform.type === "type" ? useIcon(transform.outputs.type.toLowerCase() as string, null) : transform.icon ? useIcon(transform.icon, null) : null
+ const Icon =
+ transform.type === 'type'
+ ? useIcon(transform.outputs.type.toLowerCase() as string, null)
+ : transform.icon
+ ? useIcon(transform.icon, null)
+ : null
const [isDialogOpen, setIsDialogOpen] = useState(false)
@@ -35,10 +45,10 @@ const TransformItem = memo(({ transform, category }: TransformItemProps) => {
const onDragStart = useCallback(
(event: React.DragEvent<HTMLDivElement>) => {
const data = { ...transform, category }
- event.dataTransfer.setData("application/json", JSON.stringify(data))
- event.dataTransfer.effectAllowed = "move"
+ event.dataTransfer.setData('application/json', JSON.stringify(data))
+ event.dataTransfer.effectAllowed = 'move'
},
- [transform, category],
+ [transform, category]
)
const isConfigurationRequired = transform.required_params
@@ -50,7 +60,13 @@ const TransformItem = memo(({ transform, category }: TransformItemProps) => {
draggable
onDragStart={onDragStart}
className="p-3 rounded-md relative w-full overflow-hidden cursor-grab bg-card border hover:shadow-md transition-all group"
- style={{ borderLeftWidth: "5px", borderRightWidth: "5px", borderLeftColor: borderInputColor ?? borderOutputColor, borderRightColor: borderOutputColor, cursor: "grab" }}
+ style={{
+ borderLeftWidth: '5px',
+ borderRightWidth: '5px',
+ borderLeftColor: borderInputColor ?? borderOutputColor,
+ borderRightColor: borderOutputColor,
+ cursor: 'grab'
+ }}
>
<div className="flex justify-between grow items-start">
<div className="flex items-start gap-2 grow truncate text-ellipsis">
@@ -60,20 +76,29 @@ const TransformItem = memo(({ transform, category }: TransformItemProps) => {
<div className="space-y-1 truncate">
<div className="flex items-center gap-2 truncate text-ellipsis">
{Icon && <Icon size={24} />}
- <h3 className="text-sm font-medium truncate text-ellipsis">{transform.class_name}</h3>
+ <h3 className="text-sm font-medium truncate text-ellipsis">
+ {transform.class_name}
+ </h3>
</div>
- <p className="text-xs font-normal truncate text-ellipsis opacity-60">{transform.description}</p>
- {transform.type !== "type" &&
+ <p className="text-xs font-normal truncate text-ellipsis opacity-60">
+ {transform.description}
+ </p>
+ {transform.type !== 'type' && (
<div className="mt-2 text-xs">
<div className="flex items-center gap-1">
<span className="font-medium">Input:</span>
- <span className="text-muted-foreground truncate text-ellipsis">{transform.inputs.type}</span>
+ <span className="text-muted-foreground truncate text-ellipsis">
+ {transform.inputs.type}
+ </span>
</div>
<div className="flex items-center gap-1">
<span className="font-medium">Output:</span>
- <span className="text-muted-foreground truncate text-ellipsis">{transform.outputs.type}</span>
+ <span className="text-muted-foreground truncate text-ellipsis">
+ {transform.outputs.type}
+ </span>
</div>
- </div>}
+ </div>
+ )}
</div>
</div>
<div className="flex items-center gap-1">
@@ -84,7 +109,7 @@ const TransformItem = memo(({ transform, category }: TransformItemProps) => {
</DialogTrigger>
</div>
</div>
- {isConfigurationRequired &&
+ {isConfigurationRequired && (
<div className="absolute bottom-3 right-3">
<Tooltip>
<TooltipTrigger asChild>
@@ -94,7 +119,8 @@ const TransformItem = memo(({ transform, category }: TransformItemProps) => {
<p>Configuration required</p>
</TooltipContent>
</Tooltip>
- </div>}
+ </div>
+ )}
</div>
<DialogContent className="sm:max-w-[725px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
@@ -104,37 +130,48 @@ const TransformItem = memo(({ transform, category }: TransformItemProps) => {
</DialogTitle>
</DialogHeader>
<div className="grid gap-4 py-4">
- {isConfigurationRequired &&
+ {isConfigurationRequired && (
<div>
- <Badge variant={"outline"} className=" top-3 right-3">
+ <Badge variant={'outline'} className=" top-3 right-3">
Configuration required <TriangleAlert className="h-4 w-4 text-orange-500" />
</Badge>
- </div>}
+ </div>
+ )}
<div className="space-y-2">
- <h4 className="font-medium text-sm" style={{ color: borderInputColor }}>Description</h4>
- <p className="text-sm text-muted-foreground">{transform.description || "No description available"}</p>
+ <h4 className="font-medium text-sm" style={{ color: borderInputColor }}>
+ Description
+ </h4>
+ <p className="text-sm text-muted-foreground">
+ {transform.description || 'No description available'}
+ </p>
</div>
<div className="space-y-2">
- <h4 className="font-medium text-sm" style={{ color: borderInputColor }}>Module</h4>
+ <h4 className="font-medium text-sm" style={{ color: borderInputColor }}>
+ Module
+ </h4>
<p className="text-sm text-muted-foreground">{transform.module}</p>
</div>
<div className="space-y-2">
- <h4 className="font-medium text-sm" style={{ color: borderInputColor }}>Input Properties</h4>
+ <h4 className="font-medium text-sm" style={{ color: borderInputColor }}>
+ Input Properties
+ </h4>
<div className="space-y-1">
{transform?.inputs?.properties?.map((prop, index) => (
<div key={index} className="text-sm">
- <span className="font-medium">{prop.name}:</span>{" "}
+ <span className="font-medium">{prop.name}:</span>{' '}
<span className="text-muted-foreground">{prop.type}</span>
</div>
))}
</div>
</div>
<div className="space-y-2">
- <h4 className="font-medium text-sm" style={{ color: borderOutputColor }}>Output Properties</h4>
+ <h4 className="font-medium text-sm" style={{ color: borderOutputColor }}>
+ Output Properties
+ </h4>
<div className="space-y-1">
{transform?.outputs?.properties?.map((prop, index) => (
<div key={index} className="text-sm">
- <span className="font-medium">{prop.name}:</span>{" "}
+ <span className="font-medium">{prop.name}:</span>{' '}
<span className="text-muted-foreground">{prop.type}</span>
</div>
))}
@@ -147,6 +184,6 @@ const TransformItem = memo(({ transform, category }: TransformItemProps) => {
)
}, areEqual)
-TransformItem.displayName = "TransformItem"
+TransformItem.displayName = 'TransformItem'
export default TransformItem
diff --git a/flowsint-app/src/renderer/src/components/flows/transform-node.tsx b/flowsint-app/src/renderer/src/components/flows/transform-node.tsx
index c50a6378..dd875504 100644
--- a/flowsint-app/src/renderer/src/components/flows/transform-node.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/transform-node.tsx
@@ -1,179 +1,185 @@
-import { memo, useCallback } from "react"
-import { Position } from "@xyflow/react"
-import { Badge } from "../ui/badge"
-import { BaseNode } from "../xyflow/base-node"
-import { NodeStatusIndicator } from "../xyflow/node-status-indicator"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import { cn } from "@/lib/utils"
-import { Plus, TriangleAlert } from "lucide-react"
-import { type TransformNodeProps } from "@/types/transform"
-import { FlowNode, useFlowStore } from "@/stores/flow-store"
-import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
-import { Button } from "../ui/button"
-import { ButtonHandle } from "../xyflow/button-handle"
-import { useIcon } from "@/hooks/use-icon"
+import { memo, useCallback } from 'react'
+import { Position } from '@xyflow/react'
+import { Badge } from '../ui/badge'
+import { BaseNode } from '../xyflow/base-node'
+import { NodeStatusIndicator } from '../xyflow/node-status-indicator'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { cn } from '@/lib/utils'
+import { Plus, TriangleAlert } from 'lucide-react'
+import { type TransformNodeProps } from '@/types/transform'
+import { FlowNode, useFlowStore } from '@/stores/flow-store'
+import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'
+import { Button } from '../ui/button'
+import { ButtonHandle } from '../xyflow/button-handle'
+import { useIcon } from '@/hooks/use-icon'
// Custom equality function to prevent unnecessary re-renders
function areEqual(prevProps: TransformNodeProps, nextProps: TransformNodeProps) {
- return (
- prevProps.data.class_name === nextProps.data.class_name &&
- prevProps.data.name === nextProps.data.name &&
- prevProps.data.module === nextProps.data.module &&
- prevProps.data.documentation === nextProps.data.documentation &&
- prevProps.data.description === nextProps.data.description &&
- prevProps.data.key === nextProps.data.key &&
- prevProps.data.category === nextProps.data.category &&
- prevProps.data.color === nextProps.data.color &&
- prevProps.data.computationState === nextProps.data.computationState &&
- prevProps.isConnectable === nextProps.isConnectable
- )
+ return (
+ prevProps.data.class_name === nextProps.data.class_name &&
+ prevProps.data.name === nextProps.data.name &&
+ prevProps.data.module === nextProps.data.module &&
+ prevProps.data.documentation === nextProps.data.documentation &&
+ prevProps.data.description === nextProps.data.description &&
+ prevProps.data.key === nextProps.data.key &&
+ prevProps.data.category === nextProps.data.category &&
+ prevProps.data.color === nextProps.data.color &&
+ prevProps.data.computationState === nextProps.data.computationState &&
+ prevProps.isConnectable === nextProps.isConnectable
+ )
}
const getStateColor = (state?: string) => {
- switch (state) {
- case "pending":
- return "bg-gray-200 text-gray-700"
- case "processing":
- return "bg-blue-100 text-blue-700"
- case "completed":
- return "bg-green-100 text-green-700"
- case "error":
- return "bg-red-100 text-red-700"
- default:
- return "bg-gray-200 text-gray-700"
- }
+ switch (state) {
+ case 'pending':
+ return 'bg-gray-200 text-gray-700'
+ case 'processing':
+ return 'bg-blue-100 text-blue-700'
+ case 'completed':
+ return 'bg-green-100 text-green-700'
+ case 'error':
+ return 'bg-red-100 text-red-700'
+ default:
+ return 'bg-gray-200 text-gray-700'
+ }
}
// Transform node component for transform/transform nodes only
const TransformNode = memo(({ data, isConnectable }: TransformNodeProps) => {
- const colors = useNodesDisplaySettings(s => s.colors)
- const inputColor = colors[data.inputs.type.toLowerCase()]
- const outputColor = colors[data.outputs.type.toLowerCase()]
- const opacity = data.computationState === "pending" ? 0.5 : 1
- const setOpenFlowSheet = useFlowStore(state => state.setOpenFlowSheet)
- const Icon = data.type === "type" ? useIcon(data.outputs.type.toLowerCase() as string, null) : data.icon ? useIcon(data.icon, null) : null
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ const inputColor = colors[data.inputs.type.toLowerCase()]
+ const outputColor = colors[data.outputs.type.toLowerCase()]
+ const opacity = data.computationState === 'pending' ? 0.5 : 1
+ const setOpenFlowSheet = useFlowStore((state) => state.setOpenFlowSheet)
+ const Icon =
+ data.type === 'type'
+ ? useIcon(data.outputs.type.toLowerCase() as string, null)
+ : data.icon
+ ? useIcon(data.icon, null)
+ : null
- const handleAddConnector = useCallback(() => {
- setOpenFlowSheet(true, data as unknown as FlowNode)
- }, [setOpenFlowSheet, data])
+ const handleAddConnector = useCallback(() => {
+ setOpenFlowSheet(true, data as unknown as FlowNode)
+ }, [setOpenFlowSheet, data])
- const getStatusVariant = (state?: string) => {
- switch (state) {
- case "pending":
- return "pending"
- case "processing":
- return "loading"
- case "completed":
- return "success"
- case "error":
- return "error"
- default:
- return undefined
- }
+ const getStatusVariant = (state?: string) => {
+ switch (state) {
+ case 'pending':
+ return 'pending'
+ case 'processing':
+ return 'loading'
+ case 'completed':
+ return 'success'
+ case 'error':
+ return 'error'
+ default:
+ return undefined
}
- const isConfigurationRequired = data.required_params
+ }
+ const isConfigurationRequired = data.required_params
- return (
- <NodeStatusIndicator variant={getStatusVariant(data.computationState)} showStatus={true}>
- <BaseNode
- className={cn("shadow-md relative p-0 bg-background rounded-md !w-[300px]")}
- style={{
- borderLeftWidth: 5,
- borderRightWidth: 5,
- borderLeftColor: inputColor ?? outputColor,
- borderRightColor: outputColor,
- cursor: "grab",
- opacity
- }}
- // selected={selected}
- >
- <div className="p-3 bg-card rounded-t-md">
- <div className="flex flex-col items-start gap-1 relative">
- <div className="absolute top-0 right-0 flex items-center gap-2">
- {data.computationState && (
- <Badge className={getStateColor(data.computationState)}>
- {data.computationState}
- </Badge>
- )}
- </div>
- <div className="flex items-center gap-2 truncate text-ellipsis">
- {Icon && <Icon size={24} />}
- <div className="font-semibold text-sm">{data.class_name}</div>
- </div>
- <p className="text-xs text-muted-foreground mt-2 line-clamp-2">{data.description}</p>
- </div>
- </div>
- <div>
- <div className="grid grid-cols-2 py-1">
- <div className="pl-0 pr-6">
- {data?.inputs?.properties?.length > 0 && (
- <ButtonHandle
- connectionCount={1}
- showButton={false}
- isConnectable={isConnectable}
- id={data.inputs.type}
- label={data.inputs.type}
- type="target"
- position={Position.Left}
- >
- <Button
- onClick={handleAddConnector}
- size="icon"
- variant="secondary"
- className="rounded-full"
- >
- <Plus size={10} />
- </Button>
- </ButtonHandle>
- )}
- </div>
- <div className="pr-0">
- {data?.outputs?.properties?.length > 0 && (
- <ButtonHandle
- showButton={!data.computationState}
- isConnectable={isConnectable}
- id={data.outputs.type}
- label={data.outputs.type}
- type="source"
- position={Position.Right}
- >
- <Button
- onClick={handleAddConnector}
- size="icon"
- variant="secondary"
- className="rounded-full"
- >
- <Plus size={10} />
- </Button>
- </ButtonHandle>
- )}
- </div>
- </div>
- <div className="flex items-center justify-between px-3 gap-1 py-1">
- {data?.inputs?.properties?.length > 0 && (
- <Badge variant="outline">{data.inputs.type}</Badge>
- )}
- {data?.outputs?.properties?.length > 0 && (
- <Badge variant="outline">{data.outputs.type}</Badge>
- )}
- </div>
- {isConfigurationRequired &&
- <div className="absolute top-3 right-3">
- <Tooltip>
- <TooltipTrigger asChild>
- <TriangleAlert className="h-4 w-4 text-yellow-500" />
- </TooltipTrigger>
- <TooltipContent>
- <p>Configuration required</p>
- </TooltipContent>
- </Tooltip>
- </div>}
- </div>
- </BaseNode>
- </NodeStatusIndicator>
- )
+ return (
+ <NodeStatusIndicator variant={getStatusVariant(data.computationState)} showStatus={true}>
+ <BaseNode
+ className={cn('shadow-md relative p-0 bg-background rounded-md !w-[300px]')}
+ style={{
+ borderLeftWidth: 5,
+ borderRightWidth: 5,
+ borderLeftColor: inputColor ?? outputColor,
+ borderRightColor: outputColor,
+ cursor: 'grab',
+ opacity
+ }}
+ // selected={selected}
+ >
+ <div className="p-3 bg-card rounded-t-md">
+ <div className="flex flex-col items-start gap-1 relative">
+ <div className="absolute top-0 right-0 flex items-center gap-2">
+ {data.computationState && (
+ <Badge className={getStateColor(data.computationState)}>
+ {data.computationState}
+ </Badge>
+ )}
+ </div>
+ <div className="flex items-center gap-2 truncate text-ellipsis">
+ {Icon && <Icon size={24} />}
+ <div className="font-semibold text-sm">{data.class_name}</div>
+ </div>
+ <p className="text-xs text-muted-foreground mt-2 line-clamp-2">{data.description}</p>
+ </div>
+ </div>
+ <div>
+ <div className="grid grid-cols-2 py-1">
+ <div className="pl-0 pr-6">
+ {data?.inputs?.properties?.length > 0 && (
+ <ButtonHandle
+ connectionCount={1}
+ showButton={false}
+ isConnectable={isConnectable}
+ id={data.inputs.type}
+ label={data.inputs.type}
+ type="target"
+ position={Position.Left}
+ >
+ <Button
+ onClick={handleAddConnector}
+ size="icon"
+ variant="secondary"
+ className="rounded-full"
+ >
+ <Plus size={10} />
+ </Button>
+ </ButtonHandle>
+ )}
+ </div>
+ <div className="pr-0">
+ {data?.outputs?.properties?.length > 0 && (
+ <ButtonHandle
+ showButton={!data.computationState}
+ isConnectable={isConnectable}
+ id={data.outputs.type}
+ label={data.outputs.type}
+ type="source"
+ position={Position.Right}
+ >
+ <Button
+ onClick={handleAddConnector}
+ size="icon"
+ variant="secondary"
+ className="rounded-full"
+ >
+ <Plus size={10} />
+ </Button>
+ </ButtonHandle>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center justify-between px-3 gap-1 py-1">
+ {data?.inputs?.properties?.length > 0 && (
+ <Badge variant="outline">{data.inputs.type}</Badge>
+ )}
+ {data?.outputs?.properties?.length > 0 && (
+ <Badge variant="outline">{data.outputs.type}</Badge>
+ )}
+ </div>
+ {isConfigurationRequired && (
+ <div className="absolute top-3 right-3">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <TriangleAlert className="h-4 w-4 text-yellow-500" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Configuration required</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ )}
+ </div>
+ </BaseNode>
+ </NodeStatusIndicator>
+ )
}, areEqual)
-TransformNode.displayName = "TransformNode"
+TransformNode.displayName = 'TransformNode'
export default TransformNode
diff --git a/flowsint-app/src/renderer/src/components/flows/type-node.tsx b/flowsint-app/src/renderer/src/components/flows/type-node.tsx
index 4eb9ee1c..1f44acfb 100644
--- a/flowsint-app/src/renderer/src/components/flows/type-node.tsx
+++ b/flowsint-app/src/renderer/src/components/flows/type-node.tsx
@@ -1,84 +1,89 @@
-import { memo, useCallback } from "react"
-import { Position } from "@xyflow/react"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import { useIcon } from "@/hooks/use-icon"
-import { cn } from "@/lib/utils"
-import { Plus } from "lucide-react"
-import { type TransformNodeProps } from "@/types/transform"
-import { ButtonHandle } from "@/components/xyflow/button-handle"
-import { Button } from "../ui/button"
+import { memo, useCallback } from 'react'
+import { Position } from '@xyflow/react'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { useIcon } from '@/hooks/use-icon'
+import { cn } from '@/lib/utils'
+import { Plus } from 'lucide-react'
+import { type TransformNodeProps } from '@/types/transform'
+import { ButtonHandle } from '@/components/xyflow/button-handle'
+import { Button } from '../ui/button'
import {
- NodeTooltip,
- NodeTooltipContent,
- NodeTooltipTrigger,
-} from "@/components/xyflow/node-tooltip";
-import { BaseNode, BaseNodeContent } from "@/components/xyflow/base-node";
-import { FlowNode, useFlowStore } from "@/stores/flow-store"
+ NodeTooltip,
+ NodeTooltipContent,
+ NodeTooltipTrigger
+} from '@/components/xyflow/node-tooltip'
+import { BaseNode, BaseNodeContent } from '@/components/xyflow/base-node'
+import { FlowNode, useFlowStore } from '@/stores/flow-store'
// Custom equality function to prevent unnecessary re-renders
function areEqual(prevProps: TransformNodeProps, nextProps: TransformNodeProps) {
- return (
- prevProps.data.class_name === nextProps.data.class_name &&
- prevProps.data.name === nextProps.data.name &&
- prevProps.data.color === nextProps.data.color &&
- prevProps.isConnectable === nextProps.isConnectable
- )
+ return (
+ prevProps.data.class_name === nextProps.data.class_name &&
+ prevProps.data.name === nextProps.data.name &&
+ prevProps.data.color === nextProps.data.color &&
+ prevProps.isConnectable === nextProps.isConnectable
+ )
}
// Type node component for data types (domains, websites, IPs, etc.)
const TypeNode = memo(({ data }: TransformNodeProps) => {
- const colors = useNodesDisplaySettings(s => s.colors)
- const outputColor = colors[data.outputs.type.toLowerCase()]
- const Icon = useIcon(data.outputs.type.toLowerCase() as string, null)
- const setOpenFlowSheet = useFlowStore(state => state.setOpenFlowSheet)
- const key = data.outputs.properties[0].name
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ const outputColor = colors[data.outputs.type.toLowerCase()]
+ const Icon = useIcon(data.outputs.type.toLowerCase() as string, null)
+ const setOpenFlowSheet = useFlowStore((state) => state.setOpenFlowSheet)
+ const key = data.outputs.properties[0].name
- const handleAddConnector = useCallback(() => {
- setOpenFlowSheet(true, data as unknown as FlowNode)
- }, [setOpenFlowSheet, data])
+ const handleAddConnector = useCallback(() => {
+ setOpenFlowSheet(true, data as unknown as FlowNode)
+ }, [setOpenFlowSheet, data])
- return (
- <NodeTooltip>
- <NodeTooltipContent isVisible={true} position={Position.Top} className="text-center bg-background text-foreground border shadow-md">
- {data.name}
- </NodeTooltipContent>
- <BaseNode className={cn("shadow-md relative p-0 pl-1.5 bg-background !max-w-[240px]")}
- style={{
- borderWidth: 2,
- borderColor: outputColor,
- cursor: "grab",
- borderRadius: "35px 10px 10px 35px"
- }}
- // selected={selected}
+ return (
+ <NodeTooltip>
+ <NodeTooltipContent
+ isVisible={true}
+ position={Position.Top}
+ className="text-center bg-background text-foreground border shadow-md"
+ >
+ {data.name}
+ </NodeTooltipContent>
+ <BaseNode
+ className={cn('shadow-md relative p-0 pl-1.5 bg-background !max-w-[240px]')}
+ style={{
+ borderWidth: 2,
+ borderColor: outputColor,
+ cursor: 'grab',
+ borderRadius: '35px 10px 10px 35px'
+ }}
+ // selected={selected}
+ >
+ <BaseNodeContent>
+ <NodeTooltipTrigger>
+ <div className="p-4 flex items-center justify-center">
+ <Icon size={32} />
+ </div>
+ <ButtonHandle
+ type="source"
+ id={data.outputs.type}
+ position={Position.Right}
+ showButton={true}
+ label={key}
>
- <BaseNodeContent>
- <NodeTooltipTrigger>
- <div className="p-4 flex items-center justify-center">
- <Icon size={32} />
- </div>
- <ButtonHandle
- type="source"
- id={data.outputs.type}
- position={Position.Right}
- showButton={true}
- label={key}
- >
- <Button
- onClick={handleAddConnector}
- size="icon"
- variant="secondary"
- className="rounded-full"
- >
- <Plus size={10} />
- </Button>
- </ButtonHandle>
- </NodeTooltipTrigger>
- </BaseNodeContent>
- </BaseNode>
- </NodeTooltip>
- )
+ <Button
+ onClick={handleAddConnector}
+ size="icon"
+ variant="secondary"
+ className="rounded-full"
+ >
+ <Plus size={10} />
+ </Button>
+ </ButtonHandle>
+ </NodeTooltipTrigger>
+ </BaseNodeContent>
+ </BaseNode>
+ </NodeTooltip>
+ )
}, areEqual)
-TypeNode.displayName = "TypeNode"
+TypeNode.displayName = 'TypeNode'
-export default TypeNode
\ No newline at end of file
+export default TypeNode
diff --git a/flowsint-app/src/renderer/src/components/graphs/add-item-dialog.tsx b/flowsint-app/src/renderer/src/components/graphs/add-item-dialog.tsx
index 82845dde..efa79caa 100644
--- a/flowsint-app/src/renderer/src/components/graphs/add-item-dialog.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/add-item-dialog.tsx
@@ -1,276 +1,297 @@
-import { useState, useCallback } from "react"
-import { Button } from "@/components/ui/button"
+import { useState, useCallback } from 'react'
+import { Button } from '@/components/ui/button'
import { ArrowLeft, ArrowRight } from 'lucide-react'
-import { toast } from "sonner"
-import { cn, flattenObj } from "@/lib/utils"
-import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"
-import { type ActionItem, type FormField, findActionItemByKey } from "@/lib/action-items"
-import { Card, CardContent } from "@/components/ui/card"
-import { AnimatePresence, motion } from "framer-motion"
-import { DynamicForm } from "@/components/graphs/dynamic-form"
-import { Badge } from "@/components/ui/badge"
-import { useGraphStore } from "@/stores/graph-store"
-import { sketchService } from "@/api/sketch-service"
-import { useParams } from "@tanstack/react-router"
-import { useIcon } from "@/hooks/use-icon"
-import { useLayoutStore } from "@/stores/layout-store"
-import { useActionItems } from "@/hooks/use-action-items"
-import { GraphNode } from "@/types"
+import { toast } from 'sonner'
+import { cn, flattenObj } from '@/lib/utils'
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
+import { type ActionItem, type FormField, findActionItemByKey } from '@/lib/action-items'
+import { Card, CardContent } from '@/components/ui/card'
+import { AnimatePresence, motion } from 'framer-motion'
+import { DynamicForm } from '@/components/graphs/dynamic-form'
+import { Badge } from '@/components/ui/badge'
+import { useGraphStore } from '@/stores/graph-store'
+import { sketchService } from '@/api/sketch-service'
+import { useParams } from '@tanstack/react-router'
+import { useIcon } from '@/hooks/use-icon'
+import { useLayoutStore } from '@/stores/layout-store'
+import { useActionItems } from '@/hooks/use-action-items'
+import { GraphNode } from '@/types'
export default function AddItemDialog() {
- const handleOpenFormModal = useGraphStore(state => state.handleOpenFormModal)
- const currentNodeType = useGraphStore(state => state.currentNodeType)
- const setCurrentNode = useGraphStore(state => state.setCurrentNode)
- const relatedNodeToAdd = useGraphStore(state => state.relatedNodeToAdd)
- const setRelatedNodeToAdd = useGraphStore(state => state.setRelatedNodeToAdd)
- const openMainDialog = useGraphStore(state => state.openMainDialog)
- const setOpenMainDialog = useGraphStore(state => state.setOpenMainDialog)
- const openFormDialog = useGraphStore(state => state.openFormDialog)
- const setOpenFormDialog = useGraphStore(state => state.setOpenFormDialog)
- const addNode = useGraphStore(state => state.addNode)
- const addEdge = useGraphStore(state => state.addEdge)
- const setActiveTab = useLayoutStore(state => state.setActiveTab)
- const { id: sketch_id } = useParams({ strict: false })
- const { actionItems, isLoading } = useActionItems()
+ const handleOpenFormModal = useGraphStore((state) => state.handleOpenFormModal)
+ const currentNodeType = useGraphStore((state) => state.currentNodeType)
+ const setCurrentNode = useGraphStore((state) => state.setCurrentNode)
+ const relatedNodeToAdd = useGraphStore((state) => state.relatedNodeToAdd)
+ const setRelatedNodeToAdd = useGraphStore((state) => state.setRelatedNodeToAdd)
+ const openMainDialog = useGraphStore((state) => state.openMainDialog)
+ const setOpenMainDialog = useGraphStore((state) => state.setOpenMainDialog)
+ const openFormDialog = useGraphStore((state) => state.openFormDialog)
+ const setOpenFormDialog = useGraphStore((state) => state.setOpenFormDialog)
+ const addNode = useGraphStore((state) => state.addNode)
+ const addEdge = useGraphStore((state) => state.addEdge)
+ const setActiveTab = useLayoutStore((state) => state.setActiveTab)
+ const { id: sketch_id } = useParams({ strict: false })
+ const { actionItems, isLoading } = useActionItems()
- const [currentParent, setCurrentParent] = useState<ActionItem | null>(null)
- const [navigationHistory, setNavigationHistory] = useState<ActionItem[]>([])
+ const [currentParent, setCurrentParent] = useState<ActionItem | null>(null)
+ const [navigationHistory, setNavigationHistory] = useState<ActionItem[]>([])
- const handleDialogOpenChange = useCallback((open: boolean) => {
- setOpenMainDialog(open)
- if (!open) {
- setRelatedNodeToAdd(null)
- }
- }, [setOpenMainDialog, setRelatedNodeToAdd])
-
- const handleAddNode = async (data: any) => {
- try {
- if (!currentNodeType || !sketch_id) {
- toast.error("Invalid node type or sketch ID.")
- return
- }
- const label_key = currentNodeType.fields.find((f: FormField) => f.name === currentNodeType.label_key)?.name || currentNodeType.fields[0].name
- const type = currentNodeType.type
- let label = data[label_key as keyof typeof data]
-
- const newNode = {
- type: "custom",
- label: label,
- data: {
- ...flattenObj(data),
- label,
- type: type.toLowerCase(),
- },
- }
+ const handleDialogOpenChange = useCallback(
+ (open: boolean) => {
+ setOpenMainDialog(open)
+ if (!open) {
+ setRelatedNodeToAdd(null)
+ }
+ },
+ [setOpenMainDialog, setRelatedNodeToAdd]
+ )
- // First, create the node via API to get the real database ID
- const newNodeResponse = await sketchService.addNode(sketch_id as string, JSON.stringify(newNode))
+ const handleAddNode = async (data: any) => {
+ try {
+ if (!currentNodeType || !sketch_id) {
+ toast.error('Invalid node type or sketch ID.')
+ return
+ }
+ const label_key =
+ currentNodeType.fields.find((f: FormField) => f.name === currentNodeType.label_key)?.name ||
+ currentNodeType.fields[0].name
+ const type = currentNodeType.type
+ const label = data[label_key as keyof typeof data]
- // Add the node to local state with the real ID from the API response
- if (addNode && newNodeResponse.node) {
- const nodeWithRealId = {
- ...newNode,
- id: newNodeResponse.node.id,
- position: { x: 0, y: 0 }
- }
- addNode(nodeWithRealId as any)
- }
+ const newNode = {
+ type: 'custom',
+ label: label,
+ data: {
+ ...flattenObj(data),
+ label,
+ type: type.toLowerCase()
+ }
+ }
- // If we have a related node to connect to, create the edge
- if (relatedNodeToAdd && newNodeResponse.node) {
- const newEdge = {
- source: relatedNodeToAdd,
- target: newNodeResponse.node,
- type: "one-way",
- label: `HAS_${newNode.data.type.toUpperCase()}`,
- sketch_id: sketch_id
- }
+ // First, create the node via API to get the real database ID
+ const newNodeResponse = await sketchService.addNode(
+ sketch_id as string,
+ JSON.stringify(newNode)
+ )
- // Add edge to local state
- if (addEdge) {
- const newEdgeObject = {
- type: "custom",
- label: newEdge.label,
- source: newEdge.source.id,
- target: newEdge.target.id
- }
- addEdge(newEdgeObject)
- }
+ // Add the node to local state with the real ID from the API response
+ if (addNode && newNodeResponse.node) {
+ const nodeWithRealId = {
+ ...newNode,
+ id: newNodeResponse.node.id,
+ position: { x: 0, y: 0 }
+ }
+ addNode(nodeWithRealId as any)
+ }
- // Make API call to persist the edge
- await sketchService.addEdge(sketch_id as string, JSON.stringify(newEdge))
- }
+ // If we have a related node to connect to, create the edge
+ if (relatedNodeToAdd && newNodeResponse.node) {
+ const newEdge = {
+ source: relatedNodeToAdd,
+ target: newNodeResponse.node,
+ type: 'one-way',
+ label: `HAS_${newNode.data.type.toUpperCase()}`,
+ sketch_id: sketch_id
+ }
- // Set current node using the API response (which has the correct ID from the database)
- if (setCurrentNode) setCurrentNode({ ...newNodeResponse.node, position: { x: 0, y: 0 } } as GraphNode)
- setActiveTab("entities")
- toast.success(relatedNodeToAdd ? `New relation added to ${relatedNodeToAdd.data.label}.` : "New node added.")
- } catch (error) {
- console.error(error)
- toast.error("Unexpected error during node creation.")
- } finally {
- setOpenMainDialog(false)
- setOpenFormDialog(false)
+ // Add edge to local state
+ if (addEdge) {
+ const newEdgeObject = {
+ type: 'custom',
+ label: newEdge.label,
+ source: newEdge.source.id,
+ target: newEdge.target.id
+ }
+ addEdge(newEdgeObject)
}
- }
- const navigateToSubItems = (item: ActionItem) => {
- setNavigationHistory([...navigationHistory, item])
- setCurrentParent(item)
- }
+ // Make API call to persist the edge
+ await sketchService.addEdge(sketch_id as string, JSON.stringify(newEdge))
+ }
- const navigateBack = () => {
- const newHistory = [...navigationHistory]
- newHistory.pop()
- setNavigationHistory(newHistory)
- setCurrentParent(newHistory.length > 0 ? newHistory[newHistory.length - 1] : null)
+ // Set current node using the API response (which has the correct ID from the database)
+ if (setCurrentNode)
+ setCurrentNode({ ...newNodeResponse.node, position: { x: 0, y: 0 } } as GraphNode)
+ setActiveTab('entities')
+ toast.success(
+ relatedNodeToAdd
+ ? `New relation added to ${relatedNodeToAdd.data.label}.`
+ : 'New node added.'
+ )
+ } catch (error) {
+ console.error(error)
+ toast.error('Unexpected error during node creation.')
+ } finally {
+ setOpenMainDialog(false)
+ setOpenFormDialog(false)
}
+ }
- const renderActionCards = () => {
- const items = currentParent ? currentParent.children || [] : actionItems
+ const navigateToSubItems = (item: ActionItem) => {
+ setNavigationHistory([...navigationHistory, item])
+ setCurrentParent(item)
+ }
- if (!items || items.length === 0) {
- return (
- <div className="flex items-center justify-center h-32">
- <div className="text-center">
- <p className="text-sm text-muted-foreground">No action items available</p>
- </div>
- </div>
- )
- }
+ const navigateBack = () => {
+ const newHistory = [...navigationHistory]
+ newHistory.pop()
+ setNavigationHistory(newHistory)
+ setCurrentParent(newHistory.length > 0 ? newHistory[newHistory.length - 1] : null)
+ }
- return (
- <AnimatePresence mode="wait">
- <motion.div
- key={currentParent?.id || "root"}
- initial={{ opacity: 0, x: 20 }}
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: -20 }}
- transition={{ duration: 0.2 }}
- className="grid grid-cols-3 cq-sm:grid-cols-4 cq-md:grid-cols-5 cq-lg:grid-cols-6 cq-xl:grid-cols-6 gap-3 p-1 pb-2" >
- {items.map((item) => (
- <ActionCard
- key={item.id}
- item={item}
- onSelect={item.children ? () => navigateToSubItems(item) : () => handleOpenFormModal(findActionItemByKey(item.key, actionItems))}
- />
- ))}
- </motion.div>
- </AnimatePresence>
- )
+ const renderActionCards = () => {
+ const items = currentParent ? currentParent.children || [] : actionItems
+
+ if (!items || items.length === 0) {
+ return (
+ <div className="flex items-center justify-center h-32">
+ <div className="text-center">
+ <p className="text-sm text-muted-foreground">No action items available</p>
+ </div>
+ </div>
+ )
}
return (
- <>
- <Dialog open={openMainDialog} onOpenChange={handleDialogOpenChange}>
- <DialogContent className="sm:max-w-[800px] h-[80vh] overflow-hidden flex flex-col">
- <DialogTitle className="flex items-center">
- {currentParent && (
- <Button variant="ghost" size="icon" className="mr-2" onClick={navigateBack}>
- <ArrowLeft className="h-4 w-4" />
- </Button>
- )}
- {relatedNodeToAdd
- ? `Add a relation to `
- : currentParent
- ? currentParent.label
- : "Select an item to insert"
- }
- {relatedNodeToAdd && (
- <span className="text-primary truncate max-w-[50%] text-ellipsis font-semibold ml-1">
- {relatedNodeToAdd.data.label}
- </span>
- )}
- </DialogTitle>
- <DialogDescription>
- {relatedNodeToAdd
- ? "Choose what type of relation to add to this node."
- : currentParent
- ? `Select a type of ${currentParent.label.toLowerCase()} to add`
- : "Choose an item to insert to the graph."
- }
- </DialogDescription>
-
- <div className="overflow-y-auto overflow-x-hidden pr-1 -mr-1 flex-grow @container">
- {isLoading ? (
- <div className="grid grid-cols-3 cq-sm:grid-cols-4 cq-md:grid-cols-5 cq-lg:grid-cols-6 cq-xl:grid-cols-6 gap-3 p-1 pb-2">
- {Array.from({ length: 6 }).map((_, index) => (
- <Card key={index} className="h-full">
- <CardContent className="p-2 relative flex flex-col items-center text-center h-full">
- <div className="w-8 h-8 rounded-full bg-muted animate-pulse mb-3 mt-2"></div>
- <div className="h-4 bg-muted rounded animate-pulse w-20 mb-2"></div>
- <div className="h-3 bg-muted rounded animate-pulse w-32"></div>
- </CardContent>
- </Card>
- ))}
- </div>
- ) : (
- renderActionCards()
- )}
- </div>
- </DialogContent>
- </Dialog>
- <Dialog open={openFormDialog} onOpenChange={setOpenFormDialog}>
- <DialogContent className="max-h-[95vh] flex flex-col">
- <DialogTitle>
- {currentNodeType && (
- <>Add {currentNodeType.label.toLowerCase()}</>
- )}
- </DialogTitle>
- <DialogDescription>{currentNodeType?.description}</DialogDescription>
- {currentNodeType && (
- <div className="grow overflow-y-auto">
- <DynamicForm
- currentNodeType={currentNodeType}
- isForm={true}
- onSubmit={handleAddNode}
- />
- </div>
- )}
- </DialogContent >
- </Dialog>
- </>
+ <AnimatePresence mode="wait">
+ <motion.div
+ key={currentParent?.id || 'root'}
+ initial={{ opacity: 0, x: 20 }}
+ animate={{ opacity: 1, x: 0 }}
+ exit={{ opacity: 0, x: -20 }}
+ transition={{ duration: 0.2 }}
+ className="grid grid-cols-3 cq-sm:grid-cols-4 cq-md:grid-cols-5 cq-lg:grid-cols-6 cq-xl:grid-cols-6 gap-3 p-1 pb-2"
+ >
+ {items.map((item) => (
+ <ActionCard
+ key={item.id}
+ item={item}
+ onSelect={
+ item.children
+ ? () => navigateToSubItems(item)
+ : () => handleOpenFormModal(findActionItemByKey(item.key, actionItems))
+ }
+ />
+ ))}
+ </motion.div>
+ </AnimatePresence>
)
+ }
+
+ return (
+ <>
+ <Dialog open={openMainDialog} onOpenChange={handleDialogOpenChange}>
+ <DialogContent className="sm:max-w-[800px] h-[80vh] overflow-hidden flex flex-col">
+ <DialogTitle className="flex items-center">
+ {currentParent && (
+ <Button variant="ghost" size="icon" className="mr-2" onClick={navigateBack}>
+ <ArrowLeft className="h-4 w-4" />
+ </Button>
+ )}
+ {relatedNodeToAdd
+ ? `Add a relation to `
+ : currentParent
+ ? currentParent.label
+ : 'Select an item to insert'}
+ {relatedNodeToAdd && (
+ <span className="text-primary truncate max-w-[50%] text-ellipsis font-semibold ml-1">
+ {relatedNodeToAdd.data.label}
+ </span>
+ )}
+ </DialogTitle>
+ <DialogDescription>
+ {relatedNodeToAdd
+ ? 'Choose what type of relation to add to this node.'
+ : currentParent
+ ? `Select a type of ${currentParent.label.toLowerCase()} to add`
+ : 'Choose an item to insert to the graph.'}
+ </DialogDescription>
+
+ <div className="overflow-y-auto overflow-x-hidden pr-1 -mr-1 flex-grow @container">
+ {isLoading ? (
+ <div className="grid grid-cols-3 cq-sm:grid-cols-4 cq-md:grid-cols-5 cq-lg:grid-cols-6 cq-xl:grid-cols-6 gap-3 p-1 pb-2">
+ {Array.from({ length: 6 }).map((_, index) => (
+ <Card key={index} className="h-full">
+ <CardContent className="p-2 relative flex flex-col items-center text-center h-full">
+ <div className="w-8 h-8 rounded-full bg-muted animate-pulse mb-3 mt-2"></div>
+ <div className="h-4 bg-muted rounded animate-pulse w-20 mb-2"></div>
+ <div className="h-3 bg-muted rounded animate-pulse w-32"></div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ ) : (
+ renderActionCards()
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog open={openFormDialog} onOpenChange={setOpenFormDialog}>
+ <DialogContent className="max-h-[95vh] flex flex-col">
+ <DialogTitle>
+ {currentNodeType && <>Add {currentNodeType.label.toLowerCase()}</>}
+ </DialogTitle>
+ <DialogDescription>{currentNodeType?.description}</DialogDescription>
+ {currentNodeType && (
+ <div className="grow overflow-y-auto">
+ <DynamicForm
+ currentNodeType={currentNodeType}
+ isForm={true}
+ onSubmit={handleAddNode}
+ />
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+ </>
+ )
}
interface ActionCardProps {
- item: ActionItem
- onSelect: () => void
+ item: ActionItem
+ onSelect: () => void
}
function ActionCard({ item, onSelect }: ActionCardProps) {
- const IconComponent = useIcon(item.icon)
+ const IconComponent = useIcon(item.icon)
- return (
- <Card
- className={cn(
- "cursor-pointer transition-all hover:border-primary border border-transparent hover:shadow-md bg-muted",
- item.disabled && "opacity-50 cursor-not-allowed",
- "h-full",
- )}
- onClick={item.disabled ? undefined : onSelect}
- >
- <CardContent className="p-2 relative flex flex-col items-center text-center h-full">
- <div
- className="w-8 h-8 rounded-full flex items-center justify-center mb-3 mt-2"
- >
- <IconComponent style={{ color: item.color }} className={cn("h-12 w-12", item.color ? "" : "text-primary")} />
- </div>
- <div className="font-medium text-sm">{item.label}</div>
- {!item.children && <div className="text-sm mt-2 opacity-60">{item.description}</div>}
- {!item.children && <Badge variant="outline" className="mt-2">{item.fields.length} fields</Badge>}
- {item.disabled && (
- <Badge variant="outline" className="mt-2 absolute top-2 left-2">
- Soon
- </Badge>
- )}
- {item.children && (
- <div className="absolute top-3 right-4 text-xs text-muted-foreground mt-1">
- <ArrowRight className="h-4 w-4" />
- </div>
- )}
- {item.children && <div className="text-xs text-muted-foreground mt-1">{item.children.length} options</div>}
- </CardContent>
- </Card>
- )
+ return (
+ <Card
+ className={cn(
+ 'cursor-pointer transition-all hover:border-primary border border-transparent hover:shadow-md bg-muted',
+ item.disabled && 'opacity-50 cursor-not-allowed',
+ 'h-full'
+ )}
+ onClick={item.disabled ? undefined : onSelect}
+ >
+ <CardContent className="p-2 relative flex flex-col items-center text-center h-full">
+ <div className="w-8 h-8 rounded-full flex items-center justify-center mb-3 mt-2">
+ <IconComponent
+ style={{ color: item.color }}
+ className={cn('h-12 w-12', item.color ? '' : 'text-primary')}
+ />
+ </div>
+ <div className="font-medium text-sm">{item.label}</div>
+ {!item.children && <div className="text-sm mt-2 opacity-60">{item.description}</div>}
+ {!item.children && (
+ <Badge variant="outline" className="mt-2">
+ {item.fields.length} fields
+ </Badge>
+ )}
+ {item.disabled && (
+ <Badge variant="outline" className="mt-2 absolute top-2 left-2">
+ Soon
+ </Badge>
+ )}
+ {item.children && (
+ <div className="absolute top-3 right-4 text-xs text-muted-foreground mt-1">
+ <ArrowRight className="h-4 w-4" />
+ </div>
+ )}
+ {item.children && (
+ <div className="text-xs text-muted-foreground mt-1">{item.children.length} options</div>
+ )}
+ </CardContent>
+ </Card>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/graphs/context-menu.tsx b/flowsint-app/src/renderer/src/components/graphs/context-menu.tsx
index ffb3e9d7..ef83bc7e 100644
--- a/flowsint-app/src/renderer/src/components/graphs/context-menu.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/context-menu.tsx
@@ -1,298 +1,296 @@
-import React, { useState } from 'react';
-import { transformService } from '@/api/transform-service';
-import { flowService } from '@/api/flow-service';
-import { useQuery } from '@tanstack/react-query';
-import { Skeleton } from '@/components/ui/skeleton';
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { FileCode2, Search, Info, Zap } from 'lucide-react';
-import { Transform, Flow, GraphNode } from '@/types';
-import { useLaunchFlow } from '@/hooks/use-launch-flow';
-import { useLaunchTransform } from '@/hooks/use-launch-transform';
-import { useParams } from '@tanstack/react-router';
-import { capitalizeFirstLetter } from '@/lib/utils';
-import NodeActions from '@/components/graphs/node-actions';
-import BaseContextMenu from '@/components/xyflow/context-menu';
+import React, { useState } from 'react'
+import { transformService } from '@/api/transform-service'
+import { flowService } from '@/api/flow-service'
+import { useQuery } from '@tanstack/react-query'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import { FileCode2, Search, Info, Zap } from 'lucide-react'
+import { Transform, Flow, GraphNode } from '@/types'
+import { useLaunchFlow } from '@/hooks/use-launch-flow'
+import { useLaunchTransform } from '@/hooks/use-launch-transform'
+import { useParams } from '@tanstack/react-router'
+import { capitalizeFirstLetter } from '@/lib/utils'
+import NodeActions from '@/components/graphs/node-actions'
+import BaseContextMenu from '@/components/xyflow/context-menu'
interface GraphContextMenuProps {
- node: GraphNode;
- top?: number;
- left?: number;
- right?: number;
- bottom?: number;
- rawTop?: number;
- rawLeft?: number;
- wrapperWidth: number;
- wrapperHeight: number;
- onEdit?: () => void;
- onDelete?: () => void;
- setMenu: (menu: any | null) => void;
- [key: string]: any;
+ node: GraphNode
+ top?: number
+ left?: number
+ right?: number
+ bottom?: number
+ rawTop?: number
+ rawLeft?: number
+ wrapperWidth: number
+ wrapperHeight: number
+ onEdit?: () => void
+ onDelete?: () => void
+ setMenu: (menu: any | null) => void
+ [key: string]: any
}
export default function ContextMenu({
- node,
- top,
- left,
- right,
- bottom,
- wrapperWidth,
- wrapperHeight,
- onEdit,
- onDelete,
- setMenu,
- ...props
+ node,
+ top,
+ left,
+ right,
+ bottom,
+ wrapperWidth,
+ wrapperHeight,
+ onEdit,
+ onDelete,
+ setMenu,
+ ...props
}: GraphContextMenuProps) {
- const { id: sketchId } = useParams({ strict: false })
- const [activeTab, setActiveTab] = useState('transforms');
- const [transformsSearchQuery, setTransformsSearchQuery] = useState('');
- const [flowsSearchQuery, setFlowsSearchQuery] = useState('');
- const { launchFlow } = useLaunchFlow(false);
- const { launchTransform } = useLaunchTransform(false);
+ const { id: sketchId } = useParams({ strict: false })
+ const [activeTab, setActiveTab] = useState('transforms')
+ const [transformsSearchQuery, setTransformsSearchQuery] = useState('')
+ const [flowsSearchQuery, setFlowsSearchQuery] = useState('')
+ const { launchFlow } = useLaunchFlow(false)
+ const { launchTransform } = useLaunchTransform(false)
- const { data: transforms, isLoading: isLoadingTransforms } = useQuery({
- queryKey: ["transforms", node.data.type],
- queryFn: () => transformService.get(capitalizeFirstLetter(node.data.type)),
- });
+ const { data: transforms, isLoading: isLoadingTransforms } = useQuery({
+ queryKey: ['transforms', node.data.type],
+ queryFn: () => transformService.get(capitalizeFirstLetter(node.data.type))
+ })
- const { data: flows, isLoading: isLoadingFlows } = useQuery({
- queryKey: ["flows", node.data.type],
- queryFn: () => flowService.get(capitalizeFirstLetter(node.data.type)),
- });
+ const { data: flows, isLoading: isLoadingFlows } = useQuery({
+ queryKey: ['flows', node.data.type],
+ queryFn: () => flowService.get(capitalizeFirstLetter(node.data.type))
+ })
- const filteredTransforms = transforms?.filter((transform: Transform) => {
- if (!transformsSearchQuery.trim()) return true;
- const query = transformsSearchQuery.toLowerCase().trim();
- const matchesName = transform.name?.toLowerCase().includes(query);
- const matchesDescription = transform.description?.toLowerCase().includes(query);
- return matchesName || matchesDescription;
- }) || [];
+ const filteredTransforms =
+ transforms?.filter((transform: Transform) => {
+ if (!transformsSearchQuery.trim()) return true
+ const query = transformsSearchQuery.toLowerCase().trim()
+ const matchesName = transform.name?.toLowerCase().includes(query)
+ const matchesDescription = transform.description?.toLowerCase().includes(query)
+ return matchesName || matchesDescription
+ }) || []
- const filteredFlows = flows?.filter((flow: Flow) => {
- if (!flowsSearchQuery.trim()) return true;
- const query = flowsSearchQuery.toLowerCase().trim();
- const matchesName = flow.name?.toLowerCase().includes(query);
- const matchesDescription = flow.description?.toLowerCase().includes(query);
- return matchesName || matchesDescription;
- }) || [];
+ const filteredFlows =
+ flows?.filter((flow: Flow) => {
+ if (!flowsSearchQuery.trim()) return true
+ const query = flowsSearchQuery.toLowerCase().trim()
+ const matchesName = flow.name?.toLowerCase().includes(query)
+ const matchesDescription = flow.description?.toLowerCase().includes(query)
+ return matchesName || matchesDescription
+ }) || []
- const handleFlowClick = (e: React.MouseEvent, flowId: string) => {
- e.stopPropagation();
- launchFlow([node.data.label], flowId, sketchId)
- setMenu(null)
- };
+ const handleFlowClick = (e: React.MouseEvent, flowId: string) => {
+ e.stopPropagation()
+ launchFlow([node.data.label], flowId, sketchId)
+ setMenu(null)
+ }
- const handleTransformClick = (e: React.MouseEvent, transformName: string) => {
- e.stopPropagation();
- launchTransform([node.data.label], transformName, sketchId)
- setMenu(null)
- };
+ const handleTransformClick = (e: React.MouseEvent, transformName: string) => {
+ e.stopPropagation()
+ launchTransform([node.data.label], transformName, sketchId)
+ setMenu(null)
+ }
- return (
- <BaseContextMenu
- top={top}
- left={left}
- right={right}
- bottom={bottom}
- wrapperWidth={wrapperWidth}
- wrapperHeight={wrapperHeight}
- {...props}
- >
- {/* Header with title and action buttons */}
- <div className="px-3 py-2 border-b gap-1 border-border flex items-center justify-between flex-shrink-0">
- <div className='flex text-xs items-center gap-1 truncate'>
- <span className='block truncate'>{node.data.label}</span> - <span className='block'>{node.data.type}</span>
- </div>
- <NodeActions node={node} setMenu={setMenu} />
- </div>
+ return (
+ <BaseContextMenu
+ top={top}
+ left={left}
+ right={right}
+ bottom={bottom}
+ wrapperWidth={wrapperWidth}
+ wrapperHeight={wrapperHeight}
+ {...props}
+ >
+ {/* Header with title and action buttons */}
+ <div className="px-3 py-2 border-b gap-1 border-border flex items-center justify-between flex-shrink-0">
+ <div className="flex text-xs items-center gap-1 truncate">
+ <span className="block truncate">{node.data.label}</span> -{' '}
+ <span className="block">{node.data.type}</span>
+ </div>
+ <NodeActions node={node} setMenu={setMenu} />
+ </div>
+
+ {/* Tabs */}
+ <div className="px-3 py-2 border-b border-border flex-shrink-0">
+ <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
+ <TabsList className="w-full">
+ <TabsTrigger value="transforms" className="flex-1" onClick={(e) => e.stopPropagation()}>
+ <Zap className="h-3 w-3 mr-1" />
+ Transforms
+ </TabsTrigger>
+ <TabsTrigger value="flows" className="flex-1" onClick={(e) => e.stopPropagation()}>
+ <FileCode2 className="h-3 w-3 mr-1" />
+ Flows
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
- {/* Tabs */}
- <div className="px-3 py-2 border-b border-border flex-shrink-0">
- <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
- <TabsList className="w-full">
- <TabsTrigger
- value="transforms"
- className="flex-1"
- onClick={(e) => e.stopPropagation()}
- >
- <Zap className="h-3 w-3 mr-1" />
- Transforms
- </TabsTrigger>
- <TabsTrigger
- value="flows"
- className="flex-1"
- onClick={(e) => e.stopPropagation()}
- >
- <FileCode2 className="h-3 w-3 mr-1" />
- Flows
- </TabsTrigger>
- </TabsList>
- </Tabs>
+ {/* Tab Content */}
+ <Tabs value={activeTab} className="flex-1 flex flex-col min-h-0">
+ {/* Transforms Tab */}
+ <TabsContent value="transforms" className="flex-1 flex flex-col min-h-0 mt-0">
+ {/* Transforms Search */}
+ <div className="px-3 py-2 border-b border-border flex-shrink-0">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
+ <Input
+ type="search"
+ placeholder="Search transforms..."
+ value={transformsSearchQuery}
+ onChange={(e) => {
+ e.stopPropagation()
+ setTransformsSearchQuery(e.target.value)
+ }}
+ onClick={(e) => e.stopPropagation()}
+ className="h-7 pl-7 text-xs"
+ />
</div>
+ </div>
- {/* Tab Content */}
- <Tabs value={activeTab} className="flex-1 flex flex-col min-h-0">
- {/* Transforms Tab */}
- <TabsContent value="transforms" className="flex-1 flex flex-col min-h-0 mt-0">
- {/* Transforms Search */}
- <div className="px-3 py-2 border-b border-border flex-shrink-0">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
- <Input
- type="search"
- placeholder="Search transforms..."
- value={transformsSearchQuery}
- onChange={(e) => {
- e.stopPropagation();
- setTransformsSearchQuery(e.target.value);
- }}
- onClick={(e) => e.stopPropagation()}
- className="h-7 pl-7 text-xs"
- />
- </div>
+ {/* Transforms List */}
+ <div className="flex-1 grow overflow-auto min-h-0">
+ {isLoadingTransforms ? (
+ <div className="p-2 space-y-2">
+ {[...Array(3)].map((_, i) => (
+ <div key={i} className="flex items-center gap-2 p-2 rounded-md">
+ <Skeleton className="h-4 w-4" />
+ <div className="flex-1 space-y-1">
+ <Skeleton className="h-3 w-3/4" />
+ <Skeleton className="h-2 w-1/2" />
</div>
-
- {/* Transforms List */}
- <div className="flex-1 grow overflow-auto min-h-0">
- {isLoadingTransforms ? (
- <div className="p-2 space-y-2">
- {[...Array(3)].map((_, i) => (
- <div key={i} className="flex items-center gap-2 p-2 rounded-md">
- <Skeleton className="h-4 w-4" />
- <div className="flex-1 space-y-1">
- <Skeleton className="h-3 w-3/4" />
- <Skeleton className="h-2 w-1/2" />
- </div>
- </div>
- ))}
- </div>
- ) : filteredTransforms.length > 0 ? (
- <div className="p-1">
- {filteredTransforms.map((transform: Transform) => (
- <button
- key={transform.id}
- className="w-full flex items-center gap-2 p-2 rounded-md hover:bg-muted text-left transition-colors"
- onClick={(e) => handleTransformClick(e, transform.name)}
- >
- <Zap className="h-4 w-4 text-muted-foreground flex-shrink-0" />
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {transform.name || "(Unnamed transform)"}
- </p>
- {transform.description && (
- <p className="text-xs text-muted-foreground truncate">
- {transform.description}
- </p>
- )}
- </div>
- <div className='flex items-center gap-1'>
- {/* <FavoriteButton isFavorite={false} /> */}
- <InfoButton description={transform.description ?? ""} />
- </div>
- </button>
- ))}
- </div>
- ) : (
- <div className="p-4 text-center">
- <p className="text-sm text-muted-foreground">
- {transformsSearchQuery ? 'No transforms found' : 'No transforms available'}
- </p>
- </div>
- )}
+ </div>
+ ))}
+ </div>
+ ) : filteredTransforms.length > 0 ? (
+ <div className="p-1">
+ {filteredTransforms.map((transform: Transform) => (
+ <button
+ key={transform.id}
+ className="w-full flex items-center gap-2 p-2 rounded-md hover:bg-muted text-left transition-colors"
+ onClick={(e) => handleTransformClick(e, transform.name)}
+ >
+ <Zap className="h-4 w-4 text-muted-foreground flex-shrink-0" />
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {transform.name || '(Unnamed transform)'}
+ </p>
+ {transform.description && (
+ <p className="text-xs text-muted-foreground truncate">
+ {transform.description}
+ </p>
+ )}
</div>
- </TabsContent>
-
- {/* Flows Tab */}
- <TabsContent value="flows" className="flex-1 flex flex-col min-h-0 mt-0">
- {/* Flows Search */}
- <div className="px-3 py-2 border-b border-border flex-shrink-0">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
- <Input
- type="search"
- placeholder="Search flows..."
- value={flowsSearchQuery}
- onChange={(e) => {
- e.stopPropagation();
- setFlowsSearchQuery(e.target.value);
- }}
- onClick={(e) => e.stopPropagation()}
- className="h-7 pl-7 text-xs"
- />
- </div>
+ <div className="flex items-center gap-1">
+ {/* <FavoriteButton isFavorite={false} /> */}
+ <InfoButton description={transform.description ?? ''} />
</div>
+ </button>
+ ))}
+ </div>
+ ) : (
+ <div className="p-4 text-center">
+ <p className="text-sm text-muted-foreground">
+ {transformsSearchQuery ? 'No transforms found' : 'No transforms available'}
+ </p>
+ </div>
+ )}
+ </div>
+ </TabsContent>
- {/* Flows List */}
- <div className="flex-1 grow overflow-auto min-h-0">
- {isLoadingFlows ? (
- <div className="p-2 space-y-2">
- {[...Array(3)].map((_, i) => (
- <div key={i} className="flex items-center gap-2 p-2 rounded-md">
- <Skeleton className="h-4 w-4" />
- <div className="flex-1 space-y-1">
- <Skeleton className="h-3 w-3/4" />
- <Skeleton className="h-2 w-1/2" />
- </div>
- </div>
- ))}
- </div>
- ) : filteredFlows.length > 0 ? (
- <div className="p-1">
- {filteredFlows.map((flow: Flow) => (
- <button
- key={flow.id}
- className="w-full flex items-center gap-2 p-2 rounded-md hover:bg-muted text-left transition-colors"
- onClick={(e) => handleFlowClick(e, flow.id)}
- >
- <FileCode2 className="h-4 w-4 text-muted-foreground flex-shrink-0" />
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {flow.name || "(Unnamed flow)"}
- </p>
- {flow.description && (
- <p className="text-xs text-muted-foreground truncate">
- {flow.description}
- </p>
- )}
- </div>
- <div className='flex items-center gap-1'>
- {/* <FavoriteButton isFavorite={false} /> */}
- <InfoButton description={flow.description} />
- </div>
- </button>
- ))}
- </div>
- ) : (
- <div className="p-4 text-center">
- <p className="text-sm text-muted-foreground">
- {flowsSearchQuery ? 'No flows found' : 'No flows available'}
- </p>
- </div>
- )}
+ {/* Flows Tab */}
+ <TabsContent value="flows" className="flex-1 flex flex-col min-h-0 mt-0">
+ {/* Flows Search */}
+ <div className="px-3 py-2 border-b border-border flex-shrink-0">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
+ <Input
+ type="search"
+ placeholder="Search flows..."
+ value={flowsSearchQuery}
+ onChange={(e) => {
+ e.stopPropagation()
+ setFlowsSearchQuery(e.target.value)
+ }}
+ onClick={(e) => e.stopPropagation()}
+ className="h-7 pl-7 text-xs"
+ />
+ </div>
+ </div>
+
+ {/* Flows List */}
+ <div className="flex-1 grow overflow-auto min-h-0">
+ {isLoadingFlows ? (
+ <div className="p-2 space-y-2">
+ {[...Array(3)].map((_, i) => (
+ <div key={i} className="flex items-center gap-2 p-2 rounded-md">
+ <Skeleton className="h-4 w-4" />
+ <div className="flex-1 space-y-1">
+ <Skeleton className="h-3 w-3/4" />
+ <Skeleton className="h-2 w-1/2" />
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : filteredFlows.length > 0 ? (
+ <div className="p-1">
+ {filteredFlows.map((flow: Flow) => (
+ <button
+ key={flow.id}
+ className="w-full flex items-center gap-2 p-2 rounded-md hover:bg-muted text-left transition-colors"
+ onClick={(e) => handleFlowClick(e, flow.id)}
+ >
+ <FileCode2 className="h-4 w-4 text-muted-foreground flex-shrink-0" />
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {flow.name || '(Unnamed flow)'}
+ </p>
+ {flow.description && (
+ <p className="text-xs text-muted-foreground truncate">{flow.description}</p>
+ )}
</div>
- </TabsContent>
- </Tabs>
- </BaseContextMenu>
- );
+ <div className="flex items-center gap-1">
+ {/* <FavoriteButton isFavorite={false} /> */}
+ <InfoButton description={flow.description} />
+ </div>
+ </button>
+ ))}
+ </div>
+ ) : (
+ <div className="p-4 text-center">
+ <p className="text-sm text-muted-foreground">
+ {flowsSearchQuery ? 'No flows found' : 'No flows available'}
+ </p>
+ </div>
+ )}
+ </div>
+ </TabsContent>
+ </Tabs>
+ </BaseContextMenu>
+ )
}
const InfoButton = ({ description }: { description?: string }) => {
- if (!description) return null;
+ if (!description) return null
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button onClick={(e) => e.stopPropagation()} className='w-5 h-5' variant='ghost' size={"icon"}>
- <Info className='w-4 h-4 opacity-50' strokeWidth={1.5} />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p className="whitespace-pre-wrap">{description}</p>
- </TooltipContent>
- </Tooltip >
- );
-};
\ No newline at end of file
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ onClick={(e) => e.stopPropagation()}
+ className="w-5 h-5"
+ variant="ghost"
+ size={'icon'}
+ >
+ <Info className="w-4 h-4 opacity-50" strokeWidth={1.5} />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p className="whitespace-pre-wrap">{description}</p>
+ </TooltipContent>
+ </Tooltip>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/graphs/create-relation.tsx b/flowsint-app/src/renderer/src/components/graphs/create-relation.tsx
index fb9601dc..3043fe98 100644
--- a/flowsint-app/src/renderer/src/components/graphs/create-relation.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/create-relation.tsx
@@ -1,204 +1,231 @@
-import { useState } from "react"
-import { useGraphStore } from "@/stores/graph-store"
-import { Button } from "@/components/ui/button"
-import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
-import { Input } from "@/components/ui/input"
-import { ArrowRight, ArrowLeftRight, GitPullRequestArrow } from "lucide-react"
-import { Label } from "@/components/ui/label"
-import { toast } from "sonner"
-import { sketchService } from "@/api/sketch-service"
-import { useParams } from "@tanstack/react-router"
-import { useIcon } from "@/hooks/use-icon"
-import { RadioGroupItem } from "@/components/ui/radio-group"
+import { useState } from 'react'
+import { useGraphStore } from '@/stores/graph-store'
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { ArrowRight, ArrowLeftRight, GitPullRequestArrow } from 'lucide-react'
+import { Label } from '@/components/ui/label'
+import { toast } from 'sonner'
+import { sketchService } from '@/api/sketch-service'
+import { useParams } from '@tanstack/react-router'
+import { useIcon } from '@/hooks/use-icon'
+import { RadioGroupItem } from '@/components/ui/radio-group'
export function CreateRelationDialog() {
-
- const { id: sketchId } = useParams({ strict: false })
- const selectedNodes = useGraphStore((state) => state.selectedNodes || [])
- const addEdge = useGraphStore((state) => state.addEdge)
- const openAddRelationDialog = useGraphStore((state) => state.openAddRelationDialog)
- const setOpenAddRelationDialog = useGraphStore((state) => state.setOpenAddRelationDialog)
- const [relationType, setRelationType] = useState("IS_RELATED_TO")
- const [isReversed, setIsReversed] = useState(false)
-
- const handleSubmit = async (e: { preventDefault: () => void }) => {
- e.preventDefault()
-
- // Determine source/target based on switch state. If multiple nodes are selected,
- // relate all left-side nodes to the single right-side node.
- const sourceIndex = isReversed ? selectedNodes.length - 1 : 0
- const targetIndex = isReversed ? 0 : selectedNodes.length - 1
-
- const newEdge = {
- source: selectedNodes[sourceIndex],
- target: selectedNodes[targetIndex],
- label: relationType,
- sketch_id: sketchId
- }
- const newEdgeObject = { label: relationType, type: "one-way", source: newEdge.source.id, target: newEdge.target.id } as any
-
- toast.promise(
- (async () => {
- if (addEdge) addEdge(newEdgeObject)
- setOpenAddRelationDialog(false)
- return sketchService.addEdge(sketchId as string, JSON.stringify(newEdgeObject))
- })(),
- {
- loading: 'Creating relation...',
- success: 'Relation successfully added.',
- error: 'Unexpected error during relation creation.'
- }
- )
+ const { id: sketchId } = useParams({ strict: false })
+ const selectedNodes = useGraphStore((state) => state.selectedNodes || [])
+ const addEdge = useGraphStore((state) => state.addEdge)
+ const openAddRelationDialog = useGraphStore((state) => state.openAddRelationDialog)
+ const setOpenAddRelationDialog = useGraphStore((state) => state.setOpenAddRelationDialog)
+ const [relationType, setRelationType] = useState('IS_RELATED_TO')
+ const [isReversed, setIsReversed] = useState(false)
+
+ const handleSubmit = async (e: { preventDefault: () => void }) => {
+ e.preventDefault()
+
+ // Determine source/target based on switch state. If multiple nodes are selected,
+ // relate all left-side nodes to the single right-side node.
+ const sourceIndex = isReversed ? selectedNodes.length - 1 : 0
+ const targetIndex = isReversed ? 0 : selectedNodes.length - 1
+
+ const newEdge = {
+ source: selectedNodes[sourceIndex],
+ target: selectedNodes[targetIndex],
+ label: relationType,
+ sketch_id: sketchId
}
-
- return (
- <Dialog open={openAddRelationDialog} onOpenChange={setOpenAddRelationDialog}>
- <DialogContent className="!w-full !max-w-[600px]">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <GitPullRequestArrow className="h-4 w-4" />
- New relationship
- </DialogTitle>
- </DialogHeader>
- <form onSubmit={handleSubmit} className="space-y-4">
- {/* Selected Nodes Display */}
- <div className="space-y-2">
- <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
- Selected Nodes ({selectedNodes.length})
- </Label>
- <div className="flex flex-wrap w-full gap-2">
- {selectedNodes.map((node) => (
- <NodeDisplayCard key={node.id} node={node} />
- ))}
- </div>
- </div>
-
- {/* Relationship Type */}
- <div className="space-y-2">
- <Label htmlFor="relation-type" className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
- Relationship Type
- </Label>
- <Input
- id="relation-type"
- placeholder="e.g., IS_RELATED_TO, WORKS_FOR, OWNS"
- value={relationType}
- onChange={(e) => setRelationType(e.target.value)}
- className="w-full h-9 text-sm"
- required
- />
- </div>
-
- {/* Visual Preview (one-way with switch) */}
- <div className="space-y-2">
- <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Preview</Label>
- {/* Switch control outside of the preview box */}
- <div className="flex justify-end">
- <Button
- type="button"
- variant="secondary"
- size="sm"
- className="shadow-sm"
- onClick={() => setIsReversed((v) => !v)}
- aria-label="Switch direction"
- title="Switch direction"
- >
- <ArrowLeftRight className="h-4 w-4 mr-1" />
- <span>Switch direction</span>
- </Button>
- </div>
- <div className="p-3 border rounded-md bg-muted/20">
- <div className="flex items-center justify-between">
- {/* Left side nodes */}
- <div className="flex items-center gap-2">
- {(isReversed ? selectedNodes.slice(1) : selectedNodes.slice(0, -1)).map((node) => (
- <NodeDisplayCard key={node.id} node={node} variant="preview" />
- ))}
- </div>
- <div className="flex items-center truncate justify-center px-2 flex-shrink-0 min-w-0 grow">
- <div className="flex items-center gap-1 text-xs text-muted-foreground">
- <div className="h-px bg-muted-foreground/30 flex-1"></div>
- <span className="px-2 py-1 bg-muted/50 rounded-sm truncate">
- {relationType || "IS_RELATED"}
- </span>
- <ArrowRight className="h-3 w-3 text-muted-foreground/50" />
- </div>
- </div>
- {/* Right side node */}
- <div className="flex items-center gap-2">
- {(isReversed ? selectedNodes.slice(0, 1) : selectedNodes.slice(-1)).map((node) => (
- <NodeDisplayCard key={node.id} node={node} variant="preview" />
- ))}
- </div>
- </div>
- </div>
- </div>
-
- <DialogFooter>
- <Button type="button" variant="outline" size="sm" onClick={() => setOpenAddRelationDialog(false)}>
- Cancel
- </Button>
- <Button type="submit" size="sm" disabled={!relationType.trim()}>
- Create
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
+ const newEdgeObject = {
+ label: relationType,
+ type: 'one-way',
+ source: newEdge.source.id,
+ target: newEdge.target.id
+ } as any
+
+ toast.promise(
+ (async () => {
+ if (addEdge) addEdge(newEdgeObject)
+ setOpenAddRelationDialog(false)
+ return sketchService.addEdge(sketchId as string, JSON.stringify(newEdgeObject))
+ })(),
+ {
+ loading: 'Creating relation...',
+ success: 'Relation successfully added.',
+ error: 'Unexpected error during relation creation.'
+ }
)
+ }
+
+ return (
+ <Dialog open={openAddRelationDialog} onOpenChange={setOpenAddRelationDialog}>
+ <DialogContent className="!w-full !max-w-[600px]">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <GitPullRequestArrow className="h-4 w-4" />
+ New relationship
+ </DialogTitle>
+ </DialogHeader>
+ <form onSubmit={handleSubmit} className="space-y-4">
+ {/* Selected Nodes Display */}
+ <div className="space-y-2">
+ <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
+ Selected Nodes ({selectedNodes.length})
+ </Label>
+ <div className="flex flex-wrap w-full gap-2">
+ {selectedNodes.map((node) => (
+ <NodeDisplayCard key={node.id} node={node} />
+ ))}
+ </div>
+ </div>
+
+ {/* Relationship Type */}
+ <div className="space-y-2">
+ <Label
+ htmlFor="relation-type"
+ className="text-xs font-medium text-muted-foreground uppercase tracking-wide"
+ >
+ Relationship Type
+ </Label>
+ <Input
+ id="relation-type"
+ placeholder="e.g., IS_RELATED_TO, WORKS_FOR, OWNS"
+ value={relationType}
+ onChange={(e) => setRelationType(e.target.value)}
+ className="w-full h-9 text-sm"
+ required
+ />
+ </div>
+
+ {/* Visual Preview (one-way with switch) */}
+ <div className="space-y-2">
+ <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
+ Preview
+ </Label>
+ {/* Switch control outside of the preview box */}
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ className="shadow-sm"
+ onClick={() => setIsReversed((v) => !v)}
+ aria-label="Switch direction"
+ title="Switch direction"
+ >
+ <ArrowLeftRight className="h-4 w-4 mr-1" />
+ <span>Switch direction</span>
+ </Button>
+ </div>
+ <div className="p-3 border rounded-md bg-muted/20">
+ <div className="flex items-center justify-between">
+ {/* Left side nodes */}
+ <div className="flex items-center gap-2">
+ {(isReversed ? selectedNodes.slice(1) : selectedNodes.slice(0, -1)).map(
+ (node) => (
+ <NodeDisplayCard key={node.id} node={node} variant="preview" />
+ )
+ )}
+ </div>
+ <div className="flex items-center truncate justify-center px-2 flex-shrink-0 min-w-0 grow">
+ <div className="flex items-center gap-1 text-xs text-muted-foreground">
+ <div className="h-px bg-muted-foreground/30 flex-1"></div>
+ <span className="px-2 py-1 bg-muted/50 rounded-sm truncate">
+ {relationType || 'IS_RELATED'}
+ </span>
+ <ArrowRight className="h-3 w-3 text-muted-foreground/50" />
+ </div>
+ </div>
+ {/* Right side node */}
+ <div className="flex items-center gap-2">
+ {(isReversed ? selectedNodes.slice(0, 1) : selectedNodes.slice(-1)).map(
+ (node) => (
+ <NodeDisplayCard key={node.id} node={node} variant="preview" />
+ )
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setOpenAddRelationDialog(false)}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={!relationType.trim()}>
+ Create
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
}
interface NodeDisplayCardProps {
- node: any
- variant?: "default" | "preview"
- asRadio?: boolean
- radioValue?: string
- id?: string
+ node: any
+ variant?: 'default' | 'preview'
+ asRadio?: boolean
+ radioValue?: string
+ id?: string
}
-export function NodeDisplayCard({ node, variant = "default", asRadio = false, radioValue, id }: NodeDisplayCardProps) {
- const NodeIcon = useIcon(node.data?.type, node.data?.src)
-
- const getNodeDisplayName = (node: any) => {
- return node.data?.label || node.data?.username || node.id
- }
+export function NodeDisplayCard({
+ node,
+ variant = 'default',
+ asRadio = false,
+ radioValue,
+ id
+}: NodeDisplayCardProps) {
+ const NodeIcon = useIcon(node.data?.type, node.data?.src)
- if (variant === "preview") {
- return (
- <div className="flex items-center gap-2">
- <div className="flex items-center justify-center w-6 h-6 rounded-full bg-muted">
- <NodeIcon size={20} />
- </div>
- <span className="text-xs text-muted-foreground truncate">
- {getNodeDisplayName(node)}
- </span>
- </div>
- )
- }
+ const getNodeDisplayName = (node: any) => {
+ return node.data?.label || node.data?.username || node.id
+ }
- if (asRadio) {
- return (
- <label htmlFor={id} className="flex items-center gap-2 px-3 py-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors cursor-pointer data-[state=checked]:border-primary data-[state=checked]:bg-primary/5">
- <RadioGroupItem id={id} value={radioValue || ""} className="mt-0.5" />
- <div className="flex items-center gap-2">
- <div className="flex items-center justify-center w-5 h-5 rounded-full bg-muted">
- <NodeIcon size={16} />
- </div>
- <span className="text-sm truncate">
- {getNodeDisplayName(node)}
- </span>
- </div>
- </label>
- )
- }
+ if (variant === 'preview') {
+ return (
+ <div className="flex items-center gap-2">
+ <div className="flex items-center justify-center w-6 h-6 rounded-full bg-muted">
+ <NodeIcon size={20} />
+ </div>
+ <span className="text-xs text-muted-foreground truncate">{getNodeDisplayName(node)}</span>
+ </div>
+ )
+ }
+ if (asRadio) {
return (
- <div className="flex items-center gap-2 px-3 py-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors">
- <div className="flex items-center justify-center w-5 h-5 rounded-full bg-muted">
- <NodeIcon size={16} />
- </div>
- <span className="text-sm truncate">
- {getNodeDisplayName(node)}
- </span>
+ <label
+ htmlFor={id}
+ className="flex items-center gap-2 px-3 py-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors cursor-pointer data-[state=checked]:border-primary data-[state=checked]:bg-primary/5"
+ >
+ <RadioGroupItem id={id} value={radioValue || ''} className="mt-0.5" />
+ <div className="flex items-center gap-2">
+ <div className="flex items-center justify-center w-5 h-5 rounded-full bg-muted">
+ <NodeIcon size={16} />
+ </div>
+ <span className="text-sm truncate">{getNodeDisplayName(node)}</span>
</div>
+ </label>
)
+ }
+
+ return (
+ <div className="flex items-center gap-2 px-3 py-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors">
+ <div className="flex items-center justify-center w-5 h-5 rounded-full bg-muted">
+ <NodeIcon size={16} />
+ </div>
+ <span className="text-sm truncate">{getNodeDisplayName(node)}</span>
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/graphs/details-panel/details-panel.tsx b/flowsint-app/src/renderer/src/components/graphs/details-panel/details-panel.tsx
index d0055d6f..8297c50b 100644
--- a/flowsint-app/src/renderer/src/components/graphs/details-panel/details-panel.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/details-panel/details-panel.tsx
@@ -1,147 +1,172 @@
-import { memo } from "react"
-import { cn } from "@/lib/utils"
-import { CopyButton } from "@/components/copy"
-import { Check, Rocket, X, MousePointer } from "lucide-react"
-import LaunchFlow from "../launch-transform"
-import NodeActions from "../node-actions"
-import { Button } from "../../ui/button"
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "../../ui/tooltip"
-import { useParams } from "@tanstack/react-router"
-import NeighborsGraph from "./neighbors"
-import Relationships from "./relationships"
-import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "../../ui/resizable"
-import { GraphNode } from "@/types"
-import { useGraphStore } from "@/stores/graph-store"
+import { memo } from 'react'
+import { cn } from '@/lib/utils'
+import { CopyButton } from '@/components/copy'
+import { Check, Rocket, X, MousePointer } from 'lucide-react'
+import LaunchFlow from '../launch-transform'
+import NodeActions from '../node-actions'
+import { Button } from '../../ui/button'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../../ui/tooltip'
+import { useParams } from '@tanstack/react-router'
+import NeighborsGraph from './neighbors'
+import Relationships from './relationships'
+import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '../../ui/resizable'
+import { GraphNode } from '@/types'
+import { useGraphStore } from '@/stores/graph-store'
const DetailsPanel = memo(({ node }: { node: GraphNode | null }) => {
- const { id: sketchId } = useParams({ strict: false })
- const nodes = useGraphStore((s) => s.nodes)
- node = nodes.find((n) => n.id === node?.id) || null
- if (!node) {
- return (
- <div className="flex p-12 rounded-xl border flex-col items-center justify-center h-full text-center p-8">
- <div className="w-16 h-16 bg-muted rounded-full flex items-center justify-center mb-4">
- <MousePointer className="h-8 w-8 text-muted-foreground" />
- </div>
- <h3 className="text-lg font-semibold text-foreground mb-2">
- No Node Selected
- </h3>
- <p className="text-sm text-muted-foreground max-w-xs">
- Click on any node in the graph to view its details and properties
- </p>
- </div>
- )
- }
-
+ const { id: sketchId } = useParams({ strict: false })
+ const nodes = useGraphStore((s) => s.nodes)
+ node = nodes.find((n) => n.id === node?.id) || null
+ if (!node) {
return (
- <div className="flex flex-col h-full overflow-hidden bg-card">
- {/* <ItemHero node={node} /> */}
- <div className="flex items-center bg-card sticky w-full top-0 border-b justify-start px-4 py-2 gap-2 z-1">
- <p className="text-md font-semibold truncate">{node.data?.label}</p>
- <div className="grow" />
- <div className="flex items-center">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <LaunchFlow values={[node.data.label]} type={node.data?.type}>
- <Button
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
- >
- <Rocket className="h-3 w-3" strokeWidth={2} />
- </Button>
- </LaunchFlow>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>Launch transform</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <NodeActions node={node} />
+ <div className="flex p-12 rounded-xl border flex-col items-center justify-center h-full text-center p-8">
+ <div className="w-16 h-16 bg-muted rounded-full flex items-center justify-center mb-4">
+ <MousePointer className="h-8 w-8 text-muted-foreground" />
+ </div>
+ <h3 className="text-lg font-semibold text-foreground mb-2">No Node Selected</h3>
+ <p className="text-sm text-muted-foreground max-w-xs">
+ Click on any node in the graph to view its details and properties
+ </p>
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col h-full overflow-hidden bg-card">
+ {/* <ItemHero node={node} /> */}
+ <div className="flex items-center bg-card sticky w-full top-0 border-b justify-start px-4 py-2 gap-2 z-1">
+ <p className="text-md font-semibold truncate">{node.data?.label}</p>
+ <div className="grow" />
+ <div className="flex items-center">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <LaunchFlow values={[node.data.label]} type={node.data?.type}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
+ >
+ <Rocket className="h-3 w-3" strokeWidth={2} />
+ </Button>
+ </LaunchFlow>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Launch transform</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <NodeActions node={node} />
+ </div>
+ </div>
+ <div className="flex-1 min-h-0">
+ <ResizablePanelGroup direction="vertical" className="h-full">
+ <ResizablePanel defaultSize={30} minSize={20}>
+ <div className="h-full overflow-auto">
+ {node.data?.description && (
+ <div className="px-4 py-3 border-b border-border">
+ <div
+ className="text-sm text-muted-foreground prose dark:prose-invert prose-sm max-w-none"
+ dangerouslySetInnerHTML={{ __html: node.data.description }}
+ />
</div>
+ )}
+ <MemoizedKeyValueDisplay data={node.data} />
</div>
- <div className="flex-1 min-h-0">
- <ResizablePanelGroup direction="vertical" className="h-full">
- <ResizablePanel defaultSize={30} minSize={20}>
- <div className="h-full overflow-auto">
- {node.data?.description && (
- <div className="px-4 py-3 border-b border-border">
- <div
- className="text-sm text-muted-foreground prose dark:prose-invert prose-sm max-w-none"
- dangerouslySetInnerHTML={{ __html: node.data.description }}
- />
- </div>
- )}
- <MemoizedKeyValueDisplay data={node.data} />
- </div>
- </ResizablePanel>
- <ResizableHandle />
- <ResizablePanel defaultSize={40} minSize={25}>
- <div className="h-full w-full p-3">
- <NeighborsGraph nodeLength={nodes.length} sketchId={sketchId as string} nodeId={node.id} />
- </div>
- </ResizablePanel>
- <ResizableHandle />
- <ResizablePanel defaultSize={30} minSize={20}>
- <Relationships nodeLength={nodes.length} sketchId={sketchId as string} nodeId={node.id} />
- </ResizablePanel>
- </ResizablePanelGroup>
+ </ResizablePanel>
+ <ResizableHandle />
+ <ResizablePanel defaultSize={40} minSize={25}>
+ <div className="h-full w-full p-3">
+ <NeighborsGraph
+ nodeLength={nodes.length}
+ sketchId={sketchId as string}
+ nodeId={node.id}
+ />
</div>
- </div>
- )
+ </ResizablePanel>
+ <ResizableHandle />
+ <ResizablePanel defaultSize={30} minSize={20}>
+ <Relationships
+ nodeLength={nodes.length}
+ sketchId={sketchId as string}
+ nodeId={node.id}
+ />
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ </div>
+ </div>
+ )
})
export default DetailsPanel
interface KeyValueDisplayProps {
- data: Record<string, any>
- className?: string
+ data: Record<string, any>
+ className?: string
}
function KeyValueDisplay({ data, className }: KeyValueDisplayProps) {
- return (
- <div className={cn("w-full border-collapse", className)}>
- {data && Object.entries(data)
- .filter(([key]) => !["sketch_id", "caption", "size", "color", "description"].includes(key))
- .map(([key, value], index) => {
- let val: string | null = null
- let display: React.ReactNode = null
+ return (
+ <div className={cn('w-full border-collapse', className)}>
+ {data &&
+ Object.entries(data)
+ .filter(
+ ([key]) => !['sketch_id', 'caption', 'size', 'color', 'description'].includes(key)
+ )
+ .map(([key, value], index) => {
+ let val: string | null = null
+ let display: React.ReactNode = null
- if (typeof value === "boolean") {
- val = value.toString()
- display = value ? (
- <Check className="h-4 w-4 text-green-600" />
- ) : (
- <X className="h-4 w-4 text-red-600" />
- )
- } else if (Array.isArray(value)) {
- val = `${value.length} items`
- display = val
- } else {
- val = value?.toString() || null
- display = (typeof val === "string" && val.startsWith("https://"))
- ? <a href={val} className="underline text-primary truncate" target="_blank" rel="noopener noreferrer">{val}</a>
- : val
- }
+ if (typeof value === 'boolean') {
+ val = value.toString()
+ display = value ? (
+ <Check className="h-4 w-4 text-green-600" />
+ ) : (
+ <X className="h-4 w-4 text-red-600" />
+ )
+ } else if (Array.isArray(value)) {
+ val = `${value.length} items`
+ display = val
+ } else {
+ val = value?.toString() || null
+ display =
+ typeof val === 'string' && val.startsWith('https://') ? (
+ <a
+ href={val}
+ className="underline text-primary truncate"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {val}
+ </a>
+ ) : (
+ val
+ )
+ }
- return (
- <div
- key={index}
- className="flex w-full bg-card items-center divide-x divide-border border-b border-border p-0"
- >
- <div className="w-1/2 px-4 p-2 text-sm text-muted-foreground font-normal truncate">{key}</div>
- <div className="w-1/2 px-4 p-2 text-sm font-medium flex items-center justify-between min-w-0">
- <div className="truncate font-semibold">{display || <span className="italic text-muted-foreground">N/A</span>}</div>
- {display && val && typeof value !== "boolean" && <CopyButton className="h-6 w-6 shrink-0" content={val} />}
- </div>
- </div>
- )
- })}
- </div>
- )
+ return (
+ <div
+ key={index}
+ className="flex w-full bg-card items-center divide-x divide-border border-b border-border p-0"
+ >
+ <div className="w-1/2 px-4 p-2 text-sm text-muted-foreground font-normal truncate">
+ {key}
+ </div>
+ <div className="w-1/2 px-4 p-2 text-sm font-medium flex items-center justify-between min-w-0">
+ <div className="truncate font-semibold">
+ {display || <span className="italic text-muted-foreground">N/A</span>}
+ </div>
+ {display && val && typeof value !== 'boolean' && (
+ <CopyButton className="h-6 w-6 shrink-0" content={val} />
+ )}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )
}
export const MemoizedKeyValueDisplay = memo(KeyValueDisplay)
diff --git a/flowsint-app/src/renderer/src/components/graphs/details-panel/neighbors.tsx b/flowsint-app/src/renderer/src/components/graphs/details-panel/neighbors.tsx
index bd3920df..fa3e3175 100644
--- a/flowsint-app/src/renderer/src/components/graphs/details-panel/neighbors.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/details-panel/neighbors.tsx
@@ -1,38 +1,48 @@
-import { sketchService } from "@/api/sketch-service";
-import { useQuery } from "@tanstack/react-query";
-import ForceGraphViewer from "../graph-viewer";
-import Loader from "@/components/loader";
-import { memo, useRef } from "react";
+import { sketchService } from '@/api/sketch-service'
+import { useQuery } from '@tanstack/react-query'
+import ForceGraphViewer from '../graph-viewer'
+import Loader from '@/components/loader'
+import { memo, useRef } from 'react'
-const NeighborsGraph = memo(({ sketchId, nodeId, nodeLength }: { sketchId: string, nodeId: string, nodeLength: number }) => {
+const NeighborsGraph = memo(
+ ({ sketchId, nodeId, nodeLength }: { sketchId: string; nodeId: string; nodeLength: number }) => {
const containerRef = useRef<HTMLDivElement>(null)
const { data: neighborsData, isLoading } = useQuery({
- queryKey: ['neighbors', sketchId, nodeId, nodeLength],
- queryFn: () => sketchService.getNodeNeighbors(sketchId, nodeId),
- });
+ queryKey: ['neighbors', sketchId, nodeId, nodeLength],
+ queryFn: () => sketchService.getNodeNeighbors(sketchId, nodeId)
+ })
return (
- <div ref={containerRef} className="overflow-hidden bg-background border relative h-full w-full">
- {isLoading ? <div className='flex items-center justify-center grow h-full'><Loader /></div> :
- <>
- <div className="top-0 left-0 bg-card/60 backdrop-blur z-10 p-1 rounded-br-lg absolute text-sm flex gap-1">
- <span className="font-semibold">{neighborsData.nds.length - 1}</span>
- <span className="opacity-70">neighbor(s)</span>
- </div>
- <ForceGraphViewer
- nodes={neighborsData.nds}
- edges={neighborsData.rls}
- onNodeClick={() => { }}
- onNodeRightClick={() => { }}
- onBackgroundClick={() => { }}
- showLabels={true}
- showIcons={true}
- backgroundColor="transparent"
- instanceId="neighbors"
- />
- </>}
- </div>
+ <div
+ ref={containerRef}
+ className="overflow-hidden bg-background border relative h-full w-full"
+ >
+ {isLoading ? (
+ <div className="flex items-center justify-center grow h-full">
+ <Loader />
+ </div>
+ ) : (
+ <>
+ <div className="top-0 left-0 bg-card/60 backdrop-blur z-10 p-1 rounded-br-lg absolute text-sm flex gap-1">
+ <span className="font-semibold">{neighborsData.nds.length - 1}</span>
+ <span className="opacity-70">neighbor(s)</span>
+ </div>
+ <ForceGraphViewer
+ nodes={neighborsData.nds}
+ edges={neighborsData.rls}
+ onNodeClick={() => {}}
+ onNodeRightClick={() => {}}
+ onBackgroundClick={() => {}}
+ showLabels={true}
+ showIcons={true}
+ backgroundColor="transparent"
+ instanceId="neighbors"
+ />
+ </>
+ )}
+ </div>
)
-})
+ }
+)
-export default NeighborsGraph
\ No newline at end of file
+export default NeighborsGraph
diff --git a/flowsint-app/src/renderer/src/components/graphs/details-panel/node-editor-modal.tsx b/flowsint-app/src/renderer/src/components/graphs/details-panel/node-editor-modal.tsx
index 996241e9..ee94da57 100644
--- a/flowsint-app/src/renderer/src/components/graphs/details-panel/node-editor-modal.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/details-panel/node-editor-modal.tsx
@@ -1,350 +1,357 @@
-import React, { useState, useEffect } from "react"
-import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from "@/components/ui/sheet"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Label } from "@/components/ui/label"
-import { Textarea } from "@/components/ui/textarea"
-import { Badge } from "@/components/ui/badge"
-import { Edit3, Save, X, Hash, Type, FileText, Check, Loader2 } from "lucide-react"
-import type { NodeData } from "@/types"
-import { useGraphStore } from "@/stores/graph-store"
-import { MapFromAddress } from "../../map/map"
-import { sketchService } from "@/api/sketch-service"
-import { useParams } from "@tanstack/react-router"
-import { toast } from "sonner"
-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
-import { useIcon } from "@/hooks/use-icon"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { queryKeys } from "@/api/query-keys"
+import React, { useState, useEffect } from 'react'
+import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Textarea } from '@/components/ui/textarea'
+import { Badge } from '@/components/ui/badge'
+import { Edit3, Save, X, Hash, Type, FileText, Check, Loader2 } from 'lucide-react'
+import type { NodeData } from '@/types'
+import { useGraphStore } from '@/stores/graph-store'
+import { MapFromAddress } from '../../map/map'
+import { sketchService } from '@/api/sketch-service'
+import { useParams } from '@tanstack/react-router'
+import { toast } from 'sonner'
+import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
+import { useIcon } from '@/hooks/use-icon'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { queryKeys } from '@/api/query-keys'
export const NodeEditorModal: React.FC = () => {
- const currentNode = useGraphStore(state => state.currentNode)
- const openNodeEditorModal = useGraphStore(state => state.openNodeEditorModal)
- const setOpenNodeEditorModal = useGraphStore(state => state.setOpenNodeEditorModal)
- const updateNode = useGraphStore(state => state.updateNode)
- const setCurrentNode = useGraphStore(state => state.setCurrentNode)
- const { id: sketchId } = useParams({ strict: false })
- const IconComponent = useIcon(currentNode?.data.type as string, currentNode?.data?.src as string | null);
+ const currentNode = useGraphStore((state) => state.currentNode)
+ const openNodeEditorModal = useGraphStore((state) => state.openNodeEditorModal)
+ const setOpenNodeEditorModal = useGraphStore((state) => state.setOpenNodeEditorModal)
+ const updateNode = useGraphStore((state) => state.updateNode)
+ const setCurrentNode = useGraphStore((state) => state.setCurrentNode)
+ const { id: sketchId } = useParams({ strict: false })
+ const IconComponent = useIcon(
+ currentNode?.data.type as string,
+ currentNode?.data?.src as string | null
+ )
- const [formData, setFormData] = useState<Partial<NodeData>>({
- label: "",
- caption: "",
- type: ""
- });
+ const [formData, setFormData] = useState<Partial<NodeData>>({
+ label: '',
+ caption: '',
+ type: ''
+ })
- const [isSaving, setIsSaving] = useState(false);
+ const [isSaving, setIsSaving] = useState(false)
- // Update form data when currentNode changes
- useEffect(() => {
- if (currentNode) {
- setFormData({
- ...currentNode.data,
- label: currentNode.data.label || "",
- caption: currentNode.data.caption || "",
- type: currentNode.data.type || ""
- });
- }
- }, [currentNode]);
-
- const queryClient = useQueryClient()
+ // Update form data when currentNode changes
+ useEffect(() => {
+ if (currentNode) {
+ setFormData({
+ ...currentNode.data,
+ label: currentNode.data.label || '',
+ caption: currentNode.data.caption || '',
+ type: currentNode.data.type || ''
+ })
+ }
+ }, [currentNode])
- // Update node mutation
- const updateNodeMutation = useMutation({
- mutationFn: async ({ sketchId, updateData }: { sketchId: string, updateData: any }) => {
- return sketchService.updateNode(sketchId, JSON.stringify(updateData))
- },
- onSuccess: (result, variables) => {
- if (result.status === "node updated" && currentNode) {
- // Update the local store
- updateNode(currentNode.id, formData)
- setCurrentNode({
- ...currentNode,
- data: {
- ...currentNode.data,
- ...formData
- }
- })
+ const queryClient = useQueryClient()
- // Invalidate related queries
- if (sketchId) {
- queryClient.invalidateQueries({
- queryKey: queryKeys.sketches.detail(sketchId)
- })
- queryClient.invalidateQueries({
- queryKey: queryKeys.sketches.graph(sketchId, sketchId)
- })
- // Also invalidate investigation queries that might show sketch data
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.list
- })
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.dashboard
- })
- }
+ // Update node mutation
+ const updateNodeMutation = useMutation({
+ mutationFn: async ({ sketchId, updateData }: { sketchId: string; updateData: any }) => {
+ return sketchService.updateNode(sketchId, JSON.stringify(updateData))
+ },
+ onSuccess: (result, variables) => {
+ if (result.status === 'node updated' && currentNode) {
+ // Update the local store
+ updateNode(currentNode.id, formData)
+ setCurrentNode({
+ ...currentNode,
+ data: {
+ ...currentNode.data,
+ ...formData
+ }
+ })
- toast.success("Node updated successfully")
- setOpenNodeEditorModal(false)
- } else {
- toast.error("Failed to update node")
- }
- },
- onError: (error) => {
- console.error("Error updating node:", error)
- toast.error("Failed to update node. Please try again.")
+ // Invalidate related queries
+ if (sketchId) {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.sketches.detail(sketchId)
+ })
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.sketches.graph(sketchId, sketchId)
+ })
+ // Also invalidate investigation queries that might show sketch data
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.list
+ })
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.dashboard
+ })
}
- });
- const handleSave = async () => {
- if (!currentNode || !sketchId) return
- setIsSaving(true)
+ toast.success('Node updated successfully')
+ setOpenNodeEditorModal(false)
+ } else {
+ toast.error('Failed to update node')
+ }
+ },
+ onError: (error) => {
+ console.error('Error updating node:', error)
+ toast.error('Failed to update node. Please try again.')
+ }
+ })
- try {
- // Prepare the data for the API
- const updateData = {
- nodeId: currentNode.id,
- data: formData
- };
+ const handleSave = async () => {
+ if (!currentNode || !sketchId) return
+ setIsSaving(true)
- // Call the mutation
- await updateNodeMutation.mutateAsync({ sketchId, updateData })
- } catch (error) {
- console.error("Error updating node:", error)
- } finally {
- setIsSaving(false)
- }
- };
+ try {
+ // Prepare the data for the API
+ const updateData = {
+ nodeId: currentNode.id,
+ data: formData
+ }
- const handleCancel = () => {
- setOpenNodeEditorModal(false);
- };
+ // Call the mutation
+ await updateNodeMutation.mutateAsync({ sketchId, updateData })
+ } catch (error) {
+ console.error('Error updating node:', error)
+ } finally {
+ setIsSaving(false)
+ }
+ }
- const handleInputChange = (field: keyof NodeData, value: string) => {
- setFormData(prev => ({
- ...prev,
- [field]: value
- }));
- };
+ const handleCancel = () => {
+ setOpenNodeEditorModal(false)
+ }
- const isLocation = currentNode?.data.type === "location" || (currentNode?.data.latitude && currentNode?.data.longitude)
+ const handleInputChange = (field: keyof NodeData, value: string) => {
+ setFormData((prev) => ({
+ ...prev,
+ [field]: value
+ }))
+ }
- if (!currentNode) return null;
+ const isLocation =
+ currentNode?.data.type === 'location' ||
+ (currentNode?.data.latitude && currentNode?.data.longitude)
- // Separate core fields from additional properties
- const coreFields = ["label", "caption", "type", "id"];
- const additionalFields = Object.entries(currentNode.data).filter(
- ([key]) => !coreFields.includes(key) && key !== 'ID'
- );
+ if (!currentNode) return null
- return (
- <Sheet open={openNodeEditorModal} onOpenChange={setOpenNodeEditorModal}>
- <SheetContent className="!w-full !max-w-2xl h-full !duration-100 p-0 flex flex-col h-full">
- <div className="flex flex-col h-full">
- {/* Header */}
- <SheetHeader className="px-6 py-4 border-b bg-muted/30 flex-shrink-0">
- <div className="flex items-center gap-3">
- <div className="p-2 rounded-lg bg-primary/10">
- <Edit3 className="h-5 w-5 text-primary" />
- </div>
- <div className="flex gap-3">
- <SheetTitle className="text-lg font-semibold">
- Edit Node Properties
- </SheetTitle>
- <p className="text-sm text-muted-foreground mt-1">
- {currentNode.data.label || currentNode.id}
- </p>
- <Badge variant="outline" className="text-xs">
- {currentNode.data.type || "Unknown Type"}
- </Badge>
- </div>
- </div>
- </SheetHeader>
+ // Separate core fields from additional properties
+ const coreFields = ['label', 'caption', 'type', 'id']
+ const additionalFields = Object.entries(currentNode.data).filter(
+ ([key]) => !coreFields.includes(key) && key !== 'ID'
+ )
- {/* Content */}
- <div className="flex-1 px-6 py-6 grow overflow-y-auto">
- <div className="space-y-6">
- {/* Preview Section */}
- <div className="p-4 rounded-lg bg-background border">
- <div className="flex items-center gap-4">
- <div className="relative flex-shrink-0">
- {currentNode.data.src ? (
- <Avatar className="rounded-lg h-16 w-16 border-2 border-muted">
- <AvatarImage className="rounded-lg object-cover" src={currentNode.data.src} />
- <AvatarFallback className="text-lg font-semibold rounded-lg">
- {formData.label?.[0]?.toUpperCase() || "?"}
- </AvatarFallback>
- </Avatar>
- ) : (
- <div className="h-16 w-16 rounded-lg border-2 border-muted bg-muted/30 flex items-center justify-center">
- <IconComponent className="h-8 w-8 text-muted-foreground" />
- </div>
- )}
- </div>
- <div className="flex-1 min-w-0">
- <h3 className="text-lg font-semibold text-foreground mb-1">
- {formData.label || "No label"}
- </h3>
- <p className="text-sm font-medium text-primary">
- {formData.type || "No type"}
- </p>
- </div>
- </div>
- </div>
+ return (
+ <Sheet open={openNodeEditorModal} onOpenChange={setOpenNodeEditorModal}>
+ <SheetContent className="!w-full !max-w-2xl h-full !duration-100 p-0 flex flex-col h-full">
+ <div className="flex flex-col h-full">
+ {/* Header */}
+ <SheetHeader className="px-6 py-4 border-b bg-muted/30 flex-shrink-0">
+ <div className="flex items-center gap-3">
+ <div className="p-2 rounded-lg bg-primary/10">
+ <Edit3 className="h-5 w-5 text-primary" />
+ </div>
+ <div className="flex gap-3">
+ <SheetTitle className="text-lg font-semibold">Edit Node Properties</SheetTitle>
+ <p className="text-sm text-muted-foreground mt-1">
+ {currentNode.data.label || currentNode.id}
+ </p>
+ <Badge variant="outline" className="text-xs">
+ {currentNode.data.type || 'Unknown Type'}
+ </Badge>
+ </div>
+ </div>
+ </SheetHeader>
- {/* Core Properties */}
- <div className="space-y-4">
- <h3 className="text-sm font-medium text-muted-foreground">Core Properties</h3>
- <div className="grid grid-cols-1 gap-4">
- <div className="space-y-2">
- <Label htmlFor="label" className="text-sm font-medium flex items-center gap-2">
- <FileText className="h-3 w-3" />
- Label
- </Label>
- <Input
- id="label"
- value={formData.label || ""}
- onChange={(e) => handleInputChange("label", e.target.value)}
- placeholder="Enter node label"
- className="h-9"
- />
- </div>
- <div className="space-y-2">
- <Label htmlFor="type" className="text-sm font-medium flex items-center gap-2">
- <Type className="h-3 w-3" />
- Type
- </Label>
- <Input
- id="type"
- value={formData.type || ""}
- onChange={(e) => handleInputChange("type", e.target.value)}
- placeholder="Enter node type"
- className="h-9"
- />
- </div>
- <div className="space-y-2">
- <Label htmlFor="caption" className="text-sm font-medium flex items-center gap-2">
- <FileText className="h-3 w-3" />
- Caption
- </Label>
- <Input
- id="caption"
- value={formData.caption || ""}
- onChange={(e) => handleInputChange("caption", e.target.value)}
- placeholder="Enter node caption"
- className="h-9"
- />
- </div>
- </div>
- </div>
+ {/* Content */}
+ <div className="flex-1 px-6 py-6 grow overflow-y-auto">
+ <div className="space-y-6">
+ {/* Preview Section */}
+ <div className="p-4 rounded-lg bg-background border">
+ <div className="flex items-center gap-4">
+ <div className="relative flex-shrink-0">
+ {currentNode.data.src ? (
+ <Avatar className="rounded-lg h-16 w-16 border-2 border-muted">
+ <AvatarImage
+ className="rounded-lg object-cover"
+ src={currentNode.data.src}
+ />
+ <AvatarFallback className="text-lg font-semibold rounded-lg">
+ {formData.label?.[0]?.toUpperCase() || '?'}
+ </AvatarFallback>
+ </Avatar>
+ ) : (
+ <div className="h-16 w-16 rounded-lg border-2 border-muted bg-muted/30 flex items-center justify-center">
+ <IconComponent className="h-8 w-8 text-muted-foreground" />
+ </div>
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <h3 className="text-lg font-semibold text-foreground mb-1">
+ {formData.label || 'No label'}
+ </h3>
+ <p className="text-sm font-medium text-primary">{formData.type || 'No type'}</p>
+ </div>
+ </div>
+ </div>
- {/* Additional Properties */}
- {additionalFields.length > 0 && (
- <div className="space-y-4">
- <h3 className="text-sm font-medium text-muted-foreground">Additional Properties</h3>
- <div className="space-y-4">
- {additionalFields.map(([key, value]) => (
- <div key={key} className="space-y-2">
- <Label
- htmlFor={key}
- className="text-sm font-medium capitalize"
- >
- {key.replace(/_/g, ' ')}
- </Label>
- {typeof value === "boolean" ? (
- <div className="flex items-center gap-2">
- <Button
- type="button"
- variant={formData[key as keyof NodeData] ? "default" : "outline"}
- size="sm"
- onClick={() => handleInputChange(key as keyof NodeData, (!formData[key as keyof NodeData]).toString())}
- className="gap-2"
- >
- {formData[key as keyof NodeData] ? (
- <>
- <Check className="h-3 w-3" />
- True
- </>
- ) : (
- "False"
- )}
- </Button>
- </div>
- ) : typeof value === "string" && value.length > 100 ? (
- <Textarea
- id={key}
- value={formData[key as keyof NodeData] as string || ""}
- onChange={(e) => handleInputChange(key as keyof NodeData, e.target.value)}
- placeholder={`Enter ${key.replace(/_/g, ' ').toLowerCase()}`}
- className="min-h-[80px] resize-none"
- rows={3}
- />
- ) : (
- <Input
- id={key}
- value={formData[key as keyof NodeData] as string || ""}
- onChange={(e) => handleInputChange(key as keyof NodeData, e.target.value)}
- placeholder={`Enter ${key.replace(/_/g, ' ').toLowerCase()}`}
- className="h-9"
- />
- )}
- </div>
- ))}
- </div>
- </div>
- )}
+ {/* Core Properties */}
+ <div className="space-y-4">
+ <h3 className="text-sm font-medium text-muted-foreground">Core Properties</h3>
+ <div className="grid grid-cols-1 gap-4">
+ <div className="space-y-2">
+ <Label htmlFor="label" className="text-sm font-medium flex items-center gap-2">
+ <FileText className="h-3 w-3" />
+ Label
+ </Label>
+ <Input
+ id="label"
+ value={formData.label || ''}
+ onChange={(e) => handleInputChange('label', e.target.value)}
+ placeholder="Enter node label"
+ className="h-9"
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="type" className="text-sm font-medium flex items-center gap-2">
+ <Type className="h-3 w-3" />
+ Type
+ </Label>
+ <Input
+ id="type"
+ value={formData.type || ''}
+ onChange={(e) => handleInputChange('type', e.target.value)}
+ placeholder="Enter node type"
+ className="h-9"
+ />
+ </div>
+ <div className="space-y-2">
+ <Label
+ htmlFor="caption"
+ className="text-sm font-medium flex items-center gap-2"
+ >
+ <FileText className="h-3 w-3" />
+ Caption
+ </Label>
+ <Input
+ id="caption"
+ value={formData.caption || ''}
+ onChange={(e) => handleInputChange('caption', e.target.value)}
+ placeholder="Enter node caption"
+ className="h-9"
+ />
+ </div>
+ </div>
+ </div>
- {/* Location Map */}
- {isLocation && (
- <div className="space-y-4">
- <h3 className="text-sm font-medium text-muted-foreground">Location</h3>
- <div className="overflow-hidden rounded-lg bg-background border">
- <MapFromAddress
- locations={[
- {
- lat: formData.latitude,
- lon: formData.longitude,
- address: formData.label as string,
- label: formData.label as string
- }
- ]}
- />
- </div>
- </div>
- )}
- </div>
- </div>
+ {/* Additional Properties */}
+ {additionalFields.length > 0 && (
+ <div className="space-y-4">
+ <h3 className="text-sm font-medium text-muted-foreground">
+ Additional Properties
+ </h3>
+ <div className="space-y-4">
+ {additionalFields.map(([key, value]) => (
+ <div key={key} className="space-y-2">
+ <Label htmlFor={key} className="text-sm font-medium capitalize">
+ {key.replace(/_/g, ' ')}
+ </Label>
+ {typeof value === 'boolean' ? (
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant={formData[key as keyof NodeData] ? 'default' : 'outline'}
+ size="sm"
+ onClick={() =>
+ handleInputChange(
+ key as keyof NodeData,
+ (!formData[key as keyof NodeData]).toString()
+ )
+ }
+ className="gap-2"
+ >
+ {formData[key as keyof NodeData] ? (
+ <>
+ <Check className="h-3 w-3" />
+ True
+ </>
+ ) : (
+ 'False'
+ )}
+ </Button>
+ </div>
+ ) : typeof value === 'string' && value.length > 100 ? (
+ <Textarea
+ id={key}
+ value={(formData[key as keyof NodeData] as string) || ''}
+ onChange={(e) =>
+ handleInputChange(key as keyof NodeData, e.target.value)
+ }
+ placeholder={`Enter ${key.replace(/_/g, ' ').toLowerCase()}`}
+ className="min-h-[80px] resize-none"
+ rows={3}
+ />
+ ) : (
+ <Input
+ id={key}
+ value={(formData[key as keyof NodeData] as string) || ''}
+ onChange={(e) =>
+ handleInputChange(key as keyof NodeData, e.target.value)
+ }
+ placeholder={`Enter ${key.replace(/_/g, ' ').toLowerCase()}`}
+ className="h-9"
+ />
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
- {/* Footer */}
- <SheetFooter className="px-6 py-4 border-t bg-muted/30 flex-shrink-0">
- <div className="flex justify-between items-center w-full">
- <div className="text-sm text-muted-foreground">
- {additionalFields.length} additional properties
- </div>
- <div className="flex gap-2">
- <Button
- variant="outline"
- onClick={handleCancel}
- className="gap-2"
- >
- <X className="h-4 w-4" />
- Cancel
- </Button>
- <Button
- onClick={handleSave}
- disabled={isSaving}
- className="gap-2"
- >
- {isSaving ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Save className="h-4 w-4" />
- )}
- {isSaving ? "Saving..." : "Save Changes"}
- </Button>
- </div>
- </div>
- </SheetFooter>
+ {/* Location Map */}
+ {isLocation && (
+ <div className="space-y-4">
+ <h3 className="text-sm font-medium text-muted-foreground">Location</h3>
+ <div className="overflow-hidden rounded-lg bg-background border">
+ <MapFromAddress
+ locations={[
+ {
+ lat: formData.latitude,
+ lon: formData.longitude,
+ address: formData.label as string,
+ label: formData.label as string
+ }
+ ]}
+ />
+ </div>
</div>
- </SheetContent>
- </Sheet>
- );
-};
\ No newline at end of file
+ )}
+ </div>
+ </div>
+
+ {/* Footer */}
+ <SheetFooter className="px-6 py-4 border-t bg-muted/30 flex-shrink-0">
+ <div className="flex justify-between items-center w-full">
+ <div className="text-sm text-muted-foreground">
+ {additionalFields.length} additional properties
+ </div>
+ <div className="flex gap-2">
+ <Button variant="outline" onClick={handleCancel} className="gap-2">
+ <X className="h-4 w-4" />
+ Cancel
+ </Button>
+ <Button onClick={handleSave} disabled={isSaving} className="gap-2">
+ {isSaving ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Save className="h-4 w-4" />
+ )}
+ {isSaving ? 'Saving...' : 'Save Changes'}
+ </Button>
+ </div>
+ </div>
+ </SheetFooter>
+ </div>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/graphs/details-panel/relationships.tsx b/flowsint-app/src/renderer/src/components/graphs/details-panel/relationships.tsx
index 46deec92..56c04173 100644
--- a/flowsint-app/src/renderer/src/components/graphs/details-panel/relationships.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/details-panel/relationships.tsx
@@ -1,112 +1,118 @@
-import { sketchService } from '@/api/sketch-service';
-import Loader from '@/components/loader';
-import { TypeBadge } from '@/components/type-badge';
-import { Badge } from '@/components/ui/badge';
+import { sketchService } from '@/api/sketch-service'
+import Loader from '@/components/loader'
+import { TypeBadge } from '@/components/type-badge'
+import { Badge } from '@/components/ui/badge'
import { useGraphStore } from '@/stores/graph-store'
-import { useQuery } from '@tanstack/react-query';
-import { useVirtualizer } from '@tanstack/react-virtual';
-import { ArrowRight } from 'lucide-react';
-import { memo, useCallback, useRef } from 'react';
-import { GraphEdge, GraphNode } from "@/types"
+import { useQuery } from '@tanstack/react-query'
+import { useVirtualizer } from '@tanstack/react-virtual'
+import { ArrowRight } from 'lucide-react'
+import { memo, useCallback, useRef } from 'react'
+import { GraphEdge, GraphNode } from '@/types'
type Relation = {
- source: GraphNode,
- target: GraphNode,
- edge: { label: string }
+ source: GraphNode
+ target: GraphNode
+ edge: { label: string }
}
const getInlineRelationships = (nodes: GraphNode[], edges: GraphEdge[]): Relation[] => {
- const relationships: Relation[] = []
- edges.forEach((edge) => {
- const source = nodes.find((n) => (n.id === edge.source))
- const target = nodes.find((n) => (n.id === edge.target))
- if (!target || !source) return
- relationships.push({ source, target, edge: { label: String(edge.caption || 'RELATED_TO') } })
- })
- return relationships
+ const relationships: Relation[] = []
+ edges.forEach((edge) => {
+ const source = nodes.find((n) => n.id === edge.source)
+ const target = nodes.find((n) => n.id === edge.target)
+ if (!target || !source) return
+ relationships.push({ source, target, edge: { label: String(edge.caption || 'RELATED_TO') } })
+ })
+ return relationships
}
-const Relationships = memo(({ sketchId, nodeId, nodeLength }: { sketchId: string, nodeId: string, nodeLength: number }) => {
+const Relationships = memo(
+ ({ sketchId, nodeId, nodeLength }: { sketchId: string; nodeId: string; nodeLength: number }) => {
const { data: neighborsData, isLoading } = useQuery({
- queryKey: ['neighbors', sketchId, nodeId, nodeLength],
- queryFn: () => sketchService.getNodeNeighbors(sketchId, nodeId),
- });
+ queryKey: ['neighbors', sketchId, nodeId, nodeLength],
+ queryFn: () => sketchService.getNodeNeighbors(sketchId, nodeId)
+ })
- const parentRef = useRef<HTMLDivElement>(null);
- const relationships = getInlineRelationships(neighborsData?.nds || [], neighborsData?.rls || []);
+ const parentRef = useRef<HTMLDivElement>(null)
+ const relationships = getInlineRelationships(neighborsData?.nds || [], neighborsData?.rls || [])
const rowVirtualizer = useVirtualizer({
- count: relationships.length,
- getScrollElement: () => parentRef.current,
- estimateSize: () => 40, // Estimate height of each relationship item
- overscan: 5,
- });
+ count: relationships.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => 40, // Estimate height of each relationship item
+ overscan: 5
+ })
- if (isLoading) return <div className='flex items-center justify-center grow h-full'><Loader /></div>
+ if (isLoading)
+ return (
+ <div className="flex items-center justify-center grow h-full">
+ <Loader />
+ </div>
+ )
return (
- <div ref={parentRef} className="h-full overflow-auto py-3">
- <div
+ <div ref={parentRef} className="h-full overflow-auto py-3">
+ <div
+ style={{
+ height: `${rowVirtualizer.getTotalSize()}px`,
+ width: '100%',
+ position: 'relative'
+ }}
+ >
+ {rowVirtualizer.getVirtualItems().map((virtualRow) => {
+ const rel = relationships[virtualRow.index]
+ return (
+ <div
+ key={virtualRow.index}
style={{
- height: `${rowVirtualizer.getTotalSize()}px`,
- width: '100%',
- position: 'relative',
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ height: `${virtualRow.size}px`,
+ transform: `translateY(${virtualRow.start}px)`
}}
- >
- {rowVirtualizer.getVirtualItems().map((virtualRow) => {
- const rel = relationships[virtualRow.index];
- return (
- <div
- key={virtualRow.index}
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- width: '100%',
- height: `${virtualRow.size}px`,
- transform: `translateY(${virtualRow.start}px)`,
- }}
- className="mb-1 px-3"
- >
- <Badge variant={"outline"} className='h-8 px-2 py-1 w-full'>
- <div className='flex items-center gap-1 w-full min-w-0 h-full'>
- <div className='min-w-0 flex-1 flex items-center'>
- <RelationshipItem node={rel.source} />
- </div>
- <ArrowRight className='flex-shrink-0 opacity-60 h-4 w-4' />
- <div className='min-w-0 flex-1 flex items-center justify-center'>
- <span className='opacity-60 text-xs truncate block'>{rel.edge.label}</span>
- </div>
- <ArrowRight className='flex-shrink-0 opacity-60 h-4 w-4' />
- <div className='min-w-0 flex-1 flex items-center justify-end'>
- <RelationshipItem node={rel.target} />
- </div>
- </div>
- </Badge>
- </div>
- );
- })}
- </div>
+ className="mb-1 px-3"
+ >
+ <Badge variant={'outline'} className="h-8 px-2 py-1 w-full">
+ <div className="flex items-center gap-1 w-full min-w-0 h-full">
+ <div className="min-w-0 flex-1 flex items-center">
+ <RelationshipItem node={rel.source} />
+ </div>
+ <ArrowRight className="flex-shrink-0 opacity-60 h-4 w-4" />
+ <div className="min-w-0 flex-1 flex items-center justify-center">
+ <span className="opacity-60 text-xs truncate block">{rel.edge.label}</span>
+ </div>
+ <ArrowRight className="flex-shrink-0 opacity-60 h-4 w-4" />
+ <div className="min-w-0 flex-1 flex items-center justify-end">
+ <RelationshipItem node={rel.target} />
+ </div>
+ </div>
+ </Badge>
+ </div>
+ )
+ })}
</div>
+ </div>
)
-})
+ }
+)
export default Relationships
-
const RelationshipItem = memo(({ node }: { node: GraphNode }) => {
- const setCurrentNode = useGraphStore(s => s.setCurrentNode)
- const handleClick = useCallback(() => {
- setCurrentNode(node)
- }, [setCurrentNode])
- return (
- <button
- className='w-full h-full text-left hover:underline cursor-pointer flex items-center'
- onClick={handleClick}
- >
- <TypeBadge className='w-full truncate block text-center' type={node.data.type}>
- {node.data.label}
- </TypeBadge>
- </button>
- )
-})
\ No newline at end of file
+ const setCurrentNode = useGraphStore((s) => s.setCurrentNode)
+ const handleClick = useCallback(() => {
+ setCurrentNode(node)
+ }, [setCurrentNode])
+ return (
+ <button
+ className="w-full h-full text-left hover:underline cursor-pointer flex items-center"
+ onClick={handleClick}
+ >
+ <TypeBadge className="w-full truncate block text-center" type={node.data.type}>
+ {node.data.label}
+ </TypeBadge>
+ </button>
+ )
+})
diff --git a/flowsint-app/src/renderer/src/components/graphs/draggable-card.tsx b/flowsint-app/src/renderer/src/components/graphs/draggable-card.tsx
index 02768dd8..82b11131 100644
--- a/flowsint-app/src/renderer/src/components/graphs/draggable-card.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/draggable-card.tsx
@@ -1,9 +1,9 @@
-import React from "react"
-import { Reorder, useDragControls } from "framer-motion"
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
-import { Button } from "@/components/ui/button"
-import { Edit3, Eye, GripVertical } from "lucide-react"
-import { cn } from "@/lib/utils"
+import React from 'react'
+import { Reorder, useDragControls } from 'framer-motion'
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
+import { Button } from '@/components/ui/button'
+import { Edit3, Eye, GripVertical } from 'lucide-react'
+import { cn } from '@/lib/utils'
interface DraggableCardProps {
id: string
@@ -26,7 +26,6 @@ export const DraggableCard: React.FC<DraggableCardProps> = ({
showEditButton = true,
description
}) => {
-
const controls = useDragControls()
return (
@@ -37,43 +36,25 @@ export const DraggableCard: React.FC<DraggableCardProps> = ({
whileDrag={{ scale: 1.02, zIndex: 10 }}
transition={{ duration: 0.2 }}
>
- <Card className={cn("border bg-card/50 transition-all", className)}>
+ <Card className={cn('border bg-card/50 transition-all', className)}>
<CardHeader className="pb-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 cursor-grab active:cursor-grabbing reorder-handle ">
- <div className="p-4" onPointerDown={(e) => controls.start(e)} >
- <GripVertical
- className="h-4 w-4 text-muted-foreground/50 cursor-grab" />
+ <div className="p-4" onPointerDown={(e) => controls.start(e)}>
+ <GripVertical className="h-4 w-4 text-muted-foreground/50 cursor-grab" />
</div>
- <CardTitle className="text-base font-medium">
- {title}
- </CardTitle>
+ <CardTitle className="text-base font-medium">{title}</CardTitle>
</div>
{showEditButton && (
- <Button
- variant="ghost"
- size="sm"
- onClick={onToggleEdit}
- className="h-8 w-8 p-0"
- >
- {isEditing ? (
- <Eye className="h-4 w-4" />
- ) : (
- <Edit3 className="h-4 w-4" />
- )}
+ <Button variant="ghost" size="sm" onClick={onToggleEdit} className="h-8 w-8 p-0">
+ {isEditing ? <Eye className="h-4 w-4" /> : <Edit3 className="h-4 w-4" />}
</Button>
)}
</div>
- {description && (
- <p className="text-sm text-muted-foreground mt-1">
- {description}
- </p>
- )}
+ {description && <p className="text-sm text-muted-foreground mt-1">{description}</p>}
</CardHeader>
- <CardContent>
- {children}
- </CardContent>
+ <CardContent>{children}</CardContent>
</Card>
</Reorder.Item>
)
-}
\ No newline at end of file
+}
diff --git a/flowsint-app/src/renderer/src/components/graphs/draggable-item.tsx b/flowsint-app/src/renderer/src/components/graphs/draggable-item.tsx
index ea18abb2..d4b1c202 100644
--- a/flowsint-app/src/renderer/src/components/graphs/draggable-item.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/draggable-item.tsx
@@ -1,86 +1,85 @@
-
-import { memo, useState } from "react"
-import { useIcon } from "@/hooks/use-icon"
-import { useGraphStore } from "@/stores/graph-store"
-import { cn } from "@/lib/utils"
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import { useActionItems } from "@/hooks/use-action-items"
-import { findActionItemByKey } from "@/lib/action-items"
+import { memo, useState } from 'react'
+import { useIcon } from '@/hooks/use-icon'
+import { useGraphStore } from '@/stores/graph-store'
+import { cn } from '@/lib/utils'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { useActionItems } from '@/hooks/use-action-items'
+import { findActionItemByKey } from '@/lib/action-items'
interface DraggableItemProps {
- label: string
- icon: string
- type: string
- color?: string
- disabled?: boolean
- description: string
- itemKey: string
+ label: string
+ icon: string
+ type: string
+ color?: string
+ disabled?: boolean
+ description: string
+ itemKey: string
}
export const DraggableItem = memo(function DraggableItem({
- label,
- icon,
- type,
- color,
- itemKey,
- disabled = false,
- description,
+ label,
+ icon,
+ type,
+ color,
+ itemKey,
+ disabled = false,
+ description
}: DraggableItemProps) {
- const handleOpenFormModal = useGraphStore((s) => s.handleOpenFormModal)
- const { actionItems } = useActionItems()
- const [isDragging, setIsDragging] = useState(false)
- const colors = useNodesDisplaySettings((s) => s.colors)
- const colorStr = colors[icon as string] || color
- const IconComponent = useIcon(icon)
+ const handleOpenFormModal = useGraphStore((s) => s.handleOpenFormModal)
+ const { actionItems } = useActionItems()
+ const [isDragging, setIsDragging] = useState(false)
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ const colorStr = colors[icon as string] || color
+ const IconComponent = useIcon(icon)
- const handleDragStart = (e: React.DragEvent<HTMLButtonElement>) => {
- const itemData = JSON.stringify({ label, type, color, description, itemKey })
- e.dataTransfer.setData("text/plain", itemData)
- setIsDragging(true)
- }
+ const handleDragStart = (e: React.DragEvent<HTMLButtonElement>) => {
+ const itemData = JSON.stringify({ label, type, color, description, itemKey })
+ e.dataTransfer.setData('text/plain', itemData)
+ setIsDragging(true)
+ }
- const handleDragEnd = () => {
- setIsDragging(false)
- }
+ const handleDragEnd = () => {
+ setIsDragging(false)
+ }
- const onClick = () => {
- if (disabled) return
- handleOpenFormModal(findActionItemByKey(itemKey, actionItems))
- }
+ const onClick = () => {
+ if (disabled) return
+ handleOpenFormModal(findActionItemByKey(itemKey, actionItems))
+ }
- return (
- <TooltipProvider>
- <Tooltip delayDuration={500}>
- <TooltipTrigger asChild>
- <button
- draggable={!disabled}
- onClick={onClick}
- onDragStart={handleDragStart}
- onDragEnd={handleDragEnd}
- className={cn(
- "px-3 py-2 group flex items-center w-full gap-3 text-ellipsis rounded-md relative overflow-hidden border-1 border-l-3 transition-all hover:bg-accent/50",
- {
- "opacity-50": isDragging || disabled,
- "cursor-not-allowed": disabled,
- "cursor-grab": !disabled,
- }
- )}
- style={{ borderLeftColor: colorStr }}
- >
- <div>
- <IconComponent size={16} type={type} />
- </div>
- <div className="w-full p-1 text-left flex-1 min-w-0">
- <h3 className="text-sm font-medium truncate w-full">{label}</h3>
- <p className="text-xs opacity-60 truncate w-full">{description}</p>
- </div>
- </button>
- </TooltipTrigger>
- <TooltipContent>
- {disabled ? "This item is not available" : "Drag and drop to add to the graph"}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )
+ return (
+ <TooltipProvider>
+ <Tooltip delayDuration={500}>
+ <TooltipTrigger asChild>
+ <button
+ draggable={!disabled}
+ onClick={onClick}
+ onDragStart={handleDragStart}
+ onDragEnd={handleDragEnd}
+ className={cn(
+ 'px-3 py-2 group flex items-center w-full gap-3 text-ellipsis rounded-md relative overflow-hidden border-1 border-l-3 transition-all hover:bg-accent/50',
+ {
+ 'opacity-50': isDragging || disabled,
+ 'cursor-not-allowed': disabled,
+ 'cursor-grab': !disabled
+ }
+ )}
+ style={{ borderLeftColor: colorStr }}
+ >
+ <div>
+ <IconComponent size={16} type={type} />
+ </div>
+ <div className="w-full p-1 text-left flex-1 min-w-0">
+ <h3 className="text-sm font-medium truncate w-full">{label}</h3>
+ <p className="text-xs opacity-60 truncate w-full">{description}</p>
+ </div>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>
+ {disabled ? 'This item is not available' : 'Drag and drop to add to the graph'}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )
})
diff --git a/flowsint-app/src/renderer/src/components/graphs/dynamic-form.tsx b/flowsint-app/src/renderer/src/components/graphs/dynamic-form.tsx
index 6d718dc0..c214cff2 100644
--- a/flowsint-app/src/renderer/src/components/graphs/dynamic-form.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/dynamic-form.tsx
@@ -1,431 +1,451 @@
-
-import { useState, useMemo } from "react"
-import { useForm, Controller } from "react-hook-form"
-import { zodResolver } from "@hookform/resolvers/zod"
-import * as z from "zod"
-import { format } from "date-fns"
-import { fr } from "date-fns/locale"
-import { CalendarIcon, Loader2, InfoIcon } from "lucide-react"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Label } from "@/components/ui/label"
-import { Textarea } from "@/components/ui/textarea"
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
-import { Calendar } from "@/components/ui/calendar"
-import { cn } from "@/lib/utils"
-import type { FormField } from "@/lib/action-items"
-import { MetadataField } from "@/components/graphs/metadata-field"
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
-import { toast } from "sonner"
+import { useState, useMemo } from 'react'
+import { useForm, Controller } from 'react-hook-form'
+import { zodResolver } from '@hookform/resolvers/zod'
+import * as z from 'zod'
+import { format } from 'date-fns'
+import { fr } from 'date-fns/locale'
+import { CalendarIcon, Loader2, InfoIcon } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Textarea } from '@/components/ui/textarea'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import { Calendar } from '@/components/ui/calendar'
+import { cn } from '@/lib/utils'
+import type { FormField } from '@/lib/action-items'
+import { MetadataField } from '@/components/graphs/metadata-field'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
+import { toast } from 'sonner'
interface DynamicFormProps {
- currentNodeType: any
- initialData?: Record<string, any>
- onSubmit?: (data: any) => void
- isForm?: boolean
- loading?: boolean
+ currentNodeType: any
+ initialData?: Record<string, any>
+ onSubmit?: (data: any) => void
+ isForm?: boolean
+ loading?: boolean
}
-export function DynamicForm({ currentNodeType, initialData = {}, onSubmit, isForm = true, loading = false }: DynamicFormProps) {
- const [isSubmitting, setIsSubmitting] = useState(false)
+export function DynamicForm({
+ currentNodeType,
+ initialData = {},
+ onSubmit,
+ isForm = true,
+ loading = false
+}: DynamicFormProps) {
+ const [isSubmitting, setIsSubmitting] = useState(false)
- const dynamicSchema = useMemo(() => {
- const createDynamicSchema = () => {
- const schemaMap: Record<string, z.ZodType<any>> = {}
- if (!currentNodeType) return z.object(schemaMap)
- currentNodeType.fields.forEach((field: any) => {
- switch (field.type) {
- case "email":
- schemaMap[field.name] = field.required
- ? z
- .string()
- .min(1, { message: `${field.label} is required` })
- .email({ message: "Email invalide" })
- : z.string().email({ message: "Email invalide" }).optional()
- break
- case "url":
- schemaMap[field.name] = field.required
- ? z
- .string()
- .min(1, { message: `${field.label} is required` })
- .url({ message: "URL invalide" })
- : z.string().url({ message: "URL invalide" }).optional()
- break
- case "number":
- schemaMap[field.name] = field.required
- ? z
- .string()
- .min(1, { message: `${field.label} is required` })
- .refine((val) => !isNaN(Number(val)), {
- message: "Doit être un nombre valide",
- })
- : z
- .string()
- .refine((val) => val === "" || !isNaN(Number(val)), {
- message: "Doit être un nombre valide",
- })
- .optional()
- break
- case "select":
- if (field.options && field.options.length > 0) {
- const validValues = field.options.map((option: any) => option.value)
- schemaMap[field.name] = field.required
- ? z
- .string()
- .min(1, { message: `${field.label} is required` })
- .refine((val) => validValues.includes(val), {
- message: "Valeur non valide",
- })
- : z
- .string()
- .refine((val) => val === "" || validValues.includes(val), {
- message: "Valeur non valide",
- })
- .optional()
- } else {
- schemaMap[field.name] = field.required
- ? z.string().min(1, { message: `${field.label} is required` })
- : z.string().optional()
- }
- break
- case "date":
- schemaMap[field.name] = field.required
- ? z.string().min(1, { message: `${field.label} is required` })
- : z.string().optional()
- break
- case "hidden":
- schemaMap[field.name] = z.string()
- break
- case "textarea":
- schemaMap[field.name] = field.required
- ? z.string().min(1, { message: `${field.label} is required` })
- : z.string().optional()
- break
- case "metadata":
- schemaMap[field.name] = field.required
- ? z.record(z.string(), z.string()).refine((val) => Object.keys(val).length > 0, {
- message: "Au moins une métadonnée is requirede",
- })
- : z.record(z.string(), z.string()).optional()
- break
- default:
- schemaMap[field.name] = field.required
- ? z.string().min(1, { message: `${field.label} is required` })
- : z.string().optional()
- }
- })
- return z.object(schemaMap)
+ const dynamicSchema = useMemo(() => {
+ const createDynamicSchema = () => {
+ const schemaMap: Record<string, z.ZodType<any>> = {}
+ if (!currentNodeType) return z.object(schemaMap)
+ currentNodeType.fields.forEach((field: any) => {
+ switch (field.type) {
+ case 'email':
+ schemaMap[field.name] = field.required
+ ? z
+ .string()
+ .min(1, { message: `${field.label} is required` })
+ .email({ message: 'Email invalide' })
+ : z.string().email({ message: 'Email invalide' }).optional()
+ break
+ case 'url':
+ schemaMap[field.name] = field.required
+ ? z
+ .string()
+ .min(1, { message: `${field.label} is required` })
+ .url({ message: 'URL invalide' })
+ : z.string().url({ message: 'URL invalide' }).optional()
+ break
+ case 'number':
+ schemaMap[field.name] = field.required
+ ? z
+ .string()
+ .min(1, { message: `${field.label} is required` })
+ .refine((val) => !isNaN(Number(val)), {
+ message: 'Doit être un nombre valide'
+ })
+ : z
+ .string()
+ .refine((val) => val === '' || !isNaN(Number(val)), {
+ message: 'Doit être un nombre valide'
+ })
+ .optional()
+ break
+ case 'select':
+ if (field.options && field.options.length > 0) {
+ const validValues = field.options.map((option: any) => option.value)
+ schemaMap[field.name] = field.required
+ ? z
+ .string()
+ .min(1, { message: `${field.label} is required` })
+ .refine((val) => validValues.includes(val), {
+ message: 'Valeur non valide'
+ })
+ : z
+ .string()
+ .refine((val) => val === '' || validValues.includes(val), {
+ message: 'Valeur non valide'
+ })
+ .optional()
+ } else {
+ schemaMap[field.name] = field.required
+ ? z.string().min(1, { message: `${field.label} is required` })
+ : z.string().optional()
+ }
+ break
+ case 'date':
+ schemaMap[field.name] = field.required
+ ? z.string().min(1, { message: `${field.label} is required` })
+ : z.string().optional()
+ break
+ case 'hidden':
+ schemaMap[field.name] = z.string()
+ break
+ case 'textarea':
+ schemaMap[field.name] = field.required
+ ? z.string().min(1, { message: `${field.label} is required` })
+ : z.string().optional()
+ break
+ case 'metadata':
+ schemaMap[field.name] = field.required
+ ? z.record(z.string(), z.string()).refine((val) => Object.keys(val).length > 0, {
+ message: 'Au moins une métadonnée is requirede'
+ })
+ : z.record(z.string(), z.string()).optional()
+ break
+ default:
+ schemaMap[field.name] = field.required
+ ? z.string().min(1, { message: `${field.label} is required` })
+ : z.string().optional()
}
- return createDynamicSchema()
- }, [currentNodeType])
+ })
+ return z.object(schemaMap)
+ }
+ return createDynamicSchema()
+ }, [currentNodeType])
- type FormValues = z.infer<typeof dynamicSchema>
- const getDefaultValues = () => {
- const defaults: Record<string, any> = {}
+ type FormValues = z.infer<typeof dynamicSchema>
+ const getDefaultValues = () => {
+ const defaults: Record<string, any> = {}
- if (!currentNodeType) return defaults
+ if (!currentNodeType) return defaults
- currentNodeType.fields.forEach((field: any) => {
- // Si nous avons des données initiales pour ce champ, les utiliser
- if (initialData && initialData[field.name] !== undefined) {
- defaults[field.name] = initialData[field.name]
- }
- // Sinon, gérer les différents types de champs
- else if (field.type === "hidden") {
- const fieldKey = currentNodeType.key
- const match = fieldKey.match(/_([^_]+)$/)
- if ((match && match[1] && field.name === "platform") || field.name === "type") {
- defaults[field.name] = match?.[1]
- } else {
- defaults[field.name] = ""
- }
- } else if (field.type === "select") {
- // Pour les champs select, vérifier s'il y a des options
- if (field.options && field.options.length > 0) {
- // Si requis, utilisez la première option comme valeur par défaut
- // Sinon, utilisez une chaîne vide car un champ facultatif peut être vide
- defaults[field.name] = field.required && field.options.length > 0 ? field.options[0].value : ""
- } else {
- defaults[field.name] = ""
- }
- } else if (field.type === "date") {
- // Pour les champs de date, nous laissons une chaîne vide
- // mais nous nous assurerons plus tard que les manipulations de dates sont robustes
- defaults[field.name] = ""
- } else if (field.type === "metadata") {
- defaults[field.name] = {}
- } else {
- defaults[field.name] = ""
- }
- })
+ currentNodeType.fields.forEach((field: any) => {
+ // Si nous avons des données initiales pour ce champ, les utiliser
+ if (initialData && initialData[field.name] !== undefined) {
+ defaults[field.name] = initialData[field.name]
+ }
+ // Sinon, gérer les différents types de champs
+ else if (field.type === 'hidden') {
+ const fieldKey = currentNodeType.key
+ const match = fieldKey.match(/_([^_]+)$/)
+ if ((match && match[1] && field.name === 'platform') || field.name === 'type') {
+ defaults[field.name] = match?.[1]
+ } else {
+ defaults[field.name] = ''
+ }
+ } else if (field.type === 'select') {
+ // Pour les champs select, vérifier s'il y a des options
+ if (field.options && field.options.length > 0) {
+ // Si requis, utilisez la première option comme valeur par défaut
+ // Sinon, utilisez une chaîne vide car un champ facultatif peut être vide
+ defaults[field.name] =
+ field.required && field.options.length > 0 ? field.options[0].value : ''
+ } else {
+ defaults[field.name] = ''
+ }
+ } else if (field.type === 'date') {
+ // Pour les champs de date, nous laissons une chaîne vide
+ // mais nous nous assurerons plus tard que les manipulations de dates sont robustes
+ defaults[field.name] = ''
+ } else if (field.type === 'metadata') {
+ defaults[field.name] = {}
+ } else {
+ defaults[field.name] = ''
+ }
+ })
- return defaults
- }
+ return defaults
+ }
- const {
- register,
- handleSubmit,
- control,
- formState: { errors },
- } = useForm<FormValues>({
- resolver: zodResolver(dynamicSchema),
- defaultValues: getDefaultValues(),
- })
+ const {
+ register,
+ handleSubmit,
+ control,
+ formState: { errors }
+ } = useForm<FormValues>({
+ resolver: zodResolver(dynamicSchema),
+ defaultValues: getDefaultValues()
+ })
- const handleFormSubmit = async (data: FormValues) => {
- if (!isForm) return
- try {
- setIsSubmitting(true)
- if (onSubmit) {
- await onSubmit(data)
- }
- } catch (error) {
- console.log(error)
- toast.error("An error occurred while submitting the form.")
- } finally {
- setIsSubmitting(false)
- }
+ const handleFormSubmit = async (data: FormValues) => {
+ if (!isForm) return
+ try {
+ setIsSubmitting(true)
+ if (onSubmit) {
+ await onSubmit(data)
+ }
+ } catch (error) {
+ console.log(error)
+ toast.error('An error occurred while submitting the form.')
+ } finally {
+ setIsSubmitting(false)
}
+ }
- const renderField = (field: FormField) => {
- if (field.type === "hidden") {
- return <input key={field.name} type="hidden" {...register(field.name)} />
- }
- const FieldDescription = field.description ? (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <InfoIcon className="h-4 w-4 text-muted-foreground ml-1 cursor-help" />
- </TooltipTrigger>
- <TooltipContent>
- <p className="max-w-xs">{field.description}</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : null
-
- switch (field.type) {
- case "text":
- case "email":
- case "tel":
- case "number":
- return (
- <div className="space-y-2" key={field.name}>
- <div className="flex items-center">
- <Label htmlFor={field.name} className="text-sm font-medium">
- {field.label}
- {field.required && <span className="text-destructive ml-1">*</span>}
- </Label>
- {FieldDescription}
- </div>
- <Input
- id={field.name}
- type={field.type}
- placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
- className={errors[field.name] ? "border-destructive" : ""}
- {...register(field.name)}
- />
- {errors[field.name] && <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>}
- </div>
- )
+ const renderField = (field: FormField) => {
+ if (field.type === 'hidden') {
+ return <input key={field.name} type="hidden" {...register(field.name)} />
+ }
+ const FieldDescription = field.description ? (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="h-4 w-4 text-muted-foreground ml-1 cursor-help" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p className="max-w-xs">{field.description}</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ ) : null
- case "textarea":
- return (
- <div className="space-y-2" key={field.name}>
- <div className="flex items-center">
- <Label htmlFor={field.name} className="text-sm font-medium">
- {field.label}
- {field.required && <span className="text-destructive ml-1">*</span>}
- </Label>
- {FieldDescription}
- </div>
- <Textarea
- id={field.name}
- placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
- className={errors[field.name] ? "border-destructive" : ""}
- {...register(field.name)}
- />
- {errors[field.name] && <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>}
- </div>
- )
+ switch (field.type) {
+ case 'text':
+ case 'email':
+ case 'tel':
+ case 'number':
+ return (
+ <div className="space-y-2" key={field.name}>
+ <div className="flex items-center">
+ <Label htmlFor={field.name} className="text-sm font-medium">
+ {field.label}
+ {field.required && <span className="text-destructive ml-1">*</span>}
+ </Label>
+ {FieldDescription}
+ </div>
+ <Input
+ id={field.name}
+ type={field.type}
+ placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
+ className={errors[field.name] ? 'border-destructive' : ''}
+ {...register(field.name)}
+ />
+ {errors[field.name] && (
+ <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>
+ )}
+ </div>
+ )
- case "select":
- return (
- <div className="space-y-2" key={field.name}>
- <div className="flex items-center">
- <Label htmlFor={field.name} className="text-sm font-medium">
- {field.label}
- {field.required && <span className="text-destructive ml-1">*</span>}
- </Label>
- {FieldDescription}
- </div>
- <Controller
- control={control}
- name={field.name}
- render={({ field: { onChange, value, ref } }) => (
- <Select
- onValueChange={onChange}
- value={value || ""}
- defaultValue={value || ""}
- >
- <SelectTrigger
- ref={ref}
- id={field.name}
- className={errors[field.name] ? "border-destructive" : ""}
- >
- <SelectValue placeholder={field.placeholder || `Select ${field.label.toLowerCase()}`} />
- </SelectTrigger>
- <SelectContent>
- {!field.required && (
- <SelectItem value=" ">-- Sélectionner --</SelectItem>
- )}
- {field.options?.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- {errors[field.name] && <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>}
- </div>
- )
+ case 'textarea':
+ return (
+ <div className="space-y-2" key={field.name}>
+ <div className="flex items-center">
+ <Label htmlFor={field.name} className="text-sm font-medium">
+ {field.label}
+ {field.required && <span className="text-destructive ml-1">*</span>}
+ </Label>
+ {FieldDescription}
+ </div>
+ <Textarea
+ id={field.name}
+ placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
+ className={errors[field.name] ? 'border-destructive' : ''}
+ {...register(field.name)}
+ />
+ {errors[field.name] && (
+ <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>
+ )}
+ </div>
+ )
- case "date":
- return (
- <div className="space-y-2" key={field.name}>
- <div className="flex items-center">
- <Label htmlFor={field.name} className="text-sm font-medium">
- {field.label}
- {field.required && <span className="text-destructive ml-1">*</span>}
- </Label>
- {FieldDescription}
- </div>
- <Controller
- control={control}
- name={field.name}
- render={({ field: { onChange, value, ref } }) => {
- // Sécurisation des valeurs de date
- const dateValue = value ?
- (typeof value === 'string' && value.trim() !== '' ? new Date(value) : null) :
- null;
+ case 'select':
+ return (
+ <div className="space-y-2" key={field.name}>
+ <div className="flex items-center">
+ <Label htmlFor={field.name} className="text-sm font-medium">
+ {field.label}
+ {field.required && <span className="text-destructive ml-1">*</span>}
+ </Label>
+ {FieldDescription}
+ </div>
+ <Controller
+ control={control}
+ name={field.name}
+ render={({ field: { onChange, value, ref } }) => (
+ <Select onValueChange={onChange} value={value || ''} defaultValue={value || ''}>
+ <SelectTrigger
+ ref={ref}
+ id={field.name}
+ className={errors[field.name] ? 'border-destructive' : ''}
+ >
+ <SelectValue
+ placeholder={field.placeholder || `Select ${field.label.toLowerCase()}`}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ {!field.required && <SelectItem value=" ">-- Sélectionner --</SelectItem>}
+ {field.options?.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ {errors[field.name] && (
+ <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>
+ )}
+ </div>
+ )
- // Validation pour éviter les dates invalides
- const isValidDate = dateValue instanceof Date && !isNaN(dateValue.getTime());
+ case 'date':
+ return (
+ <div className="space-y-2" key={field.name}>
+ <div className="flex items-center">
+ <Label htmlFor={field.name} className="text-sm font-medium">
+ {field.label}
+ {field.required && <span className="text-destructive ml-1">*</span>}
+ </Label>
+ {FieldDescription}
+ </div>
+ <Controller
+ control={control}
+ name={field.name}
+ render={({ field: { onChange, value, ref } }) => {
+ // Sécurisation des valeurs de date
+ const dateValue = value
+ ? typeof value === 'string' && value.trim() !== ''
+ ? new Date(value)
+ : null
+ : null
- return (
- <Popover>
- <PopoverTrigger asChild>
- <div>
- <Button
- ref={ref}
- type="button"
- variant="outline"
- className={cn(
- "w-full justify-start text-left font-normal",
- !isValidDate && "text-muted-foreground",
- errors[field.name] && "border-destructive",
- )}
- >
- <CalendarIcon className="mr-2 h-4 w-4" />
- {isValidDate
- ? format(dateValue as Date, "PPP", { locale: fr })
- : field.placeholder || `Sélectionner une date`}
- </Button>
- </div>
- </PopoverTrigger>
- <PopoverContent className="w-auto p-0" align="start">
- <Calendar
- mode="single"
- selected={isValidDate ? dateValue as Date : undefined}
- onSelect={(date) => {
- // Assurer une bonne conversion vers ISO string
- onChange(date ? date.toISOString() : "")
- }}
- initialFocus
- />
- </PopoverContent>
- </Popover>
- )
- }}
- />
- {errors[field.name] && <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>}
- </div>
- )
+ // Validation pour éviter les dates invalides
+ const isValidDate = dateValue instanceof Date && !isNaN(dateValue.getTime())
- case "url":
return (
- <div className="space-y-2" key={field.name}>
- <div className="flex items-center">
- <Label htmlFor={field.name} className="text-sm font-medium">
- {field.label}
- {field.required && <span className="text-destructive ml-1">*</span>}
- </Label>
- {FieldDescription}
- </div>
- <Input
- id={field.name}
- type="url"
- placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
- className={errors[field.name] ? "border-destructive" : ""}
- {...register(field.name)}
- />
- {errors[field.name] && <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>}
- </div>
+ <Popover>
+ <PopoverTrigger asChild>
+ <div>
+ <Button
+ ref={ref}
+ type="button"
+ variant="outline"
+ className={cn(
+ 'w-full justify-start text-left font-normal',
+ !isValidDate && 'text-muted-foreground',
+ errors[field.name] && 'border-destructive'
+ )}
+ >
+ <CalendarIcon className="mr-2 h-4 w-4" />
+ {isValidDate
+ ? format(dateValue as Date, 'PPP', { locale: fr })
+ : field.placeholder || `Sélectionner une date`}
+ </Button>
+ </div>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0" align="start">
+ <Calendar
+ mode="single"
+ selected={isValidDate ? (dateValue as Date) : undefined}
+ onSelect={(date) => {
+ // Assurer une bonne conversion vers ISO string
+ onChange(date ? date.toISOString() : '')
+ }}
+ initialFocus
+ />
+ </PopoverContent>
+ </Popover>
)
+ }}
+ />
+ {errors[field.name] && (
+ <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>
+ )}
+ </div>
+ )
- case "metadata":
- return (
- <div className="space-y-2" key={field.name}>
- <div className="flex items-center">
- <Label htmlFor={field.name} className="text-sm font-medium">
- {field.label}
- {field.required && <span className="text-destructive ml-1">*</span>}
- </Label>
- {FieldDescription}
- </div>
- <Controller
- control={control}
- name={field.name}
- render={({ field: { onChange, value } }) => (
- <MetadataField
- value={value || {}}
- onChange={onChange}
- error={errors[field.name]?.message as string}
- className="border rounded-md p-3 bg-muted/30"
- />
- )}
- />
- </div>
- )
- default:
- return null
- }
- }
+ case 'url':
+ return (
+ <div className="space-y-2" key={field.name}>
+ <div className="flex items-center">
+ <Label htmlFor={field.name} className="text-sm font-medium">
+ {field.label}
+ {field.required && <span className="text-destructive ml-1">*</span>}
+ </Label>
+ {FieldDescription}
+ </div>
+ <Input
+ id={field.name}
+ type="url"
+ placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
+ className={errors[field.name] ? 'border-destructive' : ''}
+ {...register(field.name)}
+ />
+ {errors[field.name] && (
+ <p className="text-xs text-destructive">{String(errors[field.name]?.message)}</p>
+ )}
+ </div>
+ )
- if (!currentNodeType) {
- return <div className="p-4 text-center text-muted-foreground">Could not find this item.</div>
- }
- if (!isForm) {
- return <div className="space-y-4">{currentNodeType.fields.map(renderField)}</div>
- }
- return (
- <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-4 p-1">
- <div className="space-y-4">{currentNodeType.fields.map(renderField)}</div>
- <div className="flex sticky translate-y-1 p-1 bottom-0 bg-background items-center justify-end space-x-2">
- <Button type="submit" disabled={isSubmitting || loading}>
- {isSubmitting || loading ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- Submitting...
- </>
- ) : (
- `Add ${currentNodeType.label}`
- )}
- </Button>
+ case 'metadata':
+ return (
+ <div className="space-y-2" key={field.name}>
+ <div className="flex items-center">
+ <Label htmlFor={field.name} className="text-sm font-medium">
+ {field.label}
+ {field.required && <span className="text-destructive ml-1">*</span>}
+ </Label>
+ {FieldDescription}
</div>
- </form>
- )
-}
\ No newline at end of file
+ <Controller
+ control={control}
+ name={field.name}
+ render={({ field: { onChange, value } }) => (
+ <MetadataField
+ value={value || {}}
+ onChange={onChange}
+ error={errors[field.name]?.message as string}
+ className="border rounded-md p-3 bg-muted/30"
+ />
+ )}
+ />
+ </div>
+ )
+ default:
+ return null
+ }
+ }
+
+ if (!currentNodeType) {
+ return <div className="p-4 text-center text-muted-foreground">Could not find this item.</div>
+ }
+ if (!isForm) {
+ return <div className="space-y-4">{currentNodeType.fields.map(renderField)}</div>
+ }
+ return (
+ <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-4 p-1">
+ <div className="space-y-4">{currentNodeType.fields.map(renderField)}</div>
+ <div className="flex sticky translate-y-1 p-1 bottom-0 bg-background items-center justify-end space-x-2">
+ <Button type="submit" disabled={isSubmitting || loading}>
+ {isSubmitting || loading ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Submitting...
+ </>
+ ) : (
+ `Add ${currentNodeType.label}`
+ )}
+ </Button>
+ </div>
+ </form>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/graphs/empty-state.tsx b/flowsint-app/src/renderer/src/components/graphs/empty-state.tsx
index cd415525..af793916 100644
--- a/flowsint-app/src/renderer/src/components/graphs/empty-state.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/empty-state.tsx
@@ -4,91 +4,176 @@ import { Button } from '@/components/ui/button'
import { useGraphStore } from '@/stores/graph-store'
const EmptyState = memo(() => {
- const setOpenMainDialog = useGraphStore(state => state.setOpenMainDialog)
+ const setOpenMainDialog = useGraphStore((state) => state.setOpenMainDialog)
- const handleOpenNewAddItemDialog = useCallback(() => {
- setOpenMainDialog(true)
- }, [setOpenMainDialog])
+ const handleOpenNewAddItemDialog = useCallback(() => {
+ setOpenMainDialog(true)
+ }, [setOpenMainDialog])
- return (
- <div className="flex relative bg-background gap-8 h-full flex-col w-full items-center justify-center">
- {/* Animated Graph Illustration */}
- <div className="relative">
- <svg width="200" height="120" viewBox="0 0 200 120" className="opacity-40">
- {/* Connections */}
- <g className="stroke-muted-foreground/30 fill-none stroke-2">
- <line x1="40" y1="40" x2="90" y2="60" className="animate-pulse" style={{ animationDelay: '0s' }} />
- <line x1="90" y1="60" x2="160" y2="40" className="animate-pulse" style={{ animationDelay: '0.5s' }} />
- <line x1="90" y1="60" x2="130" y2="90" className="animate-pulse" style={{ animationDelay: '1s' }} />
- <line x1="40" y1="40" x2="70" y2="90" className="animate-pulse" style={{ animationDelay: '1.5s' }} />
- <line x1="160" y1="40" x2="130" y2="90" className="animate-pulse" style={{ animationDelay: '2s' }} />
- </g>
-
- {/* Nodes */}
- <g className="fill-primary/60 stroke-primary stroke-2">
- <circle cx="40" cy="40" r="8" className="animate-pulse" style={{ animationDelay: '0s' }} />
- <circle cx="90" cy="60" r="10" className="animate-pulse" style={{ animationDelay: '0.3s' }} />
- <circle cx="160" cy="40" r="8" className="animate-pulse" style={{ animationDelay: '0.6s' }} />
- <circle cx="130" cy="90" r="8" className="animate-pulse" style={{ animationDelay: '0.9s' }} />
- <circle cx="70" cy="90" r="8" className="animate-pulse" style={{ animationDelay: '1.2s' }} />
- </g>
-
- {/* Floating particles */}
- <g className="fill-primary/20">
- <circle cx="20" cy="20" r="2" className="animate-bounce" style={{ animationDelay: '0s', animationDuration: '3s' }} />
- <circle cx="180" cy="30" r="2" className="animate-bounce" style={{ animationDelay: '1s', animationDuration: '3s' }} />
- <circle cx="170" cy="100" r="2" className="animate-bounce" style={{ animationDelay: '2s', animationDuration: '3s' }} />
- <circle cx="30" cy="100" r="2" className="animate-bounce" style={{ animationDelay: '1.5s', animationDuration: '3s' }} />
- </g>
- </svg>
-
- {/* Glow effect */}
- <div className="absolute inset-0 bg-gradient-to-r from-primary/10 via-transparent to-primary/10 rounded-full blur-xl scale-150 animate-pulse" />
- </div>
+ return (
+ <div className="flex relative bg-background gap-8 h-full flex-col w-full items-center justify-center">
+ {/* Animated Graph Illustration */}
+ <div className="relative">
+ <svg width="200" height="120" viewBox="0 0 200 120" className="opacity-40">
+ {/* Connections */}
+ <g className="stroke-muted-foreground/30 fill-none stroke-2">
+ <line
+ x1="40"
+ y1="40"
+ x2="90"
+ y2="60"
+ className="animate-pulse"
+ style={{ animationDelay: '0s' }}
+ />
+ <line
+ x1="90"
+ y1="60"
+ x2="160"
+ y2="40"
+ className="animate-pulse"
+ style={{ animationDelay: '0.5s' }}
+ />
+ <line
+ x1="90"
+ y1="60"
+ x2="130"
+ y2="90"
+ className="animate-pulse"
+ style={{ animationDelay: '1s' }}
+ />
+ <line
+ x1="40"
+ y1="40"
+ x2="70"
+ y2="90"
+ className="animate-pulse"
+ style={{ animationDelay: '1.5s' }}
+ />
+ <line
+ x1="160"
+ y1="40"
+ x2="130"
+ y2="90"
+ className="animate-pulse"
+ style={{ animationDelay: '2s' }}
+ />
+ </g>
- {/* Content */}
- <div className="text-center space-y-4 max-w-md">
- <div className="space-y-2">
- <h2 className="text-2xl font-semibold tracking-tight">
- Ready to explore connections?
- </h2>
- <p className="text-muted-foreground text-sm leading-relaxed">
- Your investigation graph will come to life here. Add nodes, discover relationships,
- and uncover hidden patterns in your data.
- </p>
- </div>
-
- {/* Feature highlights */}
- <div className="flex justify-center gap-6 text-xs text-muted-foreground pt-2">
- <div className="flex items-center gap-1.5">
- <GitBranch className="w-3 h-3" />
- <span>Network mapping</span>
- </div>
- <div className="flex items-center gap-1.5">
- <Zap className="w-3 h-3" />
- <span>Real-time analysis</span>
- </div>
- </div>
- </div>
+ {/* Nodes */}
+ <g className="fill-primary/60 stroke-primary stroke-2">
+ <circle
+ cx="40"
+ cy="40"
+ r="8"
+ className="animate-pulse"
+ style={{ animationDelay: '0s' }}
+ />
+ <circle
+ cx="90"
+ cy="60"
+ r="10"
+ className="animate-pulse"
+ style={{ animationDelay: '0.3s' }}
+ />
+ <circle
+ cx="160"
+ cy="40"
+ r="8"
+ className="animate-pulse"
+ style={{ animationDelay: '0.6s' }}
+ />
+ <circle
+ cx="130"
+ cy="90"
+ r="8"
+ className="animate-pulse"
+ style={{ animationDelay: '0.9s' }}
+ />
+ <circle
+ cx="70"
+ cy="90"
+ r="8"
+ className="animate-pulse"
+ style={{ animationDelay: '1.2s' }}
+ />
+ </g>
- {/* Call to action */}
- <div className="flex flex-col items-center gap-3">
- <Button
- onClick={handleOpenNewAddItemDialog}
- className="h-10 px-6 font-medium shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105"
- size="default"
- >
- <PlusIcon className="w-4 h-4" />
- Add your first item
- </Button>
- <p className="text-xs text-muted-foreground">
- Add your first node to begin
- </p>
- </div>
+ {/* Floating particles */}
+ <g className="fill-primary/20">
+ <circle
+ cx="20"
+ cy="20"
+ r="2"
+ className="animate-bounce"
+ style={{ animationDelay: '0s', animationDuration: '3s' }}
+ />
+ <circle
+ cx="180"
+ cy="30"
+ r="2"
+ className="animate-bounce"
+ style={{ animationDelay: '1s', animationDuration: '3s' }}
+ />
+ <circle
+ cx="170"
+ cy="100"
+ r="2"
+ className="animate-bounce"
+ style={{ animationDelay: '2s', animationDuration: '3s' }}
+ />
+ <circle
+ cx="30"
+ cy="100"
+ r="2"
+ className="animate-bounce"
+ style={{ animationDelay: '1.5s', animationDuration: '3s' }}
+ />
+ </g>
+ </svg>
+
+ {/* Glow effect */}
+ <div className="absolute inset-0 bg-gradient-to-r from-primary/10 via-transparent to-primary/10 rounded-full blur-xl scale-150 animate-pulse" />
+ </div>
+
+ {/* Content */}
+ <div className="text-center space-y-4 max-w-md">
+ <div className="space-y-2">
+ <h2 className="text-2xl font-semibold tracking-tight">Ready to explore connections?</h2>
+ <p className="text-muted-foreground text-sm leading-relaxed">
+ Your investigation graph will come to life here. Add nodes, discover relationships, and
+ uncover hidden patterns in your data.
+ </p>
</div>
- )
+
+ {/* Feature highlights */}
+ <div className="flex justify-center gap-6 text-xs text-muted-foreground pt-2">
+ <div className="flex items-center gap-1.5">
+ <GitBranch className="w-3 h-3" />
+ <span>Network mapping</span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ <Zap className="w-3 h-3" />
+ <span>Real-time analysis</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Call to action */}
+ <div className="flex flex-col items-center gap-3">
+ <Button
+ onClick={handleOpenNewAddItemDialog}
+ className="h-10 px-6 font-medium shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105"
+ size="default"
+ >
+ <PlusIcon className="w-4 h-4" />
+ Add your first item
+ </Button>
+ <p className="text-xs text-muted-foreground">Add your first node to begin</p>
+ </div>
+ </div>
+ )
})
-EmptyState.displayName = "EmptyState"
+EmptyState.displayName = 'EmptyState'
export default EmptyState
diff --git a/flowsint-app/src/renderer/src/components/graphs/filters.tsx b/flowsint-app/src/renderer/src/components/graphs/filters.tsx
index 1604a750..4aeb1958 100644
--- a/flowsint-app/src/renderer/src/components/graphs/filters.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/filters.tsx
@@ -1,42 +1,45 @@
-import { useGraphStore } from '@/stores/graph-store';
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover"
-import { Checkbox } from '../ui/checkbox';
-import { Separator } from '../ui/separator';
+import { useGraphStore } from '@/stores/graph-store'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import { Checkbox } from '../ui/checkbox'
+import { Separator } from '../ui/separator'
const Filters = ({ children }: { children: React.ReactNode }) => {
- const filters = useGraphStore(s => s.filters);
- const toggleTypeFilter = useGraphStore(s => s.toggleTypeFilter);
+ const filters = useGraphStore((s) => s.filters)
+ const toggleTypeFilter = useGraphStore((s) => s.toggleTypeFilter)
- return (
- <Popover>
- <PopoverTrigger asChild>
- <div>
- {children}
- </div>
- </PopoverTrigger>
- <PopoverContent className="w-80">
- <div className="grid gap-4">
- <div className="space-y-2">
- <h4 className="leading-none font-medium">Filters</h4>
- </div>
- <Separator />
- <p className="text-muted-foreground text-sm">Filter by entity type</p>
- {filters.types.length === 0 ? <p className="text-muted-foreground text-sm">No filter to display.</p> :
- <ul className="grid grid-cols-2 gap-2">
- {filters.types.map((filter) => (
- <li>
- <div className="flex items-center gap-1"><Checkbox checked={filter.checked} onCheckedChange={() => toggleTypeFilter(filter)} />{filter.type}</div>
- </li>
- ))}
- </ul>}
- </div>
- </PopoverContent>
- </Popover>
- );
-};
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <div>{children}</div>
+ </PopoverTrigger>
+ <PopoverContent className="w-80">
+ <div className="grid gap-4">
+ <div className="space-y-2">
+ <h4 className="leading-none font-medium">Filters</h4>
+ </div>
+ <Separator />
+ <p className="text-muted-foreground text-sm">Filter by entity type</p>
+ {filters.types.length === 0 ? (
+ <p className="text-muted-foreground text-sm">No filter to display.</p>
+ ) : (
+ <ul className="grid grid-cols-2 gap-2">
+ {filters.types.map((filter) => (
+ <li>
+ <div className="flex items-center gap-1">
+ <Checkbox
+ checked={filter.checked}
+ onCheckedChange={() => toggleTypeFilter(filter)}
+ />
+ {filter.type}
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )
+}
-export default Filters;
\ No newline at end of file
+export default Filters
diff --git a/flowsint-app/src/renderer/src/components/graphs/graph-loader.tsx b/flowsint-app/src/renderer/src/components/graphs/graph-loader.tsx
index 06f2086d..39c1c3ab 100644
--- a/flowsint-app/src/renderer/src/components/graphs/graph-loader.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/graph-loader.tsx
@@ -1,13 +1,13 @@
import Loader from '@/components/loader'
const GraphLoader = () => (
- <div className='relative h-full w-full z-50'>
- <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex flex-col items-center justify-center z-50">
- <div className="text-center flex items-center gap-2">
- <Loader />
- </div>
- </div>
+ <div className="relative h-full w-full z-50">
+ <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex flex-col items-center justify-center z-50">
+ <div className="text-center flex items-center gap-2">
+ <Loader />
+ </div>
</div>
+ </div>
)
-export default GraphLoader
\ No newline at end of file
+export default GraphLoader
diff --git a/flowsint-app/src/renderer/src/components/graphs/graph-main.tsx b/flowsint-app/src/renderer/src/components/graphs/graph-main.tsx
index 73d9cccb..07680f20 100644
--- a/flowsint-app/src/renderer/src/components/graphs/graph-main.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/graph-main.tsx
@@ -5,68 +5,71 @@ import ContextMenu from './context-menu'
import { useGraphSettingsStore } from '@/stores/graph-settings-store'
const GraphMain = () => {
- const filteredNodes = useGraphStore(s => s.filteredNodes)
- const filteredEdges = useGraphStore(s => s.filteredEdges)
- const toggleNodeSelection = useGraphStore(s => s.toggleNodeSelection)
- const clearSelectedNodes = useGraphStore(s => s.clearSelectedNodes)
- const settings = useGraphSettingsStore(s => s.settings)
+ const filteredNodes = useGraphStore((s) => s.filteredNodes)
+ const filteredEdges = useGraphStore((s) => s.filteredEdges)
+ const toggleNodeSelection = useGraphStore((s) => s.toggleNodeSelection)
+ const clearSelectedNodes = useGraphStore((s) => s.clearSelectedNodes)
+ const settings = useGraphSettingsStore((s) => s.settings)
- const graphRef = useRef<any>()
- const containerRef = useRef<HTMLDivElement>(null)
- const [menu, setMenu] = React.useState<any>(null)
+ const graphRef = useRef<any>()
+ const containerRef = useRef<HTMLDivElement>(null)
+ const [menu, setMenu] = React.useState<any>(null)
- const handleNodeClick = useCallback((node: any, event: MouseEvent) => {
- const isMultiSelect = event.ctrlKey || event.shiftKey;
- toggleNodeSelection(node, isMultiSelect)
- }, [toggleNodeSelection])
+ const handleNodeClick = useCallback(
+ (node: any, event: MouseEvent) => {
+ const isMultiSelect = event.ctrlKey || event.shiftKey
+ toggleNodeSelection(node, isMultiSelect)
+ },
+ [toggleNodeSelection]
+ )
- const handleBackgroundClick = useCallback(() => {
- clearSelectedNodes()
- setMenu(null)
- }, [clearSelectedNodes])
+ const handleBackgroundClick = useCallback(() => {
+ clearSelectedNodes()
+ setMenu(null)
+ }, [clearSelectedNodes])
- const onNodeContextMenu = useCallback((node: any, event: MouseEvent) => {
- if (!containerRef.current || !node) return
+ const onNodeContextMenu = useCallback((node: any, event: MouseEvent) => {
+ if (!containerRef.current || !node) return
- const pane = containerRef.current.getBoundingClientRect()
- const relativeX = event.clientX - pane.left
- const relativeY = event.clientY - pane.top
+ const pane = containerRef.current.getBoundingClientRect()
+ const relativeX = event.clientX - pane.left
+ const relativeY = event.clientY - pane.top
- setMenu({
- node: {
- data: node.data || {},
- id: node.id || '',
- label: node.label || node.nodeLabel || '',
- position: node.position || { x: node.x || 0, y: node.y || 0 }
- },
- rawTop: relativeY,
- rawLeft: relativeX,
- wrapperWidth: pane.width,
- wrapperHeight: pane.height,
- setMenu: setMenu,
- })
- }, [])
+ setMenu({
+ node: {
+ data: node.data || {},
+ id: node.id || '',
+ label: node.label || node.nodeLabel || '',
+ position: node.position || { x: node.x || 0, y: node.y || 0 }
+ },
+ rawTop: relativeY,
+ rawLeft: relativeX,
+ wrapperWidth: pane.width,
+ wrapperHeight: pane.height,
+ setMenu: setMenu
+ })
+ }, [])
- const handleGraphRef = useCallback((ref: any) => {
- graphRef.current = ref
- }, [])
- return (
- <div ref={containerRef} className="relative h-full w-full bg-background">
- <GraphViewer
- nodes={filteredNodes}
- edges={filteredEdges}
- onNodeClick={handleNodeClick}
- onNodeRightClick={onNodeContextMenu}
- onBackgroundClick={handleBackgroundClick}
- showLabels={true}
- showIcons={true}
- onGraphRef={handleGraphRef}
- allowLasso
- minimap={Boolean(settings?.general?.showMinimap?.value)}
- />
- {menu && <ContextMenu onClick={handleBackgroundClick} {...menu} />}
- </div>
- )
+ const handleGraphRef = useCallback((ref: any) => {
+ graphRef.current = ref
+ }, [])
+ return (
+ <div ref={containerRef} className="relative h-full w-full bg-background">
+ <GraphViewer
+ nodes={filteredNodes}
+ edges={filteredEdges}
+ onNodeClick={handleNodeClick}
+ onNodeRightClick={onNodeContextMenu}
+ onBackgroundClick={handleBackgroundClick}
+ showLabels={true}
+ showIcons={true}
+ onGraphRef={handleGraphRef}
+ allowLasso
+ minimap={false}
+ />
+ {menu && <ContextMenu onClick={handleBackgroundClick} {...menu} />}
+ </div>
+ )
}
-export default GraphMain
\ No newline at end of file
+export default GraphMain
diff --git a/flowsint-app/src/renderer/src/components/graphs/graph-navigation.tsx b/flowsint-app/src/renderer/src/components/graphs/graph-navigation.tsx
index f6417ff0..931ad3fd 100644
--- a/flowsint-app/src/renderer/src/components/graphs/graph-navigation.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/graph-navigation.tsx
@@ -1,71 +1,72 @@
-import { useGraphStore } from "@/stores/graph-store"
-import NodesPanel from "./nodes-panel"
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
-import { UserPlus, Users } from "lucide-react"
-import { ItemsPanel } from "./items-panel"
-import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "../ui/resizable"
-import { useLayoutStore } from "@/stores/layout-store"
-import SelectedItemsPanel from "./selected-items-panel"
+import { useGraphStore } from '@/stores/graph-store'
+import NodesPanel from './nodes-panel'
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
+import { UserPlus, Users } from 'lucide-react'
+import { ItemsPanel } from './items-panel'
+import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '../ui/resizable'
+import { useLayoutStore } from '@/stores/layout-store'
+import SelectedItemsPanel from './selected-items-panel'
const GraphNavigation = () => {
- const nodes = useGraphStore((s) => s.nodes)
- const activeTab = useLayoutStore((s) => s.activeTab)
- const setActiveTab = useLayoutStore((s) => s.setActiveTab)
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const selectedNodesSome = selectedNodes.length > 0
- return (
- <div className="h-full w-full min-h-0">
- <Tabs
- value={activeTab}
- onValueChange={setActiveTab}
- defaultValue="entities"
- className="w-full h-full gap-0 flex flex-col min-w-0"
- >
- <TabsList className="w-full p-0 rounded-none my-0 border-b">
- <TabsTrigger value="entities"><Users className="h-3 w-3 opacity-60" /> Entities</TabsTrigger>
- <TabsTrigger value="items"><UserPlus className="h-3 w-3 opacity-60" /> Items</TabsTrigger>
- </TabsList>
- <TabsContent
- value="entities"
- className="grow flex flex-col min-h-0 min-w-0 overflow-hidden"
- >
- <ResizablePanelGroup
- autoSaveId="conditional"
- direction="vertical"
- className="flex-1 min-h-0 flex w-full flex-col"
- >
- {selectedNodesSome && (
- <>
- <ResizablePanel
- order={2}
- id="infos"
- defaultSize={30}
- className="flex flex-col w-full overflow-hidden min-h-0 min-w-0"
- >
- <SelectedItemsPanel />
- </ResizablePanel>
- <ResizableHandle />
- </>
- )}
- <ResizablePanel
- order={3}
- id="nodes"
- defaultSize={40}
- className="flex flex-col overflow-hidden min-h-0 min-w-0"
- >
- <NodesPanel nodes={nodes} />
- </ResizablePanel>
- </ResizablePanelGroup>
- </TabsContent>
- <TabsContent
- value="items"
- className="my-0 grow h-full overflow-hidden min-h-0"
+ const nodes = useGraphStore((s) => s.nodes)
+ const activeTab = useLayoutStore((s) => s.activeTab)
+ const setActiveTab = useLayoutStore((s) => s.setActiveTab)
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const selectedNodesSome = selectedNodes.length > 0
+ return (
+ <div className="h-full w-full min-h-0">
+ <Tabs
+ value={activeTab}
+ onValueChange={setActiveTab}
+ defaultValue="entities"
+ className="w-full h-full gap-0 flex flex-col min-w-0"
+ >
+ <TabsList className="w-full p-0 rounded-none my-0 border-b">
+ <TabsTrigger value="entities">
+ <Users className="h-3 w-3 opacity-60" /> Entities
+ </TabsTrigger>
+ <TabsTrigger value="items">
+ <UserPlus className="h-3 w-3 opacity-60" /> Items
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent
+ value="entities"
+ className="grow flex flex-col min-h-0 min-w-0 overflow-hidden"
+ >
+ <ResizablePanelGroup
+ autoSaveId="conditional"
+ direction="vertical"
+ className="flex-1 min-h-0 flex w-full flex-col"
+ >
+ {selectedNodesSome && (
+ <>
+ <ResizablePanel
+ order={2}
+ id="infos"
+ defaultSize={30}
+ className="flex flex-col w-full overflow-hidden min-h-0 min-w-0"
>
- <ItemsPanel />
- </TabsContent>
- </Tabs>
- </div>
- )
+ <SelectedItemsPanel />
+ </ResizablePanel>
+ <ResizableHandle />
+ </>
+ )}
+ <ResizablePanel
+ order={3}
+ id="nodes"
+ defaultSize={40}
+ className="flex flex-col overflow-hidden min-h-0 min-w-0"
+ >
+ <NodesPanel nodes={nodes} />
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ </TabsContent>
+ <TabsContent value="items" className="my-0 grow h-full overflow-hidden min-h-0">
+ <ItemsPanel />
+ </TabsContent>
+ </Tabs>
+ </div>
+ )
}
export default GraphNavigation
diff --git a/flowsint-app/src/renderer/src/components/graphs/graph-viewer.tsx b/flowsint-app/src/renderer/src/components/graphs/graph-viewer.tsx
index aa62d3fa..06def7da 100644
--- a/flowsint-app/src/renderer/src/components/graphs/graph-viewer.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/graph-viewer.tsx
@@ -1,949 +1,1033 @@
-import { getDagreLayoutedElements } from '@/lib/utils';
-import { useGraphControls } from '@/stores/graph-controls-store';
-import { useGraphSettingsStore } from '@/stores/graph-settings-store';
-import { useGraphStore } from '@/stores/graph-store';
-import { ItemType, useNodesDisplaySettings } from '@/stores/node-display-settings';
-import React, { useCallback, useMemo, useEffect, useState, useRef } from 'react';
-import ForceGraph2D from 'react-force-graph-2d';
-import { Button } from '../ui/button';
+import { getDagreLayoutedElements } from '@/lib/utils'
+import { useGraphControls } from '@/stores/graph-controls-store'
+import { useGraphSettingsStore } from '@/stores/graph-settings-store'
+import { useGraphStore } from '@/stores/graph-store'
+import { ItemType, useNodesDisplaySettings } from '@/stores/node-display-settings'
+import React, { useCallback, useMemo, useEffect, useState, useRef } from 'react'
+import ForceGraph2D from 'react-force-graph-2d'
+import { Button } from '../ui/button'
import { useTheme } from '@/components/theme-provider'
-import { Share2, Type } from 'lucide-react';
-import Lasso from './lasso';
-import { GraphNode, GraphEdge } from '@/types';
-import MiniMap from './minimap';
+import { Share2, Type } from 'lucide-react'
+import Lasso from './lasso'
+import { GraphNode, GraphEdge } from '@/types'
+import MiniMap from './minimap'
function truncateText(text: string, limit: number = 16) {
- if (text.length <= limit)
- return text
- return text.substring(0, limit) + "..."
+ if (text.length <= limit) return text
+ return text.substring(0, limit) + '...'
}
interface GraphViewerProps {
- nodes: GraphNode[];
- edges: GraphEdge[];
- // Remove width and height props - component will handle its own sizing
- nodeColors?: Record<string, string>;
- nodeSizes?: Record<string, number>;
- onNodeClick?: (node: GraphNode, event: MouseEvent) => void;
- onNodeRightClick?: (node: GraphNode, event: MouseEvent) => void;
- onBackgroundClick?: () => void;
- showLabels?: boolean;
- showIcons?: boolean;
- backgroundColor?: string;
- className?: string;
- style?: React.CSSProperties;
- onGraphRef?: (ref: any) => void;
- instanceId?: string; // Add instanceId prop for instance-specific actions
- allowLasso?: boolean
- minimap?: boolean
+ nodes: GraphNode[]
+ edges: GraphEdge[]
+ // Remove width and height props - component will handle its own sizing
+ nodeColors?: Record<string, string>
+ nodeSizes?: Record<string, number>
+ onNodeClick?: (node: GraphNode, event: MouseEvent) => void
+ onNodeRightClick?: (node: GraphNode, event: MouseEvent) => void
+ onBackgroundClick?: () => void
+ showLabels?: boolean
+ showIcons?: boolean
+ backgroundColor?: string
+ className?: string
+ style?: React.CSSProperties
+ onGraphRef?: (ref: any) => void
+ instanceId?: string // Add instanceId prop for instance-specific actions
+ allowLasso?: boolean
+ minimap?: boolean
}
// Graph viewer specific colors
export const GRAPH_COLORS = {
- // Link colors
- LINK_DEFAULT: 'rgba(128, 128, 128, 0.6)',
- LINK_HIGHLIGHTED: 'rgba(255, 115, 0, 0.68)',
- LINK_DIMMED: 'rgba(133, 133, 133, 0.23)',
- LINK_LABEL_HIGHLIGHTED: 'rgba(255, 115, 0, 0.9)',
- LINK_LABEL_DEFAULT: 'rgba(180, 180, 180, 0.75)',
+ // Link colors
+ LINK_DEFAULT: 'rgba(128, 128, 128, 0.6)',
+ LINK_HIGHLIGHTED: 'rgba(255, 115, 0, 0.68)',
+ LINK_DIMMED: 'rgba(133, 133, 133, 0.23)',
+ LINK_LABEL_HIGHLIGHTED: 'rgba(255, 115, 0, 0.9)',
+ LINK_LABEL_DEFAULT: 'rgba(180, 180, 180, 0.75)',
- // Node highlight colors
- NODE_HIGHLIGHT_HOVER: 'rgba(255, 0, 0, 0.3)',
- NODE_HIGHLIGHT_DEFAULT: 'rgba(255, 165, 0, 0.3)',
+ // Node highlight colors
+ NODE_HIGHLIGHT_HOVER: 'rgba(255, 0, 0, 0.3)',
+ NODE_HIGHLIGHT_DEFAULT: 'rgba(255, 165, 0, 0.3)',
- LASSO_FILL: 'rgba(255, 115, 0, 0.07)',
- LASSO_STROKE: 'rgba(255, 115, 0, 0.56)',
+ LASSO_FILL: 'rgba(255, 115, 0, 0.07)',
+ LASSO_STROKE: 'rgba(255, 115, 0, 0.56)',
- // Text colors
- TEXT_LIGHT: '#161616',
- TEXT_DARK: '#FFFFFF',
+ // Text colors
+ TEXT_LIGHT: '#161616',
+ TEXT_DARK: '#FFFFFF',
- // Background colors
- BACKGROUND_LIGHT: "#FFFFFF",
- BACKGROUND_DARK: '#161616',
+ // Background colors
+ BACKGROUND_LIGHT: '#FFFFFF',
+ BACKGROUND_DARK: '#161616',
- // Transparent colors
- TRANSPARENT: "#00000000",
+ // Transparent colors
+ TRANSPARENT: '#00000000',
- // Default node color
- NODE_DEFAULT: '#0074D9',
+ // Default node color
+ NODE_DEFAULT: '#0074D9'
} as const
const CONSTANTS = {
- NODE_COUNT_THRESHOLD: 500,
- NODE_DEFAULT_SIZE: 10,
- NODE_LABEL_FONT_SIZE: 3.5,
- LABEL_FONT_SIZE: 2.5,
- NODE_FONT_SIZE: 3.5,
- LABEL_NODE_MARGIN: 18,
- PADDING_RATIO: 0.2,
- HALF_PI: Math.PI / 2,
- PI: Math.PI,
- MEASURE_FONT: '1px Sans-Serif',
- MIN_FONT_SIZE: 0.5,
- LINK_WIDTH: 1,
- ARROW_SIZE: 8,
- ARROW_ANGLE: Math.PI / 6,
- MIN_ZOOM: 0.4,
- MAX_ZOOM: 5,
- MAX_VISIBLE_LABELS: 3
-};
+ NODE_COUNT_THRESHOLD: 500,
+ NODE_DEFAULT_SIZE: 10,
+ NODE_LABEL_FONT_SIZE: 3.5,
+ LABEL_FONT_SIZE: 2.5,
+ NODE_FONT_SIZE: 3.5,
+ LABEL_NODE_MARGIN: 18,
+ PADDING_RATIO: 0.2,
+ HALF_PI: Math.PI / 2,
+ PI: Math.PI,
+ MEASURE_FONT: '1px Sans-Serif',
+ MIN_FONT_SIZE: 0.5,
+ LINK_WIDTH: 1,
+ ARROW_SIZE: 8,
+ ARROW_ANGLE: Math.PI / 6,
+ MIN_ZOOM: 0.4,
+ MAX_ZOOM: 5,
+ MAX_VISIBLE_LABELS: 3
+}
interface LabelRenderingCompound {
- weightList: Map<string, number>,
- constants: {
- nodesLength: number
- }
+ weightList: Map<string, number>
+ constants: {
+ nodesLength: number
+ }
}
// Pre-computed constants
-const LABEL_FONT_STRING = `${CONSTANTS.LABEL_FONT_SIZE}px Sans-Serif`;
+const LABEL_FONT_STRING = `${CONSTANTS.LABEL_FONT_SIZE}px Sans-Serif`
// Reusable objects to avoid allocations
-const tempPos = { x: 0, y: 0 };
-const tempDimensions = [0, 0];
+const tempPos = { x: 0, y: 0 }
+const tempDimensions = [0, 0]
// Image cache for icons
-const imageCache = new Map<string, HTMLImageElement>();
-const imageLoadPromises = new Map<string, Promise<HTMLImageElement>>();
+const imageCache = new Map<string, HTMLImageElement>()
+const imageLoadPromises = new Map<string, Promise<HTMLImageElement>>()
// Preload icon images
const preloadImage = (iconType: string): Promise<HTMLImageElement> => {
- const cacheKey = iconType;
- // Return cached image if available
- if (imageCache.has(cacheKey)) {
- return Promise.resolve(imageCache.get(cacheKey)!);
+ const cacheKey = iconType
+ // Return cached image if available
+ if (imageCache.has(cacheKey)) {
+ return Promise.resolve(imageCache.get(cacheKey)!)
+ }
+ // Return existing promise if already loading
+ if (imageLoadPromises.has(cacheKey)) {
+ return imageLoadPromises.get(cacheKey)!
+ }
+ // Create new loading promise
+ const promise = new Promise<HTMLImageElement>((resolve, reject) => {
+ const img = new Image()
+ img.onload = () => {
+ imageCache.set(cacheKey, img)
+ imageLoadPromises.delete(cacheKey)
+ resolve(img)
}
- // Return existing promise if already loading
- if (imageLoadPromises.has(cacheKey)) {
- return imageLoadPromises.get(cacheKey)!;
+ img.onerror = () => {
+ imageLoadPromises.delete(cacheKey)
+ reject(new Error(`Failed to load icon: ${iconType}`))
}
- // Create new loading promise
- const promise = new Promise<HTMLImageElement>((resolve, reject) => {
- const img = new Image();
- img.onload = () => {
- imageCache.set(cacheKey, img);
- imageLoadPromises.delete(cacheKey);
- resolve(img);
- };
- img.onerror = () => {
- imageLoadPromises.delete(cacheKey);
- reject(new Error(`Failed to load icon: ${iconType}`));
- };
- img.src = `/icons/${iconType}.svg`;
- });
- imageLoadPromises.set(cacheKey, promise);
- return promise;
-};
+ img.src = `/icons/${iconType}.svg`
+ })
+ imageLoadPromises.set(cacheKey, promise)
+ return promise
+}
const GraphViewer: React.FC<GraphViewerProps> = ({
- nodes,
- edges,
- // Remove width and height from destructuring
- onNodeClick,
- onNodeRightClick,
- onBackgroundClick,
- showLabels = true,
- showIcons = true,
- backgroundColor = 'transparent',
- className = '',
- style,
- onGraphRef,
- instanceId,
- allowLasso = false,
- minimap = false
+ nodes,
+ edges,
+ // Remove width and height from destructuring
+ onNodeClick,
+ onNodeRightClick,
+ onBackgroundClick,
+ showLabels = true,
+ showIcons = true,
+ backgroundColor = 'transparent',
+ className = '',
+ style,
+ onGraphRef,
+ instanceId,
+ allowLasso = false,
+ minimap = false
}) => {
- const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
- const isLassoActive = useGraphControls(s => s.isLassoActive)
- // Hover highlighting state
- const [highlightNodes, setHighlightNodes] = useState<Set<string>>(new Set());
- const [highlightLinks, setHighlightLinks] = useState<Set<string>>(new Set());
- const [hoverNode, setHoverNode] = useState<string | null>(null);
- const zoomRef = useRef({ k: 1, x: 0, y: 0 });
- // The ref for the node weighlist.
- const labelRenderingCompound = useRef<LabelRenderingCompound>(
- {
- weightList: new Map(), constants: {
- nodesLength: 0,
- }
- }
- );
- // Store references
- const graphRef = useRef<any>();
- const containerRef = useRef<HTMLDivElement>(null);
- const isGraphReadyRef = useRef(false);
- const lastRenderTimeRef = useRef<number>(0);
- const renderThrottleRef = useRef<number | null>(null);
-
- // Store selectors
- const nodeColors = useNodesDisplaySettings(s => s.colors);
- const getSize = useNodesDisplaySettings(s => s.getSize);
- const view = useGraphControls(s => s.view);
-
- // Get settings by categories to avoid re-renders
- const forceSettings = useGraphSettingsStore(s => s.forceSettings);
- const setActions = useGraphControls(s => s.setActions);
- const currentNode = useGraphStore(s => s.currentNode)
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const { theme } = useTheme();
- const setOpenMainDialog = useGraphStore(state => state.setOpenMainDialog);
-
- const shouldUseSimpleRendering = useMemo(() =>
- nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || zoomRef.current.k < 1.5
- , [nodes.length, zoomRef.current.k]);
-
- // Add state for tooltip
- const [tooltip, setTooltip] = useState<{
- x: number;
- y: number;
- data: {
- label: string,
- connections: string
- type: string
- } | null;
- visible: boolean;
- }>({
- x: 0,
- y: 0,
- data: null,
- visible: false
- });
-
- const graph2ScreenCoords = useCallback((node: GraphNode) => {
- return graphRef.current.graph2ScreenCoords(node.x, node.y);
- }, [graphRef.current])
-
- const isCurrent = useCallback(
- (nodeId: string) => {
- return currentNode?.id === nodeId
- },
- [currentNode],
- )
+ const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
+ const isLassoActive = useGraphControls((s) => s.isLassoActive)
+ // Hover highlighting state
+ const [highlightNodes, setHighlightNodes] = useState<Set<string>>(new Set())
+ const [highlightLinks, setHighlightLinks] = useState<Set<string>>(new Set())
+ const [hoverNode, setHoverNode] = useState<string | null>(null)
+ const zoomRef = useRef({ k: 1, x: 0, y: 0 })
+ // The ref for the node weighlist.
+ const labelRenderingCompound = useRef<LabelRenderingCompound>({
+ weightList: new Map(),
+ constants: {
+ nodesLength: 0
+ }
+ })
+ // Store references
+ const graphRef = useRef<any>()
+ const containerRef = useRef<HTMLDivElement>(null)
+ const isGraphReadyRef = useRef(false)
+ const lastRenderTimeRef = useRef<number>(0)
+ const renderThrottleRef = useRef<number | null>(null)
- const isSelected = useCallback(
- (nodeId: string) => {
- return selectedNodes.some((node) => node.id === nodeId)
- },
- [selectedNodes],
- )
+ // Store selectors
+ const nodeColors = useNodesDisplaySettings((s) => s.colors)
+ const getSize = useNodesDisplaySettings((s) => s.getSize)
+ const view = useGraphControls((s) => s.view)
- // Preload icons when nodes change
- useEffect(() => {
- if (showIcons) {
- const iconTypes = new Set(nodes.map(node => node.data?.type as ItemType).filter(Boolean));
- iconTypes.forEach(type => {
- preloadImage(type).catch(console.warn); // Silently handle failures
- });
- }
- }, [nodes, showIcons]);
-
- const handleZoom = useCallback((zoom: any) => {
- zoomRef.current = zoom;
- }, []);
-
- // Optimized graph initialization callback
- const initializeGraph = useCallback((graphInstance: any) => {
- if (!graphInstance) return;
- // Check if the graph instance has the required methods
- if (typeof graphInstance.zoom !== 'function' || typeof graphInstance.zoomToFit !== 'function') {
- // If methods aren't available yet, retry after a short delay
- setTimeout(() => {
- if (graphRef.current && !isGraphReadyRef.current) {
- initializeGraph(graphRef.current);
- }
- }, 100);
- return;
- }
- if (isGraphReadyRef.current) return;
- isGraphReadyRef.current = true;
- // Only set global actions if no instanceId is provided (for main graph)
- if (!instanceId) {
- setActions({
- zoomIn: () => {
- if (graphRef.current && typeof graphRef.current.zoom === 'function') {
- const zoom = graphRef.current.zoom();
- graphRef.current.zoom(zoom * 1.5);
- }
- },
- zoomOut: () => {
- if (graphRef.current && typeof graphRef.current.zoom === 'function') {
- const zoom = graphRef.current.zoom();
- graphRef.current.zoom(zoom * 0.75);
- }
- },
- zoomToFit: () => {
- if (graphRef.current && typeof graphRef.current.zoomToFit === 'function') {
- graphRef.current.zoomToFit(400);
- }
- }
- });
- }
- // Call external ref callback
- onGraphRef?.(graphInstance);
- }, [setActions, onGraphRef, instanceId]);
+ // Get settings by categories to avoid re-renders
+ const forceSettings = useGraphSettingsStore((s) => s.forceSettings)
+ const setActions = useGraphControls((s) => s.setActions)
+ const currentNode = useGraphStore((s) => s.currentNode)
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const { theme } = useTheme()
+ const setOpenMainDialog = useGraphStore((state) => state.setOpenMainDialog)
- // Handle graph ref changes and ensure actions are set up
- useEffect(() => {
- if (graphRef.current) {
- initializeGraph(graphRef.current);
- }
- // Cleanup: reset actions when component unmounts (only for main graph)
- return () => {
- if (!instanceId && isGraphReadyRef.current) {
- setActions({
- zoomIn: () => { },
- zoomOut: () => { },
- zoomToFit: () => { },
- });
- isGraphReadyRef.current = false;
- }
- };
- }, [initializeGraph]);
-
- // Additional effect to ensure actions are set up when graph is ready
- useEffect(() => {
- if (graphRef.current && !instanceId && !isGraphReadyRef.current) {
- // Try to initialize again if the graph is available but not marked as ready
- initializeGraph(graphRef.current);
- }
- }, [graphRef.current, initializeGraph, instanceId]);
-
- // Handle container size changes
- useEffect(() => {
- const updateSize = () => {
- if (containerRef.current) {
- const rect = containerRef.current.getBoundingClientRect();
- setContainerSize({
- width: rect.width,
- height: rect.height
- });
+ const shouldUseSimpleRendering = useMemo(
+ () => nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || zoomRef.current.k < 1.5,
+ [nodes.length, zoomRef.current.k]
+ )
+
+ // Add state for tooltip
+ const [tooltip, setTooltip] = useState<{
+ x: number
+ y: number
+ data: {
+ label: string
+ connections: string
+ type: string
+ } | null
+ visible: boolean
+ }>({
+ x: 0,
+ y: 0,
+ data: null,
+ visible: false
+ })
+
+ const graph2ScreenCoords = useCallback(
+ (node: GraphNode) => {
+ return graphRef.current.graph2ScreenCoords(node.x, node.y)
+ },
+ [graphRef.current]
+ )
+
+ const isCurrent = useCallback(
+ (nodeId: string) => {
+ return currentNode?.id === nodeId
+ },
+ [currentNode]
+ )
+
+ const isSelected = useCallback(
+ (nodeId: string) => {
+ return selectedNodes.some((node) => node.id === nodeId)
+ },
+ [selectedNodes]
+ )
+
+ // Preload icons when nodes change
+ useEffect(() => {
+ if (showIcons) {
+ const iconTypes = new Set(nodes.map((node) => node.data?.type as ItemType).filter(Boolean))
+ iconTypes.forEach((type) => {
+ preloadImage(type).catch(console.warn) // Silently handle failures
+ })
+ }
+ }, [nodes, showIcons])
+
+ const handleZoom = useCallback((zoom: any) => {
+ zoomRef.current = zoom
+ }, [])
+
+ // Optimized graph initialization callback
+ const initializeGraph = useCallback(
+ (graphInstance: any) => {
+ if (!graphInstance) return
+ // Check if the graph instance has the required methods
+ if (
+ typeof graphInstance.zoom !== 'function' ||
+ typeof graphInstance.zoomToFit !== 'function'
+ ) {
+ // If methods aren't available yet, retry after a short delay
+ setTimeout(() => {
+ if (graphRef.current && !isGraphReadyRef.current) {
+ initializeGraph(graphRef.current)
+ }
+ }, 100)
+ return
+ }
+ if (isGraphReadyRef.current) return
+ isGraphReadyRef.current = true
+ // Only set global actions if no instanceId is provided (for main graph)
+ if (!instanceId) {
+ setActions({
+ zoomIn: () => {
+ if (graphRef.current && typeof graphRef.current.zoom === 'function') {
+ const zoom = graphRef.current.zoom()
+ graphRef.current.zoom(zoom * 1.5)
}
- };
- // Initial size
- updateSize();
- // Set up resize observer
- const resizeObserver = new ResizeObserver(updateSize);
- if (containerRef.current) {
- resizeObserver.observe(containerRef.current);
- }
- // Also listen for window resize events
- window.addEventListener('resize', updateSize);
- return () => {
- resizeObserver.disconnect();
- window.removeEventListener('resize', updateSize);
- };
- }, []);
-
- // Memoized graph data transformation with proper memoization dependencies
- const graphData = useMemo(() => {
- // Transform nodes
- const transformedNodes = nodes.map(node => {
- const type = node.data?.type as ItemType;
- return {
- ...node,
- nodeLabel: node.data?.label || node.id,
- nodeColor: nodeColors[type] || GRAPH_COLORS.NODE_DEFAULT,
- nodeSize: CONSTANTS.NODE_DEFAULT_SIZE,
- nodeType: type,
- val: CONSTANTS.NODE_DEFAULT_SIZE,
- neighbors: [] as any[],
- links: [] as any[]
- } as GraphNode & { neighbors: any[]; links: any[] };
- });
- // Create a map for quick node lookup
- const nodeMap = new Map(transformedNodes.map(node => [node.id, node]));
- // Group and transform edges
- const edgeGroups = new Map<string, GraphEdge[]>();
- edges.forEach(edge => {
- const key = `${edge.source}-${edge.target}`;
- if (!edgeGroups.has(key)) {
- edgeGroups.set(key, []);
+ },
+ zoomOut: () => {
+ if (graphRef.current && typeof graphRef.current.zoom === 'function') {
+ const zoom = graphRef.current.zoom()
+ graphRef.current.zoom(zoom * 0.75)
}
- edgeGroups.get(key)!.push(edge);
- });
- const transformedEdges = edges.map((edge) => {
- const key = `${edge.source}-${edge.target}`;
- const group = edgeGroups.get(key)!;
- const groupIndex = group.indexOf(edge);
- const groupSize = group.length;
- const curvature = groupSize > 1 ? (groupIndex - (groupSize - 1) / 2) * 0.2 : 0;
- return {
- ...edge,
- edgeLabel: edge.label,
- curvature,
- groupIndex,
- groupSize
- };
- });
- // Build node relationships (neighbors and links)
- transformedEdges.forEach(link => {
- const sourceNode = nodeMap.get(link.source);
- const targetNode = nodeMap.get(link.target);
- if (sourceNode && targetNode) {
- // Add neighbors
- if (!sourceNode.neighbors.includes(targetNode)) {
- sourceNode.neighbors.push(targetNode);
- }
- if (!targetNode.neighbors.includes(sourceNode)) {
- targetNode.neighbors.push(sourceNode);
- }
- // Add links
- sourceNode.links.push(link);
- targetNode.links.push(link);
+ },
+ zoomToFit: () => {
+ if (graphRef.current && typeof graphRef.current.zoomToFit === 'function') {
+ graphRef.current.zoomToFit(400)
}
- });
- // feed the labelRenderingCompound
- labelRenderingCompound.current.weightList = new Map(
- transformedNodes
- .sort((a, b) => b.neighbors.length - a.neighbors.length)
- .map(node => [node.id, node.neighbors.length])
- );
- labelRenderingCompound.current.constants = { nodesLength: transformedNodes.length, }
- // Handle hierarchy layout
- if (view === "hierarchy") {
- const { nodes: nds, edges: eds } = getDagreLayoutedElements(transformedNodes, transformedEdges);
- return {
- nodes: nds.map((nd) => ({
- ...nd,
- // Preserve the neighbors and links from the original transformed node
- neighbors: nodeMap.get(nd.id)?.neighbors || [],
- links: nodeMap.get(nd.id)?.links || []
- })),
- links: eds,
- };
+ }
+ })
+ }
+ // Call external ref callback
+ onGraphRef?.(graphInstance)
+ },
+ [setActions, onGraphRef, instanceId]
+ )
+
+ // Handle graph ref changes and ensure actions are set up
+ useEffect(() => {
+ if (graphRef.current) {
+ initializeGraph(graphRef.current)
+ }
+ // Cleanup: reset actions when component unmounts (only for main graph)
+ return () => {
+ if (!instanceId && isGraphReadyRef.current) {
+ setActions({
+ zoomIn: () => {},
+ zoomOut: () => {},
+ zoomToFit: () => {}
+ })
+ isGraphReadyRef.current = false
+ }
+ }
+ }, [initializeGraph])
+
+ // Additional effect to ensure actions are set up when graph is ready
+ useEffect(() => {
+ if (graphRef.current && !instanceId && !isGraphReadyRef.current) {
+ // Try to initialize again if the graph is available but not marked as ready
+ initializeGraph(graphRef.current)
+ }
+ }, [graphRef.current, initializeGraph, instanceId])
+
+ // Handle container size changes
+ useEffect(() => {
+ const updateSize = () => {
+ if (containerRef.current) {
+ const rect = containerRef.current.getBoundingClientRect()
+ setContainerSize({
+ width: rect.width,
+ height: rect.height
+ })
+ }
+ }
+ // Initial size
+ updateSize()
+ // Set up resize observer
+ const resizeObserver = new ResizeObserver(updateSize)
+ if (containerRef.current) {
+ resizeObserver.observe(containerRef.current)
+ }
+ // Also listen for window resize events
+ window.addEventListener('resize', updateSize)
+ return () => {
+ resizeObserver.disconnect()
+ window.removeEventListener('resize', updateSize)
+ }
+ }, [])
+
+ // Memoized graph data transformation with proper memoization dependencies
+ const graphData = useMemo(() => {
+ // Transform nodes
+ const transformedNodes = nodes.map((node) => {
+ const type = node.data?.type as ItemType
+ return {
+ ...node,
+ nodeLabel: node.data?.label || node.id,
+ nodeColor: nodeColors[type] || GRAPH_COLORS.NODE_DEFAULT,
+ nodeSize: CONSTANTS.NODE_DEFAULT_SIZE,
+ nodeType: type,
+ val: CONSTANTS.NODE_DEFAULT_SIZE,
+ neighbors: [] as any[],
+ links: [] as any[]
+ } as GraphNode & { neighbors: any[]; links: any[] }
+ })
+ // Create a map for quick node lookup
+ const nodeMap = new Map(transformedNodes.map((node) => [node.id, node]))
+ // Group and transform edges
+ const edgeGroups = new Map<string, GraphEdge[]>()
+ edges.forEach((edge) => {
+ const key = `${edge.source}-${edge.target}`
+ if (!edgeGroups.has(key)) {
+ edgeGroups.set(key, [])
+ }
+ edgeGroups.get(key)!.push(edge)
+ })
+ const transformedEdges = edges.map((edge) => {
+ const key = `${edge.source}-${edge.target}`
+ const group = edgeGroups.get(key)!
+ const groupIndex = group.indexOf(edge)
+ const groupSize = group.length
+ const curvature = groupSize > 1 ? (groupIndex - (groupSize - 1) / 2) * 0.2 : 0
+ return {
+ ...edge,
+ edgeLabel: edge.label,
+ curvature,
+ groupIndex,
+ groupSize
+ }
+ })
+ // Build node relationships (neighbors and links)
+ transformedEdges.forEach((link) => {
+ const sourceNode = nodeMap.get(link.source)
+ const targetNode = nodeMap.get(link.target)
+ if (sourceNode && targetNode) {
+ // Add neighbors
+ if (!sourceNode.neighbors.includes(targetNode)) {
+ sourceNode.neighbors.push(targetNode)
}
- return {
- nodes: transformedNodes,
- links: transformedEdges,
- };
- }, [nodes, edges, nodeColors, getSize, view]);
-
- // Retry initialization if graph data changes and actions aren't set up
- useEffect(() => {
- if (graphData.nodes.length > 0 && graphRef.current && !instanceId && !isGraphReadyRef.current) {
- // Small delay to ensure the graph has rendered
- const timeoutId = setTimeout(() => {
- if (graphRef.current && !isGraphReadyRef.current) {
- initializeGraph(graphRef.current);
- }
- }, 200);
- return () => clearTimeout(timeoutId);
+ if (!targetNode.neighbors.includes(sourceNode)) {
+ targetNode.neighbors.push(sourceNode)
}
- return undefined;
- }, [graphData.nodes.length, initializeGraph, instanceId]);
-
- // New function to determine which labels should be visible based on zoom and weight
- const handleShouldShowLabel = useCallback((nodeId: string, ctx: CanvasRenderingContext2D, globalScale: number) => {
- if (!showLabels || !labelRenderingCompound.current) return new Set<string>();
- const nodestoDisplay: string[] = [];
- // Min and max are actually dependant on the zoom level
- const zoom = Math.round(globalScale)
- const zoomCursor = Math.max(CONSTANTS.MIN_ZOOM, Math.min(CONSTANTS.MAX_ZOOM, zoom))
- const cursor = Math.round(zoomCursor * labelRenderingCompound.current.constants.nodesLength / (CONSTANTS.MAX_ZOOM))
- const min = Math.round(cursor - CONSTANTS.MAX_VISIBLE_LABELS)
- const max = Math.round(cursor + CONSTANTS.MAX_VISIBLE_LABELS)
- let i = 0;
- for (const id of labelRenderingCompound.current.weightList.keys()) {
- i++
- const thresholdReached = nodestoDisplay.length >= CONSTANTS.MAX_VISIBLE_LABELS
- if (thresholdReached) break;
- if (i >= min && i <= max) {
- nodestoDisplay.push(id);
- }
+ // Add links
+ sourceNode.links.push(link)
+ targetNode.links.push(link)
+ }
+ })
+ // feed the labelRenderingCompound
+ labelRenderingCompound.current.weightList = new Map(
+ transformedNodes
+ .sort((a, b) => b.neighbors.length - a.neighbors.length)
+ .map((node) => [node.id, node.neighbors.length])
+ )
+ labelRenderingCompound.current.constants = { nodesLength: transformedNodes.length }
+ // Handle hierarchy layout
+ if (view === 'hierarchy') {
+ const { nodes: nds, edges: eds } = getDagreLayoutedElements(
+ transformedNodes,
+ transformedEdges
+ )
+ return {
+ nodes: nds.map((nd) => ({
+ ...nd,
+ // Preserve the neighbors and links from the original transformed node
+ neighbors: nodeMap.get(nd.id)?.neighbors || [],
+ links: nodeMap.get(nd.id)?.links || []
+ })),
+ links: eds
+ }
+ }
+ return {
+ nodes: transformedNodes,
+ links: transformedEdges
+ }
+ }, [nodes, edges, nodeColors, getSize, view])
+
+ // Retry initialization if graph data changes and actions aren't set up
+ useEffect(() => {
+ if (graphData.nodes.length > 0 && graphRef.current && !instanceId && !isGraphReadyRef.current) {
+ // Small delay to ensure the graph has rendered
+ const timeoutId = setTimeout(() => {
+ if (graphRef.current && !isGraphReadyRef.current) {
+ initializeGraph(graphRef.current)
}
- // We compute the number of labels to show, making sure it doesn't reach the threshold
- return new Set<string>(nodestoDisplay).has(nodeId);
- }, [labelRenderingCompound.current, showLabels]);
-
- // Event handlers with proper memoization
- const handleNodeClick = useCallback((node: any, event: MouseEvent) => {
- onNodeClick?.(node, event);
- }, [onNodeClick]);
-
- const handleNodeRightClick = useCallback((node: any, event: MouseEvent) => {
- onNodeRightClick?.(node, event);
- }, [onNodeRightClick]);
-
- const handleBackgroundClick = useCallback(() => {
- onBackgroundClick?.();
- }, [onBackgroundClick]);
-
- const handleOpenNewAddItemDialog = useCallback(() => {
- setOpenMainDialog(true);
- }, [setOpenMainDialog]);
-
- // Throttled hover handlers to reduce excessive re-renders
- const handleNodeHover = useCallback((node: any) => {
- // Throttle hover updates to max 60fps
- const now = Date.now();
- if (now - lastRenderTimeRef.current < 16) { // ~60fps
- if (renderThrottleRef.current) {
- clearTimeout(renderThrottleRef.current);
- }
- renderThrottleRef.current = setTimeout(() => {
- handleNodeHover(node);
- }, 16) as any;
- return;
+ }, 200)
+ return () => clearTimeout(timeoutId)
+ }
+ return undefined
+ }, [graphData.nodes.length, initializeGraph, instanceId])
+
+ // New function to determine which labels should be visible based on zoom and weight
+ const handleShouldShowLabel = useCallback(
+ (nodeId: string, ctx: CanvasRenderingContext2D, globalScale: number) => {
+ if (!showLabels || !labelRenderingCompound.current) return new Set<string>()
+ const nodestoDisplay: string[] = []
+ // Min and max are actually dependant on the zoom level
+ const zoom = Math.round(globalScale)
+ const zoomCursor = Math.max(CONSTANTS.MIN_ZOOM, Math.min(CONSTANTS.MAX_ZOOM, zoom))
+ const cursor = Math.round(
+ (zoomCursor * labelRenderingCompound.current.constants.nodesLength) / CONSTANTS.MAX_ZOOM
+ )
+ const min = Math.round(cursor - CONSTANTS.MAX_VISIBLE_LABELS)
+ const max = Math.round(cursor + CONSTANTS.MAX_VISIBLE_LABELS)
+ let i = 0
+ for (const id of labelRenderingCompound.current.weightList.keys()) {
+ i++
+ const thresholdReached = nodestoDisplay.length >= CONSTANTS.MAX_VISIBLE_LABELS
+ if (thresholdReached) break
+ if (i >= min && i <= max) {
+ nodestoDisplay.push(id)
}
- lastRenderTimeRef.current = now;
- const newHighlightNodes = new Set<string>();
- const newHighlightLinks = new Set<string>();
- if (node) {
- // Add the hovered node
- newHighlightNodes.add(node.id);
- // Add connected nodes and links
- if (node.neighbors) {
- node.neighbors.forEach((neighbor: any) => {
- newHighlightNodes.add(neighbor.id);
- });
- }
- if (node.links) {
- node.links.forEach((link: any) => {
- newHighlightLinks.add(`${link.source.id}-${link.target.id}`);
- });
+ }
+ // We compute the number of labels to show, making sure it doesn't reach the threshold
+ return new Set<string>(nodestoDisplay).has(nodeId)
+ },
+ [labelRenderingCompound.current, showLabels]
+ )
+
+ // Event handlers with proper memoization
+ const handleNodeClick = useCallback(
+ (node: any, event: MouseEvent) => {
+ onNodeClick?.(node, event)
+ },
+ [onNodeClick]
+ )
+
+ const handleNodeRightClick = useCallback(
+ (node: any, event: MouseEvent) => {
+ onNodeRightClick?.(node, event)
+ },
+ [onNodeRightClick]
+ )
+
+ const handleBackgroundClick = useCallback(() => {
+ onBackgroundClick?.()
+ }, [onBackgroundClick])
+
+ const handleOpenNewAddItemDialog = useCallback(() => {
+ setOpenMainDialog(true)
+ }, [setOpenMainDialog])
+
+ // Throttled hover handlers to reduce excessive re-renders
+ const handleNodeHover = useCallback((node: any) => {
+ // Throttle hover updates to max 60fps
+ const now = Date.now()
+ if (now - lastRenderTimeRef.current < 16) {
+ // ~60fps
+ if (renderThrottleRef.current) {
+ clearTimeout(renderThrottleRef.current)
+ }
+ renderThrottleRef.current = setTimeout(() => {
+ handleNodeHover(node)
+ }, 16) as any
+ return
+ }
+ lastRenderTimeRef.current = now
+ const newHighlightNodes = new Set<string>()
+ const newHighlightLinks = new Set<string>()
+ if (node) {
+ // Add the hovered node
+ newHighlightNodes.add(node.id)
+ // Add connected nodes and links
+ if (node.neighbors) {
+ node.neighbors.forEach((neighbor: any) => {
+ newHighlightNodes.add(neighbor.id)
+ })
+ }
+ if (node.links) {
+ node.links.forEach((link: any) => {
+ newHighlightLinks.add(`${link.source.id}-${link.target.id}`)
+ })
+ }
+ setHoverNode(node.id)
+ } else {
+ setHoverNode(null)
+ }
+ setHighlightNodes(newHighlightNodes)
+ setHighlightLinks(newHighlightLinks)
+ }, [])
+
+ // Enhanced node hover with tooltip
+ const handleNodeHoverWithTooltip = useCallback(
+ (node: any) => {
+ if (node) {
+ const weight = node.neighbors?.length || 0
+ const label = node.nodeLabel || node.label || node.id
+ // Position tooltip above the node using the graph's coordinate conversion
+ if (graphRef.current) {
+ try {
+ // Use the graph's built-in method to convert graph coordinates to screen coordinates
+ const screenCoords = graphRef.current.graph2ScreenCoords(node.x, node.y)
+ // Ensure tooltip stays within viewport bounds
+ const tooltipWidth = 120 // Approximate tooltip width
+ const tooltipHeight = 60 // Approximate tooltip height
+ let x = screenCoords.x
+ let y = screenCoords.y - 30 // Position above the node
+ // Adjust X position if tooltip would go off-screen
+ if (x + tooltipWidth > window.innerWidth) {
+ x = window.innerWidth - tooltipWidth - 10
}
- setHoverNode(node.id);
- } else {
- setHoverNode(null);
- }
- setHighlightNodes(newHighlightNodes);
- setHighlightLinks(newHighlightLinks);
- }, []);
-
- // Enhanced node hover with tooltip
- const handleNodeHoverWithTooltip = useCallback((node: any) => {
- if (node) {
- const weight = node.neighbors?.length || 0;
- const label = node.nodeLabel || node.label || node.id;
- // Position tooltip above the node using the graph's coordinate conversion
- if (graphRef.current) {
- try {
- // Use the graph's built-in method to convert graph coordinates to screen coordinates
- const screenCoords = graphRef.current.graph2ScreenCoords(node.x, node.y);
- // Ensure tooltip stays within viewport bounds
- const tooltipWidth = 120; // Approximate tooltip width
- const tooltipHeight = 60; // Approximate tooltip height
- let x = screenCoords.x;
- let y = screenCoords.y - 30; // Position above the node
- // Adjust X position if tooltip would go off-screen
- if (x + tooltipWidth > window.innerWidth) {
- x = window.innerWidth - tooltipWidth - 10;
- }
- if (x < 10) {
- x = 10;
- }
- // Adjust Y position if tooltip would go off-screen
- if (y < tooltipHeight + 10) {
- y = screenCoords.y + 100; // Position below the node instead
- }
- setTooltip({
- x,
- y,
- data: {
- label,
- type: node.data.type,
- connections: weight
- },
- visible: true
- });
- } catch (error) {
- // Fallback: hide tooltip if coordinate conversion fails
- setTooltip(prev => ({ ...prev, visible: false }));
- }
+ if (x < 10) {
+ x = 10
}
- } else {
- setTooltip(prev => ({ ...prev, visible: false }));
- }
- handleNodeHover(node);
- }, [handleNodeHover]);
-
- const handleLinkHover = useCallback((link: any) => {
- // Throttle hover updates to max 60fps
- const now = Date.now();
- if (now - lastRenderTimeRef.current < 16) { // ~60fps
- if (renderThrottleRef.current) {
- clearTimeout(renderThrottleRef.current);
+ // Adjust Y position if tooltip would go off-screen
+ if (y < tooltipHeight + 10) {
+ y = screenCoords.y + 100 // Position below the node instead
}
- renderThrottleRef.current = setTimeout(() => {
- handleLinkHover(link);
- }, 16) as any;
- return;
+ setTooltip({
+ x,
+ y,
+ data: {
+ label,
+ type: node.data.type,
+ connections: weight
+ },
+ visible: true
+ })
+ } catch (error) {
+ // Fallback: hide tooltip if coordinate conversion fails
+ setTooltip((prev) => ({ ...prev, visible: false }))
+ }
}
- lastRenderTimeRef.current = now;
- const newHighlightNodes = new Set<string>();
- const newHighlightLinks = new Set<string>();
- if (link) {
- // Add the hovered link
- newHighlightLinks.add(`${link.source}-${link.target}`);
- // Add connected nodes
- newHighlightNodes.add(link.source.id);
- newHighlightNodes.add(link.target.id);
- }
- setHoverNode(null);
- setHighlightNodes(newHighlightNodes);
- setHighlightLinks(newHighlightLinks);
- }, []);
-
- // Optimized node rendering with proper icon caching
- const renderNode = useCallback((node: any, ctx: CanvasRenderingContext2D, globalScale: number) => {
- const shouldUseSimpleRendering = nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || globalScale < 1.5
- const size = Math.min((node.nodeSize + node.neighbors.length / 5), 20) * (forceSettings.nodeSize.value / 100 + .4);
- node.val = size / 5
- const isHighlighted = highlightNodes.has(node.id) || isSelected(node.id);
- const hasAnyHighlight = highlightNodes.size > 0 || highlightLinks.size > 0;
- const isHovered = hoverNode === node.id || (isCurrent(node.id));
- // Draw highlight ring for highlighted nodes
- if (isHighlighted) {
- ctx.beginPath();
- ctx.arc(node.x, node.y, size * 1.2, 0, 2 * Math.PI);
- ctx.fillStyle = isHovered ? GRAPH_COLORS.NODE_HIGHLIGHT_HOVER : GRAPH_COLORS.NODE_HIGHLIGHT_DEFAULT;
- ctx.fill();
+ } else {
+ setTooltip((prev) => ({ ...prev, visible: false }))
+ }
+ handleNodeHover(node)
+ },
+ [handleNodeHover]
+ )
+
+ const handleLinkHover = useCallback((link: any) => {
+ // Throttle hover updates to max 60fps
+ const now = Date.now()
+ if (now - lastRenderTimeRef.current < 16) {
+ // ~60fps
+ if (renderThrottleRef.current) {
+ clearTimeout(renderThrottleRef.current)
+ }
+ renderThrottleRef.current = setTimeout(() => {
+ handleLinkHover(link)
+ }, 16) as any
+ return
+ }
+ lastRenderTimeRef.current = now
+ const newHighlightNodes = new Set<string>()
+ const newHighlightLinks = new Set<string>()
+ if (link) {
+ // Add the hovered link
+ newHighlightLinks.add(`${link.source}-${link.target}`)
+ // Add connected nodes
+ newHighlightNodes.add(link.source.id)
+ newHighlightNodes.add(link.target.id)
+ }
+ setHoverNode(null)
+ setHighlightNodes(newHighlightNodes)
+ setHighlightLinks(newHighlightLinks)
+ }, [])
+
+ // Optimized node rendering with proper icon caching
+ const renderNode = useCallback(
+ (node: any, ctx: CanvasRenderingContext2D, globalScale: number) => {
+ const shouldUseSimpleRendering =
+ nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || globalScale < 1.5
+ const size =
+ Math.min(node.nodeSize + node.neighbors.length / 5, 20) *
+ (forceSettings.nodeSize.value / 100 + 0.4)
+ node.val = size / 5
+ const isHighlighted = highlightNodes.has(node.id) || isSelected(node.id)
+ const hasAnyHighlight = highlightNodes.size > 0 || highlightLinks.size > 0
+ const isHovered = hoverNode === node.id || isCurrent(node.id)
+ // Draw highlight ring for highlighted nodes
+ if (isHighlighted) {
+ ctx.beginPath()
+ ctx.arc(node.x, node.y, size * 1.2, 0, 2 * Math.PI)
+ ctx.fillStyle = isHovered
+ ? GRAPH_COLORS.NODE_HIGHLIGHT_HOVER
+ : GRAPH_COLORS.NODE_HIGHLIGHT_DEFAULT
+ ctx.fill()
+ }
+ // Set node color based on highlight state
+ if (hasAnyHighlight) {
+ ctx.fillStyle = isHighlighted ? node.nodeColor : `${node.nodeColor}7D`
+ } else {
+ ctx.fillStyle = node.nodeColor
+ }
+ ctx.beginPath()
+ ctx.arc(node.x, node.y, size, 0, 2 * Math.PI)
+ ctx.fill()
+ // Early exit for simple rendering
+ if (shouldUseSimpleRendering && !isHovered) return
+ // Optimized icon rendering with cached images
+ if (showIcons && node.nodeType) {
+ const cachedImage = imageCache.get(node.nodeType)
+ if (cachedImage && cachedImage.complete) {
+ try {
+ ctx.drawImage(cachedImage, node.x - size / 2, node.y - size / 2, size, size)
+ } catch (error) {
+ // Silently handle drawing errors
+ }
}
- // Set node color based on highlight state
- if (hasAnyHighlight) {
- ctx.fillStyle = isHighlighted ? node.nodeColor : `${node.nodeColor}7D`;
- } else {
- ctx.fillStyle = node.nodeColor;
+ }
+ // Optimized label rendering with layered display
+ if (showLabels) {
+ const label = truncateText(node.nodeLabel || node.label || node.id, 58)
+ if (label) {
+ // Check if this node's label should be visible in current layer
+ const shouldShowLabel = handleShouldShowLabel(node.id, ctx, globalScale)
+ // Always show labels for highlighted nodes
+ if (!shouldShowLabel && !isHighlighted) {
+ return
+ }
+ const fontSize = Math.max(
+ CONSTANTS.MIN_FONT_SIZE,
+ (CONSTANTS.NODE_FONT_SIZE * (size / 2)) / globalScale
+ )
+ ctx.font = `${fontSize}px Sans-Serif`
+ const bgHeight = fontSize + 2
+ const bgY = node.y + size / 2 + 1
+ const color = theme === 'light' ? GRAPH_COLORS.TEXT_LIGHT : GRAPH_COLORS.TEXT_DARK
+ ctx.textAlign = 'center'
+ ctx.textBaseline = 'middle'
+ if (isHighlighted) {
+ ctx.fillStyle = color
+ } else {
+ ctx.fillStyle = `${color}4D` // 30% opacity
+ }
+ ctx.fillText(label, node.x, bgY + bgHeight / 2)
}
- ctx.beginPath();
- ctx.arc(node.x, node.y, size, 0, 2 * Math.PI);
- ctx.fill();
- // Early exit for simple rendering
- if (shouldUseSimpleRendering && !isHovered) return;
- // Optimized icon rendering with cached images
- if (showIcons && node.nodeType) {
- const cachedImage = imageCache.get(node.nodeType);
- if (cachedImage && cachedImage.complete) {
- try {
- ctx.drawImage(cachedImage, node.x - size / 2, node.y - size / 2, size, size);
- } catch (error) {
- // Silently handle drawing errors
- }
- }
+ }
+ },
+ [
+ forceSettings,
+ showLabels,
+ showIcons,
+ isCurrent,
+ isSelected,
+ theme,
+ highlightNodes,
+ highlightLinks,
+ hoverNode
+ ]
+ )
+
+ const renderLink = useCallback(
+ (link: any, ctx: CanvasRenderingContext2D, globalScale: number) => {
+ const { source: start, target: end } = link
+ if (typeof start !== 'object' || typeof end !== 'object') return
+ const shouldUseSimpleRendering =
+ nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || globalScale < 1.5
+ const linkKey = `${start.id}-${end.id}`
+ const isHighlighted = highlightLinks.has(linkKey)
+ const hasAnyHighlight = highlightNodes.size > 0 || highlightLinks.size > 0
+ let strokeStyle: string
+ let lineWidth: number
+ let fillStyle: string
+ if (isHighlighted) {
+ strokeStyle = GRAPH_COLORS.LINK_HIGHLIGHTED
+ fillStyle = GRAPH_COLORS.LINK_HIGHLIGHTED
+ lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 3)
+ } else if (hasAnyHighlight) {
+ strokeStyle = GRAPH_COLORS.LINK_DIMMED
+ fillStyle = GRAPH_COLORS.LINK_DIMMED
+ lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 5)
+ } else {
+ strokeStyle = GRAPH_COLORS.LINK_DEFAULT
+ fillStyle = GRAPH_COLORS.LINK_DEFAULT
+ lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 5)
+ }
+ // Draw connection line (use quadratic curve if curvature present)
+ const curvature: number = link.curvature || 0
+ const dx = end.x - start.x
+ const dy = end.y - start.y
+ const distance = Math.sqrt(dx * dx + dy * dy) || 1
+ const midX = (start.x + end.x) * 0.5
+ const midY = (start.y + end.y) * 0.5
+ const normX = -dy / distance
+ const normY = dx / distance
+ const offset = curvature * distance
+ const ctrlX = midX + normX * offset
+ const ctrlY = midY + normY * offset
+ ctx.beginPath()
+ ctx.moveTo(start.x, start.y)
+ if (curvature !== 0) {
+ ctx.quadraticCurveTo(ctrlX, ctrlY, end.x, end.y)
+ } else {
+ ctx.lineTo(end.x, end.y)
+ }
+ ctx.strokeStyle = strokeStyle
+ ctx.lineWidth = lineWidth
+ ctx.stroke()
+ // Draw directional arrow
+ const arrowLength = forceSettings.linkDirectionalArrowLength.value
+ if (arrowLength && arrowLength > 0) {
+ const arrowRelPos = forceSettings.linkDirectionalArrowRelPos.value || 1
+ // Helper to get point and tangent along straight/curved link
+ const bezierPoint = (t: number) => {
+ if (curvature === 0) {
+ return { x: start.x + dx * t, y: start.y + dy * t }
+ }
+ const oneMinusT = 1 - t
+ return {
+ x: oneMinusT * oneMinusT * start.x + 2 * oneMinusT * t * ctrlX + t * t * end.x,
+ y: oneMinusT * oneMinusT * start.y + 2 * oneMinusT * t * ctrlY + t * t * end.y
+ }
}
- // Optimized label rendering with layered display
- if (showLabels) {
- const label = truncateText(node.nodeLabel || node.label || node.id, 58);
- if (label) {
- // Check if this node's label should be visible in current layer
- const shouldShowLabel = handleShouldShowLabel(node.id, ctx, globalScale);
- // Always show labels for highlighted nodes
- if (!shouldShowLabel && !isHighlighted) {
- return;
- }
- const fontSize = Math.max(CONSTANTS.MIN_FONT_SIZE, CONSTANTS.NODE_FONT_SIZE * (size / 2) / globalScale);
- ctx.font = `${fontSize}px Sans-Serif`;
- const bgHeight = fontSize + 2;
- const bgY = node.y + size / 2 + 1;
- const color = theme === "light" ? GRAPH_COLORS.TEXT_LIGHT : GRAPH_COLORS.TEXT_DARK;
- ctx.textAlign = 'center';
- ctx.textBaseline = 'middle';
- if (isHighlighted) {
- ctx.fillStyle = color;
- } else {
- ctx.fillStyle = `${color}4D`; // 30% opacity
- }
- ctx.fillText(label, node.x, bgY + bgHeight / 2);
- }
+ const bezierTangent = (t: number) => {
+ if (curvature === 0) {
+ return { x: dx, y: dy }
+ }
+ const oneMinusT = 1 - t
+ return {
+ x: 2 * oneMinusT * (ctrlX - start.x) + 2 * t * (end.x - ctrlX),
+ y: 2 * oneMinusT * (ctrlY - start.y) + 2 * t * (end.y - ctrlY)
+ }
}
- }, [forceSettings, showLabels, showIcons, isCurrent, isSelected, theme, highlightNodes, highlightLinks, hoverNode]);
-
- const renderLink = useCallback((link: any, ctx: CanvasRenderingContext2D, globalScale: number) => {
- const { source: start, target: end } = link;
- if (typeof start !== 'object' || typeof end !== 'object') return;
- const shouldUseSimpleRendering = nodes.length > CONSTANTS.NODE_COUNT_THRESHOLD || globalScale < 1.5
- const linkKey = `${start.id}-${end.id}`;
- const isHighlighted = highlightLinks.has(linkKey);
- const hasAnyHighlight = highlightNodes.size > 0 || highlightLinks.size > 0;
- let strokeStyle: string;
- let lineWidth: number;
- let fillStyle: string;
- if (isHighlighted) {
- strokeStyle = GRAPH_COLORS.LINK_HIGHLIGHTED;
- fillStyle = GRAPH_COLORS.LINK_HIGHLIGHTED;
- lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 3);
- } else if (hasAnyHighlight) {
- strokeStyle = GRAPH_COLORS.LINK_DIMMED;
- fillStyle = GRAPH_COLORS.LINK_DIMMED;
- lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 5);
- } else {
- strokeStyle = GRAPH_COLORS.LINK_DEFAULT;
- fillStyle = GRAPH_COLORS.LINK_DEFAULT;
- lineWidth = CONSTANTS.LINK_WIDTH * (forceSettings.linkWidth.value / 5);
+ const t = arrowRelPos
+ let { x: arrowX, y: arrowY } = bezierPoint(t)
+ if (arrowRelPos === 1) {
+ const tan = bezierTangent(0.99)
+ const tanLen = Math.hypot(tan.x, tan.y) || 1
+ const targetNodeSize =
+ (end.nodeSize || CONSTANTS.NODE_DEFAULT_SIZE) *
+ (forceSettings.nodeSize.value / 100 + 0.4)
+ arrowX = end.x - (tan.x / tanLen) * targetNodeSize
+ arrowY = end.y - (tan.y / tanLen) * targetNodeSize
}
- // Draw connection line (use quadratic curve if curvature present)
- const curvature: number = link.curvature || 0;
- const dx = end.x - start.x;
- const dy = end.y - start.y;
- const distance = Math.sqrt(dx * dx + dy * dy) || 1;
- const midX = (start.x + end.x) * 0.5;
- const midY = (start.y + end.y) * 0.5;
- const normX = -dy / distance;
- const normY = dx / distance;
- const offset = curvature * distance;
- const ctrlX = midX + normX * offset;
- const ctrlY = midY + normY * offset;
- ctx.beginPath();
- ctx.moveTo(start.x, start.y);
- if (curvature !== 0) {
- ctx.quadraticCurveTo(ctrlX, ctrlY, end.x, end.y);
+ const tan = bezierTangent(t)
+ const angle = Math.atan2(tan.y, tan.x)
+ // Draw arrow head
+ ctx.save()
+ ctx.translate(arrowX, arrowY)
+ ctx.rotate(angle)
+ ctx.beginPath()
+ ctx.moveTo(0, 0)
+ ctx.lineTo(-arrowLength, -arrowLength * 0.5)
+ ctx.lineTo(-arrowLength, arrowLength * 0.5)
+ ctx.closePath()
+ ctx.fillStyle = fillStyle
+ ctx.fill()
+ ctx.restore()
+ }
+ // Early exit for simple rendering or no label
+ if (shouldUseSimpleRendering || !link.label) return
+ // Only show labels for highlighted links when there's any highlighting
+ if (isHighlighted) {
+ // Calculate label position and angle along straight/curved link
+ let textAngle: number
+ if ((link.curvature || 0) !== 0) {
+ // Bezier midpoint and tangent at t=0.5
+ const t = 0.5
+ const oneMinusT = 1 - t
+ tempPos.x = oneMinusT * oneMinusT * start.x + 2 * oneMinusT * t * ctrlX + t * t * end.x
+ tempPos.y = oneMinusT * oneMinusT * start.y + 2 * oneMinusT * t * ctrlY + t * t * end.y
+ const tx = 2 * oneMinusT * (ctrlX - start.x) + 2 * t * (end.x - ctrlX)
+ const ty = 2 * oneMinusT * (ctrlY - start.y) + 2 * t * (end.y - ctrlY)
+ textAngle = Math.atan2(ty, tx)
} else {
- ctx.lineTo(end.x, end.y);
+ tempPos.x = (start.x + end.x) * 0.5
+ tempPos.y = (start.y + end.y) * 0.5
+ const sdx = end.x - start.x
+ const sdy = end.y - start.y
+ textAngle = Math.atan2(sdy, sdx)
}
- ctx.strokeStyle = strokeStyle;
- ctx.lineWidth = lineWidth;
- ctx.stroke();
- // Draw directional arrow
- const arrowLength = forceSettings.linkDirectionalArrowLength.value;
- if (arrowLength && arrowLength > 0) {
- const arrowRelPos = forceSettings.linkDirectionalArrowRelPos.value || 1;
- // Helper to get point and tangent along straight/curved link
- const bezierPoint = (t: number) => {
- if (curvature === 0) {
- return { x: start.x + dx * t, y: start.y + dy * t };
- }
- const oneMinusT = 1 - t;
- return {
- x: oneMinusT * oneMinusT * start.x + 2 * oneMinusT * t * ctrlX + t * t * end.x,
- y: oneMinusT * oneMinusT * start.y + 2 * oneMinusT * t * ctrlY + t * t * end.y,
- };
- };
- const bezierTangent = (t: number) => {
- if (curvature === 0) {
- return { x: dx, y: dy };
- }
- const oneMinusT = 1 - t;
- return {
- x: 2 * oneMinusT * (ctrlX - start.x) + 2 * t * (end.x - ctrlX),
- y: 2 * oneMinusT * (ctrlY - start.y) + 2 * t * (end.y - ctrlY),
- };
- };
- let t = arrowRelPos;
- let { x: arrowX, y: arrowY } = bezierPoint(t);
- if (arrowRelPos === 1) {
- const tan = bezierTangent(0.99);
- const tanLen = Math.hypot(tan.x, tan.y) || 1;
- const targetNodeSize = (end.nodeSize || CONSTANTS.NODE_DEFAULT_SIZE) * (forceSettings.nodeSize.value / 100 + 0.4);
- arrowX = end.x - (tan.x / tanLen) * targetNodeSize;
- arrowY = end.y - (tan.y / tanLen) * targetNodeSize;
- }
- const tan = bezierTangent(t);
- const angle = Math.atan2(tan.y, tan.x);
- // Draw arrow head
- ctx.save();
- ctx.translate(arrowX, arrowY);
- ctx.rotate(angle);
- ctx.beginPath();
- ctx.moveTo(0, 0);
- ctx.lineTo(-arrowLength, -arrowLength * 0.5);
- ctx.lineTo(-arrowLength, arrowLength * 0.5);
- ctx.closePath();
- ctx.fillStyle = fillStyle;
- ctx.fill();
- ctx.restore();
+ // Flip text for readability
+ if (textAngle > CONSTANTS.HALF_PI || textAngle < -CONSTANTS.HALF_PI) {
+ textAngle += textAngle > 0 ? -CONSTANTS.PI : CONSTANTS.PI
}
- // Early exit for simple rendering or no label
- if (shouldUseSimpleRendering || !link.label) return;
- // Only show labels for highlighted links when there's any highlighting
- if (isHighlighted) {
- // Calculate label position and angle along straight/curved link
- let textAngle: number;
- if ((link.curvature || 0) !== 0) {
- // Bezier midpoint and tangent at t=0.5
- const t = 0.5;
- const oneMinusT = 1 - t;
- tempPos.x = oneMinusT * oneMinusT * start.x + 2 * oneMinusT * t * ctrlX + t * t * end.x;
- tempPos.y = oneMinusT * oneMinusT * start.y + 2 * oneMinusT * t * ctrlY + t * t * end.y;
- const tx = 2 * oneMinusT * (ctrlX - start.x) + 2 * t * (end.x - ctrlX);
- const ty = 2 * oneMinusT * (ctrlY - start.y) + 2 * t * (end.y - ctrlY);
- textAngle = Math.atan2(ty, tx);
- } else {
- tempPos.x = (start.x + end.x) * 0.5;
- tempPos.y = (start.y + end.y) * 0.5;
- const sdx = end.x - start.x;
- const sdy = end.y - start.y;
- textAngle = Math.atan2(sdy, sdx);
- }
- // Flip text for readability
- if (textAngle > CONSTANTS.HALF_PI || textAngle < -CONSTANTS.HALF_PI) {
- textAngle += textAngle > 0 ? -CONSTANTS.PI : CONSTANTS.PI;
- }
- // Measure and draw label
- ctx.font = LABEL_FONT_STRING;
- const textWidth = ctx.measureText(link.label).width;
- const padding = CONSTANTS.LABEL_FONT_SIZE * CONSTANTS.PADDING_RATIO;
- tempDimensions[0] = textWidth + padding;
- tempDimensions[1] = CONSTANTS.LABEL_FONT_SIZE + padding;
- const halfWidth = tempDimensions[0] * 0.5;
- const halfHeight = tempDimensions[1] * 0.5;
- // Batch canvas operations
- ctx.save();
- ctx.translate(tempPos.x, tempPos.y);
- ctx.rotate(textAngle);
- // Background
- ctx.fillStyle = theme === "light" ? GRAPH_COLORS.BACKGROUND_LIGHT : GRAPH_COLORS.BACKGROUND_DARK;
- ctx.fillRect(-halfWidth, -halfHeight, tempDimensions[0], tempDimensions[1]);
- // Text - follow same highlighting behavior as links
- ctx.fillStyle = isHighlighted ? GRAPH_COLORS.LINK_LABEL_HIGHLIGHTED : GRAPH_COLORS.LINK_LABEL_DEFAULT;
- ctx.textAlign = 'center';
- ctx.textBaseline = 'middle';
- ctx.fillText(link.label, 0, 0);
- ctx.restore();
- }
- }, [forceSettings, theme, highlightLinks, highlightNodes]);
-
- // Restart simulation when settings change (debounced)
- useEffect(() => {
- let settingsTimeout: number | undefined;
- const restartSimulation = () => {
- if (graphRef.current && isGraphReadyRef.current) {
- if (settingsTimeout) clearTimeout(settingsTimeout);
- settingsTimeout = setTimeout(() => {
- graphRef.current?.d3ReheatSimulation();
- }, 100) as any; // Debounce settings changes
- }
- };
- // Restart simulation when force settings change
- restartSimulation();
- return () => {
- if (settingsTimeout) clearTimeout(settingsTimeout);
- };
- }, [forceSettings]);
-
- // Clear highlights when graph data changes
- useEffect(() => {
- setHighlightNodes(new Set());
- setHighlightLinks(new Set());
- setHoverNode(null);
- }, [nodes, edges]);
-
- // Cleanup throttle timeouts
- useEffect(() => {
- return () => {
- if (renderThrottleRef.current) {
- clearTimeout(renderThrottleRef.current);
- }
- };
- }, []);
-
- // Empty state
- if (!nodes.length) {
- return (
- <div
- ref={containerRef}
- className={`flex h-full w-full items-center justify-center ${className}`}
- style={style}
- >
- <div className="text-center text-muted-foreground max-w-md mx-auto p-6">
- <div className="mb-4">
- <svg
- className="mx-auto h-16 w-16 text-muted-foreground/50"
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.5}
- d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
- />
- </svg>
- </div>
- <h3 className="text-lg font-semibold text-foreground mb-2">
- No data to visualize
- </h3>
- <p className="text-sm text-muted-foreground mb-4">
- Start your investigation by adding nodes to see them displayed in the graph view.
- </p>
- <div className="space-y-2 text-xs text-muted-foreground mb-6">
- <p><strong>Tip:</strong> Use the search bar to find entities or import data to get started</p>
- <p><strong>Explore:</strong> Try searching for domains, emails, or other entities</p>
- <p><strong>Labels:</strong> Zoom in to see node labels progressively by connection weight</p>
- </div>
- <Button onClick={handleOpenNewAddItemDialog}>
- <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
- </svg>
- Add your first item
- </Button>
- </div>
- </div>
- );
+ // Measure and draw label
+ ctx.font = LABEL_FONT_STRING
+ const textWidth = ctx.measureText(link.label).width
+ const padding = CONSTANTS.LABEL_FONT_SIZE * CONSTANTS.PADDING_RATIO
+ tempDimensions[0] = textWidth + padding
+ tempDimensions[1] = CONSTANTS.LABEL_FONT_SIZE + padding
+ const halfWidth = tempDimensions[0] * 0.5
+ const halfHeight = tempDimensions[1] * 0.5
+ // Batch canvas operations
+ ctx.save()
+ ctx.translate(tempPos.x, tempPos.y)
+ ctx.rotate(textAngle)
+ // Background
+ ctx.fillStyle =
+ theme === 'light' ? GRAPH_COLORS.BACKGROUND_LIGHT : GRAPH_COLORS.BACKGROUND_DARK
+ ctx.fillRect(-halfWidth, -halfHeight, tempDimensions[0], tempDimensions[1])
+ // Text - follow same highlighting behavior as links
+ ctx.fillStyle = isHighlighted
+ ? GRAPH_COLORS.LINK_LABEL_HIGHLIGHTED
+ : GRAPH_COLORS.LINK_LABEL_DEFAULT
+ ctx.textAlign = 'center'
+ ctx.textBaseline = 'middle'
+ ctx.fillText(link.label, 0, 0)
+ ctx.restore()
+ }
+ },
+ [forceSettings, theme, highlightLinks, highlightNodes]
+ )
+
+ // Restart simulation when settings change (debounced)
+ useEffect(() => {
+ let settingsTimeout: number | undefined
+ const restartSimulation = () => {
+ if (graphRef.current && isGraphReadyRef.current) {
+ if (settingsTimeout) clearTimeout(settingsTimeout)
+ settingsTimeout = setTimeout(() => {
+ graphRef.current?.d3ReheatSimulation()
+ }, 100) as any // Debounce settings changes
+ }
+ }
+ // Restart simulation when force settings change
+ restartSimulation()
+ return () => {
+ if (settingsTimeout) clearTimeout(settingsTimeout)
+ }
+ }, [forceSettings])
+
+ // Clear highlights when graph data changes
+ useEffect(() => {
+ setHighlightNodes(new Set())
+ setHighlightLinks(new Set())
+ setHoverNode(null)
+ }, [nodes, edges])
+
+ // Cleanup throttle timeouts
+ useEffect(() => {
+ return () => {
+ if (renderThrottleRef.current) {
+ clearTimeout(renderThrottleRef.current)
+ }
}
+ }, [])
+ // Empty state
+ if (!nodes.length) {
return (
+ <div
+ ref={containerRef}
+ className={`flex h-full w-full items-center justify-center ${className}`}
+ style={style}
+ >
+ <div className="text-center text-muted-foreground max-w-md mx-auto p-6">
+ <div className="mb-4">
+ <svg
+ className="mx-auto h-16 w-16 text-muted-foreground/50"
+ fill="none"
+ viewBox="0 0 24 24"
+ stroke="currentColor"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={1.5}
+ d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
+ />
+ </svg>
+ </div>
+ <h3 className="text-lg font-semibold text-foreground mb-2">No data to visualize</h3>
+ <p className="text-sm text-muted-foreground mb-4">
+ Start your investigation by adding nodes to see them displayed in the graph view.
+ </p>
+ <div className="space-y-2 text-xs text-muted-foreground mb-6">
+ <p>
+ <strong>Tip:</strong> Use the search bar to find entities or import data to get
+ started
+ </p>
+ <p>
+ <strong>Explore:</strong> Try searching for domains, emails, or other entities
+ </p>
+ <p>
+ <strong>Labels:</strong> Zoom in to see node labels progressively by connection weight
+ </p>
+ </div>
+ <Button onClick={handleOpenNewAddItemDialog}>
+ <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 6v6m0 0v6m0-6h6m-6 0H6"
+ />
+ </svg>
+ Add your first item
+ </Button>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div
+ ref={containerRef}
+ className={className}
+ data-graph-container
+ style={{
+ width: '100%',
+ height: '100%',
+ minHeight: '100%',
+ minWidth: '100%',
+ position: 'relative',
+ ...style
+ }}
+ >
+ {tooltip.visible && (
<div
- ref={containerRef}
- className={className}
- data-graph-container
- style={{
- width: '100%',
- height: '100%',
- minHeight: "100%",
- minWidth: "100%",
- position: 'relative',
- ...style
- }}
+ className="absolute z-20 bg-background border rounded-lg p-2 shadow-lg text-xs pointer-events-none"
+ style={{
+ left: tooltip.x,
+ top: tooltip.y,
+ transform: 'translate(-50%, -100%)' // Center horizontally on the node
+ }}
>
- {tooltip.visible && (
- <div
- className="absolute z-20 bg-background border rounded-lg p-2 shadow-lg text-xs pointer-events-none"
- style={{
- left: tooltip.x,
- top: tooltip.y,
- transform: 'translate(-50%, -100%)' // Center horizontally on the node
- }}
- >
- <div className="whitespace-pre-line truncate flex flex-col gap-1">
- <span className='text-md font-semibold'>{tooltip.data?.label}</span>
- <span className='flex items-center gap-1'><span className='flex items-center gap-1 opacity-60'><Type className='h-3 w-3' /> type:</span> <span className='font-medium'>{tooltip.data?.type}</span></span>
- <span className='flex items-center gap-1'><span className='flex items-center gap-1 opacity-60'><Share2 className='h-3 w-3' /> connections:</span> <span className='font-medium'>{tooltip.data?.connections}</span></span>
- </div>
- </div >
- )}
- <ForceGraph2D
- ref={graphRef}
- width={containerSize.width}
- height={containerSize.height}
- graphData={graphData}
- nodeLabel={() => ''}
- // nodeColor={node => shouldUseSimpleRendering ? node.nodeColor : GRAPH_COLORS.TRANSPARENT}
- nodeRelSize={6}
- onNodeRightClick={handleNodeRightClick}
- onNodeClick={handleNodeClick}
- onBackgroundClick={handleBackgroundClick}
- linkCurvature={link => link.curvature || 0}
- nodeCanvasObject={renderNode}
- onNodeDragEnd={(node => {
- node.fx = node.x;
- node.fy = node.y;
- })}
- cooldownTicks={view === "hierarchy" ? 0 : forceSettings.cooldownTicks.value}
- cooldownTime={forceSettings.cooldownTime.value}
- d3AlphaDecay={forceSettings.d3AlphaDecay.value}
- d3AlphaMin={forceSettings.d3AlphaMin.value}
- d3VelocityDecay={forceSettings.d3VelocityDecay.value}
- warmupTicks={forceSettings.warmupTicks.value}
- dagLevelDistance={forceSettings.dagLevelDistance.value}
- backgroundColor={backgroundColor}
- onZoom={handleZoom}
- onZoomEnd={handleZoom}
- linkCanvasObject={renderLink}
- enableNodeDrag={!shouldUseSimpleRendering}
- autoPauseRedraw={true}
- onNodeHover={handleNodeHoverWithTooltip}
- onLinkHover={handleLinkHover}
- />
- {allowLasso && isLassoActive && <Lasso nodes={graphData.nodes} graph2ScreenCoords={graph2ScreenCoords} partial={true} width={containerSize.width}
- height={containerSize.height} />}
- {/* {minimap && graphData.nodes &&
+ <div className="whitespace-pre-line truncate flex flex-col gap-1">
+ <span className="text-md font-semibold">{tooltip.data?.label}</span>
+ <span className="flex items-center gap-1">
+ <span className="flex items-center gap-1 opacity-60">
+ <Type className="h-3 w-3" /> type:
+ </span>{' '}
+ <span className="font-medium">{tooltip.data?.type}</span>
+ </span>
+ <span className="flex items-center gap-1">
+ <span className="flex items-center gap-1 opacity-60">
+ <Share2 className="h-3 w-3" /> connections:
+ </span>{' '}
+ <span className="font-medium">{tooltip.data?.connections}</span>
+ </span>
+ </div>
+ </div>
+ )}
+ <ForceGraph2D
+ ref={graphRef}
+ width={containerSize.width}
+ height={containerSize.height}
+ graphData={graphData}
+ nodeLabel={() => ''}
+ // nodeColor={node => shouldUseSimpleRendering ? node.nodeColor : GRAPH_COLORS.TRANSPARENT}
+ nodeRelSize={6}
+ onNodeRightClick={handleNodeRightClick}
+ onNodeClick={handleNodeClick}
+ onBackgroundClick={handleBackgroundClick}
+ linkCurvature={(link) => link.curvature || 0}
+ nodeCanvasObject={renderNode}
+ onNodeDragEnd={(node) => {
+ node.fx = node.x
+ node.fy = node.y
+ }}
+ cooldownTicks={view === 'hierarchy' ? 0 : forceSettings.cooldownTicks.value}
+ cooldownTime={forceSettings.cooldownTime.value}
+ d3AlphaDecay={forceSettings.d3AlphaDecay.value}
+ d3AlphaMin={forceSettings.d3AlphaMin.value}
+ d3VelocityDecay={forceSettings.d3VelocityDecay.value}
+ warmupTicks={forceSettings.warmupTicks.value}
+ dagLevelDistance={forceSettings.dagLevelDistance.value}
+ backgroundColor={backgroundColor}
+ onZoom={handleZoom}
+ onZoomEnd={handleZoom}
+ linkCanvasObject={renderLink}
+ enableNodeDrag={!shouldUseSimpleRendering}
+ autoPauseRedraw={true}
+ onNodeHover={handleNodeHoverWithTooltip}
+ onLinkHover={handleLinkHover}
+ />
+ {allowLasso && isLassoActive && (
+ <Lasso
+ nodes={graphData.nodes}
+ graph2ScreenCoords={graph2ScreenCoords}
+ partial={true}
+ width={containerSize.width}
+ height={containerSize.height}
+ />
+ )}
+ {/* {minimap && graphData.nodes &&
<MiniMap zoomTransform={zoomState}
canvasWidth={containerSize.width}
canvasHeight={containerSize.height}
nodes={graphData.nodes as GraphNode[]} />} */}
- </div >
- );
-};
+ </div>
+ )
+}
-export default GraphViewer;
\ No newline at end of file
+export default GraphViewer
diff --git a/flowsint-app/src/renderer/src/components/graphs/graph.tsx b/flowsint-app/src/renderer/src/components/graphs/graph.tsx
index 0f3e08cc..239041c5 100644
--- a/flowsint-app/src/renderer/src/components/graphs/graph.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/graph.tsx
@@ -1,276 +1,285 @@
-import { useCallback, useEffect, memo, lazy, Suspense, useRef, useState } from "react"
+import { useCallback, useEffect, memo, lazy, Suspense, useRef, useState } from 'react'
import { Cosmograph, CosmographProvider, useCosmograph } from '@cosmograph/react'
-import { useGraphStore } from "@/stores/graph-store"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import Loader from "@/components/shared/loader"
-import { useGraphControls } from "@/stores/graph-controls-store"
+import { useGraphStore } from '@/stores/graph-store'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import Loader from '@/components/shared/loader'
+import { useGraphControls } from '@/stores/graph-controls-store'
// @ts-ignore
-import { type CosmosInputNode } from "@cosmograph/cosmos"
-import { ResizablePanel, ResizablePanelGroup } from "../ui/resizable"
-import EmptyState from "./empty-state"
+import { type CosmosInputNode } from '@cosmograph/cosmos'
+import { ResizablePanel, ResizablePanelGroup } from '../ui/resizable'
+import EmptyState from './empty-state'
// Lazy loading du timeline
const CosmographTimeline = lazy(() =>
- import('@cosmograph/react').then(module => ({ default: module.CosmographTimeline }))
+ import('@cosmograph/react').then((module) => ({ default: module.CosmographTimeline }))
)
// Hook pour tracker l'état de chargement de Cosmograph
const useCosmographLoader = (nodes: any[], edges: any[]) => {
- const [isCosmographReady, setIsCosmographReady] = useState(true)
- const [loadingStage, setLoadingStage] = useState<'importing' | 'rendering' | 'ready'>('ready')
- const cosmograph = useCosmograph()
- const dataVersionRef = useRef(0)
+ const [isCosmographReady, setIsCosmographReady] = useState(true)
+ const [loadingStage, setLoadingStage] = useState<'importing' | 'rendering' | 'ready'>('ready')
+ const cosmograph = useCosmograph()
+ const dataVersionRef = useRef(0)
- useEffect(() => {
- // Reset l'état quand les données changent
- dataVersionRef.current += 1
- setIsCosmographReady(false)
- setLoadingStage('importing')
- if (!cosmograph?.cosmograph || nodes.length === 0) {
- setIsCosmographReady(true)
- setLoadingStage('ready')
- return
- }
- // Skip simulation if no edges
- if (edges.length === 0) {
- setIsCosmographReady(true)
- setLoadingStage('ready')
- return
- }
- setLoadingStage('rendering')
- }, [cosmograph?.cosmograph, nodes.length, edges.length])
+ useEffect(() => {
+ // Reset l'état quand les données changent
+ dataVersionRef.current += 1
+ setIsCosmographReady(false)
+ setLoadingStage('importing')
+ if (!cosmograph?.cosmograph || nodes.length === 0) {
+ setIsCosmographReady(true)
+ setLoadingStage('ready')
+ return
+ }
+ // Skip simulation if no edges
+ if (edges.length === 0) {
+ setIsCosmographReady(true)
+ setLoadingStage('ready')
+ return
+ }
+ setLoadingStage('rendering')
+ }, [cosmograph?.cosmograph, nodes.length, edges.length])
- const handleSimulationStart = useCallback(() => {
- if (edges.length > 0) {
- setLoadingStage('rendering')
- setIsCosmographReady(false)
- }
- }, [edges.length])
+ const handleSimulationStart = useCallback(() => {
+ if (edges.length > 0) {
+ setLoadingStage('rendering')
+ setIsCosmographReady(false)
+ }
+ }, [edges.length])
- const handleSimulationEnd = useCallback(() => {
- setLoadingStage('ready')
- setIsCosmographReady(true)
- }, [])
+ const handleSimulationEnd = useCallback(() => {
+ setLoadingStage('ready')
+ setIsCosmographReady(true)
+ }, [])
- return { isCosmographReady, loadingStage, handleSimulationStart, handleSimulationEnd }
+ return { isCosmographReady, loadingStage, handleSimulationStart, handleSimulationEnd }
}
// Composant de loader personnalisé pour Cosmograph
const CosmographLoader = memo(({ stage }: { stage: string }) => (
- <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex flex-col items-center justify-center z-50">
- <Loader />
- <div className="mt-4 text-sm text-muted-foreground">
- {stage === 'importing' && 'Importing graph data...'}
- {stage === 'simulating' && 'Running simulation...'}
- {stage === 'rendering' && 'Rendering graph...'}
- </div>
+ <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex flex-col items-center justify-center z-50">
+ <Loader />
+ <div className="mt-4 text-sm text-muted-foreground">
+ {stage === 'importing' && 'Importing graph data...'}
+ {stage === 'simulating' && 'Running simulation...'}
+ {stage === 'rendering' && 'Rendering graph...'}
</div>
+ </div>
))
-CosmographLoader.displayName = "CosmographLoader"
-
+CosmographLoader.displayName = 'CosmographLoader'
const GRAPH_CONFIG = {
- // simulationCenter: 0.2,
- useQuadtree: true,
- simulationDecay: 100,
- simulationGravity: 0.25,
- // simulationLinkSpring: 2,
- simulationRepulsion: 2,
- // simulationRepulsionTheta: 1.15,
- linkStrength: 1,
- simulationLinkDistance: .1,
- nodeSizeScale: 0.2,
- // simulationLinkDistance: 6,
- backgroundColor: "transparent" as const,
+ // simulationCenter: 0.2,
+ useQuadtree: true,
+ simulationDecay: 100,
+ simulationGravity: 0.25,
+ // simulationLinkSpring: 2,
+ simulationRepulsion: 2,
+ // simulationRepulsionTheta: 1.15,
+ linkStrength: 1,
+ simulationLinkDistance: 0.1,
+ nodeSizeScale: 0.2,
+ // simulationLinkDistance: 6,
+ backgroundColor: 'transparent' as const
}
const GraphContent = memo(() => {
- const nodes = useGraphStore(s => s.nodes)
- const edges = useGraphStore(s => s.edges)
- // const currentNode = useGraphStore(s => s.currentNode)
- const { isCosmographReady, loadingStage, handleSimulationStart, handleSimulationEnd } = useCosmographLoader(nodes, edges)
- const clearSelectedNodes = useGraphStore(s => s.clearSelectedNodes)
- const toggleNodeSelection = useGraphStore(s => s.toggleNodeSelection)
- const colors = useNodesDisplaySettings(s => s.colors)
- const getSize = useNodesDisplaySettings(s => s.getSize)
- const getIcon = useNodesDisplaySettings(s => s.getIcon)
- const setActions = useGraphControls(s => s.setActions)
+ const nodes = useGraphStore((s) => s.nodes)
+ const edges = useGraphStore((s) => s.edges)
+ // const currentNode = useGraphStore(s => s.currentNode)
+ const { isCosmographReady, loadingStage, handleSimulationStart, handleSimulationEnd } =
+ useCosmographLoader(nodes, edges)
+ const clearSelectedNodes = useGraphStore((s) => s.clearSelectedNodes)
+ const toggleNodeSelection = useGraphStore((s) => s.toggleNodeSelection)
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ const getSize = useNodesDisplaySettings((s) => s.getSize)
+ const getIcon = useNodesDisplaySettings((s) => s.getIcon)
+ const setActions = useGraphControls((s) => s.setActions)
- const cosmograph = useCosmograph()
- const actionsSetRef = useRef(false)
- const instanceId = useRef('cosmograph-main') // Add instance-specific ID
+ const cosmograph = useCosmograph()
+ const actionsSetRef = useRef(false)
+ const instanceId = useRef('cosmograph-main') // Add instance-specific ID
- const handleLabelClick = useCallback((node: any, event: MouseEvent) => {
+ const handleLabelClick = useCallback(
+ (node: any, event: MouseEvent) => {
+ const multiSelect = event.ctrlKey || event.shiftKey || event.altKey
+ toggleNodeSelection(node, multiSelect)
+ // cosmograph?.cosmograph?.zoomToNode(node)
+ },
+ [toggleNodeSelection, cosmograph?.cosmograph]
+ )
+
+ //@ts-ignore
+ const handleNodeClick = useCallback(
+ (clickedNode?: any, index?: number, nodePosition?: [number, number], event?: MouseEvent) => {
+ if (!clickedNode) {
+ clearSelectedNodes()
+ return
+ }
+ if (event) {
const multiSelect = event.ctrlKey || event.shiftKey || event.altKey
- toggleNodeSelection(node, multiSelect)
- // cosmograph?.cosmograph?.zoomToNode(node)
- }, [toggleNodeSelection, cosmograph?.cosmograph])
+ toggleNodeSelection(clickedNode, multiSelect)
+ // cosmograph?.cosmograph?.zoomToNode(clickedNode)
+ } else {
+ // cosmograph?.cosmograph?.zoomToNode(clickedNode)
+ }
+ },
+ [toggleNodeSelection, clearSelectedNodes, cosmograph?.cosmograph]
+ )
- //@ts-ignore
- const handleNodeClick = useCallback((clickedNode?: any, index?: number, nodePosition?: [number, number], event?: MouseEvent) => {
- if (!clickedNode) {
- clearSelectedNodes()
- return
- }
- if (event) {
- const multiSelect = event.ctrlKey || event.shiftKey || event.altKey
- toggleNodeSelection(clickedNode, multiSelect)
- // cosmograph?.cosmograph?.zoomToNode(clickedNode)
- } else {
- // cosmograph?.cosmograph?.zoomToNode(clickedNode)
- }
- }, [toggleNodeSelection, clearSelectedNodes, cosmograph?.cosmograph])
+ // Fonctions de style stables
+ const nodeColorFunction = useCallback(
+ (n: CosmosInputNode & { data?: { type?: string } }) =>
+ colors[n.data?.type as keyof typeof colors] || '#000000',
+ [colors]
+ )
- // Fonctions de style stables
- const nodeColorFunction = useCallback((n: CosmosInputNode & { data?: { type?: string } }) =>
- colors[n.data?.type as keyof typeof colors] || "#000000", [colors])
+ const nodeSizeFunction = useCallback((n: any) => getSize(n.data?.type), [getSize])
- const nodeSizeFunction = useCallback((n: any) => getSize(n.data?.type), [getSize])
+ const nodeLabelFunction = useCallback((n: any) => `${getIcon(n.data.type)} ${n.label}`, [getIcon])
- const nodeLabelFunction = useCallback((n: any) => `${getIcon(n.data.type)} ${n.label}`, [getIcon])
+ // Fit view to all nodes on first render
+ //@ts-ignore
+ useEffect(() => {
+ if (cosmograph?.cosmograph && isCosmographReady) {
+ const timeoutId = setTimeout(() => {
+ cosmograph.cosmograph?.fitView(500)
+ }, 100)
- // Fit view to all nodes on first render
- //@ts-ignore
- useEffect(() => {
- if (cosmograph?.cosmograph && isCosmographReady) {
- const timeoutId = setTimeout(() => {
- cosmograph.cosmograph?.fitView(500)
- }, 100)
+ return () => clearTimeout(timeoutId)
+ }
+ }, [cosmograph?.cosmograph, isCosmographReady])
- return () => clearTimeout(timeoutId)
+ // Configuration des actions une seule fois
+ useEffect(() => {
+ if (cosmograph?.cosmograph && !actionsSetRef.current) {
+ const actions = {
+ zoomIn: () => {
+ const current = cosmograph.cosmograph?.getZoomLevel()
+ const zoomLevel = current ? current * 1.5 : 1.5
+ cosmograph.cosmograph?.setZoomLevel(zoomLevel, 200)
+ },
+ zoomToFit: () => {
+ cosmograph.cosmograph?.fitView(200)
+ },
+ zoomOut: () => {
+ const current = cosmograph.cosmograph?.getZoomLevel()
+ const zoomLevel = current ? current * 0.5 : 0.5
+ cosmograph.cosmograph?.setZoomLevel(zoomLevel, 200)
}
- }, [cosmograph?.cosmograph, isCosmographReady])
+ }
- // Configuration des actions une seule fois
- useEffect(() => {
- if (cosmograph?.cosmograph && !actionsSetRef.current) {
- const actions = {
- zoomIn: () => {
- const current = cosmograph.cosmograph?.getZoomLevel()
- const zoomLevel = current ? current * 1.5 : 1.5
- cosmograph.cosmograph?.setZoomLevel(zoomLevel, 200)
- },
- zoomToFit: () => {
- cosmograph.cosmograph?.fitView(200)
- },
- zoomOut: () => {
- const current = cosmograph.cosmograph?.getZoomLevel()
- const zoomLevel = current ? current * 0.5 : 0.5
- cosmograph.cosmograph?.setZoomLevel(zoomLevel, 200)
- },
- }
-
- setActions(actions)
- cosmograph.cosmograph.restart()
- actionsSetRef.current = true
- }
+ setActions(actions)
+ cosmograph.cosmograph.restart()
+ actionsSetRef.current = true
+ }
- // Cleanup: reset actions when component unmounts
- return () => {
- if (actionsSetRef.current) {
- setActions({
- zoomIn: () => {},
- zoomOut: () => {},
- zoomToFit: () => {},
- })
- actionsSetRef.current = false
- }
- }
- }, [cosmograph?.cosmograph, setActions, instanceId.current])
+ // Cleanup: reset actions when component unmounts
+ return () => {
+ if (actionsSetRef.current) {
+ setActions({
+ zoomIn: () => {},
+ zoomOut: () => {},
+ zoomToFit: () => {}
+ })
+ actionsSetRef.current = false
+ }
+ }
+ }, [cosmograph?.cosmograph, setActions, instanceId.current])
- //@ts-ignore
- // useEffect(() => {
- // if (currentNode && cosmograph?.cosmograph && isCosmographReady) {
- // const timeoutId = setTimeout(() => {
- // cosmograph.cosmograph?.zoomToNode(currentNode)
- // cosmograph.cosmograph?.focusNode(currentNode)
- // }, 100)
+ //@ts-ignore
+ // useEffect(() => {
+ // if (currentNode && cosmograph?.cosmograph && isCosmographReady) {
+ // const timeoutId = setTimeout(() => {
+ // cosmograph.cosmograph?.zoomToNode(currentNode)
+ // cosmograph.cosmograph?.focusNode(currentNode)
+ // }, 100)
- // return () => clearTimeout(timeoutId)
- // }
- // }, [currentNode, cosmograph?.cosmograph, isCosmographReady])
+ // return () => clearTimeout(timeoutId)
+ // }
+ // }, [currentNode, cosmograph?.cosmograph, isCosmographReady])
- return (
- <div className="relative h-full w-full">
- <Cosmograph
- {...GRAPH_CONFIG}
- onSimulationStart={handleSimulationStart}
- onSimulationEnd={handleSimulationEnd}
- onLabelClick={handleLabelClick}
- onClick={handleNodeClick}
- nodeSize={nodeSizeFunction}
- nodeColor={nodeColorFunction}
- nodeLabelColor={nodeColorFunction}
- nodeLabelAccessor={nodeLabelFunction}
- />
- {!isCosmographReady && nodes.length > 0 && (
- <CosmographLoader stage={loadingStage} />
- )}
- </div>
- )
+ return (
+ <div className="relative h-full w-full">
+ <Cosmograph
+ {...GRAPH_CONFIG}
+ onSimulationStart={handleSimulationStart}
+ onSimulationEnd={handleSimulationEnd}
+ onLabelClick={handleLabelClick}
+ onClick={handleNodeClick}
+ nodeSize={nodeSizeFunction}
+ nodeColor={nodeColorFunction}
+ nodeLabelColor={nodeColorFunction}
+ nodeLabelAccessor={nodeLabelFunction}
+ />
+ {!isCosmographReady && nodes.length > 0 && <CosmographLoader stage={loadingStage} />}
+ </div>
+ )
})
-GraphContent.displayName = "GraphContent"
+GraphContent.displayName = 'GraphContent'
// Timeline avec ses propres optimisations
const TimelinePanel = memo(() => {
- const handleAnimationPlay = useCallback(() => {
- }, [])
+ const handleAnimationPlay = useCallback(() => {}, [])
- const dateAccessor = useCallback((d: any) => d.data.created_at, [])
+ const dateAccessor = useCallback((d: any) => d.data.created_at, [])
- return (
- <Suspense fallback={<div className="h-full flex items-center justify-center text-sm text-muted-foreground">Loading timeline...</div>}>
- <CosmographTimeline
- className="!bg-background !h-full"
- // @ts-ignore
- accessor={dateAccessor}
- animationSpeed={20}
- showAnimationControls
- onAnimationPlay={handleAnimationPlay}
- />
- </Suspense>
- )
+ return (
+ <Suspense
+ fallback={
+ <div className="h-full flex items-center justify-center text-sm text-muted-foreground">
+ Loading timeline...
+ </div>
+ }
+ >
+ <CosmographTimeline
+ className="!bg-background !h-full"
+ // @ts-ignore
+ accessor={dateAccessor}
+ animationSpeed={20}
+ showAnimationControls
+ onAnimationPlay={handleAnimationPlay}
+ />
+ </Suspense>
+ )
})
-TimelinePanel.displayName = "TimelinePanel"
+TimelinePanel.displayName = 'TimelinePanel'
// Provider wrapper mémorisé pour éviter les re-créations
-const GraphProvider = memo(({ nodes, edges, children }: {
- nodes: any[],
- edges: any[],
- children: React.ReactNode
-}) => {
-
+const GraphProvider = memo(
+ ({ nodes, edges, children }: { nodes: any[]; edges: any[]; children: React.ReactNode }) => {
return (
- <CosmographProvider nodes={nodes} links={edges}>
- {children}
- </CosmographProvider>
+ <CosmographProvider nodes={nodes} links={edges}>
+ {children}
+ </CosmographProvider>
)
-})
-GraphProvider.displayName = "GraphProvider"
+ }
+)
+GraphProvider.displayName = 'GraphProvider'
// Composant principal avec optimisations maximales
const Graph = memo(() => {
- const nodes = useGraphStore(s => s.filteredNodes)
- const edges = useGraphStore(s => s.filteredEdges)
+ const nodes = useGraphStore((s) => s.filteredNodes)
+ const edges = useGraphStore((s) => s.filteredEdges)
- if (!nodes.length) {
- return <EmptyState />
- }
- return (
- <div className="relative h-full grow w-full flex flex-col bg-background min-h-0">
- <GraphProvider nodes={nodes} edges={edges}>
- <ResizablePanelGroup direction="vertical" className="flex-1 min-h-0 h-full flex flex-col">
- <ResizablePanel defaultSize={75} minSize={30} className="flex-grow min-h-0 inset-shadow">
- <GraphContent />
- </ResizablePanel>
- {/* <ResizableHandle /> */}
- {/* <ResizablePanel defaultSize={25} minSize={10} className="flex-grow h-full min-h-0 inset-shadow">
+ if (!nodes.length) {
+ return <EmptyState />
+ }
+ return (
+ <div className="relative h-full grow w-full flex flex-col bg-background min-h-0">
+ <GraphProvider nodes={nodes} edges={edges}>
+ <ResizablePanelGroup direction="vertical" className="flex-1 min-h-0 h-full flex flex-col">
+ <ResizablePanel defaultSize={75} minSize={30} className="flex-grow min-h-0 inset-shadow">
+ <GraphContent />
+ </ResizablePanel>
+ {/* <ResizableHandle /> */}
+ {/* <ResizablePanel defaultSize={25} minSize={10} className="flex-grow h-full min-h-0 inset-shadow">
<TimelinePanel />
</ResizablePanel> */}
- </ResizablePanelGroup>
- </GraphProvider>
- </div>
- )
+ </ResizablePanelGroup>
+ </GraphProvider>
+ </div>
+ )
})
-Graph.displayName = "Graph"
+Graph.displayName = 'Graph'
-export default Graph
\ No newline at end of file
+export default Graph
diff --git a/flowsint-app/src/renderer/src/components/graphs/index.tsx b/flowsint-app/src/renderer/src/components/graphs/index.tsx
index a36c4fe8..c112cbd5 100644
--- a/flowsint-app/src/renderer/src/components/graphs/index.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/index.tsx
@@ -26,150 +26,148 @@ const Graph = lazy(() => import('./graph'))
// Separate component for the drag overlay
const DragOverlay = memo(({ isDragging }: { isDragging: boolean }) => (
- <div
- className={cn(
- 'absolute flex items-center justify-center inset-0 bg-background/80 backdrop-blur-sm gap-1',
- 'opacity-0 pointer-events-none transition-opacity duration-200',
- isDragging && 'opacity-100 pointer-events-auto'
- )}
- >
- <p className="font-medium">Drop here to add node</p>
- <ArrowDownToLineIcon className="opacity-60" />
- </div>
+ <div
+ className={cn(
+ 'absolute flex items-center justify-center inset-0 bg-background/80 backdrop-blur-sm gap-1',
+ 'opacity-0 pointer-events-none transition-opacity duration-200',
+ isDragging && 'opacity-100 pointer-events-auto'
+ )}
+ >
+ <p className="font-medium">Drop here to add node</p>
+ <ArrowDownToLineIcon className="opacity-60" />
+ </div>
))
DragOverlay.displayName = 'DragOverlay'
interface GraphPanelProps {
- graphData: { nds: GraphNode[]; rls: GraphEdge[] } | null;
- isLoading: boolean;
- isRefetching: boolean;
+ graphData: { nds: GraphNode[]; rls: GraphEdge[] } | null
+ isLoading: boolean
+ isRefetching: boolean
}
const GraphPanel = ({ graphData, isLoading }: GraphPanelProps) => {
- const handleOpenFormModal = useGraphStore(s => s.handleOpenFormModal)
- const nodes = useGraphStore(s => s.nodes)
- const view = useGraphControls((s) => s.view)
- const settings = useGraphSettingsStore(s => s.settings)
- const updateGraphData = useGraphStore(s => s.updateGraphData)
- const setFilters = useGraphStore(s => s.setFilters)
- const filters = useGraphStore(s => s.filters)
- const { actionItems, isLoading: isLoadingActionItems } = useActionItems()
- const NODE_COUNT_THRESHOLD = settings?.general?.graphViewerThreshold?.value || 1000
-
- const { sketch } = useLoaderData({
- from: '/_auth/dashboard/investigations/$investigationId/$type/$id',
- })
- const [isDraggingOver, setIsDraggingOver] = useState(false)
+ const handleOpenFormModal = useGraphStore((s) => s.handleOpenFormModal)
+ const nodes = useGraphStore((s) => s.nodes)
+ const view = useGraphControls((s) => s.view)
+ const settings = useGraphSettingsStore((s) => s.settings)
+ const updateGraphData = useGraphStore((s) => s.updateGraphData)
+ const setFilters = useGraphStore((s) => s.setFilters)
+ const filters = useGraphStore((s) => s.filters)
+ const { actionItems, isLoading: isLoadingActionItems } = useActionItems()
+ const NODE_COUNT_THRESHOLD = settings?.general?.graphViewerThreshold?.value || 1000
- useEffect(() => {
- if (graphData?.nds && graphData?.rls) {
- updateGraphData(graphData.nds, graphData.rls)
- const types = new Set(graphData.nds.map(n => n.data.type))
- setFilters(
- {
- ...filters, types: Array.from(types).map(t => ({
- type: t,
- checked: true
- }))
- }
- )
- }
- }, [graphData?.nds, graphData?.rls, setFilters])
+ const { sketch } = useLoaderData({
+ from: '/_auth/dashboard/investigations/$investigationId/$type/$id'
+ })
+ const [isDraggingOver, setIsDraggingOver] = useState(false)
- const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- setIsDraggingOver(true)
+ useEffect(() => {
+ if (graphData?.nds && graphData?.rls) {
+ updateGraphData(graphData.nds, graphData.rls)
+ const types = new Set(graphData.nds.map((n) => n.data.type))
+ setFilters({
+ ...filters,
+ types: Array.from(types).map((t) => ({
+ type: t,
+ checked: true
+ }))
+ })
}
+ }, [graphData?.nds, graphData?.rls, setFilters])
- const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- setIsDraggingOver(true)
- }
+ const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ setIsDraggingOver(true)
+ }
- const handleDragLeave = () => {
- setIsDraggingOver(false)
- }
+ const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ setIsDraggingOver(true)
+ }
- const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- setIsDraggingOver(false)
- if (isLoadingActionItems || !actionItems) {
- toast.error("Sorry, an error occured. Please try again.")
- return
- }
- const data = e.dataTransfer.getData("text/plain")
- if (data) {
- try {
- const parsedData = JSON.parse(data)
- handleOpenFormModal(findActionItemByKey(parsedData.itemKey, actionItems))
- } catch (error) {
- return
- }
- }
- }
- if (isLoading) {
- return <GraphLoader />
- }
+ const handleDragLeave = () => {
+ setIsDraggingOver(false)
+ }
- if (!sketch || !graphData) {
- return (
- <div className="h-full w-full flex items-center justify-center">
- <div className="text-center">
- <h2 className="text-lg font-semibold text-destructive mb-2">
- Error loading graph
- </h2>
- <p className="text-muted-foreground">
- Could not load graph data. Please try again.
- </p>
- </div>
- </div>
- )
+ const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ setIsDraggingOver(false)
+ if (isLoadingActionItems || !actionItems) {
+ toast.error('Sorry, an error occured. Please try again.')
+ return
+ }
+ const data = e.dataTransfer.getData('text/plain')
+ if (data) {
+ try {
+ const parsedData = JSON.parse(data)
+ handleOpenFormModal(findActionItemByKey(parsedData.itemKey, actionItems))
+ } catch (error) {
+ return
+ }
}
+ }
+ if (isLoading) {
+ return <GraphLoader />
+ }
+ if (!sketch || !graphData) {
return (
- <div
- className="h-full w-full flex relative outline-2 outline-transparent bg-background"
- onDragOver={handleDragOver}
- onDragEnter={handleDragEnter}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- >
- <Suspense fallback={
- <div className="h-full w-full flex items-center justify-center">
- <div className="text-center flex items-center gap-2">
- <Loader />
- </div>
- </div>
- }>
- {nodes?.length > NODE_COUNT_THRESHOLD ? (
- <>{view === "table" && <NodesTable />}
- {["force", "hierarchy"].includes(view) && <Graph />}
- {view === "map" && <MapPanel />}
- {view === "relationships" && <RelationshipsTable />}
- </>
- ) : (
- <>
- {/* {view === "hierarchy" && <Wall isLoading={false} isRefetching={false} />} */}
- {/* {view === "force" && <GraphMain />} */}
- {["force", "hierarchy"].includes(view) && <GraphMain />}
- {view === "table" && <NodesTable />}
- {view === "map" && <MapPanel />}
- {view === "relationships" && <RelationshipsTable />}
- </>
- )}
- </Suspense>
- <DragOverlay isDragging={isDraggingOver} />
- <div className='absolute z-21 left-3 top-3 right-3'>
- <Toolbar isLoading={isLoading} />
- </div>
- <NewActions />
- <CreateRelationDialog />
- <MergeDialog />
- <NodeEditorModal />
- <Settings />
- <KeyboardShortcuts />
+ <div className="h-full w-full flex items-center justify-center">
+ <div className="text-center">
+ <h2 className="text-lg font-semibold text-destructive mb-2">Error loading graph</h2>
+ <p className="text-muted-foreground">Could not load graph data. Please try again.</p>
</div>
+ </div>
)
+ }
+
+ return (
+ <div
+ className="h-full w-full flex relative outline-2 outline-transparent bg-background"
+ onDragOver={handleDragOver}
+ onDragEnter={handleDragEnter}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ >
+ <Suspense
+ fallback={
+ <div className="h-full w-full flex items-center justify-center">
+ <div className="text-center flex items-center gap-2">
+ <Loader />
+ </div>
+ </div>
+ }
+ >
+ {nodes?.length > NODE_COUNT_THRESHOLD ? (
+ <>
+ {view === 'table' && <NodesTable />}
+ {['force', 'hierarchy'].includes(view) && <Graph />}
+ {view === 'map' && <MapPanel />}
+ {view === 'relationships' && <RelationshipsTable />}
+ </>
+ ) : (
+ <>
+ {/* {view === "hierarchy" && <Wall isLoading={false} isRefetching={false} />} */}
+ {/* {view === "force" && <GraphMain />} */}
+ {['force', 'hierarchy'].includes(view) && <GraphMain />}
+ {view === 'table' && <NodesTable />}
+ {view === 'map' && <MapPanel />}
+ {view === 'relationships' && <RelationshipsTable />}
+ </>
+ )}
+ </Suspense>
+ <DragOverlay isDragging={isDraggingOver} />
+ <div className="absolute z-21 left-3 top-3 right-3">
+ <Toolbar isLoading={isLoading} />
+ </div>
+ <NewActions />
+ <CreateRelationDialog />
+ <MergeDialog />
+ <NodeEditorModal />
+ <Settings />
+ <KeyboardShortcuts />
+ </div>
+ )
}
-export default memo(GraphPanel)
\ No newline at end of file
+export default memo(GraphPanel)
diff --git a/flowsint-app/src/renderer/src/components/graphs/items-panel.tsx b/flowsint-app/src/renderer/src/components/graphs/items-panel.tsx
index b7084820..09427fff 100644
--- a/flowsint-app/src/renderer/src/components/graphs/items-panel.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/items-panel.tsx
@@ -1,94 +1,101 @@
-import { Button } from "@/components/ui/button"
-import { PlusIcon, Search } from "lucide-react"
-import { memo, useCallback, useState } from "react"
-import { type ActionItem } from "@/lib/action-items"
-import { DraggableItem } from "./draggable-item"
-import { Input } from "@/components/ui/input"
-import { useActionItems } from "@/hooks/use-action-items"
-import { SkeletonList } from "../shared/skeleton-list"
-import { useGraphStore } from "@/stores/graph-store"
+import { Button } from '@/components/ui/button'
+import { PlusIcon, Search } from 'lucide-react'
+import { memo, useCallback, useState } from 'react'
+import { type ActionItem } from '@/lib/action-items'
+import { DraggableItem } from './draggable-item'
+import { Input } from '@/components/ui/input'
+import { useActionItems } from '@/hooks/use-action-items'
+import { SkeletonList } from '../shared/skeleton-list'
+import { useGraphStore } from '@/stores/graph-store'
export const ItemsPanel = memo(function LeftPanel() {
- const [searchQuery, setSearchQuery] = useState<string>("")
- const setOpenMainDialog = useGraphStore(state => state.setOpenMainDialog)
+ const [searchQuery, setSearchQuery] = useState<string>('')
+ const setOpenMainDialog = useGraphStore((state) => state.setOpenMainDialog)
- const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
- setSearchQuery(e.target.value)
- }, [])
+ const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ setSearchQuery(e.target.value)
+ }, [])
- const handleOpenNewAddItemDialog = useCallback(() => {
- setOpenMainDialog(true)
- }, [setOpenMainDialog])
+ const handleOpenNewAddItemDialog = useCallback(() => {
+ setOpenMainDialog(true)
+ }, [setOpenMainDialog])
- const { actionItems, isLoading } = useActionItems()
+ const { actionItems, isLoading } = useActionItems()
- return (
- <div className="bg-card p-4 h-full w-full overflow-y-auto flex flex-col">
- <div className="flex items-center gap-2 mb-3">
- <div>
- <Button
- onClick={handleOpenNewAddItemDialog}
- className="h-7 !w-7"
- size="icon"
- variant={"ghost"}
- >
- <PlusIcon />
- </Button>
- </div>
- <div className="relative grow">
- <Search className="absolute left-2.5 top-1.5 h-4 w-4 text-muted-foreground" />
- <Input
- type="search"
- placeholder="Search type..."
- className="pl-8 h-7 border-border"
- value={searchQuery}
- onChange={handleSearchChange}
- />
- </div>
- </div>
- <div className="flex flex-col gap-3">
- {isLoading ? <SkeletonList rowCount={8} /> :
- actionItems?.map((item: ActionItem) => {
- if (item.children && item.children.length > 0) {
- return (
- <div key={item.id}>
- <div className="py-1 text-sm text-muted-foreground">
- <div className="flex items-center gap-2">
- <span>{item.label} ({item.children.length})</span>
- {item.comingSoon && <span className="ml-1 text-xs text-muted-foreground">(Soon)</span>}
- </div>
- </div>
- <div className="flex flex-col gap-2">
- {item.children.map((childItem) => (
- <DraggableItem
- key={childItem.id}
- itemKey={childItem.key}
- label={childItem.label}
- icon={childItem.icon}
- type={childItem.type}
- color={childItem.color}
- disabled={childItem.disabled}
- description={childItem.description}
- />
- ))}
- </div>
- </div>
- )
- }
- return (
- <DraggableItem
- key={item.id}
- label={item.label}
- itemKey={item.key}
- icon={item.icon}
- type={item.type}
- color={item.color}
- disabled={item.disabled}
- description={item.fields.map((n) => n.name).join(", ")}
- />
- )
- })}
- </div>
+ return (
+ <div className="bg-card p-4 h-full w-full overflow-y-auto flex flex-col">
+ <div className="flex items-center gap-2 mb-3">
+ <div>
+ <Button
+ onClick={handleOpenNewAddItemDialog}
+ className="h-7 !w-7"
+ size="icon"
+ variant={'ghost'}
+ >
+ <PlusIcon />
+ </Button>
</div>
- )
+ <div className="relative grow">
+ <Search className="absolute left-2.5 top-1.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ type="search"
+ placeholder="Search type..."
+ className="pl-8 h-7 border-border"
+ value={searchQuery}
+ onChange={handleSearchChange}
+ />
+ </div>
+ </div>
+ <div className="flex flex-col gap-3">
+ {isLoading ? (
+ <SkeletonList rowCount={8} />
+ ) : (
+ actionItems?.map((item: ActionItem) => {
+ if (item.children && item.children.length > 0) {
+ return (
+ <div key={item.id}>
+ <div className="py-1 text-sm text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <span>
+ {item.label} ({item.children.length})
+ </span>
+ {item.comingSoon && (
+ <span className="ml-1 text-xs text-muted-foreground">(Soon)</span>
+ )}
+ </div>
+ </div>
+ <div className="flex flex-col gap-2">
+ {item.children.map((childItem) => (
+ <DraggableItem
+ key={childItem.id}
+ itemKey={childItem.key}
+ label={childItem.label}
+ icon={childItem.icon}
+ type={childItem.type}
+ color={childItem.color}
+ disabled={childItem.disabled}
+ description={childItem.description}
+ />
+ ))}
+ </div>
+ </div>
+ )
+ }
+ return (
+ <DraggableItem
+ key={item.id}
+ label={item.label}
+ itemKey={item.key}
+ icon={item.icon}
+ type={item.type}
+ color={item.color}
+ disabled={item.disabled}
+ description={item.fields.map((n) => n.name).join(', ')}
+ />
+ )
+ })
+ )}
+ </div>
+ </div>
+ )
})
diff --git a/flowsint-app/src/renderer/src/components/graphs/lasso.tsx b/flowsint-app/src/renderer/src/components/graphs/lasso.tsx
index ce4e4f41..016ee134 100644
--- a/flowsint-app/src/renderer/src/components/graphs/lasso.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/lasso.tsx
@@ -1,140 +1,154 @@
-import { memo, useRef, type PointerEvent } from 'react';
-import { useGraphStore } from '@/stores/graph-store';
-import { GraphNode } from '@/types';
-import { GRAPH_COLORS } from './graph-viewer';
+import { memo, useRef, type PointerEvent } from 'react'
+import { useGraphStore } from '@/stores/graph-store'
+import { GraphNode } from '@/types'
+import { GRAPH_COLORS } from './graph-viewer'
-type NodePoints = ([number, number] | [number, number, number])[];
-type NodePointObject = Record<string, NodePoints>;
+type NodePoints = ([number, number] | [number, number, number])[]
+type NodePointObject = Record<string, NodePoints>
// Utilitaire pour générer un chemin SVG fermé à partir de points
function getSvgPathFromStroke(stroke: number[][]): string {
- if (!stroke.length) return "";
-
- const d = stroke.reduce(
- (acc, [x0, y0], i, arr) => {
- const [x1, y1] = arr[(i + 1) % arr.length];
- acc.push(x0, y0, ",", (x0 + x1) / 2, (y0 + y1) / 2);
- return acc;
- },
- ["M", ...stroke[0], "Q"],
- );
-
- d.push("Z");
- return d.join(" ");
+ if (!stroke.length) return ''
+
+ const d = stroke.reduce(
+ (acc, [x0, y0], i, arr) => {
+ const [x1, y1] = arr[(i + 1) % arr.length]
+ acc.push(x0, y0, ',', (x0 + x1) / 2, (y0 + y1) / 2)
+ return acc
+ },
+ ['M', ...stroke[0], 'Q']
+ )
+
+ d.push('Z')
+ return d.join(' ')
}
// Coordonnées relatives au canvas (évite le décalage)
-function getRelativeCoordinates(e: PointerEvent, canvas: HTMLCanvasElement | null): [number, number] {
- const rect = canvas?.getBoundingClientRect();
- if (!rect) return [0, 0];
- return [e.clientX - rect.left, e.clientY - rect.top];
+function getRelativeCoordinates(
+ e: PointerEvent,
+ canvas: HTMLCanvasElement | null
+): [number, number] {
+ const rect = canvas?.getBoundingClientRect()
+ if (!rect) return [0, 0]
+ return [e.clientX - rect.left, e.clientY - rect.top]
}
-export function Lasso({ partial, width, height, graph2ScreenCoords, nodes }: { partial: boolean; width: number; height: number, graph2ScreenCoords: (node: GraphNode) => { x: number, y: number }, nodes: GraphNode[] }) {
- const setSelectedNodes = useGraphStore(s => s.setSelectedNodes);
- const selectedNodes = useGraphStore(s => s.selectedNodes);
- const setCurrentNode = useGraphStore(s => s.setCurrentNode);
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
- const pointRef = useRef<[number, number][]>([]);
- const nodePointsRef = useRef<NodePointObject>({});
- const lastSelectedIds = useRef<Set<string>>(new Set());
-
- function handlePointerDown(e: PointerEvent) {
- const canvas = canvasRef.current;
- if (!canvas) return;
-
- canvas.setPointerCapture(e.pointerId);
- pointRef.current = [getRelativeCoordinates(e, canvas)];
-
- nodePointsRef.current = {};
- for (const node of nodes) {
- const { x, y } = graph2ScreenCoords(node);
- const w = 4, h = 4;
- nodePointsRef.current[node.id] = [
- [x, y],
- [x + w, y],
- [x + w, y + h],
- [x, y + h],
- ];
- }
-
- const ctx = canvas.getContext('2d');
- if (!ctx) return;
-
- ctxRef.current = ctx;
- ctx.lineWidth = 1;
- ctx.fillStyle = `${GRAPH_COLORS.LASSO_FILL}`;
- ctx.strokeStyle = GRAPH_COLORS.LASSO_STROKE;
+export function Lasso({
+ partial,
+ width,
+ height,
+ graph2ScreenCoords,
+ nodes
+}: {
+ partial: boolean
+ width: number
+ height: number
+ graph2ScreenCoords: (node: GraphNode) => { x: number; y: number }
+ nodes: GraphNode[]
+}) {
+ const setSelectedNodes = useGraphStore((s) => s.setSelectedNodes)
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const setCurrentNode = useGraphStore((s) => s.setCurrentNode)
+ const canvasRef = useRef<HTMLCanvasElement>(null)
+ const ctxRef = useRef<CanvasRenderingContext2D | null>(null)
+ const pointRef = useRef<[number, number][]>([])
+ const nodePointsRef = useRef<NodePointObject>({})
+ const lastSelectedIds = useRef<Set<string>>(new Set())
+
+ function handlePointerDown(e: PointerEvent) {
+ const canvas = canvasRef.current
+ if (!canvas) return
+
+ canvas.setPointerCapture(e.pointerId)
+ pointRef.current = [getRelativeCoordinates(e, canvas)]
+
+ nodePointsRef.current = {}
+ for (const node of nodes) {
+ const { x, y } = graph2ScreenCoords(node)
+ const w = 4,
+ h = 4
+ nodePointsRef.current[node.id] = [
+ [x, y],
+ [x + w, y],
+ [x + w, y + h],
+ [x, y + h]
+ ]
}
- function handlePointerMove(e: PointerEvent) {
- if (e.buttons !== 1) return;
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return
- const canvas = canvasRef.current;
- const ctx = ctxRef.current;
- if (!canvas || !ctx) return;
+ ctxRef.current = ctx
+ ctx.lineWidth = 1
+ ctx.fillStyle = `${GRAPH_COLORS.LASSO_FILL}`
+ ctx.strokeStyle = GRAPH_COLORS.LASSO_STROKE
+ }
- pointRef.current.push(getRelativeCoordinates(e, canvas));
+ function handlePointerMove(e: PointerEvent) {
+ if (e.buttons !== 1) return
- const path = new Path2D(getSvgPathFromStroke(pointRef.current));
- ctx.clearRect(0, 0, width, height);
- ctx.fill(path);
- ctx.stroke(path);
+ const canvas = canvasRef.current
+ const ctx = ctxRef.current
+ if (!canvas || !ctx) return
- const localSelectedNodes: GraphNode[] = [];
+ pointRef.current.push(getRelativeCoordinates(e, canvas))
- for (const [nodeId, points] of Object.entries(nodePointsRef.current)) {
- const node = nodes.find(n => n.id === nodeId);
- if (!node) continue;
+ const path = new Path2D(getSvgPathFromStroke(pointRef.current))
+ ctx.clearRect(0, 0, width, height)
+ ctx.fill(path)
+ ctx.stroke(path)
- const isSelected = partial
- ? points.some(([x, y]) => ctx.isPointInPath(path, x, y))
- : points.every(([x, y]) => ctx.isPointInPath(path, x, y));
+ const localSelectedNodes: GraphNode[] = []
- if (isSelected) {
- localSelectedNodes.push(node);
- }
- }
- const newIds = new Set(localSelectedNodes.map(n => n.id));
- const oldIds = lastSelectedIds.current;
-
- let changed = newIds.size !== oldIds.size;
- if (!changed) {
- for (const id of newIds) {
- if (!oldIds.has(id)) {
- changed = true;
- break;
- }
- }
- }
+ for (const [nodeId, points] of Object.entries(nodePointsRef.current)) {
+ const node = nodes.find((n) => n.id === nodeId)
+ if (!node) continue
- if (changed) {
- lastSelectedIds.current = newIds;
- setSelectedNodes(localSelectedNodes);
+ const isSelected = partial
+ ? points.some(([x, y]) => ctx.isPointInPath(path, x, y))
+ : points.every(([x, y]) => ctx.isPointInPath(path, x, y))
+
+ if (isSelected) {
+ localSelectedNodes.push(node)
+ }
+ }
+ const newIds = new Set(localSelectedNodes.map((n) => n.id))
+ const oldIds = lastSelectedIds.current
+
+ let changed = newIds.size !== oldIds.size
+ if (!changed) {
+ for (const id of newIds) {
+ if (!oldIds.has(id)) {
+ changed = true
+ break
}
+ }
}
- function handlePointerUp(e: PointerEvent) {
- canvasRef.current?.releasePointerCapture(e.pointerId);
- pointRef.current = [];
- if (selectedNodes.length === 1)
- setCurrentNode(selectedNodes[0])
- ctxRef.current?.clearRect(0, 0, width, height);
+ if (changed) {
+ lastSelectedIds.current = newIds
+ setSelectedNodes(localSelectedNodes)
}
-
-
- return (
- <canvas
- ref={canvasRef}
- width={width}
- height={height}
- className="tool-overlay"
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- />
- );
+ }
+
+ function handlePointerUp(e: PointerEvent) {
+ canvasRef.current?.releasePointerCapture(e.pointerId)
+ pointRef.current = []
+ if (selectedNodes.length === 1) setCurrentNode(selectedNodes[0])
+ ctxRef.current?.clearRect(0, 0, width, height)
+ }
+
+ return (
+ <canvas
+ ref={canvasRef}
+ width={width}
+ height={height}
+ className="tool-overlay"
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ />
+ )
}
-export default memo(Lasso);
+export default memo(Lasso)
diff --git a/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx b/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx
index abc7905b..d3bbdc96 100644
--- a/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx
@@ -1,32 +1,32 @@
-
-import { useCallback, useState, memo } from "react"
-import { Button } from "@/components/ui/button"
+import { useCallback, useState, memo } from 'react'
+import { Button } from '@/components/ui/button'
import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetDescription,
- SheetFooter,
- SheetTrigger,
-} from "@/components/ui/sheet"
-import { Card, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
-import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
-import { Input } from "@/components/ui/input"
-import { useLaunchTransform } from "@/hooks/use-launch-transform"
-import { useLaunchFlow } from "@/hooks/use-launch-flow"
-import { formatDistanceToNow } from "date-fns"
-import { useQuery } from "@tanstack/react-query"
-import { transformService } from "@/api/transform-service"
-import { flowService } from '@/api/flow-service';
-import { Link, useParams } from "@tanstack/react-router"
-import { capitalizeFirstLetter } from "@/lib/utils"
-import { Skeleton } from "@/components/ui/skeleton"
-import { Search, FileCode2, Zap, PlusIcon, GitBranch, FileX, Sparkles } from "lucide-react"
-import { Transform, Flow } from "@/types"
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+ SheetFooter,
+ SheetTrigger
+} from '@/components/ui/sheet'
+import { Card, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
+import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
+import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
+import { Input } from '@/components/ui/input'
+import { useLaunchTransform } from '@/hooks/use-launch-transform'
+import { useLaunchFlow } from '@/hooks/use-launch-flow'
+import { formatDistanceToNow } from 'date-fns'
+import { useQuery } from '@tanstack/react-query'
+import { transformService } from '@/api/transform-service'
+import { flowService } from '@/api/flow-service'
+import { Link, useParams } from '@tanstack/react-router'
+import { capitalizeFirstLetter } from '@/lib/utils'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Search, FileCode2, Zap, PlusIcon, GitBranch, FileX, Sparkles } from 'lucide-react'
+import { Transform, Flow } from '@/types'
-const LaunchTransformOrFlowPanel = memo(({ values, type, children }: { values: string[], type: string, children?: React.ReactNode }) => {
+const LaunchTransformOrFlowPanel = memo(
+ ({ values, type, children }: { values: string[]; type: string; children?: React.ReactNode }) => {
const { launchTransform } = useLaunchTransform()
const { launchFlow } = useLaunchFlow()
const { id: sketch_id } = useParams({ strict: false })
@@ -37,323 +37,352 @@ const LaunchTransformOrFlowPanel = memo(({ values, type, children }: { values: s
const [flowsSearchQuery, setFlowsSearchQuery] = useState('')
const { data: transforms, isLoading: isLoadingTransforms } = useQuery({
- queryKey: ["transforms", type],
- queryFn: () => transformService.get(capitalizeFirstLetter(type)),
- });
+ queryKey: ['transforms', type],
+ queryFn: () => transformService.get(capitalizeFirstLetter(type))
+ })
const { data: flows, isLoading: isLoadingFlows } = useQuery({
- queryKey: ["flows", type],
- queryFn: () => flowService.get(capitalizeFirstLetter(type)),
- });
+ queryKey: ['flows', type],
+ queryFn: () => flowService.get(capitalizeFirstLetter(type))
+ })
- const filteredTransforms = transforms?.filter((transform: Transform) => {
- if (!transformsSearchQuery.trim()) return true;
- const query = transformsSearchQuery.toLowerCase().trim();
- const matchesName = transform.name?.toLowerCase().includes(query);
- const matchesDescription = transform.description?.toLowerCase().includes(query);
- return matchesName || matchesDescription;
- }) || [];
+ const filteredTransforms =
+ transforms?.filter((transform: Transform) => {
+ if (!transformsSearchQuery.trim()) return true
+ const query = transformsSearchQuery.toLowerCase().trim()
+ const matchesName = transform.name?.toLowerCase().includes(query)
+ const matchesDescription = transform.description?.toLowerCase().includes(query)
+ return matchesName || matchesDescription
+ }) || []
- const filteredFlows = flows?.filter((transform: Flow) => {
- if (!flowsSearchQuery.trim()) return true;
- const query = flowsSearchQuery.toLowerCase().trim();
- const matchesName = transform.name?.toLowerCase().includes(query);
- const matchesDescription = transform.description?.toLowerCase().includes(query);
- return matchesName || matchesDescription;
- }) || [];
+ const filteredFlows =
+ flows?.filter((transform: Flow) => {
+ if (!flowsSearchQuery.trim()) return true
+ const query = flowsSearchQuery.toLowerCase().trim()
+ const matchesName = transform.name?.toLowerCase().includes(query)
+ const matchesDescription = transform.description?.toLowerCase().includes(query)
+ return matchesName || matchesDescription
+ }) || []
const handleCloseModal = useCallback(() => {
- setIsOpen(false)
+ setIsOpen(false)
}, [])
const handleSelectTransform = useCallback((transform: Transform | Flow) => {
- setSelectedTransform(transform)
+ setSelectedTransform(transform)
}, [])
const handleLaunchPanel = useCallback(() => {
- if (selectedTransform) {
- // Check if it's a Transform or Flow based on the active tab
- if (activeTab === 'transforms') {
- // For transforms, use name
- launchTransform(values, (selectedTransform as Transform).name, sketch_id)
- } else {
- // For flows, use id
- launchFlow(values, (selectedTransform as Flow).id, sketch_id)
- }
- handleCloseModal()
+ if (selectedTransform) {
+ // Check if it's a Transform or Flow based on the active tab
+ if (activeTab === 'transforms') {
+ // For transforms, use name
+ launchTransform(values, (selectedTransform as Transform).name, sketch_id)
+ } else {
+ // For flows, use id
+ launchFlow(values, (selectedTransform as Flow).id, sketch_id)
}
+ handleCloseModal()
+ }
}, [selectedTransform, activeTab, launchTransform, launchFlow, values, sketch_id])
return (
- <div>
- <Sheet open={isOpen} onOpenChange={setIsOpen}>
- <SheetTrigger asChild>
- <div>{children}</div>
- </SheetTrigger>
- <SheetContent className="sm:max-w-xl">
- <SheetHeader>
- <SheetTitle>Select a transform</SheetTitle>
- <SheetDescription>Choose a transform to launch from the list below.</SheetDescription>
- </SheetHeader>
-
- {/* Tabs */}
- <div className="px-4 py-2 border-b border-border">
- <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
- <TabsList className="w-full">
- <TabsTrigger
- value="transforms"
- className="flex-1"
- onClick={(e) => e.stopPropagation()}
- >
- <Zap className="h-3 w-3 mr-1" />
- Transforms
- </TabsTrigger>
- <TabsTrigger
- value="flows"
- className="flex-1"
- onClick={(e) => e.stopPropagation()}
- >
- <FileCode2 className="h-3 w-3 mr-1" />
- Flows
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
+ <div>
+ <Sheet open={isOpen} onOpenChange={setIsOpen}>
+ <SheetTrigger asChild>
+ <div>{children}</div>
+ </SheetTrigger>
+ <SheetContent className="sm:max-w-xl">
+ <SheetHeader>
+ <SheetTitle>Select a transform</SheetTitle>
+ <SheetDescription>Choose a transform to launch from the list below.</SheetDescription>
+ </SheetHeader>
- {/* Tab Content */}
- <Tabs value={activeTab} className="flex-1 flex flex-col min-h-0">
- {/* Transforms Tab */}
- <TabsContent value="transforms" className="flex-1 flex flex-col min-h-0 mt-0">
- {/* Transforms Search */}
- <div className="px-4 py-2 border-b border-border">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
- <Input
- type="search"
- placeholder="Search transforms..."
- value={transformsSearchQuery}
- onChange={(e) => setTransformsSearchQuery(e.target.value)}
- className="h-8 pl-7 text-sm"
- />
- </div>
- </div>
+ {/* Tabs */}
+ <div className="px-4 py-2 border-b border-border">
+ <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
+ <TabsList className="w-full">
+ <TabsTrigger
+ value="transforms"
+ className="flex-1"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Zap className="h-3 w-3 mr-1" />
+ Transforms
+ </TabsTrigger>
+ <TabsTrigger
+ value="flows"
+ className="flex-1"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <FileCode2 className="h-3 w-3 mr-1" />
+ Flows
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
- {/* Transforms List */}
- <div className="p-4 grow overflow-auto">
- <RadioGroup value={selectedTransform && 'name' in selectedTransform ? selectedTransform.name : undefined} className="space-y-3">
- {isLoadingTransforms ? (
- // Skeleton loading state
- Array.from({ length: 3 }).map((_, index) => (
- <Card key={index} className="border py-1">
- <CardHeader className="p-4">
- <div className="flex flex-col space-y-4">
- <div className="flex items-center gap-3">
- <Skeleton className="h-4 w-4 rounded-full" />
- <Skeleton className="h-5 w-32" />
- </div>
- <div className="pl-7 space-y-2">
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-3/4" />
- </div>
- <div className="flex flex-col space-y-1 pl-7">
- <Skeleton className="h-3 w-24" />
- <Skeleton className="h-3 w-20" />
- </div>
- </div>
- </CardHeader>
- </Card>
- ))
- ) : filteredTransforms.length > 0 ? (
- filteredTransforms.map((transform: Transform) => (
- <Card
- key={transform.name}
- className={`cursor-pointer border py-1 transition-all ${selectedTransform && 'name' in selectedTransform && selectedTransform.name === transform.name
- ? "border-primary bg-primary/5"
- : "hover:border-primary/50"
- }`}
- onClick={() => handleSelectTransform(transform)}
- >
- <CardHeader className="p-4">
- <div className="flex flex-col space-y-4">
- <div className="flex items-center gap-3">
- <RadioGroupItem value={transform.name} id={transform.name} />
- <CardTitle className="text-base">{transform.name}</CardTitle>
- </div>
+ {/* Tab Content */}
+ <Tabs value={activeTab} className="flex-1 flex flex-col min-h-0">
+ {/* Transforms Tab */}
+ <TabsContent value="transforms" className="flex-1 flex flex-col min-h-0 mt-0">
+ {/* Transforms Search */}
+ <div className="px-4 py-2 border-b border-border">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
+ <Input
+ type="search"
+ placeholder="Search transforms..."
+ value={transformsSearchQuery}
+ onChange={(e) => setTransformsSearchQuery(e.target.value)}
+ className="h-8 pl-7 text-sm"
+ />
+ </div>
+ </div>
- {transform.description && (
- <CardDescription className="text-sm pl-7">
- {transform.description || "No description available"}
- </CardDescription>
- )}
- </div>
- </CardHeader>
- </Card>
- ))
- ) : (
- <div className="p-8 text-center space-y-6">
- <div className="flex justify-center">
- <div className="p-4 rounded-full bg-muted/50">
- {transformsSearchQuery ? (
- <FileX className="h-8 w-8 text-muted-foreground" />
- ) : (
- <FileCode2 className="h-8 w-8 text-muted-foreground" />
- )}
- </div>
- </div>
- <div className="space-y-2">
- <h3 className="text-lg font-semibold">
- {transformsSearchQuery ? 'No transforms found' : 'No transforms available'}
- </h3>
- <p className="text-sm text-muted-foreground max-w-sm mx-auto">
- {transformsSearchQuery
- ? 'Try adjusting your search terms or browse all available transforms.'
- : 'Transforms are automated data processing tools that can enrich your investigation data.'
- }
- </p>
- </div>
- {!transformsSearchQuery && (
- <div className="flex items-center justify-center gap-2 text-xs text-muted-foreground">
- <Sparkles className="h-3 w-3" />
- <span>Transforms will appear here when available</span>
- </div>
- )}
- </div>
- )}
- </RadioGroup>
+ {/* Transforms List */}
+ <div className="p-4 grow overflow-auto">
+ <RadioGroup
+ value={
+ selectedTransform && 'name' in selectedTransform
+ ? selectedTransform.name
+ : undefined
+ }
+ className="space-y-3"
+ >
+ {isLoadingTransforms ? (
+ // Skeleton loading state
+ Array.from({ length: 3 }).map((_, index) => (
+ <Card key={index} className="border py-1">
+ <CardHeader className="p-4">
+ <div className="flex flex-col space-y-4">
+ <div className="flex items-center gap-3">
+ <Skeleton className="h-4 w-4 rounded-full" />
+ <Skeleton className="h-5 w-32" />
+ </div>
+ <div className="pl-7 space-y-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ </div>
+ <div className="flex flex-col space-y-1 pl-7">
+ <Skeleton className="h-3 w-24" />
+ <Skeleton className="h-3 w-20" />
+ </div>
</div>
- </TabsContent>
+ </CardHeader>
+ </Card>
+ ))
+ ) : filteredTransforms.length > 0 ? (
+ filteredTransforms.map((transform: Transform) => (
+ <Card
+ key={transform.name}
+ className={`cursor-pointer border py-1 transition-all ${
+ selectedTransform &&
+ 'name' in selectedTransform &&
+ selectedTransform.name === transform.name
+ ? 'border-primary bg-primary/5'
+ : 'hover:border-primary/50'
+ }`}
+ onClick={() => handleSelectTransform(transform)}
+ >
+ <CardHeader className="p-4">
+ <div className="flex flex-col space-y-4">
+ <div className="flex items-center gap-3">
+ <RadioGroupItem value={transform.name} id={transform.name} />
+ <CardTitle className="text-base">{transform.name}</CardTitle>
+ </div>
- {/* Flows Tab */}
- <TabsContent value="flows" className="flex-1 flex flex-col min-h-0 mt-0">
- {/* Flows Search */}
- <div className="px-4 py-2 border-b border-border">
- <div className="relative">
- <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
- <Input
- type="search"
- placeholder="Search flows..."
- value={flowsSearchQuery}
- onChange={(e) => setFlowsSearchQuery(e.target.value)}
- className="h-8 pl-7 text-sm"
- />
- </div>
+ {transform.description && (
+ <CardDescription className="text-sm pl-7">
+ {transform.description || 'No description available'}
+ </CardDescription>
+ )}
</div>
+ </CardHeader>
+ </Card>
+ ))
+ ) : (
+ <div className="p-8 text-center space-y-6">
+ <div className="flex justify-center">
+ <div className="p-4 rounded-full bg-muted/50">
+ {transformsSearchQuery ? (
+ <FileX className="h-8 w-8 text-muted-foreground" />
+ ) : (
+ <FileCode2 className="h-8 w-8 text-muted-foreground" />
+ )}
+ </div>
+ </div>
+ <div className="space-y-2">
+ <h3 className="text-lg font-semibold">
+ {transformsSearchQuery
+ ? 'No transforms found'
+ : 'No transforms available'}
+ </h3>
+ <p className="text-sm text-muted-foreground max-w-sm mx-auto">
+ {transformsSearchQuery
+ ? 'Try adjusting your search terms or browse all available transforms.'
+ : 'Transforms are automated data processing tools that can enrich your investigation data.'}
+ </p>
+ </div>
+ {!transformsSearchQuery && (
+ <div className="flex items-center justify-center gap-2 text-xs text-muted-foreground">
+ <Sparkles className="h-3 w-3" />
+ <span>Transforms will appear here when available</span>
+ </div>
+ )}
+ </div>
+ )}
+ </RadioGroup>
+ </div>
+ </TabsContent>
- {/* Flows List */}
- <div className="p-4 grow overflow-auto">
- <RadioGroup value={selectedTransform && 'id' in selectedTransform ? selectedTransform.id : undefined} className="space-y-3">
- {isLoadingFlows ? (
- // Skeleton loading state
- Array.from({ length: 3 }).map((_, index) => (
- <Card key={index} className="border py-1">
- <CardHeader className="p-4">
- <div className="flex flex-col space-y-4">
- <div className="flex items-center gap-3">
- <Skeleton className="h-4 w-4 rounded-full" />
- <Skeleton className="h-5 w-32" />
- </div>
- <div className="pl-7 space-y-2">
- <Skeleton className="h-4 w-full" />
- <Skeleton className="h-4 w-3/4" />
- </div>
- <div className="flex flex-col space-y-1 pl-7">
- <Skeleton className="h-3 w-24" />
- <Skeleton className="h-3 w-20" />
- </div>
- </div>
- </CardHeader>
- </Card>
- ))
- ) : filteredFlows.length > 0 ? (
- filteredFlows.map((flow: Flow) => (
- <Card
- key={flow.id}
- className={`cursor-pointer border py-1 transition-all ${selectedTransform && 'id' in selectedTransform && selectedTransform.id === flow.id
- ? "border-primary bg-primary/5"
- : "hover:border-primary/50"
- }`}
- onClick={() => handleSelectTransform(flow)}
- >
- <CardHeader className="p-4">
- <div className="flex flex-col space-y-4">
- <div className="flex items-center gap-3">
- <RadioGroupItem value={flow.id} id={flow.id} />
- <CardTitle className="text-base">{flow.name}</CardTitle>
- </div>
+ {/* Flows Tab */}
+ <TabsContent value="flows" className="flex-1 flex flex-col min-h-0 mt-0">
+ {/* Flows Search */}
+ <div className="px-4 py-2 border-b border-border">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
+ <Input
+ type="search"
+ placeholder="Search flows..."
+ value={flowsSearchQuery}
+ onChange={(e) => setFlowsSearchQuery(e.target.value)}
+ className="h-8 pl-7 text-sm"
+ />
+ </div>
+ </div>
- {flow.description && (
- <CardDescription className="text-sm pl-7">
- {flow.description || "No description available"}
- </CardDescription>
- )}
+ {/* Flows List */}
+ <div className="p-4 grow overflow-auto">
+ <RadioGroup
+ value={
+ selectedTransform && 'id' in selectedTransform
+ ? selectedTransform.id
+ : undefined
+ }
+ className="space-y-3"
+ >
+ {isLoadingFlows ? (
+ // Skeleton loading state
+ Array.from({ length: 3 }).map((_, index) => (
+ <Card key={index} className="border py-1">
+ <CardHeader className="p-4">
+ <div className="flex flex-col space-y-4">
+ <div className="flex items-center gap-3">
+ <Skeleton className="h-4 w-4 rounded-full" />
+ <Skeleton className="h-5 w-32" />
+ </div>
+ <div className="pl-7 space-y-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ </div>
+ <div className="flex flex-col space-y-1 pl-7">
+ <Skeleton className="h-3 w-24" />
+ <Skeleton className="h-3 w-20" />
+ </div>
+ </div>
+ </CardHeader>
+ </Card>
+ ))
+ ) : filteredFlows.length > 0 ? (
+ filteredFlows.map((flow: Flow) => (
+ <Card
+ key={flow.id}
+ className={`cursor-pointer border py-1 transition-all ${
+ selectedTransform &&
+ 'id' in selectedTransform &&
+ selectedTransform.id === flow.id
+ ? 'border-primary bg-primary/5'
+ : 'hover:border-primary/50'
+ }`}
+ onClick={() => handleSelectTransform(flow)}
+ >
+ <CardHeader className="p-4">
+ <div className="flex flex-col space-y-4">
+ <div className="flex items-center gap-3">
+ <RadioGroupItem value={flow.id} id={flow.id} />
+ <CardTitle className="text-base">{flow.name}</CardTitle>
+ </div>
+
+ {flow.description && (
+ <CardDescription className="text-sm pl-7">
+ {flow.description || 'No description available'}
+ </CardDescription>
+ )}
- <div className="flex flex-col space-y-1 text-xs text-muted-foreground pl-7">
- <div>Created {formatDistanceToNow(flow.created_at, { addSuffix: true })}</div>
- <div>Updated {formatDistanceToNow(flow.last_updated_at, { addSuffix: true })}</div>
- </div>
- </div>
- </CardHeader>
- </Card>
- ))
- ) : (
- <div className="p-8 text-center space-y-6">
- <div className="flex justify-center">
- <div className="p-4 rounded-full bg-muted/50">
- {flowsSearchQuery ? (
- <FileX className="h-8 w-8 text-muted-foreground" />
- ) : (
- <GitBranch className="h-8 w-8 text-muted-foreground" />
- )}
- </div>
- </div>
- <div className="space-y-2">
- <h3 className="text-lg font-semibold">
- {flowsSearchQuery ? 'No flows found' : 'No flows available'}
- </h3>
- <p className="text-sm text-muted-foreground max-w-sm mx-auto">
- {flowsSearchQuery
- ? 'Try adjusting your search terms or browse all available flows.'
- : 'Flows are custom automation sequences that combine multiple transforms and data sources.'
- }
- </p>
- </div>
- {!flowsSearchQuery && (
- <div className="space-y-4">
- <div className="flex items-center justify-center gap-2 text-xs text-muted-foreground">
- <Zap className="h-3 w-3" />
- <span>Create your first flow to get started</span>
- </div>
- <Link to="/dashboard/flows">
- <Button className="gap-2">
- <PlusIcon className="h-4 w-4" />
- Create your first flow
- </Button>
- </Link>
- </div>
- )}
- </div>
- )}
- </RadioGroup>
+ <div className="flex flex-col space-y-1 text-xs text-muted-foreground pl-7">
+ <div>
+ Created{' '}
+ {formatDistanceToNow(flow.created_at, { addSuffix: true })}
+ </div>
+ <div>
+ Updated{' '}
+ {formatDistanceToNow(flow.last_updated_at, { addSuffix: true })}
+ </div>
+ </div>
+ </div>
+ </CardHeader>
+ </Card>
+ ))
+ ) : (
+ <div className="p-8 text-center space-y-6">
+ <div className="flex justify-center">
+ <div className="p-4 rounded-full bg-muted/50">
+ {flowsSearchQuery ? (
+ <FileX className="h-8 w-8 text-muted-foreground" />
+ ) : (
+ <GitBranch className="h-8 w-8 text-muted-foreground" />
+ )}
+ </div>
+ </div>
+ <div className="space-y-2">
+ <h3 className="text-lg font-semibold">
+ {flowsSearchQuery ? 'No flows found' : 'No flows available'}
+ </h3>
+ <p className="text-sm text-muted-foreground max-w-sm mx-auto">
+ {flowsSearchQuery
+ ? 'Try adjusting your search terms or browse all available flows.'
+ : 'Flows are custom automation sequences that combine multiple transforms and data sources.'}
+ </p>
+ </div>
+ {!flowsSearchQuery && (
+ <div className="space-y-4">
+ <div className="flex items-center justify-center gap-2 text-xs text-muted-foreground">
+ <Zap className="h-3 w-3" />
+ <span>Create your first flow to get started</span>
</div>
- </TabsContent>
- </Tabs>
+ <Link to="/dashboard/flows">
+ <Button className="gap-2">
+ <PlusIcon className="h-4 w-4" />
+ Create your first flow
+ </Button>
+ </Link>
+ </div>
+ )}
+ </div>
+ )}
+ </RadioGroup>
+ </div>
+ </TabsContent>
+ </Tabs>
- <SheetFooter>
- <Button variant="outline" onClick={handleCloseModal} className="mr-2">
- Cancel
- </Button>
- <Button
- onClick={handleLaunchPanel}
- disabled={!selectedTransform}
- className="bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary"
- >
- Launch transform
- </Button>
- </SheetFooter>
- </SheetContent>
- </Sheet>
- </div>
+ <SheetFooter>
+ <Button variant="outline" onClick={handleCloseModal} className="mr-2">
+ Cancel
+ </Button>
+ <Button
+ onClick={handleLaunchPanel}
+ disabled={!selectedTransform}
+ className="bg-gradient-to-r from-primary to-primary/80 hover:from-primary/90 hover:to-primary"
+ >
+ Launch transform
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ </div>
)
-})
+ }
+)
export default LaunchTransformOrFlowPanel
diff --git a/flowsint-app/src/renderer/src/components/graphs/legend.tsx b/flowsint-app/src/renderer/src/components/graphs/legend.tsx
index 52331976..b56c6f80 100644
--- a/flowsint-app/src/renderer/src/components/graphs/legend.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/legend.tsx
@@ -5,42 +5,42 @@ import { Dialog, DialogContent, DialogTrigger } from '../ui/dialog'
import { Button } from '../ui/button'
const Legend = () => {
- const getIcon = useNodesDisplaySettings(s => s.getIcon)
- const colors = useNodesDisplaySettings(s => s.colors)
- const entries = Object.entries(colors)
+ const getIcon = useNodesDisplaySettings((s) => s.getIcon)
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ const entries = Object.entries(colors)
- return (
- <>
- <Dialog>
- <DialogTrigger asChild>
- <div>
- <Button variant="ghost" size="sm" className="h-6 gap-1 text-xs">
- <Info className="h-3 w-3 opacity-60" />
- </Button>
- </div>
- </DialogTrigger>
- <DialogContent className='sm:max-w-md max-h-[90vh] overflow-y-auto'>
- <div className='p-2'>
- <ul className='grid grid-cols-2 items-center gap-1'>
- {entries.map(([key, value]) => (
- <li key={key}>
- <div className='flex items-center gap-2'>
- {/* @ts-ignore */}
- <span>{getIcon(key)}</span>
- <span className='capitalize'>{key.split("_").join(" ")}</span>
- <span
- className='w-2 h-2 rounded-full'
- style={{ backgroundColor: value }}
- ></span>
- </div>
- </li>
- ))}
- </ul>
- </div>
- </DialogContent>
- </Dialog>
- </>
- )
+ return (
+ <>
+ <Dialog>
+ <DialogTrigger asChild>
+ <div>
+ <Button variant="ghost" size="sm" className="h-6 gap-1 text-xs">
+ <Info className="h-3 w-3 opacity-60" />
+ </Button>
+ </div>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-md max-h-[90vh] overflow-y-auto">
+ <div className="p-2">
+ <ul className="grid grid-cols-2 items-center gap-1">
+ {entries.map(([key, value]) => (
+ <li key={key}>
+ <div className="flex items-center gap-2">
+ {/* @ts-ignore */}
+ <span>{getIcon(key)}</span>
+ <span className="capitalize">{key.split('_').join(' ')}</span>
+ <span
+ className="w-2 h-2 rounded-full"
+ style={{ backgroundColor: value }}
+ ></span>
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
}
export default memo(Legend)
diff --git a/flowsint-app/src/renderer/src/components/graphs/merge-nodes.tsx b/flowsint-app/src/renderer/src/components/graphs/merge-nodes.tsx
index 4e709f05..61833c08 100644
--- a/flowsint-app/src/renderer/src/components/graphs/merge-nodes.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/merge-nodes.tsx
@@ -1,176 +1,217 @@
-import { useEffect, useState } from "react"
-import { useGraphStore } from "@/stores/graph-store"
-import { Button } from "@/components/ui/button"
-import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
-import { Info, Merge, MinusCircleIcon, PlusCircleIcon } from "lucide-react"
-import { Label } from "@/components/ui/label"
-import { toast } from "sonner"
-import { GraphNode } from "@/types"
-import { NodeDisplayCard } from "./create-relation"
-import { RadioGroup } from "@/components/ui/radio-group"
-import { Alert, AlertDescription, AlertTitle } from "../ui/alert"
-import { cn, deepObjectDiff } from "@/lib/utils"
-import { sketchService } from "@/api/sketch-service"
-import { useParams } from "@tanstack/react-router"
+import { useEffect, useState } from 'react'
+import { useGraphStore } from '@/stores/graph-store'
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from '@/components/ui/dialog'
+import { Info, Merge, MinusCircleIcon, PlusCircleIcon } from 'lucide-react'
+import { Label } from '@/components/ui/label'
+import { toast } from 'sonner'
+import { GraphNode } from '@/types'
+import { NodeDisplayCard } from './create-relation'
+import { RadioGroup } from '@/components/ui/radio-group'
+import { Alert, AlertDescription, AlertTitle } from '../ui/alert'
+import { cn, deepObjectDiff } from '@/lib/utils'
+import { sketchService } from '@/api/sketch-service'
+import { useParams } from '@tanstack/react-router'
export function MergeDialog() {
- const { id: sketchId } = useParams({ strict: false })
- const selectedNodes = useGraphStore((state) => state.selectedNodes || [])
- const openMergeDialog = useGraphStore((state) => state.openMergeDialog)
- const setOpenMergeDialog = useGraphStore((state) => state.setOpenMergeDialog)
- const [priorityIndex, setPriorityIndex] = useState(0)
- const [preview, setPreview] = useState<GraphNode | null>(null)
- const [old, setOld] = useState<GraphNode | null>(null)
+ const { id: sketchId } = useParams({ strict: false })
+ const selectedNodes = useGraphStore((state) => state.selectedNodes || [])
+ const openMergeDialog = useGraphStore((state) => state.openMergeDialog)
+ const setOpenMergeDialog = useGraphStore((state) => state.setOpenMergeDialog)
+ const [priorityIndex, setPriorityIndex] = useState(0)
+ const [preview, setPreview] = useState<GraphNode | null>(null)
+ const [old, setOld] = useState<GraphNode | null>(null)
- useEffect(() => {
- if (selectedNodes.length === 0) return
- const priorityEntity = selectedNodes[priorityIndex]
- if (!priorityEntity) return
- const otherEntitiesToMerge = selectedNodes.filter((node) => node?.id != priorityEntity?.id)
- const old = {
- ...otherEntitiesToMerge.reduce((acc, entity) => ({
- ...acc,
- ...entity,
- }), {} as GraphNode)
- }
- const merge = {
- ...old,
- ...priorityEntity,
- }
- setOld(old)
- setPreview(merge)
- }, [selectedNodes, priorityIndex, setPreview])
-
- const handleSubmit = async (e: { preventDefault: () => void }) => {
- e.preventDefault()
- if (!preview)
- return toast.error("No preview available.")
- if (!selectedNodes.every((n) => n.data.type === selectedNodes[0].data.type))
- return toast.error("Cannot merge entities of different types.")
- const entitiesToMerge = selectedNodes.map((node) => node.id)
- const body = JSON.stringify({ oldNodes: entitiesToMerge, newNode: preview })
- return toast.promise(
- (async () => {
- await sketchService.mergeNodes(sketchId as string, body)
- setOpenMergeDialog(false)
- })(),
- {
- loading: 'Merging entities...',
- success: 'Entities successfully merged.',
- error: (error) => {
- console.log(error)
- return 'Unexpected error during merging.'
- }
- }
- )
+ useEffect(() => {
+ if (selectedNodes.length === 0) return
+ const priorityEntity = selectedNodes[priorityIndex]
+ if (!priorityEntity) return
+ const otherEntitiesToMerge = selectedNodes.filter((node) => node?.id != priorityEntity?.id)
+ const old = {
+ ...otherEntitiesToMerge.reduce(
+ (acc, entity) => ({
+ ...acc,
+ ...entity
+ }),
+ {} as GraphNode
+ )
}
+ const merge = {
+ ...old,
+ ...priorityEntity
+ }
+ setOld(old)
+ setPreview(merge)
+ }, [selectedNodes, priorityIndex, setPreview])
- return (
- <Dialog open={openMergeDialog} onOpenChange={setOpenMergeDialog}>
- <DialogContent className="!w-full !max-w-[700px] max-h-[90vh] overflow-y-auto overflow-x-hidden">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- <Merge className="h-4 w-4" />
- Merging {selectedNodes.length} entities
- </DialogTitle>
- </DialogHeader>
- <form onSubmit={handleSubmit} className="space-y-4 w-full overflow-hidden">
- {/* Selected Nodes Display */}
- <div className="space-y-2 w-full">
- <Alert className="">
- <Info />
- <AlertTitle>Heads up!</AlertTitle>
- <AlertDescription>
- When merging, you can choose which entity is prioritary, simply click it in the list below.
- Also keep in mind:
- <div>
- <ul className="ml-2 !list-disc">
- <li>All <span className="font-semibold">attributes</span> will be merged, and the matching ones values will be based on the prioritary entity</li>
- <li>Only one node will be kept, and all <span className="font-semibold">relationships</span> will be merged</li>
- </ul>
- </div>
- </AlertDescription>
- </Alert>
- <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
- Selected Nodes ({selectedNodes.length})
- </Label>
- <RadioGroup
- className="flex overflow-x-auto w-full gap-2"
- value={String(priorityIndex)}
- onValueChange={(value) => setPriorityIndex(parseInt(value, 10))}
- >
- {selectedNodes.map((node, index) => (
- <NodeDisplayCard
- key={node.id}
- id={`priority-${node.id}`}
- node={node}
- asRadio
- radioValue={String(index)}
- />
- )
- )}
- </RadioGroup>
- </div>
- {preview && old && <div className="space-y-2 text-sm">
- <p>Merged attributes</p>
- <div className="rounded-md border overflow-hidden">
- <KeyValueDisplayDiff oldRecord={old.data} newRecord={preview.data} />
- </div>
- </div>}
- <DialogFooter>
- <Button type="button" variant="outline" size="sm" onClick={() => setOpenMergeDialog(false)}>
- Cancel
- </Button>
- <Button type="submit" size="sm">
- Merge ({selectedNodes.length})
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog >
+ const handleSubmit = async (e: { preventDefault: () => void }) => {
+ e.preventDefault()
+ if (!preview) return toast.error('No preview available.')
+ if (!selectedNodes.every((n) => n.data.type === selectedNodes[0].data.type))
+ return toast.error('Cannot merge entities of different types.')
+ const entitiesToMerge = selectedNodes.map((node) => node.id)
+ const body = JSON.stringify({ oldNodes: entitiesToMerge, newNode: preview })
+ return toast.promise(
+ (async () => {
+ await sketchService.mergeNodes(sketchId as string, body)
+ setOpenMergeDialog(false)
+ })(),
+ {
+ loading: 'Merging entities...',
+ success: 'Entities successfully merged.',
+ error: (error) => {
+ console.log(error)
+ return 'Unexpected error during merging.'
+ }
+ }
)
+ }
+
+ return (
+ <Dialog open={openMergeDialog} onOpenChange={setOpenMergeDialog}>
+ <DialogContent className="!w-full !max-w-[700px] max-h-[90vh] overflow-y-auto overflow-x-hidden">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Merge className="h-4 w-4" />
+ Merging {selectedNodes.length} entities
+ </DialogTitle>
+ </DialogHeader>
+ <form onSubmit={handleSubmit} className="space-y-4 w-full overflow-hidden">
+ {/* Selected Nodes Display */}
+ <div className="space-y-2 w-full">
+ <Alert className="">
+ <Info />
+ <AlertTitle>Heads up!</AlertTitle>
+ <AlertDescription>
+ When merging, you can choose which entity is prioritary, simply click it in the list
+ below. Also keep in mind:
+ <div>
+ <ul className="ml-2 !list-disc">
+ <li>
+ All <span className="font-semibold">attributes</span> will be merged, and the
+ matching ones values will be based on the prioritary entity
+ </li>
+ <li>
+ Only one node will be kept, and all{' '}
+ <span className="font-semibold">relationships</span> will be merged
+ </li>
+ </ul>
+ </div>
+ </AlertDescription>
+ </Alert>
+ <Label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
+ Selected Nodes ({selectedNodes.length})
+ </Label>
+ <RadioGroup
+ className="flex overflow-x-auto w-full gap-2"
+ value={String(priorityIndex)}
+ onValueChange={(value) => setPriorityIndex(parseInt(value, 10))}
+ >
+ {selectedNodes.map((node, index) => (
+ <NodeDisplayCard
+ key={node.id}
+ id={`priority-${node.id}`}
+ node={node}
+ asRadio
+ radioValue={String(index)}
+ />
+ ))}
+ </RadioGroup>
+ </div>
+ {preview && old && (
+ <div className="space-y-2 text-sm">
+ <p>Merged attributes</p>
+ <div className="rounded-md border overflow-hidden">
+ <KeyValueDisplayDiff oldRecord={old.data} newRecord={preview.data} />
+ </div>
+ </div>
+ )}
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setOpenMergeDialog(false)}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" size="sm">
+ Merge ({selectedNodes.length})
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
}
interface KeyValueDisplayDiffProps {
- oldRecord: Record<string, any>
- newRecord: Record<string, any>
+ oldRecord: Record<string, any>
+ newRecord: Record<string, any>
}
function KeyValueDisplayDiff({ oldRecord, newRecord }: KeyValueDisplayDiffProps) {
- const diffObject = deepObjectDiff(oldRecord, newRecord)
- return (
- <div className={"w-full border-collapse divide-y divide-border"}>
- {diffObject && Object.entries(diffObject)
- .filter(([key]) => !["sketch_id", "caption", "size", "color", "description"].includes(key))
- .map(([key, value], index) => {
- const isNewKey = value.new
- const hasChanged = !value.identical
- const isOldKey = value.removed
- return (
- <div
- key={index}
- className={cn("flex w-full bg-card items-center divide-x divide-border p-0",
- hasChanged && "bg-orange-300/10",
- isNewKey && "bg-green-400/10",
- isOldKey && "bg-red-400/10",
- )}
- >
- <div className={cn("w-1/2 px-4 p-2 text-sm text-muted-foreground flex items-center gap-1 font-normal truncate")}>
- {isNewKey && <PlusCircleIcon className="h-4 w-4 text-green-400" />}
- {isOldKey && <MinusCircleIcon className="h-4 w-4 text-red-400" />}
- <span className={cn(
- hasChanged && "text-orange-300",
- isNewKey && "text-green-400",
- isOldKey && "text-red-400",
- )}>{key}</span>
- </div>
- <div className="w-1/2 px-4 p-2 text-sm font-medium flex items-center justify-between min-w-0">
- {!hasChanged ? <div className="truncate font-normal">{JSON.stringify(value.value ?? "")}</div> :
- <div className="truncate flex flex-wrap gap-2 font-semibold">
- <span className="line-through text-red-300">{JSON.stringify(value.oldValue)}</span><span className={cn(isOldKey ? "text-red-500" : "text-green-500")}>{JSON.stringify(value.newValue ?? "")}</span></div>}
- </div>
- </div>
- )
- })}
- </div >
- )
+ const diffObject = deepObjectDiff(oldRecord, newRecord)
+ return (
+ <div className={'w-full border-collapse divide-y divide-border'}>
+ {diffObject &&
+ Object.entries(diffObject)
+ .filter(
+ ([key]) => !['sketch_id', 'caption', 'size', 'color', 'description'].includes(key)
+ )
+ .map(([key, value], index) => {
+ const isNewKey = value.new
+ const hasChanged = !value.identical
+ const isOldKey = value.removed
+ return (
+ <div
+ key={index}
+ className={cn(
+ 'flex w-full bg-card items-center divide-x divide-border p-0',
+ hasChanged && 'bg-orange-300/10',
+ isNewKey && 'bg-green-400/10',
+ isOldKey && 'bg-red-400/10'
+ )}
+ >
+ <div
+ className={cn(
+ 'w-1/2 px-4 p-2 text-sm text-muted-foreground flex items-center gap-1 font-normal truncate'
+ )}
+ >
+ {isNewKey && <PlusCircleIcon className="h-4 w-4 text-green-400" />}
+ {isOldKey && <MinusCircleIcon className="h-4 w-4 text-red-400" />}
+ <span
+ className={cn(
+ hasChanged && 'text-orange-300',
+ isNewKey && 'text-green-400',
+ isOldKey && 'text-red-400'
+ )}
+ >
+ {key}
+ </span>
+ </div>
+ <div className="w-1/2 px-4 p-2 text-sm font-medium flex items-center justify-between min-w-0">
+ {!hasChanged ? (
+ <div className="truncate font-normal">{JSON.stringify(value.value ?? '')}</div>
+ ) : (
+ <div className="truncate flex flex-wrap gap-2 font-semibold">
+ <span className="line-through text-red-300">
+ {JSON.stringify(value.oldValue)}
+ </span>
+ <span className={cn(isOldKey ? 'text-red-500' : 'text-green-500')}>
+ {JSON.stringify(value.newValue ?? '')}
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/graphs/metadata-field.tsx b/flowsint-app/src/renderer/src/components/graphs/metadata-field.tsx
index db3b9871..bd4a03cf 100644
--- a/flowsint-app/src/renderer/src/components/graphs/metadata-field.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/metadata-field.tsx
@@ -1,131 +1,140 @@
-
-import { useState } from "react"
-import { PlusCircle, X } from "lucide-react"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { cn } from "@/lib/utils"
+import { useState } from 'react'
+import { PlusCircle, X } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { cn } from '@/lib/utils'
interface MetadataFieldProps {
- value: Record<string, string>
- onChange: (value: Record<string, string>) => void
- error?: string
- className?: string
+ value: Record<string, string>
+ onChange: (value: Record<string, string>) => void
+ error?: string
+ className?: string
}
export function MetadataField({ value = {}, onChange, error, className }: MetadataFieldProps) {
- const [newKey, setNewKey] = useState("")
- const [newValue, setNewValue] = useState("")
- const [localError, setLocalError] = useState<string | null>(null)
-
- const handleAddPair = () => {
- if (!newKey.trim()) {
- setLocalError("Key cannot be empty.")
- return
- }
-
- if (value[newKey]) {
- setLocalError(`Key "${newKey}" already exists`)
- return
- }
+ const [newKey, setNewKey] = useState('')
+ const [newValue, setNewValue] = useState('')
+ const [localError, setLocalError] = useState<string | null>(null)
- const updatedMetadata = {
- ...value,
- [newKey]: newValue,
- }
+ const handleAddPair = () => {
+ if (!newKey.trim()) {
+ setLocalError('Key cannot be empty.')
+ return
+ }
- onChange(updatedMetadata)
- setNewKey("")
- setNewValue("")
- setLocalError(null)
+ if (value[newKey]) {
+ setLocalError(`Key "${newKey}" already exists`)
+ return
}
- const handleRemovePair = (key: string) => {
- const updatedMetadata = { ...value }
- delete updatedMetadata[key]
- onChange(updatedMetadata)
+ const updatedMetadata = {
+ ...value,
+ [newKey]: newValue
}
- const handleKeyChange = (oldKey: string, newKey: string, itemValue: string) => {
- if (!newKey.trim()) {
- return
- }
+ onChange(updatedMetadata)
+ setNewKey('')
+ setNewValue('')
+ setLocalError(null)
+ }
- if (newKey !== oldKey && value[newKey]) {
- setLocalError(`Key "${newKey}" already exists`)
- return
- }
+ const handleRemovePair = (key: string) => {
+ const updatedMetadata = { ...value }
+ delete updatedMetadata[key]
+ onChange(updatedMetadata)
+ }
- const updatedMetadata = { ...value }
- delete updatedMetadata[oldKey]
- updatedMetadata[newKey] = itemValue
- onChange(updatedMetadata)
- setLocalError(null)
+ const handleKeyChange = (oldKey: string, newKey: string, itemValue: string) => {
+ if (!newKey.trim()) {
+ return
}
- const handleValueChange = (key: string, newValue: string) => {
- const updatedMetadata = {
- ...value,
- [key]: newValue,
- }
- onChange(updatedMetadata)
+ if (newKey !== oldKey && value[newKey]) {
+ setLocalError(`Key "${newKey}" already exists`)
+ return
}
- return (
- <div className={cn("space-y-3", className)}>
- {Object.entries(value).length > 0 && (
- <div className="space-y-2">
- {Object.entries(value).map(([key, val]) => (
- <div key={key} className="flex items-center gap-2">
- <Input
- value={key}
- onChange={(e) => handleKeyChange(key, e.target.value, val)}
- placeholder="Clé"
- className="flex-1"
- />
- <span className="text-muted-foreground">:</span>
- <Input
- value={val}
- onChange={(e) => handleValueChange(key, e.target.value)}
- placeholder="Valeur"
- className="flex-1"
- />
- <Button
- type="button"
- variant="ghost"
- size="icon"
- onClick={() => handleRemovePair(key)}
- className="h-8 w-8 text-destructive"
- >
- <X className="h-4 w-4" />
- <span className="sr-only">Supprimer</span>
- </Button>
- </div>
- ))}
- </div>
- )}
+ const updatedMetadata = { ...value }
+ delete updatedMetadata[oldKey]
+ updatedMetadata[newKey] = itemValue
+ onChange(updatedMetadata)
+ setLocalError(null)
+ }
- {/* Formulaire pour ajouter une nouvelle paire */}
- <div className="flex items-end gap-2">
- <div className="space-y-1 flex-1">
- <Input
- value={newKey}
- onChange={(e) => setNewKey(e.target.value)}
- placeholder="Key"
- className={localError ? "border-destructive" : ""}
- />
- </div>
- <span className="text-muted-foreground mb-2.5">:</span>
- <div className="space-y-1 flex-1">
- <Input value={newValue} onChange={(e) => setNewValue(e.target.value)} placeholder="Value" />
- </div>
- <Button type="button" size="sm" variant="outline" onClick={handleAddPair} className="mb-0.5">
- <PlusCircle className="h-4 w-4 mr-1" />
- Add
- </Button>
+ const handleValueChange = (key: string, newValue: string) => {
+ const updatedMetadata = {
+ ...value,
+ [key]: newValue
+ }
+ onChange(updatedMetadata)
+ }
+
+ return (
+ <div className={cn('space-y-3', className)}>
+ {Object.entries(value).length > 0 && (
+ <div className="space-y-2">
+ {Object.entries(value).map(([key, val]) => (
+ <div key={key} className="flex items-center gap-2">
+ <Input
+ value={key}
+ onChange={(e) => handleKeyChange(key, e.target.value, val)}
+ placeholder="Clé"
+ className="flex-1"
+ />
+ <span className="text-muted-foreground">:</span>
+ <Input
+ value={val}
+ onChange={(e) => handleValueChange(key, e.target.value)}
+ placeholder="Valeur"
+ className="flex-1"
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => handleRemovePair(key)}
+ className="h-8 w-8 text-destructive"
+ >
+ <X className="h-4 w-4" />
+ <span className="sr-only">Supprimer</span>
+ </Button>
</div>
+ ))}
+ </div>
+ )}
- {/* Affichage des erreurs */}
- {(localError || error) && <p className="text-xs text-destructive">{localError || error}</p>}
+ {/* Formulaire pour ajouter une nouvelle paire */}
+ <div className="flex items-end gap-2">
+ <div className="space-y-1 flex-1">
+ <Input
+ value={newKey}
+ onChange={(e) => setNewKey(e.target.value)}
+ placeholder="Key"
+ className={localError ? 'border-destructive' : ''}
+ />
</div>
- )
+ <span className="text-muted-foreground mb-2.5">:</span>
+ <div className="space-y-1 flex-1">
+ <Input
+ value={newValue}
+ onChange={(e) => setNewValue(e.target.value)}
+ placeholder="Value"
+ />
+ </div>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={handleAddPair}
+ className="mb-0.5"
+ >
+ <PlusCircle className="h-4 w-4 mr-1" />
+ Add
+ </Button>
+ </div>
+
+ {/* Affichage des erreurs */}
+ {(localError || error) && <p className="text-xs text-destructive">{localError || error}</p>}
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/graphs/minimap.tsx b/flowsint-app/src/renderer/src/components/graphs/minimap.tsx
index a1f35c9e..18944946 100644
--- a/flowsint-app/src/renderer/src/components/graphs/minimap.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/minimap.tsx
@@ -1,147 +1,141 @@
-import { GraphNode } from '@/types';
-import { useMemo } from 'react';
-import { GRAPH_COLORS } from './graph-viewer';
+import { GraphNode } from '@/types'
+import { useMemo } from 'react'
+import { GRAPH_COLORS } from './graph-viewer'
interface zoomTransform {
- x: number,
- y: number,
- k: number,
+ x: number
+ y: number
+ k: number
}
interface MinimapProps {
- nodes: GraphNode[]
- zoomTransform: zoomTransform
- width?: number,
- height?: number
- canvasWidth: number
- canvasHeight: number
+ nodes: GraphNode[]
+ zoomTransform: zoomTransform
+ width?: number
+ height?: number
+ canvasWidth: number
+ canvasHeight: number
}
const Minimap = ({
- nodes,
- zoomTransform,
- width = 160,
- height = 120,
- canvasWidth = 800,
- canvasHeight = 600,
+ nodes,
+ zoomTransform,
+ width = 160,
+ height = 120,
+ canvasWidth = 800,
+ canvasHeight = 600
}: MinimapProps) => {
- // Calculate the visible viewport in world coordinates
- const invScale = 1 / zoomTransform.k;
-
- // The viewport center in world coordinates
- // zoomTransform.x and zoomTransform.y are screen offsets, so we need to convert them
- const viewportCenterX = zoomTransform.x * invScale;
- const viewportCenterY = zoomTransform.y * invScale;
-
- // Viewport dimensions in world coordinates
- const viewportWidth = canvasWidth * invScale;
- const viewportHeight = canvasHeight * invScale;
-
- // Viewport bounds in world coordinates
- const viewportX1 = viewportCenterX - viewportWidth / 2;
- const viewportY1 = viewportCenterY - viewportHeight / 2;
- const viewportX2 = viewportCenterX + viewportWidth / 2;
- const viewportY2 = viewportCenterY + viewportHeight / 2;
-
- // Calculate global bounding box including nodes and viewport
- const [minX, minY, maxX, maxY] = useMemo(() => {
- const validNodes = nodes.filter(n =>
- typeof n.x === 'number' &&
- typeof n.y === 'number'
- );
-
- if (validNodes.length === 0) {
- // If no nodes, just show the viewport
- return [viewportX1, viewportY1, viewportX2, viewportY2];
- }
-
- const nodeXs = validNodes.map(n => n.x);
- const nodeYs = validNodes.map(n => n.y);
-
- const allX = [...nodeXs, viewportX1, viewportX2];
- const allY = [...nodeYs, viewportY1, viewportY2];
-
- return [
- Math.min(...allX.filter((x): x is number => x !== undefined)),
- Math.min(...allY.filter((y): y is number => y !== undefined)),
- Math.max(...allX.filter((x): x is number => x !== undefined)),
- Math.max(...allY.filter((y): y is number => y !== undefined)),
- ];
- }, [nodes, viewportX1, viewportY1, viewportX2, viewportY2]);
-
- const worldWidth = maxX - minX || 1;
- const worldHeight = maxY - minY || 1;
-
- // Scale to fit everything in the minimap
- const scaleX = width / worldWidth;
- const scaleY = height / worldHeight;
- const scale = Math.min(scaleX, scaleY);
-
- // Center the minimap content
- const offsetX = (width - worldWidth * scale) / 2;
- const offsetY = (height - worldHeight * scale) / 2;
-
- // Project world coordinates to minimap coordinates
- const project = (x, y) => [
- (x - minX) * scale + offsetX,
- (y - minY) * scale + offsetY
- ];
-
- // Project viewport bounds to minimap coordinates
- const [vx1, vy1] = project(viewportX1, viewportY1);
- const [vx2, vy2] = project(viewportX2, viewportY2);
-
- // Calculate viewBox dimensions with padding
- const viewBoxWidth = Math.abs(vx2 - vx1) + 6;
- const viewBoxHeight = Math.abs(vy2 - vy1) + 6;
-
- // Position the viewBox to show the current viewport
- const viewBoxX = Math.min(vx1, vx2) - 3;
- const viewBoxY = Math.min(vy1, vy2) - 3;
-
- // Fixed node radius for consistent sizing
- const nodeRadius = 2;
-
- return (
- <div style={{ width: width, height: height }} className='absolute bottom-3 right-3 bg-background/90 backdrop-blur-sm overflow-hidden border border-border rounded-lg'>
- <svg
- width={width}
- height={height}
- className="bg-transparent"
- style={{ backgroundColor: "transparent" }}
- >
- {nodes
- .filter((n: GraphNode) =>
- typeof n.x === 'number' && typeof n.y === 'number'
- )
- .map((n: GraphNode, i: number) => {
- const [cx, cy] = project(n.x, n.y);
- return (
- <circle
- key={i}
- cx={cx}
- cy={cy}
- r={nodeRadius}
- fill={n.nodeColor || 'currentColor'}
- className="text-foreground"
- />
- );
- })}
-
- {/* Viewport rectangle - shows current visible area */}
- <rect
- x={viewBoxX}
- y={viewBoxY}
- rx={4}
- ry={4}
- width={viewBoxWidth}
- height={viewBoxHeight}
- fill={GRAPH_COLORS.LASSO_FILL}
- stroke={GRAPH_COLORS.LASSO_STROKE}
-
- strokeWidth={1}
- />
- </svg>
- </div>
- );
-};
-
-export default Minimap;
+ // Calculate the visible viewport in world coordinates
+ const invScale = 1 / zoomTransform.k
+
+ // The viewport center in world coordinates
+ // zoomTransform.x and zoomTransform.y are screen offsets, so we need to convert them
+ const viewportCenterX = zoomTransform.x * invScale
+ const viewportCenterY = zoomTransform.y * invScale
+
+ // Viewport dimensions in world coordinates
+ const viewportWidth = canvasWidth * invScale
+ const viewportHeight = canvasHeight * invScale
+
+ // Viewport bounds in world coordinates
+ const viewportX1 = viewportCenterX - viewportWidth / 2
+ const viewportY1 = viewportCenterY - viewportHeight / 2
+ const viewportX2 = viewportCenterX + viewportWidth / 2
+ const viewportY2 = viewportCenterY + viewportHeight / 2
+
+ // Calculate global bounding box including nodes and viewport
+ const [minX, minY, maxX, maxY] = useMemo(() => {
+ const validNodes = nodes.filter((n) => typeof n.x === 'number' && typeof n.y === 'number')
+
+ if (validNodes.length === 0) {
+ // If no nodes, just show the viewport
+ return [viewportX1, viewportY1, viewportX2, viewportY2]
+ }
+
+ const nodeXs = validNodes.map((n) => n.x)
+ const nodeYs = validNodes.map((n) => n.y)
+
+ const allX = [...nodeXs, viewportX1, viewportX2]
+ const allY = [...nodeYs, viewportY1, viewportY2]
+
+ return [
+ Math.min(...allX.filter((x): x is number => x !== undefined)),
+ Math.min(...allY.filter((y): y is number => y !== undefined)),
+ Math.max(...allX.filter((x): x is number => x !== undefined)),
+ Math.max(...allY.filter((y): y is number => y !== undefined))
+ ]
+ }, [nodes, viewportX1, viewportY1, viewportX2, viewportY2])
+
+ const worldWidth = maxX - minX || 1
+ const worldHeight = maxY - minY || 1
+
+ // Scale to fit everything in the minimap
+ const scaleX = width / worldWidth
+ const scaleY = height / worldHeight
+ const scale = Math.min(scaleX, scaleY)
+
+ // Center the minimap content
+ const offsetX = (width - worldWidth * scale) / 2
+ const offsetY = (height - worldHeight * scale) / 2
+
+ // Project world coordinates to minimap coordinates
+ const project = (x, y) => [(x - minX) * scale + offsetX, (y - minY) * scale + offsetY]
+
+ // Project viewport bounds to minimap coordinates
+ const [vx1, vy1] = project(viewportX1, viewportY1)
+ const [vx2, vy2] = project(viewportX2, viewportY2)
+
+ // Calculate viewBox dimensions with padding
+ const viewBoxWidth = Math.abs(vx2 - vx1) + 6
+ const viewBoxHeight = Math.abs(vy2 - vy1) + 6
+
+ // Position the viewBox to show the current viewport
+ const viewBoxX = Math.min(vx1, vx2) - 3
+ const viewBoxY = Math.min(vy1, vy2) - 3
+
+ // Fixed node radius for consistent sizing
+ const nodeRadius = 2
+
+ return (
+ <div
+ style={{ width: width, height: height }}
+ className="absolute bottom-3 right-3 bg-background/90 backdrop-blur-sm overflow-hidden border border-border rounded-lg"
+ >
+ <svg
+ width={width}
+ height={height}
+ className="bg-transparent"
+ style={{ backgroundColor: 'transparent' }}
+ >
+ {nodes
+ .filter((n: GraphNode) => typeof n.x === 'number' && typeof n.y === 'number')
+ .map((n: GraphNode, i: number) => {
+ const [cx, cy] = project(n.x, n.y)
+ return (
+ <circle
+ key={i}
+ cx={cx}
+ cy={cy}
+ r={nodeRadius}
+ fill={n.nodeColor || 'currentColor'}
+ className="text-foreground"
+ />
+ )
+ })}
+
+ {/* Viewport rectangle - shows current visible area */}
+ <rect
+ x={viewBoxX}
+ y={viewBoxY}
+ rx={4}
+ ry={4}
+ width={viewBoxWidth}
+ height={viewBoxHeight}
+ fill={GRAPH_COLORS.LASSO_FILL}
+ stroke={GRAPH_COLORS.LASSO_STROKE}
+ strokeWidth={1}
+ />
+ </svg>
+ </div>
+ )
+}
+
+export default Minimap
diff --git a/flowsint-app/src/renderer/src/components/graphs/new-sketch.tsx b/flowsint-app/src/renderer/src/components/graphs/new-sketch.tsx
index c513c8a1..836af172 100644
--- a/flowsint-app/src/renderer/src/components/graphs/new-sketch.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/new-sketch.tsx
@@ -1,150 +1,148 @@
-
-import { useState, type ReactNode } from "react"
-import { useForm } from "react-hook-form"
-import { useRouter, useParams } from "@tanstack/react-router"
-import { toast } from "sonner"
-import { sketchService } from "@/api/sketch-service"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { queryKeys } from "@/api/query-keys"
-import { Button } from "@/components/ui/button"
+import { useState, type ReactNode } from 'react'
+import { useForm } from 'react-hook-form'
+import { useRouter, useParams } from '@tanstack/react-router'
+import { toast } from 'sonner'
+import { sketchService } from '@/api/sketch-service'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { queryKeys } from '@/api/query-keys'
+import { Button } from '@/components/ui/button'
import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog"
-import { Input } from "@/components/ui/input"
-import { Label } from "@/components/ui/label"
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger
+} from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
interface FormValues {
- title: string
- description?: string
+ title: string
+ description?: string
}
interface NewSketchProps {
- children: ReactNode
+ children: ReactNode
}
export default function NewSketch({ children }: NewSketchProps) {
- const [open, setOpen] = useState(false)
- const router = useRouter()
- const { investigationId } = useParams({ strict: false })
- const queryClient = useQueryClient()
+ const [open, setOpen] = useState(false)
+ const router = useRouter()
+ const { investigationId } = useParams({ strict: false })
+ const queryClient = useQueryClient()
- const {
- register,
- handleSubmit,
- formState: { errors, isSubmitting },
- reset,
- } = useForm<FormValues>()
+ const {
+ register,
+ handleSubmit,
+ formState: { errors, isSubmitting },
+ reset
+ } = useForm<FormValues>()
- // Create sketch mutation
- const createSketchMutation = useMutation({
- mutationFn: sketchService.create,
- onSuccess: (result) => {
- if (result.id) {
- toast.success("New sketch created.")
- router.navigate({
- to: `/dashboard/investigations/${investigationId}/graph/${result.id}`,
- })
- reset()
- // Invalidate sketches list and investigation sketches
- queryClient.invalidateQueries({
- queryKey: queryKeys.sketches.list
- })
- if (investigationId) {
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.sketches(investigationId)
- })
- }
- } else {
- toast.error(result.error || "Failed to create sketch.")
- }
- },
- onError: (error) => {
- toast.error(error.message)
+ // Create sketch mutation
+ const createSketchMutation = useMutation({
+ mutationFn: sketchService.create,
+ onSuccess: (result) => {
+ if (result.id) {
+ toast.success('New sketch created.')
+ router.navigate({
+ to: `/dashboard/investigations/${investigationId}/graph/${result.id}`
+ })
+ reset()
+ // Invalidate sketches list and investigation sketches
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.sketches.list
+ })
+ if (investigationId) {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.sketches(investigationId)
+ })
}
- })
+ } else {
+ toast.error(result.error || 'Failed to create sketch.')
+ }
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ }
+ })
- async function onSubmit(data: FormValues) {
- if (!investigationId) {
- toast.error("A sketch must be related to an investigation.")
- return
- }
+ async function onSubmit(data: FormValues) {
+ if (!investigationId) {
+ toast.error('A sketch must be related to an investigation.')
+ return
+ }
- try {
- const payload = {
- ...data,
- investigation_id: investigationId,
- }
- await createSketchMutation.mutateAsync(JSON.stringify(payload))
- } catch (error) {
- console.error('Error creating sketch:', error)
- }
+ try {
+ const payload = {
+ ...data,
+ investigation_id: investigationId
+ }
+ await createSketchMutation.mutateAsync(JSON.stringify(payload))
+ } catch (error) {
+ console.error('Error creating sketch:', error)
}
+ }
- const formContent = (
- <form onSubmit={handleSubmit(onSubmit)}>
- <div className="grid gap-4 py-4">
- <div className="grid gap-2">
- <Label htmlFor="title">Sketch name</Label>
- <Input
- id="title"
- {...register("title", { required: "Title is required" })}
- placeholder="Fraud suspicion"
- aria-invalid={errors.title ? "true" : "false"}
- />
- {errors.title && (
- <p role="alert" className="text-red-600 text-sm mt-1">
- {errors.title.message}
- </p>
- )}
- </div>
- <div className="grid gap-2">
- <Label htmlFor="description">Description</Label>
- <Input
- id="description"
- {...register("description")}
- placeholder="Phishing domain external scope"
- />
- </div>
- </div>
+ const formContent = (
+ <form onSubmit={handleSubmit(onSubmit)}>
+ <div className="grid gap-4 py-4">
+ <div className="grid gap-2">
+ <Label htmlFor="title">Sketch name</Label>
+ <Input
+ id="title"
+ {...register('title', { required: 'Title is required' })}
+ placeholder="Fraud suspicion"
+ aria-invalid={errors.title ? 'true' : 'false'}
+ />
+ {errors.title && (
+ <p role="alert" className="text-red-600 text-sm mt-1">
+ {errors.title.message}
+ </p>
+ )}
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="description">Description</Label>
+ <Input
+ id="description"
+ {...register('description')}
+ placeholder="Phishing domain external scope"
+ />
+ </div>
+ </div>
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => {
- reset()
- setOpen(false)
- }}
- disabled={isSubmitting}
- >
- Cancel
- </Button>
- <Button type="submit" disabled={isSubmitting}>
- {isSubmitting ? "Saving..." : "Save"}
- </Button>
- </DialogFooter>
- </form>
- )
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => {
+ reset()
+ setOpen(false)
+ }}
+ disabled={isSubmitting}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isSubmitting}>
+ {isSubmitting ? 'Saving...' : 'Save'}
+ </Button>
+ </DialogFooter>
+ </form>
+ )
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger asChild>
- <span role="button">{children}</span>
- </DialogTrigger>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>New sketch</DialogTitle>
- <DialogDescription>Create a new blank sketch.</DialogDescription>
- </DialogHeader>
- {formContent}
- </DialogContent>
- </Dialog>
- )
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <span role="button">{children}</span>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>New sketch</DialogTitle>
+ <DialogDescription>Create a new blank sketch.</DialogDescription>
+ </DialogHeader>
+ {formContent}
+ </DialogContent>
+ </Dialog>
+ )
}
-
diff --git a/flowsint-app/src/renderer/src/components/graphs/node-actions.tsx b/flowsint-app/src/renderer/src/components/graphs/node-actions.tsx
index 299c1917..e2605c58 100644
--- a/flowsint-app/src/renderer/src/components/graphs/node-actions.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/node-actions.tsx
@@ -1,146 +1,154 @@
-import React, { memo, useCallback } from 'react';
-import { Button } from '@/components/ui/button';
-import { Pencil, Trash2, Sparkles, Plus } from 'lucide-react';
-import { useGraphStore } from '@/stores/graph-store';
-import { useParams } from '@tanstack/react-router';
-import { useConfirm } from '@/components/use-confirm-dialog';
-import { toast } from 'sonner';
-import { sketchService } from '@/api/sketch-service';
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from '@/components/ui/tooltip';
-import { useLayoutStore } from '@/stores/layout-store';
-import { GraphNode } from '@/types';
+import React, { memo, useCallback } from 'react'
+import { Button } from '@/components/ui/button'
+import { Pencil, Trash2, Sparkles, Plus } from 'lucide-react'
+import { useGraphStore } from '@/stores/graph-store'
+import { useParams } from '@tanstack/react-router'
+import { useConfirm } from '@/components/use-confirm-dialog'
+import { toast } from 'sonner'
+import { sketchService } from '@/api/sketch-service'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
+import { useLayoutStore } from '@/stores/layout-store'
+import { GraphNode } from '@/types'
-
-const NodeActions = memo(({ node, setMenu }: { node: GraphNode, setMenu?: (menu: any | null) => void }) => {
+const NodeActions = memo(
+ ({ node, setMenu }: { node: GraphNode; setMenu?: (menu: any | null) => void }) => {
const { id: sketchId } = useParams({ strict: false })
- const { confirm } = useConfirm();
- const setOpenMainDialog = useGraphStore(state => state.setOpenMainDialog)
- const setRelatedNodeToAdd = useGraphStore(state => state.setRelatedNodeToAdd)
- const removeNodes = useGraphStore(s => s.removeNodes);
- const toggleNodeSelection = useGraphStore(s => s.toggleNodeSelection);
- const openChat = useLayoutStore(s => s.openChat);
- const setCurrentNode = useGraphStore(s => s.setCurrentNode);
- const setOpenNodeEditorModal = useGraphStore(s => s.setOpenNodeEditorModal);
+ const { confirm } = useConfirm()
+ const setOpenMainDialog = useGraphStore((state) => state.setOpenMainDialog)
+ const setRelatedNodeToAdd = useGraphStore((state) => state.setRelatedNodeToAdd)
+ const removeNodes = useGraphStore((s) => s.removeNodes)
+ const toggleNodeSelection = useGraphStore((s) => s.toggleNodeSelection)
+ const openChat = useLayoutStore((s) => s.openChat)
+ const setCurrentNode = useGraphStore((s) => s.setCurrentNode)
+ const setOpenNodeEditorModal = useGraphStore((s) => s.setOpenNodeEditorModal)
// Add relation dialog
const handleOpenMainDialog = useCallback(() => {
- setRelatedNodeToAdd(node)
- setOpenMainDialog(true)
- setMenu?.(null)
+ setRelatedNodeToAdd(node)
+ setOpenMainDialog(true)
+ setMenu?.(null)
}, [setOpenMainDialog, setMenu, node])
// Ask AI dialog
- const handleAskAI = useCallback((e: React.MouseEvent) => {
- e.stopPropagation();
+ const handleAskAI = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation()
toggleNodeSelection(node, false)
openChat()
setMenu?.(null)
- }, [node, toggleNodeSelection, openChat, setMenu])
+ },
+ [node, toggleNodeSelection, openChat, setMenu]
+ )
// Edit node dialog
- const handleEditNode = useCallback((e: React.MouseEvent) => {
- e.stopPropagation();
+ const handleEditNode = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation()
const typedNode = node as GraphNode
setCurrentNode(typedNode)
setOpenNodeEditorModal(true)
setMenu?.(null)
- }, [node, setCurrentNode, setOpenNodeEditorModal])
+ },
+ [node, setCurrentNode, setOpenNodeEditorModal]
+ )
// Delete node
const handleDeleteNode = async () => {
- if (!node.id || !sketchId) return
- if (!await confirm({ title: `You are about to delete this node ?`, message: "The action is irreversible." })) return
- toast.promise(
- (async () => {
- removeNodes([node.id])
- return sketchService.deleteNodes(sketchId, JSON.stringify({ nodeIds: [node.id] }))
- })(),
- {
- loading: `Deleting ${node.data.label}...`,
- success: 'Node deleted successfully.',
- error: 'Failed to delete node.'
- }
- )
+ if (!node.id || !sketchId) return
+ if (
+ !(await confirm({
+ title: `You are about to delete this node ?`,
+ message: 'The action is irreversible.'
+ }))
+ )
+ return
+ toast.promise(
+ (async () => {
+ removeNodes([node.id])
+ return sketchService.deleteNodes(sketchId, JSON.stringify({ nodeIds: [node.id] }))
+ })(),
+ {
+ loading: `Deleting ${node.data.label}...`,
+ success: 'Node deleted successfully.',
+ error: 'Failed to delete node.'
+ }
+ )
}
return (
- <div className="flex items-center gap-1">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- onClick={handleOpenMainDialog}
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
- >
- <Plus className="h-3.5 w-3.5" strokeWidth={2} />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>Add relation</p>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- onClick={handleAskAI}
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
- >
- <Sparkles className="h-3 w-3" strokeWidth={1.5} />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>Ask AI</p>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- onClick={handleEditNode}
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
- >
- <Pencil className="h-3 w-3" strokeWidth={1.5} />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>Edit node</p>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100 text-destructive hover:text-destructive"
- onClick={handleDeleteNode}
- >
- <Trash2 className="h-3 w-3" strokeWidth={1.5} />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>Delete node</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
+ <div className="flex items-center gap-1">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ onClick={handleOpenMainDialog}
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
+ >
+ <Plus className="h-3.5 w-3.5" strokeWidth={2} />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Add relation</p>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ onClick={handleAskAI}
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
+ >
+ <Sparkles className="h-3 w-3" strokeWidth={1.5} />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Ask AI</p>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ onClick={handleEditNode}
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
+ >
+ <Pencil className="h-3 w-3" strokeWidth={1.5} />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Edit node</p>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100 text-destructive hover:text-destructive"
+ onClick={handleDeleteNode}
+ >
+ <Trash2 className="h-3 w-3" strokeWidth={1.5} />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Delete node</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
)
-})
+ }
+)
-export default NodeActions
\ No newline at end of file
+export default NodeActions
diff --git a/flowsint-app/src/renderer/src/components/graphs/nodes-panel.tsx b/flowsint-app/src/renderer/src/components/graphs/nodes-panel.tsx
index fdfa2311..26b98764 100644
--- a/flowsint-app/src/renderer/src/components/graphs/nodes-panel.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/nodes-panel.tsx
@@ -1,323 +1,356 @@
-import type React from "react"
-import { memo, useMemo, useState, useCallback, useRef } from "react"
+import type React from 'react'
+import { memo, useMemo, useState, useCallback, useRef } from 'react'
import { useVirtualizer } from '@tanstack/react-virtual'
-import { useGraphStore } from "@/stores/graph-store"
-import { Button } from "@/components/ui/button"
-import { Badge } from "@/components/ui/badge"
-import { TypeBadge } from "@/components/type-badge"
-import { Search, FunnelPlus, XIcon } from "lucide-react"
-import { Input } from "@/components/ui/input"
-import { cn } from "@/lib/utils"
+import { useGraphStore } from '@/stores/graph-store'
+import { Button } from '@/components/ui/button'
+import { Badge } from '@/components/ui/badge'
+import { TypeBadge } from '@/components/type-badge'
+import { Search, FunnelPlus, XIcon } from 'lucide-react'
+import { Input } from '@/components/ui/input'
+import { cn } from '@/lib/utils'
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import { GraphNode } from '@/types';
-import { Checkbox } from "@/components/ui/checkbox"
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { GraphNode } from '@/types'
+import { Checkbox } from '@/components/ui/checkbox'
const ITEM_HEIGHT = 40
// Mémoiser le composant NodeRenderer
const NodeRenderer = memo(
- ({
- node,
- setCurrentNode,
- onCheckboxChange,
- isNodeChecked,
- isCurrent
- }: {
- node: any
- setCurrentNode: (node: GraphNode) => void
- onCheckboxChange: (node: GraphNode, checked: boolean) => void
- isNodeChecked: (nodeId: string) => boolean
- isCurrent: (nodeId: string) => boolean
- }) => {
- const handleClick = useCallback(() => setCurrentNode(node), [node, setCurrentNode])
- const handleCheckboxChange = useCallback(
- (checked: boolean) => {
- onCheckboxChange(node, checked)
- },
- [node, onCheckboxChange],
- )
+ ({
+ node,
+ setCurrentNode,
+ onCheckboxChange,
+ isNodeChecked,
+ isCurrent
+ }: {
+ node: any
+ setCurrentNode: (node: GraphNode) => void
+ onCheckboxChange: (node: GraphNode, checked: boolean) => void
+ isNodeChecked: (nodeId: string) => boolean
+ isCurrent: (nodeId: string) => boolean
+ }) => {
+ const handleClick = useCallback(() => setCurrentNode(node), [node, setCurrentNode])
+ const handleCheckboxChange = useCallback(
+ (checked: boolean) => {
+ onCheckboxChange(node, checked)
+ },
+ [node, onCheckboxChange]
+ )
- return (
- <div className={cn("flex items-center overflow-hidden hover:bg-muted/50 border-b h-full", isCurrent(node.id) && "bg-muted/70")}>
- <div className="pl-2">
- <Checkbox checked={isNodeChecked(node.id)} onCheckedChange={handleCheckboxChange} className="mr-1 border-border" />
- </div>
- <button
- className={cn(
- "flex-1 flex truncate mt-0 text-sm font-medium overflow-hidden duration-0 items-center justify-start p-4 !py-5 rounded-none text-left h-full",
- )}
- onClick={handleClick}
- >
- <div className="grow truncate text-ellipsis">{node?.data?.label}</div>
- <TypeBadge className="ml-1" type={node?.data?.type} />
- </button>
- </div>
- )
- },
+ return (
+ <div
+ className={cn(
+ 'flex items-center overflow-hidden hover:bg-muted/50 border-b h-full',
+ isCurrent(node.id) && 'bg-muted/70'
+ )}
+ >
+ <div className="pl-2">
+ <Checkbox
+ checked={isNodeChecked(node.id)}
+ onCheckedChange={handleCheckboxChange}
+ className="mr-1 border-border"
+ />
+ </div>
+ <button
+ className={cn(
+ 'flex-1 flex truncate mt-0 text-sm font-medium overflow-hidden duration-0 items-center justify-start p-4 !py-5 rounded-none text-left h-full'
+ )}
+ onClick={handleClick}
+ >
+ <div className="grow truncate text-ellipsis">{node?.data?.label}</div>
+ <TypeBadge className="ml-1" type={node?.data?.type} />
+ </button>
+ </div>
+ )
+ }
)
// Composant pour un item virtualisé
-const VirtualizedItem = memo(({
+const VirtualizedItem = memo(
+ ({
node,
setCurrentNode,
onCheckboxChange,
isNodeChecked,
isCurrent
-}: {
+ }: {
index: number
node: GraphNode
setCurrentNode: (node: GraphNode) => void
onCheckboxChange: (node: GraphNode, checked: boolean) => void
isNodeChecked: (nodeId: string) => boolean
isCurrent: (nodeId: string) => boolean
-}) => {
+ }) => {
return (
- <NodeRenderer
- node={node}
- isCurrent={isCurrent}
- setCurrentNode={setCurrentNode}
- onCheckboxChange={onCheckboxChange}
- isNodeChecked={isNodeChecked}
- />
+ <NodeRenderer
+ node={node}
+ isCurrent={isCurrent}
+ setCurrentNode={setCurrentNode}
+ onCheckboxChange={onCheckboxChange}
+ isNodeChecked={isNodeChecked}
+ />
)
-})
+ }
+)
const NodesPanel = memo(({ nodes, isLoading }: { nodes: GraphNode[]; isLoading?: boolean }) => {
- const currentNode = useGraphStore((state) => state.currentNode)
- const setCurrentNode = useGraphStore((state) => state.setCurrentNode)
- const setSelectedNodes = useGraphStore((state) => state.setSelectedNodes)
- const selectedNodes = useGraphStore((state) => state.selectedNodes || [])
- const [searchQuery, setSearchQuery] = useState<string>("")
- const [filters, setFilters] = useState<string[] | null>(null)
-
- const types = useMemo(() => Array.from(new Set(nodes.map(n => n.data.type))), [nodes])
+ const currentNode = useGraphStore((state) => state.currentNode)
+ const setCurrentNode = useGraphStore((state) => state.setCurrentNode)
+ const setSelectedNodes = useGraphStore((state) => state.setSelectedNodes)
+ const selectedNodes = useGraphStore((state) => state.selectedNodes || [])
+ const [searchQuery, setSearchQuery] = useState<string>('')
+ const [filters, setFilters] = useState<string[] | null>(null)
- // Ref pour le conteneur parent du virtualizer
- const parentRef = useRef<HTMLDivElement>(null)
+ const types = useMemo(() => Array.from(new Set(nodes.map((n) => n.data.type))), [nodes])
- const filteredNodes = useMemo(() => {
- const searchText = searchQuery.toLowerCase()
- return nodes?.filter((node) => {
- const matchesSearch =
- //@ts-ignore
- node?.data?.label?.toLowerCase().includes(searchText) || node?.id?.toLowerCase().includes(searchText)
+ // Ref pour le conteneur parent du virtualizer
+ const parentRef = useRef<HTMLDivElement>(null)
- const matchesFilter = !filters || filters.some(filter =>
- filter.toLowerCase() === (node?.data?.type as string)?.toLowerCase()
- )
+ const filteredNodes = useMemo(() => {
+ const searchText = searchQuery.toLowerCase()
+ return nodes?.filter((node) => {
+ const matchesSearch =
+ //@ts-ignore
+ node?.data?.label?.toLowerCase().includes(searchText) ||
+ node?.id?.toLowerCase().includes(searchText)
- return matchesSearch && matchesFilter
- })
- }, [nodes, searchQuery, filters])
+ const matchesFilter =
+ !filters ||
+ filters.some(
+ (filter) => filter.toLowerCase() === (node?.data?.type as string)?.toLowerCase()
+ )
- // Configuration du virtualizer
- const virtualizer = useVirtualizer({
- count: filteredNodes?.length || 0,
- getScrollElement: () => parentRef.current,
- estimateSize: () => ITEM_HEIGHT,
- overscan: 5, // Nombre d'éléments à pré-rendre en dehors de la zone visible
+ return matchesSearch && matchesFilter
})
+ }, [nodes, searchQuery, filters])
- const toggleFilter = useCallback((filter: string | null) => {
- if (filter === null) {
- setFilters(null)
- } else {
- const currentFilters = filters || []
- const isChecked = currentFilters.includes(filter)
- const newFilters = isChecked ? currentFilters.filter((f) => f !== filter) : [...currentFilters, filter.toLowerCase()]
- setFilters(newFilters.length === 0 ? null : newFilters)
- }
- }, [filters, setFilters])
+ // Configuration du virtualizer
+ const virtualizer = useVirtualizer({
+ count: filteredNodes?.length || 0,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => ITEM_HEIGHT,
+ overscan: 5 // Nombre d'éléments à pré-rendre en dehors de la zone visible
+ })
- const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
- setSearchQuery(e.target.value)
- }, [])
-
- const clearFilters = useCallback(() => {
+ const toggleFilter = useCallback(
+ (filter: string | null) => {
+ if (filter === null) {
setFilters(null)
- }, [])
+ } else {
+ const currentFilters = filters || []
+ const isChecked = currentFilters.includes(filter)
+ const newFilters = isChecked
+ ? currentFilters.filter((f) => f !== filter)
+ : [...currentFilters, filter.toLowerCase()]
+ setFilters(newFilters.length === 0 ? null : newFilters)
+ }
+ },
+ [filters, setFilters]
+ )
- const isNodeChecked = useCallback(
- (nodeId: string) => {
- return selectedNodes.some((node) => node.id === nodeId)
- },
- [selectedNodes],
- )
+ const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ setSearchQuery(e.target.value)
+ }, [])
- const isCurrent = useCallback(
- (nodeId: string) => {
- return currentNode?.id === nodeId
- },
- [currentNode],
- )
+ const clearFilters = useCallback(() => {
+ setFilters(null)
+ }, [])
- const handleCheckAll = useCallback(
- (checked: boolean) => {
- if (!checked) {
- setSelectedNodes([])
- return
- }
- if (filters?.length || searchQuery) {
- setSelectedNodes(filteredNodes)
- }
- else setSelectedNodes(nodes)
- },
- [nodes, filteredNodes, filters, searchQuery, selectedNodes, setSelectedNodes],
- )
+ const isNodeChecked = useCallback(
+ (nodeId: string) => {
+ return selectedNodes.some((node) => node.id === nodeId)
+ },
+ [selectedNodes]
+ )
- const handleCheckboxChange = useCallback(
- (node: GraphNode, checked: boolean) => {
- if (checked) {
- setSelectedNodes([...selectedNodes.filter((n) => n.id !== node.id), node])
- } else {
- setSelectedNodes(selectedNodes.filter((n) => n.id !== node.id))
- }
- },
- [selectedNodes, setSelectedNodes],
- )
+ const isCurrent = useCallback(
+ (nodeId: string) => {
+ return currentNode?.id === nodeId
+ },
+ [currentNode]
+ )
- return (
- <div className="overflow-hidden bg-card h-full flex flex-col w-full !p-0 !m-0">
- {/* Header fixe */}
- <div className="sticky border-b top-0 p-2 bg-card z-10 flex-shrink-0">
+ const handleCheckAll = useCallback(
+ (checked: boolean) => {
+ if (!checked) {
+ setSelectedNodes([])
+ return
+ }
+ if (filters?.length || searchQuery) {
+ setSelectedNodes(filteredNodes)
+ } else setSelectedNodes(nodes)
+ },
+ [nodes, filteredNodes, filters, searchQuery, selectedNodes, setSelectedNodes]
+ )
+
+ const handleCheckboxChange = useCallback(
+ (node: GraphNode, checked: boolean) => {
+ if (checked) {
+ setSelectedNodes([...selectedNodes.filter((n) => n.id !== node.id), node])
+ } else {
+ setSelectedNodes(selectedNodes.filter((n) => n.id !== node.id))
+ }
+ },
+ [selectedNodes, setSelectedNodes]
+ )
- <div className="flex items-center gap-2">
- <div>
- <Checkbox onCheckedChange={handleCheckAll} className="mr-1" />
- </div>
- <Badge className="h-7" variant={"outline"}>
- <span className="font-semibold">
- {(filters?.length || searchQuery) ? `${filteredNodes?.length} / ${nodes?.length || 0}` : nodes?.length || 0}</span>{" "}
- <span className="font-normal opacity-60">nodes</span>
- </Badge>
- <div className="relative grow">
- <Search className="absolute left-2.5 top-1.5 h-4 w-4 text-muted-foreground" />
- <Input
- type="search"
- placeholder="Search..."
- className="pl-8 h-7 border-border"
- value={searchQuery}
- onChange={handleSearchChange}
- />
- </div>
- <DropdownMenu>
- <div>
- <DropdownMenuTrigger asChild>
- <div>
- <Button variant={"outline"} className="h-7 w-8 relative border-border border" size={"icon"}>
- <FunnelPlus className={cn("opacity-60 h-3 w-3", filters && "opacity-100")} />
- {filters && (
- <Badge className="absolute -top-2 -right-1 text-xs rounded-full h-4 w-4 text-white" variant={"default"}>
- {filters.length}
- </Badge>
- )}
- </Button>
- </div>
- </DropdownMenuTrigger>
- </div>
- <DropdownMenuContent className="w-48 max-h-[50vh] space-y-1 overflow-y-auto">
- <DropdownMenuLabel>
- {filters ? (
- <Badge variant={"outline"} className="flex items-center gap-1 pr-1">
- {filters?.length} filter(s)
- <Button size={"icon"} variant={"ghost"} className="h-5 w-5 rounded-full" onClick={clearFilters}>
- <XIcon className="h-3 w-3" />
- </Button>
- </Badge>
- ) : (
- "filters"
- )}
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- <DropdownMenuItem className={cn(filters == null && "bg-primary")} onClick={() => toggleFilter(null)}>
- All
- </DropdownMenuItem>
- {types.map((type: string) => (
- <DropdownMenuItem
- className={cn(filters?.includes(type) && "bg-primary/30")}
- key={type}
- onClick={() => toggleFilter(type)}
- >
- {type || "unknown"}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
+ return (
+ <div className="overflow-hidden bg-card h-full flex flex-col w-full !p-0 !m-0">
+ {/* Header fixe */}
+ <div className="sticky border-b top-0 p-2 bg-card z-10 flex-shrink-0">
+ <div className="flex items-center gap-2">
+ <div>
+ <Checkbox onCheckedChange={handleCheckAll} className="mr-1" />
+ </div>
+ <Badge className="h-7" variant={'outline'}>
+ <span className="font-semibold">
+ {filters?.length || searchQuery
+ ? `${filteredNodes?.length} / ${nodes?.length || 0}`
+ : nodes?.length || 0}
+ </span>{' '}
+ <span className="font-normal opacity-60">nodes</span>
+ </Badge>
+ <div className="relative grow">
+ <Search className="absolute left-2.5 top-1.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ type="search"
+ placeholder="Search..."
+ className="pl-8 h-7 border-border"
+ value={searchQuery}
+ onChange={handleSearchChange}
+ />
+ </div>
+ <DropdownMenu>
+ <div>
+ <DropdownMenuTrigger asChild>
+ <div>
+ <Button
+ variant={'outline'}
+ className="h-7 w-8 relative border-border border"
+ size={'icon'}
+ >
+ <FunnelPlus className={cn('opacity-60 h-3 w-3', filters && 'opacity-100')} />
+ {filters && (
+ <Badge
+ className="absolute -top-2 -right-1 text-xs rounded-full h-4 w-4 text-white"
+ variant={'default'}
+ >
+ {filters.length}
+ </Badge>
+ )}
+ </Button>
</div>
+ </DropdownMenuTrigger>
</div>
-
- {/* Contenu principal */}
- <div className="flex-1 min-h-0">
- {!isLoading && filteredNodes?.length === 0 && searchQuery === "" && (
- <div className="text-sm p-4 text-center">
- <p className="border rounded-md border-dashed p-4 text-center">
- Drag and drop you first node in the "items" section.
- </p>
- </div>
+ <DropdownMenuContent className="w-48 max-h-[50vh] space-y-1 overflow-y-auto">
+ <DropdownMenuLabel>
+ {filters ? (
+ <Badge variant={'outline'} className="flex items-center gap-1 pr-1">
+ {filters?.length} filter(s)
+ <Button
+ size={'icon'}
+ variant={'ghost'}
+ className="h-5 w-5 rounded-full"
+ onClick={clearFilters}
+ >
+ <XIcon className="h-3 w-3" />
+ </Button>
+ </Badge>
+ ) : (
+ 'filters'
)}
- {/* {isLoading || !filteredNodes?.length && (
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className={cn(filters == null && 'bg-primary')}
+ onClick={() => toggleFilter(null)}
+ >
+ All
+ </DropdownMenuItem>
+ {types.map((type: string) => (
+ <DropdownMenuItem
+ className={cn(filters?.includes(type) && 'bg-primary/30')}
+ key={type}
+ onClick={() => toggleFilter(type)}
+ >
+ {type || 'unknown'}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+
+ {/* Contenu principal */}
+ <div className="flex-1 min-h-0">
+ {!isLoading && filteredNodes?.length === 0 && searchQuery === '' && (
+ <div className="text-sm p-4 text-center">
+ <p className="border rounded-md border-dashed p-4 text-center">
+ Drag and drop you first node in the "items" section.
+ </p>
+ </div>
+ )}
+ {/* {isLoading || !filteredNodes?.length && (
<div className="p-2"><SkeletonList rowCount={7} /></div>
)} */}
- {filteredNodes?.length === 0 && searchQuery && (
- <div className="p-4 text-center text-muted-foreground">
- No nodes match your search
- </div>
- )}
+ {filteredNodes?.length === 0 && searchQuery && (
+ <div className="p-4 text-center text-muted-foreground">No nodes match your search</div>
+ )}
- {/* Liste virtualisée */}
- {!isLoading && filteredNodes && filteredNodes.length > 0 && (
- <div
- ref={parentRef}
- className="h-full overflow-auto"
- style={{
- contain: 'strict',
- }}
- >
- <div
- style={{
- height: `${virtualizer.getTotalSize()}px`,
- width: '100%',
- position: 'relative',
- }}
- >
- {virtualizer.getVirtualItems().map((virtualItem) => {
- const node = filteredNodes[virtualItem.index]
- return (
- <div
- key={virtualItem.key}
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- width: '100%',
- height: `${virtualItem.size}px`,
- transform: `translateY(${virtualItem.start}px)`,
- }}
- >
- <VirtualizedItem
- index={virtualItem.index}
- node={node}
- isCurrent={isCurrent}
- setCurrentNode={setCurrentNode}
- onCheckboxChange={handleCheckboxChange}
- isNodeChecked={isNodeChecked}
- />
- </div>
- )
- })}
- </div>
- </div>
- )}
+ {/* Liste virtualisée */}
+ {!isLoading && filteredNodes && filteredNodes.length > 0 && (
+ <div
+ ref={parentRef}
+ className="h-full overflow-auto"
+ style={{
+ contain: 'strict'
+ }}
+ >
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: '100%',
+ position: 'relative'
+ }}
+ >
+ {virtualizer.getVirtualItems().map((virtualItem) => {
+ const node = filteredNodes[virtualItem.index]
+ return (
+ <div
+ key={virtualItem.key}
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ height: `${virtualItem.size}px`,
+ transform: `translateY(${virtualItem.start}px)`
+ }}
+ >
+ <VirtualizedItem
+ index={virtualItem.index}
+ node={node}
+ isCurrent={isCurrent}
+ setCurrentNode={setCurrentNode}
+ onCheckboxChange={handleCheckboxChange}
+ isNodeChecked={isNodeChecked}
+ />
+ </div>
+ )
+ })}
</div>
- </div>
- )
+ </div>
+ )}
+ </div>
+ </div>
+ )
})
-export default NodesPanel
\ No newline at end of file
+export default NodesPanel
diff --git a/flowsint-app/src/renderer/src/components/graphs/selected-items-panel.tsx b/flowsint-app/src/renderer/src/components/graphs/selected-items-panel.tsx
index e8fdabb6..b54a8cd8 100644
--- a/flowsint-app/src/renderer/src/components/graphs/selected-items-panel.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/selected-items-panel.tsx
@@ -1,189 +1,207 @@
-import React, { memo, useCallback } from 'react';
-import { Button } from '@/components/ui/button';
-import { Trash2, Sparkles, XIcon, Rocket } from 'lucide-react';
-import { useGraphStore } from '@/stores/graph-store';
-import { useConfirm } from '@/components/use-confirm-dialog';
-import { toast } from 'sonner';
-import { sketchService } from '@/api/sketch-service';
-import { GraphNode } from '@/types';
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from '@/components/ui/tooltip';
-import { useLayoutStore } from '@/stores/layout-store';
-import { useNodesDisplaySettings } from '@/stores/node-display-settings';
-import { Badge } from '../ui/badge';
-import LaunchFlow from './launch-transform';
-import { TypeBadge } from '../type-badge';
-import { useParams } from '@tanstack/react-router';
+import React, { memo, useCallback } from 'react'
+import { Button } from '@/components/ui/button'
+import { Trash2, Sparkles, XIcon, Rocket } from 'lucide-react'
+import { useGraphStore } from '@/stores/graph-store'
+import { useConfirm } from '@/components/use-confirm-dialog'
+import { toast } from 'sonner'
+import { sketchService } from '@/api/sketch-service'
+import { GraphNode } from '@/types'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
+import { useLayoutStore } from '@/stores/layout-store'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { Badge } from '../ui/badge'
+import LaunchFlow from './launch-transform'
+import { TypeBadge } from '../type-badge'
+import { useParams } from '@tanstack/react-router'
const SelectedItemsPanel = () => {
- const selectedNodes = useGraphStore(s => s.selectedNodes)
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
- return (
- <div className='w-full flex flex-col h-full'>
- <div className='p-2 flex items-center justify-between border-b'>
- <div className='ml-2 text-sm truncate text-ellipsis'>
- <span className='font-semibold'>{selectedNodes.length}</span> selected items
- </div>
- <ActionBar />
- </div>
- <div className='grow overflow-y-auto'><SelectedList />
- </div>
+ return (
+ <div className="w-full flex flex-col h-full">
+ <div className="p-2 flex items-center justify-between border-b">
+ <div className="ml-2 text-sm truncate text-ellipsis">
+ <span className="font-semibold">{selectedNodes.length}</span> selected items
</div>
- )
+ <ActionBar />
+ </div>
+ <div className="grow overflow-y-auto">
+ <SelectedList />
+ </div>
+ </div>
+ )
}
export default memo(SelectedItemsPanel)
-
-const SelectedNodeItem = memo(({ node }: { node: GraphNode, color: string }) => {
-
- return (<Badge variant="outline" className="flex w-full items-center justify-between text-left border border-border gap-1.5 text-xs p-2 py-1.5">
- <span className='inline-flex items-center gap-2 truncate text-ellipsis'>
- <span className='truncate text-ellipsis'>{node.data?.label || 'Unknown'}</span>
- </span>
- <TypeBadge type={node?.data?.type} />
- </Badge>)
+const SelectedNodeItem = memo(({ node }: { node: GraphNode; color: string }) => {
+ return (
+ <Badge
+ variant="outline"
+ className="flex w-full items-center justify-between text-left border border-border gap-1.5 text-xs p-2 py-1.5"
+ >
+ <span className="inline-flex items-center gap-2 truncate text-ellipsis">
+ <span className="truncate text-ellipsis">{node.data?.label || 'Unknown'}</span>
+ </span>
+ <TypeBadge type={node?.data?.type} />
+ </Badge>
+ )
})
export const SelectedList = () => {
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const colors = useNodesDisplaySettings(s => s.colors)
- const displayItems = selectedNodes?.slice(0, 10) || []
- const remainingCount = selectedNodes?.length ? Math.max(0, selectedNodes.length - 10) : 0
- return (
- <div className="flex flex-col gap-1.5 p-1">
- {displayItems.map((item: GraphNode, index: number) => {
- const color = colors[item.data.type]
- return (
- <SelectedNodeItem key={index} node={item} color={color} />
- )
- })}
- {remainingCount > 0 && <Badge variant="outline" className="flex w-full items-center justify-between text-left border border-border gap-1.5 text-xs p-2 py-1.5">
- <span className='flex items-center gap-2 truncate text-ellipsis'>
- <span className='truncate text-ellipsis'>{remainingCount}+ other</span>
- </span>
- </Badge>}
- </div>
- )
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ const displayItems = selectedNodes?.slice(0, 10) || []
+ const remainingCount = selectedNodes?.length ? Math.max(0, selectedNodes.length - 10) : 0
+ return (
+ <div className="flex flex-col gap-1.5 p-1">
+ {displayItems.map((item: GraphNode, index: number) => {
+ const color = colors[item.data.type]
+ return <SelectedNodeItem key={index} node={item} color={color} />
+ })}
+ {remainingCount > 0 && (
+ <Badge
+ variant="outline"
+ className="flex w-full items-center justify-between text-left border border-border gap-1.5 text-xs p-2 py-1.5"
+ >
+ <span className="flex items-center gap-2 truncate text-ellipsis">
+ <span className="truncate text-ellipsis">{remainingCount}+ other</span>
+ </span>
+ </Badge>
+ )}
+ </div>
+ )
}
const ActionBar = () => {
- const { id: sketchId } = useParams({ strict: false })
- const { confirm } = useConfirm();
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const removeNodes = useGraphStore(s => s.removeNodes);
- const openChat = useLayoutStore(s => s.openChat);
- const clearSelectedNodes = useGraphStore((s) => s.clearSelectedNodes)
+ const { id: sketchId } = useParams({ strict: false })
+ const { confirm } = useConfirm()
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const removeNodes = useGraphStore((s) => s.removeNodes)
+ const openChat = useLayoutStore((s) => s.openChat)
+ const clearSelectedNodes = useGraphStore((s) => s.clearSelectedNodes)
- // Ask AI dialog
- const handleAskAI = useCallback((e: React.MouseEvent) => {
- e.stopPropagation();
- openChat()
- }, [openChat])
+ // Ask AI dialog
+ const handleAskAI = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation()
+ openChat()
+ },
+ [openChat]
+ )
- // Delete node
- const handleDeleteNodes = useCallback(async () => {
- if (!selectedNodes.length || !sketchId) return
- if (!await confirm({ title: `You are about to delete ${selectedNodes.length} node(s).`, message: "The action is irreversible." })) return
+ // Delete node
+ const handleDeleteNodes = useCallback(async () => {
+ if (!selectedNodes.length || !sketchId) return
+ if (
+ !(await confirm({
+ title: `You are about to delete ${selectedNodes.length} node(s).`,
+ message: 'The action is irreversible.'
+ }))
+ )
+ return
- toast.promise(
- (async () => {
- removeNodes(selectedNodes.map((n) => n.id))
- clearSelectedNodes()
- return sketchService.deleteNodes(sketchId as string, JSON.stringify({ nodeIds: selectedNodes.map((n) => n.id) }))
- })(),
- {
- loading: `Deleting ${selectedNodes.length} node(s)...`,
- success: 'Nodes deleted successfully.',
- error: 'Failed to delete selectedNodes.'
- }
+ toast.promise(
+ (async () => {
+ removeNodes(selectedNodes.map((n) => n.id))
+ clearSelectedNodes()
+ return sketchService.deleteNodes(
+ sketchId as string,
+ JSON.stringify({ nodeIds: selectedNodes.map((n) => n.id) })
)
- }, [selectedNodes, confirm, removeNodes, clearSelectedNodes, sketchId])
+ })(),
+ {
+ loading: `Deleting ${selectedNodes.length} node(s)...`,
+ success: 'Nodes deleted successfully.',
+ error: 'Failed to delete selectedNodes.'
+ }
+ )
+ }, [selectedNodes, confirm, removeNodes, clearSelectedNodes, sketchId])
- const type = selectedNodes[0].data.type
- const isSametype = (node: GraphNode) => node.data.type === type;
- const shareSameType = selectedNodes.every(isSametype)
- const values = !shareSameType ? [] : selectedNodes.map((node: GraphNode) => node.data.label)
+ const type = selectedNodes[0].data.type
+ const isSametype = (node: GraphNode) => node.data.type === type
+ const shareSameType = selectedNodes.every(isSametype)
+ const values = !shareSameType ? [] : selectedNodes.map((node: GraphNode) => node.data.label)
- return (
- <div className="flex items-center gap-1">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- onClick={handleAskAI}
- variant="ghost"
- size="sm"
- className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
- >
- <Sparkles className="h-3 w-3" strokeWidth={1.5} />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>Ask AI</p>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- variant="ghost"
- size="sm"
- disabled={selectedNodes.length === 0}
- className="h-6 w-6 p-0 relative text-destructive hover:text-destructive"
- onClick={handleDeleteNodes}
- >
- <Trash2 className="h-3 w-3" strokeWidth={1.5} />
- {selectedNodes.length > 0 && <span className="absolute -top-2 -right-2 z-50 bg-primary text-white text-[10px] rounded-full w-auto min-w-4.5 h-4.5 p-1 flex items-center justify-center">{selectedNodes.length}</span>}
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>Delete {selectedNodes.length} nodes</p>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <div className='ml-2'>
- <LaunchFlow values={values} type={type}>
- <Button
- disabled={!shareSameType}
- size={"sm"}
- className="rounded-full h-7"
- >
- <Rocket className="h-3 w-3" strokeWidth={2} />({selectedNodes.length})
- </Button>
- </LaunchFlow>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- {!shareSameType ? <p>All selected items are not the same type</p> : <p>Launch transform</p>}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- variant="ghost"
- size="sm"
- disabled={selectedNodes.length === 0}
- className="h-6 w-6"
- onClick={clearSelectedNodes}
- >
- <XIcon className="h-5 w-5" />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>
- <p>Clear selection</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- )
-}
\ No newline at end of file
+ return (
+ <div className="flex items-center gap-1">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ onClick={handleAskAI}
+ variant="ghost"
+ size="sm"
+ className="h-6 w-6 p-0 hover:bg-muted opacity-70 hover:opacity-100"
+ >
+ <Sparkles className="h-3 w-3" strokeWidth={1.5} />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Ask AI</p>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={selectedNodes.length === 0}
+ className="h-6 w-6 p-0 relative text-destructive hover:text-destructive"
+ onClick={handleDeleteNodes}
+ >
+ <Trash2 className="h-3 w-3" strokeWidth={1.5} />
+ {selectedNodes.length > 0 && (
+ <span className="absolute -top-2 -right-2 z-50 bg-primary text-white text-[10px] rounded-full w-auto min-w-4.5 h-4.5 p-1 flex items-center justify-center">
+ {selectedNodes.length}
+ </span>
+ )}
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Delete {selectedNodes.length} nodes</p>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="ml-2">
+ <LaunchFlow values={values} type={type}>
+ <Button disabled={!shareSameType} size={'sm'} className="rounded-full h-7">
+ <Rocket className="h-3 w-3" strokeWidth={2} />({selectedNodes.length})
+ </Button>
+ </LaunchFlow>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ {!shareSameType ? (
+ <p>All selected items are not the same type</p>
+ ) : (
+ <p>Launch transform</p>
+ )}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={selectedNodes.length === 0}
+ className="h-6 w-6"
+ onClick={clearSelectedNodes}
+ >
+ <XIcon className="h-5 w-5" />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Clear selection</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/graphs/settings.tsx b/flowsint-app/src/renderer/src/components/graphs/settings.tsx
index 528d77a0..e3d78f20 100644
--- a/flowsint-app/src/renderer/src/components/graphs/settings.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/settings.tsx
@@ -1,702 +1,727 @@
-import { Button } from "@/components/ui/button"
+import { Button } from '@/components/ui/button'
import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog"
-import { Input } from "@/components/ui/input"
-import { Label } from "@/components/ui/label"
-import { Textarea } from "@/components/ui/textarea"
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
-import { Skeleton } from "@/components/ui/skeleton"
-import { Switch } from "@/components/ui/switch"
-import { Slider } from "@/components/ui/slider"
-import { toast } from "sonner"
-
-import { useGraphSettingsStore } from "@/stores/graph-settings-store"
-import { isMacOS } from "@/components/analyses/editor/utils"
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
-import { Sketch } from "@/types"
-import { useParams } from "@tanstack/react-router"
-import { sketchService } from "@/api/sketch-service"
-import { useState, useEffect } from "react"
-import { queryKeys } from "@/api/query-keys"
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs"
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from '@/components/ui/dialog'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Textarea } from '@/components/ui/textarea'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Switch } from '@/components/ui/switch'
+import { Slider } from '@/components/ui/slider'
+import { toast } from 'sonner'
+
+import { useGraphSettingsStore } from '@/stores/graph-settings-store'
+import { isMacOS } from '@/components/analyses/editor/utils'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { Sketch } from '@/types'
+import { useParams } from '@tanstack/react-router'
+import { sketchService } from '@/api/sketch-service'
+import { useState, useEffect } from 'react'
+import { queryKeys } from '@/api/query-keys'
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs'
// SettingItem Components
interface SettingItemProps {
- label: string
- description?: string
- children: React.ReactNode
- inline?: boolean
+ label: string
+ description?: string
+ children: React.ReactNode
+ inline?: boolean
}
function SettingItem({ label, description, children, inline = false }: SettingItemProps) {
- if (inline) {
- return (
- <div className="flex items-center justify-between py-3">
- <div className="space-y-1 flex-1">
- <Label className="text-sm font-medium text-foreground">{label}</Label>
- {description && (
- <p className="text-xs text-muted-foreground">{description}</p>
- )}
- </div>
- <div className="ml-4">
- {children}
- </div>
- </div>
- )
- }
-
+ if (inline) {
return (
- <div className="space-y-2">
- <div className="space-y-1">
- <Label className="text-sm font-medium text-foreground">{label}</Label>
- {description && (
- <p className="text-xs text-muted-foreground">{description}</p>
- )}
- </div>
- {children}
+ <div className="flex items-center justify-between py-3">
+ <div className="space-y-1 flex-1">
+ <Label className="text-sm font-medium text-foreground">{label}</Label>
+ {description && <p className="text-xs text-muted-foreground">{description}</p>}
</div>
+ <div className="ml-4">{children}</div>
+ </div>
)
+ }
+
+ return (
+ <div className="space-y-2">
+ <div className="space-y-1">
+ <Label className="text-sm font-medium text-foreground">{label}</Label>
+ {description && <p className="text-xs text-muted-foreground">{description}</p>}
+ </div>
+ {children}
+ </div>
+ )
}
// Dynamic Setting Components
interface DynamicSettingProps {
- categoryId: string
- settingKey: string
- setting: any
- onValueChange: (value: any) => void
+ categoryId: string
+ settingKey: string
+ setting: any
+ onValueChange: (value: any) => void
}
function DynamicSetting({ categoryId, settingKey, setting, onValueChange }: DynamicSettingProps) {
+ // For force settings, always use slider regardless of type
+ const shouldUseSlider = categoryId === 'graph' || setting.type === 'slider'
- // For force settings, always use slider regardless of type
- const shouldUseSlider = categoryId === "graph" || setting.type === "slider"
-
- if (shouldUseSlider && (setting.type === "number" || setting.type === "slider")) {
- return (
- <SettingItem label={settingKey} description={setting.description} inline={true}>
- <div className="flex items-center space-x-3 w-64">
- <Slider
- value={[setting.value]}
- onValueChange={([value]) => onValueChange(value)}
- min={setting.min || 0}
- max={setting.max || 100}
- step={setting.step || 1}
- className="flex-1"
- />
- <Input
- type="number"
- value={setting.value}
- onChange={(e) => onValueChange(Number(e.target.value))}
- min={setting.min}
- max={setting.max}
- step={setting.step}
- className="h-9 w-20"
- />
- </div>
- </SettingItem>
- )
- }
+ if (shouldUseSlider && (setting.type === 'number' || setting.type === 'slider')) {
+ return (
+ <SettingItem label={settingKey} description={setting.description} inline={true}>
+ <div className="flex items-center space-x-3 w-64">
+ <Slider
+ value={[setting.value]}
+ onValueChange={([value]) => onValueChange(value)}
+ min={setting.min || 0}
+ max={setting.max || 100}
+ step={setting.step || 1}
+ className="flex-1"
+ />
+ <Input
+ type="number"
+ value={setting.value}
+ onChange={(e) => onValueChange(Number(e.target.value))}
+ min={setting.min}
+ max={setting.max}
+ step={setting.step}
+ className="h-9 w-20"
+ />
+ </div>
+ </SettingItem>
+ )
+ }
+
+ switch (setting.type) {
+ case 'boolean':
+ return (
+ <SettingItem label={settingKey} description={setting.description} inline={true}>
+ <div className="flex items-center space-x-2">
+ <Switch checked={setting.value} onCheckedChange={onValueChange} />
+ <span className="text-sm text-muted-foreground">
+ {setting.value ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ </SettingItem>
+ )
+
+ case 'select':
+ return (
+ <SettingItem label={settingKey} description={setting.description} inline={true}>
+ <Select value={setting.value} onValueChange={onValueChange}>
+ <SelectTrigger className="h-9 w-48">
+ <SelectValue placeholder="Select option" />
+ </SelectTrigger>
+ <SelectContent>
+ {setting.options?.map((option: any) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingItem>
+ )
+
+ case 'text':
+ return (
+ <SettingItem label={settingKey} description={setting.description} inline={false}>
+ <Input
+ type="text"
+ value={setting.value}
+ onChange={(e) => onValueChange(e.target.value)}
+ placeholder="Enter value"
+ className="h-10"
+ />
+ </SettingItem>
+ )
+
+ case 'textarea':
+ return (
+ <SettingItem label={settingKey} description={setting.description} inline={false}>
+ <Textarea
+ value={setting.value}
+ onChange={(e) => onValueChange(e.target.value)}
+ placeholder="Enter value"
+ rows={4}
+ className="resize-none"
+ />
+ </SettingItem>
+ )
- switch (setting.type) {
- case "boolean":
- return (
- <SettingItem label={settingKey} description={setting.description} inline={true}>
- <div className="flex items-center space-x-2">
- <Switch
- checked={setting.value}
- onCheckedChange={onValueChange}
- />
- <span className="text-sm text-muted-foreground">
- {setting.value ? "Enabled" : "Disabled"}
- </span>
- </div>
- </SettingItem>
- )
-
- case "select":
- return (
- <SettingItem label={settingKey} description={setting.description} inline={true}>
- <Select value={setting.value} onValueChange={onValueChange}>
- <SelectTrigger className="h-9 w-48">
- <SelectValue placeholder="Select option" />
- </SelectTrigger>
- <SelectContent>
- {setting.options?.map((option: any) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </SettingItem>
- )
-
- case "text":
- return (
- <SettingItem label={settingKey} description={setting.description} inline={false}>
- <Input
- type="text"
- value={setting.value}
- onChange={(e) => onValueChange(e.target.value)}
- placeholder="Enter value"
- className="h-10"
- />
- </SettingItem>
- )
-
- case "textarea":
- return (
- <SettingItem label={settingKey} description={setting.description} inline={false}>
- <Textarea
- value={setting.value}
- onChange={(e) => onValueChange(e.target.value)}
- placeholder="Enter value"
- rows={4}
- className="resize-none"
- />
- </SettingItem>
- )
-
- case "color":
- return (
- <SettingItem label={settingKey} description={setting.description} inline={true}>
- <div className="flex items-center space-x-2">
- <Input
- type="color"
- value={setting.value}
- onChange={(e) => onValueChange(e.target.value)}
- className="h-9 w-12 p-1"
- />
- <Input
- type="text"
- value={setting.value}
- onChange={(e) => onValueChange(e.target.value)}
- placeholder="#000000"
- className="h-9 w-24"
- />
- </div>
- </SettingItem>
- )
-
- case "number":
- return (
- <SettingItem label={settingKey} description={setting.description} inline={true}>
- <Input
- type="number"
- value={setting.value}
- onChange={(e) => onValueChange(Number(e.target.value))}
- placeholder="Enter number"
- min={setting.min}
- max={setting.max}
- step={setting.step}
- className="h-9 w-32"
- />
- </SettingItem>
- )
-
- default:
- return (
- <SettingItem label={settingKey} description={setting.description} inline={false}>
- <div className="text-sm text-muted-foreground">
- Unknown setting type: {setting.type}
- </div>
- </SettingItem>
- )
- }
+ case 'color':
+ return (
+ <SettingItem label={settingKey} description={setting.description} inline={true}>
+ <div className="flex items-center space-x-2">
+ <Input
+ type="color"
+ value={setting.value}
+ onChange={(e) => onValueChange(e.target.value)}
+ className="h-9 w-12 p-1"
+ />
+ <Input
+ type="text"
+ value={setting.value}
+ onChange={(e) => onValueChange(e.target.value)}
+ placeholder="#000000"
+ className="h-9 w-24"
+ />
+ </div>
+ </SettingItem>
+ )
+
+ case 'number':
+ return (
+ <SettingItem label={settingKey} description={setting.description} inline={true}>
+ <Input
+ type="number"
+ value={setting.value}
+ onChange={(e) => onValueChange(Number(e.target.value))}
+ placeholder="Enter number"
+ min={setting.min}
+ max={setting.max}
+ step={setting.step}
+ className="h-9 w-32"
+ />
+ </SettingItem>
+ )
+
+ default:
+ return (
+ <SettingItem label={settingKey} description={setting.description} inline={false}>
+ <div className="text-sm text-muted-foreground">Unknown setting type: {setting.type}</div>
+ </SettingItem>
+ )
+ }
}
// Dynamic Section Renderer
interface DynamicSectionProps {
- categoryId: string
- category: any
- title: string
- description: string
+ categoryId: string
+ category: any
+ title: string
+ description: string
}
function DynamicSection({ categoryId, category, title, description }: DynamicSectionProps) {
- const getPresets = useGraphSettingsStore(s => s.getPresets)
- const applyPreset = useGraphSettingsStore(s => s.applyPreset)
- const resetSettings = useGraphSettingsStore(s => s.resetSettings)
- const updateSetting = useGraphSettingsStore(s => s.updateSetting)
-
- if (!category) {
- return (
- <div className="space-y-6 flex flex-col h-full">
- <div className="space-y-1">
- <h3 className="text-lg font-semibold text-foreground">{title}</h3>
- <p className="text-sm text-muted-foreground">{description}</p>
- </div>
- <div className="text-sm text-muted-foreground">
- No settings available for category: {category}
- <br />
- Available categories: {Object.keys(category || {}).join(', ')}
- </div>
- </div>
- )
- }
-
- const handleSettingChange = (settingKey: string, value: any) => {
- updateSetting(categoryId, settingKey, value)
- }
+ const getPresets = useGraphSettingsStore((s) => s.getPresets)
+ const applyPreset = useGraphSettingsStore((s) => s.applyPreset)
+ const resetSettings = useGraphSettingsStore((s) => s.resetSettings)
+ const updateSetting = useGraphSettingsStore((s) => s.updateSetting)
+ if (!category) {
return (
- <div className="space-y-6 flex flex-col h-full">
- <div className="space-y-1">
- <h3 className="text-lg font-semibold text-foreground">{title}</h3>
- <p className="text-sm text-muted-foreground">{description}</p>
- </div>
-
- {/* Special handling for force section */}
- {categoryId === "graph" && (
- <div className="border-b pb-6">
- <div className="space-y-1">
- <h4 className="text-md font-semibold text-foreground">Force graph presets</h4>
- <p className="text-sm text-muted-foreground">
- Apply predefined configurations for different graph layouts.
- </p>
- </div>
- <div className="grid grid-cols-2 gap-2 mt-4">
- {Object.keys(getPresets()).map((presetName) => (
- <Button
- key={presetName}
- variant="outline"
- size="sm"
- onClick={() => applyPreset(presetName)}
- className="justify-start"
- >
- {presetName}
- </Button>
- ))}
- </div>
- <div className="mt-4">
- <Button
- variant="outline"
- size="sm"
- onClick={() => resetSettings()}
- className="w-full"
- >
- Reset to Defaults
- </Button>
- </div>
- </div>
- )}
-
- <div className="space-y-5">
- {Object.entries(category).map(([settingKey, setting]) => (
- <DynamicSetting
- key={settingKey}
- categoryId={categoryId}
- settingKey={settingKey}
- setting={setting}
- onValueChange={(value) => handleSettingChange(settingKey, value)}
- />
- ))}
- </div>
- <div className="grow" />
+ <div className="space-y-6 flex flex-col h-full">
+ <div className="space-y-1">
+ <h3 className="text-lg font-semibold text-foreground">{title}</h3>
+ <p className="text-sm text-muted-foreground">{description}</p>
+ </div>
+ <div className="text-sm text-muted-foreground">
+ No settings available for category: {category}
+ <br />
+ Available categories: {Object.keys(category || {}).join(', ')}
</div>
+ </div>
)
+ }
+
+ const handleSettingChange = (settingKey: string, value: any) => {
+ updateSetting(categoryId, settingKey, value)
+ }
+
+ return (
+ <div className="space-y-6 flex flex-col h-full">
+ <div className="space-y-1">
+ <h3 className="text-lg font-semibold text-foreground">{title}</h3>
+ <p className="text-sm text-muted-foreground">{description}</p>
+ </div>
+
+ {/* Special handling for force section */}
+ {categoryId === 'graph' && (
+ <div className="border-b pb-6">
+ <div className="space-y-1">
+ <h4 className="text-md font-semibold text-foreground">Force graph presets</h4>
+ <p className="text-sm text-muted-foreground">
+ Apply predefined configurations for different graph layouts.
+ </p>
+ </div>
+ <div className="grid grid-cols-2 gap-2 mt-4">
+ {Object.keys(getPresets()).map((presetName) => (
+ <Button
+ key={presetName}
+ variant="outline"
+ size="sm"
+ onClick={() => applyPreset(presetName)}
+ className="justify-start"
+ >
+ {presetName}
+ </Button>
+ ))}
+ </div>
+ <div className="mt-4">
+ <Button variant="outline" size="sm" onClick={() => resetSettings()} className="w-full">
+ Reset to Defaults
+ </Button>
+ </div>
+ </div>
+ )}
+
+ <div className="space-y-5">
+ {Object.entries(category).map(([settingKey, setting]) => (
+ <DynamicSetting
+ key={settingKey}
+ categoryId={categoryId}
+ settingKey={settingKey}
+ setting={setting}
+ onValueChange={(value) => handleSettingChange(settingKey, value)}
+ />
+ ))}
+ </div>
+ <div className="grow" />
+ </div>
+ )
}
export default function GlobalSettings() {
- const settingsModalOpen = useGraphSettingsStore(s => s.settingsModalOpen)
- const setSettingsModalOpen = useGraphSettingsStore(s => s.setSettingsModalOpen)
- let settings = useGraphSettingsStore(s => s.settings)
- const queryClient = useQueryClient()
-
- const [activeSection, setActiveSection] = useState("information")
-
- const { id, investigationId } = useParams({ strict: false })
- const { data: sketch, isLoading, isError, refetch } = useQuery({
- queryKey: ["investigations", investigationId, "graph", id],
- queryFn: () => sketchService.getById(id as string),
- refetchOnWindowFocus: false,
- enabled: Boolean(id)
- })
-
- // Form state
- const [formData, setFormData] = useState({
- title: "",
- description: "",
- status: "active"
- })
-
- // Update form data when sketch data changes
- useEffect(() => {
- if (sketch) {
- setFormData({
- title: sketch.title || "",
- description: sketch.description || "",
- status: sketch.status || "active"
- })
- }
- }, [sketch])
-
- const updateMutation = useMutation({
- mutationFn: async (updated: Partial<Sketch>) => {
- if (!id) return
- return sketchService.update(id, JSON.stringify(updated))
- },
- onSuccess: async (data) => {
- if (!id || !investigationId) return
-
- // Update the query cache using query key factory
- queryClient.setQueryData(queryKeys.sketches.graph(investigationId, id), data)
- // Also update the sketches list if it exists
- queryClient.setQueryData(queryKeys.investigations.sketches(investigationId), (oldData: any) => {
- if (!oldData?.sketches) return oldData
- return {
- ...oldData,
- sketches: oldData.sketches.map((s: Sketch) => s.id === id ? data : s)
- }
- })
- // Invalidate related queries
- queryClient.invalidateQueries({
- queryKey: queryKeys.sketches.detail(id)
- })
- toast.success("Sketch updated successfully")
- setSettingsModalOpen(false)
- },
- onError: (error) => {
- toast.error("Failed to update sketch: " + (error instanceof Error ? error.message : "Unknown error"))
+ const settingsModalOpen = useGraphSettingsStore((s) => s.settingsModalOpen)
+ const setSettingsModalOpen = useGraphSettingsStore((s) => s.setSettingsModalOpen)
+ const settings = useGraphSettingsStore((s) => s.settings)
+ const queryClient = useQueryClient()
+
+ const [activeSection, setActiveSection] = useState('information')
+
+ const { id, investigationId } = useParams({ strict: false })
+ const {
+ data: sketch,
+ isLoading,
+ isError,
+ refetch
+ } = useQuery({
+ queryKey: ['investigations', investigationId, 'graph', id],
+ queryFn: () => sketchService.getById(id as string),
+ refetchOnWindowFocus: false,
+ enabled: Boolean(id)
+ })
+
+ // Form state
+ const [formData, setFormData] = useState({
+ title: '',
+ description: '',
+ status: 'active'
+ })
+
+ // Update form data when sketch data changes
+ useEffect(() => {
+ if (sketch) {
+ setFormData({
+ title: sketch.title || '',
+ description: sketch.description || '',
+ status: sketch.status || 'active'
+ })
+ }
+ }, [sketch])
+
+ const updateMutation = useMutation({
+ mutationFn: async (updated: Partial<Sketch>) => {
+ if (!id) return
+ return sketchService.update(id, JSON.stringify(updated))
+ },
+ onSuccess: async (data) => {
+ if (!id || !investigationId) return
+
+ // Update the query cache using query key factory
+ queryClient.setQueryData(queryKeys.sketches.graph(investigationId, id), data)
+ // Also update the sketches list if it exists
+ queryClient.setQueryData(
+ queryKeys.investigations.sketches(investigationId),
+ (oldData: any) => {
+ if (!oldData?.sketches) return oldData
+ return {
+ ...oldData,
+ sketches: oldData.sketches.map((s: Sketch) => (s.id === id ? data : s))
+ }
}
- })
-
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault()
- updateMutation.mutate(formData)
+ )
+ // Invalidate related queries
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.sketches.detail(id)
+ })
+ toast.success('Sketch updated successfully')
+ setSettingsModalOpen(false)
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to update sketch: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
}
+ })
- const handleInputChange = (field: string, value: string) => {
- setFormData(prev => ({
- ...prev,
- [field]: value
- }))
- }
+ const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault()
+ updateMutation.mutate(formData)
+ }
- if (isLoading) {
- return (
- <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>General settings</DialogTitle>
- <DialogDescription>
- Make changes to your sketch settings here. Click save when you&apos;re done.
- </DialogDescription>
- </DialogHeader>
- <div className="grid gap-4">
- <div className="grid gap-2">
- <Skeleton className="h-4 w-16" />
- <Skeleton className="h-10 w-full" />
- </div>
- <div className="grid gap-2">
- <Skeleton className="h-4 w-24" />
- <Skeleton className="h-20 w-full" />
- </div>
- <div className="grid gap-2">
- <Skeleton className="h-4 w-16" />
- <Skeleton className="h-10 w-full" />
- </div>
- </div>
- <DialogFooter>
- <Button variant="outline" disabled>Cancel</Button>
- <Button disabled>Saving...</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
- }
+ const handleInputChange = (field: string, value: string) => {
+ setFormData((prev) => ({
+ ...prev,
+ [field]: value
+ }))
+ }
- if (isError) {
- return (
- <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>General settings</DialogTitle>
- <DialogDescription>
- Error loading sketch data. Please try again.
- </DialogDescription>
- </DialogHeader>
- <div className="grid gap-4">
- <Button onClick={() => refetch()}>Retry</Button>
- </div>
- </DialogContent>
- </Dialog>
- )
- }
+ if (isLoading) {
+ return (
+ <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>General settings</DialogTitle>
+ <DialogDescription>
+ Make changes to your sketch settings here. Click save when you&apos;re done.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4">
+ <div className="grid gap-2">
+ <Skeleton className="h-4 w-16" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ <div className="grid gap-2">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-20 w-full" />
+ </div>
+ <div className="grid gap-2">
+ <Skeleton className="h-4 w-16" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" disabled>
+ Cancel
+ </Button>
+ <Button disabled>Saving...</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+ }
- const getSelectedSectionPanel = (sectionId: string) => {
- if (sectionId === "information") {
- return (
- <div className="space-y-6 flex flex-col h-full">
- <div className="space-y-1">
- <h3 className="text-lg font-semibold text-foreground">General Information</h3>
- <p className="text-sm text-muted-foreground">
- Configure the basic details and metadata for your sketch.
- </p>
- </div>
-
- <div className="space-y-5">
- <TextSetting
- label="Title"
- description="The name of your sketch"
- value={formData.title}
- onValueChange={(value) => handleInputChange("title", value)}
- placeholder="Enter sketch title"
- />
-
- <TextareaSetting
- label="Description"
- description="A brief description of what this sketch represents"
- value={formData.description}
- onValueChange={(value) => handleInputChange("description", value)}
- placeholder="Enter sketch description"
- rows={4}
- />
-
- <SelectSetting
- label="Status"
- description="The current status of this sketch"
- value={formData.status}
- onValueChange={(value) => handleInputChange("status", value)}
- options={[
- { value: "active", label: "Active" },
- { value: "inactive", label: "Inactive" },
- { value: "archived", label: "Archived" }
- ]}
- placeholder="Select status"
- />
- </div>
-
- <div className="grow" />
-
- <div className="border-t pt-6">
- <DialogFooter className="gap-3">
- <DialogClose asChild>
- <Button variant="outline" type="button" className="h-10 px-6">
- Cancel
- </Button>
- </DialogClose>
- <Button
- type="submit"
- disabled={updateMutation.isPending}
- onClick={handleSubmit}
- className="h-10 px-6"
- >
- {updateMutation.isPending ? "Saving..." : "Save Changes"}
- </Button>
- </DialogFooter>
- </div>
- </div>
- )
- }
+ if (isError) {
+ return (
+ <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>General settings</DialogTitle>
+ <DialogDescription>Error loading sketch data. Please try again.</DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4">
+ <Button onClick={() => refetch()}>Retry</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+ }
- // For all other sections, use the dynamic renderer
- const category = settings[sectionId]
- if (category) {
- return (
- <DynamicSection
- categoryId={sectionId}
- category={category}
- title={category.title}
- description={category.description}
- />
- )
- }
+ const getSelectedSectionPanel = (sectionId: string) => {
+ if (sectionId === 'information') {
+ return (
+ <div className="space-y-6 flex flex-col h-full">
+ <div className="space-y-1">
+ <h3 className="text-lg font-semibold text-foreground">General Information</h3>
+ <p className="text-sm text-muted-foreground">
+ Configure the basic details and metadata for your sketch.
+ </p>
+ </div>
+
+ <div className="space-y-5">
+ <TextSetting
+ label="Title"
+ description="The name of your sketch"
+ value={formData.title}
+ onValueChange={(value) => handleInputChange('title', value)}
+ placeholder="Enter sketch title"
+ />
- return <div>Section not found.</div>
+ <TextareaSetting
+ label="Description"
+ description="A brief description of what this sketch represents"
+ value={formData.description}
+ onValueChange={(value) => handleInputChange('description', value)}
+ placeholder="Enter sketch description"
+ rows={4}
+ />
+
+ <SelectSetting
+ label="Status"
+ description="The current status of this sketch"
+ value={formData.status}
+ onValueChange={(value) => handleInputChange('status', value)}
+ options={[
+ { value: 'active', label: 'Active' },
+ { value: 'inactive', label: 'Inactive' },
+ { value: 'archived', label: 'Archived' }
+ ]}
+ placeholder="Select status"
+ />
+ </div>
+
+ <div className="grow" />
+
+ <div className="border-t pt-6">
+ <DialogFooter className="gap-3">
+ <DialogClose asChild>
+ <Button variant="outline" type="button" className="h-10 px-6">
+ Cancel
+ </Button>
+ </DialogClose>
+ <Button
+ type="submit"
+ disabled={updateMutation.isPending}
+ onClick={handleSubmit}
+ className="h-10 px-6"
+ >
+ {updateMutation.isPending ? 'Saving...' : 'Save Changes'}
+ </Button>
+ </DialogFooter>
+ </div>
+ </div>
+ )
}
- return (
- <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>
- <DialogContent className="sm:max-w-[800px] h-[80vh] flex flex-col items-start overflow-hidden">
- <DialogHeader>
- <DialogTitle>Sketch settings</DialogTitle>
- <DialogDescription>
- Configure your sketch settings and preferences.
- </DialogDescription>
- </DialogHeader>
- <Tabs value={activeSection} onValueChange={setActiveSection} className="w-full h-full overflow-hidden">
- <div className="grid grid-cols-4 gap-6 h-full divide-x overflow-hidden">
- {/* Left sidebar with tabs */}
- <div className="col-span-1 pr-3">
- <TabsList className="flex bg-transparent flex-col gap-2 w-full h-auto">
- {Object.keys(settings).map((category: string) => (
- <TabsTrigger
- key={category}
- value={category}
- className="w-full justify-start capitalize h-10"
- >
- {category}
- </TabsTrigger>
- ))}
- </TabsList>
- </div>
-
- {/* Right content panel */}
- <div className="col-span-3 h-full w-full overflow-auto p-1">
- {Object.keys(settings).map((category: string) => (
- <TabsContent key={category} value={category} className="mt-0 h-full w-full flex flex-col justify-center">
- {getSelectedSectionPanel(category)}
- </TabsContent>
- ))}
- </div>
- </div>
- </Tabs>
- </DialogContent>
- </Dialog>
- )
+ // For all other sections, use the dynamic renderer
+ const category = settings[sectionId]
+ if (category) {
+ return (
+ <DynamicSection
+ categoryId={sectionId}
+ category={category}
+ title={category.title}
+ description={category.description}
+ />
+ )
+ }
+
+ return <div>Section not found.</div>
+ }
+
+ return (
+ <Dialog open={settingsModalOpen} onOpenChange={setSettingsModalOpen}>
+ <DialogContent className="sm:max-w-[800px] h-[80vh] flex flex-col items-start overflow-hidden">
+ <DialogHeader>
+ <DialogTitle>Sketch settings</DialogTitle>
+ <DialogDescription>Configure your sketch settings and preferences.</DialogDescription>
+ </DialogHeader>
+ <Tabs
+ value={activeSection}
+ onValueChange={setActiveSection}
+ className="w-full h-full overflow-hidden"
+ >
+ <div className="grid grid-cols-4 gap-6 h-full divide-x overflow-hidden">
+ {/* Left sidebar with tabs */}
+ <div className="col-span-1 pr-3">
+ <TabsList className="flex bg-transparent flex-col gap-2 w-full h-auto">
+ {Object.keys(settings).map((category: string) => (
+ <TabsTrigger
+ key={category}
+ value={category}
+ className="w-full justify-start capitalize h-10"
+ >
+ {category}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </div>
+
+ {/* Right content panel */}
+ <div className="col-span-3 h-full w-full overflow-auto p-1">
+ {Object.keys(settings).map((category: string) => (
+ <TabsContent
+ key={category}
+ value={category}
+ className="mt-0 h-full w-full flex flex-col justify-center"
+ >
+ {getSelectedSectionPanel(category)}
+ </TabsContent>
+ ))}
+ </div>
+ </div>
+ </Tabs>
+ </DialogContent>
+ </Dialog>
+ )
}
// Legacy components for backward compatibility (keeping the general section working)
interface TextSettingProps {
- label: string
- description?: string
- value: string
- onValueChange: (value: string) => void
- placeholder?: string
- type?: "text" | "email" | "url" | "number"
+ label: string
+ description?: string
+ value: string
+ onValueChange: (value: string) => void
+ placeholder?: string
+ type?: 'text' | 'email' | 'url' | 'number'
}
-function TextSetting({ label, description, value, onValueChange, placeholder, type = "text" }: TextSettingProps) {
- return (
- <SettingItem label={label} description={description} inline={false}>
- <Input
- type={type}
- value={value}
- onChange={(e) => onValueChange(e.target.value)}
- placeholder={placeholder}
- className="h-10"
- />
- </SettingItem>
- )
+function TextSetting({
+ label,
+ description,
+ value,
+ onValueChange,
+ placeholder,
+ type = 'text'
+}: TextSettingProps) {
+ return (
+ <SettingItem label={label} description={description} inline={false}>
+ <Input
+ type={type}
+ value={value}
+ onChange={(e) => onValueChange(e.target.value)}
+ placeholder={placeholder}
+ className="h-10"
+ />
+ </SettingItem>
+ )
}
interface TextareaSettingProps {
- label: string
- description?: string
- value: string
- onValueChange: (value: string) => void
- placeholder?: string
- rows?: number
+ label: string
+ description?: string
+ value: string
+ onValueChange: (value: string) => void
+ placeholder?: string
+ rows?: number
}
-function TextareaSetting({ label, description, value, onValueChange, placeholder, rows = 4 }: TextareaSettingProps) {
- return (
- <SettingItem label={label} description={description} inline={false}>
- <Textarea
- value={value}
- onChange={(e) => onValueChange(e.target.value)}
- placeholder={placeholder}
- rows={rows}
- className="resize-none"
- />
- </SettingItem>
- )
+function TextareaSetting({
+ label,
+ description,
+ value,
+ onValueChange,
+ placeholder,
+ rows = 4
+}: TextareaSettingProps) {
+ return (
+ <SettingItem label={label} description={description} inline={false}>
+ <Textarea
+ value={value}
+ onChange={(e) => onValueChange(e.target.value)}
+ placeholder={placeholder}
+ rows={rows}
+ className="resize-none"
+ />
+ </SettingItem>
+ )
}
interface SelectSettingProps {
- label: string
- description?: string
- value: string
- onValueChange: (value: string) => void
- options: { value: string; label: string }[]
- placeholder?: string
+ label: string
+ description?: string
+ value: string
+ onValueChange: (value: string) => void
+ options: { value: string; label: string }[]
+ placeholder?: string
}
-function SelectSetting({ label, description, value, onValueChange, options, placeholder }: SelectSettingProps) {
- return (
- <SettingItem label={label} description={description} inline={true}>
- <Select value={value} onValueChange={onValueChange}>
- <SelectTrigger className="h-9 w-48">
- <SelectValue placeholder={placeholder} />
- </SelectTrigger>
- <SelectContent>
- {options.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </SettingItem>
- )
+function SelectSetting({
+ label,
+ description,
+ value,
+ onValueChange,
+ options,
+ placeholder
+}: SelectSettingProps) {
+ return (
+ <SettingItem label={label} description={description} inline={true}>
+ <Select value={value} onValueChange={onValueChange}>
+ <SelectTrigger className="h-9 w-48">
+ <SelectValue placeholder={placeholder} />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingItem>
+ )
}
export function KeyboardShortcuts() {
- const keyboardShortcutsOpen = useGraphSettingsStore(s => s.keyboardShortcutsOpen)
- const setKeyboardShortcutsOpen = useGraphSettingsStore(s => s.setKeyboardShortcutsOpen)
-
- const isMac = isMacOS()
- const modKey = isMac ? "⌘" : "Ctrl"
-
- const shortcuts = [
- {
- category: "Navigation & Panels",
- items: [
- { key: `${modKey}+L`, description: "Toggle Analysis Panel" },
- { key: `${modKey}+B`, description: "Toggle Panel" },
- { key: `${modKey}+D`, description: "Toggle Console" },
- { key: `${modKey}+J`, description: "Open Command Palette" },
- ]
- },
- {
- category: "Chat & Assistant",
- items: [
- { key: `${modKey}+E`, description: "Toggle Chat Assistant" },
- { key: "Escape", description: "Close Chat Assistant" },
- ]
- },
- {
- category: "File Operations",
- items: [
- { key: `${modKey}+S`, description: "Save (Analysis/Flow)" },
- ]
- }
- ]
-
- return (
- <Dialog open={keyboardShortcutsOpen} onOpenChange={setKeyboardShortcutsOpen}>
- <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
- <DialogHeader>
- <DialogTitle>Keyboard Shortcuts</DialogTitle>
- <DialogDescription>
- Here is the list of all available keyboard shortcuts.
- </DialogDescription>
- </DialogHeader>
- <div className="space-y-6">
- {shortcuts.map((category) => (
- <div key={category.category} className="space-y-3">
- <h3 className="text-sm font-semibold text-foreground/80 uppercase tracking-wide">
- {category.category}
- </h3>
- <div className="space-y-2">
- {category.items.map((item) => (
- <div key={item.key} className="flex items-center justify-between py-2 px-3 rounded-md bg-muted/50">
- <span className="text-sm text-muted-foreground">
- {item.description}
- </span>
- <kbd className="inline-flex items-center gap-1 rounded border bg-background px-2 py-1 text-xs font-mono font-medium text-foreground shadow-sm">
- {item.key}
- </kbd>
- </div>
- ))}
- </div>
- </div>
- ))}
- </div>
- <DialogFooter>
- <DialogClose asChild>
- <Button variant="outline">Close</Button>
- </DialogClose>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
\ No newline at end of file
+ const keyboardShortcutsOpen = useGraphSettingsStore((s) => s.keyboardShortcutsOpen)
+ const setKeyboardShortcutsOpen = useGraphSettingsStore((s) => s.setKeyboardShortcutsOpen)
+
+ const isMac = isMacOS()
+ const modKey = isMac ? '⌘' : 'Ctrl'
+
+ const shortcuts = [
+ {
+ category: 'Navigation & Panels',
+ items: [
+ { key: `${modKey}+L`, description: 'Toggle Analysis Panel' },
+ { key: `${modKey}+B`, description: 'Toggle Panel' },
+ { key: `${modKey}+D`, description: 'Toggle Console' },
+ { key: `${modKey}+J`, description: 'Open Command Palette' }
+ ]
+ },
+ {
+ category: 'Chat & Assistant',
+ items: [
+ { key: `${modKey}+E`, description: 'Toggle Chat Assistant' },
+ { key: 'Escape', description: 'Close Chat Assistant' }
+ ]
+ },
+ {
+ category: 'File Operations',
+ items: [{ key: `${modKey}+S`, description: 'Save (Analysis/Flow)' }]
+ }
+ ]
+
+ return (
+ <Dialog open={keyboardShortcutsOpen} onOpenChange={setKeyboardShortcutsOpen}>
+ <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle>Keyboard Shortcuts</DialogTitle>
+ <DialogDescription>
+ Here is the list of all available keyboard shortcuts.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-6">
+ {shortcuts.map((category) => (
+ <div key={category.category} className="space-y-3">
+ <h3 className="text-sm font-semibold text-foreground/80 uppercase tracking-wide">
+ {category.category}
+ </h3>
+ <div className="space-y-2">
+ {category.items.map((item) => (
+ <div
+ key={item.key}
+ className="flex items-center justify-between py-2 px-3 rounded-md bg-muted/50"
+ >
+ <span className="text-sm text-muted-foreground">{item.description}</span>
+ <kbd className="inline-flex items-center gap-1 rounded border bg-background px-2 py-1 text-xs font-mono font-medium text-foreground shadow-sm">
+ {item.key}
+ </kbd>
+ </div>
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline">Close</Button>
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/graphs/toolbar.tsx b/flowsint-app/src/renderer/src/components/graphs/toolbar.tsx
index 3d2298a3..616a1332 100644
--- a/flowsint-app/src/renderer/src/components/graphs/toolbar.tsx
+++ b/flowsint-app/src/renderer/src/components/graphs/toolbar.tsx
@@ -1,220 +1,230 @@
-
-import { Button } from "@/components/ui/button"
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
-import { useGraphControls } from "@/stores/graph-controls-store"
+import { Button } from '@/components/ui/button'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
+import { useGraphControls } from '@/stores/graph-controls-store'
import {
- Maximize,
- Minus,
- ZoomIn,
- RotateCw,
- Waypoints,
- MapPin,
- List,
- GitFork,
- ArrowRightLeft,
- FunnelPlus,
- GitPullRequestArrow,
- LassoSelect,
- Merge
-} from "lucide-react"
-import { memo, useCallback } from "react"
-import { toast } from "sonner"
-import { cn } from "@/lib/utils"
-import Filters from "./filters"
-import { useGraphStore } from "@/stores/graph-store"
+ Maximize,
+ Minus,
+ ZoomIn,
+ RotateCw,
+ Waypoints,
+ MapPin,
+ List,
+ GitFork,
+ ArrowRightLeft,
+ FunnelPlus,
+ GitPullRequestArrow,
+ LassoSelect,
+ Merge
+} from 'lucide-react'
+import { memo, useCallback } from 'react'
+import { toast } from 'sonner'
+import { cn } from '@/lib/utils'
+import Filters from './filters'
+import { useGraphStore } from '@/stores/graph-store'
// Tooltip wrapper component to avoid repetition
export const ToolbarButton = memo(function ToolbarButton({
- icon,
- tooltip,
- onClick,
- disabled = false,
- badge = null,
- toggled = false
+ icon,
+ tooltip,
+ onClick,
+ disabled = false,
+ badge = null,
+ toggled = false
}: {
- icon: React.ReactNode;
- tooltip: string | React.ReactNode;
- onClick?: () => void;
- disabled?: boolean;
- badge?: number | null;
- toggled?: boolean | null
+ icon: React.ReactNode
+ tooltip: string | React.ReactNode
+ onClick?: () => void
+ disabled?: boolean
+ badge?: number | null
+ toggled?: boolean | null
}) {
- return (
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button
- onClick={onClick}
- disabled={disabled}
- variant="outline"
- size="icon"
- className={cn("h-8 w-8 relative shadow-none", toggled && "bg-primary/30 border-primary text-primary hover:bg-primary/40 hover:text-primary")}
- >
- {icon}
- {badge && <span className="absolute -top-2 -right-2 z-50 bg-primary text-white text-[10px] rounded-full w-auto min-w-4.5 h-4.5 p-1 flex items-center justify-center">{badge}</span>}
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent>{tooltip}</TooltipContent>
- </Tooltip>
- )
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ onClick={onClick}
+ disabled={disabled}
+ variant="outline"
+ size="icon"
+ className={cn(
+ 'h-8 w-8 relative shadow-none',
+ toggled &&
+ 'bg-primary/30 border-primary text-primary hover:bg-primary/40 hover:text-primary'
+ )}
+ >
+ {icon}
+ {badge && (
+ <span className="absolute -top-2 -right-2 z-50 bg-primary text-white text-[10px] rounded-full w-auto min-w-4.5 h-4.5 p-1 flex items-center justify-center">
+ {badge}
+ </span>
+ )}
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>{tooltip}</TooltipContent>
+ </Tooltip>
+ )
})
export const Toolbar = memo(function Toolbar({ isLoading }: { isLoading: boolean }) {
- const view = useGraphControls(s => s.view)
- const setView = useGraphControls((s) => s.setView)
- const zoomToFit = useGraphControls((s) => s.zoomToFit);
- const zoomIn = useGraphControls((s) => s.zoomIn);
- const zoomOut = useGraphControls((s) => s.zoomOut);
- const onLayout = useGraphControls((s) => s.onLayout);
- const refetchGraph = useGraphControls((s) => s.refetchGraph)
- const isLassoActive = useGraphControls((s) => s.isLassoActive)
- const setIsLassoActive = useGraphControls((s) => s.setIsLassoActive)
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const setOpenAddRelationDialog = useGraphStore((state) => state.setOpenAddRelationDialog)
- const setOpenMergeDialog = useGraphStore((state) => state.setOpenMergeDialog)
- const filters = useGraphStore(s => s.filters)
-
- const handleRefresh = useCallback(() => {
- try {
- refetchGraph()
- } catch (error) {
- toast.error("Failed to refresh graph data");
- }
- }, [refetchGraph, onLayout]);
+ const view = useGraphControls((s) => s.view)
+ const setView = useGraphControls((s) => s.setView)
+ const zoomToFit = useGraphControls((s) => s.zoomToFit)
+ const zoomIn = useGraphControls((s) => s.zoomIn)
+ const zoomOut = useGraphControls((s) => s.zoomOut)
+ const onLayout = useGraphControls((s) => s.onLayout)
+ const refetchGraph = useGraphControls((s) => s.refetchGraph)
+ const isLassoActive = useGraphControls((s) => s.isLassoActive)
+ const setIsLassoActive = useGraphControls((s) => s.setIsLassoActive)
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const setOpenAddRelationDialog = useGraphStore((state) => state.setOpenAddRelationDialog)
+ const setOpenMergeDialog = useGraphStore((state) => state.setOpenMergeDialog)
+ const filters = useGraphStore((s) => s.filters)
- const handleForceLayout = useCallback(() => {
- setView("force")
- setTimeout(() => zoomToFit(), 500)
- }, [setView, zoomToFit])
+ const handleRefresh = useCallback(() => {
+ try {
+ refetchGraph()
+ } catch (error) {
+ toast.error('Failed to refresh graph data')
+ }
+ }, [refetchGraph, onLayout])
- const handleTableLayout = useCallback(() => {
- setView("table")
- }, [setView])
+ const handleForceLayout = useCallback(() => {
+ setView('force')
+ setTimeout(() => zoomToFit(), 500)
+ }, [setView, zoomToFit])
- const handleMapLayout = useCallback(() => {
- setView("map")
- }, [setView])
+ const handleTableLayout = useCallback(() => {
+ setView('table')
+ }, [setView])
- const handleRelationshipsLayout = useCallback(() => {
- setView("relationships")
- }, [setView])
+ const handleMapLayout = useCallback(() => {
+ setView('map')
+ }, [setView])
- const handleDagreLayoutTB = useCallback(() => {
- setView("hierarchy")
- onLayout && onLayout("dagre-tb")
- setTimeout(() => zoomToFit(), 200)
- }, [onLayout, setView, zoomToFit])
+ const handleRelationshipsLayout = useCallback(() => {
+ setView('relationships')
+ }, [setView])
- const handleOpenAddRelationDialog = useCallback(() => {
- setOpenAddRelationDialog(true)
- }, [setOpenAddRelationDialog])
+ const handleDagreLayoutTB = useCallback(() => {
+ setView('hierarchy')
+ onLayout && onLayout('dagre-tb')
+ setTimeout(() => zoomToFit(), 200)
+ }, [onLayout, setView, zoomToFit])
- const handleOpenMergeDialog = useCallback(() => {
- setOpenMergeDialog(true)
- }, [setOpenMergeDialog])
+ const handleOpenAddRelationDialog = useCallback(() => {
+ setOpenAddRelationDialog(true)
+ }, [setOpenAddRelationDialog])
- const handleLassoSelect = useCallback(() => {
- setIsLassoActive(!isLassoActive)
- }, [setIsLassoActive, isLassoActive])
+ const handleOpenMergeDialog = useCallback(() => {
+ setOpenMergeDialog(true)
+ }, [setOpenMergeDialog])
- const areExactlyTwoSelected = selectedNodes.length === 2
- const areMergeable = selectedNodes.length > 1 && selectedNodes.every((n) => n.data.type === selectedNodes[0].data.type)
- const hasFilters = !(filters.types.every(t => t.checked) || filters.types.every(t => !t.checked))
+ const handleLassoSelect = useCallback(() => {
+ setIsLassoActive(!isLassoActive)
+ }, [setIsLassoActive, isLassoActive])
- return (
- <div className="flex w-full justify-between gap-2 items-center">
- <div className="flex items-center gap-2">
- <TooltipProvider>
- <ToolbarButton
- icon={<GitPullRequestArrow className="h-4 w-4 opacity-70" />}
- tooltip="Connect"
- onClick={handleOpenAddRelationDialog}
- disabled={!areExactlyTwoSelected}
- badge={areExactlyTwoSelected ? 2 : null}
- />
- <ToolbarButton
- icon={<Merge className="h-4 w-4 opacity-70" />}
- tooltip="Merge"
- onClick={handleOpenMergeDialog}
- disabled={!areMergeable}
- badge={areMergeable ? selectedNodes.length : null}
+ const areExactlyTwoSelected = selectedNodes.length === 2
+ const areMergeable =
+ selectedNodes.length > 1 &&
+ selectedNodes.every((n) => n.data.type === selectedNodes[0].data.type)
+ const hasFilters = !(
+ filters.types.every((t) => t.checked) || filters.types.every((t) => !t.checked)
+ )
- />
- <ToolbarButton
- icon={<ZoomIn className="h-4 w-4 opacity-70" />}
- tooltip="Zoom In"
- onClick={zoomIn}
- disabled={!["force", "hierarchy"].includes(view) || isLassoActive}
- />
- <ToolbarButton
- icon={<Minus className="h-4 w-4 opacity-70" />}
- tooltip="Zoom Out"
- onClick={zoomOut}
- disabled={!["force", "hierarchy"].includes(view) || isLassoActive}
- />
- <ToolbarButton
- icon={<Maximize className="h-4 w-4 opacity-70" />}
- tooltip="Fit to View"
- onClick={zoomToFit}
- disabled={!["force", "hierarchy"].includes(view) || isLassoActive}
- />
- <ToolbarButton
- icon={<LassoSelect className="h-4 w-4 opacity-70" />}
- tooltip={"Lasso select"}
- onClick={handleLassoSelect}
- toggled={isLassoActive}
- disabled={!["force", "hierarchy"].includes(view)}
- />
- <Filters>
- <ToolbarButton
- disabled={isLoading}
- icon={<FunnelPlus className={cn("h-4 w-4 opacity-70")} />}
- tooltip="Filters"
- toggled={hasFilters}
- />
- </Filters>
- <ToolbarButton
- onClick={handleRefresh}
- disabled={isLoading}
- icon={<RotateCw className={cn("h-4 w-4 opacity-70", isLoading && "animate-spin")} />}
- tooltip="Refresh"
- />
- </TooltipProvider>
- </div>
- <div className="flex items-center gap-2">
- <TooltipProvider>
- <ToolbarButton
- icon={<GitFork className="h-4 w-4 opacity-70 rotate-180" />}
- tooltip={`Hierarchy`}
- toggled={["hierarchy"].includes(view)}
- onClick={handleDagreLayoutTB}
- />
- <ToolbarButton
- icon={<Waypoints className="h-4 w-4 opacity-70" />}
- tooltip={"Graph view"}
- toggled={["force"].includes(view)}
- onClick={handleForceLayout}
- />
- <ToolbarButton
- icon={<List className="h-4 w-4 opacity-70" />}
- tooltip={"Table view"}
- toggled={["table"].includes(view)}
- onClick={handleTableLayout}
- />
- <ToolbarButton
- icon={<ArrowRightLeft className="h-4 w-4 opacity-70" />}
- tooltip={"Relationships view"}
- toggled={["relationships"].includes(view)}
- onClick={handleRelationshipsLayout}
- />
- <ToolbarButton
- icon={<MapPin className="h-4 w-4 opacity-70" />}
- tooltip={"Map view"}
- toggled={["map"].includes(view)}
- onClick={handleMapLayout}
- />
- </TooltipProvider>
- </div>
- </div>
- )
-})
\ No newline at end of file
+ return (
+ <div className="flex w-full justify-between gap-2 items-center">
+ <div className="flex items-center gap-2">
+ <TooltipProvider>
+ <ToolbarButton
+ icon={<GitPullRequestArrow className="h-4 w-4 opacity-70" />}
+ tooltip="Connect"
+ onClick={handleOpenAddRelationDialog}
+ disabled={!areExactlyTwoSelected}
+ badge={areExactlyTwoSelected ? 2 : null}
+ />
+ <ToolbarButton
+ icon={<Merge className="h-4 w-4 opacity-70" />}
+ tooltip="Merge"
+ onClick={handleOpenMergeDialog}
+ disabled={!areMergeable}
+ badge={areMergeable ? selectedNodes.length : null}
+ />
+ <ToolbarButton
+ icon={<ZoomIn className="h-4 w-4 opacity-70" />}
+ tooltip="Zoom In"
+ onClick={zoomIn}
+ disabled={!['force', 'hierarchy'].includes(view) || isLassoActive}
+ />
+ <ToolbarButton
+ icon={<Minus className="h-4 w-4 opacity-70" />}
+ tooltip="Zoom Out"
+ onClick={zoomOut}
+ disabled={!['force', 'hierarchy'].includes(view) || isLassoActive}
+ />
+ <ToolbarButton
+ icon={<Maximize className="h-4 w-4 opacity-70" />}
+ tooltip="Fit to View"
+ onClick={zoomToFit}
+ disabled={!['force', 'hierarchy'].includes(view) || isLassoActive}
+ />
+ <ToolbarButton
+ icon={<LassoSelect className="h-4 w-4 opacity-70" />}
+ tooltip={'Lasso select'}
+ onClick={handleLassoSelect}
+ toggled={isLassoActive}
+ disabled={!['force', 'hierarchy'].includes(view)}
+ />
+ <Filters>
+ <ToolbarButton
+ disabled={isLoading}
+ icon={<FunnelPlus className={cn('h-4 w-4 opacity-70')} />}
+ tooltip="Filters"
+ toggled={hasFilters}
+ />
+ </Filters>
+ <ToolbarButton
+ onClick={handleRefresh}
+ disabled={isLoading}
+ icon={<RotateCw className={cn('h-4 w-4 opacity-70', isLoading && 'animate-spin')} />}
+ tooltip="Refresh"
+ />
+ </TooltipProvider>
+ </div>
+ <div className="flex items-center gap-2">
+ <TooltipProvider>
+ <ToolbarButton
+ icon={<GitFork className="h-4 w-4 opacity-70 rotate-180" />}
+ tooltip={`Hierarchy`}
+ toggled={['hierarchy'].includes(view)}
+ onClick={handleDagreLayoutTB}
+ />
+ <ToolbarButton
+ icon={<Waypoints className="h-4 w-4 opacity-70" />}
+ tooltip={'Graph view'}
+ toggled={['force'].includes(view)}
+ onClick={handleForceLayout}
+ />
+ <ToolbarButton
+ icon={<List className="h-4 w-4 opacity-70" />}
+ tooltip={'Table view'}
+ toggled={['table'].includes(view)}
+ onClick={handleTableLayout}
+ />
+ <ToolbarButton
+ icon={<ArrowRightLeft className="h-4 w-4 opacity-70" />}
+ tooltip={'Relationships view'}
+ toggled={['relationships'].includes(view)}
+ onClick={handleRelationshipsLayout}
+ />
+ <ToolbarButton
+ icon={<MapPin className="h-4 w-4 opacity-70" />}
+ tooltip={'Map view'}
+ toggled={['map'].includes(view)}
+ onClick={handleMapLayout}
+ />
+ </TooltipProvider>
+ </div>
+ </div>
+ )
+})
diff --git a/flowsint-app/src/renderer/src/components/investigations/investigation-list.tsx b/flowsint-app/src/renderer/src/components/investigations/investigation-list.tsx
index b06b57aa..fd48683e 100644
--- a/flowsint-app/src/renderer/src/components/investigations/investigation-list.tsx
+++ b/flowsint-app/src/renderer/src/components/investigations/investigation-list.tsx
@@ -1,382 +1,406 @@
-import { investigationService } from "@/api/investigation-service"
-import type { Investigation } from "@/types/investigation"
-import { useQuery, useQueryClient } from "@tanstack/react-query"
-import type { Sketch } from "@/types/sketch"
-import NewInvestigation from "./new-investigation"
-import { Button } from "../ui/button"
-import { MoreVertical, PlusIcon, Trash2, Waypoints, ChevronRight, ChevronDown, Search } from "lucide-react"
-import { Input } from "../ui/input"
-import { cn } from "@/lib/utils"
-import { Link } from "@tanstack/react-router"
-import { SkeletonList } from "../shared/skeleton-list"
-import { useConfirm } from "@/components/use-confirm-dialog"
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "../ui/dropdown-menu"
-import { toast } from "sonner"
-import { sketchService } from "@/api/sketch-service"
-import { useState, useMemo } from "react"
-import { queryKeys } from "@/api/query-keys"
-import { useMutation } from "@tanstack/react-query"
-import ErrorState from "../shared/error-state"
+import { investigationService } from '@/api/investigation-service'
+import type { Investigation } from '@/types/investigation'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import type { Sketch } from '@/types/sketch'
+import NewInvestigation from './new-investigation'
+import { Button } from '../ui/button'
+import {
+ MoreVertical,
+ PlusIcon,
+ Trash2,
+ Waypoints,
+ ChevronRight,
+ ChevronDown,
+ Search
+} from 'lucide-react'
+import { Input } from '../ui/input'
+import { cn } from '@/lib/utils'
+import { Link } from '@tanstack/react-router'
+import { SkeletonList } from '../shared/skeleton-list'
+import { useConfirm } from '@/components/use-confirm-dialog'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger
+} from '../ui/dropdown-menu'
+import { toast } from 'sonner'
+import { sketchService } from '@/api/sketch-service'
+import { useState, useMemo } from 'react'
+import { queryKeys } from '@/api/query-keys'
+import { useMutation } from '@tanstack/react-query'
+import ErrorState from '../shared/error-state'
// Tree node component for investigations and sketches
const TreeNode = ({
- item,
- level = 0,
- isExpanded,
- onToggle,
- isActive,
- onDelete,
- children,
- isClickable = true
+ item,
+ level = 0,
+ isExpanded,
+ onToggle,
+ isActive,
+ onDelete,
+ children,
+ isClickable = true
}: {
- item: { id: string, name: string, type: 'investigation' | 'sketch' },
- level?: number,
- isExpanded?: boolean,
- onToggle?: () => void,
- isActive?: boolean,
- onDelete?: (e: React.MouseEvent) => void,
- children?: React.ReactNode,
- isClickable?: boolean
+ item: { id: string; name: string; type: 'investigation' | 'sketch' }
+ level?: number
+ isExpanded?: boolean
+ onToggle?: () => void
+ isActive?: boolean
+ onDelete?: (e: React.MouseEvent) => void
+ children?: React.ReactNode
+ isClickable?: boolean
}) => {
- const isInvestigation = item.type === 'investigation'
- const hasChildren = isInvestigation && children
- const canExpand = isInvestigation && hasChildren
+ const isInvestigation = item.type === 'investigation'
+ const hasChildren = isInvestigation && children
+ const canExpand = isInvestigation && hasChildren
- const handleToggle = (e: React.MouseEvent) => {
- e.preventDefault()
- e.stopPropagation()
- onToggle?.()
- }
+ const handleToggle = (e: React.MouseEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ onToggle?.()
+ }
- const handleDelete = (e: React.MouseEvent) => {
- e.preventDefault()
- e.stopPropagation()
- onDelete?.(e)
- }
+ const handleDelete = (e: React.MouseEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ onDelete?.(e)
+ }
- const handleDropdownClick = (e: React.MouseEvent) => {
- e.preventDefault()
- e.stopPropagation()
- }
+ const handleDropdownClick = (e: React.MouseEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ }
- return (
- <div className="w-full">
- <div
- className={cn(
- "flex items-center group gap-2 px-3 py-2 hover:bg-muted/50 transition-colors",
- isActive && "bg-muted",
- level > 0 && "pl-4",
- !isClickable && "cursor-default"
- )}
- style={{ paddingLeft: `${12 + (level * 16)}px` }}
- >
- {/* Expand/collapse button for investigations */}
- {canExpand && (
- <Button
- variant="ghost"
- size="icon"
- className="h-4 w-4 p-0 hover:bg-transparent"
- onClick={handleToggle}
- >
- {isExpanded ? (
- <ChevronDown className="h-3 w-3" />
- ) : (
- <ChevronRight className="h-3 w-3" />
- )}
- </Button>
- )}
+ return (
+ <div className="w-full">
+ <div
+ className={cn(
+ 'flex items-center group gap-2 px-3 py-2 hover:bg-muted/50 transition-colors',
+ isActive && 'bg-muted',
+ level > 0 && 'pl-4',
+ !isClickable && 'cursor-default'
+ )}
+ style={{ paddingLeft: `${12 + level * 16}px` }}
+ >
+ {/* Expand/collapse button for investigations */}
+ {canExpand && (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-4 w-4 p-0 hover:bg-transparent"
+ onClick={handleToggle}
+ >
+ {isExpanded ? (
+ <ChevronDown className="h-3 w-3" />
+ ) : (
+ <ChevronRight className="h-3 w-3" />
+ )}
+ </Button>
+ )}
- {/* Icon */}
- {isInvestigation ? (
- <Search className="h-4 w-4 text-muted-foreground" />
- ) : (
- <Waypoints className="h-4 w-4 text-muted-foreground" />
- )}
+ {/* Icon */}
+ {isInvestigation ? (
+ <Search className="h-4 w-4 text-muted-foreground" />
+ ) : (
+ <Waypoints className="h-4 w-4 text-muted-foreground" />
+ )}
- {/* Name */}
- <span className="flex-1 text-sm truncate font-medium">
- {item.name}
- </span>
+ {/* Name */}
+ <span className="flex-1 text-sm truncate font-medium">{item.name}</span>
- {/* Actions */}
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <div>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 group-hover:opacity-100 opacity-0 transition-all duration-100"
- onClick={handleDropdownClick}
- >
- <MoreVertical className="h-4 w-4" />
- </Button>
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem variant="destructive" onClick={handleDelete}>
- <Trash2 className="h-4 w-4 mr-2" />
- Delete {isInvestigation ? 'Investigation' : 'Sketch'}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ {/* Actions */}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <div>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 group-hover:opacity-100 opacity-0 transition-all duration-100"
+ onClick={handleDropdownClick}
+ >
+ <MoreVertical className="h-4 w-4" />
+ </Button>
</div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem variant="destructive" onClick={handleDelete}>
+ <Trash2 className="h-4 w-4 mr-2" />
+ Delete {isInvestigation ? 'Investigation' : 'Sketch'}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
- {/* Children */}
- {canExpand && isExpanded && (
- <div className="w-full">
- {children}
- </div>
- )}
- </div>
- )
+ {/* Children */}
+ {canExpand && isExpanded && <div className="w-full">{children}</div>}
+ </div>
+ )
}
-export const SketchListItem = ({ sketch, investigationId, refetch }: { sketch: Sketch, investigationId: string, refetch: () => void }) => {
- const { confirm } = useConfirm();
- const queryClient = useQueryClient();
+export const SketchListItem = ({
+ sketch,
+ investigationId,
+ refetch
+}: {
+ sketch: Sketch
+ investigationId: string
+ refetch: () => void
+}) => {
+ const { confirm } = useConfirm()
+ const queryClient = useQueryClient()
- // Delete sketch mutation
- const deleteSketchMutation = useMutation({
- mutationFn: sketchService.delete,
- onSuccess: () => {
- // Invalidate all related queries
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.list
- })
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.detail(investigationId)
- })
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.sketches(investigationId)
- })
- queryClient.invalidateQueries({
- queryKey: queryKeys.sketches.list
- })
- queryClient.invalidateQueries({
- queryKey: queryKeys.sketches.detail(sketch.id)
- })
- queryClient.invalidateQueries({
- queryKey: queryKeys.sketches.graph(investigationId, sketch.id)
- })
- // Also invalidate dashboard queries
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.dashboard
- })
- // Ensure parent lists refresh
- try { refetch(); } catch {}
- },
- onError: (error) => {
- console.error("Error deleting sketch:", error)
- }
- });
+ // Delete sketch mutation
+ const deleteSketchMutation = useMutation({
+ mutationFn: sketchService.delete,
+ onSuccess: () => {
+ // Invalidate all related queries
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.list
+ })
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.detail(investigationId)
+ })
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.sketches(investigationId)
+ })
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.sketches.list
+ })
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.sketches.detail(sketch.id)
+ })
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.sketches.graph(investigationId, sketch.id)
+ })
+ // Also invalidate dashboard queries
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.dashboard
+ })
+ // Ensure parent lists refresh
+ try {
+ refetch()
+ } catch {}
+ },
+ onError: (error) => {
+ console.error('Error deleting sketch:', error)
+ }
+ })
- const handleDelete = async (e: React.MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
+ const handleDelete = async (e: React.MouseEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
- const confirmed = await confirm({
- title: "Delete Sketch",
- message: `Are you sure you want to delete "${sketch.title}"? This action cannot be undone.`
- });
+ const confirmed = await confirm({
+ title: 'Delete Sketch',
+ message: `Are you sure you want to delete "${sketch.title}"? This action cannot be undone.`
+ })
- if (confirmed) {
- toast.promise(deleteSketchMutation.mutateAsync(sketch.id), {
- loading: 'Deleting sketch...',
- success: () => `Sketch "${sketch.title}" has been deleted`,
- error: 'Failed to delete sketch'
- });
- }
- };
+ if (confirmed) {
+ toast.promise(deleteSketchMutation.mutateAsync(sketch.id), {
+ loading: 'Deleting sketch...',
+ success: () => `Sketch "${sketch.title}" has been deleted`,
+ error: 'Failed to delete sketch'
+ })
+ }
+ }
- return (
- <Link
- to="/dashboard/investigations/$investigationId/$type/$id"
- params={{
- investigationId: investigationId,
- type: "graph",
- id: sketch.id
- }}
- id={sketch.id}
- >
- {({ isActive }) => (
- <TreeNode
- item={{ id: sketch.id, name: sketch.title, type: 'sketch' }}
- level={1}
- isActive={isActive}
- onDelete={handleDelete}
- isClickable={false}
- />
- )}
- </Link>
- );
-};
+ return (
+ <Link
+ to="/dashboard/investigations/$investigationId/$type/$id"
+ params={{
+ investigationId: investigationId,
+ type: 'graph',
+ id: sketch.id
+ }}
+ id={sketch.id}
+ >
+ {({ isActive }) => (
+ <TreeNode
+ item={{ id: sketch.id, name: sketch.title, type: 'sketch' }}
+ level={1}
+ isActive={isActive}
+ onDelete={handleDelete}
+ isClickable={false}
+ />
+ )}
+ </Link>
+ )
+}
const InvestigationList = () => {
- const { data, isLoading, error, refetch } = useQuery({
- queryKey: queryKeys.investigations.list,
- queryFn: investigationService.get,
- })
- const { confirm } = useConfirm();
- const [searchQuery, setSearchQuery] = useState("")
- const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set())
- const queryClient = useQueryClient()
+ const { data, isLoading, error, refetch } = useQuery({
+ queryKey: queryKeys.investigations.list,
+ queryFn: investigationService.get
+ })
+ const { confirm } = useConfirm()
+ const [searchQuery, setSearchQuery] = useState('')
+ const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set())
+ const queryClient = useQueryClient()
- const filteredInvestigations = useMemo(() => {
- if (!data) return []
- if (!searchQuery.trim()) return data
+ const filteredInvestigations = useMemo(() => {
+ if (!data) return []
+ if (!searchQuery.trim()) return data
- const query = searchQuery.toLowerCase().trim()
- return data.filter((investigation: Investigation) => {
- const matchesInvestigation = investigation.name.toLowerCase().includes(query)
- const matchesSketches = investigation.sketches?.some(sketch =>
- sketch.title.toLowerCase().includes(query)
- )
- return matchesInvestigation || matchesSketches
- })
- }, [data, searchQuery])
+ const query = searchQuery.toLowerCase().trim()
+ return data.filter((investigation: Investigation) => {
+ const matchesInvestigation = investigation.name.toLowerCase().includes(query)
+ const matchesSketches = investigation.sketches?.some((sketch) =>
+ sketch.title.toLowerCase().includes(query)
+ )
+ return matchesInvestigation || matchesSketches
+ })
+ }, [data, searchQuery])
- const toggleNode = (nodeId: string) => {
- setExpandedNodes(prev => {
- const newSet = new Set(prev)
- if (newSet.has(nodeId)) {
- newSet.delete(nodeId)
- } else {
- newSet.add(nodeId)
- }
- return newSet
- })
- }
+ const toggleNode = (nodeId: string) => {
+ setExpandedNodes((prev) => {
+ const newSet = new Set(prev)
+ if (newSet.has(nodeId)) {
+ newSet.delete(nodeId)
+ } else {
+ newSet.add(nodeId)
+ }
+ return newSet
+ })
+ }
- const handleDeleteInvestigation = async (investigation: Investigation, e: React.MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
+ const handleDeleteInvestigation = async (investigation: Investigation, e: React.MouseEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
- const confirmed = await confirm({
- title: "Delete Investigation",
- message: `Are you sure you want to delete "${investigation.name}"? This will also delete all sketches within it. This action cannot be undone.`
- });
+ const confirmed = await confirm({
+ title: 'Delete Investigation',
+ message: `Are you sure you want to delete "${investigation.name}"? This will also delete all sketches within it. This action cannot be undone.`
+ })
- if (confirmed) {
- const deletePromise = () => investigationService.delete(investigation.id).then(() => {
- // Invalidate the investigations list
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.list
- })
+ if (confirmed) {
+ const deletePromise = () =>
+ investigationService.delete(investigation.id).then(() => {
+ // Invalidate the investigations list
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.list
+ })
- // Also remove related data from cache
- queryClient.removeQueries({
- queryKey: queryKeys.investigations.detail(investigation.id)
- })
- queryClient.removeQueries({
- queryKey: queryKeys.investigations.sketches(investigation.id)
- })
- queryClient.removeQueries({
- queryKey: queryKeys.investigations.analyses(investigation.id)
- })
- queryClient.removeQueries({
- queryKey: queryKeys.investigations.flows(investigation.id)
- })
- });
+ // Also remove related data from cache
+ queryClient.removeQueries({
+ queryKey: queryKeys.investigations.detail(investigation.id)
+ })
+ queryClient.removeQueries({
+ queryKey: queryKeys.investigations.sketches(investigation.id)
+ })
+ queryClient.removeQueries({
+ queryKey: queryKeys.investigations.analyses(investigation.id)
+ })
+ queryClient.removeQueries({
+ queryKey: queryKeys.investigations.flows(investigation.id)
+ })
+ })
- toast.promise(deletePromise, {
- loading: 'Deleting investigation...',
- success: () => `Investigation "${investigation.name}" has been deleted`,
- error: 'Failed to delete investigation'
- });
- }
- };
+ toast.promise(deletePromise, {
+ loading: 'Deleting investigation...',
+ success: () => `Investigation "${investigation.name}" has been deleted`,
+ error: 'Failed to delete investigation'
+ })
+ }
+ }
- if (error) return (
- <ErrorState
- title="Couldn't load investigations"
- description="Something went wrong while fetching data. Please try again."
- error={error}
- onRetry={() => refetch()}
- />
- )
+ if (error)
return (
- <div className="w-full h-full bg-card flex flex-col overflow-hidden">
- <div className="p-2 flex items-center gap-2 border-b">
- <NewInvestigation noDropDown>
- <Button variant="ghost" size="icon" className="h-7 w-7">
- <PlusIcon className="h-4 w-4" />
- </Button>
- </NewInvestigation>
- <Input
- type="search"
- className="h-7"
- placeholder="Search..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- />
- </div>
+ <ErrorState
+ title="Couldn't load investigations"
+ description="Something went wrong while fetching data. Please try again."
+ error={error}
+ onRetry={() => refetch()}
+ />
+ )
+ return (
+ <div className="w-full h-full bg-card flex flex-col overflow-hidden">
+ <div className="p-2 flex items-center gap-2 border-b">
+ <NewInvestigation noDropDown>
+ <Button variant="ghost" size="icon" className="h-7 w-7">
+ <PlusIcon className="h-4 w-4" />
+ </Button>
+ </NewInvestigation>
+ <Input
+ type="search"
+ className="h-7"
+ placeholder="Search..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ </div>
- {isLoading ? (
- <div className="p-2">
- <SkeletonList rowCount={7} />
- </div>
- ) : filteredInvestigations.length > 0 ? (
- <div className="overflow-auto">
- {filteredInvestigations.map((investigation: Investigation) => {
- const isExpanded = expandedNodes.has(investigation.id)
- const hasSketches = investigation.sketches && investigation.sketches.length > 0
+ {isLoading ? (
+ <div className="p-2">
+ <SkeletonList rowCount={7} />
+ </div>
+ ) : filteredInvestigations.length > 0 ? (
+ <div className="overflow-auto">
+ {filteredInvestigations.map((investigation: Investigation) => {
+ const isExpanded = expandedNodes.has(investigation.id)
+ const hasSketches = investigation.sketches && investigation.sketches.length > 0
- return (
- <div key={investigation.id} className="w-full">
- <Link
- to="/dashboard/investigations/$investigationId"
- params={{
- investigationId: investigation.id,
- }}
- >
- {({ isActive }) => (
- <TreeNode
- item={{ id: investigation.id, name: investigation.name, type: 'investigation' }}
- isExpanded={isExpanded}
- onToggle={() => toggleNode(investigation.id)}
- isActive={isActive}
- onDelete={(e) => handleDeleteInvestigation(investigation, e)}
- isClickable={false}
- >
- {hasSketches ? (
- investigation.sketches!.map((sketch: Sketch) => (
- <SketchListItem
- refetch={refetch}
- key={sketch.id}
- sketch={sketch}
- investigationId={investigation.id}
- />
- ))
- ) : (
- <div className="ml-8 px-3 py-2 text-sm text-muted-foreground">
- No sketches
- </div>
- )}
- </TreeNode>
- )}
- </Link>
- </div>
- )
- })}
- </div>
- ) : (
- <div className="flex-1 p-4">
- <div className="h-full w-full rounded-lg border border-dashed bg-muted/30 flex flex-col items-center justify-center text-center gap-3 p-6">
- <div className="text-sm font-medium">No investigations yet</div>
- <div className="text-xs text-muted-foreground max-w-xs">
- Create an investigation to organize your graphs and notes by case, incident, or research topic.
+ return (
+ <div key={investigation.id} className="w-full">
+ <Link
+ to="/dashboard/investigations/$investigationId"
+ params={{
+ investigationId: investigation.id
+ }}
+ >
+ {({ isActive }) => (
+ <TreeNode
+ item={{
+ id: investigation.id,
+ name: investigation.name,
+ type: 'investigation'
+ }}
+ isExpanded={isExpanded}
+ onToggle={() => toggleNode(investigation.id)}
+ isActive={isActive}
+ onDelete={(e) => handleDeleteInvestigation(investigation, e)}
+ isClickable={false}
+ >
+ {hasSketches ? (
+ investigation.sketches!.map((sketch: Sketch) => (
+ <SketchListItem
+ refetch={refetch}
+ key={sketch.id}
+ sketch={sketch}
+ investigationId={investigation.id}
+ />
+ ))
+ ) : (
+ <div className="ml-8 px-3 py-2 text-sm text-muted-foreground">
+ No sketches
</div>
- <NewInvestigation noDropDown>
- <Button size="sm">
- <PlusIcon className="w-4 h-4 mr-2" />
- Create investigation
- </Button>
- </NewInvestigation>
- </div>
- </div>
- )}
+ )}
+ </TreeNode>
+ )}
+ </Link>
+ </div>
+ )
+ })}
</div>
- )
+ ) : (
+ <div className="flex-1 p-4">
+ <div className="h-full w-full rounded-lg border border-dashed bg-muted/30 flex flex-col items-center justify-center text-center gap-3 p-6">
+ <div className="text-sm font-medium">No investigations yet</div>
+ <div className="text-xs text-muted-foreground max-w-xs">
+ Create an investigation to organize your graphs and notes by case, incident, or
+ research topic.
+ </div>
+ <NewInvestigation noDropDown>
+ <Button size="sm">
+ <PlusIcon className="w-4 h-4 mr-2" />
+ Create investigation
+ </Button>
+ </NewInvestigation>
+ </div>
+ </div>
+ )}
+ </div>
+ )
}
-export default InvestigationList
\ No newline at end of file
+export default InvestigationList
diff --git a/flowsint-app/src/renderer/src/components/investigations/new-investigation.tsx b/flowsint-app/src/renderer/src/components/investigations/new-investigation.tsx
index cfe365c2..6ee43be8 100644
--- a/flowsint-app/src/renderer/src/components/investigations/new-investigation.tsx
+++ b/flowsint-app/src/renderer/src/components/investigations/new-investigation.tsx
@@ -1,182 +1,198 @@
-
-import { useState, type ReactNode } from "react"
-import { useForm } from "react-hook-form"
-import { zodResolver } from "@hookform/resolvers/zod"
-import { useRouter } from "@tanstack/react-router"
-import { toast } from "sonner"
-import { investigationService } from "@/api/investigation-service"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { queryKeys } from "@/api/query-keys"
-import { Button } from "@/components/ui/button"
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
-import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
-import { Input } from "@/components/ui/input"
-import * as z from "zod"
+import { useState, type ReactNode } from 'react'
+import { useForm } from 'react-hook-form'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useRouter } from '@tanstack/react-router'
+import { toast } from 'sonner'
+import { investigationService } from '@/api/investigation-service'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { queryKeys } from '@/api/query-keys'
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger
+} from '@/components/ui/dialog'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage
+} from '@/components/ui/form'
+import { Input } from '@/components/ui/input'
+import * as z from 'zod'
// Schema de validation Zod
const investigationSchema = z.object({
- name: z.string()
- .min(1, "Investigation name is required")
- .min(3, "Investigation name must be at least 3 characters")
- .max(100, "Investigation name must be less than 100 characters"),
- description: z.string()
- .max(500, "Description must be less than 500 characters")
- .optional()
+ name: z
+ .string()
+ .min(1, 'Investigation name is required')
+ .min(3, 'Investigation name must be at least 3 characters')
+ .max(100, 'Investigation name must be less than 100 characters'),
+ description: z.string().max(500, 'Description must be less than 500 characters').optional()
})
type InvestigationFormData = z.infer<typeof investigationSchema>
interface NewInvestigationProps {
- children: ReactNode
- noDropDown?: boolean
+ children: ReactNode
+ noDropDown?: boolean
}
export default function NewInvestigation({ children, noDropDown = false }: NewInvestigationProps) {
- const [open, setOpen] = useState(false)
- const router = useRouter()
- const queryClient = useQueryClient()
-
- const form = useForm<InvestigationFormData>({
- resolver: zodResolver(investigationSchema),
- defaultValues: {
- name: "",
- description: ""
- }
- })
+ const [open, setOpen] = useState(false)
+ const router = useRouter()
+ const queryClient = useQueryClient()
- const { handleSubmit, formState: { isSubmitting }, reset } = form
+ const form = useForm<InvestigationFormData>({
+ resolver: zodResolver(investigationSchema),
+ defaultValues: {
+ name: '',
+ description: ''
+ }
+ })
- // Create investigation mutation
- const createInvestigationMutation = useMutation({
- mutationFn: investigationService.create,
- onSuccess: (result) => {
- if (result.id) {
- toast.success("New investigation created.")
- router.navigate({ to: `/dashboard/investigations/${result.id}` })
- // Invalidate investigations list
- queryClient.invalidateQueries({
- queryKey: queryKeys.investigations.list
- })
- } else {
- toast.error(result.error || "Failed to create investigation")
- }
- },
- onError: (error) => {
- toast.error(error.message)
- }
- })
+ const {
+ handleSubmit,
+ formState: { isSubmitting },
+ reset
+ } = form
- const onSubmit = async (data: InvestigationFormData) => {
- try {
- await createInvestigationMutation.mutateAsync(JSON.stringify(data))
- } catch (error) {
- console.error('Error creating investigation:', error)
- }
+ // Create investigation mutation
+ const createInvestigationMutation = useMutation({
+ mutationFn: investigationService.create,
+ onSuccess: (result) => {
+ if (result.id) {
+ toast.success('New investigation created.')
+ router.navigate({ to: `/dashboard/investigations/${result.id}` })
+ // Invalidate investigations list
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.investigations.list
+ })
+ } else {
+ toast.error(result.error || 'Failed to create investigation')
+ }
+ },
+ onError: (error) => {
+ toast.error(error.message)
}
+ })
- const handleClose = () => {
- setOpen(false)
- reset() // Reset du formulaire avec React Hook Form
+ const onSubmit = async (data: InvestigationFormData) => {
+ try {
+ await createInvestigationMutation.mutateAsync(JSON.stringify(data))
+ } catch (error) {
+ console.error('Error creating investigation:', error)
}
+ }
- const InvestigationForm = () => (
- <Form {...form}>
- <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
- <div className="grid gap-4 py-4">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Investigation name</FormLabel>
- <FormControl>
- <Input
- required
- placeholder="Fraud suspicion"
- disabled={isSubmitting}
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
+ const handleClose = () => {
+ setOpen(false)
+ reset() // Reset du formulaire avec React Hook Form
+ }
- <FormField
- control={form.control}
- name="description"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Description</FormLabel>
- <FormControl>
- <Input
- placeholder="Investigation into a phishing campaign via LinkedIn."
- disabled={isSubmitting}
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
+ const InvestigationForm = () => (
+ <Form {...form}>
+ <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
+ <div className="grid gap-4 py-4">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Investigation name</FormLabel>
+ <FormControl>
+ <Input
+ required
+ placeholder="Fraud suspicion"
+ disabled={isSubmitting}
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={handleClose}
- disabled={isSubmitting}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- disabled={isSubmitting}
- >
- {isSubmitting ? "Creating..." : "Create Investigation"}
- </Button>
- </DialogFooter>
- </form>
- </Form>
- )
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Description</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="Investigation into a phishing campaign via LinkedIn."
+ disabled={isSubmitting}
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
- if (noDropDown) {
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger asChild><span role="button">{children}</span></DialogTrigger>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>New investigation</DialogTitle>
- <DialogDescription>Create a new blank investigation.</DialogDescription>
- </DialogHeader>
- <InvestigationForm />
- </DialogContent>
- </Dialog>
- )
- }
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={handleClose} disabled={isSubmitting}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isSubmitting}>
+ {isSubmitting ? 'Creating...' : 'Create Investigation'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ )
+ if (noDropDown) {
return (
- <>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onSelect={() => setOpen(true)}>
- New investigation
- <span className="ml-auto text-xs text-muted-foreground">⌘ E</span>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>New investigation</DialogTitle>
- <DialogDescription>Create a new blank investigation.</DialogDescription>
- </DialogHeader>
- <InvestigationForm />
- </DialogContent>
- </Dialog>
- </>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <span role="button">{children}</span>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>New investigation</DialogTitle>
+ <DialogDescription>Create a new blank investigation.</DialogDescription>
+ </DialogHeader>
+ <InvestigationForm />
+ </DialogContent>
+ </Dialog>
)
+ }
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={() => setOpen(true)}>
+ New investigation
+ <span className="ml-auto text-xs text-muted-foreground">⌘ E</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>New investigation</DialogTitle>
+ <DialogDescription>Create a new blank investigation.</DialogDescription>
+ </DialogHeader>
+ <InvestigationForm />
+ </DialogContent>
+ </Dialog>
+ </>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/investigations/sketch-list.tsx b/flowsint-app/src/renderer/src/components/investigations/sketch-list.tsx
index 9152e570..72b08696 100644
--- a/flowsint-app/src/renderer/src/components/investigations/sketch-list.tsx
+++ b/flowsint-app/src/renderer/src/components/investigations/sketch-list.tsx
@@ -1,101 +1,104 @@
-import { investigationService } from "@/api/investigation-service"
-import { useQuery } from "@tanstack/react-query"
-import type { Sketch } from "@/types/sketch"
-import { Button } from "../ui/button"
-import { PlusIcon, Waypoints } from "lucide-react"
-import { Input } from "../ui/input"
-import { useParams } from "@tanstack/react-router"
-import { SkeletonList } from "../shared/skeleton-list"
-import NewSketch from "../graphs/new-sketch"
-import { SketchListItem } from "./investigation-list"
-import { useState, useMemo } from "react"
-import { queryKeys } from "@/api/query-keys"
-import ErrorState from "../shared/error-state"
+import { investigationService } from '@/api/investigation-service'
+import { useQuery } from '@tanstack/react-query'
+import type { Sketch } from '@/types/sketch'
+import { Button } from '../ui/button'
+import { PlusIcon, Waypoints } from 'lucide-react'
+import { Input } from '../ui/input'
+import { useParams } from '@tanstack/react-router'
+import { SkeletonList } from '../shared/skeleton-list'
+import NewSketch from '../graphs/new-sketch'
+import { SketchListItem } from './investigation-list'
+import { useState, useMemo } from 'react'
+import { queryKeys } from '@/api/query-keys'
+import ErrorState from '../shared/error-state'
const SketchList = () => {
- const { investigationId } = useParams({ strict: false })
- const { data: investigation, isLoading, refetch, error } = useQuery({
- queryKey: queryKeys.investigations.detail(investigationId as string),
- queryFn: () => investigationService.getById(investigationId as string),
- })
- const [searchQuery, setSearchQuery] = useState("")
+ const { investigationId } = useParams({ strict: false })
+ const {
+ data: investigation,
+ isLoading,
+ refetch,
+ error
+ } = useQuery({
+ queryKey: queryKeys.investigations.detail(investigationId as string),
+ queryFn: () => investigationService.getById(investigationId as string)
+ })
+ const [searchQuery, setSearchQuery] = useState('')
- const filteredSketches = useMemo(() => {
- if (!investigation?.sketches) return []
- if (!searchQuery.trim()) return investigation.sketches
+ const filteredSketches = useMemo(() => {
+ if (!investigation?.sketches) return []
+ if (!searchQuery.trim()) return investigation.sketches
- const query = searchQuery.toLowerCase().trim()
- return investigation.sketches.filter((sketch) =>
- sketch.title.toLowerCase().includes(query)
- )
- }, [investigation?.sketches, searchQuery])
+ const query = searchQuery.toLowerCase().trim()
+ return investigation.sketches.filter((sketch) => sketch.title.toLowerCase().includes(query))
+ }, [investigation?.sketches, searchQuery])
- if (error) return (
- <ErrorState
- title="Couldn't load sketches"
- description="Something went wrong while fetching data. Please try again."
- error={error}
- onRetry={() => refetch()}
- />
- )
+ if (error)
return (
- <div className="w-full h-full bg-card flex flex-col overflow-hidden">
- <div className="p-2 flex items-center gap-2 border-b shrink-0">
- <NewSketch>
- <Button variant="ghost" size="icon" className="h-7 w-7">
- <PlusIcon className="h-4 w-4" />
- </Button>
- </NewSketch>
- <Input
- type="search"
- className="!border border-border h-7"
- placeholder="Search..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- />
- </div>
+ <ErrorState
+ title="Couldn't load sketches"
+ description="Something went wrong while fetching data. Please try again."
+ error={error}
+ onRetry={() => refetch()}
+ />
+ )
+ return (
+ <div className="w-full h-full bg-card flex flex-col overflow-hidden">
+ <div className="p-2 flex items-center gap-2 border-b shrink-0">
+ <NewSketch>
+ <Button variant="ghost" size="icon" className="h-7 w-7">
+ <PlusIcon className="h-4 w-4" />
+ </Button>
+ </NewSketch>
+ <Input
+ type="search"
+ className="!border border-border h-7"
+ placeholder="Search..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ </div>
- <div className="flex-1 overflow-auto">
- {isLoading ? (
- <div className="p-2">
- <SkeletonList rowCount={7} />
- </div>
- ) : filteredSketches.length > 0 ? (
- <ul>
- {filteredSketches.map((sketch: Sketch) => (
- <SketchListItem
- refetch={refetch}
- key={sketch.id}
- sketch={sketch}
- investigationId={investigation.id}
- />
- ))}
- </ul>
- ) : (
- <div className="p-6 flex flex-col items-center text-center gap-3 text-muted-foreground">
- <Waypoints className="h-10 w-10 text-yellow-500" />
- <div className="space-y-1">
- <h3 className="text-sm font-semibold text-foreground">
- {searchQuery ? "No matching sketches" : "No sketches yet"}
- </h3>
- <p className="text-xs opacity-70 max-w-xs">
- {searchQuery
- ? "Try adjusting your search query to find what you're looking for."
- : "This investigation doesn't contain any sketch. Sketches let you organize and visualize your data as graphs."
- }
- </p>
- </div>
- <NewSketch>
- <Button size="sm" variant="outline">
- <PlusIcon className="w-4 h-4 mr-2" />
- Create your first sketch
- </Button>
- </NewSketch>
- </div>
- )}
+ <div className="flex-1 overflow-auto">
+ {isLoading ? (
+ <div className="p-2">
+ <SkeletonList rowCount={7} />
+ </div>
+ ) : filteredSketches.length > 0 ? (
+ <ul>
+ {filteredSketches.map((sketch: Sketch) => (
+ <SketchListItem
+ refetch={refetch}
+ key={sketch.id}
+ sketch={sketch}
+ investigationId={investigation.id}
+ />
+ ))}
+ </ul>
+ ) : (
+ <div className="p-6 flex flex-col items-center text-center gap-3 text-muted-foreground">
+ <Waypoints className="h-10 w-10 text-yellow-500" />
+ <div className="space-y-1">
+ <h3 className="text-sm font-semibold text-foreground">
+ {searchQuery ? 'No matching sketches' : 'No sketches yet'}
+ </h3>
+ <p className="text-xs opacity-70 max-w-xs">
+ {searchQuery
+ ? "Try adjusting your search query to find what you're looking for."
+ : "This investigation doesn't contain any sketch. Sketches let you organize and visualize your data as graphs."}
+ </p>
</div>
- </div>
- )
+ <NewSketch>
+ <Button size="sm" variant="outline">
+ <PlusIcon className="w-4 h-4 mr-2" />
+ Create your first sketch
+ </Button>
+ </NewSketch>
+ </div>
+ )}
+ </div>
+ </div>
+ )
}
export default SketchList
diff --git a/flowsint-app/src/renderer/src/components/keys/key-select.tsx b/flowsint-app/src/renderer/src/components/keys/key-select.tsx
index 5f486087..751f79bf 100644
--- a/flowsint-app/src/renderer/src/components/keys/key-select.tsx
+++ b/flowsint-app/src/renderer/src/components/keys/key-select.tsx
@@ -1,34 +1,46 @@
-import { useQuery } from "@tanstack/react-query"
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
-import { KeyService } from "@/api/key-service"
+import { useQuery } from '@tanstack/react-query'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select'
+import { KeyService } from '@/api/key-service'
import { type Key as KeyType } from '@/types/key'
-export default function KeySelector({ onChange, value }: { onChange: (value: KeyType) => void, value?: KeyType }) {
- // Fetch keys
- const { data: keys = [], isLoading } = useQuery<KeyType[]>({
- queryKey: ['keys'],
- queryFn: () => KeyService.get(),
- })
+export default function KeySelector({
+ onChange,
+ value
+}: {
+ onChange: (value: KeyType) => void
+ value?: KeyType
+}) {
+ // Fetch keys
+ const { data: keys = [], isLoading } = useQuery<KeyType[]>({
+ queryKey: ['keys'],
+ queryFn: () => KeyService.get()
+ })
- const handleValueChange = (keyId: string) => {
- const selectedKey = keys.find(key => key.id === keyId)
- if (selectedKey) {
- onChange(selectedKey)
- }
+ const handleValueChange = (keyId: string) => {
+ const selectedKey = keys.find((key) => key.id === keyId)
+ if (selectedKey) {
+ onChange(selectedKey)
}
+ }
- return (
- <Select onValueChange={handleValueChange} value={value?.id || ""} disabled={isLoading}>
- <SelectTrigger className="w-full">
- <SelectValue placeholder="Select a key" />
- </SelectTrigger>
- <SelectContent>
- {keys.map((key: KeyType) => (
- <SelectItem key={key.id} value={key.id}>
- {key.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )
+ return (
+ <Select onValueChange={handleValueChange} value={value?.id || ''} disabled={isLoading}>
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select a key" />
+ </SelectTrigger>
+ <SelectContent>
+ {keys.map((key: KeyType) => (
+ <SelectItem key={key.id} value={key.id}>
+ {key.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/layout/breadcrumb.tsx b/flowsint-app/src/renderer/src/components/layout/breadcrumb.tsx
index 570f0d34..8aeea6c0 100644
--- a/flowsint-app/src/renderer/src/components/layout/breadcrumb.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/breadcrumb.tsx
@@ -1,120 +1,122 @@
-import { useLocation, useParams } from "@tanstack/react-router"
+import { useLocation, useParams } from '@tanstack/react-router'
import {
- Breadcrumb,
- BreadcrumbItem,
- BreadcrumbLink,
- BreadcrumbList,
- BreadcrumbPage,
- BreadcrumbSeparator,
-} from "@/components/ui/breadcrumb"
-import { Link } from "@tanstack/react-router"
-import { useQuery } from "@tanstack/react-query"
-import { investigationService } from "@/api/investigation-service"
-import { sketchService } from "@/api/sketch-service"
-import { Skeleton } from "@/components/ui/skeleton"
-import { Home } from "lucide-react"
-import { flowService } from "@/api/flow-service"
+ Breadcrumb,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbList,
+ BreadcrumbPage,
+ BreadcrumbSeparator
+} from '@/components/ui/breadcrumb'
+import { Link } from '@tanstack/react-router'
+import { useQuery } from '@tanstack/react-query'
+import { investigationService } from '@/api/investigation-service'
+import { sketchService } from '@/api/sketch-service'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Home } from 'lucide-react'
+import { flowService } from '@/api/flow-service'
export function PathBreadcrumb() {
- const { investigationId, id, type, flowId } = useParams({ strict: false })
- const location = useLocation()
+ const { investigationId, id, type, flowId } = useParams({ strict: false })
+ const location = useLocation()
- const { data: investigation, isLoading: isInvestigationLoading } = useQuery({
- queryKey: ["investigation", investigationId],
- queryFn: () => investigationService.getById(investigationId!),
- enabled: !!investigationId,
- })
+ const { data: investigation, isLoading: isInvestigationLoading } = useQuery({
+ queryKey: ['investigation', investigationId],
+ queryFn: () => investigationService.getById(investigationId!),
+ enabled: !!investigationId
+ })
- const { data: sketch, isLoading: isSketchLoading } = useQuery({
- queryKey: ["sketch", id],
- queryFn: () => sketchService.getById(id!),
- enabled: !!id && type === "graph",
- })
+ const { data: sketch, isLoading: isSketchLoading } = useQuery({
+ queryKey: ['sketch', id],
+ queryFn: () => sketchService.getById(id!),
+ enabled: !!id && type === 'graph'
+ })
- const { data: flow, isLoading: isFlowLoading } = useQuery({
- queryKey: ["flow", flowId],
- queryFn: () => flowService.getById(flowId!),
- enabled: !!flowId,
- })
+ const { data: flow, isLoading: isFlowLoading } = useQuery({
+ queryKey: ['flow', flowId],
+ queryFn: () => flowService.getById(flowId!),
+ enabled: !!flowId
+ })
- const isFlowPage = location.pathname.includes('/flows')
+ const isFlowPage = location.pathname.includes('/flows')
- return (
- <div className="w-full overflow-hidden">
- <Breadcrumb className="w-full">
- <BreadcrumbList className="flex items-center justify-start gap-1 min-w-0">
- <BreadcrumbItem className="flex-shrink-0">
- <BreadcrumbLink asChild>
- <Link to="/dashboard" className="truncate font-medium">
- <Home className="h-4 w-4 opacity-60" strokeWidth={1.4} />
- </Link>
- </BreadcrumbLink>
+ return (
+ <div className="w-full overflow-hidden">
+ <Breadcrumb className="w-full">
+ <BreadcrumbList className="flex items-center justify-start gap-1 min-w-0">
+ <BreadcrumbItem className="flex-shrink-0">
+ <BreadcrumbLink asChild>
+ <Link to="/dashboard" className="truncate font-medium">
+ <Home className="h-4 w-4 opacity-60" strokeWidth={1.4} />
+ </Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ {isFlowPage ? (
+ <>
+ <BreadcrumbSeparator className="flex-shrink-0" />
+ <BreadcrumbItem className="min-w-0">
+ <BreadcrumbLink asChild>
+ <Link to="/dashboard/flows" className="truncate block font-medium">
+ Flows
+ </Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ {flowId && (
+ <>
+ <BreadcrumbSeparator className="flex-shrink-0" />
+ <BreadcrumbItem className="min-w-0 flex-1">
+ <BreadcrumbPage className="truncate block text-muted-foreground">
+ {isFlowLoading ? (
+ <Skeleton className="h-4 w-24" />
+ ) : (
+ flow?.name || '(Unnamed flow)'
+ )}
+ </BreadcrumbPage>
+ </BreadcrumbItem>
+ </>
+ )}
+ </>
+ ) : (
+ investigationId && (
+ <>
+ <BreadcrumbSeparator className="flex-shrink-0" />
+ <BreadcrumbItem className="min-w-0">
+ <BreadcrumbLink asChild>
+ <Link
+ to="/dashboard/investigations/$investigationId"
+ params={{ investigationId: investigationId! }}
+ className="truncate block font-medium"
+ >
+ {isInvestigationLoading ? (
+ <Skeleton className="h-4 w-24" />
+ ) : (
+ investigation?.name
+ )}
+ </Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ {type && id && (
+ <>
+ <BreadcrumbSeparator className="flex-shrink-0" />
+ <BreadcrumbItem className="min-w-0 flex-1">
+ <BreadcrumbPage className="truncate block text-muted-foreground">
+ {type === 'graph' ? (
+ isSketchLoading ? (
+ <Skeleton className="h-4 w-24" />
+ ) : (
+ sketch?.title
+ )
+ ) : (
+ type
+ )}
+ </BreadcrumbPage>
</BreadcrumbItem>
- {isFlowPage ? (
- <>
- <BreadcrumbSeparator className="flex-shrink-0" />
- <BreadcrumbItem className="min-w-0">
- <BreadcrumbLink asChild>
- <Link to="/dashboard/flows" className="truncate block font-medium">
- Flows
- </Link>
- </BreadcrumbLink>
- </BreadcrumbItem>
- {flowId && (
- <>
- <BreadcrumbSeparator className="flex-shrink-0" />
- <BreadcrumbItem className="min-w-0 flex-1">
- <BreadcrumbPage className="truncate block text-muted-foreground">
- {isFlowLoading ? (
- <Skeleton className="h-4 w-24" />
- ) : (
- flow?.name || "(Unnamed flow)"
- )}
- </BreadcrumbPage>
- </BreadcrumbItem>
- </>
- )}
- </>
- ) : investigationId && (
- <>
- <BreadcrumbSeparator className="flex-shrink-0" />
- <BreadcrumbItem className="min-w-0">
- <BreadcrumbLink asChild>
- <Link
- to="/dashboard/investigations/$investigationId"
- params={{ investigationId: investigationId! }}
- className="truncate block font-medium"
- >
- {isInvestigationLoading ? (
- <Skeleton className="h-4 w-24" />
- ) : (
- investigation?.name
- )}
- </Link>
- </BreadcrumbLink>
- </BreadcrumbItem>
- {type && id && (
- <>
- <BreadcrumbSeparator className="flex-shrink-0" />
- <BreadcrumbItem className="min-w-0 flex-1">
- <BreadcrumbPage className="truncate block text-muted-foreground">
- {type === "graph" ? (
- isSketchLoading ? (
- <Skeleton className="h-4 w-24" />
- ) : (
- sketch?.title
- )
- ) : (
- type
- )}
- </BreadcrumbPage>
- </BreadcrumbItem>
- </>
- )}
- </>
- )}
- </BreadcrumbList>
- </Breadcrumb>
- </div>
- )
-}
+ </>
+ )}
+ </>
+ )
+ )}
+ </BreadcrumbList>
+ </Breadcrumb>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/layout/info.tsx b/flowsint-app/src/renderer/src/components/layout/info.tsx
index 5687d38d..a654abec 100644
--- a/flowsint-app/src/renderer/src/components/layout/info.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/info.tsx
@@ -4,95 +4,148 @@ import { Dialog, DialogContent, DialogTrigger } from '../ui/dialog'
import { Button } from '../ui/button'
const InfoDialog = () => {
+ return (
+ <>
+ <Dialog>
+ <DialogTrigger asChild>
+ <div>
+ <Button variant="ghost" size="sm" className="h-6 gap-1 text-xs">
+ <HelpCircle className="h-3 w-3 opacity-60" />
+ </Button>
+ </div>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-2xl">
+ <div className="p-2">
+ <div className="p-2 text-sm space-y-4 overflow-y-auto max-h-[80vh]">
+ <h2 className="text-base font-semibold flex items-center gap-2">About Flowsint</h2>
+ <p>
+ <strong>Flowsint</strong> is an{' '}
+ <strong>investigation and intelligence platform</strong> built to support complex
+ research workflows involving{' '}
+ <strong>people, organizations, infrastructure, and online activity</strong>.
+ </p>
- return (
- <>
- <Dialog>
- <DialogTrigger asChild>
- <div>
- <Button variant="ghost" size="sm" className="h-6 gap-1 text-xs">
- <HelpCircle className="h-3 w-3 opacity-60" />
- </Button>
- </div>
- </DialogTrigger>
- <DialogContent className='sm:max-w-2xl'>
- <div className='p-2'>
- <div className="p-2 text-sm space-y-4 overflow-y-auto max-h-[80vh]">
- <h2 className="text-base font-semibold flex items-center gap-2">
- About Flowsint
- </h2>
- <p>
- <strong>Flowsint</strong> is an <strong>investigation and intelligence platform</strong> built to support complex research workflows involving <strong>people, organizations, infrastructure, and online activity</strong>.
- </p>
+ <p>
+ Whether you're conducting <strong>cyber investigations</strong>, mapping out{' '}
+ <strong>fraud networks</strong>, or gathering intelligence for{' '}
+ <strong>threat assessments</strong>, Flowsint helps you collect, visualize, and
+ understand fragmented data points in a structured and interactive way.
+ </p>
- <p>
- Whether you're conducting <strong>cyber investigations</strong>, mapping out <strong>fraud networks</strong>, or gathering intelligence for <strong>threat assessments</strong>, Flowsint helps you collect, visualize, and understand fragmented data points in a structured and interactive way.
- </p>
+ <h3 className="font-semibold">What Flowsint Does</h3>
+ <ul className="list-disc list-inside space-y-1">
+ <li>
+ <strong>Connects scattered data</strong> — emails, domains, social accounts, IPs,
+ phone numbers, addresses, and more — into a single{' '}
+ <strong>investigative graph</strong>.
+ </li>
+ <li>
+ Offers <strong>visual transforms</strong> to pivot from one entity to related
+ ones: find <strong>connected individuals</strong>, discover{' '}
+ <strong>infrastructure</strong>, uncover <strong>aliases</strong>.
+ </li>
+ <li>
+ <strong>Tracks and saves investigation states</strong> over time, letting you
+ explore multiple hypotheses or revisit older threads without losing context.
+ </li>
+ <li>
+ Supports <strong>live data enrichment</strong> from custom or built-in transforms,
+ giving you <strong>actionable insights</strong> as you explore.
+ </li>
+ </ul>
- <h3 className="font-semibold">What Flowsint Does</h3>
- <ul className="list-disc list-inside space-y-1">
- <li>
- <strong>Connects scattered data</strong> — emails, domains, social accounts, IPs, phone numbers, addresses, and more — into a single <strong>investigative graph</strong>.
- </li>
- <li>
- Offers <strong>visual transforms</strong> to pivot from one entity to related ones: find <strong>connected individuals</strong>, discover <strong>infrastructure</strong>, uncover <strong>aliases</strong>.
- </li>
- <li>
- <strong>Tracks and saves investigation states</strong> over time, letting you explore multiple hypotheses or revisit older threads without losing context.
- </li>
- <li>
- Supports <strong>live data enrichment</strong> from custom or built-in transforms, giving you <strong>actionable insights</strong> as you explore.
- </li>
- </ul>
+ <h3 className="font-semibold">Why Use Flowsint?</h3>
+ <ul className="list-disc list-inside space-y-1">
+ <li>
+ Built for <strong>speed and clarity</strong> — fast graph rendering, clean UI,
+ responsive transforms.
+ </li>
+ <li>
+ <strong>Flexible graph model</strong> that mirrors how investigators think — not
+ just tables and tags, but <strong>relationships</strong>.
+ </li>
+ <li>
+ Ideal for <strong>solo analysts and teams</strong> that need to move fast, explore
+ freely, and make sense of <strong>partial or messy data</strong>.
+ </li>
+ </ul>
- <h3 className="font-semibold">Why Use Flowsint?</h3>
- <ul className="list-disc list-inside space-y-1">
- <li>
- Built for <strong>speed and clarity</strong> — fast graph rendering, clean UI, responsive transforms.
- </li>
- <li>
- <strong>Flexible graph model</strong> that mirrors how investigators think — not just tables and tags, but <strong>relationships</strong>.
- </li>
- <li>
- Ideal for <strong>solo analysts and teams</strong> that need to move fast, explore freely, and make sense of <strong>partial or messy data</strong>.
- </li>
- </ul>
+ <h3 className="font-semibold">Use Cases</h3>
+ <ul className="list-disc list-inside space-y-1">
+ <li>
+ Mapping <strong>digital infrastructure</strong> of individuals or organizations
+ </li>
+ <li>
+ Investigating <strong>online fraud schemes</strong> or{' '}
+ <strong>fake identities</strong>
+ </li>
+ <li>
+ Uncovering <strong>links between actors</strong> across platforms
+ </li>
+ <li>
+ Visualizing the reach of <strong>leaked or exposed data</strong>
+ </li>
+ <li>
+ Tracking <strong>threat actor behavior</strong> across social and technical
+ surfaces
+ </li>
+ </ul>
- <h3 className="font-semibold">Use Cases</h3>
- <ul className="list-disc list-inside space-y-1">
- <li>Mapping <strong>digital infrastructure</strong> of individuals or organizations</li>
- <li>Investigating <strong>online fraud schemes</strong> or <strong>fake identities</strong></li>
- <li>Uncovering <strong>links between actors</strong> across platforms</li>
- <li>Visualizing the reach of <strong>leaked or exposed data</strong></li>
- <li>Tracking <strong>threat actor behavior</strong> across social and technical surfaces</li>
- </ul>
+ <h3 className="font-semibold">Graph Views & Performance</h3>
+ <p>
+ Flowsint provides <strong>multiple graph visualization modes</strong> that
+ automatically adapt based on the number of nodes in your investigation. This
+ switching ensures optimal performance and usability regardless of data complexity.
+ </p>
+ <ul className="list-disc list-inside space-y-1">
+ <li>
+ <strong>Small to large datasets (1-1500 nodes):</strong> Optimized{' '}
+ <strong>React Force Graph</strong> (
+ <a
+ href="https://github.com/vasturiano/react-force-graph"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-primary hover:underline"
+ >
+ github.com/vasturiano/react-force-graph
+ </a>
+ ) layouts with force-directed algorithms that group related entities while
+ maintaining interactive features for focused analysis.
+ </li>
+ <li>
+ <strong>Large datasets (1550-100,000 nodes):</strong> High-performance{' '}
+ <strong>Cosmograph</strong> (
+ <a
+ href="https://cosmograph.app"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-primary hover:underline"
+ >
+ cosmograph.app
+ </a>
+ ) with advanced rendering techniques, allowing you to visualize complex networks
+ without sacrificing responsiveness or browser stability.
+ </li>
+ </ul>
+ <p>
+ This <strong>adaptive approach</strong> means you can start with detailed
+ interactive exploration and seamlessly scale to handle massive investigation graphs
+ without performance degradation. Each view is optimized for its specific use case,
+ ensuring you always have the right tools for your data size.
+ </p>
- <h3 className="font-semibold">Graph Views & Performance</h3>
- <p>
- Flowsint provides <strong>multiple graph visualization modes</strong> that automatically adapt based on the number of nodes in your investigation. This switching ensures optimal performance and usability regardless of data complexity.
- </p>
- <ul className="list-disc list-inside space-y-1">
- <li>
- <strong>Small to large datasets (1-1500 nodes):</strong> Optimized <strong>React Force Graph</strong> (<a href="https://github.com/vasturiano/react-force-graph" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">github.com/vasturiano/react-force-graph</a>) layouts with force-directed algorithms that group related entities while maintaining interactive features for focused analysis.
- </li>
- <li>
- <strong>Large datasets (1550-100,000 nodes):</strong> High-performance <strong>Cosmograph</strong> (<a href="https://cosmograph.app" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">cosmograph.app</a>) with advanced rendering techniques, allowing you to visualize complex networks without sacrificing responsiveness or browser stability.
- </li>
- </ul>
- <p>
- This <strong>adaptive approach</strong> means you can start with detailed interactive exploration and seamlessly scale to handle massive investigation graphs without performance degradation. Each view is optimized for its specific use case, ensuring you always have the right tools for your data size.
- </p>
-
- <p>
- Flowsint is designed for <strong>professionals</strong> who need <strong>full control</strong> over their investigation logic, from how data is structured to how relationships are interpreted. It's not just a tool — it's a <strong>flexible workspace</strong> for building intelligence.
- </p>
- </div>
-
- </div>
- </DialogContent>
- </Dialog>
- </>
- )
+ <p>
+ Flowsint is designed for <strong>professionals</strong> who need{' '}
+ <strong>full control</strong> over their investigation logic, from how data is
+ structured to how relationships are interpreted. It's not just a tool — it's a{' '}
+ <strong>flexible workspace</strong> for building intelligence.
+ </p>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
}
export default memo(InfoDialog)
diff --git a/flowsint-app/src/renderer/src/components/layout/investigation-selector.tsx b/flowsint-app/src/renderer/src/components/layout/investigation-selector.tsx
index 357abafb..e7aa92b6 100644
--- a/flowsint-app/src/renderer/src/components/layout/investigation-selector.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/investigation-selector.tsx
@@ -1,109 +1,112 @@
-import { useState } from "react"
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Skeleton } from "@/components/ui/skeleton";
-import { Separator } from "@/components/ui/separator";
-import { useQuery } from "@tanstack/react-query";
-import { type Investigation } from "@/types/investigation";
-import { investigationService } from "@/api/investigation-service";
-import { useNavigate, useParams } from "@tanstack/react-router";
-import { Search, ChevronDown, Plus, FolderOpen } from "lucide-react";
-import NewInvestigation from "@/components/investigations/new-investigation";
-import { queryKeys } from "@/api/query-keys";
+import { useState } from 'react'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Separator } from '@/components/ui/separator'
+import { useQuery } from '@tanstack/react-query'
+import { type Investigation } from '@/types/investigation'
+import { investigationService } from '@/api/investigation-service'
+import { useNavigate, useParams } from '@tanstack/react-router'
+import { Search, ChevronDown, Plus, FolderOpen } from 'lucide-react'
+import NewInvestigation from '@/components/investigations/new-investigation'
+import { queryKeys } from '@/api/query-keys'
export default function InvestigationSelector() {
- const navigate = useNavigate()
- const { investigationId } = useParams({ strict: false })
- const [open, setOpen] = useState(false)
- const [searchQuery, setSearchQuery] = useState("")
+ const navigate = useNavigate()
+ const { investigationId } = useParams({ strict: false })
+ const [open, setOpen] = useState(false)
+ const [searchQuery, setSearchQuery] = useState('')
- const { data: investigations, isLoading } = useQuery({
- queryKey: queryKeys.investigations.selector(investigationId as string),
- queryFn: investigationService.get,
- refetchOnWindowFocus: true,
- })
+ const { data: investigations, isLoading } = useQuery({
+ queryKey: queryKeys.investigations.selector(investigationId as string),
+ queryFn: investigationService.get,
+ refetchOnWindowFocus: true
+ })
- const handleSelectionChange = (value: string) => {
- navigate({
- to: "/dashboard/investigations/$investigationId",
- params: {
- investigationId: value as string,
- },
- })
- setOpen(false)
- };
+ const handleSelectionChange = (value: string) => {
+ navigate({
+ to: '/dashboard/investigations/$investigationId',
+ params: {
+ investigationId: value as string
+ }
+ })
+ setOpen(false)
+ }
- // Filter investigations based on search
- const filteredInvestigations = investigations?.filter((investigation: Investigation) =>
+ // Filter investigations based on search
+ const filteredInvestigations =
+ investigations?.filter(
+ (investigation: Investigation) =>
!searchQuery || investigation.name.toLowerCase().includes(searchQuery.toLowerCase())
) || []
- const currentInvestigation = investigations?.find((inv: Investigation) => inv.id === investigationId)
+ const currentInvestigation = investigations?.find(
+ (inv: Investigation) => inv.id === investigationId
+ )
- return (
- <div className="flex items-center">
- {isLoading ? <Skeleton className="h-7 w-40 bg-foreground/10" /> :
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <div>
- <Button
- variant="ghost"
- className="min-w-none !h-7 rounded-sm w-full !bg-transparent hover:bg-foreground/10 font-medium shadow-none border-none text-ellipsis truncate gap-1 inset-shadow-none justify-between"
- >
- <span className="text-ellipsis truncate">
- {currentInvestigation?.name || "Select an investigation"}
- </span>
- <ChevronDown className="w-4 h-4 shrink-0" />
- </Button>
- </div>
- </PopoverTrigger>
- <PopoverContent className="w-64 p-0" align="start">
- <div className="p-2 border-b">
- <div className="relative">
- <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="Search investigations..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-8 h-8 text-sm"
- />
- </div>
- </div>
+ return (
+ <div className="flex items-center">
+ {isLoading ? (
+ <Skeleton className="h-7 w-40 bg-foreground/10" />
+ ) : (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <div>
+ <Button
+ variant="ghost"
+ className="min-w-none !h-7 rounded-sm w-full !bg-transparent hover:bg-foreground/10 font-medium shadow-none border-none text-ellipsis truncate gap-1 inset-shadow-none justify-between"
+ >
+ <span className="text-ellipsis truncate">
+ {currentInvestigation?.name || 'Select an investigation'}
+ </span>
+ <ChevronDown className="w-4 h-4 shrink-0" />
+ </Button>
+ </div>
+ </PopoverTrigger>
+ <PopoverContent className="w-64 p-0" align="start">
+ <div className="p-2 border-b">
+ <div className="relative">
+ <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder="Search investigations..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-8 h-8 text-sm"
+ />
+ </div>
+ </div>
- <div className="max-h-48 overflow-y-auto">
- {filteredInvestigations.map((investigation: Investigation) => (
- <Button
- key={investigation.id}
- variant="ghost"
- size="sm"
- className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-sm"
- onClick={() => handleSelectionChange(investigation.id)}
- >
- <FolderOpen className="w-4 h-4 text-blue-500 shrink-0" />
- <span className="text-left truncate">{investigation.name}</span>
- </Button>
- ))}
- </div>
- <Separator className="my-0.5" />
- <div className="py-0.5">
- <NewInvestigation noDropDown={true}>
- <Button
- variant="ghost"
- size="sm"
- className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-muted-foreground hover:text-foreground text-sm"
- >
- <Plus className="w-4 h-4" />
- <span className="text-left truncate">Create new investigation</span>
- </Button>
- </NewInvestigation>
- </div>
- </PopoverContent>
- </Popover>}
- </div>
- );
+ <div className="max-h-48 overflow-y-auto">
+ {filteredInvestigations.map((investigation: Investigation) => (
+ <Button
+ key={investigation.id}
+ variant="ghost"
+ size="sm"
+ className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-sm"
+ onClick={() => handleSelectionChange(investigation.id)}
+ >
+ <FolderOpen className="w-4 h-4 text-blue-500 shrink-0" />
+ <span className="text-left truncate">{investigation.name}</span>
+ </Button>
+ ))}
+ </div>
+ <Separator className="my-0.5" />
+ <div className="py-0.5">
+ <NewInvestigation noDropDown={true}>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-muted-foreground hover:text-foreground text-sm"
+ >
+ <Plus className="w-4 h-4" />
+ <span className="text-left truncate">Create new investigation</span>
+ </Button>
+ </NewInvestigation>
+ </div>
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/layout/log-panel.tsx b/flowsint-app/src/renderer/src/components/layout/log-panel.tsx
index 6f5d56d3..433fa388 100644
--- a/flowsint-app/src/renderer/src/components/layout/log-panel.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/log-panel.tsx
@@ -1,212 +1,219 @@
-
-import { Badge } from "../ui/badge"
-import { logService } from "@/api/log-service"
-import { useConfirm } from "../use-confirm-dialog"
-import { useParams } from "@tanstack/react-router"
+import { Badge } from '../ui/badge'
+import { logService } from '@/api/log-service'
+import { useConfirm } from '../use-confirm-dialog'
+import { useParams } from '@tanstack/react-router'
import {
- Info,
- AlertTriangle,
- AlertCircle,
- CheckCircle,
- Zap,
- Clock,
- RotateCcw,
- PartyPopper,
- BarChart3,
- FileText,
- Trash2,
-} from "lucide-react"
-import { useEffect, useRef, memo } from "react"
-import { CopyButton } from "../copy"
-import { EventLevel } from "@/types"
-import { cn } from "@/lib/utils"
-import { Button } from "../ui/button"
-import { useEvents } from "@/hooks/use-events"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { queryKeys } from "@/api/query-keys"
+ Info,
+ AlertTriangle,
+ AlertCircle,
+ CheckCircle,
+ Zap,
+ Clock,
+ RotateCcw,
+ PartyPopper,
+ BarChart3,
+ FileText,
+ Trash2
+} from 'lucide-react'
+import { useEffect, useRef, memo } from 'react'
+import { CopyButton } from '../copy'
+import { EventLevel } from '@/types'
+import { cn } from '@/lib/utils'
+import { Button } from '../ui/button'
+import { useEvents } from '@/hooks/use-events'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { queryKeys } from '@/api/query-keys'
const logLevelConfig = {
- [EventLevel.INFO]: {
- icon: Info,
- color: "dark:text-blue-400 text-blue-600",
- bg: "bg-blue-500/10",
- badge: "dark:bg-blue-500/20 dark:text-blue-300 bg-blue-500/20 text-blue-600",
- emoji: "ℹ️",
- },
- [EventLevel.WARNING]: {
- icon: AlertTriangle,
- color: "dark:text-yellow-400 text-yellow-600",
- bg: "bg-yellow-500/10",
- badge: "dark:bg-yellow-500/20 dark:text-yellow-300 bg-yellow-500/20 text-yellow-600",
- emoji: "⚠️",
- },
- [EventLevel.FAILED]: {
- icon: AlertCircle,
- color: "dark:text-red-400 text-red-600",
- bg: "bg-red-500/10",
- badge: "dark:bg-red-500/20 dark:text-red-300 bg-red-500/20 text-red-600",
- emoji: "❌",
- },
- [EventLevel.SUCCESS]: {
- icon: CheckCircle,
- color: "dark:text-green-400 text-green-600",
- bg: "bg-green-500/10",
- badge: "dark:bg-green-500/20 dark:text-green-300 bg-green-500/20 text-green-600",
- emoji: "✅",
- },
- [EventLevel.DEBUG]: {
- icon: Zap,
- color: "dark:text-purple-400 text-purple-600",
- bg: "bg-purple-500/10",
- badge: "dark:bg-purple-500/20 dark:text-purple-300 bg-purple-500/20 text-purple-600",
- emoji: "🐛",
- },
- [EventLevel.PENDING]: {
- icon: Clock,
- color: "dark:text-orange-400 text-orange-600",
- bg: "bg-orange-500/10",
- badge: "dark:bg-orange-500/20 dark:text-orange-300 bg-orange-500/20 text-orange-600",
- emoji: "⏳",
- },
- [EventLevel.RUNNING]: {
- icon: RotateCcw,
- color: "dark:text-blue-400 text-blue-600",
- bg: "bg-blue-500/10",
- badge: "dark:bg-blue-500/20 dark:text-blue-300 bg-blue-500/20 text-blue-600",
- emoji: "🔄",
- },
- [EventLevel.COMPLETED]: {
- icon: PartyPopper,
- color: "dark:text-green-400 text-green-600",
- bg: "bg-green-500/10",
- badge: "dark:bg-green-500/20 dark:text-green-300 bg-green-500/20 text-green-600",
- emoji: "🎉",
- },
- [EventLevel.GRAPH_APPEND]: {
- icon: BarChart3,
- color: "dark:text-purple-400 text-purple-600",
- bg: "bg-purple-500/10",
- badge: "dark:bg-purple-500/20 dark:text-purple-300 bg-purple-500/20 text-purple-600",
- emoji: "📊",
- }
+ [EventLevel.INFO]: {
+ icon: Info,
+ color: 'dark:text-blue-400 text-blue-600',
+ bg: 'bg-blue-500/10',
+ badge: 'dark:bg-blue-500/20 dark:text-blue-300 bg-blue-500/20 text-blue-600',
+ emoji: 'ℹ️'
+ },
+ [EventLevel.WARNING]: {
+ icon: AlertTriangle,
+ color: 'dark:text-yellow-400 text-yellow-600',
+ bg: 'bg-yellow-500/10',
+ badge: 'dark:bg-yellow-500/20 dark:text-yellow-300 bg-yellow-500/20 text-yellow-600',
+ emoji: '⚠️'
+ },
+ [EventLevel.FAILED]: {
+ icon: AlertCircle,
+ color: 'dark:text-red-400 text-red-600',
+ bg: 'bg-red-500/10',
+ badge: 'dark:bg-red-500/20 dark:text-red-300 bg-red-500/20 text-red-600',
+ emoji: '❌'
+ },
+ [EventLevel.SUCCESS]: {
+ icon: CheckCircle,
+ color: 'dark:text-green-400 text-green-600',
+ bg: 'bg-green-500/10',
+ badge: 'dark:bg-green-500/20 dark:text-green-300 bg-green-500/20 text-green-600',
+ emoji: '✅'
+ },
+ [EventLevel.DEBUG]: {
+ icon: Zap,
+ color: 'dark:text-purple-400 text-purple-600',
+ bg: 'bg-purple-500/10',
+ badge: 'dark:bg-purple-500/20 dark:text-purple-300 bg-purple-500/20 text-purple-600',
+ emoji: '🐛'
+ },
+ [EventLevel.PENDING]: {
+ icon: Clock,
+ color: 'dark:text-orange-400 text-orange-600',
+ bg: 'bg-orange-500/10',
+ badge: 'dark:bg-orange-500/20 dark:text-orange-300 bg-orange-500/20 text-orange-600',
+ emoji: '⏳'
+ },
+ [EventLevel.RUNNING]: {
+ icon: RotateCcw,
+ color: 'dark:text-blue-400 text-blue-600',
+ bg: 'bg-blue-500/10',
+ badge: 'dark:bg-blue-500/20 dark:text-blue-300 bg-blue-500/20 text-blue-600',
+ emoji: '🔄'
+ },
+ [EventLevel.COMPLETED]: {
+ icon: PartyPopper,
+ color: 'dark:text-green-400 text-green-600',
+ bg: 'bg-green-500/10',
+ badge: 'dark:bg-green-500/20 dark:text-green-300 bg-green-500/20 text-green-600',
+ emoji: '🎉'
+ },
+ [EventLevel.GRAPH_APPEND]: {
+ icon: BarChart3,
+ color: 'dark:text-purple-400 text-purple-600',
+ bg: 'bg-purple-500/10',
+ badge: 'dark:bg-purple-500/20 dark:text-purple-300 bg-purple-500/20 text-purple-600',
+ emoji: '📊'
+ }
}
// Fallback config for any missing event levels
const defaultConfig = {
- icon: FileText,
- color: "text-gray-400",
- bg: "bg-gray-500/10",
- badge: "bg-gray-500/20 text-gray-300",
- emoji: "📝",
+ icon: FileText,
+ color: 'text-gray-400',
+ bg: 'bg-gray-500/10',
+ badge: 'bg-gray-500/20 text-gray-300',
+ emoji: '📝'
}
export const LogPanel = memo(() => {
- const { id: sketch_id } = useParams({ strict: false })
- const { confirm } = useConfirm()
- const bottomRef = useRef<HTMLDivElement | null>(null)
- const scrollAreaRef = useRef<HTMLDivElement>(null)
- const { logs, refetch } = useEvents(sketch_id as string)
- const queryClient = useQueryClient()
-
- // Delete logs mutation
- const deleteLogsMutation = useMutation({
- mutationFn: logService.delete,
- onSuccess: () => {
- // Invalidate logs for this sketch
- if (sketch_id) {
- queryClient.invalidateQueries({
- queryKey: queryKeys.logs.bySketch(sketch_id)
- })
- }
- refetch()
- },
- onError: (error) => {
- console.error("Error deleting logs:", error)
- }
- })
-
- useEffect(() => {
- if (bottomRef.current) {
- bottomRef.current.scrollIntoView({ behavior: "smooth" })
- }
- }, [logs])
+ const { id: sketch_id } = useParams({ strict: false })
+ const { confirm } = useConfirm()
+ const bottomRef = useRef<HTMLDivElement | null>(null)
+ const scrollAreaRef = useRef<HTMLDivElement>(null)
+ const { logs, refetch } = useEvents(sketch_id as string)
+ const queryClient = useQueryClient()
- const handleDeleteLogs = async () => {
- if (!sketch_id) return
- if (
- !(await confirm({
- title: "Delete all logs",
- message: "Are you sure you want to delete all logs?",
- }))
- )
- return
- await deleteLogsMutation.mutateAsync(sketch_id)
+ // Delete logs mutation
+ const deleteLogsMutation = useMutation({
+ mutationFn: logService.delete,
+ onSuccess: () => {
+ // Invalidate logs for this sketch
+ if (sketch_id) {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.logs.bySketch(sketch_id)
+ })
+ }
+ refetch()
+ },
+ onError: (error) => {
+ console.error('Error deleting logs:', error)
}
+ })
- const formatTime = (date: string) => {
- return new Date(date).toLocaleTimeString("en-US", {
- hour12: false,
- hour: "2-digit",
- minute: "2-digit",
- second: "2-digit",
- })
+ useEffect(() => {
+ if (bottomRef.current) {
+ bottomRef.current.scrollIntoView({ behavior: 'smooth' })
}
+ }, [logs])
+
+ const handleDeleteLogs = async () => {
+ if (!sketch_id) return
+ if (
+ !(await confirm({
+ title: 'Delete all logs',
+ message: 'Are you sure you want to delete all logs?'
+ }))
+ )
+ return
+ await deleteLogsMutation.mutateAsync(sketch_id)
+ }
+
+ const formatTime = (date: string) => {
+ return new Date(date).toLocaleTimeString('en-US', {
+ hour12: false,
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit'
+ })
+ }
- return (
- <div className="h-full bg-card overflow-hidden flex flex-col relative">
- <div className={cn("flex-1 h-full", logs.length === 0 ? "overflow-hidden" : "overflow-y-auto")} ref={scrollAreaRef} >
- <div className="text-sm h-full">
- {logs.length === 0 ? (
- <div className="text-center text-muted-foreground h-full py-8 flex !overflow-hidden flex-col items-center justify-center">
- {/* <div className="flex items-center gap-2 mb-4">
+ return (
+ <div className="h-full bg-card overflow-hidden flex flex-col relative">
+ <div
+ className={cn('flex-1 h-full', logs.length === 0 ? 'overflow-hidden' : 'overflow-y-auto')}
+ ref={scrollAreaRef}
+ >
+ <div className="text-sm h-full">
+ {logs.length === 0 ? (
+ <div className="text-center text-muted-foreground h-full py-8 flex !overflow-hidden flex-col items-center justify-center">
+ {/* <div className="flex items-center gap-2 mb-4">
<div className="w-2 h-2 bg-blue-400 rounded-full animate-pulse" style={{ animationDelay: '0ms' }} />
<div className="w-2 h-2 bg-green-400 rounded-full animate-pulse" style={{ animationDelay: '200ms' }} />
<div className="w-2 h-2 bg-yellow-400 rounded-full animate-pulse" style={{ animationDelay: '400ms' }} />
</div> */}
- <p className="text-lg font-medium mb-2 flex items-center gap-2"><Zap className="w-4 h-4 text-primary animate-pulse" /> Waiting for investigation activity</p>
- <p className="text-sm opacity-70">Events will appear here as they happen</p>
- </div>
- ) : (
-
- logs.map((log, i) => {
- const config = logLevelConfig[log.type] || defaultConfig
- const Icon = config.icon
-
- return (
- <div
- key={i}
- className={cn(
- "group flex items-start gap-3 p-2 py-1 transition-colors hover:bg-card/50",
- // config.bg,
- )}
- >
- <div className="flex items-center gap-2 min-w-0">
- <Icon className={cn("w-4 h-4 mt-0.5 flex-shrink-0", config.color)} />
- <span className="text-xs font-medium min-w-[60px]">{formatTime(log.created_at)}</span>
- <Badge className={cn("text-[.6rem] px-2 py-0.5", config.badge)}>{log.type}</Badge>
+ <p className="text-lg font-medium mb-2 flex items-center gap-2">
+ <Zap className="w-4 h-4 text-primary animate-pulse" /> Waiting for investigation
+ activity
+ </p>
+ <p className="text-sm opacity-70">Events will appear here as they happen</p>
+ </div>
+ ) : (
+ logs.map((log, i) => {
+ const config = logLevelConfig[log.type] || defaultConfig
+ const Icon = config.icon
- </div>
- <div className="min-w-0 flex-1">
- <p className="break-words">{log.payload.message}</p>
- </div>
- <CopyButton
- content={`[${formatTime(log.created_at)}] ${log.type}: ${log.payload.message}`}
- className="opacity-0 group-hover:opacity-100 transition-opacity p-1 h-auto"
- />
- </div>
- )
- })
- )}
- <div ref={bottomRef} />
+ return (
+ <div
+ key={i}
+ className={cn(
+ 'group flex items-start gap-3 p-2 py-1 transition-colors hover:bg-card/50'
+ // config.bg,
+ )}
+ >
+ <div className="flex items-center gap-2 min-w-0">
+ <Icon className={cn('w-4 h-4 mt-0.5 flex-shrink-0', config.color)} />
+ <span className="text-xs font-medium min-w-[60px]">
+ {formatTime(log.created_at)}
+ </span>
+ <Badge className={cn('text-[.6rem] px-2 py-0.5', config.badge)}>
+ {log.type}
+ </Badge>
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="break-words">{log.payload.message}</p>
+ </div>
+ <CopyButton
+ content={`[${formatTime(log.created_at)}] ${log.type}: ${log.payload.message}`}
+ className="opacity-0 group-hover:opacity-100 transition-opacity p-1 h-auto"
+ />
</div>
- </div>
- <div className="absolute top-1 right-1">
- <Button variant="ghost" size="icon" onClick={refetch}>
- <RotateCcw strokeWidth={1.5} className="w-4 h-4 opacity-60" />
- </Button>
- <Button variant="ghost" size="icon" onClick={handleDeleteLogs}>
- <Trash2 strokeWidth={1.5} className="w-4 h-4 opacity-60" />
- </Button>
- </div>
+ )
+ })
+ )}
+ <div ref={bottomRef} />
</div>
- )
+ </div>
+ <div className="absolute top-1 right-1">
+ <Button variant="ghost" size="icon" onClick={refetch}>
+ <RotateCcw strokeWidth={1.5} className="w-4 h-4 opacity-60" />
+ </Button>
+ <Button variant="ghost" size="icon" onClick={handleDeleteLogs}>
+ <Trash2 strokeWidth={1.5} className="w-4 h-4 opacity-60" />
+ </Button>
+ </div>
+ </div>
+ )
})
diff --git a/flowsint-app/src/renderer/src/components/layout/root.layout.tsx b/flowsint-app/src/renderer/src/components/layout/root.layout.tsx
index 75ce0b94..68fcc6dd 100644
--- a/flowsint-app/src/renderer/src/components/layout/root.layout.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/root.layout.tsx
@@ -1,190 +1,202 @@
-import { type ReactNode, useMemo } from "react"
-import { Sidebar } from "./sidebar"
-import { TopNavbar } from "./top-navbar"
-import { StatusBar } from "./status-bar"
-import SecondaryNavigation from "./secondary-navigation"
-import { ConfirmContextProvider } from "@/components/use-confirm-dialog"
-import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "../ui/resizable"
-import { LogPanel } from "./log-panel"
-import { useLayoutStore } from "@/stores/layout-store"
-import NotesPanel from "../analyses/notes-panel"
-import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"
-import { useParams } from "@tanstack/react-router"
-import DetailsPanel from "../graphs/details-panel/details-panel"
-import { useGraphStore } from "@/stores/graph-store"
+import { type ReactNode, useMemo } from 'react'
+import { Sidebar } from './sidebar'
+import { TopNavbar } from './top-navbar'
+import { StatusBar } from './status-bar'
+import SecondaryNavigation from './secondary-navigation'
+import { ConfirmContextProvider } from '@/components/use-confirm-dialog'
+import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '../ui/resizable'
+import { LogPanel } from './log-panel'
+import { useLayoutStore } from '@/stores/layout-store'
+import NotesPanel from '../analyses/notes-panel'
+import { useKeyboardShortcut } from '@/hooks/use-keyboard-shortcut'
+import { useParams } from '@tanstack/react-router'
+import DetailsPanel from '../graphs/details-panel/details-panel'
+import { useGraphStore } from '@/stores/graph-store'
interface LayoutProps {
- children: ReactNode
+ children: ReactNode
}
export default function RootLayout({ children }: LayoutProps) {
- const isOpenConsole = useLayoutStore(s => s.isOpenConsole)
- const toggleConsole = useLayoutStore(s => s.toggleConsole)
- const isOpenPanel = useLayoutStore(s => s.isOpenPanel)
- const isOpenAnalysis = useLayoutStore(s => s.isOpenAnalysis)
- const isOpenDetails = useLayoutStore(s => s.isOpenDetails)
- const toggleAnalysis = useLayoutStore(s => s.toggleAnalysis)
- const togglePanel = useLayoutStore(s => s.togglePanel)
- const closePanel = useLayoutStore(s => s.closePanel)
- const openPanel = useLayoutStore(s => s.openPanel)
- const closeDetails = useLayoutStore(s => s.closeDetails)
- const currentNode = useGraphStore((s) => s.currentNode)
- const { id, type } = useParams({ strict: false })
+ const isOpenConsole = useLayoutStore((s) => s.isOpenConsole)
+ const toggleConsole = useLayoutStore((s) => s.toggleConsole)
+ const isOpenPanel = useLayoutStore((s) => s.isOpenPanel)
+ const isOpenAnalysis = useLayoutStore((s) => s.isOpenAnalysis)
+ const isOpenDetails = useLayoutStore((s) => s.isOpenDetails)
+ const toggleAnalysis = useLayoutStore((s) => s.toggleAnalysis)
+ const togglePanel = useLayoutStore((s) => s.togglePanel)
+ const closePanel = useLayoutStore((s) => s.closePanel)
+ const openPanel = useLayoutStore((s) => s.openPanel)
+ const closeDetails = useLayoutStore((s) => s.closeDetails)
+ const currentNode = useGraphStore((s) => s.currentNode)
+ const { id, type } = useParams({ strict: false })
- // Set up keyboard shortcut for chat panel
- useKeyboardShortcut({
- key: "l",
- ctrlOrCmd: true,
- callback: toggleAnalysis
- })
- useKeyboardShortcut({
- key: "b",
- ctrlOrCmd: true,
- callback: togglePanel
- })
- useKeyboardShortcut({
- key: "d",
- ctrlOrCmd: true,
- callback: toggleConsole
- })
+ // Set up keyboard shortcut for chat panel
+ useKeyboardShortcut({
+ key: 'l',
+ ctrlOrCmd: true,
+ callback: toggleAnalysis
+ })
+ useKeyboardShortcut({
+ key: 'b',
+ ctrlOrCmd: true,
+ callback: togglePanel
+ })
+ useKeyboardShortcut({
+ key: 'd',
+ ctrlOrCmd: true,
+ callback: toggleConsole
+ })
- // Memoize the details panel section to prevent unnecessary re-renders
- const detailsPanelSection = useMemo(() => {
- if (!id || type != "graph") return null;
+ // Memoize the details panel section to prevent unnecessary re-renders
+ const detailsPanelSection = useMemo(() => {
+ if (!id || type != 'graph') return null
- // Priority 1: NotesPanel if isOpenAnalysis is true
- if (isOpenAnalysis) {
- return (
- <>
- <ResizableHandle withHandle />
- <ResizablePanel
- id="details-panel"
- order={4}
- defaultSize={20}
- minSize={16}
- maxSize={40}
- onCollapse={closeDetails}
- onExpand={() => { }} // No auto-open here
- collapsible={true}
- collapsedSize={2}
- >
- <NotesPanel />
- </ResizablePanel>
- </>
- );
- }
+ // Priority 1: NotesPanel if isOpenAnalysis is true
+ if (isOpenAnalysis) {
+ return (
+ <>
+ <ResizableHandle withHandle />
+ <ResizablePanel
+ id="details-panel"
+ order={4}
+ defaultSize={20}
+ minSize={16}
+ maxSize={40}
+ onCollapse={closeDetails}
+ onExpand={() => {}} // No auto-open here
+ collapsible={true}
+ collapsedSize={2}
+ >
+ <NotesPanel />
+ </ResizablePanel>
+ </>
+ )
+ }
- // Priority 2: DetailsPanel when currentNode exists (auto-opens via useEffect)
- if (currentNode) {
- return (
- <>
- <ResizableHandle withHandle />
- <ResizablePanel
- id="details-panel"
- order={4}
- defaultSize={20}
- minSize={16}
- maxSize={40}
- onCollapse={closeDetails}
- onExpand={() => { }} // No auto-open here
- collapsible={true}
- collapsedSize={2}
- >
- <DetailsPanel node={currentNode} />
- </ResizablePanel>
- </>
- );
- }
+ // Priority 2: DetailsPanel when currentNode exists (auto-opens via useEffect)
+ if (currentNode) {
+ return (
+ <>
+ <ResizableHandle withHandle />
+ <ResizablePanel
+ id="details-panel"
+ order={4}
+ defaultSize={20}
+ minSize={16}
+ maxSize={40}
+ onCollapse={closeDetails}
+ onExpand={() => {}} // No auto-open here
+ collapsible={true}
+ collapsedSize={2}
+ >
+ <DetailsPanel node={currentNode} />
+ </ResizablePanel>
+ </>
+ )
+ }
- // No panel should be shown
- return null;
- }, [id, currentNode?.id, currentNode?.data, isOpenAnalysis, closeDetails]);
+ // No panel should be shown
+ return null
+ }, [id, currentNode?.id, currentNode?.data, isOpenAnalysis, closeDetails])
- // Memoize the entire layout content to prevent unnecessary re-renders
- const layoutContent = useMemo(() => (
- <div className="flex flex-col h-screen w-screen overflow-hidden">
- {/* Top navbar */}
- <TopNavbar />
- {/* Main layout */}
- <div className="flex grow">
- <Sidebar />
- <ResizablePanelGroup autoSaveId="conditional" direction="vertical" className="flex-1 min-h-0">
- {/* Main content area with optional console */}
- <ResizablePanel order={1} id="main" defaultSize={isOpenConsole ? 70 : 100} minSize={30}>
- <ResizablePanelGroup
- autoSaveId="conditional2"
- direction="vertical"
- className="h-full"
+ // Memoize the entire layout content to prevent unnecessary re-renders
+ const layoutContent = useMemo(
+ () => (
+ <div className="flex flex-col h-screen w-screen overflow-hidden">
+ {/* Top navbar */}
+ <TopNavbar />
+ {/* Main layout */}
+ <div className="flex grow">
+ <Sidebar />
+ <ResizablePanelGroup
+ autoSaveId="conditional"
+ direction="vertical"
+ className="flex-1 min-h-0"
+ >
+ {/* Main content area with optional console */}
+ <ResizablePanel order={1} id="main" defaultSize={isOpenConsole ? 70 : 100} minSize={30}>
+ <ResizablePanelGroup
+ autoSaveId="conditional2"
+ direction="vertical"
+ className="h-full"
+ >
+ {/* Main content */}
+ <ResizablePanel id="content" order={1} defaultSize={100} minSize={30}>
+ <ResizablePanelGroup
+ direction="horizontal"
+ autoSaveId="conditional3"
+ className="h-full"
+ >
+ {isOpenPanel && (
+ <>
+ <ResizablePanel
+ id="sidebar"
+ className="min-w-64"
+ order={2}
+ defaultSize={20}
+ minSize={16}
+ maxSize={30}
+ onCollapse={closePanel}
+ onExpand={openPanel}
+ collapsible={true}
+ collapsedSize={0}
>
- {/* Main content */}
- <ResizablePanel id="content" order={1} defaultSize={100} minSize={30}>
- <ResizablePanelGroup
- direction="horizontal"
- autoSaveId="conditional3"
- className="h-full"
- >
-
- {isOpenPanel && (
- <>
- <ResizablePanel
- id="sidebar"
- className="min-w-64"
- order={2}
- defaultSize={20}
- minSize={16}
- maxSize={30}
- onCollapse={closePanel}
- onExpand={openPanel}
- collapsible={true}
- collapsedSize={0}
- >
- <div className="h-full flex flex-col overflow-hidden bg-card">
- <SecondaryNavigation />
- </div>
- </ResizablePanel>
- <ResizableHandle />
- </>
- )}
- <ResizablePanel className="h-full w-full" id="children" order={3}>
- {children}
- </ResizablePanel>
- {detailsPanelSection}
- </ResizablePanelGroup>
- </ResizablePanel>
+ <div className="h-full flex flex-col overflow-hidden bg-card">
+ <SecondaryNavigation />
+ </div>
+ </ResizablePanel>
+ <ResizableHandle />
+ </>
+ )}
+ <ResizablePanel className="h-full w-full" id="children" order={3}>
+ {children}
+ </ResizablePanel>
+ {detailsPanelSection}
+ </ResizablePanelGroup>
+ </ResizablePanel>
- {/* Status bar */}
- <div className="h-8 shrink-0">
- <StatusBar />
- </div>
+ {/* Status bar */}
+ <div className="h-8 shrink-0">
+ <StatusBar />
+ </div>
- {/* Console panel - only shown when isOpen is true */}
- {isOpenConsole && id && (
- <>
- <ResizableHandle />
- <ResizablePanel
- id="console"
- order={5}
- defaultSize={30}
- minSize={10}
- maxSize={50}
- >
- <div className="h-full overflow-hidden">
- <LogPanel />
- </div>
- </ResizablePanel>
- </>
- )}
- </ResizablePanelGroup>
+ {/* Console panel - only shown when isOpen is true */}
+ {isOpenConsole && id && (
+ <>
+ <ResizableHandle />
+ <ResizablePanel
+ id="console"
+ order={5}
+ defaultSize={30}
+ minSize={10}
+ maxSize={50}
+ >
+ <div className="h-full overflow-hidden">
+ <LogPanel />
+ </div>
</ResizablePanel>
- </ResizablePanelGroup>
- </div>
+ </>
+ )}
+ </ResizablePanelGroup>
+ </ResizablePanel>
+ </ResizablePanelGroup>
</div>
- ), [isOpenConsole, isOpenPanel, isOpenAnalysis, isOpenDetails, id, children, detailsPanelSection, closePanel, openPanel, closeDetails]);
+ </div>
+ ),
+ [
+ isOpenConsole,
+ isOpenPanel,
+ isOpenAnalysis,
+ isOpenDetails,
+ id,
+ children,
+ detailsPanelSection,
+ closePanel,
+ openPanel,
+ closeDetails
+ ]
+ )
- return (
- <ConfirmContextProvider>
- {layoutContent}
- </ConfirmContextProvider>
- )
+ return <ConfirmContextProvider>{layoutContent}</ConfirmContextProvider>
}
-
diff --git a/flowsint-app/src/renderer/src/components/layout/secondary-navigation.tsx b/flowsint-app/src/renderer/src/components/layout/secondary-navigation.tsx
index 76789e63..31c442f3 100644
--- a/flowsint-app/src/renderer/src/components/layout/secondary-navigation.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/secondary-navigation.tsx
@@ -1,56 +1,53 @@
-import { useLocation, useParams } from "@tanstack/react-router"
-import InvestigationList from "../investigations/investigation-list"
-import GraphNavigation from "../graphs/graph-navigation"
-import TransformNavigation from "../flows/flow-navigation"
-import SketchList from "../investigations/sketch-list"
-import AnalysesList from "../analyses/analyses-list"
-import { memo } from "react"
+import { useLocation, useParams } from '@tanstack/react-router'
+import InvestigationList from '../investigations/investigation-list'
+import GraphNavigation from '../graphs/graph-navigation'
+import TransformNavigation from '../flows/flow-navigation'
+import SketchList from '../investigations/sketch-list'
+import AnalysesList from '../analyses/analyses-list'
+import { memo } from 'react'
const SecondaryNavigation = memo(() => {
+ const { id, investigationId, type } = useParams({ strict: false })
+ const { pathname } = useLocation()
- const { id, investigationId, type } = useParams({ strict: false })
- const { pathname } = useLocation()
-
- if (!investigationId && !id && !pathname.startsWith("/dashboard/flows")) {
- return (
- <div className="grow w-full overflow-x-hidden">
- <InvestigationList />
- </div>
- )
- }
- if (investigationId && !id) {
- return (
- <div className="grow w-full overflow-x-hidden">
- <SketchList />
- </div>
- )
- }
-
- if (investigationId && id && type === "graph") {
- return (
- <div className="grow w-full overflow-x-hidden">
- <GraphNavigation />
- </div>
- )
- }
- if (investigationId && id && type === "analysis") {
- return (
- <div className="grow w-full overflow-x-hidden">
- <AnalysesList />
- </div>
- )
- }
+ if (!investigationId && !id && !pathname.startsWith('/dashboard/flows')) {
+ return (
+ <div className="grow w-full overflow-x-hidden">
+ <InvestigationList />
+ </div>
+ )
+ }
+ if (investigationId && !id) {
+ return (
+ <div className="grow w-full overflow-x-hidden">
+ <SketchList />
+ </div>
+ )
+ }
+ if (investigationId && id && type === 'graph') {
+ return (
+ <div className="grow w-full overflow-x-hidden">
+ <GraphNavigation />
+ </div>
+ )
+ }
+ if (investigationId && id && type === 'analysis') {
+ return (
+ <div className="grow w-full overflow-x-hidden">
+ <AnalysesList />
+ </div>
+ )
+ }
- if (pathname.startsWith("/dashboard/flows")) {
- return (
- <div className="grow w-full h-full overflow-x-hidden">
- <TransformNavigation />
- </div>)
- }
+ if (pathname.startsWith('/dashboard/flows')) {
return (
- <div>secondary-navigation</div>
+ <div className="grow w-full h-full overflow-x-hidden">
+ <TransformNavigation />
+ </div>
)
+ }
+ return <div>secondary-navigation</div>
})
-export default SecondaryNavigation
\ No newline at end of file
+export default SecondaryNavigation
diff --git a/flowsint-app/src/renderer/src/components/layout/sidebar.tsx b/flowsint-app/src/renderer/src/components/layout/sidebar.tsx
index 1b76ab71..f4acaef0 100644
--- a/flowsint-app/src/renderer/src/components/layout/sidebar.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/sidebar.tsx
@@ -1,103 +1,83 @@
-import {
- Home,
- Lock,
- type LucideIcon,
- PanelLeft,
- Workflow
-} from "lucide-react"
-import { Link } from "@tanstack/react-router"
-import { useLayoutStore } from "@/stores/layout-store"
-import { Button } from "../ui/button"
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "../ui/tooltip"
-import { memo } from "react"
-import { isMac } from "@/lib/utils"
-import { NavUser } from "../nav-user"
+import { Home, Lock, type LucideIcon, PanelLeft, Workflow } from 'lucide-react'
+import { Link } from '@tanstack/react-router'
+import { useLayoutStore } from '@/stores/layout-store'
+import { Button } from '../ui/button'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip'
+import { memo } from 'react'
+import { isMac } from '@/lib/utils'
+import { NavUser } from '../nav-user'
interface NavItem {
- icon: LucideIcon
- label: string
- href?: string
+ icon: LucideIcon
+ label: string
+ href?: string
}
export const Sidebar = memo(() => {
- const togglePanel = useLayoutStore(s => s.togglePanel)
+ const togglePanel = useLayoutStore((s) => s.togglePanel)
- const navItems: NavItem[] = [
- { icon: Home, label: "Dashboard", href: "/dashboard/" },
- { icon: Workflow, label: "Flows", href: "/dashboard/flows" },
- { icon: Lock, label: "Vault", href: "/dashboard/vault" },
+ const navItems: NavItem[] = [
+ { icon: Home, label: 'Dashboard', href: '/dashboard/' },
+ { icon: Workflow, label: 'Flows', href: '/dashboard/flows' },
+ { icon: Lock, label: 'Vault', href: '/dashboard/vault' }
+ ]
- ]
+ const commonClasses = 'flex items-center justify-center h-12 w-full rounded-sm hover:bg-muted'
- const commonClasses =
- "flex items-center justify-center h-12 w-full rounded-sm hover:bg-muted"
-
- return (
- <div className="w-14 border-r h-full flex flex-col shrink-0 bg-card">
- <div className="flex flex-col items-center gap-1 p-2">
- {navItems.map((item, index) => {
- const IconComponent = item.icon
- const content = (
- <IconComponent key={index} strokeWidth={1.2} className="h-4 w-4 opacity-70" />
- )
- return item.href ? (
- <TooltipProvider key={index}>
- <Tooltip>
- <TooltipTrigger asChild>
- <Link
- to={item.href}
- className={commonClasses}
- activeProps={{ className: `${commonClasses}` }}
- >
- {content}
- </Link>
- </TooltipTrigger>
- <TooltipContent side="right">
- {item.label}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- ) : (
- <TooltipProvider key={index}>
- <Tooltip>
- <TooltipTrigger asChild>
- <button className={commonClasses}>
- {content}
- </button>
- </TooltipTrigger>
- <TooltipContent side="right">
- {item.label}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )
- })}
- </div>
- <div className="grow"></div>
- <div className="flex flex-col justify-center items-center p-3 gap-4">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Button variant={"ghost"} onClick={togglePanel}>
- <PanelLeft
- className={`h-12 w-12 transition-transform duration-200`}
- />
- </Button>
- </div>
- </TooltipTrigger>
- <TooltipContent side="right">
- Toggle panel<span className="text-[.7rem] ml-1 opacity-60">({isMac ? '⌘' : 'ctrl'}B)</span>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <NavUser />
- </div>
- </div>
- )
+ return (
+ <div className="w-14 border-r h-full flex flex-col shrink-0 bg-card">
+ <div className="flex flex-col items-center gap-1 p-2">
+ {navItems.map((item, index) => {
+ const IconComponent = item.icon
+ const content = (
+ <IconComponent key={index} strokeWidth={1.2} className="h-4 w-4 opacity-70" />
+ )
+ return item.href ? (
+ <TooltipProvider key={index}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Link
+ to={item.href}
+ className={commonClasses}
+ activeProps={{ className: `${commonClasses}` }}
+ >
+ {content}
+ </Link>
+ </TooltipTrigger>
+ <TooltipContent side="right">{item.label}</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ ) : (
+ <TooltipProvider key={index}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button className={commonClasses}>{content}</button>
+ </TooltipTrigger>
+ <TooltipContent side="right">{item.label}</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )
+ })}
+ </div>
+ <div className="grow"></div>
+ <div className="flex flex-col justify-center items-center p-3 gap-4">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button variant={'ghost'} onClick={togglePanel}>
+ <PanelLeft className={`h-12 w-12 transition-transform duration-200`} />
+ </Button>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="right">
+ Toggle panel
+ <span className="text-[.7rem] ml-1 opacity-60">({isMac ? '⌘' : 'ctrl'}B)</span>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ <NavUser />
+ </div>
+ </div>
+ )
})
diff --git a/flowsint-app/src/renderer/src/components/layout/sketch-selector.tsx b/flowsint-app/src/renderer/src/components/layout/sketch-selector.tsx
index a320e194..934bb534 100644
--- a/flowsint-app/src/renderer/src/components/layout/sketch-selector.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/sketch-selector.tsx
@@ -1,177 +1,184 @@
-import { useState } from "react"
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Skeleton } from "@/components/ui/skeleton";
-import { Separator } from "@/components/ui/separator";
-import { useQuery } from "@tanstack/react-query";
-import { type Sketch } from "@/types/sketch";
-import { type Analysis } from "@/types";
-import { useNavigate, useParams } from "@tanstack/react-router";
-import { investigationService } from "@/api/investigation-service";
-import { analysisService } from "@/api/analysis-service";
-import { Waypoints, FileText, Search, ChevronDown, Plus, ArrowLeft, Home } from "lucide-react";
-import NewSketch from "@/components/graphs/new-sketch";
-import { queryKeys } from "@/api/query-keys";
+import { useState } from 'react'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Separator } from '@/components/ui/separator'
+import { useQuery } from '@tanstack/react-query'
+import { type Sketch } from '@/types/sketch'
+import { type Analysis } from '@/types'
+import { useNavigate, useParams } from '@tanstack/react-router'
+import { investigationService } from '@/api/investigation-service'
+import { analysisService } from '@/api/analysis-service'
+import { Waypoints, FileText, Search, ChevronDown, Plus, ArrowLeft, Home } from 'lucide-react'
+import NewSketch from '@/components/graphs/new-sketch'
+import { queryKeys } from '@/api/query-keys'
export default function CaseSelector() {
- const navigate = useNavigate()
- const { id, investigationId, type } = useParams({ strict: false })
- const [open, setOpen] = useState(false)
- const [searchQuery, setSearchQuery] = useState("")
+ const navigate = useNavigate()
+ const { id, investigationId, type } = useParams({ strict: false })
+ const [open, setOpen] = useState(false)
+ const [searchQuery, setSearchQuery] = useState('')
- const { data: investigation, isLoading: isLoadingInvestigation } = useQuery({
- queryKey: queryKeys.sketches.dashboard(investigationId as string),
- queryFn: () => investigationService.getById(investigationId as string),
- refetchOnWindowFocus: true,
- })
+ const { data: investigation, isLoading: isLoadingInvestigation } = useQuery({
+ queryKey: queryKeys.sketches.dashboard(investigationId as string),
+ queryFn: () => investigationService.getById(investigationId as string),
+ refetchOnWindowFocus: true
+ })
- const { data: analyses, isLoading: isLoadingAnalyses } = useQuery({
- queryKey: queryKeys.analyses.dashboard(investigationId as string),
- queryFn: () => analysisService.getByInvestigationId(investigationId as string),
- enabled: !!investigationId,
- refetchOnWindowFocus: true,
- })
+ const { data: analyses, isLoading: isLoadingAnalyses } = useQuery({
+ queryKey: queryKeys.analyses.dashboard(investigationId as string),
+ queryFn: () => analysisService.getByInvestigationId(investigationId as string),
+ enabled: !!investigationId,
+ refetchOnWindowFocus: true
+ })
- const isLoading = isLoadingInvestigation || isLoadingAnalyses
+ const isLoading = isLoadingInvestigation || isLoadingAnalyses
- const handleSelectionChange = (value: string) => {
- if (value === "overview") {
- navigate({
- to: "/dashboard/investigations/$investigationId",
- params: {
- investigationId: investigationId as string,
- },
- })
- } else {
- // Check if the selected value is a sketch or analysis
- const isSketch = investigation?.sketches?.some((sketch: Sketch) => sketch.id === value)
- const isAnalysis = analyses?.some((analysis: Analysis) => analysis.id === value)
+ const handleSelectionChange = (value: string) => {
+ if (value === 'overview') {
+ navigate({
+ to: '/dashboard/investigations/$investigationId',
+ params: {
+ investigationId: investigationId as string
+ }
+ })
+ } else {
+ // Check if the selected value is a sketch or analysis
+ const isSketch = investigation?.sketches?.some((sketch: Sketch) => sketch.id === value)
+ const isAnalysis = analyses?.some((analysis: Analysis) => analysis.id === value)
- const itemType = isSketch ? "graph" : isAnalysis ? "analysis" : type
+ const itemType = isSketch ? 'graph' : isAnalysis ? 'analysis' : type
- navigate({
- to: "/dashboard/investigations/$investigationId/$type/$id",
- params: {
- investigationId: investigationId as string,
- type: itemType as string,
- id: value as string,
- },
- })
+ navigate({
+ to: '/dashboard/investigations/$investigationId/$type/$id',
+ params: {
+ investigationId: investigationId as string,
+ type: itemType as string,
+ id: value as string
}
- setOpen(false)
- };
+ })
+ }
+ setOpen(false)
+ }
- // Filter items based on search
- const filteredSketches = investigation?.sketches?.filter((sketch: Sketch) =>
+ // Filter items based on search
+ const filteredSketches =
+ investigation?.sketches?.filter(
+ (sketch: Sketch) =>
!searchQuery || sketch.title.toLowerCase().includes(searchQuery.toLowerCase())
) || []
- const filteredAnalyses = analyses?.filter((analysis: Analysis) =>
+ const filteredAnalyses =
+ analyses?.filter(
+ (analysis: Analysis) =>
!searchQuery || analysis.title.toLowerCase().includes(searchQuery.toLowerCase())
) || []
- return (
- <div className="flex items-center">
- {isLoading ? <Skeleton className="!h-7 w-40 bg-foreground/10" /> :
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <div>
- <Button
- variant="ghost"
- className="min-w-none !h-7 rounded-sm w-full !bg-transparent hover:bg-foreground/10 font-medium shadow-none border-none text-ellipsis truncate gap-1 inset-shadow-none justify-between"
- >
- <span className="text-ellipsis truncate">
- {id === "overview" || !id ? "Overview" :
- investigation?.sketches?.find((s: Sketch) => s.id === id)?.title ||
- analyses?.find((a: Analysis) => a.id === id)?.title ||
- "Overview"}
- </span>
- <ChevronDown className="w-4 h-4 shrink-0" />
- </Button>
- </div>
- </PopoverTrigger>
- <PopoverContent className="w-64 p-0" align="start">
- <div className="p-2 border-b">
- <div className="relative">
- <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="Search sketches and analyses..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-8 h-8 text-sm"
- />
- </div>
- </div>
+ return (
+ <div className="flex items-center">
+ {isLoading ? (
+ <Skeleton className="!h-7 w-40 bg-foreground/10" />
+ ) : (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <div>
+ <Button
+ variant="ghost"
+ className="min-w-none !h-7 rounded-sm w-full !bg-transparent hover:bg-foreground/10 font-medium shadow-none border-none text-ellipsis truncate gap-1 inset-shadow-none justify-between"
+ >
+ <span className="text-ellipsis truncate">
+ {id === 'overview' || !id
+ ? 'Overview'
+ : investigation?.sketches?.find((s: Sketch) => s.id === id)?.title ||
+ analyses?.find((a: Analysis) => a.id === id)?.title ||
+ 'Overview'}
+ </span>
+ <ChevronDown className="w-4 h-4 shrink-0" />
+ </Button>
+ </div>
+ </PopoverTrigger>
+ <PopoverContent className="w-64 p-0" align="start">
+ <div className="p-2 border-b">
+ <div className="relative">
+ <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder="Search sketches and analyses..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-8 h-8 text-sm"
+ />
+ </div>
+ </div>
- <div className="max-h-48 overflow-y-auto">
- {/* Overview Section */}
- <div className="py-0.5">
- <Button
- variant="ghost"
- size="sm"
- className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-sm"
- onClick={() => handleSelectionChange("overview")}
- >
- <span className="text-left truncate flex items-center gap-1 text-muted-foreground"><Home strokeWidth={1.5} /><ArrowLeft strokeWidth={1.5} /> back to case</span>
- </Button>
- </div>
+ <div className="max-h-48 overflow-y-auto">
+ {/* Overview Section */}
+ <div className="py-0.5">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-sm"
+ onClick={() => handleSelectionChange('overview')}
+ >
+ <span className="text-left truncate flex items-center gap-1 text-muted-foreground">
+ <Home strokeWidth={1.5} />
+ <ArrowLeft strokeWidth={1.5} /> back to case
+ </span>
+ </Button>
+ </div>
- {/* Sketches Section */}
- {filteredSketches.length > 0 && (
- <div className="py-0.5">
- {filteredSketches.map((sketch: Sketch) => (
- <Button
- key={sketch.id}
- variant="ghost"
- size="sm"
- className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-sm"
- onClick={() => handleSelectionChange(sketch.id)}
- >
- <Waypoints className="w-4 h-4 text-yellow-500 shrink-0" />
- <span className="text-left truncate">{sketch.title}</span>
- </Button>
- ))}
- </div>
- )}
+ {/* Sketches Section */}
+ {filteredSketches.length > 0 && (
+ <div className="py-0.5">
+ {filteredSketches.map((sketch: Sketch) => (
+ <Button
+ key={sketch.id}
+ variant="ghost"
+ size="sm"
+ className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-sm"
+ onClick={() => handleSelectionChange(sketch.id)}
+ >
+ <Waypoints className="w-4 h-4 text-yellow-500 shrink-0" />
+ <span className="text-left truncate">{sketch.title}</span>
+ </Button>
+ ))}
+ </div>
+ )}
- {/* Analyses Section */}
- {filteredAnalyses.length > 0 && (
- <div className="py-0.5">
- {filteredAnalyses.map((analysis: Analysis) => (
- <Button
- key={analysis.id}
- variant="ghost"
- size="sm"
- className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-sm"
- onClick={() => handleSelectionChange(analysis.id)}
- >
- <FileText className="w-4 h-4 text-blue-500 shrink-0" />
- <span className="text-left truncate">{analysis.title}</span>
- </Button>
- ))}
- </div>
- )}
- </div>
- <Separator className="my-0.5" />
- <div className="py-0.5">
- <NewSketch>
- <Button
- variant="ghost"
- size="sm"
- className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-muted-foreground hover:text-foreground text-sm"
- >
- <Plus className="w-4 h-4" />
- <span className="text-left truncate">Create new sketch</span>
- </Button>
- </NewSketch>
- </div>
- </PopoverContent>
- </Popover>}
- </div>
- );
+ {/* Analyses Section */}
+ {filteredAnalyses.length > 0 && (
+ <div className="py-0.5">
+ {filteredAnalyses.map((analysis: Analysis) => (
+ <Button
+ key={analysis.id}
+ variant="ghost"
+ size="sm"
+ className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-sm"
+ onClick={() => handleSelectionChange(analysis.id)}
+ >
+ <FileText className="w-4 h-4 text-blue-500 shrink-0" />
+ <span className="text-left truncate">{analysis.title}</span>
+ </Button>
+ ))}
+ </div>
+ )}
+ </div>
+ <Separator className="my-0.5" />
+ <div className="py-0.5">
+ <NewSketch>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="w-full justify-start gap-2 h-auto py-1.5 px-2 rounded-none hover:bg-accent text-muted-foreground hover:text-foreground text-sm"
+ >
+ <Plus className="w-4 h-4" />
+ <span className="text-left truncate">Create new sketch</span>
+ </Button>
+ </NewSketch>
+ </div>
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/layout/status-bar.tsx b/flowsint-app/src/renderer/src/components/layout/status-bar.tsx
index d8c5324c..712746a2 100644
--- a/flowsint-app/src/renderer/src/components/layout/status-bar.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/status-bar.tsx
@@ -1,48 +1,52 @@
-import { Button } from "@/components/ui/button"
-import { Terminal, Unlock } from "lucide-react"
-import { ModeToggle } from "../mode-toggle"
-import { useLayoutStore } from "@/stores/layout-store"
-import Legend from "../graphs/legend"
-import { Link, useParams } from "@tanstack/react-router"
-import InfoDialog from "./info"
-import { memo } from "react"
-import { isMac } from "@/lib/utils"
+import { Button } from '@/components/ui/button'
+import { Terminal, Unlock } from 'lucide-react'
+import { ModeToggle } from '../mode-toggle'
+import { useLayoutStore } from '@/stores/layout-store'
+import Legend from '../graphs/legend'
+import { Link, useParams } from '@tanstack/react-router'
+import InfoDialog from './info'
+import { memo } from 'react'
+import { isMac } from '@/lib/utils'
export const StatusBar = memo(() => {
- const { id: sketch_id } = useParams({ strict: false })
- const isOpenConsole = useLayoutStore(s => s.isOpenConsole)
- const toggleConsole = useLayoutStore(s => s.toggleConsole)
+ const { id: sketch_id } = useParams({ strict: false })
+ const isOpenConsole = useLayoutStore((s) => s.isOpenConsole)
+ const toggleConsole = useLayoutStore((s) => s.toggleConsole)
- return (
- <div className="flex items-center bg-card h-8 border-t px-2 text-xs text-muted-foreground">
- <div className="flex items-center gap-2">
- {sketch_id &&
- <Button
- variant="ghost"
- size="sm"
- className="h-6 gap-1 text-xs hover:bg-accent"
- onClick={toggleConsole}
- >
- <Terminal strokeWidth={1.4} className="h-3 w-3" />
- <span>Console {isOpenConsole ? '(Open)' : ''} <span className="text-[.7rem] opacity-60">({isMac ? '⌘' : 'ctrl'}D)</span></span>
- </Button>}
- </div>
- <div className="flex-1"></div>
- <div className="flex items-center gap-2">
- <Link to="/dashboard/vault">
- <Button variant="ghost" size="sm" className="h-6 gap-1 text-xs">
- <Unlock strokeWidth={1.4} className="h-3 w-3 opacity-60" />
- <span>Vault</span>
- </Button>
- </Link>
- {/* <Button variant="ghost" size="sm" className="h-6 gap-1 text-xs">
+ return (
+ <div className="flex items-center bg-card h-8 border-t px-2 text-xs text-muted-foreground">
+ <div className="flex items-center gap-2">
+ {sketch_id && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 gap-1 text-xs hover:bg-accent"
+ onClick={toggleConsole}
+ >
+ <Terminal strokeWidth={1.4} className="h-3 w-3" />
+ <span>
+ Console {isOpenConsole ? '(Open)' : ''}{' '}
+ <span className="text-[.7rem] opacity-60">({isMac ? '⌘' : 'ctrl'}D)</span>
+ </span>
+ </Button>
+ )}
+ </div>
+ <div className="flex-1"></div>
+ <div className="flex items-center gap-2">
+ <Link to="/dashboard/vault">
+ <Button variant="ghost" size="sm" className="h-6 gap-1 text-xs">
+ <Unlock strokeWidth={1.4} className="h-3 w-3 opacity-60" />
+ <span>Vault</span>
+ </Button>
+ </Link>
+ {/* <Button variant="ghost" size="sm" className="h-6 gap-1 text-xs">
<Trash strokeWidth={1.4} className="h-3 w-3 opacity-60" />
<span>Trash</span>
</Button> */}
- <Legend />
- <InfoDialog />
- <ModeToggle />
- </div>
- </div >
- )
+ <Legend />
+ <InfoDialog />
+ <ModeToggle />
+ </div>
+ </div>
+ )
})
diff --git a/flowsint-app/src/renderer/src/components/layout/top-navbar.tsx b/flowsint-app/src/renderer/src/components/layout/top-navbar.tsx
index 4594acb1..8a8ae55c 100644
--- a/flowsint-app/src/renderer/src/components/layout/top-navbar.tsx
+++ b/flowsint-app/src/renderer/src/components/layout/top-navbar.tsx
@@ -1,122 +1,135 @@
-import { Command } from "../command"
-import { Link, useParams } from "@tanstack/react-router"
-import InvestigationSelector from "./investigation-selector"
-import SketchSelector from "./sketch-selector"
-import { useEffect, useState, memo, useCallback } from "react"
-import { Switch } from "../ui/switch"
-import { Label } from "../ui/label"
-import { useLayoutStore } from "@/stores/layout-store"
-import { Button } from "@/components/ui/button"
+import { Command } from '../command'
+import { Link, useParams } from '@tanstack/react-router'
+import InvestigationSelector from './investigation-selector'
+import SketchSelector from './sketch-selector'
+import { useEffect, useState, memo, useCallback } from 'react'
+import { Switch } from '../ui/switch'
+import { Label } from '../ui/label'
+import { useLayoutStore } from '@/stores/layout-store'
+import { Button } from '@/components/ui/button'
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuGroup,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuShortcut,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import { Ellipsis } from "lucide-react"
-import { isMac } from "@/lib/utils"
-import { useGraphSettingsStore } from "@/stores/graph-settings-store"
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { Ellipsis } from 'lucide-react'
+import { isMac } from '@/lib/utils'
+import { useGraphSettingsStore } from '@/stores/graph-settings-store'
export const TopNavbar = memo(() => {
- const { investigationId, id, type } = useParams({ strict: false })
- const [isFullscreen, setIsFullscreen] = useState(false)
- const toggleAnalysis = useLayoutStore(s => s.toggleAnalysis)
- const isOpenAnalysis = useLayoutStore(s => s.isOpenAnalysis)
+ const { investigationId, id, type } = useParams({ strict: false })
+ const [isFullscreen, setIsFullscreen] = useState(false)
+ const toggleAnalysis = useLayoutStore((s) => s.toggleAnalysis)
+ const isOpenAnalysis = useLayoutStore((s) => s.isOpenAnalysis)
- const handleToggleAnalysis = useCallback(() => toggleAnalysis(), [toggleAnalysis])
+ const handleToggleAnalysis = useCallback(() => toggleAnalysis(), [toggleAnalysis])
- useEffect(() => {
- const checkWindowState = async () => {
- try {
- const windowState = await window.api.getWindowState()
- setIsFullscreen(windowState?.isFullscreen)
- } catch (error) {
- setIsFullscreen(true)
- }
- }
- checkWindowState()
- const handleResize = () => {
- setTimeout(checkWindowState, 100)
- }
- window.addEventListener('resize', handleResize)
- return () => {
- window.removeEventListener('resize', handleResize)
- }
- }, [])
+ useEffect(() => {
+ const checkWindowState = async () => {
+ try {
+ const windowState = await window.api.getWindowState()
+ setIsFullscreen(windowState?.isFullscreen)
+ } catch (error) {
+ setIsFullscreen(true)
+ }
+ }
+ checkWindowState()
+ const handleResize = () => {
+ setTimeout(checkWindowState, 100)
+ }
+ window.addEventListener('resize', handleResize)
+ return () => {
+ window.removeEventListener('resize', handleResize)
+ }
+ }, [])
-
- return (
- <header className={`flex items-center bg-card h-12 border-b shrink-0 ${isFullscreen ? 'px-4' : 'pl-20 pr-4'} -webkit-app-region-drag`}>
- <div className="flex items-center gap-4 -webkit-app-region-no-drag">
- <Link to="/dashboard" className="flex items-center gap-2">
- <img src="/icon.png" alt="Flowsint" className="h-8 w-8" />
- <span className="text-lg font-semibold">Flowsint</span>
- </Link>
- <div className="hidden lg:flex items-center gap-2">
- {investigationId &&
- <InvestigationSelector />}
- {id && <>
- <span className="opacity-30 text-sm">/</span><SketchSelector />
- </>}
- </div>
- </div>
- <div className="grow flex items-center justify-center">
- <div className="-webkit-app-region-no-drag"><Command /></div>
- </div>
- <div className="flex items-center gap-4 -webkit-app-region-no-drag">
- <div className="flex items-center space-x-2">
- {type === "graph" &&
- <>
- <Switch checked={isOpenAnalysis} onCheckedChange={handleToggleAnalysis} id="notes" />
- <Label htmlFor="notes">Toggle notes<span className="text-[.7rem] -ml-1 opacity-60">({isMac ? '⌘' : 'ctrl'}L)</span></Label>
- </>
- }
- </div>
- {id && <InvestigationMenu />}
- {/* <NavUser /> */}
- </div>
- </header>
- )
+ return (
+ <header
+ className={`flex items-center bg-card h-12 border-b shrink-0 ${isFullscreen ? 'px-4' : 'pl-20 pr-4'} -webkit-app-region-drag`}
+ >
+ <div className="flex items-center gap-4 -webkit-app-region-no-drag">
+ <Link to="/dashboard" className="flex items-center gap-2">
+ <img src="/icon.png" alt="Flowsint" className="h-8 w-8" />
+ <span className="text-lg font-semibold">Flowsint</span>
+ </Link>
+ <div className="hidden lg:flex items-center gap-2">
+ {investigationId && <InvestigationSelector />}
+ {id && (
+ <>
+ <span className="opacity-30 text-sm">/</span>
+ <SketchSelector />
+ </>
+ )}
+ </div>
+ </div>
+ <div className="grow flex items-center justify-center">
+ <div className="-webkit-app-region-no-drag">
+ <Command />
+ </div>
+ </div>
+ <div className="flex items-center gap-4 -webkit-app-region-no-drag">
+ <div className="flex items-center space-x-2">
+ {type === 'graph' && (
+ <>
+ <Switch checked={isOpenAnalysis} onCheckedChange={handleToggleAnalysis} id="notes" />
+ <Label htmlFor="notes">
+ Toggle notes
+ <span className="text-[.7rem] -ml-1 opacity-60">({isMac ? '⌘' : 'ctrl'}L)</span>
+ </Label>
+ </>
+ )}
+ </div>
+ {id && <InvestigationMenu />}
+ {/* <NavUser /> */}
+ </div>
+ </header>
+ )
})
-
export function InvestigationMenu() {
- const setSettingsModalOpen = useGraphSettingsStore(s => s.setSettingsModalOpen)
- const setKeyboardShortcutsOpen = useGraphSettingsStore(s => s.setKeyboardShortcutsOpen)
+ const setSettingsModalOpen = useGraphSettingsStore((s) => s.setSettingsModalOpen)
+ const setKeyboardShortcutsOpen = useGraphSettingsStore((s) => s.setKeyboardShortcutsOpen)
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <div>
- <Button size="icon" variant="ghost"><Ellipsis /></Button>
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent className="w-56" align="start">
- <DropdownMenuLabel>Settings</DropdownMenuLabel>
- <DropdownMenuGroup>
- <DropdownMenuItem onClick={() => setSettingsModalOpen(true)}>
- General
- <DropdownMenuShortcut>⌘G</DropdownMenuShortcut>
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => setKeyboardShortcutsOpen(true)}>
- Keyboard shortcuts
- <DropdownMenuShortcut>⌘K</DropdownMenuShortcut>
- </DropdownMenuItem>
- </DropdownMenuGroup>
- <DropdownMenuSeparator />
- <DropdownMenuItem><a href="https://github.com/reconurge">GitHub</a></DropdownMenuItem>
- <DropdownMenuItem><a href="https://github.com/reconurge">Support</a></DropdownMenuItem>
- <DropdownMenuItem disabled>API</DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem variant="destructive">
- Delete
- <DropdownMenuShortcut>⇧⌘Q</DropdownMenuShortcut>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <div>
+ <Button size="icon" variant="ghost">
+ <Ellipsis />
+ </Button>
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56" align="start">
+ <DropdownMenuLabel>Settings</DropdownMenuLabel>
+ <DropdownMenuGroup>
+ <DropdownMenuItem onClick={() => setSettingsModalOpen(true)}>
+ General
+ <DropdownMenuShortcut>⌘G</DropdownMenuShortcut>
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setKeyboardShortcutsOpen(true)}>
+ Keyboard shortcuts
+ <DropdownMenuShortcut>⌘K</DropdownMenuShortcut>
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem>
+ <a href="https://github.com/reconurge">GitHub</a>
+ </DropdownMenuItem>
+ <DropdownMenuItem>
+ <a href="https://github.com/reconurge">Support</a>
+ </DropdownMenuItem>
+ <DropdownMenuItem disabled>API</DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive">
+ Delete
+ <DropdownMenuShortcut>⇧⌘Q</DropdownMenuShortcut>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/loader.tsx b/flowsint-app/src/renderer/src/components/loader.tsx
index 45b36c21..143039d3 100644
--- a/flowsint-app/src/renderer/src/components/loader.tsx
+++ b/flowsint-app/src/renderer/src/components/loader.tsx
@@ -1,21 +1,21 @@
-import { cn } from "@/lib/utils";
+import { cn } from '@/lib/utils'
-function Loader({ className, label }: { className?: string, label?: string }) {
- return (
- <div className="h-full w-full flex items-center justify-center gap-2">
- <div className={cn("relative w-7 h-7", className)}>
- <div className="absolute inset-0 rounded-full border-3 border-t-transparent border-l-transparent border-r-primary border-b-primary animate-spin" />
- <div
- className="absolute inset-1 rounded-full border-3 border-b-transparent border-r-transparent border-t-secondary border-t-secondary animate-spin"
- style={{ animationDirection: "reverse", animationDuration: "1s" }}
- />
- <div
- className="absolute inset-2 rounded-full border-3 border-t-transparent border-l-transparent border-r-cyan-500 border-b-cyan-500 animate-spin"
- style={{ animationDuration: "0.5s" }}
- />
- </div>
- {label && <p className="text-sm">{label}</p>}
- </div>
- )
+function Loader({ className, label }: { className?: string; label?: string }) {
+ return (
+ <div className="h-full w-full flex items-center justify-center gap-2">
+ <div className={cn('relative w-7 h-7', className)}>
+ <div className="absolute inset-0 rounded-full border-3 border-t-transparent border-l-transparent border-r-primary border-b-primary animate-spin" />
+ <div
+ className="absolute inset-1 rounded-full border-3 border-b-transparent border-r-transparent border-t-secondary border-t-secondary animate-spin"
+ style={{ animationDirection: 'reverse', animationDuration: '1s' }}
+ />
+ <div
+ className="absolute inset-2 rounded-full border-3 border-t-transparent border-l-transparent border-r-cyan-500 border-b-cyan-500 animate-spin"
+ style={{ animationDuration: '0.5s' }}
+ />
+ </div>
+ {label && <p className="text-sm">{label}</p>}
+ </div>
+ )
}
-export default Loader
\ No newline at end of file
+export default Loader
diff --git a/flowsint-app/src/renderer/src/components/map/map-panel.tsx b/flowsint-app/src/renderer/src/components/map/map-panel.tsx
index c24fc987..069d6854 100644
--- a/flowsint-app/src/renderer/src/components/map/map-panel.tsx
+++ b/flowsint-app/src/renderer/src/components/map/map-panel.tsx
@@ -2,16 +2,20 @@ import { useGraphStore } from '@/stores/graph-store'
import { MapFromAddress } from './map'
import { LocationPoint } from './map'
const MapPanel = () => {
- const nodes = useGraphStore(state => state.nodes)
- const locationNodes = nodes.filter(node => node.data.type === 'location' || node.data.latitude && node.data.longitude).map(node => ({
- lat: node.data.latitude || 0,
- lon: node.data.longitude || 0,
- address: node.data.address || '',
- label: node.data.label || ''
+ const nodes = useGraphStore((state) => state.nodes)
+ const locationNodes = nodes
+ .filter((node) => node.data.type === 'location' || (node.data.latitude && node.data.longitude))
+ .map((node) => ({
+ lat: node.data.latitude || 0,
+ lon: node.data.longitude || 0,
+ address: node.data.address || '',
+ label: node.data.label || ''
}))
- return (
- <div className='w-full grow h-full z-10'><MapFromAddress locations={locationNodes as LocationPoint[]} /></div>
- )
+ return (
+ <div className="w-full grow h-full z-10">
+ <MapFromAddress locations={locationNodes as LocationPoint[]} />
+ </div>
+ )
}
-export default MapPanel
\ No newline at end of file
+export default MapPanel
diff --git a/flowsint-app/src/renderer/src/components/map/map.tsx b/flowsint-app/src/renderer/src/components/map/map.tsx
index f8f06642..9bc0cac5 100644
--- a/flowsint-app/src/renderer/src/components/map/map.tsx
+++ b/flowsint-app/src/renderer/src/components/map/map.tsx
@@ -1,190 +1,203 @@
-import React from "react";
-import { useQuery } from "@tanstack/react-query";
-import L from "leaflet";
-import "leaflet/dist/leaflet.css";
-import { useTheme } from "../theme-provider";
-import { MapPin } from "lucide-react";
+import React from 'react'
+import { useQuery } from '@tanstack/react-query'
+import L from 'leaflet'
+import 'leaflet/dist/leaflet.css'
+import { useTheme } from '../theme-provider'
+import { MapPin } from 'lucide-react'
export type LocationPoint = {
- lat?: number;
- lon?: number;
- address?: string;
- label?: string;
-};
+ lat?: number
+ lon?: number
+ address?: string
+ label?: string
+}
type MapFromAddressProps = {
- locations: LocationPoint[];
- height?: string;
- zoom?: number;
- centerOnFirst?: boolean;
-};
+ locations: LocationPoint[]
+ height?: string
+ zoom?: number
+ centerOnFirst?: boolean
+}
export const MapFromAddress: React.FC<MapFromAddressProps> = ({
- locations,
- height = "400px",
- zoom = 15,
- centerOnFirst = true,
+ locations,
+ height = '400px',
+ zoom = 15,
+ centerOnFirst = true
}) => {
- // Get locations that need geocoding
- const locationsToGeocode = locations.filter(loc => loc.lat === undefined && loc.lon === undefined && loc.address);
- const { theme } = useTheme()
- // Single query for all geocoding
- const geocodeQuery = useQuery({
- queryKey: ["geocode", locationsToGeocode.map(loc => loc.address)],
- queryFn: async () => {
- const results: ({ lat: number; lon: number } | null)[] = [];
- for (const location of locationsToGeocode) {
- if (!location.address) continue;
-
- const res = await fetch(
- `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(location.address)}`
- );
- const json = await res.json();
- if (!json || json.length === 0) {
- results.push(null);
- } else {
- results.push({
- lat: parseFloat(json[0].lat),
- lon: parseFloat(json[0].lon),
- });
- }
- }
- return results;
- },
- enabled: locationsToGeocode.length > 0,
- });
-
- // Combine all locations with their coordinates
- const processedLocations = locations.map((location) => {
- // If location already has coordinates
- if (location.lat !== undefined && location.lon !== undefined) {
- return {
- ...location,
- coordinates: { lat: location.lat, lon: location.lon },
- isLoading: false,
- isError: false,
- };
+ // Get locations that need geocoding
+ const locationsToGeocode = locations.filter(
+ (loc) => loc.lat === undefined && loc.lon === undefined && loc.address
+ )
+ const { theme } = useTheme()
+ // Single query for all geocoding
+ const geocodeQuery = useQuery({
+ queryKey: ['geocode', locationsToGeocode.map((loc) => loc.address)],
+ queryFn: async () => {
+ const results: ({ lat: number; lon: number } | null)[] = []
+ for (const location of locationsToGeocode) {
+ if (!location.address) continue
+
+ const res = await fetch(
+ `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(location.address)}`
+ )
+ const json = await res.json()
+ if (!json || json.length === 0) {
+ results.push(null)
+ } else {
+ results.push({
+ lat: parseFloat(json[0].lat),
+ lon: parseFloat(json[0].lon)
+ })
}
-
- // If location needs geocoding
- const geocodeIndex = locationsToGeocode.findIndex(loc => loc.address === location.address);
- if (geocodeIndex !== -1 && geocodeQuery.data) {
- const geocoded = geocodeQuery.data[geocodeIndex];
- return {
- ...location,
- coordinates: geocoded,
- isLoading: geocodeQuery.isLoading,
- isError: geocodeQuery.isError,
- };
- }
-
- // Fallback for locations without address
- return {
- ...location,
- coordinates: null,
- isLoading: geocodeQuery.isLoading,
- isError: geocodeQuery.isError,
- };
- });
-
- // Get valid coordinates for map bounds
- const validCoordinates = processedLocations
- .filter(location => location.coordinates)
- .map(location => location.coordinates!);
-
- const mapId = `leaflet-map-${btoa(JSON.stringify(locations)).replace(/[^a-zA-Z0-9]/g, "")}`;
-
- React.useEffect(() => {
- if (validCoordinates.length === 0) return;
-
- const map = L.map(mapId);
-
- const source = theme === 'dark' ? 'alidade_smooth_dark' : 'alidade_smooth'
- L.tileLayer("https://tiles.stadiamaps.com/tiles/{source}/{z}/{x}/{y}.{ext}", {
- // attribution: '&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a> &copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
- ext: 'png',
- source: source
- }).addTo(map);
-
- // Add markers for each location
- const markers: L.Marker[] = [];
- processedLocations.forEach((location) => {
- if (!location.coordinates) return;
-
- const marker = L.marker([location.coordinates.lat, location.coordinates.lon]).addTo(map);
-
- // Create popup text
- const popupText = location.label ||
- location.address ||
- `${location.coordinates.lat.toFixed(6)}, ${location.coordinates.lon.toFixed(6)}`;
-
- marker.bindPopup(popupText);
- markers.push(marker);
- });
-
- // Set map view
- if (centerOnFirst && validCoordinates.length > 0) {
- // Center on first coordinate
- map.setView([validCoordinates[0].lat, validCoordinates[0].lon], zoom);
- } else if (validCoordinates.length > 1) {
- // Fit bounds to include all markers
- const group = new L.featureGroup(markers);
- map.fitBounds(group.getBounds().pad(0.1));
- } else if (validCoordinates.length === 1) {
- // Single point
- map.setView([validCoordinates[0].lat, validCoordinates[0].lon], zoom);
- }
-
- return () => {
- map.remove(); // cleanup
- };
- }, [validCoordinates, mapId, zoom, centerOnFirst, theme]);
-
- // Show loading if geocoding is in progress
- if (geocodeQuery.isLoading) {
- return (
- <div className="h-full w-full flex items-center justify-center">
- <div className="text-center space-y-3">
- <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
- <p className="text-muted-foreground">Loading map data...</p>
- </div>
- </div>
- );
+ }
+ return results
+ },
+ enabled: locationsToGeocode.length > 0
+ })
+
+ // Combine all locations with their coordinates
+ const processedLocations = locations.map((location) => {
+ // If location already has coordinates
+ if (location.lat !== undefined && location.lon !== undefined) {
+ return {
+ ...location,
+ coordinates: { lat: location.lat, lon: location.lon },
+ isLoading: false,
+ isError: false
+ }
}
- // Show error if geocoding failed
- if (geocodeQuery.isError) {
- return (
- <div className="h-full w-full flex items-center justify-center">
- <div className="text-center space-y-3">
- <div className="w-12 h-12 bg-destructive/10 rounded-full flex items-center justify-center mx-auto">
- <svg className="w-6 h-6 text-destructive" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
- </svg>
- </div>
- <div>
- <p className="font-medium text-foreground">Unable to load map</p>
- <p className="text-sm text-muted-foreground">Could not find some addresses.</p>
- </div>
- </div>
- </div>
- );
+ // If location needs geocoding
+ const geocodeIndex = locationsToGeocode.findIndex((loc) => loc.address === location.address)
+ if (geocodeIndex !== -1 && geocodeQuery.data) {
+ const geocoded = geocodeQuery.data[geocodeIndex]
+ return {
+ ...location,
+ coordinates: geocoded,
+ isLoading: geocodeQuery.isLoading,
+ isError: geocodeQuery.isError
+ }
}
- // Don't render if we don't have any valid coordinates
- if (validCoordinates.length === 0) {
- return (
- <div className="w-full pt-18 flex items-center justify-center h-full">
- <div className="text-center space-y-4">
- <MapPin className="mx-auto h-12 w-12 text-muted-foreground" />
- <div>
- <h3 className="text-lg font-semibold">No location to display</h3>
- <p className="text-muted-foreground">This sketch doesn't have any location yet.</p>
- </div>
- </div>
- </div>
- );
+ // Fallback for locations without address
+ return {
+ ...location,
+ coordinates: null,
+ isLoading: geocodeQuery.isLoading,
+ isError: geocodeQuery.isError
+ }
+ })
+
+ // Get valid coordinates for map bounds
+ const validCoordinates = processedLocations
+ .filter((location) => location.coordinates)
+ .map((location) => location.coordinates!)
+
+ const mapId = `leaflet-map-${btoa(JSON.stringify(locations)).replace(/[^a-zA-Z0-9]/g, '')}`
+
+ React.useEffect(() => {
+ if (validCoordinates.length === 0) return
+
+ const map = L.map(mapId)
+
+ const source = theme === 'dark' ? 'alidade_smooth_dark' : 'alidade_smooth'
+ L.tileLayer('https://tiles.stadiamaps.com/tiles/{source}/{z}/{x}/{y}.{ext}', {
+ // attribution: '&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a> &copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
+ ext: 'png',
+ source: source
+ }).addTo(map)
+
+ // Add markers for each location
+ const markers: L.Marker[] = []
+ processedLocations.forEach((location) => {
+ if (!location.coordinates) return
+
+ const marker = L.marker([location.coordinates.lat, location.coordinates.lon]).addTo(map)
+
+ // Create popup text
+ const popupText =
+ location.label ||
+ location.address ||
+ `${location.coordinates.lat.toFixed(6)}, ${location.coordinates.lon.toFixed(6)}`
+
+ marker.bindPopup(popupText)
+ markers.push(marker)
+ })
+
+ // Set map view
+ if (centerOnFirst && validCoordinates.length > 0) {
+ // Center on first coordinate
+ map.setView([validCoordinates[0].lat, validCoordinates[0].lon], zoom)
+ } else if (validCoordinates.length > 1) {
+ // Fit bounds to include all markers
+ const group = new L.featureGroup(markers)
+ map.fitBounds(group.getBounds().pad(0.1))
+ } else if (validCoordinates.length === 1) {
+ // Single point
+ map.setView([validCoordinates[0].lat, validCoordinates[0].lon], zoom)
}
- return <div id={mapId} style={{ minHeight: height, height: '100%', width: '100%' }} />;
-};
+ return () => {
+ map.remove() // cleanup
+ }
+ }, [validCoordinates, mapId, zoom, centerOnFirst, theme])
+
+ // Show loading if geocoding is in progress
+ if (geocodeQuery.isLoading) {
+ return (
+ <div className="h-full w-full flex items-center justify-center">
+ <div className="text-center space-y-3">
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
+ <p className="text-muted-foreground">Loading map data...</p>
+ </div>
+ </div>
+ )
+ }
+
+ // Show error if geocoding failed
+ if (geocodeQuery.isError) {
+ return (
+ <div className="h-full w-full flex items-center justify-center">
+ <div className="text-center space-y-3">
+ <div className="w-12 h-12 bg-destructive/10 rounded-full flex items-center justify-center mx-auto">
+ <svg
+ className="w-6 h-6 text-destructive"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"
+ />
+ </svg>
+ </div>
+ <div>
+ <p className="font-medium text-foreground">Unable to load map</p>
+ <p className="text-sm text-muted-foreground">Could not find some addresses.</p>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ // Don't render if we don't have any valid coordinates
+ if (validCoordinates.length === 0) {
+ return (
+ <div className="w-full pt-18 flex items-center justify-center h-full">
+ <div className="text-center space-y-4">
+ <MapPin className="mx-auto h-12 w-12 text-muted-foreground" />
+ <div>
+ <h3 className="text-lg font-semibold">No location to display</h3>
+ <p className="text-muted-foreground">This sketch doesn't have any location yet.</p>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ return <div id={mapId} style={{ minHeight: height, height: '100%', width: '100%' }} />
+}
diff --git a/flowsint-app/src/renderer/src/components/mode-toggle.tsx b/flowsint-app/src/renderer/src/components/mode-toggle.tsx
index 35b51027..8e2a2d87 100644
--- a/flowsint-app/src/renderer/src/components/mode-toggle.tsx
+++ b/flowsint-app/src/renderer/src/components/mode-toggle.tsx
@@ -1,39 +1,33 @@
-import { Moon, Sun } from "lucide-react"
+import { Moon, Sun } from 'lucide-react'
-import { Button } from "@/components/ui/button"
+import { Button } from '@/components/ui/button'
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import { useTheme } from "@/components/theme-provider"
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { useTheme } from '@/components/theme-provider'
export function ModeToggle() {
- const { setTheme } = useTheme()
+ const { setTheme } = useTheme()
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <div>
- <Button variant="ghost" className="h-6" size="icon">
- <Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0 opacity-60" />
- <Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100 opacity-60" />
- <span className="sr-only">Toggle theme</span>
- </Button>
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => setTheme("light")}>
- Light
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => setTheme("dark")}>
- Dark
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => setTheme("system")}>
- System
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- )
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <div>
+ <Button variant="ghost" className="h-6" size="icon">
+ <Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0 opacity-60" />
+ <Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100 opacity-60" />
+ <span className="sr-only">Toggle theme</span>
+ </Button>
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setTheme('light')}>Light</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setTheme('dark')}>Dark</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setTheme('system')}>System</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/nav-user.tsx b/flowsint-app/src/renderer/src/components/nav-user.tsx
index 56167d32..1f0f6198 100644
--- a/flowsint-app/src/renderer/src/components/nav-user.tsx
+++ b/flowsint-app/src/renderer/src/components/nav-user.tsx
@@ -1,38 +1,31 @@
-
-import {
- LogOut,
-} from "lucide-react"
+import { LogOut } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import { Button } from "./ui/button"
-import { ModeToggle } from "./mode-toggle"
-import { authService } from "@/api/auth-service"
-import { useCallback } from "react"
-import { useNavigate } from "@tanstack/react-router"
-import { Avatar, AvatarImage, AvatarFallback } from "./ui/avatar"
-
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { Button } from './ui/button'
+import { ModeToggle } from './mode-toggle'
+import { authService } from '@/api/auth-service'
+import { useCallback } from 'react'
+import { useNavigate } from '@tanstack/react-router'
+import { Avatar, AvatarImage, AvatarFallback } from './ui/avatar'
export function NavUser() {
const navigate = useNavigate()
const logout = useCallback(() => {
authService.logout()
- navigate({ to: "/login" })
+ navigate({ to: '/login' })
}, [])
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<div className="h-auto flex items-center justify-center">
- <Button
- size="lg"
- className="p-0 h-auto rounded-full cursor-pointer"
- >
+ <Button size="lg" className="p-0 h-auto rounded-full cursor-pointer">
<Avatar>
<AvatarImage src="https://cherry.img.pmdstatic.net/fit/https.3A.2F.2Fimg.2Egamesider.2Ecom.2Fs3.2Ffrgsg.2F1280.2Fthe-last-of-us.2Fdefault_2023-11-27_291826c8-5b2b-4928-a167-259dd0b18a7c.2Ejpeg/1200x675/quality/80/the-last-of-us-saison-2-mauvaise-nouvelle-pedro-pascal.jpg" />
<AvatarFallback>U</AvatarFallback>
@@ -51,8 +44,7 @@ export function NavUser() {
<AvatarImage src="https://cherry.img.pmdstatic.net/fit/https.3A.2F.2Fimg.2Egamesider.2Ecom.2Fs3.2Ffrgsg.2F1280.2Fthe-last-of-us.2Fdefault_2023-11-27_291826c8-5b2b-4928-a167-259dd0b18a7c.2Ejpeg/1200x675/quality/80/the-last-of-us-saison-2-mauvaise-nouvelle-pedro-pascal.jpg" />
<AvatarFallback>U</AvatarFallback>
</Avatar>
- <div className="grid flex-1 text-left text-sm leading-tight">
- </div>
+ <div className="grid flex-1 text-left text-sm leading-tight"></div>
</div>
</DropdownMenuLabel>
<DropdownMenuLabel className="text-xs font-light opacity-60">Preferences</DropdownMenuLabel>
diff --git a/flowsint-app/src/renderer/src/components/shared/error-state.tsx b/flowsint-app/src/renderer/src/components/shared/error-state.tsx
index 9d1f4642..399cc667 100644
--- a/flowsint-app/src/renderer/src/components/shared/error-state.tsx
+++ b/flowsint-app/src/renderer/src/components/shared/error-state.tsx
@@ -1,54 +1,54 @@
-import { AlertTriangle, RefreshCw } from "lucide-react"
-import { Button } from "../ui/button"
-import { cn } from "@/lib/utils"
+import { AlertTriangle, RefreshCw } from 'lucide-react'
+import { Button } from '../ui/button'
+import { cn } from '@/lib/utils'
type ErrorStateProps = {
- title?: string
- description?: string
- error?: unknown
- onRetry?: () => void
- className?: string
+ title?: string
+ description?: string
+ error?: unknown
+ onRetry?: () => void
+ className?: string
}
const getErrorMessage = (error: unknown) => {
- if (!error) return null
- if (error instanceof Error) return error.message
- if (typeof error === "string") return error
- try {
- return JSON.stringify(error)
- } catch {
- return String(error)
- }
+ if (!error) return null
+ if (error instanceof Error) return error.message
+ if (typeof error === 'string') return error
+ try {
+ return JSON.stringify(error)
+ } catch {
+ return String(error)
+ }
}
-export function ErrorState({ title = "Something went wrong", description = "Please try again.", error, onRetry, className }: ErrorStateProps) {
- const message = getErrorMessage(error)
- return (
- <div className={cn("w-full h-full bg-card flex items-center justify-center", className)}>
- <div className="p-6 flex flex-col items-center text-center gap-3 text-muted-foreground max-w-sm">
- <div className="w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center">
- <AlertTriangle className="h-6 w-6 text-destructive" />
- </div>
- <div className="space-y-1">
- <h3 className="text-sm font-semibold text-foreground">{title}</h3>
- {description && <p className="text-xs opacity-70">{description}</p>}
- </div>
- {onRetry && (
- <Button size="sm" variant="outline" onClick={onRetry}>
- <RefreshCw className="w-4 h-4 mr-2" />
- Retry
- </Button>
- )}
- {message && (
- <p className="text-[11px] leading-relaxed opacity-60 break-words">
- {message}
- </p>
- )}
- </div>
+export function ErrorState({
+ title = 'Something went wrong',
+ description = 'Please try again.',
+ error,
+ onRetry,
+ className
+}: ErrorStateProps) {
+ const message = getErrorMessage(error)
+ return (
+ <div className={cn('w-full h-full bg-card flex items-center justify-center', className)}>
+ <div className="p-6 flex flex-col items-center text-center gap-3 text-muted-foreground max-w-sm">
+ <div className="w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center">
+ <AlertTriangle className="h-6 w-6 text-destructive" />
</div>
- )
+ <div className="space-y-1">
+ <h3 className="text-sm font-semibold text-foreground">{title}</h3>
+ {description && <p className="text-xs opacity-70">{description}</p>}
+ </div>
+ {onRetry && (
+ <Button size="sm" variant="outline" onClick={onRetry}>
+ <RefreshCw className="w-4 h-4 mr-2" />
+ Retry
+ </Button>
+ )}
+ {message && <p className="text-[11px] leading-relaxed opacity-60 break-words">{message}</p>}
+ </div>
+ </div>
+ )
}
export default ErrorState
-
-
diff --git a/flowsint-app/src/renderer/src/components/shared/form-field.tsx b/flowsint-app/src/renderer/src/components/shared/form-field.tsx
index b9c005dd..08f0f1b5 100644
--- a/flowsint-app/src/renderer/src/components/shared/form-field.tsx
+++ b/flowsint-app/src/renderer/src/components/shared/form-field.tsx
@@ -1,16 +1,16 @@
// src/components/FormField.tsx
-import React, { type InputHTMLAttributes } from 'react';
-import { useFormContext, type RegisterOptions, type FieldError } from 'react-hook-form';
-import { Input } from '../ui/input';
+import React, { type InputHTMLAttributes } from 'react'
+import { useFormContext, type RegisterOptions, type FieldError } from 'react-hook-form'
+import { Input } from '../ui/input'
interface FormFieldProps extends InputHTMLAttributes<HTMLInputElement> {
- name: string;
- label: string;
- registerOptions?: RegisterOptions;
- error?: FieldError;
- type?: string;
- placeholder?: string;
- className?: string;
+ name: string
+ label: string
+ registerOptions?: RegisterOptions
+ error?: FieldError
+ type?: string
+ placeholder?: string
+ className?: string
}
const FormField: React.FC<FormFieldProps> = ({
@@ -24,11 +24,11 @@ const FormField: React.FC<FormFieldProps> = ({
...rest
}) => {
// Si utilisé dans un FormProvider, on peut récupérer le registre ici
- const formContext = useFormContext();
+ const formContext = useFormContext()
// Détermine si on utilise le contexte ou des props directes
- const register = formContext ? formContext.register : undefined;
- const fieldError = error || (formContext ? formContext.formState.errors[name] : undefined);
+ const register = formContext ? formContext.register : undefined
+ const fieldError = error || (formContext ? formContext.formState.errors[name] : undefined)
return (
<div className={`space-y-1 ${className}`}>
@@ -40,22 +40,19 @@ const FormField: React.FC<FormFieldProps> = ({
id={name}
type={type}
placeholder={placeholder}
- className={`mt-1 block w-full px-3 py-2 border ${fieldError ? 'border-red-300' : 'border-border'
- } rounded-md shadow-sm placeholder-gray-400 focus:outline-none sm:text-sm`}
+ className={`mt-1 block w-full px-3 py-2 border ${
+ fieldError ? 'border-red-300' : 'border-border'
+ } rounded-md shadow-sm placeholder-gray-400 focus:outline-none sm:text-sm`}
{...(register ? register(name, registerOptions) : {})}
{...rest}
/>
- {fieldError && (
- <p className="mt-1 text-sm text-red-600">
- {fieldError.message as string}
- </p>
- )}
+ {fieldError && <p className="mt-1 text-sm text-red-600">{fieldError.message as string}</p>}
</div>
- );
-};
+ )
+}
-export default FormField;
+export default FormField
// Exemple d'utilisation avec FormProvider:
/*
@@ -98,4 +95,4 @@ const MyForm = () => {
</form>
);
};
-*/
\ No newline at end of file
+*/
diff --git a/flowsint-app/src/renderer/src/components/shared/loader.tsx b/flowsint-app/src/renderer/src/components/shared/loader.tsx
index 08e91355..f89f7cfc 100644
--- a/flowsint-app/src/renderer/src/components/shared/loader.tsx
+++ b/flowsint-app/src/renderer/src/components/shared/loader.tsx
@@ -1,47 +1,47 @@
// src/components/LoadingSpinner.tsx
-import React from 'react';
+import React from 'react'
interface LoadingSpinnerProps {
- size?: 'sm' | 'md' | 'lg';
- color?: string;
- className?: string;
+ size?: 'sm' | 'md' | 'lg'
+ color?: string
+ className?: string
}
const LoadingSpinner: React.FC<LoadingSpinnerProps> = ({
- size = 'md',
- color = 'text-primary',
- className = '',
+ size = 'md',
+ color = 'text-primary',
+ className = ''
}) => {
- // Définir la taille du spinner
- const sizeClasses = {
- sm: 'h-4 w-4',
- md: 'h-5 w-5',
- lg: 'h-8 w-8',
- };
+ // Définir la taille du spinner
+ const sizeClasses = {
+ sm: 'h-4 w-4',
+ md: 'h-5 w-5',
+ lg: 'h-8 w-8'
+ }
- return (
- <svg
- className={`animate-spin ${sizeClasses[size]} ${color} ${className}`}
- xmlns="http://www.w3.org/2000/svg"
- fill="none"
- viewBox="0 0 24 24"
- aria-hidden="true"
- >
- <circle
- className="opacity-25"
- cx="12"
- cy="12"
- r="10"
- stroke="currentColor"
- strokeWidth="4"
- ></circle>
- <path
- className="opacity-75"
- fill="currentColor"
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
- ></path>
- </svg>
- );
-};
+ return (
+ <svg
+ className={`animate-spin ${sizeClasses[size]} ${color} ${className}`}
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ aria-hidden="true"
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ ></circle>
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
+ ></path>
+ </svg>
+ )
+}
-export default LoadingSpinner;
\ No newline at end of file
+export default LoadingSpinner
diff --git a/flowsint-app/src/renderer/src/components/shared/skeleton-list.tsx b/flowsint-app/src/renderer/src/components/shared/skeleton-list.tsx
index b8aced4f..303c2a30 100644
--- a/flowsint-app/src/renderer/src/components/shared/skeleton-list.tsx
+++ b/flowsint-app/src/renderer/src/components/shared/skeleton-list.tsx
@@ -1,50 +1,50 @@
-import { cn } from "@/lib/utils"
-import { Skeleton } from "../ui/skeleton"
-import { Card, CardContent, CardHeader } from "../ui/card"
+import { cn } from '@/lib/utils'
+import { Skeleton } from '../ui/skeleton'
+import { Card, CardContent, CardHeader } from '../ui/card'
interface SkeletonListProps {
- rowCount: number
- className?: string
- mode?: 'list' | 'card'
+ rowCount: number
+ className?: string
+ mode?: 'list' | 'card'
}
export function SkeletonList({ rowCount, className, mode = 'list' }: SkeletonListProps) {
- if (mode === 'card') {
- return (
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-6">
- {Array.from({ length: rowCount }).map((_, i) => (
- <Card key={i} className="group">
- <CardHeader className="pb-2">
- <div className="flex items-start justify-between">
- <Skeleton className="h-6 w-32" />
- <Skeleton className="h-4 w-4" />
- </div>
- <Skeleton className="h-4 w-full mt-2" />
- <Skeleton className="h-4 w-3/4 mt-1" />
- </CardHeader>
- <CardContent>
- <div className="flex items-center justify-between">
- <div className="flex items-center">
- <Skeleton className="h-4 w-4 mr-1" />
- <Skeleton className="h-4 w-24" />
- </div>
- {/* <div className="flex gap-2">
+ if (mode === 'card') {
+ return (
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-6">
+ {Array.from({ length: rowCount }).map((_, i) => (
+ <Card key={i} className="group">
+ <CardHeader className="pb-2">
+ <div className="flex items-start justify-between">
+ <Skeleton className="h-6 w-32" />
+ <Skeleton className="h-4 w-4" />
+ </div>
+ <Skeleton className="h-4 w-full mt-2" />
+ <Skeleton className="h-4 w-3/4 mt-1" />
+ </CardHeader>
+ <CardContent>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center">
+ <Skeleton className="h-4 w-4 mr-1" />
+ <Skeleton className="h-4 w-24" />
+ </div>
+ {/* <div className="flex gap-2">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-16" />
</div> */}
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
- )
- }
-
- return (
- <ul role="list" className="space-y-1">
- {Array.from({ length: rowCount }).map((_, i) => (
- <Skeleton key={i} className={cn("h-7 w-full rounded-none", className)} />
- ))}
- </ul>
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
)
+ }
+
+ return (
+ <ul role="list" className="space-y-1">
+ {Array.from({ length: rowCount }).map((_, i) => (
+ <Skeleton key={i} className={cn('h-7 w-full rounded-none', className)} />
+ ))}
+ </ul>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/tab.tsx b/flowsint-app/src/renderer/src/components/tab.tsx
index 4223cd3a..f8ce0af2 100644
--- a/flowsint-app/src/renderer/src/components/tab.tsx
+++ b/flowsint-app/src/renderer/src/components/tab.tsx
@@ -30,7 +30,9 @@ export const Tab = ({ item, onClick, onRemove, isSelected, showSeparator }: Prop
transition: { ease: 'easeInOut' }
}}
className={cn(
- isSelected ? 'selected bg-card text-white border-border border-b-transparent' : 'bg-background text-white border-transparent',
+ isSelected
+ ? 'selected bg-card text-white border-border border-b-transparent'
+ : 'bg-background text-white border-transparent',
'titlebar-button min-w-[120px] max-w-[200px]',
`h-8 pl-4 relative cursor-pointer flex justify-between items-center
flex-1 overflow-hidden select-none border border-transparent`
@@ -44,7 +46,7 @@ export const Tab = ({ item, onClick, onRemove, isSelected, showSeparator }: Prop
isSelected ? 'text-foreground' : 'text-white'
)}
layout="position"
- >{`${item.title || "Flowsint"} ${item.id}`}</motion.span>
+ >{`${item.title || 'Flowsint'} ${item.id}`}</motion.span>
<motion.div
layout
className="absolute top-0 bottom-0 right-[0px] flex align-center items-center justify-end
diff --git a/flowsint-app/src/renderer/src/components/table/columns.tsx b/flowsint-app/src/renderer/src/components/table/columns.tsx
index d01815f6..d681f52b 100644
--- a/flowsint-app/src/renderer/src/components/table/columns.tsx
+++ b/flowsint-app/src/renderer/src/components/table/columns.tsx
@@ -1,356 +1,393 @@
-import { ColumnDef } from "@tanstack/react-table"
-import { useIcon } from "@/hooks/use-icon"
-import { MoreVertical, AlertTriangle, CheckCircle, Clock, XCircle } from "lucide-react"
-import { Button } from "@/components/ui/button"
-import { ArrowUpDown } from "lucide-react"
-import { TypeBadge } from "@/components/type-badge"
+import { ColumnDef } from '@tanstack/react-table'
+import { useIcon } from '@/hooks/use-icon'
+import { MoreVertical, AlertTriangle, CheckCircle, Clock, XCircle } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import { ArrowUpDown } from 'lucide-react'
+import { TypeBadge } from '@/components/type-badge'
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu"
-import { Checkbox } from "../ui/checkbox"
-import { useCallback, memo } from "react"
-import { useGraphStore } from "@/stores/graph-store"
-import { GraphNode } from "@/types"
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger
+} from '@/components/ui/dropdown-menu'
+import { Checkbox } from '../ui/checkbox'
+import { useCallback, memo } from 'react'
+import { useGraphStore } from '@/stores/graph-store'
+import { GraphNode } from '@/types'
// Memoized icon component to prevent unnecessary re-renders
const MemoizedIcon = memo(({ type, size = 16 }: { type: string; size?: number }) => {
- const IconComponent = useIcon(type)
- return <IconComponent size={size} />
+ const IconComponent = useIcon(type)
+ return <IconComponent size={size} />
})
MemoizedIcon.displayName = 'MemoizedIcon'
// Helper function to get status styling
const getStatusStyle = (status: string) => {
- switch (status?.toLowerCase()) {
- case 'active':
- return { bg: 'bg-emerald-50 dark:bg-emerald-950/20', text: 'text-emerald-700 dark:text-emerald-200', border: 'border-emerald-500 dark:border-emerald-800', icon: CheckCircle }
- case 'pending':
- return { bg: 'bg-amber-50 dark:bg-amber-950/20', text: 'text-amber-700 dark:text-amber-200', border: 'border-amber-500 dark:border-amber-800', icon: Clock }
- case 'error':
- return { bg: 'bg-red-50 dark:bg-red-950/20', text: 'text-red-700 dark:text-red-200', border: 'border-red-500 dark:border-red-800', icon: XCircle }
- case 'warning':
- return { bg: 'bg-orange-50 dark:bg-orange-950/20', text: 'text-orange-700 dark:text-orange-200', border: 'border-orange-500 dark:border-orange-800', icon: AlertTriangle }
- default:
- return { bg: 'bg-gray-50 dark:bg-gray-900', text: 'text-gray-700 dark:text-gray-200', border: 'border-gray-500 dark:border-gray-700', icon: Clock }
- }
+ switch (status?.toLowerCase()) {
+ case 'active':
+ return {
+ bg: 'bg-emerald-50 dark:bg-emerald-950/20',
+ text: 'text-emerald-700 dark:text-emerald-200',
+ border: 'border-emerald-500 dark:border-emerald-800',
+ icon: CheckCircle
+ }
+ case 'pending':
+ return {
+ bg: 'bg-amber-50 dark:bg-amber-950/20',
+ text: 'text-amber-700 dark:text-amber-200',
+ border: 'border-amber-500 dark:border-amber-800',
+ icon: Clock
+ }
+ case 'error':
+ return {
+ bg: 'bg-red-50 dark:bg-red-950/20',
+ text: 'text-red-700 dark:text-red-200',
+ border: 'border-red-500 dark:border-red-800',
+ icon: XCircle
+ }
+ case 'warning':
+ return {
+ bg: 'bg-orange-50 dark:bg-orange-950/20',
+ text: 'text-orange-700 dark:text-orange-200',
+ border: 'border-orange-500 dark:border-orange-800',
+ icon: AlertTriangle
+ }
+ default:
+ return {
+ bg: 'bg-gray-50 dark:bg-gray-900',
+ text: 'text-gray-700 dark:text-gray-200',
+ border: 'border-gray-500 dark:border-gray-700',
+ icon: Clock
+ }
+ }
}
// Helper function to get risk level styling
const getRiskStyle = (risk: string) => {
- switch (risk?.toLowerCase()) {
- case 'critical':
- return { bg: 'bg-red-200 dark:bg-red-900/30', text: 'text-red-800 dark:text-red-500' }
- case 'high':
- return { bg: 'bg-orange-200 dark:bg-orange-900/30', text: 'text-orange-800 dark:text-orange-500' }
- case 'medium':
- return { bg: 'bg-amber-200 dark:bg-amber-900/30', text: 'text-amber-800 dark:text-amber-500' }
- case 'low':
- return { bg: 'bg-emerald-200 dark:bg-emerald-900/30', text: 'text-emerald-800 dark:text-emerald-500' }
- default:
- return { bg: 'bg-gray-200 dark:bg-gray-800', text: 'text-gray-800 dark:text-gray-500' }
- }
+ switch (risk?.toLowerCase()) {
+ case 'critical':
+ return { bg: 'bg-red-200 dark:bg-red-900/30', text: 'text-red-800 dark:text-red-500' }
+ case 'high':
+ return {
+ bg: 'bg-orange-200 dark:bg-orange-900/30',
+ text: 'text-orange-800 dark:text-orange-500'
+ }
+ case 'medium':
+ return { bg: 'bg-amber-200 dark:bg-amber-900/30', text: 'text-amber-800 dark:text-amber-500' }
+ case 'low':
+ return {
+ bg: 'bg-emerald-200 dark:bg-emerald-900/30',
+ text: 'text-emerald-800 dark:text-emerald-500'
+ }
+ default:
+ return { bg: 'bg-gray-200 dark:bg-gray-800', text: 'text-gray-800 dark:text-gray-500' }
+ }
}
// Helper function to get confidence color
const getConfidenceColor = (confidence: number) => {
- if (confidence >= 80) return 'text-emerald-600 dark:text-emerald-400'
- if (confidence >= 60) return 'text-amber-600 dark:text-amber-400'
- if (confidence >= 40) return 'text-orange-600 dark:text-orange-400'
- return 'text-red-600 dark:text-red-400'
+ if (confidence >= 80) return 'text-emerald-600 dark:text-emerald-400'
+ if (confidence >= 60) return 'text-amber-600 dark:text-amber-400'
+ if (confidence >= 40) return 'text-orange-600 dark:text-orange-400'
+ return 'text-red-600 dark:text-red-400'
}
export const columns: ColumnDef<GraphNode>[] = [
- {
- size: 50,
- minSize: 50,
- maxSize: 50,
- enableResizing: false,
- accessorKey: "icon",
- header: () => {
- const setSelectedNodes = useGraphStore(s => s.setSelectedNodes)
- const nodes = useGraphStore(s => s.nodes)
- const handleToggleCheckAll = useCallback(
- (checked: boolean) => {
- if (!checked) {
- setSelectedNodes([])
- return
- }
- else setSelectedNodes(nodes)
- },
- [nodes, setSelectedNodes],
- )
- return (<div className="flex items-center h-full"><Checkbox onCheckedChange={handleToggleCheckAll} /></div>)
+ {
+ size: 50,
+ minSize: 50,
+ maxSize: 50,
+ enableResizing: false,
+ accessorKey: 'icon',
+ header: () => {
+ const setSelectedNodes = useGraphStore((s) => s.setSelectedNodes)
+ const nodes = useGraphStore((s) => s.nodes)
+ const handleToggleCheckAll = useCallback(
+ (checked: boolean) => {
+ if (!checked) {
+ setSelectedNodes([])
+ return
+ } else setSelectedNodes(nodes)
},
- cell: ({ row }) => {
- const toggleNodeSelection = useGraphStore(s => s.toggleNodeSelection)
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const toggleNode = useCallback(() => toggleNodeSelection(row.original, true), [])
- const isNodeChecked = useCallback(
- (nodeId: string) => {
- return selectedNodes.some((node) => node.id === nodeId)
- },
- [selectedNodes],
- )
- return <div className="flex items-center"><Checkbox checked={isNodeChecked(row.original.id)} onCheckedChange={toggleNode} /></div>
+ [nodes, setSelectedNodes]
+ )
+ return (
+ <div className="flex items-center h-full">
+ <Checkbox onCheckedChange={handleToggleCheckAll} />
+ </div>
+ )
+ },
+ cell: ({ row }) => {
+ const toggleNodeSelection = useGraphStore((s) => s.toggleNodeSelection)
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const toggleNode = useCallback(() => toggleNodeSelection(row.original, true), [])
+ const isNodeChecked = useCallback(
+ (nodeId: string) => {
+ return selectedNodes.some((node) => node.id === nodeId)
},
+ [selectedNodes]
+ )
+ return (
+ <div className="flex items-center">
+ <Checkbox checked={isNodeChecked(row.original.id)} onCheckedChange={toggleNode} />
+ </div>
+ )
+ }
+ },
+ {
+ enableResizing: true,
+ size: 200,
+ minSize: 120,
+ maxSize: 500,
+ accessorKey: 'data.label',
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ className="h-7"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ >
+ Label
+ <ArrowUpDown className="h-4 w-4" />
+ </Button>
+ )
},
- {
- enableResizing: true,
- size: 200,
- minSize: 120,
- maxSize: 500,
- accessorKey: "data.label",
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- className="h-7"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Label
- <ArrowUpDown className="h-4 w-4" />
- </Button>
- )
+ cell: ({ row }) => {
+ const setCurrentNode = useGraphStore((s) => s.setCurrentNode)
+ // const IconComponent = useIcon(row.original.data.type)
+ const setOpenNodeEditorModal = useGraphStore((s) => s.setOpenNodeEditorModal)
+ const openEdit = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation()
+ const typedNode = row.original as GraphNode
+ setCurrentNode(typedNode)
+ setOpenNodeEditorModal(true)
},
- cell: ({ row }) => {
- const setCurrentNode = useGraphStore(s => s.setCurrentNode)
- // const IconComponent = useIcon(row.original.data.type)
- const setOpenNodeEditorModal = useGraphStore(s => s.setOpenNodeEditorModal)
- const openEdit = useCallback((e: React.MouseEvent) => {
- e.stopPropagation();
- const typedNode = row.original as GraphNode
- setCurrentNode(typedNode)
- setOpenNodeEditorModal(true)
- }, [row.original, setCurrentNode, setOpenNodeEditorModal])
+ [row.original, setCurrentNode, setOpenNodeEditorModal]
+ )
- return (
- <button
- onClick={openEdit}
- className="text-left font-medium flex items-center gap-2 h-full truncate text-ellipsis w-full rounded-md p-2 transition-colors duration-500"
- >
- {/* <div className="flex-shrink-0">
+ return (
+ <button
+ onClick={openEdit}
+ className="text-left font-medium flex items-center gap-2 h-full truncate text-ellipsis w-full rounded-md p-2 transition-colors duration-500"
+ >
+ {/* <div className="flex-shrink-0">
<IconComponent size={16} />
</div> */}
- <span className="hover:text-primary truncate text-[.9rem] block font-medium transition-colors duration-500">
- {row.original.data.label}
- </span>
- </button>
- )
- }
+ <span className="hover:text-primary truncate text-[.9rem] block font-medium transition-colors duration-500">
+ {row.original.data.label}
+ </span>
+ </button>
+ )
+ }
+ },
+ {
+ enableResizing: true,
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ className="h-7"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ >
+ Type
+ <ArrowUpDown className="h-4 w-4" />
+ </Button>
+ )
},
- {
- enableResizing: true,
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- className="h-7"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Type
- <ArrowUpDown className="h-4 w-4" />
- </Button>
- )
- },
- size: 120,
- minSize: 80,
- maxSize: 200,
- accessorKey: "data.type",
- cell: ({ row }) => {
- const type = row.original.data.type
- return (
- <div className="text-center flex justify-center w-full font-medium flex items-center gap-2">
- <TypeBadge className="w-full" type={type} />
- </div>
- )
- }
+ size: 120,
+ minSize: 80,
+ maxSize: 200,
+ accessorKey: 'data.type',
+ cell: ({ row }) => {
+ const type = row.original.data.type
+ return (
+ <div className="text-center flex justify-center w-full font-medium flex items-center gap-2">
+ <TypeBadge className="w-full" type={type} />
+ </div>
+ )
+ }
+ },
+ {
+ enableResizing: true,
+ size: 200,
+ minSize: 120,
+ maxSize: 500,
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ className="h-7"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ >
+ Status
+ <ArrowUpDown className="h-4 w-4" />
+ </Button>
+ )
},
- {
- enableResizing: true,
- size: 200,
- minSize: 120,
- maxSize: 500,
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- className="h-7"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Status
- <ArrowUpDown className="h-4 w-4" />
- </Button>
- )
- },
- accessorKey: "data.status",
- cell: ({ row }) => {
- const status = row.original.data.status || 'Active'
- const style = getStatusStyle(status)
- const IconComponent = style.icon
+ accessorKey: 'data.status',
+ cell: ({ row }) => {
+ const status = row.original.data.status || 'Active'
+ const style = getStatusStyle(status)
+ const IconComponent = style.icon
- return (
- <div className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-md border ${style.bg} ${style.text} ${style.border} text-xs font-medium`}>
- <IconComponent size={12} />
- <span className="capitalize">{status}</span>
- </div>
- )
- }
+ return (
+ <div
+ className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-md border ${style.bg} ${style.text} ${style.border} text-xs font-medium`}
+ >
+ <IconComponent size={12} />
+ <span className="capitalize">{status}</span>
+ </div>
+ )
+ }
+ },
+ {
+ enableResizing: true,
+ size: 200,
+ minSize: 120,
+ maxSize: 500,
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ className="h-7"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ >
+ Source
+ <ArrowUpDown className="h-4 w-4" />
+ </Button>
+ )
},
- {
- enableResizing: true,
- size: 200,
- minSize: 120,
- maxSize: 500,
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- className="h-7"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Source
- <ArrowUpDown className="h-4 w-4" />
- </Button>
- )
- },
- accessorKey: "data.source",
- cell: ({ row }) => {
- const source = row.original.data.source || 'Transform'
- return (
- <div className="text-left font-medium text-gray-700 dark:text-gray-200">
- {source}
- </div>
- )
- }
+ accessorKey: 'data.source',
+ cell: ({ row }) => {
+ const source = row.original.data.source || 'Transform'
+ return <div className="text-left font-medium text-gray-700 dark:text-gray-200">{source}</div>
+ }
+ },
+ {
+ enableResizing: true,
+ size: 200,
+ minSize: 120,
+ maxSize: 500,
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ className="h-7"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ >
+ Confidence
+ <ArrowUpDown className="h-4 w-4" />
+ </Button>
+ )
},
- {
- enableResizing: true,
- size: 200,
- minSize: 120,
- maxSize: 500,
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- className="h-7"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Confidence
- <ArrowUpDown className="h-4 w-4" />
- </Button>
- )
- },
- accessorKey: "data.confidence",
- cell: ({ row }) => {
- const confidence = row.original.data.confidence || 85
- const color = getConfidenceColor(confidence)
+ accessorKey: 'data.confidence',
+ cell: ({ row }) => {
+ const confidence = row.original.data.confidence || 85
+ const color = getConfidenceColor(confidence)
- return (
- <div className="flex items-center gap-2">
- <div className="flex-1 bg-gray-500 dark:bg-gray-700 rounded-full h-1.5">
- <div
- className={`h-1.5 rounded-full transition-all duration-200 ${color.replace('text-', 'bg-')}`}
- style={{ width: `${confidence}%` }}
- />
- </div>
- <span className={`text-xs font-medium ${color} min-w-[2.5rem]`}>
- {confidence}%
- </span>
- </div>
- )
- }
+ return (
+ <div className="flex items-center gap-2">
+ <div className="flex-1 bg-gray-500 dark:bg-gray-700 rounded-full h-1.5">
+ <div
+ className={`h-1.5 rounded-full transition-all duration-200 ${color.replace('text-', 'bg-')}`}
+ style={{ width: `${confidence}%` }}
+ />
+ </div>
+ <span className={`text-xs font-medium ${color} min-w-[2.5rem]`}>{confidence}%</span>
+ </div>
+ )
+ }
+ },
+ {
+ enableResizing: true,
+ size: 200,
+ minSize: 120,
+ maxSize: 500,
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ className="h-7"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ >
+ Risk Level
+ <ArrowUpDown className="h-4 w-4" />
+ </Button>
+ )
},
- {
- enableResizing: true,
- size: 200,
- minSize: 120,
- maxSize: 500,
- header: ({ column }) => {
- return (
- <Button
- variant="ghost"
- className="h-7"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
- >
- Risk Level
- <ArrowUpDown className="h-4 w-4" />
- </Button>
- )
- },
- accessorKey: "data.riskLevel",
- cell: ({ row }) => {
- const risk = row.original.data.riskLevel || 'N/A'
- const style = getRiskStyle(risk)
+ accessorKey: 'data.riskLevel',
+ cell: ({ row }) => {
+ const risk = row.original.data.riskLevel || 'N/A'
+ const style = getRiskStyle(risk)
- return (
- <div className={`inline-flex items-center px-2 py-1 rounded-md ${style.bg} ${style.text} text-xs font-medium capitalize`}>
- {risk}
- </div>
- )
- }
+ return (
+ <div
+ className={`inline-flex items-center px-2 py-1 rounded-md ${style.bg} ${style.text} text-xs font-medium capitalize`}
+ >
+ {risk}
+ </div>
+ )
+ }
+ },
+ {
+ enableResizing: true,
+ size: 200,
+ minSize: 120,
+ maxSize: 500,
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ className="h-7"
+ onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
+ >
+ Last Updated
+ <ArrowUpDown className="h-4 w-4" />
+ </Button>
+ )
},
- {
- enableResizing: true,
- size: 200,
- minSize: 120,
- maxSize: 500,
- header: ({ column }) => {
- return (
+ accessorKey: 'data.lastUpdated',
+ cell: ({ row }) => {
+ const date = row.original.data.lastUpdated || '2024-01-15'
+ return (
+ <div className="text-left font-medium text-gray-500 dark:text-gray-400 text-xs">{date}</div>
+ )
+ }
+ },
+ {
+ id: 'actions',
+ size: 50,
+ minSize: 50,
+ maxSize: 50,
+ enableResizing: false,
+ header: () => {
+ return <div className="w-[50]"></div>
+ },
+ cell: () => {
+ return (
+ <div className="flex items-center justify-center w-full h-full">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <div>
<Button
- variant="ghost"
- className="h-7"
- onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ variant="ghost"
+ className="h-8 w-8 p-0 hover:bg-gray-200 dark:hover:bg-gray-800 transition-colors duration-500"
>
- Last Updated
- <ArrowUpDown className="h-4 w-4" />
+ <span className="sr-only">Open menu</span>
+ <MoreVertical className="h-4 w-4" />
</Button>
- )
- },
- accessorKey: "data.lastUpdated",
- cell: ({ row }) => {
- const date = row.original.data.lastUpdated || '2024-01-15'
- return (
- <div className="text-left font-medium text-gray-500 dark:text-gray-400 text-xs">
- {date}
- </div>
- )
- }
- },
- {
- id: "actions",
- size: 50,
- minSize: 50,
- maxSize: 50,
- enableResizing: false,
- header: () => {
- return (
- <div className="w-[50]"></div>
- )
- },
- cell: () => {
- return (
- <div className="flex items-center justify-center w-full h-full">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <div>
- <Button variant="ghost" className="h-8 w-8 p-0 hover:bg-gray-200 dark:hover:bg-gray-800 transition-colors duration-500">
- <span className="sr-only">Open menu</span>
- <MoreVertical className="h-4 w-4" />
- </Button>
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuLabel>Actions</DropdownMenuLabel>
- <DropdownMenuItem
- ></DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- )
- },
- },
-]
\ No newline at end of file
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuItem></DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )
+ }
+ }
+]
diff --git a/flowsint-app/src/renderer/src/components/table/data-table.tsx b/flowsint-app/src/renderer/src/components/table/data-table.tsx
index b618c187..5a3dcb62 100644
--- a/flowsint-app/src/renderer/src/components/table/data-table.tsx
+++ b/flowsint-app/src/renderer/src/components/table/data-table.tsx
@@ -1,337 +1,363 @@
import {
- type Table,
- type Row,
- ColumnDef,
- flexRender,
- getCoreRowModel,
- useReactTable,
- SortingState,
- getSortedRowModel,
-} from "@tanstack/react-table";
-import {
- useVirtualizer,
-} from "@tanstack/react-virtual";
-import React from "react";
-import { Row as RowItem } from "@/types/table";
-import { cn } from "@/lib/utils";
+ type Table,
+ type Row,
+ ColumnDef,
+ flexRender,
+ getCoreRowModel,
+ useReactTable,
+ SortingState,
+ getSortedRowModel
+} from '@tanstack/react-table'
+import { useVirtualizer } from '@tanstack/react-virtual'
+import React from 'react'
+import { Row as RowItem } from '@/types/table'
+import { cn } from '@/lib/utils'
interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
- noStickyCol?: boolean;
+ columns: ColumnDef<TData, TValue>[]
+ data: TData[]
+ noStickyCol?: boolean
}
// Stable style objects to prevent re-renders
const BASE_ROW_STYLE = {
- display: "table" as const,
- width: "100%",
- tableLayout: "fixed" as const,
- zIndex: 0,
-};
+ display: 'table' as const,
+ width: '100%',
+ tableLayout: 'fixed' as const,
+ zIndex: 0
+}
const TABLE_STYLE = {
- borderCollapse: "separate" as const,
- tableLayout: "fixed" as const,
- borderSpacing: 0,
- width: "100%",
-};
+ borderCollapse: 'separate' as const,
+ tableLayout: 'fixed' as const,
+ borderSpacing: 0,
+ width: '100%'
+}
const TBODY_STYLE = {
- display: "block" as const,
-};
+ display: 'block' as const
+}
// Memoized row component to prevent unnecessary re-renders
const VirtualRow = React.memo<{
- row: Row<RowItem>;
- virtualRow: any;
- lastCellIndex: number;
- columnSizeVars: Record<string, number>;
- noStickyCol?: boolean;
+ row: Row<RowItem>
+ virtualRow: any
+ lastCellIndex: number
+ columnSizeVars: Record<string, number>
+ noStickyCol?: boolean
}>(({ row, virtualRow, lastCellIndex, columnSizeVars, noStickyCol }) => {
- const visibleCells = row.getVisibleCells();
+ const visibleCells = row.getVisibleCells()
- // Memoize the row style with transform
- const rowStyle = React.useMemo(() => ({
- ...BASE_ROW_STYLE,
- height: `${virtualRow.size}px`,
- }), [virtualRow.size]);
+ // Memoize the row style with transform
+ const rowStyle = React.useMemo(
+ () => ({
+ ...BASE_ROW_STYLE,
+ height: `${virtualRow.size}px`
+ }),
+ [virtualRow.size]
+ )
- return (
- <tr
- key={row.id}
- data-index={virtualRow.index}
- className="border-b hover:bg-muted/50 divide-x overflow-y-hidden"
- style={rowStyle}
- >
- {visibleCells.map((cell, index) => (
- <VirtualCell
- key={cell.id}
- cell={cell}
- index={index}
- isFirst={index === 0 || index === 1}
- isBeforeLast={index === lastCellIndex - 1}
- isLast={index === lastCellIndex}
- columnSizeVars={columnSizeVars}
- noStickyCol={noStickyCol}
- />
- ))}
- </tr>
- );
-});
+ return (
+ <tr
+ key={row.id}
+ data-index={virtualRow.index}
+ className="border-b hover:bg-muted/50 divide-x overflow-y-hidden"
+ style={rowStyle}
+ >
+ {visibleCells.map((cell, index) => (
+ <VirtualCell
+ key={cell.id}
+ cell={cell}
+ index={index}
+ isFirst={index === 0 || index === 1}
+ isBeforeLast={index === lastCellIndex - 1}
+ isLast={index === lastCellIndex}
+ columnSizeVars={columnSizeVars}
+ noStickyCol={noStickyCol}
+ />
+ ))}
+ </tr>
+ )
+})
// Memoized cell component
const VirtualCell = React.memo<{
- cell: any;
- index: number;
- isFirst: boolean;
- isLast: boolean;
- isBeforeLast: boolean,
- columnSizeVars: Record<string, number>;
- noStickyCol?: boolean;
+ cell: any
+ index: number
+ isFirst: boolean
+ isLast: boolean
+ isBeforeLast: boolean
+ columnSizeVars: Record<string, number>
+ noStickyCol?: boolean
}>(({ cell, index, isFirst, isLast, isBeforeLast, columnSizeVars, noStickyCol }) => {
- const cellStyle = React.useMemo(() => ({
- width: `calc(var(--col-${cell.column.id}-size) * 1px)`,
- minWidth: `calc(var(--col-${cell.column.id}-size) * 1px)`,
- maxWidth: `calc(var(--col-${cell.column.id}-size) * 1px)`,
- height: "40px",
- verticalAlign: "middle",
- textAlign: "center"
- }), [cell.column.id, columnSizeVars[`--col-${cell.column.id}-size`]]);
+ const cellStyle = React.useMemo(
+ () => ({
+ width: `calc(var(--col-${cell.column.id}-size) * 1px)`,
+ minWidth: `calc(var(--col-${cell.column.id}-size) * 1px)`,
+ maxWidth: `calc(var(--col-${cell.column.id}-size) * 1px)`,
+ height: '40px',
+ verticalAlign: 'middle',
+ textAlign: 'center'
+ }),
+ [cell.column.id, columnSizeVars[`--col-${cell.column.id}-size`]]
+ )
- const cellClassName = React.useMemo(() => cn(
- "px-4 py-1 truncate relative overflow-hidden",
- !isBeforeLast && !isLast && "border-r",
- index === 0 && !noStickyCol && "sticky z-10 left-0 bg-card border-b border-r",
- index === 1 && !noStickyCol && "sticky z-11 left-[50px] bg-card border-b border-r",
- isLast && !noStickyCol && "sticky right-0 z-10 bg-background px-0 border-l border-b",
- ), [isFirst, isLast, index, isBeforeLast]);
+ const cellClassName = React.useMemo(
+ () =>
+ cn(
+ 'px-4 py-1 truncate relative overflow-hidden',
+ !isBeforeLast && !isLast && 'border-r',
+ index === 0 && !noStickyCol && 'sticky z-10 left-0 bg-card border-b border-r',
+ index === 1 && !noStickyCol && 'sticky z-11 left-[50px] bg-card border-b border-r',
+ isLast && !noStickyCol && 'sticky right-0 z-10 bg-background px-0 border-l border-b'
+ ),
+ [isFirst, isLast, index, isBeforeLast]
+ )
- return (
- <td
- className={cellClassName}
- //@ts-ignore
- style={cellStyle}
- >
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </td>
- );
-});
+ return (
+ <td
+ className={cellClassName}
+ //@ts-ignore
+ style={cellStyle}
+ >
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </td>
+ )
+})
// Table body component
-const TableBody = ({ table, tableContainerRef, columnSizeVars, noStickyCol }: {
- table: Table<any>;
- tableContainerRef: React.RefObject<HTMLDivElement>;
- columnSizeVars: Record<string, number>;
- noStickyCol?: boolean;
+const TableBody = ({
+ table,
+ tableContainerRef,
+ columnSizeVars,
+ noStickyCol
+}: {
+ table: Table<any>
+ tableContainerRef: React.RefObject<HTMLDivElement>
+ columnSizeVars: Record<string, number>
+ noStickyCol?: boolean
}) => {
- const { rows } = table.getRowModel();
+ const { rows } = table.getRowModel()
- const rowVirtualizer = useVirtualizer({
- count: rows.length,
- estimateSize: () => 40, // Hauteur estimée de chaque ligne
- getScrollElement: () => tableContainerRef.current,
- });
+ const rowVirtualizer = useVirtualizer({
+ count: rows.length,
+ estimateSize: () => 40, // Hauteur estimée de chaque ligne
+ getScrollElement: () => tableContainerRef.current
+ })
- // Memoize empty state
- const emptyState = React.useMemo(() => (
- <tbody>
- <tr>
- <td colSpan={table.getHeaderGroups()[0]?.headers.length || 1}>
- <div className="flex items-center justify-center h-32 text-muted-foreground">
- <div className="text-center">
- <div className="text-md font-medium">No data found yet.</div>
- <div className="text-xs">No nodes to display</div>
- </div>
- </div>
- </td>
- </tr>
- </tbody>
- ), [table.getHeaderGroups()[0]?.headers.length]);
+ // Memoize empty state
+ const emptyState = React.useMemo(
+ () => (
+ <tbody>
+ <tr>
+ <td colSpan={table.getHeaderGroups()[0]?.headers.length || 1}>
+ <div className="flex items-center justify-center h-32 text-muted-foreground">
+ <div className="text-center">
+ <div className="text-md font-medium">No data found yet.</div>
+ <div className="text-xs">No nodes to display</div>
+ </div>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ ),
+ [table.getHeaderGroups()[0]?.headers.length]
+ )
- const virtualRows = rowVirtualizer.getVirtualItems();
- const totalSize = rowVirtualizer.getTotalSize();
- const lastCellIndex = rows[0]?.getVisibleCells().length - 1 || 0;
+ const virtualRows = rowVirtualizer.getVirtualItems()
+ const totalSize = rowVirtualizer.getTotalSize()
+ const lastCellIndex = rows[0]?.getVisibleCells().length - 1 || 0
- const tbodyStyle = React.useMemo(() => ({
- ...TBODY_STYLE,
- height: `${totalSize}px`,
- paddingTop: virtualRows.length > 0 ? `${virtualRows[0]?.start ?? 0}px` : 0,
- }), [totalSize, virtualRows]);
+ const tbodyStyle = React.useMemo(
+ () => ({
+ ...TBODY_STYLE,
+ height: `${totalSize}px`,
+ paddingTop: virtualRows.length > 0 ? `${virtualRows[0]?.start ?? 0}px` : 0
+ }),
+ [totalSize, virtualRows]
+ )
- if (rows.length === 0) {
- return emptyState;
- }
+ if (rows.length === 0) {
+ return emptyState
+ }
- return (
- <tbody style={tbodyStyle}>
- {virtualRows.map((virtualRow) => {
- const row = rows[virtualRow.index] as Row<RowItem>;
- return (
- <VirtualRow
- key={row.id}
- row={row}
- virtualRow={virtualRow}
- lastCellIndex={lastCellIndex}
- columnSizeVars={columnSizeVars}
- noStickyCol={noStickyCol}
- />
- );
- })}
- {/* Spacer pour maintenir la hauteur totale */}
- {virtualRows.length > 0 && (
- <tr style={{ height: `${totalSize - (virtualRows[virtualRows.length - 1]?.end ?? 0)}px` }}>
- <td colSpan={table.getHeaderGroups()[0]?.headers.length || 1} style={{ padding: 0, border: 'none' }} />
- </tr>
- )}
- </tbody>
- );
-};
+ return (
+ <tbody style={tbodyStyle}>
+ {virtualRows.map((virtualRow) => {
+ const row = rows[virtualRow.index] as Row<RowItem>
+ return (
+ <VirtualRow
+ key={row.id}
+ row={row}
+ virtualRow={virtualRow}
+ lastCellIndex={lastCellIndex}
+ columnSizeVars={columnSizeVars}
+ noStickyCol={noStickyCol}
+ />
+ )
+ })}
+ {/* Spacer pour maintenir la hauteur totale */}
+ {virtualRows.length > 0 && (
+ <tr style={{ height: `${totalSize - (virtualRows[virtualRows.length - 1]?.end ?? 0)}px` }}>
+ <td
+ colSpan={table.getHeaderGroups()[0]?.headers.length || 1}
+ style={{ padding: 0, border: 'none' }}
+ />
+ </tr>
+ )}
+ </tbody>
+ )
+}
-export const MemoizedTableBody = React.memo(
- TableBody,
- (prev, next) => {
- const prevRows = prev.table.getRowModel().rows;
- const nextRows = next.table.getRowModel().rows;
- const prevSort = prev.table.getState().sorting;
- const nextSort = next.table.getState().sorting;
- const prevFilter = prev.table.getState().columnFilters;
- const nextFilter = next.table.getState().columnFilters;
- // 1. Si le tri ou les filtres changent, on re-render
- if (prevSort !== nextSort) return false;
- if (prevFilter !== nextFilter) return false;
- // 2. Si le nombre de lignes change, on re-render
- if (prevRows.length !== nextRows.length) return false;
- return prevRows === nextRows;
- }
-) as typeof TableBody
+export const MemoizedTableBody = React.memo(TableBody, (prev, next) => {
+ const prevRows = prev.table.getRowModel().rows
+ const nextRows = next.table.getRowModel().rows
+ const prevSort = prev.table.getState().sorting
+ const nextSort = next.table.getState().sorting
+ const prevFilter = prev.table.getState().columnFilters
+ const nextFilter = next.table.getState().columnFilters
+ // 1. Si le tri ou les filtres changent, on re-render
+ if (prevSort !== nextSort) return false
+ if (prevFilter !== nextFilter) return false
+ // 2. Si le nombre de lignes change, on re-render
+ if (prevRows.length !== nextRows.length) return false
+ return prevRows === nextRows
+}) as typeof TableBody
// Memoized header cell component
const HeaderCell = React.memo<{
- header: any;
- index: number;
- isFirst: boolean;
- isLast: boolean;
- isBeforeLast: boolean;
- columnSizeVars: Record<string, number>;
- noStickyCol?: boolean;
+ header: any
+ index: number
+ isFirst: boolean
+ isLast: boolean
+ isBeforeLast: boolean
+ columnSizeVars: Record<string, number>
+ noStickyCol?: boolean
}>(({ header, index, isFirst, isLast, isBeforeLast, columnSizeVars, noStickyCol }) => {
- const headerStyle = React.useMemo(() => ({
- width: `calc(var(--header-${header.id}-size) * 1px)`,
- minWidth: `calc(var(--header-${header.id}-size) * 1px)`,
- maxWidth: `calc(var(--header-${header.id}-size) * 1px)`,
- }), [header.id, columnSizeVars[`--header-${header.id}-size`]]);
+ const headerStyle = React.useMemo(
+ () => ({
+ width: `calc(var(--header-${header.id}-size) * 1px)`,
+ minWidth: `calc(var(--header-${header.id}-size) * 1px)`,
+ maxWidth: `calc(var(--header-${header.id}-size) * 1px)`
+ }),
+ [header.id, columnSizeVars[`--header-${header.id}-size`]]
+ )
- const headerClassName = React.useMemo(() => cn(
- !isBeforeLast && !isLast && "border-r",
- "px-4 py-1 text-center font-medium text-muted-foreground border-b overflow-hidde",
+ const headerClassName = React.useMemo(
+ () =>
+ cn(
+ !isBeforeLast && !isLast && 'border-r',
+ 'px-4 py-1 text-center font-medium text-muted-foreground border-b overflow-hidde',
isFirst && !noStickyCol && `!sticky z-30`,
- index === 0 && !noStickyCol && "left-0 bg-card",
- index === 1 && !noStickyCol && "left-[50px] bg-card",
- isLast && !noStickyCol && "!sticky right-0 z-30 bg-background border-l",
- ), [isFirst, isLast, index, isBeforeLast]);
+ index === 0 && !noStickyCol && 'left-0 bg-card',
+ index === 1 && !noStickyCol && 'left-[50px] bg-card',
+ isLast && !noStickyCol && '!sticky right-0 z-30 bg-background border-l'
+ ),
+ [isFirst, isLast, index, isBeforeLast]
+ )
- return (
- <th
- className={headerClassName}
- style={headerStyle}
- >
- {header.isPlaceholder
- ? null
- : flexRender(header.column.columnDef.header, header.getContext())}
- {header.column.getCanResize() && (
- <div
- onDoubleClick={() => header.column.resetSize()}
- onMouseDown={header.getResizeHandler()}
- onTouchStart={header.getResizeHandler()}
- className={`resizer ${header.column.getIsResizing() ? "isResizing" : ""}`}
- />
- )}
- </th>
- );
-});
+ return (
+ <th className={headerClassName} style={headerStyle}>
+ {header.isPlaceholder
+ ? null
+ : flexRender(header.column.columnDef.header, header.getContext())}
+ {header.column.getCanResize() && (
+ <div
+ onDoubleClick={() => header.column.resetSize()}
+ onMouseDown={header.getResizeHandler()}
+ onTouchStart={header.getResizeHandler()}
+ className={`resizer ${header.column.getIsResizing() ? 'isResizing' : ''}`}
+ />
+ )}
+ </th>
+ )
+})
export function DataTable<TData, TValue>({
- columns,
- data,
- noStickyCol = false,
+ columns,
+ data,
+ noStickyCol = false
}: DataTableProps<TData, TValue>) {
- const tableContainerRef = React.useRef<HTMLDivElement>(null);
- const [sorting, setSorting] = React.useState<SortingState>([]);
+ const tableContainerRef = React.useRef<HTMLDivElement>(null)
+ const [sorting, setSorting] = React.useState<SortingState>([])
- const table = useReactTable({
- data,
- columns,
- state: {
- sorting,
- },
- onSortingChange: setSorting,
- getSortedRowModel: getSortedRowModel(),
- getCoreRowModel: getCoreRowModel(),
- columnResizeMode: "onChange",
- defaultColumn: {
- minSize: 60,
- maxSize: 800,
- },
- debugTable: false,
- debugHeaders: false,
- debugColumns: false,
- });
+ const table = useReactTable({
+ data,
+ columns,
+ state: {
+ sorting
+ },
+ onSortingChange: setSorting,
+ getSortedRowModel: getSortedRowModel(),
+ getCoreRowModel: getCoreRowModel(),
+ columnResizeMode: 'onChange',
+ defaultColumn: {
+ minSize: 60,
+ maxSize: 800
+ },
+ debugTable: false,
+ debugHeaders: false,
+ debugColumns: false
+ })
- // Optimize column size variables calculation
- const columnSizeVars = React.useMemo(() => {
- const headers = table.getFlatHeaders();
- const colSizes: { [key: string]: number } = {};
- for (let i = 0; i < headers.length; i++) {
- const header = headers[i]!;
- colSizes[`--header-${header.id}-size`] = header.getSize();
- colSizes[`--col-${header.column.id}-size`] = header.column.getSize();
- }
- return colSizes;
- }, [
- table.getState().columnSizing,
- // Only depend on the actual sizing values, not the entire state objects
- JSON.stringify(table.getState().columnSizing),
- ]);
+ // Optimize column size variables calculation
+ const columnSizeVars = React.useMemo(() => {
+ const headers = table.getFlatHeaders()
+ const colSizes: { [key: string]: number } = {}
+ for (let i = 0; i < headers.length; i++) {
+ const header = headers[i]!
+ colSizes[`--header-${header.id}-size`] = header.getSize()
+ colSizes[`--col-${header.column.id}-size`] = header.column.getSize()
+ }
+ return colSizes
+ }, [
+ table.getState().columnSizing,
+ // Only depend on the actual sizing values, not the entire state objects
+ JSON.stringify(table.getState().columnSizing)
+ ])
- // Memoize table style
- const tableStyle = React.useMemo(() => ({
- ...TABLE_STYLE,
- ...columnSizeVars,
- width: table.getTotalSize(),
- }), [columnSizeVars, table.getTotalSize()]);
+ // Memoize table style
+ const tableStyle = React.useMemo(
+ () => ({
+ ...TABLE_STYLE,
+ ...columnSizeVars,
+ width: table.getTotalSize()
+ }),
+ [columnSizeVars, table.getTotalSize()]
+ )
- // Memoize header groups and calculate indices once
- const headerGroups = table.getHeaderGroups();
- const lastColumnIndex = headerGroups[0]?.headers.length - 1;
+ // Memoize header groups and calculate indices once
+ const headerGroups = table.getHeaderGroups()
+ const lastColumnIndex = headerGroups[0]?.headers.length - 1
- return (
- <div className="h-full w-full overflow-auto border-t p-0 relative" ref={tableContainerRef}>
- <table style={tableStyle}>
- <thead className="sticky top-0 z-20 bg-background">
- {headerGroups.map((headerGroup) => (
- <tr key={headerGroup.id} className="px-0">
- {headerGroup.headers.map((header, index) => (
- <HeaderCell
- key={header.id}
- header={header}
- index={index}
- isBeforeLast={index === lastColumnIndex - 1}
- isFirst={index === 0 || index === 1}
- isLast={index === lastColumnIndex}
- columnSizeVars={columnSizeVars}
- noStickyCol={noStickyCol}
- />
- ))}
- </tr>
- ))}
- </thead>
- <TableBody
- table={table}
- tableContainerRef={tableContainerRef}
- columnSizeVars={columnSizeVars}
- noStickyCol={noStickyCol}
+ return (
+ <div className="h-full w-full overflow-auto border-t p-0 relative" ref={tableContainerRef}>
+ <table style={tableStyle}>
+ <thead className="sticky top-0 z-20 bg-background">
+ {headerGroups.map((headerGroup) => (
+ <tr key={headerGroup.id} className="px-0">
+ {headerGroup.headers.map((header, index) => (
+ <HeaderCell
+ key={header.id}
+ header={header}
+ index={index}
+ isBeforeLast={index === lastColumnIndex - 1}
+ isFirst={index === 0 || index === 1}
+ isLast={index === lastColumnIndex}
+ columnSizeVars={columnSizeVars}
+ noStickyCol={noStickyCol}
/>
- </table>
- </div>
- );
-}
\ No newline at end of file
+ ))}
+ </tr>
+ ))}
+ </thead>
+ <TableBody
+ table={table}
+ tableContainerRef={tableContainerRef}
+ columnSizeVars={columnSizeVars}
+ noStickyCol={noStickyCol}
+ />
+ </table>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/table/index.tsx b/flowsint-app/src/renderer/src/components/table/index.tsx
index cbd6586b..ff83e6c2 100644
--- a/flowsint-app/src/renderer/src/components/table/index.tsx
+++ b/flowsint-app/src/renderer/src/components/table/index.tsx
@@ -1,10 +1,8 @@
-import { useGraphStore } from "@/stores/graph-store"
-import NodesTable from "./nodes-view"
+import { useGraphStore } from '@/stores/graph-store'
+import NodesTable from './nodes-view'
export default function NodesViewTable() {
- const nodes = useGraphStore(s => s.filteredNodes)
+ const nodes = useGraphStore((s) => s.filteredNodes)
- return (
- <NodesTable nodes={nodes} />
- )
-}
\ No newline at end of file
+ return <NodesTable nodes={nodes} />
+}
diff --git a/flowsint-app/src/renderer/src/components/table/nodes-view.tsx b/flowsint-app/src/renderer/src/components/table/nodes-view.tsx
index 0136827f..69ea8638 100644
--- a/flowsint-app/src/renderer/src/components/table/nodes-view.tsx
+++ b/flowsint-app/src/renderer/src/components/table/nodes-view.tsx
@@ -1,307 +1,321 @@
-import { useGraphStore } from "@/stores/graph-store";
-import { useVirtualizer } from "@tanstack/react-virtual";
-import { useRef, useState, useMemo, useCallback, memo } from "react";
-import { Input } from "@/components/ui/input";
-import { Badge } from "@/components/ui/badge";
-import { Search, Users, Link, Filter, Calendar } from "lucide-react";
-import { useIcon } from "@/hooks/use-icon";
+import { useGraphStore } from '@/stores/graph-store'
+import { useVirtualizer } from '@tanstack/react-virtual'
+import { useRef, useState, useMemo, useCallback, memo } from 'react'
+import { Input } from '@/components/ui/input'
+import { Badge } from '@/components/ui/badge'
+import { Search, Users, Link, Filter, Calendar } from 'lucide-react'
+import { useIcon } from '@/hooks/use-icon'
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { Checkbox } from "@/components/ui/checkbox";
-import { CopyButton } from "../copy";
-import { GraphNode } from '@/types';
-import { formatDistanceToNow } from "date-fns";
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select'
+import { Checkbox } from '@/components/ui/checkbox'
+import { CopyButton } from '../copy'
+import { GraphNode } from '@/types'
+import { formatDistanceToNow } from 'date-fns'
export type RelationshipType = {
- source: GraphNode
- target: GraphNode
- edge: { label: string }
+ source: GraphNode
+ target: GraphNode
+ edge: { label: string }
}
-const ITEM_HEIGHT = 56; // Row height used by virtualizer
+const ITEM_HEIGHT = 56 // Row height used by virtualizer
// Separate component for node item to avoid hook order issues
interface NodeItemProps {
- node: GraphNode;
- onNodeClick: (node: GraphNode) => void;
- isSelected: boolean;
- onSelectionChange: (node: GraphNode, checked: boolean) => void;
+ node: GraphNode
+ onNodeClick: (node: GraphNode) => void
+ isSelected: boolean
+ onSelectionChange: (node: GraphNode, checked: boolean) => void
}
-const NodeItem = memo(function NodeItem({ node, onNodeClick, isSelected, onSelectionChange }: NodeItemProps) {
- const SourceIcon = useIcon(node.data?.type, node.data?.src);
+const NodeItem = memo(function NodeItem({
+ node,
+ onNodeClick,
+ isSelected,
+ onSelectionChange
+}: NodeItemProps) {
+ const SourceIcon = useIcon(node.data?.type, node.data?.src)
- const handleNodeClick = useCallback(() => {
- onNodeClick(node)
- }, [onNodeClick, node])
+ const handleNodeClick = useCallback(() => {
+ onNodeClick(node)
+ }, [onNodeClick, node])
- const handleCheckboxChange = useCallback((checked: boolean) => {
- onSelectionChange(node, checked)
- }, [onSelectionChange, node])
+ const handleCheckboxChange = useCallback(
+ (checked: boolean) => {
+ onSelectionChange(node, checked)
+ },
+ [onSelectionChange, node]
+ )
- const formatCreatedAt = useCallback((dateString: string) => {
- try {
- return formatDistanceToNow(new Date(dateString), { addSuffix: true })
- } catch {
- return 'Unknown'
- }
- }, [])
+ const formatCreatedAt = useCallback((dateString: string) => {
+ try {
+ return formatDistanceToNow(new Date(dateString), { addSuffix: true })
+ } catch {
+ return 'Unknown'
+ }
+ }, [])
- return (
- <div className="px-4">
- <div className="grid items-center h-[56px] gap-3 text-sm border-b last:border-b-0"
- style={{
- gridTemplateColumns: "24px 32px 1fr 140px 160px 32px"
- }}
- >
- {/* Checkbox */}
- <div className="flex items-center">
- <Checkbox
- checked={isSelected}
- onCheckedChange={handleCheckboxChange}
- />
- </div>
+ return (
+ <div className="px-4">
+ <div
+ className="grid items-center h-[56px] gap-3 text-sm border-b last:border-b-0"
+ style={{
+ gridTemplateColumns: '24px 32px 1fr 140px 160px 32px'
+ }}
+ >
+ {/* Checkbox */}
+ <div className="flex items-center">
+ <Checkbox checked={isSelected} onCheckedChange={handleCheckboxChange} />
+ </div>
- {/* Icon */}
- <div className="flex items-center justify-center">
- <div className="flex items-center justify-center w-6 h-6 rounded bg-muted">
- <SourceIcon className="h-4 w-4" />
- </div>
- </div>
+ {/* Icon */}
+ <div className="flex items-center justify-center">
+ <div className="flex items-center justify-center w-6 h-6 rounded bg-muted">
+ <SourceIcon className="h-4 w-4" />
+ </div>
+ </div>
- {/* Label */}
- <div className="min-w-0 flex justify-start grow">
- <button
- onClick={handleNodeClick}
- className="font-medium hover:text-primary hover:underline cursor-pointer truncate p-0"
- >
- <span className="block truncate">
- {node.data?.label ?? node.id}
- </span>
- </button>
- </div>
+ {/* Label */}
+ <div className="min-w-0 flex justify-start grow">
+ <button
+ onClick={handleNodeClick}
+ className="font-medium hover:text-primary hover:underline cursor-pointer truncate p-0"
+ >
+ <span className="block truncate">{node.data?.label ?? node.id}</span>
+ </button>
+ </div>
- {/* Type */}
- <div>
- <Badge variant="outline" className="text-xs">
- {node.data?.type || 'Unknown'}
- </Badge>
- </div>
+ {/* Type */}
+ <div>
+ <Badge variant="outline" className="text-xs">
+ {node.data?.type || 'Unknown'}
+ </Badge>
+ </div>
- {/* Created At */}
- <div className="flex items-center gap-1 text-xs text-muted-foreground min-w-0">
- <Calendar className="h-3 w-3" />
- <span className="truncate">
- {node.data?.created_at ? formatCreatedAt(node.data.created_at) : 'Unknown'}
- </span>
- </div>
+ {/* Created At */}
+ <div className="flex items-center gap-1 text-xs text-muted-foreground min-w-0">
+ <Calendar className="h-3 w-3" />
+ <span className="truncate">
+ {node.data?.created_at ? formatCreatedAt(node.data.created_at) : 'Unknown'}
+ </span>
+ </div>
- {/* Copy Button */}
- <div className="flex justify-end">
- <CopyButton content={node.data?.label ?? node.id} />
- </div>
- </div>
+ {/* Copy Button */}
+ <div className="flex justify-end">
+ <CopyButton content={node.data?.label ?? node.id} />
</div>
- );
+ </div>
+ </div>
+ )
})
type NodesTableProps = {
- nodes: GraphNode[]
+ nodes: GraphNode[]
}
export default function NodesTable({ nodes }: NodesTableProps) {
- const [searchQuery, setSearchQuery] = useState("");
- const [selectedType, setSelectedType] = useState<string>("all");
- const parentRef = useRef<HTMLDivElement>(null);
- const setCurrentNode = useGraphStore(s => s.setCurrentNode)
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const setSelectedNodes = useGraphStore(s => s.setSelectedNodes)
- const toggleNodeSelection = useGraphStore(s => s.toggleNodeSelection)
+ const [searchQuery, setSearchQuery] = useState('')
+ const [selectedType, setSelectedType] = useState<string>('all')
+ const parentRef = useRef<HTMLDivElement>(null)
+ const setCurrentNode = useGraphStore((s) => s.setCurrentNode)
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const setSelectedNodes = useGraphStore((s) => s.setSelectedNodes)
+ const toggleNodeSelection = useGraphStore((s) => s.toggleNodeSelection)
- const onNodeClick = useCallback((node: GraphNode) => {
- setCurrentNode(node)
- }, [setCurrentNode])
+ const onNodeClick = useCallback(
+ (node: GraphNode) => {
+ setCurrentNode(node)
+ },
+ [setCurrentNode]
+ )
- // Filter nodes based on search and type
- const filteredNodes = useMemo(() => {
- if (!nodes) return [];
+ // Filter nodes based on search and type
+ const filteredNodes = useMemo(() => {
+ if (!nodes) return []
- return nodes.filter((node: GraphNode) => {
- const lower = searchQuery.toLowerCase();
- const label = node.data?.label?.toLowerCase() ?? "";
- const type = node.data?.type?.toLowerCase() ?? "";
- const matchesSearch = lower === "" || label.includes(lower) || type.includes(lower);
+ return nodes.filter((node: GraphNode) => {
+ const lower = searchQuery.toLowerCase()
+ const label = node.data?.label?.toLowerCase() ?? ''
+ const type = node.data?.type?.toLowerCase() ?? ''
+ const matchesSearch = lower === '' || label.includes(lower) || type.includes(lower)
- const matchesType = selectedType === "all" || node.data?.type === selectedType;
+ const matchesType = selectedType === 'all' || node.data?.type === selectedType
- return matchesSearch && matchesType;
- });
- }, [nodes, searchQuery, selectedType]);
+ return matchesSearch && matchesType
+ })
+ }, [nodes, searchQuery, selectedType])
- const handleSelectAll = useCallback((checked: boolean) => {
- if (checked) {
- setSelectedNodes(filteredNodes)
- } else {
- setSelectedNodes([])
- }
- }, [setSelectedNodes, filteredNodes])
+ const handleSelectAll = useCallback(
+ (checked: boolean) => {
+ if (checked) {
+ setSelectedNodes(filteredNodes)
+ } else {
+ setSelectedNodes([])
+ }
+ },
+ [setSelectedNodes, filteredNodes]
+ )
- const handleNodeSelectionChange = useCallback((node: GraphNode, checked: boolean) => {
- toggleNodeSelection(node, checked)
- }, [toggleNodeSelection])
+ const handleNodeSelectionChange = useCallback(
+ (node: GraphNode, checked: boolean) => {
+ toggleNodeSelection(node, checked)
+ },
+ [toggleNodeSelection]
+ )
- const isNodeSelected = useCallback((nodeId: string) => {
- return selectedNodes.some(node => node.id === nodeId)
- }, [selectedNodes])
+ const isNodeSelected = useCallback(
+ (nodeId: string) => {
+ return selectedNodes.some((node) => node.id === nodeId)
+ },
+ [selectedNodes]
+ )
- const isAllSelected = useMemo(() => {
- return filteredNodes.length > 0 && filteredNodes.every(node => isNodeSelected(node.id))
- }, [filteredNodes, isNodeSelected])
+ const isAllSelected = useMemo(() => {
+ return filteredNodes.length > 0 && filteredNodes.every((node) => isNodeSelected(node.id))
+ }, [filteredNodes, isNodeSelected])
- const isIndeterminate = useMemo(() => {
- const selectedCount = filteredNodes.filter(node => isNodeSelected(node.id)).length
- return selectedCount > 0 && selectedCount < filteredNodes.length
- }, [filteredNodes, isNodeSelected])
+ const isIndeterminate = useMemo(() => {
+ const selectedCount = filteredNodes.filter((node) => isNodeSelected(node.id)).length
+ return selectedCount > 0 && selectedCount < filteredNodes.length
+ }, [filteredNodes, isNodeSelected])
- // Get unique node types for filter
- const nodeTypes = useMemo(() => {
- if (!nodes) return [];
- const types = new Set<string>();
- nodes.forEach((node: GraphNode) => {
- if (node.data?.type) types.add(node.data.type);
- });
- return Array.from(types).sort();
- }, [nodes]);
+ // Get unique node types for filter
+ const nodeTypes = useMemo(() => {
+ if (!nodes) return []
+ const types = new Set<string>()
+ nodes.forEach((node: GraphNode) => {
+ if (node.data?.type) types.add(node.data.type)
+ })
+ return Array.from(types).sort()
+ }, [nodes])
- const virtualizer = useVirtualizer({
- count: filteredNodes.length,
- getScrollElement: () => parentRef.current,
- estimateSize: () => ITEM_HEIGHT,
- overscan: 5,
- });
-
- if (!nodes || nodes.length === 0) {
- return (
- <div className="w-full pt-18 flex items-center justify-center h-full">
- <div className="text-center space-y-4">
- <Link className="mx-auto h-12 w-12 text-muted-foreground" />
- <div>
- <h3 className="text-lg font-semibold">No nodes found</h3>
- <p className="text-muted-foreground">This sketch doesn't have any nodes yet.</p>
- </div>
- </div>
- </div>
- );
- }
+ const virtualizer = useVirtualizer({
+ count: filteredNodes.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => ITEM_HEIGHT,
+ overscan: 5
+ })
+ if (!nodes || nodes.length === 0) {
return (
- <div className="w-full grow flex flex-col pt-18 p-4 px-6">
- {/* Header with stats */}
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h2 className="text-2xl font-bold tracking-tight">Entities</h2>
- <p className="text-muted-foreground">
- {filteredNodes.length} of {nodes.length} nodes
- </p>
- </div>
- <Badge variant="secondary" className="flex items-center gap-2">
- <Users className="h-4 w-4" />
- {nodes.length} total
- </Badge>
- </div>
+ <div className="w-full pt-18 flex items-center justify-center h-full">
+ <div className="text-center space-y-4">
+ <Link className="mx-auto h-12 w-12 text-muted-foreground" />
+ <div>
+ <h3 className="text-lg font-semibold">No nodes found</h3>
+ <p className="text-muted-foreground">This sketch doesn't have any nodes yet.</p>
+ </div>
+ </div>
+ </div>
+ )
+ }
- {/* Search and Filter */}
- <div className="flex gap-4 my-4">
- <div className="relative flex-1">
- <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="Search nodes, nodes, or types..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-10"
- />
- </div>
- <Select value={selectedType} onValueChange={setSelectedType}>
- <SelectTrigger className="w-48">
- <Filter className="h-4 w-4 mr-2 text-muted-foreground" />
- <SelectValue placeholder="Filter by type" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">All Types</SelectItem>
- {nodeTypes.map((type) => (
- <SelectItem key={type} value={type}>
- <span className="capitalize">{type}</span>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- {/* Table Header */}
- <div className="grid items-center h-[44px] px-4 bg-muted/50 p-2 rounded-t-lg border text-sm font-medium text-muted-foreground"
- style={{ gridTemplateColumns: "24px 32px 1fr 140px 160px 32px" }}
- >
- <div className="flex items-center">
- <Checkbox
- checked={isAllSelected}
- ref={(el) => {
- if (el && 'indeterminate' in el) {
- (el as HTMLInputElement).indeterminate = isIndeterminate
- }
- }}
- onCheckedChange={handleSelectAll}
- />
- </div>
- <div></div> {/* Icon */}
- <div className="text-center">Label</div>
- <div>Type</div>
- <div>Created</div>
- <div></div> {/* Actions */}
- </div>
+ return (
+ <div className="w-full grow flex flex-col pt-18 p-4 px-6">
+ {/* Header with stats */}
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <h2 className="text-2xl font-bold tracking-tight">Entities</h2>
+ <p className="text-muted-foreground">
+ {filteredNodes.length} of {nodes.length} nodes
+ </p>
+ </div>
+ <Badge variant="secondary" className="flex items-center gap-2">
+ <Users className="h-4 w-4" />
+ {nodes.length} total
+ </Badge>
+ </div>
+
+ {/* Search and Filter */}
+ <div className="flex gap-4 my-4">
+ <div className="relative flex-1">
+ <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder="Search nodes, nodes, or types..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-10"
+ />
+ </div>
+ <Select value={selectedType} onValueChange={setSelectedType}>
+ <SelectTrigger className="w-48">
+ <Filter className="h-4 w-4 mr-2 text-muted-foreground" />
+ <SelectValue placeholder="Filter by type" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All Types</SelectItem>
+ {nodeTypes.map((type) => (
+ <SelectItem key={type} value={type}>
+ <span className="capitalize">{type}</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ {/* Table Header */}
+ <div
+ className="grid items-center h-[44px] px-4 bg-muted/50 p-2 rounded-t-lg border text-sm font-medium text-muted-foreground"
+ style={{ gridTemplateColumns: '24px 32px 1fr 140px 160px 32px' }}
+ >
+ <div className="flex items-center">
+ <Checkbox
+ checked={isAllSelected}
+ ref={(el) => {
+ if (el && 'indeterminate' in el) {
+ ;(el as HTMLInputElement).indeterminate = isIndeterminate
+ }
+ }}
+ onCheckedChange={handleSelectAll}
+ />
+ </div>
+ <div></div> {/* Icon */}
+ <div className="text-center">Label</div>
+ <div>Type</div>
+ <div>Created</div>
+ <div></div> {/* Actions */}
+ </div>
- {/* Virtualized List */}
- <div
- ref={parentRef}
- className="grow overflow-auto rounded-b-lg border border-t-0"
- >
- <div
- style={{
- height: `${virtualizer.getTotalSize()}px`,
- width: '100%',
- position: 'relative',
- }}
- className=""
- >
- {virtualizer.getVirtualItems().map((virtualRow) => {
- const node = filteredNodes[virtualRow.index];
+ {/* Virtualized List */}
+ <div ref={parentRef} className="grow overflow-auto rounded-b-lg border border-t-0">
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: '100%',
+ position: 'relative'
+ }}
+ className=""
+ >
+ {virtualizer.getVirtualItems().map((virtualRow) => {
+ const node = filteredNodes[virtualRow.index]
- return (
- <div
- key={node.id}
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- width: '100%',
- height: `${virtualRow.size}px`,
- transform: `translateY(${virtualRow.start}px)`,
- }}
- className="hover:bg-muted/40"
- >
- <NodeItem
- node={node}
- onNodeClick={onNodeClick}
- isSelected={isNodeSelected(node.id)}
- onSelectionChange={handleNodeSelectionChange}
- />
- </div>
- );
- })}
- </div>
- </div>
+ return (
+ <div
+ key={node.id}
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ height: `${virtualRow.size}px`,
+ transform: `translateY(${virtualRow.start}px)`
+ }}
+ className="hover:bg-muted/40"
+ >
+ <NodeItem
+ node={node}
+ onNodeClick={onNodeClick}
+ isSelected={isNodeSelected(node.id)}
+ onSelectionChange={handleNodeSelectionChange}
+ />
+ </div>
+ )
+ })}
</div>
- );
+ </div>
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/components/table/relationships-view.tsx b/flowsint-app/src/renderer/src/components/table/relationships-view.tsx
index 450f654a..dbf5995c 100644
--- a/flowsint-app/src/renderer/src/components/table/relationships-view.tsx
+++ b/flowsint-app/src/renderer/src/components/table/relationships-view.tsx
@@ -1,294 +1,303 @@
-import { useQuery } from "@tanstack/react-query";
-import { useParams } from "@tanstack/react-router";
-import { sketchService } from "@/api/sketch-service";
-import { useGraphStore } from "@/stores/graph-store";
-import { useVirtualizer } from "@tanstack/react-virtual";
-import { useRef, useState, useMemo, useCallback } from "react";
-import { Input } from "@/components/ui/input";
-import { Badge } from "@/components/ui/badge";
-import { Card, CardContent } from "@/components/ui/card";
-import { Search, ArrowRight, Users, Link, Filter } from "lucide-react";
-import { Skeleton } from "@/components/ui/skeleton";
-import { useIcon } from "@/hooks/use-icon";
+import { useQuery } from '@tanstack/react-query'
+import { useParams } from '@tanstack/react-router'
+import { sketchService } from '@/api/sketch-service'
+import { useGraphStore } from '@/stores/graph-store'
+import { useVirtualizer } from '@tanstack/react-virtual'
+import { useRef, useState, useMemo, useCallback } from 'react'
+import { Input } from '@/components/ui/input'
+import { Badge } from '@/components/ui/badge'
+import { Card, CardContent } from '@/components/ui/card'
+import { Search, ArrowRight, Users, Link, Filter } from 'lucide-react'
+import { Skeleton } from '@/components/ui/skeleton'
+import { useIcon } from '@/hooks/use-icon'
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { CopyButton } from "../copy";
-import { RelationshipType } from "@/types";
-import { GraphNode } from '@/types';
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select'
+import { CopyButton } from '../copy'
+import { RelationshipType } from '@/types'
+import { GraphNode } from '@/types'
-
-const ITEM_HEIGHT = 67; // Balanced spacing between items (55px card + 12px padding)
+const ITEM_HEIGHT = 67 // Balanced spacing between items (55px card + 12px padding)
// Separate component for relationship item to avoid hook order issues
interface RelationshipItemProps {
- relationship: RelationshipType;
- style: React.CSSProperties;
- onNodeClick: (node: GraphNode) => void
+ relationship: RelationshipType
+ style: React.CSSProperties
+ onNodeClick: (node: GraphNode) => void
}
function RelationshipItem({ relationship, style, onNodeClick }: RelationshipItemProps) {
- const SourceIcon = useIcon(relationship.source.data?.type, relationship.source.data?.src);
- const TargetIcon = useIcon(relationship.target.data?.type, relationship.target.data?.src);
+ const SourceIcon = useIcon(relationship.source.data?.type, relationship.source.data?.src)
+ const TargetIcon = useIcon(relationship.target.data?.type, relationship.target.data?.src)
- const handleNodeClickSource = useCallback(() => {
- onNodeClick(relationship.source)
- }, [])
- const handleNodeClickTarget = useCallback(() => {
- onNodeClick(relationship.target)
- }, [])
+ const handleNodeClickSource = useCallback(() => {
+ onNodeClick(relationship.source)
+ }, [])
+ const handleNodeClickTarget = useCallback(() => {
+ onNodeClick(relationship.target)
+ }, [])
- return (
- <div style={style} className="px-4 pb-2">
- <Card className="h-[55px] hover:shadow-md transition-shadow duration-200 p-0">
- <CardContent className="p-3 h-[55px] flex items-center gap-2 min-w-0">
- {/* Source Node */}
- <div className="flex items-center gap-2 flex-1 min-w-0">
- <div className="flex items-center justify-center w-8 h-8 rounded-full bg-muted flex-shrink-0">
- <SourceIcon className="h-4 w-4" />
- </div>
- <button onClick={handleNodeClickSource} className="font-medium text-sm hover:text-primary hover:underline cursor-pointer text-left max-w-full">
- <span className="block truncate">
- {relationship.source.data?.label ?? relationship.source.id}
- </span>
- </button>
- <CopyButton content={relationship.source.data?.label ?? relationship.source.id} />
- </div>
+ return (
+ <div style={style} className="px-4 pb-2">
+ <Card className="h-[55px] hover:shadow-md transition-shadow duration-200 p-0">
+ <CardContent className="p-3 h-[55px] flex items-center gap-2 min-w-0">
+ {/* Source Node */}
+ <div className="flex items-center gap-2 flex-1 min-w-0">
+ <div className="flex items-center justify-center w-8 h-8 rounded-full bg-muted flex-shrink-0">
+ <SourceIcon className="h-4 w-4" />
+ </div>
+ <button
+ onClick={handleNodeClickSource}
+ className="font-medium text-sm hover:text-primary hover:underline cursor-pointer text-left max-w-full"
+ >
+ <span className="block truncate">
+ {relationship.source.data?.label ?? relationship.source.id}
+ </span>
+ </button>
+ <CopyButton content={relationship.source.data?.label ?? relationship.source.id} />
+ </div>
- {/* Relationship Arrow */}
- <div className="flex items-center justify-center px-2 flex-shrink-0 min-w-0 grow">
- <div className="flex items-center gap-1 text-xs text-muted-foreground">
- <div className="h-px bg-muted-foreground/30 flex-1"></div>
- <span className="px-2 py-1 bg-muted/50 rounded-sm truncate">
- {relationship.edge.label}
- </span>
- <ArrowRight className="h-3 w-3 text-muted-foreground/50" />
- </div>
- </div>
+ {/* Relationship Arrow */}
+ <div className="flex items-center justify-center px-2 flex-shrink-0 min-w-0 grow">
+ <div className="flex items-center gap-1 text-xs text-muted-foreground">
+ <div className="h-px bg-muted-foreground/30 flex-1"></div>
+ <span className="px-2 py-1 bg-muted/50 rounded-sm truncate">
+ {relationship.edge.label}
+ </span>
+ <ArrowRight className="h-3 w-3 text-muted-foreground/50" />
+ </div>
+ </div>
- {/* Target Node */}
- <div className="flex items-center gap-2 flex-1 justify-end min-w-0 truncate text-ellipsis">
- <CopyButton content={relationship.target.data?.label ?? relationship.target.id} />
- <button onClick={handleNodeClickTarget} className="font-medium text-sm hover:text-primary hover:underline cursor-pointer max-w-full text-right">
- <span className="block truncate">
- {relationship.target.data?.label || relationship.target.id}
- </span>
- </button>
- <div className="flex items-center justify-center w-8 h-8 rounded-full bg-muted flex-shrink-0">
- <TargetIcon className="h-4 w-4" />
- </div>
- </div>
- </CardContent>
- </Card>
- </div>
- );
+ {/* Target Node */}
+ <div className="flex items-center gap-2 flex-1 justify-end min-w-0 truncate text-ellipsis">
+ <CopyButton content={relationship.target.data?.label ?? relationship.target.id} />
+ <button
+ onClick={handleNodeClickTarget}
+ className="font-medium text-sm hover:text-primary hover:underline cursor-pointer max-w-full text-right"
+ >
+ <span className="block truncate">
+ {relationship.target.data?.label || relationship.target.id}
+ </span>
+ </button>
+ <div className="flex items-center justify-center w-8 h-8 rounded-full bg-muted flex-shrink-0">
+ <TargetIcon className="h-4 w-4" />
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ )
}
export default function RelationshipsTable() {
- const { id: sketchId } = useParams({ from: "/_auth/dashboard/investigations/$investigationId/$type/$id" })
- const { data: relationships, isLoading } = useQuery({
- queryKey: ["graph", 'relationships_view', sketchId],
- enabled: Boolean(sketchId),
- queryFn: () => sketchService.getGraphDataById(sketchId as string, true),
- });
-
- const [searchQuery, setSearchQuery] = useState("");
- const [selectedType, setSelectedType] = useState<string>("all");
- const parentRef = useRef<HTMLDivElement>(null);
- const setCurrentNode = useGraphStore(s => s.setCurrentNode)
- // const setOpenNodeEditorModal = useGraphStore(s => s.setOpenNodeEditorModal)
-
- const onNodeClick = useCallback((node: GraphNode) => {
- setCurrentNode(node)
- // setOpenNodeEditorModal(true)
- }, [setCurrentNode,
- // setOpenNodeEditorModal
- ])
+ const { id: sketchId } = useParams({
+ from: '/_auth/dashboard/investigations/$investigationId/$type/$id'
+ })
+ const { data: relationships, isLoading } = useQuery({
+ queryKey: ['graph', 'relationships_view', sketchId],
+ enabled: Boolean(sketchId),
+ queryFn: () => sketchService.getGraphDataById(sketchId as string, true)
+ })
+ const [searchQuery, setSearchQuery] = useState('')
+ const [selectedType, setSelectedType] = useState<string>('all')
+ const parentRef = useRef<HTMLDivElement>(null)
+ const setCurrentNode = useGraphStore((s) => s.setCurrentNode)
+ // const setOpenNodeEditorModal = useGraphStore(s => s.setOpenNodeEditorModal)
- // Filter relationships based on search and type
- const filteredRelationships = useMemo(() => {
- if (!relationships) return [];
+ const onNodeClick = useCallback(
+ (node: GraphNode) => {
+ setCurrentNode(node)
+ // setOpenNodeEditorModal(true)
+ },
+ [
+ setCurrentNode
+ // setOpenNodeEditorModal
+ ]
+ )
- return relationships.filter((rel: RelationshipType) => {
- const matchesSearch = searchQuery === "" ||
- rel.source.data?.label?.toLowerCase().includes(searchQuery.toLowerCase()) ||
- rel.target.data?.label?.toLowerCase().includes(searchQuery.toLowerCase()) ||
- rel.edge.label?.toLowerCase().includes(searchQuery.toLowerCase());
+ // Filter relationships based on search and type
+ const filteredRelationships = useMemo(() => {
+ if (!relationships) return []
- const matchesType = selectedType === "all" ||
- rel.source.data?.type === selectedType ||
- rel.target.data?.type === selectedType;
+ return relationships.filter((rel: RelationshipType) => {
+ const matchesSearch =
+ searchQuery === '' ||
+ rel.source.data?.label?.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ rel.target.data?.label?.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ rel.edge.label?.toLowerCase().includes(searchQuery.toLowerCase())
- return matchesSearch && matchesType;
- });
- }, [relationships, searchQuery, selectedType]);
+ const matchesType =
+ selectedType === 'all' ||
+ rel.source.data?.type === selectedType ||
+ rel.target.data?.type === selectedType
- // Get unique node types for filter
- const nodeTypes = useMemo(() => {
- if (!relationships) return [];
- const types = new Set<string>();
- relationships.forEach((rel: RelationshipType) => {
- if (rel.source.data?.type) types.add(rel.source.data.type);
- if (rel.target.data?.type) types.add(rel.target.data.type);
- });
- return Array.from(types).sort();
- }, [relationships]);
+ return matchesSearch && matchesType
+ })
+ }, [relationships, searchQuery, selectedType])
- const virtualizer = useVirtualizer({
- count: filteredRelationships.length,
- getScrollElement: () => parentRef.current,
- estimateSize: () => ITEM_HEIGHT,
- overscan: 5,
- });
+ // Get unique node types for filter
+ const nodeTypes = useMemo(() => {
+ if (!relationships) return []
+ const types = new Set<string>()
+ relationships.forEach((rel: RelationshipType) => {
+ if (rel.source.data?.type) types.add(rel.source.data.type)
+ if (rel.target.data?.type) types.add(rel.target.data.type)
+ })
+ return Array.from(types).sort()
+ }, [relationships])
- if (isLoading) {
- return (
- <div className="w-full p-4 px-6 space-y-4 pt-18">
- {/* Header with stats */}
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h2 className="text-2xl font-bold tracking-tight">Relationships</h2>
- <p className="text-muted-foreground">
- <Skeleton className="h-4 w-32 inline-block" />
- </p>
- </div>
- <Badge variant="secondary" className="flex items-center gap-2">
- <Users className="h-4 w-4" />
- <Skeleton className="h-4 w-8" />
- </Badge>
- </div>
+ const virtualizer = useVirtualizer({
+ count: filteredRelationships.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => ITEM_HEIGHT,
+ overscan: 5
+ })
- {/* Search and Filter */}
- <div className="flex gap-4">
- <div className="relative flex-1">
- <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="Search relationships, nodes, or types..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-10"
- disabled
- />
- </div>
- <Select value={selectedType} onValueChange={setSelectedType} disabled>
- <SelectTrigger className="w-48">
- <Filter className="h-4 w-4 mr-2 text-muted-foreground" />
- <SelectValue placeholder="Filter by type" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">All Types</SelectItem>
- </SelectContent>
- </Select>
- </div>
+ if (isLoading) {
+ return (
+ <div className="w-full p-4 px-6 space-y-4 pt-18">
+ {/* Header with stats */}
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <h2 className="text-2xl font-bold tracking-tight">Relationships</h2>
+ <p className="text-muted-foreground">
+ <Skeleton className="h-4 w-32 inline-block" />
+ </p>
+ </div>
+ <Badge variant="secondary" className="flex items-center gap-2">
+ <Users className="h-4 w-4" />
+ <Skeleton className="h-4 w-8" />
+ </Badge>
+ </div>
- {/* Skeleton List */}
- <div className="grow overflow-auto py-4 rounded-lg border">
- <div className="space-y-2 px-4">
- {Array.from({ length: 8 }).map((_, i) => (
- <Skeleton key={i} className="h-[55px] w-full" />
- ))}
- </div>
- </div>
- </div>
- );
- }
+ {/* Search and Filter */}
+ <div className="flex gap-4">
+ <div className="relative flex-1">
+ <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder="Search relationships, nodes, or types..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-10"
+ disabled
+ />
+ </div>
+ <Select value={selectedType} onValueChange={setSelectedType} disabled>
+ <SelectTrigger className="w-48">
+ <Filter className="h-4 w-4 mr-2 text-muted-foreground" />
+ <SelectValue placeholder="Filter by type" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All Types</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
- if (!relationships || relationships.length === 0) {
- return (
- <div className="w-full pt-18 flex items-center justify-center h-full">
- <div className="text-center space-y-4">
- <Link className="mx-auto h-12 w-12 text-muted-foreground" />
- <div>
- <h3 className="text-lg font-semibold">No relationships found</h3>
- <p className="text-muted-foreground">This sketch doesn't have any relationships yet.</p>
- </div>
- </div>
- </div>
- );
- }
+ {/* Skeleton List */}
+ <div className="grow overflow-auto py-4 rounded-lg border">
+ <div className="space-y-2 px-4">
+ {Array.from({ length: 8 }).map((_, i) => (
+ <Skeleton key={i} className="h-[55px] w-full" />
+ ))}
+ </div>
+ </div>
+ </div>
+ )
+ }
+ if (!relationships || relationships.length === 0) {
return (
- <div className="w-full grow flex flex-col pt-18 space-y-4 p-4 px-6">
- {/* Header with stats */}
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h2 className="text-2xl font-bold tracking-tight">Relationships</h2>
- <p className="text-muted-foreground">
- {filteredRelationships.length} of {relationships.length} relationships
- </p>
- </div>
- <Badge variant="secondary" className="flex items-center gap-2">
- <Users className="h-4 w-4" />
- {relationships.length} total
- </Badge>
- </div>
+ <div className="w-full pt-18 flex items-center justify-center h-full">
+ <div className="text-center space-y-4">
+ <Link className="mx-auto h-12 w-12 text-muted-foreground" />
+ <div>
+ <h3 className="text-lg font-semibold">No relationships found</h3>
+ <p className="text-muted-foreground">This sketch doesn't have any relationships yet.</p>
+ </div>
+ </div>
+ </div>
+ )
+ }
- {/* Search and Filter */}
- <div className="flex gap-4">
- <div className="relative flex-1">
- <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
- <Input
- placeholder="Search relationships, nodes, or types..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="pl-10"
- />
- </div>
- <Select value={selectedType} onValueChange={setSelectedType}>
- <SelectTrigger className="w-48">
- <Filter className="h-4 w-4 mr-2 text-muted-foreground" />
- <SelectValue placeholder="Filter by type" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">All Types</SelectItem>
- {nodeTypes.map((type) => (
- <SelectItem key={type} value={type}>
- <span className="capitalize">{type}</span>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
+ return (
+ <div className="w-full grow flex flex-col pt-18 space-y-4 p-4 px-6">
+ {/* Header with stats */}
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <h2 className="text-2xl font-bold tracking-tight">Relationships</h2>
+ <p className="text-muted-foreground">
+ {filteredRelationships.length} of {relationships.length} relationships
+ </p>
+ </div>
+ <Badge variant="secondary" className="flex items-center gap-2">
+ <Users className="h-4 w-4" />
+ {relationships.length} total
+ </Badge>
+ </div>
- {/* Virtualized List */}
- <div
- ref={parentRef}
- className="grow overflow-auto py-4 rounded-lg border"
- >
- <div
- style={{
- height: `${virtualizer.getTotalSize()}px`,
- width: '100%',
- position: 'relative',
- }}
- className="space-y-2"
- >
- {virtualizer.getVirtualItems().map((virtualRow) => {
- const relationship = filteredRelationships[virtualRow.index];
+ {/* Search and Filter */}
+ <div className="flex gap-4">
+ <div className="relative flex-1">
+ <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
+ <Input
+ placeholder="Search relationships, nodes, or types..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="pl-10"
+ />
+ </div>
+ <Select value={selectedType} onValueChange={setSelectedType}>
+ <SelectTrigger className="w-48">
+ <Filter className="h-4 w-4 mr-2 text-muted-foreground" />
+ <SelectValue placeholder="Filter by type" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All Types</SelectItem>
+ {nodeTypes.map((type) => (
+ <SelectItem key={type} value={type}>
+ <span className="capitalize">{type}</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
- return (
- <RelationshipItem
- key={virtualRow.index}
- relationship={relationship}
- onNodeClick={onNodeClick}
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- width: '100%',
- height: `${virtualRow.size}px`,
- transform: `translateY(${virtualRow.start}px)`,
- }}
- />
- );
- })}
- </div>
- </div>
+ {/* Virtualized List */}
+ <div ref={parentRef} className="grow overflow-auto py-4 rounded-lg border">
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: '100%',
+ position: 'relative'
+ }}
+ className="space-y-2"
+ >
+ {virtualizer.getVirtualItems().map((virtualRow) => {
+ const relationship = filteredRelationships[virtualRow.index]
+
+ return (
+ <RelationshipItem
+ key={virtualRow.index}
+ relationship={relationship}
+ onNodeClick={onNodeClick}
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ width: '100%',
+ height: `${virtualRow.size}px`,
+ transform: `translateY(${virtualRow.start}px)`
+ }}
+ />
+ )
+ })}
</div>
- );
-}
\ No newline at end of file
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/theme-provider.tsx b/flowsint-app/src/renderer/src/components/theme-provider.tsx
index c19e7333..5a67c0ab 100644
--- a/flowsint-app/src/renderer/src/components/theme-provider.tsx
+++ b/flowsint-app/src/renderer/src/components/theme-provider.tsx
@@ -1,73 +1,71 @@
-import { createContext, useContext, useEffect, useState } from "react"
+import { createContext, useContext, useEffect, useState } from 'react'
-type Theme = "dark" | "light" | "system"
+type Theme = 'dark' | 'light' | 'system'
type ThemeProviderProps = {
- children: React.ReactNode
- defaultTheme?: Theme
- storageKey?: string
+ children: React.ReactNode
+ defaultTheme?: Theme
+ storageKey?: string
}
type ThemeProviderState = {
- theme: Theme
- setTheme: (theme: Theme) => void
+ theme: Theme
+ setTheme: (theme: Theme) => void
}
const initialState: ThemeProviderState = {
- theme: "system",
- setTheme: () => null,
+ theme: 'system',
+ setTheme: () => null
}
const ThemeProviderContext = createContext<ThemeProviderState>(initialState)
export function ThemeProvider({
- children,
- defaultTheme = "system",
- storageKey = "vite-ui-theme",
- ...props
+ children,
+ defaultTheme = 'system',
+ storageKey = 'vite-ui-theme',
+ ...props
}: ThemeProviderProps) {
- const [theme, setTheme] = useState<Theme>(
- () => (localStorage.getItem(storageKey) as Theme) || defaultTheme
- )
-
- useEffect(() => {
- const root = window.document.documentElement
-
- root.classList.remove("light", "dark")
-
- if (theme === "system") {
- const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
- .matches
- ? "dark"
- : "light"
-
- root.classList.add(systemTheme)
- return
- }
-
- root.classList.add(theme)
- }, [theme])
-
- const value = {
- theme,
- setTheme: (theme: Theme) => {
- localStorage.setItem(storageKey, theme)
- setTheme(theme)
- },
+ const [theme, setTheme] = useState<Theme>(
+ () => (localStorage.getItem(storageKey) as Theme) || defaultTheme
+ )
+
+ useEffect(() => {
+ const root = window.document.documentElement
+
+ root.classList.remove('light', 'dark')
+
+ if (theme === 'system') {
+ const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
+ ? 'dark'
+ : 'light'
+
+ root.classList.add(systemTheme)
+ return
+ }
+
+ root.classList.add(theme)
+ }, [theme])
+
+ const value = {
+ theme,
+ setTheme: (theme: Theme) => {
+ localStorage.setItem(storageKey, theme)
+ setTheme(theme)
}
+ }
- return (
- <ThemeProviderContext.Provider {...props} value={value}>
- {children}
- </ThemeProviderContext.Provider>
- )
+ return (
+ <ThemeProviderContext.Provider {...props} value={value}>
+ {children}
+ </ThemeProviderContext.Provider>
+ )
}
export const useTheme = () => {
- const context = useContext(ThemeProviderContext)
+ const context = useContext(ThemeProviderContext)
- if (context === undefined)
- throw new Error("useTheme must be used within a ThemeProvider")
+ if (context === undefined) throw new Error('useTheme must be used within a ThemeProvider')
- return context
+ return context
}
diff --git a/flowsint-app/src/renderer/src/components/tool-card.tsx b/flowsint-app/src/renderer/src/components/tool-card.tsx
index e4a7bb3e..8f36893e 100644
--- a/flowsint-app/src/renderer/src/components/tool-card.tsx
+++ b/flowsint-app/src/renderer/src/components/tool-card.tsx
@@ -1,57 +1,67 @@
-import { Terminal, Key } from "lucide-react"
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
-import { Badge } from "@/components/ui/badge"
-import type { Tool } from "@/types"
-import { cn } from "@/lib/utils"
-import { Avatar, AvatarImage } from "./ui/avatar"
+import { Terminal, Key } from 'lucide-react'
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
+import { Badge } from '@/components/ui/badge'
+import type { Tool } from '@/types'
+import { cn } from '@/lib/utils'
+import { Avatar, AvatarImage } from './ui/avatar'
interface ToolCardProps {
- tool: Tool
+ tool: Tool
}
export function ToolCard({ tool }: ToolCardProps) {
- return (
- <Card className={cn("flex flex-col shadow-none bg-card rounded-md relative", tool.active ? "opacity-100" : "opacity-70")}>
- <CardHeader >
- <CardTitle className="flex items-center gap-2 mt-4">
- {tool.avatar ?
- <Avatar
- className={cn(
- 'h-8 w-8',
- "border-2 border bg-background relative",
- "transition-transform",
- "ring-0 ring-offset-0",
- )}
- >
- <AvatarImage src={tool.avatar} alt={tool.name} />
- </Avatar> :
- <Terminal className="h-5 w-5" />}
- {tool.name}
- </CardTitle>
- </CardHeader>
- <CardContent className="flex-1">
- {tool.description && <p className="text-sm text-muted-foreground">{tool.description}</p>}
- </CardContent>
- <div className="absolute top-2 right-2 flex flex-row items-center gap-1">
- {tool.apiKeyRequired && (
- <Badge
- className={
- tool.apiKeyRequired === "paid"
- ? "bg-yellow-500/15 text-yellow-700 text-xs shadow-none border-yellow-500/30 flex items-center gap-1"
- : "bg-blue-500/15 text-blue-700 text-xs shadow-none border-blue-500/30 flex items-center gap-1"
- }
- >
- <Key className="h-3 w-3 mr-1" />
- {tool.apiKeyRequired === "paid" ? "Paid API Key" : "Free API Key"}
- </Badge>
- )}
- {tool.active ? (
- <Badge className="bg-green-500/15 text-green-500 text-xs shadow-none border-green-500/30">Active</Badge>
- ) : (
- <Badge className="bg-orange-500/15 text-orange-500 text-xs shadow-none border-orange-500/30">Coming soon</Badge>
- )}
- </div>
- </Card >
- )
+ return (
+ <Card
+ className={cn(
+ 'flex flex-col shadow-none bg-card rounded-md relative',
+ tool.active ? 'opacity-100' : 'opacity-70'
+ )}
+ >
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2 mt-4">
+ {tool.avatar ? (
+ <Avatar
+ className={cn(
+ 'h-8 w-8',
+ 'border-2 border bg-background relative',
+ 'transition-transform',
+ 'ring-0 ring-offset-0'
+ )}
+ >
+ <AvatarImage src={tool.avatar} alt={tool.name} />
+ </Avatar>
+ ) : (
+ <Terminal className="h-5 w-5" />
+ )}
+ {tool.name}
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="flex-1">
+ {tool.description && <p className="text-sm text-muted-foreground">{tool.description}</p>}
+ </CardContent>
+ <div className="absolute top-2 right-2 flex flex-row items-center gap-1">
+ {tool.apiKeyRequired && (
+ <Badge
+ className={
+ tool.apiKeyRequired === 'paid'
+ ? 'bg-yellow-500/15 text-yellow-700 text-xs shadow-none border-yellow-500/30 flex items-center gap-1'
+ : 'bg-blue-500/15 text-blue-700 text-xs shadow-none border-blue-500/30 flex items-center gap-1'
+ }
+ >
+ <Key className="h-3 w-3 mr-1" />
+ {tool.apiKeyRequired === 'paid' ? 'Paid API Key' : 'Free API Key'}
+ </Badge>
+ )}
+ {tool.active ? (
+ <Badge className="bg-green-500/15 text-green-500 text-xs shadow-none border-green-500/30">
+ Active
+ </Badge>
+ ) : (
+ <Badge className="bg-orange-500/15 text-orange-500 text-xs shadow-none border-orange-500/30">
+ Coming soon
+ </Badge>
+ )}
+ </div>
+ </Card>
+ )
}
-
diff --git a/flowsint-app/src/renderer/src/components/type-badge.tsx b/flowsint-app/src/renderer/src/components/type-badge.tsx
index 0749ac49..57e941d0 100644
--- a/flowsint-app/src/renderer/src/components/type-badge.tsx
+++ b/flowsint-app/src/renderer/src/components/type-badge.tsx
@@ -1,26 +1,28 @@
-import { Badge } from "@/components/ui/badge"
-import { cn, hexToRgba } from "@/lib/utils"
-import { useNodesDisplaySettings } from "@/stores/node-display-settings"
-import { memo } from "react"
+import { Badge } from '@/components/ui/badge'
+import { cn, hexToRgba } from '@/lib/utils'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
+import { memo } from 'react'
type TypeBadgeProps = {
- type: string
- className?: string
- children?: React.ReactNode
+ type: string
+ className?: string
+ children?: React.ReactNode
}
function TypeBadgeComponent({ type, children, className }: TypeBadgeProps) {
- const colors = useNodesDisplaySettings(s => s.colors)
- const color = colors[type as keyof typeof colors] || "bg-gray-100 text-gray-800 hover:bg-gray-100/80 dark:bg-gray-800/50 dark:text-gray-300 dark:hover:bg-gray-800/60"
- return (
- <Badge
- variant="outline"
- style={{ backgroundColor: hexToRgba(color, .5) }}
- className={cn("font-medium border-transparent", className)}
- >
- {children ?? type}
- </Badge>
- )
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ const color =
+ colors[type as keyof typeof colors] ||
+ 'bg-gray-100 text-gray-800 hover:bg-gray-100/80 dark:bg-gray-800/50 dark:text-gray-300 dark:hover:bg-gray-800/60'
+ return (
+ <Badge
+ variant="outline"
+ style={{ backgroundColor: hexToRgba(color, 0.5) }}
+ className={cn('font-medium border-transparent', className)}
+ >
+ {children ?? type}
+ </Badge>
+ )
}
export const TypeBadge = memo(TypeBadgeComponent)
diff --git a/flowsint-app/src/renderer/src/components/ui/accordion.tsx b/flowsint-app/src/renderer/src/components/ui/accordion.tsx
index c03dd29f..39346099 100644
--- a/flowsint-app/src/renderer/src/components/ui/accordion.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/accordion.tsx
@@ -1,12 +1,10 @@
-import * as React from "react"
-import * as AccordionPrimitive from "@radix-ui/react-accordion"
-import { ChevronDownIcon } from "lucide-react"
+import * as React from 'react'
+import * as AccordionPrimitive from '@radix-ui/react-accordion'
+import { ChevronDownIcon } from 'lucide-react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Accordion({
- ...props
-}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
+function Accordion({ ...props }: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}
@@ -17,7 +15,7 @@ function AccordionItem({
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
- className={cn("border-b last:border-b-0", className)}
+ className={cn('border-b last:border-b-0', className)}
{...props}
/>
)
@@ -33,7 +31,7 @@ function AccordionTrigger({
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
- "focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-center justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
+ 'focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-center justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180',
className
)}
{...props}
@@ -56,7 +54,7 @@ function AccordionContent({
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
- <div className={cn("pt-0 pb-4", className)}>{children}</div>
+ <div className={cn('pt-0 pb-4', className)}>{children}</div>
</AccordionPrimitive.Content>
)
}
diff --git a/flowsint-app/src/renderer/src/components/ui/alert-dialog.tsx b/flowsint-app/src/renderer/src/components/ui/alert-dialog.tsx
index 5885897a..50be0225 100644
--- a/flowsint-app/src/renderer/src/components/ui/alert-dialog.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/alert-dialog.tsx
@@ -1,30 +1,21 @@
+import * as React from 'react'
+import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'
-import * as React from "react"
-import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
+import { cn } from '@/lib/utils'
+import { buttonVariants } from '@/components/ui/button'
-import { cn } from "@/lib/utils"
-import { buttonVariants } from "@/components/ui/button"
-
-function AlertDialog({
- ...props
-}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
+function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
- return (
- <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
- )
+ return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
}
-function AlertDialogPortal({
- ...props
-}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
- return (
- <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
- )
+function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
+ return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
}
function AlertDialogOverlay({
@@ -35,7 +26,7 @@ function AlertDialogOverlay({
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
className
)}
{...props}
@@ -53,7 +44,7 @@ function AlertDialogContent({
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
- "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
+ 'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg',
className
)}
{...props}
@@ -62,30 +53,21 @@ function AlertDialogContent({
)
}
-function AlertDialogHeader({
- className,
- ...props
-}: React.ComponentProps<"div">) {
+function AlertDialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-dialog-header"
- className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
+ className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
{...props}
/>
)
}
-function AlertDialogFooter({
- className,
- ...props
-}: React.ComponentProps<"div">) {
+function AlertDialogFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-dialog-footer"
- className={cn(
- "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
- className
- )}
+ className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
{...props}
/>
)
@@ -98,7 +80,7 @@ function AlertDialogTitle({
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
- className={cn("text-lg font-semibold", className)}
+ className={cn('text-lg font-semibold', className)}
{...props}
/>
)
@@ -111,7 +93,7 @@ function AlertDialogDescription({
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
- className={cn("text-muted-foreground text-sm", className)}
+ className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
)
@@ -121,12 +103,7 @@ function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
- return (
- <AlertDialogPrimitive.Action
- className={cn(buttonVariants(), className)}
- {...props}
- />
- )
+ return <AlertDialogPrimitive.Action className={cn(buttonVariants(), className)} {...props} />
}
function AlertDialogCancel({
@@ -135,7 +112,7 @@ function AlertDialogCancel({
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
- className={cn(buttonVariants({ variant: "outline" }), className)}
+ className={cn(buttonVariants({ variant: 'outline' }), className)}
{...props}
/>
)
@@ -152,5 +129,5 @@ export {
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
- AlertDialogCancel,
+ AlertDialogCancel
}
diff --git a/flowsint-app/src/renderer/src/components/ui/alert.tsx b/flowsint-app/src/renderer/src/components/ui/alert.tsx
index 14213546..75e24e8c 100644
--- a/flowsint-app/src/renderer/src/components/ui/alert.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/alert.tsx
@@ -1,21 +1,21 @@
-import * as React from "react"
-import { cva, type VariantProps } from "class-variance-authority"
+import * as React from 'react'
+import { cva, type VariantProps } from 'class-variance-authority'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
const alertVariants = cva(
- "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
+ 'relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current',
{
variants: {
variant: {
- default: "bg-card text-card-foreground",
+ default: 'bg-card text-card-foreground',
destructive:
- "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
- },
+ 'text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90'
+ }
},
defaultVariants: {
- variant: "default",
- },
+ variant: 'default'
+ }
}
)
@@ -23,7 +23,7 @@ function Alert({
className,
variant,
...props
-}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
+}: React.ComponentProps<'div'> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
@@ -34,28 +34,22 @@ function Alert({
)
}
-function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
+function AlertTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-title"
- className={cn(
- "col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
- className
- )}
+ className={cn('col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight', className)}
{...props}
/>
)
}
-function AlertDescription({
- className,
- ...props
-}: React.ComponentProps<"div">) {
+function AlertDescription({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="alert-description"
className={cn(
- "text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
+ 'text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/aspect-ratio.tsx b/flowsint-app/src/renderer/src/components/ui/aspect-ratio.tsx
index 9b491fb8..da85b938 100644
--- a/flowsint-app/src/renderer/src/components/ui/aspect-ratio.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/aspect-ratio.tsx
@@ -1,8 +1,6 @@
-import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
+import * as AspectRatioPrimitive from '@radix-ui/react-aspect-ratio'
-function AspectRatio({
- ...props
-}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
+function AspectRatio({ ...props }: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
}
diff --git a/flowsint-app/src/renderer/src/components/ui/avatar.tsx b/flowsint-app/src/renderer/src/components/ui/avatar.tsx
index fe146254..1dda4c79 100644
--- a/flowsint-app/src/renderer/src/components/ui/avatar.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/avatar.tsx
@@ -1,33 +1,23 @@
+import * as React from 'react'
+import * as AvatarPrimitive from '@radix-ui/react-avatar'
-import * as React from "react"
-import * as AvatarPrimitive from "@radix-ui/react-avatar"
+import { cn } from '@/lib/utils'
-import { cn } from "@/lib/utils"
-
-function Avatar({
- className,
- ...props
-}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
+function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
- className={cn(
- "relative flex size-8 shrink-0 overflow-hidden rounded-full",
- className
- )}
+ className={cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', className)}
{...props}
/>
)
}
-function AvatarImage({
- className,
- ...props
-}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
+function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
- className={cn("aspect-square object-cover size-full", className)}
+ className={cn('aspect-square object-cover size-full', className)}
{...props}
/>
)
@@ -40,13 +30,9 @@ function AvatarFallback({
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
- className={cn(
- "bg-muted flex size-full items-center justify-center rounded-full",
- className
- )}
+ className={cn('bg-muted flex size-full items-center justify-center rounded-full', className)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback }
-
diff --git a/flowsint-app/src/renderer/src/components/ui/badge.tsx b/flowsint-app/src/renderer/src/components/ui/badge.tsx
index 02054139..c6e06f87 100644
--- a/flowsint-app/src/renderer/src/components/ui/badge.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/badge.tsx
@@ -1,27 +1,25 @@
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, type VariantProps } from "class-variance-authority"
+import * as React from 'react'
+import { Slot } from '@radix-ui/react-slot'
+import { cva, type VariantProps } from 'class-variance-authority'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
const badgeVariants = cva(
- "inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
+ 'inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden',
{
variants: {
variant: {
- default:
- "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
+ default: 'border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90',
secondary:
- "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
+ 'border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90',
destructive:
- "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
- outline:
- "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
- },
+ 'border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
+ outline: 'text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground'
+ }
},
defaultVariants: {
- variant: "default",
- },
+ variant: 'default'
+ }
}
)
@@ -30,17 +28,10 @@ function Badge({
variant,
asChild = false,
...props
-}: React.ComponentProps<"span"> &
- VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
- const Comp = asChild ? Slot : "span"
+}: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
+ const Comp = asChild ? Slot : 'span'
- return (
- <Comp
- data-slot="badge"
- className={cn(badgeVariants({ variant }), className)}
- {...props}
- />
- )
+ return <Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props} />
}
export { Badge, badgeVariants }
diff --git a/flowsint-app/src/renderer/src/components/ui/breadcrumb.tsx b/flowsint-app/src/renderer/src/components/ui/breadcrumb.tsx
index eb88f321..c9927121 100644
--- a/flowsint-app/src/renderer/src/components/ui/breadcrumb.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/breadcrumb.tsx
@@ -1,19 +1,19 @@
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { ChevronRight, MoreHorizontal } from "lucide-react"
+import * as React from 'react'
+import { Slot } from '@radix-ui/react-slot'
+import { ChevronRight, MoreHorizontal } from 'lucide-react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
+function Breadcrumb({ ...props }: React.ComponentProps<'nav'>) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
}
-function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
+function BreadcrumbList({ className, ...props }: React.ComponentProps<'ol'>) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
- "text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
+ 'text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5',
className
)}
{...props}
@@ -21,11 +21,11 @@ function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
)
}
-function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
+function BreadcrumbItem({ className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="breadcrumb-item"
- className={cn("inline-flex items-center gap-1.5", className)}
+ className={cn('inline-flex items-center gap-1.5', className)}
{...props}
/>
)
@@ -35,44 +35,40 @@ function BreadcrumbLink({
asChild,
className,
...props
-}: React.ComponentProps<"a"> & {
+}: React.ComponentProps<'a'> & {
asChild?: boolean
}) {
- const Comp = asChild ? Slot : "a"
+ const Comp = asChild ? Slot : 'a'
return (
<Comp
data-slot="breadcrumb-link"
- className={cn("hover:text-foreground transition-colors", className)}
+ className={cn('hover:text-foreground transition-colors', className)}
{...props}
/>
)
}
-function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
+function BreadcrumbPage({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
- className={cn("text-foreground font-normal", className)}
+ className={cn('text-foreground font-normal', className)}
{...props}
/>
)
}
-function BreadcrumbSeparator({
- children,
- className,
- ...props
-}: React.ComponentProps<"li">) {
+function BreadcrumbSeparator({ children, className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
- className={cn("[&>svg]:size-3.5", className)}
+ className={cn('[&>svg]:size-3.5', className)}
{...props}
>
{children ?? <ChevronRight />}
@@ -80,16 +76,13 @@ function BreadcrumbSeparator({
)
}
-function BreadcrumbEllipsis({
- className,
- ...props
-}: React.ComponentProps<"span">) {
+function BreadcrumbEllipsis({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
- className={cn("flex size-9 items-center justify-center", className)}
+ className={cn('flex size-9 items-center justify-center', className)}
{...props}
>
<MoreHorizontal className="size-4" />
@@ -105,5 +98,5 @@ export {
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
- BreadcrumbEllipsis,
+ BreadcrumbEllipsis
}
diff --git a/flowsint-app/src/renderer/src/components/ui/button.tsx b/flowsint-app/src/renderer/src/components/ui/button.tsx
index c914eabb..40e6a245 100644
--- a/flowsint-app/src/renderer/src/components/ui/button.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/button.tsx
@@ -1,37 +1,34 @@
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, type VariantProps } from "class-variance-authority"
+import * as React from 'react'
+import { Slot } from '@radix-ui/react-slot'
+import { cva, type VariantProps } from 'class-variance-authority'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
- default:
- "bg-primary text-white shadow-xs hover:bg-primary/90",
+ default: 'bg-primary text-white shadow-xs hover:bg-primary/90',
destructive:
- "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
+ 'bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60',
outline:
- "border shadow-xs hover:bg-accent hover:text-accent-foreground bg-background/80 hover:bg-background/90 backdrop-blur-sm",
- secondary:
- "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
- ghost:
- "hover:bg-muted hover:text-accent-foreground dark:hover:bg-muted",
- link: "text-primary underline-offset-4 hover:underline",
+ 'border shadow-xs hover:bg-accent hover:text-accent-foreground bg-background/80 hover:bg-background/90 backdrop-blur-sm',
+ secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80',
+ ghost: 'hover:bg-muted hover:text-accent-foreground dark:hover:bg-muted',
+ link: 'text-primary underline-offset-4 hover:underline'
},
size: {
- default: "h-9 px-4 py-2 has-[>svg]:px-3",
- sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
- lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
- icon: "size-9",
- },
+ default: 'h-9 px-4 py-2 has-[>svg]:px-3',
+ sm: 'h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5',
+ lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',
+ icon: 'size-9'
+ }
},
defaultVariants: {
- variant: "default",
- size: "default",
- },
+ variant: 'default',
+ size: 'default'
+ }
}
)
@@ -41,11 +38,11 @@ function Button({
size,
asChild = false,
...props
-}: React.ComponentProps<"button"> &
+}: React.ComponentProps<'button'> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
- const Comp = asChild ? Slot : "button"
+ const Comp = asChild ? Slot : 'button'
return (
<Comp
diff --git a/flowsint-app/src/renderer/src/components/ui/calendar.tsx b/flowsint-app/src/renderer/src/components/ui/calendar.tsx
index 3976ece8..c651d93d 100644
--- a/flowsint-app/src/renderer/src/components/ui/calendar.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/calendar.tsx
@@ -1,9 +1,9 @@
-import * as React from "react"
-import { ChevronLeft, ChevronRight } from "lucide-react"
-import { DayPicker } from "react-day-picker"
+import * as React from 'react'
+import { ChevronLeft, ChevronRight } from 'lucide-react'
+import { DayPicker } from 'react-day-picker'
-import { cn } from "@/lib/utils"
-import { buttonVariants } from "@/components/ui/button"
+import { cn } from '@/lib/utils'
+import { buttonVariants } from '@/components/ui/button'
function Calendar({
className,
@@ -14,56 +14,53 @@ function Calendar({
return (
<DayPicker
showOutsideDays={showOutsideDays}
- className={cn("p-3", className)}
+ className={cn('p-3', className)}
classNames={{
- months: "flex flex-col sm:flex-row gap-2",
- month: "flex flex-col gap-4",
- caption: "flex justify-center pt-1 relative items-center w-full",
- caption_label: "text-sm font-medium",
- nav: "flex items-center gap-1",
+ months: 'flex flex-col sm:flex-row gap-2',
+ month: 'flex flex-col gap-4',
+ caption: 'flex justify-center pt-1 relative items-center w-full',
+ caption_label: 'text-sm font-medium',
+ nav: 'flex items-center gap-1',
nav_button: cn(
- buttonVariants({ variant: "outline" }),
- "size-7 bg-transparent p-0 opacity-50 hover:opacity-100"
+ buttonVariants({ variant: 'outline' }),
+ 'size-7 bg-transparent p-0 opacity-50 hover:opacity-100'
),
- nav_button_previous: "absolute left-1",
- nav_button_next: "absolute right-1",
- table: "w-full border-collapse space-x-1",
- head_row: "flex",
- head_cell:
- "text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",
- row: "flex w-full mt-2",
+ nav_button_previous: 'absolute left-1',
+ nav_button_next: 'absolute right-1',
+ table: 'w-full border-collapse space-x-1',
+ head_row: 'flex',
+ head_cell: 'text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]',
+ row: 'flex w-full mt-2',
cell: cn(
- "relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md",
- props.mode === "range"
- ? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
- : "[&:has([aria-selected])]:rounded-md"
+ 'relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md',
+ props.mode === 'range'
+ ? '[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md'
+ : '[&:has([aria-selected])]:rounded-md'
),
day: cn(
- buttonVariants({ variant: "ghost" }),
- "size-8 p-0 font-normal aria-selected:opacity-100"
+ buttonVariants({ variant: 'ghost' }),
+ 'size-8 p-0 font-normal aria-selected:opacity-100'
),
day_range_start:
- "day-range-start aria-selected:bg-primary aria-selected:text-primary-foreground",
+ 'day-range-start aria-selected:bg-primary aria-selected:text-primary-foreground',
day_range_end:
- "day-range-end aria-selected:bg-primary aria-selected:text-primary-foreground",
+ 'day-range-end aria-selected:bg-primary aria-selected:text-primary-foreground',
day_selected:
- "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
- day_today: "bg-accent text-accent-foreground",
- day_outside:
- "day-outside text-muted-foreground aria-selected:text-muted-foreground",
- day_disabled: "text-muted-foreground opacity-50",
- day_range_middle:
- "aria-selected:bg-accent aria-selected:text-accent-foreground",
- day_hidden: "invisible",
- ...classNames,
+ 'bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground',
+ day_today: 'bg-accent text-accent-foreground',
+ day_outside: 'day-outside text-muted-foreground aria-selected:text-muted-foreground',
+ day_disabled: 'text-muted-foreground opacity-50',
+ day_range_middle: 'aria-selected:bg-accent aria-selected:text-accent-foreground',
+ day_hidden: 'invisible',
+ ...classNames
}}
components={{
IconLeft: ({ className, ...props }) => (
- <ChevronLeft className={cn("size-4", className)} {...props} />
+ <ChevronLeft className={cn('size-4', className)} {...props} />
),
IconRight: ({ className, ...props }) => (
- <ChevronRight className={cn("size-4", className)} {...props} />
- ),
+ <ChevronRight className={cn('size-4', className)} {...props} />
+ )
}}
{...props}
/>
diff --git a/flowsint-app/src/renderer/src/components/ui/card.tsx b/flowsint-app/src/renderer/src/components/ui/card.tsx
index 32f46430..f25d2236 100644
--- a/flowsint-app/src/renderer/src/components/ui/card.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/card.tsx
@@ -1,13 +1,13 @@
-import * as React from "react"
+import * as React from 'react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Card({ className, ...props }: React.ComponentProps<"div">) {
+function Card({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card"
className={cn(
- "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6",
+ 'bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6',
className
)}
{...props}
@@ -15,12 +15,12 @@ function Card({ className, ...props }: React.ComponentProps<"div">) {
)
}
-function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
+function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-header"
className={cn(
- "@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
+ '@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',
className
)}
{...props}
@@ -28,65 +28,48 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
)
}
-function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
+function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-title"
- className={cn("leading-none font-semibold", className)}
+ className={cn('leading-none font-semibold', className)}
{...props}
/>
)
}
-function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
+function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-description"
- className={cn("text-muted-foreground text-sm", className)}
+ className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
)
}
-function CardAction({ className, ...props }: React.ComponentProps<"div">) {
+function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-action"
- className={cn(
- "col-start-2 row-span-2 row-start-1 self-start justify-self-end",
- className
- )}
+ className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
{...props}
/>
)
}
-function CardContent({ className, ...props }: React.ComponentProps<"div">) {
- return (
- <div
- data-slot="card-content"
- className={cn("px-6", className)}
- {...props}
- />
- )
+function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
+ return <div data-slot="card-content" className={cn('px-6', className)} {...props} />
}
-function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
+function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-footer"
- className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
+ className={cn('flex items-center px-6 [.border-t]:pt-6', className)}
{...props}
/>
)
}
-export {
- Card,
- CardHeader,
- CardFooter,
- CardTitle,
- CardAction,
- CardDescription,
- CardContent,
-}
+export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent }
diff --git a/flowsint-app/src/renderer/src/components/ui/carousel.tsx b/flowsint-app/src/renderer/src/components/ui/carousel.tsx
index 278a19d7..a6bd56a2 100644
--- a/flowsint-app/src/renderer/src/components/ui/carousel.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/carousel.tsx
@@ -1,12 +1,9 @@
+import * as React from 'react'
+import useEmblaCarousel, { type UseEmblaCarouselType } from 'embla-carousel-react'
+import { ArrowLeft, ArrowRight } from 'lucide-react'
-import * as React from "react"
-import useEmblaCarousel, {
- type UseEmblaCarouselType,
-} from "embla-carousel-react"
-import { ArrowLeft, ArrowRight } from "lucide-react"
-
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
+import { cn } from '@/lib/utils'
+import { Button } from '@/components/ui/button'
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
@@ -16,7 +13,7 @@ type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
- orientation?: "horizontal" | "vertical"
+ orientation?: 'horizontal' | 'vertical'
setApi?: (api: CarouselApi) => void
}
@@ -35,25 +32,25 @@ function useCarousel() {
const context = React.useContext(CarouselContext)
if (!context) {
- throw new Error("useCarousel must be used within a <Carousel />")
+ throw new Error('useCarousel must be used within a <Carousel />')
}
return context
}
function Carousel({
- orientation = "horizontal",
+ orientation = 'horizontal',
opts,
setApi,
plugins,
className,
children,
...props
-}: React.ComponentProps<"div"> & CarouselProps) {
+}: React.ComponentProps<'div'> & CarouselProps) {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
- axis: orientation === "horizontal" ? "x" : "y",
+ axis: orientation === 'horizontal' ? 'x' : 'y'
},
plugins
)
@@ -76,10 +73,10 @@ function Carousel({
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
- if (event.key === "ArrowLeft") {
+ if (event.key === 'ArrowLeft') {
event.preventDefault()
scrollPrev()
- } else if (event.key === "ArrowRight") {
+ } else if (event.key === 'ArrowRight') {
event.preventDefault()
scrollNext()
}
@@ -95,11 +92,11 @@ function Carousel({
React.useEffect(() => {
if (!api) return
onSelect(api)
- api.on("reInit", onSelect)
- api.on("select", onSelect)
+ api.on('reInit', onSelect)
+ api.on('select', onSelect)
return () => {
- api?.off("select", onSelect)
+ api?.off('select', onSelect)
}
}, [api, onSelect])
@@ -109,17 +106,16 @@ function Carousel({
carouselRef,
api: api,
opts,
- orientation:
- orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
+ orientation: orientation || (opts?.axis === 'y' ? 'vertical' : 'horizontal'),
scrollPrev,
scrollNext,
canScrollPrev,
- canScrollNext,
+ canScrollNext
}}
>
<div
onKeyDownCapture={handleKeyDown}
- className={cn("relative", className)}
+ className={cn('relative', className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
@@ -131,28 +127,20 @@ function Carousel({
)
}
-function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
+function CarouselContent({ className, ...props }: React.ComponentProps<'div'>) {
const { carouselRef, orientation } = useCarousel()
return (
- <div
- ref={carouselRef}
- className="overflow-hidden"
- data-slot="carousel-content"
- >
+ <div ref={carouselRef} className="overflow-hidden" data-slot="carousel-content">
<div
- className={cn(
- "flex",
- orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
- className
- )}
+ className={cn('flex', orientation === 'horizontal' ? '-ml-4' : '-mt-4 flex-col', className)}
{...props}
/>
</div>
)
}
-function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
+function CarouselItem({ className, ...props }: React.ComponentProps<'div'>) {
const { orientation } = useCarousel()
return (
@@ -161,8 +149,8 @@ function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
- "min-w-0 shrink-0 grow-0 basis-full",
- orientation === "horizontal" ? "pl-4" : "pt-4",
+ 'min-w-0 shrink-0 grow-0 basis-full',
+ orientation === 'horizontal' ? 'pl-4' : 'pt-4',
className
)}
{...props}
@@ -172,8 +160,8 @@ function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
function CarouselPrevious({
className,
- variant = "outline",
- size = "icon",
+ variant = 'outline',
+ size = 'icon',
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
@@ -184,10 +172,10 @@ function CarouselPrevious({
variant={variant}
size={size}
className={cn(
- "absolute size-8 rounded-full",
- orientation === "horizontal"
- ? "top-1/2 -left-12 -translate-y-1/2"
- : "-top-12 left-1/2 -translate-x-1/2 rotate-90",
+ 'absolute size-8 rounded-full',
+ orientation === 'horizontal'
+ ? 'top-1/2 -left-12 -translate-y-1/2'
+ : '-top-12 left-1/2 -translate-x-1/2 rotate-90',
className
)}
disabled={!canScrollPrev}
@@ -202,8 +190,8 @@ function CarouselPrevious({
function CarouselNext({
className,
- variant = "outline",
- size = "icon",
+ variant = 'outline',
+ size = 'icon',
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel()
@@ -214,10 +202,10 @@ function CarouselNext({
variant={variant}
size={size}
className={cn(
- "absolute size-8 rounded-full",
- orientation === "horizontal"
- ? "top-1/2 -right-12 -translate-y-1/2"
- : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
+ 'absolute size-8 rounded-full',
+ orientation === 'horizontal'
+ ? 'top-1/2 -right-12 -translate-y-1/2'
+ : '-bottom-12 left-1/2 -translate-x-1/2 rotate-90',
className
)}
disabled={!canScrollNext}
@@ -230,11 +218,4 @@ function CarouselNext({
)
}
-export {
- type CarouselApi,
- Carousel,
- CarouselContent,
- CarouselItem,
- CarouselPrevious,
- CarouselNext,
-}
+export { type CarouselApi, Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext }
diff --git a/flowsint-app/src/renderer/src/components/ui/chart.tsx b/flowsint-app/src/renderer/src/components/ui/chart.tsx
index e4589f04..79c230c0 100644
--- a/flowsint-app/src/renderer/src/components/ui/chart.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/chart.tsx
@@ -1,10 +1,10 @@
-import * as React from "react"
-import * as RechartsPrimitive from "recharts"
+import * as React from 'react'
+import * as RechartsPrimitive from 'recharts'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
// Format: { THEME_NAME: CSS_SELECTOR }
-const THEMES = { light: "", dark: ".dark" } as const
+const THEMES = { light: '', dark: '.dark' } as const
export type ChartConfig = {
[k in string]: {
@@ -26,7 +26,7 @@ function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
- throw new Error("useChart must be used within a <ChartContainer />")
+ throw new Error('useChart must be used within a <ChartContainer />')
}
return context
@@ -38,14 +38,12 @@ function ChartContainer({
children,
config,
...props
-}: React.ComponentProps<"div"> & {
+}: React.ComponentProps<'div'> & {
config: ChartConfig
- children: React.ComponentProps<
- typeof RechartsPrimitive.ResponsiveContainer
- >["children"]
+ children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>['children']
}) {
const uniqueId = React.useId()
- const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
+ const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`
return (
<ChartContext.Provider value={{ config }}>
@@ -59,18 +57,14 @@ function ChartContainer({
{...props}
>
<ChartStyle id={chartId} config={config} />
- <RechartsPrimitive.ResponsiveContainer>
- {children}
- </RechartsPrimitive.ResponsiveContainer>
+ <RechartsPrimitive.ResponsiveContainer>{children}</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
- const colorConfig = Object.entries(config).filter(
- ([, config]) => config.theme || config.color
- )
+ const colorConfig = Object.entries(config).filter(([, config]) => config.theme || config.color)
if (!colorConfig.length) {
return null
@@ -85,16 +79,14 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
- const color =
- itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
- itemConfig.color
+ const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
- .join("\n")}
+ .join('\n')}
}
`
)
- .join("\n"),
+ .join('\n')
}}
/>
)
@@ -106,7 +98,7 @@ function ChartTooltipContent({
active,
payload,
className,
- indicator = "dot",
+ indicator = 'dot',
hideLabel = false,
hideIndicator = false,
label,
@@ -115,12 +107,12 @@ function ChartTooltipContent({
formatter,
color,
nameKey,
- labelKey,
+ labelKey
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
- React.ComponentProps<"div"> & {
+ React.ComponentProps<'div'> & {
hideLabel?: boolean
hideIndicator?: boolean
- indicator?: "line" | "dot" | "dashed"
+ indicator?: 'line' | 'dot' | 'dashed'
nameKey?: string
labelKey?: string
}) {
@@ -132,18 +124,16 @@ function ChartTooltipContent({
}
const [item] = payload
- const key = `${labelKey || item?.dataKey || item?.name || "value"}`
+ const key = `${labelKey || item?.dataKey || item?.name || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
- !labelKey && typeof label === "string"
+ !labelKey && typeof label === 'string'
? config[label as keyof typeof config]?.label || label
: itemConfig?.label
if (labelFormatter) {
return (
- <div className={cn("font-medium", labelClassName)}>
- {labelFormatter(value, payload)}
- </div>
+ <div className={cn('font-medium', labelClassName)}>{labelFormatter(value, payload)}</div>
)
}
@@ -151,34 +141,26 @@ function ChartTooltipContent({
return null
}
- return <div className={cn("font-medium", labelClassName)}>{value}</div>
- }, [
- label,
- labelFormatter,
- payload,
- hideLabel,
- labelClassName,
- config,
- labelKey,
- ])
+ return <div className={cn('font-medium', labelClassName)}>{value}</div>
+ }, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey])
if (!active || !payload?.length) {
return null
}
- const nestLabel = payload.length === 1 && indicator !== "dot"
+ const nestLabel = payload.length === 1 && indicator !== 'dot'
return (
<div
className={cn(
- "border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
+ 'border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl',
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
- const key = `${nameKey || item.name || item.dataKey || "value"}`
+ const key = `${nameKey || item.name || item.dataKey || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color || item.payload.fill || item.color
@@ -186,8 +168,8 @@ function ChartTooltipContent({
<div
key={item.dataKey}
className={cn(
- "[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
- indicator === "dot" && "items-center"
+ '[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5',
+ indicator === 'dot' && 'items-center'
)}
>
{formatter && item?.value !== undefined && item.name ? (
@@ -200,19 +182,19 @@ function ChartTooltipContent({
!hideIndicator && (
<div
className={cn(
- "shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
+ 'shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)',
{
- "h-2.5 w-2.5": indicator === "dot",
- "w-1": indicator === "line",
- "w-0 border-[1.5px] border-dashed bg-transparent":
- indicator === "dashed",
- "my-0.5": nestLabel && indicator === "dashed",
+ 'h-2.5 w-2.5': indicator === 'dot',
+ 'w-1': indicator === 'line',
+ 'w-0 border-[1.5px] border-dashed bg-transparent':
+ indicator === 'dashed',
+ 'my-0.5': nestLabel && indicator === 'dashed'
}
)}
style={
{
- "--color-bg": indicatorColor,
- "--color-border": indicatorColor,
+ '--color-bg': indicatorColor,
+ '--color-border': indicatorColor
} as React.CSSProperties
}
/>
@@ -220,8 +202,8 @@ function ChartTooltipContent({
)}
<div
className={cn(
- "flex flex-1 justify-between leading-none",
- nestLabel ? "items-end" : "items-center"
+ 'flex flex-1 justify-between leading-none',
+ nestLabel ? 'items-end' : 'items-center'
)}
>
<div className="grid gap-1.5">
@@ -252,10 +234,10 @@ function ChartLegendContent({
className,
hideIcon = false,
payload,
- verticalAlign = "bottom",
- nameKey,
-}: React.ComponentProps<"div"> &
- Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
+ verticalAlign = 'bottom',
+ nameKey
+}: React.ComponentProps<'div'> &
+ Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & {
hideIcon?: boolean
nameKey?: string
}) {
@@ -268,20 +250,20 @@ function ChartLegendContent({
return (
<div
className={cn(
- "flex items-center justify-center gap-4",
- verticalAlign === "top" ? "pb-3" : "pt-3",
+ 'flex items-center justify-center gap-4',
+ verticalAlign === 'top' ? 'pb-3' : 'pt-3',
className
)}
>
{payload.map((item) => {
- const key = `${nameKey || item.dataKey || "value"}`
+ const key = `${nameKey || item.dataKey || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className={cn(
- "[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
+ '[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3'
)}
>
{itemConfig?.icon && !hideIcon ? (
@@ -290,7 +272,7 @@ function ChartLegendContent({
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
- backgroundColor: item.color,
+ backgroundColor: item.color
}}
/>
)}
@@ -303,42 +285,29 @@ function ChartLegendContent({
}
// Helper to extract item config from a payload.
-function getPayloadConfigFromPayload(
- config: ChartConfig,
- payload: unknown,
- key: string
-) {
- if (typeof payload !== "object" || payload === null) {
+function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
+ if (typeof payload !== 'object' || payload === null) {
return undefined
}
const payloadPayload =
- "payload" in payload &&
- typeof payload.payload === "object" &&
- payload.payload !== null
+ 'payload' in payload && typeof payload.payload === 'object' && payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
- if (
- key in payload &&
- typeof payload[key as keyof typeof payload] === "string"
- ) {
+ if (key in payload && typeof payload[key as keyof typeof payload] === 'string') {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
- typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
+ typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
) {
- configLabelKey = payloadPayload[
- key as keyof typeof payloadPayload
- ] as string
+ configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string
}
- return configLabelKey in config
- ? config[configLabelKey]
- : config[key as keyof typeof config]
+ return configLabelKey in config ? config[configLabelKey] : config[key as keyof typeof config]
}
export {
@@ -347,5 +316,5 @@ export {
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
- ChartStyle,
+ ChartStyle
}
diff --git a/flowsint-app/src/renderer/src/components/ui/checkbox.tsx b/flowsint-app/src/renderer/src/components/ui/checkbox.tsx
index 5decb128..b822c061 100644
--- a/flowsint-app/src/renderer/src/components/ui/checkbox.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/checkbox.tsx
@@ -1,19 +1,15 @@
+import * as React from 'react'
+import * as CheckboxPrimitive from '@radix-ui/react-checkbox'
+import { CheckIcon } from 'lucide-react'
-import * as React from "react"
-import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
-import { CheckIcon } from "lucide-react"
+import { cn } from '@/lib/utils'
-import { cn } from "@/lib/utils"
-
-function Checkbox({
- className,
- ...props
-}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
+function Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
- "peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
+ 'peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/collapsible.tsx b/flowsint-app/src/renderer/src/components/ui/collapsible.tsx
index 77f86bed..56f27222 100644
--- a/flowsint-app/src/renderer/src/components/ui/collapsible.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/collapsible.tsx
@@ -1,31 +1,19 @@
-import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
+import * as CollapsiblePrimitive from '@radix-ui/react-collapsible'
-function Collapsible({
- ...props
-}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
+function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
- return (
- <CollapsiblePrimitive.CollapsibleTrigger
- data-slot="collapsible-trigger"
- {...props}
- />
- )
+ return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
- return (
- <CollapsiblePrimitive.CollapsibleContent
- data-slot="collapsible-content"
- {...props}
- />
- )
+ return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
diff --git a/flowsint-app/src/renderer/src/components/ui/command.tsx b/flowsint-app/src/renderer/src/components/ui/command.tsx
index 195a9d18..96c2f20f 100644
--- a/flowsint-app/src/renderer/src/components/ui/command.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/command.tsx
@@ -1,26 +1,22 @@
+import * as React from 'react'
+import { Command as CommandPrimitive } from 'cmdk'
+import { SearchIcon } from 'lucide-react'
-import * as React from "react"
-import { Command as CommandPrimitive } from "cmdk"
-import { SearchIcon } from "lucide-react"
-
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog"
+ DialogTitle
+} from '@/components/ui/dialog'
-function Command({
- className,
- ...props
-}: React.ComponentProps<typeof CommandPrimitive>) {
+function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
- "bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
+ 'bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md',
className
)}
{...props}
@@ -29,8 +25,8 @@ function Command({
}
function CommandDialog({
- title = "Command Palette",
- description = "Search for a command to run...",
+ title = 'Command Palette',
+ description = 'Search for a command to run...',
children,
className,
showCloseButton = true,
@@ -48,7 +44,7 @@ function CommandDialog({
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
- className={cn("overflow-hidden p-0", className)}
+ className={cn('overflow-hidden p-0', className)}
showCloseButton={showCloseButton}
>
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
@@ -64,15 +60,12 @@ function CommandInput({
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
- <div
- data-slot="command-input-wrapper"
- className="flex h-9 items-center gap-2 border-b px-3"
- >
+ <div data-slot="command-input-wrapper" className="flex h-9 items-center gap-2 border-b px-3">
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
- "placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
+ 'placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
@@ -81,25 +74,17 @@ function CommandInput({
)
}
-function CommandList({
- className,
- ...props
-}: React.ComponentProps<typeof CommandPrimitive.List>) {
+function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
- className={cn(
- "max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
- className
- )}
+ className={cn('max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto', className)}
{...props}
/>
)
}
-function CommandEmpty({
- ...props
-}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
+function CommandEmpty({ ...props }: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
@@ -117,7 +102,7 @@ function CommandGroup({
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
- "text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
+ 'text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium',
className
)}
{...props}
@@ -132,16 +117,13 @@ function CommandSeparator({
return (
<CommandPrimitive.Separator
data-slot="command-separator"
- className={cn("bg-border -mx-1 h-px", className)}
+ className={cn('bg-border -mx-1 h-px', className)}
{...props}
/>
)
}
-function CommandItem({
- className,
- ...props
-}: React.ComponentProps<typeof CommandPrimitive.Item>) {
+function CommandItem({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
@@ -154,17 +136,11 @@ function CommandItem({
)
}
-function CommandShortcut({
- className,
- ...props
-}: React.ComponentProps<"span">) {
+function CommandShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="command-shortcut"
- className={cn(
- "text-muted-foreground ml-auto text-xs tracking-widest",
- className
- )}
+ className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
{...props}
/>
)
@@ -179,5 +155,5 @@ export {
CommandGroup,
CommandItem,
CommandShortcut,
- CommandSeparator,
+ CommandSeparator
}
diff --git a/flowsint-app/src/renderer/src/components/ui/context-menu.tsx b/flowsint-app/src/renderer/src/components/ui/context-menu.tsx
index feb7a9e0..734356e7 100644
--- a/flowsint-app/src/renderer/src/components/ui/context-menu.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/context-menu.tsx
@@ -1,55 +1,35 @@
+import * as React from 'react'
+import * as ContextMenuPrimitive from '@radix-ui/react-context-menu'
+import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react'
-import * as React from "react"
-import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
-import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
+import { cn } from '@/lib/utils'
-import { cn } from "@/lib/utils"
-
-function ContextMenu({
- ...props
-}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
+function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
}
function ContextMenuTrigger({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
- return (
- <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
- )
+ return <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
}
-function ContextMenuGroup({
- ...props
-}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
- return (
- <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
- )
+function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
+ return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
}
-function ContextMenuPortal({
- ...props
-}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
- return (
- <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
- )
+function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
+ return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
}
-function ContextMenuSub({
- ...props
-}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
+function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
}
function ContextMenuRadioGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
- return (
- <ContextMenuPrimitive.RadioGroup
- data-slot="context-menu-radio-group"
- {...props}
- />
- )
+ return <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} />
}
function ContextMenuSubTrigger({
@@ -84,7 +64,7 @@ function ContextMenuSubContent({
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg',
className
)}
{...props}
@@ -101,7 +81,7 @@ function ContextMenuContent({
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md',
className
)}
{...props}
@@ -113,11 +93,11 @@ function ContextMenuContent({
function ContextMenuItem({
className,
inset,
- variant = "default",
+ variant = 'default',
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
- variant?: "default" | "destructive"
+ variant?: 'default' | 'destructive'
}) {
return (
<ContextMenuPrimitive.Item
@@ -194,10 +174,7 @@ function ContextMenuLabel({
<ContextMenuPrimitive.Label
data-slot="context-menu-label"
data-inset={inset}
- className={cn(
- "text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
- className
- )}
+ className={cn('text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}
{...props}
/>
)
@@ -210,23 +187,17 @@ function ContextMenuSeparator({
return (
<ContextMenuPrimitive.Separator
data-slot="context-menu-separator"
- className={cn("bg-border -mx-1 my-1 h-px", className)}
+ className={cn('bg-border -mx-1 my-1 h-px', className)}
{...props}
/>
)
}
-function ContextMenuShortcut({
- className,
- ...props
-}: React.ComponentProps<"span">) {
+function ContextMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="context-menu-shortcut"
- className={cn(
- "text-muted-foreground ml-auto text-xs tracking-widest",
- className
- )}
+ className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
{...props}
/>
)
@@ -247,5 +218,5 @@ export {
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
- ContextMenuRadioGroup,
+ ContextMenuRadioGroup
}
diff --git a/flowsint-app/src/renderer/src/components/ui/dialog.tsx b/flowsint-app/src/renderer/src/components/ui/dialog.tsx
index 6cb123b3..d9992d13 100644
--- a/flowsint-app/src/renderer/src/components/ui/dialog.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/dialog.tsx
@@ -1,30 +1,22 @@
-import * as React from "react"
-import * as DialogPrimitive from "@radix-ui/react-dialog"
-import { XIcon } from "lucide-react"
+import * as React from 'react'
+import * as DialogPrimitive from '@radix-ui/react-dialog'
+import { XIcon } from 'lucide-react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Dialog({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Root>) {
+function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
-function DialogTrigger({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
+function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
-function DialogPortal({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
+function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
-function DialogClose({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Close>) {
+function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
@@ -36,7 +28,7 @@ function DialogOverlay({
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
className
)}
{...props}
@@ -58,7 +50,7 @@ function DialogContent({
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
- "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
+ 'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg',
className
)}
{...props}
@@ -78,37 +70,31 @@ function DialogContent({
)
}
-function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="dialog-header"
- className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
+ className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
{...props}
/>
)
}
-function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
+function DialogFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="dialog-footer"
- className={cn(
- "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
- className
- )}
+ className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
{...props}
/>
)
}
-function DialogTitle({
- className,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Title>) {
+function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
- className={cn("text-lg leading-none font-semibold", className)}
+ className={cn('text-lg leading-none font-semibold', className)}
{...props}
/>
)
@@ -121,7 +107,7 @@ function DialogDescription({
return (
<DialogPrimitive.Description
data-slot="dialog-description"
- className={cn("text-muted-foreground text-sm", className)}
+ className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
)
@@ -137,5 +123,5 @@ export {
DialogOverlay,
DialogPortal,
DialogTitle,
- DialogTrigger,
+ DialogTrigger
}
diff --git a/flowsint-app/src/renderer/src/components/ui/drawer.tsx b/flowsint-app/src/renderer/src/components/ui/drawer.tsx
index 7fd2e988..b05e63a1 100644
--- a/flowsint-app/src/renderer/src/components/ui/drawer.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/drawer.tsx
@@ -1,29 +1,21 @@
-import * as React from "react"
-import { Drawer as DrawerPrimitive } from "vaul"
+import * as React from 'react'
+import { Drawer as DrawerPrimitive } from 'vaul'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Drawer({
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
+function Drawer({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
}
-function DrawerTrigger({
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
+function DrawerTrigger({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
}
-function DrawerPortal({
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
+function DrawerPortal({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
}
-function DrawerClose({
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
+function DrawerClose({ ...props }: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
}
@@ -35,7 +27,7 @@ function DrawerOverlay({
<DrawerPrimitive.Overlay
data-slot="drawer-overlay"
className={cn(
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
className
)}
{...props}
@@ -54,11 +46,11 @@ function DrawerContent({
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
- "group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
- "data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
- "data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
- "data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
- "data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
+ 'group/drawer-content bg-background fixed z-50 flex h-auto flex-col',
+ 'data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b',
+ 'data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t',
+ 'data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm',
+ 'data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm',
className
)}
{...props}
@@ -70,34 +62,31 @@ function DrawerContent({
)
}
-function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
+function DrawerHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="drawer-header"
- className={cn("flex flex-col gap-1.5 p-4", className)}
+ className={cn('flex flex-col gap-1.5 p-4', className)}
{...props}
/>
)
}
-function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
+function DrawerFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="drawer-footer"
- className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ className={cn('mt-auto flex flex-col gap-2 p-4', className)}
{...props}
/>
)
}
-function DrawerTitle({
- className,
- ...props
-}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
+function DrawerTitle({ className, ...props }: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
- className={cn("text-foreground font-semibold", className)}
+ className={cn('text-foreground font-semibold', className)}
{...props}
/>
)
@@ -110,7 +99,7 @@ function DrawerDescription({
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
- className={cn("text-muted-foreground text-sm", className)}
+ className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
)
@@ -126,5 +115,5 @@ export {
DrawerHeader,
DrawerFooter,
DrawerTitle,
- DrawerDescription,
+ DrawerDescription
}
diff --git a/flowsint-app/src/renderer/src/components/ui/dropdown-menu.tsx b/flowsint-app/src/renderer/src/components/ui/dropdown-menu.tsx
index fe3d6fbc..b0425dad 100644
--- a/flowsint-app/src/renderer/src/components/ui/dropdown-menu.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/dropdown-menu.tsx
@@ -1,33 +1,23 @@
+import * as React from 'react'
+import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'
+import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react'
-import * as React from "react"
-import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
-import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
+import { cn } from '@/lib/utils'
-import { cn } from "@/lib/utils"
-
-function DropdownMenu({
- ...props
-}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
+function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
- return (
- <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
- )
+ return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
- return (
- <DropdownMenuPrimitive.Trigger
- data-slot="dropdown-menu-trigger"
- {...props}
- />
- )
+ return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
}
function DropdownMenuContent({
@@ -41,7 +31,7 @@ function DropdownMenuContent({
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md mx-3",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md mx-3',
className
)}
{...props}
@@ -50,22 +40,18 @@ function DropdownMenuContent({
)
}
-function DropdownMenuGroup({
- ...props
-}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
- return (
- <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
- )
+function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
+ return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
}
function DropdownMenuItem({
className,
inset,
- variant = "default",
+ variant = 'default',
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
- variant?: "default" | "destructive"
+ variant?: 'default' | 'destructive'
}) {
return (
<DropdownMenuPrimitive.Item
@@ -110,12 +96,7 @@ function DropdownMenuCheckboxItem({
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
- return (
- <DropdownMenuPrimitive.RadioGroup
- data-slot="dropdown-menu-radio-group"
- {...props}
- />
- )
+ return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />
}
function DropdownMenuRadioItem({
@@ -153,10 +134,7 @@ function DropdownMenuLabel({
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
- className={cn(
- "px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
- className
- )}
+ className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}
{...props}
/>
)
@@ -169,31 +147,23 @@ function DropdownMenuSeparator({
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
- className={cn("bg-border -mx-1 my-1 h-px", className)}
+ className={cn('bg-border -mx-1 my-1 h-px', className)}
{...props}
/>
)
}
-function DropdownMenuShortcut({
- className,
- ...props
-}: React.ComponentProps<"span">) {
+function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="dropdown-menu-shortcut"
- className={cn(
- "text-muted-foreground ml-auto text-xs tracking-widest",
- className
- )}
+ className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
{...props}
/>
)
}
-function DropdownMenuSub({
- ...props
-}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
+function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
@@ -210,7 +180,7 @@ function DropdownMenuSubTrigger({
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
- "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
+ 'focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8',
className
)}
{...props}
@@ -229,7 +199,7 @@ function DropdownMenuSubContent({
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg',
className
)}
{...props}
@@ -252,5 +222,5 @@ export {
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
- DropdownMenuSubContent,
+ DropdownMenuSubContent
}
diff --git a/flowsint-app/src/renderer/src/components/ui/form.tsx b/flowsint-app/src/renderer/src/components/ui/form.tsx
index 7d7474cc..584cb27c 100644
--- a/flowsint-app/src/renderer/src/components/ui/form.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/form.tsx
@@ -1,6 +1,6 @@
-import * as React from "react"
-import * as LabelPrimitive from "@radix-ui/react-label"
-import { Slot } from "@radix-ui/react-slot"
+import * as React from 'react'
+import * as LabelPrimitive from '@radix-ui/react-label'
+import { Slot } from '@radix-ui/react-slot'
import {
Controller,
FormProvider,
@@ -8,28 +8,26 @@ import {
useFormState,
type ControllerProps,
type FieldPath,
- type FieldValues,
-} from "react-hook-form"
+ type FieldValues
+} from 'react-hook-form'
-import { cn } from "@/lib/utils"
-import { Label } from "@/components/ui/label"
+import { cn } from '@/lib/utils'
+import { Label } from '@/components/ui/label'
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
- TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
-const FormFieldContext = React.createContext<FormFieldContextValue>(
- {} as FormFieldContextValue
-)
+const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
- TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
@@ -48,7 +46,7 @@ const useFormField = () => {
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
- throw new Error("useFormField should be used within <FormField>")
+ throw new Error('useFormField should be used within <FormField>')
}
const { id } = itemContext
@@ -59,7 +57,7 @@ const useFormField = () => {
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
- ...fieldState,
+ ...fieldState
}
}
@@ -67,35 +65,26 @@ type FormItemContextValue = {
id: string
}
-const FormItemContext = React.createContext<FormItemContextValue>(
- {} as FormItemContextValue
-)
+const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue)
-function FormItem({ className, ...props }: React.ComponentProps<"div">) {
+function FormItem({ className, ...props }: React.ComponentProps<'div'>) {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
- <div
- data-slot="form-item"
- className={cn("grid gap-2", className)}
- {...props}
- />
+ <div data-slot="form-item" className={cn('grid gap-2', className)} {...props} />
</FormItemContext.Provider>
)
}
-function FormLabel({
- className,
- ...props
-}: React.ComponentProps<typeof LabelPrimitive.Root>) {
+function FormLabel({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField()
return (
<Label
data-slot="form-label"
data-error={!!error}
- className={cn("data-[error=true]:text-destructive", className)}
+ className={cn('data-[error=true]:text-destructive', className)}
htmlFor={formItemId}
{...props}
/>
@@ -109,33 +98,29 @@ function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
<Slot
data-slot="form-control"
id={formItemId}
- aria-describedby={
- !error
- ? `${formDescriptionId}`
- : `${formDescriptionId} ${formMessageId}`
- }
+ aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
aria-invalid={!!error}
{...props}
/>
)
}
-function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
+function FormDescription({ className, ...props }: React.ComponentProps<'p'>) {
const { formDescriptionId } = useFormField()
return (
<p
data-slot="form-description"
id={formDescriptionId}
- className={cn("text-muted-foreground text-sm", className)}
+ className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
)
}
-function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
+function FormMessage({ className, ...props }: React.ComponentProps<'p'>) {
const { error, formMessageId } = useFormField()
- const body = error ? String(error?.message ?? "") : props.children
+ const body = error ? String(error?.message ?? '') : props.children
if (!body) {
return null
@@ -145,7 +130,7 @@ function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
<p
data-slot="form-message"
id={formMessageId}
- className={cn("text-destructive text-sm", className)}
+ className={cn('text-destructive text-sm', className)}
{...props}
>
{body}
@@ -161,5 +146,5 @@ export {
FormControl,
FormDescription,
FormMessage,
- FormField,
+ FormField
}
diff --git a/flowsint-app/src/renderer/src/components/ui/hover-card.tsx b/flowsint-app/src/renderer/src/components/ui/hover-card.tsx
index e4204e0d..b76088ab 100644
--- a/flowsint-app/src/renderer/src/components/ui/hover-card.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/hover-card.tsx
@@ -1,25 +1,19 @@
-import * as React from "react"
-import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
+import * as React from 'react'
+import * as HoverCardPrimitive from '@radix-ui/react-hover-card'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function HoverCard({
- ...props
-}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
+function HoverCard({ ...props }: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
}
-function HoverCardTrigger({
- ...props
-}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
- return (
- <HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
- )
+function HoverCardTrigger({ ...props }: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
+ return <HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
}
function HoverCardContent({
className,
- align = "center",
+ align = 'center',
sideOffset = 4,
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
@@ -30,7 +24,7 @@ function HoverCardContent({
align={align}
sideOffset={sideOffset}
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/input-otp.tsx b/flowsint-app/src/renderer/src/components/ui/input-otp.tsx
index 7ff903d7..1f425a6d 100644
--- a/flowsint-app/src/renderer/src/components/ui/input-otp.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/input-otp.tsx
@@ -1,9 +1,8 @@
+import * as React from 'react'
+import { OTPInput, OTPInputContext } from 'input-otp'
+import { MinusIcon } from 'lucide-react'
-import * as React from "react"
-import { OTPInput, OTPInputContext } from "input-otp"
-import { MinusIcon } from "lucide-react"
-
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function InputOTP({
className,
@@ -15,23 +14,16 @@ function InputOTP({
return (
<OTPInput
data-slot="input-otp"
- containerClassName={cn(
- "flex items-center gap-2 has-disabled:opacity-50",
- containerClassName
- )}
- className={cn("disabled:cursor-not-allowed", className)}
+ containerClassName={cn('flex items-center gap-2 has-disabled:opacity-50', containerClassName)}
+ className={cn('disabled:cursor-not-allowed', className)}
{...props}
/>
)
}
-function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
+function InputOTPGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
- <div
- data-slot="input-otp-group"
- className={cn("flex items-center", className)}
- {...props}
- />
+ <div data-slot="input-otp-group" className={cn('flex items-center', className)} {...props} />
)
}
@@ -39,7 +31,7 @@ function InputOTPSlot({
index,
className,
...props
-}: React.ComponentProps<"div"> & {
+}: React.ComponentProps<'div'> & {
index: number
}) {
const inputOTPContext = React.useContext(OTPInputContext)
@@ -50,7 +42,7 @@ function InputOTPSlot({
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
- "data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
+ 'data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]',
className
)}
{...props}
@@ -65,7 +57,7 @@ function InputOTPSlot({
)
}
-function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
+function InputOTPSeparator({ ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
diff --git a/flowsint-app/src/renderer/src/components/ui/input.tsx b/flowsint-app/src/renderer/src/components/ui/input.tsx
index 34333d9c..04900645 100644
--- a/flowsint-app/src/renderer/src/components/ui/input.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/input.tsx
@@ -1,6 +1,6 @@
-import * as React from "react"
+import * as React from 'react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
@@ -11,9 +11,9 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
type={type}
data-slot="input"
className={cn(
- "file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
- "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
- "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
+ 'file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
+ 'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
+ 'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive',
className
)}
ref={ref}
@@ -22,6 +22,6 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
)
}
)
-Input.displayName = "Input"
+Input.displayName = 'Input'
export { Input }
diff --git a/flowsint-app/src/renderer/src/components/ui/label.tsx b/flowsint-app/src/renderer/src/components/ui/label.tsx
index aef28ff9..d7b4512a 100644
--- a/flowsint-app/src/renderer/src/components/ui/label.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/label.tsx
@@ -1,18 +1,14 @@
+import * as React from 'react'
+import * as LabelPrimitive from '@radix-ui/react-label'
-import * as React from "react"
-import * as LabelPrimitive from "@radix-ui/react-label"
+import { cn } from '@/lib/utils'
-import { cn } from "@/lib/utils"
-
-function Label({
- className,
- ...props
-}: React.ComponentProps<typeof LabelPrimitive.Root>) {
+function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
- "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
+ 'flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/menubar.tsx b/flowsint-app/src/renderer/src/components/ui/menubar.tsx
index cb45a86e..5ff69abc 100644
--- a/flowsint-app/src/renderer/src/components/ui/menubar.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/menubar.tsx
@@ -1,18 +1,15 @@
-import * as React from "react"
-import * as MenubarPrimitive from "@radix-ui/react-menubar"
-import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
+import * as React from 'react'
+import * as MenubarPrimitive from '@radix-ui/react-menubar'
+import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Menubar({
- className,
- ...props
-}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
+function Menubar({ className, ...props }: React.ComponentProps<typeof MenubarPrimitive.Root>) {
return (
<MenubarPrimitive.Root
data-slot="menubar"
className={cn(
- "bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
+ 'bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs',
className
)}
{...props}
@@ -20,30 +17,20 @@ function Menubar({
)
}
-function MenubarMenu({
- ...props
-}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
+function MenubarMenu({ ...props }: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
}
-function MenubarGroup({
- ...props
-}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
+function MenubarGroup({ ...props }: React.ComponentProps<typeof MenubarPrimitive.Group>) {
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
}
-function MenubarPortal({
- ...props
-}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
+function MenubarPortal({ ...props }: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
}
-function MenubarRadioGroup({
- ...props
-}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
- return (
- <MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
- )
+function MenubarRadioGroup({ ...props }: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
+ return <MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
}
function MenubarTrigger({
@@ -54,7 +41,7 @@ function MenubarTrigger({
<MenubarPrimitive.Trigger
data-slot="menubar-trigger"
className={cn(
- "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
+ 'focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none',
className
)}
{...props}
@@ -64,7 +51,7 @@ function MenubarTrigger({
function MenubarContent({
className,
- align = "start",
+ align = 'start',
alignOffset = -4,
sideOffset = 8,
...props
@@ -77,7 +64,7 @@ function MenubarContent({
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md',
className
)}
{...props}
@@ -89,11 +76,11 @@ function MenubarContent({
function MenubarItem({
className,
inset,
- variant = "default",
+ variant = 'default',
...props
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
inset?: boolean
- variant?: "default" | "destructive"
+ variant?: 'default' | 'destructive'
}) {
return (
<MenubarPrimitive.Item
@@ -170,10 +157,7 @@ function MenubarLabel({
<MenubarPrimitive.Label
data-slot="menubar-label"
data-inset={inset}
- className={cn(
- "px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
- className
- )}
+ className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}
{...props}
/>
)
@@ -186,31 +170,23 @@ function MenubarSeparator({
return (
<MenubarPrimitive.Separator
data-slot="menubar-separator"
- className={cn("bg-border -mx-1 my-1 h-px", className)}
+ className={cn('bg-border -mx-1 my-1 h-px', className)}
{...props}
/>
)
}
-function MenubarShortcut({
- className,
- ...props
-}: React.ComponentProps<"span">) {
+function MenubarShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="menubar-shortcut"
- className={cn(
- "text-muted-foreground ml-auto text-xs tracking-widest",
- className
- )}
+ className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
{...props}
/>
)
}
-function MenubarSub({
- ...props
-}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
+function MenubarSub({ ...props }: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
}
@@ -227,7 +203,7 @@ function MenubarSubTrigger({
data-slot="menubar-sub-trigger"
data-inset={inset}
className={cn(
- "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
+ 'focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8',
className
)}
{...props}
@@ -246,7 +222,7 @@ function MenubarSubContent({
<MenubarPrimitive.SubContent
data-slot="menubar-sub-content"
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg',
className
)}
{...props}
@@ -270,5 +246,5 @@ export {
MenubarRadioItem,
MenubarSub,
MenubarSubTrigger,
- MenubarSubContent,
+ MenubarSubContent
}
diff --git a/flowsint-app/src/renderer/src/components/ui/navigation-menu.tsx b/flowsint-app/src/renderer/src/components/ui/navigation-menu.tsx
index 1199945c..04e4a366 100644
--- a/flowsint-app/src/renderer/src/components/ui/navigation-menu.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/navigation-menu.tsx
@@ -1,9 +1,9 @@
-import * as React from "react"
-import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
-import { cva } from "class-variance-authority"
-import { ChevronDownIcon } from "lucide-react"
+import * as React from 'react'
+import * as NavigationMenuPrimitive from '@radix-ui/react-navigation-menu'
+import { cva } from 'class-variance-authority'
+import { ChevronDownIcon } from 'lucide-react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function NavigationMenu({
className,
@@ -18,7 +18,7 @@ function NavigationMenu({
data-slot="navigation-menu"
data-viewport={viewport}
className={cn(
- "group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
+ 'group/navigation-menu relative flex max-w-max flex-1 items-center justify-center',
className
)}
{...props}
@@ -36,10 +36,7 @@ function NavigationMenuList({
return (
<NavigationMenuPrimitive.List
data-slot="navigation-menu-list"
- className={cn(
- "group flex flex-1 list-none items-center justify-center gap-1",
- className
- )}
+ className={cn('group flex flex-1 list-none items-center justify-center gap-1', className)}
{...props}
/>
)
@@ -52,14 +49,14 @@ function NavigationMenuItem({
return (
<NavigationMenuPrimitive.Item
data-slot="navigation-menu-item"
- className={cn("relative", className)}
+ className={cn('relative', className)}
{...props}
/>
)
}
const navigationMenuTriggerStyle = cva(
- "group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1"
+ 'group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1'
)
function NavigationMenuTrigger({
@@ -70,10 +67,10 @@ function NavigationMenuTrigger({
return (
<NavigationMenuPrimitive.Trigger
data-slot="navigation-menu-trigger"
- className={cn(navigationMenuTriggerStyle(), "group", className)}
+ className={cn(navigationMenuTriggerStyle(), 'group', className)}
{...props}
>
- {children}{" "}
+ {children}{' '}
<ChevronDownIcon
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
aria-hidden="true"
@@ -90,8 +87,8 @@ function NavigationMenuContent({
<NavigationMenuPrimitive.Content
data-slot="navigation-menu-content"
className={cn(
- "data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
- "group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
+ 'data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto',
+ 'group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none',
className
)}
{...props}
@@ -104,15 +101,11 @@ function NavigationMenuViewport({
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
return (
- <div
- className={cn(
- "absolute top-full left-0 isolate z-50 flex justify-center"
- )}
- >
+ <div className={cn('absolute top-full left-0 isolate z-50 flex justify-center')}>
<NavigationMenuPrimitive.Viewport
data-slot="navigation-menu-viewport"
className={cn(
- "origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
+ 'origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]',
className
)}
{...props}
@@ -145,7 +138,7 @@ function NavigationMenuIndicator({
<NavigationMenuPrimitive.Indicator
data-slot="navigation-menu-indicator"
className={cn(
- "data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
+ 'data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden',
className
)}
{...props}
@@ -164,5 +157,5 @@ export {
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
- navigationMenuTriggerStyle,
+ navigationMenuTriggerStyle
}
diff --git a/flowsint-app/src/renderer/src/components/ui/pagination.tsx b/flowsint-app/src/renderer/src/components/ui/pagination.tsx
index 0d185410..4747c8ef 100644
--- a/flowsint-app/src/renderer/src/components/ui/pagination.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/pagination.tsx
@@ -1,62 +1,50 @@
-import * as React from "react"
-import {
- ChevronLeftIcon,
- ChevronRightIcon,
- MoreHorizontalIcon,
-} from "lucide-react"
+import * as React from 'react'
+import { ChevronLeftIcon, ChevronRightIcon, MoreHorizontalIcon } from 'lucide-react'
-import { cn } from "@/lib/utils"
-import { Button, buttonVariants } from "@/components/ui/button"
+import { cn } from '@/lib/utils'
+import { Button, buttonVariants } from '@/components/ui/button'
-function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
+function Pagination({ className, ...props }: React.ComponentProps<'nav'>) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
- className={cn("mx-auto flex w-full justify-center", className)}
+ className={cn('mx-auto flex w-full justify-center', className)}
{...props}
/>
)
}
-function PaginationContent({
- className,
- ...props
-}: React.ComponentProps<"ul">) {
+function PaginationContent({ className, ...props }: React.ComponentProps<'ul'>) {
return (
<ul
data-slot="pagination-content"
- className={cn("flex flex-row items-center gap-1", className)}
+ className={cn('flex flex-row items-center gap-1', className)}
{...props}
/>
)
}
-function PaginationItem({ ...props }: React.ComponentProps<"li">) {
+function PaginationItem({ ...props }: React.ComponentProps<'li'>) {
return <li data-slot="pagination-item" {...props} />
}
type PaginationLinkProps = {
isActive?: boolean
-} & Pick<React.ComponentProps<typeof Button>, "size"> &
- React.ComponentProps<"a">
+} & Pick<React.ComponentProps<typeof Button>, 'size'> &
+ React.ComponentProps<'a'>
-function PaginationLink({
- className,
- isActive,
- size = "icon",
- ...props
-}: PaginationLinkProps) {
+function PaginationLink({ className, isActive, size = 'icon', ...props }: PaginationLinkProps) {
return (
<a
- aria-current={isActive ? "page" : undefined}
+ aria-current={isActive ? 'page' : undefined}
data-slot="pagination-link"
data-active={isActive}
className={cn(
buttonVariants({
- variant: isActive ? "outline" : "ghost",
- size,
+ variant: isActive ? 'outline' : 'ghost',
+ size
}),
className
)}
@@ -65,15 +53,12 @@ function PaginationLink({
)
}
-function PaginationPrevious({
- className,
- ...props
-}: React.ComponentProps<typeof PaginationLink>) {
+function PaginationPrevious({ className, ...props }: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
- className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
+ className={cn('gap-1 px-2.5 sm:pl-2.5', className)}
{...props}
>
<ChevronLeftIcon />
@@ -82,15 +67,12 @@ function PaginationPrevious({
)
}
-function PaginationNext({
- className,
- ...props
-}: React.ComponentProps<typeof PaginationLink>) {
+function PaginationNext({ className, ...props }: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
- className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
+ className={cn('gap-1 px-2.5 sm:pr-2.5', className)}
{...props}
>
<span className="hidden sm:block">Next</span>
@@ -99,15 +81,12 @@ function PaginationNext({
)
}
-function PaginationEllipsis({
- className,
- ...props
-}: React.ComponentProps<"span">) {
+function PaginationEllipsis({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
- className={cn("flex size-9 items-center justify-center", className)}
+ className={cn('flex size-9 items-center justify-center', className)}
{...props}
>
<MoreHorizontalIcon className="size-4" />
@@ -123,5 +102,5 @@ export {
PaginationItem,
PaginationPrevious,
PaginationNext,
- PaginationEllipsis,
+ PaginationEllipsis
}
diff --git a/flowsint-app/src/renderer/src/components/ui/popover.tsx b/flowsint-app/src/renderer/src/components/ui/popover.tsx
index 40d08490..3d380b20 100644
--- a/flowsint-app/src/renderer/src/components/ui/popover.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/popover.tsx
@@ -1,24 +1,19 @@
+import * as React from 'react'
+import * as PopoverPrimitive from '@radix-ui/react-popover'
-import * as React from "react"
-import * as PopoverPrimitive from "@radix-ui/react-popover"
+import { cn } from '@/lib/utils'
-import { cn } from "@/lib/utils"
-
-function Popover({
- ...props
-}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
+function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
-function PopoverTrigger({
- ...props
-}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
+function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
- align = "center",
+ align = 'center',
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
@@ -29,7 +24,7 @@ function PopoverContent({
align={align}
sideOffset={sideOffset}
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden',
className
)}
{...props}
@@ -38,9 +33,7 @@ function PopoverContent({
)
}
-function PopoverAnchor({
- ...props
-}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
+function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
diff --git a/flowsint-app/src/renderer/src/components/ui/progress.tsx b/flowsint-app/src/renderer/src/components/ui/progress.tsx
index 10af7e63..456313ab 100644
--- a/flowsint-app/src/renderer/src/components/ui/progress.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/progress.tsx
@@ -1,7 +1,7 @@
-import * as React from "react"
-import * as ProgressPrimitive from "@radix-ui/react-progress"
+import * as React from 'react'
+import * as ProgressPrimitive from '@radix-ui/react-progress'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function Progress({
className,
@@ -11,10 +11,7 @@ function Progress({
return (
<ProgressPrimitive.Root
data-slot="progress"
- className={cn(
- "bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
- className
- )}
+ className={cn('bg-primary/20 relative h-2 w-full overflow-hidden rounded-full', className)}
{...props}
>
<ProgressPrimitive.Indicator
diff --git a/flowsint-app/src/renderer/src/components/ui/radio-group.tsx b/flowsint-app/src/renderer/src/components/ui/radio-group.tsx
index 2fb41270..14d61a65 100644
--- a/flowsint-app/src/renderer/src/components/ui/radio-group.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/radio-group.tsx
@@ -1,9 +1,8 @@
+import * as React from 'react'
+import * as RadioGroupPrimitive from '@radix-ui/react-radio-group'
+import { CircleIcon } from 'lucide-react'
-import * as React from "react"
-import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
-import { CircleIcon } from "lucide-react"
-
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function RadioGroup({
className,
@@ -12,7 +11,7 @@ function RadioGroup({
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
- className={cn("grid gap-3", className)}
+ className={cn('grid gap-3', className)}
{...props}
/>
)
@@ -26,7 +25,7 @@ function RadioGroupItem({
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
- "border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
+ 'border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/resizable.tsx b/flowsint-app/src/renderer/src/components/ui/resizable.tsx
index fe0ebbde..7a643846 100644
--- a/flowsint-app/src/renderer/src/components/ui/resizable.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/resizable.tsx
@@ -1,8 +1,8 @@
-import * as React from "react"
-import { GripVerticalIcon } from "lucide-react"
-import * as ResizablePrimitive from "react-resizable-panels"
+import * as React from 'react'
+import { GripVerticalIcon } from 'lucide-react'
+import * as ResizablePrimitive from 'react-resizable-panels'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function ResizablePanelGroup({
className,
@@ -11,18 +11,13 @@ function ResizablePanelGroup({
return (
<ResizablePrimitive.PanelGroup
data-slot="resizable-panel-group"
- className={cn(
- "flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
- className
- )}
+ className={cn('flex h-full w-full data-[panel-group-direction=vertical]:flex-col', className)}
{...props}
/>
)
}
-function ResizablePanel({
- ...props
-}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
+function ResizablePanel({ ...props }: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />
}
@@ -37,7 +32,7 @@ function ResizableHandle({
<ResizablePrimitive.PanelResizeHandle
data-slot="resizable-handle"
className={cn(
- "bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",
+ 'bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/scroll-area.tsx b/flowsint-app/src/renderer/src/components/ui/scroll-area.tsx
index 4274ea61..6f07cf6a 100644
--- a/flowsint-app/src/renderer/src/components/ui/scroll-area.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/scroll-area.tsx
@@ -1,8 +1,7 @@
+import * as React from 'react'
+import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'
-import * as React from "react"
-import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
-
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function ScrollArea({
className,
@@ -12,7 +11,7 @@ function ScrollArea({
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
- className={cn("relative", className)}
+ className={cn('relative', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
@@ -29,7 +28,7 @@ function ScrollArea({
function ScrollBar({
className,
- orientation = "vertical",
+ orientation = 'vertical',
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
@@ -37,11 +36,9 @@ function ScrollBar({
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
- "flex touch-none p-px transition-colors select-none",
- orientation === "vertical" &&
- "h-full w-2.5 border-l border-l-transparent",
- orientation === "horizontal" &&
- "h-2.5 flex-col border-t border-t-transparent",
+ 'flex touch-none p-px transition-colors select-none',
+ orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent',
+ orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/select.tsx b/flowsint-app/src/renderer/src/components/ui/select.tsx
index 88d43707..433e829a 100644
--- a/flowsint-app/src/renderer/src/components/ui/select.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/select.tsx
@@ -1,34 +1,28 @@
-import * as React from "react"
-import * as SelectPrimitive from "@radix-ui/react-select"
-import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
+import * as React from 'react'
+import * as SelectPrimitive from '@radix-ui/react-select'
+import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Select({
- ...props
-}: React.ComponentProps<typeof SelectPrimitive.Root>) {
+function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
-function SelectGroup({
- ...props
-}: React.ComponentProps<typeof SelectPrimitive.Group>) {
+function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
-function SelectValue({
- ...props
-}: React.ComponentProps<typeof SelectPrimitive.Value>) {
+function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
- size = "default",
+ size = 'default',
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
- size?: "sm" | "default"
+ size?: 'sm' | 'default'
}) {
return (
<SelectPrimitive.Trigger
@@ -51,7 +45,7 @@ function SelectTrigger({
function SelectContent({
className,
children,
- position = "popper",
+ position = 'popper',
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
@@ -59,9 +53,9 @@ function SelectContent({
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
- "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
- position === "popper" &&
- "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
+ 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md',
+ position === 'popper' &&
+ 'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className
)}
position={position}
@@ -70,9 +64,9 @@ function SelectContent({
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
- "p-1",
- position === "popper" &&
- "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
+ 'p-1',
+ position === 'popper' &&
+ 'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1'
)}
>
{children}
@@ -83,14 +77,11 @@ function SelectContent({
)
}
-function SelectLabel({
- className,
- ...props
-}: React.ComponentProps<typeof SelectPrimitive.Label>) {
+function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
- className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
+ className={cn('text-muted-foreground px-2 py-1.5 text-xs', className)}
{...props}
/>
)
@@ -127,7 +118,7 @@ function SelectSeparator({
return (
<SelectPrimitive.Separator
data-slot="select-separator"
- className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
+ className={cn('bg-border pointer-events-none -mx-1 my-1 h-px', className)}
{...props}
/>
)
@@ -140,10 +131,7 @@ function SelectScrollUpButton({
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
- className={cn(
- "flex cursor-default items-center justify-center py-1",
- className
- )}
+ className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronUpIcon className="size-4" />
@@ -158,10 +146,7 @@ function SelectScrollDownButton({
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
- className={cn(
- "flex cursor-default items-center justify-center py-1",
- className
- )}
+ className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronDownIcon className="size-4" />
@@ -179,5 +164,5 @@ export {
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
- SelectValue,
+ SelectValue
}
diff --git a/flowsint-app/src/renderer/src/components/ui/separator.tsx b/flowsint-app/src/renderer/src/components/ui/separator.tsx
index f331b1ae..89e6bcb7 100644
--- a/flowsint-app/src/renderer/src/components/ui/separator.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/separator.tsx
@@ -1,12 +1,11 @@
+import * as React from 'react'
+import * as SeparatorPrimitive from '@radix-ui/react-separator'
-import * as React from "react"
-import * as SeparatorPrimitive from "@radix-ui/react-separator"
-
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function Separator({
className,
- orientation = "horizontal",
+ orientation = 'horizontal',
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
@@ -16,7 +15,7 @@ function Separator({
decorative={decorative}
orientation={orientation}
className={cn(
- "bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
+ 'bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/sheet.tsx b/flowsint-app/src/renderer/src/components/ui/sheet.tsx
index d8c92903..69a6d6fc 100644
--- a/flowsint-app/src/renderer/src/components/ui/sheet.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/sheet.tsx
@@ -1,28 +1,22 @@
-import * as React from "react"
-import * as SheetPrimitive from "@radix-ui/react-dialog"
-import { XIcon } from "lucide-react"
+import * as React from 'react'
+import * as SheetPrimitive from '@radix-ui/react-dialog'
+import { XIcon } from 'lucide-react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
-function SheetTrigger({
- ...props
-}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
+function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
-function SheetClose({
- ...props
-}: React.ComponentProps<typeof SheetPrimitive.Close>) {
+function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
-function SheetPortal({
- ...props
-}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
+function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
@@ -34,7 +28,7 @@ function SheetOverlay({
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/30",
+ 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/30',
className
)}
{...props}
@@ -45,10 +39,10 @@ function SheetOverlay({
function SheetContent({
className,
children,
- side = "right",
+ side = 'right',
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
- side?: "top" | "right" | "bottom" | "left"
+ side?: 'top' | 'right' | 'bottom' | 'left'
}) {
return (
<SheetPortal>
@@ -56,15 +50,15 @@ function SheetContent({
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
- "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-300",
- side === "right" &&
- "data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
- side === "left" &&
- "data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
- side === "top" &&
- "data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
- side === "bottom" &&
- "data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
+ 'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-300',
+ side === 'right' &&
+ 'data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm',
+ side === 'left' &&
+ 'data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm',
+ side === 'top' &&
+ 'data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b',
+ side === 'bottom' &&
+ 'data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t',
className
)}
{...props}
@@ -79,34 +73,31 @@ function SheetContent({
)
}
-function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
+function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-header"
- className={cn("flex flex-col gap-1.5 p-4", className)}
+ className={cn('flex flex-col gap-1.5 p-4', className)}
{...props}
/>
)
}
-function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
+function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-footer"
- className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ className={cn('mt-auto flex flex-col gap-2 p-4', className)}
{...props}
/>
)
}
-function SheetTitle({
- className,
- ...props
-}: React.ComponentProps<typeof SheetPrimitive.Title>) {
+function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
- className={cn("text-foreground font-semibold", className)}
+ className={cn('text-foreground font-semibold', className)}
{...props}
/>
)
@@ -119,7 +110,7 @@ function SheetDescription({
return (
<SheetPrimitive.Description
data-slot="sheet-description"
- className={cn("text-muted-foreground text-sm", className)}
+ className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
)
@@ -133,5 +124,5 @@ export {
SheetHeader,
SheetFooter,
SheetTitle,
- SheetDescription,
+ SheetDescription
}
diff --git a/flowsint-app/src/renderer/src/components/ui/sidebar.tsx b/flowsint-app/src/renderer/src/components/ui/sidebar.tsx
index 5db2f593..27ac5f16 100644
--- a/flowsint-app/src/renderer/src/components/ui/sidebar.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/sidebar.tsx
@@ -1,38 +1,32 @@
-
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, VariantProps } from "class-variance-authority"
-import { PanelLeftIcon } from "lucide-react"
-
-import { useIsMobile } from "@/hooks/use-mobile"
-import { cn } from "@/lib/utils"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Separator } from "@/components/ui/separator"
+import * as React from 'react'
+import { Slot } from '@radix-ui/react-slot'
+import { cva, VariantProps } from 'class-variance-authority'
+import { PanelLeftIcon } from 'lucide-react'
+
+import { useIsMobile } from '@/hooks/use-mobile'
+import { cn } from '@/lib/utils'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Separator } from '@/components/ui/separator'
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
- SheetTitle,
-} from "@/components/ui/sheet"
-import { Skeleton } from "@/components/ui/skeleton"
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/ui/tooltip"
+ SheetTitle
+} from '@/components/ui/sheet'
+import { Skeleton } from '@/components/ui/skeleton'
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
-const SIDEBAR_COOKIE_NAME = "sidebar_state"
+const SIDEBAR_COOKIE_NAME = 'sidebar_state'
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
-const SIDEBAR_WIDTH = "16rem"
-const SIDEBAR_WIDTH_MOBILE = "18rem"
-const SIDEBAR_WIDTH_ICON = "3rem"
-const SIDEBAR_KEYBOARD_SHORTCUT = "b"
+const SIDEBAR_WIDTH = '16rem'
+const SIDEBAR_WIDTH_MOBILE = '18rem'
+const SIDEBAR_WIDTH_ICON = '3rem'
+const SIDEBAR_KEYBOARD_SHORTCUT = 'b'
type SidebarContextProps = {
- state: "expanded" | "collapsed"
+ state: 'expanded' | 'collapsed'
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
@@ -46,7 +40,7 @@ const SidebarContext = React.createContext<SidebarContextProps | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
- throw new Error("useSidebar must be used within a SidebarProvider.")
+ throw new Error('useSidebar must be used within a SidebarProvider.')
}
return context
@@ -60,7 +54,7 @@ function SidebarProvider({
style,
children,
...props
-}: React.ComponentProps<"div"> & {
+}: React.ComponentProps<'div'> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
@@ -74,7 +68,7 @@ function SidebarProvider({
const open = openProp ?? _open
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
- const openState = typeof value === "function" ? value(open) : value
+ const openState = typeof value === 'function' ? value(open) : value
if (setOpenProp) {
setOpenProp(openState)
} else {
@@ -95,22 +89,19 @@ function SidebarProvider({
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
- if (
- event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
- (event.metaKey || event.ctrlKey)
- ) {
+ if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
event.preventDefault()
toggleSidebar()
}
}
- window.addEventListener("keydown", handleKeyDown)
- return () => window.removeEventListener("keydown", handleKeyDown)
+ window.addEventListener('keydown', handleKeyDown)
+ return () => window.removeEventListener('keydown', handleKeyDown)
}, [toggleSidebar])
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
- const state = open ? "expanded" : "collapsed"
+ const state = open ? 'expanded' : 'collapsed'
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
@@ -120,7 +111,7 @@ function SidebarProvider({
isMobile,
openMobile,
setOpenMobile,
- toggleSidebar,
+ toggleSidebar
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
@@ -132,13 +123,13 @@ function SidebarProvider({
data-slot="sidebar-wrapper"
style={
{
- "--sidebar-width": SIDEBAR_WIDTH,
- "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
- ...style,
+ '--sidebar-width': SIDEBAR_WIDTH,
+ '--sidebar-width-icon': SIDEBAR_WIDTH_ICON,
+ ...style
} as React.CSSProperties
}
className={cn(
- "group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
+ 'group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full',
className
)}
{...props}
@@ -151,25 +142,25 @@ function SidebarProvider({
}
function Sidebar({
- side = "left",
- variant = "sidebar",
- collapsible = "offcanvas",
+ side = 'left',
+ variant = 'sidebar',
+ collapsible = 'offcanvas',
className,
children,
...props
-}: React.ComponentProps<"div"> & {
- side?: "left" | "right"
- variant?: "sidebar" | "floating" | "inset"
- collapsible?: "offcanvas" | "icon" | "none"
+}: React.ComponentProps<'div'> & {
+ side?: 'left' | 'right'
+ variant?: 'sidebar' | 'floating' | 'inset'
+ collapsible?: 'offcanvas' | 'icon' | 'none'
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
- if (collapsible === "none") {
+ if (collapsible === 'none') {
return (
<div
data-slot="sidebar"
className={cn(
- "bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
+ 'bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col',
className
)}
{...props}
@@ -189,7 +180,7 @@ function Sidebar({
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
- "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
+ '--sidebar-width': SIDEBAR_WIDTH_MOBILE
} as React.CSSProperties
}
side={side}
@@ -208,7 +199,7 @@ function Sidebar({
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
- data-collapsible={state === "collapsed" ? collapsible : ""}
+ data-collapsible={state === 'collapsed' ? collapsible : ''}
data-variant={variant}
data-side={side}
data-slot="sidebar"
@@ -217,25 +208,25 @@ function Sidebar({
<div
data-slot="sidebar-gap"
className={cn(
- "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
- "group-data-[collapsible=offcanvas]:w-0",
- "group-data-[side=right]:rotate-180",
- variant === "floating" || variant === "inset"
- ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
- : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
+ 'relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear',
+ 'group-data-[collapsible=offcanvas]:w-0',
+ 'group-data-[side=right]:rotate-180',
+ variant === 'floating' || variant === 'inset'
+ ? 'group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]'
+ : 'group-data-[collapsible=icon]:w-(--sidebar-width-icon)'
)}
/>
<div
data-slot="sidebar-container"
className={cn(
- "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
- side === "left"
- ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
- : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
+ 'fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex',
+ side === 'left'
+ ? 'left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]'
+ : 'right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]',
// Adjust the padding for floating and inset variants.
- variant === "floating" || variant === "inset"
- ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
- : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
+ variant === 'floating' || variant === 'inset'
+ ? 'p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]'
+ : 'group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l',
className
)}
{...props}
@@ -252,11 +243,7 @@ function Sidebar({
)
}
-function SidebarTrigger({
- className,
- onClick,
- ...props
-}: React.ComponentProps<typeof Button>) {
+function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
return (
@@ -265,7 +252,7 @@ function SidebarTrigger({
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
- className={cn("size-7", className)}
+ className={cn('size-7', className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
@@ -278,7 +265,7 @@ function SidebarTrigger({
)
}
-function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
+function SidebarRail({ className, ...props }: React.ComponentProps<'button'>) {
const { toggleSidebar } = useSidebar()
return (
@@ -290,12 +277,12 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
- "hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
- "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
- "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
- "hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
- "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
- "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
+ 'hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex',
+ 'in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize',
+ '[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize',
+ 'hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full',
+ '[[data-side=left][data-collapsible=offcanvas]_&]:-right-2',
+ '[[data-side=right][data-collapsible=offcanvas]_&]:-left-2',
className
)}
{...props}
@@ -303,13 +290,13 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
)
}
-function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
+function SidebarInset({ className, ...props }: React.ComponentProps<'main'>) {
return (
<main
data-slot="sidebar-inset"
className={cn(
- "bg-background relative flex w-full flex-1 flex-col",
- "md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
+ 'bg-background relative flex w-full flex-1 flex-col',
+ 'md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2',
className
)}
{...props}
@@ -317,63 +304,57 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
)
}
-function SidebarInput({
- className,
- ...props
-}: React.ComponentProps<typeof Input>) {
+function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
- className={cn("bg-background h-8 w-full shadow-none", className)}
+ className={cn('bg-background h-8 w-full shadow-none', className)}
{...props}
/>
)
}
-function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
+function SidebarHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
- className={cn("flex flex-col gap-2 p-2", className)}
+ className={cn('flex flex-col gap-2 p-2', className)}
{...props}
/>
)
}
-function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
+function SidebarFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
- className={cn("flex flex-col gap-2 p-2", className)}
+ className={cn('flex flex-col gap-2 p-2', className)}
{...props}
/>
)
}
-function SidebarSeparator({
- className,
- ...props
-}: React.ComponentProps<typeof Separator>) {
+function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
- className={cn("bg-sidebar-border mx-2 w-auto", className)}
+ className={cn('bg-sidebar-border mx-2 w-auto', className)}
{...props}
/>
)
}
-function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
+function SidebarContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
- "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
+ 'flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden',
className
)}
{...props}
@@ -381,12 +362,12 @@ function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
)
}
-function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
+function SidebarGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
- className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
+ className={cn('relative flex w-full min-w-0 flex-col p-2', className)}
{...props}
/>
)
@@ -396,16 +377,16 @@ function SidebarGroupLabel({
className,
asChild = false,
...props
-}: React.ComponentProps<"div"> & { asChild?: boolean }) {
- const Comp = asChild ? Slot : "div"
+}: React.ComponentProps<'div'> & { asChild?: boolean }) {
+ const Comp = asChild ? Slot : 'div'
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
- "text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
- "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
+ 'text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',
+ 'group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0',
className
)}
{...props}
@@ -417,18 +398,18 @@ function SidebarGroupAction({
className,
asChild = false,
...props
-}: React.ComponentProps<"button"> & { asChild?: boolean }) {
- const Comp = asChild ? Slot : "button"
+}: React.ComponentProps<'button'> & { asChild?: boolean }) {
+ const Comp = asChild ? Slot : 'button'
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ 'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',
// Increases the hit area of the button on mobile.
- "after:absolute after:-inset-2 md:after:hidden",
- "group-data-[collapsible=icon]:hidden",
+ 'after:absolute after:-inset-2 md:after:hidden',
+ 'group-data-[collapsible=icon]:hidden',
className
)}
{...props}
@@ -436,78 +417,75 @@ function SidebarGroupAction({
)
}
-function SidebarGroupContent({
- className,
- ...props
-}: React.ComponentProps<"div">) {
+function SidebarGroupContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
- className={cn("w-full text-sm", className)}
+ className={cn('w-full text-sm', className)}
{...props}
/>
)
}
-function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
+function SidebarMenu({ className, ...props }: React.ComponentProps<'ul'>) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
- className={cn("flex w-full min-w-0 flex-col gap-1", className)}
+ className={cn('flex w-full min-w-0 flex-col gap-1', className)}
{...props}
/>
)
}
-function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
+function SidebarMenuItem({ className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
- className={cn("group/menu-item relative", className)}
+ className={cn('group/menu-item relative', className)}
{...props}
/>
)
}
const sidebarMenuButtonVariants = cva(
- "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ 'peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0',
{
variants: {
variant: {
- default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
+ default: 'hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
outline:
- "bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
+ 'bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]'
},
size: {
- default: "h-8 text-sm",
- sm: "h-7 text-xs",
- lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
- },
+ default: 'h-8 text-sm',
+ sm: 'h-7 text-xs',
+ lg: 'h-12 text-sm group-data-[collapsible=icon]:p-0!'
+ }
},
defaultVariants: {
- variant: "default",
- size: "default",
- },
+ variant: 'default',
+ size: 'default'
+ }
}
)
function SidebarMenuButton({
asChild = false,
isActive = false,
- variant = "default",
- size = "default",
+ variant = 'default',
+ size = 'default',
tooltip,
className,
...props
-}: React.ComponentProps<"button"> & {
+}: React.ComponentProps<'button'> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
} & VariantProps<typeof sidebarMenuButtonVariants>) {
- const Comp = asChild ? Slot : "button"
+ const Comp = asChild ? Slot : 'button'
const { isMobile, state } = useSidebar()
const button = (
@@ -525,9 +503,9 @@ function SidebarMenuButton({
return button
}
- if (typeof tooltip === "string") {
+ if (typeof tooltip === 'string') {
tooltip = {
- children: tooltip,
+ children: tooltip
}
}
@@ -537,7 +515,7 @@ function SidebarMenuButton({
<TooltipContent
side="right"
align="center"
- hidden={state !== "collapsed" || isMobile}
+ hidden={state !== 'collapsed' || isMobile}
{...tooltip}
/>
</Tooltip>
@@ -549,26 +527,26 @@ function SidebarMenuAction({
asChild = false,
showOnHover = false,
...props
-}: React.ComponentProps<"button"> & {
+}: React.ComponentProps<'button'> & {
asChild?: boolean
showOnHover?: boolean
}) {
- const Comp = asChild ? Slot : "button"
+ const Comp = asChild ? Slot : 'button'
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ 'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',
// Increases the hit area of the button on mobile.
- "after:absolute after:-inset-2 md:after:hidden",
- "peer-data-[size=sm]/menu-button:top-1",
- "peer-data-[size=default]/menu-button:top-1.5",
- "peer-data-[size=lg]/menu-button:top-2.5",
- "group-data-[collapsible=icon]:hidden",
+ 'after:absolute after:-inset-2 md:after:hidden',
+ 'peer-data-[size=sm]/menu-button:top-1',
+ 'peer-data-[size=default]/menu-button:top-1.5',
+ 'peer-data-[size=lg]/menu-button:top-2.5',
+ 'group-data-[collapsible=icon]:hidden',
showOnHover &&
- "peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
+ 'peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0',
className
)}
{...props}
@@ -576,21 +554,18 @@ function SidebarMenuAction({
)
}
-function SidebarMenuBadge({
- className,
- ...props
-}: React.ComponentProps<"div">) {
+function SidebarMenuBadge({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
- "text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
- "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
- "peer-data-[size=sm]/menu-button:top-1",
- "peer-data-[size=default]/menu-button:top-1.5",
- "peer-data-[size=lg]/menu-button:top-2.5",
- "group-data-[collapsible=icon]:hidden",
+ 'text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none',
+ 'peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground',
+ 'peer-data-[size=sm]/menu-button:top-1',
+ 'peer-data-[size=default]/menu-button:top-1.5',
+ 'peer-data-[size=lg]/menu-button:top-2.5',
+ 'group-data-[collapsible=icon]:hidden',
className
)}
{...props}
@@ -602,7 +577,7 @@ function SidebarMenuSkeleton({
className,
showIcon = false,
...props
-}: React.ComponentProps<"div"> & {
+}: React.ComponentProps<'div'> & {
showIcon?: boolean
}) {
// Random width between 50 to 90%.
@@ -614,21 +589,16 @@ function SidebarMenuSkeleton({
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
- className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
+ className={cn('flex h-8 items-center gap-2 rounded-md px-2', className)}
{...props}
>
- {showIcon && (
- <Skeleton
- className="size-4 rounded-md"
- data-sidebar="menu-skeleton-icon"
- />
- )}
+ {showIcon && <Skeleton className="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
- "--skeleton-width": width,
+ '--skeleton-width': width
} as React.CSSProperties
}
/>
@@ -636,14 +606,14 @@ function SidebarMenuSkeleton({
)
}
-function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
+function SidebarMenuSub({ className, ...props }: React.ComponentProps<'ul'>) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
- "border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
- "group-data-[collapsible=icon]:hidden",
+ 'border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5',
+ 'group-data-[collapsible=icon]:hidden',
className
)}
{...props}
@@ -651,15 +621,12 @@ function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
)
}
-function SidebarMenuSubItem({
- className,
- ...props
-}: React.ComponentProps<"li">) {
+function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
- className={cn("group/menu-sub-item relative", className)}
+ className={cn('group/menu-sub-item relative', className)}
{...props}
/>
)
@@ -667,16 +634,16 @@ function SidebarMenuSubItem({
function SidebarMenuSubButton({
asChild = false,
- size = "md",
+ size = 'md',
isActive = false,
className,
...props
-}: React.ComponentProps<"a"> & {
+}: React.ComponentProps<'a'> & {
asChild?: boolean
- size?: "sm" | "md"
+ size?: 'sm' | 'md'
isActive?: boolean
}) {
- const Comp = asChild ? Slot : "a"
+ const Comp = asChild ? Slot : 'a'
return (
<Comp
@@ -685,11 +652,11 @@ function SidebarMenuSubButton({
data-size={size}
data-active={isActive}
className={cn(
- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
- "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
- size === "sm" && "text-xs",
- size === "md" && "text-sm",
- "group-data-[collapsible=icon]:hidden",
+ 'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0',
+ 'data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground',
+ size === 'sm' && 'text-xs',
+ size === 'md' && 'text-sm',
+ 'group-data-[collapsible=icon]:hidden',
className
)}
{...props}
@@ -721,5 +688,5 @@ export {
SidebarRail,
SidebarSeparator,
SidebarTrigger,
- useSidebar,
+ useSidebar
}
diff --git a/flowsint-app/src/renderer/src/components/ui/skeleton.tsx b/flowsint-app/src/renderer/src/components/ui/skeleton.tsx
index ec40cc78..72a02ee5 100644
--- a/flowsint-app/src/renderer/src/components/ui/skeleton.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/skeleton.tsx
@@ -1,10 +1,10 @@
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
+function Skeleton({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="skeleton"
- className={cn("bg-foreground/10 animate-pulse rounded-md", className)}
+ className={cn('bg-foreground/10 animate-pulse rounded-md', className)}
{...props}
/>
)
diff --git a/flowsint-app/src/renderer/src/components/ui/slider.tsx b/flowsint-app/src/renderer/src/components/ui/slider.tsx
index 234fd5b7..b8890d1b 100644
--- a/flowsint-app/src/renderer/src/components/ui/slider.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/slider.tsx
@@ -1,8 +1,7 @@
+import * as React from 'react'
+import * as SliderPrimitive from '@radix-ui/react-slider'
-import * as React from "react"
-import * as SliderPrimitive from "@radix-ui/react-slider"
-
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function Slider({
className,
@@ -13,12 +12,7 @@ function Slider({
...props
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
const _values = React.useMemo(
- () =>
- Array.isArray(value)
- ? value
- : Array.isArray(defaultValue)
- ? defaultValue
- : [min, max],
+ () => (Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max]),
[value, defaultValue, min, max]
)
@@ -30,7 +24,7 @@ function Slider({
min={min}
max={max}
className={cn(
- "relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
+ 'relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col',
className
)}
{...props}
@@ -38,13 +32,13 @@ function Slider({
<SliderPrimitive.Track
data-slot="slider-track"
className={cn(
- "bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
+ 'bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5'
)}
>
<SliderPrimitive.Range
data-slot="slider-range"
className={cn(
- "bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
+ 'bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full'
)}
/>
</SliderPrimitive.Track>
diff --git a/flowsint-app/src/renderer/src/components/ui/sonner.tsx b/flowsint-app/src/renderer/src/components/ui/sonner.tsx
index cd62aff2..fdd8b98b 100644
--- a/flowsint-app/src/renderer/src/components/ui/sonner.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/sonner.tsx
@@ -1,18 +1,18 @@
-import { useTheme } from "next-themes"
-import { Toaster as Sonner, ToasterProps } from "sonner"
+import { useTheme } from 'next-themes'
+import { Toaster as Sonner, ToasterProps } from 'sonner'
const Toaster = ({ ...props }: ToasterProps) => {
- const { theme = "system" } = useTheme()
+ const { theme = 'system' } = useTheme()
return (
<Sonner
- theme={theme as ToasterProps["theme"]}
+ theme={theme as ToasterProps['theme']}
className="toaster group"
style={
{
- "--normal-bg": "var(--popover)",
- "--normal-text": "var(--popover-foreground)",
- "--normal-border": "var(--border)",
+ '--normal-bg': 'var(--popover)',
+ '--normal-text': 'var(--popover-foreground)',
+ '--normal-border': 'var(--border)'
} as React.CSSProperties
}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/switch.tsx b/flowsint-app/src/renderer/src/components/ui/switch.tsx
index 802c8a90..9649c25c 100644
--- a/flowsint-app/src/renderer/src/components/ui/switch.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/switch.tsx
@@ -1,18 +1,14 @@
+import * as React from 'react'
+import * as SwitchPrimitive from '@radix-ui/react-switch'
-import * as React from "react"
-import * as SwitchPrimitive from "@radix-ui/react-switch"
+import { cn } from '@/lib/utils'
-import { cn } from "@/lib/utils"
-
-function Switch({
- className,
- ...props
-}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
+function Switch({ className, ...props }: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
- "peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
+ 'peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
@@ -20,7 +16,7 @@ function Switch({
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
- "bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
+ 'bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0'
)}
/>
</SwitchPrimitive.Root>
diff --git a/flowsint-app/src/renderer/src/components/ui/table.tsx b/flowsint-app/src/renderer/src/components/ui/table.tsx
index 5513a5cd..02b1e52c 100644
--- a/flowsint-app/src/renderer/src/components/ui/table.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/table.tsx
@@ -1,61 +1,49 @@
-import * as React from "react"
+import * as React from 'react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Table({ className, ...props }: React.ComponentProps<"table">) {
+function Table({ className, ...props }: React.ComponentProps<'table'>) {
return (
- <div
- data-slot="table-container"
- className="relative w-full overflow-x-auto"
- >
+ <div data-slot="table-container" className="relative w-full overflow-x-auto">
<table
data-slot="table"
- className={cn("w-full caption-bottom text-sm", className)}
+ className={cn('w-full caption-bottom text-sm', className)}
{...props}
/>
</div>
)
}
-function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
- return (
- <thead
- data-slot="table-header"
- className={cn("[&_tr]:border-b", className)}
- {...props}
- />
- )
+function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
+ return <thead data-slot="table-header" className={cn('[&_tr]:border-b', className)} {...props} />
}
-function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
+function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {
return (
<tbody
data-slot="table-body"
- className={cn("[&_tr:last-child]:border-0", className)}
+ className={cn('[&_tr:last-child]:border-0', className)}
{...props}
/>
)
}
-function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
+function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
return (
<tfoot
data-slot="table-footer"
- className={cn(
- "bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
- className
- )}
+ className={cn('bg-muted/50 border-t font-medium [&>tr]:last:border-b-0', className)}
{...props}
/>
)
}
-function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
+function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
return (
<tr
data-slot="table-row"
className={cn(
- "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
+ 'hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors',
className
)}
{...props}
@@ -63,12 +51,12 @@ function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
)
}
-function TableHead({ className, ...props }: React.ComponentProps<"th">) {
+function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
return (
<th
data-slot="table-head"
className={cn(
- "text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
+ 'text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',
className
)}
{...props}
@@ -76,12 +64,12 @@ function TableHead({ className, ...props }: React.ComponentProps<"th">) {
)
}
-function TableCell({ className, ...props }: React.ComponentProps<"td">) {
+function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
return (
<td
data-slot="table-cell"
className={cn(
- "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
+ 'p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',
className
)}
{...props}
@@ -89,26 +77,14 @@ function TableCell({ className, ...props }: React.ComponentProps<"td">) {
)
}
-function TableCaption({
- className,
- ...props
-}: React.ComponentProps<"caption">) {
+function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {
return (
<caption
data-slot="table-caption"
- className={cn("text-muted-foreground mt-4 text-sm", className)}
+ className={cn('text-muted-foreground mt-4 text-sm', className)}
{...props}
/>
)
}
-export {
- Table,
- TableHeader,
- TableBody,
- TableFooter,
- TableHead,
- TableRow,
- TableCell,
- TableCaption,
-}
+export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption }
diff --git a/flowsint-app/src/renderer/src/components/ui/tabs.tsx b/flowsint-app/src/renderer/src/components/ui/tabs.tsx
index 24217aa8..eb0906cf 100644
--- a/flowsint-app/src/renderer/src/components/ui/tabs.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/tabs.tsx
@@ -1,31 +1,24 @@
+import * as React from 'react'
+import * as TabsPrimitive from '@radix-ui/react-tabs'
-import * as React from "react"
-import * as TabsPrimitive from "@radix-ui/react-tabs"
+import { cn } from '@/lib/utils'
-import { cn } from "@/lib/utils"
-
-function Tabs({
- className,
- ...props
-}: React.ComponentProps<typeof TabsPrimitive.Root>) {
+function Tabs({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
- className={cn("flex flex-col gap-2", className)}
+ className={cn('flex flex-col gap-2', className)}
{...props}
/>
)
}
-function TabsList({
- className,
- ...props
-}: React.ComponentProps<typeof TabsPrimitive.List>) {
+function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
- "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg !p-1",
+ 'bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg !p-1',
className
)}
{...props}
@@ -33,10 +26,7 @@ function TabsList({
)
}
-function TabsTrigger({
- className,
- ...props
-}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
+function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
@@ -49,14 +39,11 @@ function TabsTrigger({
)
}
-function TabsContent({
- className,
- ...props
-}: React.ComponentProps<typeof TabsPrimitive.Content>) {
+function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
- className={cn("flex-1 outline-none", className)}
+ className={cn('flex-1 outline-none', className)}
{...props}
/>
)
diff --git a/flowsint-app/src/renderer/src/components/ui/textarea.tsx b/flowsint-app/src/renderer/src/components/ui/textarea.tsx
index 7f21b5e7..6b1ef4b6 100644
--- a/flowsint-app/src/renderer/src/components/ui/textarea.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/textarea.tsx
@@ -1,13 +1,13 @@
-import * as React from "react"
+import * as React from 'react'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
-function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
+function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
return (
<textarea
data-slot="textarea"
className={cn(
- "border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
+ 'border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/toggle-group.tsx b/flowsint-app/src/renderer/src/components/ui/toggle-group.tsx
index 86c2bef8..49154202 100644
--- a/flowsint-app/src/renderer/src/components/ui/toggle-group.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/toggle-group.tsx
@@ -1,16 +1,13 @@
+import * as React from 'react'
+import * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group'
+import { type VariantProps } from 'class-variance-authority'
-import * as React from "react"
-import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
-import { type VariantProps } from "class-variance-authority"
+import { cn } from '@/lib/utils'
+import { toggleVariants } from '@/components/ui/toggle'
-import { cn } from "@/lib/utils"
-import { toggleVariants } from "@/components/ui/toggle"
-
-const ToggleGroupContext = React.createContext<
- VariantProps<typeof toggleVariants>
->({
- size: "default",
- variant: "default",
+const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
+ size: 'default',
+ variant: 'default'
})
function ToggleGroup({
@@ -19,15 +16,14 @@ function ToggleGroup({
size,
children,
...props
-}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
- VariantProps<typeof toggleVariants>) {
+}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> & VariantProps<typeof toggleVariants>) {
return (
<ToggleGroupPrimitive.Root
data-slot="toggle-group"
data-variant={variant}
data-size={size}
className={cn(
- "group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
+ 'group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs',
className
)}
{...props}
@@ -45,8 +41,7 @@ function ToggleGroupItem({
variant,
size,
...props
-}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
- VariantProps<typeof toggleVariants>) {
+}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> & VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext)
return (
@@ -57,9 +52,9 @@ function ToggleGroupItem({
className={cn(
toggleVariants({
variant: context.variant || variant,
- size: context.size || size,
+ size: context.size || size
}),
- "min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
+ 'min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/ui/toggle.tsx b/flowsint-app/src/renderer/src/components/ui/toggle.tsx
index b9662212..5fb6c611 100644
--- a/flowsint-app/src/renderer/src/components/ui/toggle.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/toggle.tsx
@@ -1,28 +1,28 @@
-import * as React from "react"
-import * as TogglePrimitive from "@radix-ui/react-toggle"
-import { cva, type VariantProps } from "class-variance-authority"
+import * as React from 'react'
+import * as TogglePrimitive from '@radix-ui/react-toggle'
+import { cva, type VariantProps } from 'class-variance-authority'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
{
variants: {
variant: {
- default: "bg-transparent",
+ default: 'bg-transparent',
outline:
- "border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
+ 'border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground'
},
size: {
- default: "h-9 px-2 min-w-9",
- sm: "h-8 px-1.5 min-w-8",
- lg: "h-10 px-2.5 min-w-10",
- },
+ default: 'h-9 px-2 min-w-9',
+ sm: 'h-8 px-1.5 min-w-8',
+ lg: 'h-10 px-2.5 min-w-10'
+ }
},
defaultVariants: {
- variant: "default",
- size: "default",
- },
+ variant: 'default',
+ size: 'default'
+ }
}
)
@@ -31,8 +31,7 @@ function Toggle({
variant,
size,
...props
-}: React.ComponentProps<typeof TogglePrimitive.Root> &
- VariantProps<typeof toggleVariants>) {
+}: React.ComponentProps<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive.Root
data-slot="toggle"
diff --git a/flowsint-app/src/renderer/src/components/ui/tooltip.tsx b/flowsint-app/src/renderer/src/components/ui/tooltip.tsx
index 58f3448b..6d517fbb 100644
--- a/flowsint-app/src/renderer/src/components/ui/tooltip.tsx
+++ b/flowsint-app/src/renderer/src/components/ui/tooltip.tsx
@@ -1,7 +1,7 @@
-import * as React from "react"
-import * as TooltipPrimitive from "@radix-ui/react-tooltip"
+import * as React from 'react'
+import * as TooltipPrimitive from '@radix-ui/react-tooltip'
-import { cn } from "@/lib/utils"
+import { cn } from '@/lib/utils'
function TooltipProvider({
delayDuration = 0,
@@ -16,9 +16,7 @@ function TooltipProvider({
)
}
-function Tooltip({
- ...props
-}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
+function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
@@ -26,9 +24,7 @@ function Tooltip({
)
}
-function TooltipTrigger({
- ...props
-}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
+function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
@@ -44,7 +40,7 @@ function TooltipContent({
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
- "bg-card border animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
+ 'bg-card border animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance',
className
)}
{...props}
diff --git a/flowsint-app/src/renderer/src/components/use-confirm-dialog.tsx b/flowsint-app/src/renderer/src/components/use-confirm-dialog.tsx
index 7c12fda8..998f10f9 100644
--- a/flowsint-app/src/renderer/src/components/use-confirm-dialog.tsx
+++ b/flowsint-app/src/renderer/src/components/use-confirm-dialog.tsx
@@ -1,141 +1,134 @@
-"use client";
+'use client'
import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogTitle,
-} from "@/components/ui/dialog"
-
-import { Button } from "@/components/ui/button";
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogTitle
+} from '@/components/ui/dialog'
+
+import { Button } from '@/components/ui/button'
import React, {
- createContext,
- type ReactNode,
- useCallback,
- useContext,
- useRef,
- useState,
-} from "react";
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useRef,
+ useState
+} from 'react'
// Define a default function for the confirm dialog
-const defaultFunction = (): Promise<boolean> => Promise.resolve(true);
+const defaultFunction = (): Promise<boolean> => Promise.resolve(true)
// Define the props that the ConfirmDialog will use
interface ConfirmProps {
- title: string;
- message: string;
+ title: string
+ message: string
}
// Define the context value shape
interface ConfirmContextValue {
- confirmRef: React.MutableRefObject<(props: ConfirmProps) => Promise<boolean>>;
+ confirmRef: React.MutableRefObject<(props: ConfirmProps) => Promise<boolean>>
}
// Default value for the ConfirmContext
const defaultValue: ConfirmContextValue = {
- confirmRef: {
- current: defaultFunction,
- },
-};
+ confirmRef: {
+ current: defaultFunction
+ }
+}
// Create the ConfirmContext
-const ConfirmContext = createContext<ConfirmContextValue>(defaultValue);
+const ConfirmContext = createContext<ConfirmContextValue>(defaultValue)
// Context provider component
export function ConfirmContextProvider({ children }: { children: ReactNode }) {
- const confirmRef = useRef<(props: ConfirmProps) => Promise<boolean>>(defaultFunction);
-
- return (
- <ConfirmContext.Provider value={{ confirmRef }}>
- {children}
- <ConfirmDialogWithContext />
- </ConfirmContext.Provider>
- );
+ const confirmRef = useRef<(props: ConfirmProps) => Promise<boolean>>(defaultFunction)
+
+ return (
+ <ConfirmContext.Provider value={{ confirmRef }}>
+ {children}
+ <ConfirmDialogWithContext />
+ </ConfirmContext.Provider>
+ )
}
// Component that renders the dialog and handles its state
function ConfirmDialogWithContext() {
- const [open, setOpen] = useState(false);
- const [props, setProps] = useState<ConfirmProps | null>(null);
- const resolveRef = useRef<(value: boolean) => void>(() => { });
-
- const { confirmRef } = useContext(ConfirmContext);
-
- confirmRef.current = (dialogProps: ConfirmProps) =>
- new Promise<boolean>((resolve) => {
- setProps(dialogProps);
- setOpen(true);
- resolveRef.current = resolve;
- });
-
- const onConfirm = () => {
- resolveRef.current(true);
- setOpen(false);
- };
-
- const onCancel = () => {
- resolveRef.current(false);
- setOpen(false);
- };
-
- return (
- <ConfirmDialog
- onConfirm={onConfirm}
- onCancel={onCancel}
- open={open}
- title={props?.title || ""}
- message={props?.message || ""}
- />
- );
+ const [open, setOpen] = useState(false)
+ const [props, setProps] = useState<ConfirmProps | null>(null)
+ const resolveRef = useRef<(value: boolean) => void>(() => {})
+
+ const { confirmRef } = useContext(ConfirmContext)
+
+ confirmRef.current = (dialogProps: ConfirmProps) =>
+ new Promise<boolean>((resolve) => {
+ setProps(dialogProps)
+ setOpen(true)
+ resolveRef.current = resolve
+ })
+
+ const onConfirm = () => {
+ resolveRef.current(true)
+ setOpen(false)
+ }
+
+ const onCancel = () => {
+ resolveRef.current(false)
+ setOpen(false)
+ }
+
+ return (
+ <ConfirmDialog
+ onConfirm={onConfirm}
+ onCancel={onCancel}
+ open={open}
+ title={props?.title || ''}
+ message={props?.message || ''}
+ />
+ )
}
// Hook to access the confirm function
export function useConfirm() {
- const { confirmRef } = useContext(ConfirmContext);
-
- return {
- confirm: useCallback(
- (props: ConfirmProps) => confirmRef.current(props),
- [confirmRef]
- ),
- };
+ const { confirmRef } = useContext(ConfirmContext)
+
+ return {
+ confirm: useCallback((props: ConfirmProps) => confirmRef.current(props), [confirmRef])
+ }
}
// The ConfirmDialog component that displays the UI for the dialog
const ConfirmDialog = ({
- open,
- onConfirm,
- onCancel,
- title,
- message,
+ open,
+ onConfirm,
+ onCancel,
+ title,
+ message
}: {
- open: boolean;
- onConfirm: () => void;
- onCancel: () => void;
- title: string;
- message: string;
+ open: boolean
+ onConfirm: () => void
+ onCancel: () => void
+ title: string
+ message: string
}) => {
- return (
- <Dialog open={open} onOpenChange={onCancel}>
- <DialogContent>
- <DialogTitle>{title}</DialogTitle>
- <DialogDescription>
- {message}
- </DialogDescription>
- <div className="flex items-center gap-3 mt-4 justify-end">
- <DialogClose asChild>
- <div>
- <Button onClick={onCancel} variant="secondary">
- Cancel
- </Button>
- </div>
- </DialogClose>
- <Button onClick={onConfirm}>
- Continue
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- );
-};
\ No newline at end of file
+ return (
+ <Dialog open={open} onOpenChange={onCancel}>
+ <DialogContent>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{message}</DialogDescription>
+ <div className="flex items-center gap-3 mt-4 justify-end">
+ <DialogClose asChild>
+ <div>
+ <Button onClick={onCancel} variant="secondary">
+ Cancel
+ </Button>
+ </div>
+ </DialogClose>
+ <Button onClick={onConfirm}>Continue</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/xyflow/base-handle.tsx b/flowsint-app/src/renderer/src/components/xyflow/base-handle.tsx
index d14b5073..44da9733 100644
--- a/flowsint-app/src/renderer/src/components/xyflow/base-handle.tsx
+++ b/flowsint-app/src/renderer/src/components/xyflow/base-handle.tsx
@@ -1,26 +1,26 @@
-import { forwardRef } from "react";
-import { Handle, type HandleProps } from "@xyflow/react";
+import { forwardRef } from 'react'
+import { Handle, type HandleProps } from '@xyflow/react'
-import { cn } from "@/lib/utils";
+import { cn } from '@/lib/utils'
-export type BaseHandleProps = HandleProps;
+export type BaseHandleProps = HandleProps
export const BaseHandle = forwardRef<HTMLDivElement, BaseHandleProps>(
- ({ className, children, ...props }, ref) => {
- return (
- <Handle
- ref={ref}
- {...props}
- className={cn(
- "!h-[11px] !w-[11px] rounded-full border border-slate-300 transition dark:border-secondary dark:bg-secondary",
- className,
- )}
- {...props}
- >
- {children}
- </Handle>
- );
- },
-);
+ ({ className, children, ...props }, ref) => {
+ return (
+ <Handle
+ ref={ref}
+ {...props}
+ className={cn(
+ '!h-[11px] !w-[11px] rounded-full border border-slate-300 transition dark:border-secondary dark:bg-secondary',
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </Handle>
+ )
+ }
+)
-BaseHandle.displayName = "BaseHandle";
\ No newline at end of file
+BaseHandle.displayName = 'BaseHandle'
diff --git a/flowsint-app/src/renderer/src/components/xyflow/base-node.tsx b/flowsint-app/src/renderer/src/components/xyflow/base-node.tsx
index 20168519..11b2db57 100644
--- a/flowsint-app/src/renderer/src/components/xyflow/base-node.tsx
+++ b/flowsint-app/src/renderer/src/components/xyflow/base-node.tsx
@@ -1,93 +1,86 @@
-import { cn } from "@/lib/utils";
-import { forwardRef, HTMLAttributes } from "react";
+import { cn } from '@/lib/utils'
+import { forwardRef, HTMLAttributes } from 'react'
-export const BaseNode = forwardRef<
- HTMLDivElement,
- HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
+export const BaseNode = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
<div
- ref={ref}
- className={cn(
- "relative rounded-md border bg-card text-card-foreground",
- "hover:ring-1",
- // React Flow displays node elements inside of a `NodeWrapper` component,
- // which compiles down to a div with the class `react-flow__node`.
- // When a node is selected, the class `selected` is added to the
- // `react-flow__node` element. This allows us to style the node when it
- // is selected, using Tailwind's `&` selector.
- "[.react-flow\\_\\_node.selected_&]:border-muted-foreground",
- "[.react-flow\\_\\_node.selected_&]:shadow-lg",
- className,
- )}
- tabIndex={0}
- {...props}
+ ref={ref}
+ className={cn(
+ 'relative rounded-md border bg-card text-card-foreground',
+ 'hover:ring-1',
+ // React Flow displays node elements inside of a `NodeWrapper` component,
+ // which compiles down to a div with the class `react-flow__node`.
+ // When a node is selected, the class `selected` is added to the
+ // `react-flow__node` element. This allows us to style the node when it
+ // is selected, using Tailwind's `&` selector.
+ '[.react-flow\\_\\_node.selected_&]:border-muted-foreground',
+ '[.react-flow\\_\\_node.selected_&]:shadow-lg',
+ className
+ )}
+ tabIndex={0}
+ {...props}
/>
-));
-BaseNode.displayName = "BaseNode";
+ )
+)
+BaseNode.displayName = 'BaseNode'
/**
* A container for a consistent header layout intended to be used inside the
* `<BaseNode />` component.
*/
-export const BaseNodeHeader = forwardRef<
- HTMLElement,
- HTMLAttributes<HTMLElement>
->(({ className, ...props }, ref) => (
+export const BaseNodeHeader = forwardRef<HTMLElement, HTMLAttributes<HTMLElement>>(
+ ({ className, ...props }, ref) => (
<header
- ref={ref}
- {...props}
- className={cn(
- "mx-0 my-0 -mb-1 flex flex-row items-center justify-between gap-2 px-3 py-2",
- // Remove or modify these classes if you modify the padding in the
- // `<BaseNode />` component.
- className,
- )}
+ ref={ref}
+ {...props}
+ className={cn(
+ 'mx-0 my-0 -mb-1 flex flex-row items-center justify-between gap-2 px-3 py-2',
+ // Remove or modify these classes if you modify the padding in the
+ // `<BaseNode />` component.
+ className
+ )}
/>
-));
-BaseNodeHeader.displayName = "BaseNodeHeader";
+ )
+)
+BaseNodeHeader.displayName = 'BaseNodeHeader'
/**
* The title text for the node. To maintain a native application feel, the title
* text is not selectable.
*/
export const BaseNodeHeaderTitle = forwardRef<
- HTMLHeadingElement,
- HTMLAttributes<HTMLHeadingElement>
+ HTMLHeadingElement,
+ HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
- <h3
- ref={ref}
- data-slot="base-node-title"
- className={cn("user-select-none flex-1 font-semibold", className)}
- {...props}
- />
-));
-BaseNodeHeaderTitle.displayName = "BaseNodeHeaderTitle";
+ <h3
+ ref={ref}
+ data-slot="base-node-title"
+ className={cn('user-select-none flex-1 font-semibold', className)}
+ {...props}
+ />
+))
+BaseNodeHeaderTitle.displayName = 'BaseNodeHeaderTitle'
-export const BaseNodeContent = forwardRef<
- HTMLDivElement,
- HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
+export const BaseNodeContent = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
<div
- ref={ref}
- data-slot="base-node-content"
- className={cn("flex flex-col gap-y-2 p-3", className)}
- {...props}
+ ref={ref}
+ data-slot="base-node-content"
+ className={cn('flex flex-col gap-y-2 p-3', className)}
+ {...props}
/>
-));
-BaseNodeContent.displayName = "BaseNodeContent";
+ )
+)
+BaseNodeContent.displayName = 'BaseNodeContent'
-export const BaseNodeFooter = forwardRef<
- HTMLDivElement,
- HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
+export const BaseNodeFooter = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
<div
- ref={ref}
- data-slot="base-node-footer"
- className={cn(
- "flex flex-col items-center gap-y-2 border-t px-3 pb-3 pt-2",
- className,
- )}
- {...props}
+ ref={ref}
+ data-slot="base-node-footer"
+ className={cn('flex flex-col items-center gap-y-2 border-t px-3 pb-3 pt-2', className)}
+ {...props}
/>
-));
-BaseNodeFooter.displayName = "BaseNodeFooter";
\ No newline at end of file
+ )
+)
+BaseNodeFooter.displayName = 'BaseNodeFooter'
diff --git a/flowsint-app/src/renderer/src/components/xyflow/button-handle.tsx b/flowsint-app/src/renderer/src/components/xyflow/button-handle.tsx
index 0213f638..ae5b9f15 100644
--- a/flowsint-app/src/renderer/src/components/xyflow/button-handle.tsx
+++ b/flowsint-app/src/renderer/src/components/xyflow/button-handle.tsx
@@ -1,71 +1,72 @@
-import { HandleProps, Position, useNodeConnections } from "@xyflow/react";
-import { BaseHandle } from "./base-handle";
+import { HandleProps, Position, useNodeConnections } from '@xyflow/react'
+import { BaseHandle } from './base-handle'
const wrapperClassNames: Record<Position, string> = {
- [Position.Top]:
- "flex-col-reverse left-1/2 -translate-y-full -translate-x-1/2",
- [Position.Bottom]: "flex-col left-1/2 translate-y-[10px] -translate-x-1/2",
- [Position.Left]:
- "flex-row-reverse top-1/2 -translate-x-full -translate-y-1/2",
- [Position.Right]: "top-1/2 -translate-y-1/2 translate-x-[10px]",
-};
+ [Position.Top]: 'flex-col-reverse left-1/2 -translate-y-full -translate-x-1/2',
+ [Position.Bottom]: 'flex-col left-1/2 translate-y-[10px] -translate-x-1/2',
+ [Position.Left]: 'flex-row-reverse top-1/2 -translate-x-full -translate-y-1/2',
+ [Position.Right]: 'top-1/2 -translate-y-1/2 translate-x-[10px]'
+}
export const ButtonHandle = ({
- showButton = true,
- position = Position.Bottom,
- label = "",
- children,
- connectionCount = 5,
- color,
- ...props
+ showButton = true,
+ position = Position.Bottom,
+ label = '',
+ children,
+ connectionCount = 5,
+ color,
+ ...props
}: HandleProps & {
- showButton?: boolean,
- label?: string,
- connectionCount?: number,
- color?: string
+ showButton?: boolean
+ label?: string
+ connectionCount?: number
+ color?: string
}) => {
- const wrapperClassName = wrapperClassNames[position || Position.Bottom];
- const vertical = position === Position.Top || position === Position.Bottom;
- const connections = useNodeConnections({
- handleType: props.type,
- });
- const hasConnections = connections.length > 0;
- const hasReachedConnectionLimit = connections.length >= connectionCount;
+ const wrapperClassName = wrapperClassNames[position || Position.Bottom]
+ const vertical = position === Position.Top || position === Position.Bottom
+ const connections = useNodeConnections({
+ handleType: props.type
+ })
+ const hasConnections = connections.length > 0
+ const hasReachedConnectionLimit = connections.length >= connectionCount
- return (
- <BaseHandle
- isConnectable={!hasReachedConnectionLimit && props.isConnectable}
- position={position}
- id={props.id}
- style={{
- backgroundColor: hasReachedConnectionLimit ? "#d1d5db" : "#10b981",
- }}
- {...props}
+ return (
+ <BaseHandle
+ isConnectable={!hasReachedConnectionLimit && props.isConnectable}
+ position={position}
+ id={props.id}
+ style={{
+ backgroundColor: hasReachedConnectionLimit ? '#d1d5db' : '#10b981'
+ }}
+ {...props}
+ >
+ {showButton && (
+ <div
+ className={`absolute group flex items-center ${wrapperClassName} ${!hasConnections ? 'pointer-events-none' : ''}`}
>
- {showButton && (
- <div
- className={`absolute group flex items-center ${wrapperClassName} ${!hasConnections ? 'pointer-events-none' : ''}`}
- >
- {/* Larger hitbox for hover detection when there are connections */}
- {hasConnections && (
- <div className="absolute inset-0 -m-4 pointer-events-auto" />
- )}
+ {/* Larger hitbox for hover detection when there are connections */}
+ {hasConnections && <div className="absolute inset-0 -m-4 pointer-events-auto" />}
- {!hasConnections ?
- <>
- <div
- className={`bg-gray-300 ${vertical ? "h-16 w-[1px]" : "h-[1px] w-16"}`}
- />
+ {!hasConnections ? (
+ <>
+ <div className={`bg-gray-300 ${vertical ? 'h-16 w-[1px]' : 'h-[1px] w-16'}`} />
- <div className="nodrag nopan pointer-events-auto">{children}</div>
- </> : !hasReachedConnectionLimit &&
- <div className="nodrag opacity-0 scale-25 group-hover:opacity-100 group-hover:scale-75 transition-all duration-200 ease-out z-10 nopan pointer-events-auto">
- {children}
- </div>
- }
- {label && <span className="absolute max-w-15 bg-background z-1 truncate text-ellipsis top-1/2 -translate-y-1/2 left-1 text-xs text-muted-foreground">{label}</span>}
- </div>
- )}
- </BaseHandle>
- );
-};
\ No newline at end of file
+ <div className="nodrag nopan pointer-events-auto">{children}</div>
+ </>
+ ) : (
+ !hasReachedConnectionLimit && (
+ <div className="nodrag opacity-0 scale-25 group-hover:opacity-100 group-hover:scale-75 transition-all duration-200 ease-out z-10 nopan pointer-events-auto">
+ {children}
+ </div>
+ )
+ )}
+ {label && (
+ <span className="absolute max-w-15 bg-background z-1 truncate text-ellipsis top-1/2 -translate-y-1/2 left-1 text-xs text-muted-foreground">
+ {label}
+ </span>
+ )}
+ </div>
+ )}
+ </BaseHandle>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/xyflow/context-menu.tsx b/flowsint-app/src/renderer/src/components/xyflow/context-menu.tsx
index 9864ea83..0501b78f 100644
--- a/flowsint-app/src/renderer/src/components/xyflow/context-menu.tsx
+++ b/flowsint-app/src/renderer/src/components/xyflow/context-menu.tsx
@@ -1,118 +1,117 @@
-import React from 'react';
+import React from 'react'
interface ContextMenuProps {
- top?: number;
- left?: number;
- right?: number;
- bottom?: number;
- wrapperWidth: number;
- wrapperHeight: number;
- children: React.ReactNode;
- // Raw position for overflow calculation
- rawTop?: number;
- rawLeft?: number;
+ top?: number
+ left?: number
+ right?: number
+ bottom?: number
+ wrapperWidth: number
+ wrapperHeight: number
+ children: React.ReactNode
+ // Raw position for overflow calculation
+ rawTop?: number
+ rawLeft?: number
}
export default function ContextMenu({
-
- top,
- left,
- right,
- bottom,
- wrapperWidth,
- wrapperHeight,
- rawTop,
- rawLeft,
- children,
- ...props
-}: ContextMenuProps) {
- // If raw position is provided, calculate overflow and adjust position
- let finalTop = top;
- let finalLeft = left;
- let finalRight = right;
- let finalBottom = bottom;
-
- if (rawTop !== undefined && rawLeft !== undefined) {
- // Calculate available space in each direction
- const menuWidth = 320; // Default menu width
- const menuHeight = 250; // Use a more reasonable height for overflow calculation
- const padding = 20; // Minimum padding from edges
-
- // Determine if menu would overflow in each direction
- const wouldOverflowRight = rawLeft + menuWidth + padding > wrapperWidth;
- const wouldOverflowBottom = rawTop + menuHeight + padding > wrapperHeight;
-
- // Calculate final position
- finalTop = 0;
- finalLeft = 0;
- finalRight = 0;
- finalBottom = 0;
-
- if (wouldOverflowRight) {
- finalRight = wrapperWidth - rawLeft;
- } else {
- finalLeft = rawLeft;
- }
-
- if (wouldOverflowBottom) {
- finalBottom = wrapperHeight - rawTop;
- } else {
- finalTop = rawTop;
- }
+ top,
+ left,
+ right,
+ bottom,
+ wrapperWidth,
+ wrapperHeight,
+ rawTop,
+ rawLeft,
+ children,
+ ...props
+}: ContextMenuProps): JSX.Element {
+ // If raw position is provided, calculate overflow and adjust position
+ let finalTop = top
+ let finalLeft = left
+ let finalRight = right
+ let finalBottom = bottom
+
+ if (rawTop !== undefined && rawLeft !== undefined) {
+ // Calculate available space in each direction
+ const menuWidth = 320 // Default menu width
+ const menuHeight = 250 // Use a more reasonable height for overflow calculation
+ const padding = 20 // Minimum padding from edges
+
+ // Determine if menu would overflow in each direction
+ const wouldOverflowRight = rawLeft + menuWidth + padding > wrapperWidth
+ const wouldOverflowBottom = rawTop + menuHeight + padding > wrapperHeight
+
+ // Calculate final position
+ finalTop = 0
+ finalLeft = 0
+ finalRight = 0
+ finalBottom = 0
+
+ if (wouldOverflowRight) {
+ finalRight = wrapperWidth - rawLeft
+ } else {
+ finalLeft = rawLeft
}
- // Calculate dynamic dimensions based on available space
- const maxWidth = 320; // Default width (w-80)
- const maxHeight = 500; // Default height (h-96)
- const minWidth = 280; // Minimum width
- const minHeight = 200; // Minimum height
-
- // Calculate available space based on menu position and wrapper dimensions
- let availableWidth = maxWidth;
- let availableHeight = maxHeight;
-
- if (finalLeft && finalLeft > 0) {
- // Menu is positioned from left, so available width is from left to right edge
- availableWidth = wrapperWidth - finalLeft - 20; // 20px padding from right edge
- } else if (finalRight && finalRight > 0) {
- // Menu is positioned from right, so available width is from left edge to right position
- availableWidth = wrapperWidth - finalRight - 20; // 20px padding from left edge
+ if (wouldOverflowBottom) {
+ finalBottom = wrapperHeight - rawTop
+ } else {
+ finalTop = rawTop
}
-
- if (finalTop && finalTop > 0) {
- // Menu is positioned from top, so available height is from top to bottom edge
- availableHeight = wrapperHeight - finalTop - 20; // 20px padding from bottom edge
- } else if (finalBottom && finalBottom > 0) {
- // Menu is positioned from bottom, so available height is from top edge to bottom position
- availableHeight = wrapperHeight - finalBottom - 20; // 20px padding from top edge
- }
-
- // Determine dynamic dimensions
- const dynamicWidth = Math.min(maxWidth, Math.max(minWidth, availableWidth));
- const dynamicHeight = Math.min(maxHeight, Math.max(minHeight, availableHeight));
-
- // Calculate dynamic styles
- const dynamicStyles = {
- width: `${dynamicWidth}px`,
- maxHeight: `${dynamicHeight}px`,
- top: finalTop && finalTop > 0 ? `${finalTop}px` : 'auto',
- left: finalLeft && finalLeft > 0 ? `${finalLeft}px` : 'auto',
- right: finalRight && finalRight > 0 ? `${finalRight}px` : 'auto',
- bottom: finalBottom && finalBottom > 0 ? `${finalBottom}px` : 'auto',
- };
-
- const handleMenuClick = (e: React.MouseEvent) => {
- e.stopPropagation();
- };
-
- return (
- <div
- style={dynamicStyles}
- className="bg-background/90 backdrop-blur-sm border border-border flex flex-col rounded-lg shadow-lg absolute z-50"
- onClick={handleMenuClick}
- {...props}
- >
- {children}
- </div>
- );
-}
\ No newline at end of file
+ }
+
+ // Calculate dynamic dimensions based on available space
+ const maxWidth = 320 // Default width (w-80)
+ const maxHeight = 500 // Default height (h-96)
+ const minWidth = 280 // Minimum width
+ const minHeight = 200 // Minimum height
+
+ // Calculate available space based on menu position and wrapper dimensions
+ let availableWidth = maxWidth
+ let availableHeight = maxHeight
+
+ if (finalLeft && finalLeft > 0) {
+ // Menu is positioned from left, so available width is from left to right edge
+ availableWidth = wrapperWidth - finalLeft - 20 // 20px padding from right edge
+ } else if (finalRight && finalRight > 0) {
+ // Menu is positioned from right, so available width is from left edge to right position
+ availableWidth = wrapperWidth - finalRight - 20 // 20px padding from left edge
+ }
+
+ if (finalTop && finalTop > 0) {
+ // Menu is positioned from top, so available height is from top to bottom edge
+ availableHeight = wrapperHeight - finalTop - 20 // 20px padding from bottom edge
+ } else if (finalBottom && finalBottom > 0) {
+ // Menu is positioned from bottom, so available height is from top edge to bottom position
+ availableHeight = wrapperHeight - finalBottom - 20 // 20px padding from top edge
+ }
+
+ // Determine dynamic dimensions
+ const dynamicWidth = Math.min(maxWidth, Math.max(minWidth, availableWidth))
+ const dynamicHeight = Math.min(maxHeight, Math.max(minHeight, availableHeight))
+
+ // Calculate dynamic styles
+ const dynamicStyles = {
+ width: `${dynamicWidth}px`,
+ maxHeight: `${dynamicHeight}px`,
+ top: finalTop && finalTop > 0 ? `${finalTop}px` : 'auto',
+ left: finalLeft && finalLeft > 0 ? `${finalLeft}px` : 'auto',
+ right: finalRight && finalRight > 0 ? `${finalRight}px` : 'auto',
+ bottom: finalBottom && finalBottom > 0 ? `${finalBottom}px` : 'auto'
+ }
+
+ const handleMenuClick = (e: React.MouseEvent) => {
+ e.stopPropagation()
+ }
+
+ return (
+ <div
+ style={dynamicStyles}
+ className="bg-background/90 backdrop-blur-sm border border-border flex flex-col rounded-lg shadow-lg absolute z-50"
+ onClick={handleMenuClick}
+ {...props}
+ >
+ {children}
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/components/xyflow/custom-edge.tsx b/flowsint-app/src/renderer/src/components/xyflow/custom-edge.tsx
index a527f48f..8c26162a 100644
--- a/flowsint-app/src/renderer/src/components/xyflow/custom-edge.tsx
+++ b/flowsint-app/src/renderer/src/components/xyflow/custom-edge.tsx
@@ -1,98 +1,90 @@
-import { memo, type ReactNode, useMemo } from "react";
-import {
- BaseEdge,
- EdgeLabelRenderer,
- getStraightPath,
- type EdgeProps,
-} from "@xyflow/react";
+import { memo, type ReactNode, useMemo } from 'react'
+import { BaseEdge, EdgeLabelRenderer, getStraightPath, type EdgeProps } from '@xyflow/react'
interface EdgeCalculations {
- edgePath: string;
- labelX: number;
- labelY: number;
- adjustedAngle: number;
- maxWidth: number;
- transform: string;
+ edgePath: string
+ labelX: number
+ labelY: number
+ adjustedAngle: number
+ maxWidth: number
+ transform: string
}
const calculateEdgeProperties = (
- sourceX: number,
- sourceY: number,
- targetX: number,
- targetY: number
+ sourceX: number,
+ sourceY: number,
+ targetX: number,
+ targetY: number
): EdgeCalculations => {
- const [edgePath, labelX, labelY] = getStraightPath({
- sourceX,
- sourceY,
- targetX,
- targetY,
- });
+ const [edgePath, labelX, labelY] = getStraightPath({
+ sourceX,
+ sourceY,
+ targetX,
+ targetY
+ })
- const dx = targetX - sourceX;
- const dy = targetY - sourceY;
- const angleRad = Math.atan2(dy, dx);
- const angleDeg = (angleRad * 180) / Math.PI;
- const adjustedAngle = angleDeg > 90 || angleDeg < -90 ? angleDeg + 180 : angleDeg;
+ const dx = targetX - sourceX
+ const dy = targetY - sourceY
+ const angleRad = Math.atan2(dy, dx)
+ const angleDeg = (angleRad * 180) / Math.PI
+ const adjustedAngle = angleDeg > 90 || angleDeg < -90 ? angleDeg + 180 : angleDeg
- const edgeLength = Math.sqrt(dx * dx + dy * dy);
- const maxWidth = Math.max(edgeLength - 20, 30);
+ const edgeLength = Math.sqrt(dx * dx + dy * dy)
+ const maxWidth = Math.max(edgeLength - 20, 30)
- const transform = `translate(-50%, -50%) translate(${labelX}px, ${labelY}px) rotate(${adjustedAngle}deg)`;
+ const transform = `translate(-50%, -50%) translate(${labelX}px, ${labelY}px) rotate(${adjustedAngle}deg)`
- return {
- edgePath,
- labelX,
- labelY,
- adjustedAngle,
- maxWidth,
- transform,
- };
-};
+ return {
+ edgePath,
+ labelX,
+ labelY,
+ adjustedAngle,
+ maxWidth,
+ transform
+ }
+}
-export const CustomEdge = memo(({
+export const CustomEdge = memo(
+ ({
sourceX,
sourceY,
targetX,
targetY,
style = {},
markerEnd,
- children,
-}: EdgeProps & { children: ReactNode }) => {
-
+ children
+ }: EdgeProps & { children: ReactNode }) => {
// Memoize all calculations
const edgeProps = useMemo(
- () => calculateEdgeProperties(sourceX, sourceY, targetX, targetY),
- [sourceX, sourceY, targetX, targetY]
- );
+ () => calculateEdgeProperties(sourceX, sourceY, targetX, targetY),
+ [sourceX, sourceY, targetX, targetY]
+ )
// Memoize label style object
- const labelStyle = useMemo(() => ({
+ const labelStyle = useMemo(
+ () => ({
transform: edgeProps.transform,
- transformOrigin: "center" as const,
+ transformOrigin: 'center' as const,
maxWidth: `${edgeProps.maxWidth}px`,
- overflow: "hidden" as const,
- textOverflow: "ellipsis" as const,
- whiteSpace: "nowrap" as const,
- }), [edgeProps.transform, edgeProps.maxWidth]);
+ overflow: 'hidden' as const,
+ textOverflow: 'ellipsis' as const,
+ whiteSpace: 'nowrap' as const
+ }),
+ [edgeProps.transform, edgeProps.maxWidth]
+ )
return (
- <>
- <BaseEdge
- path={edgeProps.edgePath}
- markerEnd={markerEnd}
- style={style}
- />
- <EdgeLabelRenderer>
- <div
- className="nodrag nopan pointer-events-auto absolute"
- style={labelStyle}
- >
- {children}
- </div>
- </EdgeLabelRenderer>
- </>
- );
-});
+ <>
+ <BaseEdge path={edgeProps.edgePath} markerEnd={markerEnd} style={style} />
+ <EdgeLabelRenderer>
+ <div className="nodrag nopan pointer-events-auto absolute" style={labelStyle}>
+ {children}
+ </div>
+ </EdgeLabelRenderer>
+ </>
+ )
+ }
+)
// Add display name for debugging
-CustomEdge.displayName = 'CustomEdge';
\ No newline at end of file
+CustomEdge.displayName = 'CustomEdge'
diff --git a/flowsint-app/src/renderer/src/components/xyflow/labeled-handle.tsx b/flowsint-app/src/renderer/src/components/xyflow/labeled-handle.tsx
index 854a46ce..e95b988e 100644
--- a/flowsint-app/src/renderer/src/components/xyflow/labeled-handle.tsx
+++ b/flowsint-app/src/renderer/src/components/xyflow/labeled-handle.tsx
@@ -1,45 +1,33 @@
-import { forwardRef, ReactNode, type HTMLAttributes } from "react";
-import { cn } from "@/lib/utils";
-import { type HandleProps } from "@xyflow/react";
+import { forwardRef, ReactNode, type HTMLAttributes } from 'react'
+import { cn } from '@/lib/utils'
+import { type HandleProps } from '@xyflow/react'
-import { BaseHandle } from "@/components/xyflow/base-handle";
-import { Badge } from "@/components/ui/badge";
+import { BaseHandle } from '@/components/xyflow/base-handle'
+import { Badge } from '@/components/ui/badge'
const flexDirections = {
- top: "flex-col",
- right: "flex-row-reverse justify-end",
- bottom: "flex-col-reverse justify-end",
- left: "flex-row",
-};
+ top: 'flex-col',
+ right: 'flex-row-reverse justify-end',
+ bottom: 'flex-col-reverse justify-end',
+ left: 'flex-row'
+}
export const LabeledHandle = forwardRef<
- HTMLDivElement,
- HandleProps &
+ HTMLDivElement,
+ HandleProps &
HTMLAttributes<HTMLDivElement> & {
- label: string | (string & Element) | ReactNode;
- description: string,
- handleClassName?: string;
- labelClassName?: string;
+ label: string | (string & Element) | ReactNode
+ description: string
+ handleClassName?: string
+ labelClassName?: string
}
->(
- (
- { className, labelClassName, handleClassName, label, position, description, ...props },
- ref,
- ) => (
- <div
- ref={ref}
- className={cn(
- "relative flex items-center",
- flexDirections[position],
- className,
- )}
- >
- <BaseHandle position={position} className={handleClassName} {...props} />
- <label className={cn("px-3 text-foreground", labelClassName)}>
- {label} <Badge variant={"outline"}>{description}</Badge>
- </label>
- </div>
- ),
-);
+>(({ className, labelClassName, handleClassName, label, position, description, ...props }, ref) => (
+ <div ref={ref} className={cn('relative flex items-center', flexDirections[position], className)}>
+ <BaseHandle position={position} className={handleClassName} {...props} />
+ <label className={cn('px-3 text-foreground', labelClassName)}>
+ {label} <Badge variant={'outline'}>{description}</Badge>
+ </label>
+ </div>
+))
-LabeledHandle.displayName = "LabeledHandle";
\ No newline at end of file
+LabeledHandle.displayName = 'LabeledHandle'
diff --git a/flowsint-app/src/renderer/src/components/xyflow/node-status-indicator.tsx b/flowsint-app/src/renderer/src/components/xyflow/node-status-indicator.tsx
index b6a1a8c4..cbd6c742 100644
--- a/flowsint-app/src/renderer/src/components/xyflow/node-status-indicator.tsx
+++ b/flowsint-app/src/renderer/src/components/xyflow/node-status-indicator.tsx
@@ -1,20 +1,20 @@
-import { cn } from "@/lib/utils"
-import { cva, type VariantProps } from "class-variance-authority"
+import { cn } from '@/lib/utils'
+import { cva, type VariantProps } from 'class-variance-authority'
const nodeStatusIndicatorVariants = cva(
- "absolute -top-2 -right-2 w-4 h-4 rounded-full border-2 border-background",
+ 'absolute -top-2 -right-2 w-4 h-4 rounded-full border-2 border-background',
{
variants: {
variant: {
- success: "bg-green-500",
- error: "bg-red-500",
- loading: "bg-blue-500",
- pending: "bg-gray-500",
- },
+ success: 'bg-green-500',
+ error: 'bg-red-500',
+ loading: 'bg-blue-500',
+ pending: 'bg-gray-500'
+ }
},
defaultVariants: {
- variant: "pending",
- },
+ variant: 'pending'
+ }
}
)
@@ -33,8 +33,7 @@ export function NodeStatusIndicator({
return (
<div className="relative">
{children}
- {showStatus &&
- <div className={cn(nodeStatusIndicatorVariants({ variant }), className)} />}
+ {showStatus && <div className={cn(nodeStatusIndicatorVariants({ variant }), className)} />}
</div>
)
-}
\ No newline at end of file
+}
diff --git a/flowsint-app/src/renderer/src/components/xyflow/node-tooltip.tsx b/flowsint-app/src/renderer/src/components/xyflow/node-tooltip.tsx
index bdaa234d..58374d02 100644
--- a/flowsint-app/src/renderer/src/components/xyflow/node-tooltip.tsx
+++ b/flowsint-app/src/renderer/src/components/xyflow/node-tooltip.tsx
@@ -1,104 +1,92 @@
-import { cn } from "@/lib/utils";
-import { NodeToolbar, NodeToolbarProps } from "@xyflow/react";
+import { cn } from '@/lib/utils'
+import { NodeToolbar, NodeToolbarProps } from '@xyflow/react'
import React, {
createContext,
forwardRef,
HTMLAttributes,
useCallback,
useContext,
- useState,
-} from "react";
-
+ useState
+} from 'react'
+
/* TOOLTIP CONTEXT ---------------------------------------------------------- */
-
+
type TooltipContextType = {
- isVisible: boolean;
- showTooltip: () => void;
- hideTooltip: () => void;
-};
-
-const TooltipContext = createContext<TooltipContextType | null>(null);
-
+ isVisible: boolean
+ showTooltip: () => void
+ hideTooltip: () => void
+}
+
+const TooltipContext = createContext<TooltipContextType | null>(null)
+
/* TOOLTIP NODE ------------------------------------------------------------- */
-
-export const NodeTooltip = forwardRef<
- HTMLDivElement,
- HTMLAttributes<HTMLDivElement>
->(({ children }, ref) => {
- const [isVisible, setIsVisible] = useState(false);
-
- const showTooltip = useCallback(() => setIsVisible(true), []);
- const hideTooltip = useCallback(() => setIsVisible(false), []);
-
- return (
- <TooltipContext.Provider value={{ isVisible, showTooltip, hideTooltip }}>
- <div ref={ref}>{children}</div>
- </TooltipContext.Provider>
- );
-});
-NodeTooltip.displayName = "NodeTooltip";
-
+
+export const NodeTooltip = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
+ ({ children }, ref) => {
+ const [isVisible, setIsVisible] = useState(false)
+
+ const showTooltip = useCallback(() => setIsVisible(true), [])
+ const hideTooltip = useCallback(() => setIsVisible(false), [])
+
+ return (
+ <TooltipContext.Provider value={{ isVisible, showTooltip, hideTooltip }}>
+ <div ref={ref}>{children}</div>
+ </TooltipContext.Provider>
+ )
+ }
+)
+NodeTooltip.displayName = 'NodeTooltip'
+
/* TOOLTIP TRIGGER ---------------------------------------------------------- */
-
-export const NodeTooltipTrigger = forwardRef<
- HTMLDivElement,
- HTMLAttributes<HTMLDivElement>
->((props, ref) => {
- const tooltipContext = useContext(TooltipContext);
- if (!tooltipContext) {
- throw new Error("NodeTooltipTrigger must be used within NodeTooltip");
+
+export const NodeTooltipTrigger = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(
+ (props, ref) => {
+ const tooltipContext = useContext(TooltipContext)
+ if (!tooltipContext) {
+ throw new Error('NodeTooltipTrigger must be used within NodeTooltip')
+ }
+ const { showTooltip, hideTooltip } = tooltipContext
+
+ const onMouseEnter = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ props.onMouseEnter?.(e)
+ showTooltip()
+ },
+ [props, showTooltip]
+ )
+
+ const onMouseLeave = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ props.onMouseLeave?.(e)
+ hideTooltip()
+ },
+ [props, hideTooltip]
+ )
+
+ return <div ref={ref} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} {...props} />
}
- const { showTooltip, hideTooltip } = tooltipContext;
-
- const onMouseEnter = useCallback(
- (e: React.MouseEvent<HTMLDivElement>) => {
- props.onMouseEnter?.(e);
- showTooltip();
- },
- [props, showTooltip],
- );
-
- const onMouseLeave = useCallback(
- (e: React.MouseEvent<HTMLDivElement>) => {
- props.onMouseLeave?.(e);
- hideTooltip();
- },
- [props, hideTooltip],
- );
-
- return (
- <div
- ref={ref}
- onMouseEnter={onMouseEnter}
- onMouseLeave={onMouseLeave}
- {...props}
- />
- );
-});
-NodeTooltipTrigger.displayName = "NodeTooltipTrigger";
-
+)
+NodeTooltipTrigger.displayName = 'NodeTooltipTrigger'
+
/* TOOLTIP CONTENT ---------------------------------------------------------- */
-
+
// /**
// * A component that displays the tooltip content based on visibility context.
// */
-
+
export const NodeTooltipContent = forwardRef<HTMLDivElement, NodeToolbarProps>(
({ children, position, className, ...props }, ref) => {
- const tooltipContext = useContext(TooltipContext);
+ const tooltipContext = useContext(TooltipContext)
if (!tooltipContext) {
- throw new Error("NodeTooltipContent must be used within NodeTooltip");
+ throw new Error('NodeTooltipContent must be used within NodeTooltip')
}
- const { isVisible } = tooltipContext;
-
+ const { isVisible } = tooltipContext
+
return (
<div ref={ref}>
<NodeToolbar
isVisible={isVisible}
- className={cn(
- "rounded-sm bg-primary p-2 text-primary-foreground",
- className,
- )}
+ className={cn('rounded-sm bg-primary p-2 text-primary-foreground', className)}
tabIndex={1}
position={position}
{...props}
@@ -106,6 +94,6 @@ export const NodeTooltipContent = forwardRef<HTMLDivElement, NodeToolbarProps>(
{children}
</NodeToolbar>
</div>
- );
- },
-);
\ No newline at end of file
+ )
+ }
+)
diff --git a/flowsint-app/src/renderer/src/hooks/use-action-items.ts b/flowsint-app/src/renderer/src/hooks/use-action-items.ts
index 6daff845..d04fd97f 100644
--- a/flowsint-app/src/renderer/src/hooks/use-action-items.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-action-items.ts
@@ -1,16 +1,16 @@
-import { sketchService } from "@/api/sketch-service"
-import { ActionItem } from "@/lib/action-items"
-import { useQuery } from "@tanstack/react-query"
+import { sketchService } from '@/api/sketch-service'
+import { ActionItem } from '@/lib/action-items'
+import { useQuery } from '@tanstack/react-query'
export const useActionItems = () => {
- const { data: actionItems, isLoading } = useQuery<ActionItem[]>({
- queryKey: ["actionItems"],
- queryFn: () => sketchService.types(),
- refetchOnWindowFocus: false, // Prevent refetch on window focus
- refetchOnMount: false, // Prevent refetch on component mount if data exists
- })
- return {
- actionItems,
- isLoading
- }
-}
\ No newline at end of file
+ const { data: actionItems, isLoading } = useQuery<ActionItem[]>({
+ queryKey: ['actionItems'],
+ queryFn: () => sketchService.types(),
+ refetchOnWindowFocus: false, // Prevent refetch on window focus
+ refetchOnMount: false // Prevent refetch on component mount if data exists
+ })
+ return {
+ actionItems,
+ isLoading
+ }
+}
diff --git a/flowsint-app/src/renderer/src/hooks/use-auth.ts b/flowsint-app/src/renderer/src/hooks/use-auth.ts
index 0e26121d..f42e5381 100644
--- a/flowsint-app/src/renderer/src/hooks/use-auth.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-auth.ts
@@ -1,81 +1,80 @@
// src/hooks/use-auth.ts
-import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
-import { useNavigate } from '@tanstack/react-router';
-import { authService } from '@/api/auth-service';
-import { useAuthStore } from '@/stores/auth-store';
-
-export const SESSION_QUERY_KEY = ['session'];
+import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query'
+import { useNavigate } from '@tanstack/react-router'
+import { authService } from '@/api/auth-service'
+import { useAuthStore } from '@/stores/auth-store'
+export const SESSION_QUERY_KEY = ['session']
export const useRegister = () => {
- const navigate = useNavigate();
- const setAuth = useAuthStore((state) => state.setAuth);
+ const navigate = useNavigate()
+ const setAuth = useAuthStore((state) => state.setAuth)
- return useMutation({
- mutationFn: authService.register,
- onSuccess: (data) => {
- setAuth(data.access_token, data.user);
- navigate({ to: '/' });
- },
- onError: (error) => {
- console.error('Erreur lors de l’inscription :', error);
- },
- });
-};
+ return useMutation({
+ mutationFn: authService.register,
+ onSuccess: (data) => {
+ setAuth(data.access_token, data.user)
+ navigate({ to: '/' })
+ },
+ onError: (error) => {
+ console.error('Erreur lors de l’inscription :', error)
+ }
+ })
+}
export const useLogin = () => {
- const navigate = useNavigate();
- const setAuth = useAuthStore((s) => s.setAuth);
+ const navigate = useNavigate()
+ const setAuth = useAuthStore((s) => s.setAuth)
- return useMutation({
- mutationFn: authService.login,
- onSuccess: (data) => {
- setAuth(data.access_token, data.user);
- navigate({ to: '/' });
- },
- });
-};
+ return useMutation({
+ mutationFn: authService.login,
+ onSuccess: (data) => {
+ setAuth(data.access_token, data.user)
+ navigate({ to: '/' })
+ }
+ })
+}
export const useLogout = () => {
- const navigate = useNavigate();
- const logout = useAuthStore((s) => s.logout);
- const queryClient = useQueryClient();
+ const navigate = useNavigate()
+ const logout = useAuthStore((s) => s.logout)
+ const queryClient = useQueryClient()
- return () => {
- logout();
- queryClient.clear();
- navigate({ to: '/login' });
- };
-};
+ return () => {
+ logout()
+ queryClient.clear()
+ navigate({ to: '/login' })
+ }
+}
export const useCurrentUser = () => {
- const token = useAuthStore((s) => s.token);
- const userFromStore = useAuthStore((s) => s.user);
- const setAuth = useAuthStore((s) => s.setAuth);
- const logout = useAuthStore((s) => s.logout);
- const queryClient = useQueryClient();
+ const token = useAuthStore((s) => s.token)
+ const userFromStore = useAuthStore((s) => s.user)
+ const setAuth = useAuthStore((s) => s.setAuth)
+ const logout = useAuthStore((s) => s.logout)
+ const queryClient = useQueryClient()
- const result = useQuery({
- queryKey: SESSION_QUERY_KEY,
- queryFn: authService.getCurrentUser,
- enabled: !!token && !userFromStore,
- staleTime: 5 * 60 * 1000,
- retry: false,
- initialData: userFromStore || undefined,
- });
+ const result = useQuery({
+ queryKey: SESSION_QUERY_KEY,
+ queryFn: authService.getCurrentUser,
+ enabled: !!token && !userFromStore,
+ staleTime: 5 * 60 * 1000,
+ retry: false,
+ initialData: userFromStore || undefined
+ })
- if (result.isSuccess && result.data && token) {
- setAuth(token, result.data);
- }
+ if (result.isSuccess && result.data && token) {
+ setAuth(token, result.data)
+ }
- if (result.isError) {
- logout();
- queryClient.clear();
- }
+ if (result.isError) {
+ logout()
+ queryClient.clear()
+ }
- return {
- ...result,
- user: result.data || userFromStore,
- isLoggedIn: useAuthStore.getState().isAuthenticated,
- };
-};
+ return {
+ ...result,
+ user: result.data || userFromStore,
+ isLoggedIn: useAuthStore.getState().isAuthenticated
+ }
+}
diff --git a/flowsint-app/src/renderer/src/hooks/use-chat.ts b/flowsint-app/src/renderer/src/hooks/use-chat.ts
index 7c0b2423..ad4d4e6d 100644
--- a/flowsint-app/src/renderer/src/hooks/use-chat.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-chat.ts
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query'
import { toast } from 'sonner'
import { chatService, chatCRUDService } from '@/api/chat-service'
-import { marked } from 'marked';
+import { marked } from 'marked'
import { generateJSON } from '@tiptap/core'
import { StarterKit } from '@tiptap/starter-kit'
import { Typography } from '@tiptap/extension-typography'
@@ -15,224 +15,248 @@ import { HorizontalRule } from '@tiptap/extension-horizontal-rule'
import { CodeBlockLowlight } from '@tiptap/extension-code-block-lowlight'
import { Color } from '@tiptap/extension-color'
import type { Editor } from '@tiptap/react'
-import { useGraphStore } from '@/stores/graph-store';
-import { useChatState } from '@/stores/use-chat-store';
+import { useGraphStore } from '@/stores/graph-store'
+import { useChatState } from '@/stores/use-chat-store'
import { useParams } from '@tanstack/react-router'
-import { queryKeys } from '@/api/query-keys';
+import { queryKeys } from '@/api/query-keys'
const markdownToHtml = (markdown: string) => {
- return marked(markdown, {
- breaks: true, // Convert \n to <br>
- gfm: true, // Enable GitHub Flavored Markdown
- async: false
- });
-};
+ return marked(markdown, {
+ breaks: true, // Convert \n to <br>
+ gfm: true, // Enable GitHub Flavored Markdown
+ async: false
+ })
+}
interface UseChatOptions {
- onContentUpdate: (content: any) => void
- onSuccess?: () => void
- editor?: Editor
+ onContentUpdate: (content: any) => void
+ onSuccess?: () => void
+ editor?: Editor
}
export const useChat = ({ onContentUpdate, onSuccess, editor }: UseChatOptions) => {
- const [isAiLoading, setIsAiLoading] = useState(false)
- const [customPrompt, setCustomPrompt] = useState("")
- const selectedNodes = useGraphStore(s => s.selectedNodes)
- const currentChatId = useChatState(s => s.currentChatId)
- const setCurrentChatId = useChatState(s => s.setCurrentChatId)
- const deleteChat = useChatState(s => s.deleteChat)
- const addMessage = useChatState(s => s.addMessage)
- const { investigationId } = useParams({ strict: false })
- const queryClient = useQueryClient()
-
- // Fetch current chat data with messages
- const { data: currentChat, isLoading: isLoadingChat } = useQuery({
- queryKey: queryKeys.chats.detail(currentChatId!),
- queryFn: () => chatCRUDService.getById(currentChatId!),
- enabled: !!currentChatId,
- refetchOnWindowFocus: false,
- })
-
- // Mutation to create a new chat
- const createChatMutation = useMutation({
- mutationFn: async ({ title, description }: { title: string, description?: string }) => {
- const chatData = {
- title,
- description: description || '',
- investigation_id: investigationId
- }
- return await chatCRUDService.create(JSON.stringify(chatData))
- },
- onSuccess: (data) => {
- // Add the new chat to the store
- // Invalidate chats query to refresh the list
- queryClient.invalidateQueries({ queryKey: queryKeys.chats.detail(currentChatId!) })
- setCurrentChatId(data.id)
- toast.success("New chat created successfully!")
- },
- onError: (error) => {
- console.error("Error creating chat:", error)
- toast.error("Failed to create chat: " + (error instanceof Error ? error.message : "Unknown error"))
- }
- })
-
- // Mutation to delete a chat
- const deleteChatMutation = useMutation({
- mutationFn: async (chatId: string) => {
- deleteChat(chatId)
- return await chatCRUDService.delete(chatId)
- },
- onSuccess: () => {
- // Remove the chat from the store
- // Invalidate chats query to refresh the list
- queryClient.invalidateQueries({ queryKey: queryKeys.chats.list })
- toast.success("Chat deleted successfully!")
- },
- onError: (error) => {
- console.error("Error deleting chat:", error)
- toast.error("Failed to delete chat: " + (error instanceof Error ? error.message : "Unknown error"))
- }
- })
-
- const aiCompletionMutation = useMutation({
- mutationFn: async ({ chatId, prompt }: { chatId: string, prompt: string }) => {
- setIsAiLoading(true)
- try {
- return await chatService.streamChat(chatId, prompt, (content) => {
- const htmlContent = markdownToHtml(content);
- const extensions = [
- StarterKit.configure({
- horizontalRule: false,
- codeBlock: false,
- paragraph: { HTMLAttributes: { class: "text-node" } },
- heading: { HTMLAttributes: { class: "heading-node" } },
- blockquote: { HTMLAttributes: { class: "block-node" } },
- bulletList: { HTMLAttributes: { class: "list-node" } },
- orderedList: { HTMLAttributes: { class: "list-node" } },
- code: { HTMLAttributes: { class: "inline", spellcheck: "false" } },
- dropcursor: { width: 2, class: "ProseMirror-dropcursor border" },
- }),
- Link,
- Underline,
- Image,
- Color,
- TextStyle,
- HorizontalRule,
- CodeBlockLowlight,
- Typography,
- Placeholder.configure({ placeholder: 'Enter your analysis...' })
- ]
- const jsonContent = generateJSON(htmlContent, extensions)
-
- if (editor) {
- // If we have an editor instance, use its commands
- editor.commands.setContent(jsonContent)
- onContentUpdate(jsonContent)
- } else {
- // Otherwise, use the callback
- onContentUpdate(content)
- }
- }, selectedNodes)
- } catch (error) {
- console.error("Error in chat stream:", error)
- throw error
- } finally {
- setIsAiLoading(false)
- }
- },
- onSuccess: () => {
- onSuccess?.()
- // Invalidate the current chat query to refresh messages
- if (currentChatId) {
- onContentUpdate("")
- queryClient.invalidateQueries({ queryKey: queryKeys.chats.detail(currentChatId) })
- }
- },
- onError: (error) => {
- console.error("Chat error:", error)
- toast.error("Failed to get AI completion: " + (error instanceof Error ? error.message : "Unknown error"))
- }
- })
-
- const handleCustomPrompt = async () => {
- // Case where no chat is created - create a new chat first
- if (!currentChatId) {
- const chatTitle = selectedNodes.length > 0
- ? `${selectedNodes.map(node => node.data.label).join(", ").slice(0, 100)}`
- : "New Chat"
-
- try {
- const newChat = await createChatMutation.mutateAsync({
- title: chatTitle,
- description: "Chat created from analysis"
- })
- // After creating the chat, proceed with the prompt
- if (newChat?.id) {
- await handlePromptWithChat(newChat.id)
- }
- } catch (error) {
- console.error("Failed to create chat:", error)
- return
- }
- } else {
- addMessage({ content: customPrompt.trim(), context: selectedNodes.map(node => node.data.label), is_bot: false, id: new Date().getTime().toString(), created_at: new Date().toISOString(), chatId: currentChatId })
- await handlePromptWithChat(currentChatId)
- }
+ const [isAiLoading, setIsAiLoading] = useState(false)
+ const [customPrompt, setCustomPrompt] = useState('')
+ const selectedNodes = useGraphStore((s) => s.selectedNodes)
+ const currentChatId = useChatState((s) => s.currentChatId)
+ const setCurrentChatId = useChatState((s) => s.setCurrentChatId)
+ const deleteChat = useChatState((s) => s.deleteChat)
+ const addMessage = useChatState((s) => s.addMessage)
+ const { investigationId } = useParams({ strict: false })
+ const queryClient = useQueryClient()
+
+ // Fetch current chat data with messages
+ const { data: currentChat, isLoading: isLoadingChat } = useQuery({
+ queryKey: queryKeys.chats.detail(currentChatId!),
+ queryFn: () => chatCRUDService.getById(currentChatId!),
+ enabled: !!currentChatId,
+ refetchOnWindowFocus: false
+ })
+
+ // Mutation to create a new chat
+ const createChatMutation = useMutation({
+ mutationFn: async ({ title, description }: { title: string; description?: string }) => {
+ const chatData = {
+ title,
+ description: description || '',
+ investigation_id: investigationId
+ }
+ return await chatCRUDService.create(JSON.stringify(chatData))
+ },
+ onSuccess: (data) => {
+ // Add the new chat to the store
+ // Invalidate chats query to refresh the list
+ queryClient.invalidateQueries({ queryKey: queryKeys.chats.detail(currentChatId!) })
+ setCurrentChatId(data.id)
+ toast.success('New chat created successfully!')
+ },
+ onError: (error) => {
+ console.error('Error creating chat:', error)
+ toast.error(
+ 'Failed to create chat: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
}
+ })
- const handlePromptWithChat = async (chatId: string) => {
- if (!customPrompt.trim()) {
- toast.error("Please enter a prompt")
- return
- }
- const fullPrompt = `${customPrompt}`
- setCustomPrompt("")
- aiCompletionMutation.mutate({ chatId, prompt: fullPrompt })
+ // Mutation to delete a chat
+ const deleteChatMutation = useMutation({
+ mutationFn: async (chatId: string) => {
+ deleteChat(chatId)
+ return await chatCRUDService.delete(chatId)
+ },
+ onSuccess: () => {
+ // Remove the chat from the store
+ // Invalidate chats query to refresh the list
+ queryClient.invalidateQueries({ queryKey: queryKeys.chats.list })
+ toast.success('Chat deleted successfully!')
+ },
+ onError: (error) => {
+ console.error('Error deleting chat:', error)
+ toast.error(
+ 'Failed to delete chat: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
}
+ })
- const createNewChat = async (title?: string) => {
- const chatTitle = title || (selectedNodes.length > 0
- ? `${selectedNodes[0].data.label}`
- : "New Chat #" + Math.floor(Math.random() * 900) + 1000)
-
- try {
- await createChatMutation.mutateAsync({
- title: chatTitle,
- description: "Chat created from analysis"
- })
- } catch (error) {
- console.error("Failed to create new chat:", error)
- }
+ const aiCompletionMutation = useMutation({
+ mutationFn: async ({ chatId, prompt }: { chatId: string; prompt: string }) => {
+ setIsAiLoading(true)
+ try {
+ return await chatService.streamChat(
+ chatId,
+ prompt,
+ (content) => {
+ const htmlContent = markdownToHtml(content)
+ const extensions = [
+ StarterKit.configure({
+ horizontalRule: false,
+ codeBlock: false,
+ paragraph: { HTMLAttributes: { class: 'text-node' } },
+ heading: { HTMLAttributes: { class: 'heading-node' } },
+ blockquote: { HTMLAttributes: { class: 'block-node' } },
+ bulletList: { HTMLAttributes: { class: 'list-node' } },
+ orderedList: { HTMLAttributes: { class: 'list-node' } },
+ code: { HTMLAttributes: { class: 'inline', spellcheck: 'false' } },
+ dropcursor: { width: 2, class: 'ProseMirror-dropcursor border' }
+ }),
+ Link,
+ Underline,
+ Image,
+ Color,
+ TextStyle,
+ HorizontalRule,
+ CodeBlockLowlight,
+ Typography,
+ Placeholder.configure({ placeholder: 'Enter your analysis...' })
+ ]
+ const jsonContent = generateJSON(htmlContent, extensions)
+
+ if (editor) {
+ // If we have an editor instance, use its commands
+ editor.commands.setContent(jsonContent)
+ onContentUpdate(jsonContent)
+ } else {
+ // Otherwise, use the callback
+ onContentUpdate(content)
+ }
+ },
+ selectedNodes
+ )
+ } catch (error) {
+ console.error('Error in chat stream:', error)
+ throw error
+ } finally {
+ setIsAiLoading(false)
+ }
+ },
+ onSuccess: () => {
+ onSuccess?.()
+ // Invalidate the current chat query to refresh messages
+ if (currentChatId) {
+ onContentUpdate('')
+ queryClient.invalidateQueries({ queryKey: queryKeys.chats.detail(currentChatId) })
+ }
+ },
+ onError: (error) => {
+ console.error('Chat error:', error)
+ toast.error(
+ 'Failed to get AI completion: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
}
+ })
- const deleteCurrentChat = async () => {
- if (!currentChatId) {
- toast.error("No chat to delete")
- return
- }
- try {
- await deleteChatMutation.mutateAsync(currentChatId)
- } catch (error) {
- console.error("Failed to delete chat:", error)
+ const handleCustomPrompt = async () => {
+ // Case where no chat is created - create a new chat first
+ if (!currentChatId) {
+ const chatTitle =
+ selectedNodes.length > 0
+ ? `${selectedNodes
+ .map((node) => node.data.label)
+ .join(', ')
+ .slice(0, 100)}`
+ : 'New Chat'
+
+ try {
+ const newChat = await createChatMutation.mutateAsync({
+ title: chatTitle,
+ description: 'Chat created from analysis'
+ })
+ // After creating the chat, proceed with the prompt
+ if (newChat?.id) {
+ await handlePromptWithChat(newChat.id)
}
+ } catch (error) {
+ console.error('Failed to create chat:', error)
+ return
+ }
+ } else {
+ addMessage({
+ content: customPrompt.trim(),
+ context: selectedNodes.map((node) => node.data.label),
+ is_bot: false,
+ id: new Date().getTime().toString(),
+ created_at: new Date().toISOString(),
+ chatId: currentChatId
+ })
+ await handlePromptWithChat(currentChatId)
+ }
+ }
+
+ const handlePromptWithChat = async (chatId: string) => {
+ if (!customPrompt.trim()) {
+ toast.error('Please enter a prompt')
+ return
}
+ const fullPrompt = `${customPrompt}`
+ setCustomPrompt('')
+ aiCompletionMutation.mutate({ chatId, prompt: fullPrompt })
+ }
+
+ const createNewChat = async (title?: string) => {
+ const chatTitle =
+ title ||
+ (selectedNodes.length > 0
+ ? `${selectedNodes[0].data.label}`
+ : 'New Chat #' + Math.floor(Math.random() * 900) + 1000)
- const switchToChat = (chatId: string) => {
- setCurrentChatId(chatId)
+ try {
+ await createChatMutation.mutateAsync({
+ title: chatTitle,
+ description: 'Chat created from analysis'
+ })
+ } catch (error) {
+ console.error('Failed to create new chat:', error)
}
+ }
- return {
- isAiLoading,
- customPrompt,
- setCustomPrompt,
- handleCustomPrompt,
- createChatMutation,
- deleteChatMutation,
- currentChat,
- isLoadingChat,
- createNewChat,
- deleteCurrentChat,
- switchToChat,
- currentChatId
+ const deleteCurrentChat = async () => {
+ if (!currentChatId) {
+ toast.error('No chat to delete')
+ return
+ }
+ try {
+ await deleteChatMutation.mutateAsync(currentChatId)
+ } catch (error) {
+ console.error('Failed to delete chat:', error)
}
-}
\ No newline at end of file
+ }
+
+ const switchToChat = (chatId: string) => {
+ setCurrentChatId(chatId)
+ }
+
+ return {
+ isAiLoading,
+ customPrompt,
+ setCustomPrompt,
+ handleCustomPrompt,
+ createChatMutation,
+ deleteChatMutation,
+ currentChat,
+ isLoadingChat,
+ createNewChat,
+ deleteCurrentChat,
+ switchToChat,
+ currentChatId
+ }
+}
diff --git a/flowsint-app/src/renderer/src/hooks/use-debounce.ts b/flowsint-app/src/renderer/src/hooks/use-debounce.ts
index cd5e2ae6..c80d6fe6 100644
--- a/flowsint-app/src/renderer/src/hooks/use-debounce.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-debounce.ts
@@ -1,34 +1,36 @@
-
-import { useEffect, useState } from "react"
+import { useEffect, useState } from 'react'
// This hook creates a debounced version of a value
export function useDebounce<T>(value: T, delay: number): T {
- const [debouncedValue, setDebouncedValue] = useState<T>(value)
+ const [debouncedValue, setDebouncedValue] = useState<T>(value)
- useEffect(() => {
- const timer = setTimeout(() => {
- setDebouncedValue(value)
- }, delay)
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ setDebouncedValue(value)
+ }, delay)
- return () => {
- clearTimeout(timer)
- }
- }, [value, delay])
+ return () => {
+ clearTimeout(timer)
+ }
+ }, [value, delay])
- return debouncedValue
+ return debouncedValue
}
// This function creates a debounced version of a function
-export function debounce<T extends (...args: any[]) => any>(func: T, wait: number): (...args: Parameters<T>) => void {
- let timeout: NodeJS.Timeout | null = null
-
- return (...args: Parameters<T>) => {
- const later = () => {
- timeout = null
- func(...args)
- }
-
- if (timeout) clearTimeout(timeout)
- timeout = setTimeout(later, wait)
+export function debounce<T extends (...args: any[]) => any>(
+ func: T,
+ wait: number
+): (...args: Parameters<T>) => void {
+ let timeout: NodeJS.Timeout | null = null
+
+ return (...args: Parameters<T>) => {
+ const later = () => {
+ timeout = null
+ func(...args)
}
+
+ if (timeout) clearTimeout(timeout)
+ timeout = setTimeout(later, wait)
+ }
}
diff --git a/flowsint-app/src/renderer/src/hooks/use-drag-drop.ts b/flowsint-app/src/renderer/src/hooks/use-drag-drop.ts
index 953ddc34..96b47814 100644
--- a/flowsint-app/src/renderer/src/hooks/use-drag-drop.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-drag-drop.ts
@@ -4,61 +4,64 @@ import { findActionItemByKey } from '@/lib/action-items'
import { useActionItems } from './use-action-items'
export const useDragAndDrop = () => {
- const [isDraggingOver, setIsDraggingOver] = useState(false)
- const { actionItems } = useActionItems()
- const handleOpenFormModal = useGraphStore(s => s.handleOpenFormModal)
- const dragLeaveTimeoutRef = useRef<number | null>(null)
+ const [isDraggingOver, setIsDraggingOver] = useState(false)
+ const { actionItems } = useActionItems()
+ const handleOpenFormModal = useGraphStore((s) => s.handleOpenFormModal)
+ const dragLeaveTimeoutRef = useRef<number | null>(null)
- const handleDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- if (dragLeaveTimeoutRef.current) {
- clearTimeout(dragLeaveTimeoutRef.current)
- }
- setIsDraggingOver(true)
- }, [])
+ const handleDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ if (dragLeaveTimeoutRef.current) {
+ clearTimeout(dragLeaveTimeoutRef.current)
+ }
+ setIsDraggingOver(true)
+ }, [])
- const handleDragEnter = useCallback((e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- if (dragLeaveTimeoutRef.current) {
- clearTimeout(dragLeaveTimeoutRef.current)
- }
- setIsDraggingOver(true)
- }, [])
+ const handleDragEnter = useCallback((e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ if (dragLeaveTimeoutRef.current) {
+ clearTimeout(dragLeaveTimeoutRef.current)
+ }
+ setIsDraggingOver(true)
+ }, [])
- const handleDragLeave = useCallback(() => {
- //@ts-ignore
- dragLeaveTimeoutRef.current = setTimeout(() => {
- setIsDraggingOver(false)
- }, 100)
- }, [])
+ const handleDragLeave = useCallback(() => {
+ //@ts-ignore
+ dragLeaveTimeoutRef.current = setTimeout(() => {
+ setIsDraggingOver(false)
+ }, 100)
+ }, [])
- const handleDrop = useCallback((e: React.DragEvent<HTMLDivElement>) => {
- e.preventDefault()
- if (dragLeaveTimeoutRef.current) {
- clearTimeout(dragLeaveTimeoutRef.current)
- }
- setIsDraggingOver(false)
+ const handleDrop = useCallback(
+ (e: React.DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ if (dragLeaveTimeoutRef.current) {
+ clearTimeout(dragLeaveTimeoutRef.current)
+ }
+ setIsDraggingOver(false)
- const data = e.dataTransfer.getData("text/plain")
- if (!data) return
+ const data = e.dataTransfer.getData('text/plain')
+ if (!data) return
- try {
- const parsedData = JSON.parse(data)
- if (parsedData?.itemKey) {
- handleOpenFormModal(findActionItemByKey(parsedData.itemKey, actionItems))
- }
- } catch (error) {
- console.warn('Failed to parse dropped data:', error)
+ try {
+ const parsedData = JSON.parse(data)
+ if (parsedData?.itemKey) {
+ handleOpenFormModal(findActionItemByKey(parsedData.itemKey, actionItems))
}
- }, [handleOpenFormModal, actionItems])
+ } catch (error) {
+ console.warn('Failed to parse dropped data:', error)
+ }
+ },
+ [handleOpenFormModal, actionItems]
+ )
- return {
- isDraggingOver,
- dragHandlers: {
- onDragOver: handleDragOver,
- onDragEnter: handleDragEnter,
- onDragLeave: handleDragLeave,
- onDrop: handleDrop,
- }
+ return {
+ isDraggingOver,
+ dragHandlers: {
+ onDragOver: handleDragOver,
+ onDragEnter: handleDragEnter,
+ onDragLeave: handleDragLeave,
+ onDrop: handleDrop
}
-}
\ No newline at end of file
+ }
+}
diff --git a/flowsint-app/src/renderer/src/hooks/use-events.ts b/flowsint-app/src/renderer/src/hooks/use-events.ts
index 7c69a17d..6a20d0ce 100644
--- a/flowsint-app/src/renderer/src/hooks/use-events.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-events.ts
@@ -1,70 +1,72 @@
-import { useEffect, useState } from "react"
-import { useQuery } from "@tanstack/react-query"
-import { logService } from "@/api/log-service"
-import { EventLevel } from "@/types"
-import { useGraphControls } from "@/stores/graph-controls-store"
-import { queryKeys } from "@/api/query-keys"
+import { useEffect, useState } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { logService } from '@/api/log-service'
+import { EventLevel } from '@/types'
+import { useGraphControls } from '@/stores/graph-controls-store'
+import { queryKeys } from '@/api/query-keys'
export function useEvents(sketch_id: string | undefined) {
- const [liveLogs, setLiveLogs] = useState<Event[]>([])
- // const [graphUpdates, setGraphUpdates] = useState<{ nodes: GraphNode[]; edges: GraphEdge[] }[]>([])
- const refetchGraph = useGraphControls((s) => s.refetchGraph)
+ const [liveLogs, setLiveLogs] = useState<Event[]>([])
+ // const [graphUpdates, setGraphUpdates] = useState<{ nodes: GraphNode[]; edges: GraphEdge[] }[]>([])
+ const refetchGraph = useGraphControls((s) => s.refetchGraph)
- const { data: previousLogs = [], refetch } = useQuery({
- queryKey: queryKeys.logs.bySketch(sketch_id as string),
- queryFn: () => logService.get(sketch_id as string),
- refetchOnWindowFocus: false,
- enabled: !!sketch_id,
- staleTime: 30_000,
- })
+ const { data: previousLogs = [], refetch } = useQuery({
+ queryKey: queryKeys.logs.bySketch(sketch_id as string),
+ queryFn: () => logService.get(sketch_id as string),
+ refetchOnWindowFocus: false,
+ enabled: !!sketch_id,
+ staleTime: 30_000
+ })
- const handleRefresh = () => {
- refetch()
- setLiveLogs([]) // Pour éviter les doublons dans les logs live
- }
+ const handleRefresh = () => {
+ refetch()
+ setLiveLogs([]) // Pour éviter les doublons dans les logs live
+ }
- useEffect(() => {
- if (!sketch_id) return
+ useEffect(() => {
+ if (!sketch_id) return
- const eventSource = new EventSource(`http://localhost:5001/api/events/sketch/${sketch_id}/stream`)
+ const eventSource = new EventSource(
+ `http://localhost:5001/api/events/sketch/${sketch_id}/stream`
+ )
- eventSource.onmessage = (e) => {
- try {
- const raw = JSON.parse(e.data) as any
- const event = JSON.parse(raw.data) as Event
- if (event.type === EventLevel.COMPLETED) {
- refetchGraph()
- // const nodes = event.payload.nodes as GraphNode[]
- // const edges = event.payload.edges as GraphEdge[]
- // if (nodes && edges) {
- // setGraphUpdates((prev) => [...prev, { nodes: nodes, edges: edges }])
- // } else {
- // console.error("[useSketchEvents] Graph append event has no nodes or edges")
- // }
- }
- setLiveLogs((prev) => [...prev.slice(-99), event])
- } catch (error) {
- console.error("[useSketchEvents] Failed to parse SSE event:", error)
- }
+ eventSource.onmessage = (e) => {
+ try {
+ const raw = JSON.parse(e.data) as any
+ const event = JSON.parse(raw.data) as Event
+ if (event.type === EventLevel.COMPLETED) {
+ refetchGraph()
+ // const nodes = event.payload.nodes as GraphNode[]
+ // const edges = event.payload.edges as GraphEdge[]
+ // if (nodes && edges) {
+ // setGraphUpdates((prev) => [...prev, { nodes: nodes, edges: edges }])
+ // } else {
+ // console.error("[useSketchEvents] Graph append event has no nodes or edges")
+ // }
}
+ setLiveLogs((prev) => [...prev.slice(-99), event])
+ } catch (error) {
+ console.error('[useSketchEvents] Failed to parse SSE event:', error)
+ }
+ }
- eventSource.onerror = (error) => {
- console.error("[useSketchEvents] EventSource error:", error)
- eventSource.close()
- }
+ eventSource.onerror = (error) => {
+ console.error('[useSketchEvents] EventSource error:', error)
+ eventSource.close()
+ }
- return () => {
- console.log("[useSketchEvents] Closing SSE connection")
- eventSource.close()
- }
- }, [sketch_id])
+ return () => {
+ console.log('[useSketchEvents] Closing SSE connection')
+ eventSource.close()
+ }
+ }, [sketch_id])
- const logs = [...previousLogs, ...liveLogs].slice(-100)
+ const logs = [...previousLogs, ...liveLogs].slice(-100)
- return {
- logs,
- // graphUpdates,
- refetch: handleRefresh,
- // clearGraphUpdates: () => setGraphUpdates([]),
- }
+ return {
+ logs,
+ // graphUpdates,
+ refetch: handleRefresh
+ // clearGraphUpdates: () => setGraphUpdates([]),
+ }
}
diff --git a/flowsint-app/src/renderer/src/hooks/use-icon.tsx b/flowsint-app/src/renderer/src/hooks/use-icon.tsx
index cc5c5e00..8bc3dbe3 100644
--- a/flowsint-app/src/renderer/src/hooks/use-icon.tsx
+++ b/flowsint-app/src/renderer/src/hooks/use-icon.tsx
@@ -1,115 +1,119 @@
-import { type JSX, useMemo, useCallback } from "react";
-import { useNodesDisplaySettings } from "@/stores/node-display-settings";
+import { type JSX, useMemo, useCallback } from 'react'
+import { useNodesDisplaySettings } from '@/stores/node-display-settings'
-export type IconType = string;
+export type IconType = string
interface IconProps {
- className?: string;
- size?: number;
- style?: React.CSSProperties;
- showBorder?: boolean;
- color?: string;
- type?: string;
+ className?: string
+ size?: number
+ style?: React.CSSProperties
+ showBorder?: boolean
+ color?: string
+ type?: string
}
// Utilisation de constantes pour les valeurs par défaut
-const DEFAULT_SIZE = 24;
-const DEFAULT_COLOR = "#000000";
-const BORDER_RATIO = 8;
-const CONTAINER_PADDING = 16;
-const BACKGROUND_PADDING = 8;
+const DEFAULT_SIZE = 24
+const DEFAULT_COLOR = '#000000'
+const BORDER_RATIO = 8
+const CONTAINER_PADDING = 16
+const BACKGROUND_PADDING = 8
// Fonctions utilitaires memoizées
-const getIconPath = (type: string): string =>
- `/icons/${type}.svg`;
+const getIconPath = (type: string): string => `/icons/${type}.svg`
-const getDefaultIconPath = (): string =>
- `/icons/default.svg`;
+const getDefaultIconPath = (): string => `/icons/default.svg`
export const useIcon = (type: IconType, src?: string | null) => {
- const iconPath = useMemo(() => getIconPath(type), [type]);
- const defaultIconPath = useMemo(() => getDefaultIconPath(), []);
+ const iconPath = useMemo(() => getIconPath(type), [type])
+ const defaultIconPath = useMemo(() => getDefaultIconPath(), [])
- return useCallback(({
- className = "",
- size = DEFAULT_SIZE,
- style,
- showBorder = false,
- color,
- // @ts-ignore
- type: iconType
- }: IconProps): JSX.Element => {
- const colors = useNodesDisplaySettings((s) => s.colors);
- const resolvedColor = color || colors[type as keyof typeof colors] || DEFAULT_COLOR;
+ return useCallback(
+ ({
+ className = '',
+ size = DEFAULT_SIZE,
+ style,
+ showBorder = false,
+ color,
+ // @ts-ignore
+ type: iconType
+ }: IconProps): JSX.Element => {
+ const colors = useNodesDisplaySettings((s) => s.colors)
+ const resolvedColor = color || colors[type as keyof typeof colors] || DEFAULT_COLOR
- // Gestion de l'erreur de chargement d'image
- const handleImageError = useCallback((e: React.SyntheticEvent<HTMLImageElement>) => {
- const target = e.currentTarget;
- if (target.src !== defaultIconPath) {
- target.src = defaultIconPath;
- }
- }, [defaultIconPath]);
+ // Gestion de l'erreur de chargement d'image
+ const handleImageError = useCallback(
+ (e: React.SyntheticEvent<HTMLImageElement>) => {
+ const target = e.currentTarget
+ if (target.src !== defaultIconPath) {
+ target.src = defaultIconPath
+ }
+ },
+ [defaultIconPath]
+ )
- // Use full size for src images, scaled size for icons
- const actualIconSize = src ? size : size * 0.70;
+ // Use full size for src images, scaled size for icons
+ const actualIconSize = src ? size : size * 0.7
- const imageElement = (
- <img
- src={src || iconPath}
- width={actualIconSize}
- height={actualIconSize}
- className={`object-contain flex-shrink-0 rounded-full ${className} p-0`}
- style={{
- minWidth: actualIconSize,
- minHeight: actualIconSize,
- maxWidth: actualIconSize,
- maxHeight: actualIconSize,
- ...(showBorder ? undefined : style)
- }}
- alt={`${type} icon`}
- onError={handleImageError}
- />
- );
+ const imageElement = (
+ <img
+ src={src || iconPath}
+ width={actualIconSize}
+ height={actualIconSize}
+ className={`object-contain flex-shrink-0 rounded-full ${className} p-0`}
+ style={{
+ minWidth: actualIconSize,
+ minHeight: actualIconSize,
+ maxWidth: actualIconSize,
+ maxHeight: actualIconSize,
+ ...(showBorder ? undefined : style)
+ }}
+ alt={`${type} icon`}
+ onError={handleImageError}
+ />
+ )
- if (showBorder) {
- const containerSize = size + CONTAINER_PADDING;
- const borderWidth = Math.max(1, size / BORDER_RATIO);
+ if (showBorder) {
+ const containerSize = size + CONTAINER_PADDING
+ const borderWidth = Math.max(1, size / BORDER_RATIO)
+ return (
+ <div
+ className="flex bg-card items-center justify-center rounded-full overflow-hidden flex-shrink-0"
+ style={{
+ border: `${borderWidth}px solid ${resolvedColor}`,
+ width: containerSize,
+ height: containerSize,
+ minWidth: containerSize,
+ minHeight: containerSize,
+ maxWidth: containerSize,
+ maxHeight: containerSize,
+ ...style
+ }}
+ >
+ {imageElement}
+ </div>
+ )
+ }
+
+ const containerSize = size + BACKGROUND_PADDING
return (
<div
- className="flex bg-card items-center justify-center rounded-full overflow-hidden flex-shrink-0"
+ className="rounded-full flex items-center justify-center overflow-hidden flex-shrink-0"
style={{
- border: `${borderWidth}px solid ${resolvedColor}`,
+ background: resolvedColor,
width: containerSize,
height: containerSize,
minWidth: containerSize,
minHeight: containerSize,
maxWidth: containerSize,
- maxHeight: containerSize,
- ...style,
+ maxHeight: containerSize
}}
>
{imageElement}
</div>
- );
- }
-
- const containerSize = size + BACKGROUND_PADDING;
- return (
- <div
- className="rounded-full flex items-center justify-center overflow-hidden flex-shrink-0"
- style={{
- background: resolvedColor,
- width: containerSize,
- height: containerSize,
- minWidth: containerSize,
- minHeight: containerSize,
- maxWidth: containerSize,
- maxHeight: containerSize,
- }}
- >
- {imageElement}
- </div>
- );
- }, [iconPath, defaultIconPath, type]);
-};
\ No newline at end of file
+ )
+ },
+ [iconPath, defaultIconPath, type]
+ )
+}
diff --git a/flowsint-app/src/renderer/src/hooks/use-keyboard-shortcut.ts b/flowsint-app/src/renderer/src/hooks/use-keyboard-shortcut.ts
index 2405caa4..cdc687bb 100644
--- a/flowsint-app/src/renderer/src/hooks/use-keyboard-shortcut.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-keyboard-shortcut.ts
@@ -1,35 +1,34 @@
-import { isMac } from "@/lib/utils"
-import { useEffect, useState } from "react"
+import { isMac } from '@/lib/utils'
+import { useEffect, useState } from 'react'
type ShortcutOptions = {
- key: string
- ctrlOrCmd?: boolean
- alt?: boolean
- shift?: boolean
- callback: () => void
+ key: string
+ ctrlOrCmd?: boolean
+ alt?: boolean
+ shift?: boolean
+ callback: () => void
}
export function useKeyboardShortcut(options: ShortcutOptions) {
-
- useEffect(() => {
- const handleKeyDown = (event: KeyboardEvent) => {
- const { key, ctrlKey, altKey, shiftKey, metaKey } = event
- if (key.toLowerCase() !== options.key.toLowerCase()) {
- return
- }
- const cmdKeyPressed = isMac ? metaKey : ctrlKey
- if (
- (options.ctrlOrCmd === undefined || options.ctrlOrCmd === cmdKeyPressed) &&
- (options.alt === undefined || options.alt === altKey) &&
- (options.shift === undefined || options.shift === shiftKey)
- ) {
- event.preventDefault()
- options.callback()
- }
- }
- window.addEventListener("keydown", handleKeyDown)
- return () => {
- window.removeEventListener("keydown", handleKeyDown)
- }
- }, [options, isMac])
- return { isMac }
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const { key, ctrlKey, altKey, shiftKey, metaKey } = event
+ if (key.toLowerCase() !== options.key.toLowerCase()) {
+ return
+ }
+ const cmdKeyPressed = isMac ? metaKey : ctrlKey
+ if (
+ (options.ctrlOrCmd === undefined || options.ctrlOrCmd === cmdKeyPressed) &&
+ (options.alt === undefined || options.alt === altKey) &&
+ (options.shift === undefined || options.shift === shiftKey)
+ ) {
+ event.preventDefault()
+ options.callback()
+ }
+ }
+ window.addEventListener('keydown', handleKeyDown)
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown)
+ }
+ }, [options, isMac])
+ return { isMac }
}
diff --git a/flowsint-app/src/renderer/src/hooks/use-launch-flow.ts b/flowsint-app/src/renderer/src/hooks/use-launch-flow.ts
index 196a6ece..0ccaeecf 100644
--- a/flowsint-app/src/renderer/src/hooks/use-launch-flow.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-launch-flow.ts
@@ -1,49 +1,54 @@
-import { toast } from "sonner"
-import { useConfirm } from "@/components/use-confirm-dialog"
-import { flowService } from "@/api/flow-service"
-import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { queryKeys } from "@/api/query-keys"
+import { toast } from 'sonner'
+import { useConfirm } from '@/components/use-confirm-dialog'
+import { flowService } from '@/api/flow-service'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { queryKeys } from '@/api/query-keys'
export function useLaunchFlow(askUser: boolean = false) {
- const { confirm } = useConfirm()
- const queryClient = useQueryClient()
+ const { confirm } = useConfirm()
+ const queryClient = useQueryClient()
- // Launch flow mutation
- const launchFlowMutation = useMutation({
- mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>
- flowService.launch(flowId, body),
- onSuccess: (data, variables) => {
- queryClient.invalidateQueries({
- queryKey: queryKeys.flows.detail(variables.flowId)
- })
- },
- onError: (error) => {
- console.error("Error launching flow:", error)
- }
- })
-
- const launchFlow = async (values: string[], flow_id: string, sketch_id: string | null | undefined) => {
- if (!sketch_id) return toast.error("Could not find the graph.")
- if (askUser) {
- const confirmed = await confirm({
- title: `${flow_id} scan`,
- message: `You're about to launch ${flow_id} flow on ${values.length} items.`,
- })
- if (!confirmed) return
- }
- const body = JSON.stringify({ values, sketch_id })
- const sliced = values.slice(0, 2)
- const left = values.length - sliced.length
-
- toast.promise(launchFlowMutation.mutateAsync({ flowId: flow_id, body }), {
- loading: "Loading...",
- success: () => `Flow ${flow_id} has been launched on "${sliced.join(",")}" ${left > 0 && ` and ${left} others`}.`,
- error: () => `An error occurred launching flow.`,
- })
- return
+ // Launch flow mutation
+ const launchFlowMutation = useMutation({
+ mutationFn: ({ flowId, body }: { flowId: string; body: BodyInit }) =>
+ flowService.launch(flowId, body),
+ onSuccess: (data, variables) => {
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.flows.detail(variables.flowId)
+ })
+ },
+ onError: (error) => {
+ console.error('Error launching flow:', error)
}
-
- return {
- launchFlow,
+ })
+
+ const launchFlow = async (
+ values: string[],
+ flow_id: string,
+ sketch_id: string | null | undefined
+ ) => {
+ if (!sketch_id) return toast.error('Could not find the graph.')
+ if (askUser) {
+ const confirmed = await confirm({
+ title: `${flow_id} scan`,
+ message: `You're about to launch ${flow_id} flow on ${values.length} items.`
+ })
+ if (!confirmed) return
}
+ const body = JSON.stringify({ values, sketch_id })
+ const sliced = values.slice(0, 2)
+ const left = values.length - sliced.length
+
+ toast.promise(launchFlowMutation.mutateAsync({ flowId: flow_id, body }), {
+ loading: 'Loading...',
+ success: () =>
+ `Flow ${flow_id} has been launched on "${sliced.join(',')}" ${left > 0 && ` and ${left} others`}.`,
+ error: () => `An error occurred launching flow.`
+ })
+ return
+ }
+
+ return {
+ launchFlow
+ }
}
diff --git a/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts b/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts
index 1516058b..47a11bb7 100644
--- a/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts
@@ -1,29 +1,34 @@
-import { toast } from "sonner"
-import { useConfirm } from "@/components/use-confirm-dialog"
-import { transformService } from "@/api/transform-service"
+import { toast } from 'sonner'
+import { useConfirm } from '@/components/use-confirm-dialog'
+import { transformService } from '@/api/transform-service'
export function useLaunchTransform(askUser: boolean = false) {
- const { confirm } = useConfirm()
- const launchTransform = async (values: string[], transformName: string, sketch_id: string | null | undefined) => {
- if (!sketch_id) return toast.error("Could not find the graph.")
- if (askUser) {
- const confirmed = await confirm({
- title: `${transformName} scan`,
- message: `You're about to launch ${transformName} transform on ${values.length} items.`,
- })
- if (!confirmed) return
- }
- const body = JSON.stringify({ values, sketch_id })
- const sliced = values.slice(0, 2)
- const left = values.length - sliced.length
- toast.promise(transformService.launch(transformName, body), {
- loading: "Loading...",
- success: () => `Transform ${transformName} has been launched on ${sliced.join(", ")}${left > 0 ? ` and ${left} others` : ""}.`,
- error: () => `An error occurred launching transform.`,
- })
- return
- }
- return {
- launchTransform,
+ const { confirm } = useConfirm()
+ const launchTransform = async (
+ values: string[],
+ transformName: string,
+ sketch_id: string | null | undefined
+ ) => {
+ if (!sketch_id) return toast.error('Could not find the graph.')
+ if (askUser) {
+ const confirmed = await confirm({
+ title: `${transformName} scan`,
+ message: `You're about to launch ${transformName} transform on ${values.length} items.`
+ })
+ if (!confirmed) return
}
+ const body = JSON.stringify({ values, sketch_id })
+ const sliced = values.slice(0, 2)
+ const left = values.length - sliced.length
+ toast.promise(transformService.launch(transformName, body), {
+ loading: 'Loading...',
+ success: () =>
+ `Transform ${transformName} has been launched on ${sliced.join(', ')}${left > 0 ? ` and ${left} others` : ''}.`,
+ error: () => `An error occurred launching transform.`
+ })
+ return
+ }
+ return {
+ launchTransform
+ }
}
diff --git a/flowsint-app/src/renderer/src/hooks/use-mobile.ts b/flowsint-app/src/renderer/src/hooks/use-mobile.ts
index 2b0fe1df..4331d5c5 100644
--- a/flowsint-app/src/renderer/src/hooks/use-mobile.ts
+++ b/flowsint-app/src/renderer/src/hooks/use-mobile.ts
@@ -1,4 +1,4 @@
-import * as React from "react"
+import * as React from 'react'
const MOBILE_BREAKPOINT = 768
@@ -10,9 +10,9 @@ export function useIsMobile() {
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
- mql.addEventListener("change", onChange)
+ mql.addEventListener('change', onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
- return () => mql.removeEventListener("change", onChange)
+ return () => mql.removeEventListener('change', onChange)
}, [])
return !!isMobile
diff --git a/flowsint-app/src/renderer/src/integrations/tanstack-query/root-provider.tsx b/flowsint-app/src/renderer/src/integrations/tanstack-query/root-provider.tsx
index 00e048a1..9a488605 100644
--- a/flowsint-app/src/renderer/src/integrations/tanstack-query/root-provider.tsx
+++ b/flowsint-app/src/renderer/src/integrations/tanstack-query/root-provider.tsx
@@ -4,12 +4,10 @@ const queryClient = new QueryClient()
export function getContext() {
return {
- queryClient,
+ queryClient
}
}
export function Provider({ children }: { children: React.ReactNode }) {
- return (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- )
+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
diff --git a/flowsint-app/src/renderer/src/lib/action-items.ts b/flowsint-app/src/renderer/src/lib/action-items.ts
index 1f585405..80195be9 100644
--- a/flowsint-app/src/renderer/src/lib/action-items.ts
+++ b/flowsint-app/src/renderer/src/lib/action-items.ts
@@ -1,43 +1,56 @@
-export type FieldType = "text" | "date" | "email" | "number" | "select" | "textarea" | "hidden" | "tel" | "url" | "metadata"
+export type FieldType =
+ | 'text'
+ | 'date'
+ | 'email'
+ | 'number'
+ | 'select'
+ | 'textarea'
+ | 'hidden'
+ | 'tel'
+ | 'url'
+ | 'metadata'
export interface SelectOption {
- label: string
- value: string
+ label: string
+ value: string
}
export interface FormField {
- name: string
- label: string
- type: FieldType
- required: boolean
- options?: SelectOption[]
- placeholder?: string
- description?: string
+ name: string
+ label: string
+ type: FieldType
+ required: boolean
+ options?: SelectOption[]
+ placeholder?: string
+ description?: string
}
export interface ActionItem {
- id: number
- type: string
- key: string
- icon: string
- label: string
- color?: string
- fields: FormField[]
- size?: string
- label_key: string
- disabled?: boolean
- comingSoon?: boolean
- children?: ActionItem[]
- description: string
+ id: number
+ type: string
+ key: string
+ icon: string
+ label: string
+ color?: string
+ fields: FormField[]
+ size?: string
+ label_key: string
+ disabled?: boolean
+ comingSoon?: boolean
+ children?: ActionItem[]
+ description: string
}
-export function findActionItemByKey(key: string, actionItems: ActionItem[] | undefined): ActionItem | undefined {
- if (!actionItems) return
- for (const item of actionItems) {
- if (item.key === key) return item
- if (item.children) {
- const found = item.children.find(child => child.key === key)
- if (found) return found
- }
+export function findActionItemByKey(
+ key: string,
+ actionItems: ActionItem[] | undefined
+): ActionItem | undefined {
+ if (!actionItems) return
+ for (const item of actionItems) {
+ if (item.key === key) return item
+ if (item.children) {
+ const found = item.children.find((child) => child.key === key)
+ if (found) return found
}
- return undefined;
-}
\ No newline at end of file
+ }
+ return undefined
+}
diff --git a/flowsint-app/src/renderer/src/lib/auth-utils.ts b/flowsint-app/src/renderer/src/lib/auth-utils.ts
index 6d6b704f..3be29214 100644
--- a/flowsint-app/src/renderer/src/lib/auth-utils.ts
+++ b/flowsint-app/src/renderer/src/lib/auth-utils.ts
@@ -3,29 +3,29 @@ import { redirect } from '@tanstack/react-router'
import type { User } from '@/stores/auth-store'
export function requireAuth(locationHref: string) {
- const isAuth = useAuthStore.getState().isAuthenticated
- const token = useAuthStore.getState().token
+ const isAuth = useAuthStore.getState().isAuthenticated
+ const token = useAuthStore.getState().token
- if (!isAuth || !token) {
- throw redirect({
- to: '/login',
- search: {
- redirect: locationHref,
- },
- })
- }
+ if (!isAuth || !token) {
+ throw redirect({
+ to: '/login',
+ search: {
+ redirect: locationHref
+ }
+ })
+ }
}
export function isAuthenticated(): boolean {
- const isAuth = useAuthStore.getState().isAuthenticated
- const token = useAuthStore.getState().token
- return Boolean(isAuth && token)
+ const isAuth = useAuthStore.getState().isAuthenticated
+ const token = useAuthStore.getState().token
+ return Boolean(isAuth && token)
}
export function getAuthToken(): string | null {
- return useAuthStore.getState().token
+ return useAuthStore.getState().token
}
export function getUser(): User | null {
- return useAuthStore.getState().user
+ return useAuthStore.getState().user
}
diff --git a/flowsint-app/src/renderer/src/lib/utils.ts b/flowsint-app/src/renderer/src/lib/utils.ts
index 29d73ad2..2b10d74d 100644
--- a/flowsint-app/src/renderer/src/lib/utils.ts
+++ b/flowsint-app/src/renderer/src/lib/utils.ts
@@ -1,125 +1,123 @@
-import { clsx, type ClassValue } from "clsx"
-import { twMerge } from "tailwind-merge"
-import Dagre from '@dagrejs/dagre';
-import { GraphEdge, GraphNode } from '@/types';
-import { FlowEdge, FlowNode } from "@/stores/flow-store";
+import { clsx, type ClassValue } from 'clsx'
+import { twMerge } from 'tailwind-merge'
+import Dagre from '@dagrejs/dagre'
+import { GraphEdge, GraphNode } from '@/types'
+import { FlowEdge, FlowNode } from '@/stores/flow-store'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
interface LayoutOptions {
- direction?: "LR" | "TB";
- strength?: number;
- distance?: number;
- iterations?: number;
+ direction?: 'LR' | 'TB'
+ strength?: number
+ distance?: number
+ iterations?: number
}
// dagre layout function for the main graph component.
-export const getDagreLayoutedElements = (nodes: GraphNode[],
+export const getDagreLayoutedElements = (
+ nodes: GraphNode[],
edges: GraphEdge[],
options: LayoutOptions = {
- direction: "TB",
+ direction: 'TB',
strength: -300,
distance: 10,
- iterations: 300,
- },) => {
-
- const g = new Dagre.graphlib.Graph().setDefaultEdgeLabel(() => ({}));
- g.setGraph({ rankdir: options.direction });
- edges.forEach((edge) => g.setEdge(edge.source, edge.target));
+ iterations: 300
+ }
+) => {
+ const g = new Dagre.graphlib.Graph().setDefaultEdgeLabel(() => ({}))
+ g.setGraph({ rankdir: options.direction })
+ edges.forEach((edge) => g.setEdge(edge.source, edge.target))
nodes.forEach((node) =>
g.setNode(node.id, {
...node,
width: node.nodeSize ?? 0,
- height: node.nodeSize ?? 0,
- }),
- );
- Dagre.layout(g);
+ height: node.nodeSize ?? 0
+ })
+ )
+ Dagre.layout(g)
return {
nodes: nodes.map((node) => {
- const position = g.node(node.id);
- const x = position.x - (node.nodeSize ?? 0) / 2;
- const y = position.y - (node.nodeSize ?? 0) / 2;
- return { ...node, x, y };
+ const position = g.node(node.id)
+ const x = position.x - (node.nodeSize ?? 0) / 2
+ const y = position.y - (node.nodeSize ?? 0) / 2
+ return { ...node, x, y }
}),
- edges,
- };
-};
+ edges
+ }
+}
// dagre layout function for the flow component.
-export const getFlowDagreLayoutedElements = (nodes: FlowNode[],
+export const getFlowDagreLayoutedElements = (
+ nodes: FlowNode[],
edges: FlowEdge[],
options: LayoutOptions = {
- direction: "TB",
+ direction: 'TB',
strength: -300,
distance: 10,
- iterations: 300,
- },) => {
-
- const g = new Dagre.graphlib.Graph().setDefaultEdgeLabel(() => ({}));
- g.setGraph({ rankdir: options.direction });
- edges.forEach((edge) => g.setEdge(edge.source, edge.target));
+ iterations: 300
+ }
+) => {
+ const g = new Dagre.graphlib.Graph().setDefaultEdgeLabel(() => ({}))
+ g.setGraph({ rankdir: options.direction })
+ edges.forEach((edge) => g.setEdge(edge.source, edge.target))
nodes.forEach((node) =>
g.setNode(node.id, {
...node,
width: node.measured?.width ?? 0,
- height: node.measured?.height ?? 0,
- }),
- );
- Dagre.layout(g);
+ height: node.measured?.height ?? 0
+ })
+ )
+ Dagre.layout(g)
return {
nodes: nodes.map((node) => {
- const position = g.node(node.id);
- const x = position.x - (node.measured?.width ?? 0) / 2;
- const y = position.y - (node.measured?.height ?? 0) / 2;
- return { ...node, position: { x, y } };
+ const position = g.node(node.id)
+ const x = position.x - (node.measured?.width ?? 0) / 2
+ const y = position.y - (node.measured?.height ?? 0) / 2
+ return { ...node, position: { x, y } }
}),
- edges,
- };
-};
-
+ edges
+ }
+}
export const sanitize = (name: string) => {
return name
- .normalize("NFKD") // Decompose special characters (e.g., accents)
- .replace(/[\u0300-\u036f]/g, "") // Remove accent marks
- .replace(/[^a-zA-Z0-9.\-_]/g, "_") // Replace invalid characters with underscores
- .replace(/_{2,}/g, "_") // Replace multiple underscores with a single one
- .replace(/^_|_$/g, "") // Trim leading or trailing underscores
- .toLowerCase(); // Convert to lowercase for consistency
-};
+ .normalize('NFKD') // Decompose special characters (e.g., accents)
+ .replace(/[\u0300-\u036f]/g, '') // Remove accent marks
+ .replace(/[^a-zA-Z0-9.\-_]/g, '_') // Replace invalid characters with underscores
+ .replace(/_{2,}/g, '_') // Replace multiple underscores with a single one
+ .replace(/^_|_$/g, '') // Trim leading or trailing underscores
+ .toLowerCase() // Convert to lowercase for consistency
+}
export const formatFileSize = (bytes: number) => {
- if (bytes < 1024) return bytes + " B"
- else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB"
- else return (bytes / 1048576).toFixed(1) + " MB"
+ if (bytes < 1024) return bytes + ' B'
+ else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'
+ else return (bytes / 1048576).toFixed(1) + ' MB'
}
-
-
export const getInitials = (name: string) => {
return name
- .split(" ")
+ .split(' ')
.map((part) => part[0])
- .join("")
+ .join('')
.toUpperCase()
.substring(0, 2)
}
-
export function getAvatarColor(name: string): string {
const colors = [
- "bg-red-500",
- "bg-blue-500",
- "bg-green-500",
- "bg-yellow-500",
- "bg-purple-500",
- "bg-pink-500",
- "bg-indigo-500",
- "bg-teal-500",
- "bg-orange-500",
- "bg-cyan-500",
+ 'bg-red-500',
+ 'bg-blue-500',
+ 'bg-green-500',
+ 'bg-yellow-500',
+ 'bg-purple-500',
+ 'bg-pink-500',
+ 'bg-indigo-500',
+ 'bg-teal-500',
+ 'bg-orange-500',
+ 'bg-cyan-500'
]
let hash = 0
for (let i = 0; i < name.length; i++) {
@@ -129,43 +127,42 @@ export function getAvatarColor(name: string): string {
return colors[index]
}
-
export const flattenObj = (ob: Record<string, any>) => {
-
- let result: Record<string, any> = {};
+ const result: Record<string, any> = {}
for (const i in ob) {
if (ob[i] && typeof ob[i] === 'object' && !Array.isArray(ob[i])) {
- const temp = flattenObj(ob[i]);
+ const temp = flattenObj(ob[i])
for (const j in temp) {
- result[i + '.' + j] = temp[j];
+ result[i + '.' + j] = temp[j]
}
- }
- else {
- result[i] = ob[i];
+ } else {
+ result[i] = ob[i]
}
}
- return result;
+ return result
}
interface FlattenableNode {
- [key: string]: unknown;
- children?: FlattenableNode[];
+ [key: string]: unknown
+ children?: FlattenableNode[]
}
-export function flattenArray<T extends FlattenableNode>(nodes: T[], key: string): Omit<T, typeof key>[] {
- let result: Omit<T, typeof key>[] = [];
+export function flattenArray<T extends FlattenableNode>(
+ nodes: T[],
+ key: string
+): Omit<T, typeof key>[] {
+ let result: Omit<T, typeof key>[] = []
for (const node of nodes) {
- const { [key]: children, ...rest } = node;
- result.push(rest as Omit<T, typeof key>);
+ const { [key]: children, ...rest } = node
+ result.push(rest as Omit<T, typeof key>)
if (children) {
- result = result.concat(flattenArray(children as T[], key));
+ result = result.concat(flattenArray(children as T[], key))
}
}
- return result;
+ return result
}
-
export function hexToRgba(hex: string, alpha: number) {
const r = parseInt(hex.slice(1, 3), 16)
const g = parseInt(hex.slice(3, 5), 16)
@@ -173,17 +170,15 @@ export function hexToRgba(hex: string, alpha: number) {
return `rgba(${r}, ${g}, ${b}, ${alpha})`
}
-
export function capitalizeFirstLetter(string: string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
-
export const getAllNodeTypes = (actionItems: any[]) => {
const types: string[] = []
- actionItems.forEach(item => {
+ actionItems.forEach((item) => {
if (item.children) {
- item.children.forEach(child => {
+ item.children.forEach((child) => {
if (child.type && !types.includes(child.type)) {
types.push(child.type)
}
@@ -197,29 +192,36 @@ export const getAllNodeTypes = (actionItems: any[]) => {
export const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
-
interface Dictionary {
- [Key: string]: any;
+ [Key: string]: any
}
export function deepObjectDiff(obj1: Dictionary, obj2: Dictionary): Dictionary {
let diffObject = {}
// We want object 2 to be compared against object 1
- if (typeof obj1 != "object" || typeof obj2 != "object") throw Error("Items to compare mustr be objects.")
+ if (typeof obj1 != 'object' || typeof obj2 != 'object')
+ throw Error('Items to compare mustr be objects.')
// We map over the obj2 key:value duos to retrieve new keys that obj2 might have
Object.entries(obj2).forEach(([key, value]) => {
// We check for additional keys
- if (!obj1.hasOwnProperty(key))
- diffObject = { ...diffObject, [key]: { value, new: true } }
+ if (!obj1.hasOwnProperty(key)) diffObject = { ...diffObject, [key]: { value, new: true } }
else {
- diffObject = { ...diffObject, [key]: { value, new: false, oldValue: obj1[key] ?? null, newValue: obj2[key] ?? null, identical: obj2[key] === obj1[key] } }
+ diffObject = {
+ ...diffObject,
+ [key]: {
+ value,
+ new: false,
+ oldValue: obj1[key] ?? null,
+ newValue: obj2[key] ?? null,
+ identical: obj2[key] === obj1[key]
+ }
+ }
}
})
// We map over the obj1 key:value duos to retrieve keys that might have disapeared
Object.entries(obj1).forEach(([key, value]) => {
// We check for additional keys
- if (!obj2.hasOwnProperty(key))
- diffObject = { ...diffObject, [key]: { value, removed: true } }
+ if (!obj2.hasOwnProperty(key)) diffObject = { ...diffObject, [key]: { value, removed: true } }
})
return diffObject
-}
\ No newline at end of file
+}
diff --git a/flowsint-app/src/renderer/src/main.tsx b/flowsint-app/src/renderer/src/main.tsx
index 5982f86a..d7e6931c 100644
--- a/flowsint-app/src/renderer/src/main.tsx
+++ b/flowsint-app/src/renderer/src/main.tsx
@@ -2,7 +2,10 @@ import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider, createRouter } from '@tanstack/react-router'
import { createHashHistory } from '@tanstack/react-router'
-import { Provider as TanStackQueryProvider, getContext as getQueryContext } from '@/integrations/tanstack-query/root-provider'
+import {
+ Provider as TanStackQueryProvider,
+ getContext as getQueryContext
+} from '@/integrations/tanstack-query/root-provider'
import { routeTree } from './routeTree.gen'
import './styles.css'
import { ThemeProvider } from '@/components/theme-provider'
@@ -13,14 +16,14 @@ const router = createRouter({
routeTree,
history: hashHistory,
context: {
- ...getQueryContext(),
+ ...getQueryContext()
},
defaultPreload: false,
scrollRestoration: true,
defaultStructuralSharing: true,
// Keep components mounted but hidden during transitions
defaultPendingComponent: ({ children }) => children,
- defaultPendingMs: 0,
+ defaultPendingMs: 0
})
declare module '@tanstack/react-router' {
diff --git a/flowsint-app/src/renderer/src/routes/__root.tsx b/flowsint-app/src/renderer/src/routes/__root.tsx
index 8f1ebb8d..42bfab5a 100644
--- a/flowsint-app/src/renderer/src/routes/__root.tsx
+++ b/flowsint-app/src/renderer/src/routes/__root.tsx
@@ -13,9 +13,9 @@ export const Route = createRootRouteWithContext<MyRouterContext>()({
const { theme } = useTheme()
return (
<>
- <Toaster theme={theme} position='top-right' richColors />
+ <Toaster theme={theme} position="top-right" richColors />
<Outlet />
</>
)
- },
+ }
})
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.$flowId.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.$flowId.tsx
index 5e355599..a0b72a8b 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.$flowId.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.$flowId.tsx
@@ -4,40 +4,38 @@ import Loader from '@/components/loader'
import { flowService } from '@/api/flow-service'
export const Route = createFileRoute('/_auth/dashboard/flows/$flowId')({
- loader: async ({ params: { flowId } }) => {
- return {
- flow: await flowService.getById(flowId),
- }
- },
- component: FlowPage,
- pendingComponent: () => (
- <div className="h-full w-full flex items-center justify-center">
- <div className="flex flex-col items-center gap-4">
- <Loader />
- <p className="text-muted-foreground">Loading flow...</p>
- </div>
- </div>
- ),
- errorComponent: ({ error }) => (
- <div className="h-full w-full flex items-center justify-center">
- <div className="text-center">
- <h2 className="text-lg font-semibold text-destructive mb-2">
- Error loading flow
- </h2>
- <p className="text-muted-foreground">{error.message}</p>
- </div>
- </div>
- ),
+ loader: async ({ params: { flowId } }) => {
+ return {
+ flow: await flowService.getById(flowId)
+ }
+ },
+ component: FlowPage,
+ pendingComponent: () => (
+ <div className="h-full w-full flex items-center justify-center">
+ <div className="flex flex-col items-center gap-4">
+ <Loader />
+ <p className="text-muted-foreground">Loading flow...</p>
+ </div>
+ </div>
+ ),
+ errorComponent: ({ error }) => (
+ <div className="h-full w-full flex items-center justify-center">
+ <div className="text-center">
+ <h2 className="text-lg font-semibold text-destructive mb-2">Error loading flow</h2>
+ <p className="text-muted-foreground">{error.message}</p>
+ </div>
+ </div>
+ )
})
function FlowPage() {
- const { flow } = Route.useLoaderData()
- return (
- <Editor
- key={flow.id}
- flow={flow}
- initialNodes={flow?.flow_schema?.nodes}
- initialEdges={flow?.flow_schema?.edges}
- />
- )
-}
\ No newline at end of file
+ const { flow } = Route.useLoaderData()
+ return (
+ <Editor
+ key={flow.id}
+ flow={flow}
+ initialNodes={flow?.flow_schema?.nodes}
+ initialEdges={flow?.flow_schema?.edges}
+ />
+ )
+}
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.index.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.index.tsx
index abf36824..5b7e4929 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.index.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.flows.index.tsx
@@ -13,154 +13,161 @@ import { flowService } from '@/api/flow-service'
import ErrorState from '@/components/shared/error-state'
interface Flow {
- id: string
- name: string
- description?: string
- category?: string[]
- created_at: string
- updated_at?: string
- flow_schema?: any
+ id: string
+ name: string
+ description?: string
+ category?: string[]
+ created_at: string
+ updated_at?: string
+ flow_schema?: any
}
export const Route = createFileRoute('/_auth/dashboard/flows/')({
- component: FlowPage,
+ component: FlowPage
})
function FlowPage() {
- const navigate = useNavigate()
- const { data: flows, isLoading, error, refetch } = useQuery<Flow[]>({
- queryKey: ["flow"],
- queryFn: () => flowService.get(),
- })
+ const navigate = useNavigate()
+ const {
+ data: flows,
+ isLoading,
+ error,
+ refetch
+ } = useQuery<Flow[]>({
+ queryKey: ['flow'],
+ queryFn: () => flowService.get()
+ })
- // Get all unique categories
- const categories = flows?.reduce((acc: string[], flow) => {
- if (flow.category) {
- flow.category.forEach(cat => {
- if (!acc.includes(cat)) acc.push(cat)
- })
- }
- return acc
+ // Get all unique categories
+ const categories =
+ flows?.reduce((acc: string[], flow) => {
+ if (flow.category) {
+ flow.category.forEach((cat) => {
+ if (!acc.includes(cat)) acc.push(cat)
+ })
+ }
+ return acc
}, []) || []
- // Add "All" and "Uncategorized" to categories
- const allCategories = ['All', ...categories, 'Uncategorized']
+ // Add "All" and "Uncategorized" to categories
+ const allCategories = ['All', ...categories, 'Uncategorized']
- return (
- <div className="h-full w-full overflow-y-auto bg-background">
- <div className="border-b border-border z-10">
- <div className="max-w-7xl mx-auto p-8">
- <div className="flex items-center justify-between">
- <div className="space-y-1">
- <h1 className="text-3xl font-bold text-foreground">Flows</h1>
- <p className="text-muted-foreground">
- Create and manage your flow flows.
- </p>
- </div>
- <div className="flex items-center gap-2">
- <NewFlow>
- <Button size="sm">
- <PlusIcon className="w-4 h-4 mr-2" />
- New flow
- </Button>
- </NewFlow>
- </div>
- </div>
- </div>
+ return (
+ <div className="h-full w-full overflow-y-auto bg-background">
+ <div className="border-b border-border z-10">
+ <div className="max-w-7xl mx-auto p-8">
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <h1 className="text-3xl font-bold text-foreground">Flows</h1>
+ <p className="text-muted-foreground">Create and manage your flow flows.</p>
</div>
- <div className="max-w-7xl mx-auto p-8 space-y-8" style={{ containerType: 'inline-size' }}>
- {isLoading ? (
- <div className="p-2">
- <SkeletonList rowCount={6} mode="card" />
- </div>
- ) : error ? (
- <ErrorState
- title="Couldn't load flows"
- description="Something went wrong while fetching data. Please try again."
- error={error}
- onRetry={() => refetch()}
- />
- ) : !flows?.length ? (
- <div className="flex flex-col items-center justify-center py-12 text-center">
- <div className="rounded-full bg-muted/50 p-4 mb-4">
- <FileX className="w-8 h-8 text-muted-foreground" />
- </div>
- <h3 className="text-xl font-semibold mb-2">No flow yet</h3>
- <p className="text-muted-foreground mb-6 max-w-md">
- Get started by creating your first flow. You can use flows to process and manipulate your data in powerful ways.
- </p>
- <NewFlow>
- <Button>
- <PlusIcon className="w-4 h-4 mr-2" />
- Create your first flow
- </Button>
- </NewFlow>
- </div>
- ) : (
- <Tabs defaultValue="All" className="space-y-6">
- <TabsList className="w-full justify-start h-auto p-1 bg-muted/50 overflow-x-auto hide-scrollbar">
- {allCategories.map((category) => (
- <TabsTrigger
- key={category}
- value={category}
- className="data-[state=active]:bg-background"
- >
- {category}
- </TabsTrigger>
- ))}
- </TabsList>
-
- {allCategories.map((category) => (
- <TabsContent key={category} value={category} className="mt-0">
- <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-6">
- {flows
- ?.filter(flow =>
- category === 'All'
- ? true
- : category === 'Uncategorized'
- ? !flow.category?.length
- : flow.category?.includes(category)
- )
- .map((flow) => (
- <Card
- key={flow.id}
- className="group hover:border-primary/50 hover:shadow-md transition-all cursor-pointer"
- onClick={() => navigate({ to: `/dashboard/flows/${flow.id}` })}
- >
- <CardHeader className="pb-2">
- <div className="flex items-start justify-between">
- <CardTitle className="text-lg font-medium group-hover:text-primary transition-colors">
- {flow.name || "(Unnamed flow)"}
- </CardTitle>
- <FileCode2 className="w-4 h-4 text-muted-foreground" />
- </div>
- <CardDescription className="line-clamp-2 mt-1">
- {flow.description || "No description provided"}
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex items-center justify-between">
- <div className="flex items-center text-sm text-muted-foreground">
- <Clock className="w-4 h-4 mr-1" />
- {formatDistanceToNow(new Date(flow.updated_at || flow.created_at), { addSuffix: true })}
- </div>
- <div className="flex flex-wrap gap-2 justify-end">
- {flow.category?.map((cat) => (
- <Badge key={cat} variant="secondary">
- {cat}
- </Badge>
- ))}
- </div>
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
- </TabsContent>
- ))}
- </Tabs>
- )}
+ <div className="flex items-center gap-2">
+ <NewFlow>
+ <Button size="sm">
+ <PlusIcon className="w-4 h-4 mr-2" />
+ New flow
+ </Button>
+ </NewFlow>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="max-w-7xl mx-auto p-8 space-y-8" style={{ containerType: 'inline-size' }}>
+ {isLoading ? (
+ <div className="p-2">
+ <SkeletonList rowCount={6} mode="card" />
+ </div>
+ ) : error ? (
+ <ErrorState
+ title="Couldn't load flows"
+ description="Something went wrong while fetching data. Please try again."
+ error={error}
+ onRetry={() => refetch()}
+ />
+ ) : !flows?.length ? (
+ <div className="flex flex-col items-center justify-center py-12 text-center">
+ <div className="rounded-full bg-muted/50 p-4 mb-4">
+ <FileX className="w-8 h-8 text-muted-foreground" />
</div>
- </div >
- )
-}
\ No newline at end of file
+ <h3 className="text-xl font-semibold mb-2">No flow yet</h3>
+ <p className="text-muted-foreground mb-6 max-w-md">
+ Get started by creating your first flow. You can use flows to process and manipulate
+ your data in powerful ways.
+ </p>
+ <NewFlow>
+ <Button>
+ <PlusIcon className="w-4 h-4 mr-2" />
+ Create your first flow
+ </Button>
+ </NewFlow>
+ </div>
+ ) : (
+ <Tabs defaultValue="All" className="space-y-6">
+ <TabsList className="w-full justify-start h-auto p-1 bg-muted/50 overflow-x-auto hide-scrollbar">
+ {allCategories.map((category) => (
+ <TabsTrigger
+ key={category}
+ value={category}
+ className="data-[state=active]:bg-background"
+ >
+ {category}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+
+ {allCategories.map((category) => (
+ <TabsContent key={category} value={category} className="mt-0">
+ <div className="grid grid-cols-1 cq-sm:grid-cols-2 cq-md:grid-cols-3 cq-lg:grid-cols-4 cq-xl:grid-cols-5 gap-6">
+ {flows
+ ?.filter((flow) =>
+ category === 'All'
+ ? true
+ : category === 'Uncategorized'
+ ? !flow.category?.length
+ : flow.category?.includes(category)
+ )
+ .map((flow) => (
+ <Card
+ key={flow.id}
+ className="group hover:border-primary/50 hover:shadow-md transition-all cursor-pointer"
+ onClick={() => navigate({ to: `/dashboard/flows/${flow.id}` })}
+ >
+ <CardHeader className="pb-2">
+ <div className="flex items-start justify-between">
+ <CardTitle className="text-lg font-medium group-hover:text-primary transition-colors">
+ {flow.name || '(Unnamed flow)'}
+ </CardTitle>
+ <FileCode2 className="w-4 h-4 text-muted-foreground" />
+ </div>
+ <CardDescription className="line-clamp-2 mt-1">
+ {flow.description || 'No description provided'}
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center text-sm text-muted-foreground">
+ <Clock className="w-4 h-4 mr-1" />
+ {formatDistanceToNow(new Date(flow.updated_at || flow.created_at), {
+ addSuffix: true
+ })}
+ </div>
+ <div className="flex flex-wrap gap-2 justify-end">
+ {flow.category?.map((cat) => (
+ <Badge key={cat} variant="secondary">
+ {cat}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ </TabsContent>
+ ))}
+ </Tabs>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.index.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.index.tsx
index dca8a795..0a8bc5a9 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.index.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.index.tsx
@@ -1,22 +1,20 @@
-import { createFileRoute } from '@tanstack/react-router';
-import { InvestigationSkeleton } from '@/components/dashboard/investigation-skeleton';
-import { InvestigationCards } from '@/components/dashboard/investigation-cards';
+import { createFileRoute } from '@tanstack/react-router'
+import { InvestigationSkeleton } from '@/components/dashboard/investigation-skeleton'
+import { InvestigationCards } from '@/components/dashboard/investigation-cards'
// import { AnalysisCards } from '@/components/dashboard/analysis-cards';
export const Route = createFileRoute('/_auth/dashboard/')({
- component: DashboardPage,
- pendingComponent: InvestigationSkeleton,
-});
-
-
+ component: DashboardPage,
+ pendingComponent: InvestigationSkeleton
+})
function DashboardPage() {
- return (
- <div className="h-full w-full bg-background overflow-y-auto">
- {/* Main Content */}
- <div className="max-w-7xl mx-auto p-8 space-y-12" style={{ containerType: 'inline-size' }}>
- {/* Investigation Cards */}
- {/* <div className="flex flex-1 flex-col">
+ return (
+ <div className="h-full w-full bg-background overflow-y-auto">
+ {/* Main Content */}
+ <div className="max-w-7xl mx-auto p-8 space-y-12" style={{ containerType: 'inline-size' }}>
+ {/* Investigation Cards */}
+ {/* <div className="flex flex-1 flex-col">
<div className="@container/main px-6 flex flex-1 flex-col gap-2">
<div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
<div className="flex items-center justify-between">
@@ -37,11 +35,11 @@ function DashboardPage() {
</div>
</div>
</div> */}
- <InvestigationCards />
+ <InvestigationCards />
- {/* Analysis Cards */}
- {/* <AnalysisCards /> */}
- </div>
- </div>
- );
+ {/* Analysis Cards */}
+ {/* <AnalysisCards /> */}
+ </div>
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.$type.$id.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.$type.$id.tsx
index bfbed119..fa6b177e 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.$type.$id.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.$type.$id.tsx
@@ -10,143 +10,142 @@ import { useGraphStore } from '@/stores/graph-store'
import { useEffect } from 'react'
const services = {
- graph: sketchService.getGraphDataById,
- analysis: analysisService.getById,
+ graph: sketchService.getGraphDataById,
+ analysis: analysisService.getById
}
const GraphPageContent = () => {
- const setActions = useGraphControls((s) => s.setActions)
- const reset = useGraphStore((s) => s.reset)
- const { params: { type, id, investigationId }, sketch } = useLoaderData({
- from: '/_auth/dashboard/investigations/$investigationId/$type/$id',
- })
-
- const { data: data, isLoading, isRefetching, isError, refetch } = useQuery({
- queryKey: ["investigations", investigationId, type, id, "data"],
- queryFn: () => services[type](id),
- enabled: ["graph", "analysis"].includes(type),
- // refetchInterval: 5000,
- refetchOnWindowFocus: false,
- initialData: sketch
- })
-
- // Reset graph store when sketchId changes or is null
- useEffect(() => {
- reset()
- }, [id, reset])
-
- useEffect(() => {
- setActions({ refetchGraph: refetch })
- }, [refetch, setActions, id])
-
- if (type === "graph") {
- return <GraphPanel isLoading={isLoading} isRefetching={isRefetching} graphData={data} />
- }
-
- if (type === "analysis") {
- return <AnalysisPage analysis={data} isLoading={isLoading} isError={isError} refetch={refetch} />
- }
-
+ const setActions = useGraphControls((s) => s.setActions)
+ const reset = useGraphStore((s) => s.reset)
+ const {
+ params: { type, id, investigationId },
+ sketch
+ } = useLoaderData({
+ from: '/_auth/dashboard/investigations/$investigationId/$type/$id'
+ })
+
+ const {
+ data: data,
+ isLoading,
+ isRefetching,
+ isError,
+ refetch
+ } = useQuery({
+ queryKey: ['investigations', investigationId, type, id, 'data'],
+ queryFn: () => services[type](id),
+ enabled: ['graph', 'analysis'].includes(type),
+ // refetchInterval: 5000,
+ refetchOnWindowFocus: false,
+ initialData: sketch
+ })
+
+ // Reset graph store when sketchId changes or is null
+ useEffect(() => {
+ reset()
+ }, [id, reset])
+
+ useEffect(() => {
+ setActions({ refetchGraph: refetch })
+ }, [refetch, setActions, id])
+
+ if (type === 'graph') {
+ return <GraphPanel isLoading={isLoading} isRefetching={isRefetching} graphData={data} />
+ }
+
+ if (type === 'analysis') {
return (
- <div className="h-full w-full flex items-center justify-center">
- <div className="text-center">
- <h2 className="text-lg font-semibold mb-2">Type not supported</h2>
- <p className="text-muted-foreground">The type "{type}" is not supported yet.</p>
- </div>
- </div>
+ <AnalysisPage analysis={data} isLoading={isLoading} isError={isError} refetch={refetch} />
)
+ }
+
+ return (
+ <div className="h-full w-full flex items-center justify-center">
+ <div className="text-center">
+ <h2 className="text-lg font-semibold mb-2">Type not supported</h2>
+ <p className="text-muted-foreground">The type "{type}" is not supported yet.</p>
+ </div>
+ </div>
+ )
}
export const Route = createFileRoute('/_auth/dashboard/investigations/$investigationId/$type/$id')({
- loader: async ({ params: { id, type, investigationId } }) => {
- const sketch = await services[type](id)
- return { params: { id, type, investigationId }, sketch }
- },
-
- pendingComponent: () => (
- <div className="h-full w-full flex items-center justify-center">
- <div className="text-center flex items-center gap-2">
- <Loader />
- </div>
+ loader: async ({ params: { id, type, investigationId } }) => {
+ const sketch = await services[type](id)
+ return { params: { id, type, investigationId }, sketch }
+ },
+
+ pendingComponent: () => (
+ <div className="h-full w-full flex items-center justify-center">
+ <div className="text-center flex items-center gap-2">
+ <Loader />
+ </div>
+ </div>
+ ),
+
+ errorComponent: () => (
+ <div className="h-full w-full flex items-center justify-center bg-background">
+ <div className="text-center max-w-md mx-auto p-8">
+ <div className="flex justify-center mb-6">
+ <div className="w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center">
+ <svg
+ className="w-8 h-8 text-destructive"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
+ />
+ </svg>
+ </div>
</div>
- ),
-
- errorComponent: () => (
- <div className="h-full w-full flex items-center justify-center bg-background">
- <div className="text-center max-w-md mx-auto p-8">
- <div className="flex justify-center mb-6">
- <div className="w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center">
- <svg
- className="w-8 h-8 text-destructive"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
- />
- </svg>
- </div>
- </div>
-
- <h2 className="text-xl font-semibold text-foreground mb-2">
- Oops! Something went wrong
- </h2>
-
- <p className="text-muted-foreground mb-6 text-sm leading-relaxed">
- We couldn't load this investigation page. This might be due to a network issue,
- invalid investigation ID, or the resource may not exist.
- </p>
-
- <div className="space-y-3">
- <button
- onClick={() => window.location.reload()}
- className="w-full bg-primary text-primary-foreground hover:bg-primary/90
+
+ <h2 className="text-xl font-semibold text-foreground mb-2">Oops! Something went wrong</h2>
+
+ <p className="text-muted-foreground mb-6 text-sm leading-relaxed">
+ We couldn't load this investigation page. This might be due to a network issue, invalid
+ investigation ID, or the resource may not exist.
+ </p>
+
+ <div className="space-y-3">
+ <button
+ onClick={() => window.location.reload()}
+ className="w-full bg-primary text-primary-foreground hover:bg-primary/90
px-4 py-2 rounded-md font-medium transition-colors
flex items-center justify-center gap-2"
- >
- <svg
- className="w-4 h-4"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
- />
- </svg>
- Reload Page
- </button>
- <Link
- to="/dashboard"
- >
- <button className="w-full bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground px-4 py-2 rounded-md font-medium transition-colors"
- >
- Go home
- </button>
- </Link>
- </div>
-
- <div className="mt-6 pt-4 border-t">
- <p className="text-xs text-muted-foreground">
- If the problem persists, try:
- </p>
- <ul className="text-xs text-muted-foreground mt-2 space-y-1">
- <li>• Checking your internet connection</li>
- <li>• Verifying the investigation ID is correct</li>
- <li>• Contacting support if the issue continues</li>
- </ul>
- </div>
- </div>
+ >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
+ />
+ </svg>
+ Reload Page
+ </button>
+ <Link to="/dashboard">
+ <button className="w-full bg-muted hover:bg-muted/80 text-muted-foreground hover:text-foreground px-4 py-2 rounded-md font-medium transition-colors">
+ Go home
+ </button>
+ </Link>
+ </div>
+
+ <div className="mt-6 pt-4 border-t">
+ <p className="text-xs text-muted-foreground">If the problem persists, try:</p>
+ <ul className="text-xs text-muted-foreground mt-2 space-y-1">
+ <li>• Checking your internet connection</li>
+ <li>• Verifying the investigation ID is correct</li>
+ <li>• Contacting support if the issue continues</li>
+ </ul>
</div>
- ),
+ </div>
+ </div>
+ ),
- component: GraphPageContent
+ component: GraphPageContent
})
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.index.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.index.tsx
index 262975e6..a4918c0b 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.index.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.$investigationId.index.tsx
@@ -6,345 +6,376 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
-import { Plus, Calendar, User, FileText, BarChart3, Clock, ChevronDown, Waypoints } from 'lucide-react'
+import {
+ Plus,
+ Calendar,
+ User,
+ FileText,
+ BarChart3,
+ Clock,
+ ChevronDown,
+ Waypoints
+} from 'lucide-react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { formatDistanceToNow } from 'date-fns'
import NewSketch from '@/components/graphs/new-sketch'
function InvestigationSkeleton() {
- return (
- <div className="h-full w-full bg-background overflow-y-auto">
- <div className="max-w-7xl mx-auto p-8 space-y-8">
- {/* Header Skeleton */}
- <div className="space-y-4">
- <div className="w-64 h-8 bg-muted rounded animate-pulse" />
- <div className="w-96 h-4 bg-muted rounded animate-pulse" />
- <div className="flex items-center gap-4">
- <div className="w-20 h-6 bg-muted rounded animate-pulse" />
- <div className="w-24 h-6 bg-muted rounded animate-pulse" />
- <div className="w-32 h-6 bg-muted rounded animate-pulse" />
- </div>
- </div>
+ return (
+ <div className="h-full w-full bg-background overflow-y-auto">
+ <div className="max-w-7xl mx-auto p-8 space-y-8">
+ {/* Header Skeleton */}
+ <div className="space-y-4">
+ <div className="w-64 h-8 bg-muted rounded animate-pulse" />
+ <div className="w-96 h-4 bg-muted rounded animate-pulse" />
+ <div className="flex items-center gap-4">
+ <div className="w-20 h-6 bg-muted rounded animate-pulse" />
+ <div className="w-24 h-6 bg-muted rounded animate-pulse" />
+ <div className="w-32 h-6 bg-muted rounded animate-pulse" />
+ </div>
+ </div>
- {/* Stats Cards Skeleton */}
- <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
- {Array.from({ length: 3 }).map((_, i) => (
- <div key={i} className="h-24 bg-muted rounded-lg animate-pulse" />
- ))}
- </div>
+ {/* Stats Cards Skeleton */}
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <div key={i} className="h-24 bg-muted rounded-lg animate-pulse" />
+ ))}
+ </div>
- {/* Content Skeleton */}
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
- {Array.from({ length: 2 }).map((_, i) => (
- <div key={i} className="space-y-4">
- <div className="w-48 h-6 bg-muted rounded animate-pulse" />
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
- {Array.from({ length: 4 }).map((_, j) => (
- <div key={j} className="h-32 bg-muted rounded-lg animate-pulse" />
- ))}
- </div>
- </div>
- ))}
- </div>
+ {/* Content Skeleton */}
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
+ {Array.from({ length: 2 }).map((_, i) => (
+ <div key={i} className="space-y-4">
+ <div className="w-48 h-6 bg-muted rounded animate-pulse" />
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ {Array.from({ length: 4 }).map((_, j) => (
+ <div key={j} className="h-32 bg-muted rounded-lg animate-pulse" />
+ ))}
+ </div>
</div>
+ ))}
</div>
- )
+ </div>
+ </div>
+ )
}
export const Route = createFileRoute('/_auth/dashboard/investigations/$investigationId/')({
- loader: async ({ params: { investigationId } }) => {
- return {
- investigation: await investigationService.getById(investigationId),
- }
- },
- component: InvestigationPage,
- pendingComponent: InvestigationSkeleton,
+ loader: async ({ params: { investigationId } }) => {
+ return {
+ investigation: await investigationService.getById(investigationId)
+ }
+ },
+ component: InvestigationPage,
+ pendingComponent: InvestigationSkeleton
})
function InvestigationPage() {
- const { investigation } = Route.useLoaderData()
- const navigate = useNavigate()
- const queryClient = useQueryClient()
+ const { investigation } = Route.useLoaderData()
+ const navigate = useNavigate()
+ const queryClient = useQueryClient()
- const createAnalysisMutation = useMutation({
- mutationFn: async () => {
- const newAnalysis = {
- title: "Untitled Analysis",
- investigation_id: investigation.id,
- content: {},
- }
- return analysisService.create(JSON.stringify(newAnalysis))
- },
- onSuccess: async (data) => {
- queryClient.invalidateQueries({ queryKey: ["analyses", "investigation", investigation.id] })
- toast.success("New analysis created")
- // Navigate to the new analysis page
- navigate({
- to: "/dashboard/investigations/$investigationId/$type/$id",
- params: {
- investigationId: investigation.id,
- type: "analysis",
- id: data.id
- }
- })
- },
- onError: (error) => {
- toast.error("Failed to create analysis: " + (error instanceof Error ? error.message : "Unknown error"))
+ const createAnalysisMutation = useMutation({
+ mutationFn: async () => {
+ const newAnalysis = {
+ title: 'Untitled Analysis',
+ investigation_id: investigation.id,
+ content: {}
+ }
+ return analysisService.create(JSON.stringify(newAnalysis))
+ },
+ onSuccess: async (data) => {
+ queryClient.invalidateQueries({ queryKey: ['analyses', 'investigation', investigation.id] })
+ toast.success('New analysis created')
+ // Navigate to the new analysis page
+ navigate({
+ to: '/dashboard/investigations/$investigationId/$type/$id',
+ params: {
+ investigationId: investigation.id,
+ type: 'analysis',
+ id: data.id
}
- })
+ })
+ },
+ onError: (error) => {
+ toast.error(
+ 'Failed to create analysis: ' + (error instanceof Error ? error.message : 'Unknown error')
+ )
+ }
+ })
- const sketchCount = investigation.sketches?.length || 0
- const analysisCount = investigation.analyses?.length || 0
- const lastUpdated = formatDistanceToNow(new Date(investigation.last_updated_at), { addSuffix: true })
+ const sketchCount = investigation.sketches?.length || 0
+ const analysisCount = investigation.analyses?.length || 0
+ const lastUpdated = formatDistanceToNow(new Date(investigation.last_updated_at), {
+ addSuffix: true
+ })
- return (
- <div className="h-full w-full bg-background overflow-y-auto">
- <div className="max-w-7xl mx-auto p-8 space-y-8">
- {/* Header Section */}
- <div className="space-y-4">
- <div className="flex items-start justify-between">
- <div className="space-y-2">
- <h1 className="text-3xl font-bold tracking-tight">{investigation.name}</h1>
- <p className="text-lg text-muted-foreground max-w-2xl">
- {investigation.description || "No description provided"}
- </p>
- </div>
- <div className="flex items-center gap-3">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <div>
- <Button className="gap-2" disabled={createAnalysisMutation.isPending}>
- New
- <ChevronDown className="h-4 w-4" />
- </Button>
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <NewSketch>
- <DropdownMenuItem onSelect={(e) => e.preventDefault()}>
- <BarChart3 className="h-4 w-4 mr-2" />
- New Sketch
- </DropdownMenuItem>
- </NewSketch>
- <DropdownMenuItem
- onClick={() => createAnalysisMutation.mutate()}
- disabled={createAnalysisMutation.isPending}
- >
- <FileText className="h-4 w-4 mr-2" />
- New Analysis
- {createAnalysisMutation.isPending && (
- <span className="ml-2 text-xs text-muted-foreground">Creating...</span>
- )}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
+ return (
+ <div className="h-full w-full bg-background overflow-y-auto">
+ <div className="max-w-7xl mx-auto p-8 space-y-8">
+ {/* Header Section */}
+ <div className="space-y-4">
+ <div className="flex items-start justify-between">
+ <div className="space-y-2">
+ <h1 className="text-3xl font-bold tracking-tight">{investigation.name}</h1>
+ <p className="text-lg text-muted-foreground max-w-2xl">
+ {investigation.description || 'No description provided'}
+ </p>
+ </div>
+ <div className="flex items-center gap-3">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <div>
+ <Button className="gap-2" disabled={createAnalysisMutation.isPending}>
+ New
+ <ChevronDown className="h-4 w-4" />
+ </Button>
+ </div>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <NewSketch>
+ <DropdownMenuItem onSelect={(e) => e.preventDefault()}>
+ <BarChart3 className="h-4 w-4 mr-2" />
+ New Sketch
+ </DropdownMenuItem>
+ </NewSketch>
+ <DropdownMenuItem
+ onClick={() => createAnalysisMutation.mutate()}
+ disabled={createAnalysisMutation.isPending}
+ >
+ <FileText className="h-4 w-4 mr-2" />
+ New Analysis
+ {createAnalysisMutation.isPending && (
+ <span className="ml-2 text-xs text-muted-foreground">Creating...</span>
+ )}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
- <div className="flex items-center gap-6 text-sm text-muted-foreground">
- <div className="flex items-center gap-2">
- <Calendar className="h-4 w-4" />
- <span>Created {formatDistanceToNow(new Date(investigation.created_at), { addSuffix: true })}</span>
- </div>
- <div className="flex items-center gap-2">
- <Clock className="h-4 w-4" />
- <span>Updated {lastUpdated}</span>
- </div>
- <div className="flex items-center gap-2">
- <User className="h-4 w-4" />
- <span>{investigation.owner ? `${investigation.owner.first_name || ''} ${investigation.owner.last_name || ''}`.trim() || 'Unknown' : "Unknown"}</span>
- </div>
- <Badge variant={investigation.status === 'active' ? 'default' : 'secondary'}>
- {investigation.status}
- </Badge>
- </div>
- </div>
+ <div className="flex items-center gap-6 text-sm text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <Calendar className="h-4 w-4" />
+ <span>
+ Created{' '}
+ {formatDistanceToNow(new Date(investigation.created_at), { addSuffix: true })}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <Clock className="h-4 w-4" />
+ <span>Updated {lastUpdated}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <User className="h-4 w-4" />
+ <span>
+ {investigation.owner
+ ? `${investigation.owner.first_name || ''} ${investigation.owner.last_name || ''}`.trim() ||
+ 'Unknown'
+ : 'Unknown'}
+ </span>
+ </div>
+ <Badge variant={investigation.status === 'active' ? 'default' : 'secondary'}>
+ {investigation.status}
+ </Badge>
+ </div>
+ </div>
- {/* Stats Cards */}
- <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
- <Card>
- <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
- <CardTitle className="text-sm font-medium">Total Sketches</CardTitle>
- <BarChart3 className="h-4 w-4 text-muted-foreground" />
- </CardHeader>
- <CardContent>
- <div className="text-2xl font-bold">{sketchCount}</div>
- <p className="text-xs text-muted-foreground">
- Visual data representations
- </p>
- </CardContent>
- </Card>
+ {/* Stats Cards */}
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
+ <CardTitle className="text-sm font-medium">Total Sketches</CardTitle>
+ <BarChart3 className="h-4 w-4 text-muted-foreground" />
+ </CardHeader>
+ <CardContent>
+ <div className="text-2xl font-bold">{sketchCount}</div>
+ <p className="text-xs text-muted-foreground">Visual data representations</p>
+ </CardContent>
+ </Card>
- <Card>
- <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
- <CardTitle className="text-sm font-medium">Total Analyses</CardTitle>
- <FileText className="h-4 w-4 text-muted-foreground" />
- </CardHeader>
- <CardContent>
- <div className="text-2xl font-bold">{analysisCount}</div>
- <p className="text-xs text-muted-foreground">
- Documented findings
- </p>
- </CardContent>
- </Card>
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
+ <CardTitle className="text-sm font-medium">Total Analyses</CardTitle>
+ <FileText className="h-4 w-4 text-muted-foreground" />
+ </CardHeader>
+ <CardContent>
+ <div className="text-2xl font-bold">{analysisCount}</div>
+ <p className="text-xs text-muted-foreground">Documented findings</p>
+ </CardContent>
+ </Card>
- <Card>
- <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
- <CardTitle className="text-sm font-medium">Last Activity</CardTitle>
- <Clock className="h-4 w-4 text-muted-foreground" />
- </CardHeader>
- <CardContent>
- <div className="text-2xl font-bold">{lastUpdated}</div>
- <p className="text-xs text-muted-foreground">
- Since last update
- </p>
- </CardContent>
- </Card>
- </div>
+ <Card>
+ <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
+ <CardTitle className="text-sm font-medium">Last Activity</CardTitle>
+ <Clock className="h-4 w-4 text-muted-foreground" />
+ </CardHeader>
+ <CardContent>
+ <div className="text-2xl font-bold">{lastUpdated}</div>
+ <p className="text-xs text-muted-foreground">Since last update</p>
+ </CardContent>
+ </Card>
+ </div>
- <Separator />
+ <Separator />
- {/* Content Sections */}
- <div className="space-y-12">
- {/* Sketches Section */}
- <div className="space-y-6">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <BarChart3 className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Sketches</h2>
- <Badge variant="outline" className="ml-2">{sketchCount}</Badge>
- </div>
+ {/* Content Sections */}
+ <div className="space-y-12">
+ {/* Sketches Section */}
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <BarChart3 className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Sketches</h2>
+ <Badge variant="outline" className="ml-2">
+ {sketchCount}
+ </Badge>
+ </div>
+ </div>
+
+ {sketchCount === 0 ? (
+ <Card className="border-dashed">
+ <CardContent className="flex flex-col items-center justify-center py-8">
+ <BarChart3 className="h-12 w-12 text-muted-foreground mb-3" />
+ <h3 className="text-lg font-semibold mb-2">No sketches yet</h3>
+ <p className="text-muted-foreground mb-4 text-center max-w-md">
+ Create your first sketch to start visualizing your investigation data and
+ building relationships between entities.
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
+ {investigation.sketches?.slice(0, 8).map((sketch: any) => (
+ <Card
+ onClick={() =>
+ navigate({
+ to: '/dashboard/investigations/$investigationId/$type/$id',
+ params: {
+ investigationId: investigation.id,
+ type: 'graph',
+ id: sketch.id
+ }
+ })
+ }
+ className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border hover:border-primary/20"
+ >
+ <CardContent className="h-full flex flex-col">
+ {/* Header with title and count */}
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <div className="w-8 h-8 bg-primary/10 rounded-lg flex items-center justify-center flex-shrink-0">
+ <Waypoints className="w-4 h-4 text-primary" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <h3 className="font-semibold text-sm truncate group-hover:text-primary transition-colors">
+ {sketch.title}
+ </h3>
+ </div>
+ </div>
+ </div>
+ {/* Footer with timestamp */}
+ <div className="mt-auto">
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Clock className="w-3 h-3" />
+ <span>
+ Updated{' '}
+ {formatDistanceToNow(new Date(sketch.last_updated_at), {
+ addSuffix: true
+ })}
+ </span>
</div>
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+ </div>
- {sketchCount === 0 ? (
- <Card className="border-dashed">
- <CardContent className="flex flex-col items-center justify-center py-8">
- <BarChart3 className="h-12 w-12 text-muted-foreground mb-3" />
- <h3 className="text-lg font-semibold mb-2">No sketches yet</h3>
- <p className="text-muted-foreground mb-4 text-center max-w-md">
- Create your first sketch to start visualizing your investigation data and building relationships between entities.
- </p>
+ {/* Analyses Section */}
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <FileText className="h-6 w-6 text-muted-foreground" />
+ <h2 className="text-xl font-semibold">Analyses</h2>
+ <Badge variant="outline" className="ml-2">
+ {analysisCount}
+ </Badge>
+ </div>
+ </div>
- </CardContent>
- </Card>
- ) : (
- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
- {investigation.sketches?.slice(0, 8).map((sketch: any) => (
- <Card onClick={() => navigate({
- to: "/dashboard/investigations/$investigationId/$type/$id",
- params: {
- investigationId: investigation.id,
- type: "graph",
- id: sketch.id
- }
- })} className="hover:shadow-lg py-4 transition-all duration-200 cursor-pointer group border hover:border-primary/20">
- <CardContent className="h-full flex flex-col">
- {/* Header with title and count */}
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3 flex-1 min-w-0">
- <div className="w-8 h-8 bg-primary/10 rounded-lg flex items-center justify-center flex-shrink-0">
- <Waypoints className="w-4 h-4 text-primary" />
- </div>
- <div className="flex-1 min-w-0">
- <h3 className="font-semibold text-sm truncate group-hover:text-primary transition-colors">
- {sketch.title}
- </h3>
-
- </div>
- </div>
- </div>
- {/* Footer with timestamp */}
- <div className="mt-auto">
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Clock className="w-3 h-3" />
- <span>
- Updated {formatDistanceToNow(new Date(sketch.last_updated_at), { addSuffix: true })}
- </span>
- </div>
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
- )}
- </div>
+ {analysisCount === 0 ? (
+ <Card className="border-dashed">
+ <CardContent className="flex flex-col items-center justify-center py-8">
+ <FileText className="h-12 w-12 text-muted-foreground mb-3" />
+ <h3 className="text-lg font-semibold mb-2">No analyses yet</h3>
+ <p className="text-muted-foreground mb-4 text-center max-w-md">
+ Create your first analysis to start documenting your findings, observations, and
+ investigative notes.
+ </p>
+ <Button
+ onClick={() => createAnalysisMutation.mutate()}
+ disabled={createAnalysisMutation.isPending}
+ className="gap-2"
+ >
+ <Plus className="h-4 w-4" />
+ Create analysis
+ </Button>
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
+ {investigation.analyses?.slice(0, 8).map((analysis: any) => (
+ <Card
+ key={analysis.id}
+ className="group py-2 relative overflow-hidden cursor-pointer hover:shadow-xl border border-border hover:border-secondary"
+ onClick={() =>
+ navigate({
+ to: '/dashboard/investigations/$investigationId/$type/$id',
+ params: {
+ investigationId: investigation.id,
+ type: 'analysis',
+ id: analysis.id
+ }
+ })
+ }
+ >
+ <CardContent className="p-6 relative">
+ <div className="space-y-3">
+ <h4 className="font-semibold text-gray-900 dark:text-gray-100 line-clamp-1 group-hover:text-emerald-700 dark:group-hover:text-emerald-300 transition-colors">
+ {analysis.title}
+ </h4>
+ <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2 leading-relaxed">
+ {analysis.description || 'No description provided'}
+ </p>
+ </div>
- {/* Analyses Section */}
- <div className="space-y-6">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <FileText className="h-6 w-6 text-muted-foreground" />
- <h2 className="text-xl font-semibold">Analyses</h2>
- <Badge variant="outline" className="ml-2">{analysisCount}</Badge>
- </div>
+ <div className="mt-4 pt-4 border-t border-emerald-200/50 dark:border-emerald-800/30">
+ <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
+ <span className="flex items-center gap-1">
+ <Clock className="h-3 w-3" />
+ {formatDistanceToNow(new Date(analysis.last_updated_at), {
+ addSuffix: true
+ })}
+ </span>
+ <div className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
</div>
-
- {analysisCount === 0 ? (
- <Card className="border-dashed">
- <CardContent className="flex flex-col items-center justify-center py-8">
- <FileText className="h-12 w-12 text-muted-foreground mb-3" />
- <h3 className="text-lg font-semibold mb-2">No analyses yet</h3>
- <p className="text-muted-foreground mb-4 text-center max-w-md">
- Create your first analysis to start documenting your findings, observations, and investigative notes.
- </p>
- <Button
- onClick={() => createAnalysisMutation.mutate()}
- disabled={createAnalysisMutation.isPending}
- className="gap-2"
- >
- <Plus className="h-4 w-4" />
- Create analysis
- </Button>
- </CardContent>
- </Card>
- ) : (
- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
- {investigation.analyses?.slice(0, 8).map((analysis: any) => (
- <Card
- key={analysis.id}
- className="group py-2 relative overflow-hidden cursor-pointer hover:shadow-xl border border-border hover:border-secondary"
- onClick={() => navigate({
- to: "/dashboard/investigations/$investigationId/$type/$id",
- params: {
- investigationId: investigation.id,
- type: "analysis",
- id: analysis.id
- }
- })}
- >
- <CardContent className="p-6 relative">
- <div className="space-y-3">
- <h4 className="font-semibold text-gray-900 dark:text-gray-100 line-clamp-1 group-hover:text-emerald-700 dark:group-hover:text-emerald-300 transition-colors">
- {analysis.title}
- </h4>
- <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2 leading-relaxed">
- {analysis.description || "No description provided"}
- </p>
- </div>
-
- <div className="mt-4 pt-4 border-t border-emerald-200/50 dark:border-emerald-800/30">
- <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
- <span className="flex items-center gap-1">
- <Clock className="h-3 w-3" />
- {formatDistanceToNow(new Date(analysis.last_updated_at), { addSuffix: true })}
- </span>
- <div className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
- </div>
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
- )}
- </div>
- </div>
- </div>
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )}
+ </div>
</div>
- );
+ </div>
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.index.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.index.tsx
index 8054dd87..d072428f 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.index.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.investigations.index.tsx
@@ -4,21 +4,21 @@ import { InvestigationCards } from '@/components/dashboard/investigation-cards'
import { AnalysisCards } from '@/components/dashboard/analysis-cards'
export const Route = createFileRoute('/_auth/dashboard/investigations/')({
- component: InvestigationPage,
- pendingComponent: InvestigationSkeleton,
+ component: InvestigationPage,
+ pendingComponent: InvestigationSkeleton
})
function InvestigationPage() {
- return (
- <div className="h-full w-full bg-background overflow-y-auto">
- {/* Main Content */}
- <div className="max-w-7xl mx-auto p-8 space-y-12">
- {/* Investigation Cards */}
- <InvestigationCards />
-
- {/* Analysis Cards */}
- <AnalysisCards />
- </div>
- </div>
- );
+ return (
+ <div className="h-full w-full bg-background overflow-y-auto">
+ {/* Main Content */}
+ <div className="max-w-7xl mx-auto p-8 space-y-12">
+ {/* Investigation Cards */}
+ <InvestigationCards />
+
+ {/* Analysis Cards */}
+ <AnalysisCards />
+ </div>
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.tools.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.tools.tsx
index 4cc02344..e50042c8 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.tools.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.tools.tsx
@@ -1,210 +1,216 @@
import { createFileRoute } from '@tanstack/react-router'
-import { ToolCategory } from "@/types"
+import { ToolCategory } from '@/types'
import { ToolCard } from '@/components/tool-card'
import { useState } from 'react'
import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select"
-import { Input } from "@/components/ui/input"
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from '@/components/ui/select'
+import { Input } from '@/components/ui/input'
export const Route = createFileRoute('/_auth/dashboard/tools')({
- component: ToolsPage,
+ component: ToolsPage
})
const toolCategories: ToolCategory = {
- "Social Media & Username Search": {
- "Maigret": {
- name: "Maigret",
- path: "/tools/maigret",
- description: "Search for profiles across more than 500 sites based on a username.",
- active: true,
- link: "https://github.com/soxoj/maigret",
- avatar: "https://raw.githubusercontent.com/soxoj/maigret/main/static/maigret.png"
- },
- "Sherlock": {
- name: "Sherlock",
- path: "/tools/sherlock",
- description: "Search for user accounts across social networks.",
- active: true,
- link: "https://github.com/sherlock-project/sherlock",
- avatar: "https://avatars.githubusercontent.com/u/48293496?s=200&v=4"
- }
+ 'Social Media & Username Search': {
+ Maigret: {
+ name: 'Maigret',
+ path: '/tools/maigret',
+ description: 'Search for profiles across more than 500 sites based on a username.',
+ active: true,
+ link: 'https://github.com/soxoj/maigret',
+ avatar: 'https://raw.githubusercontent.com/soxoj/maigret/main/static/maigret.png'
},
- "Email Analysis": {
- "Holehe": {
- name: "Holehe",
- path: "/tools/holehe",
- description: "Check if an email address is associated with accounts on various websites.",
- active: true,
- link: "https://github.com/megadose/holehe",
- avatar: "https://media.licdn.com/dms/image/v2/D560BAQEJNEwF0E6QyA/company-logo_200_200/company-logo_200_200/0/1731244005282/osint_industries_logo?e=1750896000&v=beta&t=2-4rC5YaEp5Rmt48ijR46XhB-Y4iPaQ3qBDQbVNAVFU"
- },
- "EmailRep": {
- name: "EmailRep",
- path: "/tools/emailrep",
- description: "Analyze the reputation of an email address (scam, social, etc.).",
- active: false,
- link: "https://github.com/sublime-security/emailrep.io",
- avatar: "https://user-images.githubusercontent.com/11003450/115128085-5805da00-9fa9-11eb-8c7a-dc8b708053ee.png"
- },
- "theHarvester": {
- name: "theHarvester",
- path: "/tools/theharvester",
- description: "Collect emails, domain names, IPs from public sources.",
- active: false,
- link: "https://github.com/laramies/theHarvester"
- },
- "Epios": {
- name: "Epios",
- path: "/tools/epios",
- description: "Search engine to find emails, phone numbers, and more.",
- active: false,
- link: "https://epieos.com/",
- avatar: "https://lh3.googleusercontent.com/p/AF1QipPXBjt3kUBUoN9wOOwWjdbCOaNfDOpUFPcep0IS=w243-h203-n-k-no-nu",
- apiKeyRequired: "paid"
- }
+ Sherlock: {
+ name: 'Sherlock',
+ path: '/tools/sherlock',
+ description: 'Search for user accounts across social networks.',
+ active: true,
+ link: 'https://github.com/sherlock-project/sherlock',
+ avatar: 'https://avatars.githubusercontent.com/u/48293496?s=200&v=4'
+ }
+ },
+ 'Email Analysis': {
+ Holehe: {
+ name: 'Holehe',
+ path: '/tools/holehe',
+ description: 'Check if an email address is associated with accounts on various websites.',
+ active: true,
+ link: 'https://github.com/megadose/holehe',
+ avatar:
+ 'https://media.licdn.com/dms/image/v2/D560BAQEJNEwF0E6QyA/company-logo_200_200/company-logo_200_200/0/1731244005282/osint_industries_logo?e=1750896000&v=beta&t=2-4rC5YaEp5Rmt48ijR46XhB-Y4iPaQ3qBDQbVNAVFU'
+ },
+ EmailRep: {
+ name: 'EmailRep',
+ path: '/tools/emailrep',
+ description: 'Analyze the reputation of an email address (scam, social, etc.).',
+ active: false,
+ link: 'https://github.com/sublime-security/emailrep.io',
+ avatar:
+ 'https://user-images.githubusercontent.com/11003450/115128085-5805da00-9fa9-11eb-8c7a-dc8b708053ee.png'
},
- "Domain & Network Analysis": {
- "Subfinder": {
- name: "Subfinder",
- path: "/tools/subfinder",
- description: "Fast passive subdomain enumeration tool.",
- active: true,
- link: "https://github.com/projectdiscovery/subfinder",
- avatar: "https://avatars.githubusercontent.com/u/50994705?s=280&v=4"
- },
- "DnsDumpster": {
- name: "DnsDumpster",
- path: "/tools/dnsdumpster",
- description: "DNS reconnaissance and network mapping from a domain.",
- active: false,
- link: "https://github.com/PaulSec/API-dnsdumpster.com"
- },
- "ASNMap": {
- name: "ASNMap",
- path: "/tools/asnmap",
- description: "ASN mapping and network reconnaissance tool.",
- active: true,
- link: "https://github.com/projectdiscovery/asnmap",
- avatar: "https://avatars.githubusercontent.com/u/50994705?s=280&v=4"
- }
+ theHarvester: {
+ name: 'theHarvester',
+ path: '/tools/theharvester',
+ description: 'Collect emails, domain names, IPs from public sources.',
+ active: false,
+ link: 'https://github.com/laramies/theHarvester'
},
- "Blockchain Analysis": {
- "Etherscan": {
- name: "Etherscan",
- path: "/tools/etherscan",
- description: "Blockchain explorer and analytics platform for Ethereum.",
- active: true,
- link: "https://etherscan.io/apis",
- avatar: "https://cdn.worldvectorlogo.com/logos/etherscan-1.svg",
- apiKeyRequired: "free"
- }
+ Epios: {
+ name: 'Epios',
+ path: '/tools/epios',
+ description: 'Search engine to find emails, phone numbers, and more.',
+ active: false,
+ link: 'https://epieos.com/',
+ avatar:
+ 'https://lh3.googleusercontent.com/p/AF1QipPXBjt3kUBUoN9wOOwWjdbCOaNfDOpUFPcep0IS=w243-h203-n-k-no-nu',
+ apiKeyRequired: 'paid'
+ }
+ },
+ 'Domain & Network Analysis': {
+ Subfinder: {
+ name: 'Subfinder',
+ path: '/tools/subfinder',
+ description: 'Fast passive subdomain enumeration tool.',
+ active: true,
+ link: 'https://github.com/projectdiscovery/subfinder',
+ avatar: 'https://avatars.githubusercontent.com/u/50994705?s=280&v=4'
},
- "Metadata Analysis": {
- "GHunt": {
- name: "GHunt",
- path: "/tools/ghunt",
- description: "Analyze Google metadata (Gmail, Docs, Photos, etc.).",
- active: true,
- link: "https://github.com/mxrch/GHunt",
- avatar: "https://media.licdn.com/dms/image/v2/D560BAQEJNEwF0E6QyA/company-logo_200_200/company-logo_200_200/0/1731244005282/osint_industries_logo?e=1750896000&v=beta&t=2-4rC5YaEp5Rmt48ijR46XhB-Y4iPaQ3qBDQbVNAVFU"
- },
- "ExifTool": {
- name: "ExifTool",
- path: "/tools/exiftool",
- description: "Extract metadata from files (images, documents, etc.).",
- active: false,
- link: "https://github.com/exiftool/exiftool",
- avatar: "https://avatars.githubusercontent.com/u/8656631?s=200&v=4"
- }
+ DnsDumpster: {
+ name: 'DnsDumpster',
+ path: '/tools/dnsdumpster',
+ description: 'DNS reconnaissance and network mapping from a domain.',
+ active: false,
+ link: 'https://github.com/PaulSec/API-dnsdumpster.com'
},
- "Business Intelligence": {
- "API Sirene": {
- name: "API Sirene open data",
- path: "/tools/api-sirene-open-data",
- description: "The Sirene API allows you to query the Sirene directory of businesses and establishments, managed by Insee.",
- active: true,
- link: "https://www.data.gouv.fr/fr/dataservices/api-sirene-open-data/",
- avatar: "https://www.portlarochelle.com/wp-content/uploads/2020/11/logo-Marianne.jpg"
- }
+ ASNMap: {
+ name: 'ASNMap',
+ path: '/tools/asnmap',
+ description: 'ASN mapping and network reconnaissance tool.',
+ active: true,
+ link: 'https://github.com/projectdiscovery/asnmap',
+ avatar: 'https://avatars.githubusercontent.com/u/50994705?s=280&v=4'
+ }
+ },
+ 'Blockchain Analysis': {
+ Etherscan: {
+ name: 'Etherscan',
+ path: '/tools/etherscan',
+ description: 'Blockchain explorer and analytics platform for Ethereum.',
+ active: true,
+ link: 'https://etherscan.io/apis',
+ avatar: 'https://cdn.worldvectorlogo.com/logos/etherscan-1.svg',
+ apiKeyRequired: 'free'
+ }
+ },
+ 'Metadata Analysis': {
+ GHunt: {
+ name: 'GHunt',
+ path: '/tools/ghunt',
+ description: 'Analyze Google metadata (Gmail, Docs, Photos, etc.).',
+ active: true,
+ link: 'https://github.com/mxrch/GHunt',
+ avatar:
+ 'https://media.licdn.com/dms/image/v2/D560BAQEJNEwF0E6QyA/company-logo_200_200/company-logo_200_200/0/1731244005282/osint_industries_logo?e=1750896000&v=beta&t=2-4rC5YaEp5Rmt48ijR46XhB-Y4iPaQ3qBDQbVNAVFU'
},
- "Phone Analysis": {
- "PhoneInfoga": {
- name: "PhoneInfoga",
- path: "/tools/phoneinfoga",
- description: "Gather information from phone numbers.",
- active: false,
- link: "https://github.com/sundowndev/phoneinfoga"
- }
+ ExifTool: {
+ name: 'ExifTool',
+ path: '/tools/exiftool',
+ description: 'Extract metadata from files (images, documents, etc.).',
+ active: false,
+ link: 'https://github.com/exiftool/exiftool',
+ avatar: 'https://avatars.githubusercontent.com/u/8656631?s=200&v=4'
}
+ },
+ 'Business Intelligence': {
+ 'API Sirene': {
+ name: 'API Sirene open data',
+ path: '/tools/api-sirene-open-data',
+ description:
+ 'The Sirene API allows you to query the Sirene directory of businesses and establishments, managed by Insee.',
+ active: true,
+ link: 'https://www.data.gouv.fr/fr/dataservices/api-sirene-open-data/',
+ avatar: 'https://www.portlarochelle.com/wp-content/uploads/2020/11/logo-Marianne.jpg'
+ }
+ },
+ 'Phone Analysis': {
+ PhoneInfoga: {
+ name: 'PhoneInfoga',
+ path: '/tools/phoneinfoga',
+ description: 'Gather information from phone numbers.',
+ active: false,
+ link: 'https://github.com/sundowndev/phoneinfoga'
+ }
+ }
}
function ToolsPage() {
- const [searchQuery, setSearchQuery] = useState("")
- const [selectedCategory, setSelectedCategory] = useState<string>("all")
+ const [searchQuery, setSearchQuery] = useState('')
+ const [selectedCategory, setSelectedCategory] = useState<string>('all')
- // Flatten all tools into a single array with their categories
- const allTools = Object.entries(toolCategories).flatMap(([category, tools]) =>
- Object.values(tools).map(tool => ({
- ...tool,
- category
- }))
- )
+ // Flatten all tools into a single array with their categories
+ const allTools = Object.entries(toolCategories).flatMap(([category, tools]) =>
+ Object.values(tools).map((tool) => ({
+ ...tool,
+ category
+ }))
+ )
- // Filter tools based on search query and selected category
- const filteredTools = allTools.filter(tool => {
- const matchesSearch = tool.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
- tool.description?.toLowerCase().includes(searchQuery.toLowerCase())
- const matchesCategory = selectedCategory === "all" || tool.category === selectedCategory
- return matchesSearch && matchesCategory
- })
+ // Filter tools based on search query and selected category
+ const filteredTools = allTools.filter((tool) => {
+ const matchesSearch =
+ tool.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ tool.description?.toLowerCase().includes(searchQuery.toLowerCase())
+ const matchesCategory = selectedCategory === 'all' || tool.category === selectedCategory
+ return matchesSearch && matchesCategory
+ })
- return (
- <div className="h-full w-full px-12 py-12 bg-background overflow-auto">
- <div className='max-w-7xl mx-auto flex flex-col gap-12 items-center justify-start'>
- <div className='w-full'>
- <h1 className="font-semibold text-2xl">Tools</h1>
- <p className="opacity-60 mt-3">Here are the tools used to gather informations.</p>
- </div>
+ return (
+ <div className="h-full w-full px-12 py-12 bg-background overflow-auto">
+ <div className="max-w-7xl mx-auto flex flex-col gap-12 items-center justify-start">
+ <div className="w-full">
+ <h1 className="font-semibold text-2xl">Tools</h1>
+ <p className="opacity-60 mt-3">Here are the tools used to gather informations.</p>
+ </div>
- <div className="w-full flex flex-col md:flex-row gap-4">
- <div className="flex-1">
- <Input
- type="text"
- placeholder="Search tools..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- />
- </div>
- <div className="w-full md:w-64">
- <Select value={selectedCategory} onValueChange={setSelectedCategory}>
- <SelectTrigger className="h-10 w-full">
- <SelectValue placeholder="Select category" />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="all">All Categories</SelectItem>
- {Object.keys(toolCategories).map(category => (
- <SelectItem key={category} value={category}>
- {category}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
+ <div className="w-full flex flex-col md:flex-row gap-4">
+ <div className="flex-1">
+ <Input
+ type="text"
+ placeholder="Search tools..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+ </div>
+ <div className="w-full md:w-64">
+ <Select value={selectedCategory} onValueChange={setSelectedCategory}>
+ <SelectTrigger className="h-10 w-full">
+ <SelectValue placeholder="Select category" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All Categories</SelectItem>
+ {Object.keys(toolCategories).map((category) => (
+ <SelectItem key={category} value={category}>
+ {category}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
- <div className='w-full grid lg:grid-cols-3 md:grid-cols-2 grid-cols-1 xl:grid-cols-4 gap-4'>
- {filteredTools.map((tool) => (
- <ToolCard key={tool.name} tool={tool} />
- ))}
- </div>
- </div>
+ <div className="w-full grid lg:grid-cols-3 md:grid-cols-2 grid-cols-1 xl:grid-cols-4 gap-4">
+ {filteredTools.map((tool) => (
+ <ToolCard key={tool.name} tool={tool} />
+ ))}
</div>
- )
+ </div>
+ </div>
+ )
}
-export default ToolsPage
\ No newline at end of file
+export default ToolsPage
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.tsx
index 6daaffc8..c9c727cf 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.tsx
@@ -4,15 +4,15 @@ import { useGraphSettingsStore } from '@/stores/graph-settings-store'
import { createFileRoute, Outlet } from '@tanstack/react-router'
export const Route = createFileRoute('/_auth/dashboard')({
- component: DashboardPage,
+ component: DashboardPage
})
function DashboardPage() {
- const settings = useGraphSettingsStore(s => s.settings)
- return (
- <RootLayout>
- <Outlet />
- {Boolean(settings?.general?.showFlow?.value) && <FloatingChat />}
- </RootLayout>
- )
+ const settings = useGraphSettingsStore((s) => s.settings)
+ return (
+ <RootLayout>
+ <Outlet />
+ {Boolean(settings?.general?.showFlow?.value) && <FloatingChat />}
+ </RootLayout>
+ )
}
diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.vault.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.vault.tsx
index ca5a6c7e..43926f62 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.vault.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.vault.tsx
@@ -6,9 +6,24 @@ import { Button } from '../components/ui/button'
import { Input } from '../components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card'
import { Badge } from '../components/ui/badge'
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '../components/ui/dialog'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger
+} from '../components/ui/dialog'
import { Label } from '../components/ui/label'
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../components/ui/table'
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from '../components/ui/table'
import { Loader2, Plus, Trash2, Clock, Shield, Key, Zap, Lock, Sparkles } from 'lucide-react'
import { toast } from 'sonner'
import { useConfirm } from '../components/use-confirm-dialog'
@@ -17,306 +32,320 @@ import { type Key as KeyType } from '@/types/key'
import { queryKeys } from '@/api/query-keys'
import ErrorState from '@/components/shared/error-state'
export const Route = createFileRoute('/_auth/dashboard/vault')({
- component: VaultPage,
+ component: VaultPage
})
function VaultPage() {
- const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
- const [keyName, setKeyName] = useState('')
- const [apiKey, setApiKey] = useState('')
- const queryClient = useQueryClient()
- const { confirm } = useConfirm()
+ const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
+ const [keyName, setKeyName] = useState('')
+ const [apiKey, setApiKey] = useState('')
+ const queryClient = useQueryClient()
+ const { confirm } = useConfirm()
- // Fetch keys
- const { data: keys = [], isLoading: keysLoading, error: keysError, refetch } = useQuery<KeyType[]>({
- queryKey: queryKeys.keys.list,
- queryFn: () => KeyService.get(),
- })
-
- // Create key mutation
- const createKeyMutation = useMutation({
- mutationFn: KeyService.create,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: queryKeys.keys.list })
- setIsAddDialogOpen(false)
- setKeyName('')
- setApiKey('')
- toast.success('API key added successfully!')
- },
- onError: (error) => {
- toast.error('Failed to add API key. Please try again.')
- console.error('Error creating key:', error)
- }
- })
-
- // Delete key mutation
- const deleteKeyMutation = useMutation({
- mutationFn: KeyService.deleteById,
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: queryKeys.keys.list })
- toast.success('API key deleted successfully!')
- },
- onError: (error) => {
- toast.error('Failed to delete API key. Please try again.')
- console.error('Error deleting key:', error)
- }
- })
+ // Fetch keys
+ const {
+ data: keys = [],
+ isLoading: keysLoading,
+ error: keysError,
+ refetch
+ } = useQuery<KeyType[]>({
+ queryKey: queryKeys.keys.list,
+ queryFn: () => KeyService.get()
+ })
- const handleAddKey = () => {
- if (!keyName.trim() || !apiKey.trim()) {
- toast.error('Please enter both a name and an API key')
- return
- }
- createKeyMutation.mutate({ name: keyName.trim(), key: apiKey })
+ // Create key mutation
+ const createKeyMutation = useMutation({
+ mutationFn: KeyService.create,
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.keys.list })
+ setIsAddDialogOpen(false)
+ setKeyName('')
+ setApiKey('')
+ toast.success('API key added successfully!')
+ },
+ onError: (error) => {
+ toast.error('Failed to add API key. Please try again.')
+ console.error('Error creating key:', error)
}
+ })
- const handleDeleteKey = async (keyId: string, keyName: string) => {
- const confirmed = await confirm({
- title: 'Delete API Key',
- message: `Are you sure you want to delete the API key "${keyName}"? This action cannot be undone.`
- })
-
- if (confirmed) {
- deleteKeyMutation.mutate(keyId)
- }
+ // Delete key mutation
+ const deleteKeyMutation = useMutation({
+ mutationFn: KeyService.deleteById,
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.keys.list })
+ toast.success('API key deleted successfully!')
+ },
+ onError: (error) => {
+ toast.error('Failed to delete API key. Please try again.')
+ console.error('Error deleting key:', error)
}
+ })
- if (keysLoading) {
- return (
- <div className="h-full w-full px-12 py-12 bg-background overflow-auto">
- <div className='max-w-7xl mx-auto flex h-full flex-col gap-12 items-center justify-start'>
- <div className='w-full'>
- <h1 className="font-semibold text-2xl">Vault</h1>
- <p className="opacity-60 mt-3">Manage your API keys for third-party services.</p>
- </div>
- <div className="w-full h-full flex items-center justify-center">
- <Loader />
- </div>
- </div>
- </div>
- )
+ const handleAddKey = () => {
+ if (!keyName.trim() || !apiKey.trim()) {
+ toast.error('Please enter both a name and an API key')
+ return
}
+ createKeyMutation.mutate({ name: keyName.trim(), key: apiKey })
+ }
- if (keysError) {
- return (
- <div className="h-full w-full px-12 py-12 bg-background overflow-auto">
- <div className='max-w-7xl mx-auto flex h-full flex-col gap-12 items-center justify-start'>
- <div className='w-full'>
- <h1 className="font-semibold text-2xl">Vault</h1>
- <p className="opacity-60 mt-3">Manage your API keys for third-party services.</p>
- </div>
- <div className="w-full h-full flex items-center justify-center">
- <ErrorState
- title="Couldn't load keys"
- description="Something went wrong while fetching data. Please try again."
- error={keysError}
- onRetry={() => refetch()}
- />
- </div>
- </div>
- </div>
- )
+ const handleDeleteKey = async (keyId: string, keyName: string) => {
+ const confirmed = await confirm({
+ title: 'Delete API Key',
+ message: `Are you sure you want to delete the API key "${keyName}"? This action cannot be undone.`
+ })
+
+ if (confirmed) {
+ deleteKeyMutation.mutate(keyId)
}
+ }
+ if (keysLoading) {
return (
- <div className="h-full w-full px-12 py-12 bg-background overflow-auto">
- <div className='max-w-7xl mx-auto flex flex-col gap-12 items-center justify-start'>
- <div className='w-full flex justify-between items-center'>
- <div>
- <h1 className="font-semibold text-3xl bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
- Vault
- </h1>
- <p className="text-muted-foreground mt-2">Securely manage your API keys for third-party services.</p>
- </div>
- <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
- <DialogTrigger asChild>
- <Button
- >
- <Plus className="w-5 h-5" />
- Add API Key
- </Button>
- </DialogTrigger>
- <DialogContent className="sm:max-w-[425px]">
- <DialogHeader>
- <DialogTitle>Add API Key</DialogTitle>
- <DialogDescription>
- Add a new API key with a custom name. Your keys are encrypted and stored securely.
- </DialogDescription>
- </DialogHeader>
- <div className="grid gap-4 py-4">
- <div className="grid gap-2">
- <Label htmlFor="keyName">Key Name</Label>
- <Input
- id="keyName"
- placeholder="e.g., OpenAI, GitHub, Shodan..."
- value={keyName}
- onChange={(e) => setKeyName(e.target.value)}
- />
- </div>
- <div className="grid gap-2">
- <Label htmlFor="apiKey">API Key</Label>
- <Input
- id="apiKey"
- type="password"
- placeholder="Enter your API key"
- value={apiKey}
- onChange={(e) => setApiKey(e.target.value)}
- />
- </div>
- </div>
- <DialogFooter>
- <Button
- variant="outline"
- onClick={() => setIsAddDialogOpen(false)}
- disabled={createKeyMutation.isPending}
- >
- Cancel
- </Button>
- <Button
- onClick={handleAddKey}
- disabled={createKeyMutation.isPending || !keyName.trim() || !apiKey.trim()}
- >
- {createKeyMutation.isPending && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
- Add Key
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </div>
+ <div className="h-full w-full px-12 py-12 bg-background overflow-auto">
+ <div className="max-w-7xl mx-auto flex h-full flex-col gap-12 items-center justify-start">
+ <div className="w-full">
+ <h1 className="font-semibold text-2xl">Vault</h1>
+ <p className="opacity-60 mt-3">Manage your API keys for third-party services.</p>
+ </div>
+ <div className="w-full h-full flex items-center justify-center">
+ <Loader />
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ if (keysError) {
+ return (
+ <div className="h-full w-full px-12 py-12 bg-background overflow-auto">
+ <div className="max-w-7xl mx-auto flex h-full flex-col gap-12 items-center justify-start">
+ <div className="w-full">
+ <h1 className="font-semibold text-2xl">Vault</h1>
+ <p className="opacity-60 mt-3">Manage your API keys for third-party services.</p>
+ </div>
+ <div className="w-full h-full flex items-center justify-center">
+ <ErrorState
+ title="Couldn't load keys"
+ description="Something went wrong while fetching data. Please try again."
+ error={keysError}
+ onRetry={() => refetch()}
+ />
+ </div>
+ </div>
+ </div>
+ )
+ }
- <div className="w-full">
- {keys.length === 0 ? (
- <Card className="border-2 border-dashed border-primary/20 bg-gradient-to-br from-primary/5 via-background to-accent/5">
- <CardContent className="flex flex-col items-center justify-center py-20 px-8">
- <div className="text-center space-y-4 max-w-md">
- <h3 className="text-2xl font-bold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
- Your Vault is Empty
- </h3>
- <p className="text-muted-foreground text-lg leading-relaxed">
- Add your first API key to unlock the power of third-party services in your investigations.
- </p>
+ return (
+ <div className="h-full w-full px-12 py-12 bg-background overflow-auto">
+ <div className="max-w-7xl mx-auto flex flex-col gap-12 items-center justify-start">
+ <div className="w-full flex justify-between items-center">
+ <div>
+ <h1 className="font-semibold text-3xl bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
+ Vault
+ </h1>
+ <p className="text-muted-foreground mt-2">
+ Securely manage your API keys for third-party services.
+ </p>
+ </div>
+ <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
+ <DialogTrigger asChild>
+ <Button>
+ <Plus className="w-5 h-5" />
+ Add API Key
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>Add API Key</DialogTitle>
+ <DialogDescription>
+ Add a new API key with a custom name. Your keys are encrypted and stored securely.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 py-4">
+ <div className="grid gap-2">
+ <Label htmlFor="keyName">Key Name</Label>
+ <Input
+ id="keyName"
+ placeholder="e.g., OpenAI, GitHub, Shodan..."
+ value={keyName}
+ onChange={(e) => setKeyName(e.target.value)}
+ />
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor="apiKey">API Key</Label>
+ <Input
+ id="apiKey"
+ type="password"
+ placeholder="Enter your API key"
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => setIsAddDialogOpen(false)}
+ disabled={createKeyMutation.isPending}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={handleAddKey}
+ disabled={createKeyMutation.isPending || !keyName.trim() || !apiKey.trim()}
+ >
+ {createKeyMutation.isPending && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
+ Add Key
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
- <div className="flex flex-wrap justify-center gap-3 pt-4 pb-6">
- <Badge variant="secondary" className="bg-primary/10 text-primary border-primary/20 px-4 py-2">
- <Zap className="w-4 h-4 mr-2" />
- Fast Setup
- </Badge>
- <Badge variant="secondary" className="bg-emerald-500/10 text-emerald-700 border-emerald-200/40 px-4 py-2">
- <Lock className="w-4 h-4 mr-2" />
- Encrypted
- </Badge>
- <Badge variant="secondary" className="bg-violet-500/10 text-violet-700 border-violet-200/40 px-4 py-2">
- <Sparkles className="w-4 h-4 mr-2" />
- Secure
- </Badge>
- </div>
+ <div className="w-full">
+ {keys.length === 0 ? (
+ <Card className="border-2 border-dashed border-primary/20 bg-gradient-to-br from-primary/5 via-background to-accent/5">
+ <CardContent className="flex flex-col items-center justify-center py-20 px-8">
+ <div className="text-center space-y-4 max-w-md">
+ <h3 className="text-2xl font-bold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text text-transparent">
+ Your Vault is Empty
+ </h3>
+ <p className="text-muted-foreground text-lg leading-relaxed">
+ Add your first API key to unlock the power of third-party services in your
+ investigations.
+ </p>
- <Button
- onClick={() => setIsAddDialogOpen(true)}
+ <div className="flex flex-wrap justify-center gap-3 pt-4 pb-6">
+ <Badge
+ variant="secondary"
+ className="bg-primary/10 text-primary border-primary/20 px-4 py-2"
+ >
+ <Zap className="w-4 h-4 mr-2" />
+ Fast Setup
+ </Badge>
+ <Badge
+ variant="secondary"
+ className="bg-emerald-500/10 text-emerald-700 border-emerald-200/40 px-4 py-2"
+ >
+ <Lock className="w-4 h-4 mr-2" />
+ Encrypted
+ </Badge>
+ <Badge
+ variant="secondary"
+ className="bg-violet-500/10 text-violet-700 border-violet-200/40 px-4 py-2"
+ >
+ <Sparkles className="w-4 h-4 mr-2" />
+ Secure
+ </Badge>
+ </div>
- >
- <Plus className="w-5 h-5 mr-2" />
- Add Your First Key
- </Button>
- </div>
- </CardContent>
- </Card>
- ) : (
- <Card className="overflow-hidden border bg-gradient-to-br from-background to-muted/20">
- <CardHeader className="border-b">
- <div className="flex items-center justify-between">
- <CardTitle className="flex items-center gap-3 text-xl">
- <div className="p-2 bg-primary rounded-lg">
- <Shield className="w-5 h-5 text-white" strokeWidth={1.9} />
- </div>
- API Keys
- </CardTitle>
- <Badge variant="secondary" className="px-3 py-1">
- {keys.length} {keys.length === 1 ? 'key' : 'keys'}
- </Badge>
- </div>
- <CardDescription className="text-base mt-2">
- Your encrypted API keys for external services. These keys will be available for your investigations.
- </CardDescription>
- </CardHeader>
- <CardContent className="p-0">
- <Table>
- <TableHeader>
- <TableRow className="border-b bg-muted/30">
- <TableHead className="py-4 px-6 text-sm font-semibold w-2/5">
- <div className="flex items-center gap-2">
- <Key className="w-4 h-4" />
- Name
- </div>
- </TableHead>
- <TableHead className="py-4 text-sm font-semibold w-1/3">
- <div className="flex items-center gap-2">
- <Clock className="w-4 h-4" />
- Created
- </div>
- </TableHead>
- <TableHead className="py-4 px-6 text-sm font-semibold text-right w-1/5">
- Actions
- </TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {keys.map((key: KeyType) => (
- <TableRow
- key={key.id}
- className="group hover:bg-gradient-to-r hover:from-primary/5 hover:to-accent/5 transition-all duration-200 border-b border-border/50"
- >
- <TableCell className="py-5 px-6">
- <div className="flex items-center gap-4">
- <div className="p-2 bg-gradient-to-r from-primary/10 to-accent/10 border border-primary/20 rounded-lg group-hover:scale-110 transition-transform duration-200">
- <Key className="w-4 h-4 text-primary" />
- </div>
- <div>
- <div className="font-semibold text-foreground group-hover:text-primary transition-colors">
- {key.name}
- </div>
- <div className="text-sm text-muted-foreground">
- Encrypted & Secure
- </div>
- </div>
- </div>
- </TableCell>
- <TableCell className="py-5">
- <div className="flex items-center gap-2 text-sm">
- <div className="p-1.5 bg-muted rounded-full">
- <Clock className="w-3 h-3 text-muted-foreground" />
- </div>
- <span className="text-muted-foreground">
- {new Date(key.created_at).toLocaleDateString('en-US', {
- year: 'numeric',
- month: 'short',
- day: 'numeric'
- })}
- </span>
- </div>
- </TableCell>
- <TableCell className="text-right py-5 px-6">
- <Button
- variant="ghost"
- size="icon"
- className="text-destructive hover:text-destructive hover:bg-destructive/10"
- onClick={() => handleDeleteKey(key.id, key.name)}
- disabled={deleteKeyMutation.isPending}
- >
- <Trash2 className="w-4 h-4" />
- </Button>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </CardContent>
- </Card>
- )}
+ <Button onClick={() => setIsAddDialogOpen(true)}>
+ <Plus className="w-5 h-5 mr-2" />
+ Add Your First Key
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ ) : (
+ <Card className="overflow-hidden border bg-gradient-to-br from-background to-muted/20">
+ <CardHeader className="border-b">
+ <div className="flex items-center justify-between">
+ <CardTitle className="flex items-center gap-3 text-xl">
+ <div className="p-2 bg-primary rounded-lg">
+ <Shield className="w-5 h-5 text-white" strokeWidth={1.9} />
+ </div>
+ API Keys
+ </CardTitle>
+ <Badge variant="secondary" className="px-3 py-1">
+ {keys.length} {keys.length === 1 ? 'key' : 'keys'}
+ </Badge>
</div>
- </div>
+ <CardDescription className="text-base mt-2">
+ Your encrypted API keys for external services. These keys will be available for
+ your investigations.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="p-0">
+ <Table>
+ <TableHeader>
+ <TableRow className="border-b bg-muted/30">
+ <TableHead className="py-4 px-6 text-sm font-semibold w-2/5">
+ <div className="flex items-center gap-2">
+ <Key className="w-4 h-4" />
+ Name
+ </div>
+ </TableHead>
+ <TableHead className="py-4 text-sm font-semibold w-1/3">
+ <div className="flex items-center gap-2">
+ <Clock className="w-4 h-4" />
+ Created
+ </div>
+ </TableHead>
+ <TableHead className="py-4 px-6 text-sm font-semibold text-right w-1/5">
+ Actions
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {keys.map((key: KeyType) => (
+ <TableRow
+ key={key.id}
+ className="group hover:bg-gradient-to-r hover:from-primary/5 hover:to-accent/5 transition-all duration-200 border-b border-border/50"
+ >
+ <TableCell className="py-5 px-6">
+ <div className="flex items-center gap-4">
+ <div className="p-2 bg-gradient-to-r from-primary/10 to-accent/10 border border-primary/20 rounded-lg group-hover:scale-110 transition-transform duration-200">
+ <Key className="w-4 h-4 text-primary" />
+ </div>
+ <div>
+ <div className="font-semibold text-foreground group-hover:text-primary transition-colors">
+ {key.name}
+ </div>
+ <div className="text-sm text-muted-foreground">
+ Encrypted & Secure
+ </div>
+ </div>
+ </div>
+ </TableCell>
+ <TableCell className="py-5">
+ <div className="flex items-center gap-2 text-sm">
+ <div className="p-1.5 bg-muted rounded-full">
+ <Clock className="w-3 h-3 text-muted-foreground" />
+ </div>
+ <span className="text-muted-foreground">
+ {new Date(key.created_at).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric'
+ })}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell className="text-right py-5 px-6">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="text-destructive hover:text-destructive hover:bg-destructive/10"
+ onClick={() => handleDeleteKey(key.id, key.name)}
+ disabled={deleteKeyMutation.isPending}
+ >
+ <Trash2 className="w-4 h-4" />
+ </Button>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
+ )}
</div>
- )
+ </div>
+ </div>
+ )
}
-export default VaultPage
\ No newline at end of file
+export default VaultPage
diff --git a/flowsint-app/src/renderer/src/routes/_auth.tsx b/flowsint-app/src/renderer/src/routes/_auth.tsx
index 138903db..ddcb3ebb 100644
--- a/flowsint-app/src/renderer/src/routes/_auth.tsx
+++ b/flowsint-app/src/renderer/src/routes/_auth.tsx
@@ -1,8 +1,4 @@
-import {
- Link,
- Outlet,
- createFileRoute,
-} from '@tanstack/react-router'
+import { Link, Outlet, createFileRoute } from '@tanstack/react-router'
import { requireAuth } from '@/lib/auth-utils'
import { Button } from '@/components/ui/button'
@@ -10,46 +6,40 @@ import { Card, CardDescription, CardFooter, CardHeader, CardTitle } from '@/comp
import { AlertTriangle, Home } from 'lucide-react'
export const Route = createFileRoute('/_auth')({
- beforeLoad: ({ location }) => {
- requireAuth(location.href)
- },
- component: AuthLayout,
- errorComponent: ErrorComponent,
+ beforeLoad: ({ location }) => {
+ requireAuth(location.href)
+ },
+ component: AuthLayout,
+ errorComponent: ErrorComponent
})
function AuthLayout() {
- return (
- <Outlet />
- )
+ return <Outlet />
}
function ErrorComponent() {
+ return (
+ <div className="min-h-screen flex items-center justify-center p-4 bg-background">
+ <Card className="w-full max-w-md">
+ <CardHeader className="text-center">
+ <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10">
+ <AlertTriangle className="h-6 w-6 text-destructive" />
+ </div>
+ <CardTitle className="text-xl">Something went wrong</CardTitle>
+ <CardDescription>
+ We encountered an unexpected error. Please try again or navigate to a safe location.
+ </CardDescription>
+ </CardHeader>
-
- return (
- <div className="min-h-screen flex items-center justify-center p-4 bg-background">
- <Card className="w-full max-w-md">
- <CardHeader className="text-center">
- <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10">
- <AlertTriangle className="h-6 w-6 text-destructive" />
- </div>
- <CardTitle className="text-xl">Something went wrong</CardTitle>
- <CardDescription>
- We encountered an unexpected error. Please try again or navigate to a safe location.
- </CardDescription>
- </CardHeader>
-
- <CardFooter className="flex flex-col gap-2">
- <Link to="/dashboard">
- <Button
- className="flex-1"
- >
- <Home className="mr-2 h-4 w-4" />
- Go to Dashboard
- </Button>
- </Link>
- </CardFooter>
- </Card>
- </div>
- )
+ <CardFooter className="flex flex-col gap-2">
+ <Link to="/dashboard">
+ <Button className="flex-1">
+ <Home className="mr-2 h-4 w-4" />
+ Go to Dashboard
+ </Button>
+ </Link>
+ </CardFooter>
+ </Card>
+ </div>
+ )
}
diff --git a/flowsint-app/src/renderer/src/routes/index.tsx b/flowsint-app/src/renderer/src/routes/index.tsx
index a4aa466d..71c8776b 100644
--- a/flowsint-app/src/renderer/src/routes/index.tsx
+++ b/flowsint-app/src/renderer/src/routes/index.tsx
@@ -1,7 +1,5 @@
import { Navigate, createFileRoute } from '@tanstack/react-router'
-
export const Route = createFileRoute('/')({
-
- component: () => <Navigate to={"/dashboard"} />
-})
\ No newline at end of file
+ component: () => <Navigate to={'/dashboard'} />
+})
diff --git a/flowsint-app/src/renderer/src/routes/login.tsx b/flowsint-app/src/renderer/src/routes/login.tsx
index 2c72eaf7..c39c0228 100644
--- a/flowsint-app/src/renderer/src/routes/login.tsx
+++ b/flowsint-app/src/renderer/src/routes/login.tsx
@@ -1,138 +1,154 @@
-import { Link } from '@tanstack/react-router';
-import { useLogin } from '@/hooks/use-auth';
-import { FormProvider, useForm } from 'react-hook-form';
-import FormField from '@/components/shared/form-field';
-import { z } from 'zod';
-import { zodResolver } from '@hookform/resolvers/zod';
-import { createFileRoute } from '@tanstack/react-router';
+import { Link } from '@tanstack/react-router'
+import { useLogin } from '@/hooks/use-auth'
+import { FormProvider, useForm } from 'react-hook-form'
+import FormField from '@/components/shared/form-field'
+import { z } from 'zod'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/login')({
- component: Login,
-});
+ component: Login
+})
const loginSchema = z.object({
- username: z.string().min(1, 'Username is required'),
- password: z.string().min(1, 'Password is required'),
- rememberMe: z.boolean().optional(),
-});
+ username: z.string().min(1, 'Username is required'),
+ password: z.string().min(1, 'Password is required'),
+ rememberMe: z.boolean().optional()
+})
-type LoginFormValues = z.infer<typeof loginSchema>;
+type LoginFormValues = z.infer<typeof loginSchema>
function Login() {
- // Initialize React Hook Form
- const methods = useForm<LoginFormValues>({
- resolver: zodResolver(loginSchema),
- defaultValues: {
- username: '',
- password: '',
- rememberMe: false,
- },
- });
+ // Initialize React Hook Form
+ const methods = useForm<LoginFormValues>({
+ resolver: zodResolver(loginSchema),
+ defaultValues: {
+ username: '',
+ password: '',
+ rememberMe: false
+ }
+ })
- const login = useLogin();
+ const login = useLogin()
- const onSubmit = async (data: LoginFormValues) => {
- try {
- await login.mutateAsync({
- username: data.username,
- password: data.password,
- });
- } catch (error) {
- console.error('Login error:', error);
- }
- };
+ const onSubmit = async (data: LoginFormValues) => {
+ try {
+ await login.mutateAsync({
+ username: data.username,
+ password: data.password
+ })
+ } catch (error) {
+ console.error('Login error:', error)
+ }
+ }
- return (
- <div className="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
- <div className="max-w-md w-full space-y-8">
- <div>
- <h2 className="mt-6 text-center text-3xl font-extrabold">
- Sign in to your account
- </h2>
- </div>
-
- <FormProvider {...methods}>
- <form className="mt-8 space-y-6" onSubmit={methods.handleSubmit(onSubmit)}>
- {/* Display login error */}
- {login.error && (
- <div className="p-3 mb-4 text-sm bg-red-500/10 border border-red-400 text-red-700 rounded">
- {login.error instanceof Error ? login.error.message : 'Login error'}
- </div>
- )}
+ return (
+ <div className="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
+ <div className="max-w-md w-full space-y-8">
+ <div>
+ <h2 className="mt-6 text-center text-3xl font-extrabold">Sign in to your account</h2>
+ </div>
- <div className="rounded-md space-y-4">
- {/* Username field */}
- <FormField
- name="username"
- label="Username"
- placeholder="Your username"
- disabled={login.isPending}
- />
+ <FormProvider {...methods}>
+ <form className="mt-8 space-y-6" onSubmit={methods.handleSubmit(onSubmit)}>
+ {/* Display login error */}
+ {login.error && (
+ <div className="p-3 mb-4 text-sm bg-red-500/10 border border-red-400 text-red-700 rounded">
+ {login.error instanceof Error ? login.error.message : 'Login error'}
+ </div>
+ )}
- {/* Password field */}
- <FormField
- name="password"
- label="Password"
- type="password"
- placeholder="Your password"
- disabled={login.isPending}
- />
- </div>
+ <div className="rounded-md space-y-4">
+ {/* Username field */}
+ <FormField
+ name="username"
+ label="Username"
+ placeholder="Your username"
+ disabled={login.isPending}
+ />
- {/* Additional options */}
- <div className="flex items-center justify-between">
- <div className="flex items-center">
- <input
- id="rememberMe"
- {...methods.register('rememberMe')}
- type="checkbox"
- className="h-4 w-4 text-primary rounded"
- />
- <label htmlFor="rememberMe" className="ml-2 block text-sm">
- Remember me
- </label>
- </div>
+ {/* Password field */}
+ <FormField
+ name="password"
+ label="Password"
+ type="password"
+ placeholder="Your password"
+ disabled={login.isPending}
+ />
+ </div>
- <div className="text-sm">
- <a href="#" className="font-medium text-primary">
- Forgot your password?
- </a>
- </div>
- </div>
+ {/* Additional options */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center">
+ <input
+ id="rememberMe"
+ {...methods.register('rememberMe')}
+ type="checkbox"
+ className="h-4 w-4 text-primary rounded"
+ />
+ <label htmlFor="rememberMe" className="ml-2 block text-sm">
+ Remember me
+ </label>
+ </div>
- {/* Submit button */}
- <div>
- <button
- type="submit"
- disabled={login.isPending || methods.formState.isSubmitting}
- className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary focus:outline-none focus:ring-2 focus:ring-offset-2"
- >
- {login.isPending || methods.formState.isSubmitting ? (
- <span className="flex items-center">
- <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
- <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
- <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
- </svg>
- Signing in...
- </span>
- ) : 'Sign In'}
- </button>
- </div>
- </form>
- </FormProvider>
+ <div className="text-sm">
+ <a href="#" className="font-medium text-primary">
+ Forgot your password?
+ </a>
+ </div>
+ </div>
- {/* Link to registration */}
- <div className="text-center mt-4">
- <p className="text-sm text-gray-600">
- Don't have an account?{' '}
- <Link to="/register" className="font-medium text-primary">
- Create an account
- </Link>
- </p>
- </div>
+ {/* Submit button */}
+ <div>
+ <button
+ type="submit"
+ disabled={login.isPending || methods.formState.isSubmitting}
+ className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary focus:outline-none focus:ring-2 focus:ring-offset-2"
+ >
+ {login.isPending || methods.formState.isSubmitting ? (
+ <span className="flex items-center">
+ <svg
+ className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ ></circle>
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
+ ></path>
+ </svg>
+ Signing in...
+ </span>
+ ) : (
+ 'Sign In'
+ )}
+ </button>
</div>
+ </form>
+ </FormProvider>
+
+ {/* Link to registration */}
+ <div className="text-center mt-4">
+ <p className="text-sm text-gray-600">
+ Don't have an account?{' '}
+ <Link to="/register" className="font-medium text-primary">
+ Create an account
+ </Link>
+ </p>
</div>
- );
+ </div>
+ </div>
+ )
}
-export default Login;
+export default Login
diff --git a/flowsint-app/src/renderer/src/routes/middleware.tsx b/flowsint-app/src/renderer/src/routes/middleware.tsx
index 52fcef98..8e0d7557 100644
--- a/flowsint-app/src/renderer/src/routes/middleware.tsx
+++ b/flowsint-app/src/renderer/src/routes/middleware.tsx
@@ -1,60 +1,60 @@
-import { useEffect } from 'react';
-import { Outlet, useNavigate, createFileRoute } from '@tanstack/react-router';
-import { useAuthStore } from '@/stores/auth-store';
+import { useEffect } from 'react'
+import { Outlet, useNavigate, createFileRoute } from '@tanstack/react-router'
+import { useAuthStore } from '@/stores/auth-store'
-const TOKEN_EXPIRY_MINUTES = 60;
+const TOKEN_EXPIRY_MINUTES = 60
export const Route = createFileRoute('/middleware')({
- component: AuthLayout,
-});
+ component: AuthLayout
+})
function AuthLayout() {
- const navigate = useNavigate();
- const { token, isAuthenticated, logout } = useAuthStore();
-
- useEffect(() => {
- // Protection contre le clickjacking
- if (window.self !== window.top) {
- console.error('Cette application ne peut pas être chargée dans un iframe');
- logout();
- return;
+ const navigate = useNavigate()
+ const { token, isAuthenticated, logout } = useAuthStore()
+
+ useEffect(() => {
+ // Protection contre le clickjacking
+ if (window.self !== window.top) {
+ console.error('Cette application ne peut pas être chargée dans un iframe')
+ logout()
+ return
+ }
+
+ if (!isAuthenticated || !token) {
+ navigate({ to: '/login' })
+ return
+ }
+
+ // Vérifier si le token est expiré
+ // Note: Dans un système de production, vous devriez implémenter un refresh token
+ // au lieu de forcer une déconnexion
+ const checkTokenExpiry = () => {
+ try {
+ // Décodage simple du token JWT (partie payload)
+ // Dans un système réel, vous pourriez utiliser une bibliothèque comme jwt-decode
+ const payload = JSON.parse(atob(token.split('.')[1]))
+
+ if (payload.exp && payload.exp * 1000 < Date.now()) {
+ console.warn('Session expirée')
+ logout()
+ navigate({ to: '/login' })
}
+ } catch (error) {
+ console.error('Erreur lors de la vérification du token', error)
+ logout()
+ navigate({ to: '/login' })
+ }
+ }
- if (!isAuthenticated || !token) {
- navigate({ to: '/login' });
- return;
- }
+ // Vérifier l'expiration du token au démarrage
+ checkTokenExpiry()
+
+ // Vérifier périodiquement l'expiration du token
+ const interval = setInterval(checkTokenExpiry, TOKEN_EXPIRY_MINUTES * 60 * 1000)
+
+ return () => clearInterval(interval)
+ }, [token, isAuthenticated, logout, navigate])
- // Vérifier si le token est expiré
- // Note: Dans un système de production, vous devriez implémenter un refresh token
- // au lieu de forcer une déconnexion
- const checkTokenExpiry = () => {
- try {
- // Décodage simple du token JWT (partie payload)
- // Dans un système réel, vous pourriez utiliser une bibliothèque comme jwt-decode
- const payload = JSON.parse(atob(token.split('.')[1]));
-
- if (payload.exp && payload.exp * 1000 < Date.now()) {
- console.warn('Session expirée');
- logout();
- navigate({ to: '/login' });
- }
- } catch (error) {
- console.error('Erreur lors de la vérification du token', error);
- logout();
- navigate({ to: '/login' });
- }
- };
-
- // Vérifier l'expiration du token au démarrage
- checkTokenExpiry();
-
- // Vérifier périodiquement l'expiration du token
- const interval = setInterval(checkTokenExpiry, TOKEN_EXPIRY_MINUTES * 60 * 1000);
-
- return () => clearInterval(interval);
- }, [token, isAuthenticated, logout, navigate]);
-
- // Render children routes with the Outlet component
- return <Outlet />;
-}
\ No newline at end of file
+ // Render children routes with the Outlet component
+ return <Outlet />
+}
diff --git a/flowsint-app/src/renderer/src/routes/register.tsx b/flowsint-app/src/renderer/src/routes/register.tsx
index 56dd200f..7d240d43 100644
--- a/flowsint-app/src/renderer/src/routes/register.tsx
+++ b/flowsint-app/src/renderer/src/routes/register.tsx
@@ -1,15 +1,15 @@
// src/routes/register.tsx
-import { createFileRoute, Link } from '@tanstack/react-router';
-import { useRegister } from '@/hooks/use-auth';
-import { useForm, FormProvider } from 'react-hook-form';
-import { z } from 'zod';
-import { zodResolver } from '@hookform/resolvers/zod';
-import FormField from '@/components/shared/form-field';
-import { Button } from '@/components/ui/button';
+import { createFileRoute, Link } from '@tanstack/react-router'
+import { useRegister } from '@/hooks/use-auth'
+import { useForm, FormProvider } from 'react-hook-form'
+import { z } from 'zod'
+import { zodResolver } from '@hookform/resolvers/zod'
+import FormField from '@/components/shared/form-field'
+import { Button } from '@/components/ui/button'
export const Route = createFileRoute('/register')({
- component: Register,
-});
+ component: Register
+})
const registerSchema = z
.object({
@@ -19,14 +19,14 @@ const registerSchema = z
.max(50, "Le nom d'utilisateur ne peut pas dépasser 50 caractères"),
email: z.string().email('Veuillez entrer une adresse email valide'),
password: z.string().min(6, 'Le mot de passe doit contenir au moins 6 caractères'),
- confirmPassword: z.string(),
+ confirmPassword: z.string()
})
.refine((data) => data.password === data.confirmPassword, {
message: 'Les mots de passe ne correspondent pas',
- path: ['confirmPassword'],
- });
+ path: ['confirmPassword']
+ })
-type RegisterFormValues = z.infer<typeof registerSchema>;
+type RegisterFormValues = z.infer<typeof registerSchema>
function Register() {
const methods = useForm<RegisterFormValues>({
@@ -35,20 +35,20 @@ function Register() {
username: '',
email: '',
password: '',
- confirmPassword: '',
- },
- });
+ confirmPassword: ''
+ }
+ })
- const registerMutation = useRegister();
+ const registerMutation = useRegister()
const onSubmit = async (data: RegisterFormValues) => {
try {
- const { confirmPassword, ...registerData } = data;
- await registerMutation.mutateAsync(registerData);
+ const { confirmPassword, ...registerData } = data
+ await registerMutation.mutateAsync(registerData)
} catch (error) {
- console.error("Erreur d'inscription:", error);
+ console.error("Erreur d'inscription:", error)
}
- };
+ }
return (
<div className="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
@@ -124,7 +124,7 @@ function Register() {
</div>
</div>
</div>
- );
+ )
}
-export default Register;
+export default Register
diff --git a/flowsint-app/src/renderer/src/stores/analysis-panel-store.ts b/flowsint-app/src/renderer/src/stores/analysis-panel-store.ts
index fa8bf3d2..f9f6eb7c 100644
--- a/flowsint-app/src/renderer/src/stores/analysis-panel-store.ts
+++ b/flowsint-app/src/renderer/src/stores/analysis-panel-store.ts
@@ -1,5 +1,5 @@
-import { create } from "zustand"
-import { persist } from "zustand/middleware"
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
interface AnalysisPanelStore {
currentAnalysisId: string | null
@@ -10,11 +10,11 @@ export const useAnalysisPanelStore = create<AnalysisPanelStore>()(
persist(
(set) => ({
currentAnalysisId: null,
- setCurrentAnalysisId: (id) => set({ currentAnalysisId: id }),
+ setCurrentAnalysisId: (id) => set({ currentAnalysisId: id })
}),
{
- name: "currentAnalysisId",
- partialize: (state) => ({ currentAnalysisId: state.currentAnalysisId }),
+ name: 'currentAnalysisId',
+ partialize: (state) => ({ currentAnalysisId: state.currentAnalysisId })
}
)
-)
\ No newline at end of file
+)
diff --git a/flowsint-app/src/renderer/src/stores/auth-store.ts b/flowsint-app/src/renderer/src/stores/auth-store.ts
index f3a20932..f13ed3c3 100644
--- a/flowsint-app/src/renderer/src/stores/auth-store.ts
+++ b/flowsint-app/src/renderer/src/stores/auth-store.ts
@@ -1,76 +1,74 @@
// src/store/auth-store.ts
-import { create } from 'zustand';
-import { persist, createJSONStorage } from 'zustand/middleware';
+import { create } from 'zustand'
+import { persist, createJSONStorage } from 'zustand/middleware'
export interface User {
- id: string;
- username: string;
- email: string;
+ id: string
+ username: string
+ email: string
}
interface AuthState {
- token: string | null;
- user: User | null;
- isAuthenticated: boolean;
- setAuth: (token: string, user: User) => void;
- logout: () => void;
+ token: string | null
+ user: User | null
+ isAuthenticated: boolean
+ setAuth: (token: string, user: User) => void
+ logout: () => void
}
// Create a custom storage that handles cross-tab synchronization
const createCrossTabStorage = () => {
- const storage = createJSONStorage(() => localStorage);
-
- // Listen for storage changes from other tabs
- if (typeof window !== 'undefined') {
- window.addEventListener('storage', (event) => {
- if (event.key === 'auth-storage') {
- try {
- // Force a re-render when auth state changes in another tab
- const parsed = JSON.parse(event.newValue || '{}');
- if (parsed.state) {
- useAuthStore.setState(parsed.state);
- }
- } catch (error) {
- console.error('Failed to parse cross-tab auth state:', error);
- }
- }
- });
- }
-
- return storage;
-};
+ const storage = createJSONStorage(() => localStorage)
-export const useAuthStore = create<AuthState>()(
- persist(
- (set) => ({
- token: null,
- user: null,
- isAuthenticated: false,
- setAuth: (token, user) =>
- set({ token, user, isAuthenticated: true }),
- logout: () =>
- set({ token: null, user: null, isAuthenticated: false }),
- }),
- {
- name: 'auth-storage',
- storage: createCrossTabStorage(),
+ // Listen for storage changes from other tabs
+ if (typeof window !== 'undefined') {
+ window.addEventListener('storage', (event) => {
+ if (event.key === 'auth-storage') {
+ try {
+ // Force a re-render when auth state changes in another tab
+ const parsed = JSON.parse(event.newValue || '{}')
+ if (parsed.state) {
+ useAuthStore.setState(parsed.state)
+ }
+ } catch (error) {
+ console.error('Failed to parse cross-tab auth state:', error)
}
- )
-);
+ }
+ })
+ }
+
+ return storage
+}
+
+export const useAuthStore = create<AuthState>()(
+ persist(
+ (set) => ({
+ token: null,
+ user: null,
+ isAuthenticated: false,
+ setAuth: (token, user) => set({ token, user, isAuthenticated: true }),
+ logout: () => set({ token: null, user: null, isAuthenticated: false })
+ }),
+ {
+ name: 'auth-storage',
+ storage: createCrossTabStorage()
+ }
+ )
+)
// Initialize auth state from session storage on app load
if (typeof window !== 'undefined') {
- const storedAuth = localStorage.getItem('auth-storage');
- if (storedAuth) {
- try {
- const parsedAuth = JSON.parse(storedAuth);
- if (parsedAuth.state) {
- useAuthStore.setState(parsedAuth.state);
- }
- } catch (error) {
- console.error('Failed to parse stored auth state:', error);
- // Clear corrupted storage
- localStorage.removeItem('auth-storage');
- }
+ const storedAuth = localStorage.getItem('auth-storage')
+ if (storedAuth) {
+ try {
+ const parsedAuth = JSON.parse(storedAuth)
+ if (parsedAuth.state) {
+ useAuthStore.setState(parsedAuth.state)
+ }
+ } catch (error) {
+ console.error('Failed to parse stored auth state:', error)
+ // Clear corrupted storage
+ localStorage.removeItem('auth-storage')
}
+ }
}
diff --git a/flowsint-app/src/renderer/src/stores/flow-store.ts b/flowsint-app/src/renderer/src/stores/flow-store.ts
index 1e88a1ec..21ce4c58 100644
--- a/flowsint-app/src/renderer/src/stores/flow-store.ts
+++ b/flowsint-app/src/renderer/src/stores/flow-store.ts
@@ -1,18 +1,18 @@
-import { create } from "zustand"
+import { create } from 'zustand'
import {
- type Node,
- type Edge,
- type OnNodesChange,
- type OnEdgesChange,
- type OnConnect,
- type Connection,
- type EdgeMarker,
- MarkerType,
- applyNodeChanges,
- applyEdgeChanges
-} from "@xyflow/react"
-import { toast } from "sonner"
-import { type TransformNodeData } from "@/types/transform"
+ type Node,
+ type Edge,
+ type OnNodesChange,
+ type OnEdgesChange,
+ type OnConnect,
+ type Connection,
+ type EdgeMarker,
+ MarkerType,
+ applyNodeChanges,
+ applyEdgeChanges
+} from '@xyflow/react'
+import { toast } from 'sonner'
+import { type TransformNodeData } from '@/types/transform'
export type NodeData = TransformNodeData
@@ -20,41 +20,41 @@ export type FlowNode = Node<NodeData>
export type FlowEdge = Edge
export interface TransformState {
- // Node State
- nodes: FlowNode[]
- selectedNode: FlowNode | null
- // Edge State
- edges: FlowEdge[]
- // UI State
- loading: boolean
- openParamsDialog: boolean
- openFlowSheet: boolean
- // Node Actions
- setNodes: (nodes: FlowNode[] | ((prev: FlowNode[]) => FlowNode[])) => void
- onNodesChange: OnNodesChange
- setSelectedNode: (node: FlowNode | null) => void
- deleteNode: (nodeId: string) => void
- updateNode: (node: FlowNode) => void
- // Edge Actions
- setEdges: (edges: FlowEdge[] | ((prev: FlowEdge[]) => FlowEdge[])) => void
- onEdgesChange: OnEdgesChange
- onConnect: OnConnect
- // UI Actions
- setLoading: (loading: boolean) => void
- setOpenParamsDialog: (openParamsDialog: boolean, node?: FlowNode) => void
- setOpenFlowSheet: (openFlowSheet: boolean, node?: FlowNode) => void
+ // Node State
+ nodes: FlowNode[]
+ selectedNode: FlowNode | null
+ // Edge State
+ edges: FlowEdge[]
+ // UI State
+ loading: boolean
+ openParamsDialog: boolean
+ openFlowSheet: boolean
+ // Node Actions
+ setNodes: (nodes: FlowNode[] | ((prev: FlowNode[]) => FlowNode[])) => void
+ onNodesChange: OnNodesChange
+ setSelectedNode: (node: FlowNode | null) => void
+ deleteNode: (nodeId: string) => void
+ updateNode: (node: FlowNode) => void
+ // Edge Actions
+ setEdges: (edges: FlowEdge[] | ((prev: FlowEdge[]) => FlowEdge[])) => void
+ onEdgesChange: OnEdgesChange
+ onConnect: OnConnect
+ // UI Actions
+ setLoading: (loading: boolean) => void
+ setOpenParamsDialog: (openParamsDialog: boolean, node?: FlowNode) => void
+ setOpenFlowSheet: (openFlowSheet: boolean, node?: FlowNode) => void
}
// ================================
// DEFAULT STYLES & CONFIGURATION
// ================================
-const defaultEdgeStyle = { stroke: "#64748b" }
+const defaultEdgeStyle = { stroke: '#64748b' }
const defaultMarkerEnd: EdgeMarker = {
- type: MarkerType.ArrowClosed,
- width: 15,
- height: 15,
- color: "#64748b",
+ type: MarkerType.ArrowClosed,
+ width: 15,
+ height: 15,
+ color: '#64748b'
}
// ================================
@@ -62,92 +62,92 @@ const defaultMarkerEnd: EdgeMarker = {
// ================================
export const useFlowStore = create<TransformState>((set, get) => ({
- // ================================
- // STATE INITIALIZATION
- // ================================
- // Node State
- nodes: [] as FlowNode[],
- selectedNode: null,
- // Edge State
- edges: [] as FlowEdge[],
- // UI State
- loading: false,
- openParamsDialog: false,
- openFlowSheet: false,
- // ================================
- // NODE ACTIONS
- // ================================
- setNodes: (nodes) => set({ nodes: typeof nodes === 'function' ? nodes(get().nodes) : nodes }),
- onNodesChange: (changes) => {
- set({
- nodes: applyNodeChanges(changes, get().nodes) as FlowNode[],
- })
- },
- setSelectedNode: (node) => set({ selectedNode: node }),
- deleteNode: (nodeId) => {
- const { nodes, edges } = get()
- set({
- nodes: nodes.filter((node) => node.id !== nodeId),
- edges: edges.filter((edge) => edge.source !== nodeId && edge.target !== nodeId),
- selectedNode: nodes.find((node) => node.id === nodeId) ? null : get().selectedNode
- })
- },
- updateNode: (node) => {
- set({
- nodes: get().nodes.map((n) => n.id === node.id ? node : n),
- })
- },
- // ================================
- // EDGE ACTIONS
- // ================================
- setEdges: (edges) => set({ edges: typeof edges === 'function' ? edges(get().edges) : edges }),
- onEdgesChange: (changes) => {
- set({
- edges: applyEdgeChanges(changes, get().edges),
- })
- },
- onConnect: (connection: Connection) => {
- if ([connection.targetHandle, "Any"].includes(connection.sourceHandle)) {
- toast.error(`Cannot connect ${connection.sourceHandle} to ${connection.targetHandle}.`)
- return
- }
- const edge: FlowEdge = {
- id: `${connection.source}-${connection.target}`,
- source: connection.source!,
- target: connection.target!,
- sourceHandle: connection.sourceHandle,
- targetHandle: connection.targetHandle,
- style: defaultEdgeStyle,
- markerEnd: defaultMarkerEnd,
- }
- set({
- edges: [...get().edges, edge],
- })
- },
- // ================================
- // UI ACTIONS
- // ================================
- setLoading: (loading) => set({ loading }),
- setOpenParamsDialog: (openParamsDialog, node) => {
- // Only allow opening the dialog if there's a selected node
- if (node) {
- set({ selectedNode: node })
- }
- if (openParamsDialog && !get().selectedNode) {
- toast.error("Please select a node first to configure its parameters.")
- return
- }
- set({ openParamsDialog })
- },
- setOpenFlowSheet: (openFlowSheet, node) => {
- // Only allow opening the dialog if there's a selected node
- if (node) {
- set({ selectedNode: node })
- }
- if (openFlowSheet && !get().selectedNode) {
- toast.error("Please select a node first to add a connector.")
- return
- }
- set({ openFlowSheet })
+ // ================================
+ // STATE INITIALIZATION
+ // ================================
+ // Node State
+ nodes: [] as FlowNode[],
+ selectedNode: null,
+ // Edge State
+ edges: [] as FlowEdge[],
+ // UI State
+ loading: false,
+ openParamsDialog: false,
+ openFlowSheet: false,
+ // ================================
+ // NODE ACTIONS
+ // ================================
+ setNodes: (nodes) => set({ nodes: typeof nodes === 'function' ? nodes(get().nodes) : nodes }),
+ onNodesChange: (changes) => {
+ set({
+ nodes: applyNodeChanges(changes, get().nodes) as FlowNode[]
+ })
+ },
+ setSelectedNode: (node) => set({ selectedNode: node }),
+ deleteNode: (nodeId) => {
+ const { nodes, edges } = get()
+ set({
+ nodes: nodes.filter((node) => node.id !== nodeId),
+ edges: edges.filter((edge) => edge.source !== nodeId && edge.target !== nodeId),
+ selectedNode: nodes.find((node) => node.id === nodeId) ? null : get().selectedNode
+ })
+ },
+ updateNode: (node) => {
+ set({
+ nodes: get().nodes.map((n) => (n.id === node.id ? node : n))
+ })
+ },
+ // ================================
+ // EDGE ACTIONS
+ // ================================
+ setEdges: (edges) => set({ edges: typeof edges === 'function' ? edges(get().edges) : edges }),
+ onEdgesChange: (changes) => {
+ set({
+ edges: applyEdgeChanges(changes, get().edges)
+ })
+ },
+ onConnect: (connection: Connection) => {
+ if ([connection.targetHandle, 'Any'].includes(connection.sourceHandle)) {
+ toast.error(`Cannot connect ${connection.sourceHandle} to ${connection.targetHandle}.`)
+ return
}
+ const edge: FlowEdge = {
+ id: `${connection.source}-${connection.target}`,
+ source: connection.source!,
+ target: connection.target!,
+ sourceHandle: connection.sourceHandle,
+ targetHandle: connection.targetHandle,
+ style: defaultEdgeStyle,
+ markerEnd: defaultMarkerEnd
+ }
+ set({
+ edges: [...get().edges, edge]
+ })
+ },
+ // ================================
+ // UI ACTIONS
+ // ================================
+ setLoading: (loading) => set({ loading }),
+ setOpenParamsDialog: (openParamsDialog, node) => {
+ // Only allow opening the dialog if there's a selected node
+ if (node) {
+ set({ selectedNode: node })
+ }
+ if (openParamsDialog && !get().selectedNode) {
+ toast.error('Please select a node first to configure its parameters.')
+ return
+ }
+ set({ openParamsDialog })
+ },
+ setOpenFlowSheet: (openFlowSheet, node) => {
+ // Only allow opening the dialog if there's a selected node
+ if (node) {
+ set({ selectedNode: node })
+ }
+ if (openFlowSheet && !get().selectedNode) {
+ toast.error('Please select a node first to add a connector.')
+ return
+ }
+ set({ openFlowSheet })
+ }
}))
diff --git a/flowsint-app/src/renderer/src/stores/graph-controls-store.ts b/flowsint-app/src/renderer/src/stores/graph-controls-store.ts
index 3ff60f15..c98c9413 100644
--- a/flowsint-app/src/renderer/src/stores/graph-controls-store.ts
+++ b/flowsint-app/src/renderer/src/stores/graph-controls-store.ts
@@ -1,36 +1,36 @@
-import { create } from 'zustand';
-import { persist } from 'zustand/middleware';
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
type GraphControlsStore = {
- view: 'force' | 'hierarchy' | 'table' | 'map' | 'relationships';
- isLassoActive: boolean;
- zoomToFit: () => void;
- zoomIn: () => void;
- zoomOut: () => void;
- onLayout: (layout: any) => void;
- setActions: (actions: Partial<GraphControlsStore>) => void;
- refetchGraph: () => void;
- setView: (view: 'force' | 'hierarchy' | 'table' | 'map' | 'relationships') => void;
- setIsLassoActive: (active: boolean) => void
-};
+ view: 'force' | 'hierarchy' | 'table' | 'map' | 'relationships'
+ isLassoActive: boolean
+ zoomToFit: () => void
+ zoomIn: () => void
+ zoomOut: () => void
+ onLayout: (layout: any) => void
+ setActions: (actions: Partial<GraphControlsStore>) => void
+ refetchGraph: () => void
+ setView: (view: 'force' | 'hierarchy' | 'table' | 'map' | 'relationships') => void
+ setIsLassoActive: (active: boolean) => void
+}
export const useGraphControls = create<GraphControlsStore>()(
- persist(
- (set) => ({
- view: 'hierarchy',
- isLassoActive: false,
- zoomToFit: () => { },
- zoomIn: () => { },
- zoomOut: () => { },
- onLayout: () => { },
- setActions: (actions) => set(actions),
- refetchGraph: () => { },
- setView: (view) => set({ view }),
- setIsLassoActive: (active) => set({ isLassoActive: active })
- }),
- {
- name: 'graph-controls-storage',
- partialize: (state) => ({ view: state.view }),
- }
- )
-);
+ persist(
+ (set) => ({
+ view: 'hierarchy',
+ isLassoActive: false,
+ zoomToFit: () => {},
+ zoomIn: () => {},
+ zoomOut: () => {},
+ onLayout: () => {},
+ setActions: (actions) => set(actions),
+ refetchGraph: () => {},
+ setView: (view) => set({ view }),
+ setIsLassoActive: (active) => set({ isLassoActive: active })
+ }),
+ {
+ name: 'graph-controls-storage',
+ partialize: (state) => ({ view: state.view })
+ }
+ )
+)
diff --git a/flowsint-app/src/renderer/src/stores/graph-navigation-store.ts b/flowsint-app/src/renderer/src/stores/graph-navigation-store.ts
index 54a228ff..663595c8 100644
--- a/flowsint-app/src/renderer/src/stores/graph-navigation-store.ts
+++ b/flowsint-app/src/renderer/src/stores/graph-navigation-store.ts
@@ -9,5 +9,5 @@ interface GraphNavigationState {
export const useGraphNavigationStore = create<GraphNavigationState>((set) => ({
activeTab: 'entities',
setActiveTab: (tab: string) => set({ activeTab: tab }),
- resetTabs: () => set({ activeTab: 'entities' }),
-}))
\ No newline at end of file
+ resetTabs: () => set({ activeTab: 'entities' })
+}))
diff --git a/flowsint-app/src/renderer/src/stores/graph-settings-store.ts b/flowsint-app/src/renderer/src/stores/graph-settings-store.ts
index e50243cb..883d9d94 100644
--- a/flowsint-app/src/renderer/src/stores/graph-settings-store.ts
+++ b/flowsint-app/src/renderer/src/stores/graph-settings-store.ts
@@ -1,327 +1,344 @@
-import { create } from 'zustand';
-import { persist } from 'zustand/middleware';
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
// Centralized default settings organized by categories
const DEFAULT_SETTINGS = {
- information: {
-
+ information: {},
+ general: {
+ showFlow: {
+ type: 'boolean',
+ value: true,
+ description: 'Display Flo, your AI assistant.'
},
- general: {
- showFlow: {
- type: "boolean",
- value: true,
- description: "Display Flo, your AI assistant."
- },
- // showMinimap: {
- // type: "boolean",
- // value: true,
- // description: "Display the MiniMap on the graph panel."
- // },
- graphViewerThreshold: {
- type: "select",
- value: 800,
- options: [
- { value: 100, label: "100" },
- { value: 400, label: "400" },
- { value: 800, label: "800" },
- { value: 2000, label: "2000" }
- ],
- description: "Threshold to switch from general graph to less interactive but more performant) viewer."
- },
-
+ // showMinimap: {
+ // type: "boolean",
+ // value: true,
+ // description: "Display the MiniMap on the graph panel."
+ // },
+ graphViewerThreshold: {
+ type: 'select',
+ value: 800,
+ options: [
+ { value: 100, label: '100' },
+ { value: 400, label: '400' },
+ { value: 800, label: '800' },
+ { value: 2000, label: '2000' }
+ ],
+ description:
+ 'Threshold to switch from general graph to less interactive but more performant) viewer.'
+ }
+ },
+ graph: {
+ nodeSize: {
+ type: 'number',
+ value: 14,
+ min: 1,
+ max: 100,
+ step: 0.1,
+ description: 'Defines the width of the link between two nodes.'
},
- graph: {
- nodeSize: {
- type: "number",
- value: 14,
- min: 1,
- max: 100,
- step: 0.1,
- description: "Defines the width of the link between two nodes."
- },
- linkWidth: {
- type: "number",
- value: 2,
- min: 1,
- max: 10,
- step: 0.1,
- description: "Defines the width of the link between two nodes."
- },
- dagLevelDistance: {
- type: "number",
- value: 50,
- min: 0,
- max: 100,
- step: 1,
- description: "Distance between different graph depths when using DAG (directed acyclic graph) layout mode"
- },
- linkDirectionalArrowRelPos: {
- type: "number",
- value: 1,
- min: 0,
- max: 1,
- step: 0.01,
- description: "Position of directional arrows along the link line (0 = source node, 1 = target node, 0.5 = middle)"
- },
- linkDirectionalArrowLength: {
- type: "number",
- value: 3,
- min: 1,
- max: 100,
- step: 0.1,
- description: "Length of the arrow heads that indicate link direction"
- },
- linkDirectionalParticleSpeed: {
- type: "number",
- value: 0.005,
- min: 0,
- max: 0.05,
- step: 0.001,
- description: "Speed of moving particles along links (higher = faster movement)"
- },
- cooldownTicks: {
- type: "number",
- value: 200,
- min: 50,
- max: 1000,
- step: 10,
- description: "Number of simulation frames to render before stopping and freezing the layout"
- },
- cooldownTime: {
- type: "number",
- value: 15000,
- min: 1000,
- max: 60000,
- step: 1000,
- description: "Maximum time in milliseconds to run the simulation before stopping (15000 = 15 seconds)"
- },
- d3AlphaDecay: {
- type: "number",
- value: 0.045,
- min: 0,
- max: 0.3,
- step: 0.005,
- description: "Rate at which the simulation intensity decays (higher = faster convergence, lower = longer simulation)"
- },
- d3AlphaMin: {
- type: "number",
- value: 0,
- min: 0,
- max: 0.1,
- step: 0.001,
- description: "Minimum simulation intensity threshold - simulation stops when reaching this value"
- },
- d3VelocityDecay: {
- type: "number",
- value: 0.41,
- min: 0,
- max: 1,
- step: 0.01,
- description: "Velocity decay factor that simulates friction/resistance (higher = more damping, nodes slow down faster)"
- },
- warmupTicks: {
- type: "number",
- value: 0,
- min: 0,
- max: 100,
- step: 1,
- description: "Number of simulation cycles to run in background before starting to render (improves initial layout)"
- }
+ linkWidth: {
+ type: 'number',
+ value: 2,
+ min: 1,
+ max: 10,
+ step: 0.1,
+ description: 'Defines the width of the link between two nodes.'
},
-};
-
-// Force Presets
-const FORCE_PRESETS = {
- 'Tight Clusters': {
- d3AlphaDecay: 0.1,
- d3VelocityDecay: 0.8,
- cooldownTicks: 300,
- cooldownTime: 20000
+ dagLevelDistance: {
+ type: 'number',
+ value: 50,
+ min: 0,
+ max: 100,
+ step: 1,
+ description:
+ 'Distance between different graph depths when using DAG (directed acyclic graph) layout mode'
+ },
+ linkDirectionalArrowRelPos: {
+ type: 'number',
+ value: 1,
+ min: 0,
+ max: 1,
+ step: 0.01,
+ description:
+ 'Position of directional arrows along the link line (0 = source node, 1 = target node, 0.5 = middle)'
+ },
+ linkDirectionalArrowLength: {
+ type: 'number',
+ value: 3,
+ min: 1,
+ max: 100,
+ step: 0.1,
+ description: 'Length of the arrow heads that indicate link direction'
+ },
+ linkDirectionalParticleSpeed: {
+ type: 'number',
+ value: 0.005,
+ min: 0,
+ max: 0.05,
+ step: 0.001,
+ description: 'Speed of moving particles along links (higher = faster movement)'
+ },
+ cooldownTicks: {
+ type: 'number',
+ value: 200,
+ min: 50,
+ max: 1000,
+ step: 10,
+ description: 'Number of simulation frames to render before stopping and freezing the layout'
+ },
+ cooldownTime: {
+ type: 'number',
+ value: 15000,
+ min: 1000,
+ max: 60000,
+ step: 1000,
+ description:
+ 'Maximum time in milliseconds to run the simulation before stopping (15000 = 15 seconds)'
},
- 'Compact Network': {
- d3AlphaDecay: 0.08,
- d3VelocityDecay: 0.7,
- cooldownTicks: 250,
- cooldownTime: 18000
+ d3AlphaDecay: {
+ type: 'number',
+ value: 0.045,
+ min: 0,
+ max: 0.3,
+ step: 0.005,
+ description:
+ 'Rate at which the simulation intensity decays (higher = faster convergence, lower = longer simulation)'
},
- 'Balanced Layout': {
- d3AlphaDecay: 0.06,
- d3VelocityDecay: 0.6,
- cooldownTicks: 200,
- cooldownTime: 15000
+ d3AlphaMin: {
+ type: 'number',
+ value: 0,
+ min: 0,
+ max: 0.1,
+ step: 0.001,
+ description:
+ 'Minimum simulation intensity threshold - simulation stops when reaching this value'
},
- 'Loose Organic': {
- d3AlphaDecay: 0.04,
- d3VelocityDecay: 0.4,
- cooldownTicks: 150,
- cooldownTime: 12000
+ d3VelocityDecay: {
+ type: 'number',
+ value: 0.41,
+ min: 0,
+ max: 1,
+ step: 0.01,
+ description:
+ 'Velocity decay factor that simulates friction/resistance (higher = more damping, nodes slow down faster)'
},
- 'High Energy': {
- d3AlphaDecay: 0.02,
- d3VelocityDecay: 0.3,
- cooldownTicks: 100,
- cooldownTime: 10000
+ warmupTicks: {
+ type: 'number',
+ value: 0,
+ min: 0,
+ max: 100,
+ step: 1,
+ description:
+ 'Number of simulation cycles to run in background before starting to render (improves initial layout)'
}
-};
+ }
+}
+
+// Force Presets
+const FORCE_PRESETS = {
+ 'Tight Clusters': {
+ d3AlphaDecay: 0.1,
+ d3VelocityDecay: 0.8,
+ cooldownTicks: 300,
+ cooldownTime: 20000
+ },
+ 'Compact Network': {
+ d3AlphaDecay: 0.08,
+ d3VelocityDecay: 0.7,
+ cooldownTicks: 250,
+ cooldownTime: 18000
+ },
+ 'Balanced Layout': {
+ d3AlphaDecay: 0.06,
+ d3VelocityDecay: 0.6,
+ cooldownTicks: 200,
+ cooldownTime: 15000
+ },
+ 'Loose Organic': {
+ d3AlphaDecay: 0.04,
+ d3VelocityDecay: 0.4,
+ cooldownTicks: 150,
+ cooldownTime: 12000
+ },
+ 'High Energy': {
+ d3AlphaDecay: 0.02,
+ d3VelocityDecay: 0.3,
+ cooldownTicks: 100,
+ cooldownTime: 10000
+ }
+}
type GraphGeneralSettingsStore = {
- // Settings state
- settings: typeof DEFAULT_SETTINGS
- forceSettings: any
- updateSetting: (category: string, key: string, value: any) => void
- resetSettings: () => void
- getSettings: () => Record<string, any>
- getCategorySettings: (category: string) => Record<string, any>
+ // Settings state
+ settings: typeof DEFAULT_SETTINGS
+ forceSettings: any
+ updateSetting: (category: string, key: string, value: any) => void
+ resetSettings: () => void
+ getSettings: () => Record<string, any>
+ getCategorySettings: (category: string) => Record<string, any>
- // Force Presets
- currentPreset: string | null
- applyPreset: (presetName: string) => void
- getPresets: () => Record<string, any>
+ // Force Presets
+ currentPreset: string | null
+ applyPreset: (presetName: string) => void
+ getPresets: () => Record<string, any>
- // UI State
- settingsModalOpen: boolean
- setSettingsModalOpen: (open: boolean) => void
- keyboardShortcutsOpen: boolean
- setKeyboardShortcutsOpen: (open: boolean) => void
+ // UI State
+ settingsModalOpen: boolean
+ setSettingsModalOpen: (open: boolean) => void
+ keyboardShortcutsOpen: boolean
+ setKeyboardShortcutsOpen: (open: boolean) => void
- // Helper methods
- getSettingValue: (category: string, key: string) => any
- getSettingType: (category: string, key: string) => string | undefined
- getSettingOptions: (category: string, key: string) => { value: string; label: string }[] | undefined
- getSettingDescription: (category: string, key: string) => string | undefined
- getSettingConstraints: (category: string, key: string) => { min?: number; max?: number; step?: number } | undefined
-};
+ // Helper methods
+ getSettingValue: (category: string, key: string) => any
+ getSettingType: (category: string, key: string) => string | undefined
+ getSettingOptions: (
+ category: string,
+ key: string
+ ) => { value: string; label: string }[] | undefined
+ getSettingDescription: (category: string, key: string) => string | undefined
+ getSettingConstraints: (
+ category: string,
+ key: string
+ ) => { min?: number; max?: number; step?: number } | undefined
+}
export const useGraphSettingsStore = create<GraphGeneralSettingsStore>()(
- persist((set, get) => ({
- // Settings state
- settings: DEFAULT_SETTINGS,
- currentPreset: null,
- forceSettings: DEFAULT_SETTINGS.graph,
- // UI State
- settingsModalOpen: false,
- keyboardShortcutsOpen: false,
+ persist(
+ (set, get) => ({
+ // Settings state
+ settings: DEFAULT_SETTINGS,
+ currentPreset: null,
+ forceSettings: DEFAULT_SETTINGS.graph,
+ // UI State
+ settingsModalOpen: false,
+ keyboardShortcutsOpen: false,
- // Core methods
- updateSetting: (category, key, value) => set((state) => {
- const newSettings = {
- ...state.settings,
- [category]: {
- ...state.settings[category],
- [key]: {
- ...state.settings[category][key],
- value: value
- },
- },
- };
+ // Core methods
+ updateSetting: (category, key, value) =>
+ set((state) => {
+ const newSettings = {
+ ...state.settings,
+ [category]: {
+ ...state.settings[category],
+ [key]: {
+ ...state.settings[category][key],
+ value: value
+ }
+ }
+ }
- // Also update forceSettings if we're updating a force setting
- let newForceSettings = state.forceSettings;
- if (category === 'force') {
- newForceSettings = {
- ...state.forceSettings,
- [key]: {
- ...state.forceSettings[key],
- value: value
- }
- };
+ // Also update forceSettings if we're updating a force setting
+ let newForceSettings = state.forceSettings
+ if (category === 'force') {
+ newForceSettings = {
+ ...state.forceSettings,
+ [key]: {
+ ...state.forceSettings[key],
+ value: value
+ }
}
+ }
- return {
- settings: newSettings,
- forceSettings: newForceSettings,
- currentPreset: null, // Clear preset when manually changing settings
- };
+ return {
+ settings: newSettings,
+ forceSettings: newForceSettings,
+ currentPreset: null // Clear preset when manually changing settings
+ }
}),
- resetSettings: () => set({
- settings: DEFAULT_SETTINGS,
- forceSettings: DEFAULT_SETTINGS.graph,
- currentPreset: null
+ resetSettings: () =>
+ set({
+ settings: DEFAULT_SETTINGS,
+ forceSettings: DEFAULT_SETTINGS.graph,
+ currentPreset: null
}),
- getSettings: () => {
- const flatSettings: Record<string, any> = {};
- Object.entries(get().settings).forEach(([category, categorySettings]) => {
- Object.entries(categorySettings as Record<string, any>).forEach(([key, setting]) => {
- flatSettings[`${category}.${key}`] = (setting as any).value;
- });
- });
- return flatSettings;
- },
+ getSettings: () => {
+ const flatSettings: Record<string, any> = {}
+ Object.entries(get().settings).forEach(([category, categorySettings]) => {
+ Object.entries(categorySettings as Record<string, any>).forEach(([key, setting]) => {
+ flatSettings[`${category}.${key}`] = (setting as any).value
+ })
+ })
+ return flatSettings
+ },
- getCategorySettings: (category: string) => {
- const categorySettings: Record<string, any> = {};
- const settings = get().settings[category];
- if (settings) {
- Object.entries(settings as Record<string, any>).forEach(([key, setting]) => {
- categorySettings[key] = (setting as any).value;
- });
- }
- return categorySettings;
- },
+ getCategorySettings: (category: string) => {
+ const categorySettings: Record<string, any> = {}
+ const settings = get().settings[category]
+ if (settings) {
+ Object.entries(settings as Record<string, any>).forEach(([key, setting]) => {
+ categorySettings[key] = (setting as any).value
+ })
+ }
+ return categorySettings
+ },
- // Force Presets
- getPresets: () => FORCE_PRESETS,
+ // Force Presets
+ getPresets: () => FORCE_PRESETS,
- applyPreset: (presetName: string) => {
- const preset = FORCE_PRESETS[presetName as keyof typeof FORCE_PRESETS];
- if (!preset) return;
+ applyPreset: (presetName: string) => {
+ const preset = FORCE_PRESETS[presetName as keyof typeof FORCE_PRESETS]
+ if (!preset) return
- set((state) => {
- const newSettings = { ...state.settings };
- const newForceSettings = { ...state.forceSettings };
+ set((state) => {
+ const newSettings = { ...state.settings }
+ const newForceSettings = { ...state.forceSettings }
- Object.entries(preset).forEach(([key, value]) => {
- if (newSettings.graph[key]) {
- newSettings.graph[key] = {
- ...newSettings.graph[key],
- value: value
- };
- }
- if (newForceSettings[key]) {
- newForceSettings[key] = {
- ...newForceSettings[key],
- value: value
- };
- }
- });
+ Object.entries(preset).forEach(([key, value]) => {
+ if (newSettings.graph[key]) {
+ newSettings.graph[key] = {
+ ...newSettings.graph[key],
+ value: value
+ }
+ }
+ if (newForceSettings[key]) {
+ newForceSettings[key] = {
+ ...newForceSettings[key],
+ value: value
+ }
+ }
+ })
- return {
- settings: newSettings,
- forceSettings: newForceSettings,
- currentPreset: presetName
- };
- });
- },
+ return {
+ settings: newSettings,
+ forceSettings: newForceSettings,
+ currentPreset: presetName
+ }
+ })
+ },
- // UI State methods
- setSettingsModalOpen: (open) => set({ settingsModalOpen: open }),
- setKeyboardShortcutsOpen: (open) => set({ keyboardShortcutsOpen: open }),
+ // UI State methods
+ setSettingsModalOpen: (open) => set({ settingsModalOpen: open }),
+ setKeyboardShortcutsOpen: (open) => set({ keyboardShortcutsOpen: open }),
- // Helper methods
- getSettingValue: (category: string, key: string) => get().settings[category]?.[key]?.value,
- getSettingType: (category: string, key: string) => get().settings[category]?.[key]?.type,
- getSettingOptions: (category: string, key: string) => get().settings[category]?.[key]?.options,
- getSettingDescription: (category: string, key: string) => get().settings[category]?.[key]?.description,
- getSettingConstraints: (category: string, key: string) => {
- const setting = get().settings[category]?.[key];
- if (setting && 'min' in setting) {
- return {
- min: setting.min,
- max: setting.max,
- step: setting.step
- };
- }
- return undefined;
+ // Helper methods
+ getSettingValue: (category: string, key: string) => get().settings[category]?.[key]?.value,
+ getSettingType: (category: string, key: string) => get().settings[category]?.[key]?.type,
+ getSettingOptions: (category: string, key: string) =>
+ get().settings[category]?.[key]?.options,
+ getSettingDescription: (category: string, key: string) =>
+ get().settings[category]?.[key]?.description,
+ getSettingConstraints: (category: string, key: string) => {
+ const setting = get().settings[category]?.[key]
+ if (setting && 'min' in setting) {
+ return {
+ min: setting.min,
+ max: setting.max,
+ step: setting.step
+ }
}
+ return undefined
+ }
}),
- {
- name: 'graph-settings-storage',
- partialize: (state) => ({
- settings: state.settings,
- forceSettings: state.forceSettings,
- currentPreset: state.currentPreset,
- }),
- }
- ));
+ {
+ name: 'graph-settings-storage',
+ partialize: (state) => ({
+ settings: state.settings,
+ forceSettings: state.forceSettings,
+ currentPreset: state.currentPreset
+ })
+ }
+ )
+)
diff --git a/flowsint-app/src/renderer/src/stores/graph-store.ts b/flowsint-app/src/renderer/src/stores/graph-store.ts
index f27d7324..de69f3c8 100644
--- a/flowsint-app/src/renderer/src/stores/graph-store.ts
+++ b/flowsint-app/src/renderer/src/stores/graph-store.ts
@@ -1,369 +1,376 @@
-import { create } from "zustand"
-import { persist } from "zustand/middleware"
-import type { GraphNode, GraphEdge, NodeData } from "@/types"
-import { type ActionItem } from "@/lib/action-items"
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import type { GraphNode, GraphEdge, NodeData } from '@/types'
+import { type ActionItem } from '@/lib/action-items'
export type TypeFilter = {
- type: string
- checked: boolean
+ type: string
+ checked: boolean
}
export type Filters = {
- types: TypeFilter[]
+ types: TypeFilter[]
}
interface GraphState {
- // === Graph ===
- nodes: GraphNode[]
- edges: GraphEdge[]
- filteredNodes: GraphNode[]
- filteredEdges: GraphEdge[]
- setNodes: (nodes: GraphNode[]) => void
- setEdges: (edges: GraphEdge[]) => void
- addNode: (newNode: Partial<GraphNode>) => GraphNode
- addEdge: (newEdge: Partial<GraphEdge>) => GraphEdge
- removeNodes: (nodeIds: string[]) => void
- removeEdges: (edgeIds: string[]) => void
- updateGraphData: (nodes: GraphNode[], edges: GraphEdge[]) => void
- updateNode: (nodeId: string, updates: Partial<NodeData>) => void
- updateEdge: (edgeId: string, updates: Partial<GraphEdge>) => void
- reset: () => void
-
- // === Selection & Current ===
- currentNode: GraphNode | null
- selectedNodes: GraphNode[]
- setCurrentNode: (node: GraphNode | null) => void
- setSelectedNodes: (nodes: GraphNode[]) => void
- clearSelectedNodes: () => void
- toggleNodeSelection: (node: GraphNode, multiSelect?: boolean) => void
-
- // === Relation ===
- relatedNodeToAdd: GraphNode | null
- setRelatedNodeToAdd: (node: GraphNode | null) => void
-
- // === Dialogs ===
- openMainDialog: boolean
- openFormDialog: boolean
- openAddRelationDialog: boolean
- openMergeDialog: boolean
- openNodeEditorModal: boolean
- setOpenMainDialog: (open: boolean) => void
- setOpenFormDialog: (open: boolean) => void
- setOpenAddRelationDialog: (open: boolean) => void
- setOpenMergeDialog: (open: boolean) => void
- setOpenNodeEditorModal: (open: boolean) => void
-
- // === Action Type for Form ===
- currentNodeType: ActionItem | null
- setCurrentNodeType: (nodeType: ActionItem | null) => void
- handleOpenFormModal: (selectedItem: ActionItem | undefined) => void
-
- // === Action Type for Edit form ===
- handleEdit: (node: GraphNode) => void
-
- // === Filters ===
- filters: Filters
- setFilters: (filters: Filters) => void
- toggleTypeFilter: (filter: TypeFilter) => void
-
- // === Collapse/Expand logic ===
- toggleCollapse: (nodeId: string) => void
-
- // === Utils ===
- nodesLength: number
- edgesLength: number
- getNodesLength: () => number
- getEdgesLength: () => number
+ // === Graph ===
+ nodes: GraphNode[]
+ edges: GraphEdge[]
+ filteredNodes: GraphNode[]
+ filteredEdges: GraphEdge[]
+ setNodes: (nodes: GraphNode[]) => void
+ setEdges: (edges: GraphEdge[]) => void
+ addNode: (newNode: Partial<GraphNode>) => GraphNode
+ addEdge: (newEdge: Partial<GraphEdge>) => GraphEdge
+ removeNodes: (nodeIds: string[]) => void
+ removeEdges: (edgeIds: string[]) => void
+ updateGraphData: (nodes: GraphNode[], edges: GraphEdge[]) => void
+ updateNode: (nodeId: string, updates: Partial<NodeData>) => void
+ updateEdge: (edgeId: string, updates: Partial<GraphEdge>) => void
+ reset: () => void
+
+ // === Selection & Current ===
+ currentNode: GraphNode | null
+ selectedNodes: GraphNode[]
+ setCurrentNode: (node: GraphNode | null) => void
+ setSelectedNodes: (nodes: GraphNode[]) => void
+ clearSelectedNodes: () => void
+ toggleNodeSelection: (node: GraphNode, multiSelect?: boolean) => void
+
+ // === Relation ===
+ relatedNodeToAdd: GraphNode | null
+ setRelatedNodeToAdd: (node: GraphNode | null) => void
+
+ // === Dialogs ===
+ openMainDialog: boolean
+ openFormDialog: boolean
+ openAddRelationDialog: boolean
+ openMergeDialog: boolean
+ openNodeEditorModal: boolean
+ setOpenMainDialog: (open: boolean) => void
+ setOpenFormDialog: (open: boolean) => void
+ setOpenAddRelationDialog: (open: boolean) => void
+ setOpenMergeDialog: (open: boolean) => void
+ setOpenNodeEditorModal: (open: boolean) => void
+
+ // === Action Type for Form ===
+ currentNodeType: ActionItem | null
+ setCurrentNodeType: (nodeType: ActionItem | null) => void
+ handleOpenFormModal: (selectedItem: ActionItem | undefined) => void
+
+ // === Action Type for Edit form ===
+ handleEdit: (node: GraphNode) => void
+
+ // === Filters ===
+ filters: Filters
+ setFilters: (filters: Filters) => void
+ toggleTypeFilter: (filter: TypeFilter) => void
+
+ // === Collapse/Expand logic ===
+ toggleCollapse: (nodeId: string) => void
+
+ // === Utils ===
+ nodesLength: number
+ edgesLength: number
+ getNodesLength: () => number
+ getEdgesLength: () => number
}
// --- Helpers ---
const computeFilteredNodes = (nodes: GraphNode[], filters: Filters): GraphNode[] => {
- // types
- const areAllToggled = filters.types.every(t => t.checked)
- const areNoneToggled = filters.types.every(t => !t.checked)
- if (areNoneToggled || areAllToggled) return nodes
- const types = filters.types.filter(t => !t.checked).map(t => t.type)
- return nodes.filter((node) => !types.includes(node.data.type))
+ // types
+ const areAllToggled = filters.types.every((t) => t.checked)
+ const areNoneToggled = filters.types.every((t) => !t.checked)
+ if (areNoneToggled || areAllToggled) return nodes
+ const types = filters.types.filter((t) => !t.checked).map((t) => t.type)
+ return nodes.filter((node) => !types.includes(node.data.type))
}
const computeFilteredEdges = (edges: GraphEdge[], filteredNodes: GraphNode[]): GraphEdge[] => {
- const nodeIds = new Set(filteredNodes.map(n => n.id))
- return edges.filter(e => nodeIds.has(e.source) && nodeIds.has(e.target))
+ const nodeIds = new Set(filteredNodes.map((n) => n.id))
+ return edges.filter((e) => nodeIds.has(e.source) && nodeIds.has(e.target))
}
// --- Store ---
export const useGraphStore = create<GraphState>()(
- persist(
- (set, get) => ({
- // === Graph ===
- nodes: [],
- edges: [],
- filteredNodes: [],
- filteredEdges: [],
- getNodesLength: () => get().nodes.length,
- getEdgesLength: () => get().edges.length,
-
- setNodes: (nodes) => {
- const { filters, edges } = get()
- const filteredNodes = computeFilteredNodes(nodes, filters)
- const filteredEdges = computeFilteredEdges(edges, filteredNodes)
- set({ nodes, filteredNodes, filteredEdges })
- },
- setEdges: (edges) => {
- const { filters, nodes } = get()
- const filteredNodes = computeFilteredNodes(nodes, filters)
- const filteredEdges = computeFilteredEdges(edges, filteredNodes)
- set({ edges, filteredNodes, filteredEdges })
- },
-
- addNode: (newNode) => {
- const { nodes, edges, filters } = get()
- const nodeWithId: GraphNode = {
- id: newNode.id || `node-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
- position: { x: 0, y: 0 },
- ...newNode,
- } as GraphNode
- const newNodes = [...nodes, nodeWithId]
- const filteredNodes = computeFilteredNodes(newNodes, filters)
- const filteredEdges = computeFilteredEdges(edges, filteredNodes)
- set({ nodes: newNodes, currentNode: nodeWithId, filteredNodes, filteredEdges })
- return nodeWithId
- },
-
- addEdge: (newEdge) => {
- const { edges, nodes, filters } = get()
- const edgeWithId: GraphEdge = {
- id: newEdge.id || `edge-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
- ...newEdge,
- } as GraphEdge
- const newEdges = [...edges, edgeWithId]
- const filteredNodes = computeFilteredNodes(nodes, filters)
- const filteredEdges = computeFilteredEdges(newEdges, filteredNodes)
- set({ edges: newEdges, filteredNodes, filteredEdges })
- return edgeWithId
- },
-
- removeNodes: (nodeIds: string[]) => {
- const { nodes, edges, filters } = get()
- const newNodes = nodes.filter(n => !nodeIds.includes(n.id))
- const newEdges = edges.filter(e => !nodeIds.includes(e.source) && !nodeIds.includes(e.target))
- const filteredNodes = computeFilteredNodes(newNodes, filters)
- const filteredEdges = computeFilteredEdges(newEdges, filteredNodes)
- set({ nodes: newNodes, edges: newEdges, filteredNodes, filteredEdges })
- },
-
- removeEdges: (edgeIds: string[]) => {
- const { edges, nodes, filters } = get()
- const newEdges = edges.filter(e => !edgeIds.includes(e.id))
- const filteredNodes = computeFilteredNodes(nodes, filters)
- const filteredEdges = computeFilteredEdges(newEdges, filteredNodes)
- set({ edges: newEdges, filteredNodes, filteredEdges })
- },
-
- updateGraphData: (nodes, edges) => {
- const { filters } = get()
- const filteredNodes = computeFilteredNodes(nodes, filters)
- const filteredEdges = computeFilteredEdges(edges, filteredNodes)
- set({ nodes, edges, filteredNodes, filteredEdges })
- },
-
- updateNode: (nodeId, updates) => {
- const { nodes, edges, filters } = get()
- const updatedNodes = nodes.map(node =>
- node.id === nodeId ? { ...node, data: { ...node.data, ...updates } } : node
- )
- const filteredNodes = computeFilteredNodes(updatedNodes, filters)
- const filteredEdges = computeFilteredEdges(edges, filteredNodes)
- set({ nodes: updatedNodes, filteredNodes, filteredEdges })
- },
-
- updateEdge: (edgeId, updates) => {
- const { edges, nodes, filters } = get()
- const updatedEdges = edges.map(edge =>
- edge.id === edgeId ? { ...edge, data: { ...edge, ...updates } as GraphEdge } : edge
- )
- const filteredNodes = computeFilteredNodes(nodes, filters)
- const filteredEdges = computeFilteredEdges(updatedEdges, filteredNodes)
- set({ edges: updatedEdges, filteredNodes, filteredEdges })
- },
-
- // === Selection & Current ===
- currentNode: null,
- selectedNodes: [],
- setCurrentNode: (node) => {
- const { currentNode } = get()
- // Only update if the node is actually different
- if (currentNode?.id !== node?.id) {
- set({ currentNode: node })
- }
- },
- setSelectedNodes: (nodes) => set({ selectedNodes: nodes }),
- clearSelectedNodes: () => set({ selectedNodes: [], currentNode: null }),
- toggleNodeSelection: (node, multiSelect = false) => {
- const { selectedNodes, currentNode } = get()
- const isSelected = selectedNodes.some((n) => n.id === node.id)
- let newSelected: GraphNode[]
- let newCurrentNode = currentNode
-
- if (multiSelect) {
- newSelected = isSelected
- ? selectedNodes.filter((n) => n.id !== node.id)
- : [...selectedNodes, node]
- } else {
- newSelected = isSelected && selectedNodes.length === 1 ? [] : [node]
- // Only update currentNode if it's actually different
- if (!multiSelect) {
- newCurrentNode = isSelected ? null : node
- }
- }
-
- // Only update if there are actual changes
- const hasSelectionChanges = newSelected.length !== selectedNodes.length ||
- newSelected.some((n, i) => n.id !== selectedNodes[i]?.id)
- const hasCurrentNodeChanges = newCurrentNode?.id !== currentNode?.id
-
- if (hasSelectionChanges || hasCurrentNodeChanges) {
- set({
- selectedNodes: newSelected,
- currentNode: newCurrentNode,
- })
- }
- },
-
- // === Relation ===
- relatedNodeToAdd: null,
- setRelatedNodeToAdd: (node) => set({ relatedNodeToAdd: node }),
-
- // === Dialogs ===
- openMainDialog: false,
- openFormDialog: false,
- openAddRelationDialog: false,
- openMergeDialog: false,
- openNodeEditorModal: false,
- setOpenMainDialog: (open) => set({ openMainDialog: open }),
- setOpenFormDialog: (open) => set({ openFormDialog: open }),
- setOpenAddRelationDialog: (open) => set({ openAddRelationDialog: open }),
- setOpenMergeDialog: (open) => set({ openMergeDialog: open }),
- setOpenNodeEditorModal: (open) => set({ openNodeEditorModal: open }),
-
- // === Action Type for Edit form ===
- handleEdit: (node) => {
- const { currentNode, openNodeEditorModal } = get()
- // Only update if the node is actually different
- if (currentNode?.id !== node.id) {
- set({ currentNode: node, openNodeEditorModal: true })
- } else if (!openNodeEditorModal) {
- // Only open modal if it's not already open
- set({ openNodeEditorModal: true })
- }
- },
-
- // === Action Type for Form ===
- currentNodeType: null,
- setCurrentNodeType: (nodeType) => set({ currentNodeType: nodeType }),
- handleOpenFormModal: (selectedItem) => {
- if (!selectedItem) return
- set({
- currentNodeType: selectedItem,
- openMainDialog: false,
- openFormDialog: true,
- })
- },
-
- // === Filters ===
- filters: {
- types: [{
- type: "domain",
- checked: true
- }, {
- type: "ip",
- checked: true
- }, {
- type: "individual",
- checked: true
- }]
- },
- setFilters: (filters) => {
- const { nodes, edges } = get()
- const filteredNodes = computeFilteredNodes(nodes, filters)
- const filteredEdges = computeFilteredEdges(edges, filteredNodes)
- set({ filters, filteredNodes, filteredEdges })
- },
-
- toggleTypeFilter: (filter) => {
- const { filters, nodes, edges } = get()
- const newTypes = filters.types.map((f: TypeFilter) => {
- if (f.type === filter.type) return {
- type: f.type, checked: !f.checked
- }
- return f
- })
- const newFilters = { ...filters, types: newTypes }
- const filteredNodes = computeFilteredNodes(nodes, newFilters)
- const filteredEdges = computeFilteredEdges(edges, filteredNodes)
- set({ filters: newFilters, filteredNodes, filteredEdges })
- },
-
- // === Collapse/Expand logic ===
- toggleCollapse: (nodeId) => {
- const { nodes, edges, filters } = get()
- const node = nodes.find(n => n.id === nodeId)
- if (!node) return
- const isCollapsing = !node.collapsed
-
- const getDescendants = (parentId: string, accNodes: Set<string>, accEdges: Set<string>) => {
- edges.forEach(edge => {
- if (edge.source === parentId) {
- accEdges.add(edge.id)
- accNodes.add(edge.target)
- getDescendants(edge.target, accNodes, accEdges)
- }
- })
- }
-
- const descendantNodeIds = new Set<string>()
- const descendantEdgeIds = new Set<string>()
- getDescendants(nodeId, descendantNodeIds, descendantEdgeIds)
-
- const newNodes = nodes.map(n =>
- n.id === nodeId
- ? { ...n, collapsed: isCollapsing }
- : descendantNodeIds.has(n.id)
- ? { ...n, hidden: isCollapsing }
- : n
- )
- const newEdges = edges.map(e =>
- descendantEdgeIds.has(e.id)
- ? { ...e, hidden: isCollapsing }
- : e
- )
-
- const filteredNodes = computeFilteredNodes(newNodes, filters)
- const filteredEdges = computeFilteredEdges(newEdges, filteredNodes)
- set({ nodes: newNodes, edges: newEdges, filteredNodes, filteredEdges })
- },
-
- reset: () => {
- set({
- currentNode: null,
- selectedNodes: [],
- relatedNodeToAdd: null,
- openMainDialog: false,
- openFormDialog: false,
- openAddRelationDialog: false,
- openNodeEditorModal: false,
- currentNodeType: null,
- filteredNodes: get().nodes,
- filteredEdges: get().edges,
- })
- },
-
- // === Utils ===
- nodesLength: 0,
- edgesLength: 0,
- }),
- {
- name: "graph-store",
- partialize: (state) => ({ edgesLength: state.edgesLength }),
+ persist(
+ (set, get) => ({
+ // === Graph ===
+ nodes: [],
+ edges: [],
+ filteredNodes: [],
+ filteredEdges: [],
+ getNodesLength: () => get().nodes.length,
+ getEdgesLength: () => get().edges.length,
+
+ setNodes: (nodes) => {
+ const { filters, edges } = get()
+ const filteredNodes = computeFilteredNodes(nodes, filters)
+ const filteredEdges = computeFilteredEdges(edges, filteredNodes)
+ set({ nodes, filteredNodes, filteredEdges })
+ },
+ setEdges: (edges) => {
+ const { filters, nodes } = get()
+ const filteredNodes = computeFilteredNodes(nodes, filters)
+ const filteredEdges = computeFilteredEdges(edges, filteredNodes)
+ set({ edges, filteredNodes, filteredEdges })
+ },
+
+ addNode: (newNode) => {
+ const { nodes, edges, filters } = get()
+ const nodeWithId: GraphNode = {
+ id: newNode.id || `node-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
+ position: { x: 0, y: 0 },
+ ...newNode
+ } as GraphNode
+ const newNodes = [...nodes, nodeWithId]
+ const filteredNodes = computeFilteredNodes(newNodes, filters)
+ const filteredEdges = computeFilteredEdges(edges, filteredNodes)
+ set({ nodes: newNodes, currentNode: nodeWithId, filteredNodes, filteredEdges })
+ return nodeWithId
+ },
+
+ addEdge: (newEdge) => {
+ const { edges, nodes, filters } = get()
+ const edgeWithId: GraphEdge = {
+ id: newEdge.id || `edge-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
+ ...newEdge
+ } as GraphEdge
+ const newEdges = [...edges, edgeWithId]
+ const filteredNodes = computeFilteredNodes(nodes, filters)
+ const filteredEdges = computeFilteredEdges(newEdges, filteredNodes)
+ set({ edges: newEdges, filteredNodes, filteredEdges })
+ return edgeWithId
+ },
+
+ removeNodes: (nodeIds: string[]) => {
+ const { nodes, edges, filters } = get()
+ const newNodes = nodes.filter((n) => !nodeIds.includes(n.id))
+ const newEdges = edges.filter(
+ (e) => !nodeIds.includes(e.source) && !nodeIds.includes(e.target)
+ )
+ const filteredNodes = computeFilteredNodes(newNodes, filters)
+ const filteredEdges = computeFilteredEdges(newEdges, filteredNodes)
+ set({ nodes: newNodes, edges: newEdges, filteredNodes, filteredEdges })
+ },
+
+ removeEdges: (edgeIds: string[]) => {
+ const { edges, nodes, filters } = get()
+ const newEdges = edges.filter((e) => !edgeIds.includes(e.id))
+ const filteredNodes = computeFilteredNodes(nodes, filters)
+ const filteredEdges = computeFilteredEdges(newEdges, filteredNodes)
+ set({ edges: newEdges, filteredNodes, filteredEdges })
+ },
+
+ updateGraphData: (nodes, edges) => {
+ const { filters } = get()
+ const filteredNodes = computeFilteredNodes(nodes, filters)
+ const filteredEdges = computeFilteredEdges(edges, filteredNodes)
+ set({ nodes, edges, filteredNodes, filteredEdges })
+ },
+
+ updateNode: (nodeId, updates) => {
+ const { nodes, edges, filters } = get()
+ const updatedNodes = nodes.map((node) =>
+ node.id === nodeId ? { ...node, data: { ...node.data, ...updates } } : node
+ )
+ const filteredNodes = computeFilteredNodes(updatedNodes, filters)
+ const filteredEdges = computeFilteredEdges(edges, filteredNodes)
+ set({ nodes: updatedNodes, filteredNodes, filteredEdges })
+ },
+
+ updateEdge: (edgeId, updates) => {
+ const { edges, nodes, filters } = get()
+ const updatedEdges = edges.map((edge) =>
+ edge.id === edgeId ? { ...edge, data: { ...edge, ...updates } as GraphEdge } : edge
+ )
+ const filteredNodes = computeFilteredNodes(nodes, filters)
+ const filteredEdges = computeFilteredEdges(updatedEdges, filteredNodes)
+ set({ edges: updatedEdges, filteredNodes, filteredEdges })
+ },
+
+ // === Selection & Current ===
+ currentNode: null,
+ selectedNodes: [],
+ setCurrentNode: (node) => {
+ const { currentNode } = get()
+ // Only update if the node is actually different
+ if (currentNode?.id !== node?.id) {
+ set({ currentNode: node })
}
- )
+ },
+ setSelectedNodes: (nodes) => set({ selectedNodes: nodes }),
+ clearSelectedNodes: () => set({ selectedNodes: [], currentNode: null }),
+ toggleNodeSelection: (node, multiSelect = false) => {
+ const { selectedNodes, currentNode } = get()
+ const isSelected = selectedNodes.some((n) => n.id === node.id)
+ let newSelected: GraphNode[]
+ let newCurrentNode = currentNode
+
+ if (multiSelect) {
+ newSelected = isSelected
+ ? selectedNodes.filter((n) => n.id !== node.id)
+ : [...selectedNodes, node]
+ } else {
+ newSelected = isSelected && selectedNodes.length === 1 ? [] : [node]
+ // Only update currentNode if it's actually different
+ if (!multiSelect) {
+ newCurrentNode = isSelected ? null : node
+ }
+ }
+
+ // Only update if there are actual changes
+ const hasSelectionChanges =
+ newSelected.length !== selectedNodes.length ||
+ newSelected.some((n, i) => n.id !== selectedNodes[i]?.id)
+ const hasCurrentNodeChanges = newCurrentNode?.id !== currentNode?.id
+
+ if (hasSelectionChanges || hasCurrentNodeChanges) {
+ set({
+ selectedNodes: newSelected,
+ currentNode: newCurrentNode
+ })
+ }
+ },
+
+ // === Relation ===
+ relatedNodeToAdd: null,
+ setRelatedNodeToAdd: (node) => set({ relatedNodeToAdd: node }),
+
+ // === Dialogs ===
+ openMainDialog: false,
+ openFormDialog: false,
+ openAddRelationDialog: false,
+ openMergeDialog: false,
+ openNodeEditorModal: false,
+ setOpenMainDialog: (open) => set({ openMainDialog: open }),
+ setOpenFormDialog: (open) => set({ openFormDialog: open }),
+ setOpenAddRelationDialog: (open) => set({ openAddRelationDialog: open }),
+ setOpenMergeDialog: (open) => set({ openMergeDialog: open }),
+ setOpenNodeEditorModal: (open) => set({ openNodeEditorModal: open }),
+
+ // === Action Type for Edit form ===
+ handleEdit: (node) => {
+ const { currentNode, openNodeEditorModal } = get()
+ // Only update if the node is actually different
+ if (currentNode?.id !== node.id) {
+ set({ currentNode: node, openNodeEditorModal: true })
+ } else if (!openNodeEditorModal) {
+ // Only open modal if it's not already open
+ set({ openNodeEditorModal: true })
+ }
+ },
+
+ // === Action Type for Form ===
+ currentNodeType: null,
+ setCurrentNodeType: (nodeType) => set({ currentNodeType: nodeType }),
+ handleOpenFormModal: (selectedItem) => {
+ if (!selectedItem) return
+ set({
+ currentNodeType: selectedItem,
+ openMainDialog: false,
+ openFormDialog: true
+ })
+ },
+
+ // === Filters ===
+ filters: {
+ types: [
+ {
+ type: 'domain',
+ checked: true
+ },
+ {
+ type: 'ip',
+ checked: true
+ },
+ {
+ type: 'individual',
+ checked: true
+ }
+ ]
+ },
+ setFilters: (filters) => {
+ const { nodes, edges } = get()
+ const filteredNodes = computeFilteredNodes(nodes, filters)
+ const filteredEdges = computeFilteredEdges(edges, filteredNodes)
+ set({ filters, filteredNodes, filteredEdges })
+ },
+
+ toggleTypeFilter: (filter) => {
+ const { filters, nodes, edges } = get()
+ const newTypes = filters.types.map((f: TypeFilter) => {
+ if (f.type === filter.type)
+ return {
+ type: f.type,
+ checked: !f.checked
+ }
+ return f
+ })
+ const newFilters = { ...filters, types: newTypes }
+ const filteredNodes = computeFilteredNodes(nodes, newFilters)
+ const filteredEdges = computeFilteredEdges(edges, filteredNodes)
+ set({ filters: newFilters, filteredNodes, filteredEdges })
+ },
+
+ // === Collapse/Expand logic ===
+ toggleCollapse: (nodeId) => {
+ const { nodes, edges, filters } = get()
+ const node = nodes.find((n) => n.id === nodeId)
+ if (!node) return
+ const isCollapsing = !node.collapsed
+
+ const getDescendants = (parentId: string, accNodes: Set<string>, accEdges: Set<string>) => {
+ edges.forEach((edge) => {
+ if (edge.source === parentId) {
+ accEdges.add(edge.id)
+ accNodes.add(edge.target)
+ getDescendants(edge.target, accNodes, accEdges)
+ }
+ })
+ }
+
+ const descendantNodeIds = new Set<string>()
+ const descendantEdgeIds = new Set<string>()
+ getDescendants(nodeId, descendantNodeIds, descendantEdgeIds)
+
+ const newNodes = nodes.map((n) =>
+ n.id === nodeId
+ ? { ...n, collapsed: isCollapsing }
+ : descendantNodeIds.has(n.id)
+ ? { ...n, hidden: isCollapsing }
+ : n
+ )
+ const newEdges = edges.map((e) =>
+ descendantEdgeIds.has(e.id) ? { ...e, hidden: isCollapsing } : e
+ )
+
+ const filteredNodes = computeFilteredNodes(newNodes, filters)
+ const filteredEdges = computeFilteredEdges(newEdges, filteredNodes)
+ set({ nodes: newNodes, edges: newEdges, filteredNodes, filteredEdges })
+ },
+
+ reset: () => {
+ set({
+ currentNode: null,
+ selectedNodes: [],
+ relatedNodeToAdd: null,
+ openMainDialog: false,
+ openFormDialog: false,
+ openAddRelationDialog: false,
+ openNodeEditorModal: false,
+ currentNodeType: null,
+ filteredNodes: get().nodes,
+ filteredEdges: get().edges
+ })
+ },
+
+ // === Utils ===
+ nodesLength: 0,
+ edgesLength: 0
+ }),
+ {
+ name: 'graph-store',
+ partialize: (state) => ({ edgesLength: state.edgesLength })
+ }
+ )
)
diff --git a/flowsint-app/src/renderer/src/stores/layout-store.ts b/flowsint-app/src/renderer/src/stores/layout-store.ts
index df90967d..4b0ff86d 100644
--- a/flowsint-app/src/renderer/src/stores/layout-store.ts
+++ b/flowsint-app/src/renderer/src/stores/layout-store.ts
@@ -2,69 +2,70 @@ import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface LayoutStore {
- isOpenConsole: boolean
- isOpenPanel: boolean
- isOpenDetails: boolean
- isOpenChat: boolean
- isOpenAnalysis: boolean
- chatWidth: number
- chatHeight: number
- toggleConsole: () => void
- togglePanel: () => void
- toggleChat: () => void
- toggleDetails: () => void
- toggleAnalysis: () => void
- closePanel: () => void
- openPanel: () => void
- closeChat: () => void
- openChat: () => void
- openDetails: () => void
- closeDetails: () => void
- setChatDimensions: (width: number, height: number) => void
- activeTab: string
- activeTransformTab: string
- setActiveTab: (tab: "entities" | "items" | string) => void
- setActiveTransformTab: (tab: "transforms" | "items" | string) => void
+ isOpenConsole: boolean
+ isOpenPanel: boolean
+ isOpenDetails: boolean
+ isOpenChat: boolean
+ isOpenAnalysis: boolean
+ chatWidth: number
+ chatHeight: number
+ toggleConsole: () => void
+ togglePanel: () => void
+ toggleChat: () => void
+ toggleDetails: () => void
+ toggleAnalysis: () => void
+ closePanel: () => void
+ openPanel: () => void
+ closeChat: () => void
+ openChat: () => void
+ openDetails: () => void
+ closeDetails: () => void
+ setChatDimensions: (width: number, height: number) => void
+ activeTab: string
+ activeTransformTab: string
+ setActiveTab: (tab: 'entities' | 'items' | string) => void
+ setActiveTransformTab: (tab: 'transforms' | 'items' | string) => void
}
export const useLayoutStore = create<LayoutStore>()(
- persist(
- (set) => ({
- isOpenConsole: false,
- isOpenPanel: true,
- isOpenDetails: false,
- isOpenChat: false,
- isOpenAnalysis: false,
- chatWidth: 500,
- chatHeight: 600,
- activeTab: "entities",
- activeTransformTab: "transforms",
- toggleConsole: () => set((state) => ({ isOpenConsole: !state.isOpenConsole })),
- togglePanel: () => set((state) => ({ isOpenPanel: !state.isOpenPanel })),
- toggleDetails: () => set((state) => ({ isOpenDetails: !state.isOpenDetails })),
- toggleChat: () => set((state) => ({ isOpenChat: !state.isOpenChat })),
- toggleAnalysis: () => set((state) => ({ isOpenAnalysis: !state.isOpenAnalysis })),
- closePanel: () => set({ isOpenPanel: false }),
- openPanel: () => set({ isOpenPanel: true }),
- closeChat: () => set({ isOpenChat: false }),
- openChat: () => set({ isOpenChat: true }),
- closeDetails: () => set({ isOpenAnalysis: false }),
- openDetails: () => set({ isOpenAnalysis: true }),
- setChatDimensions: (width: number, height: number) => set({ chatWidth: width, chatHeight: height }),
- setActiveTab: (tab: string) => set({ activeTab: tab }),
- setActiveTransformTab: (tab: string) => set({ activeTransformTab: tab }),
- }),
- {
- name: 'layout-storage',
- partialize: (state) => ({
- isOpenPanel: state.isOpenPanel,
- isOpenAnalysis: state.isOpenAnalysis,
- isOpenDetails: state.isOpenDetails,
- chatWidth: state.chatWidth,
- chatHeight: state.chatHeight,
- activeTab: state.activeTab,
- activeTransformTab: state.activeTransformTab,
- }),
- }
- )
-)
+ persist(
+ (set) => ({
+ isOpenConsole: false,
+ isOpenPanel: true,
+ isOpenDetails: false,
+ isOpenChat: false,
+ isOpenAnalysis: false,
+ chatWidth: 500,
+ chatHeight: 600,
+ activeTab: 'entities',
+ activeTransformTab: 'transforms',
+ toggleConsole: () => set((state) => ({ isOpenConsole: !state.isOpenConsole })),
+ togglePanel: () => set((state) => ({ isOpenPanel: !state.isOpenPanel })),
+ toggleDetails: () => set((state) => ({ isOpenDetails: !state.isOpenDetails })),
+ toggleChat: () => set((state) => ({ isOpenChat: !state.isOpenChat })),
+ toggleAnalysis: () => set((state) => ({ isOpenAnalysis: !state.isOpenAnalysis })),
+ closePanel: () => set({ isOpenPanel: false }),
+ openPanel: () => set({ isOpenPanel: true }),
+ closeChat: () => set({ isOpenChat: false }),
+ openChat: () => set({ isOpenChat: true }),
+ closeDetails: () => set({ isOpenAnalysis: false }),
+ openDetails: () => set({ isOpenAnalysis: true }),
+ setChatDimensions: (width: number, height: number) =>
+ set({ chatWidth: width, chatHeight: height }),
+ setActiveTab: (tab: string) => set({ activeTab: tab }),
+ setActiveTransformTab: (tab: string) => set({ activeTransformTab: tab })
+ }),
+ {
+ name: 'layout-storage',
+ partialize: (state) => ({
+ isOpenPanel: state.isOpenPanel,
+ isOpenAnalysis: state.isOpenAnalysis,
+ isOpenDetails: state.isOpenDetails,
+ chatWidth: state.chatWidth,
+ chatHeight: state.chatHeight,
+ activeTab: state.activeTab,
+ activeTransformTab: state.activeTransformTab
+ })
+ }
+ )
+)
diff --git a/flowsint-app/src/renderer/src/stores/node-display-settings.ts b/flowsint-app/src/renderer/src/stores/node-display-settings.ts
index 6f3e9dc6..8d4cb9ee 100644
--- a/flowsint-app/src/renderer/src/stores/node-display-settings.ts
+++ b/flowsint-app/src/renderer/src/stores/node-display-settings.ts
@@ -1,338 +1,336 @@
-import { create } from "zustand"
-import { persist } from "zustand/middleware"
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
export type ItemType =
- | "individual"
- | "phone"
- | "location"
- | "email"
- | "ip"
- | "socialprofile"
- | "organization"
- | "vehicle"
- | "car"
- | "motorcycle"
- | "boat"
- | "plane"
- | "website"
- | "domain"
- | "subdomain"
- | "document"
- | "financial"
- | "event"
- | "device"
- | "media"
- | "education"
- | "relationship"
- | "online_activity"
- | "digital_footprint"
- | "biometric"
- | "credential"
- | "username"
- | "siret"
- | "siren"
- | "cryptowallet"
- | "cryptotransaction"
- | "cryptonft"
- | "asn"
- | "cidr"
- | "whois"
- | "gravatar"
- | "breach"
- | "webtracker"
- | "session"
- | "dns"
- | "ssl"
- | "message"
- | "malware"
- | "weapon"
- | "script"
- | "reputation"
- | "risk"
- | "file"
- | "bank"
- | "creditcard"
- | "alias"
- | "affiliation"
- | "phrase"
+ | 'individual'
+ | 'phone'
+ | 'location'
+ | 'email'
+ | 'ip'
+ | 'socialprofile'
+ | 'organization'
+ | 'vehicle'
+ | 'car'
+ | 'motorcycle'
+ | 'boat'
+ | 'plane'
+ | 'website'
+ | 'domain'
+ | 'subdomain'
+ | 'document'
+ | 'financial'
+ | 'event'
+ | 'device'
+ | 'media'
+ | 'education'
+ | 'relationship'
+ | 'online_activity'
+ | 'digital_footprint'
+ | 'biometric'
+ | 'credential'
+ | 'username'
+ | 'siret'
+ | 'siren'
+ | 'cryptowallet'
+ | 'cryptotransaction'
+ | 'cryptonft'
+ | 'asn'
+ | 'cidr'
+ | 'whois'
+ | 'gravatar'
+ | 'breach'
+ | 'webtracker'
+ | 'session'
+ | 'dns'
+ | 'ssl'
+ | 'message'
+ | 'malware'
+ | 'weapon'
+ | 'script'
+ | 'reputation'
+ | 'risk'
+ | 'file'
+ | 'bank'
+ | 'creditcard'
+ | 'alias'
+ | 'affiliation'
+ | 'phrase'
export const ITEM_TYPES: ItemType[] = [
- "individual",
- "phone",
- "location",
- "email",
- "ip",
- "socialprofile",
- "organization",
- "vehicle",
- "car",
- "motorcycle",
- "boat",
- "plane",
- "website",
- "domain",
- "subdomain",
- "document",
- "financial",
- "event",
- "device",
- "media",
- "education",
- "relationship",
- "online_activity",
- "digital_footprint",
- "biometric",
- "credential",
- "username",
- "siret",
- "siren",
- "cryptowallet",
- "cryptotransaction",
- "cryptonft",
- "asn",
- "cidr",
- "whois",
- "gravatar",
- "breach",
- "webtracker",
- "session",
- "dns",
- "ssl",
- "message",
- "malware",
- "weapon",
- "script",
- "reputation",
- "risk",
- "file",
- "bank",
- "creditcard",
- "alias",
- "affiliation",
- "phrase",
+ 'individual',
+ 'phone',
+ 'location',
+ 'email',
+ 'ip',
+ 'socialprofile',
+ 'organization',
+ 'vehicle',
+ 'car',
+ 'motorcycle',
+ 'boat',
+ 'plane',
+ 'website',
+ 'domain',
+ 'subdomain',
+ 'document',
+ 'financial',
+ 'event',
+ 'device',
+ 'media',
+ 'education',
+ 'relationship',
+ 'online_activity',
+ 'digital_footprint',
+ 'biometric',
+ 'credential',
+ 'username',
+ 'siret',
+ 'siren',
+ 'cryptowallet',
+ 'cryptotransaction',
+ 'cryptonft',
+ 'asn',
+ 'cidr',
+ 'whois',
+ 'gravatar',
+ 'breach',
+ 'webtracker',
+ 'session',
+ 'dns',
+ 'ssl',
+ 'message',
+ 'malware',
+ 'weapon',
+ 'script',
+ 'reputation',
+ 'risk',
+ 'file',
+ 'bank',
+ 'creditcard',
+ 'alias',
+ 'affiliation',
+ 'phrase'
]
const DEFAULT_COLORS: Record<ItemType, string> = {
- individual: "#4C8EDA", // bleu moyen
- phone: "#4CB5AE", // teal doux
- location: "#E57373", // rouge rosé
- email: "#8E7CC3", // violet pastel
- ip: "#5AA1C8", // orange chaud
- socialprofile: "#A76DAA", // mauve
- organization: "#BCA18A", // taupe clair
- vehicle: "#E1B84D", // jaune doux
- car: "#BFAF7A", // olive beige
- motorcycle: "#A78B6C", // brun taupe
- boat: "#6FB1C5", // bleu teal
- plane: "#C1A78E", // brun clair
- website: "#D279A6", // rose pastel
- domain: "#66A892", // vert sauge
- subdomain: "#F4A261", // bleu ciel
- document: "#8F9CA3", // gris bleuté
- financial: "#E98973", // corail doux
- event: "#6DBBA2", // vert menthe
- device: "#E3A857", // orange sable
- media: "#C97C73", // terracotta
- education: "#6C8CBF", // bleu acier
- relationship: "#B18B84", // brun rosé
- online_activity: "#7EAD6F", // vert sauge
- digital_footprint: "#B97777", // brique
- username: "#8B83C1", // pervenche
- credential: "#D4B030", // doré doux
- biometric: "#7F868D", // gris ardoise
- siret: "#7D8B99", // gris bleu
- siren: "#687684", // gris foncé
- cryptowallet: "#D4B030", // or clair
- cryptotransaction: "#BFA750", // or chaud
- cryptonft: "#A5BF50", // vert lime doux
- asn: "#D97474", // pêche rosée
- cidr: "#80BF80", // vert menthe
- whois: "#9B6F9B", // violet doux
- gravatar: "#6CB7CA", // cyan clair
- breach: "#CC7A7A", // rose chaud
- webtracker: "#C7BF50", // jaune doux
- session: "#A8BF50", // lime atténué
- dns: "#80BF9F", // vert teal clair
- ssl: "#BFAF80", // sable chaud
- message: "#897FC9", // violet lavande
- malware: "#4AA29E", // teal saturé
- weapon: "#E98973", // corail brun
- script: "#A36FA3", // violet doux
- reputation: "#6FA8DC", // bleu clair
- risk: "#D97474", // rouge doux
- file: "#8F9CA3", // gris bleuté
- bank: "#D4B030", // or clair
- creditcard: "#285E8E", // bleu profond
- alias: "#A36FA3", // violet
- affiliation: "#66A892", // vert sauge
- phrase: "#BFA77A", // beige chaud
-};
-
-
+ individual: '#4C8EDA', // bleu moyen
+ phone: '#4CB5AE', // teal doux
+ location: '#E57373', // rouge rosé
+ email: '#8E7CC3', // violet pastel
+ ip: '#5AA1C8', // orange chaud
+ socialprofile: '#A76DAA', // mauve
+ organization: '#BCA18A', // taupe clair
+ vehicle: '#E1B84D', // jaune doux
+ car: '#BFAF7A', // olive beige
+ motorcycle: '#A78B6C', // brun taupe
+ boat: '#6FB1C5', // bleu teal
+ plane: '#C1A78E', // brun clair
+ website: '#D279A6', // rose pastel
+ domain: '#66A892', // vert sauge
+ subdomain: '#F4A261', // bleu ciel
+ document: '#8F9CA3', // gris bleuté
+ financial: '#E98973', // corail doux
+ event: '#6DBBA2', // vert menthe
+ device: '#E3A857', // orange sable
+ media: '#C97C73', // terracotta
+ education: '#6C8CBF', // bleu acier
+ relationship: '#B18B84', // brun rosé
+ online_activity: '#7EAD6F', // vert sauge
+ digital_footprint: '#B97777', // brique
+ username: '#8B83C1', // pervenche
+ credential: '#D4B030', // doré doux
+ biometric: '#7F868D', // gris ardoise
+ siret: '#7D8B99', // gris bleu
+ siren: '#687684', // gris foncé
+ cryptowallet: '#D4B030', // or clair
+ cryptotransaction: '#BFA750', // or chaud
+ cryptonft: '#A5BF50', // vert lime doux
+ asn: '#D97474', // pêche rosée
+ cidr: '#80BF80', // vert menthe
+ whois: '#9B6F9B', // violet doux
+ gravatar: '#6CB7CA', // cyan clair
+ breach: '#CC7A7A', // rose chaud
+ webtracker: '#C7BF50', // jaune doux
+ session: '#A8BF50', // lime atténué
+ dns: '#80BF9F', // vert teal clair
+ ssl: '#BFAF80', // sable chaud
+ message: '#897FC9', // violet lavande
+ malware: '#4AA29E', // teal saturé
+ weapon: '#E98973', // corail brun
+ script: '#A36FA3', // violet doux
+ reputation: '#6FA8DC', // bleu clair
+ risk: '#D97474', // rouge doux
+ file: '#8F9CA3', // gris bleuté
+ bank: '#D4B030', // or clair
+ creditcard: '#285E8E', // bleu profond
+ alias: '#A36FA3', // violet
+ affiliation: '#66A892', // vert sauge
+ phrase: '#BFA77A' // beige chaud
+}
// Définition des icônes par défaut pour chaque type d'élément
const DEFAULT_ICONS: Record<ItemType, string> = {
- individual: "👤",
- phone: "📞",
- location: "🏠",
- email: "✉️",
- ip: "🌐",
- socialprofile: "📱",
- organization: "🏢",
- vehicle: "🚗",
- car: "🚗",
- motorcycle: "🏍️",
- boat: "🚤",
- plane: "✈️",
- website: "🔗",
- domain: "🌍",
- subdomain: "🧩",
- document: "📄",
- financial: "💳",
- event: "📅",
- device: "📱",
- media: "🖼️",
- education: "📚",
- relationship: "👥",
- online_activity: "💻",
- digital_footprint: "👣",
- biometric: "🧬",
- credential: "🔑",
- username: "🧑‍💻",
- siret: "ℹ️",
- siren: "ℹ️",
- cryptowallet: "₿",
- cryptotransaction: "💱",
- cryptonft: "🖼️",
- asn: "🌐",
- cidr: "📡",
- whois: "🌐",
- gravatar: "🖼️",
- breach: "🔓",
- webtracker: "🎯",
- session: "🔐",
- dns: "🌐",
- ssl: "🔒",
- message: "💬",
- malware: "🦠",
- weapon: "⚔️",
- script: "📜",
- reputation: "⭐",
- risk: "⚠️",
- file: "📁",
- bank: "🏦",
- creditcard: "💳",
- alias: "👤",
- affiliation: "🤝",
- phrase: "��",
-};
+ individual: '👤',
+ phone: '📞',
+ location: '🏠',
+ email: '✉️',
+ ip: '🌐',
+ socialprofile: '📱',
+ organization: '🏢',
+ vehicle: '🚗',
+ car: '🚗',
+ motorcycle: '🏍️',
+ boat: '🚤',
+ plane: '✈️',
+ website: '🔗',
+ domain: '🌍',
+ subdomain: '🧩',
+ document: '📄',
+ financial: '💳',
+ event: '📅',
+ device: '📱',
+ media: '🖼️',
+ education: '📚',
+ relationship: '👥',
+ online_activity: '💻',
+ digital_footprint: '👣',
+ biometric: '🧬',
+ credential: '🔑',
+ username: '🧑‍💻',
+ siret: 'ℹ️',
+ siren: 'ℹ️',
+ cryptowallet: '₿',
+ cryptotransaction: '💱',
+ cryptonft: '🖼️',
+ asn: '🌐',
+ cidr: '📡',
+ whois: '🌐',
+ gravatar: '🖼️',
+ breach: '🔓',
+ webtracker: '🎯',
+ session: '🔐',
+ dns: '🌐',
+ ssl: '🔒',
+ message: '💬',
+ malware: '🦠',
+ weapon: '⚔️',
+ script: '📜',
+ reputation: '⭐',
+ risk: '⚠️',
+ file: '📁',
+ bank: '🏦',
+ creditcard: '💳',
+ alias: '👤',
+ affiliation: '🤝',
+ phrase: '��'
+}
const DEFAULT_SIZES: Record<ItemType, number> = {
- individual: 24, // Large - key entities
- phone: 16, // Medium-large
- location: 14, // Medium
- email: 14, // Medium
- ip: 16, // Medium-large
- socialprofile: 14, // Medium
- organization: 28, // Very large - important entities
- vehicle: 12, // Small-medium
- car: 12, // Small-medium
- motorcycle: 12, // Small-medium
- boat: 12, // Small-medium
- plane: 12, // Small-medium
- website: 14, // Medium
- domain: 20, // Large
- subdomain: 16, // Medium-large
- document: 12, // Small-medium
- financial: 18, // Medium-large
- event: 12, // Small-medium
- device: 12, // Small-medium
- media: 12, // Small-medium
- education: 12, // Small-medium
- relationship: 10, // Small
- online_activity: 10, // Small
- digital_footprint: 10, // Small
- biometric: 14, // Medium
- credential: 16, // Medium-large
- username: 14, // Medium
- siret: 8, // Very small
- siren: 8, // Very small
- cryptowallet: 18, // Medium-large
- cryptotransaction: 14, // Medium
- cryptonft: 14, // Medium
- asn: 32, // Largest - network infrastructure
- cidr: 28, // Very large - network ranges
- whois: 10, // Small
- gravatar: 10, // Small
- breach: 20, // Large - security important
- webtracker: 12, // Small-medium
- session: 10, // Small
- dns: 16, // Medium-large
- ssl: 16, // Medium-large
- message: 12, // Small-medium
- malware: 24, // Large - security critical
- weapon: 22, // Large - high importance
- script: 12, // Small-medium
- reputation: 14, // Medium
- risk: 20, // Large - important for analysis
- file: 12, // Small-medium
- bank: 22, // Large - financial importance
- creditcard: 18, // Medium-large
- alias: 12, // Small-medium
- affiliation: 14, // Medium
- phrase: 10, // Small
+ individual: 24, // Large - key entities
+ phone: 16, // Medium-large
+ location: 14, // Medium
+ email: 14, // Medium
+ ip: 16, // Medium-large
+ socialprofile: 14, // Medium
+ organization: 28, // Very large - important entities
+ vehicle: 12, // Small-medium
+ car: 12, // Small-medium
+ motorcycle: 12, // Small-medium
+ boat: 12, // Small-medium
+ plane: 12, // Small-medium
+ website: 14, // Medium
+ domain: 20, // Large
+ subdomain: 16, // Medium-large
+ document: 12, // Small-medium
+ financial: 18, // Medium-large
+ event: 12, // Small-medium
+ device: 12, // Small-medium
+ media: 12, // Small-medium
+ education: 12, // Small-medium
+ relationship: 10, // Small
+ online_activity: 10, // Small
+ digital_footprint: 10, // Small
+ biometric: 14, // Medium
+ credential: 16, // Medium-large
+ username: 14, // Medium
+ siret: 8, // Very small
+ siren: 8, // Very small
+ cryptowallet: 18, // Medium-large
+ cryptotransaction: 14, // Medium
+ cryptonft: 14, // Medium
+ asn: 32, // Largest - network infrastructure
+ cidr: 28, // Very large - network ranges
+ whois: 10, // Small
+ gravatar: 10, // Small
+ breach: 20, // Large - security important
+ webtracker: 12, // Small-medium
+ session: 10, // Small
+ dns: 16, // Medium-large
+ ssl: 16, // Medium-large
+ message: 12, // Small-medium
+ malware: 24, // Large - security critical
+ weapon: 22, // Large - high importance
+ script: 12, // Small-medium
+ reputation: 14, // Medium
+ risk: 20, // Large - important for analysis
+ file: 12, // Small-medium
+ bank: 22, // Large - financial importance
+ creditcard: 18, // Medium-large
+ alias: 12, // Small-medium
+ affiliation: 14, // Medium
+ phrase: 10 // Small
}
interface NodesDisplaySettingsState {
- colors: Record<ItemType, string>
- icons: Record<ItemType, string>
- sizes: Record<ItemType, number>
- setColor: (itemType: ItemType, color: string) => void
- setIcon: (itemType: ItemType, iconPath: string) => void
- resetColors: () => void
- resetIcons: () => void
- resetAll: () => void
- getIcon: (itemType: ItemType) => string
- getSize: (itemType: ItemType) => number
+ colors: Record<ItemType, string>
+ icons: Record<ItemType, string>
+ sizes: Record<ItemType, number>
+ setColor: (itemType: ItemType, color: string) => void
+ setIcon: (itemType: ItemType, iconPath: string) => void
+ resetColors: () => void
+ resetIcons: () => void
+ resetAll: () => void
+ getIcon: (itemType: ItemType) => string
+ getSize: (itemType: ItemType) => number
}
export const useNodesDisplaySettings = create<NodesDisplaySettingsState>()(
- persist(
- (set, get) => ({
- colors: { ...DEFAULT_COLORS },
- icons: { ...DEFAULT_ICONS },
- sizes: { ...DEFAULT_SIZES },
- setColor: (itemType, color) =>
- set((state) => ({
- colors: {
- ...state.colors,
- [itemType]: color,
- },
- })),
- setIcon: (itemType, iconPath) =>
- set((state) => ({
- icons: {
- ...state.icons,
- [itemType]: iconPath,
- },
- })),
- resetColors: () => set({ colors: { ...DEFAULT_COLORS } }),
- resetIcons: () => set({ icons: { ...DEFAULT_ICONS } }),
- resetAll: () =>
- set({
- colors: { ...DEFAULT_COLORS },
- icons: { ...DEFAULT_ICONS },
- sizes: { ...DEFAULT_SIZES }
- }),
- getIcon: (itemType) => {
- return get().icons[itemType] || ""
- },
- getSize: (itemType) => {
- return get().sizes[itemType] * 0.4
- }
+ persist(
+ (set, get) => ({
+ colors: { ...DEFAULT_COLORS },
+ icons: { ...DEFAULT_ICONS },
+ sizes: { ...DEFAULT_SIZES },
+ setColor: (itemType, color) =>
+ set((state) => ({
+ colors: {
+ ...state.colors,
+ [itemType]: color
+ }
+ })),
+ setIcon: (itemType, iconPath) =>
+ set((state) => ({
+ icons: {
+ ...state.icons,
+ [itemType]: iconPath
+ }
+ })),
+ resetColors: () => set({ colors: { ...DEFAULT_COLORS } }),
+ resetIcons: () => set({ icons: { ...DEFAULT_ICONS } }),
+ resetAll: () =>
+ set({
+ colors: { ...DEFAULT_COLORS },
+ icons: { ...DEFAULT_ICONS },
+ sizes: { ...DEFAULT_SIZES }
}),
- {
- name: "nodes-display-settings",
- },
- ),
+ getIcon: (itemType) => {
+ return get().icons[itemType] || ''
+ },
+ getSize: (itemType) => {
+ return get().sizes[itemType] * 0.4
+ }
+ }),
+ {
+ name: 'nodes-display-settings'
+ }
+ )
)
diff --git a/flowsint-app/src/renderer/src/stores/node-editor-layout-store.ts b/flowsint-app/src/renderer/src/stores/node-editor-layout-store.ts
index 0598be4c..50362fce 100644
--- a/flowsint-app/src/renderer/src/stores/node-editor-layout-store.ts
+++ b/flowsint-app/src/renderer/src/stores/node-editor-layout-store.ts
@@ -1,7 +1,13 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
-export type CardType = 'description' | 'core-properties' | 'additional-properties' | 'preview' | 'neighbors' | 'location'
+export type CardType =
+ | 'description'
+ | 'core-properties'
+ | 'additional-properties'
+ | 'preview'
+ | 'neighbors'
+ | 'location'
interface CardState {
id: CardType
@@ -23,7 +29,7 @@ const defaultCardLayout: CardState[] = [
{ id: 'additional-properties', isEditing: false, order: 2 },
{ id: 'preview', isEditing: false, order: 3 },
{ id: 'neighbors', isEditing: false, order: 4 },
- { id: 'location', isEditing: false, order: 5 },
+ { id: 'location', isEditing: false, order: 5 }
]
export const useNodeEditorLayoutStore = create<NodeEditorLayoutState>()(
@@ -33,23 +39,23 @@ export const useNodeEditorLayoutStore = create<NodeEditorLayoutState>()(
setCardLayout: (layout) => set({ cardLayout: layout }),
toggleCardEdit: (cardId) => {
const { cardLayout } = get()
- const updatedLayout = cardLayout.map(card =>
+ const updatedLayout = cardLayout.map((card) =>
card.id === cardId ? { ...card, isEditing: !card.isEditing } : card
)
set({ cardLayout: updatedLayout })
},
setCardEditState: (cardId, isEditing) => {
const { cardLayout } = get()
- const updatedLayout = cardLayout.map(card =>
+ const updatedLayout = cardLayout.map((card) =>
card.id === cardId ? { ...card, isEditing } : card
)
set({ cardLayout: updatedLayout })
},
- resetLayout: () => set({ cardLayout: defaultCardLayout }),
+ resetLayout: () => set({ cardLayout: defaultCardLayout })
}),
{
name: 'node-editor-layout-storage',
- partialize: (state) => ({ cardLayout: state.cardLayout }),
+ partialize: (state) => ({ cardLayout: state.cardLayout })
}
)
-)
\ No newline at end of file
+)
diff --git a/flowsint-app/src/renderer/src/stores/use-chat-store.tsx b/flowsint-app/src/renderer/src/stores/use-chat-store.tsx
index 12d84b3d..20659e2f 100644
--- a/flowsint-app/src/renderer/src/stores/use-chat-store.tsx
+++ b/flowsint-app/src/renderer/src/stores/use-chat-store.tsx
@@ -2,35 +2,39 @@ import { ChatMessage } from '@/types'
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
-
interface ChatState {
- currentChatId: string | null
- setCurrentChatId: (chatId: string | null) => void
- messages: ChatMessage[]
- setMessages: (messages: ChatMessage[]) => void
- addMessage: (message: ChatMessage) => void
- deleteChat: (chatId: string) => void
+ currentChatId: string | null
+ setCurrentChatId: (chatId: string | null) => void
+ messages: ChatMessage[]
+ setMessages: (messages: ChatMessage[]) => void
+ addMessage: (message: ChatMessage) => void
+ deleteChat: (chatId: string) => void
}
export const useChatState = create<ChatState>()(
- persist(
- (set, _) => ({
- currentChatId: null,
- messages: [],
- setCurrentChatId: (chatId) => set({ currentChatId: chatId }),
- setMessages: (messages) => set({ messages: messages }),
- addMessage: (message) => set((state) => ({
- messages: [...state.messages, { ...message, chatId: message.chatId || state.currentChatId || undefined }]
- })),
- deleteChat: (chatId) => set((state) => ({
- currentChatId: state.currentChatId === chatId ? null : state.currentChatId
- }))
- }),
- {
- name: 'chat-state-storage',
- partialize: (state) => ({
- currentChatId: state.currentChatId,
- }),
- }
- )
-)
\ No newline at end of file
+ persist(
+ (set, _) => ({
+ currentChatId: null,
+ messages: [],
+ setCurrentChatId: (chatId) => set({ currentChatId: chatId }),
+ setMessages: (messages) => set({ messages: messages }),
+ addMessage: (message) =>
+ set((state) => ({
+ messages: [
+ ...state.messages,
+ { ...message, chatId: message.chatId || state.currentChatId || undefined }
+ ]
+ })),
+ deleteChat: (chatId) =>
+ set((state) => ({
+ currentChatId: state.currentChatId === chatId ? null : state.currentChatId
+ }))
+ }),
+ {
+ name: 'chat-state-storage',
+ partialize: (state) => ({
+ currentChatId: state.currentChatId
+ })
+ }
+ )
+)
diff --git a/flowsint-app/src/renderer/src/types/analysis.ts b/flowsint-app/src/renderer/src/types/analysis.ts
index 1715ea8c..485fb349 100644
--- a/flowsint-app/src/renderer/src/types/analysis.ts
+++ b/flowsint-app/src/renderer/src/types/analysis.ts
@@ -1,10 +1,10 @@
export interface Analysis {
- id: string; // UUID
- title: string;
- description?: string | null;
- content?: any; // JSONB, so can be any type
- created_at: string; // ISO date string
- last_updated_at: string; // ISO date string
- owner_id?: string | null; // UUID
- investigation_id?: string | null; // UUID
-}
\ No newline at end of file
+ id: string // UUID
+ title: string
+ description?: string | null
+ content?: any // JSONB, so can be any type
+ created_at: string // ISO date string
+ last_updated_at: string // ISO date string
+ owner_id?: string | null // UUID
+ investigation_id?: string | null // UUID
+}
diff --git a/flowsint-app/src/renderer/src/types/chat.ts b/flowsint-app/src/renderer/src/types/chat.ts
index cdc51065..1fbdce2c 100644
--- a/flowsint-app/src/renderer/src/types/chat.ts
+++ b/flowsint-app/src/renderer/src/types/chat.ts
@@ -1,16 +1,16 @@
export interface ChatMessage {
- id: string,
- content: string,
- is_bot: boolean,
- created_at: string,
- context?: any,
+ id: string
+ content: string
+ is_bot: boolean
+ created_at: string
+ context?: any
chatId?: string
}
export interface Chat {
- id: string,
- title: string,
- description: string,
- created_at: string,
- last_updated_at: string,
-}
\ No newline at end of file
+ id: string
+ title: string
+ description: string
+ created_at: string
+ last_updated_at: string
+}
diff --git a/flowsint-app/src/renderer/src/types/common.ts b/flowsint-app/src/renderer/src/types/common.ts
index 1149a788..d5f8145e 100644
--- a/flowsint-app/src/renderer/src/types/common.ts
+++ b/flowsint-app/src/renderer/src/types/common.ts
@@ -1,5 +1,5 @@
-import { type SVGProps } from "react";
+import { type SVGProps } from 'react'
export type IconSvgProps = SVGProps<SVGSVGElement> & {
- size?: number;
-};
\ No newline at end of file
+ size?: number
+}
diff --git a/flowsint-app/src/renderer/src/types/event.ts b/flowsint-app/src/renderer/src/types/event.ts
index 2d4895ca..f1b7c8c5 100644
--- a/flowsint-app/src/renderer/src/types/event.ts
+++ b/flowsint-app/src/renderer/src/types/event.ts
@@ -1,17 +1,17 @@
-import { GraphEdge, GraphNode } from "./graph"
+import { GraphEdge, GraphNode } from './graph'
export enum EventLevel {
// Standard log levels
- INFO = "INFO",
- WARNING = "WARNING",
- FAILED = "FAILED",
- SUCCESS = "SUCCESS",
- DEBUG = "DEBUG",
+ INFO = 'INFO',
+ WARNING = 'WARNING',
+ FAILED = 'FAILED',
+ SUCCESS = 'SUCCESS',
+ DEBUG = 'DEBUG',
// Transform-specific statuses
- PENDING = "PENDING",
- RUNNING = "RUNNING",
- COMPLETED = "COMPLETED",
- GRAPH_APPEND = "GRAPH_APPEND",
+ PENDING = 'PENDING',
+ RUNNING = 'RUNNING',
+ COMPLETED = 'COMPLETED',
+ GRAPH_APPEND = 'GRAPH_APPEND'
}
export interface Payload {
@@ -27,4 +27,4 @@ export type Event = {
type: EventLevel
payload: Payload
created_at: string
-}
\ No newline at end of file
+}
diff --git a/flowsint-app/src/renderer/src/types/flow.ts b/flowsint-app/src/renderer/src/types/flow.ts
index e9c3f1b4..d58d55ef 100644
--- a/flowsint-app/src/renderer/src/types/flow.ts
+++ b/flowsint-app/src/renderer/src/types/flow.ts
@@ -3,15 +3,15 @@
// ================================
export interface Flow {
- id: string;
- class_name: string;
- name: string;
- module: string;
- description: string;
- documentation: string;
- category: string;
- created_at: string;
- last_updated_at: string;
+ id: string
+ class_name: string
+ name: string
+ module: string
+ description: string
+ documentation: string
+ category: string
+ created_at: string
+ last_updated_at: string
}
// ================================
@@ -19,11 +19,11 @@ export interface Flow {
// ================================
export interface FlowsData {
- [category: string]: Flow[];
+ [category: string]: Flow[]
}
export interface FlowData {
- items: FlowsData;
+ items: FlowsData
}
// ================================
@@ -31,6 +31,6 @@ export interface FlowData {
// ================================
export interface FlowItemProps {
- flow: Flow;
- category: string;
+ flow: Flow
+ category: string
}
diff --git a/flowsint-app/src/renderer/src/types/graph.ts b/flowsint-app/src/renderer/src/types/graph.ts
index b012ab54..40802df7 100644
--- a/flowsint-app/src/renderer/src/types/graph.ts
+++ b/flowsint-app/src/renderer/src/types/graph.ts
@@ -1,66 +1,65 @@
-
export type NodeData = {
- id: string;
- type: string,
- label: string,
- created_at: string,
+ id: string
+ type: string
+ label: string
+ created_at: string
// Allow any other properties
- [key: string]: any;
-};
+ [key: string]: any
+}
export type GraphNode = {
- collapsed?: boolean;
- hidden?: boolean;
- x?: number;
- y?: number;
- nodeLabel?: string;
- nodeColor?: string;
- nodeSize?: number;
- nodeType?: string;
- val?: number;
- neighbors?: any[];
- links?: any[];
- id: string;
+ collapsed?: boolean
+ hidden?: boolean
+ x?: number
+ y?: number
+ nodeLabel?: string
+ nodeColor?: string
+ nodeSize?: number
+ nodeType?: string
+ val?: number
+ neighbors?: any[]
+ links?: any[]
+ id: string
data: NodeData
}
export type GraphEdge = {
- source: string;
- target: string;
- date?: string;
- id: string;
- label: string;
- caption?: string;
- type?: string;
+ source: string
+ target: string
+ date?: string
+ id: string
+ label: string
+ caption?: string
+ type?: string
confidence_level?: number | string
-};
+}
export type ForceGraphSetting = {
- value: any,
- min?: number,
- max?: number,
- step?: number,
- type?: string,
- description?: string,
+ value: any
+ min?: number
+ max?: number
+ step?: number
+ type?: string
+ description?: string
}
export type GeneralSetting = {
- value: any,
+ value: any
options?: any[]
- description?: string,
+ description?: string
}
// Extended setting types for the centralized store
export type ExtendedSetting = {
- value: any,
- type: string,
- min?: number,
- max?: number,
- step?: number,
+ value: any
+ type: string
+ min?: number
+ max?: number
+ step?: number
options?: { value: string; label: string }[]
- description?: string,
+ description?: string
}
export type Settings = {
- [key: string]: ExtendedSetting,
+ [key: string]: ExtendedSetting
}
diff --git a/flowsint-app/src/renderer/src/types/index.ts b/flowsint-app/src/renderer/src/types/index.ts
index 3c5e7472..d41fbca1 100644
--- a/flowsint-app/src/renderer/src/types/index.ts
+++ b/flowsint-app/src/renderer/src/types/index.ts
@@ -1,12 +1,12 @@
-export * from "./analysis";
-export * from "./chat";
-export * from "./common";
-export * from "./event";
-export * from "./flow";
-export * from "./graph";
-export * from "./investigation";
-export * from "./profile";
-export * from "./sketch";
-export * from "./table";
-export * from "./tool";
-export * from "./transform";
+export * from './analysis'
+export * from './chat'
+export * from './common'
+export * from './event'
+export * from './flow'
+export * from './graph'
+export * from './investigation'
+export * from './profile'
+export * from './sketch'
+export * from './table'
+export * from './tool'
+export * from './transform'
diff --git a/flowsint-app/src/renderer/src/types/investigation.ts b/flowsint-app/src/renderer/src/types/investigation.ts
index 07c5c83b..09c7f9b9 100644
--- a/flowsint-app/src/renderer/src/types/investigation.ts
+++ b/flowsint-app/src/renderer/src/types/investigation.ts
@@ -1,16 +1,16 @@
-import { type Sketch } from "./sketch"
-import { type Profile } from "./profile"
-import { type Analysis } from "./analysis"
+import { type Sketch } from './sketch'
+import { type Profile } from './profile'
+import { type Analysis } from './analysis'
export interface Investigation {
- id: string
- name: string
- description: string
- sketches: Sketch[]
- analyses: Analysis[]
- created_at: string
- last_updated_at: string
- owner: Profile
- owner_id: string,
- status: string
-}
\ No newline at end of file
+ id: string
+ name: string
+ description: string
+ sketches: Sketch[]
+ analyses: Analysis[]
+ created_at: string
+ last_updated_at: string
+ owner: Profile
+ owner_id: string
+ status: string
+}
diff --git a/flowsint-app/src/renderer/src/types/key.ts b/flowsint-app/src/renderer/src/types/key.ts
index da2a69a4..c9da14bf 100644
--- a/flowsint-app/src/renderer/src/types/key.ts
+++ b/flowsint-app/src/renderer/src/types/key.ts
@@ -1,5 +1,5 @@
export interface Key {
- id: string,
- name: string,
- created_at: string,
-}
\ No newline at end of file
+ id: string
+ name: string
+ created_at: string
+}
diff --git a/flowsint-app/src/renderer/src/types/profile.ts b/flowsint-app/src/renderer/src/types/profile.ts
index 29c771ae..41b8118e 100644
--- a/flowsint-app/src/renderer/src/types/profile.ts
+++ b/flowsint-app/src/renderer/src/types/profile.ts
@@ -1,7 +1,7 @@
export interface Profile {
- owner?: boolean,
- first_name: string,
- last_name: string,
- id: string,
+ owner?: boolean
+ first_name: string
+ last_name: string
+ id: string
avatar_url?: string
-}
\ No newline at end of file
+}
diff --git a/flowsint-app/src/renderer/src/types/sketch.ts b/flowsint-app/src/renderer/src/types/sketch.ts
index 75ad169d..04e53803 100644
--- a/flowsint-app/src/renderer/src/types/sketch.ts
+++ b/flowsint-app/src/renderer/src/types/sketch.ts
@@ -1,19 +1,19 @@
-import { type Profile } from "./profile"
-import { type Investigation } from "./investigation"
+import { type Profile } from './profile'
+import { type Investigation } from './investigation'
export interface Sketch {
- id: string
- title: string
- description: string
- status?: string
- priority?: string
- created_at: string
- last_updated_at: string
- owner: Profile
- owner_id: string,
- relations?: any[]
- individuals?: any[]
- investigation?: Investigation
- investigation_id: string
- members?: { profile: Profile }[]
-}
\ No newline at end of file
+ id: string
+ title: string
+ description: string
+ status?: string
+ priority?: string
+ created_at: string
+ last_updated_at: string
+ owner: Profile
+ owner_id: string
+ relations?: any[]
+ individuals?: any[]
+ investigation?: Investigation
+ investigation_id: string
+ members?: { profile: Profile }[]
+}
diff --git a/flowsint-app/src/renderer/src/types/table.ts b/flowsint-app/src/renderer/src/types/table.ts
index 5eb2a88c..8a11fb62 100644
--- a/flowsint-app/src/renderer/src/types/table.ts
+++ b/flowsint-app/src/renderer/src/types/table.ts
@@ -1,14 +1,14 @@
-import { GraphNode } from "@/stores/graph-store"
+import { GraphNode } from '@/stores/graph-store'
export type Row = {
- id: string
- label: string
- type: string,
- created_at: string
+ id: string
+ label: string
+ type: string
+ created_at: string
}
export type RelationshipType = {
- source: GraphNode
- target: GraphNode
- edge: { label: string }
-}
\ No newline at end of file
+ source: GraphNode
+ target: GraphNode
+ edge: { label: string }
+}
diff --git a/flowsint-app/src/renderer/src/types/tool.ts b/flowsint-app/src/renderer/src/types/tool.ts
index e1364416..16bbb66b 100644
--- a/flowsint-app/src/renderer/src/types/tool.ts
+++ b/flowsint-app/src/renderer/src/types/tool.ts
@@ -1,11 +1,11 @@
export interface Tool {
name: string
path: string
- description?: string,
+ description?: string
active: boolean
link?: string
avatar?: string
- apiKeyRequired?: false | "free" | "paid"
+ apiKeyRequired?: false | 'free' | 'paid'
}
export interface ToolCategory {
@@ -16,4 +16,4 @@ export interface ToolCategory {
export interface Tools {
[key: string]: ToolCategory
-}
\ No newline at end of file
+}
diff --git a/flowsint-app/src/renderer/src/types/transform.ts b/flowsint-app/src/renderer/src/types/transform.ts
index db5fc932..a43998e7 100644
--- a/flowsint-app/src/renderer/src/types/transform.ts
+++ b/flowsint-app/src/renderer/src/types/transform.ts
@@ -1,37 +1,37 @@
export interface TransformProperty {
- name: string
- type: string
+ name: string
+ type: string
}
export interface TransformIO {
- type: string
- properties: TransformProperty[]
+ type: string
+ properties: TransformProperty[]
}
export interface TransformParamSchemaItem {
- name: string
- type: string
- description: string
- default: string
- required: boolean
+ name: string
+ type: string
+ description: string
+ default: string
+ required: boolean
}
export interface Transform {
- id: string
- class_name: string
- category: string
- name: string
- module: string
- documentation: string | null
- description: string | null
- inputs: TransformIO
- outputs: TransformIO
- type: string
- required_params: boolean
- params: Record<string, string>
- params_schema: TransformParamSchemaItem[]
- settings?: Record<string, string>
- icon: string | null
+ id: string
+ class_name: string
+ category: string
+ name: string
+ module: string
+ documentation: string | null
+ description: string | null
+ inputs: TransformIO
+ outputs: TransformIO
+ type: string
+ required_params: boolean
+ params: Record<string, string>
+ params_schema: TransformParamSchemaItem[]
+ settings?: Record<string, string>
+ icon: string | null
}
// ================================
@@ -39,9 +39,9 @@ export interface Transform {
// ================================
export interface TransformNodeData extends Transform, Record<string, unknown> {
- color?: string
- computationState?: "pending" | "processing" | "completed" | "error"
- key: string
+ color?: string
+ computationState?: 'pending' | 'processing' | 'completed' | 'error'
+ key: string
}
// ================================
@@ -49,11 +49,11 @@ export interface TransformNodeData extends Transform, Record<string, unknown> {
// ================================
export interface ScansData {
- [category: string]: Transform[]
+ [category: string]: Transform[]
}
export interface TransformData {
- items: ScansData
+ items: ScansData
}
// ================================
@@ -61,14 +61,14 @@ export interface TransformData {
// ================================
export interface TransformItemProps {
- transform: Transform
- category: string
+ transform: Transform
+ category: string
}
export interface TransformNodeProps {
- data: TransformNodeData
- isConnectable?: boolean
- selected?: boolean
+ data: TransformNodeData
+ isConnectable?: boolean
+ selected?: boolean
}
// ================================
@@ -76,11 +76,11 @@ export interface TransformNodeProps {
// ================================
export interface TransformsData {
- [category: string]: Transform[];
+ [category: string]: Transform[]
}
export interface TransformData {
- items: TransformsData;
+ items: TransformsData
}
// ================================
@@ -88,6 +88,6 @@ export interface TransformData {
// ================================
export interface TransformItemProps {
- transform: Transform;
- category: string;
-}
\ No newline at end of file
+ transform: Transform
+ category: string
+}
diff --git a/flowsint-app/src/renderer/src/use-debounce.ts b/flowsint-app/src/renderer/src/use-debounce.ts
index cd5e2ae6..c80d6fe6 100644
--- a/flowsint-app/src/renderer/src/use-debounce.ts
+++ b/flowsint-app/src/renderer/src/use-debounce.ts
@@ -1,34 +1,36 @@
-
-import { useEffect, useState } from "react"
+import { useEffect, useState } from 'react'
// This hook creates a debounced version of a value
export function useDebounce<T>(value: T, delay: number): T {
- const [debouncedValue, setDebouncedValue] = useState<T>(value)
+ const [debouncedValue, setDebouncedValue] = useState<T>(value)
- useEffect(() => {
- const timer = setTimeout(() => {
- setDebouncedValue(value)
- }, delay)
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ setDebouncedValue(value)
+ }, delay)
- return () => {
- clearTimeout(timer)
- }
- }, [value, delay])
+ return () => {
+ clearTimeout(timer)
+ }
+ }, [value, delay])
- return debouncedValue
+ return debouncedValue
}
// This function creates a debounced version of a function
-export function debounce<T extends (...args: any[]) => any>(func: T, wait: number): (...args: Parameters<T>) => void {
- let timeout: NodeJS.Timeout | null = null
-
- return (...args: Parameters<T>) => {
- const later = () => {
- timeout = null
- func(...args)
- }
-
- if (timeout) clearTimeout(timeout)
- timeout = setTimeout(later, wait)
+export function debounce<T extends (...args: any[]) => any>(
+ func: T,
+ wait: number
+): (...args: Parameters<T>) => void {
+ let timeout: NodeJS.Timeout | null = null
+
+ return (...args: Parameters<T>) => {
+ const later = () => {
+ timeout = null
+ func(...args)
}
+
+ if (timeout) clearTimeout(timeout)
+ timeout = setTimeout(later, wait)
+ }
}
diff --git a/flowsint-app/src/renderer/src/utils/cn.ts b/flowsint-app/src/renderer/src/utils/cn.ts
index 1b2a2180..fed2fe91 100644
--- a/flowsint-app/src/renderer/src/utils/cn.ts
+++ b/flowsint-app/src/renderer/src/utils/cn.ts
@@ -1,6 +1,6 @@
-import { clsx, type ClassValue } from "clsx"
-import { twMerge } from "tailwind-merge"
+import { clsx, type ClassValue } from 'clsx'
+import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs))
- }
\ No newline at end of file
+ return twMerge(clsx(inputs))
+}