@@ -1786,6 +1786,57 @@ def update_chart(slider: int):
17861786 P(f"Number of data points: {slider}")
17871787 )
17881788
1789+ </example>
1790+ <example name="Observable Plot">
1791+ from fasthtml.common import *
1792+ import numpy as np
1793+
1794+ plot_js = """
1795+ function createPlot(data) {
1796+ const plot = Plot.rectY(data, Plot.binX({y: "count"},{x: d => d.value,fill:"steelblue"})).plot();
1797+ const div = document.querySelector("#plot");
1798+ div.replaceChildren(plot);
1799+ }
1800+
1801+ // Set up initial load via HTMX
1802+ htmx.on('htmx:afterSettle', evt => {
1803+ if (evt.detail.target.id === 'data-store') {
1804+ // The data is now properly JSON-encoded
1805+ const data = JSON.parse(evt.detail.target.textContent);
1806+ createPlot(data);
1807+ }
1808+ });
1809+ """
1810+
1811+ app, rt = fast_app(
1812+ hdrs=(Script(src="https://cdn.jsdelivr.net/npm/d3@7"),
1813+ Script(src="https://cdn.jsdelivr.net/npm/@observablehq/plot@0.6")))
1814+
1815+ @rt
1816+ def index():
1817+ return Div(
1818+ H1(A("Observable", href="https://observablehq.com/@observablehq/plot", target="_blank"), " Plot Demo"),
1819+ P("The data is randomly generated on the server and is fetched on initial page load."),
1820+ P("Try opening the browser developer tools and viewing the Network tab to see the data reponse for each http request."),
1821+ # On bytton click it sends a get request to the `get_data` route and puts the response in the `data-store` div
1822+ Button("Fetch New Data", get=get_data, hx_target="#data-store", cls='btn btn-primary'),
1823+ # Store for the JSON chart data
1824+ Div(id="data-store", get=get_data, hx_trigger="load", hidden=True),
1825+ # Plot container
1826+ Div(id="plot"),
1827+ # Include the JavaScript for the plot
1828+ Script(plot_js)
1829+ )
1830+
1831+ @rt
1832+ def get_data():
1833+ # Generate sample data
1834+ data = [{"value": float(x)} for x in np.random.randn(100)]
1835+ # Return as proper JSON response
1836+ return JSONResponse(data)
1837+
1838+ serve()
1839+
17891840 </example>
17901841 <example name="Plotly Charts">
17911842from fasthtml.common import *
0 commit comments