From the introductory lesson [How to create a menu](How to create menu), you learned the basics of creating interactive menus. Here you will learn in detail about the structure of the menu and the optimization capabilities of the plugin.
## <a name="file"> Menu file </a>
Any menu can be described both in a separate file, or in a single file with other menus. The example below shows one of the possible options for the menu file structure.
#### <a name="solo"> One menu in one file </a>
#### Содержание страницы
1.[Файл меню](#file)
-[Одно меню в одном файле](#solo)
-[Несколько меню в одном файле](#multi)
2.[Параметры меню](#menuVar)
3.[Авто обновление меню](#update)
4.[Кнопки меню](#buttons)
-[Правила вывода кнопки](#btnRules)
-[Обработка клика по кнопке](#btnClicks)
5.[Шаблоны](#templates)
-[Шаблон внутри файла меню](#menuTemplates)
-[Шаблоны в отдельном файле](#templatesConf)
Из вступительного урока [Как создать меню](Как создать меню) вы узнали основы основ по созданию интерактивных меню. Здесь же вы подробно познакомитесь со структурой меню и оптимизационными возможностями плагина.
## <a name="file">Файл меню</a>
Любое меню можно описывать как в отдельном файле, так и в одном файле с другими меню. Пример ниже показывает один из возможных вариантов структуры файла меню.
#### <a name="solo">Одно меню в одном файле</a>
```hocon
title:"&8Menu"// Menu name
size:6// The vertical size of the menu. Horizontal cannot be changed
activators{// Actions that may lead to opening of the menu
title:"&8Меню"// Название меню
size:6// Вертикальный размер меню. Горизонтальный не может быть изменен
activators{// Действия которые могут привести к открытию меню
Do not be afraid at first glance of a complex structure. As you read this lesson, as well as subsequent lessons, you will understand what each block means.
Не бойтесь на первый взгляд сложной структуры. Читая этот урок дальше, а также последующие уроки, вы поймете что означает каждый из блоков.
#### <a name="multi"> Multiple menus in one file </a>
#### <a name="multi">Несколько меню в одном файле</a>
---
If you are making a small menu, it may make sense to write it in one file with the menus adjacent to it. To do this, the plugin provides a design that allows you to describe several menus in one file at once. In this case, the menu name will be considered the name of the block in which it is described. Here is an example:
Если вы делаете какое-то небольшое меню, возможно есть смысл писать его в одном файле со смежными с ним меню. Для этого в плагине предусмотрена конструкция, позволяющая описывать сразу несколько меню в одном файле. В таком случае именем меню будет считаться имя блока, в котором оно описано. Вот пример:
```hocon
menus{
my_awesome_menu{// Menu name (unique)
title:"My menu"
my_awesome_menu{// Имя меню (уникальное)
title:"Мое меню"
size:6
items:[
...
]
}
my_another_menu{
title:"My other menu"
title:"Мое другое меню"
size:1
items:[
...
...
...
@@ -77,60 +77,60 @@ menus {
}
```
In the root of the file, the `menus` block is created, in which separate menus are created. In this example, two separate menus are created with the names`my_awesome_menu`and`my_another_menu`.
В корне файла создается блок `menus`, в котором и создаются отдельные меню. В данном примере созданы два отдельных меню с именами`my_awesome_menu`и`my_another_menu`.
## <a name="menuVar"> Menu Options </a>
To create a menu, whether in a separate file, or in a single file with other menus, you need to set its parameters. The table below will introduce you to the parameters that can be specified in the menu:
## <a name="menuVar">Параметры меню</a>
Для создания меню, будь то в отдельном файле, или в одном файле с другими меню, нужно задать его параметры. Таблица ниже ознакомит Вас с параметрами, которые можно указывать в меню:
| ** Parameter ** | ** Data Type ** | ** Required ** | ** Description ** |
| title | String | {+ Yes +} | Sets the title of the menu |
| size | Number | {+ Yes +} | Sets the vertical size of the menu, that is, the number of cells |
| items | [List of objects](Data types#list) | {-No-} | Sets items in the menu |
| activators | [Object](Data types#object) | {-No-} | [Actions](Actions) to open the menu |
| rules | [Object](Data types#object) / [List of objects](Data types#list) | {-No-} | [Rules](Rules) to open the menu. If at least one of the rules is not executed, the menu will not open. | | |
| openActions | [Object](Data types#object) | {-No-} | [Actions](Actions) that will be executed ** until ** the menu is opened. |
| denyActions | [Object](Data types#object) | {-No-} | [Actions](Actions) that will be executed if ** any ** of the rules is not executed. |
| closeActions | [Object(Data types#object) | {-No-} | [Actions](Actions) that will be executed after the menu is closed. |
| updateInterval | Integer | {-No-} | Sets the period for updating the menu in seconds. If absent, the menu is not updated automatically. |
| activators | [Объект](Типы данных#object) | {-Нет-} | [Действия](Действия) для открытия меню |
| rules | [Объект](Типы данных#object)/[Список объектов](Типы данных#list) | {-Нет-} | [Правила](Правила) для открытия меню. Если хоть одно из правил не будет выполнено - меню не откроется. |
| openActions | [Объект](Типы данных#object) | {-Нет-} | [Действия](Действия), которые выполнятся **до** открытия меню. |
| denyActions | [Объект](Типы данных#object) | {-Нет-} | [Действия](Действия), которые выполнятся при не выполнения **любого** из правил. |
| closeActions | [Объект](Типы данных#object) | {-Нет-} | [Действия](Действия), которые выполнятся после закрытия меню. |
| updateInterval | Целое число | {-Нет-} | Устанавливает период обновления меню в секундах. Если отсутствует - меню не обновляется автоматически. |
## <a name="update"> Auto-update menu </a>
## <a name="update">Авто обновление меню</a>
A bit more detailed about the `updateInterval` parameter. If you want to create a menu that will be automatically updated, including items, placeholders and any other dynamic data, you can specify the interval for updating the menu.
Немного подробней о параметре `updateInterval`. Если вы хотите создать меню, которое будет автоматически обновляться, включая предметы, плейсхолдеры и любые другие динамические данные, вы можете указать интервал обновления меню.
```hocon
title:"Updated menu"
title:"Обновляемое меню"
size:1
updateInterval:2
items:[
{
slot:0
material:CAKE
name:"Players: %server_players%"
name:"Игроков играет: %server_players%"
}
]
```
The menu above will be updated every 2 seconds. Along with this, the button that shows the number of players on the server will be updated, along with the placeholder`%server_players%`.
Меню представленное выше будет обновляться каждые 2 секунды. Вместе с этим будет обновляться и кнопка которая показывает число игроков на сервере, вместе с плейсхолдером`%server_players%`.
In this example, the standard [placeholder](Placeholders) plugin was used.
В данном примере использовался стандартный [плейсхолдер](Плейсхолдеры) плагина.
## <a name="buttons"> Menu Buttons </a>
## <a name="buttons">Кнопки меню</a>
The button in the menu is an ordinary [item](Item format) with advanced functionality. Below are all the parameters that can be specified in addition to the standard parameters of the subject.
Кнопка в меню - это обыкновенный [предмет](Представление предмета) с расширенным функционалом. Ниже представлены все параметры, которые можно указывать помимо стандартных параметров предмета.
| ** Parameter ** | ** Data Type ** | ** Description ** | ** Required ** |
| [slot](Item format#slot) | Integer, Object, Text | Sets item position in inventory | {+ Yes +} |
| [rules](#btnRules) | [List of objects](Data types#list) | [Rules](Rules) to display the button in the menu | {-No-} |
| [iRules](#btnRules) | [List of objects](Data types#list) | [Rules](Rules) to display a button on a menu that works exactly the opposite | {-No-} |
| [click](#btnClicks) | [Object](Data types#object) | It contains actions on a click as well as a description of actions for different types of clicks | {-No-} |
Any button can be displayed without any rules. But you can also set rules for displaying a button in the inventory menu. Such rules will limit the output of some buttons if the player does not comply with the rules. To do this, you can specify two rule blocks in the item description: `rules`and`iRules`.
Любая кнопка может быть выведена без всяких правил. Но еще вы можете устанавливать правила для вывода кнопки в инвентаре меню. Такие правила позволят ограничить вывод некоторых кнопок при не соответствии игрока правилам. Для этого в описании предмета вы можете указывать два блока правил: `rules`и`iRules`.
```hocon
items:[
...
...
@@ -148,9 +148,9 @@ items: [
]
```
In this example, the menu has two items. The first (Iron Sword) will be displayed in slot 0 in any case. The second (Diamond Sword) will be displayed in slot 0, and will replace the first item only if the player has the right "some.perm".
В данном примере в меню есть два предмета. Первый (Железный меч) выведется в слоте 0 в любом случае. Второй (Алмазный меч) выведется в слоте 0, и заменит первый предмет только в том случае, если у игрока есть право "some.perm".
Consider a similar example, but using inverted iRules rules.
Рассмотрим похожий пример, но с применением инвертированных правил `iRules`.
```hocon
...
...
@@ -169,9 +169,9 @@ items: [
]
```
In this example, the menu contains the same items. The first one will still be displayed in slot 0. The second one will be displayed in slot 0, and will replace the first item only if the player **does not** have the "some.perm" right.
В данном примере в меню все те же предметы. Первый все так же выведется в слоте 0. Второй выведется в слоте 0, и заменит первый предмет только в том случае, если у игрока **отсутствует** право "some.perm".
The`rules`and`iRules`blocks can be combined, that is, writing both in the same subject. In this case, the item will be withdrawn if the player **complies with** the rules described in `rules` and at the same time **does not comply with** the rules described by `iRules`. For instance:
Блоки`rules`и`iRules`можно комбинировать, то есть писать оба в одном предмете. В таком случае предмет выведется, если игрок **соответствует** правилам, описанным в `rules` и одновременно **не соответствует** правилам, описанным `iRules`. Например:
```hocon
items:[
...
...
@@ -188,13 +188,13 @@ items: [
]
```
In this example, a diamond sword will appear in the menu only if the player has the right "some.perm" and the right "another.perm" is missing.
В данном примере алмазный меч появится в меню только если у игрока есть право "some.perm" и отсутствует право "another.perm".
#### <a name="btnClicks"> Processing clicks </a>
#### <a name="btnClicks">Обработка кликов</a>
Almost any menu is meaningless without handling button clicks. The plugin provides a convenient system for processing clicks on buttons.
Почти любое меню бессмысленно без обработки нажатий на кнопки. В плагине предусмотрена удобная система обработки кликов по кнопкам.
So, let's look at what a click block is all about.
Итак, рассмотрим, что из себя представляет блок `click`.
```hocon
items:[
...
...
@@ -203,27 +203,27 @@ items: [
material:DIAMOND_SWORD
click{
left{
message:"Hello"
message:"Привет"
}
}
},
]
```
Inside the click block, the left block is specified. This is nothing more than the type of click that triggers the actions within the block. Inside the block responsible for the type of click, you can describe the same [actions](Actions) and [rules](Rules) as in the click block itself.
Внутри блока `click` указан блок `left`. Это ничто иное, как тип клика, при котором сработают действия внутри блока. Внутри блока, отвечающего за тип клика можно описывать те же [действия](Действия) и [правила](Правила), что и в самом блоке click.
You can find all types of clicks [here](https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/inventory/ClickType.html). We will describe the main working on all versions:
Все типы кликов вы можете найти [здесь](https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/inventory/ClickType.html). Мы же опишем основные, рабочие на всех версиях:
| SHIFT_LEFT | Клик левой кнопкой мыши с зажатой клавишой Shift |
| SHIFT_RIGHT | Клик правой кнопкой мыши с зажатой клавишой Shift |
| DOUBLE_CLICK | Двойной клик левой кнопкой мыши |
Any of these types can be used in the click block, either individually or together with other types in the same block.
Любой из этих типов можно использовать в блоке `click` как по отдельности, так и вместе с другими типами в одном блоке.
```hocon
items:[
...
...
@@ -231,65 +231,63 @@ items: [
slot:0
material:STONE
click{
message:"It was a click"// Displayed on any click
message:"Это был клик"// Выведется при любом клике
right{
message:"It was a right click"// Displayed when right-clicking
message:"Это был правый клик"// Выведется при клике правой кнопкой мыши
}
middle{
message:"It was a middle click"// Displayed when clicking with the middle mouse button
message:"Это был средний клик"// Выведется при клике средней кнопкой мыши
}
}
}
]
```
## <a name="templates"> Templates </a>
Thanks to the flexible HOCON format, you can create templates for anything. A template can be any parameter, object, list, etc. Templates can be specified both inside the menu file, and you can take all the templates to a separate file, for example, `templates.conf`. In order to tell the plugin that `templates.conf` is a file with templates, you must specify in the first line`#invisible`, otherwise `templates.conf` will be perceived by the plugin as a menu file.
## <a name="templates">Шаблоны</a>
Благодаря гибкому формату HOCON, можно создавать шаблоны чего-либо. Шаблоном может являться любой параметр, объект, список и т.д. Шаблоны можно задавать как внутри файла меню, так и вынести все шаблоны в отдельный файл, например, `tamplates.conf`. Для того, чтобы сказать плагину, что `templates.conf` является файлом с шаблонами нужно указать в первой строчке `#invisible`, в противном случае `templates.conf` будет восприниматься плагином как файл меню.
> ⚠️ **Important**: All the examples below describe only some of the features that HOCON provides. More information can be found in [official documentation](https://github.com/lightbend/config/blob/master/HOCON.md).
For example, in each of the great variety of menus, the "Close menu" button is used, which has the following form:
> ⚠️ **Важно**: Все примеры ниже описывают лишь некоторые возможности, которые предоставляет HOCON. Более подробную информацию можно найти в [официальной документации](https://github.com/lightbend/config/blob/master/HOCON.md)
Например, в каждом из большого многообразия меню используется кнопка "Закрыть меню", которая имеет такой вид:
What happens when the plugin loads the entire menu? When, while reading a file, it reaches the line where the special placeholder `${closeButton}` is indicated, **the content** of the `closeButton` block will be virtually inserted instead of the placeholder. Physically, the file itself will not change.
Что произойдет, когда плагин будет загружать все меню? Когда во время чтения файла он дойдет до строчки, где указан специальный плейсхолдер `${closeButton}`, **контент** блока `closeButton` будет виртуально вставлен вместо плейсхолдера. Физически сам файл при этом не изменится.
#### <a name="templatesConf"> Separate template file </a>
The example above is perfect if the template will be used only inside one menu file. And if there are a lot of files with different menus, what then? In this case, the template file will help. To do this, create a file in the `menus` folder with any name, for example, `templates.conf`. In this file, you can describe any blocks and parameters in any order for subsequent insertion into the menu file.
#### <a name="templatesConf">Отдельный файл с шаблонами</a>
Пример выше отлично подойдет, если шаблон будет использоваться только внутри одного файла меню. А если файлов с разными меню много, что в таком случае? В данном случае поможет файл с шаблонами. Для этого нужно создать файл в папке `menus` с любым названием, например, `templates.conf`. В этом файле можно описывать какие угодно блоки и параметры в любом порядке для последующей вставки в файл меню.
> ⚠️ **Important**: To make it clear to the plugin that this file is used for storing templates, you need to specify `#invisible` at the beginning of the file.
> ⚠️ **Важно**: Чтобы дать понять плагину, что данный файл используется для хранения шаблонов нужно указать в начале файла `#invisible`
**templates.conf**
```hocon
...
...
@@ -298,35 +296,35 @@ The example above is perfect if the template will be used only inside one menu f
include required(file("./plugins/AbstractMenus/menus/templates.conf"))
title:"&8Menu"
title: "&8Меню"
size: 6
items: [
${closeButton}
]
```
Now, when reading the **menu.conf** file, the plugin will come across a line with the `include` directive and the first thing to do is virtually insert the entire contents of the **templates.conf** file into the place where the directive itself was located. As with placeholders, the file will not physically change.
Теперь при чтении файла **menu.conf** плагин наткнется на строчку с директивой `include` и первым делом виртуально вставит весь контент файла **templates.conf** на то место, где находилась сама директива. Как и в случае с плейсхолдерами, физически файл не изменится.
As a result, the placeholder `${closeButton}` will be replaced by the contents of the `closeButton` block, which is safely located in the menu file.
В результате плейсхолдер `${closeButton}` будет заменен на контент блока `closeButton`, который благополучно "находится" в файле меню.
HOCON also allows you to overwrite any template data. This can come in handy if you need to change only one item parameter in the template, for example,`slot`.
Example: `closeButton` _(item description above)_ has `slot: "5,5"`. Not all menus may need to place a button in this slot. To do this, you can overwrite the `slot` parameter from the `closeButton` button template.
Еще HOCON позволяет перезаписывать любые данные шаблона. Это может пригодиться, если нужно изменить всего один параметр предмета в шаблоне, например `slot`.
Пример: `closeButton` _(описание предмета выше)_ имеет `slot: "5,5"`. Не во всех меню может потребоваться помещать кнопку именно в этот слот. Для этого можно перезаписать параметр `slot` из шаблона кнопки `closeButton`.
**templates.conf**
```hocon
...
...
@@ -335,8 +333,8 @@ Example: `closeButton` _(item description above)_ has `slot: "5,5"`. Not all men