Skip to content

Commit 06498bc

Browse files
committed
fix: Compute upcoming based on last updated
1 parent 93fa96e commit 06498bc

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/nextbus-card.ts

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,18 @@ export class NextBusCard extends LitElement {
6262
return `${attributes.route.replace(/-/g, ' ')} ${isInbound ? 'Inbound' : 'Outbound'}`;
6363
}
6464

65+
protected minutesUntil(target: number, now: number, defaultValue = ''): string {
66+
if (target < now) return defaultValue;
67+
68+
const timeDelta = Math.abs(target - now);
69+
let minutes = Math.ceil(timeDelta / (1000 * 604));
70+
if (target < now) {
71+
minutes = -minutes;
72+
}
73+
if (minutes === 0) return 'now';
74+
return `${minutes} min${minutes > 1 ? 's' : ''}`;
75+
}
76+
6577
protected render(): TemplateResult | void {
6678
if (!this._config || !this.hass) {
6779
return html``;
@@ -81,7 +93,13 @@ export class NextBusCard extends LitElement {
8193
`;
8294
}
8395
84-
const upcoming = stateObj.attributes.upcoming.split(',').map(v => v.replace(/\s/g, ''));
96+
const last_updated_ts = new Date(stateObj.last_updated).getTime();
97+
98+
const upcoming = stateObj.attributes.upcoming
99+
.split(',')
100+
.map(v => last_updated_ts + parseInt(v.replace(/\s/g, ''), 10) * 60 * 1000);
101+
102+
const now_ts = new Date().getTime();
85103
86104
return html`
87105
<div class="flex">
@@ -93,8 +111,8 @@ export class NextBusCard extends LitElement {
93111
<div class="routeStop"><ha-icon icon="mdi:map-marker"></ha-icon> ${stateObj.attributes.stop}</div>
94112
</div>
95113
<div class="upcoming">
96-
<div class="nextTime">${upcoming.length ? `${upcoming[0]} min` : 'n/a'}</div>
97-
<div class="afterTime">${upcoming.length > 1 ? `${upcoming[1]} min` : ''}</div>
114+
<div class="nextTime">${upcoming.length ? this.minutesUntil(upcoming[0], now_ts, 'n/a') : 'n/a'}</div>
115+
<div class="afterTime">${upcoming.length > 1 ? this.minutesUntil(upcoming[1], now_ts) : ''}</div>
98116
</div>
99117
</div>
100118
`;

0 commit comments

Comments
 (0)