|
| 1 | +import type { NeoProgressHTMLElement, NeoProgressStart } from '~/progress/neo-progress.model.js'; |
| 2 | + |
| 3 | +import { getUUID } from '@dvcol/common-utils/common/string'; |
| 4 | +import { SvelteSet } from 'svelte/reactivity'; |
| 5 | + |
| 6 | +import { NeoProgressStatus } from '~/progress/neo-progress.model.js'; |
| 7 | + |
| 8 | +/** |
| 9 | + * Queuing service to keep track of concurrent call to progress bar |
| 10 | + */ |
| 11 | +export class NeoProgressService { |
| 12 | + #ref: NeoProgressHTMLElement; |
| 13 | + #active = $state(new SvelteSet<string>()); |
| 14 | + |
| 15 | + get value() { |
| 16 | + return this.#ref.value; |
| 17 | + } |
| 18 | + |
| 19 | + get buffer() { |
| 20 | + return this.#ref.buffer; |
| 21 | + } |
| 22 | + |
| 23 | + get status() { |
| 24 | + return this.#ref.status; |
| 25 | + } |
| 26 | + |
| 27 | + get active(): Set<string> { |
| 28 | + return $state.snapshot(this.#active); |
| 29 | + } |
| 30 | + |
| 31 | + constructor(ref: NeoProgressHTMLElement) { |
| 32 | + this.#ref = ref; |
| 33 | + } |
| 34 | + |
| 35 | + sync() { |
| 36 | + if (this.status === NeoProgressStatus.Active) return; |
| 37 | + if (this.status === NeoProgressStatus.Indeterminate) return; |
| 38 | + this.#active.clear(); |
| 39 | + return this.active; |
| 40 | + } |
| 41 | + |
| 42 | + start(opts?: NeoProgressStart, id = getUUID()) { |
| 43 | + this.sync(); |
| 44 | + this.#active.add(id); |
| 45 | + if (this.status === NeoProgressStatus.Active) this.#ref.reset(true, opts); |
| 46 | + else this.#ref.start(opts); |
| 47 | + return id; |
| 48 | + } |
| 49 | + |
| 50 | + cancel(id?: string, force = !id) { |
| 51 | + this.sync(); |
| 52 | + if (id) this.#active.delete(id); |
| 53 | + if (force || this.#active.size === 0) void this.#ref.cancel(); |
| 54 | + return id; |
| 55 | + } |
| 56 | + |
| 57 | + complete(id?: string, force = !id) { |
| 58 | + this.sync(); |
| 59 | + if (id) this.#active.delete(id); |
| 60 | + if (force || this.#active.size === 0) void this.#ref.complete(); |
| 61 | + return id; |
| 62 | + } |
| 63 | + |
| 64 | + error(id?: string, force = !id) { |
| 65 | + this.sync(); |
| 66 | + if (id) this.#active.delete(id); |
| 67 | + if (force || this.#active.size === 0) void this.#ref.complete({ state: NeoProgressStatus.Error }); |
| 68 | + return id; |
| 69 | + } |
| 70 | + |
| 71 | + success(id?: string, force = !id) { |
| 72 | + this.sync(); |
| 73 | + if (id) this.#active.delete(id); |
| 74 | + if (force || this.#active.size === 0) void this.#ref.complete({ state: NeoProgressStatus.Success }); |
| 75 | + return id; |
| 76 | + } |
| 77 | + |
| 78 | + warning(id?: string, force = !id) { |
| 79 | + this.sync(); |
| 80 | + if (id) this.#active.delete(id); |
| 81 | + if (force || this.#active.size === 0) void this.#ref.complete({ state: NeoProgressStatus.Warning }); |
| 82 | + return id; |
| 83 | + } |
| 84 | +} |
0 commit comments