urbit-browser-manager/extension/options/index.js

88 lines
2.8 KiB
JavaScript
Raw Normal View History

2021-01-03 01:29:54 -08:00
import React from 'react';
import ReactDOM from 'react-dom';
const browser = require("webextension-polyfill");
class UrbitLoginForm extends React.Component {
constructor(props) {
super(props);
this.setStateFromBrowserStorage = this.setStateFromBrowserStorage.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSave = this.handleSave.bind(this);
this.state = { urbitId: "", urbitCode: "", savedUrbitId: "", savedUrbitCode: "" };
this.setStateFromBrowserStorage();
}
setStateFromBrowserStorage() {
browser.storage.sync.get("credentials")
.then((result) => {
if (result.credentials && result.credentials.urbitId && result.credentials.urbitCode) {
const urbitId = result.credentials.urbitId;
const urbitCode = result.credentials.urbitCode;
this.setState({urbitId, urbitCode, savedUrbitId: urbitId, savedUrbitCode: urbitCode});
}
});
}
handleChange(evt) {
const name = evt.target.name
const value = evt.target.value;
if (name === "urbitId") {
this.setState({urbitId: value});
} else if (name === "urbitCode") {
this.setState({urbitCode: value});
} else if (name === "resetButton") {
this.setState({urbitId: this.state.savedUrbitId, urbitCode: this.state.savedUrbitCode});
} else if (name === "clearButton") {
browser.storage.sync.remove("credentials");
this.setState({ urbitId: "", urbitCode: "", savedUrbitId: "", savedUrbitCode: "" });
}
}
handleSave() {
const urbitId = this.state.urbitId;
const urbitCode = this.state.urbitCode;
browser.storage.sync.set({credentials: {urbitId, urbitCode}});
this.setStateFromBrowserStorage();
}
render() {
const changed = !(this.state.urbitId === this.state.savedUrbitId && this.state.urbitCode === this.state.savedUrbitCode);
const style = { backgroundColor: changed ? "yellow" : "inherit" };
return (
<div style={style}>
<form>
<label>
Urbit ID: <pre>~</pre>
<input type="text" name="urbitId" value={this.state.urbitId} onChange={this.handleChange} />
</label>
<br/>
<label>
Urbit code:
<input type="password" name="urbitCode" value={this.state.urbitCode} onChange={this.handleChange} />
</label>
<button type="button" name="saveButton" onClick={this.handleSave}>Save</button>
<button type="button" name="resetButton" onClick={this.handleChange}>Reset</button>
<br/>
<button type="button" name="clearButton" onClick={this.handleChange}>Remove credentials</button>
</form>
</div>
);
}
}
const Main = () => {
return (
<>
<h1>Urbit credentials</h1>
<UrbitLoginForm />
</>
);
};
ReactDOM.render(
<Main />,
document.querySelectorAll("main")[0]);