ルモーリン

アルバム表示プラグイン

投稿:2025-05-19

以前、書いたこれ→PhotoSwipeでアルバム表示
JavaScriptで書いてサーバーにまとめました。 HTMLの方ではタグHEAD、処理経過、アルバム表示位置、記事末尾のインポートと色々書いています。 今後のアルバム表示に同じものを書くのは面倒です。 そこでHTMLの処理を書いてくれるプラグインを作りました。 あー楽ちん。

package PpGallery;
# エディタの文字コード判定用に漢字のコメントを置いておきます。
use Mojo::Base "Mojolicious::Plugin";
use GD::Image;

sub register {
	my ($self, $app, $conf) = @_;

	my $route = $app->routes;
	for (qw/ loader.js photoswipe-lightbox.esm.js photoswipe.css photoswipe.esm.js style.css /) {
		$route->get("/photoswipe/$_")->to("ThroughFile#through", directory => "photoswipe", filename => $_);
	}

	$app->helper(PpGallery => sub {
		my $self = shift;
		my @inhtml = @_;

		$self->stash(photoswipe => 1);

		my $count = $self->stash("gallery_count");
		$count //= 0;
		$self->stash(gallery_count => ++$count);

		my @outhtml;
		if (1 == $count) {
			push @outhtml, split /\n/, <<EOF;
<div id="progress"></div>
<div id="loading-overlay">
<div class="spinner"></div>
<div id="loading-count">読み込み中...</div>
</div>
EOF

			my @finish_line = split /\n/, <<EOF;
<small>
このアルバム表示はPhotoSwipeを利用しています。<a href="https://photoswipe.com/">PhotoSwipe: Responsive JavaScript Image Gallery</a>
</small>
<script type="module">
	import initGallery from '/photoswipe/loader.js';
	initGallery("album");
</script>
EOF
			$self->stash(finish_line => \@finish_line);
		}

		my $directory = "draft/" . $self->stash("directory");
		push @outhtml, qq#<div id="album$count" class="gallery album"#;
		push @outhtml, qq#data-images='[#;
		my $index = 0;
		for (@inhtml) {
			my $original = $_;
			my $thumbnail = $original;
			$thumbnail =~ s/\.(...)$/_thumb.$1/;
			my $exp = $1;
			$self->app->log->debug("thumbnail $thumbnail");
			if (!-e "$directory/$thumbnail") {
				my $gd = GD::Image->new("$directory/$original");
				my $width = $gd->width;
				my $height = $gd->height;
				my $width_thumb = 200;
				my $height_thumb = int($height / $width * $width_thumb);
				$self->app->log->debug("$_ w $width h $height thumbnail w $width_thumb h $height_thumb");
				my $thumb = GD::Image->new($width_thumb, $height_thumb, 1);
				$thumb->copyResampled($gd, 0, 0, 0, 0, $width_thumb, $height_thumb, $width, $height);
				my $thumb_data;
				if ("jpg" eq lc $exp) {
					$thumb_data = $thumb->jpeg;
				} elsif ("png" eq lc $exp) {
					$thumb_data = $thumb->png;
				}
				if (open my $fh, ">", "$directory/$thumbnail") {
					binmode $fh;
					print $fh $thumb_data;
					close $fh;
				}
			}
			$thumbnail = $_ if !-e "$directory/$thumbnail";
			my $comma = $index < @inhtml - 1 ? "," : "";
			push @outhtml, qq#{ "href" : "$_", "thumb" : "$thumbnail" }$comma#;
			$index++;
		}
		push @outhtml, qq#]'>#;
		push @outhtml, qq#</div>#;

		return @outhtml;
	});
}

1;

HTMLの記事の中ではプラグインのタグでファイル名を囲みます。 初回表示でサムネイルが無ければ自動生成して保存しますから表示したい写真を指定するだけです。

<pre ppmod="PpGallery">
photo_01.jpg
photo_02.jpg
photo_03.jpg
< /pre> <!-- 表示の都合でスペース入れてます -->