322 lines
12 KiB
TypeScript
322 lines
12 KiB
TypeScript
import { InertiaLinkProps } from '@inertiajs/vue3'
|
|
import { clsx, type ClassValue } from 'clsx'
|
|
import { twMerge } from 'tailwind-merge'
|
|
import { toast } from 'vue-sonner'
|
|
|
|
export function cn(...inputs: ClassValue[]) {
|
|
return twMerge(clsx(inputs));
|
|
}
|
|
|
|
export function urlIsActive(urlToCheck: NonNullable<InertiaLinkProps['href']>, currentUrl: string) {
|
|
return currentUrl.indexOf(toUrl(urlToCheck)) >= 0
|
|
}
|
|
|
|
export function toUrl(href: NonNullable<InertiaLinkProps['href']>) {
|
|
return typeof href === 'string' ? href : href?.url;
|
|
}
|
|
|
|
|
|
const currencyFormatter = new Intl.NumberFormat('de-DE', {
|
|
style: 'currency',
|
|
currency: 'EUR',
|
|
minimumFractionDigits: 2,
|
|
})
|
|
|
|
export function toCurrency(value: number | undefined) {
|
|
if (!value) return currencyFormatter.format(0);
|
|
return currencyFormatter.format(value);
|
|
}
|
|
|
|
const roundedCurrencyFormatter = new Intl.NumberFormat('de-DE', {
|
|
style: 'currency',
|
|
currency: 'EUR',
|
|
minimumFractionDigits: 0,
|
|
maximumFractionDigits: 0
|
|
})
|
|
|
|
export function toRoundedCurrency(value: number | undefined) {
|
|
if (!value) return roundedCurrencyFormatter.format(0);
|
|
return roundedCurrencyFormatter.format(toFixedRounded(value, 0));
|
|
}
|
|
|
|
export function toFixedRounded(num: number, precision: number): number {
|
|
return Number((Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision)).toFixed(precision))
|
|
}
|
|
|
|
export function toLocalDate(value: string | Date) {
|
|
const date = new Date(value);
|
|
return date.toLocaleDateString('de-DE', { day: '2-digit', month: 'short', year: 'numeric' });
|
|
// return date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' });
|
|
// return date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: '2-digit' });
|
|
}
|
|
|
|
export function toShortISOString(date: Date | string) {
|
|
let tempDate = (typeof date === 'string') ? new Date(date) : date
|
|
return tempDate.toISOString().split('T')[0]
|
|
}
|
|
|
|
export function calcDueDate(date: Date, daysAfterInvoice: number): Date {
|
|
let dueDate = new Date(date);
|
|
dueDate.setDate(date.getDate() + daysAfterInvoice);
|
|
return dueDate;
|
|
}
|
|
|
|
export function randomInt(max: number) {
|
|
return Math.floor(Math.random() * max);
|
|
}
|
|
|
|
const randomColors = [
|
|
'bg-rose-200 dark:bg-rose-700',
|
|
'bg-lime-200 dark:bg-lime-700',
|
|
'bg-orange-200 dark:bg-orange-700',
|
|
'bg-sky-200 dark:bg-sky-700',
|
|
'bg-amber-200 dark:bg-amber-700',
|
|
'bg-blue-200 dark:bg-blue-700',
|
|
'bg-purple-200 dark:bg-purple-700'
|
|
]
|
|
|
|
export function bgColorForString(input: string): string {
|
|
let charCodeSum = 0;
|
|
for (let i = 0; i < input.length; i++) {
|
|
charCodeSum += input.charCodeAt(i)
|
|
}
|
|
return randomColors[charCodeSum % randomColors.length];
|
|
}
|
|
|
|
export function clearSelection() {
|
|
window.getSelection()?.removeAllRanges();
|
|
};
|
|
|
|
const promise = () => new Promise((resolve) => setTimeout(resolve, 2000))
|
|
export function testToast() {
|
|
let delay = 150
|
|
toast('Toast', {
|
|
description: "Description bjksad fkjlhsd fkjhsdf jkshdf jkashdf adskljhf ", action: {
|
|
label: 'Undo',
|
|
onClick: () => console.log('Undo')
|
|
}
|
|
})
|
|
setTimeout(() => {
|
|
toast.info('Info', {
|
|
action: {
|
|
label: 'Undo',
|
|
onClick: () => console.log('Undo')
|
|
}
|
|
})
|
|
}, delay * 1)
|
|
setTimeout(() => { toast.success('Success', { description: "description" }) }, delay * 2)
|
|
setTimeout(() => { toast.warning('Warning', { description: "description" }) }, delay * 3)
|
|
setTimeout(() => { toast.error('Error', { description: "description" }) }, delay * 4)
|
|
setTimeout(() => {
|
|
toast.promise(promise, {
|
|
loading: 'Loading...',
|
|
success: (data) => {
|
|
return `${data.name} toast has been added`;
|
|
},
|
|
error: (data: any) => 'Error',
|
|
})
|
|
}, delay * 5)
|
|
|
|
}
|
|
|
|
export function loremIpsum(numWords: number): string {
|
|
let text = `Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
|
|
|
|
Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
|
|
|
|
Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
|
|
|
|
Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.`
|
|
return text.split(" ").splice(0, numWords).join(" ");
|
|
}
|
|
|
|
export function randomDate(): Date {
|
|
let d = new Date()
|
|
d.setDate(d.getDate() - Math.random() * 20)
|
|
return d
|
|
}
|
|
|
|
|
|
// -----------------------------------------------------------------------------
|
|
// Hotkeys
|
|
// -----------------------------------------------------------------------------
|
|
|
|
// Füge diese Typdefinitionen am Anfang der Datei hinzu
|
|
type HotkeyCallback = (params?: any) => void;
|
|
type HotkeyEnabledCallback = () => boolean;
|
|
|
|
// Füge diese Variablen am Anfang der Datei hinzu
|
|
const registeredHotkeys = new Map<string, {
|
|
callback: HotkeyCallback;
|
|
params: any;
|
|
enabled: HotkeyEnabledCallback | undefined;
|
|
}>();
|
|
|
|
|
|
|
|
/**
|
|
* Registriert einen globalen Tastatur-Shortcut
|
|
* @param keyCombination Tastaturkombination (z.B. 'Mod+S' für automatische Erkennung von Cmd/Ctrl)
|
|
* @param callback Funktion, die aufgerufen werden soll
|
|
* @param callbackParameters Optionale Parameter für den Callback
|
|
* @param enabled Optionaler Callback, der angibt, ob der Shortcut aktiv ist
|
|
* @returns Funktion zum Entfernen des Shortcuts
|
|
*
|
|
* @example
|
|
* // Beispiel 1: Shortcut mit Plus-Taste
|
|
* const removeZoomInShortcut = hotkey('Mod+plus', () => {
|
|
* console.log('Zoom in')
|
|
* });
|
|
*
|
|
* @example
|
|
* // Beispiel 2: Shortcut mit Pfeiltasten
|
|
* const removeMoveLeftShortcut = hotkey('leftarrow', () => {
|
|
* console.log('Move left')
|
|
* });
|
|
*
|
|
* @example
|
|
* // Beispiel 3: Shortcut mit Enter-Taste
|
|
* const removeSubmitShortcut = hotkey('enter', () => {
|
|
* console.log('Submit form')
|
|
* });
|
|
*
|
|
* @example
|
|
* // Beispiel 4: Shortcut mit Escape-Taste
|
|
* const removeCancelShortcut = hotkey('esc', () => {
|
|
* console.log('Cancel action')
|
|
* });
|
|
*
|
|
* @example
|
|
* // Beispiel 5: Shortcut, der nur ausgelöst wird, wenn kein Eingabefeld fokussiert ist
|
|
* const removeGlobalSearchShortcut = hotkey('Mod+k', () => {
|
|
* console.log('Open global search')
|
|
* });
|
|
*/
|
|
export function hotkey(
|
|
keyCombination: string,
|
|
callback: HotkeyCallback,
|
|
callbackParameters?: any,
|
|
enabled?: HotkeyEnabledCallback
|
|
): () => void {
|
|
// Ersetzen von 'Mod' durch den passenden Modifier
|
|
const modifier = getPlatformModifier()
|
|
|
|
// Normalisieren der Tastaturkombination
|
|
const normalizedCombination = keyCombination
|
|
.toLowerCase()
|
|
.replace('mod', modifier)
|
|
.split('+')
|
|
.map(key => normalizeKeyName(key))
|
|
.join('+')
|
|
|
|
// Überprüfen, ob der Shortcut bereits registriert ist
|
|
if (registeredHotkeys.has(normalizedCombination)) {
|
|
console.warn(`Hotkey '${keyCombination}' is already registered. Overwriting existing hotkey.`)
|
|
}
|
|
|
|
// Speichern der Hotkey-Informationen
|
|
registeredHotkeys.set(normalizedCombination, {
|
|
callback,
|
|
params: callbackParameters,
|
|
enabled
|
|
});
|
|
|
|
// Rückgabe einer Funktion zum Entfernen des Shortcuts
|
|
return () => {
|
|
registeredHotkeys.delete(normalizedCombination)
|
|
};
|
|
}
|
|
|
|
function getPlatformModifier(): string {
|
|
// Überprüfen, ob wir auf macOS/iOS sind
|
|
if (navigator.userAgent.includes('Macintosh') ||
|
|
navigator.userAgent.includes('iPhone') ||
|
|
navigator.userAgent.includes('iPad')) {
|
|
return 'cmd'
|
|
}
|
|
return 'ctrl'
|
|
}
|
|
|
|
export function getPlatformModifierSymbol(): string {
|
|
if (navigator.userAgent.includes('Macintosh') ||
|
|
navigator.userAgent.includes('iPhone') ||
|
|
navigator.userAgent.includes('iPad')) {
|
|
return '⌘'
|
|
}
|
|
return 'Ctrl'
|
|
}
|
|
|
|
function normalizeKeyName(key: string): string {
|
|
const keyMap: Record<string, string> = {
|
|
'+': 'plus',
|
|
'-': 'minus',
|
|
'arrowleft': 'leftarrow',
|
|
'arrowright': 'rightarrow',
|
|
'arrowup': 'uparrow',
|
|
'arrowdown': 'downarrow',
|
|
'return': 'enter',
|
|
'esc': 'escape'
|
|
};
|
|
|
|
// Konvertiere den Tastennamen in Kleinbuchstaben
|
|
const lowerKey = key.toLowerCase()
|
|
|
|
// Ersetze den Tastennamen, falls in der Map vorhanden
|
|
return keyMap[lowerKey] || lowerKey
|
|
}
|
|
|
|
function handleKeyboardEvent(event: KeyboardEvent) {
|
|
// Überprüfen, ob das Event-Element ein Eingabefeld, Textarea oder ähnliches ist
|
|
const target = event.target as HTMLElement;
|
|
if (target.tagName === 'INPUT' ||
|
|
target.tagName === 'TEXTAREA' ||
|
|
target.tagName === 'SELECT' ||
|
|
target.isContentEditable) {
|
|
// Wenn das Event-Element ein Eingabefeld ist, den Shortcut nicht auslösen
|
|
return;
|
|
}
|
|
|
|
// Erstellen einer normalisierten Tastaturkombination
|
|
let combination = ''
|
|
|
|
// Bestimmen des passenden Modifiers
|
|
const modifier = getPlatformModifier()
|
|
|
|
// Hinzufügen von Modifier-Tasten
|
|
if ((modifier === 'ctrl' && event.ctrlKey) ||
|
|
(modifier === 'cmd' && event.metaKey)) {
|
|
combination += `${modifier}+`
|
|
}
|
|
if (event.shiftKey) {
|
|
combination += 'shift+'
|
|
}
|
|
if (event.altKey) {
|
|
combination += 'alt+'
|
|
}
|
|
|
|
// Hinzufügen der Haupttaste
|
|
combination += normalizeKeyName(event.key)
|
|
|
|
// Überprüfen, ob der Shortcut registriert ist
|
|
const hotkeyInfo = registeredHotkeys.get(combination);
|
|
if (hotkeyInfo) {
|
|
// Überprüfen, ob der Shortcut aktiv ist
|
|
if (!hotkeyInfo.enabled || hotkeyInfo.enabled()) {
|
|
// Ausführen des Callbacks mit den Parametern
|
|
hotkeyInfo.callback(hotkeyInfo.params)
|
|
|
|
// Verhindern der Standardaktion, falls gewünscht
|
|
event.preventDefault()
|
|
event.stopPropagation()
|
|
return 0
|
|
}
|
|
}
|
|
}
|
|
|
|
// Registrieren des globalen Event-Listeners
|
|
window.addEventListener('keydown', handleKeyboardEvent);
|
|
|
|
// Füge die Funktion zum Entfernen aller Hotkeys hinzu
|
|
export function removeAllHotkeys() {
|
|
registeredHotkeys.clear()
|
|
} |