Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,5 @@ pip-wheel-metadata/
__pycache__/
ml_peg/app/data/*
!ml_peg/app/data/onboarding/
!ml_peg/app/data/table_download/
certs/
17 changes: 15 additions & 2 deletions ml_peg/app/build_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from ml_peg.analysis.utils.utils import calc_table_scores, get_table_style
from ml_peg.app import APP_ROOT
from ml_peg.app.utils.build_components import (
build_download_controls,
build_faqs,
build_footer,
build_weight_components,
Expand Down Expand Up @@ -475,6 +476,7 @@ def build_category(
header="Benchmark weights",
table=summary_table,
include_store=False,
include_download_controls=False,
column_widths=getattr(summary_table, "column_widths", None),
)

Expand Down Expand Up @@ -542,7 +544,12 @@ def build_category_page_layout(
H1(category_title),
H3(category_description),
Div(
[Div(summary_table), Br(), weight_components],
[
build_download_controls(summary_table.id, row=True),
Div(summary_table),
Br(),
weight_components,
],
style={"width": "fit-content"},
),
Div(
Expand Down Expand Up @@ -1124,7 +1131,12 @@ def select_page(
[
H1("Categories Summary"),
Div(
[Div(summary_table), Br(), weight_components],
[
build_download_controls(summary_table.id, row=True),
Div(summary_table),
Br(),
weight_components,
],
style={"width": "fit-content"},
),
build_faqs(),
Expand Down Expand Up @@ -1175,6 +1187,7 @@ def build_full_app(full_app: Dash, category: str = "*") -> None:
header="Category weights",
table=summary_table,
include_store=False,
include_download_controls=False,
column_widths=summary_table.column_widths,
)
# Build summary and category pages and navigation
Expand Down
111 changes: 111 additions & 0 deletions ml_peg/app/data/table_download/capture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* Dash clientside callback for PNG/SVG table export.
*
* Python registers this as table_download.captureTable. The callback receives a
* request from register_download_callbacks, captures the actual Dash table already
* drawn in the browser, and returns a dcc.Download-compatible payload.
*
* This intentionally captures the browser's drawn table instead of rebuilding an
* image from table data. Rebuiling the table is much much easier, but results in an
* image that doenst actually look anything like our ml-peg tables.
* Dash has already applied style_data_conditional,
* tooltip/header changes, warning colours, column widths, and CSS assets, so
* html-to-image can export the same visual table the user sees.
*/
window.dash_clientside = Object.assign({}, window.dash_clientside, {
table_download: {
captureTable: function (request) {
const dash = window.dash_clientside;
const noUpdate = dash ? dash.no_update : null;
if (!request) {
return noUpdate;
}

// register_download_callbacks passes the Dash DataTable component id.
// Capturing this existing page element preserves the current appearance,
// including conditional cell colours and any user-adjusted table state.
const tableNode = document.getElementById(request.element_id);
if (!tableNode) {
return noUpdate;
}

const source =
"https://cdn.jsdelivr.net/npm/html-to-image@1.11.11/dist/html-to-image.min.js";

// Load html-to-image only when the user asks for an image export. Cache the
// promise so repeated downloads do not append duplicate script tags.
const ensureLib = () => {
if (window.htmlToImage) {
return Promise.resolve(window.htmlToImage);
}
if (window._mlpegHtmlToImagePromise) {
return window._mlpegHtmlToImagePromise;
}
window._mlpegHtmlToImagePromise = new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = source;
script.async = true;
script.onload = () => resolve(window.htmlToImage);
script.onerror = () => reject(new Error("Failed to load html-to-image"));
document.head.appendChild(script);
});
return window._mlpegHtmlToImagePromise;
};

const fmt = (request.format || "png").toLowerCase();
const filename = request.filename || `table.${fmt}`;
const basePixelRatio = window.devicePixelRatio || 1;

// A higher PNG pixel ratio keeps text and colour blocks crisp in the export.
// SVG is vector output, so the browser pixel ratio is enough there.
const options = {
cacheBust: true,
pixelRatio: fmt === "png" ? Math.max(3, basePixelRatio * 1.5) : basePixelRatio,
backgroundColor: "#ffffff",
};

return ensureLib()
.then((htmlToImage) => {
if (!htmlToImage) {
throw new Error("html-to-image unavailable");
}
// html-to-image reads the table already drawn by the browser, including
// computed styles, so the export matches the live Dash table instead of
// just the raw table values.
if (fmt === "svg") {
return htmlToImage.toSvg(tableNode, options);
}
return htmlToImage.toPng(tableNode, options);
})
.then((dataUrl) => {
// html-to-image returns a data URL. Dash downloads need the payload split
// into content plus metadata.
const parts = String(dataUrl || "").split(",");
if (parts.length < 2) {
return noUpdate;
}

if (fmt === "svg") {
const content = decodeURIComponent(parts.slice(1).join(","));
return {
content: content,
filename: filename,
type: "image/svg+xml",
};
}

// PNG content remains base64 encoded so dcc.Download can write it as bytes.
return {
base64: true,
content: parts.slice(1).join(","),
filename: filename,
type: "image/png",
};
})
.catch((error) => {
console.error("Table export failed", error);
return noUpdate;
});
},
},
});
88 changes: 88 additions & 0 deletions ml_peg/app/data/table_download/controls.css
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this loaded automatically? I don't see any references to it

