Revision of Twine macro: << addtag >>, << removetag >>, << toggletag >> from Mon, 01/28/2013 - 09:14

This requires my code for applying Twine tags to passage divs, and extends on it as a mechanism for CSS selection. What these macros do, in order, is add a tag to the current passage's tag attribute, remove a tag, and toggle its presence (remove it if it's there, add it if it isn't). This means that conditional application of CSS, controlled by << if >> statements, is possible.


version.extensions['toggletag'] = {major:1, minor:0, revision:0};
macros['toggletag'] = {
handler: function (a, b, c) {
var p = e(a);
if (p) {
var t = p.getAttribute("tags");
var i = t.indexOf(c[0]);
if (b!="addtag" && i>=0) {
p.setAttribute("tags",t.replace(c[0],""));
}
else if (b!="removetag" && i<0) p.setAttribute("tags",t+" "+c[0]);
}
else {
var t = state.history[0].passage.tags;
var i = t.indexOf(c[0]);
if (b!="addtag" && i>=0) {
t.splice(i,1);
} else if (b!="removetag" && i<0) {
t.push(c[0]);
}
}
function e(f) {
while(f.parentNode && f.className != "passage") { f = f.parentNode; }
if (f.getAttribute("tags")) return f;
return null;
}
}
}
macros['addtag'] = macros['toggletag'];
macros['removetag'] = macros['toggletag'];



Usage examples: <<addtag "dream">> <<toggletag "lightworld">> <<toggletag "darkworld">>


These are guaranteed to work both inside passages, inside << replace >> macros, and, tantalysingly enough, inside << display >> macros. Interesting, very interesting.