Skip to content

Commit

Permalink
downloads and edit mode
Browse files Browse the repository at this point in the history
  • Loading branch information
szweibel committed Sep 14, 2023
1 parent eb307a8 commit 1735775
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 99 deletions.
17 changes: 13 additions & 4 deletions components/ConvertMarkdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ import { renderToStaticMarkup } from 'react-dom/server';
import he from 'he';


export default function ConvertMarkdown(markdown, uploads, workshop, language, setCode, setEditorOpen, setAskToRun, gitUser, gitRepo, gitFile) {
console.log(uploads)
export default function ConvertMarkdown(markdown, uploads, workshopTitle, language, setCode, setEditorOpen, setAskToRun, gitUser, gitRepo, gitFile) {

const Imager = ({ className, ...props }) => {
let newProps = { ...props };
Expand Down Expand Up @@ -113,6 +112,16 @@ export default function ConvertMarkdown(markdown, uploads, workshop, language, s
}
}

// const Downloader = ({ className, children, ...props }) => {
// if (uploads == undefined) return null;
// return (
// <div>
// <Download {...props} />
// </div>
// )
// }


const EditorWithTabs = ({ className, children }) => {
const codeText = children.join('');
return (
Expand Down Expand Up @@ -229,14 +238,14 @@ export default function ConvertMarkdown(markdown, uploads, workshop, language, s
setCode: setCode,
setEditorOpen: setEditorOpen,
setAskToRun: setAskToRun,
workshop: workshop,
workshopTitle: workshopTitle,
}

},
Download: {
component: Download,
props: {
workshop: workshop,
workshopTitle: workshopTitle,
allUploads: uploads,
}
},
Expand Down
110 changes: 72 additions & 38 deletions components/Download.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,59 +3,93 @@ import JSZip from "jszip";
import { saveAs } from "file-saver";

export default function Download(props) {

console.log('props', props);
const allUploads = props.allUploads;

const chosenUploads = typeof props.files === 'string' ? props.files.split(',') : [];
console.log(allUploads);
var filteredUploads = [];

if (chosenUploads != undefined) {
chosenUploads.forEach(upload => {
const currentFile = allUploads.find(file => file.slug === upload.trim());
if (currentFile != undefined) {
filteredUploads.push(currentFile);
}
})
if (chosenUploads != undefined && allUploads.length > 0) {
chosenUploads.forEach(upload => {
const currentFile = allUploads?.find(file => file.name === upload.trim());
if (currentFile != undefined) {
filteredUploads.push(currentFile);
}
})
}
console.log('filteredUploads', filteredUploads);

let headers;
if (process.env.NEXT_PUBLIC_GITHUBSECRET === 'true') {
headers = new Headers(
{
'Content-Type': 'application/json',
'authorization': `token ${process.env.NEXT_PUBLIC_GITHUBSECRET}`
});
} else {
headers = new Headers(
{
'Content-Type': 'application/json',
});
}

const handleDownload = (file) => {
// if there is more than one file, then download all files as a zip
// if there is only one file, then download that file
if (filteredUploads.length > 1) {
console.log(filteredUploads);
if (filteredUploads.length > 0) {
// download all files as a zip
const zip = new JSZip();
filteredUploads.forEach(upload => {
zip.file(upload.slug, upload.content);
});
zip.generateAsync({type: 'blob'})
.then(function(content) {
saveAs(content, props.workshop.slug + '.zip');
});
}
else {
// download the single file
const file = filteredUploads[0];
const blob = new Blob([file.content], {type: 'text/plain'});
saveAs(blob, file.slug);
var downloadFile = function (url, filename) {
return new Promise((resolve, reject) => {
fetch(url, {
headers: headers,
method: 'GET',
}).then(
res => res.json()
).then(
// decode from base64
res => Buffer.from(res.content, 'base64').toString()
).then(
res => {
zip.file(filename, res);
resolve();
}
).catch(
err => {
console.log('err', err)
console.log('workshop.url', url)
}
)
})
}

var downloadAllFiles = async function (files) {
for (let i = 0; i < files.length; i++) {
await downloadFile(files[i].url, files[i].name);
}
}

downloadAllFiles(filteredUploads).then(() => {
zip.generateAsync({ type: "blob" })
.then(function (content) {
saveAs(content, "files.zip");
});
})
}
}

return (
<div className="download-button"
style={{
marginTop: '20px',
// marginBottom: '10px',
}}
>
<button
className="brutalist-button"
style={{
cursor: 'pointer',
marginTop: '20px',
// marginBottom: '10px',
}}
onClick={() => handleDownload(filteredUploads)}>Download: {filteredUploads.map(file =>
<span key={file.slug}>{file.slug} </span>
)}</button>
>
<button
className="brutalist-button"
style={{
cursor: 'pointer',
}}
onClick={() => handleDownload(filteredUploads)}>Download: {filteredUploads.map(file =>
<span key={file.name}>{file.name} </span>
)}</button>
</div>
)
}
4 changes: 2 additions & 2 deletions components/Editor/EditorTopbar.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import CircularProgress from '@mui/material/CircularProgress';
import FileList from "./FileList";
// import FileList from "./FileList";
import Button from '@mui/material/Button';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import CodeIcon from '@mui/icons-material/Code';
Expand Down Expand Up @@ -51,7 +51,7 @@ export default function EditorTopbar(props) {
marginTop: "10px"
}}
/>}
{props.snippets && <FileList snippets={props.snippets} />}
{/* {props.snippets && <FileList snippets={props.snippets} />} */}


{/* <Button
Expand Down
1 change: 1 addition & 0 deletions components/Editor/FileList.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import Select, { SelectChangeEvent } from '@mui/material/Select';


export default function FileList(filteredSnippets) {
console.log(filteredSnippets);
const [files, setFiles] = useState([]);
const [open, setOpen] = useState(false);
const [file, setFile] = useState(null);
Expand Down
2 changes: 1 addition & 1 deletion components/Uploads.js → components/UseUploads.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@ export default function useUploads(allUploads, setAllUploads, gitUser, gitRepo)
}
}, [uploads])

return { uploads, error }
return uploads

}
15 changes: 9 additions & 6 deletions components/useWorkshop.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import useSWRImmutable from "swr/immutable";
import { useState, useEffect } from "react";

export default function useWorkshop(gitUser, gitRepo, gitFile){
export default function useWorkshop(gitUser, builtURL, editing){

let headers;

Expand Down Expand Up @@ -31,11 +31,11 @@ export default function useWorkshop(gitUser, gitRepo, gitFile){
const { data, isLoading, error } = useSWRImmutable(gitUser !=null ? builtURL : null, fetcher(headers),
{
onSuccess(data) {
const matterResult = matter(data)
setCurrentFile(matterResult)
setContent(matterResult.content)
setLanguage(matterResult.data.programming_language);
setWorkshopTitle(matterResult.data.title);
// const matterResult = matter(data)
// setCurrentFile(matterResult)
// setContent(matterResult.content)
// setLanguage(matterResult.data.programming_language);
// setWorkshopTitle(matterResult.data.title);
},
onFailure(err) {
console.log('err', err)
Expand All @@ -46,6 +46,9 @@ export default function useWorkshop(gitUser, gitRepo, gitFile){
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
revalidateOnMount: editing ? true : false
})

return data

}
56 changes: 8 additions & 48 deletions pages/dynamic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import DrawerEditor from '../../components/Editor/DrawerEditor'
import { styled, useTheme } from '@mui/material/styles';
import ClassFacilitator from '../../components/ClassFacilitator'
import useSWRImmutable from 'swr/immutable';
import useUploads from '../../components/Uploads'
import useUploads from '../../components/UseUploads'
import useWorkshop from '../../components/UseWorkshop'

const drawerWidth = '-30%';

Expand All @@ -40,9 +41,7 @@ const Main = styled('main', { shouldForwardProp: (prop) => prop !== 'open' })(


export default function WorkshopPage({
workshop,
authors,
// uploads,
title,
setTitle
// facilitators,
Expand All @@ -66,13 +65,14 @@ export default function WorkshopPage({
const [gitRepo, setGitRepo] = useState(null);
const [gitFile, setGitFile] = useState(null);
const [builtURL, setBuiltURL] = useState(null);
const [editing, setEditing] = useState(false);

const [allUploads, setAllUploads] = useState([]);
const uploads = useUploads(allUploads, setAllUploads, gitUser, gitRepo);

// convert markdown to html and split into pages
const convertContenttoHTML = function (content) {
const htmlifiedContent = ConvertMarkdown(content, uploads, workshop, language, setCode, setEditorOpen, setAskToRun, gitUser, gitRepo, gitFile);
const htmlifiedContent = ConvertMarkdown(content, uploads, workshopTitle, language, setCode, setEditorOpen, setAskToRun, gitUser, gitRepo, gitFile);
// split react element array into pages
const allPages = [];
const pages = htmlifiedContent?.props.children.reduce((acc, curr) => {
Expand Down Expand Up @@ -109,58 +109,18 @@ export default function WorkshopPage({
)
}

let headers;
if (process.env.NEXT_PUBLIC_GITHUBSECRET === 'true') {
headers = new Headers(
{
'Content-Type': 'application/json',
'authorization': `token ${process.env.NEXT_PUBLIC_GITHUBSECRET}`
});
} else {
headers = new Headers(
{
'Content-Type': 'application/json',
});
}

const fetcher = (headers) => (...args) => fetch(...args, {
headers: headers,
method: 'GET',
}).then(
res => res.json()
).then(
// decode from base64
res => Buffer.from(res.content, 'base64').toString()
)

const { data, isLoading, error } = useSWRImmutable(gitUser !=null ? builtURL : null, fetcher(headers),
{
onSuccess(data) {
const matterResult = matter(data)
setCurrentFile(matterResult)
setContent(matterResult.content)
setLanguage(matterResult.data.programming_language);
setWorkshopTitle(matterResult.data.title);
},
onFailure(err) {
console.log('err', err)
console.log('workshop.url', builtURL)
}
},
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
})
const data = useWorkshop(gitUser, builtURL, editing);

useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
setGitUser(urlParams.get('user'));
setGitRepo(urlParams.get('repo'));
setGitFile(urlParams.get('file'));
setEditing(urlParams.get('edit'));
if (gitFile === null) {
setBuiltURL(`https://api.github.com/repos/${gitUser}/${gitRepo}/contents/${gitRepo}.md`)
} else {
}
else {
setBuiltURL(`https://api.github.com/repos/${gitUser}/${gitRepo}/contents/${gitFile}.md`)
}
}, [gitUser, gitRepo, gitFile])
Expand Down

0 comments on commit 1735775

Please sign in to comment.