Debian Codegraph @

ivette/src/dome/renderer/dialogs.tsx

raw
1 /* ************************************************************************ */
2 /* */
3 /* This file is part of Frama-C. */
4 /* */
5 /* Copyright (C) 2007-2022 */
6 /* CEA (Commissariat à l'énergie atomique et aux énergies */
7 /* alternatives) */
8 /* */
9 /* you can redistribute it and/or modify it under the terms of the GNU */
10 /* Lesser General Public License as published by the Free Software */
11 /* Foundation, version 2.1. */
12 /* */
13 /* It is distributed in the hope that it will be useful, */
14 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
15 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
16 /* GNU Lesser General Public License for more details. */
17 /* */
18 /* See the GNU Lesser General Public License version 2.1 */
19 /* for more details (enclosed in the file licenses/LGPLv2.1). */
20 /* */
21 /* ************************************************************************ */
22
23 /**
24 Various kind of (modal) dialogs attached to the main application window.
25 @packageDocumentation
26 @module dome/dialogs
27 */
28
29 import filepath from 'path';
30 import { ipcRenderer } from 'electron';
31 import * as System from 'dome/system';
32
33 // --------------------------------------------------------------------------
34 // --- Message Box
35 // --------------------------------------------------------------------------
36
37 export interface DialogButton<A> {
38 label?: string;
39 value?: A;
40 }
41
42 const defaultItems: DialogButton<boolean>[] = [
43 { value: undefined },
44 { value: true, label: 'Ok' },
45 ];
46
47 const valueLabel = (v: unknown): string => {
48 switch (v) {
49 case undefined: return 'Cancel';
50 case true: return 'Ok';
51 case false: return 'No';
52 default: return `${v}`;
53 }
54 };
55
56 const itemLabel = ({ value, label }: DialogButton<unknown>): string => (
57 (label || valueLabel(value))
58 );
59
60 const isDefault = ({ value, label }: DialogButton<unknown>): boolean => (
61 (value === true || label === 'Ok' || label === 'Yes')
62 );
63
64 const isCancel = ({ value, label }: DialogButton<unknown>): boolean => (
65 (!value || label === 'Cancel' || label === 'No')
66 );
67
68 export type MessageKind = 'none' | 'info' | 'error' | 'warning';
69
70 export interface MessageProps<A> {
71 /** Dialog window icon (default is `'none'`. */
72 kind?: MessageKind;
73 /** Message text (short sentence). */
74 message: string;
75 /** Message details (short sentence). */
76 details?: string;
77 /** Message buttons. */
78 buttons?: DialogButton<A>[];
79 /** Default button's value. */
80 defaultValue?: A;
81 /** Cancel value. */
82 cancelValue?: A;
83 }
84
85 /**
86 Show a configurable message box.
87
88 The returned promise object is never rejected, and is asynchronously
89 resolved into:
90 - the cancel value if the cancel key is pressed,
91 - the default value if the enter key is pressed,
92 - or the value of the clicked button otherwised.
93
94 The default buttons are `"Ok"` and `"Cancel"` associated to values `true` and
95 `undefined`, which are also associated to the enter and cancel keys.
96 Unless specified, the default value is associated with the first button
97 with 'true' value or 'Ok' or 'Yes' label,
98 and the cancel value is the first button with a falsy value or 'Cancel'
99 or 'No' label.
100 */
101 export async function showMessageBox<A>(
102 props: MessageProps<A>,
103 ): Promise<A | boolean | undefined> {
104 const {
105 kind,
106 message,
107 details,
108 defaultValue,
109 cancelValue,
110 buttons = (defaultItems as DialogButton<A | boolean>[]),
111 } = props;
112
113 const labels = buttons.map(itemLabel);
114 const defaultId =
115 defaultValue === undefined
116 ? buttons.findIndex(isDefault)
117 : buttons.findIndex((a) => a.value === defaultValue);
118 let cancelId =
119 cancelValue === undefined
120 ? buttons.findIndex(isCancel)
121 : buttons.findIndex((a) => a.value === cancelValue);
122
123 if (cancelId === defaultId) cancelId = -1;
124
125 return ipcRenderer.invoke('dome.dialog.showMessageBox',
126 {
127 'type': kind,
128 message,
129 detail: details,
130 defaultId,
131 cancelId,
132 buttons: labels,
133 },
134 ).then((result) => {
135 const itemIndex = result ? result.response : -1;
136 return itemIndex ? buttons[itemIndex].value : cancelValue;
137 });
138 }
139
140 // --------------------------------------------------------------------------
141 // --- File Dialogs
142 // --------------------------------------------------------------------------
143
144 const defaultPath =
145 (path: string): string =>
146 (filepath.extname(path) ? filepath.dirname(path) : path);
147
148 export interface FileFilter {
149 /** Filter name. */
150 name: string;
151 /**
152 Allowed extensions, _without_ dot.
153 Use `['*']` to accept all files.
154 */
155 extensions: string[];
156 }
157
158 export interface FileDialogProps {
159 /** Prompt message. */
160 title?: string;
161 /** Open button label (default is « Open »). */
162 label?: string;
163 /** Initially selected path. */
164 path?: string;
165 }
166
167 export interface SaveFileProps extends FileDialogProps {
168 /** File filters (default to all). */
169 filters?: FileFilter[];
170 }
171
172 export interface OpenFileProps extends SaveFileProps {
173 /** Show hidden files (default is `false`). */
174 hidden?: boolean;
175 }
176
177 export interface OpenDirProps extends FileDialogProps {
178 /** Show hidden directories (default is `false`). */
179 hidden?: boolean;
180 }
181
182 // --------------------------------------------------------------------------
183 // --- openFile dialog
184 // --------------------------------------------------------------------------
185
186 /**
187 Show a dialog for opening file.
188 A file filter with `extensions:["*"]` would accept any file extension.
189
190 The returned promise object will be asynchronously:
191 - either _resolved_ with `undefined` if no file has been selected,
192 - or _resolved_ with the selected path
193
194 The promise is never rejected.
195 */
196 export async function showOpenFile(
197 props: OpenFileProps,
198 ): Promise<string | undefined> {
199 const { title, label, path, hidden = false, filters } = props;
200 return ipcRenderer.invoke('dome.dialog.showOpenDialog',
201 {
202 title,
203 buttonLabel: label,
204 defaultPath: path && defaultPath(path),
205 properties: (hidden ? ['openFile', 'showHiddenFiles'] : ['openFile']),
206 filters,
207 },
208 ).then((result) => {
209 if (!result.canceled && result.filePaths && result.filePaths.length > 0)
210 return result.filePaths[0];
211 return undefined;
212 });
213 }
214
215 /**
216 Show a dialog for opening files multiple files.
217 */
218 export async function showOpenFiles(
219 props: OpenFileProps,
220 ): Promise<string[] | undefined> {
221 const { title, label, path, hidden, filters } = props;
222
223 return ipcRenderer.invoke('dome.dialog.showOpenDialog',
224 {
225 title,
226 buttonLabel: label,
227 defaultPath: path && defaultPath(path),
228 properties: (
229 hidden
230 ? ['openFile', 'multiSelections', 'showHiddenFiles']
231 : ['openFile', 'multiSelections']
232 ),
233 filters,
234 },
235 ).then((result) => {
236 if (!result.canceled && result.filePaths && result.filePaths.length > 0)
237 return result.filePaths;
238 return undefined;
239 });
240 }
241
242 // --------------------------------------------------------------------------
243 // --- saveFile dialog
244 // --------------------------------------------------------------------------
245
246 /**
247 Show a dialog for saving file.
248
249 The returned promise object will be asynchronously:
250 - either _resolved_ with `undefined` when canceled,
251 - or _resolved_ with the selected (single) path.
252
253 The promise is never rejected.
254 */
255 export async function showSaveFile(
256 props: SaveFileProps,
257 ): Promise<string | undefined> {
258 const { title, label, path, filters } = props;
259 return ipcRenderer.invoke('dome.dialog.showSaveDialog',
260 {
261 title,
262 buttonLabel: label,
263 defaultPath: path,
264 filters,
265 },
266 ).then(({ canceled, filePath }) => (canceled ? undefined : filePath));
267 }
268
269 // --------------------------------------------------------------------------
270 // --- openDir dialog
271 // --------------------------------------------------------------------------
272
273 type openDirProperty =
274 'openDirectory' | 'showHiddenFiles' | 'createDirectory' | 'promptToCreate';
275
276 /**
277 Show a dialog for selecting directories.
278 */
279 export async function showOpenDir(
280 props: OpenDirProps,
281 ): Promise<string | undefined> {
282 const { title, label, path, hidden } = props;
283 const properties: openDirProperty[] = ['openDirectory'];
284 if (hidden) properties.push('showHiddenFiles');
285
286 switch (System.platform) {
287 case 'macos': properties.push('createDirectory'); break;
288 case 'windows': properties.push('promptToCreate'); break;
289 default: break;
290 }
291
292 return ipcRenderer.invoke('dome.dialog.showOpenDialog',
293 {
294 title,
295 buttonLabel: label,
296 defaultPath: path,
297 properties,
298 },
299 ).then((result) => {
300 if (!result.canceled && result.filePaths && result.filePaths.length > 0)
301 return result.filePaths[0];
302 return undefined;
303 });
304 }
305
306 // --------------------------------------------------------------------------