The `.gitignore` was too aggressive and new files under `docs/latest`
weren't added. Now we ignore the `vXX-y-z` folders.

Also tweaked the `sidebars.js` creation process so new tutorials are
added under `How To` instead of creating a new section.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Rel #95
This commit is contained in:
Antón Molleda 2021-10-22 09:34:52 -07:00
Родитель 1078ea54bc
Коммит 707718fa7a
8 изменённых файлов: 466 добавлений и 18 удалений

3
.gitignore поставляемый
Просмотреть файл

@ -8,5 +8,4 @@ build/
content/
i18n/
!i18n/en/
docs/
!docs/latest
docs/v**

Просмотреть файл

@ -0,0 +1,178 @@
---
title: "Creating a New Electron Browser Module"
description: "Welcome to the Electron API guide! If you are unfamiliar with creating a new Electron API module within the browser directory, this guide serves as a checklist for some of the necessary steps that you will need to implement."
slug: creating-api
hide_title: false
---
# Creating a New Electron Browser Module
Welcome to the Electron API guide! If you are unfamiliar with creating a new Electron API module within the [`browser`](https://github.com/electron/electron/tree/main/shell/browser) directory, this guide serves as a checklist for some of the necessary steps that you will need to implement.
This is not a comprehensive end-all guide to creating an Electron Browser API, rather an outline documenting some of the more unintuitive steps.
## Add your files to Electron's project configuration
Electron uses [GN](https://gn.googlesource.com/gn) as a meta build system to generate files for its compiler, [Ninja](https://ninja-build.org/). This means that in order to tell Electron to compile your code, we have to add your API's code and header file names into [`filenames.gni`](https://github.com/electron/electron/blob/main/filenames.gni).
You will need to append your API file names alphabetically into the appropriate files like so:
```cpp title='filenames.gni'
lib_sources = [
"path/to/api/api_name.cc",
"path/to/api/api_name.h",
]
lib_sources_mac = [
"path/to/api/api_name_mac.h",
"path/to/api/api_name_mac.mm",
]
lib_sources_win = [
"path/to/api/api_name_win.cc",
"path/to/api/api_name_win.h",
]
lib_sources_linux = [
"path/to/api/api_name_linux.cc",
"path/to/api/api_name_linux.h",
]
```
Note that the Windows, macOS and Linux array additions are optional and should only be added if your API has specific platform implementations.
## Create API documentation
Type definitions are generated by Electron using [`@electron/docs-parser`](https://github.com/electron/docs-parser) and [`@electron/typescript-definitions`](https://github.com/electron/typescript-definitions). This step is necessary to ensure consistency across Electron's API documentation. This means that for your API type definition to appear in the `electron.d.ts` file, we must create a `.md` file. Examples can be found in [this folder](https://github.com/electron/electron/tree/main/docs/api).
## Set up `ObjectTemplateBuilder` and `Wrappable`
Electron constructs its modules using [`object_template_builder`](https://www.electronjs.org/blog/from-native-to-js#mateobjecttemplatebuilder).
[`wrappable`](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/gin/wrappable.h) is a base class for C++ objects that have corresponding v8 wrapper objects.
Here is a basic example of code that you may need to add, in order to incorporate `object_template_builder` and `wrappable` into your API. For further reference, you can find more implementations [here](https://github.com/electron/electron/tree/main/shell/browser/api).
In your `api_name.h` file:
```cpp title='api_name.h'
#ifndef SHELL_BROWSER_API_ELECTRON_API_{API_NAME}_H_
#define SHELL_BROWSER_API_ELECTRON_API_{API_NAME}_H_
#include "gin/handle.h"
#include "gin/wrappable.h"
namespace electron {
namespace api {
class ApiName : public gin::Wrappable<ApiName> {
public:
static gin::Handle<ApiName> Create(v8::Isolate* isolate);
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
const char* GetTypeName() override;
} // namespace api
} // namespace electron
```
In your `api_name.cc` file:
```cpp title='api_name.cc'
#include "shell/browser/api/electron_api_safe_storage.h"
#include "shell/browser/browser.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/platform_util.h"
namespace electron {
namespace api {
gin::WrapperInfo ApiName::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::ObjectTemplateBuilder ApiName::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::ObjectTemplateBuilder(isolate)
.SetMethod("methodName", &ApiName::methodName);
}
const char* ApiName::GetTypeName() {
return "ApiName";
}
// static
gin::Handle<ApiName> ApiName::Create(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, new ApiName());
}
} // namespace api
} // namespace electron
namespace {
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("apiName", electron::api::ApiName::Create(isolate));
}
} // namespace
```
## Link your Electron API with Node
In the [`typings/internal-ambient.d.ts`](https://github.com/electron/electron/blob/main/typings/internal-ambient.d.ts) file, we need to append a new property onto the `Process` interface like so:
```ts title='typings/internal-ambient.d.ts'
interface Process {
_linkedBinding(name: 'electron_browser_{api_name}', Electron.ApiName);
}
```
At the very bottom of your `api_name.cc` file:
```cpp title='api_name.cc'
NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_{api_name},Initialize)
```
In your [`shell/common/node_bindings.cc`](https://github.com/electron/electron/blob/main/shell/common/node_bindings.cc) file, add your node binding name to Electron's built-in modules.
```cpp title='shell/common/node_bindings.cc'
#define ELECTRON_BUILTIN_MODULES(V) \
V(electron_browser_{api_name})
```
> Note: More technical details on how Node links with Electron can be found on [our blog](https://www.electronjs.org/blog/electron-internals-using-node-as-a-library#link-node-with-electron).
## Expose your API to TypeScript
### Export your API as a module
We will need to create a new TypeScript file in the path that follows:
`"lib/browser/api/{electron_browser_{api_name}}.ts"`
An example of the contents of this file can be found [here](https://github.com/electron/electron/blob/main/lib/browser/api/native-image.ts).
### Expose your module to TypeScript
Add your module to the module list found at `"lib/browser/api/module-list.ts"` like so:
```typescript title='lib/browser/api/module-list.ts'
export const browserModuleList: ElectronInternal.ModuleEntry[] = [
{ name: 'apiName', loader: () => require('./api-name') },
];
```

Просмотреть файл

@ -0,0 +1,278 @@
---
title: "Window Customization"
description: "The BrowserWindow module is the foundation of your Electron application, and it exposes many APIs that can change the look and behavior of your browser windows. In this tutorial, we will be going over the various use-cases for window customization on macOS, Windows, and Linux."
slug: window-customization
hide_title: false
---
# Window Customization
The `BrowserWindow` module is the foundation of your Electron application, and it exposes
many APIs that can change the look and behavior of your browser windows. In this
tutorial, we will be going over the various use-cases for window customization on
macOS, Windows, and Linux.
## Create frameless windows
A frameless window is a window that has no [chrome]. Not to be confused with the Google
Chrome browser, window _chrome_ refers to the parts of the window (e.g. toolbars, controls)
that are not a part of the web page.
To create a frameless window, you need to set `frame` to `false` in the `BrowserWindow`
constructor.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ frame: false })
```
## Apply custom title bar styles _macOS_ _Windows_
Title bar styles allow you to hide most of a BrowserWindow's chrome while keeping the
system's native window controls intact and can be configured with the `titleBarStyle`
option in the `BrowserWindow` constructor.
Applying the `hidden` title bar style results in a hidden title bar and a full-size
content window.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'hidden' })
```
### Control the traffic lights _macOS_
On macOS, applying the `hidden` title bar style will still expose the standard window
controls (“traffic lights”) in the top left.
#### Customize the look of your traffic lights _macOS_
The `customButtonsOnHover` title bar style will hide the traffic lights until you hover
over them. This is useful if you want to create custom traffic lights in your HTML but still
use the native UI to control the window.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'customButtonsOnHover' })
```
#### Customize the traffic light position _macOS_
To modify the position of the traffic light window controls, there are two configuration
options available.
Applying `hiddenInset` title bar style will shift the vertical inset of the traffic lights
by a fixed amount.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'hiddenInset' })
```
If you need more granular control over the positioning of the traffic lights, you can pass
a set of coordinates to the `trafficLightPosition` option in the `BrowserWindow`
constructor.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
trafficLightPosition: { x: 10, y: 10 }
})
```
#### Show and hide the traffic lights programmatically _macOS_
You can also show and hide the traffic lights programmatically from the main process.
The `win.setWindowButtonVisibility` forces traffic lights to be show or hidden depending
on the value of its boolean parameter.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
// hides the traffic lights
win.setWindowButtonVisibility(false)
```
> Note: Given the number of APIs available, there are many ways of achieving this. For instance,
> combining `frame: false` with `win.setWindowButtonVisibility(true)` will yield the same
> layout outcome as setting `titleBarStyle: 'hidden'`.
## Window Controls Overlay _macOS_ _Windows_
The [Window Controls Overlay API] is a web standard that gives web apps the ability to
customize their title bar region when installed on desktop. Electron exposes this API
through the `BrowserWindow` constructor option `titleBarOverlay`.
This option only works whenever a custom `titlebarStyle` is applied on macOS or Windows.
When `titleBarOverlay` is enabled, the window controls become exposed in their default
position, and DOM elements cannot use the area underneath this region.
The `titleBarOverlay` option accepts two different value formats.
Specifying `true` on either platform will result in an overlay region with default
system colors:
```javascript title='main.js'
// on macOS or Windows
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
titleBarOverlay: true
})
```
On Windows, you can also specify the color of the overlay and its symbols by setting
`titleBarOverlay` to an object with the `color` and `symbolColor` properties. If an option
is not specified, the color will default to its system color for the window control buttons:
```javascript title='main.js'
// on Windows
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
titleBarOverlay: {
color: '#2f3241',
symbolColor: '#74b1be'
}
})
```
> Note: Once your title bar overlay is enabled from the main process, you can access the overlay's
> color and dimension values from a renderer using a set of readonly
> [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars].
## Create transparent windows
By setting the `transparent` option to `true`, you can make a fully transparent window.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ transparent: true })
```
### Limitations
* You cannot click through the transparent area. See
[#1335](https://github.com/electron/electron/issues/1335) for details.
* Transparent windows are not resizable. Setting `resizable` to `true` may make
a transparent window stop working on some platforms.
* The CSS [`blur()`] filter only applies to the window's web contents, so there is no way to apply
blur effect to the content below the window (i.e. other applications open on
the user's system).
* The window will not be transparent when DevTools is opened.
* On _Windows_:
* Transparent windows will not work when DWM is disabled.
* Transparent windows can not be maximized using the Windows system menu or by double
clicking the title bar. The reasoning behind this can be seen on
PR [#28207](https://github.com/electron/electron/pull/28207).
* On _macOS_:
* The native window shadow will not be shown on a transparent window.
## Create click-through windows
To create a click-through window, i.e. making the window ignore all mouse
events, you can call the [win.setIgnoreMouseEvents(ignore)][ignore-mouse-events]
API:
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.setIgnoreMouseEvents(true)
```
### Forward mouse events _macOS_ _Windows_
Ignoring mouse messages makes the web contents oblivious to mouse movement,
meaning that mouse movement events will not be emitted. On Windows and macOS, an
optional parameter can be used to forward mouse move messages to the web page,
allowing events such as `mouseleave` to be emitted:
```javascript title='main.js'
const { BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
ipcMain.on('set-ignore-mouse-events', (event, ...args) => {
const win = BrowserWindow.fromWebContents(event.sender)
win.setIgnoreMouseEvents(...args)
})
```
```javascript title='preload.js'
window.addEventListener('DOMContentLoaded', () => {
const el = document.getElementById('clickThroughElement')
el.addEventListener('mouseenter', () => {
ipcRenderer.send('set-ignore-mouse-events', true, { forward: true })
})
el.addEventListener('mouseleave', () => {
ipcRenderer.send('set-ignore-mouse-events', false)
})
})
```
This makes the web page click-through when over the `#clickThroughElement` element,
and returns to normal outside it.
## Set custom draggable region
By default, the frameless window is non-draggable. Apps need to specify
`-webkit-app-region: drag` in CSS to tell Electron which regions are draggable
(like the OS's standard titlebar), and apps can also use
`-webkit-app-region: no-drag` to exclude the non-draggable area from the
draggable region. Note that only rectangular shapes are currently supported.
To make the whole window draggable, you can add `-webkit-app-region: drag` as
`body`'s style:
```css title='styles.css'
body {
-webkit-app-region: drag;
}
```
And note that if you have made the whole window draggable, you must also mark
buttons as non-draggable, otherwise it would be impossible for users to click on
them:
```css title='styles.css'
button {
-webkit-app-region: no-drag;
}
```
If you're only setting a custom titlebar as draggable, you also need to make all
buttons in titlebar non-draggable.
### Tip: disable text selection
When creating a draggable region, the dragging behavior may conflict with text selection.
For example, when you drag the titlebar, you may accidentally select its text contents.
To prevent this, you need to disable text selection within a draggable area like this:
```css
.titlebar {
-webkit-user-select: none;
-webkit-app-region: drag;
}
```
### Tip: disable context menus
On some platforms, the draggable area will be treated as a non-client frame, so
when you right click on it, a system menu will pop up. To make the context menu
behave correctly on all platforms, you should never use a custom context menu on
draggable areas.
[`blur()`]: https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/blur()
[`BrowserWindow`]: latest/api/browser-window.md
[chrome]: https://developer.mozilla.org/en-US/docs/Glossary/Chrome
[ignore-mouse-events]: latest/api/browser-window.md#winsetignoremouseeventsignore-options
[overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables
[overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
[Window Controls Overlay API]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md

Просмотреть файл

@ -10,7 +10,7 @@
"i18n:build": "node scripts/i18n-build.js",
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "yarn pre-build && docusaurus build --locale en",
"build": "docusaurus build --locale en",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",

Просмотреть файл

@ -19,6 +19,8 @@ const IGNORE_LIST = [
'api/synopsis',
];
const categoryAliases = new Map([['Tutorial', 'How To']]);
/**
* @typedef Entry
* @property {string} type
@ -50,11 +52,13 @@ const capitalize = (title) => {
const findCategoryForDocument = (categoryName, sidebars, defaultTopLevel) => {
const topLevelIds = Object.keys(sidebars);
const categoryAlias = categoryAliases.get(categoryName) || categoryName;
for (const topLevelId of topLevelIds) {
const entries = sidebars[topLevelId];
for (const category of entries) {
if (category.type === 'category' && category.label === categoryName) {
if (category.type === 'category' && category.label === categoryAlias) {
return category;
}
}

Просмотреть файл

@ -21,7 +21,7 @@ const { createPR } = require('../git-commands.js');
describe('git-commands', () => {
it('creates a new PR if there are no PRs opened', async () => {
executeMock.execute.mockResolvedValue();
executeMock.execute.mockResolvedValue({ stdout: '' });
octokitMock.pulls.list.mockResolvedValue({ data: [] });
octokitMock.pulls.create.mockResolvedValue({ data: { id: 42 } });
@ -38,7 +38,7 @@ describe('git-commands', () => {
});
it('force pushes to the branch if there is already a PR', async () => {
executeMock.execute.mockResolvedValue();
executeMock.execute.mockResolvedValue({ stdout: '' });
octokitMock.pulls.list.mockResolvedValue({
data: [{ head: { ref: 'mock-branch' } }],
});

Просмотреть файл

@ -35,6 +35,7 @@ module.exports = {
'latest/tutorial/updates',
'latest/tutorial/web-embeds',
'latest/tutorial/windows-arm',
'latest/tutorial/window-customization',
'latest/tutorial/windows-taskbar',
'latest/tutorial/tray',
],
@ -126,13 +127,6 @@ module.exports = {
'latest/development/v8-development',
],
},
{
type: 'category',
label: 'Tutorial',
items: [
'latest/tutorial/window-customization',
],
},
],
api: [
{

Просмотреть файл

@ -3,10 +3,5 @@
"label": "Current",
"href": "/docs/latest",
"target": "_self"
},
{
"label": "main",
"href": "https://electronjs.org/docs/main",
"target": "_blank"
}
]