Spaces:
Running
Running
File size: 21,817 Bytes
83b232f | 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 | // Shape definitions with formulas and parameters
const shapes = {
cube: {
name: 'Куб',
icon: 'box',
inputs: [
{ name: 'side', label: 'Сторона (a)', placeholder: 'Введите длину стороны' }
],
formulas: {
volume: 'V = a³',
area: 'S = 6a²',
lateralArea: 'S_{бок} = 4a²'
},
calculate: (vals) => {
const a = parseFloat(vals.side);
return {
volume: Math.pow(a, 3),
area: 6 * Math.pow(a, 2),
lateralArea: 4 * Math.pow(a, 2),
details: { 'Сторона': a }
};
}
},
sphere: {
name: 'Сфера',
icon: 'circle',
inputs: [
{ name: 'radius', label: 'Радиус (r)', placeholder: 'Введите радиус' }
],
formulas: {
volume: 'V = (4/3)πr³',
area: 'S = 4πr²',
diameter: 'd = 2r'
},
calculate: (vals) => {
const r = parseFloat(vals.radius);
return {
volume: (4/3) * Math.PI * Math.pow(r, 3),
area: 4 * Math.PI * Math.pow(r, 2),
diameter: 2 * r,
details: { 'Радиус': r, 'Диаметр': 2*r }
};
}
},
cylinder: {
name: 'Цилиндр',
icon: 'cylinder',
inputs: [
{ name: 'radius', label: 'Радиус основания (r)', placeholder: 'Введите радиус' },
{ name: 'height', label: 'Высота (h)', placeholder: 'Введите высоту' }
],
formulas: {
volume: 'V = πr²h',
area: 'S = 2πr(r + h)',
lateralArea: 'S_{бок} = 2πrh'
},
calculate: (vals) => {
const r = parseFloat(vals.radius);
const h = parseFloat(vals.height);
return {
volume: Math.PI * Math.pow(r, 2) * h,
area: 2 * Math.PI * r * (r + h),
lateralArea: 2 * Math.PI * r * h,
baseArea: Math.PI * Math.pow(r, 2),
details: { 'Радиус': r, 'Высота': h }
};
}
},
cone: {
name: 'Конус',
icon: 'triangle',
inputs: [
{ name: 'radius', label: 'Радиус основания (r)', placeholder: 'Введите радиус' },
{ name: 'height', label: 'Высота (h)', placeholder: 'Введите высоту' }
],
formulas: {
volume: 'V = (1/3)πr²h',
area: 'S = πr(r + l), где l = √(r² + h²)',
lateralArea: 'S_{бок} = πrl'
},
calculate: (vals) => {
const r = parseFloat(vals.radius);
const h = parseFloat(vals.height);
const l = Math.sqrt(Math.pow(r, 2) + Math.pow(h, 2));
return {
volume: (1/3) * Math.PI * Math.pow(r, 2) * h,
area: Math.PI * r * (r + l),
lateralArea: Math.PI * r * l,
slantHeight: l,
details: { 'Радиус': r, 'Высота': h, 'Образующая': l }
};
}
},
pyramid: {
name: 'Пирамида',
icon: 'pyramid',
inputs: [
{ name: 'baseLength', label: 'Сторона основания (a)', placeholder: 'Введите сторону основания' },
{ name: 'height', label: 'Высота (h)', placeholder: 'Введите высоту' }
],
formulas: {
volume: 'V = (1/3)a²h',
area: 'S = a² + 2a√((a/2)² + h²)',
baseArea: 'S_{осн} = a²'
},
calculate: (vals) => {
const a = parseFloat(vals.baseLength);
const h = parseFloat(vals.height);
const baseArea = Math.pow(a, 2);
const apothem = Math.sqrt(Math.pow(a/2, 2) + Math.pow(h, 2));
return {
volume: (1/3) * baseArea * h,
area: baseArea + 2 * a * apothem,
baseArea: baseArea,
apothem: apothem,
details: { 'Сторона основания': a, 'Высота': h }
};
}
},
rectangular: {
name: 'Прямоугольный параллелепипед',
icon: 'square',
inputs: [
{ name: 'length', label: 'Длина (a)', placeholder: 'Введите длину' },
{ name: 'width', label: 'Ширина (b)', placeholder: 'Введите ширину' },
{ name: 'height', label: 'Высота (c)', placeholder: 'Введите высоту' }
],
formulas: {
volume: 'V = a × b × c',
area: 'S = 2(ab + bc + ac)',
diagonal: 'd = √(a² + b² + c²)'
},
calculate: (vals) => {
const a = parseFloat(vals.length);
const b = parseFloat(vals.width);
const c = parseFloat(vals.height);
return {
volume: a * b * c,
area: 2 * (a*b + b*c + a*c),
diagonal: Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2) + Math.pow(c, 2)),
details: { 'Длина': a, 'Ширина': b, 'Высота': c }
};
}
},
torus: {
name: 'Тор (бублик)',
icon: 'donut',
inputs: [
{ name: 'majorRadius', label: 'Большой радиус (R)', placeholder: 'Радиус от центра до центра трубы' },
{ name: 'minorRadius', label: 'Малый радиус (r)', placeholder: 'Радиус сечения трубы' }
],
formulas: {
volume: 'V = 2π²Rr²',
area: 'S = 4π²Rr',
lateralArea: 'Нет боковой поверхности'
},
calculate: (vals) => {
const R = parseFloat(vals.majorRadius);
const r = parseFloat(vals.minorRadius);
return {
volume: 2 * Math.pow(Math.PI, 2) * R * Math.pow(r, 2),
area: 4 * Math.pow(Math.PI, 2) * R * r,
details: { 'Большой радиус': R, 'Малый радиус': r }
};
}
},
ellipsoid: {
name: 'Эллипсоид',
icon: 'oval',
inputs: [
{ name: 'axisA', label: 'Полуось a', placeholder: 'Введите полуось a' },
{ name: 'axisB', label: 'Полуось b', placeholder: 'Введите полуось b' },
{ name: 'axisC', label: 'Полуось c', placeholder: 'Введите полуось c' }
],
formulas: {
volume: 'V = (4/3)πabc',
area: 'S ≈ 4π[((ab)^1.6 + (ac)^1.6 + (bc)^1.6)/3]^(1/1.6)',
lateralArea: 'Нет отдельной боковой поверхности'
},
calculate: (vals) => {
const a = parseFloat(vals.axisA);
const b = parseFloat(vals.axisB);
const c = parseFloat(vals.axisC);
// Approximation for surface area of ellipsoid
const p = 1.6;
const area = 4 * Math.PI * Math.pow((Math.pow(a*b, p) + Math.pow(a*c, p) + Math.pow(b*c, p))/3, 1/p);
return {
volume: (4/3) * Math.PI * a * b * c,
area: area,
details: { 'Полуось a': a, 'Полуось b': b, 'Полуось c': c }
};
}
}
};
// Conversion factors to meters (base unit)
const toMeters = {
mm: 0.001,
cm: 0.01,
m: 1,
km: 1000,
in: 0.0254,
ft: 0.3048,
yd: 0.9144
};
const fromMeters = {
mm3: 1000000000,
cm3: 1000000,
m3: 1,
km3: 0.000000001,
in3: 61023.744095,
ft3: 35.314667,
yd3: 1.307951,
l: 1000,
gal: 264.172,
mm2: 1000000,
cm2: 10000,
m2: 1,
km2: 0.000001,
in2: 1550.0031,
ft2: 10.76391,
yd2: 1.19599
};
let currentShape = 'cube';
let calculationHistory = [];
// Initialize
document.addEventListener('DOMContentLoaded', () => {
renderShapeList();
selectShape('cube');
loadHistory();
// Event listeners for units
document.getElementById('inputUnit').addEventListener('change', calculate);
document.getElementById('outputUnit').addEventListener('change', calculate);
});
function renderShapeList() {
const container = document.getElementById('shapeList');
container.innerHTML = Object.entries(shapes).map(([key, shape]) => `
<div class="shape-card ${key === currentShape ? 'active' : ''} rounded-lg p-2 sm:p-3 border border-slate-700/50 bg-slate-800/30 flex items-center gap-2 sm:gap-3 whitespace-nowrap lg:whitespace-normal flex-shrink-0 lg:flex-shrink-1" onclick="selectShape('${key}')" data-shape="${key}">
<div class="w-6 h-6 sm:w-8 sm:h-8 rounded-md bg-gradient-to-br from-blue-500/20 to-purple-500/20 flex items-center justify-center flex-shrink-0">
<i data-lucide="${shape.icon}" class="w-3 h-3 sm:w-4 sm:h-4 text-blue-400"></i>
</div>
<span class="text-xs sm:text-sm font-medium text-gray-200">${shape.name}</span>
</div>
`).join('');
lucide.createIcons();
}
function selectShape(shapeKey) {
currentShape = shapeKey;
const shape = shapes[shapeKey];
// Update active state in list
document.querySelectorAll('.shape-card').forEach(card => {
card.classList.toggle('active', card.dataset.shape === shapeKey);
});
// Update header
document.getElementById('currentShapeName').textContent = shape.name;
// Render inputs
const inputContainer = document.getElementById('inputContainer');
inputContainer.innerHTML = shape.inputs.map(input => `
<div class="space-y-1.5 sm:space-y-2">
<label class="text-xs sm:text-sm font-medium text-gray-300 flex items-center justify-between">
<span class="truncate mr-2">${input.label}</span>
<span class="text-[10px] sm:text-xs text-slate-500 mono flex-shrink-0" id="unit-label-${input.name}"></span>
</label>
<input type="number"
id="input-${input.name}"
placeholder="${input.placeholder}"
class="input-field w-full px-3 sm:px-4 py-2.5 sm:py-3 rounded-lg text-white placeholder-gray-500 mono text-sm min-h-[44px]"
step="any"
min="0"
inputmode="decimal"
>
</div>
`).join('');
// Display formulas
displayFormulas(shape);
// Clear results
clearResults();
// Add input listeners
shape.inputs.forEach(input => {
document.getElementById(`input-${input.name}`).addEventListener('input', debounce(calculate, 300));
});
updateUnitLabels();
}
function displayFormulas(shape) {
const formulaDisplay = document.getElementById('formulaDisplay');
if (!shape || !shape.formulas) {
formulaDisplay.innerHTML = '<div class="text-gray-500 text-sm">Формулы недоступны</div>';
return;
}
formulaDisplay.innerHTML = Object.entries(shape.formulas).map(([key, formula]) => {
const label = getFormulaLabel(key);
const safeFormula = formula || '—';
return `
<div class="flex items-start gap-2">
<span class="text-blue-400 mono text-xs mt-1">•</span>
<div>
<span class="text-gray-400 text-xs uppercase tracking-wider">${label}:</span>
<div class="text-gray-200 mono text-xs sm:text-sm break-all">${safeFormula}</div>
</div>
</div>
`;
}).join('');
}
function getFormulaLabel(key) {
const labels = {
volume: 'Объём',
area: 'Площадь поверхности',
lateralArea: 'Боковая поверхность',
baseArea: 'Площадь основания',
diameter: 'Диаметр',
diagonal: 'Диагональ',
slantHeight: 'Образующая',
apothem: 'Апофема'
};
return labels[key] || key || 'Формула';
}
function getFormulaName(key) {
const names = {
volume: 'V',
area: 'S',
lateralArea: 'S_{бок}',
baseArea: 'S_{осн}',
diameter: 'd',
diagonal: 'd',
slantHeight: 'l',
apothem: 'a'
};
return names[key] || '';
}
function calculate() {
const shape = shapes[currentShape];
const inputs = {};
// Get input values
for (let input of shape.inputs) {
const val = document.getElementById(`input-${input.name}`).value;
if (!val || isNaN(val) || parseFloat(val) <= 0) {
return; // Don't calculate if invalid
}
inputs[input.name] = parseFloat(val);
}
// Convert to meters first (base unit)
const inputUnit = document.getElementById('inputUnit').value;
const factor = toMeters[inputUnit];
const meterInputs = {};
for (let [key, val] of Object.entries(inputs)) {
meterInputs[key] = val * factor;
}
// Calculate in meters
const result = shape.calculate(meterInputs);
// Convert to output unit
const outputUnit = document.getElementById('outputUnit').value;
const outputFactor = fromMeters[outputUnit];
const displayVolume = result.volume * outputFactor;
const displayArea = result.area * outputFactor;
// Display results
displayResults(displayVolume, displayArea, result, outputUnit);
// Add to history
addToHistory(shape.name, displayVolume, displayArea, outputUnit);
}
function displayResults(volume, area, details, unit) {
// Determine display unit text
const unitText = getUnitDisplayName(unit);
const areaUnitText = unitText.replace('³', '²').replace('л', 'л²').replace('gal', 'gal²');
document.getElementById('volumeResult').textContent = formatNumber(volume);
document.getElementById('volumeUnit').textContent = unitText;
document.getElementById('areaResult').textContent = formatNumber(area);
document.getElementById('areaUnit').textContent = areaUnitText;
// Additional results
const additionalContainer = document.getElementById('additionalResults');
const outputUnit = document.getElementById('outputUnit').value;
const factor = fromMeters[outputUnit];
let additionalHTML = '';
if (details.lateralArea) {
additionalHTML += createResultCard('Боковая поверхность', details.lateralArea * factor, areaUnitText);
}
if (details.baseArea) {
additionalHTML += createResultCard('Площадь основания', details.baseArea * factor, areaUnitText);
}
if (details.slantHeight) {
const lenFactor = factor / Math.pow(factor, 1/3); // Rough conversion for length
additionalHTML += createResultCard('Образующая', details.slantHeight * lenFactor, getUnitDisplayName(outputUnit).replace('³', '').replace('²', ''));
}
if (details.diagonal) {
const lenFactor = factor / Math.pow(factor, 1/3);
additionalHTML += createResultCard('Диагональ', details.diagonal * lenFactor, getUnitDisplayName(outputUnit).replace('³', '').replace('²', ''));
}
if (details.diameter) {
const lenFactor = factor / Math.pow(factor, 1/3);
additionalHTML += createResultCard('Диаметр', details.diameter * lenFactor, getUnitDisplayName(outputUnit).replace('³', '').replace('²', ''));
}
additionalContainer.innerHTML = additionalHTML;
}
function createResultCard(label, value, unit) {
return `
<div class="bg-slate-800/30 rounded-lg p-2.5 sm:p-3 border border-slate-700/50">
<div class="text-[10px] sm:text-xs text-gray-400 mb-0.5 sm:mb-1 truncate">${label}</div>
<div class="text-base sm:text-lg font-semibold text-gray-200 mono break-all">${formatNumber(value)}</div>
<div class="text-[10px] sm:text-xs text-slate-600">${unit}</div>
</div>
`;
}
function getUnitDisplayName(unit) {
const names = {
mm3: 'мм³', cm3: 'см³', m3: 'м³', km3: 'км³',
in3: 'in³', ft3: 'ft³', yd3: 'yd³',
l: 'л', gal: 'gal',
mm2: 'мм²', cm2: 'см²', m2: 'м²', km2: 'км²',
in2: 'in²', ft2: 'ft²', yd2: 'yd²'
};
return names[unit] || unit;
}
function formatNumber(num) {
if (num === 0) return '0';
if (num < 0.001 || num > 1000000) {
return num.toExponential(4);
}
return num.toLocaleString('ru-RU', { maximumFractionDigits: 4 });
}
function clearInputs() {
const inputs = document.querySelectorAll('input[type="number"]');
inputs.forEach(input => input.value = '');
clearResults();
}
function clearResults() {
document.getElementById('volumeResult').textContent = '0';
document.getElementById('areaResult').textContent = '0';
document.getElementById('additionalResults').innerHTML = '';
}
function updateUnitLabels() {
const unit = document.getElementById('inputUnit').value;
const labels = { mm: 'мм', cm: 'см', m: 'м', km: 'км', in: 'in', ft: 'ft', yd: 'yd' };
document.querySelectorAll('[id^="unit-label-"]').forEach(el => {
el.textContent = labels[unit];
});
}
function addToHistory(shapeName, volume, area, unit) {
const historyItem = {
shape: shapeName,
volume: volume,
area: area,
unit: unit,
timestamp: new Date().toLocaleTimeString('ru-RU')
};
calculationHistory.unshift(historyItem);
if (calculationHistory.length > 10) calculationHistory.pop();
renderHistory();
saveHistory();
}
function renderHistory() {
const container = document.getElementById('historyList');
if (calculationHistory.length === 0) {
container.innerHTML = '<p class="text-gray-500 text-sm text-center py-4">История пуста</p>';
return;
}
container.innerHTML = calculationHistory.map((item, index) => `
<div class="flex items-center justify-between p-3 bg-gradient-to-r from-slate-900/60 to-purple-900/10 rounded-lg border border-purple-500/20 text-sm crystal-glow hover:border-purple-500/40 transition-all hover:scale-[1.01]">
<div class="flex items-center gap-3">
<span class="text-xs text-purple-400/50 mono">${item.timestamp}</span>
<span class="font-medium text-purple-200">${item.shape}</span>
</div>
<div class="text-right mono text-xs">
<div class="text-violet-300">V: ${formatNumber(item.volume)} ${getUnitDisplayName(item.unit)}</div>
<div class="text-indigo-300">S: ${formatNumber(item.area)} ${getUnitDisplayName(item.unit).replace('³', '²')}</div>
</div>
</div>
`).join('');
}
function clearHistory() {
calculationHistory = [];
renderHistory();
localStorage.removeItem('geoCalcHistory');
}
function saveHistory() {
localStorage.setItem('geoCalcHistory', JSON.stringify(calculationHistory));
}
function loadHistory() {
const saved = localStorage.getItem('geoCalcHistory');
if (saved) {
calculationHistory = JSON.parse(saved);
renderHistory();
}
}
function copyResults() {
const vol = document.getElementById('volumeResult').textContent;
const area = document.getElementById('areaResult').textContent;
const volUnit = document.getElementById('volumeUnit').textContent;
const areaUnit = document.getElementById('areaUnit').textContent;
const text = `Результаты расчёта (${shapes[currentShape].name}):\nОбъём: ${vol} ${volUnit}\nПлощадь: ${area} ${areaUnit}`;
navigator.clipboard.writeText(text).then(() => {
// Show temporary notification
const btn = document.querySelector('button[onclick="copyResults()"]');
const originalHTML = btn.innerHTML;
btn.innerHTML = '<i data-lucide="check" class="w-4 h-4"></i> Скопировано!';
btn.classList.add('text-green-400');
lucide.createIcons();
setTimeout(() => {
btn.innerHTML = originalHTML;
btn.classList.remove('text-green-400');
lucide.createIcons();
}, 2000);
});
}
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
function toggleTheme() {
// Simple theme toggle (could be expanded)
document.body.classList.toggle('light-theme');
}
let formulasVisible = false;
function toggleFormulas() {
const section = document.getElementById('formulaSection');
const btn = document.getElementById('toggleFormulasBtn');
const span = btn.querySelector('span');
const icon = btn.querySelector('i');
formulasVisible = !formulasVisible;
if (formulasVisible) {
section.classList.remove('hidden');
span.textContent = 'Скрыть формулы';
icon.setAttribute('data-lucide', 'chevron-up');
} else {
section.classList.add('hidden');
span.textContent = 'Показать формулы';
icon.setAttribute('data-lucide', 'function-square');
}
lucide.createIcons();
} |