File size: 11,945 Bytes
ddd0be5
 
 
d5ea29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd0be5
 
 
 
d5ea29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd0be5
 
 
 
d5ea29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd0be5
 
 
 
 
 
 
 
 
 
 
 
d5ea29f
ddd0be5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ea29f
 
ddd0be5
d5ea29f
 
 
ddd0be5
d5ea29f
 
 
ddd0be5
d5ea29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd0be5
 
 
 
 
 
d5ea29f
 
 
ddd0be5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ea29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd0be5
d5ea29f
 
 
 
 
 
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
// Export the field as a standalone, shareable image: a dark card with the player's photo (or team logo), name and
// season, a strip of the chart's key numbers, the 2D field (whatever 3D tilt is on screen), a legend, the filters in
// force and a source line - as PNG (2x), SVG, or straight to the clipboard.

const NS = "http://www.w3.org/2000/svg"
const SANS = "Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Helvetica, Arial, sans-serif"
const MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"

export type LegendSpec =
  | { items: [string, string][]; dashed?: boolean }
  | { gradient: [string, string, string]; lo: string; hi: string }

export interface HeatImage { url: string; x: number; y: number; w: number; h: number }

export interface ExportOptions {
  view: "plays" | "heat"
  heat?: HeatImage | null
  title: string
  subtitle: string
  /** who the chart is of: the photo (or team logo, drawn square) goes beside the name */
  subject?: { name: string; line: string; image?: string | null; logo?: boolean }
  /** the chart's key numbers, shown as a strip under the header */
  stats?: { label: string; value: string }[]
  legend: LegendSpec
  filename: string
  format: "png" | "svg" | "clipboard"
}

function el(name: string, attrs: Record<string, string | number>, text?: string) {
  const e = document.createElementNS(NS, name)
  for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, String(v))
  if (text != null) e.textContent = text
  return e
}

