Calendar/src/utils/ColumnDetectionUtils.ts

94 lines
2.5 KiB
TypeScript
Raw Normal View History

/**
* ColumnDetectionUtils - Shared utility for column detection and caching
* Used by both DragDropManager and AllDayManager for consistent column detection
*/
export interface ColumnBounds {
date: string;
left: number;
right: number;
}
export class ColumnDetectionUtils {
private static columnBoundsCache: ColumnBounds[] = [];
/**
* Update column bounds cache for coordinate-based column detection
*/
public static updateColumnBoundsCache(): void {
// Reset cache
this.columnBoundsCache = [];
// Find alle kolonner
const columns = document.querySelectorAll('swp-day-column');
// Cache hver kolonnes x-grænser
columns.forEach(column => {
const rect = column.getBoundingClientRect();
const date = (column as HTMLElement).dataset.date;
if (date) {
this.columnBoundsCache.push({
date,
left: rect.left,
right: rect.right
});
}
});
// Sorter efter x-position (fra venstre til højre)
this.columnBoundsCache.sort((a, b) => a.left - b.left);
}
/**
* Get column date from X coordinate using cached bounds
*/
public static getColumnDateFromX(x: number): string | null {
// Opdater cache hvis tom
if (this.columnBoundsCache.length === 0) {
this.updateColumnBoundsCache();
}
// Find den kolonne hvor x-koordinaten er indenfor grænserne
const column = this.columnBoundsCache.find(col =>
x >= col.left && x <= col.right
);
return column ? column.date : null;
}
/**
* Get column index (1-based) from date
*/
public static getColumnIndexFromDate(date: string): number {
// Opdater cache hvis tom
if (this.columnBoundsCache.length === 0) {
this.updateColumnBoundsCache();
}
const columnIndex = this.columnBoundsCache.findIndex(col => col.date === date);
return columnIndex >= 0 ? columnIndex + 1 : 1; // 1-based index
}
/**
* Get column index from X coordinate
*/
public static getColumnIndexFromX(x: number): number {
const date = this.getColumnDateFromX(x);
return date ? this.getColumnIndexFromDate(date) : 1;
}
/**
* Clear cache (useful for testing or when DOM structure changes)
*/
public static clearCache(): void {
this.columnBoundsCache = [];
}
/**
* Get current cache for debugging
*/
public static getCache(): ColumnBounds[] {
return [...this.columnBoundsCache];
}
}