+page.svelte 13.7 KB
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
<script>
  import { onMount } from 'svelte';
  import * as d3 from 'd3';

  let container;
  let data = $state([]);
  let width = $state(800);
  let height = $state(600);
  let searchQuery = $state('');
  let searchResults = $state([]);
  let selectedEntity = $state(null);
  let circlesSelection = null;
  let nodesData = null;

  onMount(async () => {
    // Load CSV data
    const response = await fetch('/bubbles.csv');
    const text = await response.text();
    data = d3.csvParse(text, d => ({
      entidad: +d.entidad,
      sueldos: +d.sueldos,
      prop: +d.prop
    }));

    // Set dimensions based on container
    const rect = container.getBoundingClientRect();
    width = rect.width;
    height = rect.height || 600;

    createVisualization();

    // Handle resize
    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
        width = entry.contentRect.width;
        height = entry.contentRect.height || 600;
        createVisualization();
      }
    });
    resizeObserver.observe(container);

    return () => resizeObserver.disconnect();
  });

  function handleSearch(e) {
    const query = e.target.value;
    searchQuery = query;

    if (query.length >= 1) {
      // Search by entity code
      searchResults = data
        .filter(d => d.entidad.toString().includes(query))
        .slice(0, 8);
    } else {
      searchResults = [];
      clearHighlight();
    }
  }

  function selectEntity(entity) {
    selectedEntity = entity;
    searchQuery = entity.entidad.toString();
    searchResults = [];
    highlightEntity(entity.entidad);
  }

  function highlightEntity(entidadId) {
    if (!circlesSelection) return;

    circlesSelection
      .transition()
      .duration(300)
      .attr('opacity', d => d.entidad === entidadId ? 1 : 0.15)
      .attr('stroke', d => d.entidad === entidadId ? '#fff' : 'rgba(255,255,255,0.05)')
      .attr('stroke-width', d => d.entidad === entidadId ? 3 : 0.5);

    // Add pulse animation to selected
    const selected = circlesSelection.filter(d => d.entidad === entidadId);
    selected
      .classed('pulse', true);
  }

  function clearHighlight() {
    selectedEntity = null;
    searchQuery = '';
    searchResults = [];

    if (!circlesSelection) return;

    circlesSelection
      .classed('pulse', false)
      .transition()
      .duration(300)
      .attr('opacity', 0.9)
      .attr('stroke', 'rgba(255,255,255,0.15)')
      .attr('stroke-width', 0.5);
  }

  function createVisualization() {
    if (!data.length || !container) return;

    // Clear previous
    d3.select(container).selectAll('*').remove();

    // Create SVG
    const svg = d3.select(container)
      .append('svg')
      .attr('width', width)
      .attr('height', height)
      .attr('viewBox', [0, 0, width, height]);

    // Scale for radius - responsive to screen size
    const minDim = Math.min(width, height);
    const maxRadius = minDim * 0.09;  // 9% del lado menor
    const minRadius = minDim * 0.007; // 0.7% del lado menor

    const radiusScale = d3.scaleSqrt()
      .domain([0, d3.max(data, d => d.prop)])
      .range([minRadius, maxRadius]);

    // Paleta cálida: amarillo banana → naranja salmón
    const colorScale = d3.scaleThreshold()
      .domain([0.001, 0.005, 0.01, 0.03, 0.05])  // 0.1%, 0.5%, 1%, 3%, 5%
      .range([
        '#5c5448',  // < 0.1%  - marrón apagado
        '#8b7355',  // 0.1-0.5% - tierra suave
        '#d4c4a8',  // 0.5-1% - beige
        '#f5e6c4',  // 1-3% - amarillo banana claro
        '#f8d4a6',  // 3-5% - durazno
        '#f4a574'   // > 5% - salmón naranja
      ]);

    // Create nodes with initial positions
    const nodes = data.map(d => ({
      ...d,
      r: radiusScale(d.prop),
      x: width / 2 + (Math.random() - 0.5) * 100,
      y: height / 2 + (Math.random() - 0.5) * 100
    }));
    nodesData = nodes;

    // Create force simulation with faster convergence
    const simulation = d3.forceSimulation(nodes)
      .force('charge', d3.forceManyBody().strength(5))
      .force('center', d3.forceCenter(width / 2, height / 2))
      .force('collision', d3.forceCollide().radius(d => d.r + 1.4).strength(1).iterations(3))
      .force('x', d3.forceX(width / 2).strength(0.1))
      .force('y', d3.forceY(height / 2).strength(0.1))
      .alphaDecay(0.05)
      .velocityDecay(0.4);

    // Pre-calculate some ticks, but leave room for visible settling
    for (let i = 0; i < 60; i++) simulation.tick();

    // Create circles
    const circles = svg.append('g')
      .selectAll('circle')
      .data(nodes)
      .join('circle')
      .attr('r', d => d.r)
      .attr('fill', d => colorScale(d.prop))
      .attr('stroke', 'rgba(255,255,255,0.15)')
      .attr('stroke-width', 0.5)
      .attr('opacity', 0.9)
      .style('cursor', 'pointer');

    // Store reference for highlighting
    circlesSelection = circles;

    // Add tooltip
    const tooltip = d3.select(container)
      .append('div')
      .attr('class', 'tooltip')
      .style('position', 'absolute')
      .style('visibility', 'hidden')
      .style('background', 'var(--theme-surface, #1a1a1a)')
      .style('border', '1px solid var(--theme-borde, #333)')
      .style('border-radius', '8px')
      .style('padding', '12px')
      .style('font-size', '13px')
      .style('color', 'var(--theme-titulo, #fff)')
      .style('box-shadow', '0 4px 12px rgba(0,0,0,0.3)')
      .style('pointer-events', 'none')
      .style('z-index', '100');

    circles
      .on('mouseover', (event, d) => {
        tooltip
          .style('visibility', 'visible')
          .html(`
            <div style="font-weight: 600; margin-bottom: 6px;">Entidad ${d.entidad}</div>
            <div style="color: var(--theme-texto, #999);">
              Sueldos: Bs ${d3.format(',.0f')(d.sueldos)}<br/>
              Proporción: ${(d.prop * 100).toFixed(2)}%
            </div>
          `);
        if (!selectedEntity) {
          d3.select(event.currentTarget)
            .attr('stroke', '#fff')
            .attr('stroke-width', 2)
            .attr('opacity', 1);
        }
      })
      .on('mousemove', (event) => {
        tooltip
          .style('left', (event.offsetX + 15) + 'px')
          .style('top', (event.offsetY - 10) + 'px');
      })
      .on('mouseout', (event, d) => {
        tooltip.style('visibility', 'hidden');
        if (!selectedEntity) {
          d3.select(event.currentTarget)
            .attr('stroke', 'rgba(255,255,255,0.15)')
            .attr('stroke-width', 0.5)
            .attr('opacity', 0.9);
        }
      })
      .on('click', (event, d) => {
        selectEntity(d);
      });

    // Add drag behavior
    circles.call(d3.drag()
      .on('start', (event, d) => {
        if (!event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
      })
      .on('drag', (event, d) => {
        d.fx = event.x;
        d.fy = event.y;
      })
      .on('end', (event, d) => {
        if (!event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
      }));

    // Update positions on each tick
    simulation.on('tick', () => {
      circles
        .attr('cx', d => d.x)
        .attr('cy', d => d.y);
    });

    // Restore highlight if there was a selection
    if (selectedEntity) {
      highlightEntity(selectedEntity.entidad);
    }
  }
</script>

<div class="page">
  <header>
    <h1>Distribución de Sueldos por Entidad</h1>
    <p class="subtitle">Visualización de partículas proporcionales al gasto en sueldos</p>
  </header>

  <div class="search-container">
    <div class="search-box">
      <svg class="search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/>
      </svg>
      <input
        type="text"
        placeholder="Buscar entidad por código..."
        value={searchQuery}
        oninput={handleSearch}
      />
      {#if searchQuery}
        <button class="clear-btn" onclick={clearHighlight}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
      {/if}
    </div>

    {#if searchResults.length > 0}
      <div class="search-dropdown">
        {#each searchResults as result}
          <button class="search-result" onclick={() => selectEntity(result)}>
            <span class="result-code">{result.entidad}</span>
            <span class="result-info">Bs {d3.format(',.0f')(result.sueldos)} · {(result.prop * 100).toFixed(2)}%</span>
          </button>
        {/each}
      </div>
    {/if}
  </div>

  {#if selectedEntity}
    <div class="selected-info">
      <span class="selected-label">Entidad {selectedEntity.entidad}</span>
      <span class="selected-value">Bs {d3.format(',.0f')(selectedEntity.sueldos)}</span>
      <span class="selected-pct">{(selectedEntity.prop * 100).toFixed(2)}% del total</span>
    </div>
  {/if}

  <div class="container" bind:this={container}></div>

  <footer>
    <div class="legend">
      <span class="legend-item"><span class="dot" style="background: #5c5448"></span> &lt;0.1%</span>
      <span class="legend-item"><span class="dot" style="background: #8b7355"></span> 0.1-0.5%</span>
      <span class="legend-item"><span class="dot" style="background: #d4c4a8"></span> 0.5-1%</span>
      <span class="legend-item"><span class="dot" style="background: #f5e6c4"></span> 1-3%</span>
      <span class="legend-item"><span class="dot" style="background: #f8d4a6"></span> 3-5%</span>
      <span class="legend-item"><span class="dot" style="background: #f4a574"></span> &gt;5%</span>
    </div>
  </footer>
</div>

<style>
  .page {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 2rem;
    background: var(--theme-fondo, #0d0d0d);
  }

  header {
    text-align: center;
    margin-bottom: 1rem;
  }

  h1 {
    font-size: 1.5rem;
    font-weight: 600;
    color: var(--theme-titulo, #fff);
    margin: 0 0 0.5rem 0;
  }

  .subtitle {
    font-size: 0.875rem;
    color: var(--theme-texto, #999);
    margin: 0;
  }

  .search-container {
    position: relative;
    width: 100%;
    max-width: 320px;
    margin-bottom: 1rem;
  }

  .search-box {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    background: var(--theme-surface, #1a1a1a);
    border: 1px solid var(--theme-borde, #333);
    border-radius: 8px;
    padding: 0.625rem 1rem;
    transition: border-color 0.2s, box-shadow 0.2s;
  }

  .search-box:focus-within {
    border-color: #f4a574;
    box-shadow: 0 0 0 3px rgba(244, 165, 116, 0.15);
  }

  .search-icon {
    color: var(--theme-texto, #999);
    opacity: 0.5;
    flex-shrink: 0;
  }

  .search-box input {
    flex: 1;
    border: none;
    background: transparent;
    color: var(--theme-titulo, #fff);
    font-size: 0.875rem;
    outline: none;
  }

  .search-box input::placeholder {
    color: var(--theme-texto, #999);
    opacity: 0.5;
  }

  .clear-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0.25rem;
    border: none;
    background: transparent;
    color: var(--theme-texto, #999);
    cursor: pointer;
    border-radius: 4px;
    transition: background 0.2s;
  }

  .clear-btn:hover {
    background: rgba(255,255,255,0.1);
  }

  .search-dropdown {
    position: absolute;
    top: calc(100% + 4px);
    left: 0;
    right: 0;
    background: var(--theme-surface, #1a1a1a);
    border: 1px solid var(--theme-borde, #333);
    border-radius: 8px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.3);
    overflow: hidden;
    z-index: 50;
  }

  .search-result {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 0.75rem 1rem;
    border: none;
    background: transparent;
    color: var(--theme-titulo, #fff);
    cursor: pointer;
    transition: background 0.15s;
    text-align: left;
  }

  .search-result:hover {
    background: rgba(255,255,255,0.05);
  }

  .result-code {
    font-family: 'DM Mono', monospace;
    font-weight: 600;
    color: #f4a574;
  }

  .result-info {
    font-size: 0.75rem;
    color: var(--theme-texto, #999);
  }

  .selected-info {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 0.75rem 1.25rem;
    background: rgba(244, 165, 116, 0.1);
    border: 1px solid rgba(244, 165, 116, 0.3);
    border-radius: 8px;
    margin-bottom: 1rem;
  }

  .selected-label {
    font-weight: 600;
    color: #f4a574;
  }

  .selected-value {
    color: var(--theme-titulo, #fff);
  }

  .selected-pct {
    font-size: 0.875rem;
    color: var(--theme-texto, #999);
  }

  .container {
    flex: 1;
    width: 100%;
    max-width: 1200px;
    min-height: 500px;
    position: relative;
    background: var(--theme-surface, #1a1a1a);
    border-radius: 12px;
    overflow: hidden;
  }

  footer {
    margin-top: 1.5rem;
    display: flex;
    justify-content: center;
  }

  .legend {
    display: flex;
    gap: 2rem;
    font-size: 0.8125rem;
    color: var(--theme-texto, #999);
  }

  .legend-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    border: 1px solid rgba(255,255,255,0.15);
  }

  /* Pulse animation for highlighted bubble */
  :global(.pulse) {
    animation: pulse 1.5s ease-in-out infinite;
  }

  @keyframes pulse {
    0%, 100% {
      filter: drop-shadow(0 0 0 rgba(255,255,255,0));
    }
    50% {
      filter: drop-shadow(0 0 12px rgba(255,255,255,0.6));
    }
  }

  @media (max-width: 640px) {
    .legend {
      flex-wrap: wrap;
      justify-content: center;
      gap: 1rem;
    }

    .selected-info {
      flex-direction: column;
      gap: 0.25rem;
      text-align: center;
    }
  }
</style>