electron#remote TypeScript Examples

The following examples show how to use electron#remote. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From yana with MIT License 7 votes vote down vote up
getElectronPath = (
  pathIdentifier:
    | 'home'
    | 'appData'
    | 'userData'
    | 'cache'
    | 'temp'
    | 'exe'
    | 'module'
    | 'desktop'
    | 'documents'
    | 'downloads'
    | 'music'
    | 'pictures'
    | 'videos'
    | 'recent'
    | 'logs'
    | 'pepperFlashSystemPlugin'
    | 'crashDumps'
) => (remote?.app || app).getPath(pathIdentifier)
Example #2
Source File: Toggle.tsx    From electron with MIT License 6 votes vote down vote up
Wrap: React.FC = () => {
  const [isMaximized, setMaximized] = React.useState(remote.getCurrentWindow().isMaximized());
  React.useEffect(() => {
    const resizeHandle = () => {
      setMaximized(remote.getCurrentWindow().isMaximized());
    };
    remote.getCurrentWindow().on('resize', resizeHandle);
    return () => {
      remote.getCurrentWindow().off('resize', resizeHandle);
    };
  }, []);
  const onFunc = () => {
    isMaximized ? remote.getCurrentWindow().restore() : remote.getCurrentWindow().maximize();
  };
  return (
    <>
      <span onClick={onFunc}>{isMaximized ? <WrapFullToNormal /> : <WrapNormalToFull />}</span>
      <style jsx>{`
        span {
          padding: 0 16px;
          display: flex;
          justify-content: center;
          width: auto;
          align-items: center;
          background-color: transparent;
        }
        span:hover {
          background-color: rgba(0, 0, 0, 0.08);
        }
      `}</style>
    </>
  );
}
Example #3
Source File: SettingsFilesystemPathInput.tsx    From yana with MIT License 6 votes vote down vote up
SettingsFilesystemPathInput: React.FC<{
  settingsKey: keyof SettingsObject;
  label: string;
  helperText?: string;
  labelInfo?: string;
  placeholder?: string;
}> = props => {
  const settings = useSettingsPageContext();
  const id = props.label.toLowerCase().replace(/\s/g, '_');

  return (
    <FormGroup helperText={props.helperText} label={props.label} labelInfo={props.labelInfo} labelFor={id}>
      <ControlGroup fill>
        <InputGroup
          fill
          id={id}
          placeholder={props.placeholder || props.label}
          value={settings.settings[props.settingsKey] as string}
          onChange={(e: any) => settings.changeSettings({ [props.settingsKey]: e.target.value })}
        />
        <Button
          outlined
          onClick={async () => {
            const result = await remote.dialog.showOpenDialog({
              defaultPath: settings.settings[props.settingsKey] as string,
              buttonLabel: 'Choose',
              title: 'Choose location for automatic backups',
              properties: ['createDirectory', 'openDirectory'],
            });
            if (result.canceled) return;
            settings.changeSettings({ [props.settingsKey]: result.filePaths[0] });
          }}
        >
          &nbsp;&nbsp;&nbsp;Choose&nbsp;path...&nbsp;&nbsp;&nbsp;
        </Button>
      </ControlGroup>
    </FormGroup>
  );
}
Example #4
Source File: index.tsx    From Aragorn with MIT License 6 votes vote down vote up
About = () => {
  function handleUpdate() {
    ipcRenderer.send('check-update', true);
  }

  return (
    <div className="info-wrapper">
      <header>
        <span>关于</span>
        <Divider />
      </header>
      <main>
        <h3>Aragorn</h3>
        <a
          style={{ margin: 10 }}
          onClick={() => {
            shell.openExternal(AppUrl);
          }}
        >
          {AppUrl}
        </a>
        <p className="desc">v{remote.app.getVersion()}</p>
        <Button type="primary" onClick={handleUpdate}>
          检查更新
        </Button>
      </main>
    </div>
  );
}
Example #5
Source File: index.tsx    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
Home: FC = () => {
    const history = useHistory();
    const { loadProject } = useProjects();

    const handleOpenProject = async () => {
        const result = await remote.dialog.showOpenDialog({
            title: 'Select the root directory of your project',
            properties: ['openDirectory'],
        });

        if (result.filePaths.length !== 1) {
            return;
        }

        loadProject(result.filePaths[0]);
    };

    return (
        <div className="relative h-full flex flex-col justify-center">
            <div className="h-72 flex flex-row justify-center items-center divide-x divide-gray-600 space-x-12">
                <div className="w-72 h-full flex flex-col gap-y-2">
                    <h1 className="text-5xl font-medium mb-1.5">Welcome.</h1>
                    <p className="text-2xl">Where do you want to start today?</p>

                    <button className="w-full h-12 px-4 mt-auto bg-gray-700 text-xl flex flex-row gap-x-4 items-center" type="button" onClick={handleOpenProject}>
                        Open Project
                        <IconFolder size={28} className="ml-auto" />
                    </button>
                    <button className="w-full h-12 px-4 bg-teal-medium text-xl flex flex-row gap-x-4 items-center" type="button" onClick={() => history.push('/create-project')}>
                        Create Project
                        <IconFolderPlus size={28} className="ml-auto" />
                    </button>
                </div>

                <RecentProjects />
            </div>
        </div>
    );
}
Example #6
Source File: utils.ts    From electron-playground with MIT License 6 votes vote down vote up
function getDownloadPath(version: string): string {
  return path.join(remote.app.getPath('appData'), 'electron-bin', version)
}
Example #7
Source File: preview.ts    From wow-mdx-viewer with MIT License 6 votes vote down vote up
function initControls() {
    const sequence = <HTMLSelectElement>document.getElementById('sequence');
    sequence.addEventListener('input', () => modelRenderer.setSequence(parseInt(sequence.value, 10)));

    const variation = <HTMLSelectElement>document.getElementById('variation');
    variation.addEventListener('input', () => setTextures(parseInt(variation.value), true));

    const inputZ = <HTMLInputElement>document.getElementById('targetZ');
    inputZ.addEventListener('input', () => controller.cameraTargetZ = parseInt(inputZ.value, 10));

    const inputDistance = <HTMLInputElement>document.getElementById('distance');
    inputDistance.addEventListener('input', () => controller.cameraDistance = parseInt(inputDistance.value, 10));

    const particles = <HTMLInputElement>document.getElementById('particles');
    particles.addEventListener('change', () => modelRenderer.enableParticles(particles.checked));

    const ribbons = <HTMLInputElement>document.getElementById('ribbons');
    ribbons.addEventListener('change', () => modelRenderer.enableRibbons(ribbons.checked));

    const directory = <HTMLButtonElement>document.getElementById("directory");
    const directorylabel = <HTMLInputElement>document.getElementById("directory-label");
    directory.addEventListener('click', () => {
        const directory: string[] = remote
            .require("electron").dialog
            .showOpenDialogSync(remote.getCurrentWindow(), {
                properties: ['openDirectory']
            });

        if (directory && directory[0]) {
            setDirectory(directory[0]);
            directorylabel.value = directory[0];
        }
    });

    initCharControls();
}
Example #8
Source File: useReadIpc.tsx    From Account-Manager with MIT License 6 votes vote down vote up
function useReadIpc({
  channel,
  downloadOptions,
  failCallback,
  postSendCallback,
  successCallback,
}: {
  channel: IpcChannel;
  downloadOptions: DownloadOptions;
  failCallback: GenericVoidFunction;
  postSendCallback?: GenericVoidFunction;
  successCallback: GenericVoidFunction;
}) {
  useIpcEffect(getSuccessChannel(channel), successCallback);
  useIpcEffect(getFailChannel(channel), failCallback);

  const options: OpenDialogOptions = useMemo(
    () => ({
      buttonLabel: downloadOptions.buttonLabel,
      filters: [
        {extensions: ['json'], name: 'json'},
        {extensions: ['*'], name: 'All Files'},
      ],
      title: downloadOptions.title,
    }),
    [downloadOptions.buttonLabel, downloadOptions.title],
  );

  return useCallback(async (): Promise<void> => {
    remote.dialog.showOpenDialog(options).then(({filePaths}) => {
      if (!filePaths.length) return;

      ipcRenderer.send(channel, {filePath: filePaths[0]});
      postSendCallback?.();
    });
  }, [channel, options, postSendCallback]);
}
Example #9
Source File: Home.tsx    From Oratio with MIT License 6 votes vote down vote up
async function handleOpenObs() {
  // electron.ipcRenderer.on();
  // BrowserWindow is just the type import, remote.BrowserWindow is the value
  // const win: BrowserWindow = new remote.BrowserWindow({ .. })
  if (win === undefined) {
    win = new remote.BrowserWindow({
      // backgroundColor: 'blue',
      height: 600,
      width: 800,
      title: 'Oratio OBS Display',
      autoHideMenuBar: true,
      // focusable: false,
      // transparent: true,
      webPreferences: {
        nodeIntegration: true,
        // devTools: true,
        // Soffscreen: true,
      },
    });
    win.loadURL(`file://${__dirname}/index.html#/obs`);

    win.on('closed', () => {
      win = undefined;
    });
  }
}
Example #10
Source File: electron.service.ts    From VIR with MIT License 6 votes vote down vote up
constructor() {
    // Conditional imports
    if (this.isElectron) {
      this.ipcRenderer = window.require('electron').ipcRenderer
      this.webFrame = window.require('electron').webFrame

      // If you wan to use remote object, pleanse set enableRemoteModule to
      // true in main.ts
      this.remote = window.require('electron').remote

      this.childProcess = window.require('child_process')
      this.fs = window.require('fs')
      this.os = window.require('os')
      this.path = window.require('path')
    }
  }
