Перейти к основному содержанию

5 постов с тегом "Функции"

Showcasing new features in Electron core

Показать все теги

Introducing electron/rfcs

· 3 мин. прочитано

Electron’s API Working Group is adopting an open Requests for Comments (RFC) process to help shepherd larger changes to Electron core.

Why RFCs?

In short, we want to smooth out the process of landing significant changes to Electron core.

Currently, new code changes are mostly discussed through issues and pull requests on GitHub. For most changes to Electron, this is a good system. Many bug fixes, documentation changes, and even new features are straightforward enough to review and merge asynchronously through standard GitHub flows.

For changes that are more significant—for instance, large API surfaces or breaking changes that would affect the majority of Electron apps—it makes sense for review to happen at the ideation stage before most of the code is written.

This process is designed to be open to the public, which will also make it easier for the open source community at large to give feedback on potential changes before they land in Electron.

Как это работает?

The entire RFC process lives in the electron/rfcs repository on GitHub. The steps are described in detail in the repository README.

In brief, an RFC is Proposed once a PR is made to the electron/rfcs repository. A Proposed RFC becomes:

  • Active when the PR is merged into the main branch of the repository, which means that Electron maintainers are amenable to an implementation in electron/electron, or
  • Declined if the PR is ultimately rejected.
информация

For the RFC to become Active, the PR must be approved by at least 2 API Working Group members. Before merging, the RFC should be presented synchronously and accepted unanimously by a quorum of at least two-thirds of the WG members. If consensus is reached, a one-month final comment period will be triggered, after which the PR will be merged.

An Active RFC is Completed if the implementation has been merged into electron/electron.

Who can participate?

Anyone in the Electron community can submit RFCs or leave feedback on the electron/rfcs repository!

We wanted to make this process a two-way dialogue and encourage community participation to get a diverse set of opinions from Electron apps that might consume these APIs in the future. If you’re interested in leaving feedback on currently proposed RFCs, the Electron maintainers have already created a few:

Credits

Electron's RFC process was modeled on many established open source RFC processes. Inspiration for many ideas and major portions of copywriting go to:

Поддержка Silicon Apple

· 3 мин. прочитано

С Apple Silicon аппаратное обеспечение, выпускается позднее в этом году, как выглядит путь для того, чтобы приложение Electron запущено на новом оборудовании?


С выпуском Electron 11.0.0-beta., команда Electron в настоящее время поставляет сборки Electron, которые работают на новом аппаратном обеспечении Apple Silicon, которое Apple планирует осуществлять доставку позднее в этом году. Вы можете получить последнюю бета-версию с npm install electron@beta или загрузить ее непосредственно с нашего сайта релизов.

Как это работает?

Начиная с Electron 11, мы будем отправлять отдельные версии Electron для Intel Macs и Apple Silicon Mac. До этого изменения мы уже были доставлены два артефакта: darwin-x64 и mas-x64, причем последнее использовалось для Mac App Store. Теперь мы доставляем еще два артефакта: darwin-arm64 и mas-arm64, которые являются Apple Silicon эквивалентами вышеупомянутых артефактов.

Что вам нужно сделать?

Вам нужно будет отправить две версии приложения: одну для x64 (Intel Mac) и одну для arm64 (Apple Silicon). Для большинства пользователей это просто, потому "из коробки" поддерживаются electron-packager, electron-rebuildelectron-forge. До тех пор, пока вы используете последние версии этих пакетов, ваше приложение должно работать безупречно, как только вы обновите целевую архитектуру до arm64.


