Files
2026-11-07 18:31:45 +04:00

120 lines
3.3 KiB
Plaintext

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { on } from '@ember/modifier';
import { service } from '@ember/service';
import autofocus from '../modifiers/autofocus';
// Greets the user by the name stored in the `user` service. The name is
// clickable and edits in place; saving and cancelling are idempotent so the
// blur that follows either path is a no-op.
export default class GreetingComponent extends Component {
@service clock;
@service user;
@tracked isEditing = false;
@tracked draft = '';
@tracked refocusName = false;
get greeting() {
const hour = this.clock.time.getHours();
if (hour < 12) return 'Good morning';
if (hour < 18) return 'Good afternoon';
return 'Good evening';
}
@action
startEditing() {
this.refocusName = false;
this.draft = this.user.name ?? '';
this.isEditing = true;
}
@action
updateDraft(event) {
this.draft = event.target.value;
}
@action
handleKeyDown(event) {
if (event.key === 'Escape') {
event.preventDefault();
this.cancel({ refocus: true });
}
}
@action
handleBlur() {
this.save();
}
@action
async handleSubmit(event) {
event.preventDefault();
await this.save();
}
async save() {
if (!this.isEditing) return;
const name = (this.draft ?? '').trim();
if (!name) {
// Blurring an empty field reverts rather than clearing the name.
this.cancel();
return;
}
// Do not refocus the name after saving; otherwise the focus-visible ring
// stays drawn around it once the input is replaced by the button.
this.refocusName = false;
this.isEditing = false;
await this.user.setName(name);
}
cancel({ refocus = false } = {}) {
if (!this.isEditing) return;
this.refocusName = refocus;
this.isEditing = false;
}
<template>
{{#if this.user.name}}
<div class="text-[2rem]">
{{this.greeting}},
{{#if this.isEditing}}
<form class="inline" {{on "submit" this.handleSubmit}}>
<label class="sr-only" for="greeting-name-input">Your name</label>
<input
id="greeting-name-input"
name="name"
type="text"
required
size="8"
class="name border-0 border-b border-white/70 bg-transparent px-1 text-[2rem] text-white text-shadow-lg focus:border-white focus:outline-none"
value={{this.draft}}
{{on "input" this.updateDraft}}
{{on "keydown" this.handleKeyDown}}
{{on "blur" this.handleBlur}}
{{autofocus select=true}}
/>
</form>
{{else}}
<button
type="button"
class="name cursor-pointer align-baseline text-shadow-lg no-underline underline-offset-4 transition-colors hover:underline hover:decoration-dotted hover:decoration-white/60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white/70"
aria-label="Edit name"
title="Edit name"
data-test-greeting-name
{{on "click" this.startEditing}}
{{autofocus when=this.refocusName}}
>
{{~this.user.name~}}
</button>
{{~/if}}.
</div>
{{/if}}
</template>
}