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
|
/*
This file is part of jshelper (https://codeberg.org/metamuffin/jshelper)
which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
Copyright (C) 2024 metamuffin <metamuffin.org>
*/
import { e } from "./element.ts"
export class Logger<T = HTMLElement> {
public element: HTMLElement = e("div", { class: "jsh-log" })
public bins: Map<string, HTMLElement> = new Map()
constructor(
private map_fn: (value: T) => HTMLElement = e => {
if (e instanceof HTMLElement) return e;
else throw new Error("logger: map_fn required if T is not HTMLElement");
},
private reverse = false,
private timeout = 3000,
private animation_duration = 1000,
) {
}
private add(v: T) {
const el = this.map_fn(v)
if (this.reverse) this.element.prepend(el)
else this.element.append(el)
return el
}
log(value: T, bin?: string) {
const el = this.add(value)
if (bin) {
const oel = this.bins.get(bin)
if (oel && oel.parentElement) this.element.removeChild(oel)
else el.classList.add("jsh-log-line-appear")
this.bins.set(bin, el)
} else {
el.classList.add("jsh-log-line-appear")
}
el.classList.add("jsh-log-line", "jsh-log-line-timeout")
setTimeout(() => {
el.classList.add("jsh-log-line-disappear")
setTimeout(() => {
if (el.parentElement)
this.element.removeChild(el)
}, this.animation_duration)
}, this.timeout + this.animation_duration)
}
log_persistent(value: T): () => void {
const el = this.add(value)
el.classList.add("jsh-log-line", "jsh-log-line-persistent", "jsh-log-line-appear")
return () => {
el.classList.add("jsh-log-line-disappear")
setTimeout(() => {
if (el.parentElement)
this.element.removeChild(el)
}, this.animation_duration)
}
}
}
|