/** The card as SVG markup, plus its pixel size. */
export function buildChartSvg(src: SVGSVGElement, o: ExportOptions): { markup: string; width: number; height: number } {
  const vb = src.viewBox.baseVal
  const field = src.cloneNode(true) as SVGSVGElement
  field.removeAttribute("class")
  field.removeAttribute("style")
  // the two layers: plays on their own, or the heatmap over faint plays
  const plays = field.querySelector('[data-layer="plays"]')
  let heat = field.querySelector('[data-layer="heat"]')
  if (o.view === "plays") {
    heat?.remove()
    plays?.setAttribute("opacity", "1")
  } else {
    if (!heat && o.heat) {
      heat = el("image", { href: o.heat.url, x: o.heat.x, y: o.heat.y, width: o.heat.w, height: o.heat.h, preserveAspectRatio: "none",
        style: "mix-blend-mode: screen", "data-layer": "heat" })
      plays?.parentNode?.insertBefore(heat, plays)
    }
    plays?.setAttribute("opacity", "0.18")
  }
  // nothing interactive or half-animated in a still image
  field.querySelectorAll("[class]").forEach((n) => n.removeAttribute("class"))
  field.querySelectorAll("[style]").forEach((n) => {
    if (n.getAttribute("data-layer") !== "heat") n.removeAttribute("style")
  })

  const W = 1600
  const pad = 56
  const who = o.subject
  const headH = who ? 200 : 150
  const stats = o.stats ?? []
  const statH = stats.length ? 116 : 0
  const fw = W - 2 * pad
  const fh = Math.round((fw * vb.height) / vb.width)
  // lay the legend out first (it may wrap) so the card can be sized to fit
  const rows: { label: string; color: string; x: number; row: number }[] = []
  if ("items" in o.legend) {
    let x = pad
    let row = 0
    const entries: [string, string][] = [...o.legend.items, ...(o.legend.dashed ? [["unmatched", ""] as [string, string]] : [])]
    for (const [label, color] of entries) {
      const w = 24 + label.length * 10.5 + 34
      if (x + w > W - pad && x > pad) {
        x = pad
        row += 1
      }
      rows.push({ label, color, x, row })
      x += w
    }
  }
  const legendRows = rows.length ? Math.max(...rows.map((r) => r.row)) + 1 : 1
  // the filters line wraps to the card's width (~95 characters a line at this size)
  const sub = wrap(o.subtitle, 118)
  const footH = 48 + 34 * legendRows + 30 * sub.length + 64
  const fieldY = headH + statH
  const H = fieldY + fh + footH
  const out = el("svg", { xmlns: NS, "xmlns:xlink": "http://www.w3.org/1999/xlink", width: W, height: H, viewBox: `0 0 ${W} ${H}`, "font-family": SANS })
  const defs = el("defs", {})
  out.append(defs)
  // background: near-black with a soft green glow from the top left
  const glow = el("radialGradient", { id: "export-glow", cx: 0, cy: 0, r: 1, gradientUnits: "objectBoundingBox" })
  glow.append(el("stop", { offset: 0, "stop-color": "#10b981", "stop-opacity": 0.16 }), el("stop", { offset: 0.55, "stop-color": "#10b981", "stop-opacity": 0 }))
  defs.append(glow)
  out.append(el("rect", { x: 0, y: 0, width: W, height: H, fill: "#0b0c0f" }))
  out.append(el("rect", { x: 0, y: 0, width: W, height: Math.min(H, 900), fill: "url(#export-glow)" }))
  out.append(el("rect", { x: 0, y: 0, width: W, height: 5, fill: "#10b981" }))

  if (who) {
    const r = 64
    const cx = pad + r
    const cy = 100
    if (who.image) {
      const clip = el("clipPath", { id: "export-face" })
      clip.append(who.logo ? el("rect", { x: cx - r, y: cy - r, width: 2 * r, height: 2 * r, rx: 22 }) : el("circle", { cx, cy, r }))
      defs.append(clip)
      out.append(who.logo ? el("rect", { x: cx - r, y: cy - r, width: 2 * r, height: 2 * r, rx: 22, fill: "#16181d" }) : el("circle", { cx, cy, r, fill: "#16181d" }))
      const inset = who.logo ? 14 : 0
      out.append(el("image", { href: who.image, x: cx - r + inset, y: cy - r + inset, width: 2 * (r - inset), height: 2 * (r - inset),
        preserveAspectRatio: who.logo ? "xMidYMid meet" : "xMidYMid slice", "clip-path": "url(#export-face)" }))
    }
    out.append(who.logo ? el("rect", { x: cx - r, y: cy - r, width: 2 * r, height: 2 * r, rx: 22, fill: "none", stroke: "#10b981", "stroke-width": 3 })
      : el("circle", { cx, cy, r, fill: "none", stroke: "#10b981", "stroke-width": 3 }))
    const tx = cx + r + 32
    out.append(el("text", { x: tx, y: 74, fill: "#34d399", "font-size": 19, "font-family": MONO, "letter-spacing": 2.5 }, who.line.toUpperCase()))
    out.append(el("text", { x: tx, y: 128, fill: "#fafafa", "font-size": 54, "font-weight": 700, "letter-spacing": -1 }, who.name))
    out.append(el("text", { x: tx, y: 166, fill: "#a1a1aa", "font-size": 23 }, o.title))
  } else {
    out.append(el("text", { x: pad, y: 78, fill: "#fafafa", "font-size": 44, "font-weight": 600, "letter-spacing": -0.5 }, o.title))
  }
  // wordmark, top right: "Gridiron" in green, "Matrix" muted
  out.append(el("text", { x: W - pad, y: 76, "text-anchor": "end", "font-size": 22, fill: "#71717a" }, "Matrix"))
  out.append(el("text", { x: W - pad - 74, y: 76, "text-anchor": "end", "font-size": 22, "font-weight": 600, fill: "#10b981" }, "Gridiron"))

  // the numbers: equal boxes across the card
  if (stats.length) {
    const gap = 14
    const bw = (fw - gap * (stats.length - 1)) / stats.length
    stats.forEach((st, i) => {
      const x = pad + i * (bw + gap)
      const y = headH
      out.append(el("rect", { x, y, width: bw, height: 92, rx: 14, fill: "#121419", stroke: "#23262d" }))
      out.append(el("text", { x: x + 22, y: y + 32, fill: "#8b8b94", "font-size": 17, "letter-spacing": 0.5 }, st.label))
      out.append(el("text", { x: x + 22, y: y + 74, fill: "#fafafa", "font-size": 36, "font-weight": 600, "font-family": MONO }, st.value))
    })
  }

  field.setAttribute("x", String(pad))
  field.setAttribute("y", String(fieldY))
  field.setAttribute("width", String(fw))
  field.setAttribute("height", String(fh))
  field.setAttribute("font-family", MONO)
  out.append(el("rect", { x: pad - 1, y: fieldY - 1, width: fw + 2, height: fh + 2, rx: 14, fill: "#101215", stroke: "#27272a" }))
  out.append(field)

  // legend
  const ly = fieldY + fh + 52
  const lg = el("g", { "font-size": 19, fill: "#d4d4d8" })
  if ("items" in o.legend) {
    for (const { label, color, x, row } of rows) {
      const y = ly + row * 34
      if (color) lg.append(el("circle", { cx: x + 8, cy: y - 6, r: 8, fill: color }))
      else lg.append(el("line", { x1: x - 4, x2: x + 18, y1: y - 6, y2: y - 6, stroke: "#a1a1aa", "stroke-width": 3, "stroke-dasharray": "6 5" }))
      lg.append(el("text", { x: x + 24, y }, label))
    }
  } else {
    const [a, b, c] = o.legend.gradient
    const grad = el("linearGradient", { id: "export-legend", x1: 0, x2: 1, y1: 0, y2: 0 })
    grad.append(el("stop", { offset: 0, "stop-color": a }), el("stop", { offset: 0.5, "stop-color": b }), el("stop", { offset: 1, "stop-color": c }))
    defs.append(grad)
    lg.append(el("text", { x: pad, y: ly }, o.legend.lo))
    const gx = pad + o.legend.lo.length * 10.5 + 18
    lg.append(el("rect", { x: gx, y: ly - 14, width: 260, height: 14, rx: 7, fill: "url(#export-legend)" }))
    lg.append(el("text", { x: gx + 278, y: ly }, o.legend.hi))
  }
  out.append(lg)
  // what's on the chart (filters, weeks, colouring), then the source line
  const sy = ly + 34 * legendRows + 8
  sub.forEach((line, i) => out.append(el("text", { x: pad, y: sy + i * 30, fill: "#8b8b94", "font-size": 19 }, line)))
  out.append(el("line", { x1: pad, x2: W - pad, y1: H - 50, y2: H - 50, stroke: "#23262d" }))
  out.append(el("text", { x: pad, y: H - 20, fill: "#6b6b74", "font-size": 16 }, "Data: NFL Next Gen Stats charts, read and matched to nflverse play-by-play"))
  out.append(el("text", { x: W - pad, y: H - 20, "text-anchor": "end", fill: "#6b6b74", "font-size": 16 }, "Not affiliated with the NFL"))
  return { markup: new XMLSerializer().serializeToString(out), width: W, height: H }
}

