dialog.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const {dialog, ipcMain} = require('electron');
  2. const window = require('../../../helper/window');
  3. const config = require('../../../config');
  4. const dlg = {};
  5. dlg.messagePromise = function(title, content, type = '', buttons = ['Ok'], defaultButton = 0, attach = true) {
  6. const opts = {
  7. type: type,
  8. title: title,
  9. message: content,
  10. buttons: buttons,
  11. defaultId: defaultButton
  12. };
  13. if (attach) {
  14. return dialog.showMessageBox(mainWindow, opts);
  15. } else {
  16. return dialog.showMessageBox(opts);
  17. }
  18. }
  19. dlg.message = function(title, content, type = 'info', buttons = ['Ok'], defaultButton = 0, attach = true, callback = null) {
  20. const promise = dlg.messagePromise(title, content, type, buttons, defaultButton, attach);
  21. if (callback !== null) {
  22. promise.then(data => {
  23. callback(data.response, buttons[data.response]);
  24. });
  25. }
  26. }
  27. dlg.fileSelectorPromise = function(openFile = true, openDir = false, filters = [{name: 'Tous les fichiers', extensions: ['*']}]) {
  28. const opts = {
  29. properties: [],
  30. filters: filters
  31. }
  32. if (openFile) {
  33. opts.properties.push('openFile');
  34. }
  35. if (openDir) {
  36. opts.properties.push('openDirectory');
  37. }
  38. return dialog.showOpenDialog(opts)
  39. }
  40. dlg.fileSelector = function(openFile = true, openDir = false, filters = [{name: 'Tous les fichiers', extensions: ['*']}], callback = null) {
  41. const promise = dlg.fileSelectorPromise(openFile, openDir, filters);
  42. if (callback !== null) {
  43. promise.then(data => {
  44. callback(data.canceled, data.filePaths[0]);
  45. });
  46. }
  47. }
  48. dlg.error = function (title, content) {
  49. dialog.showErrorBox(title, content);
  50. }
  51. dlg.customPromise = function (file) {
  52. let win = null;
  53. return new Promise(resolve => {
  54. // Genererate key for answer
  55. const key = '-' + Math.random().toString(36).substr(2, 9);
  56. // Wait win answser
  57. ipcMain.once('dialog-answer' + key, (arg, answer) => {
  58. win.close();
  59. resolve(answer);
  60. });
  61. // Create win
  62. win = window.frameless(file, mainWindow, config.dialog.width, config.dialog.height);
  63. // When win is ready send the key
  64. win.on('focus', () => {
  65. setTimeout(() => {
  66. win.webContents.send('dialog-key', key);
  67. }, 500);
  68. })
  69. });
  70. }
  71. dlg.custom = function (file, callback) {
  72. const promise = dlg.customPromise(file);
  73. if (callback) {
  74. promise.then(data => {
  75. callback(data);
  76. });
  77. }
  78. }
  79. module.exports = dlg;