-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathAddFileButton.ts
More file actions
112 lines (97 loc) · 3.18 KB
/
AddFileButton.ts
File metadata and controls
112 lines (97 loc) · 3.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { customElement, state } from "lit/decorators.js";
import { PapyrosElement } from "./PapyrosElement";
import { css, CSSResult, html, TemplateResult } from "lit";
import { createRef, ref, Ref } from "lit/directives/ref.js";
import { inlineInputStyles } from "./shared-styles";
import { isValidFileName } from "../../util/Util";
@customElement("p-add-file-button")
export class AddFileButton extends PapyrosElement {
@state()
private adding = false;
@state()
private invalid = false;
private addInputRef: Ref<HTMLInputElement> = createRef();
static get styles(): CSSResult {
return css`
:host {
display: flex;
}
.add-btn {
padding: 0.375rem 0.5rem;
border: none;
border-bottom: 2px solid var(--md-sys-color-outline);
border-radius: 0.375rem 0.375rem 0 0;
cursor: pointer;
font-size: 1rem;
line-height: 1;
background-color: var(--md-sys-color-surface-variant);
color: var(--md-sys-color-on-surface-variant);
}
.add-btn:hover {
opacity: 0.8;
}
${inlineInputStyles}
`;
}
private startAdding(): void {
this.adding = true;
this.invalid = false;
}
private confirmAdd(): void {
const name = this.addInputRef.value?.value.trim() ?? "";
if (!this.papyros.io.addFile(name)) {
return;
}
void this.papyros.runner.updateFile(name, "", false);
this.adding = false;
}
private cancelAdd(): void {
this.adding = false;
}
private onAddInput(): void {
const value = this.addInputRef.value?.value.trim() ?? "";
this.invalid = !isValidFileName(value) || this.papyros.io.files.some((f) => f.name === value);
}
private onBlur(): void {
if (!this.adding) return;
const name = this.addInputRef.value?.value.trim() ?? "";
if (name.length === 0) {
this.cancelAdd();
} else {
this.confirmAdd();
}
}
private onAddKeydown(e: KeyboardEvent): void {
if (e.key === "Enter") {
e.preventDefault();
this.confirmAdd();
} else if (e.key === "Escape") {
this.cancelAdd();
}
}
protected override updated(): void {
if (this.adding) {
this.addInputRef.value?.focus();
}
}
protected override render(): TemplateResult {
if (this.adding) {
return html`<input
${ref(this.addInputRef)}
class=${this.invalid ? "inline-input invalid" : "inline-input"}
placeholder=${this.t("Papyros.add_file_placeholder")}
@input=${this.onAddInput}
@keydown=${this.onAddKeydown}
@blur=${this.onBlur}
/>`;
}
return html`<button
class="add-btn"
title=${this.t("Papyros.add_file")}
aria-label=${this.t("Papyros.add_file")}
@click=${this.startAdding}
>
+
</button>`;
}
}