diff options
Diffstat (limited to 'src/web/helpers/image.php')
-rw-r--r-- | src/web/helpers/image.php | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/src/web/helpers/image.php b/src/web/helpers/image.php new file mode 100644 index 0000000..c18154a --- /dev/null +++ b/src/web/helpers/image.php @@ -0,0 +1,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; +} |