{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# reactable themes and titles\n",
    "\n",
    "reactablefmtr dresses an R reactable with a title, subtitle, source line, legend and Google font, and ships 27 table\n",
    "themes, from ESPN's and The New York Times' to Bootswatch's. `sdvplot.reactable` ports both to reactable-py:\n",
    "`reactable_sdv_frame` wraps a `Reactable` in that furniture (with `reactable_sdv_legend` or\n",
    "`reactable_sdv_icon_legend` for the legend), `reactable_sdv_theme(name)` returns any of the 27 themes as a\n",
    "`reactable.Theme` with reactablefmtr's own colors, fonts, borders and paddings, and `reactable_sdv_theme_team` builds a\n",
    "theme from a team's colors. The data is the 2025 NFL season, the 2025-26 NHL and men's college basketball seasons and\n",
    "the 2026 WNBA season, all loaded through sportsdataverse-py."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import polars as pl\n",
    "import sportsdataverse.mbb as mbb\n",
    "import sportsdataverse.nfl as nfl\n",
    "import sportsdataverse.nhl as nhl\n",
    "import sportsdataverse.wnba as wnba\n",
    "from htmltools import tags\n",
    "from matplotlib.colors import LinearSegmentedColormap, to_hex\n",
    "from reactable import Column, Reactable, embed_css\n",
    "from reactable.tags import to_widget\n",
    "\n",
    "from sdvplot.reactable import (\n",
    "    reactable_sdv_frame,\n",
    "    reactable_sdv_icon_legend,\n",
    "    reactable_sdv_legend,\n",
    "    reactable_sdv_logos,\n",
    "    reactable_sdv_theme,\n",
    "    reactable_sdv_theme_team,\n",
    ")\n",
    "\n",
    "NFL_SEASON = 2025  # nflverse names a season by the year it starts\n",
    "SEASON = 2026  # the 2026 WNBA season and the 2025-26 NHL and men's college basketball seasons\n",
    "SOURCE = \"Data: sportsdataverse-py\"\n",
    "embed_css()\n",
    "\n",
    "weeks = nfl.load_nfl_team_stats([NFL_SEASON]).filter(pl.col(\"season_type\") == \"REG\")\n",
    "dropbacks = pl.col(\"attempts\") + pl.col(\"sacks_suffered\")\n",
    "nfl_epa = (\n",
    "    weeks.group_by(\"team\")\n",
    "    .agg(\n",
    "        epa=(pl.col(\"passing_epa\") + pl.col(\"rushing_epa\")).sum() / (dropbacks + pl.col(\"carries\")).sum(),\n",
    "        pass_epa=pl.col(\"passing_epa\").sum() / dropbacks.sum(),\n",
    "        rush_epa=pl.col(\"rushing_epa\").sum() / pl.col(\"carries\").sum(),\n",
    "    )\n",
    "    .with_columns(pl.selectors.float().round(3), logo=pl.col(\"team\"))\n",
    "    .sort(\"epa\", descending=True)\n",
    "    .select(\"logo\", \"team\", \"epa\", \"pass_epa\", \"rush_epa\")\n",
    ")\n",
    "nfl_epa.head(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "## 1. Title, subtitle, source, legend and font\n",
    "\n",
    "`reactable_sdv_frame` puts a title and subtitle over the table and a legend and source line under it, with\n",
    "reactablefmtr's sizes (a 32 px title, a 24 px subtitle, a 16 px source). `font` names a Google font, loaded when the\n",
    "page shows, for the whole frame, table included. The legend here is the one the cells are colored with: the EPA\n",
    "cells sit on a three-color ramp over the column's range, and `reactable_sdv_legend(bins=5)` spreads the same three\n",
    "colors over five swatches labelled with the values they stand for. The result displays like any `Reactable`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "RAMP = [\"#d7191c\", \"#ffffbf\", \"#1a9641\"]\n",
    "cmap = LinearSegmentedColormap.from_list(\"epa\", RAMP)\n",
    "lo, hi = nfl_epa[\"epa\"].min(), nfl_epa[\"epa\"].max()\n",
    "\n",
    "\n",
    "def epa_fill(info):\n",
    "    return {\"background-color\": to_hex(cmap((info.value - lo) / (hi - lo)))}\n",
    "\n",
    "\n",
    "table = Reactable(\n",
    "    nfl_epa,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"nfl\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "        Column(id=\"team\", name=\"Team\"),\n",
    "        Column(id=\"epa\", name=\"EPA/play\", style=epa_fill),\n",
    "        Column(id=\"pass_epa\", name=\"Pass EPA\"),\n",
    "        Column(id=\"rush_epa\", name=\"Rush EPA\"),\n",
    "    ],\n",
    "    default_page_size=10,\n",
    "    compact=True,\n",
    ")\n",
    "steps = [lo + i * (hi - lo) / 4 for i in range(5)]\n",
    "reactable_sdv_frame(\n",
    "    table,\n",
    "    title=\"Who moved the ball in 2025\",\n",
    "    subtitle=\"Expected points added per play, NFL regular season\",\n",
    "    source=SOURCE,\n",
    "    legend=reactable_sdv_legend(colors=RAMP, bins=5, labels=[f\"{v:+.2f}\" for v in steps], title=\"EPA/play\"),\n",
    "    font=\"Roboto Condensed\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "`reactable_sdv_icon_legend` explains icons rather than colors. Its shapes are inline SVG (no icon font to load), so a\n",
    "cell can draw the same shape with the same color. Here a filled circle marks the teams with a winning record and EPA\n",
    "above zero:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "games = nfl.load_nfl_schedule([NFL_SEASON]).filter(pl.col(\"game_type\") == \"REG\")\n",
    "sides = [(\"home_team\", \"home_score\", \"away_score\"), (\"away_team\", \"away_score\", \"home_score\")]\n",
    "records = (\n",
    "    pl.concat(games.select(team=pl.col(t), win=(pl.col(us) > pl.col(them)).cast(pl.Int32)) for t, us, them in sides)\n",
    "    .group_by(\"team\")\n",
    "    .agg(w=pl.col(\"win\").sum(), gp=pl.len())\n",
    ")\n",
    "both = (\n",
    "    nfl_epa.join(records, on=\"team\")\n",
    "    .with_columns(good=(pl.col(\"w\") * 2 > pl.col(\"gp\")) & (pl.col(\"epa\") > 0))\n",
    "    .sort(\"w\", descending=True)\n",
    ")\n",
    "\n",
    "\n",
    "def dot(color):\n",
    "    return f'<svg viewBox=\"0 0 16 16\" width=\"12\" height=\"12\"><circle cx=\"8\" cy=\"8\" r=\"7\" fill=\"{color}\"/></svg>'\n",
    "\n",
    "\n",
    "reactable_sdv_frame(\n",
    "    Reactable(\n",
    "        both.select(\"logo\", \"team\", \"w\", \"epa\", \"good\"),\n",
    "        columns=[\n",
    "            reactable_sdv_logos(league=\"nfl\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "            Column(id=\"team\", name=\"Team\"),\n",
    "            Column(id=\"w\", name=\"Wins\"),\n",
    "            Column(id=\"epa\", name=\"EPA/play\"),\n",
    "            Column(id=\"good\", name=\"\", html=True, cell=lambda info: dot(\"#1a9641\" if info.value else \"#d9d9d9\")),\n",
    "        ],\n",
    "        default_page_size=8,\n",
    "        compact=True,\n",
    "    ),\n",
    "    title=\"Winning and efficient\",\n",
    "    source=SOURCE,\n",
    "    legend=reactable_sdv_icon_legend(\n",
    "        icons=\"circle\", colors=[\"#1a9641\", \"#d9d9d9\"], labels=[\"winning record and positive EPA\", \"the rest\"]\n",
    "    ),\n",
    "    align=\"left\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 2. The sports-media themes\n",
    "\n",
    "Four of reactablefmtr's themes copy a newsroom's tables: `espn`, `nytimes`, `fivethirtyeight` and `pff`. Each is a\n",
    "`reactable.Theme` built from reactablefmtr's own values (its `espn()` gives a 12 px gray body, 11 px uppercase headers\n",
    "between light rules and 7 px of padding, for one), so pass it to `Reactable(theme=...)`; every argument the R function takes, such\n",
    "as `font_size` or `header_font_color`, can be overridden. First ESPN's look on the NHL's final 2025-26 standings:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "nhl_table = (\n",
    "    nhl.nhl_standings(\"2026-04-16\")\n",
    "    .select(team=\"team_abbrev_default\", gp=\"games_played\", w=\"wins\", l=\"losses\", otl=\"ot_losses\", pts=\"points\")\n",
    "    .with_columns(logo=pl.col(\"team\"))\n",
    "    .sort(\"pts\", descending=True)\n",
    "    .head(10)\n",
    "    .select(\"logo\", \"team\", \"gp\", \"w\", \"l\", \"otl\", \"pts\")\n",
    ")\n",
    "reactable_sdv_frame(\n",
    "    Reactable(\n",
    "        nhl_table,\n",
    "        columns=[\n",
    "            reactable_sdv_logos(league=\"nhl\", id=\"logo\", name=\"\", width=46, height=24),\n",
    "            Column(id=\"team\", name=\"TEAM\"),\n",
    "            Column(id=\"gp\", name=\"GP\"),\n",
    "            Column(id=\"w\", name=\"W\"),\n",
    "            Column(id=\"l\", name=\"L\"),\n",
    "            Column(id=\"otl\", name=\"OTL\"),\n",
    "            Column(id=\"pts\", name=\"PTS\"),\n",
    "        ],\n",
    "        theme=reactable_sdv_theme(\"espn\"),\n",
    "    ),\n",
    "    subtitle=\"NHL standings, 2025-26: the top ten\",\n",
    "    source=SOURCE,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "`nytimes` on the WNBA's 2026 scoring leaders (20 or more games), its 13 px body and gray 11 px headers between thin\n",
    "rules:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "schedule = wnba.load_wnba_schedule(seasons=[SEASON]).filter(\n",
    "    (pl.col(\"season_type\") == 2) & (pl.col(\"type_abbreviation\") == \"STD\")\n",
    ")\n",
    "players = wnba.load_wnba_player_boxscore(seasons=[SEASON]).filter(\n",
    "    pl.col(\"game_id\").is_in(schedule[\"game_id\"].implode()) & ~pl.col(\"did_not_play\")\n",
    ")\n",
    "scorers = (\n",
    "    players.group_by(\"athlete_display_name\")\n",
    "    .agg(team=pl.col(\"team_abbreviation\").last(), gp=pl.len(), ppg=pl.col(\"points\").mean().round(1))\n",
    "    .filter(pl.col(\"gp\") >= 20)\n",
    "    .sort(\"ppg\", descending=True)\n",
    "    .head(10)\n",
    ")\n",
    "reactable_sdv_frame(\n",
    "    Reactable(\n",
    "        scorers,\n",
    "        columns=[\n",
    "            Column(id=\"athlete_display_name\", name=\"Player\", min_width=170),\n",
    "            Column(id=\"team\", name=\"Team\"),\n",
    "            Column(id=\"gp\", name=\"Games\"),\n",
    "            Column(id=\"ppg\", name=\"Points per game\"),\n",
    "        ],\n",
    "        theme=reactable_sdv_theme(\"nytimes\"),\n",
    "    ),\n",
    "    title=\"The WNBA's top scorers\",\n",
    "    source=SOURCE,\n",
    "    font=\"Libre Franklin\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "`fivethirtyeight` on the top 15 of men's college basketball's 2025-26 adjusted efficiency ratings, and `pff` (its\n",
    "slate-gray header bar) on the NFL's best passing offenses:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "names = mbb.load_mbb_team_boxscore(seasons=[SEASON]).select(\"team_id\", \"team_location\").unique(\"team_id\")\n",
    "mbb_ratings = mbb.load_mbb_ratings(SEASON).with_columns(pl.col(\"team_id\").cast(pl.Int32))  # ids ship as text here\n",
    "assert names.schema[\"team_id\"] == mbb_ratings.schema[\"team_id\"]\n",
    "top15 = (\n",
    "    mbb_ratings.sort(\"rank\")\n",
    "    .head(15)\n",
    "    .join(names, on=\"team_id\", how=\"left\")\n",
    "    .with_columns(pl.col(\"adj_em\", \"adj_o\", \"adj_d\").round(1))\n",
    "    .select(\"rank\", \"team_location\", \"adj_em\", \"adj_o\", \"adj_d\")\n",
    ")\n",
    "reactable_sdv_frame(\n",
    "    Reactable(\n",
    "        top15,\n",
    "        columns=[\n",
    "            Column(id=\"rank\", name=\"RANK\", width=60),\n",
    "            Column(id=\"team_location\", name=\"TEAM\", min_width=150),\n",
    "            Column(id=\"adj_em\", name=\"ADJ. MARGIN\"),\n",
    "            Column(id=\"adj_o\", name=\"ADJ. OFFENSE\"),\n",
    "            Column(id=\"adj_d\", name=\"ADJ. DEFENSE\"),\n",
    "        ],\n",
    "        theme=reactable_sdv_theme(\"fivethirtyeight\"),\n",
    "        default_page_size=15,\n",
    "    ),\n",
    "    title=\"College basketball's best, by adjusted margin\",\n",
    "    source=SOURCE,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12",
   "metadata": {},
   "outputs": [],
   "source": [
    "passing = nfl_epa.sort(\"pass_epa\", descending=True).head(10)\n",
    "Reactable(\n",
    "    passing,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"nfl\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "        Column(id=\"team\", name=\"TEAM\"),\n",
    "        Column(id=\"pass_epa\", name=\"PASS EPA\"),\n",
    "        Column(id=\"rush_epa\", name=\"RUSH EPA\"),\n",
    "        Column(id=\"epa\", name=\"EPA\"),\n",
    "    ],\n",
    "    theme=reactable_sdv_theme(\"pff\", centered=True),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13",
   "metadata": {},
   "source": [
    "## 3. The other 23 themes\n",
    "\n",
    "The rest, each on the same five rows (the NFL's top offenses by EPA per play), titled with its name. A\n",
    "`reactable_sdv_frame` is htmltools markup, so several fit in one grid: `reactable.tags.to_widget` shows the grid as one\n",
    "widget. The dark themes (`cyborg`, `dark`, `darkly`, `hoverlight`, `midnight`, `midnightblue`, `slate`, `superhero`)\n",
    "bring their own background; `hoverdark` and `hoverlight` restyle a row as the pointer passes over it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14",
   "metadata": {},
   "outputs": [],
   "source": [
    "others = [\"cerulean\", \"clean\", \"cosmo\", \"cyborg\", \"dark\", \"darkly\", \"default\", \"flatly\", \"hoverdark\", \"hoverlight\",\n",
    "          \"journal\", \"lux\", \"midnight\", \"midnightblue\", \"minty\", \"no_lines\", \"sandstone\", \"sanfran\", \"slate\",\n",
    "          \"spacelab\", \"sunrise\", \"superhero\", \"void\"]  # fmt: skip\n",
    "top5 = nfl_epa.head(5).select(\"team\", \"epa\", \"pass_epa\", \"rush_epa\")\n",
    "cards = [\n",
    "    tags.div(\n",
    "        reactable_sdv_frame(\n",
    "            Reactable(top5, theme=reactable_sdv_theme(name, font_size=13, header_font_size=13), compact=True),\n",
    "            subtitle=name,\n",
    "        ),\n",
    "        style=\"min-width:0\",\n",
    "    )\n",
    "    for name in others\n",
    "]\n",
    "to_widget(tags.div(*cards, style=\"display:grid;grid-template-columns:repeat(auto-fill, minmax(300px, 1fr));gap:16px\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15",
   "metadata": {},
   "source": [
    "## 4. A team's own theme\n",
    "\n",
    "`reactable_sdv_theme_team(team, league)` fills the header with the team's primary color over a rule in its\n",
    "secondary, tints the stripes and hover with the primary, and picks black or white for every text by contrast, so the\n",
    "same call works for a light primary and a dark one. The Chiefs' and the Packers' 2025 regular seasons, game by game:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16",
   "metadata": {},
   "outputs": [],
   "source": [
    "def game_log(team):\n",
    "    home = games.filter(pl.col(\"home_team\") == team).select(\n",
    "        \"week\", opp=\"away_team\", pf=\"home_score\", pa=\"away_score\", at=pl.lit(\"vs\")\n",
    "    )\n",
    "    away = games.filter(pl.col(\"away_team\") == team).select(\n",
    "        \"week\", opp=\"home_team\", pf=\"away_score\", pa=\"home_score\", at=pl.lit(\"@\")\n",
    "    )\n",
    "    return (\n",
    "        pl.concat([home, away])\n",
    "        .sort(\"week\")\n",
    "        .with_columns(result=pl.when(pl.col(\"pf\") > pl.col(\"pa\")).then(pl.lit(\"W\")).otherwise(pl.lit(\"L\")))\n",
    "        .select(\"week\", \"at\", \"opp\", \"result\", \"pf\", \"pa\")\n",
    "    )\n",
    "\n",
    "\n",
    "def team_table(team, name):\n",
    "    return reactable_sdv_frame(\n",
    "        Reactable(\n",
    "            game_log(team),\n",
    "            columns=[\n",
    "                Column(id=\"week\", name=\"Week\", width=70),\n",
    "                Column(id=\"at\", name=\"\", width=40),\n",
    "                reactable_sdv_logos(league=\"nfl\", id=\"opp\", name=\"Opponent\", include_name=True, height=22),\n",
    "                Column(id=\"result\", name=\"\"),\n",
    "                Column(id=\"pf\", name=\"PF\"),\n",
    "                Column(id=\"pa\", name=\"PA\"),\n",
    "            ],\n",
    "            theme=reactable_sdv_theme_team(team, \"nfl\", centered=True),\n",
    "            striped=True,\n",
    "            highlight=True,\n",
    "            default_page_size=17,\n",
    "            compact=True,\n",
    "        ),\n",
    "        subtitle=f\"{name}, 2025\",\n",
    "        source=SOURCE,\n",
    "    )\n",
    "\n",
    "\n",
    "team_table(\"KC\", \"Kansas City Chiefs\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17",
   "metadata": {},
   "outputs": [],
   "source": [
    "team_table(\"GB\", \"Green Bay Packers\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "reactablefmtr's table furniture and themes in reactable-py: a title, subtitle, source line, legend and Google font around a table; ESPN, New York Times, FiveThirtyEight and PFF looks on NHL, WNBA, men's college basketball and NFL data; the other 23 themes side by side; and themes in the Chiefs' and Packers' colors.",
   "label": "reactable themes and titles",
   "position": 15
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