Обновление: Этот пакет теперь доступен на [`@electron/universal`](https://github.com/electron/universal). You can use it to merge two packaged x64 and arm64 apps into a single binary.

## Potential Issues

### Native Modules

As you are targeting a new architecture, you'll need to update several dependencies which may cause build issues. The minimum version of certain dependencies are included below for your reference.

| Dependency | Version Requirement |
| ------------------- | ------------------- |
| Xcode | `>=12.2.0` |
| `node-gyp` | `>=7.1.0` |
| `electron-rebuild` | `>=1.12.0` |
| `electron-packager` | `>=15.1.0` |

As a result of these dependency version requirements, you may have to fix/update certain native modules. One thing of note is that the Xcode upgrade will introduce a new version of the macOS SDK, which may cause build failures for your native modules.

## How do I test it?

Currently, Apple Silicon applications only run on Apple Silicon hardware, which isn't commercially available at the time of writing this blog post. If you have a [Developer Transition Kit](https://developer.apple.com/programs/universal/), you can test your application on that. Otherwise, you'll have to wait for the release of production Apple Silicon hardware to test if your application works.

## What about Rosetta 2?

Rosetta 2 is Apple's latest iteration of their [Rosetta](https://en.wikipedia.org/wiki/Rosetta_(software)) technology, which allows you to run x64 Intel applications on their new arm64 Apple Silicon hardware. Although we believe that x64 Electron apps will run under Rosetta 2, there are some important things to note (and reasons why you should ship a native arm64 binary).

- Your app's performance will be significantly degraded. Electron / V8 uses [JIT](https://en.wikipedia.org/wiki/Just-in-time_compilation) compilation for JavaScript, and due to how Rosetta works, you will effectively be running JIT twice (once in V8 and once in Rosetta).
- You lose the benefit of new technology in Apple Silicon, such as the increased memory page size.
- Did we mention that the performance will be **significantly** degraded?

New in Electron 2: In-App Purchases

· 2 мин. прочитано

The new Electron 2.0 release line is packed with new features and fixes. One of the highlights from this new major version is a new inAppPurchase API for Apple's Mac App Store.


In-app purchases enable content or subscriptions to be purchased directly from within apps. This gives developers an easy way to embrace the freemium business model, wherein users pay nothing to download an app and are offered optional in-app purchases for premium features, additional content, or subscriptions.

The new API was added to Electron by community contributor Adrien Fery to enable in-app purchases in Amanote, a note-taking Electron app for lectures and conferences. Amanote is free to download and allows clear and structured notes to be added to PDFs, with features like mathematical formulae, drawings, audio recording, and more.

Since adding in-app purchase support to the Mac version of Amanote, Adrien has noted a 40% increase in sales!

Начало работы

The new inAppPurchase API has already landed in the latest Electron beta:

npm i -D electron@beta

The docs for the API can be found on GitHub, and Adrien has been kind enough to write a tutorial on how to use the API. To get started adding in-app purchases to your app, see the tutorial.

More improvements to the API are in the works, and will soon be landing in an upcoming Electron beta release.

Windows Could Be Next

Up next, Adrien is hoping to open a new revenue channel for Amanote by adding support for Microsoft Store in-app purchases in Electron. Stay tuned for developments on that!

Touch Bar Support

· 3 мин. прочитано

Electron 1.6.3 бета-версия содержит первоначальную поддержку macOS Touch Bar.


The new Touch Bar API allows you to add buttons, labels, popovers, color pickers, sliders, and spacers. These elements can be dynamically updated and also emit events when they are interacted with.

This is the first release of this API so it will be evolving over the next few Electron releases. Please check out the release notes for further updates and open issues for any problems or missing functionality.

You can install this version via npm install electron@beta and learn more about it in the TouchBar and BrowserWindow Electron docs.

Big thanks to @MarshallOfSound for contributing this to Electron. 🎉

Touch Bar Example

Touch Bar Gif

Below is an example of creating a simple slot machine game in the touch bar. It demonstrates how to create a touch bar, style the items, associate it with a window, handle button click events, and update the labels dynamically.

const { app, BrowserWindow, TouchBar } = require('electron');

const { TouchBarButton, TouchBarLabel, TouchBarSpacer } = TouchBar;

let spinning = false;

// Reel labels
const reel1 = new TouchBarLabel();
const reel2 = new TouchBarLabel();
const reel3 = new TouchBarLabel();

// Spin result label
const result = new TouchBarLabel();

// Spin button
const spin = new TouchBarButton({
label: '🎰 Spin',
backgroundColor: '#7851A9',
click: () => {
// Ignore clicks if already spinning
if (spinning) {
return;
}

spinning = true;
result.label = '';

let timeout = 10;
const spinLength = 4 * 1000; // 4 seconds
const startTime = Date.now();

const spinReels = () => {
updateReels();

if (Date.now() - startTime >= spinLength) {
finishSpin();
} else {
// Slow down a bit on each spin
timeout *= 1.1;
setTimeout(spinReels, timeout);
}
};

spinReels();
},
});

const getRandomValue = () => {
const values = ['🍒', '💎', '7️⃣', '🍊', '🔔', '⭐', '🍇', '🍀'];
return values[Math.floor(Math.random() * values.length)];
};

const updateReels = () => {
reel1.label = getRandomValue();
reel2.label = getRandomValue();
reel3.label = getRandomValue();
};

const finishSpin = () => {
const uniqueValues = new Set([reel1.label, reel2.label, reel3.label]).size;
if (uniqueValues === 1) {
// All 3 values are the same
result.label = '💰 Jackpot!';
result.textColor = '#FDFF00';
} else if (uniqueValues === 2) {
// 2 values are the same
result.label = '😍 Winner!';
result.textColor = '#FDFF00';
} else {
// No values are the same
result.label = '🙁 Spin Again';
result.textColor = null;
}
spinning = false;
};

const touchBar = new TouchBar([
spin,
new TouchBarSpacer({ size: 'large' }),
reel1,
new TouchBarSpacer({ size: 'small' }),
reel2,
new TouchBarSpacer({ size: 'small' }),
reel3,
new TouchBarSpacer({ size: 'large' }),
result,
]);

let window;

app.once('ready', () => {
window = new BrowserWindow({
frame: false,
titleBarStyle: 'hidden-inset',
width: 200,
height: 200,
backgroundColor: '#000',
});
window.loadURL('about:blank');
window.setTouchBar(touchBar);
});

Use V8 and Chromium Features in Electron

· 2 мин. прочитано

Building an Electron application means you only need to create one codebase and design for one browser, which is pretty handy. But because Electron stays up to date with Node.js and Chromium as they release, you also get to make use of the great features they ship with. In some cases this eliminates dependencies you might have previously needed to include in a web app.


There are many features and we'll cover some here as examples, but if you're interested in learning about all features you can keep an eye on the Google Chromium blog and Node.js changelogs. You can see what versions of Node.js, Chromium and V8 Electron is using at electronjs.org/#electron-versions.

ES6 Support through V8

Electron combines Chromium's rendering library with Node.js. The two share the same JavaScript engine, V8. Many ECMAScript 2015 (ES6) features are already built into V8 which means you can use them in your Electron application without any compilers.

Below are a few examples but you can also get classes (in strict mode), block scoping, promises, typed arrays and more. Check out this list for more information on ES6 features in V8.

Arrow Functions

findTime () => {
console.log(new Date())
}

String Interpolation

var octocat = 'Mona Lisa';
console.log(`The octocat's name is ${octocat}`);

New Target

Octocat() => {
if (!new.target) throw "Not new";
console.log("New Octocat");
}

// Throws
Octocat();
// Logs
new Octocat();

Array Includes

// Returns true
[1, 2].includes(2);

Rest Parameters

// Represent indefinite number of arguments as an array
(o, c, ...args) => {
console.log(args.length);
};

Chromium Features

Thanks to all the hard work Google and contributors put into Chromium, when you build Electron apps you can also use cool things like (but not limited to):

Follow along with the Google Chromium blog to learn about features as new versions ship and again, you can check the version of Chromium that Electron uses here.

What are you excited about?

Tweet to us @ElectronJS with your favorite features built into V8 or Chromium.