/
app.js
1380 lines (1183 loc) · 43.5 KB
/
app.js
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import autobind from 'autobind-decorator';
import fs from 'fs';
import { clipboard, ipcRenderer, remote } from 'electron';
import { parse as urlParse } from 'url';
import HTTPSnippet from 'httpsnippet';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Wrapper from '../components/wrapper';
import WorkspaceEnvironmentsEditModal from '../components/modals/workspace-environments-edit-modal';
import Toast from '../components/toast';
import CookiesModal from '../components/modals/cookies-modal';
import RequestSwitcherModal from '../components/modals/request-switcher-modal';
import SettingsModal, { TAB_INDEX_SHORTCUTS } from '../components/modals/settings-modal';
import {
COLLAPSE_SIDEBAR_REMS,
DEFAULT_PANE_HEIGHT,
DEFAULT_PANE_WIDTH,
DEFAULT_SIDEBAR_WIDTH,
MAX_PANE_HEIGHT,
MAX_PANE_WIDTH,
MAX_SIDEBAR_REMS,
MIN_PANE_HEIGHT,
MIN_PANE_WIDTH,
MIN_SIDEBAR_REMS,
PREVIEW_MODE_SOURCE,
} from '../../common/constants';
import * as globalActions from '../redux/modules/global';
import * as db from '../../common/database';
import * as models from '../../models';
import {
selectActiveCookieJar,
selectActiveOAuth2Token,
selectActiveRequest,
selectActiveRequestMeta,
selectActiveRequestResponses,
selectActiveResponse,
selectActiveWorkspace,
selectActiveWorkspaceClientCertificates,
selectActiveWorkspaceMeta,
selectEntitiesLists,
selectSidebarChildren,
selectSyncItems,
selectUnseenWorkspaces,
selectWorkspaceRequestsAndRequestGroups,
} from '../redux/selectors';
import RequestCreateModal from '../components/modals/request-create-modal';
import GenerateCodeModal from '../components/modals/generate-code-modal';
import WorkspaceSettingsModal from '../components/modals/workspace-settings-modal';
import RequestSettingsModal from '../components/modals/request-settings-modal';
import RequestRenderErrorModal from '../components/modals/request-render-error-modal';
import * as network from '../../network/network';
import { debounce, getContentDispositionHeader, getDataDirectory } from '../../common/misc';
import * as mime from 'mime-types';
import * as path from 'path';
import * as render from '../../common/render';
import { getKeys } from '../../templating/utils';
import { showAlert, showModal, showPrompt } from '../components/modals/index';
import { exportHarRequest } from '../../common/har';
import { hotKeyRefs } from '../../common/hotkeys';
import { executeHotKey } from '../../common/hotkeys-listener';
import KeydownBinder from '../components/keydown-binder';
import ErrorBoundary from '../components/error-boundary';
import * as plugins from '../../plugins';
import * as templating from '../../templating/index';
import AskModal from '../components/modals/ask-modal';
import { updateMimeType } from '../../models/request';
import MoveRequestGroupModal from '../components/modals/move-request-group-modal';
import * as themes from '../../plugins/misc';
import ExportRequestsModal from '../components/modals/export-requests-modal';
import FileSystemDriver from '../../sync/store/drivers/file-system-driver';
import VCS from '../../sync/vcs';
import SyncMergeModal from '../components/modals/sync-merge-modal';
@autobind
class App extends PureComponent {
constructor(props) {
super(props);
this.state = {
showDragOverlay: false,
draggingSidebar: false,
draggingPaneHorizontal: false,
draggingPaneVertical: false,
sidebarWidth: props.sidebarWidth || DEFAULT_SIDEBAR_WIDTH,
paneWidth: props.paneWidth || DEFAULT_PANE_WIDTH,
paneHeight: props.paneHeight || DEFAULT_PANE_HEIGHT,
isVariableUncovered: props.isVariableUncovered || false,
vcs: null,
forceRefreshCounter: 0,
forceRefreshHeaderCounter: 0,
isMigratingChildren: false,
};
this._getRenderContextPromiseCache = {};
this._savePaneWidth = debounce(paneWidth => this._updateActiveWorkspaceMeta({ paneWidth }));
this._savePaneHeight = debounce(paneHeight => this._updateActiveWorkspaceMeta({ paneHeight }));
this._saveSidebarWidth = debounce(sidebarWidth =>
this._updateActiveWorkspaceMeta({ sidebarWidth }),
);
this._globalKeyMap = null;
}
_setGlobalKeyMap() {
this._globalKeyMap = [
[
hotKeyRefs.PREFERENCES_SHOW_GENERAL,
() => {
showModal(SettingsModal);
},
],
[
hotKeyRefs.PREFERENCES_SHOW_KEYBOARD_SHORTCUTS,
() => {
showModal(SettingsModal, TAB_INDEX_SHORTCUTS);
},
],
[
hotKeyRefs.SHOW_RECENT_REQUESTS,
() => {
showModal(RequestSwitcherModal, {
disableInput: true,
maxRequests: 10,
maxWorkspaces: 0,
selectOnKeyup: true,
title: 'Recent Requests',
hideNeverActiveRequests: true,
// Add an open delay so the dialog won't show for quick presses
openDelay: 150,
});
},
],
[
hotKeyRefs.WORKSPACE_SHOW_SETTINGS,
() => {
const { activeWorkspace } = this.props;
showModal(WorkspaceSettingsModal, activeWorkspace);
},
],
[
hotKeyRefs.REQUEST_SHOW_SETTINGS,
() => {
if (this.props.activeRequest) {
showModal(RequestSettingsModal, {
request: this.props.activeRequest,
});
}
},
],
[
hotKeyRefs.REQUEST_QUICK_SWITCH,
() => {
showModal(RequestSwitcherModal);
},
],
[hotKeyRefs.REQUEST_SEND, this._handleSendShortcut],
[
hotKeyRefs.ENVIRONMENT_SHOW_EDITOR,
() => {
const { activeWorkspace } = this.props;
showModal(WorkspaceEnvironmentsEditModal, activeWorkspace);
},
],
[
hotKeyRefs.SHOW_COOKIES_EDITOR,
() => {
const { activeWorkspace } = this.props;
showModal(CookiesModal, activeWorkspace);
},
],
[
hotKeyRefs.REQUEST_QUICK_CREATE,
async () => {
const { activeRequest, activeWorkspace } = this.props;
const parentId = activeRequest ? activeRequest.parentId : activeWorkspace._id;
const request = await models.request.create({ parentId, name: 'New Request' });
await this._handleSetActiveRequest(request._id);
},
],
[
hotKeyRefs.REQUEST_SHOW_CREATE,
() => {
const { activeRequest, activeWorkspace } = this.props;
const parentId = activeRequest ? activeRequest.parentId : activeWorkspace._id;
this._requestCreate(parentId);
},
],
[
hotKeyRefs.REQUEST_SHOW_DELETE,
() => {
const { activeRequest } = this.props;
if (!activeRequest) {
return;
}
showModal(AskModal, {
title: 'Delete Request?',
message: `Really delete ${activeRequest.name}?`,
onDone: confirmed => {
if (!confirmed) {
return;
}
models.request.remove(activeRequest);
},
});
},
],
[
hotKeyRefs.REQUEST_SHOW_CREATE_FOLDER,
() => {
const { activeRequest, activeWorkspace } = this.props;
const parentId = activeRequest ? activeRequest.parentId : activeWorkspace._id;
this._requestGroupCreate(parentId);
},
],
[
hotKeyRefs.REQUEST_SHOW_GENERATE_CODE_EDITOR,
async () => {
showModal(GenerateCodeModal, this.props.activeRequest);
},
],
[
hotKeyRefs.REQUEST_SHOW_DUPLICATE,
async () => {
await this._requestDuplicate(this.props.activeRequest);
},
],
[
hotKeyRefs.REQUEST_TOGGLE_PIN,
async () => {
if (!this.props.activeRequest) {
return;
}
const metas = Object.values(this.props.entities.requestMetas).find(
m => m.parentId === this.props.activeRequest._id,
);
await this._handleSetRequestPinned(this.props.activeRequest, !(metas && metas.pinned));
},
],
[hotKeyRefs.PLUGIN_RELOAD, this._handleReloadPlugins],
[
hotKeyRefs.ENVIRONMENT_UNCOVER_VARIABLES,
async () => {
await this._updateIsVariableUncovered();
},
],
[
hotKeyRefs.SIDEBAR_TOGGLE,
() => {
this._handleToggleSidebar();
},
],
];
}
async _handleSendShortcut() {
const { activeRequest, activeEnvironment } = this.props;
await this._handleSendRequestWithEnvironment(
activeRequest ? activeRequest._id : 'n/a',
activeEnvironment ? activeEnvironment._id : 'n/a',
);
}
_setRequestPaneRef(n) {
this._requestPane = n;
}
_setResponsePaneRef(n) {
this._responsePane = n;
}
_setSidebarRef(n) {
this._sidebar = n;
}
_requestGroupCreate(parentId) {
showPrompt({
title: 'New Folder',
defaultValue: 'My Folder',
submitName: 'Create',
label: 'Name',
selectText: true,
onComplete: async name => {
const requestGroup = await models.requestGroup.create({
parentId,
name,
});
await models.requestGroupMeta.create({
parentId: requestGroup._id,
collapsed: false,
});
},
});
}
_requestCreate(parentId) {
showModal(RequestCreateModal, {
parentId,
onComplete: request => {
this._handleSetActiveRequest(request._id);
},
});
}
static async _requestGroupDuplicate(requestGroup) {
showPrompt({
title: 'Duplicate Folder',
defaultValue: requestGroup.name,
submitName: 'Create',
label: 'New Name',
selectText: true,
onComplete: async name => {
await models.requestGroup.duplicate(requestGroup, { name });
},
});
}
static async _requestGroupMove(requestGroup) {
showModal(MoveRequestGroupModal, { requestGroup });
}
_requestDuplicate(request) {
if (!request) {
return;
}
showPrompt({
title: 'Duplicate Request',
defaultValue: request.name,
submitName: 'Create',
label: 'New Name',
selectText: true,
onComplete: async name => {
const newRequest = await models.request.duplicate(request, { name });
await this._handleSetActiveRequest(newRequest._id);
},
});
}
_workspaceDuplicate(callback) {
const workspace = this.props.activeWorkspace;
showPrompt({
title: 'Duplicate Workspace',
defaultValue: workspace.name,
submitName: 'Create',
selectText: true,
label: 'New Name',
onComplete: async name => {
const newWorkspace = await db.duplicate(workspace, { name });
await this.props.handleSetActiveWorkspace(newWorkspace._id);
callback();
},
});
}
async _fetchRenderContext() {
const { activeEnvironment, activeRequest, activeWorkspace } = this.props;
const environmentId = activeEnvironment ? activeEnvironment._id : null;
const ancestors = await db.withAncestors(activeRequest || activeWorkspace, [
models.request.type,
models.requestGroup.type,
models.workspace.type,
]);
return render.getRenderContext(activeRequest, environmentId, ancestors);
}
async _handleGetRenderContext() {
const context = await this._fetchRenderContext();
const keys = getKeys(context);
return { context, keys };
}
/**
* Heavily optimized render function
*
* @param text - template to render
* @param contextCacheKey - if rendering multiple times in parallel, set this
* @returns {Promise}
* @private
*/
async _handleRenderText(text, contextCacheKey = null) {
if (!contextCacheKey || !this._getRenderContextPromiseCache[contextCacheKey]) {
// NOTE: We're caching promises here to avoid race conditions
this._getRenderContextPromiseCache[contextCacheKey] = this._fetchRenderContext();
}
// Set timeout to delete the key eventually
setTimeout(() => delete this._getRenderContextPromiseCache[contextCacheKey], 5000);
const context = await this._getRenderContextPromiseCache[contextCacheKey];
return render.render(text, context);
}
_handleGenerateCodeForActiveRequest() {
App._handleGenerateCode(this.props.activeRequest);
}
static _handleGenerateCode(request) {
showModal(GenerateCodeModal, request);
}
async _handleCopyAsCurl(request) {
const { activeEnvironment } = this.props;
const environmentId = activeEnvironment ? activeEnvironment._id : 'n/a';
const har = await exportHarRequest(request._id, environmentId);
const snippet = new HTTPSnippet(har);
const cmd = snippet.convert('shell', 'curl');
clipboard.writeText(cmd);
}
static async _updateRequestGroupMetaByParentId(requestGroupId, patch) {
const requestGroupMeta = await models.requestGroupMeta.getByParentId(requestGroupId);
if (requestGroupMeta) {
await models.requestGroupMeta.update(requestGroupMeta, patch);
} else {
const newPatch = Object.assign({ parentId: requestGroupId }, patch);
await models.requestGroupMeta.create(newPatch);
}
}
async _updateActiveWorkspaceMeta(patch) {
const workspaceId = this.props.activeWorkspace._id;
const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId(workspaceId);
if (workspaceMeta) {
return models.workspaceMeta.update(workspaceMeta, patch);
} else {
const newPatch = Object.assign({ parentId: workspaceId }, patch);
return models.workspaceMeta.create(newPatch);
}
}
static async _updateRequestMetaByParentId(requestId, patch) {
const requestMeta = await models.requestMeta.getByParentId(requestId);
if (requestMeta) {
return models.requestMeta.update(requestMeta, patch);
} else {
const newPatch = Object.assign({ parentId: requestId }, patch);
return models.requestMeta.create(newPatch);
}
}
_updateIsVariableUncovered() {
this.setState({ isVariableUncovered: !this.state.isVariableUncovered });
}
_handleSetPaneWidth(paneWidth) {
this.setState({ paneWidth });
this._savePaneWidth(paneWidth);
}
_handleSetPaneHeight(paneHeight) {
this.setState({ paneHeight });
this._savePaneHeight(paneHeight);
}
async _handleSetActiveRequest(activeRequestId) {
await this._updateActiveWorkspaceMeta({ activeRequestId });
await App._updateRequestMetaByParentId(activeRequestId, { lastActive: Date.now() });
}
async _handleSetActiveEnvironment(activeEnvironmentId) {
await this._updateActiveWorkspaceMeta({ activeEnvironmentId });
// Give it time to update and re-render
setTimeout(() => {
this._wrapper && this._wrapper._forceRequestPaneRefresh();
}, 300);
}
_handleSetSidebarWidth(sidebarWidth) {
this.setState({ sidebarWidth });
this._saveSidebarWidth(sidebarWidth);
}
async _handleSetSidebarHidden(sidebarHidden) {
await this._updateActiveWorkspaceMeta({ sidebarHidden });
}
async _handleSetSidebarFilter(sidebarFilter) {
await this._updateActiveWorkspaceMeta({ sidebarFilter });
}
_handleSetRequestGroupCollapsed(requestGroupId, collapsed) {
App._updateRequestGroupMetaByParentId(requestGroupId, { collapsed });
}
async _handleSetRequestPinned(request, pinned) {
App._updateRequestMetaByParentId(request._id, { pinned });
}
_handleSetResponsePreviewMode(requestId, previewMode) {
App._updateRequestMetaByParentId(requestId, { previewMode });
}
_handleUpdateDownloadPath(requestId, downloadPath) {
App._updateRequestMetaByParentId(requestId, { downloadPath });
}
async _handleSetResponseFilter(requestId, responseFilter) {
await App._updateRequestMetaByParentId(requestId, { responseFilter });
clearTimeout(this._responseFilterHistorySaveTimeout);
this._responseFilterHistorySaveTimeout = setTimeout(async () => {
const meta = await models.requestMeta.getByParentId(requestId);
const responseFilterHistory = meta.responseFilterHistory.slice(0, 10);
// Already in history?
if (responseFilterHistory.includes(responseFilter)) {
return;
}
// Blank?
if (!responseFilter) {
return;
}
responseFilterHistory.unshift(responseFilter);
await App._updateRequestMetaByParentId(requestId, {
responseFilterHistory,
});
}, 2000);
}
async _handleUpdateRequestMimeType(mimeType) {
if (!this.props.activeRequest) {
console.warn('Tried to update request mime-type when no active request');
return null;
}
const requestMeta = await models.requestMeta.getOrCreateByParentId(
this.props.activeRequest._id,
);
const savedBody = requestMeta.savedRequestBody;
const saveValue =
typeof mimeType !== 'string' // Switched to No body
? this.props.activeRequest.body
: {}; // Clear saved value in requestMeta
await models.requestMeta.update(requestMeta, {
savedRequestBody: saveValue,
});
const newRequest = await updateMimeType(this.props.activeRequest, mimeType, false, savedBody);
// Force it to update, because other editor components (header editor)
// needs to change. Need to wait a delay so the next render can finish
setTimeout(() => {
this.setState({ forceRefreshHeaderCounter: this.state.forceRefreshHeaderCounter + 1 });
}, 500);
return newRequest;
}
async _getDownloadLocation() {
return new Promise(resolve => {
const options = {
title: 'Select Download Location',
buttonLabel: 'Send and Save',
defaultPath: window.localStorage.getItem('insomnia.sendAndDownloadLocation'),
};
remote.dialog.showSaveDialog(options, filename => {
window.localStorage.setItem('insomnia.sendAndDownloadLocation', filename);
resolve(filename);
});
});
}
async _handleSendAndDownloadRequestWithEnvironment(requestId, environmentId, dir) {
const { settings, handleStartLoading, handleStopLoading } = this.props;
const request = await models.request.getById(requestId);
if (!request) {
return;
}
// NOTE: Since request is by far the most popular event, we will throttle
// it so that we only track it if the request has changed since the last one
const key = request._id;
if (this._sendRequestTrackingKey !== key) {
this._sendRequestTrackingKey = key;
}
// Start loading
handleStartLoading(requestId);
try {
const responsePatch = await network.send(requestId, environmentId);
const headers = responsePatch.headers || [];
const header = getContentDispositionHeader(headers);
const nameFromHeader = header ? header.value : null;
if (
responsePatch.bodyPath &&
responsePatch.statusCode >= 200 &&
responsePatch.statusCode < 300
) {
const extension = mime.extension(responsePatch.contentType) || 'unknown';
const name =
nameFromHeader || `${request.name.replace(/\s/g, '-').toLowerCase()}.${extension}`;
let filename;
if (dir) {
filename = path.join(dir, name);
} else {
filename = await this._getDownloadLocation();
}
const to = fs.createWriteStream(filename);
const readStream = models.response.getBodyStream(responsePatch);
if (!readStream) {
return;
}
readStream.pipe(to);
readStream.on('end', async () => {
responsePatch.error = `Saved to ${filename}`;
await models.response.create(responsePatch, settings.maxHistoryResponses);
});
readStream.on('error', async err => {
console.warn('Failed to download request after sending', responsePatch.bodyPath, err);
await models.response.create(responsePatch, settings.maxHistoryResponses);
});
} else {
// Save the bad responses so failures are shown still
await models.response.create(responsePatch, settings.maxHistoryResponses);
}
} catch (err) {
showAlert({
title: 'Unexpected Request Failure',
message: (
<div>
<p>The request failed due to an unhandled error:</p>
<code className="wide selectable">
<pre>{err.message}</pre>
</code>
</div>
),
});
}
// Unset active response because we just made a new one
await App._updateRequestMetaByParentId(requestId, {
activeResponseId: null,
});
// Stop loading
handleStopLoading(requestId);
}
async _handleSendRequestWithEnvironment(requestId, environmentId) {
const { handleStartLoading, handleStopLoading, settings } = this.props;
const request = await models.request.getById(requestId);
if (!request) {
return;
}
// NOTE: Since request is by far the most popular event, we will throttle
// it so that we only track it if the request has changed since the last noe
const key = `${request._id}::${request.modified}`;
if (this._sendRequestTrackingKey !== key) {
this._sendRequestTrackingKey = key;
}
handleStartLoading(requestId);
try {
const responsePatch = await network.send(requestId, environmentId);
await models.response.create(responsePatch, settings.maxHistoryResponses);
} catch (err) {
if (err.type === 'render') {
showModal(RequestRenderErrorModal, { request, error: err });
} else {
showAlert({
title: 'Unexpected Request Failure',
message: (
<div>
<p>The request failed due to an unhandled error:</p>
<code className="wide selectable">
<pre>{err.message}</pre>
</code>
</div>
),
});
}
}
// Unset active response because we just made a new one
await App._updateRequestMetaByParentId(requestId, {
activeResponseId: null,
});
// Stop loading
handleStopLoading(requestId);
}
async _handleSetActiveResponse(requestId, activeResponse = null) {
const activeResponseId = activeResponse ? activeResponse._id : null;
await App._updateRequestMetaByParentId(requestId, { activeResponseId });
let response;
if (activeResponseId) {
response = await models.response.getById(activeResponseId);
} else {
response = await models.response.getLatestForRequest(requestId);
}
const requestVersionId = response ? response.requestVersionId : 'n/a';
const request = await models.requestVersion.restore(requestVersionId);
if (request) {
// Refresh app to reflect changes. Using timeout because we need to
// wait for the request update to propagate.
setTimeout(() => this._wrapper._forceRequestPaneRefresh(), 500);
} else {
// Couldn't restore request. That's okay
}
}
_requestCreateForWorkspace() {
this._requestCreate(this.props.activeWorkspace._id);
}
_startDragSidebar() {
this.setState({ draggingSidebar: true });
}
_resetDragSidebar() {
// TODO: Remove setTimeout need be not triggering drag on double click
setTimeout(() => this._handleSetSidebarWidth(DEFAULT_SIDEBAR_WIDTH), 50);
}
_startDragPaneHorizontal() {
this.setState({ draggingPaneHorizontal: true });
}
_startDragPaneVertical() {
this.setState({ draggingPaneVertical: true });
}
_resetDragPaneHorizontal() {
// TODO: Remove setTimeout need be not triggering drag on double click
setTimeout(() => this._handleSetPaneWidth(DEFAULT_PANE_WIDTH), 50);
}
_resetDragPaneVertical() {
// TODO: Remove setTimeout need be not triggering drag on double click
setTimeout(() => this._handleSetPaneHeight(DEFAULT_PANE_HEIGHT), 50);
}
_handleMouseMove(e) {
if (this.state.draggingPaneHorizontal) {
// Only pop the overlay after we've moved it a bit (so we don't block doubleclick);
const distance = this.props.paneWidth - this.state.paneWidth;
if (!this.state.showDragOverlay && Math.abs(distance) > 0.02 /* % */) {
this.setState({ showDragOverlay: true });
}
const requestPane = ReactDOM.findDOMNode(this._requestPane);
const responsePane = ReactDOM.findDOMNode(this._responsePane);
const requestPaneWidth = requestPane.offsetWidth;
const responsePaneWidth = responsePane.offsetWidth;
const pixelOffset = e.clientX - requestPane.offsetLeft;
let paneWidth = pixelOffset / (requestPaneWidth + responsePaneWidth);
paneWidth = Math.min(Math.max(paneWidth, MIN_PANE_WIDTH), MAX_PANE_WIDTH);
this._handleSetPaneWidth(paneWidth);
} else if (this.state.draggingPaneVertical) {
// Only pop the overlay after we've moved it a bit (so we don't block doubleclick);
const distance = this.props.paneHeight - this.state.paneHeight;
if (!this.state.showDragOverlay && Math.abs(distance) > 0.02 /* % */) {
this.setState({ showDragOverlay: true });
}
const requestPane = ReactDOM.findDOMNode(this._requestPane);
const responsePane = ReactDOM.findDOMNode(this._responsePane);
const requestPaneHeight = requestPane.offsetHeight;
const responsePaneHeight = responsePane.offsetHeight;
const pixelOffset = e.clientY - requestPane.offsetTop;
let paneHeight = pixelOffset / (requestPaneHeight + responsePaneHeight);
paneHeight = Math.min(Math.max(paneHeight, MIN_PANE_HEIGHT), MAX_PANE_HEIGHT);
this._handleSetPaneHeight(paneHeight);
} else if (this.state.draggingSidebar) {
// Only pop the overlay after we've moved it a bit (so we don't block doubleclick);
const distance = this.props.sidebarWidth - this.state.sidebarWidth;
if (!this.state.showDragOverlay && Math.abs(distance) > 2 /* ems */) {
this.setState({ showDragOverlay: true });
}
const sidebar = ReactDOM.findDOMNode(this._sidebar);
const currentPixelWidth = sidebar.offsetWidth;
const ratio = (e.clientX - sidebar.offsetLeft) / currentPixelWidth;
const width = this.state.sidebarWidth * ratio;
let sidebarWidth = Math.min(width, MAX_SIDEBAR_REMS);
if (sidebarWidth < COLLAPSE_SIDEBAR_REMS) {
sidebarWidth = MIN_SIDEBAR_REMS;
}
this._handleSetSidebarWidth(sidebarWidth);
}
}
_handleMouseUp() {
if (this.state.draggingSidebar) {
this.setState({ draggingSidebar: false, showDragOverlay: false });
}
if (this.state.draggingPaneHorizontal) {
this.setState({ draggingPaneHorizontal: false, showDragOverlay: false });
}
if (this.state.draggingPaneVertical) {
this.setState({ draggingPaneVertical: false, showDragOverlay: false });
}
}
_handleKeyDown(e) {
for (const [definition, callback] of this._globalKeyMap) {
executeHotKey(e, definition, callback);
}
}
_handleToggleMenuBar(hide) {
for (const win of remote.BrowserWindow.getAllWindows()) {
if (win.isMenuBarAutoHide() !== hide) {
win.setAutoHideMenuBar(hide);
win.setMenuBarVisibility(!hide);
}
}
}
async _handleToggleSidebar() {
const sidebarHidden = !this.props.sidebarHidden;
await this._handleSetSidebarHidden(sidebarHidden);
}
_handleShowExportRequestsModal() {
showModal(ExportRequestsModal);
}
_setWrapperRef(n) {
this._wrapper = n;
}
async _handleReloadPlugins() {
const { settings } = this.props;
await plugins.getPlugins(true);
templating.reload();
themes.setTheme(settings.theme);
console.log('[plugins] reloaded');
}
/**
* Update document.title to be "Workspace (Environment) – Request"
* @private
*/
_updateDocumentTitle() {
const { activeWorkspace, activeEnvironment, activeRequest } = this.props;
let title = activeWorkspace.name;
if (activeEnvironment) {
title += ` (${activeEnvironment.name})`;
}
if (activeRequest) {
title += ` – ${activeRequest.name}`;
}
document.title = title;
}
componentDidUpdate(prevProps) {
this._updateDocumentTitle();
// Force app refresh if login state changes
if (prevProps.isLoggedIn !== this.props.isLoggedIn) {
this.setState(state => ({
forceRefreshCounter: state.forceRefreshCounter + 1,
}));
}
}
async _updateVCS(activeWorkspace) {
// Get the vcs and set it to null in the state while we update it
let vcs = this.state.vcs;
this.setState({ vcs: null });
if (!vcs) {
const directory = path.join(getDataDirectory(), 'version-control');
const driver = new FileSystemDriver({ directory });
vcs = new VCS(driver, async conflicts => {
return new Promise(resolve => {
showModal(SyncMergeModal, {
conflicts,
handleDone: conflicts => resolve(conflicts),
});
});
});
}
await vcs.switchProject(activeWorkspace._id);
this.setState({ vcs });
}
async componentDidMount() {
// Bind mouse and key handlers
document.addEventListener('mouseup', this._handleMouseUp);
document.addEventListener('mousemove', this._handleMouseMove);
this._setGlobalKeyMap();
// Update title
this._updateDocumentTitle();
// Update VCS
await this._updateVCS(this.props.activeWorkspace);
db.onChange(async changes => {
let needsRefresh = false;
for (const change of changes) {
const [type, doc, fromSync] = change;
const { vcs } = this.state;
const { activeRequest } = this.props;
// Force refresh if environment changes
// TODO: Only do this for environments in this workspace (not easy because they're nested)
if (doc.type === models.environment.type) {
console.log('[App] Forcing update from environment change', change);
needsRefresh = true;
}
// Force refresh if sync changes the active request
if (fromSync && activeRequest && doc._id === activeRequest._id) {
needsRefresh = true;
console.log('[App] Forcing update from request change', change);
}
// Delete VCS project if workspace deleted
if (vcs && doc.type === models.workspace.type && type === db.CHANGE_REMOVE) {
await vcs.removeProjectsForRoot(doc._id);
}
}
if (needsRefresh) {
setTimeout(() => {
this._wrapper && this._wrapper._forceRequestPaneRefresh();
}, 300);
}
});
ipcRenderer.on('toggle-preferences', () => {
showModal(SettingsModal);
});
ipcRenderer.on('reload-plugins', this._handleReloadPlugins);
ipcRenderer.on('toggle-preferences-shortcuts', () => {
showModal(SettingsModal, TAB_INDEX_SHORTCUTS);
});
ipcRenderer.on('run-command', (e, commandUri) => {
const parsed = urlParse(commandUri, true);
const command = `${parsed.hostname}${parsed.pathname}`;
const args = JSON.parse(JSON.stringify(parsed.query));
args.workspaceId = args.workspaceId || this.props.activeWorkspace._id;
this.props.handleCommand(command, args);
});
// NOTE: This is required for "drop" event to trigger.
document.addEventListener(
'dragover',
e => {
e.preventDefault();
},