1. Windows
  2. Centering a Panel Window in the Current Monitor

Windows

Centering a Panel Window in the Current Monitor

ToDesktop allows you to create panel windows in two different ways:

  1. Manually, through the ToDesktop Builder interface.
  2. Programmatically, via the npm package @todesktop/client-core.

Panel windows that are created via the Builder interface come pre-configured with additional functionality so that they behave how users expect. For example, the panel window will display in the center of the current monitor when used in multi-monitor environments.

To replicate this behaviour for panels that are created programmatically, first create the panel using the API:

        import { nativeWindow, screen } from '@todesktop/client-core';

// make sure to create window with `type` panel.
const panelWindow = await nativeWindow.create({
  width: 400,
  height: 200,
  type: 'panel',
  show: false
});

      

When you later want to display that window in the current monitor, do the following:

  1. Use the screen API to retrieve the bounds of the display nearest the cursor.
  2. Use the retrieved monitor bounds and the window's current dimensions to center the window in the monitor
  3. Show the window using the showInactive function (to ensure the panel window doesn't steal focus when it's finally revealed).
        // 1.
const cursor = await screen.getCursorScreenPoint();
const bounds = (await screen.getDisplayNearestPoint(cursor)).bounds;

// 2.
const [width, height] = await nativeWindow.getSize({ ref: panelWindow });
await nativeWindow.setPosition(
  { ref: panelWindow },
  Math.round(bounds.x + (bounds.width - width) / 2),
  Math.round(bounds.y + (bounds.height - height) / 2)
);

// 3.
await nativeWindow.showInactive({ ref: panelWindow });

      

And that's it! You can then combine this behaviour with other ToDesktop APIs to create Panel Windows that work like Spotlight or Raycast. For example, we can show and center a panel window in response to keyboard shortcuts:

        import { nativeWindow, globalShortcut, screen } from '@todesktop/client-core';

const panelWindow = await nativeWindow.create({
  width: 400,
  height: 200,
  type: 'panel',
  show: false
});

await globalShortcut.register('CommandOrControl+Shift+Space', async () => {
  const isVisible = await nativeWindow.isVisible({ ref: panelWindow });

  if (isVisible) {
    nativeWindow.hide({ ref: panelWindow });
  } else {
    const cursor = await screen.getCursorScreenPoint();
    const bounds = (await screen.getDisplayNearestPoint(cursor)).bounds;

    const [width, height] = await nativeWindow.getSize({ ref: panelWindow });
    await nativeWindow.setPosition(
      { ref: panelWindow },
      bounds.x + (bounds.width - width) / 2,
      bounds.y + (bounds.height - height) / 2
    );

    await nativeWindow.showInactive({ ref: panelWindow });
  }
});