manage-your-printer/static/js/core-bundle.min.js
2025-06-04 10:03:22 +02:00

1 line
15 KiB
JavaScript

(function(window){'use strict';const MYP = window.MYP ||{};const config ={apiTimeout:30000,cacheExpiry:5 * 60 * 1000,notificationDuration:5000,debounceDelay:300,throttleDelay:100};const cache = new Map();const requestCache = new Map();const csrf ={token:null,get(){if(!this.token){const meta = document.querySelector('meta[name="csrf-token"]');this.token = meta ? meta.getAttribute('content'):'';}return this.token;},headers(){return{'X-CSRFToken':this.get(),'Content-Type':'application/json'};}};const dom ={selectors:new Map(),get(selector,parent = document){const key = `${parent === document ? 'doc':'el'}_${selector}`;if(!this.selectors.has(key)){this.selectors.set(key,parent.querySelector(selector));}return this.selectors.get(key);},getAll(selector,parent = document){return parent.querySelectorAll(selector);},clearCache(){this.selectors.clear();},create(tag,attrs ={},text = ''){const el = document.createElement(tag);Object.entries(attrs).forEach(([key,val])=>{if(key === 'class'){el.className = val;}else if(key === 'dataset'){Object.entries(val).forEach(([k,v])=>{el.dataset[k] = v;});}else{el.setAttribute(key,val);}});if(text)el.textContent = text;return el;}};const api ={pending:new Map(),async request(url,options ={}){const key = `${options.method || 'GET'}_${url}`;if(this.pending.has(key)){return this.pending.get(key);}if(!options.method || options.method === 'GET'){const cached = requestCache.get(key);if(cached && Date.now()- cached.timestamp < config.cacheExpiry){return Promise.resolve(cached.data);}}const requestOptions ={...options,headers:{...csrf.headers(),...options.headers}};const promise = fetch(url,requestOptions).then(response =>{if(!response.ok){throw new Error(`HTTP error! status:${response.status}`);}return response.json();}).then(data =>{if(!options.method || options.method === 'GET'){requestCache.set(key,{data,timestamp:Date.now()});}return data;}).finally(()=>{this.pending.delete(key);});this.pending.set(key,promise);return promise;},get(url,options ={}){return this.request(url,{...options,method:'GET'});},post(url,data,options ={}){return this.request(url,{...options,method:'POST',body:JSON.stringify(data)});},put(url,data,options ={}){return this.request(url,{...options,method:'PUT',body:JSON.stringify(data)});},delete(url,options ={}){return this.request(url,{...options,method:'DELETE'});}};const notifications ={container:null,queue:[],init(){if(this.container)return;this.container = dom.create('div',{id:'myp-notifications',class:'fixed top-4 right-4 z-50 space-y-2'});document.body.appendChild(this.container);},show(message,type = 'info',duration = config.notificationDuration){this.init();const notification = dom.create('div',{class:`notification notification-${type}glass-navbar p-4 rounded-lg shadow-lg transform translate-x-full transition-transform duration-300`,role:'alert'});const content = dom.create('div',{class:'flex items-center space-x-3'});const icon = dom.create('i',{class:`fas ${this.getIcon(type)}text-lg`});const text = dom.create('span',{class:'flex-1'},message);const close = dom.create('button',{class:'ml-4 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200','aria-label':'Close'});close.innerHTML = '&times;';close.onclick =()=> this.remove(notification);content.appendChild(icon);content.appendChild(text);content.appendChild(close);notification.appendChild(content);this.container.appendChild(notification);requestAnimationFrame(()=>{notification.classList.remove('translate-x-full');});if(duration > 0){setTimeout(()=> this.remove(notification),duration);}return notification;},remove(notification){notification.classList.add('translate-x-full');setTimeout(()=>{notification.remove();},300);},getIcon(type){const icons ={success:'fa-check-circle text-green-500',error:'fa-exclamation-circle text-red-500',warning:'fa-exclamation-triangle text-yellow-500',info:'fa-info-circle text-blue-500'};return icons[type] || icons.info;},success(message,duration){return this.show(message,'success',duration);},error(message,duration){return this.show(message,'error',duration);},warning(message,duration){return this.show(message,'warning',duration);},info(message,duration){return this.show(message,'info',duration);}};const performance ={debounce(func,delay = config.debounceDelay){let timeoutId;return function(...args){clearTimeout(timeoutId);timeoutId = setTimeout(()=> func.apply(this,args),delay);};},throttle(func,delay = config.throttleDelay){let lastCall = 0;return function(...args){const now = Date.now();if(now - lastCall >= delay){lastCall = now;return func.apply(this,args);}};},memoize(func){const cache = new Map();return function(...args){const key = JSON.stringify(args);if(cache.has(key)){return cache.get(key);}const result = func.apply(this,args);cache.set(key,result);return result;};},lazy(selector,callback){const observer = new IntersectionObserver((entries)=>{entries.forEach(entry =>{if(entry.isIntersecting){callback(entry.target);observer.unobserve(entry.target);}});});dom.getAll(selector).forEach(el => observer.observe(el));return observer;}};const storage ={set(key,value,expiry = null){const data ={value,timestamp:Date.now(),expiry};try{localStorage.setItem(`myp_${key}`,JSON.stringify(data));return true;}catch(e){console.error('Storage error:',e);return false;}},get(key){try{const item = localStorage.getItem(`myp_${key}`);if(!item)return null;const data = JSON.parse(item);if(data.expiry && Date.now()- data.timestamp > data.expiry){this.remove(key);return null;}return data.value;}catch(e){console.error('Storage error:',e);return null;}},remove(key){localStorage.removeItem(`myp_${key}`);},clear(){Object.keys(localStorage).filter(key => key.startsWith('myp_')).forEach(key => localStorage.removeItem(key));}};const events ={listeners:new Map(),on(element,event,handler,options ={}){const key = `${element}_${event}`;if(!this.listeners.has(key)){this.listeners.set(key,new Set());}this.listeners.get(key).add(handler);element.addEventListener(event,handler,options);},off(element,event,handler){const key = `${element}_${event}`;if(this.listeners.has(key)){this.listeners.get(key).delete(handler);if(this.listeners.get(key).size === 0){this.listeners.delete(key);}}element.removeEventListener(event,handler);},once(element,event,handler,options ={}){const onceHandler =(e)=>{handler(e);this.off(element,event,onceHandler);};this.on(element,event,onceHandler,options);},emit(name,detail ={}){const event = new CustomEvent(name,{detail,bubbles:true,cancelable:true});document.dispatchEvent(event);},cleanup(){this.listeners.forEach((handlers,key)=>{const [element,event] = key.split('_');handlers.forEach(handler =>{element.removeEventListener(event,handler);});});this.listeners.clear();}};const forms ={serialize(form){const data = new FormData(form);const obj ={};for(const [key,value] of data.entries()){if(obj[key]){if(!Array.isArray(obj[key])){obj[key] = [obj[key]];}obj[key].push(value);}else{obj[key] = value;}}return obj;},validate(form){const inputs = form.querySelectorAll('[required]');let valid = true;inputs.forEach(input =>{if(!input.value.trim()){input.classList.add('border-red-500');valid = false;}else{input.classList.remove('border-red-500');}});return valid;},reset(form){form.reset();form.querySelectorAll('.border-red-500').forEach(el =>{el.classList.remove('border-red-500');});}};const init =()=>{notifications.init();window.addEventListener('beforeunload',()=>{events.cleanup();dom.clearCache();});};MYP.utils ={csrf,dom,api,notifications,performance,storage,events,forms,init,config};if(document.readyState === 'loading'){document.addEventListener('DOMContentLoaded',init);}else{init();}window.MYP = MYP;})(window);(function(){"use strict";const STORAGE_KEY = 'myp-dark-mode';let darkModeToggle;const html = document.documentElement;document.addEventListener('DOMContentLoaded',initialize);function shouldUseDarkMode(){const savedMode = localStorage.getItem(STORAGE_KEY);if(savedMode !== null){return savedMode === 'true';}return window.matchMedia('(prefers-color-scheme:dark)').matches;}function setDarkMode(enable){html.classList.add('disable-transitions');if(enable){html.classList.add('dark');html.setAttribute('data-theme','dark');html.style.colorScheme = 'dark';}else{html.classList.remove('dark');html.setAttribute('data-theme','light');html.style.colorScheme = 'light';}localStorage.setItem(STORAGE_KEY,enable);updateMetaThemeColor(enable);if(darkModeToggle){updateDarkModeToggle(enable);}window.dispatchEvent(new CustomEvent('darkModeChanged',{detail:{isDark:enable,source:'dark-mode-toggle',timestamp:new Date().toISOString()}}));const eventName = enable ? 'darkModeEnabled':'darkModeDisabled';window.dispatchEvent(new CustomEvent(eventName,{detail:{timestamp:new Date().toISOString()}}));setTimeout(function(){html.classList.remove('disable-transitions');},100);console.log(`${enable ? '🌙':'☀️'}${enable ? 'Dark Mode aktiviert - Augenschonender Modus aktiv':'Light Mode aktiviert - Heller Modus aktiv'}`);}function updateMetaThemeColor(isDark){const metaTags = [ document.getElementById('metaThemeColor'),document.querySelector('meta[name="theme-color"]'),document.querySelector('meta[name="theme-color"][media="(prefers-color-scheme:light)"]'),document.querySelector('meta[name="theme-color"][media="(prefers-color-scheme:dark)"]')];const darkColor = getComputedStyle(document.documentElement).getPropertyValue('--color-bg')|| '#0f172a';const lightColor = getComputedStyle(document.documentElement).getPropertyValue('--color-bg')|| '#ffffff';metaTags.forEach(tag =>{if(tag){if(tag.getAttribute('media')=== '(prefers-color-scheme:dark)'){tag.setAttribute('content',darkColor);}else if(tag.getAttribute('media')=== '(prefers-color-scheme:light)'){tag.setAttribute('content',lightColor);}else{tag.setAttribute('content',isDark ? darkColor:lightColor);}}});}function updateDarkModeToggle(isDark){darkModeToggle.setAttribute('aria-pressed',isDark.toString());darkModeToggle.title = isDark ? "Light Mode aktivieren":"Dark Mode aktivieren";const sunIcon = darkModeToggle.querySelector('.sun-icon');const moonIcon = darkModeToggle.querySelector('.moon-icon');if(sunIcon && moonIcon){if(isDark){sunIcon.classList.add('hidden');moonIcon.classList.remove('hidden');}else{sunIcon.classList.remove('hidden');moonIcon.classList.add('hidden');}}else{const icon = darkModeToggle.querySelector('svg');if(icon){icon.classList.add('animate-spin-once');setTimeout(()=>{icon.classList.remove('animate-spin-once');},300);const pathElement = icon.querySelector('path');if(pathElement){if(isDark){pathElement.setAttribute("d","M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z");}else{pathElement.setAttribute("d","M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z");}}}}}function initialize(){darkModeToggle = document.getElementById('darkModeToggle');if(!darkModeToggle){console.log('🔧 Dark Mode Toggle nicht gefunden - erstelle automatisch einen neuen Button');createDarkModeToggle();}if(darkModeToggle){darkModeToggle.addEventListener('click',function(){const isDark = !shouldUseDarkMode();console.log(`👆 Dark Mode Toggle:Wechsel zu ${isDark ? '🌙 dunkel':'☀️ hell'}angefordert`);setDarkMode(isDark);});}document.addEventListener('keydown',function(e){if(e.ctrlKey && e.shiftKey && e.key === 'D'){const isDark = !shouldUseDarkMode();console.log(`⌨️ Tastenkombination STRG+SHIFT+D erkannt:Wechsel zu ${isDark ? '🌙 dunkel':'☀️ hell'}`);setDarkMode(isDark);e.preventDefault();}});const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme:dark)');try{darkModeMediaQuery.addEventListener('change',function(e){if(localStorage.getItem(STORAGE_KEY)=== null){console.log(`🖥️ Systemeinstellung geändert:${e.matches ? '🌙 dunkel':'☀️ hell'}`);setDarkMode(e.matches);}});}catch(error){darkModeMediaQuery.addListener(function(e){if(localStorage.getItem(STORAGE_KEY)=== null){console.log(`🖥️ Systemeinstellung geändert(Legacy-Browser):${e.matches ? '🌙 dunkel':'☀️ hell'}`);setDarkMode(e.matches);}});}const initialState = shouldUseDarkMode();console.log(`🔍 Ermittelter Ausgangszustand:${initialState ? '🌙 Dark Mode':'☀️ Light Mode'}`);setDarkMode(initialState);const animClass = initialState ? 'dark-mode-transition':'light-mode-transition';document.body.classList.add(animClass);setTimeout(()=>{document.body.classList.remove(animClass);},300);console.log('🚀 Dark Mode Handler erfolgreich initialisiert');}function createDarkModeToggle(){const header = document.querySelector('header');const nav = document.querySelector('nav');const container = document.querySelector('.dark-mode-container')|| header || nav;if(!container){console.error('⚠️ Kein geeigneter Container für Dark Mode Toggle gefunden');return;}darkModeToggle = document.createElement('button');darkModeToggle.id = 'darkModeToggle';darkModeToggle.className = 'dark-mode-toggle-new';darkModeToggle.setAttribute('aria-label','Dark Mode umschalten');darkModeToggle.setAttribute('title','Dark Mode aktivieren');darkModeToggle.setAttribute('data-action','toggle-dark-mode');const sunIcon = document.createElementNS("http:sunIcon.setAttribute("class","w-5 h-5 sm:w-5 sm:h-5 sun-icon");sunIcon.setAttribute("fill","none");sunIcon.setAttribute("stroke","currentColor");sunIcon.setAttribute("viewBox","0 0 24 24");sunIcon.setAttribute("aria-hidden","true");const sunPath = document.createElementNS("http:sunPath.setAttribute("stroke-linecap","round");sunPath.setAttribute("stroke-linejoin","round");sunPath.setAttribute("stroke-width","2");sunPath.setAttribute("d","M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z");const moonIcon = document.createElementNS("http:moonIcon.setAttribute("class","w-5 h-5 sm:w-5 sm:h-5 moon-icon hidden");moonIcon.setAttribute("fill","none");moonIcon.setAttribute("stroke","currentColor");moonIcon.setAttribute("viewBox","0 0 24 24");moonIcon.setAttribute("aria-hidden","true");const moonPath = document.createElementNS("http:moonPath.setAttribute("stroke-linecap","round");moonPath.setAttribute("stroke-linejoin","round");moonPath.setAttribute("stroke-width","2");moonPath.setAttribute("d","M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z");sunIcon.appendChild(sunPath);moonIcon.appendChild(moonPath);darkModeToggle.appendChild(sunIcon);darkModeToggle.appendChild(moonIcon);container.appendChild(darkModeToggle);console.log('✅ Dark Mode Toggle Button erfolgreich erstellt und zur Benutzeroberfläche hinzugefügt');}const isDark = shouldUseDarkMode();console.log(`🏃‍♂️ Sofortige Anwendung:${isDark ? '🌙 Dark Mode':'☀️ Light Mode'}(vor DOM-Ladung)`);setDarkMode(isDark);})();if(!document.querySelector('style#dark-mode-animations')){const styleTag = document.createElement('style');styleTag.id = 'dark-mode-animations';styleTag.textContent = ` @keyframes spin-once{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}.animate-spin-once{animation:spin-once 0.3s ease-in-out;}`;document.head.appendChild(styleTag);console.log('💫 Animations-Styles für Dark Mode Toggle hinzugefügt');}