forked from teuchezh/dynamic-weather-card
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
372 lines (327 loc) · 11.9 KB
/
utils.ts
File metadata and controls
372 lines (327 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { TIME_THRESHOLDS } from './constants';
import type { TimeOfDay, Position, BackgroundGradient, SunMoonData, HassEntity, HomeAssistant } from './types';
/**
* Determine time of day and its progress (internal fallback)
*/
function getTimeOfDay(): TimeOfDay {
const now = new Date();
const hour = now.getHours();
const minute = now.getMinutes();
const totalMinutes = hour * 60 + minute;
// Sunrise: 6:00 - 8:00 (120 minutes)
if (totalMinutes >= TIME_THRESHOLDS.SUNRISE_START && totalMinutes < TIME_THRESHOLDS.SUNRISE_END) {
const progress = (totalMinutes - TIME_THRESHOLDS.SUNRISE_START) / 120;
return { type: 'sunrise', progress };
}
// Day: 8:00 - 18:00
if (totalMinutes >= TIME_THRESHOLDS.SUNRISE_END && totalMinutes < TIME_THRESHOLDS.DAY_END) {
const progress = (totalMinutes - TIME_THRESHOLDS.SUNRISE_END) / 600;
return { type: 'day', progress };
}
// Sunset: 18:00 - 20:00 (120 minutes)
if (totalMinutes >= TIME_THRESHOLDS.DAY_END && totalMinutes < TIME_THRESHOLDS.SUNSET_END) {
const progress = (totalMinutes - TIME_THRESHOLDS.DAY_END) / 120;
return { type: 'sunset', progress };
}
// Night
return { type: 'night', progress: 0 };
}
/**
* Get sun/moon position based on time of day
*/
export function getSunPosition(timeOfDay: TimeOfDay, width: number, height: number): Position {
if (timeOfDay.type === 'sunrise') {
const progress = timeOfDay.progress;
return {
x: width * (0.3 + progress * 0.4),
y: height * (0.85 - progress * 0.55)
};
} else if (timeOfDay.type === 'sunset') {
const progress = timeOfDay.progress;
return {
x: width * (0.5 + progress * 0.3),
y: height * (0.3 + progress * 0.55)
};
} else if (timeOfDay.type === 'day') {
const progress = timeOfDay.progress;
const angle = progress * Math.PI;
return {
x: width * (0.5 + Math.sin(angle) * 0.25),
y: height * (0.25 - Math.sin(angle) * 0.1)
};
} else {
// Night: moon position
return {
x: width * 0.75,
y: height * 0.3
};
}
}
/**
* Get background gradient colors for sunrise/sunset
*/
export function getBackgroundGradient(timeOfDay: TimeOfDay): BackgroundGradient | null {
if (timeOfDay.type === 'sunrise') {
const progress = timeOfDay.progress;
const nightStart = { r: 26, g: 26, b: 46 };
const dayStart = { r: 255, g: 160, b: 122 };
const dayEnd = { r: 255, g: 215, b: 0 };
return {
start: {
r: Math.round(nightStart.r + (dayStart.r - nightStart.r) * progress),
g: Math.round(nightStart.g + (dayStart.g - nightStart.g) * progress),
b: Math.round(nightStart.b + (dayStart.b - nightStart.b) * progress)
},
end: {
r: Math.round(nightStart.r + (dayEnd.r - nightStart.r) * progress),
g: Math.round(nightStart.g + (dayEnd.g - nightStart.g) * progress),
b: Math.round(nightStart.b + (dayEnd.b - nightStart.b) * progress)
}
};
} else if (timeOfDay.type === 'sunset') {
const progress = timeOfDay.progress;
const dayStart = { r: 255, g: 107, b: 107 };
const dayEnd = { r: 255, g: 160, b: 122 };
const nightStart = { r: 26, g: 26, b: 46 };
return {
start: {
r: Math.round(dayStart.r + (nightStart.r - dayStart.r) * progress),
g: Math.round(dayStart.g + (nightStart.g - dayStart.g) * progress),
b: Math.round(dayStart.b + (nightStart.b - dayStart.b) * progress)
},
end: {
r: Math.round(dayEnd.r + (nightStart.r - dayEnd.r) * progress),
g: Math.round(dayEnd.g + (nightStart.g - dayEnd.g) * progress),
b: Math.round(dayEnd.b + (nightStart.b - dayEnd.b) * progress)
}
};
}
return null;
}
/**
* Format forecast time as HH:00 (24h) or H AM/PM (12h)
*/
export function formatForecastTime(datetime: string, format: '12h' | '24h' = '24h', am = 'AM', pm = 'PM'): string {
if (!datetime) return '';
const date = new Date(datetime);
const hours = date.getHours();
if (format === '12h') {
const h = hours % 12 || 12;
const period = hours < 12 ? am : pm;
return `${h} ${period}`;
}
return `${hours.toString().padStart(2, '0')}:00`;
}
/**
* Format forecast date as a short weekday + day/month label.
*/
export function formatForecastDay(datetime: string, locale?: string): string {
if (!datetime) return '';
const date = new Date(datetime);
if (Number.isNaN(date.getTime())) return '';
return date.toLocaleDateString(locale || undefined, {
weekday: 'short',
day: 'numeric',
month: 'short'
});
}
/**
* Format time as HH:MM or HH:MM AM/PM
*/
export function formatTime(datetime: Date | string, format: '12h' | '24h' = '24h', amText = 'AM', pmText = 'PM'): string {
if (!datetime) return '';
const date = typeof datetime === 'string' ? new Date(datetime) : datetime;
let hours = date.getHours();
const minutes = date.getMinutes();
if (format === '12h') {
const period = hours >= 12 ? pmText : amText;
hours = hours % 12 || 12; // Convert 0 to 12 for 12-hour format
return `${hours}:${minutes.toString().padStart(2, '0')} ${period}`;
} else {
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
}
}
/**
* Get sunrise and sunset data from weather entity or separate sensors
*/
export function getSunriseSunsetData(
weatherState: HassEntity,
sunriseEntity: string | null = null,
sunsetEntity: string | null = null,
hass: HomeAssistant | null = null
): SunMoonData & { hasSunData: boolean } {
let sunrise: Date | null = null;
let sunset: Date | null = null;
// Try to get from separate sensors first (if configured)
if (sunriseEntity && hass && hass.states[sunriseEntity]) {
const sunriseState = hass.states[sunriseEntity];
sunrise = new Date(sunriseState.state);
}
if (sunsetEntity && hass && hass.states[sunsetEntity]) {
const sunsetState = hass.states[sunsetEntity];
sunset = new Date(sunsetState.state);
}
// If not found in separate sensors, try weather entity attributes
if (!sunrise || !sunset) {
if (weatherState && weatherState.attributes) {
const attrs = weatherState.attributes;
if (!sunrise && (attrs.forecast_sunrise || attrs.sunrise)) {
sunrise = new Date(attrs.forecast_sunrise as string || attrs.sunrise as string);
}
if (!sunset && (attrs.forecast_sunset || attrs.sunset)) {
sunset = new Date(attrs.forecast_sunset as string || attrs.sunset as string);
}
}
}
// If still no sun data, try default sun.sun entity from Home Assistant
if ((!sunrise || !sunset) && hass && hass.states['sun.sun']) {
const sunEntity = hass.states['sun.sun'];
const sunAttrs = sunEntity.attributes;
if (!sunrise && sunAttrs.next_rising) {
sunrise = new Date(sunAttrs.next_rising as string);
}
if (!sunset && sunAttrs.next_setting) {
sunset = new Date(sunAttrs.next_setting as string);
}
}
return {
sunrise,
sunset,
hasSunData: !!(sunrise && sunset)
};
}
/**
* Determine time of day based on sunrise/sunset or fallback to static times
*/
export function getTimeOfDayWithSunData(sunData: SunMoonData & { hasSunData: boolean }): TimeOfDay {
const now = new Date();
// If we have real sun data, use it
if (sunData.hasSunData && sunData.sunrise && sunData.sunset) {
const currentTime = now.getTime();
let sunriseTime = sunData.sunrise.getTime();
let sunsetTime = sunData.sunset.getTime();
// Check if sunrise/sunset are for tomorrow (common with Yandex Weather and similar integrations)
// If sunrise is more than 12 hours in the future, subtract 24 hours to get today's time
if (sunriseTime - currentTime > 12 * 60 * 60 * 1000) {
sunriseTime -= 24 * 60 * 60 * 1000;
}
if (sunsetTime - currentTime > 12 * 60 * 60 * 1000) {
sunsetTime -= 24 * 60 * 60 * 1000;
}
// Calculate sunrise/sunset window (±1 hour)
const sunriseStart = sunriseTime - 60 * 60 * 1000; // 1 hour before
const sunriseEnd = sunriseTime + 60 * 60 * 1000; // 1 hour after
const sunsetStart = sunsetTime - 60 * 60 * 1000; // 1 hour before
const sunsetEnd = sunsetTime + 60 * 60 * 1000; // 1 hour after
// Sunrise period
if (currentTime >= sunriseStart && currentTime < sunriseEnd) {
const progress = (currentTime - sunriseStart) / (sunriseEnd - sunriseStart);
return { type: 'sunrise', progress };
}
// Day period (after sunrise, before sunset)
if (currentTime >= sunriseEnd && currentTime < sunsetStart) {
const progress = (currentTime - sunriseEnd) / (sunsetStart - sunriseEnd);
return { type: 'day', progress };
}
// Sunset period
if (currentTime >= sunsetStart && currentTime < sunsetEnd) {
const progress = (currentTime - sunsetStart) / (sunsetEnd - sunsetStart);
return { type: 'sunset', progress };
}
// Night period
return { type: 'night', progress: 0 };
}
// Fallback to static time-based calculation
return getTimeOfDay();
}
/**
* Convert wind speed for legacy providers that don't specify wind_speed_unit
* If provider has wind_speed_unit attribute, returns value as-is (no conversion)
*/
export function convertWindSpeed(
speed: number | null,
attrs: { wind_speed_unit?: string },
configUnit: 'ms' | 'kmh'
): number | null {
if (speed == null) return null;
// If provider specifies wind_speed_unit, trust it and don't convert
if (attrs.wind_speed_unit) {
return Math.round(speed * 10) / 10;
}
// Legacy provider without wind_speed_unit - use config option
// Assume provider returns m/s, convert to km/h if requested
if (configUnit === 'kmh') {
return Math.round(speed * 3.6 * 10) / 10;
}
return Math.round(speed * 10) / 10;
}
/**
* Get wind speed unit label based on entity attributes or config
*/
export function getWindSpeedUnit(
attrs: { wind_speed_unit?: string },
configUnit: 'ms' | 'kmh',
t: (key: string) => string
): string {
const unit = attrs.wind_speed_unit;
// If provider specifies wind_speed_unit, use it
if (unit) {
const normalizedUnit = unit.toLowerCase().replace(/[^a-z]/g, '');
if (normalizedUnit === 'kmh' || normalizedUnit === 'kmph') {
return t('wind_unit_kmh');
} else if (normalizedUnit === 'ms' || normalizedUnit === 'mps') {
return t('wind_unit_ms');
} else if (normalizedUnit === 'mph') {
return t('wind_unit_mph');
} else if (normalizedUnit === 'knots' || normalizedUnit === 'kn' || normalizedUnit === 'kt') {
return t('wind_unit_knots');
} else if (normalizedUnit === 'fts' || normalizedUnit === 'ftps') {
return t('wind_unit_fts');
}
// Fallback: return the original unit if we don't recognize it
return unit;
}
// Legacy provider - use config option
return configUnit === 'kmh' ? t('wind_unit_kmh') : t('wind_unit_ms');
}
/**
* Format current time for clock display
*/
export function formatClockTime(
date: Date,
format: '12h' | '24h',
amLabel: string,
pmLabel: string
): string {
if (format === '12h') {
let hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, '0');
const period = hours >= 12 ? pmLabel : amLabel;
hours = hours % 12 || 12;
return `${hours}:${minutes} ${period}`;
} else {
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${hours}:${minutes}`;
}
}
/**
* Setup horizontal scroll with mouse wheel for containers
* Returns cleanup function to remove event listener
*/
export function setupHorizontalScroll(
root: ShadowRoot | null,
selector: string
): (() => void) | null {
const element = root?.querySelector(selector) as HTMLElement | null;
if (!element) return null;
const handler = (e: Event) => {
const wheelEvent = e as WheelEvent;
if (wheelEvent.deltaY !== 0) {
e.preventDefault();
element.scrollLeft += wheelEvent.deltaY;
}
};
element.addEventListener('wheel', handler, { passive: false });
return () => element.removeEventListener('wheel', handler);
}