Skip to content

Sync with upstream @ 193319c9 #208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Oct 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
1b31575
promise chain flow
joaquinelio Aug 15, 2021
8287e24
edge
joaquinelio Aug 16, 2021
623737b
Update article.md
deisner Aug 21, 2021
22b7b51
Update article.md
Aug 26, 2021
e69a943
Update urls
imba-tjd Aug 27, 2021
08a5308
Update article.md
baooab Sep 11, 2021
1059096
Update URL.
odsantos Sep 14, 2021
df39e1a
Update article.md
vladdoroniuk Sep 14, 2021
76ef126
Fix typo
rizkyzhang Sep 22, 2021
7651ae0
minor typo
fionatagious Oct 1, 2021
2f98054
chore: fix a typo
mahdyar Oct 4, 2021
f4801c3
closes #2738
iliakan Oct 10, 2021
171d2e7
Merge pull request #2731 from mahdyar/patch-1
iliakan Oct 10, 2021
3d47402
Merge pull request #2729 from fionatagious/patch-1
iliakan Oct 10, 2021
5c1ee32
Merge pull request #2725 from rizkyzhang/patch-6
iliakan Oct 10, 2021
1c63023
Merge pull request #2721 from xirly/master
iliakan Oct 10, 2021
9e4a1e9
Merge pull request #2720 from odsantos/object-references
iliakan Oct 10, 2021
8794b71
Merge pull request #2717 from baooab/patch-9
iliakan Oct 10, 2021
2e494c7
Merge pull request #2697 from joaquinelio/patch-4
iliakan Oct 10, 2021
f1210b4
minor
iliakan Oct 10, 2021
cbc4350
Merge pull request #2698 from joaquinelio/patch-5
iliakan Oct 10, 2021
0d67376
Merge pull request #2701 from deisner/patch-1
iliakan Oct 10, 2021
ab2c57c
Merge pull request #2704 from wilburn98/master
iliakan Oct 10, 2021
193319c
Merge pull request #2705 from imba-tjd/patch-1
iliakan Oct 10, 2021
0591efc
merging all conflicts
iliakan Oct 11, 2021
227af85
Sync with upstream @ 193319c9
tarasyyyk Oct 11, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions 1-js/01-getting-started/1-intro/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@

Різні рушії мають різні "кодові назви". Наприклад:

