forked from BagelBeef/ha-departureCard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathha-departureCard.js
More file actions
415 lines (383 loc) · 14.5 KB
/
ha-departureCard.js
File metadata and controls
415 lines (383 loc) · 14.5 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// developed by BagelBeef
class DepartureCard extends HTMLElement {
constructor() {
super();
this.prevState = null; // saves the previous state of the departure entity
this.prevHass = null; // saves the previous Hass
}
validateConfig(config, hass) {
const errors = [];
if (!config.entity) errors.push("No entity configured.");
else if (!hass.states?.[config.entity]) errors.push(`Entity '${config.entity}' not found in Home Assistant.`);
if (!config.departure) errors.push("Missing 'departure' attribute in config.");
if (!config.train) errors.push("Missing 'train' attribute in config.");
if (!config.delay) errors.push("Missing 'delay' attribute in config.");
if (!config.connections_attribute) errors.push("Missing connection attribute.");
return errors;
}
// Sets the 'hass' state, which holds the Home Assistant data
set hass(hass) {
const config = this.config;
const errors = this.validateConfig(config, hass);
if (errors.length > 0) {
this.innerHTML = `<ha-card>
<div class="card-content">
<h1>${config.title || "Departure Card"}</h1>
<p>${errors.join("<br>")}</p>
</div>
</ha-card>`;
return;
}
const entity = config.entity;
const currentState = hass.states[entity].state;
// Check if entity and attributes has changed
if (this.prevHass && this.prevHass.states[entity] === hass.states[entity]) {
return;
}
// Check if the state of entity has changed
if (this.prevState === currentState) {
return;
}
this.prevState = currentState; // save current state
this.prevHass = hass; // save current hass
const connectionsAttribute = config.connections_attribute || 'next_departures';
const displayed_connections = config.displayed_connections || 5;
const unixTime = config.unix_time || false;
const convertTimeHHMM = config.convertTimeHHMM || false;
const relativeTime = config.relativeTime || false;
const limit = config.limit || 60;
// Targets (destinations) that should be filtered from the connections list
const targets = config.targets || [];
const connections = hass.states[entity].attributes[connectionsAttribute];
const exclude = config.exclude || false;
const line = config.line ? (Array.isArray(config.line) ? config.line.map(String) : [String(config.line)]) : [];
const lineExclude = config.lineExclude || false;
// Get stopAttribute and stop for filtering
const stopAttribute = config.stopAttribute || 'route'; //where to found route list
const stop = config.filterByStop || null; // filterByStop stop can be null
const stationName = config.stationName || null; // stationName to slice route up to statioName
// If no connections are available, display a message saying no departures are available
if (!connections || connections.length === 0) {
this.innerHTML = `<ha-card>
<div class="card-content">
<h1>${config.title}</h1>
<p>No departures available.</p>
</div>
</ha-card>`;
return;
}
// If there are specified target destinations, filter the connections accordingly
let filtered_connections = connections;
if (targets.length > 0) {
if (exclude) {
filtered_connections = connections.filter(connection =>
!targets.includes(connection.destination)
);
} else {
filtered_connections = connections.filter(connection =>
targets.includes(connection.destination)
);
}
}
if (line.length > 0) {
if (lineExclude) {
filtered_connections = filtered_connections.filter(connection =>
!line.includes(String(connection[config.train]))
);
} else {
filtered_connections = filtered_connections.filter(connection =>
line.includes(String(connection[config.train]))
);
}
}
// Filter by the specified stop in the route, but only if stop and stopAttribute are valid
if (stop && stopAttribute) {
filtered_connections = filtered_connections.filter(connection => {
const route = connection[stopAttribute];
if (route && Array.isArray(route)) {
// Find the index of stationName in the route
const stationIndex = route.findIndex(routeStop => routeStop.name === stationName);
if (stationIndex === -1) {
return false; // stationName is not in the route, so skip this connection
}
// Extract stops after stationName
const stopsAfterStation = route.slice(stationIndex);
connection[stopAttribute] = stopsAfterStation; // Update the route list to include only stops after stationName
// Check if the stop exists in the stops after stationName
return stopsAfterStation.some(routeStop => routeStop.name === stop);
}
return false; // No valid route or no valid stops in the route
});
}
// If no connections match the specified targets, show a message saying no departures were found
if (filtered_connections.length === 0) {
this.innerHTML = `<ha-card>
<div class="card-content">
<h1>${config.title}</h1>
<p>No departures found for the specified destinations or stops. Check statioName if you want to use filter by stop!</p>
</div>
</ha-card>`;
return;
}
// Build HTML content to display the departure information
let departuresHtml = `
<ha-card>
<style>
.card-content {
max-width: 100%;
padding: 16px;
overflow-x: auto;
}
h1 {
margin: 0;
}
.filtered-stop {
font-size: 0.8em;
color: gray;
margin-top: 0;
}
.table {
width: 100%;
border-collapse: collapse;
}
.departure-row {
padding: 4px 0;
}
.departure-row td{
border-bottom: 1px solid rgba(180, 180, 180, 0.6);
line-height: 1.2;
}
.cancelled {
text-decoration: line-through;
opacity: 0.6;
}
.train, .destination, .platform, .departure, .delay {
font-size: 0.9em;
padding: 4px;
}
.train {
text-align: left;
white-space: nowrap;
}
.destination {
text-align: left;
max-width: 150px;
}
.destination-text {
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.platform {
text-align: left;
white-space: nowrap;
}
.departure {
text-align: right;
white-space: nowrap;
}
.delay {
text-align: left;
padding-left: 4px;
min-width: 20px;
white-space: nowrap;
}
.delay span {
color: red;
}
</style>
<div class="card-content">
<h1>${config.title}</h1>
`;
// Display the filtered stop information, if any
if (stop) {
departuresHtml += `<p class="filtered-stop">Filtered by stop: ${stop}</p>`; // Show filtered stop
}
//Start table
departuresHtml += '<table class="table"><tbody>';
// Loop through the filtered connections and display them
filtered_connections.slice(0, displayed_connections).forEach(connection => {
const train = connection[config.train];
const destination = connection.destination;
const delay = connection[config.delay] || 0;
const platform = connection[config.platform] || 'N/A'; // Default to 'N/A' if no platform info
const isCancelled = connection[config.isCancelled || 'isCancelled'] || 0;
// Check if a conversion of unix-time is necessary
let departure;
if (unixTime && !relativeTime) {
departure = new Date(connection[config.departure] * 1000).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
} else if (convertTimeHHMM) {
departure = new Date(connection[config.departure].replace(' ', 'T')).toTimeString().slice(0, 5);
} else {
departure = connection[config.departure] || '';
}
// Default color for departure time and text for no delay.mIf there is a delay, adjust color and add delay text
let departureColor = delay > 0 ? "red" : "green";
let delayText = delay > 0 ? `+${delay}` : "";
let isCancelledClass = isCancelled == 1 ? "cancelled" : "";
if (relativeTime && !unixTime) {
let [h, m] = departure.split(':').map(Number),
now = new Date(),
d = new Date(now);
d.setHours(h, m + delay, 0, 0);
if (d < now && d-now > 5) d.setDate(d.getDate() + 1); // Mitternacht-Übergang
let diffMinutes = Math.round((d - now) / 60000);
if (diffMinutes < limit) {
departure = diffMinutes <= 0 ? "Jetzt" : `In ${diffMinutes} Minuten`;
delayText = "";
}
}
if (relativeTime && unixTime) {
let d = new Date(connection[config.departure] * 1000);
d.setMinutes(d.getMinutes() + Number(delay));
let diffMinutes = Math.round((d - new Date()) / 60000);
if (diffMinutes < limit) {
departure = diffMinutes <= 0 ? "Jetzt" : `In ${diffMinutes} Minuten`;
delayText = "";
} else {
departure = new Date(connection[config.departure] * 1000).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
}
}
departuresHtml += `
<tr class="departure-row ${isCancelledClass}">
<td class="train"><strong>${train}</strong></td>
<td class="destination"><span class="destination-text">${destination}</span></td>
${config.show_platform ? `<td class="platform">${platform}</td>` : ""}
<td class="departure" style="color: ${departureColor};">${departure}</td>
${!relativeTime ? `<td class="delay">${delayText ? `<span>${delayText}</span>` : ""}</td>` : ""}
</tr>
`;
});
departuresHtml += `</tbody></table></div></ha-card>`;
this.innerHTML = departuresHtml;
}
// Saves the configuration for the custom card
setConfig(config) {
this.config = config;
}
modifyConfig(config) {
const Config = {
tap_action: {
action: 'url',
},
...config,
};
return Config;
}
// Returns a sample configuration for the custom card
static getStubConfig() {
return {
title: "Departures",
entity: '',
connections_attribute: 'next_departures',
displayed_connections: 5,
unix_time: false,
convertTimeHHMM: false,
relativeTime: false,
limit : 60,
targets: '',
exclude: false,
line: '',
lineExclude: false,
train: 'train',
departure: 'scheduledTime',
delay: 'delay',
platform: 'platform',
show_platform: true, // Default to true (platform column always rendered)
isCancelled: 'isCancelled',
stopAttribute: 'route', // Attribute for the stops/route
filterByStop: '', // The specific stop to filter by
stationName: '' // Your stationName for deleting stops before it
};
}
static getConfigForm() {
return {
schema: [
{
name: "title",
required: true,
selector: { text: {} }
},
{
name: "entity",
required: true,
selector: { entity: {} }
},
{
name: "connections_attribute",
required: true,
selector: { text: {} }
},
{
type: "constant",
name: "Properties"
},
{
name: "",
type: "grid",
multiple: false,
default: {},
schema: [
{ name: "train", selector: { text: {} } },
{ name: "isCancelled", selector: { text: {} } },
{ name: "platform", selector: { text: {} } },
{ name: "show_platform", selector: { boolean: {} } },
]
},
{
name: "displayed_connections",
required: true,
selector: { number: { min: 1, max: 20, mode: "box" } }
},
{
type: "constant",
name: "Time Information"
},
{
name: "",
type: "grid",
multiple: false,
default: {},
schema: [
{ name: "departure", description: "Departure time attribute", selector: { text: {} } },
{ name: "delay", selector: { text: {} } },
{ name: "unix_time", selector: { boolean: {} } },
{ name: "convertTimeHHMM", selector: { boolean: {} } },
{ name: "relativeTime", selector: { boolean: {} } },
{ name: "limit", selector: { number: {min: 1, max: 60, mode: "box" } } }
]
},
{
type: "constant",
name: "Filter"
},
{
name: "",
type: "grid",
multiple: false,
default: {},
schema: [
{ name: "targets", selector: { text: {} } },
{ name: "exclude", selector: { boolean: {} } },
{ name: "line", selector: { text: {} } },
{ name: "lineExclude", selector: { boolean: {} } },
{ name: "stopAttribute", selector: { text: {} } },
{ name: "filterByStop", selector: { text: {} } },
{ name: "stationName", selector: { text: {} } }
]
},
]
};
}
}
// Defines the custom HTML element 'departure-card'
customElements.define('departure-card', DepartureCard);
window.customCards = window.customCards || [];
window.customCards.push({
type: "departure-card",
name: "HA Departure Card",
preview: true,
description: "Display your next departures",
documentationURL: "https://github.com/BagelBeef/ha-departureCard",
});