summaryrefslogtreecommitdiff
path: root/src/web/helpers/image.php
blob: c18154a30b251e157c09f5347cc6437ac4134502 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php /* Copyright (c) 2024 Freya Murphy */

function __get_mime($type) {
	switch ($type) {
		case 'mp4':
			return 'video/mp4';
		case 'webm':
			return 'video/webm';
		case 'gif':
			return 'image/gif';
		case 'png':
			return 'image/png';
		case 'jpg':
			return 'image/jpeg';
		case 'webp':
			return 'image/webp';
		default:
			return NULL;
	}
}

function __make_source(
	$name,
	$format,
	$media
) {
	if ($media) {
		$media = "media=\"$media\"";
	} else {
		$media = '';
	}
	$main = $GLOBALS['main_model'];
	$path = $main->get_url('public/' . $name . '.' . $format);
	$mime = __get_mime($format);
	return sprintf('<source type="%s" srcset="%s" %s>',
		$mime, $path, $media);
}

function image(
	$name,
	$alt,
	$formats = array('webp', 'png'),
	$animated = FALSE,
	$attrs = array(),

	$height = NULL,
	$width = NULL,
	$size = NULL,
) :string {

	if ($animated === TRUE) {
		$animated = array('gif');
	}

	if (!$animated) {
		$animated = array();
	}

	$out = "<picture>";

	foreach ($formats as $format) {
		$media = count($animated) ? '(prefers-reduced-motion: reduce)' : NULL;
		$out .= __make_source($name, $format, $media);
	}

	foreach ($animated as $format) {
		$out .= __make_source($name, $format, NULL);
	}

	$format = end($formats);
	$main = $GLOBALS['main_model'];
	$path = $main->get_url('public/' . $name . '.' . $format);
	$out .= "<img src=\"$path\"";
	if ($alt) {
		$alt = lang($alt);
		$attrs['alt'] = $alt;
	}
	if ($width) {
		$attrs['width'] = $width;
	}
	if ($height) {
		$attrs['height'] = $height;
	}
	if ($size) {
		$attrs['width'] = $size;
		$attrs['height'] = $size;
	}
	foreach ($attrs as $key => $value) {
		$out .= " $key=\"$value\"";
	}
	$out .= '></picture>';

	return $out;
}