script.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. class FaqPage {
  2. static Lang = {
  3. Ru: 'ru',
  4. En: 'en'
  5. };
  6. static FaqNotes = {
  7. [FaqPage.Lang.Ru]: {
  8. 'Что это?':
  9. 'Doczilla JS Docs - это инструмент для документирования клиентского кода Doczilla.',
  10. 'Зачем?':
  11. 'Главной целью данного инструмента является упрощение процесса ознакомления разработчиков с клиентской частью фреймворка Z8.',
  12. 'Как работает?':
  13. '1. Автоматическое обновление требуемых репозиториев раз в сутки.\n' +
  14. '2. Двухэтапный анализ кода.\n' +
  15. '<span class="list-spacing"></span>2.1. Статический анализ. Маппинг классов и путей к файлам, в которых описаны классы. Определение динамически заданных свойств (this).\n' +
  16. '<span class="list-spacing"></span>2.2. Динамический анализ. Определение типов свойств, сигнатур методов. Формирование дерева предков, "mixins" для каждого класса. Категоризация методов и свойств: собственные, переопредленные, наследованные.\n' +
  17. '3. Формирование карты классов.\n' +
  18. '4. Веб-сервер.',
  19. 'Как пользоваться? (читатель)':
  20. '<b>1. Список классов.</b>\n' +
  21. 'Список представлен в левой части страницы. Список имеет два режима отображения: древовидная структура и простой список классов. В древовидной структуре классы расположены в пакетах, которые заданы в названиях классов. В простом списке все классы просто перечислены в алфавитном порядке. '+
  22. 'Режимы переключаются с помощью соответствюущих кнопок, расположенных над строкой поиска. После переключения режима, ваш выбор будет сохранен с помощью cookies на 12 часов. Таким же образом запоминаются и раскрытые пакеты в древовидной структуре списка.\n\n' +
  23. '<b>2. Поиск по классам.</b>\n' +
  24. 'Чтобы найти интересующие классы, необходимо написать запрос в соответствующее поле, после чего нажать Enter. При нажатии на элемент класса в списке, вы будете перенаправлены на страницу выбранного класса.\n\n'+
  25. '<b>3. Страница класса.</b>\n' +
  26. 'На странице класса доступно два режима отображения: вкладки и список. Режим переключается с помощью соответствующих кнопок в верхней правой части страницы. После переключения режима, ваш выбор будет сохранен с помощью cookies на 12 часов.\n' +
  27. 'В верхней части страницы расположено наименование класса, а также процент заполненной документации к классу.\n' +
  28. 'В основной части страницы можно наблюдать 7 разделов: Editor, Methods, Properties, Parents, Mixins, Children, Mixed in.\n\n' +
  29. 'Подробнее про каждый из разделов можно прочитать в следующем пункте FAQ.',
  30. 'Разделы страницы класса':
  31. '<b>1. Editor</b>\n' +
  32. 'В данном разделе представлен readonly редактор кода с подсветкой синтаксиса JS. Редактор обладает некоторыми особыми функциями:\n' +
  33. '<span class="list-spacing"></span>1. Переход к родительскому классу. Осуществляется при помощи нажатия Ctrl+Click по наименованию родительского класса в свойстве extend.\n' +
  34. '<span class="list-spacing"></span>2. Переход к mixins. Осуществляется при помощи нажатия Ctrl+Click по наименованиям классов перечисленных в свойстве mixins.\n' +
  35. '<span class="list-spacing"></span>3. Предпросмотр i18n messages. Все места вида "Z8.$(\'...\')" подсвечены в коде, чтобы увидеть, какие строки в действительности кроются за этими выражениями, нужно просто навести курсор мыши на них.\n\n' +
  36. '<b>2. Methods</b>\n' +
  37. 'В данном разделе представлен список методов класса. Методы разделены на следующие категории:\n' +
  38. '<span class="list-spacing"></span>1. Static methods: статические методы, описанные в свойстве statics.\n'+
  39. '<span class="list-spacing"></span>2. Base methods: собственные методы класса, которых нет ни в одном из родительских классов.\n' +
  40. '<span class="list-spacing"></span>3. Overridden methods: переопределенные методы. Если метод отображается в данной категории, значит, он встречается в одном из родительских классов и явным образом переопределен в текущем классе.\n' +
  41. '<span class="list-spacing"></span>4. Inherited: наследованные методы. Данные методы пристутствуют в родительских классах, но не были переопределены в текущем классе.\n' +
  42. 'Комментируемыми являются методы всех категорий, кроме Inherited. В Inherited отображаются readonly-комментарии, которые берутся из ближайших родительских классов (последний ближайший родительский класс, в котором метод был переопределен).\n\n' +
  43. '<b>3. Properties</b>\n' +
  44. 'В данном разделе представлен список свойств класса. Свойства разделены на те же категории, что и методы, + категория Dynamic properties.\n' +
  45. 'В категории Dynamic properties перечислены свойства, которые задаются "динамически" в коде (например, this.abc = 1).\n' +
  46. 'В отличие от методов, в свойствах, помимо наименования, в большинстве случаев отображается также тип данных и значение по-умолчанию.\n\n' +
  47. '<b>4. Parents</b>\n' +
  48. 'В данном разделе отображается родительская ветка текущего класса (от самого базового класса к ближайшему родительскому).\n\n' +
  49. '<b>5. Mixins</b>\n' +
  50. 'В данном разделе перечислен список mixins.\n\n' +
  51. '<b>6. Children</b>\n' +
  52. 'В данном разделе перечислен список классов, которым текущий класс приходится родителем (не обязательно ближайшим).\n\n' +
  53. '<b>7. Mixed in</b>\n' +
  54. 'В данном разделе представлен список классов, в которых текущий класс присутстсвует в свойстве mixins.\n\n\n' +
  55. '<b>Контекстное меню</b>\n' +
  56. 'Во всех перечисленных разделах, кроме Editor, доступно контекстное меню (вызывается нажатием ПКМ по элементу).',
  57. 'Как пользоваться? (редактор)':
  58. 'Сперва необходимо авторизоваться. Используйте свои логин и пароль с git.doczilla.pro, которые следует ввести на <a href="/login">данной странице</a>. Также на эту страницу можно попасть с помощью кнопки <img width="24px" height="24px" src="/img/user.svg" />, находящейся над строкой поиска в левой части страницы. Будучи авторизованными, у вас появится возможность редактировать комментарии.<hr/>' +
  59. 'Комментируемыми объектами являются свойства(Properties) и методы(Methods) классов, причем комментировать можно только не Inherited.\n' +
  60. 'Чтобы оставить комментарий нужно нажать на поле комментария, после чего появится поле ввода (textarea). Комментарий может содержать html-теги. Переносы строк автоматически конвертируются в тег &lt;br&gt;!\n' +
  61. 'После завершения написания комментария, необходимо нажать на кнопку "OK", либо нажать Enter. Переносы строк ставятся с помощью комбинации Shift+Enter.'
  62. },
  63. [FaqPage.Lang.En]: {
  64. 'What is it?':
  65. 'Doczilla JS Docs - is a tool for documenting client-side code of Doczilla.',
  66. 'Why?':
  67. 'The main goal of this tool is to simplify the process of familiarizing developers with the client part of the Z8 framework.',
  68. 'How does it work?':
  69. '1. Automatic updating of required repositories once a day.\n' +
  70. '2. Two-stage code analysis.\n' +
  71. '<span class="list-spacing"></span>2.1. Static analysis. Mapping of classes and paths to files where classes are described. Determination of dynamically assigned properties (this).\n' +
  72. '<span class="list-spacing"></span>2.2. Dynamic analysis. Determination of property types, method signatures. Formation of ancestor tree, "mixins" for each class. Categorization of methods and properties: own, overridden, inherited.\n' +
  73. '3. Generating a class map.\n' +
  74. '4. Web server.',
  75. 'How to use? (reader)':
  76. '<b>1. Class list.</b>\n' +
  77. 'The list is presented on the left side of the page. The list has two display modes: tree structure and simple class list. In tree structure, classes are arranged in packages specified in class names. In the simple list, all classes are simply listed in alphabetical order. '+
  78. 'Modes are switched using the corresponding buttons located above the search bar. After switching the mode, your choice will be saved using cookies for 12 hours. The same applies to expanded packages in the tree structure list.\n\n' +
  79. '<b>2. Class search.</b>\n' +
  80. 'To find classes of interest, you need to enter a query in the corresponding field, then press Enter. When clicking on a class item in the list, you will be redirected to the page of the selected class.\n\n'+
  81. '<b>3. Class page.</b>\n' +
  82. 'On the class page, there are two display modes: tabs and list. The mode is switched using the corresponding buttons in the top right corner of the page. After switching the mode, your choice will be saved using cookies for 12 hours.\n' +
  83. 'At the top of the page is the class name and the percentage of documentation filled for the class.\n' +
  84. 'In the main part of the page, you can see 7 sections: Editor, Methods, Properties, Parents, Mixins, Children, Mixed in.\n\n' +
  85. 'More details about each section can be found in the next FAQ item.',
  86. 'Class page sections':
  87. '<b>1. Editor</b>\n' +
  88. 'This section presents a readonly code editor with JS syntax highlighting. The editor has some special features:\n' +
  89. '<span class="list-spacing"></span>1. Go to parent class. Done by Ctrl+Click on the parent class name in the extend property.\n' +
  90. '<span class="list-spacing"></span>2. Go to mixins. Done by Ctrl+Click on the names of classes listed in the mixins property.\n' +
  91. '<span class="list-spacing"></span>3. Preview i18n messages. All occurrences of "Z8.$(\'...\')" are highlighted in the code, to see what strings are actually behind these expressions, simply hover over them with the mouse cursor.\n\n' +
  92. '<b>2. Methods</b>\n' +
  93. 'This section presents a list of class methods. Methods are divided into the following categories:\n' +
  94. '<span class="list-spacing"></span>1. Static methods: static methods described in the statics property.\n'+
  95. '<span class="list-spacing"></span>2. Base methods: own class methods that are not in any of the parent classes.\n' +
  96. '<span class="list-spacing"></span>3. Overridden methods: overridden methods. If a method is displayed in this category, it means it is encountered in one of the parent classes and is explicitly overridden in the current class.\n' +
  97. '<span class="list-spacing"></span>4. Inherited: inherited methods. These methods exist in parent classes but have not been overridden in the current class.\n' +
  98. 'Methods of all categories except Inherited are commentable. In Inherited, readonly comments are displayed, taken from the nearest parent classes (the last nearest parent class where the method was overridden).\n\n' +
  99. '<b>3. Properties</b>\n' +
  100. 'This section presents a list of class properties. Properties are divided into the same categories as methods, plus the Dynamic properties category.\n' +
  101. 'The Dynamic properties category lists properties that are set "dynamically" in the code (for example, this.abc = 1).\n' +
  102. 'Unlike methods, properties, in addition to the name, in most cases also display the data type and default value.\n\n' +
  103. '<b>4. Parents</b>\n' +
  104. 'This section displays the parent branch of the current class (from the base class to the nearest parent).\n\n' +
  105. '<b>5. Mixins</b>\n' +
  106. 'This section lists mixins.\n\n' +
  107. '<b>6. Children</b>\n' +
  108. 'This section lists classes for which the current class is a parent (not necessarily the nearest).\n\n' +
  109. '<b>7. Mixed in</b>\n' +
  110. 'This section presents a list of classes in which the current class is present in the mixins property.\n\n\n' +
  111. '<b>Context menu</b>\n' +
  112. 'In all listed sections, excluding the Editor, a context menu is available (triggered by right-clicking on the element).',
  113. 'How to use? (editor)':
  114. 'First, you need to log in. Use your login and password from git.doczilla.pro, which should be entered on <a href="/login">this page</a>. You can also access this page using the <img width="24px" height="24px" src="/img/user.svg" /> button located above the search bar on the left side of the page. Once authorized, you will be able to edit comments.<hr/>' +
  115. 'Commentable objects are properties (Properties) and methods (Methods) of classes, and you can only comment on non-Inherited ones.\n' +
  116. 'To leave a comment, click on the comment field, after which an input field (textarea) will appear. Comments can contain HTML tags. Line breaks are automatically converted to the <br> tag!\n' +
  117. 'After finishing writing the comment, click the "OK" button or press Enter. Line breaks could be placed using Shift+Enter.'
  118. }
  119. };
  120. start() {
  121. this.faqContent = DOM.get('.faq-content');
  122. this.renderContent();
  123. return this;
  124. }
  125. renderContent() {
  126. const faqContent = this.faqContent;
  127. const lang = Url.getHash() || FaqPage.Lang.En;
  128. const faq = FaqPage.FaqNotes[lang] || FaqPage.FaqNotes[FaqPage.Lang.En];
  129. let index = 1;
  130. this.themeElements = [];
  131. for(const theme of Object.keys(faq)) {
  132. const noteContent = DOM.create({ tag: DOM.Tags.Div, cls: 'faq-note-content hidden', innerHTML: CDUtils.nl2br(faq[theme]) });
  133. const noteThemeText = DOM.create({ tag: DOM.Tags.Span, innerHTML: `${index}. ${theme}` });
  134. const noteThemeCollapsedIcon = DOM.create({ tag: DOM.Tags.Div, cls: 'collapsed-icon' });
  135. const onClick = (e) => {
  136. noteContent.switchClass('hidden');
  137. noteTheme.switchClass('collapsed');
  138. };
  139. const noteTheme = DOM.create({ tag: DOM.Tags.Div, cls: 'faq-note-theme collapsed', cn: [noteThemeText, noteThemeCollapsedIcon] }, faqContent).on(DOM.Events.Click, onClick);
  140. this.themeElements.push({ element: noteTheme, handler: onClick });
  141. faqContent.append(noteContent);
  142. index++;
  143. }
  144. }
  145. clearThemes() {
  146. for(const theme of this.themeElements) {
  147. theme.element.un(DOM.Events.Click, theme.handler);
  148. theme.element.remove();
  149. }
  150. this.themeElements = [];
  151. }
  152. clear() {
  153. this.clearThemes();
  154. this.faqContent.getChildren().forEach((child) => {
  155. child.remove();
  156. });
  157. }
  158. reload() {
  159. this.clear();
  160. this.renderContent();
  161. }
  162. }
  163. window_.on(DOM.Events.Load, (e) => {
  164. window.page = new FaqPage().start();
  165. });
  166. window_.on(DOM.Events.HashChange, (e) => {
  167. if(window.page)
  168. window.page.reload();
  169. });