Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Feature: state restoration #68

Merged
merged 9 commits into from
Aug 5, 2020
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "babel-sandboxes",
"version": "1.0.0",
"description": "",
"proxy": "http://localhost:3005",
"dependencies": {
"@babel/core": "~7.10.0",
"@babel/plugin-external-helpers": "~7.10.0",
Expand Down
43 changes: 22 additions & 21 deletions src/components/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,33 @@ import { Output } from "./Output";
import { gzipSize } from "../gzip";
import { Root } from "./styles";
import { useDebounce } from "../utils/useDebounce";
import REPLState from "../state/REPLState.js";
import { REPLState } from "../state";

import { Grid } from "semantic-ui-react";
import {plugins} from "../plugins-list";
import { plugins } from "../plugins-list";

window.babel = Babel;

/**
* Converts internal json plugin/preset config to babel form
* @param {Object} jsonConfig
* @param {Object} jsonConfig
*/
export function convertToBabelConfig(jsonConfig) {
let result = {plugins: [], presets: []};
result.plugins = jsonConfig.plugins?.map(plugin => [plugin.name, plugin.defaultConfig]);
result.presets = jsonConfig.presets?.map(preset => [preset.name, preset.defaultConfig]);
let result = { plugins: [], presets: [] };
result.plugins = jsonConfig.plugins?.map(plugin => [
plugin.name,
plugin.defaultConfig,
]);
result.presets = jsonConfig.presets?.map(preset => [
preset.name,
preset.defaultConfig,
]);
return result;
}

export function convertToJsonConfig(babelConfig) {
let result = {plugins: [], presets: []}
result.plugins = babelConfig.plugins?.map((plugin) => {
let result = { plugins: [], presets: [] };
result.plugins = babelConfig.plugins?.map(plugin => {
return {
name: plugin[0],
description: plugins[plugin[0]].description,
Expand Down Expand Up @@ -71,16 +77,12 @@ function registerDefaultPlugins() {
);
}



export const App = ({ defaultSource, defaultConfig, defCustomPlugin }) => {
const [source, setSource] = React.useState(defaultSource);
const [enableCustomPlugin, toggleCustomPlugin] = React.useState(true);
const [customPlugin, setCustomPlugin] = React.useState(defCustomPlugin);
const [jsonConfig, setJsonConfig] = useState(
Array.isArray(defaultConfig)
? defaultConfig
: [defaultConfig]
Array.isArray(defaultConfig) ? defaultConfig : [defaultConfig]
);
const [size, setSize] = useState(null);
const [gzip, setGzip] = useState(null);
Expand All @@ -89,16 +91,16 @@ export const App = ({ defaultSource, defaultConfig, defCustomPlugin }) => {
const [showShareLink, setShowShareLink] = React.useState(false);

const updateBabelConfig = useCallback((config, index) => {
setJsonConfig((configs) => {
setJsonConfig(configs => {
const newConfigs = [...configs];
newConfigs[index] = config;

return newConfigs;
});
}, []);

const removeBabelConfig = useCallback((index) => {
setJsonConfig((configs) => configs.filter((c, i) => index !== i));
const removeBabelConfig = useCallback(index => {
setJsonConfig(configs => configs.filter((c, i) => index !== i));
}, []);

useEffect(() => {
Expand All @@ -124,18 +126,17 @@ export const App = ({ defaultSource, defaultConfig, defCustomPlugin }) => {
const state = new REPLState(
source,
enableCustomPlugin ? customPlugin : "",
jsonConfig.map((config) => JSON.stringify(config))
jsonConfig.map(config => JSON.stringify(config))
);
const link = await state.Link();

setShareLink(link);
setShowShareLink(true);
}}
>
Share
</button>
{showShareLink && (
<input type="text" value={shareLink} readOnly></input>
)}
</button>
{showShareLink && <input type="text" value={shareLink} readOnly></input>}
<Grid celled="internally">
<Input size={size} gzip={gzip} source={source} setSource={setSource} />
{enableCustomPlugin && (
Expand Down
37 changes: 29 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from "react";
import { render } from "react-dom";
import { App } from "./components/App";
import { extractID, isShareLink, REPLState } from "./state";

// css
import "semantic-ui-less/semantic.less";
Expand Down Expand Up @@ -45,7 +46,7 @@ const CONFIG = [
// description: "does this",
// defaultConfig: {},
// }
]
],
},
// {},
];
Expand All @@ -61,11 +62,31 @@ const PLUGIN = `export default function customPlugin(babel) {
}
`;

render(
<App
defaultConfig={CONFIG}
defaultSource={SOURCE}
defCustomPlugin={PLUGIN}
/>,
document.getElementById("root")
const defaultState = new REPLState(
SOURCE,
PLUGIN,
CONFIG.map(conf => JSON.stringify(conf))
);

/**
* @returns {Promise<REPLState>}
*/
async function getState() {
if (!isShareLink()) {
return defaultState;
}
const state = await REPLState.FromID(extractID());
return state === null ? defaultState : state;
}

(async () => {
const state = await getState();
render(
<App
defaultConfig={state.configs.map(conf => JSON.parse(conf))}
defaultSource={state.jsSource}
defCustomPlugin={state.pluginSource}
/>,
document.getElementById("root")
);
})();
71 changes: 49 additions & 22 deletions src/state/REPLState.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,30 +62,12 @@ class REPLState {
return JSON.stringify({
source: encodeToBase64(this.jsSource),
plugin: encodeToBase64(this.pluginSource),
configs: this.configs.map((configSrc) => {
configs: this.configs.map(configSrc => {
return encodeToBase64(configSrc);
}),
});
}

/**
* Link gets the sharing the sharing link
* for the given REPL state.
* @returns {Promise<string>} String URL.
*/
async Link() {
const url = "http://localhost:1337/api/v1/blobs/create";
const resp = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: this.Encode(),
});
return resp.text();
}

/**
* Decode decodes the json string.
* @param {string} encodedState
Expand All @@ -94,13 +76,58 @@ class REPLState {
static Decode(encodedState) {
let jsonState = JSON.parse(encodedState);
return new REPLState(
decodeBase64(jsonState.source),
decodeBase64(jsonState.plugin),
jsonState.configs.map((configs) => {
decodeBase64(jsonState.base64SourceKey),
decodeBase64(jsonState.base64PluginKey),
jsonState.configIDs.map(configs => {
mohammedsahl marked this conversation as resolved.
Show resolved Hide resolved
return decodeBase64(configs);
})
);
}

/**
* Link gets the sharing the sharing link
* for the given REPL state.
* @returns {Promise<string>} String URL.
*/
async Link() {
const url = `/api/v1/blobs/create`;
try {
const resp = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: this.Encode(),
});
const message = await resp.json();

// https://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
return (
window.location.href.split("/").slice(0, 3).join("/") + message.url
);
} catch (err) {
console.error(err);
return err;
}
}

/**
* REPLState.FromID returns a REPLState given a unique identifier.
* @param {string} ID
* @returns {Promise<REPLState | null>}
*/
static async FromID(ID) {
const url = `/api/v1/blobs/${ID}`;
try {
const resp = await fetch(url);
const text = await resp.text();
return REPLState.Decode(text);
} catch (err) {
console.error(err);
return null;
}
}
}

export default REPLState;
22 changes: 22 additions & 0 deletions src/state/detectShare.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* isShareLink returns true iff the pathname contains the text `share`
* @returns {boolean}
*/
function isShareLink() {
const path = window.location.pathname;
const shareIndicator = "share";
return path.includes(shareIndicator);
}

function extractID() {

// Attempt to capture :key from http://example.com/share/:key/
const pathParts = window.location.pathname.split('/');
if (pathParts[1] == 'share' && pathParts[2]) {
return pathParts[2];
} else {
throw new Error("Trying to extract ID from a share link that doesn't have one.")
}
}

export { isShareLink, extractID };
4 changes: 4 additions & 0 deletions src/state/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import REPLState from "./REPLState.js";
import { extractID, isShareLink } from "./detectShare.js";

export { REPLState, extractID, isShareLink };