68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217 | class Chart(Component):
"""
A generic component for rendering charts using the ApexCharts library.
It expects a URL to fetch chart data from. The endpoint should return
JSON data compatible with ApexCharts options (e.g., {"series": [...], "xaxis": {...}}).
"""
def __init__(
self,
type: str = "line",
height: Union[int, str] = 350,
options: Optional[dict] = None,
filter_component: Optional[Component] = None,
title: str = "",
subtitle: str = "",
**kwargs,
):
super().__init__(**kwargs)
header_uid = f"{self.uid}_header" if self.uid else "header"
header = ChartHeader(
filter_component=filter_component,
title=title,
subtitle=subtitle,
uid=header_uid,
)
self.type = type
self.height = height
self.options = options or {}
self.header = header
def render_html(self, **kwargs) -> str:
chart_id = f"chart_{self.uid}"
# Base options to ensure the chart renders properly
base_options = {
"chart": {
"type": self.type,
"height": self.height,
},
"series": [],
"noData": {"text": "No data to display"},
}
# Merge custom options provided during instantiation
for k, v in self.options.items():
if k == "chart" and isinstance(v, dict):
base_options["chart"].update(v)
else:
base_options[k] = v
options_json = json.dumps(base_options)
header_html = self.header.render(**kwargs)
url_js = f"'{self.url}'" if self.url else "window.location.pathname"
return f"""
<div id="{self.uid}" class="w-full {self.classes}" x-data="{{
chart: null,
init() {{
const optionsEl = document.getElementById('{chart_id}_options');
if (!optionsEl) return;
const options = JSON.parse(optionsEl.textContent);
// Attach click handler for data points
if (!options.chart) options.chart = {{}};
if (!options.chart.events) options.chart.events = {{}};
options.chart.events.dataPointSelection = (event, chartContext, config) => {{
const seriesIndex = config.seriesIndex;
const dataPointIndex = config.dataPointIndex;
// Extract the exact data point that was clicked from the updated internal options
const dataPoint = chartContext.w.config.series[seriesIndex].data[dataPointIndex];
// If the data point has a URL attached, trigger HTMX navigation
if (dataPoint && dataPoint.url) {{
htmx.ajax('GET', dataPoint.url, {{ target: '#app-layout', swap: 'outerHTML' }});
}}
}};
// Refetch data when the chart is zoomed or panned (debounced)
let zoomTimeout = null;
options.chart.events.zoomed = (chartContext, {{ xaxis }}) => {{
if (xaxis && xaxis.min && xaxis.max) {{
clearTimeout(zoomTimeout);
zoomTimeout = setTimeout(() => {{
const params = new URLSearchParams(window.location.search);
params.set('range_min', new Date(xaxis.min).toISOString());
params.set('range_max', new Date(xaxis.max).toISOString());
this.loadData(params);
}}, 1000);
}}
}};
this.$nextTick(() => {{
this.chart = new ApexCharts(this.$refs.chart, options);
this.chart.render();
}});
}},
destroy() {{
if (this.chart) {{
this.chart.destroy();
this.chart = null;
}}
}},
loadData(params = null) {{
const baseUrl = {url_js};
const fetchUrl = new window.URL(baseUrl, window.location.origin);
if (params) {{
// Use params from the form submission
params.forEach((value, key) => {{
if (value) {{
fetchUrl.searchParams.append(key, value);
}}
}});
}} else {{
// Fallback to reading from the current URL on initial load
const currentParams = new window.URLSearchParams(window.location.search);
currentParams.forEach((value, key) => {{
if (value) {{
fetchUrl.searchParams.append(key, value);
}}
}});
}}
fetch(fetchUrl, {{
headers: {{
'Accept': 'application/json'
}}
}})
.then(res => res.json())
.then(data => {{
if (this.chart) {{
this.chart.updateOptions(data);
}}
}})
.catch(() => {{}});
}}
}}" @chart-filter-submit.window="loadData(new window.URLSearchParams(new window.FormData($event.detail.form)))" x-init="loadData()">
{header_html}
<script type="application/json" id="{chart_id}_options">
{options_json}
</script>
<div id="{chart_id}" x-ref="chart"></div>
</div>
"""
|