{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import panel as pn\n",
    "\n",
    "pn.extension('tabulator', sizing_mode=\"stretch_width\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This example demonstrates the powerful streaming capabilities of the `Tabulator` widget."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD')).cumsum()\n",
    "\n",
    "rollover = pn.widgets.IntInput(name='Rollover', value=15)\n",
    "follow = pn.widgets.Checkbox(name='Follow', value=True, align='end')\n",
    "\n",
    "tabulator = pn.widgets.Tabulator(df, height=450)\n",
    "\n",
    "def color_negative_red(val):\n",
    "    \"\"\"\n",
    "    Takes a scalar and returns a string with\n",
    "    the css property `'color: red'` for negative\n",
    "    strings, black otherwise.\n",
    "    \"\"\"\n",
    "    color = 'red' if val < 0 else 'green'\n",
    "    return 'color: %s' % color\n",
    "\n",
    "tabulator.style.applymap(color_negative_red)\n",
    "\n",
    "def stream():\n",
    "    data = df.iloc[-1] + np.random.randn(4)\n",
    "    tabulator.stream(data, rollover=rollover.value, follow=follow.value)\n",
    "\n",
    "cb = pn.state.add_periodic_callback(stream, 200)\n",
    "\n",
    "component = pn.Column(\n",
    "    pn.Row(cb.param.period, rollover, follow, width=400),\n",
    "    tabulator,\n",
    ")\n",
    "component"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## App\n",
    "\n",
    "Lets wrap it into nice template that can be served via `panel serve streaming_tabulator.ipynb`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pn.template.FastListTemplate(\n",
    "    site=\"Panel\", \n",
    "    title=\"Streaming Tabulator\", \n",
    "    main=[\n",
    "        \"This example demonstrates the **powerful streaming capabilities** of Panel and the `Tabulator` widget.\",\n",
    "        component,\n",
    "    ]\n",
    ").servable();"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
