Skip to content

Commit

Permalink
WIP: Handle report loading on copy to clipboard
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarssanchez committed Feb 21, 2025
1 parent 7d98765 commit 63e055e
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions assets/js/status-report/components/reports.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
*/
import { Button, Flex, FlexItem } from '@wordpress/components';
import { useCopyToClipboard } from '@wordpress/compose';
import { WPElement } from '@wordpress/element';
import { WPElement, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies.
*/
import Report from './reports/report';
import { useSettingsScreen } from '../../settings-screen';
import { loadGroupAjax } from '../utilities';

/**
* Styles.
Expand All @@ -28,17 +29,47 @@ import '../style.css';
export default ({ plainTextReport, reports }) => {
const { createNotice } = useSettingsScreen();

const [reportText, setReportText] = useState(null);
const downloadUrl = `data:text/plain;charset=utf-8,${encodeURIComponent(plainTextReport)}`;

/**
* Copy to clipboard button ref.
*
* @type {object}
*/
const ref = useCopyToClipboard(plainTextReport, () => {
createNotice('info', __('Copied status report to clipboard.', 'elasticpress'));
const ref = useCopyToClipboard(reportText, () => {
createNotice(
'success',
__(
'The status report has been copied to the clipboard. You can now paste it into a text editor.',
'elasticpress',
),
);
});

/**
* Handle loading and building report plain text.
*/
const handleReportLoading = async () => {
if (reportText) {
return;
}

const ajaxReportPromises = Object.entries(reports)
.filter(([key, reportData]) => reportData.is_ajax_report) // eslint-disable-line no-unused-vars
.map(async ([key]) => {
const response = await loadGroupAjax(key);
const jsonData = await response.json();
return jsonData;
});

const text = await Promise.all(ajaxReportPromises).then((ajaxReportTexts) => {
return JSON.stringify(ajaxReportTexts, null, 2);
});

setReportText(text);
};

return (
<>
<p>
Expand All @@ -52,14 +83,15 @@ export default ({ plainTextReport, reports }) => {
<FlexItem>
<Button
download="elasticpress-report.txt"
href={downloadUrl}
onClick={handleReportLoading}
href={reportText ? null : downloadUrl}
variant="primary"
>
{__('Download status report', 'elasticpress')}
</Button>
</FlexItem>
<FlexItem>
<Button ref={ref} variant="secondary">
<Button ref={ref} onClick={handleReportLoading} variant="secondary">
{__('Copy status report to clipboard', 'elasticpress')}
</Button>
</FlexItem>
Expand Down

0 comments on commit 63e055e

Please sign in to comment.