1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | import { Widget } from '@lumino/widgets';
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | interface ISemanticCommand {
|
12 | |
13 |
|
14 |
|
15 | id: string;
|
16 | |
17 |
|
18 |
|
19 |
|
20 | isEnabled?(widget: Widget): boolean;
|
21 | |
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | rank?: number;
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | export class SemanticCommand {
|
35 | |
36 |
|
37 |
|
38 | static readonly DEFAULT_RANK = 500;
|
39 |
|
40 | |
41 |
|
42 |
|
43 | get ids(): string[] {
|
44 | return this._commands.map(c => c.id);
|
45 | }
|
46 |
|
47 | |
48 |
|
49 |
|
50 |
|
51 |
|
52 | add(command: ISemanticCommand): void {
|
53 | if (this._commands.map(c => c.id).includes(command.id)) {
|
54 | throw Error(`Command ${command.id} is already defined.`);
|
55 | }
|
56 |
|
57 | this._commands.push({
|
58 | isEnabled: () => true,
|
59 | rank: SemanticCommand.DEFAULT_RANK,
|
60 | ...command
|
61 | });
|
62 | }
|
63 |
|
64 | |
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | getActiveCommandId(widget: Widget): string | null {
|
72 | const commands = this._commands
|
73 | .filter(c => c.isEnabled(widget))
|
74 | .sort((a, b) => {
|
75 | const rankDelta = a.rank - b.rank;
|
76 | return rankDelta || (a.id < b.id ? -1 : 1);
|
77 | });
|
78 |
|
79 | const command = commands[0] ?? { id: null };
|
80 | return command.id;
|
81 | }
|
82 |
|
83 | |
84 |
|
85 |
|
86 |
|
87 |
|
88 | remove(id: string): void {
|
89 | const index = this._commands.findIndex(c => c.id === id);
|
90 | if (index >= 0) {
|
91 | this._commands.splice(index, 1);
|
92 | }
|
93 | }
|
94 |
|
95 | protected _commands = new Array<Required<ISemanticCommand>>();
|
96 | }
|