busted parrot
parent
previous
next
Для справки идиотам большим оригиналам которые используют htic.js кроме меня: туда добавилась возможность запускать сторонние javascript функции и выполнять переходы относительно указанного узла.
If there are idiots unique people like me that use htic.js be advised: the option to run external javascript functions has been added and also the ability to set transitions relative to a given node.
За примером далеко ходить не надо, в меню "У меня есть" на главной странице используется 2 runCode узла. Они отвечают за размер меню в зависимости от ширины экрана.
For example you don't have to look further then the main page "Checkitout" menu. It uses 2 runCode nodes for managing menu size depending on screen width.
Вот картинка для тех кому лень открывать neverParrotMain.fodg самому.
Here's the picture for people who can't be bothered to open neverParrotMain.fodg themselves.
Если вы всё-таки захотите попробовать сами, не забывайте что все узлы должны быть подписаны в title, иначе не заработает. Для runCode узла нужно вписать "runCode", внезапно, да.
If for any reason you decide to give it a go yourselve remember that all nodes should have their type put into the title field or it won't work. For runCode node you should put in "runCode", duh.
Файл neverParrotMain.fodg большой, учиться использовать overrideNext будем на кошках примере поменьше.
The file neverParrotMain.fodg is big so let me introduce todays victim visual aid for overrideNext usage tutorial.
testOverrideNext.fodg
Neocities не даёт мне сохранить файл с расширением *.fodg поэтому вам придётся скачать testOverrideNext.xml и поменять расширение. Заметьте что я даже не вру что testOverrideNext.xml это XML, flat-ODG это правда XML, в него просто сохраняется диаграмма в XML формате, а не просто любая информация в XML формате как в файлы с *.xml расширением. Любая информация в XML формате включает в себя диаграммы в XML формате.
Neocities doesn't let me save a file with *.fodg extention so you would have to download testOverrideNext.xml and rename it. For your information I'm not even lying about testOverrideNext.xml being XML, flat-ODG is actually XML, but for storing diagrams in XML format as opposed to storing any sort of information in XML format in a file with an *.xml extention. Any information in XML format includes diagrams in XML format.
Помимо fodg нам понадобится html шаблон tmpE5.html . В него сохранена копия htic.js, так как я хочу приколотить гвоздями версию библиотеки, а основная версия на сайте будет обновляться в будущем. Но помимо htic.js в него сохранены ещё дополнительные функции, я выделил представляющие особый интерес.
But besides fodg we would also need an html template tmpE5.html . It contains a separate copy of htic.js because I want to nail down the version of that and the main copy of htic.js on this site will be updated in the future. But besides htic.js there are several more functions of note stored there.

 1 
 2 function replaceInnerHtmlIfHasGivenValueAttr(name,repl,node){
 3   var node;
 4   if(node.getAttribute("value")==name){
 5     n.innerHTML repl;
 6   }
 7   return n;
 8 }
 9 
10 function setOverrideNextToThisBranch_(e,v){
11 
12   var branchName e.target.parentNode.getAttribute("value").split("option_")[1];
13 
14   ([].slice.call(document.getElementById("cache").children)).map(function(n){
15     return replaceInnerHtmlIfHasGivenValueAttr(v
16       ,"<param value=\"" branchName "\">"
17       ,n
18       );
19     }
20     );
21 }
22 
23 
24 function setOverrideNextToThisBranchString(branchName,v){
25   ([].slice.call(document.getElementById("cache").children)).map(function(n){
26     return replaceInnerHtmlIfHasGivenValueAttr(v
27       ,"<param value=\"" branchName "\">"
28       ,n
29       );
30     }
31     );
32 }
33 
34 
35 function clearOverrideNext1(e){
36   clearOverrideNext_(e,"overrideNxt1");
37 }
38 
39 function clearOverrideNext_(e,v){
40   ([].slice.call(document.getElementById("cache").children)).map(function(n){
41     return replaceInnerHtmlIfHasGivenValueAttr(v,"",n);
42     }
43     );
44 
45 }
46 
47 function autostart(e){
48   document.getElementById("display").children[1].children[0].click();
49 }
50 
51 window.addEventListener('load'autostartfalse);
52    
53 
54 function runCode(c){
55   var a=new Function(c);
56   a.apply(null);
57 }

