import { Post } from "./types"; export const parseFilename = (titleToFilename: string): string => { if (!titleToFilename) { return 'None yet.' } titleToFilename = titleToFilename.replace(/[^a-zA-Z0-9_]+/gi, '-').toLowerCase(); while (titleToFilename.endsWith('-')) { titleToFilename = titleToFilename.slice(0, -1); } // Limit filename size if (titleToFilename.length > 50) { titleToFilename = titleToFilename.substring(0, 50); if (titleToFilename.includes('-')) { // Re-trim to avoid cutting a word in half. titleToFilename = titleToFilename.substring(0, Math.min(titleToFilename.length, titleToFilename.lastIndexOf('-'))); } } return titleToFilename; } export const downloadFile = (dataObj: any, fileName: string): void => { const blob = new Blob([JSON.stringify(dataObj, null, 2)], { type: 'text/plain;charset=utf-8;' }); const a = document.createElement('a'); a.setAttribute('download', `${fileName}.json`); a.setAttribute('href', window.URL.createObjectURL(blob)); a.click(); } // Bad code ahead. Sail with caution! export const loadFromFile = (file: any): Promise => { return new Promise((resolve, reject) => { const reader = new FileReader(); if (!file) { reject('No file!'); } reader.onload = (event => { const contents: any = (event.target as FileReader).result; // Yes, this is extremely hacky... Empty object just to test below. 'Cuz I'm lazy. const objCompare: Post = { postTitle: "", timestamp: "", editedTimestamp: "", postContent: "", filename: "", draft: false }; // And yes, I know this is crazy but it works. try { if (Object.keys(JSON.parse(contents.toString())).toString() === Object.keys(objCompare).toString()) { resolve(JSON.parse(contents.toString())); } else { alert('Invalid file! Are you sure it\'s an Dumblog compatible JSON?'); reject('Invalid file!'); } } catch (e) { alert('Error loading file! Check the console for more info.'); console.log(e); reject('Error loading file!'); } }); reader.onerror = reject; reader.readAsText(file); }); }