Skip to content

Commit

Permalink
global functions for figure & row, don't need to import in templates
Browse files Browse the repository at this point in the history
  • Loading branch information
oliverlambson committed Aug 21, 2024
1 parent 637d31e commit 1bef202
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 58 deletions.
1 change: 0 additions & 1 deletion boredcharts/figures.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import matplotlib.pyplot as plt
import numpy as np
import plotly.express as px
import plotly.tools as tls
from plotly.graph_objects import Figure


Expand Down
88 changes: 88 additions & 0 deletions boredcharts/jinja.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from textwrap import dedent
from typing import Any

import markdown
from fastapi import Request
from jinja2 import Undefined, pass_context
from jinja2.runtime import Context
from markupsafe import Markup
from plotly.graph_objects import Figure


def to_html(fig: Figure) -> Markup:
"""Renders a Plotly Figure to an HTML string."""
if not isinstance(fig, Figure):
raise ValueError(f"Input must be a Plotly Figure, got {type(fig)}")
return Markup(
fig.to_html(
full_html=False,
include_plotlyjs=False,
default_height="100%",
default_width="100%",
config={
"displaylogo": False,
"responsive": True,
"displayModeBar": False,
},
)
)


def md_to_html(md: str) -> Markup:
"""Renders a Markdown string to HTML."""
return Markup(markdown.markdown(md))


@pass_context
def figure(
context: Context,
figure: str,
*,
css_class: str = "min-h-112 min-w-80",
**kwargs: dict[str, Any],
) -> Markup:
""""""
report = context.resolve("report")
if isinstance(report, Undefined):
raise ValueError("report is not available in the context")
if not isinstance(report, str):
raise ValueError(f"report must be a string, got {type(report)}")

request = context.resolve("request")
if isinstance(request, Undefined):
raise ValueError("request is not available in the context")
if not isinstance(request, Request):
raise ValueError(f"request must be a Request, got {type(request)}")

url = request.url_for(figure, report_name=report).include_query_params(**kwargs)

return Markup(
dedent(f"""
<div
hx-ext="response-targets"
class="not-prose {css_class} flex flex-1 items-stretch"
>
<figure
class="plotly-container min-h-0 min-w-0 flex-1"
hx-get="{url}"
hx-trigger="load"
hx-swap="innerHTML"
hx-target-error="find div"
>
<div class="flex h-full w-full items-center justify-center bg-stone-100">
<p>loading...</p>
</div>
</figure>
</div>
""")
)


def row(*figures: Markup) -> Markup:
return Markup(
dedent(f"""
<div class="flex flex-wrap">
{"\n".join(figures)}
</div>
""")
)
28 changes: 0 additions & 28 deletions boredcharts/templates/components/figure.html

This file was deleted.

2 changes: 0 additions & 2 deletions boredcharts/templates/pages/example.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
{% from "components/figure.html" import figure, row with context %}

August 2024

## Summary
Expand Down
30 changes: 3 additions & 27 deletions boredcharts/webapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,16 @@
from pathlib import Path
from textwrap import dedent

import markdown
import mpld3
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from jinja2 import Environment, StrictUndefined
from markupsafe import Markup
from plotly.graph_objects import Figure
from plotly.offline import get_plotlyjs

from boredcharts.figures import elasticity_vs_profit, example


def to_html(fig: Figure) -> Markup:
if not isinstance(fig, Figure):
raise ValueError(f"Input must be a Plotly Figure, got {type(fig)}")
return Markup(
fig.to_html(
full_html=False,
include_plotlyjs=False,
default_height="100%",
default_width="100%",
config={
"displaylogo": False,
"responsive": True,
"displayModeBar": False,
},
)
)


def md_to_html(md: str) -> Markup:
return Markup(markdown.markdown(md))

from boredcharts.jinja import figure, md_to_html, row, to_html

module_root = Path(__file__).parent.absolute()
Path(module_root / "static" / "plotlyjs.min.js").write_text(get_plotlyjs())
Expand All @@ -65,7 +40,8 @@ def md_to_html(md: str) -> Markup:
)
]
templates.env.filters["markdown"] = md_to_html
templates.env.filters["html"] = to_html
templates.env.globals["figure"] = figure
templates.env.globals["row"] = row


@app.get("/")
Expand Down

0 comments on commit 1bef202

Please sign in to comment.