All files / src/components ControlPanel.jsx

62.74% Statements 32/51
52.63% Branches 10/19
62.96% Functions 17/27
60.41% Lines 29/48

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                                                        18x                     45x   45x       3x                                           14x 14x 14x 14x     252x 252x         14x                         14x 1x 1x 1x             14x                 14x                                     84x             168x                     1x 1x               182x   126x         182x   56x                 56x                                                                                                                 98x 98x                                                                                                             70x                                    
/**
 * @fileoverview Control Panel Component for Molecular Dynamics Simulation
 * @description Provides UI controls for simulation parameters, atom selection,
 * molecule presets, force field selection, and display options.
 * @module components/ControlPanel
 */
 
import { useState } from 'react';
import { useSimulation, useSimulationDispatch } from '../context/SimulationContext';
import { useParameters } from '../context/ParametersContext';
import { ATOM_TYPES as PHYSICS_ATOM_TYPES, MOLECULE_PRESETS } from '../simulation/physics';
import { getAvailableForceFields, getForceFieldInfo } from '../simulation/forceFieldParser';
import { PRESET_CONFIGS } from '../context/simulationReducer';
import './ControlPanel.css';
 
/**
 * UI-friendly atom type representation
 * @typedef {Object} UIAtomType
 * @property {number} id - Atom type identifier
 * @property {string} name - Full element name
 * @property {string} symbol - Chemical symbol
 * @property {string} color - Display color in hex format
 */
 
/**
 * Convert physics atom types to array for UI rendering
 * @type {UIAtomType[]}
 */
const ATOM_TYPES = Object.entries(PHYSICS_ATOM_TYPES).map(([id, data]) => ({
  id: parseInt(id, 10),
  name: data.name,
  symbol: data.symbol,
  color: data.color,
}));
 
/**
 * Collapsible Section Component
 */
function CollapsibleSection({ title, icon, children, defaultOpen = false }) {
  const [isOpen, setIsOpen] = useState(defaultOpen);
  
  return (
    <div className={`collapsible-section ${isOpen ? 'open' : ''}`}>
      <button 
        className="collapsible-header"
        onClick={() => setIsOpen(!isOpen)}
        aria-expanded={isOpen}
      >
        <span className="section-icon">{icon}</span>
        <span className="section-title">{title}</span>
        <span className="chevron">{isOpen ? '▾' : '▸'}</span>
      </button>
      {isOpen && (
        <div className="collapsible-content">
          {children}
        </div>
      )}
    </div>
  );
}
 
/**
 * Control Panel Component
 * Provides UI controls for simulation parameters, atoms, and molecules
 * @returns {JSX.Element} Control panel with simulation controls
 */
