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

53 постов с тегом "версия"

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

What's new in Electron 0.37

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

Electron 0.37 was recently released and included a major upgrade from Chrome 47 to Chrome 49 and also several new core APIs. This latest release brings in all the new features shipped in Chrome 48 and Chrome 49. This includes CSS custom properties, increased ES6 support, KeyboardEvent improvements, Promise improvements, and many other new features now available in your Electron app.


What's New​

CSS Custom Properties​

If you've used preprocessed languages like Sass and Less, you're probably familiar with variables, which allow you to define reusable values for things like color schemes and layouts. Variables help keep your stylesheets DRY and more maintainable.

CSS custom properties are similar to preprocessed variables in that they are reusable, but they also have a unique quality that makes them even more powerful and flexible: they can be manipulated with JavaScript. This subtle but powerful feature allows for dynamic changes to visual interfaces while still benefitting from CSS's hardware acceleration, and reduced code duplication between your frontend code and stylesheets.

For more info on CSS custom properties, see the MDN article and the Google Chrome demo.

CSS Variables In Action​

Let's walk through a simple variable example that can be tweaked live in your app.

:root {
--awesome-color: #a5ecfa;
}

body {
background-color: var(--awesome-color);
}

The variable value can be retrieved and changed directly in JavaScript:

// Get the variable value ' #A5ECFA'
let color = window
.getComputedStyle(document.body)
.getPropertyValue('--awesome-color');

// Set the variable value to 'orange'
document.body.style.setProperty('--awesome-color', 'orange');

The variable values can be also edited from the Styles section of the development tools for quick feedback and tweaks:

Свойства CSS на вкладке Styles

KeyboardEvent.code Property​

Chrome 48 added the new code property available on KeyboardEvent events that will be the physical key pressed independent of the operating system keyboard layout.

This should make implementing custom keyboard shortcuts in your Electron app more accurate and consistent across machines and configurations.

window.addEventListener('keydown', function (event) {
console.log(`${event.code} was pressed.`);
});

Check out this example to see it in action.

Promise Rejection Events​

Chrome 49 added two new window events that allow you to be notified when an rejected Promise goes unhandled.

window.addEventListener('unhandledrejection', function (event) {
console.log('A rejected promise was unhandled', event.promise, event.reason);
});

window.addEventListener('rejectionhandled', function (event) {
console.log('A rejected promise was handled', event.promise, event.reason);
});

Check out this example to see it in action.

ES2015 Updates in V8​

The version of V8 now in Electron incorporates 91% of ES2015. Here are a few interesting additions you can use out of the box—without flags or pre-compilers:

Default parameters​

function multiply(x, y = 1) {
return x * y;
}

multiply(5); // 5

Деструктирующее присваивание​

Chrome 49 added destructuring assignment to make assigning variables and function parameters much easier.

This makes Electron requires cleaner and more compact to assign now:

Browser Process Requires​
const { app, BrowserWindow, Menu } = require('electron');
Renderer Process Requires​
const { dialog, Tray } = require('electron').remote;
Other Examples​
// Destructuring an array and skipping the second element
const [first, , last] = findAll();

// Destructuring function parameters
function whois({ displayName: displayName, fullName: { firstName: name } }) {
console.log(`${displayName} is ${name}`);
}

let user = {
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe',
},
};
whois(user); // "jdoe is John"

// Destructuring an object
let { name, avatar } = getUser();

Новые API Electron​

Ниже приведены некоторые из новых API Electron, а также вы можете ознакомиться с каждым новым API в примечаниях к релизам Electron releases.

События show и hide для BrowserWindow​

Эти события происходят, когда окно показывается или скрывается.

const { BrowserWindow } = require('electron');

let window = new BrowserWindow({ width: 500, height: 500 });
window.on('show', function () {
console.log('Окно было отображено');
});
window.on('hide', function () {
console.log('Окно было скрыто');
});

platform-theme-changed на app для OS X​

Это событие возникает, когда переключается системная тема Dark Mode.

const { app } = require('electron');

app.on('platform-theme-changed', function () {
console.log(`Тема платформы изменена. Тёмный режим? ${app.isDarkMode()}`);
});

app.isDarkMode() для OS X​

Этот метод возвращает true, если система находится в темном режиме, и false в противном случае.

События scroll-touch-begin и scroll-touch-end в BrowserWindow для OS X​

Эти события возникают, когда начинается или заканчивается фаза событий при прокрутке.

const { BrowserWindow } = require('electron');

let window = new BrowserWindow({ width: 500, height: 500 });
window.on('scroll-touch-begin', function () {
console.log('Прокрутка касанием началась');
});
window.on('scroll-touch-end', function () {
console.log(''Прокрутка касанием закончилась'');
});

API Changes Coming in Electron 1.0

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

Since the beginning of Electron, starting way back when it used to be called Atom-Shell, we have been experimenting with providing a nice cross-platform JavaScript API for Chromium's content module and native GUI components. The APIs started very organically, and over time we have made several changes to improve the initial designs.


Now with Electron gearing up for a 1.0 release, we'd like to take the opportunity for change by addressing the last niggling API details. The changes described below are included in 0.35.x, with the old APIs reporting deprecation warnings so you can get up to date for the future 1.0 release. An Electron 1.0 won't be out for a few months so you have some time before these changes become breaking.

Deprecation warnings​

