aboutsummaryrefslogtreecommitdiff
path: root/source/library/components/ResultViewer.svelte
blob: d277ec8dfcdb72669dd9077da1b47f482dbb27ab (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
<script lang="ts">
  import Editor from "./Editor.svelte";
  import type { Extension } from "@codemirror/state";
  import type { Snippet } from "svelte";
  import type { TabTiming } from "../state/session.svelte.ts";

  type Props = {
    footer?: Snippet<[{ result: string }]>;
    streamIntervals?: number[];
    theme?: Extension;
    timing?: TabTiming | null;
    value: string;
  };

  let {
    footer,
    streamIntervals = [],
    theme,
    timing = null,
    value
  }: Props = $props();

  function median(values: number[]): number {
    if (values.length === 0)
      return 0;

    const sorted = [...values].sort((a, b) => a - b);
    const mid = Math.floor(sorted.length / 2);

    return sorted.length % 2 === 0 ?
      (sorted[mid - 1] + sorted[mid]) / 2 :
      sorted[mid];
  }

  let metadata = $derived.by(() => {
    if (!timing)
      return null;

    if (streamIntervals.length > 0) {
      const medianMs = Math.round(median(streamIntervals));
      const messages = streamIntervals.length + 1;
      return `→ ${messages} messages · median ${medianMs}ms`;
    }

    const totalMs = Math.round(timing.endMs - timing.startMs);
    const firstByteMs = Math.round(timing.firstByteMs - timing.startMs);
    return `→ ${totalMs}ms · first byte ${firstByteMs}ms`;
  });

  function noop(_v: string) {}
</script>

<style lang="scss">
  .result {
    display: grid;
    grid-template-rows: auto 1fr auto auto;
    height: 100%;
    min-height: 0;
  }

  .label {
    background: var(--graphiql-panel, #252526);
    font-size: 0.75rem;
    letter-spacing: 0.05em;
    padding: 0.25rem 0.75rem;
    text-transform: uppercase;
  }

  .metadata {
    background: var(--graphiql-panel, #252526);
    border-top: 1px solid var(--graphiql-border, #333);
    color: var(--graphiql-muted, #858585);
    font-size: 0.75rem;
    padding: 0.25rem 0.75rem;
  }

  .footer {
    background: var(--graphiql-panel, #252526);
    border-top: 1px solid var(--graphiql-border, #333);
    font-size: 0.75rem;
    padding: 0.25rem 0.75rem;
  }
</style>

<div class="result">
  <div class="label">Response</div>
  <Editor language="json" onChange={noop} readOnly {theme} {value}/>
  {#if metadata}
    <div class="metadata">{metadata}</div>
  {/if}
  {#if footer}
    <div class="footer">{@render footer({ result: value })}</div>
  {/if}
</div>