function ControlPanel() {
  const simulation = useSimulation();
  const parameters = useParameters();
  const dispatch = useSimulationDispatch();
  const [selectedForceField, setSelectedForceField] = useState('');
 
  // Combine all atom types into a single categorized list
  const organicAtoms = ATOM_TYPES.filter(t => t.id <= 6);
  const metalAtoms = ATOM_TYPES.filter(t => t.id > 6);
 
  /**
   * Add a single atom at random position within canvas bounds
   */
  const handleAddAtom = (atomType) => {
    const x = Math.random() * simulation.size.x * 0.6 + simulation.size.x * 0.2;
    const y = Math.random() * simulation.size.y * 0.6 + simulation.size.y * 0.2;
    dispatch({ 
      type: 'ADD_ATOM', 
      payload: { x, y, z: 0, atomType } 
    });
  };
 
  /**
   * Load a preset molecule configuration
   * @param {string} moleculeKey - Key identifying the molecule preset
   */
  const handleLoadMolecule = (moleculeKey) => {
    const molecule = MOLECULE_PRESETS[moleculeKey];
    Eif (molecule) {
      dispatch({ 
        type: 'LOAD_MOLECULE', 
        payload: { atoms: molecule.atoms } 
      });
    }
  };
 
  const handleForceFieldChange = (event) => {
    const filename = event.target.value;
    setSelectedForceField(filename);
    if (filename) {
      const info = getForceFieldInfo(filename);
      dispatch({ type: 'SET_FORCE_FIELD', payload: { filename, info } });
    }
  };
 
  return (
    <div className="control-panel">
      <h3>⚙️ Controls</h3>
 
      {/* Quick Actions - Always visible */}
      <div className="quick-actions">
        <select
          className="quick-select"
          value=""
          onChange={(e) => {
            if (e.target.value) {
              handleAddAtom(parseInt(e.target.value, 10));
            }
          }}
          title="Add atom"
        >
          <option value="">➕ Add Atom...</option>
          <optgroup label="Elements">
            {organicAtoms.map(type => (
              <option key={type.id} value={type.id}>
                {type.symbol} - {type.name}
              </option>
            ))}
          </optgroup>
          <optgroup label="Metals">
            {metalAtoms.map(type => (
              <option key={type.id} value={type.id}>
                {type.symbol} - {type.name}
              </option>
            ))}
          </optgroup>
        </select>
 
        <select
          className="quick-select"
          value=""
          onChange={(e) => {
            Eif (e.target.value) {
              handleLoadMolecule(e.target.value);
            }
          }}
          title="Add molecule"
        >
          <option value="">🔬 Add Molecule...</option>
          <optgroup label="Common">
            {Object.entries(MOLECULE_PRESETS)
              .filter(([, mol]) => mol.category === 'common')
              .map(([key, mol]) => (
                <option key={key} value={key}>{mol.name}</option>
              ))}
          </optgroup>
          <optgroup label="Metals">
            {Object.entries(MOLECULE_PRESETS)
              .filter(([, mol]) => mol.category === 'metals')
              .map(([key, mol]) => (
                <option key={key} value={key}>{mol.name}</option>
              ))}
          </optgroup>
        </select>
      </div>
 
      {/* Preset Configurations - Compact buttons */}
      <div className="presets-row">
        {Object.entries(PRESET_CONFIGS).slice(0, 4).map(([key, preset]) => (
          <button
            key={key}
            className="preset-chip"
            onClick={() => {
              dispatch({ type: 'PUSH_UNDO' });
              dispatch({ type: 'LOAD_PRESET', payload: key });
            }}
            title={`Load ${preset.name}`}
          >
            {preset.name.split(' ')[0]}
          </button>
        ))}
      </div>
 
      {/* Temperature & Speed - Inline compact */}
      <div className="inline-controls">
        <div className="inline-control">
          <label>🌡️ Temp</label>
          <input
            type="range"
            min="0"
            max="1000"
            step="10"
            value={simulation.targetTemperature}
            onChange={(e) => dispatch({ 
              type: 'SET_TARGET_TEMPERATURE', 
              payload: parseFloat(e.target.value) 
            })}
          />
          <span className="control-value">{simulation.targetTemperature}K</span>
        </div>
        <div className="inline-control">
          <label>⚡ Speed</label>
          <input
            type="range"
            min="0.1"
            max="3"
            step="0.1"
            value={simulation.timeStepMultiplier}
            onChange={(e) => dispatch({ 
              type: 'SET_TIME_STEP_MULTIPLIER', 
              payload: parseFloat(e.target.value) 
            })}
          />
          <span className="control-value">{simulation.timeStepMultiplier.toFixed(1)}x</span>
        </div>
      </div>
 
      {/* Collapsible Advanced Options */}
      <CollapsibleSection title="Force Field" icon="⚛️" defaultOpen={false}>
        <select 
          className="full-select"
          value={selectedForceField}
          onChange={handleForceFieldChange}
        >
          <option value="">Select Force Field...</option>
          {getAvailableForceFields().map(ff => {
            const info = getForceFieldInfo(ff);
            return (
              <option key={ff} value={ff}>{info.name}</option>
            );
          })}
        </select>
        {selectedForceField && (
          <div className="force-field-info">
            <p>{getForceFieldInfo(selectedForceField).description}</p>
            <small>Elements: {getForceFieldInfo(selectedForceField).elements.join(', ')}</small>
          </div>
        )}
        {parameters.isLoaded && (
          <div className="params-loaded">✓ ReaxFF loaded</div>
        )}
      </CollapsibleSection>
 
      <CollapsibleSection title="Boundary & Display" icon="🖼️" defaultOpen={false}>
        <div className="compact-control">
          <label>Boundary</label>
          <select 
            className="compact-select"
            value={simulation.boundaryCondition}
            onChange={(e) => dispatch({ 
              type: 'SET_BOUNDARY_CONDITION', 
              payload: e.target.value 
            })}
          >
            <option value="reflective">Reflective</option>
            <option value="periodic">Periodic</option>
            <option value="open">Open</option>
          </select>
        </div>
        <div className="checkbox-row">
          <label className="mini-checkbox">
            <input
              type="checkbox"
              checked={simulation.showBondLengths}
              onChange={() => dispatch({ type: 'TOGGLE_BOND_LENGTHS' })}
            />
            Bond Lengths
          </label>
          <label className="mini-checkbox">
            <input
              type="checkbox"
              checked={!simulation.clearScreen}
              onChange={() => dispatch({ type: 'TOGGLE' })}
            />
            Trails
          </label>
        </div>
      </CollapsibleSection>
 
      <CollapsibleSection title="All Presets" icon="📋" defaultOpen={false}>
        <div className="all-presets">
          {Object.entries(PRESET_CONFIGS).map(([key, preset]) => (
            <button
              key={key}
              className="preset-btn-full"
              onClick={() => {
                dispatch({ type: 'PUSH_UNDO' });
                dispatch({ type: 'LOAD_PRESET', payload: key });
              }}
            >
              {preset.name}
            </button>
          ))}
        </div>
      </CollapsibleSection>
    </div>
  );
}
 
export default ControlPanel;