summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/toggle.pm
blob: 20967d3fd79e85fb5f0e677b0a7d76eb6e7ac38f (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}, $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/ikiwiki.js", $page, $absolute).
  68. '" type="text/javascript" charset="utf-8"></script>'."\n".
  69. '<script src="'.urlto("ikiwiki/toggle.js", $page, $absolute).
  70. '" type="text/javascript" charset="utf-8"></script>';
  71. }
  72. 1