summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/toggle.pm
blob: 657d8d3c2d49dbc40a415fde9446aaeffe761d46 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::toggle;
  3. use warnings;
  4. use strict;
  5. use IkiWiki 2.00;
  6. sub import { #{{{
  7. add_underlay("javascript");
  8. hook(type => "getsetup", id => "toggle", call => \&getsetup);
  9. hook(type => "preprocess", id => "toggle",
  10. call => \&preprocess_toggle);
  11. hook(type => "preprocess", id => "toggleable",
  12. call => \&preprocess_toggleable);
  13. hook(type => "format", id => "toggle", call => \&format);
  14. } # }}}
  15. sub getsetup () { #{{{
  16. return
  17. plugin => {
  18. safe => 1,
  19. rebuild => undef,
  20. },
  21. } #}}}
  22. sub genid ($$) { #{{{
  23. my $page=shift;
  24. my $id=shift;
  25. $id="$page.$id";
  26. # make it a legal html id attribute
  27. $id=~s/[^-a-zA-Z0-9.]/-/g;
  28. if ($id !~ /^[a-zA-Z]/) {
  29. $id="id$id";
  30. }
  31. return $id;
  32. } #}}}
  33. sub preprocess_toggle (@) { #{{{
  34. my %params=(id => "default", text => "more", @_);
  35. my $id=genid($params{page}, $params{id});
  36. return "<a class=\"toggle\" href=\"#$id\">$params{text}</a>";
  37. } # }}}
  38. sub preprocess_toggleable (@) { #{{{
  39. my %params=(id => "default", text => "", open => "no", @_);
  40. # Preprocess the text to expand any preprocessor directives
  41. # embedded inside it.
  42. $params{text}=IkiWiki::preprocess($params{page}, $params{destpage},
  43. IkiWiki::filter($params{page}, $params{destpage}, $params{text}));
  44. my $id=genid($params{page}, $params{id});
  45. my $class=(lc($params{open}) ne "yes") ? "toggleable" : "toggleable-open";
  46. # Should really be a postprocessor directive, oh well. Work around
  47. # markdown's dislike of markdown inside a <div> with various funky
  48. # whitespace.
  49. my ($indent)=$params{text}=~/( +)$/;
  50. $indent="" unless defined $indent;
  51. return "<div class=\"$class\" id=\"$id\"></div>\n\n$params{text}\n$indent<div class=\"toggleableend\"></div>";
  52. } # }}}
  53. sub format (@) { #{{{
  54. my %params=@_;
  55. if ($params{content}=~s!(<div class="toggleable(?:-open)?" id="[^"]+">\s*)</div>!$1!g) {
  56. $params{content}=~s/<div class="toggleableend">//g;
  57. if (! ($params{content}=~s!^(<body>)!$1.include_javascript($params{page})!em)) {
  58. # no </body> tag, probably in preview mode
  59. $params{content}=include_javascript($params{page}, 1).$params{content};
  60. }
  61. }
  62. return $params{content};
  63. } # }}}
  64. sub include_javascript ($;$) { #{{{
  65. my $page=shift;
  66. my $absolute=shift;
  67. return '<script src="'.urlto("ikiwiki.js", $page, $absolute).
  68. '" type="text/javascript" charset="utf-8"></script>'."\n".
  69. '<script src="'.urlto("toggle.js", $page, $absolute).
  70. '" type="text/javascript" charset="utf-8"></script>';
  71. } #}}}
  72. 1