diff --git a/content/docs/codebase-overview.md b/content/docs/codebase-overview.md index 010fdfb5d..03f8a5a8d 100644 --- a/content/docs/codebase-overview.md +++ b/content/docs/codebase-overview.md @@ -1,6 +1,6 @@ --- id: codebase-overview -title: Codebase Overview +title: Устройство кодовой базы layout: contributing permalink: docs/codebase-overview.html prev: how-to-contribute.html @@ -9,54 +9,54 @@ redirect_from: - "contributing/codebase-overview.html" --- -This section will give you an overview of the React codebase organization, its conventions, and the implementation. +В этой главе вы узнаете об устройстве кодовой базы React, используемых соглашениях и реализации. -If you want to [contribute to React](/docs/how-to-contribute.html) we hope that this guide will help you feel more comfortable making changes. +Если вы хотите [внести свой вклад в React](/docs/how-to-contribute.html), то мы надеемся, что эта глава вам поможет. -We don't necessarily recommend any of these conventions in React apps. Many of them exist for historical reasons and might change with time. +Мы считаем, что вам не обязательно следовать этим соглашениям в ваших React-приложениях. Многие из этих соглашений существуют по историческим причинам и могут быть изменены со временем. -### External Dependencies {#external-dependencies} +### Внешние зависимости {#external-dependencies} -React has almost no external dependencies. Usually, a `require()` points to a file in React's own codebase. However, there are a few relatively rare exceptions. +У React практически нет внешних зависимостей. Обычно `require()` указывает на файл из собственной кодовой базы React. Однако есть несколько исключений. -The [fbjs repository](https://github.com/facebook/fbjs) exists because React shares some small utilities with libraries like [Relay](https://github.com/facebook/relay), and we keep them in sync. We don't depend on equivalent small modules in the Node ecosystem because we want Facebook engineers to be able to make changes to them whenever necessary. None of the utilities inside fbjs are considered to be public API, and they are only intended for use by Facebook projects such as React. +[Репозиторий fbjs](https://github.com/facebook/fbjs) существует, потому что React использует общий код с такими библиотеками как [Relay](https://github.com/facebook/relay). React не имеет зависимостей от модулей из экосистемы Node, для того, чтобы разработчики Facebook могли вносить изменения тогда, когда они им необходимы. fbjs не имеет внешнего API, а все его внутренние модули используются только проектами Facebook, например React. -### Top-Level Folders {#top-level-folders} +### Папки верхнего уровня {#top-level-folders} -After cloning the [React repository](https://github.com/facebook/react), you will see a few top-level folders in it: +После клонирования [репозитория React](https://github.com/facebook/react) вы увидите папки верхнего уровня: -* [`packages`](https://github.com/facebook/react/tree/master/packages) contains metadata (such as `package.json`) and the source code (`src` subdirectory) for all packages in the React repository. **If your change is related to the code, the `src` subdirectory of each package is where you'll spend most of your time.** -* [`fixtures`](https://github.com/facebook/react/tree/master/fixtures) contains a few small React test applications for contributors. -* `build` is the build output of React. It is not in the repository but it will appear in your React clone after you [build it](/docs/how-to-contribute.html#development-workflow) for the first time. +* [`packages`](https://github.com/facebook/react/tree/master/packages) содержит метаданные (такие как `package.json`) и исходный код (подпапка `src`) для каждого пакета из репозитория React. **Большая часть работы с кодом происходит в подпапках `src` внутри каждого пакета.** +* [`fixtures`](https://github.com/facebook/react/tree/master/fixtures) содержит несколько небольших React-приложений для контрибьютеров. +* `build` содержит скомпилированную версию React. Этого каталога нет в репозитории, но он появится после того, как вы [соберёте проект](/docs/how-to-contribute.html#development-workflow) в первый раз. -The documentation is hosted [in a separate repository from React](https://github.com/reactjs/reactjs.org). +Документация расположена в [отдельном репозитории](https://github.com/reactjs/reactjs.org). -There are a few other top-level folders but they are mostly used for the tooling and you likely won't ever encounter them when contributing. +Существуют ещё несколько вспомогательных верхнеуровневых папок. Но вы, вероятно, не столкнётесь с ними при изменении кода. -### Colocated Tests {#colocated-tests} +### Тесты {#colocated-tests} -We don't have a top-level directory for unit tests. Instead, we put them into a directory called `__tests__` relative to the files that they test. +У нас нет отдельной верхнеуровневой папки с юнит тестами. Вместо этого, мы помещаем их в папку `__tests__`, расположенную рядом с тестируемыми файлами. -For example, a test for [`setInnerHTML.js`](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/dom/client/utils/setInnerHTML.js) is located in [`__tests__/setInnerHTML-test.js`](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/dom/client/utils/__tests__/setInnerHTML-test.js) right next to it. +Например, тесты для [`setInnerHTML.js`](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/dom/client/utils/setInnerHTML.js) расположены в [`__tests__/setInnerHTML-test.js`](https://github.com/facebook/react/blob/87724bd87506325fcaf2648c70fc1f43411a87be/src/renderers/dom/client/utils/__tests__/setInnerHTML-test.js). -### Warnings and Invariants {#warnings-and-invariants} +### Предупреждения и инварианты {#warnings-and-invariants} -The React codebase uses the `warning` module to display warnings: +Для работы с предупреждениями в React используется модуль `warning`. ```js var warning = require('warning'); warning( 2 + 2 === 4, - 'Math is not working today.' + 'Математика сегодня не работает.' ); ``` -**The warning is shown when the `warning` condition is `false`.** +**Предупреждения будут показаны, когда условие внутри `warning` равно `false`.** -One way to think about it is that the condition should reflect the normal situation rather than the exceptional one. +Это сделано для того, чтобы в первую очередь обрабатывать обычные ситуации, а лишь затем исключительные. -It is a good idea to avoid spamming the console with duplicate warnings: +Использование дополнительной переменной поможет избежать спама в консоль. ```js var warning = require('warning'); @@ -65,48 +65,48 @@ var didWarnAboutMath = false; if (!didWarnAboutMath) { warning( 2 + 2 === 4, - 'Math is not working today.' + 'Математика сегодня не работает.' ); didWarnAboutMath = true; } ``` -Warnings are only enabled in development. In production, they are completely stripped out. If you need to forbid some code path from executing, use `invariant` module instead: +Предупреждения включены только в режиме разработки и полностью вырезаны из продакшена. Если вам необходимо запретить выполнение какого-либо кода, тогда используйте модуль `invariant`: ```js var invariant = require('invariant'); invariant( 2 + 2 === 4, - 'You shall not pass!' + 'Ты не пройдёшь!' ); ``` -**The invariant is thrown when the `invariant` condition is `false`.** +**Если условие внутри `invariant` равно `false`, тогда выбрасывается исключение.** -"Invariant" is just a way of saying "this condition always holds true". You can think about it as making an assertion. +"Инварианты" -- это всего лишь способ сказать: "Условие всегда истинно". Вы можете думать о них как об утверждениях (assertion). -It is important to keep development and production behavior similar, so `invariant` throws both in development and in production. The error messages are automatically replaced with error codes in production to avoid negatively affecting the byte size. +Важно чтобы режимы разработки и продакшена имели похожее поведение, поэтому исключения выбрасываются в обоих режимах. Сообщения об ошибках в продакшене автоматически заменяются кодами ошибок, для того, чтобы избежать разрастания бандла. -### Development and Production {#development-and-production} +### Режимы разработки и продакшена {#development-and-production} -You can use `__DEV__` pseudo-global variable in the codebase to guard development-only blocks of code. +Вы можете использовать псевдоглобальную переменную `__DEV__`, чтобы блок кода присутствовал только в режиме разработки. -It is inlined during the compile step, and turns into `process.env.NODE_ENV !== 'production'` checks in the CommonJS builds. +На этапе компиляции добавится проверка `process.env.NODE_ENV !== 'production'`, определяющая, должен ли данный блок кода присутствовать в сборке CommonJS. -For standalone builds, it becomes `true` in the unminified build, and gets completely stripped out with the `if` blocks it guards in the minified build. +Выражение будет равно `true` в неминифицированной сборке, а в минифицированном будет вырезан весь блок вместе с `if`. ```js if (__DEV__) { - // This code will only run in development. + // Это код будет выполнен только в режиме разработки. } ``` ### Flow {#flow} -We recently started introducing [Flow](https://flow.org/) checks to the codebase. Files marked with the `@flow` annotation in the license header comment are being typechecked. +Недавно мы представили статический анализатор [Flow](https://flow.org/). Файлы, помеченные аннотацией `@flow` в заголовке после лицензии, будут подвергнуты проверке типов. -We accept pull requests [adding Flow annotations to existing code](https://github.com/facebook/react/pull/7600/files). Flow annotations look like this: +Мы принимаем пулл реквесты [на дополнение аннотаций Flow в уже существующий код](https://github.com/facebook/react/pull/7600/files). Вот пример кода: ```js ReactRef.detachRefs = function( @@ -117,20 +117,19 @@ ReactRef.detachRefs = function( } ``` -When possible, new code should use Flow annotations. -You can run `yarn flow` locally to check your code with Flow. +Новый код, если это возможно, должен искользовать Flow. Вы можете выполнить `yarn` `flow`, чтобы произвести проверку типов. -### Dynamic Injection {#dynamic-injection} +### Динамические инъекции {#dynamic-injection} -React uses dynamic injection in some modules. While it is always explicit, it is still unfortunate because it hinders understanding of the code. The main reason it exists is because React originally only supported DOM as a target. React Native started as a React fork. We had to add dynamic injection to let React Native override some behaviors. +React использует динамические инъекции в некоторых модулях. Несмотря на то, что они явные, это всё ещё неудачное решение, потому что затрудняет понимание кода. Причина их существования в том, что изначально React поддерживал только DOM. React Native появился как форк React. Мы должны добавлять динамические инъекции, чтобы позволить React Native переопределять некоторое поведение. -You may see modules declaring their dynamic dependencies like this: +Ниже вы можете увидеть, как в модулях объявляются динамические зависимости: ```js -// Dynamically injected +// Инжектится динамически var textComponentClass = null; -// Relies on dynamically injected value +// Зависит от инжектируемого значения function createInstanceForText(text) { return new textComponentClass(text); } @@ -138,7 +137,7 @@ function createInstanceForText(text) { var ReactHostComponent = { createInstanceForText, - // Provides an opportunity for dynamic injection + // Позволяет использовать динамические инъекции injection: { injectTextComponentClass: function(componentClass) { textComponentClass = componentClass; @@ -149,78 +148,78 @@ var ReactHostComponent = { module.exports = ReactHostComponent; ``` -The `injection` field is not handled specially in any way. But by convention, it means that this module wants to have some (presumably platform-specific) dependencies injected into it at runtime. +Поле `injection` нигде не используется. Но по соглашению оно означает, что модуль может иметь зависимости (предположительно, платформо-зависимые), которые будут подключаться во время выполнения. -There are multiple injection points in the codebase. In the future, we intend to get rid of the dynamic injection mechanism and wire up all the pieces statically during the build. +В репозитории существует много мест с использованием инъекций. В будущем мы хотим избавиться от механизма динамических инъекций и соединять все фрагменты статически во время сборки. -### Multiple Packages {#multiple-packages} +### Множество пакетов {#multiple-packages} -React is a [monorepo](https://danluu.com/monorepo/). Its repository contains multiple separate packages so that their changes can be coordinated together, and issues live in one place. +React является [монолитным репозиторием](https://danluu.com/monorepo/). Он содержит множество отдельных пакетов, чтобы изменения были согласованными, а проблемы решались в одном месте. -### React Core {#react-core} +### Ядро React {#react-core} -The "core" of React includes all the [top-level `React` APIs](/docs/top-level-api.html#react), for example: +Ядро включает в себя весь [верхнеуровневый API](/docs/top-level-api.html#react), например: * `React.createElement()` * `React.Component` * `React.Children` -**React core only includes the APIs necessary to define components.** It does not include the [reconciliation](/docs/reconciliation.html) algorithm or any platform-specific code. It is used both by React DOM and React Native components. +**Ядро включает в себя только API необходимый для объявления компонентов.** Оно не включает [алгоритм согласования](/docs/reconciliation.html) или какой-либо платформо-специфический код. Этот код находится в компонентах React DOM и React Native. -The code for React core is located in [`packages/react`](https://github.com/facebook/react/tree/master/packages/react) in the source tree. It is available on npm as the [`react`](https://www.npmjs.com/package/react) package. The corresponding standalone browser build is called `react.js`, and it exports a global called `React`. +Код ядра расположен в папке [`packages/react`](https://github.com/facebook/react/tree/master/packages/react). Он доступен в npm в виде пакета [`react`](https://www.npmjs.com/package/react). Соответствующая сборка для браузера экспортирует глобальную переменную `React` и называется `react.js`. -### Renderers {#renderers} +### Рендереры {#renderers} -React was originally created for the DOM but it was later adapted to also support native platforms with [React Native](https://facebook.github.io/react-native/). This introduced the concept of "renderers" to React internals. +Изначально React создавался для DOM, но позже был адаптирован к другим платформам, таким как [React Native](https://facebook.github.io/react-native/). В этом разделе мы расскажем об используемых рендерерах. -**Renderers manage how a React tree turns into the underlying platform calls.** +**Рендереры превращают React дерево в платформо-специфический код.** -Renderers are also located in [`packages/`](https://github.com/facebook/react/tree/master/packages/): +Они расположены в каталоге [`packages/`](https://github.com/facebook/react/tree/master/packages/): -* [React DOM Renderer](https://github.com/facebook/react/tree/master/packages/react-dom) renders React components to the DOM. It implements [top-level `ReactDOM` APIs](/docs/react-dom.html) and is available as [`react-dom`](https://www.npmjs.com/package/react-dom) npm package. It can also be used as standalone browser bundle called `react-dom.js` that exports a `ReactDOM` global. -* [React Native Renderer](https://github.com/facebook/react/tree/master/packages/react-native-renderer) renders React components to native views. It is used internally by React Native. -* [React Test Renderer](https://github.com/facebook/react/tree/master/packages/react-test-renderer) renders React components to JSON trees. It is used by the [Snapshot Testing](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html) feature of [Jest](https://facebook.github.io/jest) and is available as [react-test-renderer](https://www.npmjs.com/package/react-test-renderer) npm package. +* [React DOM Renderer](https://github.com/facebook/react/tree/master/packages/react-dom) рендерит React-компоненты в DOM. Он реализует [`ReactDOM` API](/docs/react-dom.html) и доступен как пакет [`react-dom`](https://www.npmjs.com/package/react-dom) из npm репозитория. Можно подключать как отдельный бандл `react-dom.js`, экспортирующий глобальную переменную `ReactDOM`. +* [React Native Renderer](https://github.com/facebook/react/tree/master/packages/react-native-renderer) рендерит React компоненты в нативные представления. Используется внутри React Native. +* [React Test Renderer](https://github.com/facebook/react/tree/master/packages/react-test-renderer) рендерит React компоненты в JSON-дерево. Используется при [тестировании снимками](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html) через фреймворк [Jest](https://facebook.github.io/jest) и доступен как пакет [react-test-renderer](https://www.npmjs.com/package/react-test-renderer) в npm. -The only other officially supported renderer is [`react-art`](https://github.com/facebook/react/tree/master/packages/react-art). It used to be in a separate [GitHub repository](https://github.com/reactjs/react-art) but we moved it into the main source tree for now. +Мы начали поддерживать единственный неофициальный рендерер [`react-art`](https://github.com/facebook/react/tree/master/packages/react-art), который раньше находился в отдельном [GitHub-репозитории](https://github.com/reactjs/react-art). ->**Note:** +>**Примечание:** > ->Technically the [`react-native-renderer`](https://github.com/facebook/react/tree/master/packages/react-native-renderer) is a very thin layer that teaches React to interact with React Native implementation. The real platform-specific code managing the native views lives in the [React Native repository](https://github.com/facebook/react-native) together with its components. +>Технически [`react-native-renderer`](https://github.com/facebook/react/tree/master/packages/react-native-renderer) -- это очень тонкий слой, который учит React взаимодействовать с React Native. Платформо-специфический код, управляющий нативными представлениями, расположен в [репозитории React Native](https://github.com/facebook/react-native) вместе с его компонентами. -### Reconcilers {#reconcilers} +### Согласователи {#reconcilers} -Even vastly different renderers like React DOM and React Native need to share a lot of logic. In particular, the [reconciliation](/docs/reconciliation.html) algorithm should be as similar as possible so that declarative rendering, custom components, state, lifecycle methods, and refs work consistently across platforms. +Даже очень непохожим рендерерам, таким как React DOM и React Native, необходимо разделять много логики. В частности, реализации [алгоритма согласования](/docs/reconciliation.html) должны быть настолько похожими, чтобы декларативный рендеринг, пользовательские компоненты, состояние, методы жизненного цикла и рефы работали одинаково между различными платформами. -To solve this, different renderers share some code between them. We call this part of React a "reconciler". When an update such as `setState()` is scheduled, the reconciler calls `render()` on components in the tree and mounts, updates, or unmounts them. +В качестве решения, различные рендереры имеют между собой общий код. В React мы называем эту часть «согласователь». Когда запланировано такое обновление, как `setState()`, согласователь вызывает `render()` в дереве компонентов и монтирует, обновляет либо размонтирует их. -Reconcilers are not packaged separately because they currently have no public API. Instead, they are exclusively used by renderers such as React DOM and React Native. +Согласователи не являются отдельнымы пакетами, потому что не имеют открытого API. Вместо этого они используются исключительно такими рендерерами как React DOM и React Native. -### Stack Reconciler {#stack-reconciler} +### Согласователь Stack {#stack-reconciler} -The "stack" reconciler is the implementation powering React 15 and earlier. We have since stopped using it, but it is documented in detail in the [next section](/docs/implementation-notes.html). +Cогласователь «Stack» -- это реализация, которая использовалась в React 15 и более ранних версиях. Мы перестали его использовать, но задокументировали в [следующией главе](/docs/implementation-notes.html). -### Fiber Reconciler {#fiber-reconciler} +### Cоглаcователь Fiber {#fiber-reconciler} -The "fiber" reconciler is a new effort aiming to resolve the problems inherent in the stack reconciler and fix a few long-standing issues. It has been the default reconciler since React 16. +В согласователе «Fiber» мы пытаемся исправить давно существующие ошибки и решить проблемы, появившиеся в согласователе Stack. -Its main goals are: +Его основными целями являются: -* Ability to split interruptible work in chunks. -* Ability to prioritize, rebase and reuse work in progress. -* Ability to yield back and forth between parents and children to support layout in React. -* Ability to return multiple elements from `render()`. -* Better support for error boundaries. +* Разделение прерываемых задач на подзадачи. +* Дать задачам приоритеты, иметь возможность перемещать их и переиспользовать. +* Иметь возможность перемещаться вперёд и назад между родителями и детьми в разметке React. +* Иметь возможность возвращать множество элементов из метода `render()`. +* Улучшенная обработка ошибок. -You can read more about React Fiber Architecture [here](https://github.com/acdlite/react-fiber-architecture) and [here](https://blog.ag-grid.com/inside-fiber-an-in-depth-overview-of-the-new-reconciliation-algorithm-in-react). While it has shipped with React 16, the async features are not enabled by default yet. +Вы можете узнать больше об архитектуре React Fiber [здесь](https://github.com/acdlite/react-fiber-architecture) и [здесь](https://blog.ag-grid.com/inside-fiber-an-in-depth-overview-of-the-new-reconciliation-algorithm-in-react). Несмотря на то, что он включён в React 16, асинхронная функциональность по умолчанию не включена. -Its source code is located in [`packages/react-reconciler`](https://github.com/facebook/react/tree/master/packages/react-reconciler). +Исходный код расположен в папке [`packages/react-reconciler`](https://github.com/facebook/react/tree/master/packages/react-reconciler). -### Event System {#event-system} +### Система событий {#event-system} -React implements a synthetic event system which is agnostic of the renderers and works both with React DOM and React Native. Its source code is located in [`packages/legacy-events`](https://github.com/facebook/react/tree/master/packages/legacy-events). +В React реализована система синтетических событий, которая не зависит от используемого рендерера, и работает одинаково как React DOM, так и в React Native. Исходный код расположен в каталоге [`packages/react-events`](https://github.com/facebook/react/tree/master/packages/react-events). -There is a [video with a deep code dive into it](https://www.youtube.com/watch?v=dRo_egw7tBc) (66 mins). +Больше подробностей вы можете узнать из [видео](https://www.youtube.com/watch?v=dRo_egw7tBc) (66 mins). -### What Next? {#what-next} +### Что дальше? {#what-next} -Read the [next section](/docs/implementation-notes.html) to learn about the pre-React 16 implementation of reconciler in more detail. We haven't documented the internals of the new reconciler yet. +В [следующей главе](/docs/implementation-notes.html) вы познакомитесь с реализацией согласователя (версий React 15 и ранее) больее подробно. Для нового согласователя мы ещё не писали документацию. diff --git a/content/docs/nav.yml b/content/docs/nav.yml index ee335fe48..f88bac6cd 100644 --- a/content/docs/nav.yml +++ b/content/docs/nav.yml @@ -153,7 +153,7 @@ - id: how-to-contribute title: Как внести свой вклад? - id: codebase-overview - title: Codebase Overview + title: Устройство кодовой базы - id: implementation-notes title: Implementation Notes - id: design-principles