All files / apps/web/src/components SchemaEditor.jsx

0% Statements 0/155
0% Branches 0/143
0% Functions 0/45
0% Lines 0/149

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { useState, useCallback } from 'react';
import { 
  Plus, 
  Trash2, 
  ChevronDown, 
  ChevronRight,
  HelpCircle,
  Copy,
  AlertCircle,
  Code
} from 'lucide-react';
 
// Types avec labels user-friendly
const FIELD_TYPES = {
  string: { label: 'Texte' },
  number: { label: 'Nombre' },
  integer: { label: 'Entier' },
  boolean: { label: 'Booléen' },
  array: { label: 'Tableau' },
  object: { label: 'Objet' },
};
 
// Types pour les items de tableau
const ARRAY_ITEM_TYPES = ['string', 'number', 'integer', 'boolean', 'object'];
 
// Générer un ID unique
const generateId = () => `field_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
 
// Créer un nouveau champ vide
const createEmptyField = (baseName = 'propriete') => ({
  id: generateId(),
  name: `${baseName}_${Date.now() % 1000}`,
  type: 'string',
  description: '',
  required: false,
});
 
/**
 * Composant pour éditer une propriété individuelle (récursif pour les objets imbriqués)
 */
function PropertyEditor({ field, onUpdate, onDelete, onDuplicate, disabled = false, depth = 0 }) {
  const [isExpanded, setIsExpanded] = useState(true);
  const [showDescription, setShowDescription] = useState(false);
  
  const hasChildren = field.type === 'object' || (field.type === 'array' && field.itemType === 'object');
  const needsItemType = field.type === 'array';
 
  const handleNameChange = (name) => {
    const sanitized = name.replace(/[^a-zA-Z0-9_]/g, '_').toLowerCase();
    onUpdate({ ...field, name: sanitized });
  };
 
  const handleTypeChange = (type) => {
    const updatedField = { ...field, type };
    
    if (type === 'object') {
      updatedField.children = field.children || [];
      delete updatedField.itemType;
    } else if (type === 'array') {
      updatedField.itemType = field.itemType || 'string';
      if (updatedField.itemType === 'object') {
        updatedField.children = field.children || [];
      } else {
        delete updatedField.children;
      }
    } else {
      delete updatedField.children;
      delete updatedField.itemType;
    }
    
    onUpdate(updatedField);
  };
 
  const handleItemTypeChange = (itemType) => {
    const updatedField = { ...field, itemType };
    
    if (itemType === 'object') {
      updatedField.children = field.children || [];
    } else {
      delete updatedField.children;
    }
    
    onUpdate(updatedField);
  };
 
  const handleAddChild = () => {
    const children = field.children || [];
    onUpdate({
      ...field,
      children: [...children, createEmptyField()],
    });
  };
 
  const handleUpdateChild = (index, updatedChild) => {
    const children = [...(field.children || [])];
    children[index] = updatedChild;
    onUpdate({ ...field, children });
  };
 
  const handleDeleteChild = (index) => {
    const children = (field.children || []).filter((_, i) => i !== index);
    onUpdate({ ...field, children });
  };
 
  const handleDuplicateChild = (index) => {
    const children = [...(field.children || [])];
    const duplicated = { ...children[index], id: generateId(), name: `${children[index].name}_copie` };
    children.splice(index + 1, 0, duplicated);
    onUpdate({ ...field, children });
  };
 
  return (
    <div className={`${depth > 0 ? 'ml-4 pl-3 border-l-2 border-gray-200' : ''}`}>
      <div className={`
        bg-white border rounded-lg overflow-hidden
        ${depth > 0 ? 'border-gray-200' : 'border-gray-300'}
        ${disabled ? 'opacity-60' : ''}
      `}>
        {/* Ligne de propriété */}
        <div className="flex items-center gap-2 p-2.5 bg-gray-50">
          {/* Expand/Collapse */}
          {hasChildren ? (
            <button
              type="button"
              onClick={() => setIsExpanded(!isExpanded)}
              className="p-1 hover:bg-gray-200 rounded transition-colors"
              disabled={disabled}
            >
              {isExpanded ? (
                <ChevronDown className="h-4 w-4 text-gray-500" />
              ) : (
                <ChevronRight className="h-4 w-4 text-gray-500" />
              )}
            </button>
          ) : (
            <div className="w-6" />
          )}
 
          {/* Dropdown Type */}
          <select
            value={field.type}
            onChange={(e) => handleTypeChange(e.target.value)}
            className="px-2 py-1 text-xs font-medium bg-white border border-gray-300 rounded text-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
            disabled={disabled}
          >
            {Object.entries(FIELD_TYPES).map(([type, info]) => (
              <option key={type} value={type}>{info.label}</option>
            ))}
          </select>
 
          {/* Type d'item pour les tableaux */}
          {needsItemType && (
            <>
              <span className="text-xs text-gray-500">de</span>
              <select
                value={field.itemType || 'string'}
                onChange={(e) => handleItemTypeChange(e.target.value)}
                className="px-2 py-1 text-xs font-medium bg-white border border-gray-300 rounded text-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                disabled={disabled}
              >
                {ARRAY_ITEM_TYPES.map((type) => (
                  <option key={type} value={type}>{FIELD_TYPES[type].label}</option>
                ))}
              </select>
            </>
          )}
 
          {/* Nom du champ */}
          <input
            type="text"
            value={field.name}
            onChange={(e) => handleNameChange(e.target.value)}
            className="flex-1 px-2 py-1 text-sm font-medium bg-white border border-gray-300 rounded text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-indigo-500 focus:border-transparent min-w-0"
            placeholder="nom_propriete"
            disabled={disabled}
          />
 
          {/* Toggle Required */}
          <label className="flex items-center gap-1.5 text-xs text-gray-600 cursor-pointer select-none whitespace-nowrap">
            <input
              type="checkbox"
              checked={field.required}
              onChange={(e) => onUpdate({ ...field, required: e.target.checked })}
              className="rounded bg-white border-gray-300 text-indigo-600 focus:ring-indigo-500 h-3.5 w-3.5"
              disabled={disabled}
            />
            Requis
          </label>
 
          {/* Toggle Description */}
          <button
            type="button"
            onClick={() => setShowDescription(!showDescription)}
            className={`p-1.5 rounded transition-colors ${
              showDescription || field.description 
                ? 'text-indigo-600 bg-indigo-100' 
                : 'text-gray-400 hover:text-gray-600 hover:bg-gray-200'
            }`}
            title="Ajouter une description"
            disabled={disabled}
          >
            <HelpCircle className="h-3.5 w-3.5" />
          </button>
 
          {/* Duplicate */}
          <button
            type="button"
            onClick={onDuplicate}
            className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-200 rounded transition-colors"
            title="Dupliquer"
            disabled={disabled}
          >
            <Copy className="h-3.5 w-3.5" />
          </button>
 
          {/* Delete */}
          <button
            type="button"
            onClick={onDelete}
            className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
            title="Supprimer"
            disabled={disabled}
          >
            <Trash2 className="h-3.5 w-3.5" />
          </button>
        </div>
 
        {/* Input Description */}
        {showDescription && (
          <div className="px-3 py-2 border-t border-gray-200 bg-gray-50">
            <input
              type="text"
              value={field.description}
              onChange={(e) => onUpdate({ ...field, description: e.target.value })}
              placeholder="Description (aide l'IA à comprendre quoi extraire)..."
              className="w-full px-2 py-1.5 text-sm bg-white border border-gray-300 rounded text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              disabled={disabled}
            />
          </div>
        )}
 
        {/* Propriétés imbriquées */}
        {hasChildren && isExpanded && (
          <div className="border-t border-gray-200 bg-gray-50 p-3">
            {field.children && field.children.length > 0 && (
              <div className="space-y-2 mb-3">
                {field.children.map((child, index) => (
                  <PropertyEditor
                    key={child.id}
                    field={child}
                    onUpdate={(updated) => handleUpdateChild(index, updated)}
                    onDelete={() => handleDeleteChild(index)}
                    onDuplicate={() => handleDuplicateChild(index)}
                    disabled={disabled}
                    depth={depth + 1}
                  />
                ))}
              </div>
            )}
            
            <button
              type="button"
              onClick={handleAddChild}
              className="w-full flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium text-indigo-600 bg-indigo-50 border border-dashed border-indigo-300 rounded-lg hover:bg-indigo-100 hover:border-indigo-400 transition-colors"
              disabled={disabled}
            >
              <Plus className="h-3.5 w-3.5" />
              Ajouter une propriété
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
 
/**
 * Composant principal SchemaEditor
 * Éditeur visuel de JSON Schema pour le mode DATA
 */
export default function SchemaEditor({ fields, onChange, disabled = false }) {
  const [showJsonPreview, setShowJsonPreview] = useState(false);
 
  const handleAddField = useCallback(() => {
    onChange([...fields, createEmptyField()]);
  }, [fields, onChange]);
 
  const handleUpdateField = useCallback((index, updatedField) => {
    const newFields = [...fields];
    newFields[index] = updatedField;
    onChange(newFields);
  }, [fields, onChange]);
 
  const handleDeleteField = useCallback((index) => {
    onChange(fields.filter((_, i) => i !== index));
  }, [fields, onChange]);
 
  const handleDuplicateField = useCallback((index) => {
    const newFields = [...fields];
    const duplicated = { ...fields[index], id: generateId(), name: `${fields[index].name}_copie` };
    newFields.splice(index + 1, 0, duplicated);
    onChange(newFields);
  }, [fields, onChange]);
 
  // Convertir les fields en JSON Schema
  const toJsonSchema = useCallback((fieldList) => {
    const schema = {};
    
    for (const field of fieldList) {
      const definition = {
        type: field.type,
        description: field.description || `Extraire ${field.name.replace(/_/g, ' ')}`,
        required: field.required,
      };
 
      if (field.type === 'object' && field.children) {
        definition.properties = toJsonSchema(field.children);
      }
 
      if (field.type === 'array' && field.itemType) {
        if (field.itemType === 'object' && field.children) {
          definition.items = {
            type: 'object',
            properties: toJsonSchema(field.children),
          };
        } else {
          definition.items = { type: field.itemType };
        }
      }
 
      schema[field.name] = definition;
    }
    
    return schema;
  }, []);
 
  // Valider les champs
  const validationErrors = useCallback(() => {
    const errors = [];
    const names = new Set();
 
    const validateField = (field, path = '') => {
      const fieldPath = path ? `${path}.${field.name}` : field.name;
      
      if (!field.name.trim()) {
        errors.push(`La propriété à ${fieldPath || 'la racine'} doit avoir un nom`);
      } else if (names.has(fieldPath)) {
        errors.push(`Nom de propriété dupliqué: ${fieldPath}`);
      } else {
        names.add(fieldPath);
      }
 
      if (field.type === 'object' && field.children) {
        for (const child of field.children) {
          validateField(child, fieldPath);
        }
      }
 
      if (field.type === 'array' && field.itemType === 'object' && field.children) {
        for (const child of field.children) {
          validateField(child, `${fieldPath}[]`);
        }
      }
    };
 
    for (const field of fields) {
      validateField(field);
    }
 
    return errors;
  }, [fields]);
 
  const errors = validationErrors();
  
  // Générer le JSON Schema complet
  const jsonSchema = useCallback(() => {
    const propertiesSchema = toJsonSchema(fields);
    return {
      type: 'object',
      properties: propertiesSchema,
    };
  }, [fields, toJsonSchema]);
 
  return (
    <div className="space-y-3">
      {/* Bloc Racine */}
      <div className="border-2 border-indigo-200 rounded-xl overflow-hidden bg-indigo-50/30">
        {/* Header Racine */}
        <div className="flex items-center gap-2 px-3 py-2.5 bg-indigo-100/50 border-b border-indigo-200">
          <Code className="h-4 w-4 text-indigo-600" />
          <span className="px-2 py-1 text-xs font-medium bg-white border border-indigo-300 rounded text-indigo-700">
            Object
          </span>
          <span className="text-xs text-gray-500 ml-2">
            Schéma JSON pour extraction de données structurées
          </span>
        </div>
 
        {/* Contenu Racine - Propriétés */}
        <div className="p-3">
          {fields.length > 0 && (
            <div className="space-y-2 mb-3">
              {fields.map((field, index) => (
                <PropertyEditor
                  key={field.id}
                  field={field}
                  onUpdate={(updated) => handleUpdateField(index, updated)}
                  onDelete={() => handleDeleteField(index)}
                  onDuplicate={() => handleDuplicateField(index)}
                  disabled={disabled}
                  depth={0}
                />
              ))}
            </div>
          )}
 
          {/* Bouton Ajouter Propriété */}
          <button
            type="button"
            onClick={handleAddField}
            className="w-full flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-indigo-600 bg-indigo-50 border-2 border-dashed border-indigo-300 rounded-lg hover:bg-indigo-100 hover:border-indigo-400 transition-colors"
            disabled={disabled}
          >
            <Plus className="h-4 w-4" />
            Ajouter une propriété
          </button>
        </div>
      </div>
 
      {/* Erreurs de Validation */}
      {errors.length > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-3">
          <div className="flex items-center gap-2 text-red-700 font-medium mb-2">
            <AlertCircle className="h-4 w-4" />
            Problèmes de validation
          </div>
          <ul className="text-sm text-red-600 list-disc list-inside space-y-1">
            {errors.map((error, i) => (
              <li key={i}>{error}</li>
            ))}
          </ul>
        </div>
      )}
 
      {/* Aperçu JSON */}
      {fields.length > 0 && (
        <div className="border-t border-gray-200 pt-3">
          <button
            type="button"
            onClick={() => setShowJsonPreview(!showJsonPreview)}
            className="text-sm text-gray-500 hover:text-gray-700 flex items-center gap-1"
          >
            {showJsonPreview ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
            {showJsonPreview ? 'Masquer' : 'Afficher'} le JSON Schema
          </button>
          
          {showJsonPreview && (
            <pre className="mt-2 p-3 bg-gray-900 text-gray-100 rounded-lg text-xs overflow-auto max-h-48 border border-gray-700 font-mono">
              {JSON.stringify(jsonSchema(), null, 2)}
            </pre>
          )}
        </div>
      )}
    </div>
  );
}
 
/**
 * Fonction utilitaire: Convertit les fields en schéma JSON
 */
export const fieldsToSchema = (fields) => {
  const schema = {};
  
  for (const field of fields) {
    const definition = {
      type: field.type,
      description: field.description || `Extraire ${field.name.replace(/_/g, ' ')}`,
      required: field.required,
    };
 
    if (field.type === 'object' && field.children) {
      definition.properties = fieldsToSchema(field.children);
    }
 
    if (field.type === 'array' && field.itemType) {
      if (field.itemType === 'object' && field.children) {
        definition.items = {
          type: 'object',
          properties: fieldsToSchema(field.children),
        };
      } else {
        definition.items = { type: field.itemType };
      }
    }
 
    schema[field.name] = definition;
  }
  
  return schema;
};
 
/**
 * Fonction utilitaire: Convertit les fields en schéma complet avec type racine
 */
export const fieldsToSchemaWithRoot = (fields) => {
  const propertiesSchema = fieldsToSchema(fields);
  return {
    type: 'object',
    properties: propertiesSchema,
  };
};
 
/**
 * Fonction utilitaire: Convertit un schéma JSON en fields
 */
export const schemaToFields = (schema) => {
  const fields = [];
  
  for (const [name, definition] of Object.entries(schema)) {
    if (!definition || typeof definition !== 'object') continue;
    
    const field = {
      id: generateId(),
      name,
      type: definition.type || 'string',
      description: definition.description || '',
      required: definition.required || false,
    };
    
    if (field.type === 'object' && definition.properties) {
      field.children = schemaToFields(definition.properties);
    }
    
    if (field.type === 'array' && definition.items) {
      const itemType = definition.items.type || 'string';
      field.itemType = itemType;
      
      if (itemType === 'object' && definition.items.properties) {
        field.children = schemaToFields(definition.items.properties);
      }
    }
    
    fields.push(field);
  }
  
  return fields;
};
 
/**
 * Fonction utilitaire: Parse un schéma (supporte ancien et nouveau format)
 */
export const parseSchema = (schema) => {
  // Nouveau format: { type: 'object', properties: {...} }
  if (schema.type === 'object' && schema.properties) {
    return schemaToFields(schema.properties);
  }
  // Ancien format: { fieldName: { type, description, ... }, ... }
  return schemaToFields(schema);
};
 
/**
 * Créer des fields initiaux vides
 */
export const createInitialFields = () => [];