Не обращайте внимание на autostart, это просто небольшой костыль к которому мне пришлось прибегнуть.
The autostart function is a little crutch I had to resort to. Ignore it.
Функция runCode нужна для запуска стороннего кода библиотекой htic.js. Теоретически можно сделать её не обязательной, но я не сделал.
The runCode function is there to let htic.js run external functions. It's not realy necessary and in theory I could do without it. In theory.
Функция setOverrideNextToThisBranch_(e,v), и остальные похожие, позволяют устанавливать указатель для overrideNext при помощи события onclick. Но ими нельзя пользоваться если элемент с "option_< id >" не является непосредственным родителем элемента породившего событие onclick. В приводимом примере это условие не соблюдается.
The function setOverrideNextToThisBranch_(e,v) and alike allow you to set overrideNext pointer using an onclick event. But it can only be used if the element with "option_< id >" is an immediate parent of the element triggering the onclick event. The provided example does not satisfy this condition.
Функция clearOverrideNext_(e,v) стирает установленый указатель. Ёе варианты без переменной v нужны потому что я не хотел писать лишние лямбды.
The clearOverrideNext_(e,v) function erases the overrideNext pointer. There are versions of it without the v argument because I didn't like to write extra lambda-expressions.
Наконец

setOverrideNextToThisBranchString(branchName,v)

это функция использующаяся в примере для установки указателя overrideNext. Обратите внимание, что на момент создания fodg невозможно знать id узла-ветки на который должен быть установлен указатель, а значит параметр branchName не может быть заполнен. Однако hticExt заполнит этот параметр вместо нас на этапе сбороки html. Для этого в Description узла runCode нужно вписать какая подстрока текста в runCode должна быть заменена на искомый id. В приведённом примере это "branchName", таким образом текст

setOverrideNextToThisBranchString("branchName","overrideNxt1")

будет заменён на

setOverrideNextToThisBranchString("id1id2","overrideNxt1")

, где "id1id2" это произвольное значение призванное иллюстрировать id узла-ветки на который указывает нулевой переход на следующий узел-ветку (переходы считаются начиная с 0) относительно узла-ветки к которому привязан runCode.
Finally

setOverrideNextToThisBranchString(branchName,v)

is a function that was used in the given example to set the overrideNext pointer. Do note that at the time of fodg creation it is impossible to know the id of the branch-node the pointer is supposed to be set to, which means that the value of the branchName argument can not be provided. This conundrum is solved by hticExt that provides value for us during html assembly. To do that hticExt looks into the Description of the runCode-node for the substring it should search for in the text of the runCode-node to replace it with the appropriate id value. In the given example the substring is "branchName" so

setOverrideNextToThisBranchString("branchName","overrideNxt1")

would be turned into

setOverrideNextToThisBranchString("id1id2","overrideNxt1")

where "id1id2" is some arbitrary value that was used to illustrate the id of a branch-node that the number 0 transition points to (transitions are counted starting with 0) relative to the branch-node the runCode belongs to.
Рассмотрим алгоритм работы узла overrideNext. У каждого узла-ветки есть набор переходов на другие узлы-ветки. В отсутствии узлов-модификаторов, к которым относится overrideNext этот набор остаётся неизменным. Однако в присутствии модификатора overrideNext выполняется проверка наличия установленного указателя, имя которого записано в текст узла overrideNext. В представленном примере проверяется установка указателя(переменной) "overrideNxt1". В случае если указатель установлен, прочитывается Description узла overrideNext, и набор переходов узла-ветки, к которой прикреплён overrideNext, заменяется на переход, путь к которому указан в Description. Путь в Description указывается относительно узла на который установлен указатель.
Let's inspect the algorithm of an overrideNext node operation. Each branch-node possesses a set of transition options to other branch-nodes. In absence of modificator-nodes such as overrideNext the given set of transition options remains constant. But when an overrideNext node is assigned to a branch-node a check is performed. In case the pointer the overrideNext text specifies is set("overrideNxt1" in the given example), the set of transition options is replaced with the transition that the path stored in the overrideNext Description points to. The path is given relative to the branch-node the overrideNext pointer dictates.
Сборка html файла выполняется стандартным способом. Файл testOverrideNext.json содержит необходимые настройки для получения testOverrideNext.html . Описание остальных узлов можно прочитать в предыдущей публикации .
The html assembly can be done the standard way. The file testOverrideNext.json contains the settings necessary to produce testOverrideNext.html . To read the description of the rest of the node-types refere to the previous publication .

hticExt testOverrideNext.json > testOverrideNext.log