I don't fully understand what this does that isn't done by container_style etc below?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changing the container style does not edit the size of the buttons so that we can make them the same size as it only controls the outer wrapper layout around the dropdown/butto to the CSS targets the dropdown’s generated inner elements, plus button hover/active/focus states, which can’t be handled from the wrapper style

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dash loads this automatically because ml_peg/app/data is passed as the app’s assets_folder, so CSS files under that directory are picked up without an explicit import

Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/* Dash loads this file as an asset. These rules support the table export UI. */

/* Normalise Dash Dropdown internals so it aligns with the Download button. */
.table-download-format {
box-sizing: border-box;
height: 30px;
}

.table-download-format .Select {
box-sizing: border-box;
min-height: 30px;
height: 30px;
}

.table-download-format .Select-control {
box-sizing: border-box;
min-height: 30px;
height: 30px;
border: 1px solid #8aa1b4;
border-radius: 6px;
box-shadow: none;
}

.table-download-format .Select-placeholder,
.table-download-format .Select--single > .Select-control .Select-value {
line-height: 28px;
color: #243746;
padding-left: 10px;
}

.table-download-format .Select-input {
height: 28px;
}

.table-download-format .Select-input > input {
line-height: 28px;
padding-top: 0;
padding-bottom: 0;
}

.table-download-format .Select-arrow-zone {
width: 24px;
padding-top: 0;
padding-bottom: 0;
}

/* Small primary action used next to the format dropdown. */
.table-download-button {
box-sizing: border-box;
display: inline-flex;
align-items: center;
justify-content: center;
height: 30px;
min-height: 30px;
padding: 0 12px;
border: 1px solid #0b5cad;
border-radius: 6px;
background: #0b73d9;
color: #ffffff;
font-size: 12px;
font-weight: 600;
line-height: 1;
box-shadow: 0 1px 2px rgb(15 23 42 / 18%);
cursor: pointer;
vertical-align: top;
transition:
background-color 120ms ease,
border-color 120ms ease,
box-shadow 120ms ease;
}

/* Interaction states mirror the app's restrained blue action styling. */
.table-download-button:hover {
background: #095fb5;
border-color: #084f96;
box-shadow: 0 2px 5px rgb(15 23 42 / 24%);
}

.table-download-button:active {
background: #084f96;
box-shadow: inset 0 1px 2px rgb(15 23 42 / 28%);
}

.table-download-button:focus-visible,
.table-download-format .Select.is-focused > .Select-control {
outline: 2px solid #8ec5ff;
outline-offset: 2px;
}
Loading
Loading