Example #11
Source File: Mini.tsx    From electron with MIT License 6 votes vote down vote up
Wrap: React.FC = () => {
  const __size__ = 16;
  const __color__ = '#666';
  const onFunc = () => {
    remote.getCurrentWindow().minimize();
  };
  return (
    <>
      <span onClick={onFunc}>
        <svg className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6887" width={__size__} height={__size__}>
          <path d="M128 512h768a25.6 25.6 0 1 1 0 51.2h-768a25.6 25.6 0 1 1 0-51.2z" p-id="6888" fill={__color__}></path>
        </svg>
      </span>
      <style jsx>{`
        span {
          padding: 0 16px;
          display: flex;
          justify-content: center;
          width: auto;
          align-items: center;
          background-color: transparent;
        }
        span:hover {
          background-color: rgba(0, 0, 0, 0.08);
        }
      `}</style>
    </>
  );
}
Example #12
Source File: logs-subscription.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
async function showFatalMessageDialog(line: LogLine) {
  const browserWindow = new remote.BrowserWindow({
    show: false,
    alwaysOnTop: true,
  });

  await remote.dialog.showMessageBox(browserWindow, {
    type: 'error',
    title: line.modName,
    message: line.text,
  });

  browserWindow.destroy();
}
Example #13
Source File: getdb.ts    From elec-sqlite-vue with GNU General Public License v3.0 5 votes vote down vote up
univDb = path.join(remote.app.getPath("userData"), "data.db")
Example #14
Source File: index.tsx    From electron with MIT License 5 votes vote down vote up
ReactDOM.render(App, window.document.getElementById('root'), remote.getCurrentWindow().show);
Example #15
Source File: AdvancedSettings.tsx    From yana with MIT License 5 votes vote down vote up
AdvancedSettings: React.FC<{}> = props => {
  const appData = useAppData();
  return (
    <div>
      <SettingsSection title="Privacy">
        <SettingsSwitchInput settingsKey={'telemetry'} label="Help Yana improve" helperText={telemetryHelperText} />
        <SettingsClickable
          title="View Yana's privacy policy"
          subtitle="https://yana.js.org/privacy"
          icon={'help'}
          onClick={() => remote.shell.openExternal('https://yana.js.org/privacy')}
        />
      </SettingsSection>

      <SettingsSection title="Project Campaigns">
        <SettingsSwitchInput
          settingsKey={'campaigns'}
          label="Show links to my other projects"
          helperText={campaignsHelperText}
        />
      </SettingsSection>

      <SettingsSection title="Devtools">
        <SettingsSwitchInput settingsKey={'devToolsOpen'} label={'Yana Devtools Sidebar open'} />
        <SettingsClickable
          title="Create performance testing workspace"
          subtitle="This will create a new workspace with *very* many items. This might take a very long time or crash the app."
          onClick={() => createPerformanceTestingWorkspace(appData)}
        />
        <SettingsClickable
          title="Reset app notifications view state"
          onClick={() => appData.saveSettings({ ...appData.settings, notifications: [] })}
        />
      </SettingsSection>

      <SettingsSection title="Logging">
        <SettingsSwitchInput
          settingsKey={'devLoggerActive'}
          label={'Logging active'}
          helperText="Logging happens in the Chrome Devtools Console. Press CTRL+SHIFT+I to open."
        />
        <SettingsTextAreaInput
          settingsKey={'devLoggerWhitelist'}
          label={'Logging Whitelist'}
          helperText="If not empty, only components listed below may log to the console. One component name per line."
        />
        <SettingsTextAreaInput
          settingsKey={'devLoggerBlacklist'}
          label={'Logging Blacklist'}
          helperText="Components listed below may not log to the console. Overwrites whitelist. One component name per line."
        />
        <SettingsClickable
          title="Open Chrome Devtools"
          onClick={() => remote.getCurrentWindow().webContents.openDevTools()}
        />
      </SettingsSection>
    </div>
  );
}
Example #16
Source File: Close.tsx    From electron with MIT License 5 votes vote down vote up
Wrap: React.FC = () => {
  const __size__ = 16;
  const __color__ = '#666';
  const [color, setColor] = React.useState<string>(__color__);
  const onFunc = () => {
    remote.getCurrentWindow().close();
  };
  const onMouseEnter = () => {
    setColor('#fff');
  };
  const onMouseLeave = () => {
    setColor(__color__);
  };
  return (
    <>
      <span onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onClick={onFunc}>
        <svg className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5512" width={__size__} height={__size__}>
          <path
            d="M822.003 776.822l0.023-0.022-575.522-575.483c-5.788-5.792-13.786-9.374-22.621-9.374-17.662 0-31.98 14.318-31.98 31.98 0 8.834 3.582 16.832 9.373 22.62L776.112 821.34c5.84 6.278 14.167 10.21 23.417 10.21 17.662 0 31.98-14.318 31.98-31.98 0-8.901-3.638-16.949-9.506-22.747z"
            p-id="5513"
            fill={color}
          ></path>
          <path
            d="M776.784 201.448l-0.023-0.022-575.483 575.521c-5.792 5.788-9.374 13.786-9.374 22.621 0 17.663 14.318 31.98 31.98 31.98 8.834 0 16.832-3.582 22.62-9.373L821.301 247.34c6.278-5.839 10.21-14.166 10.21-23.416 0-17.662-14.318-31.98-31.98-31.98-8.902 0-16.95 3.637-22.747 9.505z"
            p-id="5514"
            fill={color}
          ></path>
        </svg>
      </span>
      <style jsx>{`
        span {
          padding: 0 16px;
          display: flex;
          justify-content: center;
          width: auto;
          align-items: center;
          background-color: transparent;
        }
        span:hover {
          background-color: #e81123;
        }
      `}</style>
    </>
  );
}
Example #17
Source File: data.service.ts    From tabby with MIT License 5 votes vote down vote up
app: any = remote.app;
Example #18
Source File: index.tsx    From Aragorn with MIT License 5 votes vote down vote up
mainWindow = remote.getCurrentWindow()
Example #19
Source File: index.tsx    From electron with MIT License 5 votes vote down vote up
Wrap: React.FC = () => {
  const [focus, setFocus] = React.useState(remote.getCurrentWindow().isFocused());
  const [hover, setHover] = React.useState(false);
  React.useEffect(() => {
    const focusHandle = () => {
      setFocus(true);
    };
    const blurHandle = () => {
      setFocus(false);
    };
    remote.getCurrentWindow().on('focus', focusHandle);
    remote.getCurrentWindow().on('blur', blurHandle);
    return () => {
      remote.getCurrentWindow().off('focus', focusHandle);
      remote.getCurrentWindow().off('blur', blurHandle);
    };
  }, []);
  const onMouseEnter = () => {
    /** 失去焦点hover */
    if (!remote.getCurrentWindow().isFocused()) {
      setFocus(true);
      setHover(true);
    } else {
      setHover(true);
    }
  };
  const onMouseLeave = () => {
    if (!remote.getCurrentWindow().isFocused()) {
      setFocus(false);
      setHover(false);
    } else {
      setHover(false);
    }
  };
  return (
    <>
      <div className="ctl-box" onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
        <Close focus={focus} hover={hover} />
        <Mini focus={focus} hover={hover} />
        <Toggle focus={focus} hover={hover} />
      </div>
      <style jsx>{`
        .ctl-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 68px;
          padding: 0 7.5px;
        }
      `}</style>
    </>
  );
}
Example #20
Source File: AddNewDbModalCorrect.tsx    From SeeQR with MIT License 5 votes vote down vote up
{ dialog } = remote
Example #21
Source File: index.tsx    From electron with MIT License 5 votes vote down vote up
autoUpdater = (): AUTO_updater | undefined => {
  return remote.getGlobal('AUTO_updater');
}
Example #22
Source File: index.tsx    From MagicUI with Apache License 2.0 5 votes vote down vote up
function App() {
  const [avatarList, setAvatarList] = useState([] as { id: string, source: string, name: string, type: string }[]);
  const [selected, setSelected] = useState(0);
  const [avatar, setAvatar] = useState({ id: '', source: '', name: '', type: '' });
  useEffect(() => {

    fetchAvatars().then(res => {
      if (!res.err) {
        setAvatarList(res.avatars);
        setAvatar(res.avatars[0]);
      }
    });
  }, []);
  const handleSelect = (index: number) => {
    setSelected(index);
    setAvatar(avatarList[index]);
  };

  const selectAvatar = () => {
    remote.getCurrentWindow().getParentWindow().webContents.send('avatar-data', { ...avatar });
    close();
  };

  return (
    <div className={style.app}>
      <div className={style.header}>
        <ControlButtonGroup close onClose={close}/>
      </div>
      <div className={style.content}>
        <div className={style.left}>
          <Avatar size={80} src={avatar.source || defaultAvatar}/>
          <span>{avatar.name || ''}</span>
        </div>
        <div className={style.right}>
          <AvatarList avatars={avatarList} selected={selected} onSelect={handleSelect}/>
        </div>
      </div>
      <div className={style.footer}>
        <button onClick={selectAvatar}>SELECT</button>
      </div>
    </div>
  );
}
Example #23
Source File: demo-communication.ts    From electron-playground with MIT License 5 votes vote down vote up
{ BrowserWindow } = remote
Example #24
Source File: Toggle.tsx    From electron with MIT License 5 votes vote down vote up
Wrap: React.FC<{ focus: boolean; hover: boolean }> = (props) => {
  const [color, setColor] = React.useState('#dcdddd');
  const [isFullScreen, setIsFullScreen] = React.useState(remote.getCurrentWindow().isFullScreen());
  const onFunc = () => {
    remote.getCurrentWindow().setFullScreen(!isFullScreen);
  };
  React.useEffect(() => {
    const resizeHandle = () => {
      setIsFullScreen(remote.getCurrentWindow().isFullScreen());
    };
    remote.getCurrentWindow().on('resize', resizeHandle);
    return () => {
      remote.getCurrentWindow().off('resize', resizeHandle);
    };
  }, []);
  React.useEffect(() => {
    setColor(props.focus ? '#28ca40' : '#dcdddd');
  }, [props.focus]);
  React.useEffect(() => {
    setColor(props.hover ? '#444' : '#28ca40');
  }, [props.hover]);
  return (
    <>
      <span onClick={onFunc} className={props.focus ? 'focus' : 'unfocus'}>
        {isFullScreen ? <WrapFullToNormal color={color} /> : <WrapNormalToFull color={color} />}
      </span>
      <style jsx>{`
        .focus {
          background-color: #28ca40;
          border: 1px solid #30ae2e;
        }
        .unfocus {
          background-color: #dcdddd;
          border: 1px solid #ced4cc;
        }
        span {
          display: flex;
          width: 12px;
          height: 12px;
          border-radius: 6px;
          justify-content: center;
          align-items: center;
          overflow: hidden;
        }
      `}</style>
    </>
  );
}
Example #25
Source File: demo-full-screen.ts    From electron-playground with MIT License 5 votes vote down vote up
isFullScreen = remote.getCurrentWindow().isFullScreen
Example #26
Source File: Mini.tsx    From electron with MIT License 5 votes vote down vote up
Wrap: React.FC<{ focus: boolean; hover: boolean }> = (props) => {
  const __size__ = 24;
  const [color, setColor] = React.useState('#dcdddd');
  const [isFullScreen, setIsFullScreen] = React.useState(remote.getCurrentWindow().isFullScreen());

  const onFunc = () => {
    !isFullScreen && remote.getCurrentWindow().minimize();
  };
  React.useEffect(() => {
    const resizeHandle = () => {
      setIsFullScreen(remote.getCurrentWindow().isFullScreen());
    };
    remote.getCurrentWindow().on('resize', resizeHandle);
    return () => {
      remote.getCurrentWindow().off('resize', resizeHandle);
    };
  }, []);
  React.useEffect(() => {
    setColor(props.focus && !isFullScreen ? '#ffbd2d' : '#dcdddd');
  }, [props.focus, isFullScreen]);
  React.useEffect(() => {
    if (isFullScreen) {
      setColor('#dcdddd');
    } else {
      setColor(props.hover ? '#666' : '#ffbd2d');
    }
  }, [props.hover, isFullScreen]);
  return (
    <>
      <span onClick={onFunc} className={props.focus && !isFullScreen ? 'focus' : 'unfocus'}>
        <svg className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6887" width={__size__} height={__size__}>
          <path d="M128 512h768a25.6 25.6 0 1 1 0 51.2h-768a25.6 25.6 0 1 1 0-51.2z" p-id="6888" fill={color}></path>
        </svg>
      </span>
      <style jsx>{`
        .focus {
          background-color: #ffbd2d;
          border: 1px solid #e0a32d;
        }
        .unfocus {
          background-color: #dcdddd;
          border: 1px solid #ced4cc;
        }
        span {
          display: flex;
          width: 12px;
          height: 12px;
          border-radius: 6px;
          justify-content: center;
          align-items: center;
          overflow: hidden;
        }
        svg {
          transform: scale(1, 2);
        }
      `}</style>
    </>
  );
}
Example #27
Source File: useWriteIpc.tsx    From Account-Manager with MIT License 5 votes vote down vote up
function useWriteIpc({
  channel,
  downloadOptions,
  extension,
  failCallback,
  payload,
  postSendCallback,
  successCallback,
}: {
  channel: IpcChannel;
  extension: 'json' | 'txt';
  downloadOptions: DownloadOptions;
  failCallback: GenericVoidFunction;
  payload: string;
  postSendCallback?: GenericVoidFunction;
  successCallback: GenericVoidFunction;
}) {
  useIpcEffect(getSuccessChannel(channel), successCallback);
  useIpcEffect(getFailChannel(channel), failCallback);

  const options: SaveDialogOptions = useMemo(
    () => ({
      buttonLabel: downloadOptions.buttonLabel,
      defaultPath: downloadOptions.defaultPath,
      filters: [
        {extensions: [extension], name: extension},
        {extensions: ['*'], name: 'All Files'},
      ],
      title: downloadOptions.title,
    }),
    [downloadOptions.buttonLabel, downloadOptions.defaultPath, downloadOptions.title, extension],
  );

  return useCallback(async (): Promise<void> => {
    remote.dialog.showSaveDialog(options).then(({canceled, filePath}) => {
      if (canceled) return;
      ipcRenderer.send(channel, {filePath, payload});
      postSendCallback?.();
    });
  }, [channel, options, payload, postSendCallback]);
}
Example #28
Source File: runAddWorkspaceWizard.tsx    From yana with MIT License 5 votes vote down vote up
runAddWorkspaceWizard = async (appDataContext: AppDataContextValue) => {
  const folderResult = await remote.dialog.showOpenDialog({
    buttonLabel: 'Load workspace',
    properties: ['openDirectory', 'createDirectory'],
    title: 'Choose the directory of a Yana workspace to add',
    message: 'Note that this directory must contain a notebook.json file',
  });

  if (folderResult.canceled || !folderResult.filePaths[0]) return;

  const folder = folderResult.filePaths[0];

  if (!(await fs.existsSync(path.join(folder, 'notebook.json')))) {
    Alerter.Instance.alert({
      confirmButtonText: 'Okay',
      content: (
        <>
          The chosen directory is not a valid Yana workspace. It must contain a <code>notebook.json</code> file.
        </>
      ),
      canOutsideClickCancel: true,
      canEscapeKeyCancel: true,
    });
    return;
  }

  const workspaceName: string = await new Promise(res => {
    Alerter.Instance.alert({
      confirmButtonText: 'Okay',
      cancelButtonText: 'Cancel',
      content: 'Choose a name for the workspace',
      canOutsideClickCancel: true,
      canEscapeKeyCancel: true,
      prompt: {
        type: 'string',
        onConfirmText: value => res(value),
      },
    });
  });

  try {
    await appDataContext.addWorkSpace(workspaceName, folder);
  } catch (e) {
    Alerter.Instance.alert({
      confirmButtonText: 'Okay',
      content: 'Error: ' + e.message,
      canOutsideClickCancel: true,
      canEscapeKeyCancel: true,
    });
  }
}
Example #29
Source File: index.tsx    From rocketredis with MIT License 5 votes vote down vote up
Header: React.FC = () => {
  const handleCloseWindow = useCallback(() => {
    const window = remote.getCurrentWindow()

    window.close()
  }, [])

  const handleMaximize = useCallback(() => {
    const window = remote.getCurrentWindow()

    const isMacSystem = os.platform() === 'darwin'
    if (isMacSystem) {
      return window.setFullScreen(!window.isFullScreen())
    }

    const { width: currentWidth, height: currentHeight } = window.getBounds()

    const {
      width: maxWidth,
      height: maxHeight
    } = remote.screen.getPrimaryDisplay().workAreaSize

    const isMaximized = currentWidth === maxWidth && currentHeight === maxHeight

    if (!isMaximized) {
      window.maximize()
    } else {
      window.unmaximize()
    }
  }, [])

  const handleMinimize = useCallback(() => {
    const window = remote.getCurrentWindow()

    window.minimize()
  }, [])

  const useMacOSWindowActionButtons = useConfig('useMacOSWindowActionButtons')

  const shouldUseMacOSWindowActions = useMemo(() => {
    return useMacOSWindowActionButtons || os.platform() === 'darwin'
  }, [useMacOSWindowActionButtons])

  return (
    <Container>
      <strong>Rocket Redis</strong>

      {shouldUseMacOSWindowActions ? (
        <WindowActions position="left" shouldShowIconsOnHover>
          <MacActionButton color="close" onClick={handleCloseWindow}>
            <FiX />
          </MacActionButton>
          <MacActionButton color="minimize" onClick={handleMinimize}>
            <FiMinus />
          </MacActionButton>
          <MacActionButton color="maximize" onClick={handleMaximize}>
            <FiMaximize2 />
          </MacActionButton>
        </WindowActions>
      ) : (
        <WindowActions position="right">
          <DefaultActionButton onClick={handleMinimize}>
            <FiMinus />
          </DefaultActionButton>
          <DefaultActionButton onClick={handleMaximize}>
            <FiSquare />
          </DefaultActionButton>
          <DefaultActionButton onClick={handleCloseWindow}>
            <FiX />
          </DefaultActionButton>
        </WindowActions>
      )}
    </Container>
  )
}