Basic download button

This commit is contained in:
Rene Saarsoo 2023-01-04 16:33:58 +02:00
parent 59e6ae4726
commit 6d53809fc3
2 changed files with 29 additions and 1 deletions

View File

@ -1,6 +1,7 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { Workout, generateZwo } from "zwiftout"; import { Workout, generateZwo } from "zwiftout";
import styled from "styled-components"; import styled from "styled-components";
import { download } from "../download";
const Header = styled.h2` const Header = styled.h2`
font-weight: normal; font-weight: normal;
@ -20,11 +21,26 @@ const ShowHideButton = styled.button`
float: right; float: right;
`; `;
const DownloadButton = styled.button`
border: 1px solid #bbb;
border-radius: 3px;
padding: 3px 8px;
margin-left: 16px;
`;
// Creates .zwo file name from workout name
const workoutFileName = (name: string): string => name.replace(/[^\w]/, "-").replace(/-+/, "-").toLowerCase() + ".zwo";
export const ZwoOutput: React.FC<{ workout: Workout }> = ({ workout }) => { export const ZwoOutput: React.FC<{ workout: Workout }> = ({ workout }) => {
const [expanded, setExpanded] = useState(false); const [expanded, setExpanded] = useState(false);
return ( return (
<div> <div>
<Header>Generated Zwift workout file (.zwo):</Header> <Header>
Generated Zwift workout file (.zwo):
<DownloadButton onClick={() => download(workoutFileName(workout.name), generateZwo(workout))}>
Download
</DownloadButton>
</Header>
<ZwoCode> <ZwoCode>
<ShowHideButton onClick={() => setExpanded(!expanded)}>{expanded ? "Hide ZWO" : "Show ZWO"}</ShowHideButton> <ShowHideButton onClick={() => setExpanded(!expanded)}>{expanded ? "Hide ZWO" : "Show ZWO"}</ShowHideButton>
{expanded ? generateZwo(workout) : ""} {expanded ? generateZwo(workout) : ""}

12
src/download.ts Normal file
View File

@ -0,0 +1,12 @@
export function download(filename: string, xml: string) {
const file = new Blob([xml], { type: "application/xml" });
const url = URL.createObjectURL(file);
var a = document.createElement("a");
document.body.appendChild(a);
a.style.display = "none";
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}