import { h, Component, createRef } from 'https://unpkg.com/preact?module'; import htm from 'https://unpkg.com/htm?module'; const html = htm.bind(h); import { generateAvatar, setLocalStorage } from '../../utils/helpers.js'; import { KEY_USERNAME, KEY_AVATAR } from '../../utils/constants.js'; export default class UsernameForm extends Component { constructor(props, context) { super(props, context); this.state = { displayForm: 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); } 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, handleUsernameChange } = this.props; let newName = this.textInput.current.value; newName = newName.trim(); if (newName !== '' && newName !== curName) { const newAvatar = generateAvatar(`${newName}${Date.now()}`); setLocalStorage(KEY_USERNAME, newName); setLocalStorage(KEY_AVATAR, newAvatar); if (handleUsernameChange) { handleUsernameChange(newName, newAvatar); } this.handleHideForm(); } } render(props, state) { const { username, userAvatarImage } = props; const { displayForm } = state; const narrowSpace = document.body.clientWidth < 640; const formDisplayStyle = narrowSpace ? 'inline-block' : 'flex'; const styles = { info: { display: displayForm ? 'none' : 'flex', }, form: { display: displayForm ? formDisplayStyle : 'none', }, }; return ( html`
${username}
`); } }