aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/Timetable.svelte
blob: 5fa6e9519af8d13affd6892fb28378272129f2f9 (plain) (blame)
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
<script lang="ts">
  import { browser, building, dev } from '$app/environment';
  import { page } from '$app/state';
  import { S } from '$lib';
  import { operators } from './aliases';
  import LineGlyph from './assets/LineGlyph.svelte';
  import Pictogram from './assets/Pictogram.svelte';
  import { Mode, type StoptimesResponse } from './motis-types';
  import { m } from './paraglide/messages';

  let relativeSecondPrecision = $derived(
    ['seconds', 'second', 'sec', 'secs', 's', '2'].includes(
      building ? null! : page.url.searchParams.get('relative')!
    )
  );
  let isRelativeTime = $derived(
    relativeSecondPrecision ||
      ['1', 'true'].includes(
        building ? null! : page.url.searchParams.get('relative')!
      )
  );
  /** only if isRelativeTime is true */
  let now = $state(0);
  const updateNow = () => {
    now = Date.now();
    setTimeout(updateNow, 33);
  };
  $effect(() => (isRelativeTime ? updateNow() : void 0));

  let {
    stopTimes,
    isArrivals = false,
    placeName = '',
    placeId,
    isResultsPage = true,
    setSearch = (q) => void 0,
  }: {
    stopTimes: null | StoptimesResponse;
    isArrivals?: boolean;
    placeName?: string;
    isResultsPage?: boolean;
    placeId: string | null;
    setSearch: (query: string) => void;
  } = $props();
  const timeRelative = (ms: number, relativeTo = now) => {
    const _totalMillis = ms - relativeTo;
    const totalMillis = Math.abs(_totalMillis);
    const totalSeconds = totalMillis / 1000;
    const totalMinutes = totalSeconds / 60;
    const totalHours = totalMinutes / 60;
    const hours = Math.floor(totalHours);
    const minutes = Math.floor(totalMinutes) - hours * 60;
    const seconds = Math.floor(totalSeconds) - hours * 60 * 60 - minutes * 60;
    const results = [] as string[];
    if (hours)
      results.push(
        `${m.hours({
          hours,
        })}`
      );
    if (hours || minutes) results.push(`${m.minutes({ minutes })}`);
    if (seconds && relativeSecondPrecision)
      results.push(`${m.seconds({ seconds })}`);
    if (results.length > 1) {
      const [r, l] = [results.pop()!, results.pop()!];
      results.push(
        m.timeJoiner({
          l,
          r,
        })
      );
    }
    const relTime =
      results.length === 1
        ? results[0]
        : results.length === 0
          ? ''
          : results.reduce((pv, cv) => m.timeJoiner2({ l: pv, r: cv }));
    if (relTime === '')
      return m.timeImmediate({
        isPastTense: _totalMillis < 0 ? 'true' : 'false',
      });
    if (_totalMillis < 0)
      return m.timeInPast({
        relTime,
      });
    else
      return m.timeInFuture({
        relTime,
      });
  };
  const localTime = async (
    time: Date,
    forceAbsolute = false,
    relativeTo = now
  ) => {
    const offset = parseFloat(
      browser
        ? // Browsers like Librewolf love patching time to be a fixed timezone, breaking us.
          (localStorage.getItem(
            isRelativeTime && !forceAbsolute
              ? 'relative-offset-time'
              : 'offset-time'
          ) ?? '0')
        : // @ts-ignore
          ((typeof process !== 'undefined' ? process.env : undefined)?.env[
            isRelativeTime && !forceAbsolute
              ? 'PRIVATE_RELATIVE_TIME_OFFSET'
              : 'PRIVATE_SERVER_TIMEZONE'
          ] ?? '0')
    );
    if (isRelativeTime && !forceAbsolute) {
      return timeRelative(time.getTime() - offset * 60 * 60 * 1000, relativeTo);
    } else {
      let hours = time.getHours() + Math.floor(offset);
      const minutes = time.getMinutes() + Math.floor((offset % 1) * 60);
      const seconds =
        time.getSeconds() + Math.floor(((offset % 1) * 60) % 1) * 60;
      if (hours < 0) while (hours < 0) hours += 24;
      else if (hours >= 24) while (hours >= 24) hours -= 24;
      return (
        hours.toString().padStart(2, '0') +
        ':' +
        minutes.toString().padStart(2, '0') +
        (seconds !== 0 ? `:${seconds.toString().padStart(2, '0')}` : '')
      );
    }
  };
