UNPKG

2.11 kBPlain TextView Raw
1/*
2 * Copyright (c) Jupyter Development Team.
3 * Distributed under the terms of the Modified BSD License.
4 */
5
6import { Widget } from '@lumino/widgets';
7
8/**
9 * Options when add a command to a semantic group.
10 */
11interface ISemanticCommand {
12 /**
13 * Command id
14 */
15 id: string;
16 /**
17 * Whether this command is enabled for a given widget
18 * @param widget Widget
19 */
20 isEnabled?(widget: Widget): boolean;
21 /**
22 * Command rank in the semantic group
23 *
24 * #### Note
25 * If multiple commands are enabled at the same time,
26 * the one with the smallest rank will be executed.
27 */
28 rank?: number;
29}
30
31/**
32 * Semantic group of commands
33 */
34export class SemanticCommand {
35 /**
36 * Default rank for semantic command
37 */
38 static readonly DEFAULT_RANK = 500;
39
40 /**
41 * The command IDs used by this semantic command.
42 */
43 get ids(): string[] {
44 return this._commands.map(c => c.id);
45 }
46
47 /**
48 * Add a command to the semantic group
49 *
50 * @param command Command to add
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 * Get the command id of the enabled command from this group
66 * for the given widget.
67 *
68 * @param widget Widget
69 * @returns Command id
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 * Remove a command ID.
85 *
86 * @param id Command ID to remove
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}