kasergey's picture
Initial DeepSite commit
83b232f verified
Raw History Blame Contribute Delete
21.8 kB
// 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();
}