A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
feat: org to asn, asn to cidr, ip to asn
dextmorgnb8914ae8c01f
diff --git a/flowsint-api/alembic/versions/fa0ab51b2f64_add_analysis_model_and_investigation_.py b/flowsint-api/alembic/versions/fa0ab51b2f64_add_analysis_model_and_investigation_.pynew file mode 100644index 00000000..1fb2498a--- /dev/null+++ b/flowsint-api/alembic/versions/fa0ab51b2f64_add_analysis_model_and_investigation_.py@@ -0,0 +1,48 @@+"""add analysis model and investigation relationship++Revision ID: fa0ab51b2f64+Revises: 76f5436251e3+Create Date: 2025-06-04 11:15:03.736931++"""+from typing import Sequence, Union++from alembic import op+import sqlalchemy as sa+++# revision identifiers, used by Alembic.+revision: str = 'fa0ab51b2f64'+down_revision: Union[str, None] = '76f5436251e3'+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ """Upgrade schema."""+ # ### commands auto generated by Alembic - please adjust! ###+ op.create_table('analyses',+ sa.Column('id', sa.UUID(), nullable=False),+ sa.Column('title', sa.Text(), nullable=False),+ sa.Column('description', sa.Text(), nullable=True),+ sa.Column('content', sa.JSON(), nullable=True),+ sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),+ sa.Column('last_updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),+ sa.Column('owner_id', sa.UUID(), nullable=True),+ sa.Column('investigation_id', sa.UUID(), nullable=True),+ sa.ForeignKeyConstraint(['investigation_id'], ['investigations.id'], onupdate='CASCADE', ondelete='CASCADE'),+ sa.ForeignKeyConstraint(['owner_id'], ['profiles.id'], onupdate='CASCADE', ondelete='CASCADE'),+ sa.PrimaryKeyConstraint('id')+ )+ op.create_index('idx_analyses_investigation_id', 'analyses', ['investigation_id'], unique=False)+ op.create_index('idx_analyses_owner_id', 'analyses', ['owner_id'], unique=False)+ # ### end Alembic commands ###+++def downgrade() -> None:+ """Downgrade schema."""+ # ### commands auto generated by Alembic - please adjust! ###+ op.drop_index('idx_analyses_owner_id', table_name='analyses')+ op.drop_index('idx_analyses_investigation_id', table_name='analyses')+ op.drop_table('analyses')+ # ### end Alembic commands ###diff --git a/flowsint-api/app/api/routes/analysis.py b/flowsint-api/app/api/routes/analysis.pynew file mode 100644index 00000000..a9b3f512--- /dev/null+++ b/flowsint-api/app/api/routes/analysis.py@@ -0,0 +1,85 @@+from uuid import UUID, uuid4+from fastapi import APIRouter, HTTPException, Depends, status+from typing import List+from datetime import datetime+from sqlalchemy.orm import Session, selectinload+from app.core.postgre_db import get_db+from app.models.models import Analysis, Profile+from app.api.deps import get_current_user+from app.api.schemas.analysis import AnalysisRead, AnalysisCreate, AnalysisUpdate++router = APIRouter()++# Get the list of all analyses for the current user[email protected]("", response_model=List[AnalysisRead])+def get_analyses(db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):+ analyses = db.query(Analysis).filter(Analysis.owner_id == current_user.id).all()+ return analyses++# Create a new analysis[email protected]("/create", response_model=AnalysisRead, status_code=status.HTTP_201_CREATED)+def create_analysis(payload: AnalysisCreate, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):+ new_analysis = Analysis(+ id=uuid4(),+ title=payload.title,+ description=payload.description,+ content=payload.content,+ owner_id=current_user.id,+ investigation_id=payload.investigation_id,+ created_at=datetime.utcnow(),+ last_updated_at=datetime.utcnow(),+ )+ db.add(new_analysis)+ db.commit()+ db.refresh(new_analysis)+ return new_analysis++# Get an analysis by ID[email protected]("/{analysis_id}", response_model=AnalysisRead)+def get_analysis_by_id(analysis_id: UUID, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):+ analysis = db.query(Analysis).filter(Analysis.id == analysis_id, Analysis.owner_id == current_user.id).first()+ if not analysis:+ raise HTTPException(status_code=404, detail="Analysis not found")+ return analysis++# Get analyses by investigation ID[email protected]("/investigation/{investigation_id}", response_model=List[AnalysisRead])+def get_analyses_by_investigation(+ investigation_id: UUID,+ db: Session = Depends(get_db),+ current_user: Profile = Depends(get_current_user)+):+ analyses = db.query(Analysis).filter(+ Analysis.investigation_id == investigation_id,+ Analysis.owner_id == current_user.id+ ).all()+ return analyses++# Update an analysis by ID[email protected]("/{analysis_id}", response_model=AnalysisRead)+def update_analysis(analysis_id: UUID, payload: AnalysisUpdate, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):+ analysis = db.query(Analysis).filter(Analysis.id == analysis_id, Analysis.owner_id == current_user.id).first()+ if not analysis:+ raise HTTPException(status_code=404, detail="Analysis not found")+ if payload.title is not None:+ analysis.title = payload.title+ if payload.description is not None:+ analysis.description = payload.description+ if payload.content is not None:+ analysis.content = payload.content+ if payload.investigation_id is not None:+ analysis.investigation_id = payload.investigation_id+ analysis.last_updated_at = datetime.utcnow()+ db.commit()+ db.refresh(analysis)+ return analysis++# Delete an analysis by ID[email protected]("/{analysis_id}", status_code=status.HTTP_204_NO_CONTENT)+def delete_analysis(analysis_id: UUID, db: Session = Depends(get_db), current_user: Profile = Depends(get_current_user)):+ analysis = db.query(Analysis).filter(Analysis.id == analysis_id, Analysis.owner_id == current_user.id).first()+ if not analysis:+ raise HTTPException(status_code=404, detail="Analysis not found")+ db.delete(analysis)+ db.commit()+ return None\ No newline at end of filediff --git a/flowsint-api/app/api/routes/sketches.py b/flowsint-api/app/api/routes/sketches.pyindex c1a3893b..6f0ad1ec 100644--- a/flowsint-api/app/api/routes/sketches.py+++ b/flowsint-api/app/api/routes/sketches.py@@ -84,7 +84,7 @@ async def get_sketch_nodes(id: str, db: Session = Depends(get_db), current_user:MATCH (n)WHERE n.sketch_id = $sketch_idRETURN elementId(n) as id, labels(n) as labels, properties(n) as data- LIMIT 10000+ LIMIT 100000"""nodes_result = neo4j_connection.query(nodes_query, parameters={"sketch_id": id})@@ -107,9 +107,10 @@ async def get_sketch_nodes(id: str, db: Session = Depends(get_db), current_user:"type": record["labels"][0].lower(),"caption": record["data"].get("label", "Node"),"x": random.random() * 1000,- "y": random.random() * 1000+ "y": random.random() * 1000,+ "idx": idx}- for record in nodes_result+ for idx, record in enumerate(nodes_result)]rels = [diff --git a/flowsint-api/app/api/routes/transforms.py b/flowsint-api/app/api/routes/transforms.pyindex c6f67577..7cfef0c4 100644--- a/flowsint-api/app/api/routes/transforms.py+++ b/flowsint-api/app/api/routes/transforms.py@@ -2,7 +2,6 @@ from uuid import UUID, uuid4from fastapi import APIRouter, HTTPException, Depends, status, Queryfrom typing import Dict, List, Any, Optionalfrom pydantic import BaseModel-import jsonfrom datetime import datetimefrom app.utils import extract_input_schemafrom app.scanners.registry import ScannerRegistry@@ -18,6 +17,9 @@ from app.core.postgre_db import get_dbfrom app.models.models import Transform, Profilefrom app.api.deps import get_current_userfrom app.api.schemas.transform import TransformRead, TransformCreate, TransformUpdate+from app.types.asn import ASN+from app.types.cidr import CIDR+class FlowComputationRequest(BaseModel):nodes: List[Node]@@ -45,9 +47,9 @@ def get_transforms(db: Session = Depends(get_db),current_user: Profile = Depends(get_current_user)):- query = db.query(Transform)# if category is not None and category != "undefined":# query = query.filter(Transform.category.any(category))+ query = db.query(Transform).order_by(Transform.last_updated_at.desc())return query.all()# Returns the "raw_materials" for the transform editor@@ -72,12 +74,15 @@ async def get_scans_list(current_user: Profile = Depends(get_current_user)):# Ajoute les types comme des "scanners" spéciaux de type 'type'object_inputs = [- extract_input_schema("MinimalDomain", MinimalDomain),- extract_input_schema("MinimalIp", MinimalIp),- extract_input_schema("MinimalSocial", MinimalSocial),+ extract_input_schema("Domain", MinimalDomain),+ extract_input_schema("ASN", ASN),+ extract_input_schema("CIDR", CIDR),+ extract_input_schema("IP address", MinimalIp),+ extract_input_schema("Social profile", MinimalSocial),extract_input_schema("Email", Email),- extract_input_schema("MinimalOrganization", MinimalOrganization)+ extract_input_schema("Organization", MinimalOrganization)]+ print(extract_input_schema("ASN", ASN))flattened_scanners["types"] = object_inputsdiff --git a/flowsint-api/app/api/schemas/analysis.py b/flowsint-api/app/api/schemas/analysis.pynew file mode 100644index 00000000..0dbd8933--- /dev/null+++ b/flowsint-api/app/api/schemas/analysis.py@@ -0,0 +1,29 @@+from .base import ORMBase+from pydantic import UUID4, BaseModel+from typing import Optional, Any+from datetime import datetime++class AnalysisCreate(BaseModel):+ title: str+ description: Optional[str] = None+ content: Optional[Any] = None+ owner_id: Optional[UUID4] = None+ investigation_id: Optional[UUID4] = None++class AnalysisRead(ORMBase):+ id: UUID4+ title: str+ description: Optional[str]+ content: Optional[Any]+ created_at: datetime+ last_updated_at: datetime+ owner_id: Optional[UUID4]+ investigation_id: Optional[UUID4]++class AnalysisUpdate(BaseModel):+ title: Optional[str] = None+ description: Optional[str] = None+ content: Optional[Any] = None+ last_updated_at: Optional[datetime] = None+ owner_id: Optional[UUID4] = None+ investigation_id: Optional[UUID4] = None\ No newline at end of filediff --git a/flowsint-api/app/core/logger.py b/flowsint-api/app/core/logger.pyindex 9fbfb253..dca7f042 100644--- a/flowsint-api/app/core/logger.py+++ b/flowsint-api/app/core/logger.py@@ -59,10 +59,10 @@ class Logger:log = self._create_log("ERROR", formatted_message)emit_log_task.delay(str(log.id), self.scan_id, "ERROR", formatted_message)- def warning(self, message: str):+ def warn(self, message: str):"""Log a warning message"""formatted_message = self._format_message("WARNING", message)- logger.warning(formatted_message)+ logger.warn(formatted_message)log = self._create_log("WARNING", formatted_message)emit_log_task.delay(str(log.id), self.scan_id, "WARNING", formatted_message)diff --git a/flowsint-api/app/main.py b/flowsint-api/app/main.pyindex 2de690a0..7e5ce30e 100644--- a/flowsint-api/app/main.py+++ b/flowsint-api/app/main.py@@ -1,5 +1,4 @@-from fastapi import FastAPI, Depends-from app.scanners.registry import ScannerRegistry+from fastapi import FastAPIfrom app.core.graph_db import Neo4jConnectionfrom app.core.events import init_eventsimport os@@ -12,10 +11,8 @@ from app.api.routes import investigationsfrom app.api.routes import sketchesfrom app.api.routes import transformsfrom app.api.routes import logs-from sqlalchemy.orm import Session-from app.core.postgre_db import get_db-from app.api.schemas.log import LogSchema-from app.models.models import Log+from app.api.routes import analysis+load_dotenv()URI = os.getenv("NEO4J_URI_BOLT")@@ -56,6 +53,7 @@ app.include_router(sketches.router, prefix="/api/sketches", tags=["sketches"])app.include_router(investigations.router, prefix="/api/investigations", tags=["investigations"])app.include_router(transforms.router, prefix="/api/transforms", tags=["transforms"])app.include_router(logs.router, prefix="/api/logs", tags=["logs"])+app.include_router(analysis.router, prefix="/api/analyses", tags=["analyses"])# Initialize event systeminit_events(app)diff --git a/flowsint-api/app/models/models.py b/flowsint-api/app/models/models.pyindex c4fee738..f9e3b426 100644--- a/flowsint-api/app/models/models.py+++ b/flowsint-api/app/models/models.py@@ -30,6 +30,7 @@ class Investigation(Base):last_updated_at = mapped_column(DateTime(timezone=True), server_default=func.now())status = mapped_column(String, server_default='active')sketches = relationship("Sketch", back_populates="investigation")+ analyses = relationship("Analysis", back_populates="investigation")__table_args__ = (Index("idx_investigations_id", "id"),Index("idx_investigations_owner_id", "owner_id"),@@ -135,4 +136,23 @@ class Transform(Base):category = mapped_column(ARRAY(Text), nullable=True)transform_schema = mapped_column(JSON, nullable=True)created_at = mapped_column(DateTime(timezone=True), server_default=func.now())- last_updated_at = mapped_column(DateTime(timezone=True), server_default=func.now())\ No newline at end of file+ last_updated_at = mapped_column(DateTime(timezone=True), server_default=func.now())+++class Analysis(Base):+ __tablename__ = "analyses"++ id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ title = mapped_column(Text, nullable=False)+ description = mapped_column(Text, nullable=True)+ content = mapped_column(JSON, nullable=True)+ created_at = mapped_column(DateTime(timezone=True), server_default=func.now())+ last_updated_at = mapped_column(DateTime(timezone=True), server_default=func.now())+ owner_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("profiles.id", onupdate="CASCADE", ondelete="CASCADE"), nullable=True)+ investigation_id = mapped_column(PGUUID(as_uuid=True), ForeignKey("investigations.id", onupdate="CASCADE", ondelete="CASCADE"), nullable=True)+ investigation = relationship("Investigation", back_populates="analyses")++ __table_args__ = (+ Index("idx_analyses_owner_id", "owner_id"),+ Index("idx_analyses_investigation_id", "investigation_id"),+ )\ No newline at end of filediff --git a/flowsint-api/app/scanners/domains/resolve.py b/flowsint-api/app/scanners/domains/resolve.pyindex d20d8eff..974c87c1 100644--- a/flowsint-api/app/scanners/domains/resolve.py+++ b/flowsint-api/app/scanners/domains/resolve.py@@ -60,7 +60,7 @@ class ResolveScanner(Scanner):domain_obj = MinimalDomain(domain=item["domain"])elif isinstance(item, MinimalDomain):domain_obj = item- if domain_obj and is_valid_domain(domain_obj.domain) != "invalid":+ if domain_obj and is_valid_domain(domain_obj.domain):cleaned.append(domain_obj)return cleaneddiff --git a/flowsint-api/app/scanners/domains/subdomains.py b/flowsint-api/app/scanners/domains/subdomains.pyindex 93f9d7f6..0ce18eb4 100644--- a/flowsint-api/app/scanners/domains/subdomains.py+++ b/flowsint-api/app/scanners/domains/subdomains.py@@ -63,7 +63,7 @@ class SubdomainScanner(Scanner):domain_obj = MinimalDomain(domain=item["domain"])elif isinstance(item, MinimalDomain):domain_obj = item- if domain_obj and is_valid_domain(domain_obj.domain) != "invalid":+ if domain_obj and is_valid_domain(domain_obj.domain):cleaned.append(domain_obj)self.logger.debug(message=f"[SUBDOMAIN_SCANNER]: postprocessed: {str(cleaned)}")return cleaneddiff --git a/flowsint-api/app/scanners/domains/whois.py b/flowsint-api/app/scanners/domains/whois.pyindex 9b2f8a23..a86706b5 100644--- a/flowsint-api/app/scanners/domains/whois.py+++ b/flowsint-api/app/scanners/domains/whois.py@@ -63,7 +63,7 @@ class WhoisScanner(Scanner):domain_obj = MinimalDomain(domain=item["domain"])elif isinstance(item, MinimalDomain):domain_obj = item- if domain_obj and is_valid_domain(domain_obj.domain) != "invalid":+ if domain_obj and is_valid_domain(domain_obj.domain):cleaned.append(domain_obj)return cleaneddiff --git a/flowsint-api/app/scanners/emails/ghunt.py b/flowsint-api/app/scanners/emails/ghunt.pydeleted file mode 100644index 77d9c8e6..00000000--- a/flowsint-api/app/scanners/emails/ghunt.py+++ /dev/null@@ -1,74 +0,0 @@-import json-import uuid-from typing import Dict, Any, List-from pathlib import Path-from app.scanners.base import Scanner-import tempfile--class GHuntGmailScanner(Scanner):- @classmethod- def name(self) -> str:- return "ghunt_gmail_scanner"-- @classmethod- def category(self) -> str:- return "emails"-- @classmethod- def key(self) -> str:- return "email"-- @classmethod- def input_schema(self) -> Dict[str, str]:- return ["email"]-- @classmethod- def output_schema(self) -> Dict[str, str]:- return ["full_name", "social_profile", "leak_info", "email", "number", "location", "profile_picture", "metadata"]-- async def scan(self, emails: List[str]) -> List[Dict[str, Any]]:- results = []-- for email in emails:- report_id = str(uuid.uuid4())-- with tempfile.NamedTemporaryFile(delete=False) as temp_file:- output_file = temp_file.name-- try:- from ghunt.modules import email as email_module- await email_module.hunt(None, email, output_file)-- if not Path(output_file).exists():- results.append({- "email": email,- "error": "GHunt did not produce any output file."- })- continue-- with open(output_file, "r") as f:- scan_results = json.load(f)-- results.append({- "email": email,- "report_id": report_id,- "scanner": self.name(),- "results": scan_results- })-- except Exception as e:- results.append({- "email": email,- "error": f"Exception during GHunt Gmail scan: {str(e)}"- })-- return results-- def postprocess(self, results: List[Dict[str, Any]]) -> List[Dict[str, Any]]:- """- Ajoute des métadonnées supplémentaires aux résultats.- """- for result in results:- result["scanner"] = "ghunt_gmail"- result["count"] = len(result.get("results", {}).get("found", [])) # Ajusté en fonction de la structure de résultats- return {"output":results}diff --git a/flowsint-api/app/scanners/ips/asn_to_cidrs.py b/flowsint-api/app/scanners/ips/asn_to_cidrs.pynew file mode 100644index 00000000..bd7a550a--- /dev/null+++ b/flowsint-api/app/scanners/ips/asn_to_cidrs.py@@ -0,0 +1,173 @@+import json+import socket+import subprocess+from typing import List, Dict, Any, TypeAlias, Union+from pydantic import TypeAdapter+from app.scanners.base import Scanner+from app.types.cidr import CIDR+from app.types.ip import MinimalIp+from app.types.asn import ASN+from app.utils import is_valid_asn, parse_asn, resolve_type++InputType: TypeAlias = List[ASN]+OutputType: TypeAlias = List[CIDR]++class AsnToCidrsScanner(Scanner):+ """Takes an ASN and returns its corresponding CIDRs."""++ @classmethod+ def name(cls) -> str:+ return "asn_to_cidrs_scanner"++ @classmethod+ def category(cls) -> str:+ return "asns"++ @classmethod+ def key(cls) -> str:+ return "number"++ @classmethod+ def input_schema(cls) -> Dict[str, Any]:+ adapter = TypeAdapter(InputType)+ schema = adapter.json_schema()+ type_name, details = list(schema["$defs"].items())[0]+ return {+ "type": type_name,+ "properties": [+ {"name": prop, "type": resolve_type(info)}+ for prop, info in details["properties"].items()+ ]+ }++ @classmethod+ def output_schema(cls) -> Dict[str, Any]:+ adapter = TypeAdapter(OutputType)+ schema = adapter.json_schema()+ type_name, details = list(schema["$defs"].items())[0]+ return {+ "type": type_name,+ "properties": [+ {"name": prop, "type": resolve_type(info)}+ for prop, info in details["properties"].items()+ ]+ }++ def preprocess(self, data: Union[List[str], List[int], List[dict], InputType]) -> InputType:+ cleaned: InputType = []+ for item in data:+ asn_obj = None+ try:+ if isinstance(item, (str, int)):+ asn_obj = ASN(number=parse_asn(str(item)))+ elif isinstance(item, dict) and "number" in item:+ asn_obj = ASN(number=parse_asn(str(item["number"])))+ elif isinstance(item, ASN):+ asn_obj = item+ if asn_obj and is_valid_asn(str(asn_obj.number)):+ cleaned.append(asn_obj)+ except ValueError:+ self.logger.warn(f"Invalid ASN format: {item}")+ continue+ return cleaned++ def scan(self, data: InputType) -> OutputType:+ """Find CIDR from ASN using asnmap."""+ cidrs: OutputType = []+ self.logger.debug(message=f"[ASN_TO_CIDRS_SCANNER]: input data: {str(data)}")++ for asn in data:+ cidr_data = self.__get_cidrs_from_asn(asn.number)+ if cidr_data and "as_range" in cidr_data and cidr_data["as_range"]:+ # Add all CIDRs for this ASN+ for cidr_str in cidr_data["as_range"]:+ try:+ cidr = CIDR(network=cidr_str)+ cidrs.append(cidr)+ except Exception as e:+ self.logger.error(f"Failed to parse CIDR {cidr_str}: {str(e)}")+ # If no valid CIDRs were added, add the default one+ if not any(str(c.network) != "0.0.0.0/0" for c in cidrs):+ cidrs.append(CIDR(network="0.0.0.0/0"))+ else:+ self.logger.warn(f"No CIDRs found for ASN {asn.number}")+ # Add an empty CIDR to maintain input/output mapping+ cidrs.append(CIDR(network="0.0.0.0/0"))++ return cidrs++ def __get_cidrs_from_asn(self, asn: int) -> Dict[str, Any]:+ try:+ command = f"echo {asn} | asnmap -silent -json | jq -s '.'"+ result = subprocess.run(+ command,+ shell=True,+ capture_output=True, text=True, timeout=60+ )+ if not result.stdout.strip():+ self.logger.info(f"No CIDRs found for {asn}.")+ return None+ try:+ # Parse the JSON array+ data_array = json.loads(result.stdout)+ if not data_array:+ return None++ combined_data = {+ "as_range": [],+ "as_name": None,+ "as_country": None,+ "as_number": None+ }++ for data in data_array:+ if "as_range" in data:+ combined_data["as_range"].extend(data["as_range"])+ if data.get("as_name") and not combined_data["as_name"]:+ combined_data["as_name"] = data["as_name"]+ if data.get("as_country") and not combined_data["as_country"]:+ combined_data["as_country"] = data["as_country"]+ if data.get("as_number") and not combined_data["as_number"]:+ combined_data["as_number"] = data["as_number"]++ return combined_data if combined_data["as_range"] else None++ except json.JSONDecodeError:+ self.logger.error(f"Failed to parse JSON from asnmap output: {result.stdout}")+ return None++ except Exception as e:+ self.logger.error(message=f"asnmap exception for {asn}: {str(e)}")+ return None++ def postprocess(self, results: OutputType, original_input: InputType) -> OutputType:+ # Create Neo4j relationships between ASNs and their corresponding CIDRs+ for asn, cidr in zip(original_input, results):+ if self.neo4j_conn:+ query = """+ MERGE (asn:ASN {number: $asn_number})+ SET asn.sketch_id = $sketch_id,+ asn.name = $asn_name,+ asn.country = $asn_country,+ asn.label = $asn_label,+ asn.caption = $asn_caption,+ asn.type = "asn"++ MERGE (cidr:CIDR {network: $cidr_network})+ SET cidr.sketch_id = $sketch_id,+ cidr.label = $cidr_network,+ cidr.caption = $cidr_network,+ cidr.type = "cidr"++ MERGE (asn)-[:ANNOUNCES {sketch_id: $sketch_id}]->(cidr)+ """+ self.neo4j_conn.query(query, {+ "asn_number": asn.number,+ "asn_name": asn.name or "Unknown",+ "asn_country": asn.country or "Unknown",+ "asn_label": f"AS{asn.number}",+ "asn_caption": f"AS{asn.number} - {asn.name or 'Unknown'}",+ "cidr_network": str(cidr.network),+ "sketch_id": self.sketch_id,+ })+ return results\ No newline at end of filediff --git a/flowsint-api/app/scanners/ips/cidr_to_ips.py b/flowsint-api/app/scanners/ips/cidr_to_ips.pynew file mode 100644index 00000000..fd3234a7--- /dev/null+++ b/flowsint-api/app/scanners/ips/cidr_to_ips.py@@ -0,0 +1,134 @@+import subprocess+from typing import List, Dict, Any, TypeAlias, Union+from pydantic import TypeAdapter+from app.scanners.base import Scanner+from app.types.cidr import CIDR+from app.types.ip import MinimalIp+from app.utils import resolve_type++InputType: TypeAlias = List[CIDR]+OutputType: TypeAlias = List[MinimalIp]++class CidrToIpsScanner(Scanner):+ """Takes a CIDR and returns its corresponding IP addresses."""++ @classmethod+ def name(cls) -> str:+ return "cidr_to_ips_scanner"++ @classmethod+ def category(cls) -> str:+ return "cidrs"++ @classmethod+ def key(cls) -> str:+ return "network"++ @classmethod+ def input_schema(cls) -> Dict[str, Any]:+ adapter = TypeAdapter(InputType)+ schema = adapter.json_schema()+ type_name, details = list(schema["$defs"].items())[0]+ return {+ "type": type_name,+ "properties": [+ {"name": prop, "type": resolve_type(info)}+ for prop, info in details["properties"].items()+ ]+ }++ @classmethod+ def output_schema(cls) -> Dict[str, Any]:+ adapter = TypeAdapter(OutputType)+ schema = adapter.json_schema()+ type_name, details = list(schema["$defs"].items())[0]+ return {+ "type": type_name,+ "properties": [+ {"name": prop, "type": resolve_type(info)}+ for prop, info in details["properties"].items()+ ]+ }++ def preprocess(self, data: Union[List[str], List[dict], InputType]) -> InputType:+ cleaned: InputType = []+ for item in data:+ cidr_obj = None+ try:+ if isinstance(item, str):+ cidr_obj = CIDR(network=item)+ elif isinstance(item, dict) and "network" in item:+ cidr_obj = CIDR(network=item["network"])+ elif isinstance(item, CIDR):+ cidr_obj = item+ if cidr_obj:+ cleaned.append(cidr_obj)+ except ValueError:+ self.logger.warn(f"Invalid CIDR format: {item}")+ continue+ return cleaned++ def scan(self, data: InputType) -> OutputType:+ """Find IP addresses from CIDR using dnsx."""+ ips: OutputType = []+ self.logger.debug(message=f"[CIDR_TO_IPS_SCANNER]: input data: {str(data)}")+ for cidr in data:+ ip_addresses = self.__get_ips_from_cidr(cidr.network)+ if ip_addresses:+ for ip_str in ip_addresses:+ try:+ ip = MinimalIp(address=ip_str.strip())+ ips.append(ip)+ except Exception as e:+ self.logger.error(f"Failed to parse IP {ip_str}: {str(e)}")+ else:+ self.logger.warn(f"No IPs found for CIDR {cidr.network}")+ return ips++ def __get_ips_from_cidr(self, cidr: str) -> List[str]:+ try:+ command = f"echo {cidr} | dnsx -ptr"+ result = subprocess.run(+ command,+ shell=True,+ capture_output=True,+ text=True,+ timeout=60+ )+ if not result.stdout.strip():+ self.logger.info(f"No IPs found for {cidr}.")+ return []++ # Split the output by newlines and filter out empty lines+ ip_addresses = [ip.strip() for ip in result.stdout.split('\n') if ip.strip()]+ return ip_addresses++ except Exception as e:+ self.logger.error(message=f"dnsx exception for {cidr}: {str(e)}")+ return []++ def postprocess(self, results: OutputType, original_input: InputType) -> OutputType:+ # Create Neo4j relationships between CIDRs and their corresponding IPs+ for cidr, ip in zip(original_input, results):+ if self.neo4j_conn:+ query = """+ MERGE (cidr:CIDR {network: $cidr_network})+ SET cidr.sketch_id = $sketch_id,+ cidr.label = $cidr_network,+ cidr.caption = $cidr_network,+ cidr.type = "cidr"++ MERGE (ip:IP {address: $ip_address})+ SET ip.sketch_id = $sketch_id,+ ip.label = $ip_address,+ ip.caption = $ip_address,+ ip.type = "ip"++ MERGE (cidr)-[:CONTAINS {sketch_id: $sketch_id}]->(ip)+ """+ self.neo4j_conn.query(query, {+ "cidr_network": str(cidr.network),+ "ip_address": ip.address,+ "sketch_id": self.sketch_id,+ })+ return results\ No newline at end of filediff --git a/flowsint-api/app/scanners/ips/ip_to_asn.py b/flowsint-api/app/scanners/ips/ip_to_asn.pynew file mode 100644index 00000000..11f1e121--- /dev/null+++ b/flowsint-api/app/scanners/ips/ip_to_asn.py@@ -0,0 +1,142 @@+import json+import socket+import subprocess+from typing import List, Dict, Any, TypeAlias, Union+from pydantic import TypeAdapter+from app.scanners.base import Scanner+from app.types.cidr import CIDR+from app.types.ip import MinimalIp+from app.types.asn import ASN+from app.utils import is_valid_ip, resolve_type++InputType: TypeAlias = List[MinimalIp]+OutputType: TypeAlias = List[ASN]++class AsnScanner(Scanner):+ """Takes an IP addreses and returns its corresponding ASN."""++ @classmethod+ def name(cls) -> str:+ return "asn_resolve_scanner"++ @classmethod+ def category(cls) -> str:+ return "ips"++ @classmethod+ def key(cls) -> str:+ return "address"++ @classmethod+ def input_schema(cls) -> Dict[str, Any]:+ adapter = TypeAdapter(InputType)+ schema = adapter.json_schema()+ type_name, details = list(schema["$defs"].items())[0]+ return {+ "type": type_name,+ "properties": [+ {"name": prop, "type": resolve_type(info)}+ for prop, info in details["properties"].items()+ ]+ }++ @classmethod+ def output_schema(cls) -> Dict[str, Any]:+ adapter = TypeAdapter(OutputType)+ schema = adapter.json_schema()+ type_name, details = list(schema["$defs"].items())[0]+ return {+ "type": type_name,+ "properties": [+ {"name": prop, "type": resolve_type(info)}+ for prop, info in details["properties"].items()+ ]+ }++ def preprocess(self, data: Union[List[str], List[dict], InputType]) -> InputType:+ cleaned: InputType = []+ for item in data:+ ip_obj = None+ if isinstance(item, str):+ ip_obj = MinimalIp(address=item)+ elif isinstance(item, dict) and "address" in item:+ ip_obj = MinimalIp(address=item["address"])+ elif isinstance(item, MinimalIp):+ ip_obj = item+ if ip_obj and is_valid_ip(ip_obj.address):+ cleaned.append(ip_obj)+ return cleaned++ def scan(self, data: InputType) -> OutputType:+ """Find ASN information for IP addresses using asnmap."""+ asns: OutputType = []+ self.logger.debug(message=f"[ASN_SCANNER]: input data: {str(data)}")++ for ip in data:+ asn_data = self.__get_asn_from_asnmap(ip.address)+ if asn_data:+ self.logger.info(message=f"IP {ip.address} has ASN {asn_data['as_number']}.")+ asns.append(ASN(+ number=int(asn_data["as_number"].lstrip("AS")),+ name=asn_data["as_name"],+ country=asn_data["as_country"],+ cidrs=[CIDR(network=cidr) for cidr in asn_data["as_range"]]+ ))+ else:+ self.logger.info(f"No ASN found for IP {ip.address}")+ return asns++ def __get_asn_from_asnmap(self, ip: str) -> Dict[str, Any]:+ try:+ # Properly run the shell pipeline using shell=True+ command = f"echo {ip} | asnmap -silent -json | jq"+ result = subprocess.run(+ command,+ shell=True,+ capture_output=True, text=True, timeout=60+ )+ if not result.stdout.strip():+ self.logger.info(f"No ASN found for {ip}.")+ return None+ return json.loads(result.stdout)+ except Exception as e:+ self.logger.error(message=f"asnmap exception for {ip}: {str(e)}")+ return None++ def postprocess(self, results: OutputType, original_input: InputType) -> OutputType:+ # Create Neo4j relationships between IP addresses and their corresponding ASNs+ for input_ip, result_asn in zip(original_input, results):+ # Skip if no valid ASN was found+ if result_asn.number == 0:+ continue++ query = """+ MERGE (ip:IP {address: $ip_address})+ SET ip.sketch_id = $sketch_id,+ ip.label = $ip_address,+ ip.caption = $ip_address,+ ip.type = "ip"++ MERGE (asn:ASN {number: $asn_number})+ SET asn.sketch_id = $sketch_id,+ asn.name = $asn_name,+ asn.country = $asn_country,+ asn.label = $asn_label,+ asn.caption = $asn_caption,+ asn.type = "asn"++ MERGE (ip)-[:BELONGS_TO {sketch_id: $sketch_id}]->(asn)+ """++ if self.neo4j_conn:+ self.neo4j_conn.query(query, {+ "ip_address": input_ip.address,+ "asn_number": result_asn.number,+ "asn_name": result_asn.name,+ "asn_country": result_asn.country,+ "asn_label": f"AS{result_asn.number}",+ "asn_caption": f"AS{result_asn.number} - {result_asn.name}",+ "sketch_id": self.sketch_id,+ })++ return results\ No newline at end of filediff --git a/flowsint-api/app/scanners/ips/reverse_resolve.py b/flowsint-api/app/scanners/ips/reverse_resolve.pyindex 7dcef527..ec05be73 100644--- a/flowsint-api/app/scanners/ips/reverse_resolve.py+++ b/flowsint-api/app/scanners/ips/reverse_resolve.py@@ -77,12 +77,33 @@ class ReverseResolveScanner(Scanner):print(f"Error resolving {ip.address}: {e}")return results- def postprocess(self, results: OutputType) -> OutputType:+ def postprocess(self, results: OutputType, original_input: InputType) -> OutputType:+ for ip_obj, domain_obj in zip(original_input, results):+ self.logger.success(message=f"Resolved {ip_obj.address} to {domain_obj.domain}")+ query = """+ MERGE (d:ip {ip: $ip})+ SET d.sketch_id = $sketch_id+ MERGE (domain:domain {domain: $domain})+ SET d.label = $label+ SET d.caption = $caption+ SET d.type = $type+ MERGE (d)-[:REVERSE_RESOLVES_TO {sketch_id: $sketch_id}]->(domain)+ """+ if self.neo4j_conn:+ self.neo4j_conn.query(query, {+ "domain": domain_obj.domain,+ "ip": ip_obj.address,+ "sketch_id": self.sketch_id,+ "label": ip_obj.address,+ "caption": ip_obj.address,+ "type": "ip"+ })+return results@classmethoddef get_domains_from_ip(cls, address: str) -> List[str]:- """+ """1) Attempt PTR lookup and filter generic provider names.2) Query crt.sh for certificates matching the IP SAN/CN.3) (Optional) Query a Reverse-IP API if API key is set.@@ -137,29 +158,4 @@ class ReverseResolveScanner(Scanner):if c not in unique:unique.append(c)- return unique-- def postprocess(self, results: OutputType, original_input: InputType) -> OutputType:- for domain_obj, ip_obj in zip(original_input, results):- self.logger.success(message=f"Resolved {ip_obj.address} to {domain_obj.domain}")- query = """- MERGE (d:ip {ip: $ip})- SET d.sketch_id = $sketch_id- MERGE (domain:domain {domain: $domain})- SET ip.sketch_id = $sketch_id- SET ip.label = $label- SET ip.caption = $caption- SET ip.type = $type- MERGE (ip)-[:REVERSE_RESOLVES_TO {sketch_id: $sketch_id}]->(d)- """- if self.neo4j_conn:- self.neo4j_conn.query(query, {- "domain": domain_obj.domain,- "ip": ip_obj.address,- "sketch_id": self.sketch_id,- "label": ip_obj.address,- "caption": ip_obj.address,- "type": "ip"- })-- return results\ No newline at end of file+ return unique\ No newline at end of filediff --git a/flowsint-api/app/scanners/orchestrator.py b/flowsint-api/app/scanners/orchestrator.pyindex 2ecebc3a..3049edb3 100644--- a/flowsint-api/app/scanners/orchestrator.py+++ b/flowsint-api/app/scanners/orchestrator.py@@ -41,29 +41,7 @@ class TransformOrchestrator(Scanner):scanner = ScannerRegistry.get_scanner(scanner_name, self.sketch_id, self.scan_id, neo4j_conn=self.neo4j_conn, logger=self.logger)self.scanners[node_id] = scanner-- # Log the execution plan for debugging- self.log_execution_plan()- def log_execution_plan(self):- """Log the execution plan for debugging purposes"""- self.logger.info(message="Workflow execution plan:")-- for branch_idx, branch in enumerate(self.transform_branches):- branch_id = branch.id- branch_name = branch.name-- self.logger.info(message=f"Branch: {branch_name} (ID: {branch_id})")-- steps = branch.steps- for step_idx, step in enumerate(steps):- node_id = step.nodeId- scanner_name = node_id.split('-')[0]- depth = step.depth-- # Log the step information- inputs_str = ', '.join([f"{k}: {v}" for k, v in step.inputs.items()])- outputs_str = ', '.join([f"{k}: {v}" for k, v in step.outputs.items()])def resolve_reference(self, ref_value: str, results_mapping: Dict[str, Any]) -> Any:"""@@ -194,8 +172,8 @@ class TransformOrchestrator(Scanner):# Check if we already have results for this scanner with these inputscache_key = f"{node_id}:{str(scanner_inputs)}"if cache_key in scanner_results_cache:- self.logger.info(message=f"Reusing cached results for scanner {scanner_name}")outputs = scanner_results_cache[cache_key]+ self.logger.info(message=f"Using cached results for {scanner_name}")else:# Execute the scanneroutputs = scanner.execute(scanner_inputs)diff --git a/flowsint-api/app/scanners/organizations/org_to_asn.py b/flowsint-api/app/scanners/organizations/org_to_asn.pynew file mode 100644index 00000000..faa130d9--- /dev/null+++ b/flowsint-api/app/scanners/organizations/org_to_asn.py@@ -0,0 +1,135 @@+import json+import subprocess+from typing import List, Dict, Any, TypeAlias, Union+from pydantic import TypeAdapter+from app.scanners.base import Scanner+from app.types.cidr import CIDR+from app.types.ip import MinimalIp+from app.types.organization import MinimalOrganization+from app.types.asn import ASN+from app.utils import resolve_type++InputType: TypeAlias = List[MinimalOrganization]+OutputType: TypeAlias = List[ASN]++class OrgToAsnScanner(Scanner):+ """Takes an organization and returns the ASN(s) if any."""++ @classmethod+ def name(cls) -> str:+ return "org_to_asn_scanner"++ @classmethod+ def category(cls) -> str:+ return "organizations"++ @classmethod+ def key(cls) -> str:+ return "name"++ @classmethod+ def input_schema(cls) -> Dict[str, Any]:+ adapter = TypeAdapter(InputType)+ schema = adapter.json_schema()+ type_name, details = list(schema["$defs"].items())[0]+ return {+ "type": type_name,+ "properties": [+ {"name": prop, "type": resolve_type(info)}+ for prop, info in details["properties"].items()+ ]+ }++ @classmethod+ def output_schema(cls) -> Dict[str, Any]:+ adapter = TypeAdapter(OutputType)+ schema = adapter.json_schema()+ type_name, details = list(schema["$defs"].items())[0]+ return {+ "type": type_name,+ "properties": [+ {"name": prop, "type": resolve_type(info)}+ for prop, info in details["properties"].items()+ ]+ }++ def preprocess(self, data: Union[List[str], List[dict], InputType]) -> InputType:+ cleaned: InputType = []+ for item in data:+ if isinstance(item, str):+ cleaned.append(MinimalOrganization(name=item))+ elif isinstance(item, dict) and "name" in item:+ cleaned.append(MinimalOrganization(**item))+ elif isinstance(item, MinimalOrganization):+ cleaned.append(item)+ return cleaned++ def scan(self, data: InputType) -> OutputType:+ """Find ASN information for organization name using asnmap."""+ asns: OutputType = []+ self.logger.debug(message=f"[ASN_SCANNER]: input data: {str(data)}")++ for org in data:+ asn_data = self.__get_asn_from_asnmap(org.name)+ if asn_data:+ self.logger.info(message=f"ASN {asn_data['as_number']} found for org {org.name}.")+ asns.append(ASN(+ number=int(asn_data["as_number"].lstrip("AS")),+ name=asn_data["as_name"],+ country=asn_data["as_country"],+ cidrs=[CIDR(network=cidr) for cidr in asn_data["as_range"]]+ ))+ else:+ self.logger.info(f"No ASN found for org {org.name}")+ return asns++ def __get_asn_from_asnmap(self, name: str) -> Dict[str, Any]:+ try:+ # Properly run the shell pipeline using shell=True+ command = f"echo '{name}' | asnmap -silent -json | jq"+ result = subprocess.run(+ command,+ shell=True,+ capture_output=True, text=True, timeout=60+ )+ if not result.stdout.strip():+ self.logger.info(f"No ASN found for {name}.")+ return None+ return json.loads(result.stdout)+ except Exception as e:+ self.logger.error(message=f"asnmap exception for {name}: {str(e)}")+ return None++ def postprocess(self, results: OutputType, original_input: InputType) -> OutputType:+ # Create Neo4j relationships between organizations and their corresponding ASNs+ for org, asn in zip(original_input, results):+ if asn.number == 0:+ continue+ if self.neo4j_conn:+ query = """+ MERGE (org:Organization {name: $org_name})+ SET org.sketch_id = $sketch_id,+ org.label = $org_name,+ org.caption = $org_name,+ org.type = "organization"++ MERGE (asn:ASN {number: $asn_number})+ SET asn.sketch_id = $sketch_id,+ asn.name = $asn_name,+ asn.country = $asn_country,+ asn.label = $asn_label,+ asn.caption = $asn_caption,+ asn.type = "asn"++ MERGE (org)-[:OWNS {sketch_id: $sketch_id}]->(asn)+ """+ self.neo4j_conn.query(query, {+ "org_name": org.name,+ "asn_number": asn.number,+ "asn_name": asn.name,+ "asn_country": asn.country,+ "asn_label": f"AS{asn.number}",+ "asn_caption": f"AS{asn.number} - {asn.name}",+ "sketch_id": self.sketch_id,+ })+ return results\ No newline at end of filediff --git a/flowsint-api/app/scanners/organizations/sirene.py b/flowsint-api/app/scanners/organizations/sirene.pyindex 5d81ff7f..c5f007db 100644--- a/flowsint-api/app/scanners/organizations/sirene.py+++ b/flowsint-api/app/scanners/organizations/sirene.py@@ -18,6 +18,10 @@ class SireneScanner(Scanner):@classmethoddef category(cls) -> str:return "organizations"++ @classmethod+ def key(cls) -> str:+ return "name"@classmethoddef input_schema(cls) -> Dict[str, Any]:diff --git a/flowsint-api/app/scanners/registry.py b/flowsint-api/app/scanners/registry.pyindex 074a75f8..cb52a642 100644--- a/flowsint-api/app/scanners/registry.py+++ b/flowsint-api/app/scanners/registry.py@@ -9,6 +9,11 @@ from app.scanners.ips.geolocation import GeolocationScannerfrom app.scanners.socials.maigret import MaigretScannerfrom app.scanners.emails.holehe import HoleheScannerfrom app.scanners.organizations.sirene import SireneScanner+from app.scanners.ips.ip_to_asn import AsnScanner+from app.scanners.ips.asn_to_cidrs import AsnToCidrsScanner+from app.scanners.ips.cidr_to_ips import CidrToIpsScanner+from app.scanners.organizations.org_to_asn import OrgToAsnScanner+class ScannerRegistry:_scanners: Dict[str, Type[Scanner]] = {}@@ -67,4 +72,8 @@ ScannerRegistry.register(WhoisScanner)ScannerRegistry.register(GeolocationScanner)ScannerRegistry.register(MaigretScanner)ScannerRegistry.register(HoleheScanner)-ScannerRegistry.register(SireneScanner)\ No newline at end of file+ScannerRegistry.register(SireneScanner)+ScannerRegistry.register(AsnScanner)+ScannerRegistry.register(AsnToCidrsScanner)+ScannerRegistry.register(CidrToIpsScanner)+ScannerRegistry.register(OrgToAsnScanner)\ No newline at end of filediff --git a/flowsint-api/app/types/address.py b/flowsint-api/app/types/address.pyindex d5924df6..94461da9 100644--- a/flowsint-api/app/types/address.py+++ b/flowsint-api/app/types/address.py@@ -1,12 +1,11 @@--from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing import Optionalclass Address(BaseModel):- address: str- city: str- country: str- zip: str- latitude: Optional[float] = None- longitude: Optional[float] = None+ address: str = Field(..., description="Street address")+ city: str = Field(..., description="City name")+ country: str = Field(..., description="Country name")+ zip: str = Field(..., description="ZIP or postal code")+ latitude: Optional[float] = Field(None, description="Latitude coordinate of the address")+ longitude: Optional[float] = Field(None, description="Longitude coordinate of the address")diff --git a/flowsint-api/app/types/asn.py b/flowsint-api/app/types/asn.pynew file mode 100644index 00000000..3c4c1a87--- /dev/null+++ b/flowsint-api/app/types/asn.py@@ -0,0 +1,12 @@+from typing import List, Optional+from pydantic import BaseModel, Field+from .cidr import CIDR++class ASN(BaseModel):+ number: int = Field(..., description="Autonomous System Number (e.g., 15169)")+ name: Optional[str] = Field(None, description="Name of the organization owning the ASN")+ country: Optional[str] = Field(None, description="ISO 3166-1 alpha-2 country code")+ description: Optional[str] = Field(None, description="Additional information about the ASN")+ cidrs: List[CIDR] = Field(default_factory=list, description="List of announced CIDR blocks")++ASN.model_rebuild()diff --git a/flowsint-api/app/types/cidr.py b/flowsint-api/app/types/cidr.pynew file mode 100644index 00000000..2fd313b4--- /dev/null+++ b/flowsint-api/app/types/cidr.py@@ -0,0 +1,4 @@+from pydantic import BaseModel, IPvAnyNetwork, Field++class CIDR(BaseModel):+ network: IPvAnyNetwork = Field(..., description="CIDR block (e.g., 8.8.8.0/24)")diff --git a/flowsint-api/app/types/domain.py b/flowsint-api/app/types/domain.pyindex 06729bc2..f52409c8 100644--- a/flowsint-api/app/types/domain.py+++ b/flowsint-api/app/types/domain.py@@ -1,13 +1,13 @@-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing import List, Optionalfrom .ip import Ipclass MinimalDomain(BaseModel):- domain: str+ domain: str = Field(..., description="Domain name")class Domain(MinimalDomain):- subdomains: Optional[List["Domain"]] = []- ips: Optional[List[Ip]] = []+ subdomains: Optional[List["Domain"]] = Field(default=[], description="List of subdomains associated with this domain")+ ips: Optional[List[Ip]] = Field(default=[], description="List of IP addresses associated with this domain")Domain.model_rebuild()diff --git a/flowsint-api/app/types/email.py b/flowsint-api/app/types/email.pyindex 1d6c6e2d..4d13647c 100644--- a/flowsint-api/app/types/email.py+++ b/flowsint-api/app/types/email.py@@ -1,4 +1,4 @@-from pydantic import BaseModel+from pydantic import BaseModel, Fieldclass Email(BaseModel):- email: str+ email: str = Field(..., description="Email address")diff --git a/flowsint-api/app/types/individual.py b/flowsint-api/app/types/individual.pyindex 8a72ebf3..bc030d50 100644--- a/flowsint-api/app/types/individual.py+++ b/flowsint-api/app/types/individual.py@@ -1,9 +1,9 @@-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing import Optionalclass Individual(BaseModel):- first_name: str- last_name: str- full_name: str- birth_date: Optional[str] = None- gender: Optional[str] = None\ No newline at end of file+ first_name: str = Field(..., description="First name of the individual")+ last_name: str = Field(..., description="Last name of the individual")+ full_name: str = Field(..., description="Full name of the individual")+ birth_date: Optional[str] = Field(None, description="Date of birth")+ gender: Optional[str] = Field(None, description="Gender of the individual")\ No newline at end of filediff --git a/flowsint-api/app/types/ip.py b/flowsint-api/app/types/ip.pyindex 2988dbb4..fe0ce9d6 100644--- a/flowsint-api/app/types/ip.py+++ b/flowsint-api/app/types/ip.py@@ -1,12 +1,12 @@-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing import Optionalclass MinimalIp(BaseModel):- address: str+ address: str = Field(..., description="IP address")class Ip(MinimalIp):- latitude: Optional[float] = None- longitude: Optional[float] = None- country: Optional[str] = None- city: Optional[str] = None- isp: Optional[str] = None+ latitude: Optional[float] = Field(None, description="Latitude coordinate of the IP location")+ longitude: Optional[float] = Field(None, description="Longitude coordinate of the IP location")+ country: Optional[str] = Field(None, description="Country where the IP is located")+ city: Optional[str] = Field(None, description="City where the IP is located")+ isp: Optional[str] = Field(None, description="Internet Service Provider")diff --git a/flowsint-api/app/types/leak.py b/flowsint-api/app/types/leak.pyindex 74e10879..2fbe7cc3 100644--- a/flowsint-api/app/types/leak.py+++ b/flowsint-api/app/types/leak.py@@ -1,7 +1,6 @@-from typing import List, Dict-from pydantic import BaseModel-from typing import Optional+from typing import List, Dict, Optional+from pydantic import BaseModel, Fieldclass Leak(BaseModel):- leaks: Optional[List[Dict]] = None- breaches: Optional[List[Dict]] = None+ leaks: Optional[List[Dict]] = Field(None, description="List of data leaks found")+ breaches: Optional[List[Dict]] = Field(None, description="List of security breaches found")diff --git a/flowsint-api/app/types/organization.py b/flowsint-api/app/types/organization.pyindex 18d04f3b..1b313e15 100644--- a/flowsint-api/app/types/organization.py+++ b/flowsint-api/app/types/organization.py@@ -1,17 +1,17 @@-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing import Optional, Listclass Identifier(BaseModel):- type: str # Example: "SIREN", "SIRET", "DUNS", "VAT", "LEI", etc.- value: str- country: Optional[str] = None- issued_by: Optional[str] = None+ type: str = Field(..., description="Type of identifier (e.g., SIREN, SIRET, DUNS, VAT, LEI)")+ value: str = Field(..., description="The identifier value")+ country: Optional[str] = Field(None, description="Country where the identifier was issued")+ issued_by: Optional[str] = Field(None, description="Authority that issued the identifier")class MinimalOrganization(BaseModel):- name: str+ name: str = Field(..., description="Organization name")class Organization(MinimalOrganization):- founding_date: Optional[str] = None- country: Optional[str] = None- description: Optional[str] = None- identifiers: Optional[List[Identifier]] = None\ No newline at end of file+ founding_date: Optional[str] = Field(None, description="Date when the organization was founded")+ country: Optional[str] = Field(None, description="Country where the organization is based")+ description: Optional[str] = Field(None, description="Description of the organization's activities")+ identifiers: Optional[List[Identifier]] = Field(None, description="List of official identifiers for the organization")\ No newline at end of filediff --git a/flowsint-api/app/types/phone.py b/flowsint-api/app/types/phone.pyindex 2c6b8681..f03df887 100644--- a/flowsint-api/app/types/phone.py+++ b/flowsint-api/app/types/phone.py@@ -1,7 +1,7 @@-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing import Optionalclass Phone(BaseModel):- number: str- country: Optional[str] = None- carrier: Optional[str] = None\ No newline at end of file+ number: str = Field(..., description="Phone number")+ country: Optional[str] = Field(None, description="Country code (ISO 3166-1 alpha-2)")+ carrier: Optional[str] = Field(None, description="Mobile carrier or service provider")\ No newline at end of filediff --git a/flowsint-api/app/types/social.py b/flowsint-api/app/types/social.pyindex 019b4159..aa153ec5 100644--- a/flowsint-api/app/types/social.py+++ b/flowsint-api/app/types/social.py@@ -1,16 +1,16 @@-from pydantic import BaseModel, HttpUrl+from pydantic import BaseModel, Field, HttpUrlfrom typing import Optionalclass MinimalSocial(BaseModel):- username: Optional[str] = None+ username: Optional[str] = Field(None, description="Username on the social platform")class Social(BaseModel):- username: Optional[str] = None- profile_url: str- platform: Optional[str] = None- profile_picture_url: Optional[str] = None- bio: Optional[str] = None- followers_count: Optional[int] = None- following_count: Optional[int] = None- posts_count: Optional[int] = None+ username: Optional[str] = Field(None, description="Username on the social platform")+ profile_url: str = Field(..., description="URL to the user's profile page")+ platform: Optional[str] = Field(None, description="Name of the social media platform")+ profile_picture_url: Optional[str] = Field(None, description="URL to the user's profile picture")+ bio: Optional[str] = Field(None, description="User's biography or description")+ followers_count: Optional[int] = Field(None, description="Number of followers")+ following_count: Optional[int] = Field(None, description="Number of users being followed")+ posts_count: Optional[int] = Field(None, description="Number of posts made by the user")\ No newline at end of filediff --git a/flowsint-api/app/types/transform.py b/flowsint-api/app/types/transform.pyindex c32255b4..69b5617d 100644--- a/flowsint-api/app/types/transform.py+++ b/flowsint-api/app/types/transform.py@@ -1,29 +1,29 @@-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing import Dict, List, Any, Optional, Literalclass Node(BaseModel):- id: str- data: Dict[str, Any]- position: Optional[Dict[str, float]] = None- type: Optional[str] = None+ id: str = Field(..., description="Unique identifier for the node")+ data: Dict[str, Any] = Field(..., description="Data payload associated with the node")+ position: Optional[Dict[str, float]] = Field(None, description="X and Y coordinates for node positioning")+ type: Optional[str] = Field(None, description="Type of node (e.g., input, output, process)")class Edge(BaseModel):- id: str- source: str- target: str- sourceHandle: Optional[str] = None- targetHandle: Optional[str] = None+ id: str = Field(..., description="Unique identifier for the edge")+ source: str = Field(..., description="ID of the source node")+ target: str = Field(..., description="ID of the target node")+ sourceHandle: Optional[str] = Field(None, description="Handle ID on the source node")+ targetHandle: Optional[str] = Field(None, description="Handle ID on the target node")class FlowStep(BaseModel):- nodeId: str- type: Literal["type", "scanner"]- inputs: Dict[str, Any]- outputs: Dict[str, Any]- status: Literal["pending", "processing", "completed", "error"]- branchId: str- depth: int+ nodeId: str = Field(..., description="ID of the associated node")+ type: Literal["type", "scanner"] = Field(..., description="Type of step - either type transformation or scanner")+ inputs: Dict[str, Any] = Field(..., description="Input data for this step")+ outputs: Dict[str, Any] = Field(..., description="Output data from this step")+ status: Literal["pending", "processing", "completed", "error"] = Field(..., description="Current execution status of the step")+ branchId: str = Field(..., description="ID of the branch this step belongs to")+ depth: int = Field(..., description="Depth level of this step in the flow")class FlowBranch(BaseModel):- id: str- name: str- steps: List[FlowStep]\ No newline at end of file+ id: str = Field(..., description="Unique identifier for the branch")+ name: str = Field(..., description="Human-readable name of the branch")+ steps: List[FlowStep] = Field(..., description="List of steps in this branch")\ No newline at end of filediff --git a/flowsint-api/app/types/website.py b/flowsint-api/app/types/website.pyindex 19f6ecc7..7ea06dc4 100644--- a/flowsint-api/app/types/website.py+++ b/flowsint-api/app/types/website.py@@ -1,7 +1,7 @@from typing import Optional-from pydantic import BaseModel, HttpUrl+from pydantic import BaseModel, Field, HttpUrlfrom app.types.domain import Domainclass Website(BaseModel):- url: HttpUrl- domain: Domain\ No newline at end of file+ url: HttpUrl = Field(..., description="Full URL of the website")+ domain: Domain = Field(..., description="Domain information for the website")\ No newline at end of filediff --git a/flowsint-api/app/types/whois.py b/flowsint-api/app/types/whois.pyindex 973473e9..fc22d686 100644--- a/flowsint-api/app/types/whois.py+++ b/flowsint-api/app/types/whois.py@@ -1,13 +1,13 @@from typing import Optional-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom app.types.email import Emailfrom app.types.domain import Domainclass Whois(BaseModel):- registrar: Optional[str] = None- org: Optional[str] = None- city: Optional[str] = None- country: Optional[str] = None- email: Optional[Email] = None- creation_date: Optional[str] = None- expiration_date: Optional[str] = None+ registrar: Optional[str] = Field(None, description="Domain registrar name")+ org: Optional[str] = Field(None, description="Organization name associated with the domain")+ city: Optional[str] = Field(None, description="City where the domain is registered")+ country: Optional[str] = Field(None, description="Country where the domain is registered")+ email: Optional[Email] = Field(None, description="Contact email for the domain")+ creation_date: Optional[str] = Field(None, description="Date when the domain was created")+ expiration_date: Optional[str] = Field(None, description="Date when the domain expires")diff --git a/flowsint-api/app/utils.py b/flowsint-api/app/utils.pyindex 755f002e..ca8bc18b 100644--- a/flowsint-api/app/utils.py+++ b/flowsint-api/app/utils.py@@ -37,10 +37,10 @@ def is_valid_domain(url_or_domain: str) -> str:hostname = parsed.hostname or url_or_domainif not hostname or "." not in hostname:- return "invalid"+ return Falseif not re.match(r"^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", hostname):- return "invalid"+ return Falsereturn hostname@@ -52,10 +52,24 @@ def is_valid_number(phone: str, region: str = "FR") -> None:try:parsed = phonenumbers.parse(phone, region)if not phonenumbers.is_valid_number(parsed):- raise ValueError(f"Invalid phone number: {phone}")+ return Falseexcept NumberParseException:- raise ValueError(f"Invalid phone number: {phone}")+ return False+def parse_asn(asn: str) -> int:+ if not is_valid_asn(asn):+ raise ValueError(f"Invalid ASN format: {asn}")+ return int(re.sub(r"(?i)^AS", "", asn))+++def is_valid_asn(asn: str) -> bool:+ # ASN numbers are 16-bit numbers (0-65535)+ if not re.fullmatch(r"(AS)?\d+", asn, re.IGNORECASE):+ return False+ # Remove 'AS' prefix if present and convert to int+ asn_num = int(re.sub(r"(?i)^AS", "", asn))+ return 0 <= asn_num <= 65535+def resolve_type(details: dict) -> str:if "anyOf" in details:types = []@@ -79,12 +93,9 @@ def extract_input_schema(name: str, model: Type[BaseModel]) -> Dict[str, Any]:adapter = TypeAdapter(model)schema = adapter.json_schema()- # Vérifie si le schéma utilise $defs (références internes)- if "$defs" in schema:- type_name, details = list(schema["$defs"].items())[0]- else:- type_name = name- details = schema+ # Use the main schema properties, not the $defs+ type_name = name+ details = schemareturn {"class_name": name,diff --git a/flowsint-api/requirements.txt b/flowsint-api/requirements.txtindex a2e1b0e8..05f39ead 100644--- a/flowsint-api/requirements.txt+++ b/flowsint-api/requirements.txt@@ -25,3 +25,4 @@ psycopg2-binaryalembicpasslib[bcrypt]sse-starlette+networkxdiff --git a/flowsint-api/test.cypher b/flowsint-api/test.cypherdeleted file mode 100644index affb65ea..00000000--- a/flowsint-api/test.cypher+++ /dev/null@@ -1,96 +0,0 @@-// Définir le sketch_id-WITH "fe8a0a8e-2fed-4149-9353-3c1293ea6d65" AS sketchId--// 1. Créer 3 organisations-UNWIND range(1, 3) AS i-CREATE (:Organization {- id: randomUUID(),- name: 'Org ' + i,- label: 'Org ' + i,- type: 'organization',- sketch_id: sketchId-});--// 2. Créer 10 individuals liés aux organisations-WITH "fe8a0a8e-2fed-4149-9353-3c1293ea6d65" AS sketchId-MATCH (org:Organization)-WITH collect(org) AS orgs, sketchId-UNWIND range(1, 10) AS i-WITH orgs[toInteger(rand() * size(orgs))] AS org, i, sketchId-CREATE (ind:Individual {- id: randomUUID(),- name: 'Person ' + i,- label: 'Person ' + i,- type: 'individual',- sketch_id: sketchId-})-CREATE (ind)-[:WORKS_FOR { sketch_id: sketchId, type: 'WORKS_FOR', label: 'works for' }]->(org);--// 3. Créer 5 domaines liés aux organisations-WITH "fe8a0a8e-2fed-4149-9353-3c1293ea6d65" AS sketchId-MATCH (org:Organization)-WITH collect(org) AS orgs, sketchId-UNWIND range(1, 5) AS i-WITH orgs[toInteger(rand() * size(orgs))] AS org, i, sketchId-CREATE (d:Domain {- id: randomUUID(),- name: 'example' + i + '.com',- label: 'example' + i + '.com',- type: 'domain',- sketch_id: sketchId-})-CREATE (d)-[:OWNED_BY { sketch_id: sketchId, type: 'OWNED_BY', label: 'owned by' }]->(org);--// 4. Créer 10 subdomains liés aux domaines-WITH "fe8a0a8e-2fed-4149-9353-3c1293ea6d65" AS sketchId-MATCH (d:Domain)-WITH collect(d) AS domains, sketchId-UNWIND range(1, 10) AS i-WITH domains[toInteger(rand() * size(domains))] AS domain, i, sketchId-CREATE (sd:Subdomain {- id: randomUUID(),- name: 'sub' + i + '.' + domain.name,- label: 'sub' + i + '.' + domain.name,- type: 'subdomain',- sketch_id: sketchId-})-CREATE (sd)-[:SUBDOMAIN_OF { sketch_id: sketchId, type: 'SUBDOMAIN_OF', label: 'subdomain of' }]->(domain);--// 5. Créer 10 usernames liés à des individuals-WITH "fe8a0a8e-2fed-4149-9353-3c1293ea6d65" AS sketchId-MATCH (ind:Individual)-WITH collect(ind) AS individuals, sketchId-UNWIND range(1, 10) AS i-WITH individuals[toInteger(rand() * size(individuals))] AS person, i, sketchId-CREATE (u:Username {- id: randomUUID(),- name: 'user' + i,- label: 'user' + i,- type: 'username',- sketch_id: sketchId-})-CREATE (u)-[:ALIAS_OF { sketch_id: sketchId, type: 'ALIAS_OF', label: 'alias of' }]->(person);--// 6. Créer 10 social_profiles liés aux usernames-WITH "fe8a0a8e-2fed-4149-9353-3c1293ea6d65" AS sketchId-MATCH (u:Username)-WITH collect(u) AS usernames, sketchId,- ['twitter', 'linkedin', 'github', 'facebook'] AS platforms-UNWIND usernames AS uname-WITH uname, platforms[toInteger(rand() * size(platforms))] AS platform, sketchId-CREATE (sp:SocialProfile {- id: randomUUID(),- platform: platform,- profile_url: 'https://' + platform + '.com/' + uname.name,- label: uname.name + ' on ' + platform,- type: 'social_profile',- sketch_id: sketchId-})-CREATE (sp)-[:ASSOCIATED_WITH { sketch_id: sketchId, type: 'ASSOCIATED_WITH', label: 'associated with' }]->(uname);---// Relier les organisations entre elles pour unifier le graphe-WITH "fe8a0a8e-2fed-4149-9353-3c1293ea6d65" AS sketchId-MATCH (o1:Organization), (o2:Organization)-WHERE id(o1) < id(o2) // éviter les doublons et self-loop-MERGE (o1)-[:RELATED_TO { sketch_id: sketchId, type: 'RELATED_TO', label: 'related to' }]->(o2)diff --git a/flowsint-api/tests/logger.py b/flowsint-api/tests/logger.pynew file mode 100644index 00000000..bc09bc60--- /dev/null+++ b/flowsint-api/tests/logger.py@@ -0,0 +1,45 @@+from typing import Literal++LogLevel = Literal["info", "warn", "error", "success", "debug"]++LEVEL_MAP = {+ "info": "INFO",+ "warn": "WARN",+ "error": "ERROR",+ "success": "SUCCESS",+ "debug": "DEBUG",+}+++class TestLogger:+ def __init__(self):+ pass++ def _format_message(self, type: str, message: str) -> str:+ """Format the log message with type prefix"""+ return f"[{type.upper()}] {message}"++ def info(self, message: str):+ """Log an info message"""+ formatted_message = self._format_message("INFO", message)+ print(formatted_message)++ def error(self, message: str):+ """Log an error message"""+ formatted_message = self._format_message("ERROR", message)+ print(formatted_message)++ def warn(self, message: str):+ """Log a warning message"""+ formatted_message = self._format_message("WARNING", message)+ print(formatted_message)++ def debug(self, message: str):+ """Log a debug message"""+ formatted_message = self._format_message("DEBUG", message)+ print(formatted_message)++ def success(self, message: str):+ """Log a success message"""+ formatted_message = self._format_message("SUCCESS", message)+ print(formatted_message)diff --git a/flowsint-api/tests/scanners/ip/__init__.py b/flowsint-api/tests/scanners/ips/__init__.pysimilarity index 100%rename from flowsint-api/tests/scanners/ip/__init__.pyrename to flowsint-api/tests/scanners/ips/__init__.pydiff --git a/flowsint-api/tests/scanners/ips/asn_to_cidrs.py b/flowsint-api/tests/scanners/ips/asn_to_cidrs.pynew file mode 100644index 00000000..fc6b0b74--- /dev/null+++ b/flowsint-api/tests/scanners/ips/asn_to_cidrs.py@@ -0,0 +1,222 @@+import json+from unittest.mock import Mock+from app.scanners.ips.asn_to_cidrs import AsnToCidrsScanner+from app.types.asn import ASN+from app.types.cidr import CIDR+from tests.logger import TestLogger++logger = TestLogger()+# The scanner will get a mock logger from conftest.py automatically+scanner = AsnToCidrsScanner("sketch_123", "scan_123", logger)++def test_preprocess_valid_asns():+ asns = [+ ASN(number=15169),+ ASN(number=13335),+ ]+ result = scanner.preprocess(asns)++ result_numbers = [asn.number for asn in result]+ expected_numbers = [asn.number for asn in asns]++ assert result_numbers == expected_numbers++def test_unprocessed_valid_asns():+ asns = [+ "15169",+ "13335",+ ]+ result = scanner.preprocess(asns)+ result_asns = [asn for asn in result]+ expected_asns = [ASN(number=int(asn)) for asn in asns]+ assert result_asns == expected_asns++def test_preprocess_invalid_asns():+ asns = [+ ASN(number=15169),+ ASN(number=999999), # Invalid ASN number+ ASN(number=13335),+ ]+ result = scanner.preprocess(asns)++ result_numbers = [asn.number for asn in result]+ assert 15169 in result_numbers+ assert 13335 in result_numbers+ assert 999999 not in result_numbers++def test_preprocess_multiple_formats():+ asns = [+ {"number": 15169},+ {"invalid_key": 13335},+ ASN(number=13335),+ "15169",+ ]+ result = scanner.preprocess(asns)++ result_numbers = [asn.number for asn in result]+ assert 15169 in result_numbers+ assert 13335 in result_numbers+ assert "invalid_key" not in result_numbers # Should be filtered out due to invalid key++def test_scan_extracts_cidrs(monkeypatch):+ mock_asnmap_output = {+ "input": "15169",+ "as_number": "AS15169",+ "as_name": "GOOGLE",+ "as_country": "US",+ "as_range": ["8.8.8.0/24", "8.8.4.0/24"]+ }++ class MockSubprocessResult:+ def __init__(self, stdout):+ self.stdout = stdout+ self.returncode = 0++ def mock_subprocess_run(cmd, input, capture_output, text, timeout):+ assert "asnmap" in cmd+ assert input == "15169"+ return MockSubprocessResult(json.dumps(mock_asnmap_output))++ # Patch the subprocess call in the scanner+ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [ASN(number=15169)]+ cidrs = scanner.scan(input_data)++ assert isinstance(cidrs, list)+ assert len(cidrs) == 2++ # Check CIDRs+ assert str(cidrs[0].network) == "8.8.8.0/24"+ assert str(cidrs[1].network) == "8.8.4.0/24"++def test_scan_handles_no_cidrs_found(monkeypatch):+ class MockSubprocessResult:+ def __init__(self, stdout):+ self.stdout = stdout+ self.returncode = 0++ def mock_subprocess_run(cmd, input, capture_output, text, timeout):+ # Return empty output to simulate no CIDRs found+ return MockSubprocessResult("")++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [ASN(number=999999)]+ cidrs = scanner.scan(input_data)++ assert isinstance(cidrs, list)+ assert len(cidrs) == 1++ # Should return default CIDR for unknown ASN+ assert str(cidrs[0].network) == "0.0.0.0/0"++def test_scan_handles_subprocess_exception(monkeypatch):+ def mock_subprocess_run(cmd, input, capture_output, text, timeout):+ raise Exception("Subprocess failed")++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [ASN(number=15169)]+ cidrs = scanner.scan(input_data)++ assert isinstance(cidrs, list)+ assert len(cidrs) == 1++ # Should return default CIDR on error+ assert str(cidrs[0].network) == "0.0.0.0/0"++def test_scan_multiple_asns(monkeypatch):+ mock_responses = {+ "15169": {+ "input": "15169",+ "as_number": "AS15169",+ "as_name": "GOOGLE",+ "as_country": "US",+ "as_range": ["8.8.8.0/24"]+ },+ "13335": {+ "input": "13335",+ "as_number": "AS13335",+ "as_name": "CLOUDFLARE",+ "as_country": "US",+ "as_range": ["1.1.1.0/24"]+ }+ }++ class MockSubprocessResult:+ def __init__(self, stdout):+ self.stdout = stdout+ self.returncode = 0++ def mock_subprocess_run(cmd, input, capture_output, text, timeout):+ if input in mock_responses:+ return MockSubprocessResult(json.dumps(mock_responses[input]))+ return MockSubprocessResult("")++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [ASN(number=15169), ASN(number=13335)]+ cidrs = scanner.scan(input_data)++ assert len(cidrs) == 2++ # Check CIDRs+ assert str(cidrs[0].network) == "8.8.8.0/24"+ assert str(cidrs[1].network) == "1.1.1.0/24"++def test_schemas():+ input_schema = scanner.input_schema()+ output_schema = scanner.output_schema()++ # Input schema should have number field+ assert "properties" in input_schema+ number_prop = next((prop for prop in input_schema["properties"] if prop["name"] == "number"), None)+ assert number_prop is not None+ assert number_prop["type"] == "integer"++ # Output schema should have network field+ assert "properties" in output_schema+ prop_names = [prop["name"] for prop in output_schema["properties"]]+ assert "network" in prop_names++def test_postprocess_creates_neo4j_relationships(monkeypatch):+ # Mock Neo4j connection+ mock_neo4j = Mock()+ scanner.neo4j_conn = mock_neo4j++ input_data = [ASN(number=15169, name="GOOGLE", country="US")]+ cidr_results = [CIDR(network="8.8.8.0/24")]++ result = scanner.postprocess(cidr_results, input_data)++ # Verify Neo4j query was called+ mock_neo4j.query.assert_called_once()++ # Check the query parameters+ call_args = mock_neo4j.query.call_args+ params = call_args[0][1]+ assert params["asn_number"] == 15169+ assert params["asn_name"] == "GOOGLE"+ assert params["asn_country"] == "US"+ assert params["cidr_network"] == "8.8.8.0/24"+ assert params["sketch_id"] == "sketch_123"++ # Should return the same results+ assert result == cidr_results++def test_postprocess_skips_default_cidr(monkeypatch):+ # Mock Neo4j connection+ mock_neo4j = Mock()+ scanner.neo4j_conn = mock_neo4j++ input_data = [ASN(number=999999)]+ cidr_results = [CIDR(network="0.0.0.0/0")] # Default CIDR for unknown ASN++ result = scanner.postprocess(cidr_results, input_data)++ # Verify Neo4j query was NOT called for default CIDR+ mock_neo4j.query.assert_not_called()++ # Should return the same results+ assert result == cidr_results\ No newline at end of filediff --git a/flowsint-api/tests/scanners/ips/cidr_to_ips.py b/flowsint-api/tests/scanners/ips/cidr_to_ips.pynew file mode 100644index 00000000..70fe48b3--- /dev/null+++ b/flowsint-api/tests/scanners/ips/cidr_to_ips.py@@ -0,0 +1,121 @@+import pytest+from app.scanners.ips.cidr_to_ips import CidrToIpsScanner+from app.types.cidr import CIDR+from app.types.ip import MinimalIp+from tests.logger import TestLogger++logger = TestLogger()+scanner = CidrToIpsScanner("sketch_123", "scan_123", logger)++def test_preprocess_valid_cidrs():+ cidrs = [+ CIDR(network="8.8.8.0/24"),+ CIDR(network="1.1.1.0/24"),+ ]+ result = scanner.preprocess(cidrs)++ result_networks = [cidr.network for cidr in result]+ expected_networks = [cidr.network for cidr in cidrs]++ assert result_networks == expected_networks++def test_preprocess_unprocessed_valid_cidrs():+ cidrs = [+ "8.8.8.0/24",+ "1.1.1.0/24",+ ]+ result = scanner.preprocess(cidrs)+ result_cidrs = [c for c in result]+ expected_cidrs = [CIDR(network=c) for c in cidrs]+ assert result_cidrs == expected_cidrs++def test_preprocess_invalid_cidrs():+ cidrs = [+ CIDR(network="8.8.8.0/24"),+ "invalid-cidr",+ "not-a-cidr",+ ]+ result = scanner.preprocess(cidrs)+ result_networks = [cidr.network for cidr in result]+ assert "8.8.8.0/24" in result_networks+ assert "invalid-cidr" not in result_networks+ assert "not-a-cidr" not in result_networks++def test_preprocess_multiple_formats():+ cidrs = [+ {"network": "8.8.8.0/24"},+ {"invalid_key": "1.1.1.0/24"},+ CIDR(network="9.9.9.0/24"),+ "InvalidCIDR",+ ]+ result = scanner.preprocess(cidrs)+ result_networks = [cidr.network for cidr in result]+ assert "8.8.8.0/24" in result_networks+ assert "9.9.9.0/24" in result_networks+ assert "1.1.1.0/24" not in result_networks+ assert "InvalidCIDR" not in result_networks++def test_scan_extracts_ips(monkeypatch):+ mock_dnsx_output = """8.35.200.12+8.35.200.112+8.35.200.16+8.35.200.170"""++ class MockSubprocessResult:+ def __init__(self, stdout):+ self.stdout = stdout+ self.returncode = 0++ def mock_subprocess_run(cmd, shell, capture_output, text, timeout):+ assert "dnsx" in cmd+ assert "-ptr" in cmd+ return MockSubprocessResult(mock_dnsx_output)++ # Patch the subprocess call in the scanner+ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [CIDR(network="8.35.200.0/24")]+ ips = scanner.scan(input_data)++ assert isinstance(ips, list)+ assert len(ips) == 4++ expected_ips = [+ "8.35.200.12",+ "8.35.200.112",+ "8.35.200.16",+ "8.35.200.170"+ ]++ for ip in ips:+ assert isinstance(ip, MinimalIp)+ assert ip.address in expected_ips++def test_scan_handles_empty_output(monkeypatch):+ class MockSubprocessResult:+ def __init__(self):+ self.stdout = ""+ self.returncode = 0++ def mock_subprocess_run(cmd, shell, capture_output, text, timeout):+ return MockSubprocessResult()++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [CIDR(network="8.8.8.0/24")]+ ips = scanner.scan(input_data)++ assert isinstance(ips, list)+ assert len(ips) == 0++def test_scan_handles_subprocess_exception(monkeypatch):+ def mock_subprocess_run(cmd, shell, capture_output, text, timeout):+ raise Exception("Subprocess failed")++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [CIDR(network="8.8.8.0/24")]+ ips = scanner.scan(input_data)++ assert isinstance(ips, list)+ assert len(ips) == 0\ No newline at end of filediff --git a/flowsint-api/tests/scanners/ip/geolocation.py b/flowsint-api/tests/scanners/ips/geolocation.pysimilarity index 100%rename from flowsint-api/tests/scanners/ip/geolocation.pyrename to flowsint-api/tests/scanners/ips/geolocation.pydiff --git a/flowsint-api/tests/scanners/ips/ip_to_asn.py b/flowsint-api/tests/scanners/ips/ip_to_asn.pynew file mode 100644index 00000000..94a99970--- /dev/null+++ b/flowsint-api/tests/scanners/ips/ip_to_asn.py@@ -0,0 +1,261 @@+import pytest+import json+from unittest.mock import Mock+from app.scanners.ips.ip_to_asn import AsnScanner+from app.types.ip import MinimalIp+from app.types.asn import ASN+from app.types.cidr import CIDR+from tests.logger import TestLogger++logger = TestLogger()+# The scanner will get a mock logger from conftest.py automatically+scanner = AsnScanner("sketch_123", "scan_123", logger)++def test_preprocess_valid_ips():+ ips = [+ MinimalIp(address="8.8.8.8"),+ MinimalIp(address="1.1.1.1"),+ ]+ result = scanner.preprocess(ips)++ result_addresses = [ip.address for ip in result]+ expected_addresses = [ip.address for ip in ips]++ assert result_addresses == expected_addresses++def test_unprocessed_valid_ips():+ ips = [+ "8.8.8.8",+ "1.1.1.1",+ ]+ result = scanner.preprocess(ips)+ result_ips = [ip for ip in result]+ expected_ips = [MinimalIp(address=ip) for ip in ips]+ assert result_ips == expected_ips++def test_preprocess_invalid_ips():+ ips = [+ MinimalIp(address="8.8.8.8"),+ MinimalIp(address="invalid_ip"),+ MinimalIp(address="192.168.1.1"),+ ]+ result = scanner.preprocess(ips)++ result_addresses = [ip.address for ip in result]+ assert "8.8.8.8" in result_addresses+ assert "192.168.1.1" in result_addresses+ assert "invalid_ip" not in result_addresses++def test_preprocess_multiple_formats():+ ips = [+ {"address": "8.8.8.8"},+ {"invalid_key": "1.1.1.1"},+ MinimalIp(address="192.168.1.1"),+ "10.0.0.1",+ ]+ result = scanner.preprocess(ips)++ result_addresses = [ip.address for ip in result]+ assert "8.8.8.8" in result_addresses+ assert "192.168.1.1" in result_addresses+ assert "10.0.0.1" in result_addresses+ assert "1.1.1.1" not in result_addresses # Should be filtered out due to invalid key+++def test_scan_extracts_asn_info(monkeypatch):+ mock_asnmap_output = {+ "input": "8.8.8.8",+ "as_number": "AS15169",+ "as_name": "GOOGLE",+ "as_country": "US",+ "as_range": ["8.8.8.0/24", "8.8.4.0/24"]+ }++ class MockSubprocessResult:+ def __init__(self, stdout):+ self.stdout = stdout+ self.returncode = 0++ def mock_subprocess_run(cmd, input, capture_output, text, timeout):+ assert "asnmap" in cmd+ assert input == "8.8.8.8"+ return MockSubprocessResult(json.dumps(mock_asnmap_output))++ # Patch the subprocess call in the scanner+ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [MinimalIp(address="8.8.8.8")]+ asns = scanner.scan(input_data)++ assert isinstance(asns, list)+ assert len(asns) == 1++ asn = asns[0]+ assert isinstance(asn, ASN)+ assert asn.number == 15169 # AS15169 -> 15169+ assert asn.name == "GOOGLE"+ assert asn.country == "US"+ assert len(asn.cidrs) == 2+ assert str(asn.cidrs[0].network) == "8.8.8.0/24"+ assert str(asn.cidrs[1].network) == "8.8.4.0/24"+++def test_scan_handles_no_asn_found(monkeypatch):+ class MockSubprocessResult:+ def __init__(self, stdout):+ self.stdout = stdout+ self.returncode = 0++ def mock_subprocess_run(cmd, input, capture_output, text, timeout):+ # Return empty output to simulate no ASN found+ return MockSubprocessResult("")++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [MinimalIp(address="192.168.1.1")]+ asns = scanner.scan(input_data)++ assert isinstance(asns, list)+ assert len(asns) == 1++ asn = asns[0]+ assert isinstance(asn, ASN)+ assert asn.number == 0+ assert asn.name == "Unknown"+ assert asn.country == "Unknown"+ assert len(asn.cidrs) == 0+++def test_scan_handles_subprocess_exception(monkeypatch):+ def mock_subprocess_run(cmd, input, capture_output, text, timeout):+ raise Exception("Subprocess failed")++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [MinimalIp(address="8.8.8.8")]+ asns = scanner.scan(input_data)++ assert isinstance(asns, list)+ assert len(asns) == 1++ asn = asns[0]+ assert isinstance(asn, ASN)+ assert asn.number == 0+ assert asn.name == "Unknown"+ assert asn.country == "Unknown"+++def test_scan_multiple_ips(monkeypatch):+ mock_responses = {+ "8.8.8.8": {+ "input": "8.8.8.8",+ "as_number": "AS15169",+ "as_name": "GOOGLE",+ "as_country": "US",+ "as_range": ["8.8.8.0/24"]+ },+ "1.1.1.1": {+ "input": "1.1.1.1",+ "as_number": "AS13335",+ "as_name": "CLOUDFLARE",+ "as_country": "US",+ "as_range": ["1.1.1.0/24"]+ }+ }++ class MockSubprocessResult:+ def __init__(self, stdout):+ self.stdout = stdout+ self.returncode = 0++ def mock_subprocess_run(cmd, input, capture_output, text, timeout):+ if input in mock_responses:+ return MockSubprocessResult(json.dumps(mock_responses[input]))+ return MockSubprocessResult("")++ monkeypatch.setattr("subprocess.run", mock_subprocess_run)++ input_data = [MinimalIp(address="8.8.8.8"), MinimalIp(address="1.1.1.1")]+ asns = scanner.scan(input_data)++ assert len(asns) == 2++ # Check first ASN+ assert asns[0].number == 15169+ assert asns[0].name == "GOOGLE"++ # Check second ASN+ assert asns[1].number == 13335+ assert asns[1].name == "CLOUDFLARE"+++def test_schemas():+ input_schema = scanner.input_schema()+ output_schema = scanner.output_schema()++ # Input schema should have address field+ assert "properties" in input_schema+ address_prop = next((prop for prop in input_schema["properties"] if prop["name"] == "address"), None)+ assert address_prop is not None+ assert address_prop["type"] == "string"++ # Output schema should have ASN fields+ assert "properties" in output_schema+ prop_names = [prop["name"] for prop in output_schema["properties"]]+ assert "number" in prop_names+ assert "name" in prop_names+ assert "country" in prop_names+ assert "cidrs" in prop_names+++def test_postprocess_creates_neo4j_relationships(monkeypatch):+ # Mock Neo4j connection+ mock_neo4j = Mock()+ scanner.neo4j_conn = mock_neo4j++ input_data = [MinimalIp(address="8.8.8.8")]+ asn_results = [ASN(+ number=15169,+ name="GOOGLE",+ country="US",+ cidrs=[CIDR(network="8.8.8.0/24")]+ )]++ result = scanner.postprocess(asn_results, input_data)++ # Verify Neo4j query was called+ mock_neo4j.query.assert_called_once()++ # Check the query parameters+ call_args = mock_neo4j.query.call_args+ params = call_args[0][1]+ assert params["ip_address"] == "8.8.8.8"+ assert params["asn_number"] == 15169+ assert params["asn_name"] == "GOOGLE"+ assert params["asn_country"] == "US"+ assert params["sketch_id"] == "sketch_123"++ # Should return the same results+ assert result == asn_results+++def test_postprocess_skips_unknown_asns(monkeypatch):+ # Mock Neo4j connection+ mock_neo4j = Mock()+ scanner.neo4j_conn = mock_neo4j++ input_data = [MinimalIp(address="192.168.1.1")]+ asn_results = [ASN(+ number=0, # Unknown ASN+ name="Unknown",+ country="Unknown",+ cidrs=[]+ )]++ result = scanner.postprocess(asn_results, input_data)++ # Verify Neo4j query was NOT called for unknown ASN+ mock_neo4j.query.assert_not_called()++ # Should return the same results+ assert result == asn_results\ No newline at end of filediff --git a/flowsint-app/.vscode/settings.json b/flowsint-app/.vscode/settings.jsonindex 4c05394e..20951e4b 100644--- a/flowsint-app/.vscode/settings.json+++ b/flowsint-app/.vscode/settings.json@@ -1,6 +1,6 @@{"[typescript]": {- "editor.defaultFormatter": "esbenp.prettier-vscode"+ "editor.defaultFormatter": "vscode.typescript-language-features"},"[javascript]": {"editor.defaultFormatter": "esbenp.prettier-vscode"diff --git a/flowsint-app/package.json b/flowsint-app/package.jsonindex 36422dc9..c2553b39 100644--- a/flowsint-app/package.json+++ b/flowsint-app/package.json@@ -52,26 +52,53 @@"@radix-ui/react-toggle": "^1.1.9","@radix-ui/react-toggle-group": "^1.1.10","@radix-ui/react-tooltip": "^1.2.7",+ "@react-sigma/core": "^5.0.4","@tailwindcss/vite": "^3.4.1","@tanstack/react-query": "^5.79.0","@tanstack/react-virtual": "^3.13.9",+ "@tiptap/extension-code-block-lowlight": "^2.12.0",+ "@tiptap/extension-color": "^2.12.0",+ "@tiptap/extension-heading": "^2.12.0",+ "@tiptap/extension-highlight": "^2.12.0",+ "@tiptap/extension-horizontal-rule": "^2.12.0",+ "@tiptap/extension-image": "^2.12.0",+ "@tiptap/extension-link": "^2.12.0",+ "@tiptap/extension-placeholder": "^2.12.0",+ "@tiptap/extension-subscript": "^2.12.0",+ "@tiptap/extension-superscript": "^2.12.0",+ "@tiptap/extension-task-item": "^2.12.0",+ "@tiptap/extension-task-list": "^2.12.0",+ "@tiptap/extension-text-align": "^2.12.0",+ "@tiptap/extension-text-style": "^2.12.0",+ "@tiptap/extension-typography": "^2.12.0",+ "@tiptap/extension-underline": "^2.12.0",+ "@tiptap/pm": "^2.12.0",+ "@tiptap/react": "^2.12.0",+ "@tiptap/starter-kit": "^2.12.0","@xyflow/react": "^12.6.4","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "cytoscape": "^3.32.0","d3-force": "^3.0.0","date-fns": "^4.1.0","electron-updater": "^6.1.7","embla-carousel-react": "^8.6.0",+ "graphology": "^0.26.0",+ "graphology-layout-force": "^0.2.4",+ "graphology-layout-forceatlas2": "^0.10.1","input-otp": "^1.4.2",+ "lowlight": "^3.3.0","lucide-react": "^0.511.0","next-themes": "^0.4.6","react-day-picker": "8.10.1","react-hook-form": "^7.56.4",+ "react-medium-image-zoom": "^5.2.14","react-resizable-panels": "^3.0.2","recharts": "^2.15.3",+ "sigma": "^3.0.2","sonner": "^2.0.4",- "tailwindcss": "^3.4.1",+ "tailwindcss": "^4.1.8","tailwindcss-animate": "^1.0.7","tw-animate-css": "^1.3.2","usehooks-ts": "^3.1.1",diff --git a/flowsint-app/src/renderer/index.html b/flowsint-app/src/renderer/index.htmlindex 9ed61218..6a64e722 100644--- a/flowsint-app/src/renderer/index.html+++ b/flowsint-app/src/renderer/index.html@@ -1,11 +1,11 @@<!DOCTYPE html><html lang="en" theme="dark"><head>- <!-- <script+ <scriptcrossOrigin="anonymous"src="//unpkg.com/react-scan/dist/auto.global.js">- </script> -->+ </script><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />diff --git a/flowsint-app/src/renderer/src/api/analysis-service.ts b/flowsint-app/src/renderer/src/api/analysis-service.tsnew file mode 100644index 00000000..679302b9--- /dev/null+++ b/flowsint-app/src/renderer/src/api/analysis-service.ts@@ -0,0 +1,37 @@+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 filediff --git a/flowsint-app/src/renderer/src/components/command.tsx b/flowsint-app/src/renderer/src/components/command.tsxindex 04bf59af..d0694b73 100644--- a/flowsint-app/src/renderer/src/components/command.tsx+++ b/flowsint-app/src/renderer/src/components/command.tsx@@ -2,14 +2,8 @@import * as React from "react"import {- Calculator,- Calendar,- CreditCard,Fingerprint,Search,- Settings,- Smile,- User,Workflow,} from "lucide-react"@@ -20,8 +14,6 @@ import {CommandInput,CommandItem,CommandList,- CommandSeparator,- CommandShortcut,} from "@/components/ui/command"import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"import { Button } from "./ui/button"@@ -41,7 +33,7 @@ export function Command() {<><Button variant="ghost" onClick={() => setOpen(true)} className="text-xs h-8 w-full max-w-3xs border flex 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 border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100">+ <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>diff --git a/flowsint-app/src/renderer/src/components/graphs/graph-panel.tsx b/flowsint-app/src/renderer/src/components/graphs/graph-panel.tsxindex 92ca2efa..f44a011f 100644--- a/flowsint-app/src/renderer/src/components/graphs/graph-panel.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/graph-panel.tsx@@ -1,17 +1,19 @@import { useLoaderData } from '@tanstack/react-router'import { useEffect, useRef, memo, useState } from 'react'-import Graph from '../sketches/graph'+// import Graph from '../sketches/graph'import { useSketchStore } from '@/stores/sketch-store'import { Toolbar } from '../sketches/toolbar'import { cn } from '@/lib/utils'import { ArrowDownToLineIcon } from 'lucide-react'import { CreateRelationDialog } from './create-relation'+// import GraphSigma from '../sketches/graph-sigma'+import Graph from '../sketches/graph'// Separate component for the drag overlayconst DragOverlay = memo(({ isDragging }: { isDragging: boolean }) => (<divclassName={cn(- 'absolute flex items-center justify-center inset-0 bg-primary/20 backdrop-blur-xs gap-1',+ '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')}@@ -89,7 +91,8 @@ const GraphPanel = () => {onDragLeave={handleDragLeave}onDrop={handleDrop}>- <Graph isLoading={false} />+ <Graph />+ {/* <GraphSigma /> */}<DragOverlay isDragging={isDraggingOver} /><div className='absolute w-10 right-3 top-3 h-min shadow-sm border rounded-full overflow-y-auto'><Toolbar />diff --git a/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx b/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsxindex dd3a60e0..ff83c37b 100644--- a/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/launch-transform.tsx@@ -13,7 +13,6 @@ import {} from "@/components/ui/sheet"import { Card, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"-import { Label } from "@/components/ui/label"import { useLaunchTransform } from "@/hooks/use-launch-transform"import { formatDistanceToNow } from "date-fns"import { useQuery } from "@tanstack/react-query"@@ -86,11 +85,10 @@ const LaunchTransform = ({ values, type }: { values: string[], type: string }) ={transforms?.map((transform: Transform) => (<Cardkey={transform.id}- className={`cursor-pointer border transition-all ${- selectedTransform?.id === transform.id- ? "border-primary bg-primary/5"+ className={`cursor-pointer border transition-all ${selectedTransform?.id === transform.id+ ? "border-primary bg-primary/5": "hover:border-primary/50"- }`}+ }`}onClick={() => handleSelectTransform(transform)}><CardHeader className="p-4">@@ -99,13 +97,13 @@ const LaunchTransform = ({ values, type }: { values: string[], type: string }) =<RadioGroupItem value={transform.id} id={transform.id} /><CardTitle className="text-base">{transform.name}</CardTitle></div>-+{transform.description && (<CardDescription className="text-sm pl-7">{transform.description || "No description available"}</CardDescription>)}-+<div className="flex flex-col space-y-1 text-xs text-muted-foreground pl-7"><div>Created {formatDistanceToNow(transform.created_at, { addSuffix: true })}</div><div>Updated {formatDistanceToNow(transform.last_updated_at, { addSuffix: true })}</div>diff --git a/flowsint-app/src/renderer/src/components/graphs/nodes-panel.tsx b/flowsint-app/src/renderer/src/components/graphs/nodes-panel.tsxindex 380b7c20..4e74e177 100644--- a/flowsint-app/src/renderer/src/components/graphs/nodes-panel.tsx+++ b/flowsint-app/src/renderer/src/components/graphs/nodes-panel.tsx@@ -250,7 +250,7 @@ const NodesPanel = memo(({ nodes, isLoading }: { nodes: NodeData[]; isLoading?:<Button variant={"outline"} className="h-7 w-8 relative border-border border" size={"icon"}><FilterIcon 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" variant={"default"}>+ <Badge className="absolute -top-2 -right-1 text-xs rounded-full h-4 w-4 text-white" variant={"default"}>{filters.length}</Badge>)}diff --git a/flowsint-app/src/renderer/src/components/layout/log-panel.tsx b/flowsint-app/src/renderer/src/components/layout/log-panel.tsxindex 0fa7b412..f5b965f7 100644--- a/flowsint-app/src/renderer/src/components/layout/log-panel.tsx+++ b/flowsint-app/src/renderer/src/components/layout/log-panel.tsx@@ -18,7 +18,7 @@ export function LogPanel() {}return (- <div className="h-full bg-card relative">+ <div className="h-full bg-background relative"><ScrollArea className="h-full"><div className="space-y-1 p-2 font-mono text-xs">{logs.map((log) => (diff --git a/flowsint-app/src/renderer/src/components/layout/notes-panel.tsx b/flowsint-app/src/renderer/src/components/layout/notes-panel.tsxnew file mode 100644index 00000000..f1c3b220--- /dev/null+++ b/flowsint-app/src/renderer/src/components/layout/notes-panel.tsx@@ -0,0 +1,274 @@+import { useState, useEffect } from "react"+import { useQuery, useMutation } from "@tanstack/react-query"+import { MinimalTiptapEditor } from "@/components/shared/editor"+import { analysisService } from "@/api/analysis-service"+import type { Analysis } from "@/types"+import { useParams } from "@tanstack/react-router"+import { Button } from "@/components/ui/button"+import { Skeleton } from "@/components/ui/skeleton"+import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select"+import { PlusIcon, Trash2, Save } from "lucide-react"+import { useAnalysisPanelStore } from "@/stores/analysis-panel-store"+import { toast } from "sonner"+import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"+import { useConfirm } from "../use-confirm-dialog"++export const AnalysisPanel = () => {+ const { investigationId } = useParams({ strict: false }) as { investigationId: string }+ const currentAnalysisId = useAnalysisPanelStore(s => s.currentAnalysisId)+ const setCurrentAnalysisId = useAnalysisPanelStore(s => s.setCurrentAnalysisId)+ const { confirm } = useConfirm()+++ // 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 = analyses?.find(a => a.id === currentAnalysisId) || (analyses && analyses[0])++ // 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])++ // State for editor+ const [editorValue, setEditorValue] = useState<any>("")+ const [titleValue, setTitleValue] = useState("")++ useEffect(() => {+ if (currentAnalysis) {+ // Handle both string content and object content+ const content = currentAnalysis.content+ if (typeof content === 'string') {+ try {+ // Try to parse if it's a JSON string+ setEditorValue(JSON.parse(content))+ } catch {+ // If parsing fails, treat as plain text and convert to editor format+ setEditorValue(content || "")+ }+ } else {+ // If it's already an object, use it directly+ setEditorValue(content || "")+ }+ console.log("Setting editorValue:", content)+ setTitleValue(currentAnalysis.title || "")+ } else {+ // Reset when no analysis is selected+ setEditorValue("")+ setTitleValue("")+ console.log("Resetting editorValue")+ }+ }, [currentAnalysisId, currentAnalysis?.id, currentAnalysis?.content, currentAnalysis?.title])++ // Mutations+ const createMutation = useMutation({+ mutationFn: async () => {+ const newAnalysis: Partial<Analysis> = {+ title: "Untitled Analysis",+ investigation_id: investigationId,+ content: {},+ }+ const res = await analysisService.create(JSON.stringify(newAnalysis))++ return res+ },+ onSuccess: async (data) => {+ await refetch()+ setCurrentAnalysisId(data.id)+ 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 (!currentAnalysis) return+ return analysisService.update(currentAnalysis.id, JSON.stringify({+ ...currentAnalysis,+ ...updated,+ content: editorValue+ }))+ },+ onSuccess: async () => {+ await refetch()+ toast.success("Analysis saved !")+ },+ onError: (error) => {+ toast.error("Failed to save analysis: " + (error instanceof Error ? error.message : "Unknown error"))+ }+ })++ const deleteMutation = useMutation({+ mutationFn: async (id: string) => {+ return analysisService.delete(id)+ },+ onSuccess: async () => {+ await 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)+ }+ toast.success("Analysis deleted")+ },+ onError: (error) => {+ toast.error("Failed to delete analysis: " + (error instanceof Error ? error.message : "Unknown error"))+ }+ })++ const deleteAnalysis = async () => {+ if (!currentAnalysisId) {+ 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(currentAnalysisId)+ }++ useKeyboardShortcut({+ key: "s",+ ctrlOrCmd: true,+ callback: () => {+ saveMutation.mutate({})+ },+ })++ return (+ <div className="flex flex-col h-full w-full">+ {/* Header with unified title/analysis selector and controls */}+ <div className="border-b bg-background">+ <div className="flex items-center justify-between p-4">+ {/* Unified title and analysis selector */}+ <div className="flex items-center gap-3 flex-1 min-w-0">+ {isLoadingAnalyses ? (+ <Skeleton className="h-9 w-64" />+ ) : isError ? (+ <div className="text-sm text-destructive">Error loading analyses</div>+ ) : analyses && analyses.length > 0 ? (+ <div className="flex items-center gap-2 flex-1 min-w-0">+ <Select+ value={currentAnalysisId || ""}+ onValueChange={(value) => setCurrentAnalysisId(value)}+ >+ <SelectTrigger className="border-none shadow-none bg-transparent hover:bg-muted/20 focus:bg-muted/30 p-2 h-auto min-w-0 flex-1">+ <div className="flex flex-col items-start min-w-0 flex-1">+ <input+ className="text-xl font-bold bg-transparent outline-none border-none p-0 m-0 w-full placeholder:text-muted-foreground/60"+ value={titleValue}+ onChange={e => setTitleValue(e.target.value)}+ placeholder="Untitled Analysis"+ disabled={!currentAnalysis}+ onClick={e => e.stopPropagation()}+ />+ </div>+ </SelectTrigger>+ <SelectContent className="shadow-none border-muted">+ {analyses.map((analysis) => (+ <SelectItem key={analysis.id} value={analysis.id}>+ <div className="flex flex-col items-start">+ <span className="font-medium">{analysis.title || "Untitled"}</span>+ <span className="text-xs text-muted-foreground">+ {analysis.id === currentAnalysisId ? "Current" : "Switch to this analysis"}+ </span>+ </div>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ ) : (+ <div className="flex items-center gap-2 flex-1 min-w-0">+ <div className="text-sm font-bold text-muted-foreground/60 truncate text-ellipsis">No analyses yet</div>+ </div>+ )}+ </div>++ {/* Action buttons */}+ <div className="flex items-center gap-1">+ <Button+ size="icon"+ variant="ghost"+ onClick={() => createMutation.mutate()}+ disabled={createMutation.isPending}+ title="New Analysis"+ className="h-8 w-8"+ >+ <PlusIcon className="w-4 h-4" strokeWidth={1.5} />+ </Button>+ <Button+ size="icon"+ variant="ghost"+ onClick={() => saveMutation.mutate({})}+ disabled={!currentAnalysis || saveMutation.isPending}+ title="Save"+ className="h-8 w-8"+ >+ <Save className="w-4 h-4" strokeWidth={1.5} />+ </Button>+ <Button+ size="icon"+ variant="ghost"+ onClick={deleteAnalysis}+ disabled={!currentAnalysis || deleteMutation.isPending}+ title="Delete"+ className="h-8 w-8"+ >+ <Trash2 className="w-4 h-4" strokeWidth={1.5} />+ </Button>+ </div>+ </div>+ </div>++ {/* Editor */}+ <div className="flex-1 min-h-0">+ {currentAnalysis ? (+ <MinimalTiptapEditor+ key={currentAnalysisId}+ immediatelyRender={false}+ value={editorValue}+ onChange={setEditorValue}+ className="w-full h-full"+ editorContentClassName="p-5 min-h-[300px]"+ output="json"+ placeholder="Enter your analysis..."+ autofocus={true}+ editable={true}+ editorClassName="focus:outline-hidden"+ />+ ) : (+ <div className="flex flex-col items-center justify-center h-full text-muted-foreground space-y-3">+ <div>No analysis selected.</div>+ {analyses && analyses.length === 0 && (+ <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>+ )+}++export default AnalysisPanel\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/components/layout/root.layout.tsx b/flowsint-app/src/renderer/src/components/layout/root.layout.tsxindex 0e88de6e..20081f63 100644--- a/flowsint-app/src/renderer/src/components/layout/root.layout.tsx+++ b/flowsint-app/src/renderer/src/components/layout/root.layout.tsx@@ -6,58 +6,110 @@ 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 { useConsoleStore } from "@/stores/console-store"+import { useLayoutStore } from "@/stores/layout-store"import { PathBreadcrumb } from "./breadcrumb"+import NotesPanel from "./notes-panel"+import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"interface LayoutProps {children: ReactNode}export default function RootLayout({ children }: LayoutProps) {- const { isOpen } = useConsoleStore()+ const isOpenConsole = useLayoutStore(s => s.isOpenConsole)+ const toggleConsole = useLayoutStore(s => s.toggleConsole)+ const isOpenPanel = useLayoutStore(s => s.isOpenPanel)+ const isOpenChat = useLayoutStore(s => s.isOpenChat)+ const togglePanel = useLayoutStore(s => s.togglePanel)+ const closePanel = useLayoutStore(s => s.closePanel)+ const openPanel = useLayoutStore(s => s.openPanel)+ const toggleChat = useLayoutStore(s => s.toggleChat)+ const closeChat = useLayoutStore(s => s.closeChat)+ const openChat = useLayoutStore(s => s.openChat)++ // Set up keyboard shortcut for chat panel+ useKeyboardShortcut({+ key: "l",+ ctrlOrCmd: true,+ callback: toggleChat+ })+ useKeyboardShortcut({+ key: "b",+ ctrlOrCmd: true,+ callback: togglePanel+ })+ useKeyboardShortcut({+ key: "x",+ ctrlOrCmd: true,+ callback: toggleConsole+ })return (<ConfirmContextProvider><div className="flex flex-col h-screen w-screen overflow-hidden">{/* Top navbar */}<TopNavbar />-{/* Main layout */}- <ResizablePanelGroup direction="vertical" className="flex-1 min-h-0">+ <ResizablePanelGroup autoSaveId="conditional" direction="vertical" className="flex-1 min-h-0">{/* Main content area with optional console */}- <ResizablePanel order={1} defaultSize={isOpen ? 70 : 100} minSize={30}>+ <ResizablePanel order={1} id="main" defaultSize={isOpenConsole ? 70 : 100} minSize={30}><ResizablePanelGroup+ autoSaveId="conditional2"direction="vertical"className="h-full">{/* Main content */}- <ResizablePanel defaultSize={100} minSize={30}>+ <ResizablePanel id="content" order={1} defaultSize={100} minSize={30}><ResizablePanelGroupdirection="horizontal"+ autoSaveId="conditional3"className="h-full"><Sidebar />-- {/* Secondary Navigation panel */}- <ResizablePanel- defaultSize={20}- minSize={16}- maxSize={30}- collapsible={true}- collapsedSize={0}- >- <div className="h-10 bg-card flex items-center justify-end px-2 text-sm w-full font-semibold border-b">- <PathBreadcrumb />- </div>- <div className="h-[calc(100%-40px)] flex flex-col overflow-hidden bg-card">- <SecondaryNavigation />- </div>- </ResizablePanel>-- <ResizableHandle withHandle />- <ResizablePanel className="h-full w-full">+ {isOpenPanel && (+ <>+ <ResizablePanel+ id="sidebar"+ order={2}+ defaultSize={20}+ minSize={16}+ maxSize={30}+ onCollapse={closePanel}+ onExpand={openPanel}+ collapsible={true}+ collapsedSize={0}+ >+ <div className="h-10 bg-card flex items-center justify-end px-2 text-sm w-full font-semibold border-b">+ <PathBreadcrumb />+ </div>+ <div className="h-[calc(100%-40px)] flex flex-col overflow-hidden bg-card">+ <SecondaryNavigation />+ </div>+ </ResizablePanel>+ <ResizableHandle withHandle />+ </>+ )}+ <ResizablePanel className="h-full w-full" id="children" order={3}>{children}</ResizablePanel>+ {isOpenChat && (+ <>+ <ResizableHandle withHandle />+ <ResizablePanel+ id="notes"+ order={4}+ defaultSize={20}+ minSize={16}+ maxSize={40}+ onCollapse={closeChat}+ onExpand={openChat}+ collapsible={true}+ collapsedSize={2}+ >+ <NotesPanel />+ </ResizablePanel>+ </>+ )}</ResizablePanelGroup></ResizablePanel>@@ -67,10 +119,12 @@ export default function RootLayout({ children }: LayoutProps) {</div>{/* Console panel - only shown when isOpen is true */}- {isOpen && (+ {isOpenConsole && (<><ResizableHandle /><ResizablePanel+ id="console"+ order={5}defaultSize={30}minSize={20}maxSize={50}diff --git a/flowsint-app/src/renderer/src/components/layout/sidebar.tsx b/flowsint-app/src/renderer/src/components/layout/sidebar.tsxindex a27f2d4d..99ac17e8 100644--- a/flowsint-app/src/renderer/src/components/layout/sidebar.tsx+++ b/flowsint-app/src/renderer/src/components/layout/sidebar.tsx@@ -1,10 +1,13 @@import {+ ChevronsRightIcon,Fingerprint,Home,type LucideIcon,Workflow} from "lucide-react"import { Link } from "@tanstack/react-router"+import { useLayoutStore } from "@/stores/layout-store"+import { Button } from "../ui/button"interface NavItem {icon: LucideIcon@@ -13,6 +16,10 @@ interface NavItem {}export function Sidebar() {++ const togglePanel = useLayoutStore(s => s.togglePanel)+ const isOpenPanel = useLayoutStore(s => s.isOpenPanel)+const navItems: NavItem[] = [{ icon: Home, label: "Dashboard", href: "/dashboard" },{ icon: Fingerprint, label: "Cases", href: "/dashboard/investigations" },@@ -23,8 +30,8 @@ export function Sidebar() {"flex flex-col items-center justify-center h-14 w-full rounded-sm gap-1 text-xs font-normal hover:bg-muted"return (- <div className="w-22 border-r h-full shrink-0 bg-card">- <div className="flex flex-col items-center gap-1 p-2 h-full">+ <div className="w-22 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// Render content consistently regardless of container@@ -50,6 +57,14 @@ export function Sidebar() {)})}</div>+ <div className="grow"></div>+ <div className="flex justify-center items-center p-3">+ <Button variant={"ghost"} onClick={togglePanel}>+ <ChevronsRightIcon+ className={`h-12 w-12 transition-transform duration-200 ${isOpenPanel ? 'rotate-180' : 'rotate-0'}`}+ />+ </Button>+ </div></div>)}diff --git a/flowsint-app/src/renderer/src/components/layout/status-bar.tsx b/flowsint-app/src/renderer/src/components/layout/status-bar.tsxindex 7cdd3ce7..c79ced3f 100644--- a/flowsint-app/src/renderer/src/components/layout/status-bar.tsx+++ b/flowsint-app/src/renderer/src/components/layout/status-bar.tsx@@ -1,11 +1,11 @@import { Button } from "@/components/ui/button"import { HelpCircle, Info, Laptop, Terminal, Trash, Unlock } from "lucide-react"import { ModeToggle } from "../mode-toggle"-import { useConsoleStore } from "@/stores/console-store"+import { useLayoutStore } from "@/stores/layout-store"export function StatusBar() {- const { isOpen, toggleConsole } = useConsoleStore()-+ 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">@@ -16,14 +16,14 @@ export function StatusBar() {</div><div className="flex-1"></div><div className="flex items-center gap-2">- <Button- variant="ghost"- size="sm"+ <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 {isOpen ? '(Open)' : ''}</span>+ <span>Console {isOpenConsole ? '(Open)' : ''}</span></Button><Button variant="ghost" size="sm" className="h-6 gap-1 text-xs"><Unlock strokeWidth={1.4} className="h-3 w-3 opacity-60" />diff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/bubble-menu/link-bubble-menu.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/bubble-menu/link-bubble-menu.tsxnew file mode 100644index 00000000..0b063502--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/bubble-menu/link-bubble-menu.tsx@@ -0,0 +1,117 @@+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+}++interface LinkAttributes {+ href: string+ target: string+}++export const LinkBubbleMenu: React.FC<LinkBubbleMenuProps> = ({ editor }) => {+ const [showEdit, setShowEdit] = React.useState(false)+ const [linkAttrs, setLinkAttrs] = React.useState<LinkAttributes>({+ href: "",+ target: "",+ })+ 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, " ")++ setLinkAttrs({ href, target })+ setSelectedText(text)+ }, [editor])++ const shouldShow = React.useCallback(+ ({ editor, from, to }: ShouldShowProps) => {+ if (from === to) {+ return false+ }+ const { href } = editor.getAttributes("link")++ if (!editor.isActive("link") || !editor.isEditable) {+ return false+ }++ if (href) {+ updateLinkState()+ return true+ }+ return false+ },+ [updateLinkState]+ )++ const handleEdit = React.useCallback(() => {+ setShowEdit(true)+ }, [])++ const onSetLink = React.useCallback(+ (url: string, text?: string, openInNewTab?: boolean) => {+ editor+ .chain()+ .focus()+ .extendMarkRange("link")+ .insertContent({+ type: "text",+ text: text || url,+ marks: [+ {+ type: "link",+ attrs: {+ href: url,+ target: openInNewTab ? "_blank" : "",+ },+ },+ ],+ })+ .setLink({ href: url, target: openInNewTab ? "_blank" : "" })+ .run()+ setShowEdit(false)+ updateLinkState()+ },+ [editor, updateLinkState]+ )++ const onUnsetLink = React.useCallback(() => {+ editor.chain().focus().extendMarkRange("link").unsetLink().run()+ setShowEdit(false)+ updateLinkState()+ }, [editor, updateLinkState])++ return (+ <BubbleMenu+ editor={editor}+ shouldShow={shouldShow}+ tippyOptions={{+ placement: "bottom-start",+ onHidden: () => setShowEdit(false),+ }}+ >+ {showEdit ? (+ <LinkEditBlock+ defaultUrl={linkAttrs.href}+ defaultText={selectedText}+ 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}+ />+ )}+ </BubbleMenu>+ )+}diff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/image/image-edit-block.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/image/image-edit-block.tsxnew file mode 100644index 00000000..4ebe152c--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/image/image-edit-block.tsx@@ -0,0 +1,94 @@+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,+}) => {+ const fileInputRef = React.useRef<HTMLInputElement>(null)+ const [link, setLink] = React.useState("")++ const handleClick = React.useCallback(() => {+ fileInputRef.current?.click()+ }, [])++ const handleFile = React.useCallback(+ async (e: React.ChangeEvent<HTMLInputElement>) => {+ const files = e.target.files+ if (!files?.length) return++ const insertImages = async () => {+ const contentBucket: { src: File | string }[] = []+ const filesArray = Array.from(files)++ for (const file of filesArray) {+ contentBucket.push({ src: file })+ }++ editor.commands.setImages(contentBucket)+ }++ await insertImages()+ close()+ },+ [editor, close]+ )++ const handleSubmit = React.useCallback(+ (e: React.FormEvent<HTMLFormElement>) => {+ e.preventDefault()+ e.stopPropagation()++ if (link) {+ editor.commands.setImages([{ src: link }])+ close()+ }+ },+ [editor, link, close]+ )++ return (+ <form onSubmit={handleSubmit} className="space-y-6">+ <div className="space-y-1">+ <Label htmlFor="image-link">Attach an image link</Label>+ <div className="flex">+ <Input+ id="image-link"+ type="url"+ required+ placeholder="https://example.com"+ value={link}+ className="grow"+ onChange={(e: React.ChangeEvent<HTMLInputElement>) =>+ setLink(e.target.value)+ }+ />+ <Button type="submit" className="ml-2">+ Submit+ </Button>+ </div>+ </div>+ <Button type="button" className="w-full" onClick={handleClick}>+ Upload from your computer+ </Button>+ <input+ type="file"+ accept="image/*"+ ref={fileInputRef}+ multiple+ className="hidden"+ onChange={handleFile}+ />+ </form>+ )+}++export default ImageEditBlockdiff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/image/image-edit-dialog.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/image/image-edit-dialog.tsxnew file mode 100644index 00000000..6ae5eadb--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/image/image-edit-dialog.tsx@@ -0,0 +1,50 @@+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"++interface ImageEditDialogProps extends VariantProps<typeof toggleVariants> {+ editor: Editor+}++const ImageEditDialog = ({ editor, size, variant }: ImageEditDialogProps) => {+ const [open, setOpen] = useState(false)++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>+ <ToolbarButton+ isActive={editor.isActive("image")}+ tooltip="Image"+ aria-label="Image"+ size={size}+ variant={variant}+ >+ <ImageIcon className="size-5" />+ </ToolbarButton>+ </DialogTrigger>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Select image</DialogTitle>+ <DialogDescription className="sr-only">+ Upload an image from your computer+ </DialogDescription>+ </DialogHeader>+ <ImageEditBlock editor={editor} close={() => setOpen(false)} />+ </DialogContent>+ </Dialog>+ )+}++export { ImageEditDialog }diff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-edit-block.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-edit-block.tsxnew file mode 100644index 00000000..47f74e29--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-edit-block.tsx@@ -0,0 +1,88 @@+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+ defaultText?: string+ defaultIsNewTab?: boolean+ onSave: (url: string, text?: string, isNewTab?: boolean) => void+}++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 [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())++ if (isValid) {+ onSave(url, text, isNewTab)+ } else {+ formRef.current.querySelectorAll("input").forEach((input) => {+ if (!input.checkValidity()) {+ input.reportValidity()+ }+ })+ }+ }+ },+ [onSave, url, text, isNewTab]+ )++ React.useImperativeHandle(ref, () => formRef.current as HTMLDivElement)++ return (+ <div ref={formRef}>+ <div className={cn("space-y-4", className)}>+ <div className="space-y-1">+ <Label>URL</Label>+ <Input+ type="url"+ required+ placeholder="Enter URL"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ />+ </div>++ <div className="space-y-1">+ <Label>Display Text (optional)</Label>+ <Input+ type="text"+ placeholder="Enter display text"+ value={text}+ onChange={(e) => setText(e.target.value)}+ />+ </div>++ <div className="flex items-center space-x-2">+ <Label>Open in New Tab</Label>+ <Switch checked={isNewTab} onCheckedChange={setIsNewTab} />+ </div>++ <div className="flex justify-end space-x-2">+ <Button type="button" onClick={handleSave}>+ Save+ </Button>+ </div>+ </div>+ </div>+ )+ }+)++LinkEditBlock.displayName = "LinkEditBlock"++export default LinkEditBlockdiff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-edit-popover.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-edit-popover.tsxnew file mode 100644index 00000000..5ec11eb3--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-edit-popover.tsx@@ -0,0 +1,72 @@+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+}++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 onSetLink = React.useCallback(+ (url: string, text?: string, openInNewTab?: boolean) => {+ editor+ .chain()+ .focus()+ .extendMarkRange("link")+ .insertContent({+ type: "text",+ text: text || url,+ marks: [+ {+ type: "link",+ attrs: {+ href: url,+ target: openInNewTab ? "_blank" : "",+ },+ },+ ],+ })+ .setLink({ href: url })+ .run()++ editor.commands.enter()+ },+ [editor]+ )++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <ToolbarButton+ isActive={editor.isActive("link")}+ tooltip="Link"+ aria-label="Insert link"+ disabled={editor.isActive("codeBlock")}+ size={size}+ variant={variant}+ >+ <Link2 className="size-5" />+ </ToolbarButton>+ </PopoverTrigger>+ <PopoverContent className="w-full min-w-80" align="end" side="bottom">+ <LinkEditBlock onSave={onSetLink} defaultText={text} />+ </PopoverContent>+ </Popover>+ )+}++export { LinkEditPopover }diff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-popover-block.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-popover-block.tsxnew file mode 100644index 00000000..ea09b568--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/link/link-popover-block.tsx@@ -0,0 +1,77 @@+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+ onClear: () => void+ onEdit: (e: React.MouseEvent<HTMLButtonElement>) => void+}++export const LinkPopoverBlock: React.FC<LinkPopoverBlockProps> = ({+ url,+ onClear,+ onEdit,+}) => {+ const [copyTitle, setCopyTitle] = React.useState<string>("Copy")++ const handleCopy = React.useCallback(+ (e: React.MouseEvent<HTMLButtonElement>) => {+ e.preventDefault()+ navigator.clipboard+ .writeText(url)+ .then(() => {+ setCopyTitle("Copied!")+ setTimeout(() => setCopyTitle("Copy"), 1000)+ })+ .catch(console.error)+ },+ [url]+ )++ const handleOpenLink = React.useCallback(() => {+ 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"+ >+ Edit link+ </ToolbarButton>+ <Separator orientation="vertical" />+ <ToolbarButton+ tooltip="Open link in a new tab"+ onClick={handleOpenLink}+ >+ <ExternalLink className="size-4" />+ </ToolbarButton>+ <Separator orientation="vertical" />+ <ToolbarButton tooltip="Clear link" onClick={onClear}>+ <Unlink className="size-4" />+ </ToolbarButton>+ <Separator orientation="vertical" />+ <ToolbarButton+ tooltip={copyTitle}+ onClick={handleCopy}+ tooltipOptions={{+ onPointerDownOutside: (e) => {+ if (e.target === e.currentTarget) e.preventDefault()+ },+ }}+ >+ <Copy className="size-4" />+ </ToolbarButton>+ </div>+ </div>+ )+}diff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/measured-container.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/measured-container.tsxnew file mode 100644index 00000000..9c51b9d6--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/measured-container.tsx@@ -0,0 +1,39 @@+import * as React from "react"+import { useContainerSize } from "../hooks/use-container-size"++interface MeasuredContainerProps<T extends React.ElementType> {+ as: T+ name: string+ children?: React.ReactNode+}++export const MeasuredContainer = React.forwardRef(+ <T extends React.ElementType>(+ {+ as: Component,+ name,+ children,+ style = {},+ ...props+ }: MeasuredContainerProps<T> & React.ComponentProps<T>,+ ref: React.Ref<HTMLElement>+ ) => {+ const innerRef = React.useRef<HTMLElement>(null)+ const rect = useContainerSize(innerRef.current)++ React.useImperativeHandle(ref, () => innerRef.current as HTMLElement)++ const customStyle = {+ [`--${name}-width`]: `${rect.width}px`,+ [`--${name}-height`]: `${rect.height}px`,+ }++ return (+ <Component {...props} ref={innerRef} style={{ ...customStyle, ...style }}>+ {children}+ </Component>+ )+ }+)++MeasuredContainer.displayName = "MeasuredContainer"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/section/five.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/section/five.tsxnew file mode 100644index 00000000..73d9553b--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/section/five.tsx@@ -0,0 +1,93 @@+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"+interface InsertElement extends FormatAction {+ value: InsertElementAction+}++const formatActions: InsertElement[] = [+ {+ 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"],+ },+ {+ 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"],+ },+ {+ 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", "-"],+ },+]++interface SectionFiveProps extends VariantProps<typeof toggleVariants> {+ editor: Editor+ activeActions?: InsertElementAction[]+ mainActionCount?: number+}++export const SectionFive: React.FC<SectionFiveProps> = ({+ editor,+ activeActions = formatActions.map((action) => action.value),+ mainActionCount = 0,+ size,+ variant,+}) => {+ return (+ <>+ <LinkEditPopover editor={editor} size={size} variant={variant} />+ <ImageEditDialog editor={editor} size={size} variant={variant} />+ <ToolbarSection+ editor={editor}+ actions={formatActions}+ activeActions={activeActions}+ mainActionCount={mainActionCount}+ dropdownIcon={+ <>+ <Plus className="size-5" />+ <ChevronDown className="size-5" />+ </>+ }+ dropdownTooltip="Insert elements"+ size={size}+ variant={variant}+ />+ </>+ )+}++SectionFive.displayName = "SectionFive"++export default SectionFivediff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/section/four.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/section/four.tsxnew file mode 100644index 00000000..49b5a897--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/section/four.tsx@@ -0,0 +1,81 @@+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"+interface ListItem extends FormatAction {+ value: ListItemAction+}++const formatActions: ListItem[] = [+ {+ value: "orderedList",+ label: "Numbered list",+ icon: (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ height="20px"+ viewBox="0 -960 960 960"+ width="20px"+ fill="currentColor"+ >+ <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"),+ action: (editor) => editor.chain().focus().toggleOrderedList().run(),+ canExecute: (editor) =>+ editor.can().chain().focus().toggleOrderedList().run(),+ shortcuts: ["mod", "shift", "7"],+ },+ {+ value: "bulletList",+ label: "Bullet list",+ icon: <List className="size-5" />,+ isActive: (editor) => editor.isActive("bulletList"),+ action: (editor) => editor.chain().focus().toggleBulletList().run(),+ canExecute: (editor) =>+ editor.can().chain().focus().toggleBulletList().run(),+ shortcuts: ["mod", "shift", "8"],+ },+]++interface SectionFourProps extends VariantProps<typeof toggleVariants> {+ editor: Editor+ activeActions?: ListItemAction[]+ mainActionCount?: number+}++export const SectionFour: React.FC<SectionFourProps> = ({+ editor,+ activeActions = formatActions.map((action) => action.value),+ mainActionCount = 0,+ size,+ variant,+}) => {+ return (+ <ToolbarSection+ editor={editor}+ actions={formatActions}+ activeActions={activeActions}+ mainActionCount={mainActionCount}+ dropdownIcon={+ <>+ <List className="size-5" />+ <ChevronDown className="size-5" />+ </>+ }+ dropdownTooltip="Lists"+ size={size}+ variant={variant}+ />+ )+}++SectionFour.displayName = "SectionFour"++export default SectionFourdiff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/section/one.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/section/one.tsxnew file mode 100644index 00000000..873ee658--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/section/one.tsx@@ -0,0 +1,151 @@+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"++interface TextStyle+ extends Omit<+ FormatAction,+ "value" | "icon" | "action" | "isActive" | "canExecute"+ > {+ element: keyof React.JSX.IntrinsicElements+ level?: Level+ className: string+}++const formatActions: TextStyle[] = [+ {+ label: "Normal Text",+ element: "span",+ className: "grow",+ shortcuts: ["mod", "alt", "0"],+ },+ {+ label: "Heading 1",+ element: "h1",+ level: 1,+ className: "m-0 grow text-3xl font-extrabold",+ shortcuts: ["mod", "alt", "1"],+ },+ {+ label: "Heading 2",+ element: "h2",+ level: 2,+ className: "m-0 grow text-xl font-bold",+ shortcuts: ["mod", "alt", "2"],+ },+ {+ label: "Heading 3",+ element: "h3",+ level: 3,+ className: "m-0 grow text-lg font-semibold",+ shortcuts: ["mod", "alt", "3"],+ },+ {+ label: "Heading 4",+ element: "h4",+ level: 4,+ className: "m-0 grow text-base font-semibold",+ shortcuts: ["mod", "alt", "4"],+ },+ {+ label: "Heading 5",+ element: "h5",+ level: 5,+ className: "m-0 grow text-sm font-normal",+ shortcuts: ["mod", "alt", "5"],+ },+ {+ label: "Heading 6",+ element: "h6",+ level: 6,+ className: "m-0 grow text-sm font-normal",+ shortcuts: ["mod", "alt", "6"],+ },+]++interface SectionOneProps extends VariantProps<typeof toggleVariants> {+ editor: Editor+ activeLevels?: Level[]+}++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)+ ),+ [activeLevels]+ )++ const handleStyleChange = React.useCallback(+ (level?: Level) => {+ if (level) {+ editor.chain().focus().toggleHeading({ level }).run()+ } else {+ editor.chain().focus().setParagraph().run()+ }+ },+ [editor]+ )++ const renderMenuItem = React.useCallback(+ ({ label, element: Element, level, className, shortcuts }: TextStyle) => (+ <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"),+ })}+ aria-label={label}+ >+ <Element className={className}>{label}</Element>+ <ShortcutKey keys={shortcuts} />+ </DropdownMenuItem>+ ),+ [editor, handleStyleChange]+ )++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <ToolbarButton+ isActive={editor.isActive("heading")}+ tooltip="Text styles"+ aria-label="Text styles"+ pressed={editor.isActive("heading")}+ className="w-12"+ disabled={editor.isActive("codeBlock")}+ size={size}+ variant={variant}+ >+ <Type className="size-5" />+ <ChevronDown className="size-5" />+ </ToolbarButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-full">+ {filteredActions.map(renderMenuItem)}+ </DropdownMenuContent>+ </DropdownMenu>+ )+ }+)++SectionOne.displayName = "SectionOne"++export default SectionOnediff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/section/three.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/section/three.tsxnew file mode 100644index 00000000..11eee777--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/section/three.tsx@@ -0,0 +1,216 @@+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+ label: string+ darkLabel?: string+}++interface ColorPalette {+ label: string+ colors: ColorItem[]+ inverse: string+}++const COLORS: ColorPalette[] = [+ {+ 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" },+ ],+ },+ {+ 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" },+ ],+ },+ {+ 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" },+ ],+ },+]++const MemoizedColorButton = React.memo<{+ color: ColorItem+ isSelected: boolean+ inverse: string+ onClick: (value: string) => void+}>(({ color, isSelected, inverse, onClick }) => {+ const isDarkMode = useTheme()+ const label = isDarkMode && color.darkLabel ? color.darkLabel : color.label++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <ToggleGroupItem+ tabIndex={0}+ className="relative size-7 rounded-md p-0"+ value={color.cssVar}+ aria-label={label}+ style={{ backgroundColor: color.cssVar }}+ onClick={(e: React.MouseEvent<HTMLButtonElement>) => {+ e.preventDefault()+ onClick(color.cssVar)+ }}+ >+ {isSelected && (+ <Check+ className="absolute inset-0 m-auto size-6"+ style={{ color: inverse }}+ />+ )}+ </ToggleGroupItem>+ </TooltipTrigger>+ <TooltipContent side="bottom">+ <p>{label}</p>+ </TooltipContent>+ </Tooltip>+ )+})++MemoizedColorButton.displayName = "MemoizedColorButton"++const MemoizedColorPicker = React.memo<{+ palette: ColorPalette+ selectedColor: string+ inverse: string+ onColorChange: (value: string) => void+}>(({ palette, selectedColor, inverse, onColorChange }) => (+ <ToggleGroup+ type="single"+ value={selectedColor}+ onValueChange={(value: string) => {+ if (value) onColorChange(value)+ }}+ className="gap-1.5"+ >+ {palette.colors.map((color, index) => (+ <MemoizedColorButton+ key={index}+ inverse={inverse}+ color={color}+ isSelected={selectedColor === color.cssVar}+ onClick={onColorChange}+ />+ ))}+ </ToggleGroup>+))++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))"+ const [selectedColor, setSelectedColor] = React.useState(color)++ const handleColorChange = React.useCallback(+ (value: string) => {+ setSelectedColor(value)+ editor.chain().setColor(value).run()+ },+ [editor]+ )++ React.useEffect(() => {+ setSelectedColor(color)+ }, [color])++ return (+ <Popover>+ <PopoverTrigger asChild>+ <ToolbarButton+ tooltip="Text color"+ aria-label="Text color"+ className="w-12"+ size={size}+ variant={variant}+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className="size-5"+ style={{ color: selectedColor }}+ >+ <path d="M4 20h16" />+ <path d="m6 16 6-12 6 12" />+ <path d="M8 12h8" />+ </svg>+ <ChevronDown className="size-5" />+ </ToolbarButton>+ </PopoverTrigger>+ <PopoverContent align="start" className="w-full">+ <div className="space-y-1.5">+ {COLORS.map((palette, index) => (+ <MemoizedColorPicker+ key={index}+ palette={palette}+ inverse={palette.inverse}+ selectedColor={selectedColor}+ onColorChange={handleColorChange}+ />+ ))}+ </div>+ </PopoverContent>+ </Popover>+ )+}++SectionThree.displayName = "SectionThree"++export default SectionThreediff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/section/two.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/section/two.tsxnew file mode 100644index 00000000..fead65d3--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/section/two.tsx@@ -0,0 +1,128 @@+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"++interface TextStyle extends FormatAction {+ value: TextStyleAction+}++const formatActions: TextStyle[] = [+ {+ value: "bold",+ label: "Bold",+ icon: <Bold className="size-5" />,+ action: (editor) => editor.chain().focus().toggleBold().run(),+ isActive: (editor) => editor.isActive("bold"),+ canExecute: (editor) =>+ editor.can().chain().focus().toggleBold().run() &&+ !editor.isActive("codeBlock"),+ shortcuts: ["mod", "B"],+ },+ {+ value: "italic",+ label: "Italic",+ icon: <Italic className="size-5" />,+ action: (editor) => editor.chain().focus().toggleItalic().run(),+ isActive: (editor) => editor.isActive("italic"),+ canExecute: (editor) =>+ editor.can().chain().focus().toggleItalic().run() &&+ !editor.isActive("codeBlock"),+ shortcuts: ["mod", "I"],+ },+ {+ value: "underline",+ label: "Underline",+ icon: <Underline className="size-5" />,+ action: (editor) => editor.chain().focus().toggleUnderline().run(),+ isActive: (editor) => editor.isActive("underline"),+ canExecute: (editor) =>+ editor.can().chain().focus().toggleUnderline().run() &&+ !editor.isActive("codeBlock"),+ shortcuts: ["mod", "U"],+ },+ {+ value: "strikethrough",+ label: "Strikethrough",+ icon: <Strikethrough className="size-5" />,+ action: (editor) => editor.chain().focus().toggleStrike().run(),+ isActive: (editor) => editor.isActive("strike"),+ canExecute: (editor) =>+ editor.can().chain().focus().toggleStrike().run() &&+ !editor.isActive("codeBlock"),+ shortcuts: ["mod", "shift", "S"],+ },+ {+ value: "code",+ label: "Code",+ icon: <Code className="size-5" />,+ action: (editor) => editor.chain().focus().toggleCode().run(),+ isActive: (editor) => editor.isActive("code"),+ canExecute: (editor) =>+ editor.can().chain().focus().toggleCode().run() &&+ !editor.isActive("codeBlock"),+ shortcuts: ["mod", "E"],+ },+ {+ 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", "\\"],+ },+]++interface SectionTwoProps extends VariantProps<typeof toggleVariants> {+ editor: Editor+ activeActions?: TextStyleAction[]+ mainActionCount?: number+}++export const SectionTwo: React.FC<SectionTwoProps> = ({+ editor,+ activeActions = formatActions.map((action) => action.value),+ mainActionCount = 2,+ size,+ variant,+}) => {+ return (+ <ToolbarSection+ editor={editor}+ actions={formatActions}+ activeActions={activeActions}+ mainActionCount={mainActionCount}+ dropdownIcon={<MoreHorizontal className="size-5" />}+ dropdownTooltip="More formatting"+ dropdownClassName="w-8"+ size={size}+ variant={variant}+ />+ )+}++SectionTwo.displayName = "SectionTwo"++export default SectionTwodiff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/shortcut-key.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/shortcut-key.tsxnew file mode 100644index 00000000..8adc1024--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/shortcut-key.tsx@@ -0,0 +1,43 @@+import * as React from "react"+import { cn } from "@/lib/utils"+import { getShortcutKey } from "../utils"++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(" + ")++ return (+ <span+ aria-label={ariaLabel}+ className={cn("inline-flex items-center gap-0.5", className)}+ {...props}+ ref={ref}+ >+ {modifiedKeys.map((shortcut) => (+ <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)]",++ className+ )}+ {...props}+ ref={ref}+ >+ {shortcut.symbol}+ </kbd>+ ))}+ </span>+ )+ }+)++ShortcutKey.displayName = "ShortcutKey"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/spinner.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/spinner.tsxnew file mode 100644index 00000000..f985c33c--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/spinner.tsx@@ -0,0 +1,37 @@+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>+ )+ }+)++SpinnerComponent.displayName = "Spinner"++export const Spinner = React.memo(SpinnerComponent)diff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/toolbar-button.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/toolbar-button.tsxnew file mode 100644index 00000000..2f09a64a--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/toolbar-button.tsx@@ -0,0 +1,56 @@+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> {+ isActive?: boolean+ tooltip?: string+ tooltipOptions?: TooltipContentProps+}++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)}+ {...props}+ >+ {children}+ </Toggle>+ )++ if (!tooltip) {+ return toggleButton+ }++ return (+ <Tooltip>+ <TooltipTrigger asChild>{toggleButton}</TooltipTrigger>+ <TooltipContent {...tooltipOptions}>+ <div className="flex flex-col items-center text-center">+ {tooltip}+ </div>+ </TooltipContent>+ </Tooltip>+ )+ }+)++ToolbarButton.displayName = "ToolbarButton"++export default ToolbarButtondiff --git a/flowsint-app/src/renderer/src/components/shared/editor/components/toolbar-section.tsx b/flowsint-app/src/renderer/src/components/shared/editor/components/toolbar-section.tsxnew file mode 100644index 00000000..ed8ca648--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/components/toolbar-section.tsx@@ -0,0 +1,120 @@+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"++interface ToolbarSectionProps extends VariantProps<typeof toggleVariants> {+ editor: Editor+ actions: FormatAction[]+ activeActions?: string[]+ mainActionCount?: number+ dropdownIcon?: React.ReactNode+ dropdownTooltip?: string+ dropdownClassName?: string+}++export const ToolbarSection: React.FC<ToolbarSectionProps> = ({+ editor,+ actions,+ activeActions = actions.map((action) => action.value),+ mainActionCount = 0,+ dropdownIcon,+ dropdownTooltip = "More options",+ dropdownClassName = "w-12",+ size,+ 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)+ )++ return {+ mainActions: sortedActions.slice(0, mainActionCount),+ dropdownActions: sortedActions.slice(mainActionCount),+ }+ }, [actions, activeActions, mainActionCount])++ const renderToolbarButton = React.useCallback(+ (action: FormatAction) => (+ <ToolbarButton+ key={action.label}+ onClick={() => action.action(editor)}+ disabled={!action.canExecute(editor)}+ isActive={action.isActive(editor)}+ tooltip={`${action.label} ${action.shortcuts.map((s) => getShortcutKey(s).symbol).join(" ")}`}+ aria-label={action.label}+ size={size}+ variant={variant}+ >+ {action.icon}+ </ToolbarButton>+ ),+ [editor, size, variant]+ )++ const renderDropdownMenuItem = React.useCallback(+ (action: FormatAction) => (+ <DropdownMenuItem+ 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),+ })}+ aria-label={action.label}+ >+ <span className="grow">{action.label}</span>+ <ShortcutKey keys={action.shortcuts} />+ </DropdownMenuItem>+ ),+ [editor]+ )++ const isDropdownActive = React.useMemo(+ () => dropdownActions.some((action) => action.isActive(editor)),+ [dropdownActions, editor]+ )++ return (+ <>+ {mainActions.map(renderToolbarButton)}+ {dropdownActions.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <ToolbarButton+ isActive={isDropdownActive}+ tooltip={dropdownTooltip}+ aria-label={dropdownTooltip}+ className={cn(dropdownClassName)}+ size={size}+ variant={variant}+ >+ {dropdownIcon || <ChevronDownIcon className="size-5" />}+ </ToolbarButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-full">+ {dropdownActions.map(renderDropdownMenuItem)}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </>+ )+}++export default ToolbarSectiondiff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/code-block-lowlight/code-block-lowlight.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/code-block-lowlight/code-block-lowlight.tsnew file mode 100644index 00000000..36f8e975--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/code-block-lowlight/code-block-lowlight.ts@@ -0,0 +1,17 @@+import { CodeBlockLowlight as TiptapCodeBlockLowlight } from "@tiptap/extension-code-block-lowlight"+import { common, createLowlight } from "lowlight"++export const CodeBlockLowlight = TiptapCodeBlockLowlight.extend({+ addOptions() {+ return {+ ...this.parent?.(),+ lowlight: createLowlight(common),+ defaultLanguage: null,+ HTMLAttributes: {+ class: "block-node",+ },+ }+ },+})++export default CodeBlockLowlightdiff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/code-block-lowlight/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/code-block-lowlight/index.tsnew file mode 100644index 00000000..4d6759ea--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/code-block-lowlight/index.ts@@ -0,0 +1 @@+export * from "./code-block-lowlight"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/color/color.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/color/color.tsnew file mode 100644index 00000000..ecb28430--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/color/color.ts@@ -0,0 +1,20 @@+import { Color as TiptapColor } from "@tiptap/extension-color"+import { Plugin } from "@tiptap/pm/state"++export const Color = TiptapColor.extend({+ addProseMirrorPlugins() {+ return [+ ...(this.parent?.() || []),+ new Plugin({+ props: {+ handleKeyDown: (_, event) => {+ if (event.key === "Enter") {+ this.editor.commands.unsetColor()+ }+ return false+ },+ },+ }),+ ]+ },+})diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/color/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/color/index.tsnew file mode 100644index 00000000..eb963340--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/color/index.ts@@ -0,0 +1 @@+export * from "./color"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/file-handler/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/file-handler/index.tsnew file mode 100644index 00000000..dcb87abd--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/file-handler/index.ts@@ -0,0 +1,116 @@+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+ editor: Editor+ onPaste?: (editor: Editor, files: File[], pasteContent?: string) => void+ onDrop?: (editor: Editor, files: File[], pos: number) => void+ onValidationError?: (errors: FileError[]) => void+} & FileValidationOptions++const FileHandlePlugin = (options: FileHandlePluginOptions) => {+ const {+ key,+ editor,+ onPaste,+ onDrop,+ onValidationError,+ allowedMimeTypes,+ maxFileSize,+ } = options++ return new Plugin({+ key: key || new PluginKey("fileHandler"),++ props: {+ handleDrop(view, event) {+ event.preventDefault()+ event.stopPropagation()++ const { dataTransfer } = event++ if (!dataTransfer?.files.length) {+ return+ }++ const pos = view.posAtCoords({+ left: event.clientX,+ top: event.clientY,+ })++ const [validFiles, errors] = filterFiles(+ Array.from(dataTransfer.files),+ {+ allowedMimeTypes,+ maxFileSize,+ allowBase64: options.allowBase64,+ }+ )++ if (errors.length > 0 && onValidationError) {+ onValidationError(errors)+ }++ if (validFiles.length > 0 && onDrop) {+ onDrop(editor, validFiles, pos?.pos ?? 0)+ }+ },++ handlePaste(_, event) {+ event.preventDefault()+ event.stopPropagation()++ const { clipboardData } = event++ if (!clipboardData?.files.length) {+ return+ }++ 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)+ }++ if (validFiles.length > 0 && onPaste) {+ onPaste(editor, validFiles, html)+ }+ },+ },+ })+}++export const FileHandler = Extension.create<+ Omit<FileHandlePluginOptions, "key" | "editor">+>({+ name: "fileHandler",++ addOptions() {+ return {+ allowBase64: false,+ allowedMimeTypes: [],+ maxFileSize: 0,+ }+ },++ addProseMirrorPlugins() {+ return [+ FileHandlePlugin({+ key: new PluginKey(this.name),+ editor: this.editor,+ ...this.options,+ }),+ ]+ },+})diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/horizontal-rule/horizontal-rule.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/horizontal-rule/horizontal-rule.tsnew file mode 100644index 00000000..4b6d5334--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/horizontal-rule/horizontal-rule.ts@@ -0,0 +1,18 @@+/*+ * 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"++export const HorizontalRule = TiptapHorizontalRule.extend({+ addKeyboardShortcuts() {+ return {+ "Mod-Alt--": () =>+ this.editor.commands.insertContent({+ type: this.name,+ }),+ }+ },+})++export default HorizontalRulediff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/horizontal-rule/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/horizontal-rule/index.tsnew file mode 100644index 00000000..7cc78542--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/horizontal-rule/index.ts@@ -0,0 +1 @@+export * from "./horizontal-rule"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-actions.tsx b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-actions.tsxnew file mode 100644index 00000000..b51ee87c--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-actions.tsx@@ -0,0 +1,173 @@+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"++interface ImageActionsProps {+ shouldMerge?: boolean+ isLink?: boolean+ onView?: () => void+ onDownload?: () => void+ onCopy?: () => void+ onCopyLink?: () => void+}++interface ActionButtonProps+ extends React.ButtonHTMLAttributes<HTMLButtonElement> {+ icon: React.ReactNode+ tooltip: string+}++export const ActionWrapper = React.memo(+ React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(+ ({ children, className, ...props }, ref) => (+ <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)]",+ className+ )}+ {...props}+ >+ {children}+ </div>+ )+ )+)++ActionWrapper.displayName = "ActionWrapper"++export const ActionButton = React.memo(+ React.forwardRef<HTMLButtonElement, ActionButtonProps>(+ ({ icon, tooltip, className, ...props }, ref) => (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ 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",+ className+ )}+ {...props}+ >+ {icon}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="bottom">{tooltip}</TooltipContent>+ </Tooltip>+ )+ )+)++ActionButton.displayName = "ActionButton"++type ActionKey = "onView" | "onDownload" | "onCopy" | "onCopyLink"++const ActionItems: Array<{+ key: ActionKey+ icon: React.ReactNode+ tooltip: string+ isLink?: boolean+}> = [+ {+ key: "onView",+ icon: <Maximize className="size-4" />,+ tooltip: "View image",+ },+ {+ key: "onDownload",+ icon: <Download className="size-4" />,+ tooltip: "Download image",+ },+ {+ key: "onCopy",+ icon: <Copy className="size-4" />,+ tooltip: "Copy image to clipboard",+ },+ {+ key: "onCopyLink",+ icon: <Link2 className="size-4" />,+ tooltip: "Copy image link",+ isLink: true,+ },+]++export const ImageActions: React.FC<ImageActionsProps> = React.memo(+ ({ shouldMerge = false, isLink = false, ...actions }) => {+ const [isOpen, setIsOpen] = React.useState(false)++ const handleAction = React.useCallback(+ (e: React.MouseEvent, action: (() => void) | undefined) => {+ e.preventDefault()+ e.stopPropagation()+ action?.()+ },+ []+ )++ const filteredActions = React.useMemo(+ () => ActionItems.filter((item) => isLink || !item.isLink),+ [isLink]+ )++ return (+ <ActionWrapper className={cn({ "opacity-100": isOpen })}>+ {shouldMerge ? (+ <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>+ <DropdownMenuTrigger asChild>+ <ActionButton+ icon={<MoreHorizontal className="size-4" />}+ tooltip="Open menu"+ onClick={(e) => e.preventDefault()}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-56" align="end">+ {filteredActions.map(({ key, icon, tooltip }) => (+ <DropdownMenuItem+ key={key}+ onClick={(e) => handleAction(e, actions[key])}+ >+ <div className="flex flex-row items-center gap-2">+ {icon}+ <span>{tooltip}</span>+ </div>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ filteredActions.map(({ key, icon, tooltip }) => (+ <ActionButton+ key={key}+ icon={icon}+ tooltip={tooltip}+ onClick={(e) => handleAction(e, actions[key])}+ />+ ))+ )}+ </ActionWrapper>+ )+ }+)++ImageActions.displayName = "ImageActions"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-overlay.tsx b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-overlay.tsxnew file mode 100644index 00000000..666402a3--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-overlay.tsx@@ -0,0 +1,18 @@+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"+ )}+ >+ <Spinner className="size-7" />+ </div>+ )+})++ImageOverlay.displayName = "ImageOverlay"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-view-block.tsx b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-view-block.tsxnew file mode 100644index 00000000..5befd665--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/image-view-block.tsx@@ -0,0 +1,338 @@+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+const MIN_WIDTH = 120++interface ImageState {+ src: string+ isServerUploading: boolean+ imageLoaded: boolean+ isZoomed: boolean+ error: boolean+ naturalSize: ElementDimensions+}++const normalizeUploadResponse = (res: UploadReturnType) => ({+ src: typeof res === "string" ? res : res.src,+ id: typeof res === "string" ? randomId() : res.id,+})++export const ImageViewBlock: React.FC<NodeViewProps> = ({+ editor,+ node,+ selected,+ updateAttributes,+}) => {+ const {+ src: initialSrc,+ width: initialWidth,+ height: initialHeight,+ fileName,+ } = node.attrs+ const uploadAttemptedRef = React.useRef(false)++ const initSrc = React.useMemo(() => {+ if (typeof initialSrc === "string") {+ return initialSrc+ }+ return initialSrc.src+ }, [initialSrc])++ const [imageState, setImageState] = React.useState<ImageState>({+ src: initSrc,+ isServerUploading: false,+ imageLoaded: false,+ isZoomed: false,+ error: false,+ naturalSize: { width: initialWidth, height: initialHeight },+ })++ const containerRef = React.useRef<HTMLDivElement>(null)+ const [activeResizeHandle, setActiveResizeHandle] = React.useState<+ "left" | "right" | null+ >(null)++ const onDimensionsChange = React.useCallback(+ ({ width, height }: ElementDimensions) => {+ updateAttributes({ width, height })+ },+ [updateAttributes]+ )++ const aspectRatio =+ imageState.naturalSize.width / imageState.naturalSize.height+ const maxWidth = MAX_HEIGHT * aspectRatio+ const containerMaxWidth = containerRef.current+ ? 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 shouldMerge = React.useMemo(() => currentWidth <= 180, [currentWidth])++ const handleImageLoad = React.useCallback(+ (ev: React.SyntheticEvent<HTMLImageElement>) => {+ const img = ev.target as HTMLImageElement+ const newNaturalSize = {+ width: img.naturalWidth,+ height: img.naturalHeight,+ }+ setImageState((prev) => ({+ ...prev,+ naturalSize: newNaturalSize,+ imageLoaded: true,+ }))+ updateAttributes({+ width: img.width || newNaturalSize.width,+ height: img.height || newNaturalSize.height,+ alt: img.alt,+ title: img.title,+ })++ if (!initialWidth) {+ updateDimensions((state) => ({ ...state, width: newNaturalSize.width }))+ }+ },+ [initialWidth, updateAttributes, updateDimensions]+ )++ const handleImageError = React.useCallback(() => {+ setImageState((prev) => ({ ...prev, error: true, imageLoaded: true }))+ }, [])++ const handleResizeStart = React.useCallback(+ (direction: "left" | "right") =>+ (event: React.PointerEvent<HTMLDivElement>) => {+ setActiveResizeHandle(direction)+ initiateResize(direction)(event)+ },+ [initiateResize]+ )++ const handleResizeEnd = React.useCallback(() => {+ setActiveResizeHandle(null)+ }, [])++ React.useEffect(() => {+ if (!isResizing) {+ handleResizeEnd()+ }+ }, [isResizing, handleResizeEnd])++ React.useEffect(() => {+ const handleImage = async () => {+ if (!initSrc.startsWith("blob:") || uploadAttemptedRef.current) {+ return+ }++ uploadAttemptedRef.current = true+ const imageExtension = editor.options.extensions.find(+ (ext) => ext.name === "image"+ )+ const { uploadFn } = imageExtension?.options ?? {}++ if (!uploadFn) {+ try {+ const base64 = await blobUrlToBase64(initSrc)+ setImageState((prev) => ({ ...prev, src: base64 }))+ updateAttributes({ src: base64 })+ } catch {+ setImageState((prev) => ({ ...prev, error: true }))+ }+ return+ }++ try {+ setImageState((prev) => ({ ...prev, isServerUploading: true }))+ const response = await fetch(initSrc)+ const blob = await response.blob()+ const file = new File([blob], fileName, { type: blob.type })++ const url = await uploadFn(file, editor)+ const normalizedData = normalizeUploadResponse(url)++ setImageState((prev) => ({+ ...prev,+ ...normalizedData,+ isServerUploading: false,+ }))++ updateAttributes(normalizedData)+ } catch (error) {+ setImageState((prev) => ({+ ...prev,+ error: true,+ isServerUploading: false,+ }))+ }+ }++ handleImage()+ }, [editor, fileName, initSrc, updateAttributes])++ return (+ <NodeViewWrapper+ ref={containerRef}+ data-drag-handle+ className="relative text-center leading-none"+ >+ <div+ className="group/node-image relative mx-auto rounded-md object-contain"+ style={{+ maxWidth: `min(${maxWidth}px, 100%)`,+ width: currentWidth,+ maxHeight: MAX_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,+ }+ )}+ >+ <div className="h-full contain-paint">+ <div className="relative h-full">+ {imageState.isServerUploading && !imageState.error && (+ <div className="absolute inset-0 flex items-center justify-center">+ <Spinner className="size-7" />+ </div>+ )}++ {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>+ </div>+ )}++ <ControlledZoom+ isZoomed={imageState.isZoomed}+ onZoomChange={() =>+ setImageState((prev) => ({ ...prev, isZoomed: false }))+ }+ >+ <img+ 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,+ }}+ width={currentWidth}+ height={currentHeight}+ src={imageState.src}+ onError={handleImageError}+ onLoad={handleImageLoad}+ alt={node.attrs.alt || ""}+ title={node.attrs.title || ""}+ id={node.attrs.id}+ />+ </ControlledZoom>+ </div>++ {imageState.isServerUploading && <ImageOverlay />}++ {editor.isEditable &&+ imageState.imageLoaded &&+ !imageState.error &&+ !imageState.isServerUploading && (+ <>+ <ResizeHandle+ onPointerDown={handleResizeStart("left")}+ className={cn("left-1", {+ hidden: isResizing && activeResizeHandle === "right",+ })}+ isResizing={isResizing && activeResizeHandle === "left"}+ />+ <ResizeHandle+ onPointerDown={handleResizeStart("right")}+ className={cn("right-1", {+ hidden: isResizing && activeResizeHandle === "left",+ })}+ isResizing={isResizing && activeResizeHandle === "right"}+ />+ </>+ )}+ </div>++ {imageState.error && (+ <ActionWrapper>+ <ActionButton+ icon={<Trash2 className="size-4" />}+ tooltip="Remove image"+ onClick={onRemoveImg}+ />+ </ActionWrapper>+ )}++ {!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/shared/editor/extensions/image/components/resize-handle.tsx b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/resize-handle.tsxnew file mode 100644index 00000000..312a8d7e--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/components/resize-handle.tsx@@ -0,0 +1,29 @@+import * as React from "react"+import { cn } from "@/lib/utils"++interface ResizeProps extends React.HTMLAttributes<HTMLDivElement> {+ isResizing?: boolean+}++export const ResizeHandle = React.forwardRef<HTMLDivElement, ResizeProps>(+ ({ className, isResizing = false, ...props }, ref) => {+ 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)]",+ {+ "opacity-80": isResizing,+ "group-hover/node-image:opacity-80": !isResizing,+ },+ "before:absolute before:inset-y-0 before:-left-1 before:-right-1",+ className+ )}+ ref={ref}+ {...props}+ ></div>+ )+ }+)++ResizeHandle.displayName = "ResizeHandle"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/hooks/use-drag-resize.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/hooks/use-drag-resize.tsnew file mode 100644index 00000000..5575ac2d--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/hooks/use-drag-resize.ts@@ -0,0 +1,171 @@+import { useState, useCallback, useEffect } from "react"++type ResizeDirection = "left" | "right"+export type ElementDimensions = { width: number; height: number }++type HookParams = {+ initialWidth?: number+ initialHeight?: number+ contentWidth?: number+ contentHeight?: number+ gridInterval: number+ minWidth: number+ minHeight: number+ maxWidth: number+ onDimensionsChange?: (dimensions: ElementDimensions) => void+}++export function useDragResize({+ initialWidth,+ initialHeight,+ contentWidth,+ contentHeight,+ gridInterval,+ minWidth,+ minHeight,+ maxWidth,+ onDimensionsChange,+}: HookParams) {+ const [dimensions, updateDimensions] = useState<ElementDimensions>({+ width: Math.max(initialWidth ?? minWidth, minWidth),+ 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 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)+ )+ },+ [gridInterval, contentWidth, minWidth]+ )++ const handlePointerMove = useCallback(+ (event: PointerEvent) => {+ event.preventDefault()+ const movementDelta =+ (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 finalWidth = widthConstraint(alignedWidth, boundaryWidth)+ const aspectRatio =+ contentHeight && contentWidth ? contentHeight / contentWidth : 1++ updateDimensions({+ width: Math.max(finalWidth, minWidth),+ height: Math.max(+ contentWidth+ ? finalWidth * aspectRatio+ : (contentHeight ?? minHeight),+ minHeight+ ),+ })+ },+ [+ widthConstraint,+ resizeDirection,+ boundaryWidth,+ resizeOrigin,+ gridInterval,+ contentHeight,+ contentWidth,+ initialDimensions.width,+ minWidth,+ minHeight,+ ]+ )++ const handlePointerUp = useCallback(+ (event: PointerEvent) => {+ event.preventDefault()+ event.stopPropagation()++ setResizeOrigin(0)+ setResizeDirection(undefined)+ onDimensionsChange?.(dimensions)+ },+ [onDimensionsChange, dimensions]+ )++ const handleKeydown = useCallback(+ (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault()+ event.stopPropagation()+ updateDimensions({+ width: Math.max(initialDimensions.width, minWidth),+ height: Math.max(initialDimensions.height, minHeight),+ })+ setResizeDirection(undefined)+ }+ },+ [initialDimensions, minWidth, minHeight]+ )++ const initiateResize = useCallback(+ (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,+ ]+ )++ useEffect(() => {+ if (resizeDirection) {+ 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)+ }+ }+ }, [resizeDirection, handleKeydown, handlePointerMove, handlePointerUp])++ return {+ initiateResize,+ isResizing: !!resizeDirection,+ updateDimensions,+ currentWidth: Math.max(dimensions.width, minWidth),+ currentHeight: Math.max(dimensions.height, minHeight),+ }+}diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/hooks/use-image-actions.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/hooks/use-image-actions.tsnew file mode 100644index 00000000..b8e1c51f--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/hooks/use-image-actions.ts@@ -0,0 +1,61 @@+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+ node: Node+ src: string+ onViewClick: (value: boolean) => void+}++export type ImageActionHandlers = {+ onView?: () => void+ onDownload?: () => void+ onCopy?: () => void+ onCopyLink?: () => void+ onRemoveImg?: () => void+}++export const useImageActions = ({+ editor,+ node,+ src,+ onViewClick,+}: UseImageActionsProps) => {+ const isLink = React.useMemo(() => isUrl(src), [src])++ const onView = React.useCallback(() => {+ onViewClick(true)+ }, [onViewClick])++ const onDownload = React.useCallback(() => {+ editor.commands.downloadImage({ src: node.attrs.src, alt: node.attrs.alt })+ }, [editor.commands, node.attrs.alt, node.attrs.src])++ const onCopy = React.useCallback(() => {+ editor.commands.copyImage({ src: node.attrs.src })+ }, [editor.commands, node.attrs.src])++ const onCopyLink = React.useCallback(() => {+ editor.commands.copyLink({ src: node.attrs.src })+ }, [editor.commands, node.attrs.src])++ const onRemoveImg = React.useCallback(() => {+ editor.commands.command(({ tr, dispatch }) => {+ const { selection } = tr+ const nodeAtSelection = tr.doc.nodeAt(selection.from)++ if (nodeAtSelection && nodeAtSelection.type.name === "image") {+ if (dispatch) {+ tr.deleteSelection()+ return true+ }+ }+ return false+ })+ }, [editor.commands])++ return { isLink, onView, onDownload, onCopy, onCopyLink, onRemoveImg }+}diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/image.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/image.tsnew file mode 100644index 00000000..6347ac10--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/image.ts@@ -0,0 +1,351 @@+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+ alt?: string+}++interface ImageActionProps extends DownloadImageCommandProps {+ action: ImageAction+}++export type UploadReturnType =+ | string+ | {+ id: string | number+ src: string+ }++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>+ onValidationError?: (errors: FileError[]) => void+ onToggle?: (editor: Editor, files: File[], pos: number) => void+}++declare module "@tiptap/react" {+ interface Commands<ReturnType> {+ setImages: {+ setImages: (+ attrs: { src: string | File; alt?: string; title?: string }[]+ ) => ReturnType+ }+ downloadImage: {+ downloadImage: (attrs: DownloadImageCommandProps) => ReturnType+ }+ copyImage: {+ copyImage: (attrs: DownloadImageCommandProps) => ReturnType+ }+ copyLink: {+ copyLink: (attrs: DownloadImageCommandProps) => ReturnType+ }+ toggleImage: {+ toggleImage: () => ReturnType+ }+ }+}++const handleError = (+ error: unknown,+ props: ImageActionProps,+ errorHandler?: (error: Error, props: ImageActionProps) => void+): void => {+ 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 byteCharacters = atob(base64Data)+ const byteArray = new Uint8Array(byteCharacters.length)+ for (let i = 0; i < byteCharacters.length; i++) {+ byteArray[i] = byteCharacters.charCodeAt(i)+ }+ const blob = new Blob([byteArray], { type: mimeType })+ return { blob, extension }+}++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")+ 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 saveImage = async (+ blob: Blob,+ name: string,+ extension: string+): Promise<void> => {+ const imageURL = URL.createObjectURL(blob)+ const link = document.createElement("a")+ link.href = imageURL+ link.download = `${name}.${extension}`+ document.body.appendChild(link)+ link.click()+ document.body.removeChild(link)+ URL.revokeObjectURL(imageURL)+}++const downloadImage = async (+ props: ImageActionProps,+ options: CustomImageOptions+): Promise<void> => {+ const { src, alt } = props+ const potentialName = alt || "image"++ try {+ const { blob, extension } = await fetchImageBlob(src)+ await saveImage(blob, potentialName, extension)+ options.onActionSuccess?.({ ...props, action: "download" })+ } catch (error) {+ handleError(error, { ...props, action: "download" }, options.onActionError)+ }+}++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" })+ } catch (error) {+ handleError(error, { ...props, action: "copyImage" }, options.onActionError)+ }+}++const copyLink = async (+ props: ImageActionProps,+ options: CustomImageOptions+): Promise<void> => {+ const { src } = props+ try {+ await navigator.clipboard.writeText(src)+ options.onActionSuccess?.({ ...props, action: "copyLink" })+ } catch (error) {+ handleError(error, { ...props, action: "copyLink" }, options.onActionError)+ }+}++export const Image = TiptapImage.extend<CustomImageOptions>({+ atom: true,++ addOptions() {+ return {+ ...this.parent?.(),+ allowedMimeTypes: [],+ maxFileSize: 0,+ uploadFn: undefined,+ onToggle: undefined,+ downloadImage: undefined,+ copyImage: undefined,+ copyLink: undefined,+ }+ },++ addAttributes() {+ return {+ src: {+ default: null,+ },+ alt: {+ default: null,+ },+ title: {+ default: null,+ },+ id: {+ default: null,+ },+ width: {+ default: null,+ },+ height: {+ default: null,+ },+ fileName: {+ default: null,+ },+ }+ },++ addCommands() {+ return {+ setImages:+ (attrs) =>+ ({ commands }) => {+ const [validImages, errors] = filterFiles(attrs, {+ allowedMimeTypes: this.options.allowedMimeTypes,+ maxFileSize: this.options.maxFileSize,+ allowBase64: this.options.allowBase64,+ })++ if (errors.length > 0 && this.options.onValidationError) {+ this.options.onValidationError(errors)+ }++ if (validImages.length > 0) {+ return commands.insertContent(+ validImages.map((image) => {+ if (image.src instanceof File) {+ const blobUrl = URL.createObjectURL(image.src)+ const id = randomId()++ return {+ type: this.type.name,+ attrs: {+ id,+ src: blobUrl,+ alt: image.alt,+ title: image.title,+ fileName: image.src.name,+ },+ }+ } else {+ return {+ type: this.type.name,+ attrs: {+ id: randomId(),+ src: image.src,+ alt: image.alt,+ title: image.title,+ fileName: null,+ },+ }+ }+ })+ )+ }++ return false+ },++ downloadImage: (attrs) => () => {+ const downloadFunc = this.options.downloadImage || downloadImage+ void downloadFunc({ ...attrs, action: "download" }, this.options)+ return true+ },++ copyImage: (attrs) => () => {+ const copyImageFunc = this.options.copyImage || copyImage+ void copyImageFunc({ ...attrs, action: "copyImage" }, this.options)+ return true+ },++ copyLink: (attrs) => () => {+ const copyLinkFunc = this.options.copyLink || copyLink+ 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(",")+ input.onchange = () => {+ const files = input.files+ if (!files) return++ const [validImages, errors] = filterFiles(Array.from(files), {+ allowedMimeTypes: this.options.allowedMimeTypes,+ maxFileSize: this.options.maxFileSize,+ allowBase64: this.options.allowBase64,+ })++ if (errors.length > 0 && this.options.onValidationError) {+ this.options.onValidationError(errors)+ return false+ }++ if (validImages.length === 0) return false++ if (this.options.onToggle) {+ this.options.onToggle(+ editor,+ validImages,+ editor.state.selection.from+ )+ }++ return false+ }++ input.click()+ return true+ },+ }+ },++ onTransaction({ transaction }) {+ transaction.steps.forEach((step) => {+ if (step instanceof ReplaceStep && step.slice.size === 0) {+ const deletedPages = transaction.before.content.cut(step.from, step.to)++ deletedPages.forEach((node) => {+ if (node.type.name === "image") {+ const attrs = node.attrs++ if (attrs.src.startsWith("blob:")) {+ URL.revokeObjectURL(attrs.src)+ }++ this.options.onImageRemoved?.(attrs)+ }+ })+ }+ })+ },++ addNodeView() {+ return ReactNodeViewRenderer(ImageViewBlock, {+ className: "block-node",+ })+ },+})diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/index.tsnew file mode 100644index 00000000..61769c6d--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/image/index.ts@@ -0,0 +1 @@+export * from "./image"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/index.tsnew file mode 100644index 00000000..0cbab761--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/index.ts@@ -0,0 +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"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/link/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/link/index.tsnew file mode 100644index 00000000..6ada303c--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/link/index.ts@@ -0,0 +1 @@+export * from "./link"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/link/link.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/link/link.tsnew file mode 100644index 00000000..82fd2646--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/link/link.ts@@ -0,0 +1,97 @@+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({+ /*+ * Determines whether typing next to a link automatically becomes part of the link.+ * In this case, we dont want any characters to be included as part of the link.+ */+ inclusive: false,++ /*+ * Match all <a> elements that have an href attribute, except for:+ * - <a> elements with a data-type attribute set to button+ * - <a> elements with an href attribute that contains 'javascript:'+ */+ parseHTML() {+ return [+ {+ tag: 'a[href]:not([data-type="button"]):not([href *= "javascript:" i])',+ },+ ]+ },++ renderHTML({ HTMLAttributes }) {+ return [+ "a",+ mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),+ 0,+ ]+ },++ addOptions() {+ return {+ ...this.parent?.(),+ openOnClick: false,+ HTMLAttributes: {+ class: "link",+ },+ }+ },++ addProseMirrorPlugins() {+ const { editor } = this++ return [+ ...(this.parent?.() || []),+ new Plugin({+ props: {+ handleKeyDown: (_: EditorView, event: KeyboardEvent) => {+ const { selection } = editor.state++ /*+ * 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) {+ editor.commands.focus(selection.to, { scrollIntoView: false })+ }++ return false+ },+ handleClick(view, pos) {+ /*+ * Marks the entire link when the user clicks on it.+ */++ const { schema, doc, tr } = view.state+ const range = getMarkRange(doc.resolve(pos), schema.marks.link)++ if (!range) {+ return+ }++ const { from, to } = range+ const start = Math.min(from, to)+ const end = Math.max(from, to)++ if (pos < start || pos > end) {+ return+ }++ const $start = doc.resolve(start)+ const $end = doc.resolve(end)+ const transaction = tr.setSelection(new TextSelection($start, $end))++ view.dispatch(transaction)+ },+ },+ }),+ ]+ },+})++export default Linkdiff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/reset-marks-on-enter/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/reset-marks-on-enter/index.tsnew file mode 100644index 00000000..4c06c8d8--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/reset-marks-on-enter/index.ts@@ -0,0 +1 @@+export * from "./reset-marks-on-enter"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/reset-marks-on-enter/reset-marks-on-enter.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/reset-marks-on-enter/reset-marks-on-enter.tsnew file mode 100644index 00000000..7daee524--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/reset-marks-on-enter/reset-marks-on-enter.ts@@ -0,0 +1,25 @@+import { Extension } from "@tiptap/react"++export const ResetMarksOnEnter = Extension.create({+ name: "resetMarksOnEnter",++ addKeyboardShortcuts() {+ return {+ Enter: ({ editor }) => {+ if (+ editor.isActive("bold") ||+ editor.isActive("italic") ||+ editor.isActive("strike") ||+ editor.isActive("underline") ||+ editor.isActive("code")+ ) {+ editor.commands.splitBlock({ keepMarks: false })++ return true+ }++ return false+ },+ }+ },+})diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/selection/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/selection/index.tsnew file mode 100644index 00000000..c8f61024--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/selection/index.ts@@ -0,0 +1 @@+export * from "./selection"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/selection/selection.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/selection/selection.tsnew file mode 100644index 00000000..872882c7--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/selection/selection.ts@@ -0,0 +1,40 @@+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",++ addProseMirrorPlugins() {+ const { editor } = this++ return [+ new Plugin({+ key: new PluginKey("selection"),+ props: {+ decorations(state) {+ if (state.selection.empty) {+ return null+ }++ if (editor.isFocused === true) {+ return null+ }++ if (!editor.isEditable) {+ return null+ }++ return DecorationSet.create(state.doc, [+ Decoration.inline(state.selection.from, state.selection.to, {+ class: "selection",+ }),+ ])+ },+ },+ }),+ ]+ },+})++export default Selectiondiff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/unset-all-marks/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/unset-all-marks/index.tsnew file mode 100644index 00000000..4abdbe86--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/unset-all-marks/index.ts@@ -0,0 +1 @@+export * from "./unset-all-marks"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/extensions/unset-all-marks/unset-all-marks.ts b/flowsint-app/src/renderer/src/components/shared/editor/extensions/unset-all-marks/unset-all-marks.tsnew file mode 100644index 00000000..10dcbb23--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/extensions/unset-all-marks/unset-all-marks.ts@@ -0,0 +1,9 @@+import { Extension } from "@tiptap/react"++export const UnsetAllMarks = Extension.create({+ addKeyboardShortcuts() {+ return {+ "Mod-\\": () => this.editor.commands.unsetAllMarks(),+ }+ },+})diff --git a/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-container-size.ts b/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-container-size.tsnew file mode 100644index 00000000..8b50fa5a--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-container-size.ts@@ -0,0 +1,55 @@+import { useState, useEffect, useCallback } from "react"++const DEFAULT_RECT: DOMRect = {+ top: 0,+ left: 0,+ bottom: 0,+ right: 0,+ x: 0,+ y: 0,+ width: 0,+ height: 0,+ toJSON: () => "{}",+}++export function useContainerSize(element: HTMLElement | null): DOMRect {+ const [size, setSize] = useState<DOMRect>(+ () => element?.getBoundingClientRect() ?? DEFAULT_RECT+ )++ const handleResize = useCallback(() => {+ if (!element) return++ const newRect = element.getBoundingClientRect()++ setSize((prevRect) => {+ if (+ Math.round(prevRect.width) === Math.round(newRect.width) &&+ Math.round(prevRect.height) === Math.round(newRect.height) &&+ Math.round(prevRect.x) === Math.round(newRect.x) &&+ Math.round(prevRect.y) === Math.round(newRect.y)+ ) {+ return prevRect+ }+ return newRect+ })+ }, [element])++ useEffect(() => {+ if (!element) return++ const resizeObserver = new ResizeObserver(handleResize)+ resizeObserver.observe(element)++ window.addEventListener("click", handleResize)+ window.addEventListener("resize", handleResize)++ return () => {+ resizeObserver.disconnect()+ window.removeEventListener("click", handleResize)+ window.removeEventListener("resize", handleResize)+ }+ }, [element, handleResize])++ return size+}diff --git a/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-minimal-tiptap.ts b/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-minimal-tiptap.tsnew file mode 100644index 00000000..1f003ad3--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-minimal-tiptap.ts@@ -0,0 +1,226 @@+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,+ HorizontalRule,+ CodeBlockLowlight,+ Selection,+ 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"++export interface UseMinimalTiptapEditorProps extends UseEditorOptions {+ value?: Content+ output?: "html" | "json" | "text"+ placeholder?: string+ editorClassName?: string+ throttleDelay?: number+ onUpdate?: (content: Content) => void+ onBlur?: (content: Content) => void+ uploader?: (file: File) => Promise<string>+}++async function fakeuploader(file: File): Promise<string> {+ // NOTE: This is a fake upload function. Replace this with your own upload logic.+ // This function should return the uploaded image URL.++ // wait 3s to simulate upload+ await new Promise((resolve) => setTimeout(resolve, 3000))++ const src = await fileToBase64(file)++ return src+}++const createExtensions = ({+ placeholder,+ uploader,+}: {+ placeholder: string+ uploader?: (file: File) => Promise<string>+}) => [+ 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.configure({+ allowedMimeTypes: ["image/*"],+ maxFileSize: 5 * 1024 * 1024,+ allowBase64: true,+ uploadFn: async (file) => {+ return uploader ? await uploader(file) : await fakeuploader(file)+ },+ onToggle(editor, files, pos) {+ editor.commands.insertContentAt(+ pos,+ files.map((image) => {+ const blobUrl = URL.createObjectURL(image)+ const id = randomId()++ return {+ type: "image",+ attrs: {+ id,+ src: blobUrl,+ alt: image.name,+ title: image.name,+ fileName: image.name,+ },+ }+ })+ )+ },+ onImageRemoved({ id, src }) {+ console.log("Image removed", { id, src })+ },+ onValidationError(errors) {+ errors.forEach((error) => {+ toast.error("Image validation error", {+ position: "bottom-right",+ description: error.reason,+ })+ })+ },+ onActionSuccess({ action }) {+ const mapping = {+ copyImage: "Copy Image",+ copyLink: "Copy Link",+ download: "Download",+ }+ toast.success(mapping[action], {+ position: "bottom-right",+ description: "Image action success",+ })+ },+ onActionError(error, { action }) {+ const mapping = {+ copyImage: "Copy Image",+ copyLink: "Copy Link",+ download: "Download",+ }+ toast.error(`Failed to ${mapping[action]}`, {+ position: "bottom-right",+ description: error.message,+ })+ },+ }),+ FileHandler.configure({+ allowBase64: true,+ 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 },+ })+ })+ },+ onPaste: (editor, files) => {+ files.forEach(async (file) => {+ const src = await fileToBase64(file)+ editor.commands.insertContent({+ type: "image",+ attrs: { src },+ })+ })+ },+ onValidationError: (errors) => {+ errors.forEach((error) => {+ toast.error("Image validation error", {+ position: "bottom-right",+ description: error.reason,+ })+ })+ },+ }),+ Color,+ TextStyle,+ Selection,+ Typography,+ UnsetAllMarks,+ HorizontalRule,+ ResetMarksOnEnter,+ CodeBlockLowlight,+ Placeholder.configure({ placeholder: () => placeholder }),+]++export const useMinimalTiptapEditor = ({+ value,+ output = "json",+ placeholder = "",+ editorClassName,+ throttleDelay = 0,+ onUpdate,+ onBlur,+ uploader,+ ...props+}: UseMinimalTiptapEditorProps) => {+ const throttledSetValue = useThrottle(+ (value: Content) => onUpdate?.(value),+ throttleDelay+ )++ const handleUpdate = React.useCallback(+ (editor: Editor) => throttledSetValue(getOutput(editor, output)),+ [output, throttledSetValue]+ )++ const handleCreate = React.useCallback(+ (editor: Editor) => {+ if (value && editor.isEmpty) {+ editor.commands.setContent(value)+ }+ },+ [value]+ )++ const handleBlur = React.useCallback(+ (editor: Editor) => onBlur?.(getOutput(editor, output)),+ [output, onBlur]+ )++ const editor = useEditor({+ extensions: createExtensions({ placeholder, uploader }),+ editorProps: {+ attributes: {+ 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,+ })++ return editor+}++export default useMinimalTiptapEditordiff --git a/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-throttle.ts b/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-throttle.tsnew file mode 100644index 00000000..332e3f1c--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/hooks/use-throttle.ts@@ -0,0 +1,34 @@+import { useRef, useCallback } from "react"++export function useThrottle<T extends (...args: any[]) => void>(+ callback: T,+ delay: number+): (...args: Parameters<T>) => void {+ const lastRan = useRef(Date.now())+ const timeoutRef = useRef<NodeJS.Timeout | null>(null)++ return useCallback(+ (...args: Parameters<T>) => {+ const handler = () => {+ if (Date.now() - lastRan.current >= delay) {+ callback(...args)+ lastRan.current = Date.now()+ } else {+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current)+ }+ timeoutRef.current = setTimeout(+ () => {+ callback(...args)+ lastRan.current = Date.now()+ },+ delay - (Date.now() - lastRan.current)+ )+ }+ }++ handler()+ },+ [callback, delay]+ )+}diff --git a/flowsint-app/src/renderer/src/components/shared/editor/index.ts b/flowsint-app/src/renderer/src/components/shared/editor/index.tsnew file mode 100644index 00000000..ce8d6544--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/index.ts@@ -0,0 +1 @@+export * from "./minimal-tiptap"diff --git a/flowsint-app/src/renderer/src/components/shared/editor/minimal-tiptap.tsx b/flowsint-app/src/renderer/src/components/shared/editor/minimal-tiptap.tsxnew file mode 100644index 00000000..3cea52e4--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/minimal-tiptap.tsx@@ -0,0 +1,103 @@+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"++export interface MinimalTiptapProps+ extends Omit<UseMinimalTiptapEditorProps, "onUpdate"> {+ value?: Content+ onChange?: (value: Content) => void+ className?: string+ editorContentClassName?: string+}++const Toolbar = ({ editor }: { editor: Editor }) => (+ <div className="shrink-0 overflow-x-auto border-b border-border p-2">+ <div className="flex w-max items-center gap-px">+ <SectionOne editor={editor} activeLevels={[1, 2, 3, 4, 5, 6]} />++ <Separator orientation="vertical" className="mx-2 h-7" />++ <SectionTwo+ editor={editor}+ activeActions={[+ "bold",+ "italic",+ "underline",+ "strikethrough",+ "code",+ "clearFormatting",+ ]}+ mainActionCount={3}+ />++ <Separator orientation="vertical" className="mx-2 h-7" />++ <SectionThree editor={editor} />++ <Separator orientation="vertical" className="mx-2 h-7" />++ <SectionFour+ editor={editor}+ activeActions={["orderedList", "bulletList"]}+ mainActionCount={0}+ />++ <Separator orientation="vertical" className="mx-2 h-7" />++ <SectionFive+ editor={editor}+ activeActions={["codeBlock", "blockquote", "horizontalRule"]}+ mainActionCount={0}+ />+ </div>+ </div>+)++export const MinimalTiptapEditor = React.forwardRef<+ HTMLDivElement,+ MinimalTiptapProps+>(({ value, onChange, className, editorContentClassName, ...props }, ref) => {+ const editor = useMinimalTiptapEditor({+ value,+ onUpdate: onChange,+ ...props,+ })++ if (!editor) {+ return null+ }++ return (+ <MeasuredContainer+ as="div"+ name="editor"+ ref={ref}+ className={cn(+ "flex h-full grow overflow-y-auto w-full flex-col",+ className+ )}+ >+ {/* <Toolbar editor={editor} /> */}+ <EditorContent+ editor={editor}+ className={cn("minimal-tiptap-editor", editorContentClassName)}+ />+ <LinkBubbleMenu editor={editor} />+ </MeasuredContainer>+ )+})++MinimalTiptapEditor.displayName = "MinimalTiptapEditor"++export default MinimalTiptapEditordiff --git a/flowsint-app/src/renderer/src/components/shared/editor/types.ts b/flowsint-app/src/renderer/src/components/shared/editor/types.tsnew file mode 100644index 00000000..da4907c8--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/types.ts@@ -0,0 +1,28 @@+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+ text?: string+ openInNewTab?: boolean+}++export interface ShouldShowProps {+ editor: Editor+ view: EditorView+ state: EditorState+ oldState?: EditorState+ from: number+ to: number+}++export interface FormatAction {+ label: string+ icon?: React.ReactNode+ action: (editor: Editor) => void+ isActive: (editor: Editor) => boolean+ canExecute: (editor: Editor) => boolean+ shortcuts: string[]+ value: string+}diff --git a/flowsint-app/src/renderer/src/components/shared/editor/utils.ts b/flowsint-app/src/renderer/src/components/shared/editor/utils.tsnew file mode 100644index 00000000..68c332e1--- /dev/null+++ b/flowsint-app/src/renderer/src/components/shared/editor/utils.ts@@ -0,0 +1,231 @@+import type { Editor } from "@tiptap/react"+import type { MinimalTiptapProps } from "./minimal-tiptap"++type ShortcutKeyResult = {+ symbol: string+ readable: string+}++export type FileError = {+ file: File | string+ reason: "type" | "size" | "invalidBase64" | "base64NotAllowed"+}++export type FileValidationOptions = {+ allowedMimeTypes: string[]+ maxFileSize?: number+ allowBase64: boolean+}++type FileInput = File | { src: string | File; alt?: string; title?: string }++export const isClient = (): boolean => typeof window !== "undefined"+export const isServer = (): boolean => !isClient()+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" },+}++export const getShortcutKey = (key: string): ShortcutKeyResult =>+ shortcutKeyMap[key.toLowerCase()] || { symbol: key, readable: key }++export const getShortcutKeys = (keys: string[]): ShortcutKeyResult[] =>+ keys.map(getShortcutKey)++export const getOutput = (+ editor: Editor,+ format: MinimalTiptapProps["output"]+): object | string => {+ switch (format) {+ case "json":+ return editor.getJSON()+ case "html":+ return editor.isEmpty ? "" : editor.getHTML()+ default:+ return editor.getText()+ }+}++export const isUrl = (+ text: string,+ options: { requireHostname: boolean; allowBase64?: boolean } = {+ requireHostname: false,+ }+): boolean => {+ if (text.includes("\n")) return false++ try {+ const url = new URL(text)+ const blockedProtocols = [+ "javascript:",+ "file:",+ "vbscript:",+ ...(options.allowBase64 ? [] : ["data:"]),+ ]++ if (blockedProtocols.includes(url.protocol)) return false+ 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")) &&+ !options.requireHostname+ )+ } catch {+ return false+ }+}++export const sanitizeUrl = (+ url: string | null | undefined,+ options: { allowBase64?: boolean } = {}+): string | undefined => {+ if (!url) return 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,+ }) || /^(\/|#|mailto:|sms:|fax:|tel:)/.test(url)+ ? url+ : `https://${url}`+}++export const blobUrlToBase64 = async (blobUrl: string): Promise<string> => {+ const response = await fetch(blobUrl)+ const blob = await response.blob()++ return new Promise((resolve, reject) => {+ const reader = new FileReader()+ reader.onloadend = () => {+ if (typeof reader.result === "string") {+ resolve(reader.result)+ } else {+ reject(new Error("Failed to convert Blob to base64"))+ }+ }+ reader.onerror = reject+ reader.readAsDataURL(blob)+ })+}++export const randomId = (): string => Math.random().toString(36).slice(2, 11)++export const fileToBase64 = (file: File | Blob): Promise<string> => {+ return new Promise((resolve, reject) => {+ const reader = new FileReader()+ reader.onloadend = () => {+ if (typeof reader.result === "string") {+ resolve(reader.result)+ } else {+ reject(new Error("Failed to convert File to base64"))+ }+ }+ reader.onerror = reject+ reader.readAsDataURL(file)+ })+}++const validateFileOrBase64 = <T extends FileInput>(+ input: File | string,+ options: FileValidationOptions,+ originalFile: T,+ validFiles: T[],+ errors: FileError[]+): void => {+ const { isValidType, isValidSize } = checkTypeAndSize(input, options)++ if (isValidType && isValidSize) {+ validFiles.push(originalFile)+ } else {+ if (!isValidType) errors.push({ file: input, reason: "type" })+ if (!isValidSize) errors.push({ file: input, reason: "size" })+ }+}++const checkTypeAndSize = (+ input: File | string,+ { 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 isValidType =+ allowedMimeTypes.length === 0 ||+ allowedMimeTypes.includes(mimeType) ||+ allowedMimeTypes.includes(`${mimeType.split("/")[0]}/*`)++ const isValidSize = !maxFileSize || size <= maxFileSize++ return { isValidType, isValidSize }+}++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"+}++const isBase64 = (str: string): boolean => {+ if (str.startsWith("data:")) {+ const matches = str.match(/^data:[^;]+;base64,(.+)$/)+ if (matches && matches[1]) {+ str = matches[1]+ } else {+ return false+ }+ }++ try {+ return btoa(atob(str)) === str+ } catch {+ return false+ }+}++export const filterFiles = <T extends FileInput>(+ files: T[],+ options: FileValidationOptions+): [T[], FileError[]] => {+ const validFiles: T[] = []+ const errors: FileError[] = []++ files.forEach((file) => {+ const actualFile = "src" in file ? file.src : file++ if (actualFile instanceof File) {+ validateFileOrBase64(actualFile, options, file, validFiles, errors)+ } else if (typeof actualFile === "string") {+ if (isBase64(actualFile)) {+ if (options.allowBase64) {+ validateFileOrBase64(actualFile, options, file, validFiles, errors)+ } else {+ errors.push({ file: actualFile, reason: "base64NotAllowed" })+ }+ } else {+ if (!sanitizeUrl(actualFile, { allowBase64: options.allowBase64 })) {+ errors.push({ file: actualFile, reason: "invalidBase64" })+ } else {+ validFiles.push(file)+ }+ }+ }+ })++ return [validFiles, errors]+}diff --git a/flowsint-app/src/renderer/src/components/shared/skeleton-list.tsx b/flowsint-app/src/renderer/src/components/shared/skeleton-list.tsxindex d668ee32..a68c2d4e 100644--- a/flowsint-app/src/renderer/src/components/shared/skeleton-list.tsx+++ b/flowsint-app/src/renderer/src/components/shared/skeleton-list.tsx@@ -1,11 +1,45 @@import { cn } from "@/lib/utils"import { Skeleton } from "../ui/skeleton"+import { Card, CardContent, CardHeader } from "../ui/card"+interface SkeletonListProps {rowCount: numberclassName?: string+ mode?: 'list' | 'card'}-export function SkeletonList({ rowCount, className }: SkeletonListProps) {+export function SkeletonList({ rowCount, className, mode = 'list' }: SkeletonListProps) {+ if (mode === 'card') {+ return (+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 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) => (diff --git a/flowsint-app/src/renderer/src/components/sketches/graph-sigma.tsx b/flowsint-app/src/renderer/src/components/sketches/graph-sigma.tsxnew file mode 100644index 00000000..0d8935eb--- /dev/null+++ b/flowsint-app/src/renderer/src/components/sketches/graph-sigma.tsx@@ -0,0 +1,199 @@+import React, { useMemo, useCallback } from 'react';+import Graph from 'graphology';+import { SigmaContainer, useLoadGraph, useSigma, useRegisterEvents } from '@react-sigma/core';+import { useSketchStore } from '@/stores/sketch-store';+import { useNodesDisplaySettings } from '@/stores/node-display-settings';+import { useGraphControls } from '@/stores/graph-controls-store';+import "@react-sigma/core/lib/style.css";+import type { NodeData, EdgeData } from '@/types';+import type { ItemType } from '@/stores/node-display-settings';++interface Graph3Props {+ style?: React.CSSProperties;+}++function GraphLoader() {+ const nodes = useSketchStore(s => s.nodes) as NodeData[];+ const rawEdges = useSketchStore(s => s.edges) as EdgeData[];+ const getIcon = useNodesDisplaySettings(s => s.getIcon);+ const getSize = useNodesDisplaySettings(s => s.getSize);+ const colors = useNodesDisplaySettings(s => s.colors) as Record<ItemType, string>;+ const loadGraph = useLoadGraph();+ const sigma = useSigma();+ const setActions = useGraphControls(s => s.setActions);+ const setSelectedNodes = useSketchStore(s => s.setSelectedNodes);+ const selectedNodes = useSketchStore(s => s.selectedNodes) as NodeData[];+ const registerEvents = useRegisterEvents();++ useMemo(() => {+ const graph = new Graph();+ nodes.forEach((node) => {+ const type = node.type || node.data?.type;+ const color = colors[type] || '#0074D9';+ const icon = getIcon(type);+ const size = getSize(type) * 0.5;+ let nodeLabel = node.label;+ if (!nodeLabel && 'caption' in node) nodeLabel = (node as any).caption;+ if (!nodeLabel) nodeLabel = node.id;+ const { label: _, type: __, ...restNode } = node;+ (graph as any).addNode(node.id, {+ label: `${icon ? icon + ' ' : ''}${nodeLabel}`,+ color,+ size,+ x: Math.random() * 1000 - 500, // Random position between -500 and 500+ y: Math.random() * 1000 - 500,+ type: 'circle',+ ...restNode,+ highlighted: false,+ hidden: false,+ });+ });+ rawEdges.forEach(edge => {+ const { label: edgeLabel, type: edgeType, ...restEdge } = edge;+ (graph as any).addEdge(edge.from, edge.to, {+ label: edgeLabel,+ type: 'arrow',+ ...restEdge,+ highlighted: false,+ hidden: false,+ });+ });+ loadGraph(graph);+ }, [nodes, rawEdges, getIcon, getSize, colors, loadGraph]);++ // Camera controls (memoized)+ const handleZoomIn = useCallback(() => {+ sigma.getCamera().animatedZoom({ duration: 200, factor: 1.5 });+ }, [sigma]);+ const handleZoomOut = useCallback(() => {+ sigma.getCamera().animatedZoom({ duration: 200, factor: 0.75 });+ }, [sigma]);+ const handleFit = useCallback(() => {+ sigma.getCamera().animatedReset({ duration: 200 });+ }, [sigma]);++ // Set actions in store (only once)+ React.useEffect(() => {+ setActions({+ zoomIn: handleZoomIn,+ zoomOut: handleZoomOut,+ zoomToFit: handleFit,+ });+ }, [setActions, handleZoomIn, handleZoomOut, handleFit]);++ // Node click event: zoom and highlight (memoized, minimal camera move)+ React.useEffect(() => {+ registerEvents({+ clickNode: ({ node }) => {+ const camera = sigma.getCamera();+ const graph = sigma.getGraph();+ const pos = graph.getNodeAttributes(node);+ // Only move camera if not already at target+ const state = camera.getState();+ if (state.x !== pos.x || state.y !== pos.y || state.ratio !== 0.3) {+ camera.setState({+ x: pos.x,+ y: pos.y,+ ratio: 0.3, // zoom level+ });+ }+ // Find the full node object from the store+ const selected = nodes.find(n => n.id === node);+ if (selected) setSelectedNodes([selected]);+ },+ clickStage: () => {+ setSelectedNodes([]);+ }+ });+ }, [registerEvents, sigma, setSelectedNodes, nodes]);++ // Highlight logic: batch and only update if changed+ React.useEffect(() => {+ if (!sigma) return;+ const graph = sigma.getGraph();+ let changed = false;+ if (selectedNodes.length === 0) {+ graph.forEachNode((node, attr) => {+ if (attr.highlighted || attr.dimmed) {+ graph.setNodeAttribute(node, 'highlighted', false);+ graph.setNodeAttribute(node, 'dimmed', false);+ changed = true;+ }+ });+ graph.forEachEdge((edge, attr) => {+ if (attr.highlighted || attr.dimmed) {+ graph.setEdgeAttribute(edge, 'highlighted', false);+ graph.setEdgeAttribute(edge, 'dimmed', false);+ changed = true;+ }+ });+ if (changed) sigma.refresh();+ return;+ }+ const selectedId = selectedNodes[0]?.id;+ const neighbors = new Set(graph.neighbors(selectedId));+ neighbors.add(selectedId);+ graph.forEachNode((node, attr) => {+ const isConnected = neighbors.has(node);+ if (!!attr.highlighted !== isConnected || !!attr.dimmed === isConnected) {+ graph.setNodeAttribute(node, 'highlighted', isConnected);+ graph.setNodeAttribute(node, 'dimmed', !isConnected);+ changed = true;+ }+ });+ graph.forEachEdge((edge, attr, source, target) => {+ const isEdgeConnected = neighbors.has(source) && neighbors.has(target);+ if (!!attr.highlighted !== isEdgeConnected || !!attr.dimmed === isEdgeConnected) {+ graph.setEdgeAttribute(edge, 'highlighted', isEdgeConnected);+ graph.setEdgeAttribute(edge, 'dimmed', !isEdgeConnected);+ changed = true;+ }+ });+ if (changed) sigma.refresh();+ }, [selectedNodes, sigma]);++ return null;+}++const Graph3: React.FC<Graph3Props> = ({ style }) => {+ return (+ <div className="relative h-full grow w-full bg-background">+ <SigmaContainer+ style={{ width: '100%', height: '100%', minHeight: 300, background: 'transparent', ...style }}+ settings={{+ renderEdgeLabels: false,+ labelDensity: 0.03,+ labelGridCellSize: 80,+ zIndex: false,+ hideEdgesOnMove: true,+ hideLabelsOnMove: true,+ defaultNodeColor: '#0074D9',+ defaultEdgeColor: '#aaa',+ allowInvalidContainer: false,+ nodeReducer: (_, data) => {+ if (data.dimmed) {+ return { ...data, color: '#eee', zIndex: 0, label: '' };+ }+ if (data.highlighted) {+ return { ...data, color: '#0074D9', zIndex: 1 };+ }+ return data;+ },+ edgeReducer: (_, data) => {+ if (data.dimmed) {+ return { ...data, color: '#eee', size: 0.5 };+ }+ if (data.highlighted) {+ return { ...data, color: '#0074D9', size: 2 };+ }+ return data;+ },+ }}+ >+ <GraphLoader />+ </SigmaContainer>+ </div>+ );+};++export default Graph3;\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/components/sketches/graph.tsx b/flowsint-app/src/renderer/src/components/sketches/graph.tsxindex 3c8793ee..63c05143 100644--- a/flowsint-app/src/renderer/src/components/sketches/graph.tsx+++ b/flowsint-app/src/renderer/src/components/sketches/graph.tsx@@ -9,17 +9,13 @@ import { PlusIcon } from "lucide-react"import { useGraphControls } from "@/stores/graph-controls-store"// @ts-ignoreimport { type CosmosInputNode } from "@cosmograph/cosmos"-import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "../ui/resizable"+import { ResizablePanel, ResizablePanelGroup } from "../ui/resizable"import Legend from "./legend"// Lazy loading du timelineconst CosmographTimeline = lazy(() =>import('@cosmograph/react').then(module => ({ default: module.CosmographTimeline })))--interface GraphProps {- isLoading: boolean-}// Hook pour tracker l'état de chargement de Cosmographconst useCosmographLoader = (nodes: any[], edges: any[]) => {const [isCosmographReady, setIsCosmographReady] = useState(true)@@ -262,13 +258,10 @@ const GraphProvider = memo(({ nodes, edges, children }: {GraphProvider.displayName = "GraphProvider"// Composant principal avec optimisations maximales-const Graph = memo(({ isLoading }: GraphProps) => {+const Graph = memo(() => {const nodes = useSketchStore(s => s.nodes)const edges = useSketchStore(s => s.edges)- if (isLoading) {- return <div className="h-full w-full flex items-center justify-center"><Loader /></div>- }if (!nodes.length) {return <EmptyState />}@@ -279,7 +272,7 @@ const Graph = memo(({ isLoading }: GraphProps) => {<ResizablePanel defaultSize={75} minSize={30} className="flex-grow min-h-0 inset-shadow"><GraphContent /></ResizablePanel>- <ResizableHandle />+ {/* <ResizableHandle /> */}{/* <ResizablePanel defaultSize={25} minSize={10} className="flex-grow h-full min-h-0 inset-shadow"><TimelinePanel /></ResizablePanel> */}diff --git a/flowsint-app/src/renderer/src/components/sketches/legend.tsx b/flowsint-app/src/renderer/src/components/sketches/legend.tsxindex 091bbf22..79b770f1 100644--- a/flowsint-app/src/renderer/src/components/sketches/legend.tsx+++ b/flowsint-app/src/renderer/src/components/sketches/legend.tsx@@ -35,7 +35,7 @@ const Legend = () => {exit={{ opacity: 0, scale: 0.95 }}transition={{ duration: 0.2 }}>- <Card className='p-2 rounded backdrop-blur-sm bg-background/30 border-none'>+ <Card className='p-2 rounded-mdbackdrop-blur-sm bg-background/30 border-none'><div><ul className={cn('grid grid-cols-2 items-center gap-1', showAll && 'grid-cols-3')}><AnimatePresence initial={false}>diff --git a/flowsint-app/src/renderer/src/components/transforms/editor.tsx b/flowsint-app/src/renderer/src/components/transforms/editor.tsxindex 76da4252..c27c5c97 100644--- a/flowsint-app/src/renderer/src/components/transforms/editor.tsx+++ b/flowsint-app/src/renderer/src/components/transforms/editor.tsx@@ -119,6 +119,7 @@ const FlowEditor = memo(({ initialEdges, initialNodes, theme, transform }: FlowE}, [])const onDrop = useCallback(+ //@ts-ignore(event: React.DragEvent<HTMLDivElement>) => {event.preventDefault()if (!reactFlowWrapper.current || !reactFlowInstance) returndiff --git a/flowsint-app/src/renderer/src/components/transforms/raw-material.tsx b/flowsint-app/src/renderer/src/components/transforms/raw-material.tsxindex e6243877..fa368d2e 100644--- a/flowsint-app/src/renderer/src/components/transforms/raw-material.tsx+++ b/flowsint-app/src/renderer/src/components/transforms/raw-material.tsx@@ -69,7 +69,7 @@ export default function RawMaterial() {<div className="flex-1 w-full">{Object.entries(filteredScanners).map(([category, scanners]) => (<div key={category} className="space-y-2 w-full">- <h3 className="text-sm font-medium capitalize pb-1">{category.replace("_", " ")}</h3>+ <h3 className="text-sm font-medium capitalize mt-4">{category.replace("_", " ")}</h3><div className="space-y-2">{/* @ts-ignore */}{scanners.map((scanner: Scanner) => (diff --git a/flowsint-app/src/renderer/src/components/transforms/transform-name-panel.tsx b/flowsint-app/src/renderer/src/components/transforms/transform-name-panel.tsxindex 5aa45cd8..1c791224 100644--- a/flowsint-app/src/renderer/src/components/transforms/transform-name-panel.tsx+++ b/flowsint-app/src/renderer/src/components/transforms/transform-name-panel.tsx@@ -98,7 +98,7 @@ export function TransformDetailsPanel({ transform, onUpdate, disabled = false }:return (<Panel position="top-left" className="m-4">- <Card className="px-3 py-2 space-y-1 w-sm rounded gap-1">+ <Card className="px-3 py-2 gap-1 w-sm rounded-mdgap-1">{isEditingName ? (<inputref={nameInputRef}@@ -113,7 +113,7 @@ export function TransformDetailsPanel({ transform, onUpdate, disabled = false }:/>) : (<h1- className="text-xl font-semibold cursor-pointer hover:bg-foreground/10 px-1 py-0.5 rounded transition-colors"+ 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 Transform"}@@ -134,7 +134,7 @@ export function TransformDetailsPanel({ transform, onUpdate, disabled = false }:/>) : (<p- className="text-sm text-muted-foreground cursor-pointer hover:bg-foreground/10 px-1 py-0.5 rounded transition-colors min-h-[1.5rem]"+ 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>}diff --git a/flowsint-app/src/renderer/src/hooks/use-drag-drop.ts b/flowsint-app/src/renderer/src/hooks/use-drag-drop.tsindex 9675a40c..ec95ca22 100644--- a/flowsint-app/src/renderer/src/hooks/use-drag-drop.ts+++ b/flowsint-app/src/renderer/src/hooks/use-drag-drop.ts@@ -23,6 +23,7 @@ export const useDragAndDrop = () => {}, [])const handleDragLeave = useCallback(() => {+ //@ts-ignoredragLeaveTimeoutRef.current = setTimeout(() => {setIsDraggingOver(false)}, 100)diff --git a/flowsint-app/src/renderer/src/hooks/use-electron-navigation.ts b/flowsint-app/src/renderer/src/hooks/use-electron-navigation.tsindex e5e15ad9..6db28d80 100644--- a/flowsint-app/src/renderer/src/hooks/use-electron-navigation.ts+++ b/flowsint-app/src/renderer/src/hooks/use-electron-navigation.ts@@ -12,7 +12,7 @@ export function useElectronNavigation() {data?: anytitle?: string}) => {- const { id, type, investigationId, data, title } = params+ const { id, type, investigationId, title } = paramsconst path = `/dashboard/investigations/${investigationId}/${type}/${id}`// Add a new tab with titlediff --git a/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts b/flowsint-app/src/renderer/src/hooks/use-launch-transform.tsindex 790b5471..3f811eec 100644--- a/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts+++ b/flowsint-app/src/renderer/src/hooks/use-launch-transform.ts@@ -20,6 +20,7 @@ export function useLaunchTransform(askUser: boolean = false) {success: () => `Scan on "${values.join(",")}" has been launched.`,error: () => `An error occurred launching transform.`,})+ return}return {launchTransform,diff --git a/flowsint-app/src/renderer/src/hooks/useToolbarInitialization.ts b/flowsint-app/src/renderer/src/hooks/use-toolbar-initialization.tssimilarity index 100%rename from flowsint-app/src/renderer/src/hooks/useToolbarInitialization.tsrename to flowsint-app/src/renderer/src/hooks/use-toolbar-initialization.tsdiff --git a/flowsint-app/src/renderer/src/routes/__root.tsx b/flowsint-app/src/renderer/src/routes/__root.tsxindex fb713acc..50d20ac8 100644--- a/flowsint-app/src/renderer/src/routes/__root.tsx+++ b/flowsint-app/src/renderer/src/routes/__root.tsx@@ -1,7 +1,6 @@import { Outlet, createRootRouteWithContext } from '@tanstack/react-router'import type { QueryClient } from '@tanstack/react-query'import { Toaster } from '@/components/ui/sonner'-import { AuthDebug } from '@/components/auth-debug'import '@/styles.css'export interface MyRouterContext {@@ -13,7 +12,6 @@ export const Route = createRootRouteWithContext<MyRouterContext>()({<><Toaster richColors /><Outlet />- {/* {process.env.NODE_ENV === 'development' && <AuthDebug />} */}</>),})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.tsxindex d8e3188b..2d6740ec 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@@ -5,6 +5,7 @@ import type { InvestigationGraph } from '@/types'// Get queryClient from where it's initializedimport { getContext } from '@/integrations/tanstack-query/root-provider'+import Loader from '@/components/loader'const { queryClient } = getContext();@@ -51,7 +52,7 @@ export const Route = createFileRoute('/_auth/dashboard/investigations/$investiga<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 page...</p>+ <p className="text-muted-foreground"><Loader /> Fetching nodes...</p></div></div>),diff --git a/flowsint-app/src/renderer/src/routes/_auth.dashboard.transforms.index.tsx b/flowsint-app/src/renderer/src/routes/_auth.dashboard.transforms.index.tsxindex aedc3838..87625152 100644--- a/flowsint-app/src/renderer/src/routes/_auth.dashboard.transforms.index.tsx+++ b/flowsint-app/src/renderer/src/routes/_auth.dashboard.transforms.index.tsx@@ -76,7 +76,7 @@ function TransformsPage() {Create and manage your data transformation workflows.</p></div>- <Button size="lg" onClick={handleCreateTransform}>+ <Button size="sm" onClick={handleCreateTransform}><PlusIcon className="w-4 h-4 mr-2" />New Transform</Button>@@ -84,7 +84,7 @@ function TransformsPage() {{isLoading ? (<div className="p-2">- <SkeletonList rowCount={7} />+ <SkeletonList rowCount={6} mode="card" /></div>) : (<Tabs defaultValue="All" className="space-y-6">diff --git a/flowsint-app/src/renderer/src/routes/toolbar.lazy.tsx b/flowsint-app/src/renderer/src/routes/toolbar.lazy.tsxindex 085feca0..0f57f957 100644--- a/flowsint-app/src/renderer/src/routes/toolbar.lazy.tsx+++ b/flowsint-app/src/renderer/src/routes/toolbar.lazy.tsx@@ -1,5 +1,5 @@import TabBar from '@/components/tab-bar'-import { useToolbarInitialization } from '@/hooks/useToolbarInitialization'+import { useToolbarInitialization } from '@/hooks/use-toolbar-initialization'import { createLazyFileRoute } from '@tanstack/react-router'export const Route = createLazyFileRoute('/toolbar')({component: Toolbardiff --git a/flowsint-app/src/renderer/src/store/useBoundStore.ts b/flowsint-app/src/renderer/src/store/useBoundStore.tsindex cf943d0e..02bc8799 100644--- a/flowsint-app/src/renderer/src/store/useBoundStore.ts+++ b/flowsint-app/src/renderer/src/store/useBoundStore.ts@@ -1,4 +1,4 @@-import { TabsSlice } from '@renderer/types/tab-slice'+import { TabsSlice } from '@/types/tab-slice'import { merge } from 'lodash'import { create } from 'zustand'import { createJSONStorage, persist } from 'zustand/middleware'@@ -18,7 +18,7 @@ export const useBoundStore = create(//? We need this otherwise action (functions inside the state) will be undefined.return merge({}, currentState, persistedState)},- partialize: (state) =>+ partialize: () =>({tabs: {}}) as Pick<Store, 'tabs'>diff --git a/flowsint-app/src/renderer/src/stores/analysis-panel-store.ts b/flowsint-app/src/renderer/src/stores/analysis-panel-store.tsnew file mode 100644index 00000000..fa8bf3d2--- /dev/null+++ b/flowsint-app/src/renderer/src/stores/analysis-panel-store.ts@@ -0,0 +1,20 @@+import { create } from "zustand"+import { persist } from "zustand/middleware"++interface AnalysisPanelStore {+ currentAnalysisId: string | null+ setCurrentAnalysisId: (id: string | null) => void+}++export const useAnalysisPanelStore = create<AnalysisPanelStore>()(+ persist(+ (set) => ({+ currentAnalysisId: null,+ setCurrentAnalysisId: (id) => set({ currentAnalysisId: id }),+ }),+ {+ name: "currentAnalysisId",+ partialize: (state) => ({ currentAnalysisId: state.currentAnalysisId }),+ }+ )+)\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/stores/console-store.ts b/flowsint-app/src/renderer/src/stores/console-store.tsdeleted file mode 100644index 6d785f72..00000000--- a/flowsint-app/src/renderer/src/stores/console-store.ts+++ /dev/null@@ -1,15 +0,0 @@-import { create } from 'zustand'--interface ConsoleStore {- isOpen: boolean- toggleConsole: () => void- openConsole: () => void- closeConsole: () => void-}--export const useConsoleStore = create<ConsoleStore>((set) => ({- isOpen: false,- toggleConsole: () => set((state) => ({ isOpen: !state.isOpen })),- openConsole: () => set({ isOpen: true }),- closeConsole: () => set({ isOpen: false }),-}))\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/stores/layout-store.ts b/flowsint-app/src/renderer/src/stores/layout-store.tsnew file mode 100644index 00000000..38eb2136--- /dev/null+++ b/flowsint-app/src/renderer/src/stores/layout-store.ts@@ -0,0 +1,27 @@+import { create } from 'zustand'++interface LayoutStore {+ isOpenConsole: boolean+ isOpenPanel: boolean+ isOpenChat: boolean+ toggleConsole: () => void+ togglePanel: () => void+ toggleChat: () => void+ closePanel: () => void+ openPanel: () => void+ closeChat: () => void+ openChat: () => void+}++export const useLayoutStore = create<LayoutStore>((set) => ({+ isOpenConsole: false,+ isOpenPanel: true,+ isOpenChat: false,+ toggleConsole: () => set((state) => ({ isOpenConsole: !state.isOpenConsole })),+ togglePanel: () => set((state) => ({ isOpenPanel: !state.isOpenPanel })),+ toggleChat: () => set((state) => ({ isOpenChat: !state.isOpenChat })),+ closePanel: () => set({ isOpenPanel: false }),+ openPanel: () => set({ isOpenPanel: true }),+ closeChat: () => set({ isOpenChat: false }),+ openChat: () => set({ isOpenChat: true }),+}))\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/stores/node-display-settings.ts b/flowsint-app/src/renderer/src/stores/node-display-settings.tsindex a3ff057e..e54d7f70 100644--- a/flowsint-app/src/renderer/src/stores/node-display-settings.ts+++ b/flowsint-app/src/renderer/src/stores/node-display-settings.ts@@ -29,6 +29,8 @@ export type ItemType =| "siret"| "siren"| "crypto_wallet"+ | "asn"+ | "cidr"export const ITEM_TYPES: ItemType[] = ["individual",@@ -56,7 +58,9 @@ export const ITEM_TYPES: ItemType[] = ["username","siret","siren",- "crypto_wallet"+ "crypto_wallet",+ "asn",+ "cidr",]const DEFAULT_COLORS: Record<ItemType, string> = {@@ -85,7 +89,9 @@ const DEFAULT_COLORS: Record<ItemType, string> = {biometric: "#AEB3B9", // Notion slate graysiret: "#ADB9C6", // Notion blue-graysiren: "#9FAAB8", // Notion dark slate- crypto_wallet: "#F7D154" // Notion gold+ crypto_wallet: "#F7D154", // Notion gold+ asn: "#F7D154",+ cidr: "#A2D4BF"}// Définition des icônes par défaut pour chaque type d'élément@@ -115,7 +121,9 @@ const DEFAULT_ICONS: Record<ItemType, string> = {username: "🧑💻",siret: "ℹ️",siren: "ℹ️",- crypto_wallet: "₿"+ crypto_wallet: "₿",+ asn: "🌐",+ cidr: "📡"};const DEFAULT_SIZES: Record<ItemType, number> = {@@ -144,7 +152,9 @@ const DEFAULT_SIZES: Record<ItemType, number> = {username: 8,siret: 5,siren: 5,- crypto_wallet: 7+ crypto_wallet: 7,+ asn: 12,+ cidr: 10}interface NodesDisplaySettingsState {@@ -189,7 +199,7 @@ export const useNodesDisplaySettings = create<NodesDisplaySettingsState>()(sizes: { ...DEFAULT_SIZES }}),getIcon: (itemType) => {- return get().icons[itemType]+ return get().icons[itemType] || ""},getSize: (itemType) => {return get().sizes[itemType]@@ -200,3 +210,4 @@ export const useNodesDisplaySettings = create<NodesDisplaySettingsState>()(},),)+diff --git a/flowsint-app/src/renderer/src/stores/tab-slice.ts b/flowsint-app/src/renderer/src/stores/tab-slice.tsindex a9b4a9f7..cdb3703c 100644--- a/flowsint-app/src/renderer/src/stores/tab-slice.ts+++ b/flowsint-app/src/renderer/src/stores/tab-slice.ts@@ -2,7 +2,6 @@ import type { TabsSlice } from '../types/tabs'import type { TabInfo } from '../types/tabs'import { produce } from 'immer'import type { StateCreator } from 'zustand'-import { persist } from 'zustand/middleware'export const createTabSlice: StateCreator<TabsSlice, [], [], TabsSlice> = (set) => ({tabs: {diff --git a/flowsint-app/src/renderer/src/styles.css b/flowsint-app/src/renderer/src/styles.cssindex 392ae44c..616f23a2 100644--- a/flowsint-app/src/renderer/src/styles.css+++ b/flowsint-app/src/renderer/src/styles.css@@ -11,6 +11,7 @@ body {'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;+ letter-spacing: var(--tracking-normal);}@layer base {@@ -36,22 +37,6 @@ body {--sidebar-ring: hsl(217.2, 91.2%, 59.8%);}- body {- letter-spacing: var(--tracking-normal);- }-}--@layer base {- * {- @apply border-border;- }-- body {- @apply bg-background text-foreground;- }-}--@layer base {* {@apply border-border outline-ring/50;}@@ -113,12 +98,271 @@ body {z-index: 103;}-body {- letter-spacing: var(--tracking-normal);+.style_module_watermark__6b4371ae {+ display: none !important;+ opacity: 0 !important;}-body {- letter-spacing: var(--tracking-normal);+.minimal-tiptap-editor .ProseMirror code.inline {+ @apply rounded border-[var(--mt-code-color)] bg-[var(--mt-code-background)] px-1 py-0.5 text-sm;+}++.minimal-tiptap-editor .ProseMirror pre {+ @apply relative overflow-auto rounded font-mono text-sm;+ @apply border-[var(--mt-pre-border)] bg-[var(--mt-pre-background)] text-[var(--mt-pre-color)];+ @apply hyphens-none whitespace-pre text-left;+}++.minimal-tiptap-editor .ProseMirror code {+ @apply break-words leading-[1.7em];+}++.minimal-tiptap-editor .ProseMirror pre code {+ @apply block overflow-x-auto p-3.5;+}++.minimal-tiptap-editor .ProseMirror pre {++ .hljs-keyword,+ .hljs-operator,+ .hljs-function,+ .hljs-built_in,+ .hljs-builtin-name {+ color: var(--hljs-keyword);+ }++ .hljs-attr,+ .hljs-symbol,+ .hljs-property,+ .hljs-attribute,+ .hljs-variable,+ .hljs-template-variable,+ .hljs-params {+ color: var(--hljs-attr);+ }++ .hljs-name,+ .hljs-regexp,+ .hljs-link,+ .hljs-type,+ .hljs-addition {+ color: var(--hljs-name);+ }++ .hljs-string,+ .hljs-bullet {+ color: var(--hljs-string);+ }++ .hljs-title,+ .hljs-subst,+ .hljs-section {+ color: var(--hljs-title);+ }++ .hljs-literal,+ .hljs-type,+ .hljs-deletion {+ color: var(--hljs-literal);+ }++ .hljs-selector-tag,+ .hljs-selector-id,+ .hljs-selector-class {+ color: var(--hljs-selector-tag);+ }++ .hljs-number {+ color: var(--hljs-number);+ }++ .hljs-comment,+ .hljs-meta,+ .hljs-quote {+ color: var(--hljs-comment);+ }++ .hljs-emphasis {+ @apply italic;+ }++ .hljs-strong {+ @apply font-bold;+ }+}++.minimal-tiptap-editor .ProseMirror ol {+ @apply list-decimal;+}++.minimal-tiptap-editor .ProseMirror ol ol {+ list-style: lower-alpha;+}++.minimal-tiptap-editor .ProseMirror ol ol ol {+ list-style: lower-roman;+}++.minimal-tiptap-editor .ProseMirror ul {+ list-style: disc;+}++.minimal-tiptap-editor .ProseMirror ul ul {+ list-style: circle;+}++.minimal-tiptap-editor .ProseMirror ul ul ul {+ list-style: square;+}++.minimal-tiptap-editor .ProseMirror>p.is-editor-empty::before {+ content: attr(data-placeholder);+ @apply pointer-events-none float-left h-0 text-[var(--mt-secondary)];+}++.minimal-tiptap-editor .ProseMirror .heading-node {+ @apply relative font-semibold;+}++.minimal-tiptap-editor .ProseMirror .heading-node:first-child {+ @apply mt-0;+}++.minimal-tiptap-editor .ProseMirror h1 {+ @apply mb-4 mt-[46px] text-[1.375rem] leading-7 tracking-[-0.004375rem];+}++.minimal-tiptap-editor .ProseMirror h2 {+ @apply mb-3.5 mt-8 text-[1.1875rem] leading-7 tracking-[0.003125rem];+}++.minimal-tiptap-editor .ProseMirror h3 {+ @apply mb-3 mt-6 text-[1.0625rem] leading-6 tracking-[0.00625rem];+}++.minimal-tiptap-editor .ProseMirror h4 {+ @apply mb-2 mt-4 text-[0.9375rem] leading-6;+}++.minimal-tiptap-editor .ProseMirror h5 {+ @apply mb-2 mt-4 text-sm;+}++.minimal-tiptap-editor .ProseMirror a.link {+ @apply cursor-pointer text-primary;+}++.minimal-tiptap-editor .ProseMirror a.link:hover {+ @apply underline;+}++[data-rmiz-ghost] {+ position: absolute;+ pointer-events: none;+}++[data-rmiz-btn-zoom],+[data-rmiz-btn-unzoom] {+ background-color: rgba(0, 0, 0, 0.7);+ border-radius: 50%;+ border: none;+ box-shadow: 0 0 1px rgba(255, 255, 255, 0.5);+ color: #fff;+ height: 40px;+ margin: 0;+ outline-offset: 2px;+ padding: 9px;+ touch-action: manipulation;+ width: 40px;+ -webkit-appearance: none;+ -moz-appearance: none;+ appearance: none;+}++[data-rmiz-btn-zoom]:not(:focus):not(:active) {+ position: absolute;+ clip: rect(0 0 0 0);+ clip-path: inset(50%);+ height: 1px;+ overflow: hidden;+ pointer-events: none;+ white-space: nowrap;+ width: 1px;+}++[data-rmiz-btn-zoom] {+ position: absolute;+ inset: 10px 10px auto auto;+ cursor: zoom-in;+}++[data-rmiz-btn-unzoom] {+ position: absolute;+ inset: 20px 20px auto auto;+ cursor: zoom-out;+ z-index: 1;+}++[data-rmiz-content="found"] img,+[data-rmiz-content="found"] svg,+[data-rmiz-content="found"] [role="img"],+[data-rmiz-content="found"] [data-zoom] {+ cursor: inherit;+}++[data-rmiz-modal]::backdrop {+ display: none;+}++[data-rmiz-modal][open] {+ position: fixed;+ width: 100vw;+ width: 100dvw;+ height: 100vh;+ height: 100dvh;+ max-width: none;+ max-height: none;+ margin: 0;+ padding: 0;+ border: 0;+ background: transparent;+ overflow: hidden;+}++[data-rmiz-modal-overlay] {+ position: absolute;+ inset: 0;+ transition: background-color 0.3s;+}++[data-rmiz-modal-overlay="hidden"] {+ background-color: rgba(255, 255, 255, 0);+}++[data-rmiz-modal-overlay="visible"] {+ background-color: rgba(255, 255, 255, 1);+}++[data-rmiz-modal-content] {+ position: relative;+ width: 100%;+ height: 100%;+}++[data-rmiz-modal-img] {+ position: absolute;+ cursor: zoom-out;+ image-rendering: high-quality;+ transform-origin: top left;+ transition: transform 0.3s;+}++@media (prefers-reduced-motion: reduce) {++ [data-rmiz-modal-overlay],+ [data-rmiz-modal-img] {+ transition-duration: 0.01ms !important;+ }}:root {@@ -268,7 +512,93 @@ body {--shadow-2xl: var(--shadow-2xl);}-.style_module_watermark__6b4371ae {- display: none !important;- opacity: 0 !important;+.minimal-tiptap-editor .ProseMirror {+ @apply flex max-w-full cursor-text flex-col;+ @apply z-0 outline-0;+}++.minimal-tiptap-editor .ProseMirror>div.editor {+ @apply block flex-1 whitespace-pre-wrap;+}++.minimal-tiptap-editor .ProseMirror .block-node:not(:last-child),+.minimal-tiptap-editor .ProseMirror .list-node:not(:last-child),+.minimal-tiptap-editor .ProseMirror .text-node:not(:last-child) {+ @apply mb-2.5;+}++.minimal-tiptap-editor .ProseMirror ol,+.minimal-tiptap-editor .ProseMirror ul {+ @apply pl-6;+}++.minimal-tiptap-editor .ProseMirror blockquote,+.minimal-tiptap-editor .ProseMirror dl,+.minimal-tiptap-editor .ProseMirror ol,+.minimal-tiptap-editor .ProseMirror p,+.minimal-tiptap-editor .ProseMirror pre,+.minimal-tiptap-editor .ProseMirror ul {+ @apply m-0;+}++.minimal-tiptap-editor .ProseMirror li {+ @apply leading-7;+}++.minimal-tiptap-editor .ProseMirror p {+ @apply break-words;+}++.minimal-tiptap-editor .ProseMirror li .text-node:has(+ .list-node),+.minimal-tiptap-editor .ProseMirror li>.list-node,+.minimal-tiptap-editor .ProseMirror li>.text-node,+.minimal-tiptap-editor .ProseMirror li p {+ @apply mb-0;+}++.minimal-tiptap-editor .ProseMirror blockquote {+ @apply relative pl-3.5;+}++.minimal-tiptap-editor .ProseMirror blockquote::before,+.minimal-tiptap-editor .ProseMirror blockquote.is-empty::before {+ @apply absolute bottom-0 left-0 top-0 h-full w-1 rounded-sm bg-accent-foreground/15 content-[''];+}++.minimal-tiptap-editor .ProseMirror hr {+ @apply my-3 h-0.5 w-full border-none bg-[var(--mt-hr)];+}++.minimal-tiptap-editor .ProseMirror-focused hr.ProseMirror-selectednode {+ @apply rounded-full outline outline-2 outline-offset-1 outline-muted-foreground;+}++.minimal-tiptap-editor .ProseMirror .ProseMirror-gapcursor {+ @apply pointer-events-none absolute hidden;+}++.minimal-tiptap-editor .ProseMirror .ProseMirror-hideselection {+ @apply caret-transparent;+}++.minimal-tiptap-editor .ProseMirror.resize-cursor {+ @apply cursor-col-resize;+}++.minimal-tiptap-editor .ProseMirror .selection {+ @apply inline-block;+}++.minimal-tiptap-editor .ProseMirror s span {+ @apply line-through;+}++.minimal-tiptap-editor .ProseMirror .selection,+.minimal-tiptap-editor .ProseMirror *::selection {+ @apply bg-primary/25;+}++/* Override native selection when custom selection is present */+.minimal-tiptap-editor .ProseMirror .selection::selection {+ background: transparent;}\ No newline at end of filediff --git a/flowsint-app/src/renderer/src/types/index.ts b/flowsint-app/src/renderer/src/types/index.tsindex 75d38714..2debf5c4 100644--- a/flowsint-app/src/renderer/src/types/index.ts+++ b/flowsint-app/src/renderer/src/types/index.ts@@ -86,4 +86,15 @@ export type NodesData = {initialEdges?: Edge[];initialNodes?: Node[];transform?: Transform;-};\ No newline at end of file+};++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 filediff --git a/flowsint-app/yarn.lock b/flowsint-app/yarn.lockindex 134c1c4b..52c9cc00 100644--- a/flowsint-app/yarn.lock+++ b/flowsint-app/yarn.lock@@ -823,6 +823,11 @@resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.2.4.tgz#d897170a2b0ba51f78a099edccd968f7b103387c"integrity sha512-ROFF39F6ZrnzSUEmQQZUar0Jt4xVoP9WnDRdWwF4NNcXs3xBTLgBUDoOwW141y1jP+S8nahIbdxbFC7IShw9Iw==+"@popperjs/core@^2.9.0":+ version "2.11.8"+ resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.8.tgz#6b79032e760a0899cd4204710beede972a3a185f"+ integrity sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==+"@radix-ui/[email protected]":version "1.1.1"resolved "https://registry.yarnpkg.com/@radix-ui/number/-/number-1.1.1.tgz#7b2c9225fbf1b126539551f5985769d0048d9090"@@ -1411,6 +1416,16 @@resolved "https://registry.yarnpkg.com/@ranfdev/deepobj/-/deepobj-1.0.2.tgz#9dba923578fa24aed3d3961975037b6423a03771"integrity sha512-FM3y6kfJaj5MCoAjdv24EDCTDbuFz+4+pgAunbjYfugwIE4O/xx8mPNji1n/ouG8pHCntSnBr1xwTOensF23Gg==+"@react-sigma/core@^5.0.4":+ version "5.0.4"+ resolved "https://registry.yarnpkg.com/@react-sigma/core/-/core-5.0.4.tgz#8207e340c2103a3aad7871be5a6d31b27d198072"+ integrity sha512-C0hjr069x9oLlVe7t+Y1vE8Qi9UV1dhvrwxNi96TWxrFcTSHO5ntduj5yKTGnUF4SiIszAz6Xmjga8SHT/836Q==++"@remirror/[email protected]":+ version "3.0.0"+ resolved "https://registry.yarnpkg.com/@remirror/core-constants/-/core-constants-3.0.0.tgz#96fdb89d25c62e7b6a5d08caf0ce5114370e3b8f"+ integrity sha512-42aWfPrimMfDKDi4YegyS7x+/0tlzaqwPQCULLanv3DMIlu96KTJR0fM5isWX2UViOqlGnX6YFgqWepcX+XMNg==+"@rolldown/[email protected]":version "1.0.0-beta.9"resolved "https://registry.yarnpkg.com/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.9.tgz#68ef9fff5a9791a642cea0dc4380ce6cb487a84a"@@ -1547,6 +1562,13 @@dependencies:whatwg-url "^5.0.0"+"@supabase/node-fetch@^2.6.13":+ version "2.6.13"+ resolved "https://registry.yarnpkg.com/@supabase/node-fetch/-/node-fetch-2.6.13.tgz#0d36219a9e2134049a7317591e1d4fbf73a42ec4"+ integrity sha512-rEHQaDVzxLZMCK3p+JW2nzEsK4AJpOQhetppaqAzrFum0Ub8wcnoM/8f1dWRZSulY5fRDP6rJaWT/8X3VleCzg==+ dependencies:+ whatwg-url "^5.0.0"+"@supabase/[email protected]":version "1.19.4"resolved "https://registry.yarnpkg.com/@supabase/postgrest-js/-/postgrest-js-1.19.4.tgz#41de1e4310ce8ddba87becd7e0878f4ad7a659a2"@@ -1554,15 +1576,15 @@dependencies:"@supabase/node-fetch" "^2.6.14"-"@supabase/[email protected]":- version "2.11.2"- resolved "https://registry.yarnpkg.com/@supabase/realtime-js/-/realtime-js-2.11.2.tgz#7f7399c326be717eadc9d5e259f9e2690fbf83dd"- integrity sha512-u/XeuL2Y0QEhXSoIPZZwR6wMXgB+RQbJzG9VErA3VghVt7uRfSVsjeqd7m5GhX3JR6dM/WRmLbVR8URpDWG4+w==+"@supabase/[email protected]":+ version "2.11.9"+ resolved "https://registry.yarnpkg.com/@supabase/realtime-js/-/realtime-js-2.11.9.tgz#d2f923f08ba666c0e2380be5b0eab9ae6c4074d1"+ integrity sha512-fLseWq8tEPCO85x3TrV9Hqvk7H4SGOqnFQ223NPJSsxjSYn0EmzU1lvYO6wbA0fc8DE94beCAiiWvGvo4g33lQ==dependencies:- "@supabase/node-fetch" "^2.6.14"- "@types/phoenix" "^1.5.4"- "@types/ws" "^8.5.10"- ws "^8.18.0"+ "@supabase/node-fetch" "^2.6.13"+ "@types/phoenix" "^1.6.6"+ "@types/ws" "^8.18.1"+ ws "^8.18.2""@supabase/[email protected]":version "2.7.1"@@ -1572,15 +1594,15 @@"@supabase/node-fetch" "^2.6.14""@supabase/supabase-js@^2.38.4":- version "2.49.8"- resolved "https://registry.yarnpkg.com/@supabase/supabase-js/-/supabase-js-2.49.8.tgz#ba673f42e3a2bc309f7cfe8dbc1ae589b96618b7"- integrity sha512-zzBQLgS/jZs7btWcIAc7V5yfB+juG7h0AXxKowMJuySsO5vK+F7Vp+HCa07Z+tu9lZtr3sT9fofkc86bdylmtw==+ version "2.49.9"+ resolved "https://registry.yarnpkg.com/@supabase/supabase-js/-/supabase-js-2.49.9.tgz#55ca13df1434f0ca498eda73d4d72f0e89cb8deb"+ integrity sha512-lB2A2X8k1aWAqvlpO4uZOdfvSuZ2s0fCMwJ1Vq6tjWsi3F+au5lMbVVn92G0pG8gfmis33d64Plkm6eSDs6jRA==dependencies:"@supabase/auth-js" "2.69.1""@supabase/functions-js" "2.4.4""@supabase/node-fetch" "2.6.15""@supabase/postgrest-js" "1.19.4"- "@supabase/realtime-js" "2.11.2"+ "@supabase/realtime-js" "2.11.9""@supabase/storage-js" "2.7.1""@szmarczak/http-timer@^4.0.5":@@ -1691,7 +1713,7 @@"@tailwindcss/oxide-win32-arm64-msvc" "4.1.8""@tailwindcss/oxide-win32-x64-msvc" "4.1.8"-"@tailwindcss/vite@^4.1.8":+"@tailwindcss/vite@^3.4.1":version "4.1.8"resolved "https://registry.yarnpkg.com/@tailwindcss/vite/-/vite-4.1.8.tgz#4da74494e2e0578767e02b96450b7f5127862698"integrity sha512-CQ+I8yxNV5/6uGaJjiuymgw0kEQiNKRinYbZXPdx1fk5WgiyReG0VaUx/Xq6aVNSUNJFzxm6o8FNKS5aMaim5A==@@ -1843,6 +1865,249 @@resolved "https://registry.yarnpkg.com/@tanstack/virtual-file-routes/-/virtual-file-routes-1.115.0.tgz#7d5bfa133808cf6718687a54822671ecf744a9bb"integrity sha512-XLUh1Py3AftcERrxkxC5Y5m5mfllRH3YR6YVlyjFgI2Tc2Ssy2NKmQFQIafoxfW459UJ8Dn81nWKETEIJifE4g==+"@tiptap/core@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/core/-/core-2.12.0.tgz#e0bc9255865db53682e83d843c8fef19596a8899"+ integrity sha512-3qX8oGVKFFZzQ0vit+ZolR6AJIATBzmEmjAA0llFhWk4vf3v64p1YcXcJsOBsr5scizJu5L6RYWEFatFwqckRg==++"@tiptap/extension-blockquote@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-blockquote/-/extension-blockquote-2.12.0.tgz#72e49f61544ae74b04566c9a6e614a11ff49620b"+ integrity sha512-XUC2A77YAPMJS2SqZ2S62IGcUH8gZ7cdhoWlYQb1pR4ZzXFByeKDJPxfYeAePSiuI01YGrlzgY2c6Ncx/DtO0A==++"@tiptap/extension-bold@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bold/-/extension-bold-2.12.0.tgz#9dc0dfb8853df20a3beb317f6ab1259aa1a8b620"+ integrity sha512-lAUtoLDLRc5ofD2I9MFY6MQ7d1qBLLqS1rvpwaPjOaoQb/GPVnaHj9qXYG0SY9K3erMtto48bMFpAcscjZHzZQ==++"@tiptap/extension-bubble-menu@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bubble-menu/-/extension-bubble-menu-2.12.0.tgz#9457fe79ba1622559a1755bac3c4a5b764394a74"+ integrity sha512-DYijoE0igV0Oi+ZppFsp2UrQsM/4HZtmmpD78BJM9zfCbd1YvAUIxmzmXr8uqU18OHd1uQy+/zvuNoUNYyw67g==+ dependencies:+ tippy.js "^6.3.7"++"@tiptap/extension-bullet-list@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-bullet-list/-/extension-bullet-list-2.12.0.tgz#abadbfd8a12949e2d8cc68881dd204bf96ef9f1e"+ integrity sha512-YTCjztB8MaIpwyxFYr81H4+LdKCq1VlaSXQyrPdB44mVdhhRqc46BYQb8/B//XE3UIu3X2QWFjwrqRlUq6vUiw==++"@tiptap/extension-code-block-lowlight@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-code-block-lowlight/-/extension-code-block-lowlight-2.12.0.tgz#b313ca25878214b3f044d891639c47d93ea56b79"+ integrity sha512-q5dg3GbWCMT0xniVuxjDwAd3CdMfGXFmptulzgaV31HLU+6nu4zZ5sNtMLDA7RU05lnvatKLeXNUhJ2gPouhtw==++"@tiptap/extension-code-block@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-code-block/-/extension-code-block-2.12.0.tgz#73bceaa90ba54de65ade42db5a28cc299c16158b"+ integrity sha512-1D7cYAjgxEFHdfC/35Ooi4GqWKB5sszbW8iI7N16XILNln26xb0d5KflXqYrwr9CN/ZnZoCl2o6YsP7xEObcZA==++"@tiptap/extension-code@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-code/-/extension-code-2.12.0.tgz#99f352a65706fcbbe978df6919e918b6084f0280"+ integrity sha512-R7RaS+hJeHFim7alImQ9L9CSWSMjWXvz0Ote568x9ea5gdBGUYW8PcH+5a91lh8e1XGYWBM12a8oJZRyxg/tQA==++"@tiptap/extension-color@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-color/-/extension-color-2.12.0.tgz#90415c27e528eacd21f2a88338732e85811c8af6"+ integrity sha512-tb3KDhH2Hf3Pwm7pIEH80TKBOLmHU+T/0seR3R+6flamPC7t9S4mcehDX35qvTQTqDU9v429Rw5SL40FRW7AMg==++"@tiptap/extension-document@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-document/-/extension-document-2.12.0.tgz#8a0765ca0401f30c501dea7c115b680435b73ee6"+ integrity sha512-sA1Q+mxDIv0Y3qQTBkYGwknNbDcGFiJ/fyAFholXpqbrcRx3GavwR/o0chBdsJZlFht0x7AWGwUYWvIo7wYilA==++"@tiptap/extension-dropcursor@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-dropcursor/-/extension-dropcursor-2.12.0.tgz#49d555ddbeef275a32355edcf9c0f6782629b0ce"+ integrity sha512-zcZSOXFj+7LVnmdPWTfKr5AoxYIzFPFlLJe35AdTQC5IhkljLn1Exct8I30ZREojX/00hKYsO7JJmePS6TEVlQ==++"@tiptap/extension-floating-menu@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-floating-menu/-/extension-floating-menu-2.12.0.tgz#92356639af7d68ffff159b06c30f2e6ad21b9db7"+ integrity sha512-BYpyZx/56KCDksWuJJbhki/uNgt9sACuSSZFH5AN1yS1ISD+EzIxqf6Pzzv8QCoNJ+KcRNVaZsOlOFaJGoyzag==+ dependencies:+ tippy.js "^6.3.7"++"@tiptap/extension-gapcursor@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-gapcursor/-/extension-gapcursor-2.12.0.tgz#486581ddb95e68c9d5481caf124bbd3942d22089"+ integrity sha512-k8ji5v9YKn7bNjo8UtI9hEfXfl4tKUp1hpJOEmUxGJQa3LIwrwSbReupUTnHszGQelzxikS/l1xO9P0TIGwRoA==++"@tiptap/extension-hard-break@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-hard-break/-/extension-hard-break-2.12.0.tgz#9293e12f4932d7cea43f813ed01bb2915d48652a"+ integrity sha512-08MNS2PK5DzdnAfqXn4krmJ/xebKmWpRpYqqN5EM8AvetYKlAJyTVSpo0ZUeGbZ3EZiPm9djgSnrLqpFUDjRCg==++"@tiptap/extension-heading@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-heading/-/extension-heading-2.12.0.tgz#d019bc1bb9b72d63dc0c995b6e24fb40b1011da3"+ integrity sha512-9DfES4Wd5TX1foI70N9sAL+35NN1UHrtzDYN2+dTHupnmKir9RaMXyZcbkUb4aDVzYrGxIqxJzHBVkquKIlTrw==++"@tiptap/extension-highlight@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-highlight/-/extension-highlight-2.12.0.tgz#b31c536df0037f934f9ff28e91c599214b431193"+ integrity sha512-dQNaDXslN9ion0NgVVOOKJNS3MP8Lnx9xT01mDa/R9Qdulh7xmK6n8O2GCb86TnjX1OyZURx+fEK/WLM8oKK+A==++"@tiptap/extension-history@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-history/-/extension-history-2.12.0.tgz#92173bc05b67701995f76fbdaf9fa7f5fde11945"+ integrity sha512-+B9CAf2BFURC6mQiM1OQtahVTzdEOEgT/UUNlRZkeeBc0K5of3dr6UdBqaoaMAefja3jx5PqiQ7mhUBAjSt6AA==++"@tiptap/extension-horizontal-rule@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-2.12.0.tgz#4bde11af5421f795d235423becf709df0d90627b"+ integrity sha512-Vi2+6RIehDSpoJn/7PDuOieUj7W7WrEb4wBxK9TG8PDscihR0mehhhzm/K2xhH4TN48iPJGRsjDFrFjTbXmcnw==++"@tiptap/extension-image@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-image/-/extension-image-2.12.0.tgz#e3a57ae699cac4bc944f1d4830c92dbadb157b5b"+ integrity sha512-wO+yrfMlnW3SYCb1Q1qAb+nt5WH6jnlQPTV6qdoIabRtW0puwMWULZDUgclPN5hxn8EXb9vBEu44egvH6hgkfQ==++"@tiptap/extension-italic@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-italic/-/extension-italic-2.12.0.tgz#280e92ed4bddedeb2a39ba9b9578c2ed304044c0"+ integrity sha512-JKcXK3LmEsmxNzEq5e06rPUGMRLUxmJ2mYtBY4NlJ6yLM9XMDljtgeTnWT0ySLYmfINSFTkX4S7WIRbpl9l4pw==++"@tiptap/extension-link@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-link/-/extension-link-2.12.0.tgz#4c8996b5926684d5dadc0d9b540171c7e4c98ebe"+ integrity sha512-N6f78F2onvcL8FAwFOJexOF02UwGETLjQ7cCguhBe/w7vtx7aX8/f+IlaSGY/pIcWyEQpoC28ciM0+QsrJRr1A==+ dependencies:+ linkifyjs "^4.2.0"++"@tiptap/extension-list-item@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-list-item/-/extension-list-item-2.12.0.tgz#ba89b42eb2027daebb14df1b7ecfe8172f92d53b"+ integrity sha512-4YwZooC8HP+gPxs6YrkB1ayggyYbgVvJx/rWBT6lKSW2MVVg8QXi1zAcSI3MhIhHmqDysXXFPL8JURlbeGjaFA==++"@tiptap/extension-ordered-list@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-ordered-list/-/extension-ordered-list-2.12.0.tgz#ad8fca7886cfd172165392dd3380bc15cdc98dce"+ integrity sha512-1ys0e/oqk09oXxrB1WzAx5EntK/QreObG/V1yhgihGm429fxHMsxzIYN6dKAYxx0YOPQG7qEZRrrPuWU70Ms7g==++"@tiptap/extension-paragraph@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-paragraph/-/extension-paragraph-2.12.0.tgz#35987cfa842f254e67ecec403441578a1b2189a1"+ integrity sha512-QNK5cgewCunWFxpLlbvvoO1rrLgEtNKxiY79fctP9toV+e59R+1i1Q9lXC1O5mOfDgVxCb6uFDMsqmKhFjpPog==++"@tiptap/extension-placeholder@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-placeholder/-/extension-placeholder-2.12.0.tgz#ae4ca5c04f392beaff004c7ebf18f5d51f865e5d"+ integrity sha512-K7irDox4P+NLAMjVrJeG72f0sulsCRYpx1Cy4gxKCdi1LTivj5VkXa6MXmi42KTCwBu3pWajBctYIOAES1FTAA==++"@tiptap/extension-strike@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-strike/-/extension-strike-2.12.0.tgz#7bcddac8162c6ef598e271341b8919b6a1f9a287"+ integrity sha512-nBaa5YtBsLJPZFfSs36sBz4Zgi/c8b3MsmS/Az8uXaHb0R9yPewOVUMDIQbxMct8SXUlIo9VtKlOL+mVJ3Nkpw==++"@tiptap/extension-subscript@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-subscript/-/extension-subscript-2.12.0.tgz#f65946608f913e4999912bd86a8cd469afaaf772"+ integrity sha512-9hQE28oHkIjLtn6ixysQJtHBSpEvcaV2pmYFkmoVDf4mHqbXGOUuywO3b/Fc0lNOU2aD/kgZNENNsFPWWaRWJA==++"@tiptap/extension-superscript@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-superscript/-/extension-superscript-2.12.0.tgz#71c430e91f95171cf6e22e1c2bc7daa86cfa6267"+ integrity sha512-qdUDRNGluGAG2Jok8DUezgSwTryZDs/72SyY4+gIB8nOkEfIOeM2avx8F0jETLk4Eyasfl8wbMbS1qY7s6ydfA==++"@tiptap/extension-task-item@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-task-item/-/extension-task-item-2.12.0.tgz#afa6968e01ebd1ce4958b5b49a2c77c31c0dc5d3"+ integrity sha512-IyAcy5CGU4Oesb5HpoZ7nU3wvP61Spz5/KCy1aXCgBfx3c1tF+JOijxKDnYKWSvfxzziGGIiOKR89EllnzTsdw==++"@tiptap/extension-task-list@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-task-list/-/extension-task-list-2.12.0.tgz#231c42eaf90b636194227208deb081fe5a058049"+ integrity sha512-KqXL4bRsras3a2sswxoddo7GYgBE0ZqzJgGgYVWvczA7TG3WShjJheaB1tFbt9DmVJzaZR34hKhXvDbVspbznQ==++"@tiptap/extension-text-align@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-text-align/-/extension-text-align-2.12.0.tgz#6b316c14d0fd30d99b8cc90277c71b09d23f7601"+ integrity sha512-ntGjHFPrb9iQ+QGVUr6U53/wcWI/qaAwDyApW7F7GcTpQbmimwUqvUHti1RsSh9nTrQmZD6g8SdRbIR/Y31gOw==++"@tiptap/extension-text-style@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-text-style/-/extension-text-style-2.12.0.tgz#391e1086650075ddd99afe66c477e1cc359a7061"+ integrity sha512-Pxwt23ZlvbQUahV0PvHy8Ej6IAuKR1FvHobUvwP3T8AiY7hob66fWRe7tQbESzSAzm5Vv2xkvyHeU8vekMTezA==++"@tiptap/extension-text@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-text/-/extension-text-2.12.0.tgz#973b9c832e189c012f53fc4d1f314c83c09a803c"+ integrity sha512-0ytN9V1tZYTXdiYDQg4FB2SQ56JAJC9r/65snefb9ztl+gZzDrIvih7CflHs1ic9PgyjexfMLeH+VzuMccNyZw==++"@tiptap/extension-typography@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-typography/-/extension-typography-2.12.0.tgz#683cdb1871e48948afa64a5a3a4d1d8b475f1766"+ integrity sha512-Sh95D8ON3KcGR/6wQ1B2PwVQNQXSHItQFodDAEgT9c6CCPzrz0omLWJvG7lx7NzMoZ7cvPE/BBoEujsDIT1XRA==++"@tiptap/extension-underline@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/extension-underline/-/extension-underline-2.12.0.tgz#1f1c023cc01d6eeaee39b504224459e1dfdfac57"+ integrity sha512-u95lrUCesw1SN3BXY4xrgfSuxtoCYmJ9uaU7IVVOu0zVsDFtLlOa82kd63KVF+URL0kMdO+FBmvdS6d8Era70Q==++"@tiptap/pm@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/pm/-/pm-2.12.0.tgz#72c2b574c10a0442af03c8754869f0b7ad6e2a4c"+ integrity sha512-TNzVwpeNzFfHAcYTOKqX9iU4fRxliyoZrCnERR+RRzeg7gWrXrCLubQt1WEx0sojMAfznshSL3M5HGsYjEbYwA==+ dependencies:+ prosemirror-changeset "^2.3.0"+ prosemirror-collab "^1.3.1"+ prosemirror-commands "^1.6.2"+ prosemirror-dropcursor "^1.8.1"+ prosemirror-gapcursor "^1.3.2"+ prosemirror-history "^1.4.1"+ prosemirror-inputrules "^1.4.0"+ prosemirror-keymap "^1.2.2"+ prosemirror-markdown "^1.13.1"+ prosemirror-menu "^1.2.4"+ prosemirror-model "^1.23.0"+ prosemirror-schema-basic "^1.2.3"+ prosemirror-schema-list "^1.4.1"+ prosemirror-state "^1.4.3"+ prosemirror-tables "^1.6.4"+ prosemirror-trailing-node "^3.0.0"+ prosemirror-transform "^1.10.2"+ prosemirror-view "^1.37.0"++"@tiptap/react@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/react/-/react-2.12.0.tgz#b3bb971c8a50cb0f95e85785a2d1d796ccc75a48"+ integrity sha512-D+PR+4kJO9h8AB/7XyQ/Anw8tqeS2ecv5QemBOCHi9JlMAjytauUrj6IfFBO9RbsCowlBjW5GnSpFhzpk2Gghg==+ dependencies:+ "@tiptap/extension-bubble-menu" "^2.12.0"+ "@tiptap/extension-floating-menu" "^2.12.0"+ "@types/use-sync-external-store" "^0.0.6"+ fast-deep-equal "^3"+ use-sync-external-store "^1"++"@tiptap/starter-kit@^2.12.0":+ version "2.12.0"+ resolved "https://registry.yarnpkg.com/@tiptap/starter-kit/-/starter-kit-2.12.0.tgz#02d840fe63b07c729ede1604cf1d6030aea76158"+ integrity sha512-wlcEEtexd6u0gbR311/OFZnbtRWU97DUsY6/GsSQzN4rqZ7Ra6YbfHEN5Lutu+I/anomK8vKy8k9NyvfY5Hllg==+ dependencies:+ "@tiptap/core" "^2.12.0"+ "@tiptap/extension-blockquote" "^2.12.0"+ "@tiptap/extension-bold" "^2.12.0"+ "@tiptap/extension-bullet-list" "^2.12.0"+ "@tiptap/extension-code" "^2.12.0"+ "@tiptap/extension-code-block" "^2.12.0"+ "@tiptap/extension-document" "^2.12.0"+ "@tiptap/extension-dropcursor" "^2.12.0"+ "@tiptap/extension-gapcursor" "^2.12.0"+ "@tiptap/extension-hard-break" "^2.12.0"+ "@tiptap/extension-heading" "^2.12.0"+ "@tiptap/extension-history" "^2.12.0"+ "@tiptap/extension-horizontal-rule" "^2.12.0"+ "@tiptap/extension-italic" "^2.12.0"+ "@tiptap/extension-list-item" "^2.12.0"+ "@tiptap/extension-ordered-list" "^2.12.0"+ "@tiptap/extension-paragraph" "^2.12.0"+ "@tiptap/extension-strike" "^2.12.0"+ "@tiptap/extension-text" "^2.12.0"+ "@tiptap/extension-text-style" "^2.12.0"+ "@tiptap/pm" "^2.12.0"+"@tootallnate/once@2":version "2.0.0"resolved "https://registry.yarnpkg.com/@tootallnate/once/-/once-2.0.0.tgz#f544a148d3ab35801c1f633a7441fd87c2e484bf"@@ -1995,6 +2260,13 @@dependencies:"@types/node" "*"+"@types/hast@^3.0.0":+ version "3.0.4"+ resolved "https://registry.yarnpkg.com/@types/hast/-/hast-3.0.4.tgz#1d6b39993b82cea6ad783945b0508c25903e15aa"+ integrity sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==+ dependencies:+ "@types/unist" "*"+"@types/http-cache-semantics@*":version "4.0.4"resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.4.tgz#b979ebad3919799c979b17c72621c0bc0a31c6c4"@@ -2007,6 +2279,24 @@dependencies:"@types/node" "*"+"@types/linkify-it@^5":+ version "5.0.0"+ resolved "https://registry.yarnpkg.com/@types/linkify-it/-/linkify-it-5.0.0.tgz#21413001973106cda1c3a9b91eedd4ccd5469d76"+ integrity sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==++"@types/markdown-it@^14.0.0":+ version "14.1.2"+ resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-14.1.2.tgz#57f2532a0800067d9b934f3521429a2e8bfb4c61"+ integrity sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==+ dependencies:+ "@types/linkify-it" "^5"+ "@types/mdurl" "^2"++"@types/mdurl@^2":+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/@types/mdurl/-/mdurl-2.0.0.tgz#d43878b5b20222682163ae6f897b20447233bdfd"+ integrity sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==+"@types/ms@*":version "2.1.0"resolved "https://registry.yarnpkg.com/@types/ms/-/ms-2.1.0.tgz#052aa67a48eccc4309d7f0191b7e41434b90bb78"@@ -2026,7 +2316,7 @@dependencies:undici-types "~6.19.2"-"@types/phoenix@^1.5.4":+"@types/phoenix@^1.6.6":version "1.6.6"resolved "https://registry.yarnpkg.com/@types/phoenix/-/phoenix-1.6.6.tgz#3c1ab53fd5a23634b8e37ea72ccacbf07fbc7816"integrity sha512-PIzZZlEppgrpoT2QgbnDU+MMzuR6BbCjllj0bM70lWoejMeNJAxCchxnv7J3XFkI8MpygtRpzXrIlmWUBclP5A==@@ -2064,12 +2354,22 @@dependencies:"@types/node" "*"+"@types/unist@*":+ version "3.0.3"+ resolved "https://registry.yarnpkg.com/@types/unist/-/unist-3.0.3.tgz#acaab0f919ce69cce629c2d4ed2eb4adc1b6c20c"+ integrity sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==++"@types/use-sync-external-store@^0.0.6":+ version "0.0.6"+ resolved "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz#60be8d21baab8c305132eb9cb912ed497852aadc"+ integrity sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==+"@types/verror@^1.10.3":version "1.10.11"resolved "https://registry.yarnpkg.com/@types/verror/-/verror-1.10.11.tgz#d3d6b418978c8aa202d41e5bb3483227b6ecc1bb"integrity sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg==-"@types/ws@^8.5.10":+"@types/ws@^8.18.1":version "8.18.1"resolved "https://registry.yarnpkg.com/@types/ws/-/ws-8.18.1.tgz#48464e4bf2ddfd17db13d845467f6070ffea4aa9"integrity sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==@@ -2847,6 +3147,11 @@ crc@^3.8.0:dependencies:buffer "^5.1.0"+crelt@^1.0.0:+ version "1.0.6"+ resolved "https://registry.yarnpkg.com/crelt/-/crelt-1.0.6.tgz#7cc898ea74e190fb6ef9dae57f8f81cf7302df72"+ integrity sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==+cross-spawn@^7.0.1, cross-spawn@^7.0.2, cross-spawn@^7.0.3, cross-spawn@^7.0.6:version "7.0.6"resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.6.tgz#8a58fe78f00dcd70c370451759dfbfaf03e8ee9f"@@ -2868,6 +3173,11 @@ csstype@^3.0.2, csstype@^3.1.0:resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.1.3.tgz#d80ff294d114fb0e6ac500fbf85b60137d7eff81"integrity sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==+cytoscape@^3.32.0:+ version "3.32.0"+ resolved "https://registry.yarnpkg.com/cytoscape/-/cytoscape-3.32.0.tgz#34bc2402c9bc7457ab7d9492745f034b7bf47644"+ integrity sha512-5JHBC9n75kz5851jeklCPmZWcg3hUe6sjqJvyk3+hVqFaKcHwHgxsjeN1yLmggoUc6STbtm9/NQyabQehfjvWQ==+"d3-array@2 - 3", "[email protected] - 3", d3-array@^3.1.6, d3-array@^3.2.0, d3-array@^3.2.4:version "3.2.4"resolved "https://registry.yarnpkg.com/d3-array/-/d3-array-3.2.4.tgz#15fec33b237f97ac5d7c986dc77da273a8ed0bb5"@@ -3100,6 +3410,11 @@ delayed-stream@~1.0.0:resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==+dequal@^2.0.0:+ version "2.0.3"+ resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be"+ integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==+detect-libc@^2.0.3, detect-libc@^2.0.4:version "2.0.4"resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.4.tgz#f04715b8ba815e53b4d8109655b6508a6865a7e8"@@ -3115,6 +3430,13 @@ detect-node@^2.0.4:resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1"integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==+devlop@^1.0.0:+ version "1.1.0"+ resolved "https://registry.yarnpkg.com/devlop/-/devlop-1.1.0.tgz#4db7c2ca4dc6e0e834c30be70c94bbc976dc7018"+ integrity sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==+ dependencies:+ dequal "^2.0.0"+diff@^7.0.0:version "7.0.0"resolved "https://registry.yarnpkg.com/diff/-/diff-7.0.0.tgz#3fb34d387cd76d803f6eebea67b921dab0182a9a"@@ -3344,6 +3666,11 @@ enhanced-resolve@^5.18.1:graceful-fs "^4.2.4"tapable "^2.2.0"+entities@^4.4.0:+ version "4.5.0"+ resolved "https://registry.yarnpkg.com/entities/-/entities-4.5.0.tgz#5d268ea5e7113ec74c4d033b79ea5a35a488fb48"+ integrity sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==+env-paths@^2.2.0:version "2.2.1"resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2"@@ -3701,6 +4028,11 @@ eventemitter3@^4.0.1:resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-4.0.7.tgz#2de9b68f6528d5644ef5c59526a1b4a07306169f"integrity sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==+events@^3.3.0:+ version "3.3.0"+ resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400"+ integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==+extract-zip@^2.0.1:version "2.0.1"resolved "https://registry.yarnpkg.com/extract-zip/-/extract-zip-2.0.1.tgz#663dca56fe46df890d5f131ef4a06d22bb8ba13a"@@ -3717,7 +4049,7 @@ extsprintf@^1.2.0:resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.1.tgz#8d172c064867f235c0c84a596806d279bf4bcc07"integrity sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==-fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3:+fast-deep-equal@^3, fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3:version "3.1.3"resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525"integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==@@ -4112,6 +4444,32 @@ graphemer@^1.4.0:resolved "https://registry.yarnpkg.com/graphemer/-/graphemer-1.4.0.tgz#fb2f1d55e0e3a1849aeffc90c4fa0dd53a0e66c6"integrity sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==+graphology-layout-force@^0.2.4:+ version "0.2.4"+ resolved "https://registry.yarnpkg.com/graphology-layout-force/-/graphology-layout-force-0.2.4.tgz#a9b5f2aa5c7b56985503d302dbce4c73c76b9eb3"+ integrity sha512-NYZz0YAnDkn5pkm30cvB0IScFoWGtbzJMrqaiH070dYlYJiag12Oc89dbVfaMaVR/w8DMIKxn/ix9Bqj+Umm9Q==+ dependencies:+ graphology-utils "^2.4.2"++graphology-layout-forceatlas2@^0.10.1:+ version "0.10.1"+ resolved "https://registry.yarnpkg.com/graphology-layout-forceatlas2/-/graphology-layout-forceatlas2-0.10.1.tgz#741842135609d82d12db5a5fdf74672062c28205"+ integrity sha512-ogzBeF1FvWzjkikrIFwxhlZXvD2+wlY54lqhsrWprcdPjopM2J9HoMweUmIgwaTvY4bUYVimpSsOdvDv1gPRFQ==+ dependencies:+ graphology-utils "^2.1.0"++graphology-utils@^2.1.0, graphology-utils@^2.4.2, graphology-utils@^2.5.2:+ version "2.5.2"+ resolved "https://registry.yarnpkg.com/graphology-utils/-/graphology-utils-2.5.2.tgz#4d30d6e567d27c01f105e1494af816742e8d2440"+ integrity sha512-ckHg8MXrXJkOARk56ZaSCM1g1Wihe2d6iTmz1enGOz4W/l831MBCKSayeFQfowgF8wd+PQ4rlch/56Vs/VZLDQ==++graphology@^0.26.0:+ version "0.26.0"+ resolved "https://registry.yarnpkg.com/graphology/-/graphology-0.26.0.tgz#7f866a831feaa364af750f141a7bf40489533336"+ integrity sha512-8SSImzgUUYC89Z042s+0r/vMibY7GX/Emz4LDO5e7jYXhuoWfHISPFJYjpRLUSJGq6UQ6xlenvX1p/hJdfXuXg==+ dependencies:+ events "^3.3.0"+has-bigints@^1.0.2:version "1.1.0"resolved "https://registry.yarnpkg.com/has-bigints/-/has-bigints-1.1.0.tgz#28607e965ac967e03cd2a2c70a2636a1edad49fe"@@ -4155,6 +4513,11 @@ hasown@^2.0.2:dependencies:function-bind "^1.1.2"+highlight.js@~11.11.0:+ version "11.11.1"+ resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-11.11.1.tgz#fca06fa0e5aeecf6c4d437239135fabc15213585"+ integrity sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==+hosted-git-info@^4.1.0:version "4.1.0"resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-4.1.0.tgz#827b82867e9ff1c8d0c4d9d53880397d2c86d224"@@ -4695,6 +5058,18 @@ [email protected]:lightningcss-win32-arm64-msvc "1.30.1"lightningcss-win32-x64-msvc "1.30.1"+linkify-it@^5.0.0:+ version "5.0.0"+ resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-5.0.0.tgz#9ef238bfa6dc70bd8e7f9572b52d369af569b421"+ integrity sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==+ dependencies:+ uc.micro "^2.0.0"++linkifyjs@^4.2.0:+ version "4.3.1"+ resolved "https://registry.yarnpkg.com/linkifyjs/-/linkifyjs-4.3.1.tgz#1f246ebf4be040002accd1f4535b6af7c7e37898"+ integrity sha512-DRSlB9DKVW04c4SUdGvKK5FR6be45lTU9M76JnngqPeeGDqPwYc0zdUErtsNVMtxPXgUWV4HbXbnC4sNyBxkYg==+locate-path@^6.0.0:version "6.0.0"resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-6.0.0.tgz#55321eb309febbc59c4801d931a72452a681d286"@@ -4739,6 +5114,15 @@ lowercase-keys@^2.0.0:resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-2.0.0.tgz#2603e78b7b4b0006cbca2fbcc8a3202558ac9479"integrity sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==+lowlight@^3.3.0:+ version "3.3.0"+ resolved "https://registry.yarnpkg.com/lowlight/-/lowlight-3.3.0.tgz#007b8a5bfcfd27cc65b96246d2de3e9dd4e23c6c"+ integrity sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ==+ dependencies:+ "@types/hast" "^3.0.0"+ devlop "^1.0.0"+ highlight.js "~11.11.0"+lru-cache@^10.2.0:version "10.4.3"resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.4.3.tgz#410fc8a17b70e598013df257c2446b7f3383f119"@@ -4777,6 +5161,18 @@ magic-string@^0.30.10, magic-string@^0.30.17:dependencies:"@jridgewell/sourcemap-codec" "^1.5.0"+markdown-it@^14.0.0:+ version "14.1.0"+ resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-14.1.0.tgz#3c3c5992883c633db4714ccb4d7b5935d98b7d45"+ integrity sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==+ dependencies:+ argparse "^2.0.1"+ entities "^4.4.0"+ linkify-it "^5.0.0"+ mdurl "^2.0.0"+ punycode.js "^2.3.1"+ uc.micro "^2.1.0"+matcher@^3.0.0:version "3.0.0"resolved "https://registry.yarnpkg.com/matcher/-/matcher-3.0.0.tgz#bd9060f4c5b70aa8041ccc6f80368760994f30ca"@@ -4789,6 +5185,11 @@ math-intrinsics@^1.1.0:resolved "https://registry.yarnpkg.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz#a0dd74be81e2aa5c2f27e65ce283605ee4e2b7f9"integrity sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==+mdurl@^2.0.0:+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-2.0.0.tgz#80676ec0433025dd3e17ee983d0fe8de5a2237e0"+ integrity sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==+merge2@^1.3.0, merge2@^1.4.1:version "1.4.1"resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae"@@ -5035,6 +5436,11 @@ optionator@^0.9.3:type-check "^0.4.0"word-wrap "^1.2.5"+orderedmap@^2.0.0:+ version "2.1.1"+ resolved "https://registry.yarnpkg.com/orderedmap/-/orderedmap-2.1.1.tgz#61481269c44031c449915497bf5a4ad273c512d2"+ integrity sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==+own-keys@^1.0.1:version "1.0.1"resolved "https://registry.yarnpkg.com/own-keys/-/own-keys-1.0.1.tgz#e4006910a2bf913585289676eebd6f390cf51358"@@ -5147,7 +5553,7 @@ postcss-value-parser@^4.2.0:resolved "https://registry.yarnpkg.com/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz#723c09920836ba6d3e5af019f92bc0971c02e514"integrity sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==-postcss@^8.4.43, postcss@^8.5.1:+postcss@^8.4.35, postcss@^8.4.43:version "8.5.4"resolved "https://registry.yarnpkg.com/postcss/-/postcss-8.5.4.tgz#d61014ac00e11d5f58458ed7247d899bd65f99c0"integrity sha512-QSa9EBe+uwlGTFmHsPKokv3B/oEMQZxfqW0QqNCyhpa6mB1afzulwn8hihglqAb2pOw+BJgNlmXQ8la2VeHB7w==@@ -5195,6 +5601,160 @@ prop-types@^15.6.2, prop-types@^15.8.1:object-assign "^4.1.1"react-is "^16.13.1"+prosemirror-changeset@^2.3.0:+ version "2.3.1"+ resolved "https://registry.yarnpkg.com/prosemirror-changeset/-/prosemirror-changeset-2.3.1.tgz#eee3299cfabc7a027694e9abdc4e85505e9dd5e7"+ integrity sha512-j0kORIBm8ayJNl3zQvD1TTPHJX3g042et6y/KQhZhnPrruO8exkTgG8X+NRpj7kIyMMEx74Xb3DyMIBtO0IKkQ==+ dependencies:+ prosemirror-transform "^1.0.0"++prosemirror-collab@^1.3.1:+ version "1.3.1"+ resolved "https://registry.yarnpkg.com/prosemirror-collab/-/prosemirror-collab-1.3.1.tgz#0e8c91e76e009b53457eb3b3051fb68dad029a33"+ integrity sha512-4SnynYR9TTYaQVXd/ieUvsVV4PDMBzrq2xPUWutHivDuOshZXqQ5rGbZM84HEaXKbLdItse7weMGOUdDVcLKEQ==+ dependencies:+ prosemirror-state "^1.0.0"++prosemirror-commands@^1.0.0, prosemirror-commands@^1.6.2:+ version "1.7.1"+ resolved "https://registry.yarnpkg.com/prosemirror-commands/-/prosemirror-commands-1.7.1.tgz#d101fef85618b1be53d5b99ea17bee5600781b38"+ integrity sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==+ dependencies:+ prosemirror-model "^1.0.0"+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.10.2"++prosemirror-dropcursor@^1.8.1:+ version "1.8.2"+ resolved "https://registry.yarnpkg.com/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.2.tgz#2ed30c4796109ddeb1cf7282372b3850528b7228"+ integrity sha512-CCk6Gyx9+Tt2sbYk5NK0nB1ukHi2ryaRgadV/LvyNuO3ena1payM2z6Cg0vO1ebK8cxbzo41ku2DE5Axj1Zuiw==+ dependencies:+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.1.0"+ prosemirror-view "^1.1.0"++prosemirror-gapcursor@^1.3.2:+ version "1.3.2"+ resolved "https://registry.yarnpkg.com/prosemirror-gapcursor/-/prosemirror-gapcursor-1.3.2.tgz#5fa336b83789c6199a7341c9493587e249215cb4"+ integrity sha512-wtjswVBd2vaQRrnYZaBCbyDqr232Ed4p2QPtRIUK5FuqHYKGWkEwl08oQM4Tw7DOR0FsasARV5uJFvMZWxdNxQ==+ dependencies:+ prosemirror-keymap "^1.0.0"+ prosemirror-model "^1.0.0"+ prosemirror-state "^1.0.0"+ prosemirror-view "^1.0.0"++prosemirror-history@^1.0.0, prosemirror-history@^1.4.1:+ version "1.4.1"+ resolved "https://registry.yarnpkg.com/prosemirror-history/-/prosemirror-history-1.4.1.tgz#cc370a46fb629e83a33946a0e12612e934ab8b98"+ integrity sha512-2JZD8z2JviJrboD9cPuX/Sv/1ChFng+xh2tChQ2X4bB2HeK+rra/bmJ3xGntCcjhOqIzSDG6Id7e8RJ9QPXLEQ==+ dependencies:+ prosemirror-state "^1.2.2"+ prosemirror-transform "^1.0.0"+ prosemirror-view "^1.31.0"+ rope-sequence "^1.3.0"++prosemirror-inputrules@^1.4.0:+ version "1.5.0"+ resolved "https://registry.yarnpkg.com/prosemirror-inputrules/-/prosemirror-inputrules-1.5.0.tgz#e22bfaf1d6ea4fe240ad447c184af3d520d43c37"+ integrity sha512-K0xJRCmt+uSw7xesnHmcn72yBGTbY45vm8gXI4LZXbx2Z0jwh5aF9xrGQgrVPu0WbyFVFF3E/o9VhJYz6SQWnA==+ dependencies:+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.0.0"++prosemirror-keymap@^1.0.0, prosemirror-keymap@^1.2.2:+ version "1.2.3"+ resolved "https://registry.yarnpkg.com/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz#c0f6ab95f75c0b82c97e44eb6aaf29cbfc150472"+ integrity sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==+ dependencies:+ prosemirror-state "^1.0.0"+ w3c-keyname "^2.2.0"++prosemirror-markdown@^1.13.1:+ version "1.13.2"+ resolved "https://registry.yarnpkg.com/prosemirror-markdown/-/prosemirror-markdown-1.13.2.tgz#863eb3fd5f57a444e4378174622b562735b1c503"+ integrity sha512-FPD9rHPdA9fqzNmIIDhhnYQ6WgNoSWX9StUZ8LEKapaXU9i6XgykaHKhp6XMyXlOWetmaFgGDS/nu/w9/vUc5g==+ dependencies:+ "@types/markdown-it" "^14.0.0"+ markdown-it "^14.0.0"+ prosemirror-model "^1.25.0"++prosemirror-menu@^1.2.4:+ version "1.2.5"+ resolved "https://registry.yarnpkg.com/prosemirror-menu/-/prosemirror-menu-1.2.5.tgz#dea00e7b623cea89f4d76963bee22d2ac2343250"+ integrity sha512-qwXzynnpBIeg1D7BAtjOusR+81xCp53j7iWu/IargiRZqRjGIlQuu1f3jFi+ehrHhWMLoyOQTSRx/IWZJqOYtQ==+ dependencies:+ crelt "^1.0.0"+ prosemirror-commands "^1.0.0"+ prosemirror-history "^1.0.0"+ prosemirror-state "^1.0.0"++prosemirror-model@^1.0.0, prosemirror-model@^1.20.0, prosemirror-model@^1.21.0, prosemirror-model@^1.23.0, prosemirror-model@^1.25.0:+ version "1.25.1"+ resolved "https://registry.yarnpkg.com/prosemirror-model/-/prosemirror-model-1.25.1.tgz#aeae9f1ec79fcaa76f6fc619800d91fbcf726870"+ integrity sha512-AUvbm7qqmpZa5d9fPKMvH1Q5bqYQvAZWOGRvxsB6iFLyycvC9MwNemNVjHVrWgjaoxAfY8XVg7DbvQ/qxvI9Eg==+ dependencies:+ orderedmap "^2.0.0"++prosemirror-schema-basic@^1.2.3:+ version "1.2.4"+ resolved "https://registry.yarnpkg.com/prosemirror-schema-basic/-/prosemirror-schema-basic-1.2.4.tgz#389ce1ec09b8a30ea9bbb92c58569cb690c2d695"+ integrity sha512-ELxP4TlX3yr2v5rM7Sb70SqStq5NvI15c0j9j/gjsrO5vaw+fnnpovCLEGIcpeGfifkuqJwl4fon6b+KdrODYQ==+ dependencies:+ prosemirror-model "^1.25.0"++prosemirror-schema-list@^1.4.1:+ version "1.5.1"+ resolved "https://registry.yarnpkg.com/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz#5869c8f749e8745c394548bb11820b0feb1e32f5"+ integrity sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==+ dependencies:+ prosemirror-model "^1.0.0"+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.7.3"++prosemirror-state@^1.0.0, prosemirror-state@^1.2.2, prosemirror-state@^1.4.3:+ version "1.4.3"+ resolved "https://registry.yarnpkg.com/prosemirror-state/-/prosemirror-state-1.4.3.tgz#94aecf3ffd54ec37e87aa7179d13508da181a080"+ integrity sha512-goFKORVbvPuAQaXhpbemJFRKJ2aixr+AZMGiquiqKxaucC6hlpHNZHWgz5R7dS4roHiwq9vDctE//CZ++o0W1Q==+ dependencies:+ prosemirror-model "^1.0.0"+ prosemirror-transform "^1.0.0"+ prosemirror-view "^1.27.0"++prosemirror-tables@^1.6.4:+ version "1.7.1"+ resolved "https://registry.yarnpkg.com/prosemirror-tables/-/prosemirror-tables-1.7.1.tgz#df2507f285c6c7563097b4904cb7c4b9e0cd724b"+ integrity sha512-eRQ97Bf+i9Eby99QbyAiyov43iOKgWa7QCGly+lrDt7efZ1v8NWolhXiB43hSDGIXT1UXgbs4KJN3a06FGpr1Q==+ dependencies:+ prosemirror-keymap "^1.2.2"+ prosemirror-model "^1.25.0"+ prosemirror-state "^1.4.3"+ prosemirror-transform "^1.10.3"+ prosemirror-view "^1.39.1"++prosemirror-trailing-node@^3.0.0:+ version "3.0.0"+ resolved "https://registry.yarnpkg.com/prosemirror-trailing-node/-/prosemirror-trailing-node-3.0.0.tgz#5bc223d4fc1e8d9145e4079ec77a932b54e19e04"+ integrity sha512-xiun5/3q0w5eRnGYfNlW1uU9W6x5MoFKWwq/0TIRgt09lv7Hcser2QYV8t4muXbEr+Fwo0geYn79Xs4GKywrRQ==+ dependencies:+ "@remirror/core-constants" "3.0.0"+ escape-string-regexp "^4.0.0"++prosemirror-transform@^1.0.0, prosemirror-transform@^1.1.0, prosemirror-transform@^1.10.2, prosemirror-transform@^1.10.3, prosemirror-transform@^1.7.3:+ version "1.10.4"+ resolved "https://registry.yarnpkg.com/prosemirror-transform/-/prosemirror-transform-1.10.4.tgz#56419eac14f9f56612c806ae46f9238648f3f02e"+ integrity sha512-pwDy22nAnGqNR1feOQKHxoFkkUtepoFAd3r2hbEDsnf4wp57kKA36hXsB3njA9FtONBEwSDnDeCiJe+ItD+ykw==+ dependencies:+ prosemirror-model "^1.21.0"++prosemirror-view@^1.0.0, prosemirror-view@^1.1.0, prosemirror-view@^1.27.0, prosemirror-view@^1.31.0, prosemirror-view@^1.37.0, prosemirror-view@^1.39.1:+ version "1.40.0"+ resolved "https://registry.yarnpkg.com/prosemirror-view/-/prosemirror-view-1.40.0.tgz#212e627a0c4f0198ac9823a1232e0099c9a92865"+ integrity sha512-2G3svX0Cr1sJjkD/DYWSe3cfV5VPVTBOxI9XQEGWJDFEpsZb/gh4MV29ctv+OJx2RFX4BLt09i+6zaGM/ldkCw==+ dependencies:+ prosemirror-model "^1.20.0"+ prosemirror-state "^1.0.0"+ prosemirror-transform "^1.1.0"+pump@^3.0.0:version "3.0.2"resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.2.tgz#836f3edd6bc2ee599256c924ffe0d88573ddcbf8"@@ -5203,6 +5763,11 @@ pump@^3.0.0:end-of-stream "^1.1.0"once "^1.3.1"+punycode.js@^2.3.1:+ version "2.3.1"+ resolved "https://registry.yarnpkg.com/punycode.js/-/punycode.js-2.3.1.tgz#6b53e56ad75588234e79f4affa90972c7dd8cdb7"+ integrity sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==+punycode@^2.1.0:version "2.3.1"resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.1.tgz#027422e2faec0b25e1549c3e1bd8309b9133b6e5"@@ -5258,6 +5823,11 @@ react-is@^18.3.1:resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.3.1.tgz#e83557dc12eae63a99e003a46388b1dcbb44db7e"integrity sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==+react-medium-image-zoom@^5.2.14:+ version "5.2.14"+ resolved "https://registry.yarnpkg.com/react-medium-image-zoom/-/react-medium-image-zoom-5.2.14.tgz#87032d079fce4a21a17770d6709f739872580906"+ integrity sha512-nfTVYcAUnBzXQpPDcZL+cG/e6UceYUIG+zDcnemL7jtAqbJjVVkA85RgneGtJeni12dTyiRPZVM6Szkmwd/o8w==+react-refresh@^0.17.0:version "0.17.0"resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.17.0.tgz#b7e579c3657f23d04eccbe4ad2e58a8ed51e7e53"@@ -5499,6 +6069,11 @@ rollup@^4.20.0:"@rollup/rollup-win32-x64-msvc" "4.41.1"fsevents "~2.3.2"+rope-sequence@^1.3.0:+ version "1.3.4"+ resolved "https://registry.yarnpkg.com/rope-sequence/-/rope-sequence-1.3.4.tgz#df85711aaecd32f1e756f76e43a415171235d425"+ integrity sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==+run-parallel@^1.1.9:version "1.2.0"resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.2.0.tgz#66d1368da7bdf921eb9d95bd1a9229e7f21a43ee"@@ -5678,6 +6253,14 @@ side-channel@^1.1.0:side-channel-map "^1.0.1"side-channel-weakmap "^1.0.2"+sigma@^3.0.2:+ version "3.0.2"+ resolved "https://registry.yarnpkg.com/sigma/-/sigma-3.0.2.tgz#3bf9ea22c0871ad122e2b40ffc29235565bd1a1a"+ integrity sha512-/BUbeOwPGruiBOm0YQQ6ZMcLIZ6tf/W+Jcm7dxZyAX0tK3WP9/sq7/NAWBxPIxVahdGjCJoGwej0Gdrv0DxlQQ==+ dependencies:+ events "^3.3.0"+ graphology-utils "^2.5.2"+signal-exit@^4.0.1:version "4.1.0"resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04"@@ -5979,6 +6562,13 @@ tiny-warning@^1.0.3:resolved "https://registry.yarnpkg.com/tiny-warning/-/tiny-warning-1.0.3.tgz#94a30db453df4c643d0fd566060d60a875d84754"integrity sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==+tippy.js@^6.3.7:+ version "6.3.7"+ resolved "https://registry.yarnpkg.com/tippy.js/-/tippy.js-6.3.7.tgz#8ccfb651d642010ed9a32ff29b0e9e19c5b8c61c"+ integrity sha512-E1d3oP2emgJ9dRQZdf3Kkn0qJgI6ZLpyS5z6ZkY1DF3kaQaBsGZsndEpHwx+eC+tYM41HaSNvNtLx8tU57FzTQ==+ dependencies:+ "@popperjs/core" "^2.9.0"+tmp-promise@^3.0.2:version "3.0.3"resolved "https://registry.yarnpkg.com/tmp-promise/-/tmp-promise-3.0.3.tgz#60a1a1cc98c988674fcbfd23b6e3367bdeac4ce7"@@ -6107,6 +6697,11 @@ typescript@^5.3.3, typescript@^5.5.2:resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.8.3.tgz#92f8a3e5e3cf497356f4178c34cd65a7f5e8440e"integrity sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==+uc.micro@^2.0.0, uc.micro@^2.1.0:+ version "2.1.0"+ resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-2.1.0.tgz#f8d3f7d0ec4c3dea35a7e3c8efa4cb8b45c9e7ee"+ integrity sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==+uint8array-extras@^1.4.0:version "1.4.0"resolved "https://registry.yarnpkg.com/uint8array-extras/-/uint8array-extras-1.4.0.tgz#e42a678a6dd335ec2d21661333ed42f44ae7cc74"@@ -6181,7 +6776,7 @@ use-sidecar@^1.1.3:detect-node-es "^1.1.0"tslib "^2.0.0"-use-sync-external-store@^1.2.2, use-sync-external-store@^1.5.0:+use-sync-external-store@^1, use-sync-external-store@^1.2.2, use-sync-external-store@^1.5.0:version "1.5.0"resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.5.0.tgz#55122e2a3edd2a6c106174c27485e0fd59bcfca0"integrity sha512-Rb46I4cGGVBmjamjphe8L/UnvJD+uPPtTkNvX5mZgqdbavhI4EbgIWJiIHXJ8bc/i9EQGPRh4DwEURJ552Do0A==@@ -6245,6 +6840,11 @@ vite@^5.3.1:optionalDependencies:fsevents "~2.3.3"+w3c-keyname@^2.2.0:+ version "2.2.8"+ resolved "https://registry.yarnpkg.com/w3c-keyname/-/w3c-keyname-2.2.8.tgz#7b17c8c6883d4e8b86ac8aba79d39e880f8869c5"+ integrity sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==+webidl-conversions@^3.0.0:version "3.0.1"resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871"@@ -6365,7 +6965,7 @@ wrappy@1:resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==-ws@^8.18.0:+ws@^8.18.2:version "8.18.2"resolved "https://registry.yarnpkg.com/ws/-/ws-8.18.2.tgz#42738b2be57ced85f46154320aabb51ab003705a"integrity sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==