- [V8](https://uk.wikipedia.org/wiki/V8_(рушій_JavaScript)) -- в Chrome і Opera.
- [V8](https://uk.wikipedia.org/wiki/V8_(рушій_JavaScript)) -- в Chrome, Opera та Edge.
- [SpiderMonkey](https://uk.wikipedia.org/wiki/SpiderMonkey) -- в Firefox.
- ...Є також інші кодові назви як "Chakra" для IE, "JavaScriptCore", "Nitro" і "SquirrelFish" для Safari, та інші.

Написані вище терміни добре було б запам’ятати, оскільки вони використовуються в статтях розробників на просторах інтернету. Ми також будемо їх використовувати. Наприклад, якщо "можливість X підтримується в V8", тоді ймовірно це буде працювати в Chrome і Opera.
Написані вище терміни добре було б запам’ятати, оскільки вони використовуються в статтях розробників на просторах інтернету. Ми також будемо їх використовувати. Наприклад, якщо "можливість X підтримується в V8", тоді ймовірно це буде працювати в Chrome, Opera та Edge.

```smart header="Як рушії працюють?"

Expand Down
1 change: 0 additions & 1 deletion 1-js/01-getting-started/3-code-editors/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ IDE завантажує проект (який може мати багато
Ось ці варіанти заслуговують вашої уваги:

- [Atom](https://atom.io/) (багатоплатформний, безкоштовний).
- [Visual Studio Code](https://code.visualstudio.com/) (багатоплатформний, безкоштовний).
- [Sublime Text](http://www.sublimetext.com) (багатоплатформний, випробувальний термін).
- [Notepad++](https://notepad-plus-plus.org/) (Windows, безкоштовний).
- [Vim](http://www.vim.org/) та [Emacs](https://www.gnu.org/software/emacs/) також хороші, якщо знати, як ними користуватися.
Expand Down
2 changes: 1 addition & 1 deletion 1-js/02-first-steps/09-comparison/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
- Більше/менше: <code>a &gt; b</code>, <code>a &lt; b</code>.
- Більше/менше або дорівнює: <code>a &gt;= b</code>, <code>a &lt;= b</code>.
- Дорівнює: `a == b`. Зверніть увагу, для порівняння потрібно використовувати два знаки рівності `==`. Один знак рівності `a = b` означав б присвоєння.
- Не дорівнює. В математиці позначається символом <code>&ne;</code>, проте в JavaScript записується як <code>a != b</code>.
- Не дорівнює: в математиці позначається символом <code>&ne;</code>, проте в JavaScript записується як <code>a != b</code>.

В цьому розділі ми вивчимо різні типи порівнянь, узнаємо, як JavaScript їх виконує, та розглянемо важливі особливості.

Expand Down
10 changes: 5 additions & 5 deletions 1-js/03-code-quality/02-coding-style/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,11 +301,11 @@ function pow(x, n) {

Ось декілька добре відомих засобів для перевірки:

- [JSLint](http://www.jslint.com/) -- один з перших лінтерів.
- [JSHint](http://www.jshint.com/) -- має більше налаштувань ніж JSLint.
- [ESLint](http://eslint.org/) -- напевно, найсучасніший лінтер.
- [JSLint](https://www.jslint.com/) -- один з перших лінтерів.
- [JSHint](https://www.jshint.com/) -- має більше налаштувань ніж JSLint.
- [ESLint](https://eslint.org/) -- напевно, найсучасніший лінтер.

Всі вони роблять свою справу. Автор використовує [ESLint](http://eslint.org/).
Всі вони роблять свою справу. Автор використовує [ESLint](https://eslint.org/).

Більшість лінтерів інтегровані в популярні редактори: просто увімкніть відповідний плаґін в редакторі і налаштуйте стиль.

Expand Down Expand Up @@ -335,7 +335,7 @@ function pow(x, n) {

Директива `"extends"` означає, що конфігурація базується на наборі налаштувань "eslint:recommended". Після цього, ви вказуєте ваші власні.

Крім того, можна завантажити набори правил з мережі та розширити їх. Дивіться <http://eslint.org/docs/user-guide/getting-started> для отримання більш детальної інструкції зі встановлення.
Крім того, можна завантажити набори правил з мережі та розширити їх. Дивіться <https://eslint.org/docs/user-guide/getting-started> для отримання більш детальної інструкції зі встановлення.

Також, деякі середовища розробки (IDE) мають вбудовані засоби первірки коду, що є зручним, але не таким гнучким в налаштуванні рішенням, як ESLint.

Expand Down
2 changes: 1 addition & 1 deletion 1-js/04-object-basics/02-object-copy/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ clone.name = "Петро"; // змінемо його вміст
alert( user.name ); // як і раніше Іван залишився в оригінальному об’єкті
```

Також ми можемо використати метод [Object.assign](mdn:js/Object/assign) для цього.
Також ми можемо використати метод [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) для цього.

Його синтаксис:

Expand Down
2 changes: 1 addition & 1 deletion 1-js/05-data-types/01-primitives-methods/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ john.sayHi(); // Привіт друже!
2. JavaScript дозволяє отримати доступ до методів та властивостей рядків, чисел, булеанів та символів.
3. Для цього створюється спеціальний "об’єкт обгортка" з додатковою функціональністю, та потім він знищується.

Для кожного примітиву створюється своя "обгортка": `String`, `Number`, `Boolean` та `Symbol`. Отже, вони містять різні набори методів.
Для кожного примітиву створюється своя "обгортка": `String`, `Number`, `Boolean`, `Symbol` та `BigInt`. Отже, вони містять різні набори методів.

Наприклад: існує такий метод для рядка, як [str.toUpperCase()](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase), який поверне рядок `str` з великими літерами.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ printReverseList(list);

# За допомогою циклу

Варіант циклу також трохи складніше, ніж прямий вивід.
Варіант з циклом також трохи складніший, ніж прямий вивід.

Немає можливості отримати останнє значення в нашому `list`. Ми також не можемо "повернутися назад".

Expand Down
6 changes: 3 additions & 3 deletions 1-js/11-async/03-promise-chaining/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ The idea is that the result is passed through the chain of `.then` handlers.

Here the flow is:
1. The initial promise resolves in 1 second `(*)`,
2. Then the `.then` handler is called `(**)`.
3. The value that it returns is passed to the next `.then` handler `(***)`
2. Then the `.then` handler is called `(**)`, which in turn creates a new promise (resolved with `2` value).
3. The next `then` `(***)` gets the result of the previous one, processes it (doubles) and passes the next handler.
4. ...and so on.

As the result is passed along the chain of handlers, we can see a sequence of `alert` calls: `1` -> `2` -> `4`.

![](promise-then-chain.svg)

The whole thing works, because a call to `promise.then` returns a promise, so that we can call the next `.then` on it.
The whole thing works, because every call to a `.then` returns a new promise, so that we can call the next `.then` on it.

When a handler returns a value, it becomes the result of that promise, so the next `.then` is called with it.

Expand Down
43 changes: 31 additions & 12 deletions 2-ui/4-forms-controls/3-events-change-input/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,31 +58,50 @@ So we can't use `event.preventDefault()` there -- it's just too late, there woul

These events occur on cutting/copying/pasting a value.

They belong to [ClipboardEvent](https://www.w3.org/TR/clipboard-apis/#clipboard-event-interfaces) class and provide access to the data that is copied/pasted.
They belong to [ClipboardEvent](https://www.w3.org/TR/clipboard-apis/#clipboard-event-interfaces) class and provide access to the data that is cut/copied/pasted.

We also can use `event.preventDefault()` to abort the action, then nothing gets copied/pasted.

For instance, the code below prevents all such events and shows what we are trying to cut/copy/paste:
For instance, the code below prevents all `cut/copy/paste` events and shows the text we're trying to cut/copy/paste:

```html autorun height=40 run
<input type="text" id="input">
<script>
input.oncut = input.oncopy = input.onpaste = function(event) {
alert(event.type + ' - ' + event.clipboardData.getData('text/plain'));
return false;
input.onpaste = function(event) {
alert("paste: " + event.clipboardData.getData('text/plain'));
event.preventDefault();
};

input.oncut = input.oncopy = function(event) {
alert(event.type + '-' + document.getSelection());
event.preventDefault();
};
</script>
```

Please note, that it's possible to copy/paste not just text, but everything. For instance, we can copy a file in the OS file manager, and paste it.
Please note: inside `cut` and `copy` event handlers a call to `event.clipboardData.getData(...)` returns an empty string. That's because technically the data isn't in the clipboard yet. If we use `event.preventDefault()` it won't be copied at all.

That's because `clipboardData` implements `DataTransfer` interface, commonly used for drag'n'drop and copy/pasting. It's bit beyond our scope now, but you can find its methods [in the specification](https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface).
So the example above uses `document.getSelection()` to get the selected text. You can find more details about document selection in the article <info:selection-range>.

```warn header="ClipboardAPI: user safety restrictions"
The clipboard is a "global" OS-level thing. So most browsers allow read/write access to the clipboard only in the scope of certain user actions for the safety, e.g. in `onclick` event handlers.
It's possible to copy/paste not just text, but everything. For instance, we can copy a file in the OS file manager, and paste it.

Also it's forbidden to generate "custom" clipboard events with `dispatchEvent` in all browsers except Firefox.
```
That's because `clipboardData` implements `DataTransfer` interface, commonly used for drag'n'drop and copy/pasting. It's bit beyond our scope now, but you can find its methods in the [DataTransfer specification](https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface).

Also, there's an additional asynchronous API of accessing the clipboard: `navigator.clipboard`. More about it in the specification [Clipboard API and events](https://www.w3.org/TR/clipboard-apis/), [not supported by Firefox](https://caniuse.com/async-clipboard).

### Safety restrictions

The clipboard is a "global" OS-level thing. A user may switch between various applications, copy/paste different things, and a browser page shouldn't see all that.

So most browsers allow seamless read/write access to the clipboard only in the scope of certain user actions, such as copying/pasting etc.

It's forbidden to generate "custom" clipboard events with `dispatchEvent` in all browsers except Firefox. And even if we manage to dispatch such event, the specification clearly states that such "syntetic" events must not provide access to the clipboard.

Even if someone decides to save `event.clipboardData` in an event handler, and then access it later -- it won't work.

To reiterate, [event.clipboardData](https://www.w3.org/TR/clipboard-apis/#clipboardevent-clipboarddata) works solely in the context of user-initiated event handlers.

On the other hand, [navigator.clipboard](https://www.w3.org/TR/clipboard-apis/#h-navigator-clipboard) is the more recent API, meant for use in any context. It asks for user permission, if needed. Not supported in Firefox.

## Summary

Expand All @@ -92,4 +111,4 @@ Data change events:
|---------|----------|-------------|
| `change`| A value was changed. | For text inputs triggers on focus loss. |
| `input` | For text inputs on every change. | Triggers immediately unlike `change`. |
| `cut/copy/paste` | Cut/copy/paste actions. | The action can be prevented. The `event.clipboardData` property gives read/write access to the clipboard. |
| `cut/copy/paste` | Cut/copy/paste actions. | The action can be prevented. The `event.clipboardData` property gives access to the clipboard. All browsers except Firefox also support `navigator.clipboard`. |
2 changes: 1 addition & 1 deletion 2-ui/5-loading/02-script-async-defer/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ In practice, `defer` is used for scripts that need the whole DOM and/or their re
And `async` is used for independent scripts, like counters or ads. And their relative execution order does not matter.

```warn header="Page without scripts should be usable"
Please note: if you're using `defer` or `async`, then user will see the the page *before* the script loads.
Please note: if you're using `defer` or `async`, then user will see the page *before* the script loads.

In such case, some graphical components are probably not initialized yet.

Expand Down
2 changes: 1 addition & 1 deletion 4-binary/02-text-decoder/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

What if the binary data is actually a string? For instance, we received a file with textual data.

The build-in [TextDecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) object allows to read the value into an actual JavaScript string, given the buffer and the encoding.
The built-in [TextDecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) object allows one to read the value into an actual JavaScript string, given the buffer and the encoding.

We first need to create it:
```js
Expand Down