{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# reactable\n",
    "\n",
    "[reactable-py](https://machow.github.io/reactable-py/) is the Python port of R's reactable: an interactive HTML\n",
    "table with sorting, searching, paging, grouped rows with aggregates, expandable row details, column groups and\n",
    "themes. `sdvplot.reactable` adds the SportsDataverse marks to it as ordinary `reactable.Column` objects: team logos\n",
    "and wordmarks, player headshots, logos in column headers, and cells tinted or barred in each row's team color.\n",
    "These six recipes build on the [Tables](tables.md) cookbook's single example (logos and team-color bars on NBA\n",
    "wins) with the parts it does not show, across the WNBA, NFL, NHL, college football and men's college basketball,\n",
    "all loaded through sportsdataverse-py."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import warnings\n",
    "\n",
    "import polars as pl\n",
    "import sportsdataverse.cfb as cfb\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 matplotlib import colormaps\n",
    "from reactable import ColGroup, Column, Reactable, Theme, embed_css\n",
    "\n",
    "import sdvplot\n",
    "from sdvplot.reactable import (\n",
    "    reactable_sdv_cols_label,\n",
    "    reactable_sdv_headshots,\n",
    "    reactable_sdv_logos,\n",
    "    reactable_sdv_team_color_bg,\n",
    "    reactable_sdv_wordmarks,\n",
    ")\n",
    "\n",
    "NFL_SEASON = 2025  # nflverse and cfbfastR name 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",
    "embed_css()\n",
    "\n",
    "\n",
    "def heat(frame, column, cmap=\"RdYlGn\", reverse=False, alpha=0.55):\n",
    "    \"\"\"A reactable ``style`` function: each cell's background on a color scale over the column's range.\"\"\"\n",
    "    lo, hi = frame[column].min(), frame[column].max()\n",
    "    scale = colormaps[cmap].reversed() if reverse else colormaps[cmap]\n",
    "\n",
    "    def style(info):\n",
    "        r, g, b, _ = scale((info.value - lo) / (hi - lo))\n",
    "        return {\"background-color\": f\"rgba({r * 255:.0f}, {g * 255:.0f}, {b * 255:.0f}, {alpha})\"}\n",
    "\n",
    "    return style"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "## 1. Headshots: the WNBA's leading scorers\n",
    "\n",
    "`reactable_sdv_headshots` turns a column of ESPN athlete ids into player photos, and `reactable_sdv_team_color_bg`\n",
    "fills another column with each row's team color at low opacity, so the player's name sits on a tint of the team\n",
    "they finished the season with. Both read the team from a column of the same frame: here `team`, which the table\n",
    "hides once it has done that job. ESPN files the All-Star Game and the Commissioner's Cup final under the regular season too, so the box scores\n",
    "are first cut to the schedule's standard games, and the cell checks that no one played more games than a team's\n",
    "schedule holds. The 2026 regular season, 20 or more games:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ESPN files the All-Star Game and the Commissioner's Cup final as regular-season games: keep the standard ones\n",
    "schedule = wnba.load_wnba_schedule(seasons=[SEASON]).filter(\n",
    "    (pl.col(\"season_type\") == 2) & (pl.col(\"type_abbreviation\") == \"STD\")\n",
    ")\n",
    "season_games = pl.concat([schedule[\"home_id\"], schedule[\"away_id\"]]).value_counts()[\"count\"].max()\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",
    "per_player = (\n",
    "    players.sort(\"game_date\")\n",
    "    .group_by(\"athlete_id\", \"athlete_display_name\", maintain_order=True)\n",
    "    .agg(\n",
    "        team=pl.col(\"team_abbreviation\").last(),\n",
    "        gp=pl.len(),\n",
    "        ppg=pl.col(\"points\").mean().round(1),\n",
    "        rpg=pl.col(\"rebounds\").mean().round(1),\n",
    "        apg=pl.col(\"assists\").mean().round(1),\n",
    "    )\n",
    ")\n",
    "assert per_player[\"gp\"].max() <= season_games, \"a player has more games than the schedule\"\n",
    "leaders = (\n",
    "    per_player.filter(pl.col(\"gp\") >= 20)\n",
    "    .sort(\"ppg\", descending=True)\n",
    "    .head(15)\n",
    "    .with_columns(photo=pl.col(\"athlete_id\"), logo=pl.col(\"team\"))\n",
    "    .select(\"photo\", \"athlete_display_name\", \"logo\", \"team\", \"gp\", \"ppg\", \"rpg\", \"apg\")\n",
    ")\n",
    "Reactable(\n",
    "    leaders,\n",
    "    columns=[\n",
    "        reactable_sdv_headshots(league=\"wnba\", id=\"photo\", name=\"\", width=70, height=44),\n",
    "        reactable_sdv_team_color_bg(\n",
    "            leaders, \"team\", league=\"wnba\", alpha=0.3, id=\"athlete_display_name\", name=\"Player\", min_width=190\n",
    "        ),\n",
    "        reactable_sdv_logos(league=\"wnba\", id=\"logo\", name=\"\", width=50, height=26),\n",
    "        Column(id=\"team\", show=False),\n",
    "        Column(id=\"gp\", name=\"GP\"),\n",
    "        Column(id=\"ppg\", name=\"PTS\"),\n",
    "        Column(id=\"rpg\", name=\"REB\"),\n",
    "        Column(id=\"apg\", name=\"AST\"),\n",
    "    ],\n",
    "    default_page_size=15,\n",
    "    default_col_def=Column(v_align=\"center\"),\n",
    "    highlight=True,\n",
    "    compact=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "## 2. Wordmarks, column groups and heat cells: NFL EPA\n",
    "\n",
    "`reactable_sdv_wordmarks` shows each team as its wordmark instead of its logo; NFL teams have one for every club.\n",
    "Here it heads an offense-versus-defense table built from nflverse's weekly team stats: expected points added per\n",
    "dropback and per carry, for each team's offense and for what its defense allowed. `ColGroup` puts a spanning\n",
    "header over each side, and a small `heat` style function (defined above) colors every cell on the column's range:\n",
    "green is good, so the defensive columns use the reversed scale. Click any header to re-sort."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "weeks = nfl.load_nfl_team_stats([NFL_SEASON]).filter(pl.col(\"season_type\") == \"REG\")\n",
    "dropbacks = pl.col(\"attempts\") + pl.col(\"sacks_suffered\")\n",
    "\n",
    "\n",
    "def epa_rates(by):\n",
    "    return weeks.group_by(team=by, maintain_order=True).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",
    "\n",
    "\n",
    "nfl_epa = (\n",
    "    epa_rates(pl.col(\"team\"))\n",
    "    .join(epa_rates(pl.col(\"opponent_team\")), on=\"team\", suffix=\"_allowed\")\n",
    "    .with_columns(pl.selectors.float().round(3), mark=pl.col(\"team\"))\n",
    "    .sort(\"epa\", descending=True)\n",
    "    .select(\"mark\", \"team\", \"epa\", \"pass_epa\", \"rush_epa\", \"epa_allowed\", \"pass_epa_allowed\", \"rush_epa_allowed\")\n",
    ")\n",
    "offense = [\"epa\", \"pass_epa\", \"rush_epa\"]\n",
    "defense = [f\"{c}_allowed\" for c in offense]\n",
    "labels = {\"epa\": \"Per play\", \"pass_epa\": \"Per dropback\", \"rush_epa\": \"Per carry\"}\n",
    "Reactable(\n",
    "    nfl_epa,\n",
    "    columns=[\n",
    "        reactable_sdv_wordmarks(league=\"nfl\", id=\"mark\", name=\"\", height=22, width=150),\n",
    "        Column(id=\"team\", show=False),\n",
    "        *[Column(id=c, name=labels[c], style=heat(nfl_epa, c), align=\"center\") for c in offense],\n",
    "        *[\n",
    "            Column(id=c, name=labels[c.removesuffix(\"_allowed\")], style=heat(nfl_epa, c, reverse=True), align=\"center\")\n",
    "            for c in defense\n",
    "        ],\n",
    "    ],\n",
    "    column_groups=[\n",
    "        ColGroup(name=\"Offense: EPA\", columns=offense),\n",
    "        ColGroup(name=\"Defense: EPA allowed\", columns=defense),\n",
    "    ],\n",
    "    default_page_size=12,\n",
    "    compact=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 3. Grouped rows with aggregates: NHL standings by division\n",
    "\n",
    "reactable groups rows with `group_by` and fills each group's header row with the column's `aggregate`. With\n",
    "`reactable_sdv_logos(include_name=True)` the team column keeps its abbreviation after the logo, so the four\n",
    "division groups of the NHL's final 2025-26 standings read as one table: each group row sums its teams' wins,\n",
    "losses, points and goal differential. Collapse a division by clicking its row."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "nhl_table = (\n",
    "    nhl.nhl_standings(\"2026-04-16\")\n",
    "    .select(\n",
    "        division=\"division_name\",\n",
    "        team=\"team_abbrev_default\",\n",
    "        gp=\"games_played\",\n",
    "        w=\"wins\",\n",
    "        l=\"losses\",\n",
    "        otl=\"ot_losses\",\n",
    "        pts=\"points\",\n",
    "        gd=\"goal_differential\",\n",
    "    )\n",
    "    .sort([\"division\", \"pts\", \"team\"], descending=[False, True, False])\n",
    ")\n",
    "Reactable(\n",
    "    nhl_table,\n",
    "    group_by=\"division\",\n",
    "    columns=[\n",
    "        Column(id=\"division\", name=\"Division\", min_width=150),\n",
    "        reactable_sdv_logos(league=\"nhl\", id=\"team\", name=\"Team\", include_name=True, height=24, min_width=110),\n",
    "        Column(id=\"gp\", name=\"GP\", aggregate=\"sum\"),\n",
    "        Column(id=\"w\", name=\"W\", aggregate=\"sum\"),\n",
    "        Column(id=\"l\", name=\"L\", aggregate=\"sum\"),\n",
    "        Column(id=\"otl\", name=\"OTL\", aggregate=\"sum\"),\n",
    "        Column(id=\"pts\", name=\"PTS\", aggregate=\"sum\"),\n",
    "        Column(id=\"gd\", name=\"Goal diff.\", aggregate=\"sum\"),\n",
    "    ],\n",
    "    default_expanded=True,\n",
    "    pagination=False,\n",
    "    compact=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## 4. Logos in the column headers: an NFC North head-to-head\n",
    "\n",
    "`reactable_sdv_cols_label` makes one column per team-named column of a frame, its header the team's logo. That fits\n",
    "a matrix: one row and one column per team, each cell the row team's combined point margin over its two games\n",
    "against the column team in the 2025 regular season. Pass it only the team-named columns; the extra keyword\n",
    "arguments (a margin color and an empty-cell text) go to every column it makes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "division = [\"CHI\", \"DET\", \"GB\", \"MIN\"]\n",
    "games = nfl.load_nfl_schedule([NFL_SEASON]).filter(\n",
    "    (pl.col(\"game_type\") == \"REG\") & pl.col(\"home_team\").is_in(division) & pl.col(\"away_team\").is_in(division)\n",
    ")\n",
    "sides = [(\"home_team\", \"away_team\", \"home_score\", \"away_score\"), (\"away_team\", \"home_team\", \"away_score\", \"home_score\")]\n",
    "margins = pl.concat(games.select(team=pl.col(t), opp=pl.col(o), margin=pl.col(a) - pl.col(b)) for t, o, a, b in sides)\n",
    "matrix = (\n",
    "    margins.group_by(\"team\", \"opp\")\n",
    "    .agg(pl.col(\"margin\").sum())\n",
    "    .pivot(on=\"opp\", index=\"team\", values=\"margin\")\n",
    "    .select(\"team\", *division)\n",
    "    .sort(\"team\")\n",
    ")\n",
    "\n",
    "\n",
    "def margin_color(info):\n",
    "    if info.value is None:\n",
    "        return {\"background-color\": \"#f2f2f2\"}\n",
    "    return {\"color\": \"#1a7f37\" if info.value > 0 else \"#c0392b\", \"font-weight\": \"600\"}\n",
    "\n",
    "\n",
    "Reactable(\n",
    "    matrix,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"nfl\", id=\"team\", name=\"\", height=34, width=80),\n",
    "        *reactable_sdv_cols_label(\n",
    "            matrix.select(division),\n",
    "            league=\"nfl\",\n",
    "            height=34,\n",
    "            style=margin_color,\n",
    "            align=\"center\",\n",
    "            v_align=\"center\",\n",
    "            na=\"\",\n",
    "            width=90,\n",
    "        ),\n",
    "    ],\n",
    "    bordered=True,\n",
    "    sortable=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "## 5. Expandable row details: the SEC's games\n",
    "\n",
    "A `details` column renders extra content under a row when you expand it. Each row here is an SEC team in\n",
    "cfbfastR's 2025 adjusted ratings (net adjusted EPA per play, with its national rank), logo first; expanding it\n",
    "lists the team's completed games, each opponent drawn by its logo from `sdvplot.logo_url`. The detail function runs\n",
    "once per row when the table is built, so the page needs no Python to open a row."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "ratings = cfb.load_cfb_ratings(NFL_SEASON).select(\"team_id\", \"net_rank\", \"adj_off_epa\", \"adj_def_epa\", \"adj_net\")\n",
    "sec_teams = cfb.load_cfb_team_summaries(NFL_SEASON).filter(pl.col(\"conference\") == \"SEC\").select(\"team_id\", \"pos_team\")\n",
    "assert sec_teams.schema[\"team_id\"] == ratings.schema[\"team_id\"]\n",
    "sec = (\n",
    "    sec_teams.join(ratings, on=\"team_id\")\n",
    "    .with_columns(pl.selectors.float().round(3), logo=pl.col(\"team_id\"))\n",
    "    .sort(\"adj_net\", descending=True)\n",
    "    .select(\"logo\", \"pos_team\", \"net_rank\", \"adj_off_epa\", \"adj_def_epa\", \"adj_net\", \"team_id\")\n",
    ")\n",
    "schedule = cfb.load_cfb_schedule(NFL_SEASON).filter(pl.col(\"completed\"))\n",
    "results = pl.concat(\n",
    "    schedule.select(\n",
    "        \"week\",\n",
    "        team_id=pl.col(f\"{us}_id\"),\n",
    "        opp_id=pl.col(f\"{them}_id\"),\n",
    "        opp=pl.col(f\"{them}_team\"),\n",
    "        pts=pl.col(f\"{us}_points\"),\n",
    "        opp_pts=pl.col(f\"{them}_points\"),\n",
    "    )\n",
    "    for us, them in [(\"home\", \"away\"), (\"away\", \"home\")]\n",
    ").sort(\"team_id\", \"week\")\n",
    "by_team = results.partition_by(\"team_id\", as_dict=True)\n",
    "\n",
    "\n",
    "def game_html(game):\n",
    "    with warnings.catch_warnings():  # an opponent without a logo keeps its name instead\n",
    "        warnings.simplefilter(\"ignore\", sdvplot.SdvplotWarning)\n",
    "        url = sdvplot.logo_url(game[\"opp_id\"], \"cfb\", id_system=\"espn\")\n",
    "    mark = f'<img src=\"{url}\" alt=\"{game[\"opp\"]}\" height=\"24\">' if url else game[\"opp\"]\n",
    "    won = game[\"pts\"] > game[\"opp_pts\"]\n",
    "    return (\n",
    "        f'<span style=\"display:inline-flex;align-items:center;gap:4px;margin:4px 12px 4px 0\">{mark}'\n",
    "        f'<b style=\"color:{\"#1a7f37\" if won else \"#c0392b\"}\">{\"W\" if won else \"L\"}</b>'\n",
    "        f\" {game['pts']}-{game['opp_pts']}</span>\"\n",
    "    )\n",
    "\n",
    "\n",
    "def details(row):\n",
    "    team_id = sec[\"team_id\"][row.row_index]\n",
    "    return \"\".join(game_html(g) for g in by_team[(team_id,)].iter_rows(named=True))\n",
    "\n",
    "\n",
    "Reactable(\n",
    "    sec,\n",
    "    columns=[\n",
    "        reactable_sdv_logos(league=\"cfb\", id=\"logo\", name=\"\", id_system=\"espn\", height=28, width=60),\n",
    "        Column(id=\"pos_team\", name=\"Team\", min_width=140),\n",
    "        Column(id=\"net_rank\", name=\"Natl. rank\"),\n",
    "        Column(id=\"adj_off_epa\", name=\"Off. EPA/play\"),\n",
    "        Column(id=\"adj_def_epa\", name=\"Def. EPA/play\"),\n",
    "        Column(id=\"adj_net\", name=\"Net\"),\n",
    "        Column(id=\"team_id\", show=False),\n",
    "    ],\n",
    "    details=Column(details=details, html=True),\n",
    "    default_page_size=16,\n",
    "    highlight=True,\n",
    "    compact=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "## 6. A dark theme with the dark logo variant: men's college basketball\n",
    "\n",
    "reactable's `Theme` restyles the whole table, and `reactable_sdv_logos(variant=\"dark\")` swaps in the logo variant\n",
    "drawn for dark backgrounds, so the marks stay readable on it. The table is the top 25 of the 2025-26 adjusted\n",
    "efficiency ratings from hoopR's men's college basketball data: adjusted offense and defense (points per 100\n",
    "possessions) carry heat cells, with the defensive scale reversed because fewer points allowed is better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "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",
    "top25 = (\n",
    "    mbb_ratings.sort(\"rank\")\n",
    "    .head(25)\n",
    "    .join(names, on=\"team_id\", how=\"left\")\n",
    "    .with_columns(pl.col(\"adj_em\", \"adj_o\", \"adj_d\", \"adj_tempo\").round(1), logo=pl.col(\"team_id\"))\n",
    "    .select(\"rank\", \"logo\", \"team_location\", \"adj_em\", \"adj_o\", \"adj_d\", \"adj_tempo\")\n",
    ")\n",
    "dark = Theme(\n",
    "    color=\"#e8e8e8\",\n",
    "    background_color=\"#14161a\",\n",
    "    border_color=\"#2c3038\",\n",
    "    striped_color=\"#1b1e23\",\n",
    "    highlight_color=\"#262a31\",\n",
    "    header_style={\"color\": \"#a8adb7\", \"text-transform\": \"uppercase\", \"font-size\": \"0.8rem\"},\n",
    "    page_button_style={\"color\": \"#e8e8e8\"},\n",
    ")\n",
    "Reactable(\n",
    "    top25,\n",
    "    columns=[\n",
    "        Column(id=\"rank\", name=\"#\", width=50),\n",
    "        reactable_sdv_logos(league=\"mbb\", id=\"logo\", name=\"\", variant=\"dark\", id_system=\"espn\", height=28, 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\", style=heat(top25, \"adj_o\", alpha=0.45)),\n",
    "        Column(id=\"adj_d\", name=\"Adj. defense\", style=heat(top25, \"adj_d\", reverse=True, alpha=0.45)),\n",
    "        Column(id=\"adj_tempo\", name=\"Tempo\"),\n",
    "    ],\n",
    "    theme=dark,\n",
    "    striped=True,\n",
    "    default_page_size=25,\n",
    "    compact=True,\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "Six reactable recipes with sdvplot: WNBA headshots, NFL wordmarks with column groups and heat cells, NHL standings grouped by division, logos in the headers of an NFC North matrix, expandable SEC game details, and a dark theme with dark logos.",
   "label": "reactable",
   "position": 7
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
