{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `Textual` pane allows rendering a [Textual](https://textual.textualize.io/) application inside a Panel application. It patches a custom Panel driver and renders the application into a [`Terminal`](../widgets/Terminal.ipynb) component with full support for mouse and keyboard events.\n",
    "\n",
    "There are a few things to note:\n",
    "\n",
    "- Once an `App` instance is bound to a `Textual` pane it cannot be reused in another pane or otherwise and you can only bind an App instance to a single session.\n",
    "- The application must be instantiated on the same thread as the server it will be running on, i.e. if you serve the app with `pn.serve(..., threaded=True)` you must instantiate the `App` inside a function.\n",
    "\n",
    "<img src=\"../../assets/panel_textual.png\" style=\"margin-left: auto; margin-right: auto; display: block;\"></img>",
    "\n",
    "#### Parameters:\n",
    "\n",
    "For details on other options for customizing the component see the [layout](../../how_to/layout/index.md) and [styling](../../how_to/styling/index.md) how-to guides.\n",
    "\n",
    "* **``object``** (`textual.app.App`): The Textual application to render.\n",
    "\n",
    "___"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A Textual `App` can be passed directly to the `Textual` pane and Panel will handle the rest, i.e. it will start the application, handle inputs, re-rendering and so on. In other words the application will work just as if it was running inside a regular terminal.\n",
    "\n",
    "Let us start with a very simple example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import panel as pn\n",
    "\n",
    "from textual.app import App, ComposeResult\n",
    "from textual.containers import Container, Horizontal\n",
    "from textual.widgets import Button, Footer, Header, Static\n",
    "\n",
    "pn.extension(\"terminal\")\n",
    "\n",
    "QUESTION = \"Do you want to learn about Textual CSS?\"\n",
    "\n",
    "class ExampleApp(App):\n",
    "    def compose(self) -> ComposeResult:\n",
    "        yield Header()\n",
    "        yield Footer()\n",
    "        yield Container(\n",
    "            Static(QUESTION, classes=\"question\"),\n",
    "            Horizontal(\n",
    "                Button(\"Yes\", variant=\"success\"),\n",
    "                Button(\"No\", variant=\"error\"),\n",
    "                classes=\"buttons\",\n",
    "            ),\n",
    "            id=\"dialog\",\n",
    "        )\n",
    "\n",
    "example_app = ExampleApp()\n",
    "\n",
    "pn.pane.Textual(example_app, width=600, height=400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This will work just as well for simple apps as it does for more complex applications. As an example here we have embedded the Calculator example application from the Textual documentation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import panel as pn\n",
    "\n",
    "from decimal import Decimal\n",
    "\n",
    "from textual import events, on\n",
    "from textual.app import App, ComposeResult\n",
    "from textual.containers import Container\n",
    "from textual.css.query import NoMatches\n",
    "from textual.reactive import var\n",
    "from textual.widgets import Button, Digits\n",
    "\n",
    "from pathlib import Path\n",
    "import requests\n",
    "\n",
    "pn.extension(\"terminal\")\n",
    "\n",
    "def _download_file_if_not_exists(url: str, local_path: str) -> Path:\n",
    "    local_file_path = Path(local_path)\n",
    "\n",
    "    if not local_file_path.exists():\n",
    "        response = requests.get(url)\n",
    "        response.raise_for_status()\n",
    "        local_file_path.write_bytes(response.content)\n",
    "\n",
    "    return local_file_path\n",
    "\n",
    "\n",
    "file_url = \"https://raw.githubusercontent.com/holoviz/panel/main/examples/assets/calculator.tcss\"\n",
    "local_file_path = \"calculator.tcss\"\n",
    "calculator_tcss = _download_file_if_not_exists(file_url, local_file_path)\n",
    "\n",
    "\n",
    "class CalculatorApp(App):\n",
    "    \"\"\"A working 'desktop' calculator.\"\"\"\n",
    "\n",
    "    CSS_PATH = calculator_tcss.absolute()\n",
    "\n",
    "    numbers = var(\"0\")\n",
    "    show_ac = var(True)\n",
    "    left = var(Decimal(\"0\"))\n",
    "    right = var(Decimal(\"0\"))\n",
    "    value = var(\"\")\n",
    "    operator = var(\"plus\")\n",
    "\n",
    "    NAME_MAP = {\n",
    "        \"asterisk\": \"multiply\",\n",
    "        \"slash\": \"divide\",\n",
    "        \"underscore\": \"plus-minus\",\n",
    "        \"full_stop\": \"point\",\n",
    "        \"plus_minus_sign\": \"plus-minus\",\n",
    "        \"percent_sign\": \"percent\",\n",
    "        \"equals_sign\": \"equals\",\n",
    "        \"minus\": \"minus\",\n",
    "        \"plus\": \"plus\",\n",
    "    }\n",
    "\n",
    "    def watch_numbers(self, value: str) -> None:\n",
    "        \"\"\"Called when numbers is updated.\"\"\"\n",
    "        self.query_one(\"#numbers\", Digits).update(value)\n",
    "\n",
    "    def compute_show_ac(self) -> bool:\n",
    "        \"\"\"Compute switch to show AC or C button\"\"\"\n",
    "        return self.value in (\"\", \"0\") and self.numbers == \"0\"\n",
    "\n",
    "    def watch_show_ac(self, show_ac: bool) -> None:\n",
    "        \"\"\"Called when show_ac changes.\"\"\"\n",
    "        self.query_one(\"#c\").display = not show_ac\n",
    "        self.query_one(\"#ac\").display = show_ac\n",
    "\n",
    "    def compose(self) -> ComposeResult:\n",
    "        \"\"\"Add our buttons.\"\"\"\n",
    "        with Container(id=\"calculator\"):\n",
    "            yield Digits(id=\"numbers\")\n",
    "            yield Button(\"AC\", id=\"ac\", variant=\"primary\")\n",
    "            yield Button(\"C\", id=\"c\", variant=\"primary\")\n",
    "            yield Button(\"+/-\", id=\"plus-minus\", variant=\"primary\")\n",
    "            yield Button(\"%\", id=\"percent\", variant=\"primary\")\n",
    "            yield Button(\"÷\", id=\"divide\", variant=\"warning\")\n",
    "            yield Button(\"7\", id=\"number-7\", classes=\"number\")\n",
    "            yield Button(\"8\", id=\"number-8\", classes=\"number\")\n",
    "            yield Button(\"9\", id=\"number-9\", classes=\"number\")\n",
    "            yield Button(\"×\", id=\"multiply\", variant=\"warning\")\n",
    "            yield Button(\"4\", id=\"number-4\", classes=\"number\")\n",
    "            yield Button(\"5\", id=\"number-5\", classes=\"number\")\n",
    "            yield Button(\"6\", id=\"number-6\", classes=\"number\")\n",
    "            yield Button(\"-\", id=\"minus\", variant=\"warning\")\n",
    "            yield Button(\"1\", id=\"number-1\", classes=\"number\")\n",
    "            yield Button(\"2\", id=\"number-2\", classes=\"number\")\n",
    "            yield Button(\"3\", id=\"number-3\", classes=\"number\")\n",
    "            yield Button(\"+\", id=\"plus\", variant=\"warning\")\n",
    "            yield Button(\"0\", id=\"number-0\", classes=\"number\")\n",
    "            yield Button(\".\", id=\"point\")\n",
    "            yield Button(\"=\", id=\"equals\", variant=\"warning\")\n",
    "\n",
    "    def on_key(self, event: events.Key) -> None:\n",
    "        \"\"\"Called when the user presses a key.\"\"\"\n",
    "\n",
    "        def press(button_id: str) -> None:\n",
    "            \"\"\"Press a button, should it exist.\"\"\"\n",
    "            try:\n",
    "                self.query_one(f\"#{button_id}\", Button).press()\n",
    "            except NoMatches:\n",
    "                pass\n",
    "\n",
    "        key = event.key\n",
    "        if key.isdecimal():\n",
    "            press(f\"number-{key}\")\n",
    "        elif key == \"c\":\n",
    "            press(\"c\")\n",
    "            press(\"ac\")\n",
    "        else:\n",
    "            button_id = self.NAME_MAP.get(key)\n",
    "            if button_id is not None:\n",
    "                press(self.NAME_MAP.get(key, key))\n",
    "\n",
    "    @on(Button.Pressed, \".number\")\n",
    "    def number_pressed(self, event: Button.Pressed) -> None:\n",
    "        \"\"\"Pressed a number.\"\"\"\n",
    "        assert event.button.id is not None\n",
    "        number = event.button.id.partition(\"-\")[-1]\n",
    "        self.numbers = self.value = self.value.lstrip(\"0\") + number\n",
    "\n",
    "    @on(Button.Pressed, \"#plus-minus\")\n",
    "    def plus_minus_pressed(self) -> None:\n",
    "        \"\"\"Pressed + / -\"\"\"\n",
    "        self.numbers = self.value = str(Decimal(self.value or \"0\") * -1)\n",
    "\n",
    "    @on(Button.Pressed, \"#percent\")\n",
    "    def percent_pressed(self) -> None:\n",
    "        \"\"\"Pressed %\"\"\"\n",
    "        self.numbers = self.value = str(Decimal(self.value or \"0\") / Decimal(100))\n",
    "\n",
    "    @on(Button.Pressed, \"#point\")\n",
    "    def pressed_point(self) -> None:\n",
    "        \"\"\"Pressed .\"\"\"\n",
    "        if \".\" not in self.value:\n",
    "            self.numbers = self.value = (self.value or \"0\") + \".\"\n",
    "\n",
    "    @on(Button.Pressed, \"#ac\")\n",
    "    def pressed_ac(self) -> None:\n",
    "        \"\"\"Pressed AC\"\"\"\n",
    "        self.value = \"\"\n",
    "        self.left = self.right = Decimal(0)\n",
    "        self.operator = \"plus\"\n",
    "        self.numbers = \"0\"\n",
    "\n",
    "    @on(Button.Pressed, \"#c\")\n",
    "    def pressed_c(self) -> None:\n",
    "        \"\"\"Pressed C\"\"\"\n",
    "        self.value = \"\"\n",
    "        self.numbers = \"0\"\n",
    "\n",
    "    def _do_math(self) -> None:\n",
    "        \"\"\"Does the math: LEFT OPERATOR RIGHT\"\"\"\n",
    "        try:\n",
    "            if self.operator == \"plus\":\n",
    "                self.left += self.right\n",
    "            elif self.operator == \"minus\":\n",
    "                self.left -= self.right\n",
    "            elif self.operator == \"divide\":\n",
    "                self.left /= self.right\n",
    "            elif self.operator == \"multiply\":\n",
    "                self.left *= self.right\n",
    "            self.numbers = str(self.left)\n",
    "            self.value = \"\"\n",
    "        except Exception:\n",
    "            self.numbers = \"Error\"\n",
    "\n",
    "    @on(Button.Pressed, \"#plus,#minus,#divide,#multiply\")\n",
    "    def pressed_op(self, event: Button.Pressed) -> None:\n",
    "        \"\"\"Pressed one of the arithmetic operations.\"\"\"\n",
    "        self.right = Decimal(self.value or \"0\")\n",
    "        self._do_math()\n",
    "        assert event.button.id is not None\n",
    "        self.operator = event.button.id\n",
    "\n",
    "    @on(Button.Pressed, \"#equals\")\n",
    "    def pressed_equals(self) -> None:\n",
    "        \"\"\"Pressed =\"\"\"\n",
    "        if self.value:\n",
    "            self.right = Decimal(self.value)\n",
    "        self._do_math()\n",
    "\n",
    "\n",
    "calculator = CalculatorApp()\n",
    "textual_pane = pn.pane.Textual(calculator, height=600, width=400)\n",
    "\n",
    "pn.template.FastListTemplate(\n",
    "    site=\"Panel\",\n",
    "    title=\"Textual\",\n",
    "    main=[textual_pane],\n",
    "    main_max_width=\"610px\",\n",
    "    main_layout=None,\n",
    "    theme_toggle=False,   \n",
    ").servable();"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
