Spaces:
Running
Running
thibaud frere commited on
Commit ·
5846c4a
1
Parent(s): 3f64d97
feat(fragments): add HtmlFragment component and example fragments/banner.html
Browse filesFiles changed (9)
- app/src/components/HtmlFragment.astroAdded+27
- app/src/fragments/banner.htmlAdded+13
- app/src/pages/index.astro+5-8
- python/convert.pyAdded+32
- python/convert_to_md.pyAdded+110
- python/fragments/banner.pyAdded+100
- python/fragments/bar.pyAdded+131
- python/fragments/heatmap.pyAdded+122
- python/fragments/line.pyAdded+243
123456789101112131415161718192021222324252627---interface Props { src: string }const { src } = Astro.props as Props;
// Charge tous les fragments .html sous src/fragments/** en tant que string (dev & build)const fragments = import.meta.glob('../fragments/**/*.html', { as: 'raw', eager: true }) as Record<string, string>;
function resolveFragment(requested: string): string | null { // Autorise "banner.html" ou "fragments/banner.html" const needle = requested.replace(/^\/*/, ''); for (const [key, html] of Object.entries(fragments)) { if (key.endsWith('/' + needle) || key.endsWith('/' + needle.replace(/^fragments\//, ''))) { return html; } } return null;}
const html = resolveFragment(src);---{ html ? ( <div set:html={html} /> ) : ( <div><!-- Fragment introuvable: {src} --></div> ) }
12345678910111213<div id="fragment-banner" style="max-width: 980px; margin: 0 auto;"> <div id="banner-plot" style="width:100%;height:360px;"></div> <script> if (window.Plotly && document.getElementById('banner-plot')) { const el = document.getElementById('banner-plot'); const x = Array.from({length: 200}, (_, i) => i/10); const y = x.map(v => Math.sin(v)); window.Plotly.newPlot(el, [{x, y, mode:'lines'}], {margin:{t:16,r:16,b:32,l:32}}); } </script></div>
12345638 unmodified lines45464748495034 unmodified lines858687888990919293949596979899---import { Image } from 'astro:assets';import banner from "../assets/images/banner.png";const title = 'The Distill Blog Template (Astro)';---<html lang="en">38 unmodified lines<Image src={banner} alt="Banner" widths={[480,768,1080,1440]} formats={["avif","webp","png"]} sizes="(max-width: 768px) 100vw, var(--page-width)" loading="eager" /></figure></div><p style="text-align: center; font-style: italic; margin-top: 10px; max-width: 900px; margin-left: auto; margin-right: auto;">It's nice to have a cute interactive banner!</p></div></d-title>34 unmodified lines<h2>Interactive Components</h2><div class="plot-card"><div id="fragment-line"></div></div><script>// Example: simple Plotly line chart using the CDNconst container = document.getElementById('fragment-line');if (container && window.Plotly) {window.Plotly.newPlot(container, [{x:[1,2,3,4], y:[1,3,2,4], type:'scatter'}], {margin:{t:16,r:16,b:32,l:32}});}</script></d-article>123456738 unmodified lines46474849505152535434 unmodified lines8990919293949596---import { Image } from 'astro:assets';import banner from "../assets/images/banner.png";import HtmlFragment from "../components/HtmlFragment.astro";const title = 'The Distill Blog Template (Astro)';---<html lang="en">38 unmodified lines<Image src={banner} alt="Banner" widths={[480,768,1080,1440]} formats={["avif","webp","png"]} sizes="(max-width: 768px) 100vw, var(--page-width)" loading="eager" /></figure></div><div class="l-page" style="margin-top:12px;"><HtmlFragment src="banner.html" /></div><p style="text-align: center; font-style: italic; margin-top: 10px; max-width: 900px; margin-left: auto; margin-right: auto;">It's nice to have a cute interactive banner!</p></div></d-title>34 unmodified lines<h2>Interactive Components</h2><div class="plot-card"><HtmlFragment src="banner.html" /></div></d-article>
1234567891011121314151617181920212223242526272829303132#!/usr/bin/env python3import markdownfrom pathlib import Pathimport sys
def convert_md_to_html(filepath): input_path = Path(filepath) output_path = input_path.with_suffix('.html') try: with open(input_path, 'r', encoding='utf-8') as md_file: text = md_file.read() html = markdown.markdown(text) with open(output_path, 'w', encoding='utf-8', errors='xmlcharrefreplace') as html_file: html_file.write(html) print(f"Converted {input_path} -> {output_path}") except FileNotFoundError: print(f"Error: Could not find file {input_path}") sys.exit(1) except Exception as e: print(f"Error converting file: {e}") sys.exit(1)
if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: python convert.py FILEPATH.md") sys.exit(1) convert_md_to_html(sys.argv[1])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110#!/usr/bin/env python3"""HTML to Markdown Converter
This script converts HTML files to Markdown format.Usage: python html_to_md.py input.html [output.md]If no output file is specified, it will use the input filename with .md extension."""
import sysimport osimport argparseimport html2textimport requestsfrom urllib.parse import urlparse
def is_url(path): """Check if the given path is a URL.""" parsed = urlparse(path) return parsed.scheme != '' and parsed.netloc != ''
def convert_html_to_markdown(html_content, **options): """Convert HTML content to Markdown.""" converter = html2text.HTML2Text() # Configure converter options converter.ignore_links = options.get('ignore_links', False) converter.ignore_images = options.get('ignore_images', False) converter.ignore_tables = options.get('ignore_tables', False) converter.body_width = options.get('body_width', 0) # 0 means no wrapping converter.unicode_snob = options.get('unicode_snob', True) # Use Unicode instead of ASCII converter.wrap_links = options.get('wrap_links', False) converter.inline_links = options.get('inline_links', True) # Convert HTML to Markdown return converter.handle(html_content)
def main(): parser = argparse.ArgumentParser(description='Convert HTML to Markdown') parser.add_argument('input', help='Input HTML file or URL') parser.add_argument('output', nargs='?', help='Output Markdown file (optional)') parser.add_argument('--ignore-links', action='store_true', help='Ignore links in the HTML') parser.add_argument('--ignore-images', action='store_true', help='Ignore images in the HTML') parser.add_argument('--ignore-tables', action='store_true', help='Ignore tables in the HTML') parser.add_argument('--body-width', type=int, default=0, help='Wrap text at this width (0 for no wrapping)') parser.add_argument('--unicode', action='store_true', help='Use Unicode characters instead of ASCII approximations') parser.add_argument('--wrap-links', action='store_true', help='Wrap links in angle brackets') parser.add_argument('--reference-links', action='store_true', help='Use reference style links instead of inline links') args = parser.parse_args() # Determine input if is_url(args.input): try: response = requests.get(args.input) response.raise_for_status() html_content = response.text except requests.exceptions.RequestException as e: print(f"Error fetching URL: {e}", file=sys.stderr) return 1 else: try: with open(args.input, 'r', encoding='utf-8') as f: html_content = f.read() except IOError as e: print(f"Error reading file: {e}", file=sys.stderr) return 1 # Configure conversion options options = { 'ignore_links': args.ignore_links, 'ignore_images': args.ignore_images, 'ignore_tables': args.ignore_tables, 'body_width': args.body_width, 'unicode_snob': args.unicode, 'wrap_links': args.wrap_links, 'inline_links': not args.reference_links, } # Convert HTML to Markdown markdown_content = convert_html_to_markdown(html_content, **options) # Determine output if args.output: output_file = args.output else: if is_url(args.input): # Generate a filename from the URL url_parts = urlparse(args.input) base_name = os.path.basename(url_parts.path) or 'index' if not base_name.endswith('.html'): base_name += '.html' output_file = os.path.splitext(base_name)[0] + '.md' else: # Generate a filename from the input file output_file = os.path.splitext(args.input)[0] + '.md' # Write output try: with open(output_file, 'w', encoding='utf-8') as f: f.write(markdown_content) print(f"Conversion successful! Output saved to: {output_file}") except IOError as e: print(f"Error writing file: {e}", file=sys.stderr) return 1 return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import plotly.graph_objects as goimport numpy as npimport pandas as pd
# Paramètres de l'ellipse (galaxie) et échantillonnagenum_points = 512cx, cy = 1.5, 0.5 # centre (au milieu des ranges actuels)a, b = 1.3, 0.45 # demi‑axes (ellipse horizontale)
# Échantillonnage en coordonnées polaires puis transformation elliptique# r concentré vers le centre (alpha>1) pour densité centrale façon galaxietheta = 2*np.pi*np.random.rand(num_points)r_base = np.random.rand(num_points)**2
# Légère irrégularité pour un aspect plus naturelnoise_x = 0.015*np.random.randn(num_points)noise_y = 0.015*np.random.randn(num_points)
x = cx + a * r_base * np.cos(theta) + noise_xy = cy + b * r_base * np.sin(theta) + noise_y
# Taille plus grande au centre, plus petite en périphérie# On conserve la même échelle finale qu'avant: (valeur in [0,1]) -> (val+1)*5z_raw = 1 - r_base # 1 au centre, 0 au bordsizes = (z_raw + 1) * 5 # 5..10, comme précédemment
df = pd.DataFrame({ "x": x, "y": y, "z": sizes, # réutilisé pour size+color comme avant})
def get_label(z): if z<0.25: return "smol dot" if z<0.5: return "ok-ish dot" if z<0.75: return "a dot" else: return "biiig dot"
# Les labels sont fondés sur l'intensité centrale (z_raw en [0,1])df["label"] = pd.Series(z_raw).apply(get_label)
fig = go.Figure()
fig.add_trace(go.Scatter( x=df['x'], y=df['y'], mode='markers', marker=dict( size=df['z'], color=df['z'], colorscale=[ [0, 'rgb(78, 165, 183)'], # Light blue [0.5, 'rgb(206, 192, 250)'], # Purple [1, 'rgb(232, 137, 171)'] # Pink ], opacity=0.9, ), customdata=df[["label"]], hovertemplate="Dot category: %{customdata[0]}", hoverlabel=dict(namelength=0), showlegend=False))
fig.update_layout( autosize=True, paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', showlegend=False, margin=dict(l=0, r=0, t=0, b=0), xaxis=dict( showgrid=False, zeroline=False, showticklabels=False, range=[0, 3] ), yaxis=dict( showgrid=False, zeroline=False, showticklabels=False, scaleanchor="x", scaleratio=1, range=[0, 1] ))
fig.show()
fig.write_html("../../src/fragments/banner.html", include_plotlyjs=False, full_html=False, config={ 'displayModeBar': False, 'responsive': True, 'scrollZoom': False, })123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import plotly.graph_objects as goimport plotly.io as pioimport os
"""Simple grouped bar chart (Baseline / Improved / Target), minimal Distill-like style.Responsive, no zoom/pan, clean hover (rounded tooltip corners via post_script)."""
# Data (five categories)categories = ["A", "B", "C", "D", "E"]baseline = [0.52, 0.61, 0.67, 0.73, 0.78]improved = [0.58, 0.66, 0.72, 0.79, 0.86]target = [0.60, 0.68, 0.75, 0.82, 0.90]
color_base = "#64748b" # slate-500color_improved = "#2563eb" # blue-600color_target = "#4b5563" # gray-600
fig = go.Figure()fig.add_bar( x=categories, y=baseline, name="Baseline", marker=dict(color=color_base), offsetgroup="grp", hovertemplate="<b>%{x}</b><br>%{fullData.name}: %{y:.3f}<extra></extra>",)
fig.add_bar( x=categories, y=improved, name="Improved", marker=dict(color=color_improved), offsetgroup="grp", hovertemplate="<b>%{x}</b><br>%{fullData.name}: %{y:.3f}<extra></extra>",)
fig.add_bar( x=categories, y=target, name="Target", marker=dict(color=color_target, opacity=0.65, line=dict(color=color_target, width=1)), offsetgroup="grp", hovertemplate="<b>%{x}</b><br>%{fullData.name}: %{y:.3f}<extra></extra>",)
fig.update_layout( barmode="group", autosize=True, paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", margin=dict(l=28, r=12, t=8, b=28), hovermode="x unified", legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="left", x=0), xaxis=dict( showgrid=False, zeroline=False, showline=True, linecolor="rgba(0,0,0,0.25)", linewidth=1, ticks="outside", ticklen=6, tickcolor="rgba(0,0,0,0.25)", tickfont=dict(size=12, color="rgba(0,0,0,0.65)"), title=None, automargin=True, fixedrange=True, ), yaxis=dict( showgrid=False, zeroline=False, showline=True, linecolor="rgba(0,0,0,0.25)", linewidth=1, ticks="outside", ticklen=6, tickcolor="rgba(0,0,0,0.25)", tickfont=dict(size=12, color="rgba(0,0,0,0.65)"), title=None, tickformat=".2f", automargin=True, fixedrange=True, ),)
post_script = """(function(){ var plots = document.querySelectorAll('.js-plotly-plot'); plots.forEach(function(gd){ function round(){ try { var root = gd && gd.parentNode ? gd.parentNode : document; var rects = root.querySelectorAll('.hoverlayer .hovertext rect'); rects.forEach(function(r){ r.setAttribute('rx', 8); r.setAttribute('ry', 8); }); } catch(e) {} } if (gd && gd.on){ gd.on('plotly_hover', round); gd.on('plotly_unhover', round); gd.on('plotly_relayout', round); } setTimeout(round, 0); });})();"""
html = pio.to_html( fig, include_plotlyjs=False, full_html=False, post_script=post_script, config={ "displayModeBar": False, "responsive": True, "scrollZoom": False, "doubleClick": False, "modeBarButtonsToRemove": [ "zoom2d", "pan2d", "select2d", "lasso2d", "zoomIn2d", "zoomOut2d", "autoScale2d", "resetScale2d", "toggleSpikelines" ], },)
output_path = os.path.join(os.path.dirname(__file__), "fragments", "bar.html")os.makedirs(os.path.dirname(output_path), exist_ok=True)with open(output_path, "w", encoding="utf-8") as f: f.write(html)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import plotly.graph_objects as goimport plotly.io as pioimport numpy as npimport datetime as dtimport os
"""Calendar-like heatmap (GitHub-style) over the last 52 weeks.Minimal, responsive, transparent background; suitable for Distill."""
# ParametersNUM_WEEKS = 52DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
# Build dates matrix (7 rows x NUM_WEEKS columns)today = dt.date.today()# Align to start of current week (Monday)start = today - dt.timedelta(days=(today.weekday())) # Monday of current weekweeks = [start - dt.timedelta(weeks=w) for w in range(NUM_WEEKS-1, -1, -1)]dates = [[weeks[c] + dt.timedelta(days=r) for c in range(NUM_WEEKS)] for r in range(7)]
# Generate values (synthetic) — smooth seasonal pattern + noisedef gen_value(d: dt.date) -> float: day_of_year = d.timetuple().tm_yday base = 0.5 + 0.45 * np.sin(2 * np.pi * (day_of_year / 365.0)) noise = np.random.default_rng(hash(d) % 2**32).uniform(-0.15, 0.15) return max(0.0, min(1.0, base + noise))
z = [[gen_value(d) for d in row] for row in dates]custom = [[d.isoformat() for d in row] for row in dates]
# Colors aligned with other charts (slate / blue / gray)colorscale = [ [0.00, "#e5e7eb"], # light gray background for low [0.40, "#64748b"], # slate-500 [0.75, "#2563eb"], # blue-600 [1.00, "#4b5563"], # gray-600 (high end accent)]
fig = go.Figure( data=go.Heatmap( z=z, x=[w.isoformat() for w in weeks], y=DAYS, colorscale=colorscale, showscale=False, hovertemplate="Date: %{customdata}<br>Value: %{z:.2f}<extra></extra>", customdata=custom, xgap=2, ygap=2, ))
fig.update_layout( autosize=True, paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", margin=dict(l=28, r=12, t=8, b=28), xaxis=dict( showgrid=False, zeroline=False, showline=False, ticks="", showticklabels=False, fixedrange=True, ), yaxis=dict( showgrid=False, zeroline=False, showline=False, ticks="", tickfont=dict(size=12, color="rgba(0,0,0,0.65)"), fixedrange=True, ),)
post_script = """(function(){ var plots = document.querySelectorAll('.js-plotly-plot'); plots.forEach(function(gd){ function round(){ try { var root = gd && gd.parentNode ? gd.parentNode : document; var rects = root.querySelectorAll('.hoverlayer .hovertext rect'); rects.forEach(function(r){ r.setAttribute('rx', 8); r.setAttribute('ry', 8); }); } catch(e) {} } if (gd && gd.on){ gd.on('plotly_hover', round); gd.on('plotly_unhover', round); gd.on('plotly_relayout', round); } setTimeout(round, 0); });})();"""
html = pio.to_html( fig, include_plotlyjs=False, full_html=False, post_script=post_script, config={ "displayModeBar": False, "responsive": True, "scrollZoom": False, "doubleClick": False, "modeBarButtonsToRemove": [ "zoom2d", "pan2d", "select2d", "lasso2d", "zoomIn2d", "zoomOut2d", "autoScale2d", "resetScale2d", "toggleSpikelines" ], },)
output_path = os.path.join(os.path.dirname(__file__), "fragments", "heatmap.html")os.makedirs(os.path.dirname(output_path), exist_ok=True)with open(output_path, "w", encoding="utf-8") as f: f.write(html)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243import plotly.graph_objects as goimport plotly.io as pioimport numpy as npimport osimport uuid
"""Interactive line chart example (3 curves + live slider)
The slider blends each curve from linear to exponential in real time (no mouseup required).This fragment is safe to insert multiple times on the page (unique IDs per instance)."""
# Grid (x) and parameterizationN = 240x = np.linspace(0, 1, N)
# Linear baselines (increasing)lin1 = 0.20 + 0.60 * xlin2 = 0.15 + 0.70 * xlin3 = 0.10 + 0.80 * x
# Helper: normalized exponential on [0,1]def exp_norm(xv: np.ndarray, k: float) -> np.ndarray: return (np.exp(k * xv) - 1.0) / (np.exp(k) - 1.0)
# Exponential counterparts (similar ranges)exp1 = 0.20 + 0.60 * exp_norm(x, 3.0)exp2 = 0.15 + 0.70 * exp_norm(x, 3.5)exp3 = 0.10 + 0.80 * exp_norm(x, 2.8)
# Initial blend (alpha=0 ⇒ pure linear)alpha0 = 0.0blend = lambda l, e, a: (1 - a) * l + a * ey1 = blend(lin1, exp1, alpha0)y2 = blend(lin2, exp2, alpha0)y3 = blend(lin3, exp3, alpha0)
color_base = "#64748b" # slate-500color_improved = "#2563eb" # blue-600color_target = "#4b5563" # gray-600 (dash)
fig = go.Figure()fig.add_trace( go.Scatter( x=x, y=y1, name="Baseline", mode="lines", line=dict(color=color_base, width=2, shape="spline", smoothing=0.6), hovertemplate="<b>%{fullData.name}</b><br>x=%{x:.2f}<br>y=%{y:.3f}<extra></extra>", showlegend=True, ))fig.add_trace( go.Scatter( x=x, y=y2, name="Improved", mode="lines", line=dict(color=color_improved, width=2, shape="spline", smoothing=0.6), hovertemplate="<b>%{fullData.name}</b><br>x=%{x:.2f}<br>y=%{y:.3f}<extra></extra>", showlegend=True, ))fig.add_trace( go.Scatter( x=x, y=y3, name="Target", mode="lines", line=dict(color=color_target, width=2, dash="dash"), hovertemplate="<b>%{fullData.name}</b><br>x=%{x:.2f}<br>y=%{y:.3f}<extra></extra>", showlegend=True, ))
fig.update_layout( autosize=True, paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", margin=dict(l=28, r=12, t=8, b=28), hovermode="x unified", hoverlabel=dict( bgcolor="white", font=dict(color="#111827", size=12), bordercolor="rgba(0,0,0,0.15)", align="left", namelength=-1, ), xaxis=dict( showgrid=False, zeroline=False, showline=True, linecolor="rgba(0,0,0,0.25)", linewidth=1, ticks="outside", ticklen=6, tickcolor="rgba(0,0,0,0.25)", tickfont=dict(size=12, color="rgba(0,0,0,0.55)"), title=None, automargin=True, fixedrange=True, ), yaxis=dict( showgrid=False, zeroline=False, showline=True, linecolor="rgba(0,0,0,0.25)", linewidth=1, ticks="outside", ticklen=6, tickcolor="rgba(0,0,0,0.25)", tickfont=dict(size=12, color="rgba(0,0,0,0.55)"), title=None, tickformat=".2f", rangemode="tozero", automargin=True, fixedrange=True, ),)
# Écrit le fragment de manière robuste à côté de ce fichier, dans src/fragments/line.htmloutput_path = os.path.join(os.path.dirname(__file__), "fragments", "line.html")os.makedirs(os.path.dirname(output_path), exist_ok=True)
# Injecte un petit script post-rendu pour arrondir les coins de la boîte de hoverpost_script = """(function(){ function attach(gd){ function round(){ try { var root = gd && gd.parentNode ? gd.parentNode : document; var rects = root.querySelectorAll('.hoverlayer .hovertext rect'); rects.forEach(function(r){ r.setAttribute('rx', 8); r.setAttribute('ry', 8); }); } catch(e) {} } if (gd && gd.on) { gd.on('plotly_hover', round); gd.on('plotly_unhover', round); gd.on('plotly_relayout', round); } setTimeout(round, 0); } var plots = document.querySelectorAll('.js-plotly-plot'); plots.forEach(attach);})();"""
html_plot = pio.to_html( fig, include_plotlyjs=False, full_html=False, post_script=post_script, config={ "displayModeBar": False, "responsive": True, "scrollZoom": False, "doubleClick": False, "modeBarButtonsToRemove": [ "zoom2d", "pan2d", "select2d", "lasso2d", "zoomIn2d", "zoomOut2d", "autoScale2d", "resetScale2d", "toggleSpikelines" ], },)
# Build a self-contained fragment with a live slider (no mouseup required)uid = uuid.uuid4().hex[:8]slider_id = f"line-ex-alpha-{uid}"container_id = f"line-ex-container-{uid}"
slider_tpl = '''<div id="__CID__"> __PLOT__ <div class="plotly_controls" style="margin-top:10px; display:flex; gap:14px; align-items:center;"> <label style="font-size:12px;color:rgba(0,0,0,.65); display:flex; align-items:center; gap:6px; white-space:nowrap;"> Dataset <select id="__DSID__" style="font-size:12px; padding:2px 6px;"> <option value="0">Dataset A</option> <option value="1">Dataset B</option> <option value="2">Dataset C</option> </select> </label> <label style="font-size:12px;color:rgba(0,0,0,.65);display:flex;align-items:center;gap:8px; flex:1;"> Nonlinearity <input id="__SID__" type="range" min="0" max="1" step="0.01" value="__A0__" style="flex:1;"> <span class="alpha-value">__A0__</span> </label> </div></div><script>(function(){ var container = document.getElementById('__CID__'); if(!container) return; var gd = container.querySelector('.js-plotly-plot'); var slider = document.getElementById('__SID__'); var dsSelect = document.getElementById('__DSID__'); var valueEl = container.querySelector('.alpha-value'); var N = __N__; var xs = Array.from({length: N}, function(_,i){ return i/(N-1); }); function expNorm(x,k){ return (Math.exp(k*x)-1)/(Math.exp(k)-1); } function blend(l,e,a){ return (1-a)*l + a*e; } var datasets = [ { curves: [ {o:0.20,s:0.60,k:3.0}, {o:0.15,s:0.70,k:3.5}, {o:0.10,s:0.80,k:2.8} ] }, { curves: [ {o:0.30,s:0.55,k:2.2}, {o:0.18,s:0.65,k:2.8}, {o:0.12,s:0.70,k:2.0} ] }, { curves: [ {o:0.10,s:0.85,k:3.8}, {o:0.12,s:0.80,k:3.2}, {o:0.08,s:0.90,k:3.0} ] } ]; var dsi = 0; function makeY(a){ var cs = datasets[dsi].curves; var y1 = xs.map(function(x){ return blend(cs[0].o + cs[0].s*x, cs[0].o + cs[0].s*expNorm(x,cs[0].k), a); }); var y2 = xs.map(function(x){ return blend(cs[1].o + cs[1].s*x, cs[1].o + cs[1].s*expNorm(x,cs[1].k), a); }); var y3 = xs.map(function(x){ return blend(cs[2].o + cs[2].s*x, cs[2].o + cs[2].s*expNorm(x,cs[2].k), a); }); return [y1,y2,y3]; } function apply(a){ var ys = makeY(a); Plotly.restyle(gd, {y:[ys[0]]}, [0]); Plotly.restyle(gd, {y:[ys[1]]}, [1]); Plotly.restyle(gd, {y:[ys[2]]}, [2]); if(valueEl) valueEl.textContent = a.toFixed(2); } var initA = parseFloat(slider.value)||0; slider.addEventListener('input', function(e){ apply(parseFloat(e.target.value)||0); }); dsSelect.addEventListener('change', function(e){ dsi = parseInt(e.target.value)||0; apply(parseFloat(slider.value)||0); }); setTimeout(function(){ apply(initA); }, 0);})();</script>'''
slider_html = (slider_tpl .replace('__CID__', container_id) .replace('__SID__', slider_id) .replace('__A0__', f"{alpha0:.2f}") .replace('__N__', str(N)) .replace('__PLOT__', html_plot))
with open(output_path, 'w', encoding='utf-8') as f: f.write(slider_html)
app/src/components/HtmlFragment.astroAdded+27
app/src/fragments/banner.htmlAdded+13
app/src/pages/index.astro+5-8
python/convert.pyAdded+32
python/convert_to_md.pyAdded+110
python/fragments/banner.pyAdded+100
python/fragments/bar.pyAdded+131
python/fragments/heatmap.pyAdded+122
python/fragments/line.pyAdded+243