/
saveable.ts
322 lines (296 loc) · 11 KB
/
saveable.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// *****************************************************************************
// Copyright (C) 2017 TypeFox 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-only WITH Classpath-exception-2.0
// *****************************************************************************
import { Widget } from '@phosphor/widgets';
import { Message } from '@phosphor/messaging';
import { Event } from '../common/event';
import { MaybePromise } from '../common/types';
import { Key } from './keyboard/keys';
import { AbstractDialog } from './dialogs';
import { waitForClosed } from './widgets';
import { nls } from '../common/nls';
import { isObject } from '../common';
export interface Saveable {
readonly dirty: boolean;
readonly onDirtyChanged: Event<void>;
readonly autoSave: 'off' | 'afterDelay' | 'onFocusChange' | 'onWindowChange';
/**
* Saves dirty changes.
*/
save(options?: SaveOptions): MaybePromise<void>;
/**
* Reverts dirty changes.
*/
revert?(options?: Saveable.RevertOptions): Promise<void>;
/**
* Creates a snapshot of the dirty state.
*/
createSnapshot?(): Saveable.Snapshot;
/**
* Applies the given snapshot to the dirty state.
*/
applySnapshot?(snapshot: object): void;
}
export interface SaveableSource {
readonly saveable: Saveable;
}
export namespace Saveable {
export interface RevertOptions {
/**
* If soft then only dirty flag should be updated, otherwise
* the underlying data should be reverted as well.
*/
soft?: boolean
}
export type Snapshot = { value: string } | { read(): string | null };
export function isSource(arg: unknown): arg is SaveableSource {
return isObject<SaveableSource>(arg) && is(arg.saveable);
}
export function is(arg: unknown): arg is Saveable {
return isObject(arg) && 'dirty' in arg && 'onDirtyChanged' in arg;
}
export function get(arg: unknown): Saveable | undefined {
if (is(arg)) {
return arg;
}
if (isSource(arg)) {
return arg.saveable;
}
return undefined;
}
export function getDirty(arg: unknown): Saveable | undefined {
const saveable = get(arg);
if (saveable && saveable.dirty) {
return saveable;
}
return undefined;
}
export function isDirty(arg: unknown): boolean {
return !!getDirty(arg);
}
export async function save(arg: unknown, options?: SaveOptions): Promise<void> {
const saveable = get(arg);
if (saveable) {
await saveable.save(options);
}
}
async function closeWithoutSaving(this: PostCreationSaveableWidget, doRevert: boolean = true): Promise<void> {
const saveable = get(this);
if (saveable && doRevert && saveable.dirty && saveable.revert) {
await saveable.revert();
}
this[close]();
return waitForClosed(this);
}
function createCloseWithSaving(
getOtherSaveables?: () => Array<Widget | SaveableWidget>,
doSave?: (widget: Widget, options?: SaveOptions) => Promise<void>
): (this: SaveableWidget, options?: SaveableWidget.CloseOptions) => Promise<void> {
let closing = false;
return async function (this: SaveableWidget, options: SaveableWidget.CloseOptions): Promise<void> {
if (closing) { return; }
const saveable = get(this);
if (!saveable) { return; }
closing = true;
try {
const result = await shouldSave(saveable, () => {
const notLastWithDocument = !closingWidgetWouldLoseSaveable(this, getOtherSaveables?.() ?? []);
if (notLastWithDocument) {
return this.closeWithoutSaving(false).then(() => undefined);
}
if (options && options.shouldSave) {
return options.shouldSave();
}
return new ShouldSaveDialog(this).open();
});
if (typeof result === 'boolean') {
if (result) {
await (doSave?.(this) ?? Saveable.save(this));
}
await this.closeWithoutSaving();
}
} finally {
closing = false;
}
};
}
export async function confirmSaveBeforeClose(toClose: Iterable<Widget>, others: Widget[]): Promise<boolean | undefined> {
for (const widget of toClose) {
const saveable = Saveable.get(widget);
if (saveable?.dirty) {
if (!closingWidgetWouldLoseSaveable(widget, others)) {
continue;
}
const userWantsToSave = await new ShouldSaveDialog(widget).open();
if (userWantsToSave === undefined) { // User clicked cancel.
return undefined;
} else if (userWantsToSave) {
await saveable.save();
} else {
await saveable.revert?.();
}
}
}
return true;
}
/**
* @param widget the widget that may be closed
* @param others widgets that will not be closed.
* @returns `true` if widget is saveable and no widget among the `others` refers to the same saveable. `false` otherwise.
*/
function closingWidgetWouldLoseSaveable(widget: Widget, others: Widget[]): boolean {
const saveable = get(widget);
return !!saveable && !others.some(otherWidget => otherWidget !== widget && get(otherWidget) === saveable);
}
export function apply(
widget: Widget,
getOtherSaveables?: () => Array<Widget | SaveableWidget>,
doSave?: (widget: Widget, options?: SaveOptions) => Promise<void>,
): SaveableWidget | undefined {
if (SaveableWidget.is(widget)) {
return widget;
}
const saveable = Saveable.get(widget);
if (!saveable) {
return undefined;
}
const saveableWidget = widget as SaveableWidget;
setDirty(saveableWidget, saveable.dirty);
saveable.onDirtyChanged(() => setDirty(saveableWidget, saveable.dirty));
const closeWithSaving = createCloseWithSaving(getOtherSaveables, doSave);
return Object.assign(saveableWidget, {
closeWithoutSaving,
closeWithSaving,
close: closeWithSaving,
[close]: saveableWidget.close,
});
}
export async function shouldSave(saveable: Saveable, cb: () => MaybePromise<boolean | undefined>): Promise<boolean | undefined> {
if (!saveable.dirty) {
return false;
}
if (saveable.autoSave !== 'off') {
return true;
}
return cb();
}
}
export interface SaveableWidget extends Widget {
/**
* @param doRevert whether the saveable should be reverted before being saved. Defaults to `true`.
*/
closeWithoutSaving(doRevert?: boolean): Promise<void>;
closeWithSaving(options?: SaveableWidget.CloseOptions): Promise<void>;
}
export const close = Symbol('close');
/**
* An interface describing saveable widgets that are created by the `Saveable.apply` function.
* The original `close` function is reassigned to a locally-defined `Symbol`
*/
export interface PostCreationSaveableWidget extends SaveableWidget {
/**
* The original `close` function of the widget
*/
[close](): void;
}
export namespace SaveableWidget {
export function is(widget: Widget | undefined): widget is SaveableWidget {
return !!widget && 'closeWithoutSaving' in widget;
}
export function getDirty<T extends Widget>(widgets: Iterable<T>): IterableIterator<SaveableWidget & T> {
return get<T>(widgets, Saveable.isDirty);
}
export function* get<T extends Widget>(
widgets: Iterable<T>,
filter: (widget: T) => boolean = () => true
): IterableIterator<SaveableWidget & T> {
for (const widget of widgets) {
if (SaveableWidget.is(widget) && filter(widget)) {
yield widget;
}
}
}
export interface CloseOptions {
shouldSave?(): MaybePromise<boolean | undefined>
}
}
/**
* Possible formatting types when saving.
*/
export const enum FormatType {
/**
* Formatting should occur (default).
*/
ON = 1,
/**
* Formatting should not occur.
*/
OFF,
/**
* Formatting should only occur if the resource is dirty.
*/
DIRTY
};
export interface SaveOptions {
/**
* Formatting type to apply when saving.
*/
readonly formatType?: FormatType;
}
/**
* The class name added to the dirty widget's title.
*/
const DIRTY_CLASS = 'theia-mod-dirty';
export function setDirty(widget: Widget, dirty: boolean): void {
const dirtyClass = ` ${DIRTY_CLASS}`;
widget.title.className = widget.title.className.replace(dirtyClass, '');
if (dirty) {
widget.title.className += dirtyClass;
}
}
export class ShouldSaveDialog extends AbstractDialog<boolean> {
protected shouldSave = true;
protected readonly dontSaveButton: HTMLButtonElement;
constructor(widget: Widget) {
super({
title: nls.localizeByDefault('Do you want to save the changes you made to {0}?', widget.title.label || widget.title.caption)
}, {
node: widget.node.ownerDocument.createElement('div')
});
const messageNode = this.node.ownerDocument.createElement('div');
messageNode.textContent = nls.localizeByDefault("Your changes will be lost if you don't save them.");
messageNode.setAttribute('style', 'flex: 1 100%; padding-bottom: calc(var(--theia-ui-padding)*3);');
this.contentNode.appendChild(messageNode);
this.appendCloseButton();
this.dontSaveButton = this.appendDontSaveButton();
this.appendAcceptButton(nls.localizeByDefault('Save'));
}
protected appendDontSaveButton(): HTMLButtonElement {
const button = this.createButton(nls.localizeByDefault("Don't Save"));
this.controlPanel.appendChild(button);
button.classList.add('secondary');
return button;
}
protected override onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this.addKeyListener(this.dontSaveButton, Key.ENTER, () => {
this.shouldSave = false;
this.accept();
}, 'click');
}
get value(): boolean {
return this.shouldSave;
}
}