/** greedy word wrap to about `n` characters a line */
function wrap(text: string, n: number): string[] {
  const out: string[] = []
  let line = ""
  for (const w of text.split(" ")) {
    if (line && (line + " " + w).length > n) {
      out.push(line)
      line = w
    } else line = line ? `${line} ${w}` : w
  }
  if (line) out.push(line)
  return out
}

/** an image as a data: URL, so the rasterised SVG (which can't load anything external) can draw it */
async function inline(url: string | null | undefined): Promise<string | null> {
  if (!url) return null
  try {
    const r = await fetch(url, { mode: "cors" })
    if (!r.ok) return null
    const b = await r.blob()
    return await new Promise((ok) => {
      const fr = new FileReader()
      fr.onload = () => ok(String(fr.result))
      fr.onerror = () => ok(null)
      fr.readAsDataURL(b)
    })
  } catch {
    return null
  }
}

function download(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob)
  const a = document.createElement("a")
  a.href = url
  a.download = filename
  document.body.append(a)
  a.click()
  a.remove()
  setTimeout(() => URL.revokeObjectURL(url), 2000)
}

async function rasterize(markup: string, width: number, height: number, scale = 2): Promise<Blob> {
  const url = URL.createObjectURL(new Blob([markup], { type: "image/svg+xml;charset=utf-8" }))
  try {
    const img = new Image()
    img.decoding = "async"
    await new Promise<void>((ok, fail) => {
      img.onload = () => ok()
      img.onerror = () => fail(new Error("couldn't render the chart"))
      img.src = url
    })
    const canvas = document.createElement("canvas")
    canvas.width = width * scale
    canvas.height = height * scale
    const ctx = canvas.getContext("2d")!
    ctx.scale(scale, scale)
    ctx.drawImage(img, 0, 0, width, height)
    return await new Promise<Blob>((ok, fail) => canvas.toBlob((b) => (b ? ok(b) : fail(new Error("couldn't encode PNG"))), "image/png"))
  } finally {
    URL.revokeObjectURL(url)
  }
}

export async function exportChart(src: SVGSVGElement, o: ExportOptions) {
  if (o.subject?.image) o = { ...o, subject: { ...o.subject, image: await inline(o.subject.image) } }
  const { markup, width, height } = buildChartSvg(src, o)
  if (o.format === "svg") return download(new Blob([markup], { type: "image/svg+xml" }), `${o.filename}.svg`)
  const png = await rasterize(markup, width, height)
  if (o.format === "png") return download(png, `${o.filename}.png`)
  await navigator.clipboard.write([new ClipboardItem({ "image/png": png })])
}