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