Files
Pigmento/js/eingabe.js

78 lines
2.3 KiB
JavaScript

import { hexToHsl, hslToHex, hslToRgb, rgbToHsl } from './converter.js';
import { state } from './app.js';
function hslToDisplay({ h, s, l }) { return h + ', ' + s + '%, ' + l + '%'; }
function rgbToDisplay({ r, g, b }) { return r + ', ' + g + ', ' + b; }
function parseRgb(str) {
const parts = str.replace(/[^\d,]/g, '').split(',').map(Number);
if (parts.length !== 3 || parts.some(isNaN)) return null;
const [r, g, b] = parts;
if ([r, g, b].some(v => v < 0 || v > 255)) return null;
return { r, g, b };
}
function parseHsl(str) {
const parts = str.replace(/[^\d,]/g, '').split(',').map(Number);
if (parts.length !== 3 || parts.some(isNaN)) return null;
const [h, s, l] = parts;
if (h < 0 || h > 360 || s < 0 || s > 100 || l < 0 || l > 100) return null;
return { h, s, l };
}
function updateUI(hsl) {
const hex = hslToHex(hsl);
const rgb = hslToRgb(hsl);
document.getElementById('eingabe-preview').style.background = hex;
document.getElementById('eingabe-hex').value = hex;
document.getElementById('eingabe-rgb').value = rgbToDisplay(rgb);
document.getElementById('eingabe-hsl').value = hslToDisplay(hsl);
}
export function initEingabe(onSaveFavorit, onSaveSchema) {
const hexInput = document.getElementById('eingabe-hex');
const rgbInput = document.getElementById('eingabe-rgb');
const hslInput = document.getElementById('eingabe-hsl');
hexInput.addEventListener('input', () => {
const val = hexInput.value.trim();
if (/^#[0-9a-fA-F]{6}$/.test(val)) {
const hsl = hexToHsl(val);
state.setColor(hsl);
}
});
rgbInput.addEventListener('input', () => {
const rgb = parseRgb(rgbInput.value);
if (rgb) {
const hsl = rgbToHsl(rgb);
state.setColor(hsl);
}
});
hslInput.addEventListener('input', () => {
const hsl = parseHsl(hslInput.value);
if (hsl) {
state.setColor(hsl);
}
});
document.addEventListener('colorChanged', () => {
if (document.activeElement !== hexInput &&
document.activeElement !== rgbInput &&
document.activeElement !== hslInput) {
updateUI(state.color);
}
});
document.getElementById('eingabe-fav-btn').addEventListener('click', () => {
onSaveFavorit(state.color);
});
document.getElementById('eingabe-schema-btn').addEventListener('click', () => {
onSaveSchema(state.color);
});
updateUI(state.color);
}