diff --git a/css/dashboard.css b/css/dashboard.css index 240dfd8..63f44cf 100644 --- a/css/dashboard.css +++ b/css/dashboard.css @@ -79,6 +79,10 @@ body.rtl .statify-chart * { width: 80%; } +.statify-table + a.button { + margin: 1em 0 0 1em; +} + #statify_dashboard .postbox-title-action a, #statify_dashboard .settings-link a { diff --git a/inc/class-statify.php b/inc/class-statify.php index 57892ad..78571c8 100755 --- a/inc/class-statify.php +++ b/inc/class-statify.php @@ -269,7 +269,8 @@ public static function add_js(): void { 'statifyDashboard', array( 'i18n' => array( - 'months' => array_map( + 'sitename' => sanitize_key( get_bloginfo( 'name' ) ), + 'months' => array_map( function ( $m ) { return date_i18n( 'M', strtotime( '0000-' . $m . '-01' ) ); }, diff --git a/js/dashboard.js b/js/dashboard.js index 8b92b4c..c6f1781 100644 --- a/js/dashboard.js +++ b/js/dashboard.js @@ -354,13 +354,15 @@ tbody.insertBefore(row, tbody.firstChild); } + + addExportButton(table); } /** * Render yearly table. * - * @param {HTMLElement} table Root element. - * @param {any} data Data from API. + * @param {HTMLTableElement} table Root element. + * @param {any} data Data from API. */ function renderDailyTable(table, data) { const rows = Array.from(table.querySelectorAll('tbody > tr')); @@ -427,6 +429,8 @@ for (const row of rows) { row.classList.remove('placeholder'); } + + addExportButton(table); } /** @@ -500,4 +504,43 @@ '

'; }); } + + /** + * Add a CSV export button to a table. + * + * @param {HTMLTableElement} table Table to process + */ + function addExportButton(table) { + const exportBtn = document.createElement('a'); + exportBtn.classList.add('button'); + exportBtn.role = 'button'; + + // Generate filename from table caption. + exportBtn.download = + statifyDashboard.i18n.sitename + + '-' + + table.caption.innerText.replaceAll(/\s+/g, '_') + + '-export-' + + new Date() + .toISOString() + .replace('T', '_') + .replaceAll(':', '-') + .substring(0, 16) + + '.csv'; + + // Generate CSV on demand. + exportBtn.innerText = wp.i18n.__('Export (CSV)', 'statify'); + exportBtn.addEventListener('click', () => { + exportBtn.href = + 'data:text/csv;charset=utf-8,' + + Array.from(table.rows) + .map((row) => + Array.from(row.cells) + .map((col) => col.innerText) + .join(',') + ) + .join('\r\n'); + }); + table.after(exportBtn); + } } diff --git a/views/view-dashboard.php b/views/view-dashboard.php index d4026d0..37c4efe 100644 --- a/views/view-dashboard.php +++ b/views/view-dashboard.php @@ -91,6 +91,7 @@ class="nav-tab"

+ @@ -134,6 +135,15 @@ class="nav-tab" ?>
+
+ +