</script>

{#snippet renderLocalTime(
  time: Date,
  forceAbsolute = false
)}{#await localTime(time, forceAbsolute, now)}{isRelativeTime && !forceAbsolute
      ? timeRelative(time.getTime(), now)
      : time.getUTCHours() +
        ':' +
        time.getUTCMinutes() +
        (time.getUTCSeconds() !== 0 ? `:${time.getUTCSeconds()}` : '') +
        ' UTC'}{:then t}{t}{/await}{/snippet}

{#if stopTimes}
  {#each stopTimes.stopTimes
    // garbage data
    .filter((v) => v.agencyUrl !== 'http://www.rta.ae') as departure}
    {@const expectedTime =
      new Date(
        (isArrivals
          ? departure.place.scheduledArrival
          : departure.place.scheduledDeparture) ?? '0'
      ).getTime() /
      1000 /
      60}
    {@const receivedTime =
      new Date(
        (isArrivals ? departure.place.arrival : departure.place.departure) ??
          '0'
      ).getTime() /
      1000 /
      60}
    {@const delayMinutes = receivedTime - expectedTime}
    {@const avoidGlyph = departure.routeShortName.startsWith('FlixTrain')}
    {@const routeShortName = (() => {
      let n = departure.routeShortName;
      if (n.startsWith('EC ')) n = n.replace('EC ', 'EC');
      if (departure.mode === 'TRAM' && !isNaN(parseInt(n))) n = 'T ' + n;
      if (departure.mode === 'BUS' && !isNaN(parseInt(n))) n = 'B ' + n;
      if (
        departure.routeShortName === 'European Sleeper' &&
        departure.agencyName === 'Eu Sleeper'
      )
        n = 'EN'; // TODO: validate these are real euronights
      if (n === '?') n = '';
      if (n.startsWith('FlixTrain ')) n = n.substring(10);
      // Note: may also catch ECs/ICs/EXTs operated by DB
      if (
        departure.agencyId === '12681' &&
        departure.agencyName === 'DB Fernverkehr AG' &&
        departure.mode === 'HIGHSPEED_RAIL' &&
        departure.source.startsWith('de_DELFI.gtfs.zip/') &&
        !isNaN(parseInt(n))
      )
        n = `ICE ${n}`;
      return n;
    })()}
    {@const pictogram = (() => {
      switch (true) {
        case departure.mode === Mode.Bike:
          return 'Velo_l';
        case departure.mode === Mode.ODM:
        case departure.mode === Mode.Rental:
          return 'Taxi_l';
        case departure.mode === Mode.Car:
        case departure.mode === Mode.CarDropoff:
        case departure.mode === Mode.CarParking:
          return 'Auto_l';

        // Transit //
        case departure.mode === Mode.Airplane:
          return 'Abflug_l';
        case departure.mode === Mode.LongDistanceRail:
        case departure.mode === Mode.RegionalFastRail:
        case departure.mode === Mode.RegionalRail:
        case departure.mode === Mode.Metro:
        case departure.mode === Mode.HighspeedRail:
          return 'Zug_l';
        case departure.mode === Mode.NightRail:
          return 'Schlafwagen';
        case departure.mode === Mode.Subway:
          return 'Metro_l_' + (m.lang_short() === 'en' ? 'de' : m.lang_short());
        case departure.mode === Mode.Bus:
          return 'Bus_l';
        case departure.mode === Mode.Coach:
          return 'Fernbus_l';
        case departure.mode === Mode.Tram:
        case departure.mode === Mode.CableTram:
          return 'Tram_l';
        case departure.mode === Mode.Funicular:
          return 'Zahnradbahn_l';
        case departure.mode === Mode.AerialLift:
          // return 'Gondelbahn_l';
          return 'Luftseilbahn_l';
        case departure.mode === Mode.Ferry:
          return 'Schiff_l';
        case departure.mode === Mode.Other:
        default:
          return 'Licht';
      }
    })()}
    {@const notices = (() => {
      let notices = [] as [pictogram: string[], content: string][];
      if (departure.cancelled)
        notices.push([['Cancellation', 'Attention'], m.connection_cancelled()]);
      if (delayMinutes < -0.5) {
        notices.push([
          ['Hint'],
          m.connection_early({
            minutes: -delayMinutes,
            arrival: isArrivals.toString(),
          }),
        ]);
      } else if (delayMinutes >= 1) {
        notices.push([
          delayMinutes >= 3
            ? ['Delay', 'Attention']
            : delayMinutes >= 2
              ? ['Delay', 'Hint']
              : ['Hint'],
          m.connection_delayed({
            minutes: delayMinutes.toFixed(0),
          }),
        ]);
      }
      return notices;
    })()}
    {@const situationIsBad = notices.find((v) => v[0].includes('Attention'))}
    <div
      class={{
        'p-4 pr-3 sm:pr-4 md:p-6 md:pr-6 rounded-xl': true,
        'bg-[#28282C]': !situationIsBad,
        'bg-[#452525]': situationIsBad,
      }}
      data-data={dev ? JSON.stringify(departure, null, 2) : undefined}
    >
      <div class="flex gap-1 md:items-center md:flex-row flex-col flex-wrap">
        <div class="pictoline flex gap-1 md:items-center flex-r">
          {#if pictogram}
            <Pictogram which={pictogram} />
          {/if}
          {#if ([Mode.NightRail, Mode.HighspeedRail, Mode.LongDistanceRail, Mode.RegionalFastRail, Mode.RegionalRail].includes(departure.mode) || (departure.mode === 'BUS' && routeShortName.startsWith('EV')) || (departure.mode === 'METRO' && departure.routeShortName.startsWith('S'))) && !avoidGlyph}
            <LineGlyph
              currentColor="#fff"
              kind={routeShortName}
              nightIsFilled={false}
            />
          {:else}
            <span
              class="ml-1 -mr-0.5 md:mt-0.5 font-sbb-typo text-nowrap font-bold"
            >
              {routeShortName}
            </span>
          {/if}
          <span class="ml-1 -mr-0.5 md:mt-0.5 font-sbb-typo">
            <!-- {isArrivals ? m.from() : m.to()} -->
            {m.to()}
            <span class="font-semibold">{departure.headsign}</span>
          </span>
        </div>
        <div class="flex-1"></div>
        {#if departure.place.scheduledTrack && departure.place.track}
          <span
            class={{
              'ml-1 mt-0.5 font-[SBB,Inter,system-ui,sans-serif]': true,
              'text-red-400':
                departure.place.scheduledTrack !== departure.place.track,
            }}
          >
            {#if departure.place.name !== placeName}{`${
                departure.place.name === placeName + ', Bahnhof'
                  ? placeName + ', Busbahnhof'
                  : departure.place.name
              }, `}
            {/if}<span class="font-semibold"
              >{m.station_location({
                track: departure.place.track,
                mode: departure.mode,
              })}</span
            >
          </span>
        {:else if departure.place.name !== placeName}{departure.place.name ===
          placeName + ', Bahnhof'
            ? placeName + ', Busbahnhof'
            : departure.place.name}
        {/if}
      </div>
      <div class="flex gap-1 items-center">
        {departure.cancelled
          ? m.antsy_weird_cowfish_wish() + ' '
          : ''}{isRelativeTime && Math.abs(expectedTime - receivedTime) < 1
          ? isArrivals
            ? m.arrival_in()
            : m.departure_in()
          : isArrivals
            ? m.arrival_at()
            : m.departure_at()}
        {#if Math.abs(expectedTime - receivedTime) < 1}
          <span class="font-bold">
            {@render renderLocalTime(new Date(receivedTime * 60 * 1000))}
          </span>
        {:else}
          <span class="line-through">
            {@render renderLocalTime(new Date(expectedTime * 60 * 1000), true)}
          </span>
          <span class="font-bold">
            {@render renderLocalTime(new Date(receivedTime * 60 * 1000), true)}
          </span>
          {#if isRelativeTime}
            <span class="opacity">
              ({@render renderLocalTime(new Date(receivedTime * 60 * 1000))})
            </span>
          {/if}
        {/if}
      </div>
      {#if notices.length !== 0}
        <div class="notices pt-2 flex flex-col gap-1">
          {#each notices as notice}
            <div class="flex items-center gap-2">
              {#each notice[0] as pictogram}<Pictogram
                  which={pictogram}
                />{/each}
              <span class="ml-0.5">
                {notice[1]}
              </span>
            </div>
          {/each}
        </div>
      {/if}
      <!-- <pre>{JSON.stringify(departure, null, 2)}</pre> -->
      {#if departure.agencyName}
        <small class="-mb-1 mt-2 block opacity-70"
          >{m.operated_by({
            operator: operators.has(departure.agencyName)
              ? operators.get(departure.agencyName)!
              : departure.agencyName,
          })}{#if departure.agencyName === 'DB Fernverkehr AG'}
            {' '}
            <b>·</b>
            {m.line_number_accuracy()}{/if}</small
        >
      {/if}
    </div>
  {/each}
{:else}
  <div class="flex items-center justify-center">
    <div class="results">
      {#if (placeName || placeId) && isResultsPage}
        <h2 class="text-2xl opacity-90">No results</h2>
        <p>
          No results have been found for the station <b
            >{placeName ?? placeId}</b
          >.<br />
          Please try again.
        </p>
      {:else if placeId}
        <h2 class="text-2xl opacity-90">No results</h2>
        <p>
          No results have been found for the station <b
            >{placeName ?? placeId}</b
          >.<br />
          Please try again.
        </p>
      {:else}
        <h2 class="text-2xl opacity-90">No Station</h2>
        <p class="pb-1">
          Please input a station in the search field above and select a search
          result.
        </p>
        <p class="py-1">
          Examples:
          <span class="pt-2 flex flex-wrap gap-2 max-w-xl">
            <button
              class="{S.button('secondary').replace(
                'not-disabled:bg-[#0000]',
                'not-disabled:bg-[#2E2E3299]'
              )} flex-1 text-nowrap p-3 w-max min-w-20"
              onclick={() => setSearch('Zürich HB')}>Zürich HB</button
            >
            <button
              class="{S.button('secondary').replace(
                'not-disabled:bg-[#0000]',
                'not-disabled:bg-[#2E2E3299]'
              )} flex-1 text-nowrap p-3 w-max min-w-20"
              onclick={() => setSearch('Bielefeld Hbf')}>Bielefeld Hbf</button
            >
            <button
              class="{S.button('secondary').replace(
                'not-disabled:bg-[#0000]',
                'not-disabled:bg-[#2E2E3299]'
              )} flex-1 text-nowrap p-3 w-max min-w-20"
              onclick={() => setSearch('Berlin Hbf')}>Berlin Hbf</button
            >
            <button
              class="{S.button('secondary').replace(
                'not-disabled:bg-[#0000]',
                'not-disabled:bg-[#2E2E3299]'
              )} flex-1 text-nowrap p-3 w-max min-w-20"
              onclick={() => setSearch('Hamburg Hbf')}>Hamburg Hbf</button
            >
            <button
              class="{S.button('secondary').replace(
                'not-disabled:bg-[#0000]',
                'not-disabled:bg-[#2E2E3299]'
              )} flex-1 text-nowrap p-3 w-max min-w-20"
              onclick={() => setSearch('Bern')}>Bern</button
            >
            <button
              class="{S.button('secondary').replace(
                'not-disabled:bg-[#0000]',
                'not-disabled:bg-[#2E2E3299]'
              )} flex-1 text-nowrap p-3 w-max min-w-20"
              onclick={() => setSearch('Basel SBB')}>Basel SBB</button
            >
            <button
              class="{S.button('secondary').replace(
                'not-disabled:bg-[#0000]',
                'not-disabled:bg-[#2E2E3299]'
              )} flex-1 text-nowrap p-3 w-max min-w-20"
              onclick={() => setSearch('Genève-Aéroport')}
              >Genève-Aéroport</button
            >
          </span>
        </p>
      {/if}
    </div>
  </div>
{/if}