import { h, Component, createRef } from '/js/web_modules/preact.js'; import htm from '/js/web_modules/htm.js'; const html = htm.bind(h); import { setLocalStorage } from '../../utils/helpers.js'; import { KEY_USERNAME, KEY_CUSTOM_USERNAME_SET } from '../../utils/constants.js'; export default class UsernameForm extends Component { constructor(props, context) { super(props, context); this.state = { displayForm: false, isFocused: false, }; this.textInput = createRef(); this.handleKeydown = this.handleKeydown.bind(this); this.handleDisplayForm = this.handleDisplayForm.bind(this); this.handleHideForm = this.handleHideForm.bind(this); this.handleUpdateUsername = this.handleUpdateUsername.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); } handleDisplayForm() { const { displayForm: curDisplay } = this.state; this.setState({ displayForm: !curDisplay, }); } handleHideForm() { this.setState({ displayForm: false, }); } handleKeydown(event) { if (event.keyCode === 13) { // enter this.handleUpdateUsername(); } else if (event.keyCode === 27) { // esc this.handleHideForm(); } } handleUpdateUsername() { const { username: curName, onUsernameChange } = this.props; let newName = this.textInput.current.value; newName = newName.trim(); if (newName !== '' && newName !== curName) { setLocalStorage(KEY_USERNAME, newName); // So we know that the user has set a custom name setLocalStorage(KEY_CUSTOM_USERNAME_SET, true); if (onUsernameChange) { onUsernameChange(newName); } this.handleHideForm(); } } handleFocus() { const { onFocus } = this.props; if (onFocus) { onFocus(); } } handleBlur() { const { onBlur } = this.props; if (onBlur) { onBlur(); } } render(props, state) { const { username } = props; const { displayForm } = state; const styles = { info: { display: displayForm ? 'none' : 'flex', }, form: { display: displayForm ? 'flex' : 'none', }, }; return ( html`