-
Notifications
You must be signed in to change notification settings - Fork 29
/
navigation-action-handler.ts
247 lines (221 loc) · 11.9 KB
/
navigation-action-handler.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
/********************************************************************************
* Copyright (c) 2020 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 { inject, injectable, optional } from "inversify";
import {
CenterAction,
generateRequestId,
ILogger,
RequestAction,
ResponseAction,
SelectAction,
SelectAllAction
} from "sprotty";
import { Action, IActionDispatcher, IActionHandler, ICommand, TYPES } from "sprotty/lib";
import { Args } from "../../base/args";
import { EditorContext, EditorContextServiceProvider } from "../../base/editor-context";
import { GLSP_TYPES } from "../../base/types";
import { GLSPServerStatusAction, ServerMessageAction } from "../../model-source/glsp-server-status";
import { ExternalNavigateToTargetHandler } from "./external-navigate-to-target-handler";
import { NavigationTarget, NavigationTargetResolver, SetResolvedNavigationTargetAction } from "./navigation-target-resolver";
/**
* Action for triggering a navigation of a certain target type.
*
* Examples for target types could be `documentation`, `implementation`, etc.
* but this is up to the domain-specific diagram implementation to decide.
* Such an action will eventually trigger a `RequestNavigationTargetsAction`
* (see `NavigationActionHandler`) in order to request the navigation targets
* from the server.
*
* This action is typically triggered by a user action.
*/
export class NavigateAction implements Action {
static readonly KIND = 'navigate';
readonly kind = NavigateAction.KIND;
constructor(readonly targetTypeId: string, readonly args?: Args) { }
}
export function isNavigateAction(action: Action): action is NavigateAction {
return action !== undefined && (action.kind === NavigateAction.KIND)
&& (<NavigateAction>action).targetTypeId !== undefined;
}
/** Action that is usually sent to the server to request navigation targets for a navigation type. */
export class RequestNavigationTargetsAction implements RequestAction<SetNavigationTargetsAction> {
static readonly KIND = "requestNavigationTargets";
kind = RequestNavigationTargetsAction.KIND;
constructor(readonly targetTypeId: string, readonly editorContext: EditorContext,
readonly requestId: string = generateRequestId()) { }
}
/** Action that is usually sent from the server to the client as a repsonse to a `RequestNavigationTargetsAction`. */
export class SetNavigationTargetsAction implements ResponseAction {
static readonly KIND = "setNavigationTargets";
kind = SetNavigationTargetsAction.KIND;
constructor(readonly targets: NavigationTarget[], readonly responseId: string = '', readonly args?: Args) { }
}
export function isSetNavigationTargetsAction(action: Action): action is SetNavigationTargetsAction {
return action !== undefined && (action.kind === SetNavigationTargetsAction.KIND)
&& (<SetNavigationTargetsAction>action).targets !== undefined;
}
/** Action that triggers the navigation to a particular navigation target, such as element IDs, queries, etc.. */
export class NavigateToTargetAction implements Action {
static readonly KIND = 'navigateToTarget';
readonly kind = NavigateToTargetAction.KIND;
constructor(readonly target: NavigationTarget) { }
}
export function isNavigateToTargetAction(action: Action): action is NavigateToTargetAction {
return action !== undefined && (action.kind === NavigateToTargetAction.KIND)
&& (<NavigateToTargetAction>action).target !== undefined;
}
/** Action to trigger the processing of additional navigation arguments.
*
* The resolution of a `NavigationTarget` may entail additional arguments. In this case, this action is
* triggered allowing the client to react to those arguments. The default `NavigationActionHandler` will
* only process the arguments' keys `info`, `warning`, and `error` to present them to the user.
* Customizations, however, may add domain-specific arguments and register custom handler to also process
* other arguments and trigger some additional behavior (e.g. update other views, etc.).
*/
export class ProcessNavigationArgumentsAction implements Action {
static readonly KIND = 'processNavigationArguments';
readonly kind = ProcessNavigationArgumentsAction.KIND;
constructor(readonly args: Args) { }
}
export function isProcessNavigationArgumentsAction(action: Action): action is ProcessNavigationArgumentsAction {
return action !== undefined && (action.kind === ProcessNavigationArgumentsAction.KIND)
&& (<ProcessNavigationArgumentsAction>action).args !== undefined;
}
/**
* Default handler for all actions that are related to the navigation.
*
* For a `NavigateAction` this handler triggers a `RequestNavigationTargetAction` to obtain the actual
* navigation targets for the navigation type that is specified in the `NavigateAction`.
* Once the navigation targets are available, it will trigger a `NavigateToTargetAction` to actually
* perform the navigation.
*
* In other scenarios, clients may also trigger the `NavigateToTargetAction` directly, e.g. when opening
* the diagram.
*
* Depending on the URI and arguments of the navigation target we may encounter three cases:
* *(a)* the navigation target already specifies element IDs, in which case this action handler navigates
* to the specified elements directly, by the selecting them and centering them in the viewport.
* *(b)* the arguments of the navigation targets don't contain element IDs, but other arguments, the
* navigation target needs to be resolved into actual elment IDs by the `NavigationTargetResolver`.
* This can for instance be useful, if the navigation deals with queries or some other more complex
* logic that can't be dealt with on the client.
* *(c)* the target isn't resolved by the `NavigationTargetResolver`, e.g. because the `uri` doesn't match
* the URI of the current diagram. In this case, the navigation request is forwarded to the
* `ExternalNavigateToTargetHandler`, if it exists.
*/
@injectable()
export class NavigationActionHandler implements IActionHandler {
readonly notificationTimeout = 5000;
@inject(TYPES.ILogger) protected logger: ILogger;
@inject(TYPES.IActionDispatcher) protected dispatcher: IActionDispatcher;
@inject(GLSP_TYPES.IEditorContextServiceProvider) protected editorContextService: EditorContextServiceProvider;
@inject(NavigationTargetResolver) protected resolver: NavigationTargetResolver;
@inject(ExternalNavigateToTargetHandler) @optional() protected externalHandler: ExternalNavigateToTargetHandler;
handle(action: Action): ICommand | Action | void {
if (isNavigateAction(action)) {
this.handleNavigateAction(action);
} else if (isNavigateToTargetAction(action)) {
this.handleNavigateToTarget(action);
} else if (isProcessNavigationArgumentsAction(action)) {
this.processNavigationArguments(action.args);
}
}
protected async handleNavigateAction(action: NavigateAction) {
try {
const editorContextService = await this.editorContextService();
const context = editorContextService.get(action.args);
const response = await this.dispatcher.request(new RequestNavigationTargetsAction(action.targetTypeId, context));
if (isSetNavigationTargetsAction(response) && response.targets && response.targets.length === 1) {
if (response.targets.length > 1) {
this.logger.warn(this, 'Processing of multiple targets is not supported yet. ' +
'Only the first is being processed.', response.targets);
}
return this.dispatcher.dispatch(new NavigateToTargetAction(response.targets[0]));
}
this.warnAboutFailedNavigation('No valid navigation target found');
} catch (reason) {
this.logger.error(this, 'Failed to obtain navigation target', reason, action);
}
}
protected async handleNavigateToTarget(action: NavigateToTargetAction) {
try {
const resolvedElements = await this.resolveElements(action);
if (this.containsElementIdsOrArguments(resolvedElements)) {
this.navigateTo(resolvedElements);
this.handleResolutionArguments(resolvedElements);
return;
} else if (this.externalHandler) {
this.navigateToExternal(action.target);
return;
}
this.warnAboutFailedNavigation('Could not resolve or navigate to target', action.target);
} catch (reason) {
this.logger.error(this, 'Failed to navigate', reason, action);
}
}
protected resolveElements(action: NavigateToTargetAction): Promise<SetResolvedNavigationTargetAction | undefined> {
return this.resolver.resolve(action.target);
}
protected containsElementIdsOrArguments(target: SetResolvedNavigationTargetAction | undefined): target is SetResolvedNavigationTargetAction {
return target !== undefined && (this.containsElementIds(target.elementIds) || this.containsArguments(target.args));
}
protected containsElementIds(elementIds: string[] | undefined): elementIds is string[] {
return elementIds !== undefined && elementIds.length > 0;
}
protected containsArguments(args: Args | undefined): args is Args {
return args !== undefined && args !== undefined && Object.keys(args).length > 0;
}
protected navigateTo(target: SetResolvedNavigationTargetAction) {
const elementIds = target.elementIds;
if (!this.containsElementIds(elementIds)) {
return;
}
this.dispatcher.dispatchAll([new SelectAllAction(false), new SelectAction(elementIds), new CenterAction(elementIds)]);
}
protected handleResolutionArguments(target: SetResolvedNavigationTargetAction) {
const args = target.args;
if (!this.containsArguments(args)) {
return;
}
this.dispatcher.dispatch(new ProcessNavigationArgumentsAction(args));
}
protected navigateToExternal(target: NavigationTarget): Promise<void> {
return this.externalHandler.navigateTo(target.uri, target.args);
}
protected processNavigationArguments(args: Args) {
if (args.info && args.info.toString().length > 0) {
this.notify('INFO', args.info.toString());
}
if (args.warning && args.warning.toString().length > 0) {
this.notify('WARNING', args.warning.toString());
}
if (args.error && args.error.toString().length > 0) {
this.notify('ERROR', args.error.toString());
}
}
protected warnAboutFailedNavigation(msg: string, target?: NavigationTarget) {
const message = `${msg}` + (target ? `: '${target.uri}' (arguments: ${JSON.stringify(target.args)})` : '');
this.logger.warn(this, msg, target);
this.notify('WARNING', message);
}
private notify(severity: string, message: string) {
const timeout = this.notificationTimeout;
this.dispatcher.dispatchAll([
<GLSPServerStatusAction>{ kind: GLSPServerStatusAction.KIND, severity, timeout, message },
<ServerMessageAction>{ kind: ServerMessageAction.KIND, severity, timeout, message }
]);
}
}