-
Notifications
You must be signed in to change notification settings - Fork 30
/
selection-service.ts
302 lines (252 loc) · 11.3 KB
/
selection-service.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/********************************************************************************
* Copyright (c) 2019-2024 EclipseSource and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the Eclipse
* Public License v. 2.0 are satisfied: GNU General Public License, version 2
* with the GNU Classpath Exception which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
********************************************************************************/
import {
Action,
Command,
CommandExecutionContext,
Disposable,
DisposableCollection,
Emitter,
Event,
GChildElement,
GModelElement,
GModelRoot,
ILogger,
SelectAction,
SelectAllAction,
Selectable,
SprottySelectAllCommand,
SprottySelectCommand,
TYPES,
hasArrayProp,
isSelectable,
pluck
} from '@eclipse-glsp/sprotty';
import { inject, injectable, multiInject, optional, postConstruct, preDestroy } from 'inversify';
import { getElements, getMatchingElements } from '../utils/gmodel-util';
import { GLSPCommandStack, IGModelRootListener } from './command-stack';
import { IFeedbackActionDispatcher } from './feedback/feedback-action-dispatcher';
export interface ISelectionListener {
selectionChanged(root: Readonly<GModelRoot>, selectedElements: string[], deselectedElements?: string[]): void;
}
export interface SelectionChange {
root: Readonly<GModelRoot>;
selectedElements: string[];
deselectedElements: string[];
}
@injectable()
export class SelectionService implements IGModelRootListener, Disposable {
protected root: Readonly<GModelRoot>;
protected selectedElementIDs: Set<string> = new Set();
@inject(TYPES.IFeedbackActionDispatcher)
protected feedbackDispatcher: IFeedbackActionDispatcher;
@inject(TYPES.ILogger)
protected logger: ILogger;
@inject(TYPES.ICommandStack)
protected commandStack: GLSPCommandStack;
@multiInject(TYPES.ISelectionListener)
@optional()
protected selectionListeners: ISelectionListener[] = [];
protected toDispose = new DisposableCollection();
@postConstruct()
protected initialize(): void {
this.toDispose.push(
this.onSelectionChangedEmitter,
this.commandStack.onModelRootChanged(root => this.modelRootChanged(root))
);
this.selectionListeners.forEach(listener =>
this.onSelectionChanged(change => listener.selectionChanged(change.root, change.selectedElements, change.deselectedElements))
);
}
@preDestroy()
dispose(): void {
this.toDispose.dispose();
}
protected onSelectionChangedEmitter = new Emitter<SelectionChange>();
get onSelectionChanged(): Event<SelectionChange> {
return this.onSelectionChangedEmitter.event;
}
modelRootChanged(root: Readonly<GModelRoot>): void {
this.updateSelection(root, [], []);
}
updateSelection(newRoot: Readonly<GModelRoot>, select: string[], deselect: string[]): void {
if (newRoot === undefined && select.length === 0 && deselect.length === 0) {
return;
}
const prevRoot = this.root;
const prevSelectedElementIDs = new Set(this.selectedElementIDs);
this.root = newRoot;
// We only select elements that are not part of the deselection
const toSelect = [...select].filter(selectId => deselect.indexOf(selectId) === -1);
// We only need to deselect elements that are not part of the selection
// If an element is part of both the select and deselect, it's state is not changed
const toDeselect = [...deselect].filter(deselectId => select.indexOf(deselectId) === -1 && this.selectedElementIDs.has(deselectId));
// update selected element ids
toDeselect.forEach(toDeselectId => this.selectedElementIDs.delete(toDeselectId));
toSelect.forEach(toSelectId => this.selectedElementIDs.add(toSelectId));
// check if the newly or previously selected elements still exist in the updated root
const deselectedElementIDs = new Set(toDeselect);
for (const id of this.selectedElementIDs) {
const element = newRoot.index.getById(id);
if (element === undefined) {
// element to be selected does not exist in the root...
this.selectedElementIDs.delete(id);
if (prevRoot?.index.getById(id)) {
// ...but existed in the previous root, so we want to consider it deselected
deselectedElementIDs.add(id);
}
}
}
// only send out changes if there actually are changes, i.e., any of the selected elements ids has changed
const selectionChanged =
prevSelectedElementIDs.size !== this.selectedElementIDs.size ||
![...prevSelectedElementIDs].every(value => this.selectedElementIDs.has(value));
if (selectionChanged) {
// aggregate to feedback action handling all elements as only the last feedback is restored
this.dispatchFeedback([
SelectFeedbackAction.create({
selectedElementsIDs: [...this.selectedElementIDs],
deselectedElementsIDs: [...deselectedElementIDs]
})
]);
// notify listeners after the feedback action
this.notifyListeners(this.root, this.selectedElementIDs, deselectedElementIDs);
}
}
dispatchFeedback(actions: Action[]): void {
this.feedbackDispatcher.registerFeedback(this, actions);
}
notifyListeners(root: GModelRoot, selectedElementIDs: Set<string>, deselectedElementIDs: Set<string>): void {
this.onSelectionChangedEmitter.fire({
root,
selectedElements: Array.from(selectedElementIDs),
deselectedElements: Array.from(deselectedElementIDs)
});
}
getModelRoot(): Readonly<GModelRoot> {
return this.root;
}
getSelectedElements(): Readonly<GModelElement & Selectable>[] {
return !this.root ? [] : getElements(this.root.index, Array.from(this.selectedElementIDs), isSelectable);
}
/**
* QUERY METHODS
*/
getSelectedElementIDs(): string[] {
return [...this.selectedElementIDs];
}
hasSelectedElements(): boolean {
return this.selectedElementIDs.size > 0;
}
isSingleSelection(): boolean {
return this.selectedElementIDs.size === 1;
}
isMultiSelection(): boolean {
return this.selectedElementIDs.size > 1;
}
}
/**
* Handles a {@link SelectAction} and propagates the new selection to the {@link SelectionService}.
* Other tools might be selection-sensitive which means {@link SelectAction}s must be processed as fast as possible.
* Handling the action with a command ensures that the action is processed before the next render tick.
*/
@injectable()
export class SelectCommand extends Command {
static readonly KIND = SprottySelectCommand.KIND;
protected selected: GModelElement[] = [];
protected deselected: GModelElement[] = [];
constructor(
@inject(TYPES.Action) public action: SelectAction,
@inject(SelectionService) public selectionService: SelectionService
) {
super();
}
execute(context: CommandExecutionContext): GModelRoot {
const model = context.root;
const selectionGuard = (element: any): element is GModelElement => element instanceof GChildElement && isSelectable(element);
const selectedElements = getElements(model.index, this.action.selectedElementsIDs, selectionGuard);
const deselectedElements = this.action.deselectAll
? this.selectionService.getSelectedElements()
: getElements(model.index, this.action.deselectedElementsIDs, selectionGuard);
this.selectionService.updateSelection(model, pluck(selectedElements, 'id'), pluck(deselectedElements, 'id'));
return model;
}
// Basically no-op since client-side undo is not supported in GLSP.
undo(context: CommandExecutionContext): GModelRoot {
return context.root;
}
// Basically no-op since client-side redo is not supported in GLSP.
redo(context: CommandExecutionContext): GModelRoot {
return context.root;
}
}
/**
* Handles a {@link SelectAllAction} and propagates the new selection to the {@link SelectionService}.
* Other tools might be selection-sensitive which means {@link SelectionAllAction}s must be processed as fast as possible.
* Handling the action with a command ensures that the action is processed before the next render tick.
*/
@injectable()
export class SelectAllCommand extends Command {
static readonly KIND = SprottySelectAllCommand.KIND;
protected previousSelection: Map<string, boolean> = new Map<string, boolean>();
constructor(
@inject(TYPES.Action) public action: SelectAllAction,
@inject(SelectionService) public selectionService: SelectionService
) {
super();
}
execute(context: CommandExecutionContext): GModelRoot {
const model = context.root;
const selectionGuard = (element: any): element is GModelElement => element instanceof GChildElement && isSelectable(element);
const selectables = getMatchingElements(model.index, selectionGuard);
const selectableIds = pluck(selectables, 'id');
if (this.action.select) {
this.selectionService.updateSelection(model, selectableIds, []);
} else {
this.selectionService.updateSelection(model, [], selectableIds);
}
return model;
}
// Basically no-op since client-side undo is not supported in GLSP.
undo(context: CommandExecutionContext): GModelRoot {
return context.root;
}
// Basically no-op since client-side redo is not supported in GLSP.
redo(context: CommandExecutionContext): GModelRoot {
return context.root;
}
}
export interface SelectFeedbackAction extends Omit<SelectAction, 'kind'>, Action {
kind: typeof SelectFeedbackAction.KIND;
}
export namespace SelectFeedbackAction {
export const KIND = 'selectFeedback';
export function is(object: any): object is SelectFeedbackAction {
return Action.hasKind(object, KIND) && hasArrayProp(object, 'selectedElementsIDs') && hasArrayProp(object, 'deselectedElementsIDs');
}
export function create(options?: { selectedElementsIDs?: string[]; deselectedElementsIDs?: string[] | boolean }): SelectFeedbackAction {
return { ...SelectAction.create(options), kind: KIND };
}
export function addSelection(selectedElementsIDs: string[]): SelectFeedbackAction {
return { ...SelectAction.addSelection(selectedElementsIDs), kind: KIND };
}
export function removeSelection(deselectedElementsIDs: string[]): SelectFeedbackAction {
return { ...SelectAction.removeSelection(deselectedElementsIDs), kind: KIND };
}
export function setSelection(selectedElementsIDs: string[]): SelectFeedbackAction {
return { ...SelectAction.setSelection(selectedElementsIDs), kind: KIND };
}
}