import {OOElement} from '../oo-element' import {html} from '../../lib/html' import weakMap from '../../lib/weak-map' import {permalinks, usable, put} from './lib/fetch-permalink' interface HTMLElementEvent extends KeyboardEvent { target: T } const ATTR = { DATA_IAM: 'data-iam' } const stateIam = weakMap() const statePermalink = weakMap() const stateProgress = weakMap() const stateUsable = weakMap() const stateSaved = weakMap() const stateSaveSuccess = weakMap() const stateThrottleTimer = weakMap() export default class extends OOElement { static get observedAttributes() { return [ATTR.DATA_IAM] } attributeChangedCallback(attr, prev, next) { if (prev === next || !next) { return } stateIam.set(this, next) this.fetchPermalink() } connectedCallback() { super.connectedCallback(false) } render() { const {p, s, u, sd, ss} = { p: stateProgress.get(this), s: statePermalink.get(this), u: stateUsable.get(this), sd: stateSaved.get(this), ss: stateSaveSuccess.get(this) } const iam = stateIam.get(this) const cls = p ? 'progress' : u === false ? 'not-usable' : u && s ? 'usable' : '' const btn = html`` return html`
${btn}
https://ooapp.co/${s || iam} ` } async fetchPermalink() { stateProgress.set(this, true) this.update() const permalink = await permalinks(stateIam.get(this)) if (typeof permalink !== 'boolean') { const {slug} = permalink statePermalink.set(this, slug) } stateProgress.delete(this) this.update() } async validatePermalink(path: string) { stateProgress.set(this, true) stateSaved.delete(this) stateSaveSuccess.delete(this) this.update() const isUsable = await usable(path) stateUsable.set(this, isUsable) stateProgress.delete(this) this.update() } async putPermalink() { stateProgress.set(this, true) this.update() const permalink = await put(statePermalink.get(this)) stateSaved.set(this, true) stateSaveSuccess.set(this, Boolean(permalink)) stateProgress.delete(this) this.update() } onKeyup(e: HTMLElementEvent) { const {target} = e const {value} = target statePermalink.set(this, value) const timer = stateThrottleTimer.get(this) if (timer) { clearTimeout(timer) } stateThrottleTimer.set(this, setTimeout(() => { this.validatePermalink(statePermalink.get(this)) }, 300)) } }