]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/string/string.service.ts
Docs: merge 3.2 release notes
[working/Evergreen.git] / Open-ILS / src / eg2 / src / app / share / string / string.service.ts
1 import {Injectable} from '@angular/core';
2
3 interface StringAssignment {
4     key: string;     // keyboard command
5     resolver: (ctx: any) => Promise<string>;
6 }
7
8 interface PendingInterpolation {
9     key: string;
10     ctx: any;
11     resolve: (string) => any;
12     reject: (string) => any;
13 }
14
15 @Injectable()
16 export class StringService {
17
18     strings: {[key: string]: StringAssignment} = {};
19
20     // This service can only interpolate one string at a time, since it
21     // maintains only one string component instance.  Avoid clobbering
22     // in-process interpolation requests by maintaining a request queue.
23     private pending: PendingInterpolation[];
24
25     constructor() {
26         this.pending = [];
27     }
28
29     register(assn: StringAssignment) {
30         this.strings[assn.key] = assn;
31     }
32
33     interpolate(key: string, ctx?: any): Promise<string> {
34
35         if (!this.strings[key]) {
36             return Promise.reject(`String key not found: "${key}"`);
37         }
38
39         return new Promise( (resolve, reject) => {
40             const pend: PendingInterpolation = {
41                 key: key,
42                 ctx: ctx,
43                 resolve: resolve,
44                 reject: reject
45             };
46
47             this.pending.push(pend);
48
49             // Avoid launching the pending string processer with >1
50             // pending, because the processor will have already started.
51             if (this.pending.length === 1) {
52                 this.processPending();
53             }
54         });
55     }
56
57     processPending() {
58         const pstring = this.pending[0];
59         this.strings[pstring.key].resolver(pstring.ctx).then(
60             txt => {
61                 pstring.resolve(txt);
62                 this.pending.shift();
63                 if (this.pending.length) {
64                     this.processPending();
65                 }
66             },
67             err => {
68                 pstring.reject(err);
69                 this.pending.shift();
70                 if (this.pending.length) {
71                     this.processPending();
72                 }
73             }
74         );
75     }
76 }
77
78