A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
feat(app): cleaner icon management
dextmorgn47dcfe3bace8
diff --git a/flowsint-app/src/components/sketches/add-item-dialog.tsx b/flowsint-app/src/components/sketches/add-item-dialog.tsxindex 69daa878..5aff9577 100644--- a/flowsint-app/src/components/sketches/add-item-dialog.tsx+++ b/flowsint-app/src/components/sketches/add-item-dialog.tsx@@ -106,7 +106,7 @@ export default function AddItemDialog() {},// Position fields for client-side graph rendering (at viewport center)x: nodeX,- y: nodeY,+ y: nodeY}if (addNode) {addNode(nodeWithTempId)@@ -135,9 +135,7 @@ export default function AddItemDialog() {setOpenFormDialog(false)// Show optimistic success messagetoast.success(- relatedNodeToAdd- ? `New relation added to ${relatedNodeToAdd.data.label}.`- : 'New node added.'+ relatedNodeToAdd ? `New relation added to ${relatedNodeToAdd.data.label}.` : 'New node added.')// Make API calls in the backgroundtry {@@ -245,12 +243,8 @@ export default function AddItemDialog() {</span>)}</div>- <div className='pt-6'>- <Button- size="sm"- onClick={handleImportData}- className="flex items-center gap-2"- >+ <div className="pt-6">+ <Button size="sm" onClick={handleImportData} className="flex items-center gap-2"><Upload className="h-4 w-4" />Import</Button>@@ -323,10 +317,7 @@ function ActionCard({ item, onSelect }: ActionCardProps) {><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')}- />+ <IconComponent /></div><div className="font-medium text-sm">{item.label}</div>{!item.children && <div className="text-sm mt-2 opacity-60">{item.description}</div>}diff --git a/flowsint-app/src/components/sketches/graph/image-cache.ts b/flowsint-app/src/components/sketches/graph/image-cache.tsdeleted file mode 100644index c52a75ea..00000000--- a/flowsint-app/src/components/sketches/graph/image-cache.ts+++ /dev/null@@ -1,35 +0,0 @@-const imageCache = new Map<string, HTMLImageElement>()-const imageLoadPromises = new Map<string, Promise<HTMLImageElement>>()--export const preloadImage = (iconType: string): Promise<HTMLImageElement> => {- const cacheKey = iconType-- if (imageCache.has(cacheKey)) {- return Promise.resolve(imageCache.get(cacheKey)!)- }-- if (imageLoadPromises.has(cacheKey)) {- return imageLoadPromises.get(cacheKey)!- }-- 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-}--export const getCachedImage = (iconType: string): HTMLImageElement | undefined => {- return imageCache.get(iconType)-}diff --git a/flowsint-app/src/components/sketches/graph/image-cache.tsx b/flowsint-app/src/components/sketches/graph/image-cache.tsxnew file mode 100644index 00000000..c9487aeb--- /dev/null+++ b/flowsint-app/src/components/sketches/graph/image-cache.tsx@@ -0,0 +1,131 @@+import { TYPE_TO_ICON } from '@/config/icon-mapping'+//@ts-ignore+import * as lucideIcons from 'lucide-react/dist/esm/icons'+import { renderToStaticMarkup } from 'react-dom/server'++const imageCache = new Map<string, HTMLImageElement>()+const imageLoadPromises = new Map<string, Promise<HTMLImageElement>>()++const createSvgDataUrl = (iconType: string, color: string = '#FFFFFF'): string => {+ const iconName = TYPE_TO_ICON[iconType] || TYPE_TO_ICON.default+ const IconComponent = (lucideIcons as any)[iconName]++ let svgString: string++ if (IconComponent) {+ try {+ svgString = renderToStaticMarkup(<IconComponent color={color} />)+ } catch (err) {+ console.warn('[icon] Failed to render icon, fallback used for', iconType)+ svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="${color}" stroke-width="2"><circle cx="12" cy="12" r="10"/></svg>`+ }+ } else {+ console.warn('[icon] Icon not found, fallback used for', iconType, iconName)+ svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="${color}" stroke-width="2"><circle cx="12" cy="12" r="10"/></svg>`+ }++ const utf8 = encodeURIComponent(svgString).replace(/%([0-9A-F]{2})/g, (_, p1) =>+ String.fromCharCode(parseInt(p1, 16))+ )++ return `data:image/svg+xml;base64,${btoa(utf8)}`+}++export const preloadImage = (+ iconType: string,+ color: string = '#FFFFFF'+): Promise<HTMLImageElement> => {+ const cacheKey = `${iconType}-${color}`++ if (imageCache.has(cacheKey)) {+ return Promise.resolve(imageCache.get(cacheKey)!)+ }++ if (imageLoadPromises.has(cacheKey)) {+ return imageLoadPromises.get(cacheKey)!+ }++ 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 = createSvgDataUrl(iconType, color)+ })++ imageLoadPromises.set(cacheKey, promise)+ return promise+}++export const getCachedImage = (+ iconType: string,+ color: string = '#FFFFFF'+): HTMLImageElement | undefined => {+ return imageCache.get(`${iconType}-${color}`)+}++const createFlagSvgDataUrl = (strokeColor: string, fillColor: string): string => {+ const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" fill="${fillColor}" stroke="${strokeColor}"/>+ <line x1="4" x2="4" y1="22" y2="15" stroke="${strokeColor}" fill="none"/>+</svg>`++ const utf8 = encodeURIComponent(svgString).replace(/%([0-9A-F]{2})/g, (_, p1) =>+ String.fromCharCode(parseInt(p1, 16))+ )++ return `data:image/svg+xml;base64,${btoa(utf8)}`+}++export const preloadFlagImage = (+ strokeColor: string,+ fillColor: string+): Promise<HTMLImageElement> => {+ const cacheKey = `flag-${strokeColor}-${fillColor}`++ if (imageCache.has(cacheKey)) {+ return Promise.resolve(imageCache.get(cacheKey)!)+ }++ if (imageLoadPromises.has(cacheKey)) {+ return imageLoadPromises.get(cacheKey)!+ }++ 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 flag with colors: ${strokeColor}, ${fillColor}`))+ }++ img.src = createFlagSvgDataUrl(strokeColor, fillColor)+ })++ imageLoadPromises.set(cacheKey, promise)+ return promise+}++export const getCachedFlagImage = (+ strokeColor: string,+ fillColor: string+): HTMLImageElement | undefined => {+ return imageCache.get(`flag-${strokeColor}-${fillColor}`)+}++export const clearImageCache = (): void => {+ imageCache.clear()+ imageLoadPromises.clear()+ console.log('[image-cache] Cache cleared')+}diff --git a/flowsint-app/src/components/sketches/graph/index.tsx b/flowsint-app/src/components/sketches/graph/index.tsxindex 48c4e8a4..237c4b2f 100644--- a/flowsint-app/src/components/sketches/graph/index.tsx+++ b/flowsint-app/src/components/sketches/graph/index.tsx@@ -113,12 +113,23 @@ const GraphViewer: React.FC<GraphViewerProps> = ({// Preload iconsuseEffect(() => {if (showIcons) {+ const isOutlined = forceSettings.nodeOutlined?.value ?? falseconst iconTypes = new Set(nodes.map((node) => node.data?.type as ItemType).filter(Boolean))- iconTypes.forEach((type) => {- preloadImage(type).catch(console.warn)- })++ if (isOutlined) {+ // In outlined mode, preload icons in both white and black+ iconTypes.forEach((type) => {+ preloadImage(type, '#FFFFFF').catch(console.warn) // for dark theme+ preloadImage(type, '#000000').catch(console.warn) // for light theme+ })+ } else {+ // In filled mode, preload icons with white color only+ iconTypes.forEach((type) => {+ preloadImage(type, '#FFFFFF').catch(console.warn)+ })+ }}- }, [nodes, showIcons])+ }, [nodes, showIcons, forceSettings.nodeOutlined?.value])// Container size managementuseEffect(() => {diff --git a/flowsint-app/src/components/sketches/graph/node-renderer.ts b/flowsint-app/src/components/sketches/graph/node-renderer.tsindex acfe2125..e7d7127f 100644--- a/flowsint-app/src/components/sketches/graph/node-renderer.ts+++ b/flowsint-app/src/components/sketches/graph/node-renderer.ts@@ -1,5 +1,5 @@import { CONSTANTS, GRAPH_COLORS } from './constants'-import { getCachedImage } from './image-cache'+import { getCachedImage, getCachedFlagImage } from './image-cache'import { truncateText } from './utils'interface NodeRenderParams {@@ -60,9 +60,7 @@ export const renderNode = ({const shouldRenderDetails = globalScale > CONSTANTS.ZOOM_NODE_DETAIL_THRESHOLD- const size = shouldRenderDetails- ? baseSize- : baseSize * CONSTANTS.ZOOMED_OUT_SIZE_MULTIPLIER+ const size = shouldRenderDetails ? baseSize : baseSize * CONSTANTS.ZOOMED_OUT_SIZE_MULTIPLIERconst isHighlighted = highlightNodes.has(node.id) || isSelected(node.id) || isCurrent(node.id)const hasAnyHighlight = highlightNodes.size > 0 || highlightLinks.size > 0@@ -80,29 +78,94 @@ export const renderNode = ({}// Set node color- if (hasAnyHighlight) {- ctx.fillStyle = isHighlighted ? node.nodeColor : `${node.nodeColor}7D`- } else {- ctx.fillStyle = node.nodeColor- }+ const nodeColor = hasAnyHighlight+ ? isHighlighted+ ? node.nodeColor+ : `${node.nodeColor}7D`+ : node.nodeColor++ const isOutlined = forceSettings.nodeOutlined?.value ?? false- // Draw node circle+ // Draw node circle (filled or outlined)ctx.beginPath()ctx.arc(node.x, node.y, size, 0, 2 * Math.PI)- ctx.fill()++ if (isOutlined) {+ ctx.strokeStyle = nodeColor+ ctx.lineWidth = Math.max(2, size * 0.15) / globalScale+ ctx.stroke()+ } else {+ ctx.fillStyle = nodeColor+ ctx.fill()+ // Draw subtle border for filled nodes+ ctx.beginPath()+ ctx.arc(node.x, node.y, size, 0, 2 * Math.PI)+ ctx.strokeStyle = theme === 'light' ? 'rgba(44, 44, 44, 0.19)' : 'rgba(222, 222, 222, 0.13)'+ ctx.lineWidth = 0.3+ ctx.stroke()+ }// Only render details if zoomed in enoughif (!shouldRenderDetails) return+ // Draw flag if present+ if (node.data?.flag) {+ const flagColors: Record<string, { stroke: string; fill: string }> = {+ red: { stroke: '#f87171', fill: '#fecaca' },+ orange: { stroke: '#fb923c', fill: '#fed7aa' },+ blue: { stroke: '#60a5fa', fill: '#bfdbfe' },+ green: { stroke: '#4ade80', fill: '#bbf7d0' },+ yellow: { stroke: '#facc15', fill: '#fef08a' }+ }++ const flagColor = flagColors[node.data.flag]+ if (flagColor) {+ const cachedFlag = getCachedFlagImage(flagColor.stroke, flagColor.fill)+ if (cachedFlag && cachedFlag.complete) {+ try {+ const flagSize = size * 0.8+ const flagX = node.x + 0.8 + size * 0.5 - flagSize / 2+ const flagY = node.y - 1.4 - size * 0.5 - flagSize / 2++ ctx.save()+ ctx.globalAlpha = 1+ ctx.drawImage(cachedFlag, flagX, flagY, flagSize, flagSize)+ ctx.restore()+ } catch (error) {+ console.warn('[node-renderer] Failed to draw flag:', error)+ }+ }+ }+ }+// Render iconsif (showIcons && node.nodeType) {- const cachedImage = getCachedImage(node.nodeType)+ // In outlined mode: white for dark theme, black for light theme+ // In filled mode: always white+ const iconColor = isOutlined+ ? (theme === 'dark' ? '#FFFFFF' : '#000000')+ : '#FFFFFF'+ const cachedImage = getCachedImage(node.nodeType, iconColor)if (cachedImage && cachedImage.complete) {try {- ctx.drawImage(cachedImage, node.x - size / 2, node.y - size / 2, size, size)- } catch (error) {- // Silent fail- }+ // Dessiner l'icône au centre du node+ const iconSize = size * 1.2+ ctx.save()+ // Apply transparency if node is not highlighted+ const iconAlpha = hasAnyHighlight && !isHighlighted ? 0.5 : 0.9+ ctx.globalAlpha = iconAlpha+ ctx.drawImage(cachedImage, node.x - iconSize / 2, node.y - iconSize / 2, iconSize, iconSize)+ ctx.restore()+ } catch (error) {}+ } else {+ console.warn(+ '[node-renderer] No cached image for type:',+ node.nodeType,+ 'color:',+ iconColor,+ 'complete:',+ cachedImage?.complete+ )}}@@ -132,28 +195,26 @@ export const renderNode = ({ctx.roundRect(bgX, bgY, bgWidth, bgHeight, borderRadius)if (theme === 'light') {- ctx.fillStyle = isHighlighted- ? 'rgba(255, 255, 255, 0.95)'- : 'rgba(255, 255, 255, 0.75)'+ ctx.fillStyle = isHighlighted ? 'rgba(255, 255, 255, 0.95)' : 'rgba(255, 255, 255, 0.75)'} else {- ctx.fillStyle = isHighlighted- ? 'rgba(32, 32, 32, 0.95)'- : 'rgba(32, 32, 32, 0.75)'+ ctx.fillStyle = isHighlighted ? 'rgba(32, 32, 32, 0.95)' : 'rgba(32, 32, 32, 0.75)'}ctx.fill()- ctx.strokeStyle = theme === 'light'- ? 'rgba(0, 0, 0, 0.1)'- : 'rgba(255, 255, 255, 0.1)'+ ctx.strokeStyle = theme === 'light' ? 'rgba(0, 0, 0, 0.1)' : 'rgba(255, 255, 255, 0.1)'ctx.lineWidth = 0.1ctx.stroke()- // Draw text+ // Draw text with consistent baseline across browsersconst color = theme === 'light' ? GRAPH_COLORS.TEXT_LIGHT : GRAPH_COLORS.TEXT_DARKctx.textAlign = 'center'- ctx.textBaseline = 'middle'+ ctx.textBaseline = 'alphabetic' // More consistent across browsers than 'middle'ctx.fillStyle = isHighlighted ? color : `${color}CC`- ctx.fillText(label, node.x, bgY + bgHeight / 2)++ const metrics = ctx.measureText(label)+ const textY = bgY + paddingY + metrics.actualBoundingBoxAscent++ ctx.fillText(label, node.x, textY)}}}diff --git a/flowsint-app/src/config/icon-mapping.ts b/flowsint-app/src/config/icon-mapping.tsnew file mode 100644index 00000000..b26dc0d3--- /dev/null+++ b/flowsint-app/src/config/icon-mapping.ts@@ -0,0 +1,58 @@+import type * as LucideIcons from 'lucide-react'++export const TYPE_TO_ICON: Record<string, keyof typeof LucideIcons> = {+ individual: 'User',+ phone: 'Phone',+ location: 'MapPin',+ email: 'Mail',+ ip: 'Network',+ port: 'Plug',+ socialaccount: 'Share2',+ organization: 'Building2',+ vehicle: 'Car',+ car: 'Car',+ motorcycle: 'Bike',+ boat: 'Ship',+ plane: 'Plane',+ website: 'Globe',+ domain: 'Globe',+ document: 'FileText',+ financial: 'DollarSign',+ event: 'Calendar',+ device: 'Smartphone',+ media: 'Image',+ education: 'GraduationCap',+ relationship: 'Users',+ online_activity: 'Activity',+ digital_footprint: 'Footprints',+ biometric: 'Fingerprint',+ credential: 'Key',+ username: 'UserCircle',+ siret: 'Building',+ siren: 'Building',+ cryptowallet: 'Wallet',+ cryptotransaction: 'ArrowRightLeft',+ cryptonft: 'Image',+ asn: 'Network',+ cidr: 'Network',+ whois: 'Info',+ gravatar: 'UserCircle',+ breach: 'ShieldAlert',+ webtracker: 'Target',+ session: 'Clock',+ dnsrecord: 'Database',+ ssl: 'Lock',+ message: 'MessageSquare',+ malware: 'Bug',+ weapon: 'Sword',+ script: 'FileCode',+ reputation: 'Star',+ risk: 'AlertTriangle',+ file: 'File',+ bank: 'Landmark',+ creditcard: 'CreditCard',+ alias: 'UserCog',+ affiliation: 'Link2',+ phrase: 'Quote',+ default: 'Circle'+}diff --git a/flowsint-app/src/hooks/use-icon.tsx b/flowsint-app/src/hooks/use-icon.tsxindex 8bc3dbe3..59f3909f 100644--- a/flowsint-app/src/hooks/use-icon.tsx+++ b/flowsint-app/src/hooks/use-icon.tsx@@ -1,5 +1,8 @@-import { type JSX, useMemo, useCallback } from 'react'+import { type JSX, useCallback } from 'react'import { useNodesDisplaySettings } from '@/stores/node-display-settings'+import * as LucideIcons from 'lucide-react'+import { TYPE_TO_ICON } from '@/config/icon-mapping'+import { cn } from '@/lib/utils'export type IconType = string@@ -10,24 +13,16 @@ interface IconProps {showBorder?: booleancolor?: stringtype?: string+ iconOnly?: boolean}-// Utilisation de constantes pour les valeurs par défautconst DEFAULT_SIZE = 24-const DEFAULT_COLOR = '#000000'+const DEFAULT_COLOR = '#FFFFFF'const BORDER_RATIO = 8const CONTAINER_PADDING = 16const BACKGROUND_PADDING = 8-// Fonctions utilitaires memoizées-const getIconPath = (type: string): string => `/icons/${type}.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(), [])-return useCallback(({className = '',@@ -35,44 +30,57 @@ export const useIcon = (type: IconType, src?: string | null) => {style,showBorder = false,color,- // @ts-ignore- type: iconType+ iconOnly = false}: 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]- )-// Use full size for src images, scaled size for iconsconst 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`}+ // Si src est fourni, utiliser une image+ if (src) {+ const imageElement = (+ <img+ src={src}+ 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`}+ />+ )+ if (iconOnly) return imageElement+ }++ // Utiliser une icône Lucide (PERFORMANT - pas de requête HTTP)+ const iconName = TYPE_TO_ICON[type] || TYPE_TO_ICON.default+ const LucideIcon = LucideIcons[iconName] as React.ComponentType<{+ size?: number+ fontSize?: number+ className?: string+ style?: React.CSSProperties+ }>++ const iconElement = (+ <LucideIcon+ size={actualIconSize}+ fontSize={1}+ className={cn(`flex-shrink-0`, !iconOnly && !showBorder && 'text-white', className)}style={{- minWidth: actualIconSize,- minHeight: actualIconSize,- maxWidth: actualIconSize,- maxHeight: actualIconSize,...(showBorder ? undefined : style)}}- alt={`${type} icon`}- onError={handleImageError}/>)+ if (iconOnly) return iconElement+if (showBorder) {const containerSize = size + CONTAINER_PADDINGconst borderWidth = Math.max(1, size / BORDER_RATIO)@@ -91,7 +99,7 @@ export const useIcon = (type: IconType, src?: string | null) => {...style}}>- {imageElement}+ {iconElement}</div>)}@@ -110,10 +118,10 @@ export const useIcon = (type: IconType, src?: string | null) => {maxHeight: containerSize}}>- {imageElement}+ {iconElement}</div>)},- [iconPath, defaultIconPath, type]+ [type, src])}diff --git a/flowsint-app/src/stores/graph-settings-store.ts b/flowsint-app/src/stores/graph-settings-store.tsindex 9d5515fb..62528c27 100644--- a/flowsint-app/src/stores/graph-settings-store.ts+++ b/flowsint-app/src/stores/graph-settings-store.ts@@ -25,6 +25,12 @@ const DEFAULT_SETTINGS = {}},graph: {+ nodeOutlined: {+ name: 'Node style (outlined/fill)',+ type: 'boolean',+ value: false,+ description: 'Node style, filled by default.'+ },nodeSize: {name: 'Node Size',type: 'number',@@ -368,7 +374,7 @@ type GraphGeneralSettingsStore = {}// Storage version - increment this whenever you make breaking changes to DEFAULT_SETTINGS-const STORAGE_VERSION = 2+const STORAGE_VERSION = 3export const useGraphSettingsStore = create<GraphGeneralSettingsStore>()(persist(