All files / app/features/disot/disot-entry disot-entry.component.ts

43.37% Statements 72/166
21.05% Branches 8/38
57.14% Functions 16/28
46.1% Lines 71/154

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 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              1x 25x 25x   25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x             25x               25x 25x 25x       2x       1x 1x 1x 1x 1x             10x 1x 1x       9x 1x             8x 1x 1x       8x 8x   8x 8x     8x 1x     1x 1x     1x     8x         8x 8x 2x   8x 2x     8x           7x     7x   1x 1x   8x         20x       1x         1x       1x 1x       1x           1x 1x       1x       1x           1x 1x       1x       9x 9x                                                                                                                                                                                                                                                                                                                                                          
import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { SharedModule } from '../../../shared/shared-module';
import { DisotService } from '../../../core/services/disot.service';
import { SignatureService } from '../../../core/services/signature.service';
import { CasService } from '../../../core/services/cas.service';
import { ContentHash } from '../../../core/domain/interfaces/content.interface';
import { DisotEntry, DisotEntryType } from '../../../core/domain/interfaces/disot.interface';
 
@Component({
  selector: 'app-disot-entry',
  standalone: true,
  imports: [CommonModule, SharedModule, FormsModule],
  template: `
    <div class="disot-entry">
      <h2>Create DISOT Entry</h2>
      
      <!-- Content Selection Modal -->
      <app-content-selection-modal 
        *ngIf="showContentModal"
        (contentSelected)="onContentSelected($event)"
        (closed)="showContentModal = false"
      ></app-content-selection-modal>
      
      <!-- Author Selection Modal (Reusing content selection for authors) -->
      <app-content-selection-modal 
        *ngIf="showAuthorModal"
        [title]="'Select Author Entry'"
        [searchPlaceholder]="'Search by public key or entry ID...'"
        [filterByContentType]="'author'"
        (contentSelected)="onAuthorSelected($event)"
        (closed)="showAuthorModal = false"
      ></app-content-selection-modal>
      
      <!-- Previous Version Selection Modal -->
      <app-content-selection-modal 
        *ngIf="showPreviousVersionModal"
        [title]="'Select Previous Version'"
        [searchPlaceholder]="'Search by entry ID or content hash...'"
        (contentSelected)="onPreviousVersionSelected($event)"
        (closed)="showPreviousVersionModal = false"
      ></app-content-selection-modal>
      
      <div class="form-section">
        <h3>Content Information</h3>
        <div *ngIf="contentHash" class="content-info">
          <p><strong>Algorithm:</strong> {{ contentHash.algorithm | uppercase }}</p>
          <p><strong>Hash:</strong> <code>{{ contentHash.value }}</code></p>
          <button (click)="clearContent()" class="clear-button">Clear Selection</button>
        </div>
        <div *ngIf="!contentHash" class="no-content">
          <p>No content selected. Please select content from the content list.</p>
          <button (click)="selectContent()" class="select-button">Select Content</button>
        </div>
      </div>
 
      <div class="form-section">
        <h3>Entry Type</h3>
        <select [(ngModel)]="selectedType" class="type-select">
          <option *ngFor="let type of entryTypes" [value]="type">
            {{ formatEntryType(type) }}
          </option>
        </select>
      </div>
 
      <div class="form-section">
        <h3>Signing Key</h3>
        <div class="key-section">
          <textarea 
            [(ngModel)]="privateKey"
            placeholder="Enter your private key..."
            rows="3"
            class="key-input"
            [disabled]="isCreating"
          ></textarea>
          <button 
            (click)="generateKeyPair()"
            [disabled]="isCreating"
            class="generate-button"
          >
            Generate New Key Pair
          </button>
          <div *ngIf="publicKey" class="public-key-display">
            <p><strong>Public Key:</strong></p>
            <code>{{ publicKey }}</code>
          </div>
        </div>
      </div>
 
      <div class="form-section" *ngIf="selectedType === 'blog_post'">
        <h3>Blog Post Content</h3>
        <textarea 
          [(ngModel)]="blogPostContent"
          placeholder="Enter your blog post content..."
          rows="6"
          class="blog-input"
          [disabled]="isCreating"
        ></textarea>
      </div>
 
      <div class="form-section">
        <h3>Author (Optional)</h3>
        <div *ngIf="selectedAuthor" class="content-info">
          <p><strong>Author ID:</strong> <code>{{ selectedAuthor }}</code></p>
          <button (click)="clearAuthor()" class="clear-button">Clear Selection</button>
        </div>
        <div *ngIf="!selectedAuthor" class="no-content">
          <p>No author selected. Optionally select an author entry.</p>
          <button (click)="selectAuthor()" class="select-button">Select Author</button>
        </div>
      </div>
 
      <div class="form-section">
        <h3>Previous Version (Optional)</h3>
        <div *ngIf="selectedPreviousVersion" class="content-info">
          <p><strong>Previous Version ID:</strong> <code>{{ selectedPreviousVersion }}</code></p>
          <button (click)="clearPreviousVersion()" class="clear-button">Clear Selection</button>
        </div>
        <div *ngIf="!selectedPreviousVersion" class="no-content">
          <p>No previous version selected. Optionally link to a previous version.</p>
          <button (click)="selectPreviousVersion()" class="select-button">Select Previous Version</button>
        </div>
      </div>
 
      <button 
        (click)="createEntry()"
        [disabled]="!contentHash || !privateKey || isCreating"
        class="create-button"
      >
        {{ isCreating ? 'Creating...' : 'Create Entry' }}
      </button>
 
      <div *ngIf="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
 
      <div *ngIf="createdEntry" class="success-section">
        <h3>Entry Created Successfully!</h3>
        <div class="entry-details">
          <p><strong>Entry ID:</strong> <code>{{ createdEntry.id }}</code></p>
          <p><strong>Type:</strong> {{ formatEntryType(createdEntry.type) }}</p>
          <p><strong>Timestamp:</strong> {{ createdEntry.timestamp | date:'medium' }}</p>
          <p><strong>Public Key:</strong> <code>{{ createdEntry.signature.publicKey }}</code></p>
          <p><strong>Signature:</strong> <code>{{ createdEntry.signature.value }}</code></p>
        </div>
      </div>
 
      <div class="entries-section" *ngIf="previousEntries.length > 0">
        <h3>Previous Entries</h3>
        <div class="entries-list">
          <div *ngFor="let entry of previousEntries" class="entry-item">
            <div class="entry-header">
              <div class="entry-info">
                <p><strong>Type:</strong> {{ formatEntryType(entry.type) }}</p>
                <p><strong>Time:</strong> {{ entry.timestamp | date:'short' }}</p>
                <p><strong>ID:</strong> <code class="small-code">{{ entry.id }}</code></p>
                <p><strong>Content Hash:</strong> <code class="small-code">{{ entry.contentHash.value }}</code></p>
              </div>
              <div class="entry-actions">
                <button 
                  (click)="toggleEntryPreview(entry)" 
                  class="preview-entry-button"
                  [disabled]="getEntryPreview(entry.id)?.isLoading"
                >
                  {{ getEntryPreview(entry.id)?.isLoading ? 'Loading...' : (getEntryPreview(entry.id)?.previewData ? 'Hide Preview' : 'Show Preview') }}
                </button>
              </div>
            </div>
            
            <div *ngIf="getEntryPreview(entry.id)?.previewData" class="entry-preview-section">
              <div class="entry-preview-controls">
                <label>Preview as: </label>
                <select [(ngModel)]="getEntryPreview(entry.id)!.previewType" (change)="updateEntryPreview(entry)" class="preview-type-select">
                  <option value="text">Text</option>
                  <option value="json">JSON</option>
                  <option value="hex">Hex</option>
                  <option value="base64">Base64</option>
                  <option value="image">Image</option>
                </select>
                <span *ngIf="getEntryPreview(entry.id)?.detectedType" class="detected-type">(Detected: {{ getEntryPreview(entry.id)?.detectedType }})</span>
              </div>
              <div class="entry-preview" [ngClass]="'preview-' + getEntryPreview(entry.id)?.previewType">
                <pre *ngIf="getEntryPreview(entry.id)?.previewType === 'json'">{{ getEntryPreview(entry.id)?.previewData }}</pre>
                <code *ngIf="getEntryPreview(entry.id)?.previewType === 'hex' || getEntryPreview(entry.id)?.previewType === 'base64'">{{ getEntryPreview(entry.id)?.previewData }}</code>
                <p *ngIf="getEntryPreview(entry.id)?.previewType === 'text'">{{ getEntryPreview(entry.id)?.previewData }}</p>
                <img *ngIf="getEntryPreview(entry.id)?.previewType === 'image'" [src]="getEntryPreview(entry.id)?.previewData" alt="Preview" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styles: [`
    .disot-entry {
      padding: 20px;
      max-width: 800px;
      margin: 0 auto;
    }
 
    .form-section {
      margin-bottom: 25px;
      padding: 20px;
      background-color: #f9f9f9;
      border-radius: 8px;
    }
 
    .form-section h3 {
      margin-top: 0;
      margin-bottom: 15px;
      color: #333;
    }
 
    .content-info, .no-content {
      padding: 15px;
      background-color: #fff;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
    }
 
    .content-info p {
      margin: 5px 0;
    }
 
    .content-info code {
      background-color: #e9ecef;
      padding: 2px 4px;
      border-radius: 3px;
      font-family: monospace;
      word-break: break-all;
    }
 
    .no-content {
      color: #666;
      font-style: italic;
    }
 
    .type-select {
      width: 100%;
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background-color: white;
    }
 
    .key-section {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
 
    .key-input {
      width: 100%;
      padding: 10px;
      font-family: monospace;
      font-size: 14px;
      border: 1px solid #ddd;
      border-radius: 4px;
      resize: vertical;
    }
 
    .generate-button {
      align-self: flex-start;
      padding: 8px 16px;
      background-color: #6c757d;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
 
    .generate-button:hover:not(:disabled) {
      background-color: #5a6268;
    }
 
    .clear-button, .select-button {
      margin-top: 10px;
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
 
    .clear-button {
      background-color: #dc3545;
      color: white;
    }
 
    .clear-button:hover {
      background-color: #c82333;
    }
 
    .select-button {
      background-color: #007bff;
      color: white;
    }
 
    .select-button:hover {
      background-color: #0056b3;
    }
 
    .public-key-display {
      margin-top: 15px;
      padding: 10px;
      background-color: #e9ecef;
      border-radius: 4px;
    }
 
    .public-key-display p {
      margin: 0 0 5px 0;
    }
 
    .public-key-display code {
      display: block;
      word-break: break-all;
      font-family: monospace;
      font-size: 12px;
    }
 
    .blog-input {
      width: 100%;
      padding: 10px;
      font-size: 14px;
      border: 1px solid #ddd;
      border-radius: 4px;
      resize: vertical;
    }
 
    .create-button {
      width: 100%;
      padding: 12px;
      font-size: 18px;
      background-color: #28a745;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
 
    .create-button:hover:not(:disabled) {
      background-color: #218838;
    }
 
    .create-button:disabled {
      background-color: #6c757d;
      cursor: not-allowed;
    }
 
    .error-message {
      margin-top: 15px;
      padding: 15px;
      background-color: #f8d7da;
      color: #721c24;
      border-radius: 4px;
    }
 
    .success-section {
      margin-top: 20px;
      padding: 20px;
      background-color: #d4edda;
      border-radius: 8px;
    }
 
    .success-section h3 {
      margin-top: 0;
      color: #155724;
    }
 
    .entry-details {
      background-color: #fff;
      padding: 15px;
      border-radius: 4px;
      margin-top: 10px;
    }
 
    .entry-details p {
      margin: 8px 0;
      word-break: break-all;
    }
 
    .entry-details code {
      background-color: #e9ecef;
      padding: 2px 4px;
      border-radius: 3px;
      font-family: monospace;
      font-size: 12px;
    }
 
    .entries-section {
      margin-top: 30px;
      padding: 20px;
      background-color: #f9f9f9;
      border-radius: 8px;
    }
 
    .entries-section h3 {
      margin-top: 0;
      margin-bottom: 15px;
      color: #333;
    }
 
    .entries-list {
      display: grid;
      gap: 10px;
    }
 
    .entry-item {
      background-color: #fff;
      padding: 10px;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
    }
 
    .entry-item p {
      margin: 5px 0;
      font-size: 14px;
    }
 
    .small-code {
      font-size: 11px !important;
      word-break: break-all;
    }
 
    .entry-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 15px;
    }
 
    .entry-info {
      flex: 1;
    }
 
    .entry-info p {
      margin: 5px 0;
      font-size: 14px;
    }
 
    .entry-actions {
      flex-shrink: 0;
    }
 
    .preview-entry-button {
      padding: 6px 12px;
      background-color: #6c757d;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
      transition: background-color 0.2s;
    }
 
    .preview-entry-button:hover:not(:disabled) {
      background-color: #5a6268;
    }
 
    .preview-entry-button:disabled {
      opacity: 0.6;
      cursor: not-allowed;
    }
 
    .entry-preview-section {
      margin-top: 15px;
      padding: 15px;
      background-color: #f5f5f5;
      border-radius: 4px;
    }
 
    .entry-preview-controls {
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 14px;
    }
 
    .entry-preview-controls .preview-type-select {
      padding: 4px 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
    }
 
    .entry-preview-controls .detected-type {
      color: #666;
      font-style: italic;
      font-size: 12px;
    }
 
    .entry-preview {
      padding: 10px;
      background-color: #fff;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      max-height: 200px;
      overflow-y: auto;
      font-size: 14px;
    }
 
    .entry-preview pre {
      margin: 0;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
 
    .entry-preview code {
      display: block;
      font-family: monospace;
      word-break: break-all;
    }
 
    .entry-preview img {
      max-width: 100%;
      height: auto;
    }
 
    .entry-preview.preview-hex code, 
    .entry-preview.preview-base64 code {
      font-size: 12px;
      line-height: 1.4;
    }
  `]
})
export class DisotEntryComponent implements OnInit {
  @Input() contentHash: ContentHash | null = null;
  @Output() entryCreated = new EventEmitter<DisotEntry>();
 
  selectedType = DisotEntryType.DOCUMENT;
  privateKey = '';
  publicKey = '';
  blogPostContent = '';
  isCreating = false;
  errorMessage = '';
  createdEntry: DisotEntry | null = null;
  previousEntries: DisotEntry[] = [];
  showContentModal = false;
  showAuthorModal = false;
  showPreviousVersionModal = false;
  selectedAuthor: string | null = null;
  selectedPreviousVersion: string | null = null;
  entryPreviews = new Map<string, {
    previewData: string | null;
    previewType: 'text' | 'json' | 'hex' | 'base64' | 'image' | null;
    detectedType?: string;
    isLoading?: boolean;
  }>();
 
  entryTypes = [
    DisotEntryType.BLOG_POST,
    DisotEntryType.DOCUMENT,
    DisotEntryType.IMAGE,
    DisotEntryType.SIGNATURE
  ];
 
  constructor(
    private disotService: DisotService,
    private signatureService: SignatureService,
    private casService: CasService
  ) {}
 
  ngOnInit(): void {
    this.loadPreviousEntries();
  }
 
  async generateKeyPair(): Promise<void> {
    try {
      const keyPair = await this.signatureService.generateKeyPair();
      this.privateKey = keyPair.privateKey;
      this.publicKey = keyPair.publicKey;
      this.errorMessage = '';
    } catch (error) {
      this.errorMessage = 'Failed to generate key pair';
    }
  }
 
  async createEntry(): Promise<void> {
    if (!this.privateKey) {
      this.errorMessage = 'Please enter or generate a private key';
      return;
    }
 
    // For blog posts, we need to create the content first
    if (this.selectedType === DisotEntryType.BLOG_POST) {
      Iif (!this.blogPostContent.trim()) {
        this.errorMessage = 'Please enter blog post content';
        return;
      }
      // Blog posts don't need existing content, they create their own
    } else {
      // Other types need existing content
      if (!this.contentHash) {
        this.errorMessage = 'Please select content first';
        return;
      }
    }
 
    this.isCreating = true;
    this.errorMessage = '';
 
    try {
      let hashToUse = this.contentHash;
      
      // For blog posts, create the content first
      if (this.selectedType === DisotEntryType.BLOG_POST) {
        const blogData = {
          blogPost: this.blogPostContent
        };
        const jsonContent = JSON.stringify(blogData);
        const contentData = new TextEncoder().encode(jsonContent);
        
        // Store the blog post content
        hashToUse = await this.casService.store({ data: contentData });
      }
 
      Iif (!hashToUse) {
        throw new Error('No content hash available');
      }
 
      // Build metadata with author and previous version if provided
      const metadata: Record<string, any> = {};
      if (this.selectedAuthor) {
        metadata['author'] = this.selectedAuthor;
      }
      if (this.selectedPreviousVersion) {
        metadata['previousVersion'] = this.selectedPreviousVersion;
      }
 
      this.createdEntry = await this.disotService.createEntry(
        hashToUse,
        this.selectedType,
        this.privateKey,
        metadata
      );
      this.entryCreated.emit(this.createdEntry);
      
      // Reload previous entries
      await this.loadPreviousEntries();
    } catch (error) {
      this.errorMessage = `Failed to create entry: ${error instanceof Error ? error.message : 'Unknown error'}`;
      this.createdEntry = null;
    } finally {
      this.isCreating = false;
    }
  }
 
  formatEntryType(type: DisotEntryType): string {
    return type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
  }
 
  clearContent(): void {
    this.contentHash = null;
  }
 
  selectContent(): void {
    // Show content selection modal
    this.showContentModal = true;
  }
 
  onContentSelected(hash: ContentHash): void {
    this.contentHash = hash;
    this.showContentModal = false;
  }
 
  selectAuthor(): void {
    this.showAuthorModal = true;
  }
 
  onAuthorSelected(hash: ContentHash): void {
    // For now, we'll use the hash value as the author ID
    // In a real implementation, you might want to look up the entry ID
    this.selectedAuthor = hash.value;
    this.showAuthorModal = false;
  }
 
  clearAuthor(): void {
    this.selectedAuthor = null;
  }
 
  selectPreviousVersion(): void {
    this.showPreviousVersionModal = true;
  }
 
  onPreviousVersionSelected(hash: ContentHash): void {
    // For now, we'll use the hash value as the previous version ID
    // In a real implementation, you might want to look up the entry ID
    this.selectedPreviousVersion = hash.value;
    this.showPreviousVersionModal = false;
  }
 
  clearPreviousVersion(): void {
    this.selectedPreviousVersion = null;
  }
 
  async loadPreviousEntries(): Promise<void> {
    try {
      this.previousEntries = await this.disotService.listEntries();
    } catch (error) {
      console.error('Failed to load previous entries:', error);
    }
  }
 
  getEntryPreview(entryId: string) {
    return this.entryPreviews.get(entryId);
  }
 
  async toggleEntryPreview(entry: DisotEntry): Promise<void> {
    const preview = this.entryPreviews.get(entry.id);
    
    if (preview?.previewData) {
      // Hide preview
      this.entryPreviews.delete(entry.id);
    } else {
      // Load preview
      await this.loadEntryPreview(entry);
    }
  }
 
  async loadEntryPreview(entry: DisotEntry): Promise<void> {
    const preview = this.entryPreviews.get(entry.id) || {
      previewData: null,
      previewType: null,
      isLoading: false
    };
 
    Iif (preview.isLoading) return;
    
    preview.isLoading = true;
    this.entryPreviews.set(entry.id, preview);
 
    try {
      const content = await this.casService.retrieve(entry.contentHash);
      
      // Detect content type
      const detectedType = this.detectContentType(content.data);
      preview.detectedType = detectedType;
      
      // Set initial preview type based on detection
      preview.previewType = this.getInitialPreviewType(detectedType, content.data);
      
      // Generate preview based on type
      this.updateEntryPreviewData(entry.id, content.data);
    } catch (error) {
      console.error('Failed to preview entry content:', error);
      preview.previewData = 'Failed to load content';
      preview.previewType = 'text';
    } finally {
      preview.isLoading = false;
      this.entryPreviews.set(entry.id, preview);
    }
  }
 
  private detectContentType(data: Uint8Array): string {
    // Check for common file signatures
    Iif (data.length >= 4) {
      const header = Array.from(data.slice(0, 4)).map(b => b.toString(16).padStart(2, '0')).join('');
      
      // PNG
      Iif (header === '89504e47') return 'image/png';
      // JPEG
      Iif (header.startsWith('ffd8ff')) return 'image/jpeg';
      // GIF
      Iif (header.startsWith('47494638')) return 'image/gif';
      // PDF
      Iif (header === '25504446') return 'application/pdf';
    }
    
    // Try to decode as text
    try {
      const text = new TextDecoder('utf-8', { fatal: true }).decode(data.slice(0, 1000));
      
      // Check if it's JSON
      try {
        JSON.parse(text);
        return 'application/json';
      } catch {
        // Not JSON, but is text
        return 'text/plain';
      }
    } catch {
      // Not valid UTF-8, treat as binary
      return 'application/octet-stream';
    }
  }
 
  private getInitialPreviewType(detectedType: string, data: Uint8Array): 'text' | 'json' | 'hex' | 'base64' | 'image' {
    Iif (detectedType.startsWith('image/')) return 'image';
    Iif (detectedType === 'application/json') return 'json';
    Iif (detectedType === 'text/plain') return 'text';
    
    // For binary data, default to hex if small, base64 if larger
    return data.length <= 256 ? 'hex' : 'base64';
  }
 
  updateEntryPreview(entry: DisotEntry): void {
    const preview = this.entryPreviews.get(entry.id);
    Iif (!preview?.previewData) return;
    
    this.casService.retrieve(entry.contentHash).then(content => {
      this.updateEntryPreviewData(entry.id, content.data);
    }).catch(error => {
      console.error('Failed to update entry preview:', error);
    });
  }
 
  private updateEntryPreviewData(entryId: string, data: Uint8Array): void {
    const preview = this.entryPreviews.get(entryId);
    Iif (!preview) return;
 
    const maxSize = 1000;
    
    switch (preview.previewType) {
      case 'text':
        try {
          const text = new TextDecoder().decode(data);
          preview.previewData = text.length > maxSize 
            ? text.substring(0, maxSize) + '...' 
            : text;
        } catch {
          preview.previewData = 'Unable to decode as text';
        }
        break;
        
      case 'json':
        try {
          const text = new TextDecoder().decode(data);
          const json = JSON.parse(text);
          preview.previewData = JSON.stringify(json, null, 2);
          Iif (preview.previewData.length > maxSize) {
            preview.previewData = preview.previewData.substring(0, maxSize) + '...';
          }
        } catch {
          preview.previewData = 'Invalid JSON';
        }
        break;
        
      case 'hex':
        const hexBytes = Math.min(data.length, 256);
        preview.previewData = Array.from(data.slice(0, hexBytes))
          .map(b => b.toString(16).padStart(2, '0'))
          .join(' ')
          .toUpperCase();
        Iif (data.length > hexBytes) {
          preview.previewData += ' ...';
        }
        break;
        
      case 'base64':
        const base64Bytes = Math.min(data.length, 1000);
        preview.previewData = btoa(String.fromCharCode(...data.slice(0, base64Bytes)));
        Iif (data.length > base64Bytes) {
          preview.previewData += '...';
        }
        break;
        
      case 'image':
        // Create data URL for image
        const blob = new Blob([data]);
        const reader = new FileReader();
        reader.onload = () => {
          preview.previewData = reader.result as string;
          this.entryPreviews.set(entryId, preview);
        };
        reader.readAsDataURL(blob);
        return; // Don't set the preview here, it will be set in the FileReader callback
    }
    
    this.entryPreviews.set(entryId, preview);
  }
}