By default, warnings will show if you are using deprecated APIs. To turn them off you can set process.noDeprecation to true. To track the sources of deprecated API usages, you can set process.throwDeprecation to true to throw exceptions instead of printing warnings, or set process.traceDeprecation to true to print the traces of the deprecations.

New way of using built-in modules​

Встроенные модули теперь сгруппированы в один модуль, а не разделены на независимые модули, так что вы можете использовать их без конфликтов с другими модулями:

var app = require('electron').app;
var BrowserWindow = require('electron').BrowserWindow;

The old way of require('app') is still supported for backward compatibility, but you can also turn if off:

require('electron').hideInternalModules();
require('app'); // throws error.

An easier way to use the remote module​

Because of the way using built-in modules has changed, we have made it easier to use main-process-side modules in renderer process. You can now just access remote's attributes to use them:

// New way.
var app = require('electron').remote.app;
var BrowserWindow = require('electron').remote.BrowserWindow;

Instead of using a long require chain:

// Old way.
var app = require('electron').remote.require('app');
var BrowserWindow = require('electron').remote.require('BrowserWindow');

Splitting the ipc module​

The ipc module existed on both the main process and renderer process and the API was different on each side, which is quite confusing for new users. We have renamed the module to ipcMain in the main process, and ipcRenderer in the renderer process to avoid confusion:

// В main процессе.
var ipcMain = require('electron').ipcMain;
// In renderer process.
var ipcRenderer = require('electron').ipcRenderer;

And for the ipcRenderer module, an extra event object has been added when receiving messages, to match how messages are handled in ipcMain modules:

ipcRenderer.on('message', function (event) {
console.log(event);
});

Standardizing BrowserWindow options​

The BrowserWindow options had different styles based on the options of other APIs, and were a bit hard to use in JavaScript because of the - in the names. They are now standardized to the traditional JavaScript names:

new BrowserWindow({ minWidth: 800, minHeight: 600 });

Following DOM's conventions for API names​

The API names in Electron used to prefer camelCase for all API names, like Url to URL, but the DOM has its own conventions, and they prefer URL to Url, while using Id instead of ID. We have done the following API renames to match the DOM's styles:

  • Url is renamed to URL
  • Csp is renamed to CSP

You will notice lots of deprecations when using Electron v0.35.0 for your app because of these changes. An easy way to fix them is to replace all instances of Url with URL.

Changes to Tray's event names​

The style of Tray event names was a bit different from other modules so a rename has been done to make it match the others.

  • clicked is renamed to click
  • double-clicked is renamed to double-click
  • right-clicked is renamed to right-click

Что нового в Electron

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

В последнее время были интересные обновления и разговоры про Electron, вот их сводка.


Источник​

Electron теперь обновлен до версии Chrome 45 по состоянию на v0.32.0. Другие обновления включают...

Лучшая документация​

новая документация

Мы изменили структуру и стандартизировали документацию, с тем чтобы она лучше выглядела и лучше читалась. Существуют также переводы документации, внесенные общинами, такие, как японский и корейский.

Похожие pull requests: electron/electron#2028, electron/electron#2533, electron/electron#2557, electron/electron#2709, electron/electron#2725, electron/electron#2698, electron/electron#2649.

Node.js 4.1.0​

Начиная с v0.33.0 Electron поставляется с Node.js 4.1.0.

Похожие pull requests: electron/electron#2817.

node-pre-gyp​

Теперь модули, основанные на node-pre-gyp, могут быть скомпилированы без Electron при сборке из исходного кода.

Похожие pull requests: mapbox/node-pre-gyp#175.

Поддержка ARM​

Electron теперь предоставляет сборки для Linux на ARMv7. Он работает на популярных платформах, таких как Chromebook и Raspberry Pi 2.

Связанные вопросы: atom/libchromiumcontent#138, electron/electron#2094, electron/electron#366.

Безрамное окно в стиле Yosemite​

безрамное окно

Патч от @jaanus объединен с другими встроенными приложениями OS X, позволяет создавать ненужные окна с системными светофорами на OS X Yosemite и более поздней версии.

Похожие pull requests: electron/electron#2776.

Поддержка печати Google Summer of Code​

После Google Summer of Code мы объединили патчи на [@hokein](https://github. com/hokein), чтобы улучшить поддержку печати, и добавили возможность печати страницы в PDF файлы.

Связанные вопросы: Электрон/электрон#2677, электрон/электрон#1935, электрон/электрон#1532, electron/electron#805, electron/electron#1669, electron/electron#1835.

Atom​

Atom обновлен до v0.30.6 с Chrome 44. Идет обновление до v0.33.0 на atom/atom#8779.

Talks​

GitHubber Amy Palamountain дал отличное представление о Electron в разговоре на Nordic.js. Она также создала библиотеку electron-accelerator

Создание нативных приложений с Electron от Amy Palomountain​

Ben Ogle, также команда Atom опубликовала доклад Electron на Азии YAPC:

Создание настольных приложений с помощью веб-технологий от Ben Ogle​

Участник команды Atom Кевин Савицки (Kevin Sawicki) и другие недавно выступили с докладами об Electron на встрече Bay Area Electron User Group видео были опубликованы этими людьми:

История Electron от Кевина Савицки​

Заставить веб-приложение чувствовать себя нативными благодаря Бен Гооу​